@qrcode-ai-com/qrcode-barcode-scanner-wasm
Version:
QR and barcode decoding + scannability scoring — one portable browser WASM with camera, tracking and overlay modules, plus optional URL destination checks
152 lines (142 loc) • 7.9 kB
JavaScript
// A module worker that owns one scanner for the page that starts it. It knows nothing about
// that page: the image example and a camera page can share it. Start it with
// new Worker(new URL('./scanner.worker.js', import.meta.url), { type: 'module' })
// and post requests { id, type, ... }. Every request gets one reply carrying the same id:
// { id, type: 'load' }
// -> { id, type, ok: true, version, variant, runtime, capabilities }
// runtime: what this browser supports, { wasm, simd, baseline } (scannerCapabilities()
// of ../auto.js); capabilities: the readers compiled into the loaded module,
// { versions, engines, symbologies } (its capabilities()).
// { id, type: 'scan_image', bytes, ...options }
// -> { id, type, ok: true, report, ms } bytes: the encoded image (an ArrayBuffer or a view)
// { id, type: 'scan_frame', rgba, width, height, ...options }
// -> { id, type, ok: true, report, ms } rgba: width * height * 4 bytes, row by row
// options are the named options of scan() and scanFrame() in ../scan.js (ScanOptions), each a
// field of the request and each left out at will: profile, formats, budgetMs, retryBudgetMs,
// maxDimension, maxPixels, scoreSkipAxes, scoreSkipChecks, scorePreset, alphaBackground and
// alphaPalette. profile is a profile name and budgetMs a number of milliseconds (0: no time
// budget); an editor that reads QR codes only, and scans once more with no limit when its
// budget cut the first scan, posts
// { id, type: 'scan_image', bytes, formats: ['qr_code'], budgetMs: 800, retryBudgetMs: 0 }
// report is the report of the last scan the request ran, and ms the time of all of them.
// When a request fails, the reply is { id, type, ok: false, phase, error }
// where phase is 'load' (the scanner could not load), 'scan' (the engine refused the call or
// its input, or stopped) or 'request' (the message itself is malformed: an unknown type, missing
// bytes, a field that is no option, or an option of the wrong type). Transfer a large buffer
// instead of copying it: postMessage(request, [bytes]) for an ArrayBuffer, [bytes.buffer] for a
// typed array, which is not transferable itself. The transfer detaches the whole buffer, with
// every view on it. Requests run one at a time, in the order they arrive.
import { createScannerLoader, scannerCapabilities } from '../auto.js';
// One attempt for the life of this worker: every request shares it, a failure included.
// Terminating the worker and starting a new one is the explicit retry. `load` is that attempt's
// Promise, which the worker keeps itself: a loader alone starts over after a failed request or
// read (ScannerInitError.retryable).
let load = null;
const QRS_CODE = /\[(QRS-\d{3})\]/;
// An error rebuilt from plain fields: an Error object does not keep its own fields (code,
// status, cause) across postMessage in every browser.
function describe(error) {
const object = error !== null && typeof error === 'object';
const message = object && error.message !== undefined ? String(error.message) : String(error);
const qrs = QRS_CODE.exec(message);
const cause = object && error.cause !== undefined && error.cause !== null ? error.cause : null;
return {
name: object && error.name ? String(error.name) : 'Error',
message,
// A loader failure names its stable code (ScannerInitError); a scan fault ends with [QRS-xxx].
code: object && typeof error.code === 'string' ? error.code : null,
qrs: qrs ? qrs[1] : null,
status: object && typeof error.status === 'number' ? error.status : null,
cause: cause === null ? null : {
name: typeof cause === 'object' && cause.name ? String(cause.name) : 'Error',
message: typeof cause === 'object' && cause.message !== undefined
? String(cause.message) : String(cause),
},
};
}
function malformed(text) {
const error = new TypeError(text);
error.malformed = true;
return error;
}
function bytesOf(value, what) {
if (value instanceof ArrayBuffer) return new Uint8Array(value);
if (ArrayBuffer.isView(value)) {
return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
}
throw malformed(`${what} must be an ArrayBuffer or a typed array`);
}
// The named options of scan() and scanFrame() in ../scan.js (ScanOptions), and the type this
// worker checks before the scanner receives each: a string, a number or a list of names. The
// engine judges the values.
const OPTION_KINDS = Object.freeze({ profile: 'string', formats: 'names', budgetMs: 'number',
retryBudgetMs: 'number', maxDimension: 'number', maxPixels: 'number', scoreSkipAxes: 'names',
scoreSkipChecks: 'names', scorePreset: 'string', alphaBackground: 'string',
alphaPalette: 'names' });
const OPTION_KEYS = Object.freeze(Object.keys(OPTION_KINDS));
// The fields of each scan request that are not options.
const REQUEST_FIELDS = Object.freeze({ scan_image: Object.freeze(['id', 'type', 'bytes']),
scan_frame: Object.freeze(['id', 'type', 'rgba', 'width', 'height']) });
// The options of one scan request, checked. A field that is neither the request's own nor an
// option is a malformed request: a misspelling such as budget_ms would otherwise run a default
// scan without a word. So is an option of the wrong type: the binding would coerce it (a budget
// given as text becomes NaN, which means no time budget) or fail with an unrelated error.
function optionsOf(message) {
const options = {};
for (const key of Object.keys(message)) {
if (REQUEST_FIELDS[message.type].includes(key)) continue;
if (!OPTION_KEYS.includes(key)) {
throw malformed(`${message.type}: unknown option ${JSON.stringify(key)}; the options are ` +
OPTION_KEYS.join(', '));
}
const value = message[key];
if (value === undefined) continue;
const kind = OPTION_KINDS[key];
if (kind === 'names') {
if (!Array.isArray(value) || !value.every((name) => typeof name === 'string')) {
throw malformed(`${message.type} ${key} must be an array of strings when given`);
}
} else if (typeof value !== kind) {
throw malformed(`${message.type} ${key} must be a ${kind} when given`);
}
options[key] = value;
}
return options;
}
// One request through the scanner's named scan() or scanFrame(): one scan, and one more when the
// request carries retryBudgetMs and the time budget cut the first.
function scan(scanner, message) {
const options = optionsOf(message);
if (message.type === 'scan_image') {
return scanner.scan(bytesOf(message.bytes, 'scan_image bytes'), options);
}
const rgba = bytesOf(message.rgba, 'scan_frame rgba');
return scanner.scanFrame({ data: rgba, width: message.width, height: message.height }, options);
}
self.onmessage = async (event) => {
const message = event.data !== null && typeof event.data === 'object' ? event.data : {};
const { id, type } = message;
let phase = 'request';
try {
if (type !== 'load' && type !== 'scan_image' && type !== 'scan_frame') {
throw malformed(`unknown request type ${JSON.stringify(type)}`);
}
phase = 'load';
if (load === null) load = createScannerLoader()();
const scanner = await load;
if (type === 'load') {
self.postMessage({ id, type, ok: true, version: scanner.version(), variant: scanner.variant,
runtime: scannerCapabilities(), capabilities: scanner.capabilities() });
return;
}
phase = 'scan';
const started = performance.now();
const report = scan(scanner, message);
self.postMessage({ id, type, ok: true, report, ms: performance.now() - started });
} catch (error) {
const malformedRequest = error !== null && typeof error === 'object'
&& error.malformed === true;
self.postMessage({ id, type, ok: false, phase: malformedRequest ? 'request' : phase,
error: describe(error) });
}
};