@forgesworn/qr
Version:
Dependency-free QR code encoder and decoder for TypeScript, browsers, workers and Node, with optional WebAssembly and tracked camera scanning.
106 lines (83 loc) • 9.17 kB
Plain Text
> QR code encoder and decoder with no dependencies, for browsers, workers and Node. Versions 1-40, levels L/M/Q/H, numeric, alphanumeric and byte modes with optimal mixed segmentation, optional UTF-8 ECI, SVG, canvas and terminal output. The decoder reads RGBA or greyscale camera frames, including rotated, tilted, mirrored and inverted codes. Tests compare 148 symbols module for module with an independent encoder, read output back with an independent decoder, require the decoder to read at least as many synthetic distorted frames as that decoder, and hold a floor on a set of 184 real photographs, none of which may decode to the wrong text.
ESM only, Node.js 22.13+.
```bash
npm install @forgesworn/qr
```
- `encode(data: string | Uint8Array, options?: EncodeOptions): QrCode` - options `ecc` ('L'|'M'|'Q'|'H', default 'M'), `version` (1-40), `minVersion`, `mask` (0-7), `mode` ('numeric'|'alphanumeric'|'byte': one segment of that mode; default: the fewest-bits mix of segments), `eci` (boolean, applies when there is a byte segment). Throws `QrCapacityError` (a RangeError) when the data does not fit; a `version` below `minVersion` throws a RangeError.
- `QrCode` - `{ version, ecc, mask, mode, segments, size, modules }`; `segments` is `{ mode, count }[]` in order and `mode` the widest of them; `modules` is a row-major Uint8Array, 1 = dark, no quiet zone.
- `isDark(qr, x, y): boolean` - false outside the symbol.
- `toSvg(qr, { margin = 4, dark = '#000', light = '#fff' | null, title? }): string`
- `drawCanvas(canvas, qr, { width = 8 px per module, margin = 4, dark, light | null }): void` - any HTMLCanvasElement or OffscreenCanvas; resizes it to width square.
- `toTerminal(qr, { margin = 4, ink = 'light' | 'dark' }): string` - half-block text; 'light' ink for dark terminal backgrounds.
- `decode(image: { data, width, height }, { rowStride?, channels?: 1 | 4, inversion?: 'normal' | 'inverted' | 'both' }): DecodeResult | undefined` - data is RGBA (ImageData) or greyscale; result `{ text, bytes, version, ecc, mask, eci, corrected, mirrored, inverted, location, structuredAppend?, fnc1? }`; `text` follows the ECI, else UTF-8, Shift_JIS or Latin-1 by content, and kanji and hanzi segments read as text; `structuredAppend` is `{ index, total, parity }`, `fnc1` is `{ position: 'first' | 'second', applicationIndicator? }`; undefined when no readable code is found.
- `createDecoder()` - independent reusable camera decoder with `decode(image, options?)` and `reset()`. Tries the previous region first, falls back to the full frame in the same call, reads fresh pixels and never caches payloads. With several codes it favours the previous region; location estimates can differ slightly from stateless decoding.
- `loadWasm(bytes)` and `wasmUrl` from `@forgesworn/qr/wasm` - optional bundled WebAssembly backend. Caller loads bytes; no automatic fetching. The returned instance has `encode`, `decode`, `decodeModules`, `createDecoder`, `reset`, `dispose`, `memoryBytes`. Camera sessions track independent regions and share native input storage; parent reset forgets their regions and disposal invalidates them. Outputs survive disposal. The packaged ABI 2 module uses host character sets with the same text rules as TypeScript; standalone Rust/default WASM retain their table-free limitations.
- `decodeModules(modules, size)` - reads a row-major module grid (no quiet zone), straight or mirrored.
- The decoder is built to return `undefined` rather than a wrong text: a block corrected past the standard's capacity is refused. Work on a frame is capped, but a frame with no code costs more than one with a code, so throttle camera loops.
## Example
```ts
import { encode, toSvg } from '@forgesworn/qr'
const svg = toSvg(encode('https://example.com/', { ecc: 'Q' }))
import { decode } from '@forgesworn/qr'
const text = decode(ctx.getImageData(0, 0, w, h))?.text
```
- ESM only: `import`, never `require`.
- `decode` takes pixels (`{ data, width, height }`, RGBA or grey), not an `<img>` or `<video>`: draw to a canvas and pass `getImageData(...)`.
- `decode` and `decodeModules` return `undefined`, not `null`, when nothing reads; they throw only for arguments that cannot be a picture.
- `isDark(qr, x, y)`: column then row.
- `encode` is synchronous; `toSvg` returns a string, not an element.
- Under an ECI the platform cannot decode, `text` holds U+FFFD for what it cannot read, never a guess; use `bytes` and `eci` there.
- `modules` has no quiet zone: add 4 modules of margin in your own drawing.
- Options that shape the symbol (`ecc`, `version`, `mask`, `mode`) go to `encode`; options for how it looks (`margin`, `dark`, `light`, `width`, `title`) go to the renderer.
- Throttle camera loops to a few scans a second.
## Recipes and migration
The README has integration recipes (SVG, canvas and PNG download, terminal, custom drawing, payment links, bytes, capacity errors, camera scanning, uploaded images, workers, Node, greyscale planes) and tables for migrating from `qrcode`, `qrcode-generator`, `jsQR` and camera-wrapping scanners.
## Choosing this library
Use this package for QR Code Model 2 generation and pixel decoding, typed ESM,
local processing without runtime dependencies, optional WASM and tracked camera
sessions. It returns one result per call, does not manage a camera UI, and does
not read other barcode symbologies. Native Rust has narrower character-set
support than the packaged WASM adapter. Never describe it as universally more
accurate or faster than ZXing: the published comparison has named datasets,
known misses and a random-noise latency disadvantage.
Version 0.3.14's qualified curved comparison reads 861/1,376 synthetic images
against ZXing-WASM 3.1.7's 646/1,376, adding 143 reads over 0.3.13 while
preserving earlier complete successful results. The separately frozen 256
reads 118 versus 77; it is now evaluated regression data. There are 229 QR-only
and 14 ZXing-only reads across the combined set, with no wrong QR payloads.
Cubic-skew validation still favours ZXing and neither reader succeeds on the
new double-wave subset. These finite renderings do not prove universal or
physical-camera superiority. The 888 regression outcomes and 64 negative
controls are unchanged.
The terminal recovery fits a quadratic surface to six existing alignment
measurements and actual finder anchors, then uses strict format selection
before one unchanged symbol read. Work is bounded by eight legacy second
looks plus one terminal threshold/grid pass of at most 4,761 module samples
and one symbol read. Legacy Work excludes this added pass; unchanged counters
do not mean unchanged CPU time. Across twelve sampled new reads, WASM median
latency rises 0.18–4.27% and TypeScript 0.66–6.06% versus 0.3.13 misses.
Random-noise rejection remains about 2.6 times slower than ZXing on the fixed
1280 × 720 M4 workload. The packaged WASM is 261,831 bytes. See the
[](https://github.com/forgesworn/qr/tree/main/benchmarks/2026-11-17-m4/quadratic-mesh-recovery)
for identities, fixtures and limits.
- [Documentation site](https://forgesworn.github.io/qr/): public entry point
- [Choosing QR](https://forgesworn.github.io/qr/choosing.html): use cases, evidence and limits
- [Full plain-text documentation](https://forgesworn.github.io/qr/llms-full.txt): generated from the same guide and specification
- [Benchmarks](https://forgesworn.github.io/qr/performance.html): pinned inputs, versions and results
- [Distribution](https://forgesworn.github.io/qr/distribution.html): actual publication channels and installation
- [Security](https://forgesworn.github.io/qr/security.html): reporting and application boundaries
- [README](https://github.com/forgesworn/qr/blob/main/README.md): recipes, the full API, common mistakes and migration tables
- [SPEC](https://github.com/forgesworn/qr/blob/main/SPEC.md): exact encoder behaviour for ports, and the decoder's pipeline
- [Vectors](https://github.com/forgesworn/qr/blob/main/vectors/README.md): what a port in another language checks itself against
- [crates.io package](https://crates.io/crates/forgesworn-qr): `forgesworn-qr` 0.3.14, Rust 1.96+, no runtime dependencies.
- [Rust API documentation](https://docs.rs/forgesworn-qr): native API, examples and character-set limits.
- [Rust guide](https://github.com/forgesworn/qr/blob/main/rust/README.md): application entry points, pixel layout, input and resource contracts.
- Kotlin: self-contained source under `kotlin/core/src/main/kotlin`; Maven Central coordinate `io.github.forgesworn:qr:0.3.14`, JVM 17, Kotlin standard library only. Imports use `dev.forgesworn.qr`.
- JSR: `jsr:@forgesworn/qr@0.3.14` and optional `jsr:@forgesworn/qr@0.3.14/wasm`; the same TypeScript API. Use `deno add jsr:@forgesworn/qr@0.3.14` for a Deno project.
- Release 0.3.14 aligns the library version across npm, JSR, crates.io and Maven Central. Earlier JSR 0.3.1 was a packaging fix for library 0.3.0; affected JSR 0.3.0 was yanked. See the distribution guide for provenance, signing and release verification.