import { Buffer } from "node:buffer"; import { writeFileSync } from "node:fs"; import { join } from "node:path"; import { deflateSync } from "node:zlib"; import { defineTool, FilePath, Type } from "@toolpal/tool"; type Level = "L" | "M" | "Q" | "H"; // Error-correction codewords per block, and number of blocks, indexed by version 1-40 (ISO/IEC 18004). const ECC_PER_BLOCK: Record = { L: [ 0, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, ], M: [ 0, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, ], Q: [ 0, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, ], H: [ 0, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, ], }; const BLOCKS: Record = { L: [ 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25, ], M: [ 0, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49, ], Q: [ 0, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68, ], H: [ 0, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81, ], }; const FORMAT_BITS: Record = { L: 1, M: 0, Q: 3, H: 2 }; const MASKS: ((x: number, y: number) => boolean)[] = [ (x, y) => (x + y) % 2 === 0, (_, y) => y % 2 === 0, (x) => x % 3 === 0, (x, y) => (x + y) % 3 === 0, (x, y) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0, (x, y) => ((x * y) % 2) + ((x * y) % 3) === 0, (x, y) => (((x * y) % 2) + ((x * y) % 3)) % 2 === 0, (x, y) => (((x + y) % 2) + ((x * y) % 3)) % 2 === 0, ]; function rawDataModules(version: number): number { let result = (16 * version + 128) * version + 64; if (version >= 2) { const align = Math.floor(version / 7) + 2; result -= (25 * align - 10) * align - 55; if (version >= 7) result -= 36; } return result; } function dataCodewords(version: number, level: Level): number { return ( Math.floor(rawDataModules(version) / 8) - ECC_PER_BLOCK[level][version] * BLOCKS[level][version] ); } function alignmentPositions(version: number, size: number): number[] { if (version === 1) return []; const count = Math.floor(version / 7) + 2; const step = Math.floor((version * 8 + count * 3 + 5) / (count * 4 - 4)) * 2; const result = [6]; for (let pos = size - 7; result.length < count; pos -= step) result.splice(1, 0, pos); return result; } // Multiplication in GF(2^8) modulo x^8 + x^4 + x^3 + x^2 + 1. function gfMul(x: number, y: number): number { let z = 0; for (let i = 7; i >= 0; i--) { z = (z << 1) ^ ((z >>> 7) * 0x11d); z ^= ((y >>> i) & 1) * x; } return z; } function reedSolomonDivisor(degree: number): number[] { const result = new Array(degree).fill(0); result[degree - 1] = 1; let root = 1; for (let i = 0; i < degree; i++) { for (let j = 0; j < degree; j++) { result[j] = gfMul(result[j], root); if (j + 1 < degree) result[j] ^= result[j + 1]; } root = gfMul(root, 0x02); } return result; } function reedSolomonRemainder(data: number[], divisor: number[]): number[] { const result = divisor.map(() => 0); for (const b of data) { const factor = b ^ (result.shift() as number); result.push(0); divisor.forEach((coef, i) => { result[i] ^= gfMul(coef, factor); }); } return result; } // Byte-mode data plus padding, split into blocks with error correction, then interleaved. function codewords(bytes: Uint8Array, version: number, level: Level): number[] { const bits: number[] = []; const push = (value: number, length: number) => { for (let i = length - 1; i >= 0; i--) bits.push((value >>> i) & 1); }; const capacity = dataCodewords(version, level) * 8; push(0b0100, 4); push(bytes.length, version < 10 ? 8 : 16); for (const b of bytes) push(b, 8); push(0, Math.min(4, capacity - bits.length)); push(0, (8 - (bits.length % 8)) % 8); for (let pad = 0xec; bits.length < capacity; pad ^= 0xec ^ 0x11) push(pad, 8); const data: number[] = []; for (let i = 0; i < bits.length; i += 8) { data.push(bits.slice(i, i + 8).reduce((acc, bit) => (acc << 1) | bit, 0)); } const numBlocks = BLOCKS[level][version]; const eccLength = ECC_PER_BLOCK[level][version]; const total = Math.floor(rawDataModules(version) / 8); const numShort = numBlocks - (total % numBlocks); const shortLength = Math.floor(total / numBlocks); const divisor = reedSolomonDivisor(eccLength); const blocks: number[][] = []; for (let i = 0, k = 0; i < numBlocks; i++) { const block = data.slice(k, k + shortLength - eccLength + (i < numShort ? 0 : 1)); k += block.length; const ecc = reedSolomonRemainder(block, divisor); if (i < numShort) block.push(0); blocks.push(block.concat(ecc)); } const result: number[] = []; for (let i = 0; i < blocks[0].length; i++) { blocks.forEach((block, j) => { if (i !== shortLength - eccLength || j >= numShort) result.push(block[i]); }); } return result; } function penalty(m: boolean[][]): number { const n = m.length; const finderLike = [ [1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1], ]; let score = 0; let dark = 0; for (const horizontal of [true, false]) { for (let a = 0; a < n; a++) { const line = Array.from({ length: n }, (_, b) => (horizontal ? m[a][b] : m[b][a])); let run = 1; for (let b = 1; b <= n; b++) { if (b < n && line[b] === line[b - 1]) run++; else { if (run >= 5) score += run - 2; run = 1; } } for (let b = 0; b + 11 <= n; b++) { if (finderLike.some((p) => p.every((v, k) => line[b + k] === (v === 1)))) score += 40; } } } for (let y = 0; y < n; y++) { for (let x = 0; x < n; x++) { if (m[y][x]) dark++; const c = m[y][x]; if (y + 1 < n && x + 1 < n && c === m[y][x + 1] && c === m[y + 1][x] && c === m[y + 1][x + 1]) { score += 3; } } } return score + (Math.ceil(Math.abs(dark * 20 - n * n * 10) / (n * n)) - 1) * 10; } function encode(text: string, level: Level) { const bytes = new TextEncoder().encode(text); let version = 1; while (4 + (version < 10 ? 8 : 16) + bytes.length * 8 > dataCodewords(version, level) * 8) { if (++version > 40) { throw new Error( `The text is ${bytes.length} bytes, more than a QR code can hold at error correction level ${level}.`, ); } } const size = version * 4 + 17; const grid = () => Array.from({ length: size }, () => new Array(size).fill(false)); const modules = grid(); const isFunction = grid(); const setFunction = (x: number, y: number, dark: boolean) => { modules[y][x] = dark; isFunction[y][x] = true; }; for (let i = 0; i < size; i++) { setFunction(6, i, i % 2 === 0); setFunction(i, 6, i % 2 === 0); } for (const [cx, cy] of [ [3, 3], [size - 4, 3], [3, size - 4], ]) { for (let dy = -4; dy <= 4; dy++) { for (let dx = -4; dx <= 4; dx++) { const x = cx + dx; const y = cy + dy; const dist = Math.max(Math.abs(dx), Math.abs(dy)); if (x >= 0 && x < size && y >= 0 && y < size) setFunction(x, y, dist !== 2 && dist !== 4); } } } const align = alignmentPositions(version, size); const last = align.length - 1; align.forEach((ax, i) => { align.forEach((ay, j) => { if ((i === 0 && j === 0) || (i === 0 && j === last) || (i === last && j === 0)) return; for (let dy = -2; dy <= 2; dy++) { for (let dx = -2; dx <= 2; dx++) { setFunction(ax + dx, ay + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1); } } }); }); const drawFormat = (mask: number) => { const data = (FORMAT_BITS[level] << 3) | mask; let rem = data; for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537); const bits = ((data << 10) | rem) ^ 0x5412; const bit = (i: number) => ((bits >>> i) & 1) === 1; for (let i = 0; i <= 5; i++) setFunction(8, i, bit(i)); setFunction(8, 7, bit(6)); setFunction(8, 8, bit(7)); setFunction(7, 8, bit(8)); for (let i = 9; i < 15; i++) setFunction(14 - i, 8, bit(i)); for (let i = 0; i < 8; i++) setFunction(size - 1 - i, 8, bit(i)); for (let i = 8; i < 15; i++) setFunction(8, size - 15 + i, bit(i)); setFunction(8, size - 8, true); }; drawFormat(0); if (version >= 7) { let rem = version; for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25); const bits = (version << 12) | rem; for (let i = 0; i < 18; i++) { const dark = ((bits >>> i) & 1) === 1; const a = size - 11 + (i % 3); const b = Math.floor(i / 3); setFunction(a, b, dark); setFunction(b, a, dark); } } const data = codewords(bytes, version, level); let i = 0; for (let right = size - 1; right >= 1; right -= 2) { if (right === 6) right = 5; for (let vert = 0; vert < size; vert++) { for (let j = 0; j < 2; j++) { const x = right - j; const y = ((right + 1) & 2) === 0 ? size - 1 - vert : vert; if (!isFunction[y][x] && i < data.length * 8) { modules[y][x] = ((data[i >>> 3] >>> (7 - (i & 7))) & 1) === 1; i++; } } } } const applyMask = (mask: number) => { for (let y = 0; y < size; y++) { for (let x = 0; x < size; x++) { if (!isFunction[y][x] && MASKS[mask](x, y)) modules[y][x] = !modules[y][x]; } } }; let best = 0; let bestScore = Infinity; for (let mask = 0; mask < 8; mask++) { applyMask(mask); drawFormat(mask); const score = penalty(modules); if (score < bestScore) [best, bestScore] = [mask, score]; applyMask(mask); } applyMask(best); drawFormat(best); return { version, size, modules, bytes: bytes.length }; } const CRC_TABLE = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; }); function pngChunk(type: string, data: Buffer): Buffer { const body = Buffer.concat([Buffer.from(type, "ascii"), data]); let crc = 0xffffffff; for (const b of body) crc = CRC_TABLE[(crc ^ b) & 0xff] ^ (crc >>> 8); const out = Buffer.alloc(body.length + 8); out.writeUInt32BE(data.length, 0); body.copy(out, 4); out.writeUInt32BE((crc ^ 0xffffffff) >>> 0, body.length + 4); return out; } function toPng(modules: boolean[][], scale: number, margin: number): Buffer { const n = modules.length; const width = (n + margin * 2) * scale; const raw = Buffer.alloc((width + 1) * width, 255); for (let py = 0; py < width; py++) { raw[py * (width + 1)] = 0; // filter type: none const my = Math.floor(py / scale) - margin; if (my < 0 || my >= n) continue; for (let px = 0; px < width; px++) { const mx = Math.floor(px / scale) - margin; if (mx >= 0 && mx < n && modules[my][mx]) raw[py * (width + 1) + 1 + px] = 0; } } const header = Buffer.alloc(13); header.writeUInt32BE(width, 0); header.writeUInt32BE(width, 4); header[8] = 8; // 8-bit grayscale return Buffer.concat([ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), pngChunk("IHDR", header), pngChunk("IDAT", deflateSync(raw)), pngChunk("IEND", Buffer.alloc(0)), ]); } function toSvg(modules: boolean[][], margin: number): string { const width = modules.length + margin * 2; let path = ""; modules.forEach((row, y) => { row.forEach((dark, x) => { if (dark) path += `M${x + margin},${y + margin}h1v1h-1z`; }); }); return ( `` + `\n` ); } export default defineTool({ description: "Generates a scannable QR code image (PNG or SVG) offline for any text: a URL, a Wi-Fi login (WIFI:T:WPA;S:;P:;;), a vCard, a phone number (tel:...), an email (mailto:...) or plain text. Returns the image file. No API key needed.", input: Type.Object({ text: Type.String({ minLength: 1, maxLength: 2953, description: "What the QR code should contain", }), errorCorrection: Type.Optional( Type.Union([Type.Literal("L"), Type.Literal("M"), Type.Literal("Q"), Type.Literal("H")], { description: "How much damage the code survives: L 7%, M 15% (default), Q 25%, H 30%. Higher means a denser code.", }), ), format: Type.Optional( Type.Union([Type.Literal("png"), Type.Literal("svg")], { description: "Image format, png by default", }), ), scale: Type.Optional( Type.Integer({ minimum: 1, maximum: 20, description: "PNG pixels per QR module, 10 by default", }), ), }), output: Type.Object({ image: FilePath({ description: "Generated QR code image (.png or .svg)" }), version: Type.Integer({ description: "QR version, 1 (21x21) to 40 (177x177)" }), modules: Type.Integer({ description: "Width of the code in modules, without the quiet zone" }), errorCorrection: Type.String(), bytes: Type.Integer({ description: "Bytes of UTF-8 data encoded" }), }), handler: async ({ text, errorCorrection = "M", format = "png", scale = 10 }, ctx) => { const qr = encode(text, errorCorrection); const image = join(ctx.outputDir, `qr-code.${format}`); writeFileSync(image, format === "svg" ? toSvg(qr.modules, 4) : toPng(qr.modules, scale, 4)); ctx.log( "info", `Encoded ${qr.bytes} bytes as a version ${qr.version} QR code (${errorCorrection})`, ); return { image, version: qr.version, modules: qr.size, errorCorrection, bytes: qr.bytes }; }, });