k-qr-scanner 0.0.0-stage → 0.3.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.
Files changed (50) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE +30 -0
  4. package/README.md +337 -2
  5. package/THIRD_PARTY_NOTICES.md +11 -0
  6. package/app.plugin.d.ts +6 -0
  7. package/app.plugin.js +27 -0
  8. package/dist/autozoom.d.ts +43 -0
  9. package/dist/chunks/chunk-PUUIGXID.js +149 -0
  10. package/dist/chunks/engine-EJ4OC3LZ.js +1 -0
  11. package/dist/cli.js +481 -0
  12. package/dist/element.d.ts +135 -0
  13. package/dist/emv.d.ts +89 -0
  14. package/dist/engine.d.ts +104 -0
  15. package/dist/formats.d.ts +8 -0
  16. package/dist/index.cjs +149 -0
  17. package/dist/index.d.ts +12 -0
  18. package/dist/index.js +1 -0
  19. package/dist/kqrcode.engine.js +1 -0
  20. package/dist/kqrcode.global.js +150 -0
  21. package/dist/kqrcode.jsqr.js +1 -0
  22. package/dist/react-native.d.ts +78 -0
  23. package/dist/react.cjs +2 -0
  24. package/dist/react.d.ts +54 -0
  25. package/dist/react.js +2 -0
  26. package/dist/rn/index.js +53 -0
  27. package/dist/rn/package.json +1 -0
  28. package/dist/rn/runtime.js +1 -0
  29. package/dist/scan-qr.d.ts +49 -0
  30. package/dist/scanner.d.ts +174 -0
  31. package/dist/sr-entry.d.ts +5 -0
  32. package/dist/sr-providers.d.ts +19 -0
  33. package/dist/sr.cjs +1 -0
  34. package/dist/sr.d.ts +19 -0
  35. package/dist/sr.js +1 -0
  36. package/dist/svelte.cjs +1 -0
  37. package/dist/svelte.d.ts +56 -0
  38. package/dist/svelte.js +1 -0
  39. package/dist/vue.cjs +1 -0
  40. package/dist/vue.d.ts +87 -0
  41. package/dist/vue.js +1 -0
  42. package/licenses/WECHAT_QRCODE-Apache-2.0.txt +253 -0
  43. package/licenses/fflate-MIT.txt +21 -0
  44. package/licenses/jsQR-Apache-2.0.txt +202 -0
  45. package/licenses/zxing-cpp-Apache-2.0.txt +202 -0
  46. package/licenses/zxing-wasm-MIT.txt +21 -0
  47. package/llms.txt +77 -0
  48. package/models/wechat_sr.onnx +0 -0
  49. package/package.json +145 -4
  50. package/react-native/package.json +6 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,78 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses [Semantic Versioning](https://semver.org/). Until 1.0, minor versions may contain breaking changes.
4
+
5
+ ## [Unreleased]
6
+
7
+ ## [0.3.0] – 2026-11-21
8
+
9
+ ### Added
10
+
11
+ - **Payment QR codes (EMV)**: `parseEMV()` reads LAO QR, PromptPay, VietQR, DuitNow, QRIS, UnionPay and other EMVCo merchant codes into fields (merchant, amount, currency, accounts, bill number…) and checks the CRC. `acceptEMV({ currency, country, accounts, dynamicOnly, message, check })` is a ready-made `accept` callback that lets only intact payment codes through. `emvCRC()` computes the checksum. Exported from the main entry and from `k-qr-scanner/react-native`; tree-shakeable.
12
+ - **`layout="bar"`** (`layout` prop and option everywhere): flashlight on the left, a large album button in the middle and your own button on the right, in one row, as in many banking apps.
13
+ - Slots `banner` (under the top bar, e.g. a "supported QR" strip) and `actions-center`; part `banner`.
14
+ - **Capacitor**: `npx k-qr-scanner init` and `doctor` add and check the camera permissions in the native iOS and Android projects. New guide `docs/MOBILE.md` for PWAs, Capacitor, native `WKWebView` and Android `WebView`, and Flutter.
15
+ - CSS variables `--kqr-frame-border` and `--kqr-gallery-bg`, `--kqr-gallery-size`, `--kqr-gallery-radius`. `--kqr-corner-width: 0` hides the frame corners.
16
+
17
+ ### Changed
18
+
19
+ - **Package 2.4 MB → 750 kB** (unpacked 4.4 → 1.4 MB, 89 → 50 files). The ESM, CJS, `<script>` and React Native builds now share one engine file and one jsQR file (`kqrcode.engine.js` and `kqrcode.jsqr.js`, both ES modules loaded with `import()`) instead of four and three copies; source maps and internal type files are no longer published. Apps still get the engine as a separate, lazily loaded chunk.
20
+ - Self-hosted script builds: `kqrcode.engine.js` is now an ES module, so serve it as `text/javascript`, with CORS headers when it comes from another origin.
21
+
22
+ ### Improved
23
+
24
+ - **Codes filmed off a screen**: the engine recognizes the moiré of a display's pixel grid and decodes a smoothed copy of the frame. With strong moiré, a dense payment code at 3–4 px per module went from 2/8 to 8/8 frames.
25
+ - **Farthest and rotated codes**: the crop around a located code is now sized for any rotation plus the quiet zone; it used to cut the corners off rotated codes. Codes at 1.5 px per module: 17 % → 38 % (WeChat's open-source engine: 29 %); all frames: 65 % → 69 %.
26
+
27
+ ## [0.2.0] – 2026-11-21
28
+
29
+ ### Changed
30
+
31
+ - **New package name: `k-qr-scanner`** (was `kqr-scanner`). Imports become `k-qr-scanner`, `k-qr-scanner/react` and so on, and the CLI is `npx k-qr-scanner`. The `<kqr-scanner>` element, the `KQRCode` global and the `kqrcode.*.js` file names are unchanged.
32
+ - Documentation rewritten.
33
+ - **Smaller engine**: 631 → 458 kB gzip (−27 %), 1.5 MB → 648 kB raw. The WebAssembly is gzip-compressed inside the engine and inflated with `DecompressionStream`; jsQR is no longer bundled in the worker; the super-resolution weights are read from the ONNX model instead of being shipped twice.
34
+ - **Smaller `<script>` build**: `kqrcode.global.js` 63 → 17 kB gzip. The engine loads from `kqrcode.engine.js` next to it on first use.
35
+ - **Smaller package**: 2.4 → 1.8 MB tarball. CJS entries share a single engine file.
36
+ - **Faster**: the finder-pattern locator is 2.5× faster (block thresholds). Frames without a code take 24 ms instead of 34 ms at 1080p, and live analysis runs at ~19 fps instead of ~13 fps in Chrome.
37
+ - **Faster restarts**: one decoding worker is shared and kept warm (`QRScanner.engineIdleTimeout`, default 30 s). `QRScanner.preload()` now also compiles the WebAssembly.
38
+
39
+ ### Added
40
+
41
+ - **React Native** (`k-qr-scanner/react-native`): a `<QRScanner>` component for iOS, Android and Expo. It runs the same scanner in `react-native-webview` with the engine bundled (works offline), and carries over every prop, `accept`, `formats` and events. Extras: `cssVars`, HTML `slots` with `onSlotPress`, `keepCamera`, `scriptUrl`, and ref methods. The component asks for the Android camera permission itself, releases the camera while the app is in the background, and reloads if the OS kills the WebView process.
42
+ - **Expo config plugin**: `"plugins": ["k-qr-scanner"]` adds the iOS and Android camera permission entries (`cameraPermission` sets the iOS text).
43
+ - `npx k-qr-scanner init` for React Native / Expo installs `react-native-webview`, writes the camera permission entries (the Expo plugin in app.json, or Info.plist + AndroidManifest.xml) and a starter component; `doctor` checks them.
44
+ - `<kqr-scanner>`: read-only `active` property; `resume()` reopens the camera when it was already stopped.
45
+ - **Every QR format**: Micro QR (M1–M4) and rMQR are read alongside QR Code (Model 1 and 2). `ScanResult.format` is now `'qr_code' | 'micro_qr_code' | 'rm_qr_code'`, and results carry `version` and `ecLevel`. Auto-zoom and tracking use the real module count of each symbol.
46
+ - `formats` option (`scanQR`, `QRScanner`, wrappers) and `formats` attribute to limit which QR-family members are read. `QR_FORMATS` lists them.
47
+ - **`accept` callback**: check a code before it counts. Return `true` to accept, `false` to ignore it and keep scanning, or a string to ignore it and show that message. May be async. A turned-down code is not re-checked while it stays in view. Also applies to album photos. New `reject` event / `onReject` everywhere; `QRScanner.setFormats()` and `setAccept()`.
48
+ - `QRScanner.dispose()` and `QRScanner.engineIdleTimeout`.
49
+
50
+ ### Fixed
51
+
52
+ - iOS: the camera came back black after the app or tab was in the background; the scanner now reopens it.
53
+
54
+ ### Removed
55
+
56
+ - The undocumented `decodeFrame` export.
57
+
58
+ ## [0.1.0] – 2026-11-19
59
+
60
+ First public release.
61
+
62
+ ### Added
63
+
64
+ - `<kqr-scanner>`: a full-screen scanner custom element that scans anywhere in the camera view, at any angle.
65
+ - Decoder: ZXing-C++ (WebAssembly) in a Web Worker, with jsQR as a fallback when workers or WASM are blocked.
66
+ - Detection of codes that are too small to decode (a finder-pattern locator and a texture detector), driving auto-zoom.
67
+ - Auto-zoom with hardware zoom where available; on iOS Safari, digital zoom on a 4K stream.
68
+ - Optional super-resolution with WeChat's CNN: built-in kernel, or ONNX Runtime Web (WebGPU / WASM).
69
+ - Themes `wechat`, `alipay`, `grid`, `frame` and `none`, plus CSS variables, `::part()` and slots.
70
+ - `scanQR()` one-call API and the headless `QRScanner` class.
71
+ - React, Vue and Svelte wrappers; Angular and plain HTML through the custom element; SSR-safe imports.
72
+ - `npx kqr-scanner init` and `npx kqr-scanner doctor` CLI.
73
+ - English, Lao and Chinese labels.
74
+
75
+ [Unreleased]: https://github.com/kris-lx/kqrcode/compare/v0.3.0...HEAD
76
+ [0.3.0]: https://github.com/kris-lx/kqrcode/compare/v0.2.0...v0.3.0
77
+ [0.2.0]: https://github.com/kris-lx/kqrcode/compare/v0.1.0...v0.2.0
78
+ [0.1.0]: https://github.com/kris-lx/kqrcode/releases/tag/v0.1.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kris
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,30 @@
1
+ k-qr-scanner
2
+ Copyright (c) 2026 kris
3
+
4
+ This product includes software and models developed by third parties:
5
+
6
+ 1. WeChat QRCode super-resolution model ("sr.caffemodel" / "sr.prototxt")
7
+ Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
8
+ Licensed under the Apache License, Version 2.0 – see licenses/WECHAT_QRCODE-Apache-2.0.txt
9
+ Source: https://github.com/WeChatCV/opencv_3rdparty/tree/wechat_qrcode
10
+ MODIFICATIONS: the original Caffe weights were converted, without retraining or
11
+ changing any weight values, by scripts/convert-sr.py into
12
+ - models/wechat_sr.onnx (ONNX format), and
13
+ - src/sr-weights.generated.ts (raw float32 array for a JavaScript re-implementation
14
+ of the same network in src/sr.ts).
15
+
16
+ 2. ZXing-C++ (compiled to WebAssembly and bundled in the decoding worker)
17
+ Copyright (c) the ZXing-C++ authors. Licensed under the Apache License, Version 2.0
18
+ – see licenses/zxing-cpp-Apache-2.0.txt. Source: https://github.com/zxing-cpp/zxing-cpp
19
+
20
+ 3. zxing-wasm (JavaScript bindings for ZXing-C++), Copyright (c) 2023 Ze-Zheng Wu,
21
+ MIT License – see licenses/zxing-wasm-MIT.txt. Source: https://github.com/Sec-ant/zxing-wasm
22
+
23
+ 4. jsQR (fallback decoder), Copyright (c) the jsQR authors. Apache License, Version 2.0
24
+ – see licenses/jsQR-Apache-2.0.txt. Source: https://github.com/cozmo/jsQR
25
+
26
+ 5. fflate (gzip fallback for browsers without DecompressionStream), Copyright (c) 2023 Arjun Barrett.
27
+ MIT License – see licenses/fflate-MIT.txt. Source: https://github.com/101arrowz/fflate
28
+
29
+ ONNX Runtime Web (MIT, Microsoft) is NOT bundled; it is only loaded at runtime from a URL
30
+ you configure when superResolution: 'webgpu' is used.
package/README.md CHANGED
@@ -1,3 +1,338 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
+ <br />
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/logo-dark.svg" />
5
+ <img src="docs/assets/logo.svg" alt="k-qr-scanner" width="360" />
6
+ </picture>
2
7
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
8
+ <p><strong>A WeChat-style QR code scanner for the web and React Native</strong></p>
9
+
10
+ <p>
11
+ <a href="https://www.npmjs.com/package/k-qr-scanner"><img src="https://img.shields.io/npm/v/k-qr-scanner?style=for-the-badge&logo=npm&color=CB3837" alt="npm version"></a>
12
+ <a href="https://github.com/kris-lx/kqrcode/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/kris-lx/kqrcode/ci.yml?branch=main&label=tests&style=for-the-badge&logo=github" alt="Tests"></a>
13
+ <a href="#size"><img src="https://img.shields.io/badge/initial_load-14_kB_gzip-07c160?style=for-the-badge" alt="14 kB gzip"></a>
14
+ <a href="https://www.typescriptlang.org/"><img src="https://img.shields.io/badge/TypeScript-ready-3178C6?style=for-the-badge&logo=typescript&logoColor=white" alt="TypeScript"></a>
15
+ <a href="LICENSE"><img src="https://img.shields.io/github/license/kris-lx/kqrcode?style=for-the-badge&color=blue" alt="License"></a>
16
+ </p>
17
+
18
+ <img src="docs/assets/themes.png" alt="The five themes: wechat, alipay, grid, frame and the success marker" width="860" />
19
+ </div>
20
+
21
+ ---
22
+
23
+ k-qr-scanner opens a full-screen camera view that reads a QR code **anywhere in the picture**: at an angle, upside down, inverted, or from across the room. When a code is too small to read, the scanner finds it anyway and **zooms in by itself**, the way the WeChat and Alipay scanners do.
24
+
25
+ - **Reads far and blurry codes.** ZXing-C++ (WebAssembly) runs in a Web Worker. A finder-pattern locator drives auto-zoom, and WeChat's super-resolution model has a last try at small, blurry codes.
26
+ - **Reads the whole QR family.** QR Code (Model 1 and 2), Micro QR and rMQR, including codes filmed off a screen.
27
+ - **Made for payment QR codes.** EMV helpers check the CRC and read the merchant, amount and currency of LAO QR, PromptPay, VietQR and other EMVCo codes.
28
+ - **You decide what counts.** An `accept` callback checks each code before it becomes the result. It can be async and can show the user a message.
29
+ - **Works everywhere.** React, Next.js, Vue, Nuxt, Svelte, SvelteKit, Angular, React Native (iOS, Android, Expo) and plain HTML.
30
+ - **Looks native.** Five themes, CSS variables, `::part()` and slots. Pinch zoom, tap to focus, flashlight, album import, beep and haptics.
31
+ - **Small and private.** 14 kB gzip on page load; the engine loads when the scanner opens. Camera frames never leave the device.
32
+
33
+ ## Contents
34
+
35
+ - [Install](#install)
36
+ - [Quick start](#quick-start)
37
+ - [Frameworks](#frameworks)
38
+ - [Check codes before they count](#check-codes-before-they-count)
39
+ - [Look and feel](#look-and-feel)
40
+ - [Headless mode](#headless-mode)
41
+ - [Going to production](#going-to-production)
42
+ - [Benchmarks](#benchmarks)
43
+ - [Size](#size)
44
+ - [Browser and platform support](#browser-and-platform-support)
45
+ - [Documentation](#documentation)
46
+ - [Migrating from kqr-scanner](#migrating-from-kqr-scanner)
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ npx k-qr-scanner init
52
+ ```
53
+
54
+ `init` detects your framework and package manager, installs the package and writes a ready-to-use scanner component. For React Native it also installs `react-native-webview` and adds the camera permissions.
55
+
56
+ Or install it yourself:
57
+
58
+ ```bash
59
+ npm install k-qr-scanner # pnpm add · yarn add · bun add
60
+ ```
61
+
62
+ ## Quick start
63
+
64
+ ```ts
65
+ import { scanQR } from 'k-qr-scanner';
66
+
67
+ const { text } = await scanQR({ locale: 'lo', heading: 'ສະແກນເພື່ອຈ່າຍ' });
68
+ ```
69
+
70
+ `scanQR()` opens the scanner, resolves with the first code and removes the scanner again. It rejects with a `ScanError` when the camera cannot start, or with an `AbortError` when the user closes it:
71
+
72
+ ```ts
73
+ import { scanQR, QRScanner, ScanError } from 'k-qr-scanner';
74
+
75
+ QRScanner.preload(); // fetch and compile the engine early, e.g. when the Scan button appears
76
+
77
+ try {
78
+ const result = await scanQR({ theme: 'alipay', signal: AbortSignal.timeout(60_000) });
79
+ console.log(result.text, result.format, result.source); // source: 'camera' | 'image'
80
+ } catch (err) {
81
+ if (err instanceof ScanError) showCameraHelp(err.code); // 'permission-denied', 'no-camera', …
82
+ // otherwise the user closed the scanner, or the signal fired
83
+ }
84
+ ```
85
+
86
+ No build step? Use the script tag:
87
+
88
+ ```html
89
+ <script src="https://cdn.jsdelivr.net/npm/k-qr-scanner/dist/kqrcode.global.js"></script>
90
+
91
+ <kqr-scanner locale="lo"></kqr-scanner>
92
+ <script>
93
+ document.querySelector('kqr-scanner').addEventListener('scan', (e) => alert(e.detail.text));
94
+ </script>
95
+ ```
96
+
97
+ ## Frameworks
98
+
99
+ Every entry point is safe to import during server-side rendering; the scanner only activates in the browser.
100
+
101
+ **React / Next.js**: the wrapper ships with `'use client'`.
102
+
103
+ ```tsx
104
+ import { QRScanner } from 'k-qr-scanner/react';
105
+
106
+ {open && (
107
+ <QRScanner locale="lo" onScan={(r) => { setOpen(false); pay(r.text); }} onClose={() => setOpen(false)}>
108
+ <button slot="actions-left" onClick={showMyCode}>My QR code</button>
109
+ </QRScanner>
110
+ )}
111
+ ```
112
+
113
+ **Vue / Nuxt**: in Nuxt, render it inside `<ClientOnly>`.
114
+
115
+ ```vue
116
+ <QRScanner v-if="open" theme="alipay" locale="zh" @scan="onScan" @close="open = false" />
117
+ ```
118
+
119
+ **Svelte / SvelteKit**: an action; children use `data-slot`.
120
+
121
+ ```svelte
122
+ <div use:qrScanner={{ locale: 'lo', onScan: (r) => pay(r.text), onClose: () => (open = false) }}></div>
123
+ ```
124
+
125
+ **Angular**: the custom element, with `CUSTOM_ELEMENTS_SCHEMA`.
126
+
127
+ ```html
128
+ <kqr-scanner locale="lo" (scan)="onScan($any($event).detail)" (close)="open = false"></kqr-scanner>
129
+ ```
130
+
131
+ **React Native / Expo**: the same scanner, running in a WebView with the engine bundled, so it works offline and in Expo Go.
132
+
133
+ ```tsx
134
+ import { QRScanner } from 'k-qr-scanner/react-native';
135
+
136
+ <Modal visible={open} presentationStyle="fullScreen" onRequestClose={() => setOpen(false)}>
137
+ <QRScanner style={{ flex: 1 }} locale="lo" onScan={(r) => pay(r.text)} onClose={() => setOpen(false)} />
138
+ </Modal>
139
+ ```
140
+
141
+ The component asks for the camera permission itself, releases the camera while the app is in the background and recovers if the OS kills the WebView. On Expo, the config plugin (`"plugins": ["k-qr-scanner"]`) adds the permission entries.
142
+
143
+ Full examples for every framework: **[docs/FRAMEWORKS.md](docs/FRAMEWORKS.md)**. React Native setup and props: **[docs/REACT_NATIVE.md](docs/REACT_NATIVE.md)**.
144
+
145
+ ## Check codes before they count
146
+
147
+ `accept` runs for every decoded code, from the camera and from album photos, before it becomes the result:
148
+
149
+ | `accept` returns | what happens |
150
+ | :--- | :--- |
151
+ | `true` or nothing | the code is the result |
152
+ | `false` | the code is ignored and scanning continues |
153
+ | a string | the code is ignored, scanning continues, and the string is shown to the user |
154
+
155
+ ```ts
156
+ const result = await scanQR({
157
+ formats: ['qr_code'], // read only regular QR codes (default: QR Code, Micro QR and rMQR)
158
+ accept: async (r) => {
159
+ if (!r.text.startsWith('000201')) return 'This is not a payment QR code';
160
+ const res = await fetch(`/api/qr/check?c=${encodeURIComponent(r.text)}`);
161
+ return res.ok || 'Unknown merchant';
162
+ },
163
+ });
164
+ console.log(result.format, result.version, result.ecLevel); // 'qr_code' '7' 'M'
165
+ ```
166
+
167
+ A code that is turned down is not checked again while it stays in view. `accept`, `formats` and a `reject` event (`onReject` in the wrappers) work the same in `scanQR`, `<kqr-scanner>`, the headless `QRScanner` and every framework wrapper.
168
+
169
+ ### Payment QR codes (EMV)
170
+
171
+ LAO QR, PromptPay, VietQR, DuitNow, QRIS, UnionPay and most other payment codes use the EMVCo format. `acceptEMV()` lets through only intact payment codes (the CRC must match), and `parseEMV()` reads their fields:
172
+
173
+ ```ts
174
+ import { scanQR, acceptEMV, parseEMV } from 'k-qr-scanner';
175
+
176
+ const { text } = await scanQR({ accept: acceptEMV({ currency: 'LAK', message: 'ນີ້ບໍ່ແມ່ນ QR ຈ່າຍເງິນ' }) });
177
+ const emv = parseEMV(text)!;
178
+ pay({ to: emv.merchantName, amount: emv.amount, currency: emv.currencyCode }); // 'LAK'
179
+ ```
180
+
181
+ The helpers are plain string code (about 1 kB), work in Node and React Native too, and are left out of your bundle if you don't use them. Details: [API.md](docs/API.md#payment-qr-codes-emv).
182
+
183
+ ## Look and feel
184
+
185
+ ```html
186
+ <kqr-scanner theme="alipay" locale="zh" heading="扫一扫" style="--kqr-accent: #1677ff">
187
+ <button slot="actions-left" onclick="openMyCode()">我的二维码</button>
188
+ <nav slot="footer"><b>扫码</b><span>识物</span><span>AR</span></nav>
189
+ </kqr-scanner>
190
+
191
+ <style>
192
+ kqr-scanner::part(hint) { background: #0006; padding: 6px 14px; border-radius: 20px; }
193
+ </style>
194
+ ```
195
+
196
+ | theme | look |
197
+ | :--- | :--- |
198
+ | `wechat` (default) | a thin glowing line sweeps the whole screen |
199
+ | `alipay` | a gradient band with a bright edge sweeps the whole screen |
200
+ | `grid` | corner brackets with a grid sweeping inside |
201
+ | `frame` | a dimmed mask around a frame with a scan line |
202
+ | `none` | the camera only; you draw the UI |
203
+
204
+ The frame is decoration only: the whole camera image is always scanned.
205
+
206
+ For a banking-app screen, `layout="bar"` puts the flashlight, a large album button and your own button in one row at the bottom, and the `banner` slot holds a "supported QR" strip under the top bar:
207
+
208
+ ```html
209
+ <kqr-scanner theme="frame" layout="bar" style="--kqr-accent: #e60012; --kqr-corner-width: 0; --kqr-frame-border: 1px solid #fff6">
210
+ <div slot="banner">Support QR: <img src="/img/supported-qr.png" alt="LAO QR, UnionPay, WeChat Pay" height="48"></div>
211
+ <button slot="actions-right" onclick="openMyQr()">My QR</button>
212
+ </kqr-scanner>
213
+ ```
214
+
215
+ Themes, all 19 CSS variables, 19 parts, 10 slots, the bar layout and the built-in languages (English, Lao, Chinese) are covered in **[docs/CUSTOMIZE.md](docs/CUSTOMIZE.md)**.
216
+
217
+ ## Headless mode
218
+
219
+ Bring your own `<video>` and UI, e.g. for a checkout counter that scans continuously:
220
+
221
+ ```ts
222
+ import { QRScanner } from 'k-qr-scanner';
223
+
224
+ const scanner = new QRScanner({ video, continuous: true });
225
+ scanner.on('hint', ({ hint }) => drawBox(hint)); // where a code is, even before it can be read
226
+ scanner.on('result', (r) => addToCart(r.text));
227
+ await scanner.start();
228
+ ```
229
+
230
+ It can also read a photo without camera permission:
231
+
232
+ ```ts
233
+ const result = await new QRScanner({ video: document.createElement('video') }).scanImage(file);
234
+ ```
235
+
236
+ Every option, method, event and type: **[docs/API.md](docs/API.md)**.
237
+
238
+ ## Going to production
239
+
240
+ - **HTTPS.** Browsers only open the camera on secure origins; `localhost` is fine during development.
241
+ - **Content-Security-Policy.** Allow `worker-src blob:` and `script-src 'wasm-unsafe-eval'`. `npx k-qr-scanner doctor` checks your project for this and more.
242
+ - **Treat scanned text as untrusted input.** Validate it before acting on it, and never insert it as HTML. `accept` is a good place to do this.
243
+ - **Preload.** Call `QRScanner.preload()` when your Scan button appears, so the first scan opens instantly.
244
+ - **Self-hosting the script build.** Serve `kqrcode.global.js`, `kqrcode.engine.js` and `kqrcode.jsqr.js` from one directory, as JavaScript (`text/javascript`). The engine and jsQR load as ES modules, so a different origin needs CORS headers (jsDelivr and unpkg send them).
245
+ - **WebGPU super-resolution** loads ONNX Runtime Web from jsDelivr. To avoid third-party scripts, self-host it and set `onnx-runtime-url`.
246
+
247
+ ## Benchmarks
248
+
249
+ Every engine sees the same pixels: synthetic camera frames with perspective, rotation, defocus, sensor noise, uneven light and low contrast, carrying real payloads (a URL and an EMVCo / LaoQR payment string). The WeChat column is the real `wechat_qrcode` engine from OpenCV contrib, running as native C++.
250
+
251
+ <!-- BENCH:START -->
252
+
253
+ | Scenario | **k-qr-scanner** | WeChat ¹ | ZXing-WASM | jsQR |
254
+ | :--- | :---: | :---: | :---: | :---: |
255
+ | **🎯 Decode rate: all frames** | **`69%`** 🏆 | `62%` | `61%` | `42%` |
256
+ | **🔭 Far: 1.5 px modules** | **`38%`** 🏆 | `29%` | `4%` | `0%` |
257
+ | **🔭 Far: 2.5 px modules** | **`63%`** 🏆 | `50%` | **`63%`** 🏆 | `25%` |
258
+ | **🌫️ Blurred (σ 0.8)** | **`77%`** 🏆 | `73%` | `67%` | `46%` |
259
+ | **🌗 Low contrast** | **`64%`** 🏆 | `53%` | `60%` | `44%` |
260
+ | **⏱️ Latency per frame (p50 / p95)** | `14.4 ms`<br><sub>p95: 50.6 ms</sub> | `13.4 ms`<br><sub>p95: 106.7 ms</sub> | **`10.6 ms`** 🏆<br><sub>p95: 12.4 ms</sub> | `34.0 ms`<br><sub>p95: 50.1 ms</sub> |
261
+ | **💤 Frame without a code (p50)** | `18.8 ms` | `271.1 ms` | **`8.6 ms`** 🏆 | `116.3 ms` |
262
+
263
+ > 144 synthetic 1280×720 frames + 8 without a code · single CPU thread · decode rates from 2026-11-21, times and the WeChat column from the 2026-11-19 run (same machine as WeChat)
264
+
265
+ <!-- BENCH:END -->
266
+
267
+ ¹ WeChat = OpenCV `wechat_qrcode` 4.14, native C++, one thread. k-qr-scanner runs with `superResolution: 'webgpu'`; the default `'js'` mode is within one point.
268
+
269
+ The scanner reads more codes than WeChat's open-source engine in every row, including the farthest ones, and does far less work on frames without a code, which is most of what a live camera sees. Codes filmed off a screen, where the display's pixel grid causes moiré, get their own recovery pass. Method, more tables and how to reproduce: **[docs/BENCHMARK.md](docs/BENCHMARK.md)**.
270
+
271
+ ## Size
272
+
273
+ | what | when it loads | gzip |
274
+ | :--- | :--- | :--- |
275
+ | UI and scanner logic | on import | ~14 kB |
276
+ | decoding engine (ZXing WebAssembly, detectors, super-resolution) | when the scanner first opens, or on `QRScanner.preload()` | ~460 kB, then cached |
277
+ | jsQR fallback | only when a CSP blocks workers or WebAssembly | ~47 kB |
278
+ | ONNX Runtime Web | only with `superResolution: 'webgpu'` | from a CDN or your server |
279
+
280
+ One decoding worker is shared by every scanner on the page and stays warm for 30 seconds after the last one closes, so reopening is instant. In React Native the engine is bundled with the component (about 0.5 MB gzip).
281
+
282
+ ## Browser and platform support
283
+
284
+ | platform | notes |
285
+ | :--- | :--- |
286
+ | Chrome and Edge (desktop, Android) | full support, including hardware zoom and the flashlight on Android |
287
+ | Firefox | full support |
288
+ | Safari 15.4+ (iOS, macOS) | full support with digital zoom on a 4K stream (Safari has no camera zoom API) |
289
+ | React Native | iOS 14.5+ and Android 7+, through `react-native-webview` 13+ |
290
+ | Capacitor, native web views, Flutter | iOS 14.5+ and Android 7+; see [iOS and Android](docs/MOBILE.md) |
291
+
292
+ If a strict CSP blocks WebAssembly or workers, the scanner falls back to jsQR, which reads regular QR codes only.
293
+
294
+ Tested with 82 automated tests, production builds of React, Next.js, Nuxt, SvelteKit and Angular apps scanning end to end, and Chrome, Firefox and WebKit runs (20 start/stop cycles with no leaked workers or camera tracks). See **[docs/TESTING.md](docs/TESTING.md)**.
295
+
296
+ > [!NOTE]
297
+ > k-qr-scanner is in **beta (0.x)**, so the API may still change before 1.0. Reports from real phones are very welcome: [open an issue](https://github.com/kris-lx/kqrcode/issues/new/choose).
298
+
299
+ ## Documentation
300
+
301
+ | guide | covers |
302
+ | :--- | :--- |
303
+ | [API reference](docs/API.md) | `scanQR`, `<kqr-scanner>`, the headless `QRScanner`, types, the CLI |
304
+ | [Frameworks](docs/FRAMEWORKS.md) | React, Next.js, Vue, Nuxt, Svelte, SvelteKit, Angular, plain HTML |
305
+ | [React Native](docs/REACT_NATIVE.md) | setup, permissions, props, platform notes |
306
+ | [iOS and Android](docs/MOBILE.md) | PWAs, Capacitor, native WKWebView and Android WebView, Flutter |
307
+ | [Customizing](docs/CUSTOMIZE.md) | themes, CSS variables, parts, slots, languages |
308
+ | [Benchmark](docs/BENCHMARK.md) | method and full results |
309
+ | [Testing](docs/TESTING.md) | the test layers and how to run them |
310
+ | [`llms.txt`](llms.txt) | the whole API on one page, for AI assistants |
311
+
312
+ ## Migrating from kqr-scanner
313
+
314
+ The package used to be published as `kqr-scanner`. The API is the same; only the package name changed:
315
+
316
+ ```bash
317
+ npm uninstall kqr-scanner && npm install k-qr-scanner
318
+ ```
319
+
320
+ Then replace `kqr-scanner` with `k-qr-scanner` in your imports (`'k-qr-scanner/react'` and so on). The `<kqr-scanner>` element and its attributes keep their names. Version 0.2.0 also changed `ScanResult.format`; see the [changelog](CHANGELOG.md).
321
+
322
+ ## Buy me a coffee
323
+
324
+ If k-qr-scanner saves you time, you can support its development. Thank you! 🙏
325
+
326
+ <table align="center">
327
+ <tr>
328
+ <td align="center"><img src="docs/assets/support/wechat-pay.png" alt="WeChat Pay" width="200" /><br /><b>WeChat Pay</b> · 微信支付</td>
329
+ <td align="center"><img src="docs/assets/support/lao-qr.png" alt="LAO QR" width="200" /><br /><b>LAO QR</b> · ໂອນຜ່ານ LAPNet</td>
330
+ <td align="center"><img src="docs/assets/support/alipay.png" alt="Alipay" width="200" /><br /><b>Alipay</b> · 支付宝</td>
331
+ </tr>
332
+ </table>
333
+
334
+ <p align="center"><sub>Each of these codes was read by k-qr-scanner before it went into this README.</sub></p>
335
+
336
+ ---
337
+
338
+ **Maintained by [kris](https://github.com/kris-lx)** · [Contributing](CONTRIBUTING.md) · [Security](SECURITY.md) · [Changelog](CHANGELOG.md) · [MIT License](LICENSE) · [Third-party notices](NOTICE)
@@ -0,0 +1,11 @@
1
+ # Third-party notices
2
+
3
+ | Component | Used for | License |
4
+ |---|---|---|
5
+ | [ZXing-C++](https://github.com/zxing-cpp/zxing-cpp) via [zxing-wasm](https://github.com/Sec-ant/zxing-wasm) | main decoder (WASM, inlined in the worker) | Apache-2.0 (ZXing-C++), MIT (zxing-wasm) |
6
+ | [jsQR](https://github.com/cozmo/jsQR) | fallback decoder when WASM/workers are blocked | Apache-2.0 |
7
+ | WeChat QR super-resolution model `sr.caffemodel` from [WeChatCV/opencv_3rdparty](https://github.com/WeChatCV/opencv_3rdparty/tree/wechat_qrcode), used by OpenCV contrib [`wechat_qrcode`](https://docs.opencv.org/5.0/extra_modules/wechat_qrcode.html) | weights converted by `scripts/convert-sr.py` into `models/wechat_sr.onnx` and `src/sr-weights.generated.ts` | **Apache-2.0**, © 2021 THL A29 Limited (Tencent). Verified against the upstream LICENSE on 2026-11-19, copy in `licenses/WECHAT_QRCODE-Apache-2.0.txt`. Converted to ONNX/JS without changing weights (see NOTICE) |
8
+ | [fflate](https://github.com/101arrowz/fflate) | gzip fallback for browsers without `DecompressionStream` (bundled in the worker) | MIT |
9
+ | [ONNX Runtime Web](https://github.com/microsoft/onnxruntime) | optional, loaded at runtime from a CDN only when `superResolution: 'webgpu'` | MIT |
10
+
11
+ Full license texts are in [`licenses/`](licenses/), and attribution and modification notes are in [`NOTICE`](NOTICE). Both ship in the npm package.
@@ -0,0 +1,6 @@
1
+ /** Expo config plugin for k-qr-scanner/react-native: adds the iOS and Android camera permission entries. */
2
+ export interface KqrcodePluginProps {
3
+ /** iOS NSCameraUsageDescription. Default: "Allow $(PRODUCT_NAME) to use the camera to scan QR codes". */
4
+ cameraPermission?: string;
5
+ }
6
+ export default function withKqrcode(config: Record<string, any>, props?: KqrcodePluginProps): Record<string, any>;
package/app.plugin.js ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Expo config plugin for k-qr-scanner/react-native. Adds the camera permission entries on prebuild / EAS:
3
+ *
4
+ * "plugins": ["k-qr-scanner"]
5
+ * "plugins": [["k-qr-scanner", { "cameraPermission": "Scan QR codes to pay" }]]
6
+ *
7
+ * iOS: NSCameraUsageDescription (an existing text is kept unless you pass cameraPermission).
8
+ * Android: android.permission.CAMERA. Expo Go needs nothing: it already has both.
9
+ */
10
+ const DEFAULT_TEXT = 'Allow $(PRODUCT_NAME) to use the camera to scan QR codes';
11
+
12
+ /** @param {Record<string, any>} config @param {{ cameraPermission?: string }} [props] */
13
+ export default function withKqrcode(config, props = {}) {
14
+ const infoPlist = { ...(config.ios && config.ios.infoPlist) };
15
+ if (props.cameraPermission || !infoPlist.NSCameraUsageDescription) {
16
+ infoPlist.NSCameraUsageDescription = props.cameraPermission || DEFAULT_TEXT;
17
+ }
18
+ const permissions = [...((config.android && config.android.permissions) || [])];
19
+ if (!permissions.some((p) => p === 'CAMERA' || p === 'android.permission.CAMERA')) {
20
+ permissions.push('android.permission.CAMERA');
21
+ }
22
+ return {
23
+ ...config,
24
+ ios: { ...config.ios, infoPlist },
25
+ android: { ...config.android, permissions },
26
+ };
27
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Auto-zoom controller (pure logic, no DOM) – the "WeChat/Alipay" behaviour:
3
+ *
4
+ * • a code is seen but too small / undecodable → zoom in until its modules
5
+ * are big enough for the decoder, never so far that it leaves the view
6
+ * • a code is decoded but tiny → zoom to a comfortable size
7
+ * • nothing seen for a while → sweep zoom levels (1× → max → 1×) to find far codes
8
+ * • user pinched / dragged the slider → leave zoom alone for a few seconds
9
+ */
10
+ import type { QRHint } from './engine';
11
+ export interface ZoomInput {
12
+ now: number;
13
+ zoom: number;
14
+ min: number;
15
+ max: number;
16
+ /** Hint in *video* pixel coordinates, or null when nothing is visible. */
17
+ hint: QRHint | null;
18
+ decoded: boolean;
19
+ videoWidth: number;
20
+ videoHeight: number;
21
+ }
22
+ export declare class AutoZoom {
23
+ private settleMs;
24
+ constructor(opts?: {
25
+ settleMs?: number;
26
+ });
27
+ private settleUntil;
28
+ private holdUntil;
29
+ private lostAt;
30
+ private resetDone;
31
+ private sweepIdx;
32
+ private sweepDir;
33
+ private lastSweepAt;
34
+ /** The user took control (pinch / slider / tap): back off for a while. */
35
+ hold(now: number, ms?: number): void;
36
+ /** Call after any zoom change so we wait for the camera to settle. */
37
+ settle(now: number, ms?: number): void;
38
+ /** Returns the zoom value to apply, or null for "leave it". */
39
+ update(i: ZoomInput): number | null;
40
+ private follow;
41
+ private search;
42
+ }
43
+ export declare function sweepLevels(min: number, max: number): number[];