qr-camera-scanner 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/llms.txt ADDED
@@ -0,0 +1,389 @@
1
+ # qr-camera-scanner
2
+
3
+ > Browser library for scanning QR codes and other barcodes with the device camera. Decoding runs in a Web Worker and frames are handed to it without a blocking copy on the page, so the page stays smooth. Uses the browser's BarcodeDetector where it supports the requested formats, otherwise ZXing-C++ compiled to WebAssembly (bundled, served from the app's own origin, no CDN). No UI and no framework dependency: the app draws its own interface.
4
+
5
+ This file is for AI assistants (any model) helping a developer use the package, and for people who want the full reference in one place. It describes version 0.1.x. The type definitions in `src/index.d.ts` are the authoritative API; if this file and the types ever disagree, trust the types.
6
+
7
+ ## Requirements (check these first)
8
+
9
+ - **A bundler** that understands `new Worker(new URL('./file.js', import.meta.url))` and `new URL('./file.wasm', import.meta.url)`: Vite, webpack 5, Parcel, Rollup with the usual plugins. It does not work as a plain `<script>` tag or from a CDN import.
10
+ - **HTTPS or localhost.** Browsers only allow the camera in a secure context. On plain HTTP over a network address, `start()` rejects and `cameraErrorKind(error)` returns `'insecure'`.
11
+ - **Content Security Policy**, if the site has one: `worker-src 'self'`, `script-src 'wasm-unsafe-eval'`, and `connect-src` must allow `'self'` (the worker fetches the `.wasm` file from your site). Browsers older than Chrome 97, Firefox 102 or Safari 16 do not know `'wasm-unsafe-eval'` and need `'unsafe-eval'` instead.
12
+ - **Browsers:** made for recent Chrome, Edge, Safari 15+ and Firefox 114+ (module workers are required). Tested so far in Chrome on Android and on desktop; Safari and Firefox are not tested yet.
13
+ - **Vite dev server:** works without configuration (tested with Vite 8). If a dev server cannot find the worker or the `.wasm` file, add `optimizeDeps: { exclude: ['qr-camera-scanner'] }` to the Vite config.
14
+ - **Server rendering (Next.js, Nuxt, SvelteKit, ...):** importing the package on the server is safe (it touches no browser API when imported). Create the scanner only in the browser: inside `useEffect` (React, in a `'use client'` component), `onMounted` (Vue), `onMount` (Svelte). Bundling through Next.js (webpack or Turbopack) has not been tested yet; Turbopack in particular may need checking.
15
+
16
+ ## Install
17
+
18
+ ```sh
19
+ npm install qr-camera-scanner
20
+ ```
21
+
22
+ ## Minimal example (plain JavaScript)
23
+
24
+ ```html
25
+ <div style="position: relative; width: 360px; height: 480px">
26
+ <video id="camera" style="width: 100%; height: 100%; object-fit: cover"></video>
27
+ <div id="frame" style="position: absolute; inset: 25%; border: 3px solid white"></div>
28
+ </div>
29
+ <p id="message"></p>
30
+ ```
31
+
32
+ ```js
33
+ import QrCameraScanner, { cameraErrorKind } from 'qr-camera-scanner';
34
+
35
+ const message = document.getElementById('message');
36
+
37
+ const scanner = new QrCameraScanner(
38
+ document.getElementById('camera'),
39
+ (result) => {
40
+ message.textContent = result.data;
41
+ },
42
+ {
43
+ region: document.getElementById('frame'), // read only inside the drawn box
44
+ repeatQuietMs: 3000, // report a code held up only once
45
+ },
46
+ );
47
+
48
+ try {
49
+ await scanner.start();
50
+ } catch (error) {
51
+ message.textContent = {
52
+ permission: 'Please allow the camera in your browser settings.',
53
+ 'no-camera': 'No camera found.',
54
+ 'in-use': 'The camera is used by another app.',
55
+ unsupported: 'This camera is not supported.',
56
+ insecure: 'The camera needs a secure (HTTPS) page.',
57
+ unknown: 'The camera could not start.',
58
+ }[cameraErrorKind(error)];
59
+ }
60
+
61
+ scanner.decoderReady().catch(() => {
62
+ message.textContent = 'The scanner could not load. Check your connection and reload.';
63
+ });
64
+ ```
65
+
66
+ ## Rules for code you write with this package
67
+
68
+ 1. **One scanner per `<video>` element, and always `destroy()` it** when the page, component or dialog goes away. A scanner that is not destroyed keeps the camera on. (`stop()` turns the camera off but keeps the scanner ready for `start()`; `destroy()` also frees its background worker.)
69
+ 2. **Do not set `srcObject`, call `play()`, or set `style.transform` on the video yourself.** The scanner manages the stream, playback and front-camera mirroring. It also sets `muted` and `playsinline`.
70
+ 3. **Style the video with `object-fit`** (usually `cover`) and put the region element on top of it, positioned over the video. The scanner maps the element's on-screen box to camera pixels using the video's `object-fit`; `object-position` must stay centered (the default).
71
+ 4. **What `onDecode` returns matters.** Returning `false` (synchronously) means "not now": the code is offered again on a following read, a fraction of a second later, while it is still in view. Anything else counts as accepted, including a Promise from an `async` function (if that Promise rejects, the error goes to `onError`). So write `(result) => { handle(result.data); }` with braces, not `(result) => handle(result.data)`, unless `handle` is meant to decline codes by returning `false`.
72
+ 5. **Use `repeatQuietMs`** (for example 3000) for most apps. With it, a code is reported once when it appears; while it stays in view it stays quiet; once it has been out of view for `repeatQuietMs` it counts as new again. Every recently seen code is remembered, so codes that take turns in front of the camera are each reported once. (One code is read per frame, so with two codes in view at the same time the second may not be read until the first leaves; use `region` to read one at a time.) Without it (the default `0`), a code held in front of the camera is reported on every read (up to 10 times a second). It is not a fixed "once per N seconds" timer; for that, keep your own timestamp and return `false` inside the window.
73
+ 6. **Call `QrCameraScanner.listCameras()` after `start()`.** Browsers hide camera names until the camera was allowed; labels may be empty strings, so have a fallback such as "Camera 1". The id of the camera in use is `scanner.track?.getSettings().deviceId`.
74
+ 7. **Show the torch and zoom controls only when available:** check `scanner.hasTorch()` and `scanner.zoomRange()` after `start()` and after `setCamera()`, since each camera differs. The video's `loadedmetadata` event fires for every new camera stream, including after the page was hidden and shown again, so it is a good moment to refresh such controls.
75
+ 8. **Errors:** `start()` and `setCamera()` reject with the browser's own error. Turn it into a message with `cameraErrorKind(error)`. Problems while running go to the `onError` option: a decoding problem, the camera disappearing (unplugged or taken by another app: a `NotReadableError`, after which `start()` opens it again), or a rejected Promise from `onDecode`. If the decoder cannot load at all, the camera is turned off, `onError` is told once and `decoderReady()` rejects; `start()` tries again.
76
+ 9. **Do not poll or restart the scanner** to "refresh" it. It turns the camera off while the page is hidden and back on when shown (`releaseWhenHidden`, on by default; a `start()` called while hidden opens the camera only once the page is shown), and keeps exactly one read loop. A scanner the user stopped with `stop()` stays stopped when the tab comes back. Camera operations (`start`, `setCamera`, `setTorch`) run one after another; one waiting for the user to answer the camera permission prompt makes the others wait too, while `stop()` and `destroy()` work at any moment (a `start()` still waiting then resolves without opening the camera).
77
+ 10. **Keeping the instance in reactive state is fine** (Vue `ref`/`reactive`, Alpine data, MobX). The scanner works through those proxies.
78
+ 11. **`wasmUrl` and `workerFactory` must point to files you serve yourself.** Never build them from user input (for example a URL parameter): code loaded there sees every camera frame.
79
+ 12. **Leaving the page:** destroying the scanner in `pagehide` is fine, but a page restored from the browser's back/forward cache then has no scanner; create a new one in `pageshow` when `event.persisted` is true.
80
+
81
+ ## React
82
+
83
+ ```jsx
84
+ import { useEffect, useRef, useState } from 'react';
85
+ import QrCameraScanner, { cameraErrorKind } from 'qr-camera-scanner';
86
+
87
+ export function Scanner({ onScan }) {
88
+ const videoRef = useRef(null);
89
+ const frameRef = useRef(null);
90
+ const onScanRef = useRef(onScan);
91
+ const [error, setError] = useState(null);
92
+
93
+ onScanRef.current = onScan; // always call the latest handler without restarting the camera
94
+
95
+ useEffect(() => {
96
+ let cancelled = false;
97
+ const scanner = new QrCameraScanner(
98
+ videoRef.current,
99
+ (result) => { onScanRef.current(result.data); },
100
+ { region: frameRef.current, repeatQuietMs: 3000 },
101
+ );
102
+ scanner.start().catch((e) => {
103
+ if (!cancelled) setError(cameraErrorKind(e));
104
+ });
105
+ return () => {
106
+ cancelled = true;
107
+ scanner.destroy();
108
+ };
109
+ }, []); // create once; React StrictMode's double run is safe (destroy, then a new scanner)
110
+
111
+ return (
112
+ <div style={{ position: 'relative', width: 360, height: 480 }}>
113
+ <video ref={videoRef} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
114
+ <div ref={frameRef} style={{ position: 'absolute', inset: '25%', border: '3px solid white' }} />
115
+ {error && <p>Camera problem: {error}</p>}
116
+ </div>
117
+ );
118
+ }
119
+ ```
120
+
121
+ ## Vue 3
122
+
123
+ ```vue
124
+ <script setup>
125
+ import { onBeforeUnmount, onMounted, ref } from 'vue';
126
+ import QrCameraScanner, { cameraErrorKind } from 'qr-camera-scanner';
127
+
128
+ const emit = defineEmits(['scan']);
129
+ const video = ref(null);
130
+ const frame = ref(null);
131
+ const error = ref(null);
132
+ let scanner = null;
133
+
134
+ onMounted(async () => {
135
+ scanner = new QrCameraScanner(video.value, (result) => { emit('scan', result.data); }, {
136
+ region: frame.value,
137
+ repeatQuietMs: 3000,
138
+ });
139
+ try {
140
+ await scanner.start();
141
+ } catch (e) {
142
+ error.value = cameraErrorKind(e);
143
+ }
144
+ });
145
+
146
+ onBeforeUnmount(() => scanner?.destroy());
147
+ </script>
148
+
149
+ <template>
150
+ <div style="position: relative; width: 360px; height: 480px">
151
+ <video ref="video" style="width: 100%; height: 100%; object-fit: cover"></video>
152
+ <div ref="frame" style="position: absolute; inset: 25%; border: 3px solid white"></div>
153
+ <p v-if="error">Camera problem: {{ error }}</p>
154
+ </div>
155
+ </template>
156
+ ```
157
+
158
+ ## Common tasks
159
+
160
+ Switch between front and back camera:
161
+
162
+ ```js
163
+ await scanner.setCamera(scanner.facingMode === 'user' ? 'environment' : 'user');
164
+ // If the new camera fails, the previous one is reopened and the error is thrown.
165
+ // Before start(), setCamera() only remembers the choice for start().
166
+ ```
167
+
168
+ Pick a camera by name (camera names are only known after the camera was allowed in this session, so start first). Names are whatever the device reports: on many Android phones they are like "camera2 0, facing back" and say nothing about the lens, so treat this as a best effort:
169
+
170
+ ```js
171
+ await scanner.start(); // opens the default back camera
172
+ const cameras = await QrCameraScanner.listCameras(); // [{ id, label }]
173
+ const main = cameras.find((camera) => /back|rear/i.test(camera.label)
174
+ && !/ultra|wide.?angle|tele|macro|depth|zoom/i.test(camera.label));
175
+ if (main) await scanner.setCamera(main.id).catch(() => {}); // on failure the previous camera stays
176
+
177
+ // a dropdown of all cameras, with the one in use selected:
178
+ const current = scanner.track?.getSettings().deviceId;
179
+ select.innerHTML = '';
180
+ cameras.forEach((camera, i) => select.add(new Option(camera.label || `Camera ${i + 1}`, camera.id, false, camera.id === current)));
181
+ select.onchange = () => {
182
+ scanner.setCamera(select.value).catch((error) => showMessage(cameraErrorKind(error)));
183
+ };
184
+ ```
185
+
186
+ Remember the chosen camera for next time: pass the saved id straight as the `camera` option (no switch after start). If that camera is gone, `start()` rejects (an `OverconstrainedError` or `NotFoundError`); forget the id and start with the default:
187
+
188
+ ```js
189
+ const saved = localStorage.getItem('cameraId');
190
+ let scanner = new QrCameraScanner(video, onScan, { camera: saved || 'environment' });
191
+ try {
192
+ await scanner.start();
193
+ } catch (error) {
194
+ if (!saved) throw error;
195
+ localStorage.removeItem('cameraId');
196
+ scanner.destroy();
197
+ scanner = new QrCameraScanner(video, onScan, { camera: 'environment' });
198
+ await scanner.start();
199
+ }
200
+ // after the user picks one: localStorage.setItem('cameraId', id)
201
+ ```
202
+
203
+ Torch (flash) button:
204
+
205
+ ```js
206
+ torchButton.hidden = !scanner.hasTorch();
207
+ torchButton.onclick = async () => {
208
+ const on = await scanner.setTorch(!scanner.isTorchOn());
209
+ torchButton.classList.toggle('active', on);
210
+ };
211
+ ```
212
+
213
+ Zoom slider:
214
+
215
+ ```js
216
+ const range = scanner.zoomRange(); // { min, max, step } or null
217
+ if (range) {
218
+ slider.min = range.min; slider.max = range.max; slider.step = range.step;
219
+ slider.oninput = () => scanner.setZoom(Number(slider.value));
220
+ }
221
+ ```
222
+
223
+ Ignore codes while the app is busy (for example while a request is running or a dialog is open):
224
+
225
+ ```js
226
+ let busy = false;
227
+ const scanner = new QrCameraScanner(video, (result) => {
228
+ if (busy) return false; // not now: offered again on a following read
229
+ busy = true;
230
+ sendToServer(result.data).then(
231
+ () => { busy = false; scanner.restartQuiet(); }, // done: keep the code quiet while it is still held up
232
+ () => {
233
+ // Failed: allow the same code again, but not at once, so a server that
234
+ // is down is not hit up to 10 times a second.
235
+ setTimeout(() => { busy = false; scanner.forgetLastCode(); }, 2000);
236
+ },
237
+ );
238
+ }, { repeatQuietMs: 5000 });
239
+ ```
240
+
241
+ Offer the torch when it is too dark:
242
+
243
+ ```js
244
+ const scanner = new QrCameraScanner(video, onScan, {
245
+ onDarkChange: (dark) => {
246
+ torchHint.hidden = !(dark && scanner.hasTorch() && !scanner.isTorchOn());
247
+ },
248
+ });
249
+ ```
250
+
251
+ Read other barcode types:
252
+
253
+ ```js
254
+ new QrCameraScanner(video, onScan, { formats: ['qr_code', 'ean_13', 'ean_8', 'code_128'] });
255
+ // result.format tells which one was read.
256
+ ```
257
+
258
+ Find out why scanning is slow on a device:
259
+
260
+ ```js
261
+ const scanner = new QrCameraScanner(video, onScan, { collectStats: true });
262
+ setInterval(() => console.log(scanner.stats()), 1000);
263
+ // readsPerSecond, readMs.avg / readMs.max, engine, picture size, luma (brightness), ...
264
+ ```
265
+
266
+ Stop reading for a while but keep the camera picture: `scanner.pause()` and later `scanner.resume()`. Turn the camera off: `scanner.stop()` (start again with `start()`), or `scanner.destroy()` for good.
267
+
268
+ ## API reference
269
+
270
+ ### Imports
271
+
272
+ ```js
273
+ import QrCameraScanner from 'qr-camera-scanner'; // default export
274
+ import {
275
+ QrCameraScanner, // same class
276
+ cameraErrorKind, // camera error -> kind
277
+ DEFAULT_OPTIONS, // every default value
278
+ frameRegion, // building blocks for custom setups:
279
+ centerRegion,
280
+ RepeatFilter,
281
+ DarkWatch,
282
+ ReadStats,
283
+ } from 'qr-camera-scanner';
284
+ ```
285
+
286
+ Extra entry points for setups without worker bundling: `qr-camera-scanner/worker` (the worker module; it imports `barcode-detector`, so it still has to be bundled) and `qr-camera-scanner/zxing_reader.wasm`. Pass them with the `workerFactory` and `wasmUrl` options.
287
+
288
+ ### TypeScript
289
+
290
+ Types ship with the package (`src/index.d.ts`); no `@types` package is needed. Import the ones you need:
291
+
292
+ ```ts
293
+ import QrCameraScanner, {
294
+ cameraErrorKind,
295
+ type QrCameraScannerOptions, // the constructor's options
296
+ type ScanResult, // { data, format, cornerPoints }
297
+ type ScannerStats, // what stats() returns
298
+ type CameraErrorKind, // 'permission' | 'no-camera' | 'in-use' | 'unsupported' | 'insecure' | 'unknown'
299
+ type DecoderInfo, // what decoderReady() resolves to
300
+ type FacingMode, // 'environment' | 'user'
301
+ type Region, // { x, y, width, height } in camera pixels
302
+ type ObjectFit, // 'cover' | 'contain' | 'fill' | 'none' | 'scale-down'
303
+ } from 'qr-camera-scanner';
304
+ ```
305
+
306
+ ### `new QrCameraScanner(video, onDecode, options?)`
307
+
308
+ - `video`: an `HTMLVideoElement`. Throws `TypeError` if it is not one.
309
+ - `onDecode(result)`: called with each new code. `result` is `{ data: string, format: string, cornerPoints: Array<{ x, y }> }` (corner points in camera picture pixels). Return `false` synchronously to decline the code for now; a returned Promise counts as accepted, and its rejection goes to `onError`.
310
+ - `options`: see below.
311
+
312
+ ### Options
313
+
314
+ | Option | Default | Meaning |
315
+ |---|---|---|
316
+ | `camera` | `'environment'` | `'environment'` (back), `'user'` (front), or a deviceId from `listCameras()` |
317
+ | `formats` | `['qr_code']` | barcode formats, as BarcodeDetector names them: `'qr_code'`, `'ean_13'`, `'ean_8'`, `'upc_a'`, `'upc_e'`, `'code_128'`, `'code_39'`, `'code_93'`, `'codabar'`, `'itf'`, `'data_matrix'`, `'aztec'`, `'pdf417'`, ... The browser's detector is used only if it supports all of them. `result.format` uses the same names. |
318
+ | `region` | `null` | an element drawn over the video (only codes inside it are read), a function `(video) => ({ x, y, width, height })` in camera pixels (returning `null` reads nothing for that frame), or `null` for the middle of the picture |
319
+ | `centerRegionShare` | `2/3` | size of the middle area read when no region applies, as a share of the picture's shorter side |
320
+ | `repeatQuietMs` | `0` | report the same code again only after it was out of view this long (ms); `0` reports every read |
321
+ | `maxScansPerSecond` | `10` | upper limit on reads per second (0.1 to 120) |
322
+ | `width`, `height` | `1280`, `720` | preferred camera picture size |
323
+ | `videoConstraints` | `null` | extra `getUserMedia` video constraints, e.g. `{ frameRate: { ideal: 30 } }` |
324
+ | `mirrorFrontCamera` | `true` | show the front camera mirrored |
325
+ | `meterOnRegion` | `true` | ask the camera to focus and expose on the scan area, where supported |
326
+ | `releaseWhenHidden` | `true` | turn the camera off while the page is hidden and back on when shown |
327
+ | `preferNative` | `true` | use the browser's BarcodeDetector when possible |
328
+ | `onError` | `null` | `(error) => {}` for problems while running |
329
+ | `onDarkChange` | `null` | `(dark: boolean) => {}` when the scan area becomes too dark to read, and when it is light again |
330
+ | `darkThreshold` | `50` | brightness (0 to 255) below which it counts as dark |
331
+ | `darkForMs` | `2000` | how long it must stay dark before `onDarkChange(true)` |
332
+ | `darkCheckIntervalMs` | `1000` | how often brightness is measured |
333
+ | `collectStats` | `false` | keep statistics for `stats()` |
334
+ | `statsWindowMs` | `2000` | the time window `stats()` averages over (100 to 60000) |
335
+ | `wasmUrl` | bundled file | where to load `zxing_reader.wasm` from; must be a file you serve, never user input |
336
+ | `workerFactory` | bundled worker | `() => Worker`, for custom setups; same rule as `wasmUrl` |
337
+
338
+ Invalid numbers fall back to the default instead of throwing.
339
+
340
+ ### Methods
341
+
342
+ | Method | Returns | Notes |
343
+ |---|---|---|
344
+ | `start()` | `Promise<void>` | opens the camera and starts reading; rejects with the browser's camera error; also retries a decoder that failed to load |
345
+ | `decoderReady()` | `Promise<{ engine: 'native' \| 'zxing', acceptsBitmap: boolean }>` | rejects if the decoder files cannot load or do not answer within 30 s (offline, CSP, missing file); the camera is then turned off until `start()` is called again. The same happens later if one frame takes more than 10 s to decode (a stuck decoder); `onError` gets a `TimeoutError` |
346
+ | `pause()` / `resume()` | `void` | stop / continue reading; the camera stays on |
347
+ | `stop()` | `void` | camera off; `start()` turns it on again |
348
+ | `destroy()` | `void` | camera off and background worker released; the instance cannot start again |
349
+ | `setCamera(camera)` | `Promise<void>` | switch camera (`'environment'`, `'user'` or a device id from `listCameras()`); on failure the previous one is reopened and the error rethrown; before `start()` it only remembers the choice; switches requested at the same time run one after the other |
350
+ | `hasTorch()` / `isTorchOn()` | `boolean` | |
351
+ | `setTorch(on)` / `toggleTorch()` | `Promise<boolean>` | resolves to whether the torch is on; may reject if the camera has to be reopened to turn the light off and that fails |
352
+ | `zoomRange()` | `{ min, max, step } \| null` | |
353
+ | `setZoom(value)` | `Promise<number \| null>` | the camera's zoom now, or `null` without zoom or when refused |
354
+ | `scanRegion()` | `{ x, y, width, height } \| null` | the area being read, in camera pixels |
355
+ | `applySettings()` | `Promise<boolean>` | re-applies focus, zoom and torch (done automatically for every new stream) |
356
+ | `stats()` | object or `null` | with `collectStats`: `readsPerSecond`, `readMs: { avg, max }`, `reads`, `codes`, `errors`, `luma`, `engine`, `picture: { width, height }`, `frameRate`, `facingMode`, `region`, `torch`, `zoom` |
357
+ | `forgetLastCode()` | `void` | the last code is reported again on its next read |
358
+ | `restartQuiet()` | `void` | the `repeatQuietMs` wait starts over now |
359
+ | `QrCameraScanner.listCameras()` | `Promise<Array<{ id, label }>>` | static; call after `start()` |
360
+
361
+ ### Properties (read-only)
362
+
363
+ `video`, `options` (with defaults filled in), `track` (the live `MediaStreamTrack` or `null`), `facingMode` (`'user'`, `'environment'` or `null`), `engine` (`'native'`, `'zxing'` or `null`), `isDark`.
364
+
365
+ ### `cameraErrorKind(error)`
366
+
367
+ Returns `'permission'` (blocked by the user or browser), `'no-camera'`, `'in-use'` (another app holds the camera), `'unsupported'` (the camera cannot do what was asked), `'insecure'` (not HTTPS or localhost), or `'unknown'`. Works on errors from `start()` / `setCamera()` and on those passed to `onError` (a camera that disappeared while scanning gives `'in-use'`; it may also have been unplugged, so a message like "The camera stopped. Check that it is connected and not used by another app." fits both). After such an error, `start()` reopens the camera; no `stop()` is needed first.
368
+
369
+ ## Troubleshooting
370
+
371
+ | Symptom | Likely cause and fix |
372
+ |---|---|
373
+ | `start()` rejects, kind `'insecure'` | page is not HTTPS or localhost; serve it securely (for phone testing, use an HTTPS tunnel or deploy) |
374
+ | `start()` rejects, kind `'permission'` | the camera was blocked; the user must allow it in the browser's site settings, then reload |
375
+ | the camera turns off by itself shortly after starting (at the latest after 30 s), `decoderReady()` rejects | the worker or `.wasm` file did not load: check the CSP (`worker-src 'self'`, `'wasm-unsafe-eval'`), that the build includes the files, or try `optimizeDeps.exclude` on a dev server |
376
+ | `onError` gets a `NotReadableError` while scanning | the camera was unplugged or taken by another app; call `start()` again (for example from a "Retry" button) |
377
+ | codes outside the drawn box are read, or codes inside are not | the region element is not over the video, the video has no `object-fit`, or `object-position` was changed |
378
+ | the same code fires many times | set `repeatQuietMs` |
379
+ | a code is never read again after an error | call `scanner.forgetLastCode()` when handling it failed |
380
+ | camera stays on after leaving the page or component | `destroy()` was not called on unmount |
381
+ | camera names are empty or generic | call `listCameras()` after `start()` |
382
+ | torch or zoom buttons do nothing | check `hasTorch()` / `zoomRange()`; many cameras (most front cameras, desktop webcams) have neither, and browser support varies |
383
+ | scanning feels slow on one device | turn on `collectStats` and look at `readMs`, `readsPerSecond` and `picture`; lower `width`/`height` or `maxScansPerSecond` |
384
+
385
+ ## Links
386
+
387
+ - Demo: https://daviddawe.github.io/qr-camera-scanner/
388
+ - Source and issues: https://github.com/daviddawe/qr-camera-scanner
389
+ - Types (authoritative API): `src/index.d.ts` in the package
package/package.json CHANGED
@@ -1,6 +1,80 @@
1
1
  {
2
2
  "name": "qr-camera-scanner",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Fast QR code and barcode scanner for the browser camera that keeps the page smooth on every phone. Decodes in a Web Worker (BarcodeDetector or ZXing WebAssembly), reads only inside your scan box, with torch, zoom, camera switching and TypeScript types. Works with React, Vue and plain JavaScript.",
5
+ "author": "daviddawe",
6
+ "license": "MIT",
7
+ "homepage": "https://daviddawe.github.io/qr-camera-scanner/",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/daviddawe/qr-camera-scanner.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/daviddawe/qr-camera-scanner/issues"
14
+ },
15
+ "type": "module",
16
+ "main": "./src/index.js",
17
+ "module": "./src/index.js",
18
+ "types": "./src/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./src/index.d.ts",
22
+ "default": "./src/index.js"
23
+ },
24
+ "./worker": "./src/decode-worker.js",
25
+ "./zxing_reader.wasm": "./src/zxing_reader.wasm",
26
+ "./package.json": "./package.json"
27
+ },
28
+ "files": [
29
+ "src",
30
+ "README.md",
31
+ "MIGRATING.md",
32
+ "CHANGELOG.md",
33
+ "llms.txt",
34
+ "LICENSE",
35
+ "THIRD_PARTY_LICENSES"
36
+ ],
37
+ "sideEffects": false,
38
+ "scripts": {
39
+ "prepare": "node scripts/copy-wasm.mjs",
40
+ "prepack": "node scripts/copy-wasm.mjs",
41
+ "test": "node --test \"test/*.test.js\"",
42
+ "lint": "eslint .",
43
+ "typecheck": "tsc -p test/types/tsconfig.json",
44
+ "check": "npm run lint && npm run typecheck && npm test",
45
+ "demo": "node scripts/copy-wasm.mjs && vite --config demo/vite.config.js",
46
+ "demo:build": "node scripts/copy-wasm.mjs && vite build --config demo/vite.config.js"
47
+ },
48
+ "keywords": [
49
+ "qr",
50
+ "qr-code",
51
+ "qrcode",
52
+ "qr-scanner",
53
+ "qr-code-scanner",
54
+ "qr-reader",
55
+ "barcode",
56
+ "barcode-scanner",
57
+ "barcode-reader",
58
+ "scanner",
59
+ "camera",
60
+ "webcam",
61
+ "getusermedia",
62
+ "barcodedetector",
63
+ "zxing",
64
+ "wasm",
65
+ "web-worker",
66
+ "react",
67
+ "vue",
68
+ "typescript"
69
+ ],
70
+ "dependencies": {
71
+ "barcode-detector": "3.2.5"
72
+ },
73
+ "devDependencies": {
74
+ "@eslint/js": "^9.39.5",
75
+ "eslint": "^9.39.5",
76
+ "globals": "^17.14.0",
77
+ "typescript": "^5.9.3",
78
+ "vite": "^8.4.0"
79
+ }
80
+ }
package/src/camera.js ADDED
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Camera helpers: opening a stream, reading a track's abilities, and building
3
+ * the one constraint set the scanner applies. No scanner state lives here.
4
+ *
5
+ * @module qr-camera-scanner/camera
6
+ */
7
+
8
+ /**
9
+ * @typedef {'environment' | 'user'} FacingMode
10
+ * @typedef {{ facingMode: FacingMode } | { deviceId: string }} CameraChoice
11
+ */
12
+
13
+ /** Track labels that name a front camera when the facing mode is not reported. */
14
+ const FRONT_CAMERA_LABEL = /front|user|face/i;
15
+
16
+ /**
17
+ * 'environment' and 'user' select by facing mode; anything else is a deviceId.
18
+ *
19
+ * @param {FacingMode | string} camera
20
+ * @returns {CameraChoice}
21
+ */
22
+ export function cameraChoice(camera) {
23
+ return camera === 'environment' || camera === 'user' ? { facingMode: camera } : { deviceId: String(camera) };
24
+ }
25
+
26
+ /**
27
+ * The getUserMedia video constraints for a camera choice. Size and facing are
28
+ * `ideal`, so a camera that cannot match still opens; a deviceId is `exact`.
29
+ *
30
+ * @param {CameraChoice} choice
31
+ * @param {{ width: number, height: number, videoConstraints?: MediaTrackConstraints | null }} options
32
+ * @returns {MediaTrackConstraints}
33
+ */
34
+ export function videoConstraintsFor(choice, options) {
35
+ /** @type {MediaTrackConstraints} */
36
+ const video = {
37
+ width: { ideal: options.width },
38
+ height: { ideal: options.height },
39
+ };
40
+ if ('deviceId' in choice) {
41
+ video.deviceId = { exact: choice.deviceId };
42
+ } else {
43
+ video.facingMode = { ideal: choice.facingMode };
44
+ }
45
+ return { ...video, ...(options.videoConstraints || {}) };
46
+ }
47
+
48
+ /**
49
+ * Opens a camera stream. Rejects with the browser's own error; without a
50
+ * camera API at all (an insecure page) with a NotSupportedError.
51
+ *
52
+ * @param {MediaTrackConstraints} video
53
+ * @returns {Promise<MediaStream>}
54
+ */
55
+ export function openStream(video) {
56
+ const devices = globalThis.navigator && navigator.mediaDevices;
57
+ if (!devices || typeof devices.getUserMedia !== 'function') {
58
+ return Promise.reject(new DOMException('Camera API not available (insecure context?)', 'NotSupportedError'));
59
+ }
60
+ return devices.getUserMedia({ video, audio: false });
61
+ }
62
+
63
+ /**
64
+ * @param {MediaStream | null} stream
65
+ */
66
+ export function stopStream(stream) {
67
+ if (stream) {
68
+ stream.getTracks().forEach((track) => track.stop());
69
+ }
70
+ }
71
+
72
+ /**
73
+ * @param {MediaStream | null} stream
74
+ * @returns {MediaStreamTrack | null}
75
+ */
76
+ export function videoTrackOf(stream) {
77
+ return stream ? stream.getVideoTracks()[0] || null : null;
78
+ }
79
+
80
+ /**
81
+ * @param {MediaStreamTrack | null} track
82
+ * @returns {Record<string, any>}
83
+ */
84
+ export function capabilitiesOf(track) {
85
+ return track && typeof track.getCapabilities === 'function' ? track.getCapabilities() : {};
86
+ }
87
+
88
+ /**
89
+ * @param {MediaStreamTrack | null} track
90
+ * @returns {Record<string, any>}
91
+ */
92
+ export function settingsOf(track) {
93
+ return track && typeof track.getSettings === 'function' ? track.getSettings() : {};
94
+ }
95
+
96
+ /**
97
+ * Whether the track has a torch: it reports the capability, or (some
98
+ * browsers) only a torch setting.
99
+ *
100
+ * @param {MediaStreamTrack | null} track
101
+ * @returns {boolean}
102
+ */
103
+ export function hasTorch(track) {
104
+ return !!track && (!!capabilitiesOf(track).torch || 'torch' in settingsOf(track));
105
+ }
106
+
107
+ /**
108
+ * @param {MediaStreamTrack | null} track
109
+ * @returns {{ min: number, max: number, step: number } | null}
110
+ */
111
+ export function zoomRangeOf(track) {
112
+ const zoom = capabilitiesOf(track).zoom;
113
+ return zoom ? { min: zoom.min, max: zoom.max, step: zoom.step } : null;
114
+ }
115
+
116
+ /**
117
+ * Which way the track's camera faces: the reported setting, else a guess
118
+ * from its label, else what was asked for.
119
+ *
120
+ * @param {MediaStreamTrack | null} track
121
+ * @param {CameraChoice} requested
122
+ * @returns {FacingMode | null}
123
+ */
124
+ export function facingModeOf(track, requested) {
125
+ const reported = settingsOf(track).facingMode;
126
+ if (reported === 'user' || reported === 'environment') {
127
+ return reported;
128
+ }
129
+ if (track && FRONT_CAMERA_LABEL.test(track.label || '')) {
130
+ return 'user';
131
+ }
132
+ return 'facingMode' in requested ? requested.facingMode : null;
133
+ }
134
+
135
+ /**
136
+ * The `advanced` constraint list for everything the scanner sets on a camera:
137
+ * continuous exposure and focus, a point of interest, zoom and torch. One set
138
+ * per setting, so a camera that lacks one still takes the others.
139
+ *
140
+ * @param {object} input
141
+ * @param {Record<string, any>} input.capabilities track.getCapabilities()
142
+ * @param {Record<string, any>} input.supported navigator.mediaDevices.getSupportedConstraints()
143
+ * @param {boolean} input.meter focus and expose on the scan area
144
+ * @param {{ x: number, y: number } | null} input.pointOfInterest 0..1 of the picture
145
+ * @param {number | null} input.zoom
146
+ * @param {boolean} input.torchAvailable
147
+ * @param {boolean} input.torch
148
+ * @returns {MediaTrackConstraintSet[]}
149
+ */
150
+ export function advancedConstraints({ capabilities, supported, meter, pointOfInterest, zoom, torchAvailable, torch }) {
151
+ const advanced = [];
152
+ if (meter) {
153
+ if (Array.isArray(capabilities.exposureMode) && capabilities.exposureMode.includes('continuous')) {
154
+ advanced.push({ exposureMode: 'continuous' });
155
+ }
156
+ if (Array.isArray(capabilities.focusMode) && capabilities.focusMode.includes('continuous')) {
157
+ advanced.push({ focusMode: 'continuous' });
158
+ }
159
+ if (supported.pointsOfInterest && pointOfInterest) {
160
+ advanced.push({ pointsOfInterest: [pointOfInterest] });
161
+ }
162
+ }
163
+ if (capabilities.zoom && zoom != null) {
164
+ advanced.push({ zoom });
165
+ }
166
+ if (torchAvailable) {
167
+ advanced.push({ torch });
168
+ }
169
+ return /** @type {MediaTrackConstraintSet[]} */ (advanced);
170
+ }