generated from nhcarrigan/template
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* @file CLI for generating branded Naomi QR codes.
|
||||
* @copyright 2026 NHCarrigan
|
||||
* @license Naomi's Public License
|
||||
* @author Hikari <hikari@nhcarrigan.com>
|
||||
*/
|
||||
|
||||
/* eslint-disable no-console -- CLI tool requires console output */
|
||||
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { generateQrCode, urlToFilename } from "./qr.js";
|
||||
|
||||
const outputDirectory = new URL("../output", import.meta.url).pathname;
|
||||
|
||||
async function generate(rawUrl: string): Promise<void> {
|
||||
mkdirSync(outputDirectory, { recursive: true });
|
||||
|
||||
const url = rawUrl.startsWith("http")
|
||||
? rawUrl
|
||||
: `https://${rawUrl}`;
|
||||
console.log(`Generating QR code for: ${url}`);
|
||||
|
||||
const finalBuffer = await generateQrCode(rawUrl);
|
||||
|
||||
const filename = `${urlToFilename(url)}.png`;
|
||||
const outputPath = join(outputDirectory, filename);
|
||||
writeFileSync(outputPath, finalBuffer);
|
||||
console.log(` → Saved: ${outputPath}`);
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const urls = process.argv.slice(2).filter((argument) => {
|
||||
return argument !== "--";
|
||||
});
|
||||
|
||||
if (urls.length === 0) {
|
||||
console.log(
|
||||
"Usage: pnpm generate -- <url> [<url> ...]\n"
|
||||
+ "Example: pnpm generate -- chat.naomi.lgbt",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
for (const url of urls) {
|
||||
// eslint-disable-next-line no-await-in-loop -- sequential output is intentional
|
||||
await generate(url);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await main();
|
||||
} catch (error: unknown) {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
/**
|
||||
* @file Core QR code generation pipeline.
|
||||
* @copyright 2026 NHCarrigan
|
||||
* @license Naomi's Public License
|
||||
* @author Hikari <hikari@nhcarrigan.com>
|
||||
*/
|
||||
|
||||
/* eslint-disable import/no-commonjs -- qr-code-styling and @xmldom/xmldom ship CJS-only */
|
||||
/* eslint-disable @typescript-eslint/consistent-type-assertions -- CJS interop requires casts */
|
||||
/* eslint-disable @typescript-eslint/naming-convention -- module-level constants use UPPER_SNAKE_CASE */
|
||||
|
||||
import { createRequire } from "node:module";
|
||||
import { createCanvas, loadImage } from "canvas";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
const g = globalThis as Record<string, unknown>;
|
||||
g.self = globalThis;
|
||||
|
||||
interface DomImplementationFactory {
|
||||
createDocument: (ns: string, name: string, doctype: null)=> XMLDocument;
|
||||
}
|
||||
|
||||
interface XmlDomModule {
|
||||
DOMImplementation: new ()=> DomImplementationFactory;
|
||||
XMLSerializer: unknown;
|
||||
}
|
||||
|
||||
interface QrCodeInstance {
|
||||
getRawData: (type: string)=> Promise<Buffer>;
|
||||
}
|
||||
|
||||
interface NodeCanvasModule {
|
||||
createCanvas: typeof createCanvas;
|
||||
}
|
||||
|
||||
const xmldomModule = require("@xmldom/xmldom") as XmlDomModule;
|
||||
const nodeCanvas = require("canvas") as NodeCanvasModule;
|
||||
|
||||
type QrCodeStyler = new (options: unknown)=> QrCodeInstance;
|
||||
const QRCodeStyling = require("qr-code-styling") as QrCodeStyler;
|
||||
|
||||
const domImpl = new xmldomModule.DOMImplementation();
|
||||
const svgDocument = domImpl.createDocument(
|
||||
"http://www.w3.org/2000/svg",
|
||||
"svg",
|
||||
null,
|
||||
);
|
||||
|
||||
g.window = {
|
||||
XMLSerializer: xmldomModule.XMLSerializer,
|
||||
document: {
|
||||
// eslint-disable-next-line @typescript-eslint/promise-function-async -- sync factory, not async
|
||||
createElement: (tag: string): unknown => {
|
||||
return tag === "canvas"
|
||||
? nodeCanvas.createCanvas(512, 512)
|
||||
: (svgDocument as unknown as {
|
||||
createElement: (tag: string)=> unknown;
|
||||
}).createElement(tag);
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/promise-function-async -- sync factory, not async
|
||||
createElementNS: (ns: string, tag: string): unknown => {
|
||||
return (svgDocument as unknown as {
|
||||
createElementNS: (ns: string, tag: string)=> unknown;
|
||||
}).createElementNS(ns, tag);
|
||||
},
|
||||
},
|
||||
};
|
||||
g.document = (g.window as { document: unknown }).document;
|
||||
|
||||
// --- Config ---
|
||||
|
||||
const QR_SIZE = 1028;
|
||||
const PAD_SIDES = 56;
|
||||
const PAD_TOP = 56;
|
||||
const BRANDING_GAP = 28;
|
||||
const BRANDING_HEIGHT = 56;
|
||||
const PAD_BOTTOM = 40;
|
||||
|
||||
const LOGO_FRACTION = 0.22;
|
||||
const LOGO_CIRCLE_FRACTION = 0.5;
|
||||
|
||||
const NAOMI_PURPLE = "#44275A";
|
||||
const NAOMI_LAVENDER = "#E8D5E8";
|
||||
const BRANDING_TEXT_COLOUR = "#A8577E";
|
||||
const AVATAR_URL = "https://cdn.nhcarrigan.com/profile.png";
|
||||
|
||||
type CanvasContext = ReturnType<ReturnType<typeof createCanvas>["getContext"]>;
|
||||
|
||||
async function generateQrBase(url: string): Promise<Buffer> {
|
||||
const qrCode = new QRCodeStyling({
|
||||
backgroundOptions: { color: NAOMI_LAVENDER },
|
||||
cornersDotOptions: { color: NAOMI_PURPLE, type: "dot" },
|
||||
cornersSquareOptions: { color: NAOMI_PURPLE, type: "extra-rounded" },
|
||||
data: url,
|
||||
dotsOptions: { color: NAOMI_PURPLE, type: "dots" },
|
||||
height: QR_SIZE,
|
||||
nodeCanvas: nodeCanvas,
|
||||
type: "canvas",
|
||||
width: QR_SIZE,
|
||||
});
|
||||
|
||||
return await qrCode.getRawData("png");
|
||||
}
|
||||
|
||||
async function overlayLogo(qrBuffer: Buffer): Promise<Buffer> {
|
||||
const canvas = createCanvas(QR_SIZE, QR_SIZE);
|
||||
const context = canvas.getContext("2d");
|
||||
|
||||
const qrImage = await loadImage(qrBuffer);
|
||||
context.drawImage(qrImage, 0, 0, QR_SIZE, QR_SIZE);
|
||||
|
||||
const logoSize = Math.round(QR_SIZE * LOGO_FRACTION);
|
||||
const logoX = (QR_SIZE - logoSize) / 2;
|
||||
const logoY = (QR_SIZE - logoSize) / 2;
|
||||
const circleRadius = logoSize * LOGO_CIRCLE_FRACTION;
|
||||
|
||||
context.fillStyle = NAOMI_LAVENDER;
|
||||
context.beginPath();
|
||||
context.arc(QR_SIZE / 2, QR_SIZE / 2, circleRadius, 0, Math.PI * 2);
|
||||
context.fill();
|
||||
|
||||
const avatarImage = await loadImage(AVATAR_URL);
|
||||
context.save();
|
||||
context.beginPath();
|
||||
context.arc(QR_SIZE / 2, QR_SIZE / 2, circleRadius, 0, Math.PI * 2);
|
||||
context.clip();
|
||||
context.drawImage(avatarImage, logoX, logoY, logoSize, logoSize);
|
||||
context.restore();
|
||||
|
||||
return canvas.toBuffer("image/png");
|
||||
}
|
||||
|
||||
function drawBrandingStrip(
|
||||
context: CanvasContext,
|
||||
totalWidth: number,
|
||||
brandingMidY: number,
|
||||
): void {
|
||||
const fontSize = Math.max(14, Math.round(QR_SIZE * 0.044));
|
||||
const label = "chat.naomi.lgbt";
|
||||
|
||||
context.font = `600 ${String(fontSize)}px "DejaVu Sans", Inter, sans-serif`;
|
||||
context.textAlign = "center";
|
||||
context.textBaseline = "middle";
|
||||
|
||||
const textWidth = context.measureText(label).width;
|
||||
const dotRadius = Math.max(4, Math.round(fontSize * 0.38));
|
||||
const halfTextWidth = textWidth / 2;
|
||||
const dotPad = dotRadius * 3;
|
||||
const dotOffset = halfTextWidth + dotPad;
|
||||
const centerX = totalWidth / 2;
|
||||
|
||||
context.fillStyle = NAOMI_PURPLE;
|
||||
for (const xOffset of [ -dotOffset, dotOffset ]) {
|
||||
context.beginPath();
|
||||
context.arc(centerX + xOffset, brandingMidY, dotRadius, 0, Math.PI * 2);
|
||||
context.fill();
|
||||
}
|
||||
|
||||
context.fillStyle = BRANDING_TEXT_COLOUR;
|
||||
context.fillText(label, centerX, brandingMidY);
|
||||
}
|
||||
|
||||
async function compositeWithBranding(buffer: Buffer): Promise<Buffer> {
|
||||
const sidePadding = PAD_SIDES * 2;
|
||||
const totalWidth = QR_SIZE + sidePadding;
|
||||
const totalHeight
|
||||
= PAD_TOP + QR_SIZE + BRANDING_GAP + BRANDING_HEIGHT + PAD_BOTTOM;
|
||||
|
||||
const canvas = createCanvas(totalWidth, totalHeight);
|
||||
const context = canvas.getContext("2d");
|
||||
|
||||
context.fillStyle = NAOMI_LAVENDER;
|
||||
context.fillRect(0, 0, totalWidth, totalHeight);
|
||||
|
||||
const qrImage = await loadImage(buffer);
|
||||
context.drawImage(qrImage, PAD_SIDES, PAD_TOP, QR_SIZE, QR_SIZE);
|
||||
|
||||
const halfBrandingHeight = BRANDING_HEIGHT / 2;
|
||||
const brandingMidY = PAD_TOP + QR_SIZE + BRANDING_GAP + halfBrandingHeight;
|
||||
drawBrandingStrip(context, totalWidth, brandingMidY);
|
||||
|
||||
return canvas.toBuffer("image/png");
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a complete branded QR code PNG for the given URL.
|
||||
* @param rawUrl - The URL to encode (scheme optional).
|
||||
* @returns A PNG buffer of the finished QR image.
|
||||
*/
|
||||
/**
|
||||
* Generates a complete branded QR code PNG for the given URL.
|
||||
* @param rawUrl - The URL to encode (scheme optional).
|
||||
* @returns A PNG buffer of the finished QR image.
|
||||
*/
|
||||
async function generateQrCode(rawUrl: string): Promise<Buffer> {
|
||||
const url = rawUrl.startsWith("http")
|
||||
? rawUrl
|
||||
: `https://${rawUrl}`;
|
||||
const qrBase = await generateQrBase(url);
|
||||
const qrWithLogo = await overlayLogo(qrBase);
|
||||
return await compositeWithBranding(qrWithLogo);
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives a safe filesystem/download filename from a URL.
|
||||
* @param url - The URL to convert.
|
||||
* @returns A lowercase, hyphenated slug of at most 60 characters.
|
||||
*/
|
||||
function urlToFilename(url: string): string {
|
||||
const trimmed = url.
|
||||
replace(/https?:\/\//u, "").
|
||||
replaceAll(/[^a-z0-9]/giu, "-").
|
||||
replaceAll(/-+/gu, "-").
|
||||
replaceAll(/^-|-$/gu, "").
|
||||
slice(0, 60);
|
||||
return trimmed.length > 0
|
||||
? trimmed
|
||||
: "naomi-qr";
|
||||
}
|
||||
|
||||
export { generateQrCode, urlToFilename };
|
||||
+297
@@ -0,0 +1,297 @@
|
||||
/**
|
||||
* @file HTTP server for generating branded Naomi QR codes on demand.
|
||||
* @copyright 2026 NHCarrigan
|
||||
* @license Naomi's Public License
|
||||
* @author Hikari <hikari@nhcarrigan.com>
|
||||
*/
|
||||
|
||||
/* eslint-disable no-console -- server lifecycle logging */
|
||||
/* eslint-disable @typescript-eslint/naming-convention -- Fastify generic uses Querystring by convention */
|
||||
|
||||
import fastify from "fastify";
|
||||
import { generateQrCode, urlToFilename } from "./qr.js";
|
||||
|
||||
const port = 15555;
|
||||
const host = "0.0.0.0";
|
||||
|
||||
const pageHtml = `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Naomi QR Generator</title>
|
||||
<style>
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
body {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: #E8D5E8;
|
||||
font-family: system-ui, sans-serif;
|
||||
padding: 2rem;
|
||||
gap: 2rem;
|
||||
}
|
||||
|
||||
header {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
header img {
|
||||
width: 80px;
|
||||
height: 80px;
|
||||
border-radius: 50%;
|
||||
border: 3px solid #44275A;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.75rem;
|
||||
color: #44275A;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
p.subtitle {
|
||||
color: #6b4d7a;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
width: 100%;
|
||||
max-width: 480px;
|
||||
}
|
||||
|
||||
label {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
color: #44275A;
|
||||
}
|
||||
|
||||
input[type="text"] {
|
||||
width: 100%;
|
||||
padding: 0.625rem 0.875rem;
|
||||
border: 2px solid #44275A;
|
||||
border-radius: 8px;
|
||||
font-size: 1rem;
|
||||
background: #f9f0f9;
|
||||
color: #1a0022;
|
||||
outline: none;
|
||||
transition: border-color 0.15s;
|
||||
}
|
||||
|
||||
input[type="text"]:focus {
|
||||
border-color: #6b3d8a;
|
||||
}
|
||||
|
||||
button[type="submit"] {
|
||||
padding: 0.625rem 1.25rem;
|
||||
background: #44275A;
|
||||
color: #E8D5E8;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
button[type="submit"]:hover {
|
||||
background: #5c3a7a;
|
||||
}
|
||||
|
||||
button[type="submit"]:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
#result {
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
#result img {
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 24px rgba(68, 39, 90, 0.18);
|
||||
max-width: 320px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#download-btn {
|
||||
padding: 0.5rem 1.25rem;
|
||||
background: transparent;
|
||||
color: #44275A;
|
||||
border: 2px solid #44275A;
|
||||
border-radius: 8px;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
transition: background 0.15s, color 0.15s;
|
||||
}
|
||||
|
||||
#download-btn:hover {
|
||||
background: #44275A;
|
||||
color: #E8D5E8;
|
||||
}
|
||||
|
||||
#error-msg {
|
||||
display: none;
|
||||
color: #8b0000;
|
||||
font-size: 0.9rem;
|
||||
background: #fde8e8;
|
||||
border: 1px solid #f5a5a5;
|
||||
border-radius: 8px;
|
||||
padding: 0.5rem 1rem;
|
||||
max-width: 480px;
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#spinner {
|
||||
display: none;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border: 3px solid #c8a8d8;
|
||||
border-top-color: #44275A;
|
||||
border-radius: 50%;
|
||||
animation: spin 0.7s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<img src="https://cdn.nhcarrigan.com/profile.png" alt="Naomi's avatar" />
|
||||
<h1>Naomi QR Generator</h1>
|
||||
<p class="subtitle">Enter a URL to generate a branded QR code.</p>
|
||||
</header>
|
||||
|
||||
<form id="qr-form">
|
||||
<label for="url-input">URL</label>
|
||||
<input
|
||||
id="url-input"
|
||||
type="text"
|
||||
name="url"
|
||||
placeholder="e.g. chat.naomi.lgbt"
|
||||
required
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
/>
|
||||
<button type="submit" id="submit-btn">Generate</button>
|
||||
</form>
|
||||
|
||||
<div id="spinner"></div>
|
||||
<p id="error-msg"></p>
|
||||
|
||||
<div id="result">
|
||||
<img id="qr-img" src="" alt="Generated QR code" />
|
||||
<a id="download-btn" download="naomi-qr.png">Download PNG</a>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const form = document.getElementById('qr-form');
|
||||
const input = document.getElementById('url-input');
|
||||
const submitBtn = document.getElementById('submit-btn');
|
||||
const spinner = document.getElementById('spinner');
|
||||
const result = document.getElementById('result');
|
||||
const qrImg = document.getElementById('qr-img');
|
||||
const downloadBtn = document.getElementById('download-btn');
|
||||
const errorMsg = document.getElementById('error-msg');
|
||||
|
||||
form.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
|
||||
const url = input.value.trim();
|
||||
if (!url) return;
|
||||
|
||||
submitBtn.disabled = true;
|
||||
spinner.style.display = 'block';
|
||||
result.style.display = 'none';
|
||||
errorMsg.style.display = 'none';
|
||||
|
||||
try {
|
||||
const response = await fetch('/generate?url=' + encodeURIComponent(url));
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
throw new Error(text || response.statusText);
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
|
||||
qrImg.src = objectUrl;
|
||||
|
||||
const slug = url.
|
||||
replace(/https?:\\/\\//, '').
|
||||
replace(/[^a-z0-9]/gi, '-').
|
||||
replace(/-+/g, '-').
|
||||
replace(/^-|-$/g, '').
|
||||
slice(0, 60) || 'naomi-qr';
|
||||
downloadBtn.href = objectUrl;
|
||||
downloadBtn.download = slug + '.png';
|
||||
|
||||
result.style.display = 'flex';
|
||||
} catch (err) {
|
||||
errorMsg.textContent = err instanceof Error ? err.message : 'Something went wrong.';
|
||||
errorMsg.style.display = 'block';
|
||||
} finally {
|
||||
submitBtn.disabled = false;
|
||||
spinner.style.display = 'none';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
|
||||
const server = fastify();
|
||||
|
||||
server.get("/", async(_request, reply) => {
|
||||
await reply.type("text/html").send(pageHtml);
|
||||
});
|
||||
|
||||
server.get<{ Querystring: { url?: string } }>(
|
||||
"/generate",
|
||||
async(request, reply) => {
|
||||
const rawUrl = request.query.url;
|
||||
|
||||
if (rawUrl === undefined || rawUrl.trim() === "") {
|
||||
await reply.status(400).send("Missing required query parameter: url");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const pngBuffer = await generateQrCode(rawUrl.trim());
|
||||
const filename = `${urlToFilename(rawUrl.trim())}.png`;
|
||||
|
||||
await reply.
|
||||
type("image/png").
|
||||
header("Content-Disposition", `attachment; filename="${filename}"`).
|
||||
send(pngBuffer);
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error
|
||||
? error.message
|
||||
: "Unknown error";
|
||||
console.error(`QR generation failed for "${rawUrl}": ${message}`);
|
||||
await reply.status(500).send("Failed to generate QR code.");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
try {
|
||||
await server.listen({ host, port });
|
||||
console.log(`Server listening on http://${host}:${String(port)}`);
|
||||
} catch (error: unknown) {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
}
|
||||
Reference in New Issue
Block a user