/** * QR Code encoder for the LAN Share pairing URL. * * One compact, dependency-free encoder: byte mode, error-correction level M, * versions 1 through 10 — enough for a LAN URL of a few hundred characters at * a module count a tablet camera reads comfortably. The implementation follows * ISO/IEC 18004: data codewords with terminator and pad bytes, Reed-Solomon * blocks over GF(256), the standard interleaving, function patterns, the eight * data masks with the specification's penalty scoring, and the BCH-protected * format and version information. * * The encoder is deliberately pure: it returns the module matrix and never * touches the DOM, so the same code can be tested in Node and rendered as SVG * by either half of the plugin. */ /** Error-correction level M: 15 format bits value 0b00. */ const ECC_FORMAT_BITS = 0b00; /** * Byte-mode data capacity per version at level M: one or two block groups, * each group a count and the data codewords in one block, plus the ECC * codewords every block carries. */ const VERSIONS = { 1: { ecc: 10, groups: [[1, 16]] }, 2: { ecc: 16, groups: [[1, 28]] }, 3: { ecc: 26, groups: [[1, 44]] }, 4: { ecc: 18, groups: [[2, 32]] }, 5: { ecc: 24, groups: [[2, 43]] }, 6: { ecc: 16, groups: [[4, 27]] }, 7: { ecc: 18, groups: [[4, 31]] }, 8: { ecc: 22, groups: [[2, 38], [2, 39]] }, 9: { ecc: 22, groups: [[3, 36], [2, 37]] }, 10: { ecc: 26, groups: [[4, 43], [1, 44]] }, }; /** Alignment-pattern centre coordinates per version (empty for version 1). */ const ALIGNMENT = { 1: [], 2: [6, 18], 3: [6, 22], 4: [6, 26], 5: [6, 30], 6: [6, 34], 7: [6, 22, 38], 8: [6, 24, 42], 9: [6, 26, 46], 10: [6, 28, 50], }; /** Highest version this encoder produces. */ const MAX_VERSION = 10; /** Penalty weights from ISO/IEC 18004 table 24. */ const PENALTY_N1 = 3; const PENALTY_N2 = 3; const PENALTY_N3 = 40; const PENALTY_N4 = 10; /** GF(256) tables, primitive polynomial x^8 + x^4 + x^3 + x^2 + 1 (0x11d). */ const GF_EXP = new Uint8Array(512); const GF_LOG = new Uint8Array(256); (function buildGaloisTables() { let value = 1; for (let i = 0; i < 255; i++) { GF_EXP[i] = value; GF_LOG[value] = i; value <<= 1; if ((value & 0x100) !== 0) value ^= 0x11d; } for (let i = 255; i < 512; i++) GF_EXP[i] = GF_EXP[i - 255]; })(); /** * Multiply two field elements. * @param {number} a first element. * @param {number} b second element. * @returns {number} the product. */ function gfMultiply(a, b) { if (a === 0 || b === 0) return 0; return GF_EXP[GF_LOG[a] + GF_LOG[b]]; } /** * Reed-Solomon generator polynomial of the given degree. * @param {number} degree number of ECC codewords. * @returns {Uint8Array} coefficients, highest order first. */ function reedSolomonGenerator(degree) { const result = new Uint8Array(degree); result[degree - 1] = 1; let root = 1; for (let i = 0; i < degree; i++) { for (let j = 0; j < degree; j++) { result[j] = gfMultiply(result[j], root); if (j + 1 < degree) result[j] ^= result[j + 1]; } root = gfMultiply(root, 0x02); } return result; } /** * Reed-Solomon remainder of one data block. * @param {Uint8Array} data data codewords of the block. * @param {Uint8Array} generator generator polynomial. * @returns {Uint8Array} ECC codewords for the block. */ function reedSolomonRemainder(data, generator) { const result = new Uint8Array(generator.length); for (const byte of data) { const factor = byte ^ result[0]; result.copyWithin(0, 1); result[result.length - 1] = 0; for (let i = 0; i < result.length; i++) result[i] ^= gfMultiply(generator[i], factor); } return result; } /** * Number of data bits a version reserves for the byte-mode character count. * @param {number} version QR version. * @returns {number} 8 for versions 1-9 and 16 from version 10. */ function charCountBits(version) { return version <= 9 ? 8 : 16; } /** * Data capacity in whole bytes for one version. * @param {number} version QR version. * @returns {number} bytes available to mode, length and payload. */ function dataCapacityBytes(version) { const spec = VERSIONS[version]; const codewords = spec.groups.reduce((sum, [count, length]) => sum + count * length, 0); return codewords; } /** * Largest payload this encoder accepts in one version. * @param {number} version QR version. * @returns {number} payload byte budget. */ function payloadCapacityBytes(version) { return Math.floor((dataCapacityBytes(version) * 8 - 4 - charCountBits(version)) / 8); } /** * Choose the smallest version that fits the payload. * @param {number} length payload length in bytes. * @returns {number} a version between 1 and {@link MAX_VERSION}. * @throws {RangeError} when the payload is too long for version 10. */ function chooseVersion(length) { for (let version = 1; version <= MAX_VERSION; version++) { if (length <= payloadCapacityBytes(version)) return version; } throw new RangeError('qr: payload is too long for a version-10 QR code'); } /** * Append the low bits of a value to a growing bit array. * @param {number[]} bits destination. * @param {number} value bits to append. * @param {number} length how many bits of value to append, most significant first. */ function appendBits(bits, value, length) { if (length < 0 || length > 31 || value >>> length !== 0) throw new RangeError('qr: bit append out of range'); for (let i = length - 1; i >= 0; i--) bits.push((value >>> i) & 1); } /** * Assemble the data codewords: mode indicator, character count, payload, * terminator, byte padding and the alternating pad bytes. * @param {Uint8Array} bytes payload bytes. * @param {number} version QR version. * @returns {Uint8Array} data codewords before ECC. */ function buildDataCodewords(bytes, version) { const bits = []; appendBits(bits, 0b0100, 4); appendBits(bits, bytes.length, charCountBits(version)); for (const byte of bytes) appendBits(bits, byte, 8); const capacity = dataCapacityBytes(version); const capacityBits = capacity * 8; appendBits(bits, 0, Math.min(4, capacityBits - bits.length)); appendBits(bits, 0, (8 - (bits.length % 8)) % 8); const codewords = new Uint8Array(capacity); for (let i = 0; i < bits.length; i += 8) { let value = 0; for (let j = 0; j < 8; j++) value = (value << 1) | bits[i + j]; codewords[i >>> 3] = value; } for (let i = bits.length >>> 3, pad = 0xec; i < capacity; i++, pad ^= 0xec ^ 0x11) codewords[i] = pad; return codewords; } /** * Split data codewords into blocks and interleave data with ECC codewords. * @param {Uint8Array} codewords data codewords. * @param {number} version QR version. * @returns {Uint8Array} final codeword sequence. */ function interleave(codewords, version) { const spec = VERSIONS[version]; const generator = reedSolomonGenerator(spec.ecc); const blocks = []; let offset = 0; for (const [count, length] of spec.groups) { for (let i = 0; i < count; i++) { const block = codewords.slice(offset, offset + length); offset += length; blocks.push({ data: block, ecc: reedSolomonRemainder(block, generator) }); } } const result = []; const maxData = Math.max(...blocks.map((block) => block.data.length)); for (let i = 0; i < maxData; i++) { for (const block of blocks) if (i < block.data.length) result.push(block.data[i]); } for (let i = 0; i < spec.ecc; i++) { for (const block of blocks) result.push(block.ecc[i]); } return Uint8Array.from(result); } /** * BCH(15,5) format bits with the specification's mask. * @param {number} mask data mask 0-7. * @returns {number} 15 format bits. */ function formatBits(mask) { const data = (ECC_FORMAT_BITS << 3) | mask; let remainder = data; for (let i = 0; i < 10; i++) remainder = (remainder << 1) ^ ((remainder >>> 9) * 0x537); return ((data << 10) | remainder) ^ 0x5412; } /** * BCH(18,6) version bits. * @param {number} version QR version, 7 or higher. * @returns {number} 18 version bits. */ function versionBits(version) { let remainder = version; for (let i = 0; i < 12; i++) remainder = (remainder << 1) ^ ((remainder >>> 11) * 0x1f25); return (version << 12) | remainder; } /** * Query one bit of a value, counting from the least significant bit. * @param {number} value source value. * @param {number} index bit index. * @returns {boolean} true for a set bit. */ function bit(value, index) { return ((value >>> index) & 1) !== 0; } /** * One QR matrix under construction. */ class Matrix { /** * @param {number} size side length in modules. */ constructor(size) { this.size = size; this.modules = Array.from({ length: size }, () => new Array(size).fill(false)); this.reserved = Array.from({ length: size }, () => new Array(size).fill(false)); } /** * Set a module and mark it as a function pattern. * @param {number} row row index. * @param {number} col column index. * @param {boolean} dark whether the module is dark. */ setFunction(row, col, dark) { this.modules[row][col] = dark; this.reserved[row][col] = true; } /** * Draw a finder pattern and its separator. * @param {number} row centre row. * @param {number} col centre column. */ drawFinder(row, col) { for (let dy = -4; dy <= 4; dy++) { for (let dx = -4; dx <= 4; dx++) { const y = row + dy; const x = col + dx; if (y < 0 || y >= this.size || x < 0 || x >= this.size) continue; const distance = Math.max(Math.abs(dx), Math.abs(dy)); this.setFunction(y, x, distance !== 2 && distance !== 4); } } } /** * Draw one 5x5 alignment pattern. * @param {number} row centre row. * @param {number} col centre column. */ drawAlignment(row, col) { for (let dy = -2; dy <= 2; dy++) { for (let dx = -2; dx <= 2; dx++) { this.setFunction(row + dy, col + dx, Math.max(Math.abs(dx), Math.abs(dy)) !== 1); } } } } /** * Draw all fixed function patterns for one version. * @param {Matrix} matrix destination. * @param {number} version QR version. */ function drawFunctionPatterns(matrix, version) { const size = matrix.size; matrix.drawFinder(3, 3); matrix.drawFinder(3, size - 4); matrix.drawFinder(size - 4, 3); for (let i = 8; i < size - 8; i++) { const dark = i % 2 === 0; matrix.setFunction(6, i, dark); matrix.setFunction(i, 6, dark); } const centres = ALIGNMENT[version]; for (const row of centres) { for (const col of centres) { if ((row === 6 && col === 6) || (row === 6 && col === size - 7) || (row === size - 7 && col === 6)) continue; matrix.drawAlignment(row, col); } } /* Reserve the format-information areas. */ for (let i = 0; i <= 8; i++) { if (i !== 6) { matrix.setFunction(8, i, false); matrix.setFunction(i, 8, false); } } for (let i = 0; i < 8; i++) matrix.setFunction(8, size - 1 - i, false); for (let i = 8; i < 15; i++) matrix.setFunction(size - 15 + i, 8, false); matrix.setFunction(size - 8, 8, true); if (version >= 7) { for (let i = 0; i < 18; i++) { const a = size - 11 + (i % 3); const b = Math.floor(i / 3); matrix.setFunction(b, a, false); matrix.setFunction(a, b, false); } } } /** * Draw the two format-information copies. * @param {Matrix} matrix destination. * @param {number} mask data mask. */ function drawFormatBits(matrix, mask) { const size = matrix.size; const bits = formatBits(mask); for (let i = 0; i <= 5; i++) matrix.setFunction(i, 8, bit(bits, i)); matrix.setFunction(7, 8, bit(bits, 6)); matrix.setFunction(8, 8, bit(bits, 7)); matrix.setFunction(8, 7, bit(bits, 8)); for (let i = 9; i < 15; i++) matrix.setFunction(8, 14 - i, bit(bits, i)); for (let i = 0; i < 8; i++) matrix.setFunction(8, size - 1 - i, bit(bits, i)); for (let i = 8; i < 15; i++) matrix.setFunction(size - 15 + i, 8, bit(bits, i)); matrix.setFunction(size - 8, 8, true); } /** * Draw the two version-information copies (versions 7 and above). * @param {Matrix} matrix destination. * @param {number} version QR version. */ function drawVersionBits(matrix, version) { if (version < 7) return; const size = matrix.size; const bits = versionBits(version); for (let i = 0; i < 18; i++) { const a = size - 11 + (i % 3); const b = Math.floor(i / 3); matrix.setFunction(b, a, bit(bits, i)); matrix.setFunction(a, b, bit(bits, i)); } } /** * Place the final codeword stream into the remaining modules in zigzag order. * @param {Matrix} matrix destination. * @param {Uint8Array} codewords interleaved codewords. */ function drawCodewords(matrix, codewords) { const size = matrix.size; let index = 0; for (let right = size - 1; right >= 1; right -= 2) { if (right === 6) right = 5; for (let vertical = 0; vertical < size; vertical++) { for (let j = 0; j < 2; j++) { const col = right - j; const upward = ((right + 1) & 2) === 0; const row = upward ? size - 1 - vertical : vertical; if (matrix.reserved[row][col] || index >= codewords.length * 8) continue; matrix.modules[row][col] = ((codewords[index >>> 3] >>> (7 - (index & 7))) & 1) !== 0; index++; } } } } /** * Whether the data mask inverts one module. * @param {number} mask mask index 0-7. * @param {number} row module row. * @param {number} col module column. * @returns {boolean} true when the module flips. */ function maskCondition(mask, row, col) { switch (mask) { case 0: return (row + col) % 2 === 0; case 1: return row % 2 === 0; case 2: return col % 3 === 0; case 3: return (row + col) % 3 === 0; case 4: return (Math.floor(row / 2) + Math.floor(col / 3)) % 2 === 0; case 5: return ((row * col) % 2) + ((row * col) % 3) === 0; case 6: return (((row * col) % 2) + ((row * col) % 3)) % 2 === 0; case 7: return (((row + col) % 2) + ((row * col) % 3)) % 2 === 0; default: throw new RangeError('qr: mask must be 0-7'); } } /** * Apply one mask to every non-function module. * @param {Matrix} matrix matrix to modify. * @param {number} mask mask index 0-7. */ function applyMask(matrix, mask) { for (let row = 0; row < matrix.size; row++) { for (let col = 0; col < matrix.size; col++) { if (!matrix.reserved[row][col] && maskCondition(mask, row, col)) matrix.modules[row][col] = !matrix.modules[row][col]; } } } /** * Finder-like pattern history helpers used by penalty rule 3. */ function addHistory(runLength, history, size) { if (history[0] === 0) runLength += size; history.pop(); history.unshift(runLength); } function countPatterns(history) { const n = history[1]; const core = n > 0 && history[2] === n && history[3] === n * 3 && history[4] === n && history[5] === n; return (core && history[0] >= n * 4 && history[6] >= n ? 1 : 0) + (core && history[6] >= n * 4 && history[0] >= n ? 1 : 0); } function terminateAndCount(runColor, runLength, history, size) { if (runColor) { addHistory(runLength, history, size); runLength = 0; } runLength += size; addHistory(runLength, history, size); return countPatterns(history); } /** * Specification penalty score of one masked matrix. * @param {Matrix} matrix masked matrix. * @returns {number} penalty; lower is better. */ function penaltyScore(matrix) { const size = matrix.size; const modules = matrix.modules; let result = 0; for (let row = 0; row < size; row++) { let runColor = false; let runLength = 0; const history = [0, 0, 0, 0, 0, 0, 0]; for (let col = 0; col < size; col++) { if (modules[row][col] === runColor) { runLength++; if (runLength === 5) result += PENALTY_N1; else if (runLength > 5) result++; } else { addHistory(runLength, history, size); if (!runColor) result += countPatterns(history) * PENALTY_N3; runColor = modules[row][col]; runLength = 1; } } result += terminateAndCount(runColor, runLength, history, size) * PENALTY_N3; } for (let col = 0; col < size; col++) { let runColor = false; let runLength = 0; const history = [0, 0, 0, 0, 0, 0, 0]; for (let row = 0; row < size; row++) { if (modules[row][col] === runColor) { runLength++; if (runLength === 5) result += PENALTY_N1; else if (runLength > 5) result++; } else { addHistory(runLength, history, size); if (!runColor) result += countPatterns(history) * PENALTY_N3; runColor = modules[row][col]; runLength = 1; } } result += terminateAndCount(runColor, runLength, history, size) * PENALTY_N3; } for (let row = 0; row < size - 1; row++) { for (let col = 0; col < size - 1; col++) { const color = modules[row][col]; if (color === modules[row][col + 1] && color === modules[row + 1][col] && color === modules[row + 1][col + 1]) { result += PENALTY_N2; } } } let dark = 0; for (const row of modules) for (const cell of row) if (cell) dark++; const total = size * size; const k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1; result += k * PENALTY_N4; return result; } /** * Encode one payload into a QR module matrix. * @param {string} text payload, encoded as UTF-8 bytes. * @param {{ mask?: number, minVersion?: number, maxVersion?: number }} [options] * a fixed mask for tests, or version bounds for callers that need a minimum size. * @returns {{ version: number, size: number, mask: number, rows: string[] }} * the chosen version, side length, mask, and one string of '0'/'1' per row. */ export function encodeQr(text, options = {}) { if (typeof text !== 'string') throw new TypeError('qr: text must be a string'); const bytes = new TextEncoder().encode(text); let version = chooseVersion(bytes.length); if (options.minVersion !== undefined) { if (!Number.isInteger(options.minVersion) || options.minVersion < 1 || options.minVersion > MAX_VERSION) { throw new RangeError('qr: minVersion must be an integer between 1 and 10'); } version = Math.max(version, options.minVersion); } if (options.maxVersion !== undefined) { if (!Number.isInteger(options.maxVersion) || options.maxVersion < 1 || options.maxVersion > MAX_VERSION) { throw new RangeError('qr: maxVersion must be an integer between 1 and 10'); } if (version > options.maxVersion) throw new RangeError('qr: payload does not fit the requested maximum version'); } const codewords = interleave(buildDataCodewords(bytes, version), version); const size = version * 4 + 17; const base = new Matrix(size); drawFunctionPatterns(base, version); drawCodewords(base, codewords); const masks = options.mask === undefined ? [0, 1, 2, 3, 4, 5, 6, 7] : [options.mask]; let best; let bestPenalty = Infinity; for (const mask of masks) { const candidate = new Matrix(size); candidate.modules = base.modules.map((row) => row.slice()); candidate.reserved = base.reserved.map((row) => row.slice()); applyMask(candidate, mask); drawFormatBits(candidate, mask); drawVersionBits(candidate, version); const penalty = penaltyScore(candidate); if (penalty < bestPenalty) { bestPenalty = penalty; best = { mask, matrix: candidate }; } } return { version, size, mask: best.mask, rows: best.matrix.modules.map((row) => row.map((dark) => (dark ? '1' : '0')).join('')), }; } export const qrInternals = { payloadCapacityBytes, chooseVersion, formatBits, versionBits, penaltyScore };