k-qr-scanner 0.2.0 → 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 (72) hide show
  1. package/CHANGELOG.md +22 -1
  2. package/README.md +38 -10
  3. package/dist/chunks/chunk-PUUIGXID.js +149 -0
  4. package/dist/chunks/engine-EJ4OC3LZ.js +1 -0
  5. package/dist/cli.js +22 -9
  6. package/dist/element.d.ts +11 -1
  7. package/dist/emv.d.ts +89 -0
  8. package/dist/engine.d.ts +5 -0
  9. package/dist/index.cjs +24 -10
  10. package/dist/index.d.ts +2 -0
  11. package/dist/index.js +1 -2
  12. package/dist/kqrcode.engine.js +1 -1
  13. package/dist/kqrcode.global.js +24 -10
  14. package/dist/kqrcode.jsqr.js +0 -1
  15. package/dist/react-native.d.ts +4 -0
  16. package/dist/react.cjs +1 -2
  17. package/dist/react.d.ts +2 -0
  18. package/dist/react.js +1 -2
  19. package/dist/rn/index.js +5 -6
  20. package/dist/rn/runtime.js +1 -1
  21. package/dist/scan-qr.d.ts +2 -0
  22. package/dist/sr.cjs +0 -1
  23. package/dist/sr.js +1 -2
  24. package/dist/svelte.cjs +1 -2
  25. package/dist/svelte.d.ts +2 -0
  26. package/dist/svelte.js +1 -2
  27. package/dist/vue.cjs +1 -2
  28. package/dist/vue.d.ts +2 -0
  29. package/dist/vue.js +1 -2
  30. package/llms.txt +15 -8
  31. package/package.json +2 -3
  32. package/dist/chunks/chunk-E66QYIQI.js +0 -135
  33. package/dist/chunks/chunk-E66QYIQI.js.map +0 -6
  34. package/dist/chunks/chunk-HCGRA6GM.js +0 -2
  35. package/dist/chunks/chunk-HCGRA6GM.js.map +0 -6
  36. package/dist/chunks/decoder-jsqr-54X2IQSI.js +0 -2
  37. package/dist/chunks/decoder-jsqr-54X2IQSI.js.map +0 -6
  38. package/dist/chunks/engine-QWSAAVKN.js +0 -2
  39. package/dist/chunks/engine-QWSAAVKN.js.map +0 -6
  40. package/dist/chunks/worker-source.generated-24WX42PC.js +0 -2
  41. package/dist/chunks/worker-source.generated-24WX42PC.js.map +0 -6
  42. package/dist/cli.d.ts +0 -17
  43. package/dist/decoder-jsqr.d.ts +0 -3
  44. package/dist/decoder-zxing.d.ts +0 -3
  45. package/dist/engine-host.d.ts +0 -48
  46. package/dist/engine.cjs +0 -1
  47. package/dist/index.cjs.map +0 -6
  48. package/dist/index.js.map +0 -6
  49. package/dist/jsqr.cjs +0 -2
  50. package/dist/jsqr.cjs.map +0 -6
  51. package/dist/kqrcode.global.js.map +0 -6
  52. package/dist/kqrcode.jsqr.js.map +0 -6
  53. package/dist/react.cjs.map +0 -6
  54. package/dist/react.js.map +0 -6
  55. package/dist/rn/index.js.map +0 -6
  56. package/dist/rn-bridge.d.ts +0 -103
  57. package/dist/rn-runtime.generated.d.ts +0 -2
  58. package/dist/sr-model.generated.d.ts +0 -4
  59. package/dist/sr.cjs.map +0 -6
  60. package/dist/sr.js.map +0 -6
  61. package/dist/svelte.cjs.map +0 -6
  62. package/dist/svelte.js.map +0 -6
  63. package/dist/vue.cjs.map +0 -6
  64. package/dist/vue.js.map +0 -6
  65. package/dist/worker-source.generated.d.ts +0 -2
  66. package/dist/worker.d.ts +0 -1
  67. package/docs/API.md +0 -292
  68. package/docs/BENCHMARK.md +0 -101
  69. package/docs/CUSTOMIZE.md +0 -150
  70. package/docs/FRAMEWORKS.md +0 -241
  71. package/docs/REACT_NATIVE.md +0 -181
  72. package/docs/TESTING.md +0 -90
package/CHANGELOG.md CHANGED
@@ -4,6 +4,26 @@ All notable changes to this project are documented here. The format follows [Kee
4
4
 
5
5
  ## [Unreleased]
6
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
+
7
27
  ## [0.2.0] – 2026-11-21
8
28
 
9
29
  ### Changed
@@ -52,6 +72,7 @@ First public release.
52
72
  - `npx kqr-scanner init` and `npx kqr-scanner doctor` CLI.
53
73
  - English, Lao and Chinese labels.
54
74
 
55
- [Unreleased]: https://github.com/kris-lx/kqrcode/compare/v0.2.0...HEAD
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
56
77
  [0.2.0]: https://github.com/kris-lx/kqrcode/compare/v0.1.0...v0.2.0
57
78
  [0.1.0]: https://github.com/kris-lx/kqrcode/releases/tag/v0.1.0
package/README.md CHANGED
@@ -23,7 +23,8 @@
23
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
24
 
25
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.
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.
27
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.
28
29
  - **Works everywhere.** React, Next.js, Vue, Nuxt, Svelte, SvelteKit, Angular, React Native (iOS, Android, Expo) and plain HTML.
29
30
  - **Looks native.** Five themes, CSS variables, `::part()` and slots. Pinch zoom, tap to focus, flashlight, album import, beep and haptics.
@@ -165,6 +166,20 @@ console.log(result.format, result.version, result.ecLevel); // 'qr_code' '7' 'M'
165
166
 
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.
167
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
+
168
183
  ## Look and feel
169
184
 
170
185
  ```html
@@ -186,7 +201,18 @@ A code that is turned down is not checked again while it stays in view. `accept`
186
201
  | `frame` | a dimmed mask around a frame with a scan line |
187
202
  | `none` | the camera only; you draw the UI |
188
203
 
189
- The frame is decoration only: the whole camera image is always scanned. Themes, all 15 CSS variables, 18 parts, 8 slots and the built-in languages (English, Lao, Chinese) are covered in **[docs/CUSTOMIZE.md](docs/CUSTOMIZE.md)**.
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)**.
190
216
 
191
217
  ## Headless mode
192
218
 
@@ -215,7 +241,7 @@ Every option, method, event and type: **[docs/API.md](docs/API.md)**.
215
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.
216
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.
217
243
  - **Preload.** Call `QRScanner.preload()` when your Scan button appears, so the first scan opens instantly.
218
- - **Self-hosting the script build.** Serve `kqrcode.global.js`, `kqrcode.engine.js` and `kqrcode.jsqr.js` from one directory.
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).
219
245
  - **WebGPU super-resolution** loads ONNX Runtime Web from jsDelivr. To avoid third-party scripts, self-host it and set `onnx-runtime-url`.
220
246
 
221
247
  ## Benchmarks
@@ -226,21 +252,21 @@ Every engine sees the same pixels: synthetic camera frames with perspective, rot
226
252
 
227
253
  | Scenario | **k-qr-scanner** | WeChat ¹ | ZXing-WASM | jsQR |
228
254
  | :--- | :---: | :---: | :---: | :---: |
229
- | **🎯 Decode rate: all frames** | **`65%`** 🏆 | `62%` | `61%` | `42%` |
230
- | **🔭 Far: 1.5 px modules** | `17%` | **`29%`** 🏆 | `4%` | `0%` |
255
+ | **🎯 Decode rate: all frames** | **`69%`** 🏆 | `62%` | `61%` | `42%` |
256
+ | **🔭 Far: 1.5 px modules** | **`38%`** 🏆 | `29%` | `4%` | `0%` |
231
257
  | **🔭 Far: 2.5 px modules** | **`63%`** 🏆 | `50%` | **`63%`** 🏆 | `25%` |
232
- | **🌫️ Blurred (σ 0.8)** | **`75%`** 🏆 | `73%` | `67%` | `46%` |
233
- | **🌗 Low contrast** | **`61%`** 🏆 | `53%` | `60%` | `44%` |
258
+ | **🌫️ Blurred (σ 0.8)** | **`77%`** 🏆 | `73%` | `67%` | `46%` |
259
+ | **🌗 Low contrast** | **`64%`** 🏆 | `53%` | `60%` | `44%` |
234
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> |
235
261
  | **💤 Frame without a code (p50)** | `18.8 ms` | `271.1 ms` | **`8.6 ms`** 🏆 | `116.3 ms` |
236
262
 
237
- > 144 synthetic 1280×720 frames + 8 without a code · single CPU thread · last updated 2026-11-19
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)
238
264
 
239
265
  <!-- BENCH:END -->
240
266
 
241
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.
242
268
 
243
- The scanner matches WeChat's open-source engine overall and does far less work on frames without a code, which is most of what a live camera sees. WeChat's CNN detector still wins on the very farthest codes. Method, more tables and how to reproduce: **[docs/BENCHMARK.md](docs/BENCHMARK.md)**.
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)**.
244
270
 
245
271
  ## Size
246
272
 
@@ -261,10 +287,11 @@ One decoding worker is shared by every scanner on the page and stays warm for 30
261
287
  | Firefox | full support |
262
288
  | Safari 15.4+ (iOS, macOS) | full support with digital zoom on a 4K stream (Safari has no camera zoom API) |
263
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) |
264
291
 
265
292
  If a strict CSP blocks WebAssembly or workers, the scanner falls back to jsQR, which reads regular QR codes only.
266
293
 
267
- Tested with 70 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)**.
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)**.
268
295
 
269
296
  > [!NOTE]
270
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).
@@ -276,6 +303,7 @@ Tested with 70 automated tests, production builds of React, Next.js, Nuxt, Svelt
276
303
  | [API reference](docs/API.md) | `scanQR`, `<kqr-scanner>`, the headless `QRScanner`, types, the CLI |
277
304
  | [Frameworks](docs/FRAMEWORKS.md) | React, Next.js, Vue, Nuxt, Svelte, SvelteKit, Angular, plain HTML |
278
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 |
279
307
  | [Customizing](docs/CUSTOMIZE.md) | themes, CSS variables, parts, slots, languages |
280
308
  | [Benchmark](docs/BENCHMARK.md) | method and full results |
281
309
  | [Testing](docs/TESTING.md) | the test layers and how to run them |
@@ -0,0 +1,149 @@
1
+ var z=class{constructor(e={}){this.settleUntil=0;this.holdUntil=0;this.lostAt=null;this.resetDone=!1;this.sweepIdx=0;this.sweepDir=1;this.lastSweepAt=0;this.settleMs=e.settleMs??380}hold(e,t=3500){this.holdUntil=e+t}settle(e,t=this.settleMs){this.settleUntil=Math.max(this.settleUntil,e+t)}update(e){return e.max<=e.min*1.05||e.now<this.settleUntil||e.now<this.holdUntil?null:e.hint?(this.lostAt=null,this.resetDone=!1,this.follow(e)):this.search(e)}follow(e){let t=e.hint,i=Math.min(e.videoWidth,e.videoHeight),n=t.size/i,s=1;e.decoded?n<.42*.7&&(s=.42/n):(t.module<4&&(s=6/Math.max(.5,t.module)),t.full||(s=Math.min(s,2))),s=Math.min(s,.7/n);let r=Math.abs(t.cx-e.videoWidth/2)+t.size/2,o=Math.abs(t.cy-e.videoHeight/2)+t.size/2;if(s=Math.min(s,e.videoWidth/2/r*.92,e.videoHeight/2/o*.92),s=Math.max(.8,Math.min(3.5,s)),s>.9&&s<1.18)return null;let c=_(e.zoom*s,e.min,e.max);if(Math.abs(c-e.zoom)/e.zoom<.08)return null;let u=e.zoom+(c-e.zoom)*.75;return this.settle(e.now),_(u,e.min,e.max)}search(e){if(this.lostAt===null&&(this.lostAt=e.now),e.now-this.lostAt<700)return null;if(!this.resetDone)return this.resetDone=!0,this.sweepIdx=0,this.sweepDir=1,this.lastSweepAt=e.now,this.settle(e.now,300),e.zoom>e.min*1.05?e.min:null;if(e.now-this.lastSweepAt<700)return null;let t=O(e.min,e.max);if(t.length<2)return null;let i=this.sweepIdx+this.sweepDir;return i>=t.length&&(this.sweepDir=-1,i=t.length-2),i<0&&(this.sweepDir=1,i=1),this.sweepIdx=i,this.lastSweepAt=e.now,this.settle(e.now,300),t[i]}};function O(l,e){let t=[l];for(let i of[2,3.5,5.5,8,12])i>l*1.4&&i<=e&&t.push(i);return t}function _(l,e,t){return Math.max(e,Math.min(t,l))}var $=null,j=()=>$??($=import("../kqrcode.engine.js").then(l=>l.default)),C=class{constructor(){this.idleTimeout=3e4;this.srBackend="off";this.unavailable=!1;this.worker=null;this.starting=null;this.ready=null;this.refs=0;this.idleTimer=0;this.pending=new Map;this.nextId=0}warm(){return this.ensure().then(()=>this.ready??void 0).then(()=>this.scheduleIdle())}async acquire(e){this.refs++,this.clearIdle();let t=await this.ensure();return t?(t.postMessage({type:"config",...e}),!0):(this.refs--,!1)}release(){this.refs=Math.max(0,this.refs-1),this.refs===0&&this.scheduleIdle()}analyze(e,t){let i=this.worker;if(!i)return Promise.resolve(null);let n=++this.nextId;return new Promise(s=>{this.pending.set(n,s),"bitmap"in e?i.postMessage({id:n,bitmap:e.bitmap,opts:t},[e.bitmap]):i.postMessage({id:n,pixels:e.pixels,width:e.width,height:e.height,opts:t},[e.pixels])})}get alive(){return!!this.worker}dispose(){this.clearIdle(),this.worker?.terminate(),this.worker=null,this.starting=null,this.ready=null,this.pending.forEach(e=>e(null)),this.pending.clear()}ensure(){return this.worker?Promise.resolve(this.worker):this.unavailable||typeof Worker>"u"?Promise.resolve(null):this.starting??(this.starting=this.spawn())}async spawn(){try{let e=await j(),t=URL.createObjectURL(new Blob([e],{type:"text/javascript"})),i=new Worker(t);URL.revokeObjectURL(t);let n;return this.ready=new Promise(s=>n=s),i.onmessage=s=>{let r=s.data;if(r.type==="ready"){r.wasm===!1&&this.fail(),n();return}if(r.type==="config-done"){this.srBackend=r.sr??"off";return}if(r.id===void 0)return;let o=this.pending.get(r.id);this.pending.delete(r.id),r.error==="no-wasm"&&this.fail(),o?.(r.result??null)},i.onerror=()=>{this.fail(),n()},this.worker=i,i}catch{return this.unavailable=!0,null}finally{this.starting=null}}fail(){this.unavailable=!0,this.dispose()}scheduleIdle(){this.clearIdle(),!(this.refs>0||!this.worker)&&(this.idleTimer=setTimeout(()=>{this.refs===0&&this.dispose()},this.idleTimeout))}clearIdle(){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=0}},f=new C;var b=class extends Error{constructor(t,i){super(i??t);this.code=t;this.name="ScanError"}},B=l=>new Promise(e=>{let t=l;if(t.requestVideoFrameCallback){let i=!1,n=()=>{i||(i=!0,e())};t.requestVideoFrameCallback(n),setTimeout(n,100)}else requestAnimationFrame(()=>e())}),A=l=>"bitmap"in l?{bitmap:l.bitmap}:{pixels:l.pixels,width:l.width,height:l.height},T=class l{constructor(e){this.listeners={};this.stream=null;this.track=null;this.running=!1;this.paused=!1;this.loopToken=0;this.engine=!1;this.useBitmap=typeof OffscreenCanvas<"u";this.grabCanvas=null;this.native=null;this.frame=0;this.lastHint=null;this.zoomCtl=new z;this.zoomRange={min:1,max:1};this.zoomValue=1;this.digital=!1;this.lastText="";this.lastTextAt=0;this.rejected=new Map;this.lumaEma=128;this.darkState=!1;this.onVisibility=()=>{this.paused=document.hidden,!document.hidden&&this.running&&this.track?.readyState==="ended"&&(this.stop(),this.start().catch(()=>{}))};this.video=e.video,this.opts={facingMode:"environment",autoZoom:!0,maxZoom:8,continuous:!1,maxFrameSide:1920,hiRes:!0,superResolution:"js",onnxRuntimeUrl:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.20.1/dist/ort.webgpu.min.js",...e},this.opts.deviceId=e.deviceId}on(e,t){var n;let i=(n=this.listeners)[e]??(n[e]=new Set);return i.add(t),()=>i.delete(t)}emit(e,t){this.listeners[e]?.forEach(i=>i(t))}static preload(){return f.warm()}static dispose(){f.dispose()}static get engineIdleTimeout(){return f.idleTimeout}static set engineIdleTimeout(e){f.idleTimeout=e}static isSupported(){return typeof navigator<"u"&&!!navigator.mediaDevices?.getUserMedia}get zoom(){return this.zoomValue}get zoomMin(){return this.zoomRange.min}get zoomMax(){return this.zoomRange.max}get canZoom(){return this.zoomRange.max>this.zoomRange.min*1.05}get isDigitalZoom(){return this.digital}get superResolutionBackend(){return f.srBackend}get canTorch(){return!!this.track?.getCapabilities?.()?.torch}async start(){if(this.running)return;if(typeof window<"u"&&window.isSecureContext===!1)throw this.fail(new b("insecure-context","Camera needs HTTPS (or localhost)."));if(!l.isSupported())throw this.fail(new b("unsupported","getUserMedia is not available."));try{let i=this.opts.deviceId?{deviceId:{exact:this.opts.deviceId},width:{ideal:1920},height:{ideal:1080}}:{facingMode:{ideal:this.opts.facingMode},width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}};this.stream=await navigator.mediaDevices.getUserMedia({video:i,audio:!1})}catch(i){throw this.fail(V(i))}this.track=this.stream.getVideoTracks()[0];let e=this.video;e.muted=!0,e.setAttribute("playsinline",""),e.setAttribute("webkit-playsinline",""),e.srcObject=this.stream;try{await e.play()}catch{}await Promise.all([this.tune(),this.setupDetectors()]),document.addEventListener("visibilitychange",this.onVisibility),this.running=!0,this.paused=!1;let t=++this.loopToken;this.loop(t)}stop(){this.running=!1,this.loopToken++,document.removeEventListener("visibilitychange",this.onVisibility),this.stream?.getTracks().forEach(e=>e.stop()),this.stream=null,this.track=null,this.video.srcObject=null,this.video.style.transform="",this.releaseEngine(),this.lastHint=null,this.zoomValue=1}pause(){this.paused=!0}resume(){this.paused=!1,this.lastText="",this.rejected.clear()}setFormats(e){this.opts.formats=e?.length?[...e]:void 0,this.setupNative()}setAccept(e){this.opts.accept=e,this.rejected.clear()}async switchCamera(){this.opts.facingMode=this.opts.facingMode==="environment"?"user":"environment",this.opts.deviceId=void 0,this.stop(),await this.start()}async setZoom(e,t=!0){if(!this.track||!this.canZoom)return;let i=Math.max(this.zoomRange.min,Math.min(this.zoomRange.max,e)),n=performance.now();if(t&&this.zoomCtl.hold(n),this.zoomCtl.settle(n,this.digital?90:380),this.zoomValue=i,this.lastHint=null,this.emit("zoom",{zoom:i,min:this.zoomRange.min,max:this.zoomRange.max,auto:!t,digital:this.digital}),!this.digital)try{await this.track.applyConstraints({advanced:[{zoom:i}]})}catch{}}async setTorch(e){if(!this.track||!this.canTorch)return!1;try{return await this.track.applyConstraints({advanced:[{torch:e}]}),!0}catch{return!1}}async focusAt(e,t){if(this.track){this.zoomCtl.settle(performance.now(),600);try{await this.track.applyConstraints({advanced:[{focusMode:"single-shot",pointsOfInterest:[{x:e,y:t}]}]}),setTimeout(()=>{this.track?.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})},1500)}catch{}}}async scanImage(e){let t=e instanceof Blob?await createImageBitmap(e):e,i=!this.engine;i&&await this.setupDetectors();try{let n=Math.max(t.width,t.height),s=[...new Set([Math.min(n,1600),Math.min(n,1e3),Math.min(n,2600)])];for(let r of s){let o=r/n,c=Math.max(1,Math.round(t.width*o)),u=Math.max(1,Math.round(t.height*o)),k=document.createElement("canvas");k.width=c,k.height=u;let g=k.getContext("2d",{willReadFrequently:!0});g.fillStyle="#fff",g.fillRect(0,0,c,u),g.drawImage(t,0,0,c,u);let v=g.getImageData(0,0,c,u),h=await this.analyzeFrame({pixels:v.data.buffer,width:c,height:u},{invert:!0,thorough:!0,formats:this.opts.formats});if(h&&h.text!==void 0){let d=q(h,[],1,"image"),x=await this.check(d);return x===!0?d:(this.emit("reject",{result:d,message:x||void 0}),null)}}return null}finally{e instanceof Blob&&t.close(),i&&!this.running&&this.releaseEngine()}}fail(e){return this.emit("error",e),e}async tune(){let e=this.track,t=e.getCapabilities?.()??{};if(t.zoom&&typeof t.zoom.max=="number")this.digital=!1,this.zoomRange={min:t.zoom.min??1,max:Math.min(t.zoom.max,this.opts.maxZoom)},this.zoomValue=e.getSettings().zoom??this.zoomRange.min,this.zoomCtl=new z({settleMs:380});else{if(this.digital=!0,this.opts.hiRes)try{await e.applyConstraints({width:{ideal:3840},height:{ideal:2160}}),await new Promise(s=>setTimeout(s,250))}catch{}let i=this.video.videoWidth||1920,n=Math.min(this.opts.maxZoom,4,Math.max(1.5,i/960));this.zoomRange={min:1,max:n},this.zoomValue=1,this.zoomCtl=new z({settleMs:120})}if(t.focusMode?.includes("continuous"))try{await e.applyConstraints({advanced:[{focusMode:"continuous"}]})}catch{}this.emit("zoom",{zoom:this.zoomValue,min:this.zoomRange.min,max:this.zoomRange.max,auto:!0,digital:this.digital})}async setupDetectors(){if(this.setupNative(),!this.engine){let e=this.opts.superResolution;this.engine=await f.acquire({sr:e===!1?"off":e,ortUrl:this.opts.onnxRuntimeUrl})}}setupNative(){if(this.native=null,this.opts.formats&&!this.opts.formats.includes("qr_code"))return;let e=globalThis.BarcodeDetector;e&&e.getSupportedFormats().then(t=>{t.includes("qr_code")&&(this.native=new e({formats:["qr_code"]}))}).catch(()=>{})}async check(e){let t=this.opts.accept;if(!t)return!0;try{let i=await t(e);return i===void 0||i===!0?!0:typeof i=="string"?i:!1}catch{return!1}}releaseEngine(){this.engine&&(this.engine=!1,f.release())}async loop(e){for(;this.running&&e===this.loopToken&&(await B(this.video),!(!this.running||e!==this.loopToken));)if(!this.paused)try{await this.step()}catch(t){this.running&&e===this.loopToken&&this.emit("error",new b("unknown",String(t))),await new Promise(i=>setTimeout(i,300))}}async grab(e,t,i){let n=this.video;if(this.useBitmap&&this.engine&&f.alive){try{let c=await createImageBitmap(n,e.x,e.y,e.w,e.h,{resizeWidth:t,resizeHeight:i,resizeQuality:"low"});if(Math.abs(c.width-t)<=1)return{bitmap:c,src:c};c.close()}catch{}this.useBitmap=!1}let s=this.grabCanvas??(this.grabCanvas=document.createElement("canvas"));(s.width!==t||s.height!==i)&&(s.width=t,s.height=i);let r=s.getContext("2d",{willReadFrequently:!0});r.drawImage(n,e.x,e.y,e.w,e.h,0,0,t,i);let o=r.getImageData(0,0,t,i);return{pixels:o.data.buffer,width:t,height:i,src:o}}async analyzeFrame(e,t){if(this.engine&&f.alive)return f.analyze(e,t);let[{analyze:i},{jsqrDecoder:n}]=await Promise.all([import("./engine-EJ4OC3LZ.js"),import("../kqrcode.jsqr.js")]),s;if("bitmap"in e){let r=document.createElement("canvas");r.width=e.bitmap.width,r.height=e.bitmap.height;let o=r.getContext("2d",{willReadFrequently:!0});o.drawImage(e.bitmap,0,0),e.bitmap.close(),s=o.getImageData(0,0,r.width,r.height)}else s={data:new Uint8ClampedArray(e.pixels),width:e.width,height:e.height};return i(s,t,n)}async step(){let e=this.video;if(e.readyState<2||!e.videoWidth)return;let t=e.videoWidth,i=e.videoHeight,n=performance.now();this.frame++;let s=this.digital?this.zoomValue:1,r={w:t/s,h:i/s,x:0,y:0};r.x=(t-r.w)/2,r.y=(i-r.h)/2;let o=Math.min(1,this.opts.maxFrameSide/Math.max(r.w,r.h)),c=Math.max(2,Math.round(r.w*o)),u=Math.max(2,Math.round(r.h*o)),k=a=>({x:r.x+a.x/o,y:r.y+a.y/o}),g=a=>({cx:(a.cx-r.x)*o,cy:(a.cy-r.y)*o,size:a.size*o,module:a.module*o,full:a.full}),v=await this.grab(r,c,u),h=null;if(this.native)try{let a=await this.native.detect(v.src);if(a.length&&a[0].rawValue){let m=a[0],p=Math.hypot(m.cornerPoints[0].x-m.cornerPoints[1].x,m.cornerPoints[0].y-m.cornerPoints[1].y);h={text:m.rawValue,bytes:new TextEncoder().encode(m.rawValue),corners:m.cornerPoints,hint:{cx:(m.cornerPoints[0].x+m.cornerPoints[2].x)/2,cy:(m.cornerPoints[0].y+m.cornerPoints[2].y)/2,size:p,module:p/25,full:!0},format:"qr_code",version:"",ecLevel:"",luma:128}}}catch{this.native=null}if(h)"bitmap"in v&&v.bitmap.close();else{let a=this.lastHint&&n-this.lastHint.at<700?g(this.lastHint.hint):null;h=await this.analyzeFrame(A(v),{hint:a,invert:this.frame%6===5,thorough:this.frame%5===0,formats:this.opts.formats})}if(!this.running)return;let d=h?.hint?{cx:r.x+h.hint.cx/o,cy:r.y+h.hint.cy/o,size:h.hint.size/o,module:h.hint.module/o,full:h.hint.full}:null,x=h?.corners?h.corners.map(k):[];if(h&&h.text===void 0&&d&&o<.95&&d.module<5/o){let a=Math.min(Math.max(160,d.size*1.6),Math.min(t,i),1400),m={w:a,h:a,x:Math.max(0,Math.min(t-a,d.cx-a/2)),y:Math.max(0,Math.min(i-a,d.cy-a/2))},p=await this.grab(m,Math.round(a),Math.round(a)),E=Math.min(3,Math.max(1,4/Math.max(1,d.module))),w=await this.analyzeFrame(A(p),{roiOnly:!0,upscale:E,invert:this.frame%3===0,formats:this.opts.formats});w&&w.text!==void 0&&w.corners&&(h={...w,hint:h.hint,luma:h.luma},x=w.corners.map(M=>({x:m.x+M.x,y:m.y+M.y})))}if(!this.running)return;if(h&&h.luma){this.lumaEma=this.lumaEma*.85+h.luma*.15;let a=this.darkState?this.lumaEma<70:this.lumaEma<45;a!==this.darkState&&(this.darkState=a,this.emit("dark",a))}d&&(this.lastHint={hint:d,at:n});let y=!!h&&h.text!==void 0;if(this.emit("hint",{hint:d,decoded:y,videoWidth:t,videoHeight:i}),this.opts.autoZoom&&this.canZoom&&!y){let a=this.zoomValue,m=d&&this.digital?{cx:(d.cx-t/2)*a+t/2,cy:(d.cy-i/2)*a+i/2,size:d.size*a,module:d.module*a,full:d.full}:d,p=this.zoomCtl.update({now:n,zoom:a,min:this.zoomRange.min,max:this.zoomRange.max,hint:m,decoded:y,videoWidth:t,videoHeight:i});p!==null&&this.setZoom(p,!1)}if(y&&h){let a=h.text;if(this.opts.continuous&&a===this.lastText&&n-this.lastTextAt<1500){this.lastTextAt=n;return}let m=this.rejected.get(a);if(m!==void 0&&n<m){this.rejected.set(a,n+L);return}let p=q(h,x,this.zoomValue,"camera"),E=this.loopToken,w=await this.check(p);if(!this.running||E!==this.loopToken)return;if(w!==!0){let M=performance.now();for(let[F,H]of this.rejected)H<M&&this.rejected.delete(F);this.rejected.set(a,M+L),this.emit("reject",{result:p,message:w||void 0});return}this.lastText=a,this.lastTextAt=performance.now(),this.opts.continuous||(this.paused=!0),this.emit("result",p)}}},L=2e3;function q(l,e,t,i){let n=l.text;return{text:n,bytes:l.bytes??new TextEncoder().encode(n),corners:e,format:l.format??"qr_code",version:l.version??"",ecLevel:l.ecLevel??"",zoom:t,timestamp:Date.now(),source:i}}function V(l){let e=l?.name;return e==="NotAllowedError"||e==="SecurityError"?new b("permission-denied","Camera permission denied."):e==="NotFoundError"||e==="OverconstrainedError"?new b("no-camera","No camera found."):e==="NotReadableError"||e==="AbortError"?new b("camera-busy","Camera is in use by another app."):new b("unknown",String(l))}var I=["qr_code","micro_qr_code","rm_qr_code"];var P={en:{hint:"Scan a QR code anywhere in view",zooming:"Zooming in\u2026",dark:"Too dark \u2013 turn on the light",torchOn:"Tap to turn light on",torchOff:"Tap to turn light off",gallery:"Album",noQrInImage:"No QR code found in the image",close:"Close",permission:"Camera permission denied. Please allow camera access.",noCamera:"No camera found on this device.",busy:"The camera is being used by another app.",insecure:"Camera needs HTTPS.",unsupported:"This browser cannot access the camera."},lo:{hint:"\u0EAA\u0EB0\u0EC1\u0E81\u0E99 QR code \u0E9A\u0EC8\u0EAD\u0E99\u0EC3\u0E94\u0E81\u0ECD\u0EC4\u0E94\u0EC9\u0EC3\u0E99\u0E81\u0EC9\u0EAD\u0E87",zooming:"\u0E81\u0EB3\u0EA5\u0EB1\u0E87\u0E8A\u0EB9\u0EA1\u0EC0\u0E82\u0EBB\u0EC9\u0EB2\u2026",dark:"\u0EA1\u0EB7\u0E94\u0EC0\u0E81\u0EB5\u0E99\u0EC4\u0E9B \u2013 \u0EC0\u0E9B\u0EB5\u0E94\u0EC4\u0E9F\u0EAA\u0EB2\u0E8D",torchOn:"\u0EC1\u0E95\u0EB0\u0EC0\u0E9E\u0EB7\u0EC8\u0EAD\u0EC0\u0E9B\u0EB5\u0E94\u0EC4\u0E9F",torchOff:"\u0EC1\u0E95\u0EB0\u0EC0\u0E9E\u0EB7\u0EC8\u0EAD\u0E9B\u0EB4\u0E94\u0EC4\u0E9F",gallery:"\u0EAD\u0EB1\u0E99\u0EA5\u0EB0\u0E9A\u0EB1\u0EC9\u0EA1",noQrInImage:"\u0E9A\u0ECD\u0EC8\u0E9E\u0EBB\u0E9A QR code \u0EC3\u0E99\u0EAE\u0EB9\u0E9A",close:"\u0E9B\u0EB4\u0E94",permission:"\u0E9A\u0ECD\u0EC8\u0EC4\u0E94\u0EC9\u0EAE\u0EB1\u0E9A\u0EAA\u0EB4\u0E94\u0EC3\u0E8A\u0EC9\u0E81\u0EC9\u0EAD\u0E87 \u0E81\u0EB0\u0EA5\u0EB8\u0E99\u0EB2\u0EAD\u0EB0\u0E99\u0EB8\u0E8D\u0EB2\u0E94",noCamera:"\u0E9A\u0ECD\u0EC8\u0E9E\u0EBB\u0E9A\u0E81\u0EC9\u0EAD\u0E87\u0EC3\u0E99\u0EAD\u0EB8\u0E9B\u0EB0\u0E81\u0EAD\u0E99\u0E99\u0EB5\u0EC9",busy:"\u0E81\u0EC9\u0EAD\u0E87\u0E81\u0EB3\u0EA5\u0EB1\u0E87\u0E96\u0EB7\u0E81\u0EC3\u0E8A\u0EC9\u0EC2\u0E94\u0E8D\u0EC1\u0EAD\u0EB1\u0E9A\u0EAD\u0EB7\u0EC8\u0E99",insecure:"\u0E81\u0EC9\u0EAD\u0E87\u0E95\u0EC9\u0EAD\u0E87\u0EC3\u0E8A\u0EC9 HTTPS",unsupported:"\u0E9A\u0EA3\u0EB2\u0EA7\u0EC0\u0E8A\u0EB5\u0E99\u0EB5\u0EC9\u0E9A\u0ECD\u0EC8\u0EAE\u0EAD\u0E87\u0EAE\u0EB1\u0E9A\u0E81\u0EB2\u0E99\u0EC3\u0E8A\u0EC9\u0E81\u0EC9\u0EAD\u0E87"},zh:{hint:"\u626B\u4E8C\u7EF4\u7801 / \u6761\u7801",zooming:"\u6B63\u5728\u653E\u5927\u2026",dark:"\u5149\u7EBF\u592A\u6697",torchOn:"\u8F7B\u89E6\u7167\u4EAE",torchOff:"\u8F7B\u89E6\u5173\u95ED",gallery:"\u76F8\u518C",noQrInImage:"\u672A\u5728\u56FE\u7247\u4E2D\u53D1\u73B0\u4E8C\u7EF4\u7801",close:"\u5173\u95ED",permission:"\u76F8\u673A\u6743\u9650\u88AB\u62D2\u7EDD\uFF0C\u8BF7\u5141\u8BB8\u8BBF\u95EE\u76F8\u673A",noCamera:"\u672A\u627E\u5230\u76F8\u673A",busy:"\u76F8\u673A\u88AB\u5176\u4ED6\u5E94\u7528\u5360\u7528",insecure:"\u76F8\u673A\u9700\u8981 HTTPS",unsupported:"\u6B64\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u76F8\u673A"}},et={"--kqr-accent":"scan line / corner colour (theme default: wechat #07c160, alipay #1677ff, frame/grid #1fd17a)","--kqr-success":'colour of the "found it" dot (default: accent)',"--kqr-mask":"dim colour outside the frame (frame theme), default rgba(0,0,0,.45)","--kqr-frame-size":"frame side, default min(70vmin, 300px)","--kqr-frame-top":"vertical centre of the frame, default 42%","--kqr-frame-radius":"default 14px","--kqr-frame-border":"border around the frame, e.g. 1px solid #fff9; default none","--kqr-corner-size":"default 24px","--kqr-corner-width":"default 4px (0 hides the corners)","--kqr-scan-duration":"one sweep, default 2.4s","--kqr-line-width":"scan line thickness, default 3px","--kqr-text":"text colour, default #fff","--kqr-font":"font stack","--kqr-button-bg":"round button background, default rgba(40,40,40,.55)","--kqr-button-size":"default 52px","--kqr-bg":"background behind the video, default #000","--kqr-gallery-bg":'album button background in layout="bar", default: accent',"--kqr-gallery-size":'album button size in layout="bar", default 68px',"--kqr-gallery-radius":'album button corner radius in layout="bar", default 22px'},R={close:'<svg viewBox="0 0 24 24"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></svg>',torch:'<svg viewBox="0 0 24 24"><path d="M8 2h8l-1.5 6h-5L8 2zm1.5 6h5V13l2 3v6h-9v-6l2-3V8z" fill="currentColor"/></svg>',image:'<svg viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="16" rx="3" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="9" cy="10" r="1.8" fill="currentColor"/><path d="M4 18l5.5-5.5 4 4 3-3L21 18" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></svg>',plus:'<svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></svg>',minus:'<svg viewBox="0 0 24 24"><path d="M5 12h14" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></svg>'},D=`
2
+ :host{--_accent:var(--kqr-accent,#07c160);--_ok:var(--kqr-success,var(--_accent));--_dur:var(--kqr-scan-duration,2.4s);
3
+ --_fs:var(--kqr-frame-size,min(70vmin,300px));--_ft:var(--kqr-frame-top,42%);--_fr:var(--kqr-frame-radius,14px);
4
+ --_cs:var(--kqr-corner-size,24px);--_cw:var(--kqr-corner-width,4px);--_lw:var(--kqr-line-width,3px);
5
+ --_btn:var(--kqr-button-bg,rgba(40,40,40,.55));--_bs:var(--kqr-button-size,52px);
6
+ position:fixed;inset:0;z-index:2147483000;display:block;overflow:hidden;
7
+ background:var(--kqr-bg,#000);color:var(--kqr-text,#fff);
8
+ font:14px/1.4 var(--kqr-font,system-ui,-apple-system,"Segoe UI",Roboto,"Noto Sans Lao","PingFang SC","Noto Sans SC",sans-serif);
9
+ -webkit-tap-highlight-color:transparent;user-select:none;-webkit-user-select:none}
10
+ :host([theme=alipay]){--_accent:var(--kqr-accent,#1677ff)}
11
+ :host([theme=frame]),:host([theme=grid]){--_accent:var(--kqr-accent,#1fd17a)}
12
+ :host([inline]){position:relative;inset:auto;width:100%;height:100%;min-height:240px;z-index:auto}
13
+ :host([hidden]){display:none}
14
+ *{box-sizing:border-box}
15
+ .stage{position:absolute;inset:0;touch-action:none}
16
+ video{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;background:var(--kqr-bg,#000);transform-origin:50% 50%}
17
+ canvas{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}
18
+ .fx{position:absolute;inset:0;pointer-events:none}
19
+
20
+ /* ---------- full-screen sweep (wechat / alipay) ---------- */
21
+ .sweep{position:absolute;left:0;right:0;top:0;display:none;will-change:transform,opacity}
22
+ :host(:not([theme])) .sweep,:host([theme=wechat]) .sweep{display:block;height:var(--_lw);
23
+ background:radial-gradient(50% 50% at 50% 50%,var(--_accent) 0%,color-mix(in srgb,var(--_accent) 60%,transparent) 45%,transparent 100%);
24
+ box-shadow:0 0 18px 2px color-mix(in srgb,var(--_accent) 55%,transparent);
25
+ margin:0 6%;animation:kqr-wechat var(--_dur) ease-in-out infinite}
26
+ @keyframes kqr-wechat{0%{transform:translateY(16vh);opacity:0}12%{opacity:1}80%{opacity:1}100%{transform:translateY(72vh);opacity:0}}
27
+ :host([theme=alipay]) .sweep{display:block;height:28vh;
28
+ background:linear-gradient(to bottom,transparent 0%,color-mix(in srgb,var(--_accent) 10%,transparent) 55%,color-mix(in srgb,var(--_accent) 45%,transparent) 100%);
29
+ border-bottom:var(--_lw) solid color-mix(in srgb,var(--_accent) 85%,#fff);
30
+ animation:kqr-alipay var(--_dur) linear infinite}
31
+ @keyframes kqr-alipay{0%{transform:translateY(-28vh);opacity:0}15%{opacity:1}85%{opacity:1}100%{transform:translateY(78vh);opacity:0}}
32
+
33
+ /* ---------- frame (frame / grid) ---------- */
34
+ .frame{position:absolute;left:50%;top:var(--_ft);width:var(--_fs);aspect-ratio:1;transform:translate(-50%,-50%);
35
+ border-radius:var(--_fr);display:none;overflow:hidden;border:var(--kqr-frame-border,none)}
36
+ :host([theme=frame]) .frame,:host([theme=grid]) .frame{display:block}
37
+ :host([theme=frame]) .frame{box-shadow:0 0 0 100vmax var(--kqr-mask,rgba(0,0,0,.45));overflow:visible}
38
+ .frame i{position:absolute;width:var(--_cs);height:var(--_cs);border:0 solid var(--_accent);z-index:1}
39
+ :host([theme=grid]) .frame i{border-color:#fff}
40
+ .frame i:nth-of-type(1){left:0;top:0;border-left-width:var(--_cw);border-top-width:var(--_cw);border-top-left-radius:var(--_fr)}
41
+ .frame i:nth-of-type(2){right:0;top:0;border-right-width:var(--_cw);border-top-width:var(--_cw);border-top-right-radius:var(--_fr)}
42
+ .frame i:nth-of-type(3){left:0;bottom:0;border-left-width:var(--_cw);border-bottom-width:var(--_cw);border-bottom-left-radius:var(--_fr)}
43
+ .frame i:nth-of-type(4){right:0;bottom:0;border-right-width:var(--_cw);border-bottom-width:var(--_cw);border-bottom-right-radius:var(--_fr)}
44
+ .scan{position:absolute;left:0;right:0;top:0}
45
+ :host([theme=frame]) .scan{left:8%;right:8%;height:var(--_lw);border-radius:2px;
46
+ background:linear-gradient(90deg,transparent,var(--_accent),transparent);box-shadow:0 0 12px var(--_accent);
47
+ animation:kqr-frame calc(var(--_dur) * .9) ease-in-out infinite alternate}
48
+ @keyframes kqr-frame{from{transform:translateY(calc(var(--_fs) * .05))}to{transform:translateY(calc(var(--_fs) * .93))}}
49
+ :host([theme=grid]) .scan{height:55%;
50
+ background-image:linear-gradient(color-mix(in srgb,var(--_accent) 55%,transparent) 1px,transparent 1px),
51
+ linear-gradient(90deg,color-mix(in srgb,var(--_accent) 55%,transparent) 1px,transparent 1px);
52
+ background-size:11px 11px;
53
+ -webkit-mask-image:linear-gradient(to bottom,transparent,#000 92%,transparent);mask-image:linear-gradient(to bottom,transparent,#000 92%,transparent);
54
+ animation:kqr-grid var(--_dur) linear infinite}
55
+ @keyframes kqr-grid{from{transform:translateY(-100%)}to{transform:translateY(190%)}}
56
+ :host([found]) .sweep,:host([found]) .scan{animation:none!important;visibility:hidden}
57
+
58
+ /* ---------- success dot ---------- */
59
+ .dot{position:absolute;width:44px;height:44px;margin:-22px 0 0 -22px;border-radius:50%;display:none;
60
+ background:var(--_ok);border:3px solid #fff;box-shadow:0 2px 14px rgba(0,0,0,.35);pointer-events:none}
61
+ .dot::after{content:"";position:absolute;left:50%;top:50%;width:14px;height:8px;border:solid #fff;border-width:0 0 3px 3px;
62
+ transform:translate(-50%,-70%) rotate(-45deg)}
63
+ .dot.go{display:block;animation:kqr-pop .38s cubic-bezier(.2,1.6,.4,1)}
64
+ .dot.go::before{content:"";position:absolute;inset:-3px;border-radius:50%;border:3px solid var(--_ok);animation:kqr-ripple 1s ease-out .2s infinite}
65
+ @keyframes kqr-pop{from{transform:scale(0)}to{transform:scale(1)}}
66
+ @keyframes kqr-ripple{from{transform:scale(1);opacity:.9}to{transform:scale(2.2);opacity:0}}
67
+ :host([success=box]) .dot{display:none!important}
68
+
69
+ /* ---------- chrome ---------- */
70
+ .top{position:absolute;left:0;right:0;top:0;display:grid;grid-template-columns:1fr auto 1fr;align-items:center;
71
+ padding:max(12px,env(safe-area-inset-top)) 14px 10px}
72
+ .top .r{justify-self:end;display:flex;gap:10px}.top .l{display:flex;gap:10px}
73
+ .title{font-size:17px;font-weight:600;text-shadow:0 1px 3px #0008}
74
+ .bottom{position:absolute;left:0;right:0;bottom:0;display:flex;flex-direction:column;align-items:center;gap:16px;
75
+ padding:20px 22px max(18px,env(safe-area-inset-bottom));pointer-events:none}
76
+ .bottom>*{pointer-events:auto}
77
+ button{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;gap:6px;
78
+ font-size:12px;color:inherit}
79
+ button:focus-visible{outline:2px solid currentColor;outline-offset:3px;border-radius:12px}
80
+ .ic{width:var(--_bs);height:var(--_bs);border-radius:50%;background:var(--_btn);
81
+ -webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);display:grid;place-items:center}
82
+ .ic svg{width:24px;height:24px}
83
+ .close .ic{width:36px;height:36px;background:rgba(0,0,0,.35)}.close .ic svg{width:20px;height:20px}
84
+ .msg{min-height:20px;text-align:center;text-shadow:0 1px 3px #000a;padding:0 8px;opacity:.95}
85
+ .msg.warn{color:#ffd24d}
86
+ .torch{flex-direction:column;gap:4px;font-size:12px;padding:6px 10px}
87
+ .torch .ic{width:44px;height:44px;background:transparent;-webkit-backdrop-filter:none;backdrop-filter:none}
88
+ .torch.on{color:var(--_accent)}
89
+ .actions{display:grid;grid-template-columns:1fr auto 1fr;align-items:end;width:100%}
90
+ .cl{justify-self:start;display:flex;gap:12px}.cc{justify-self:center;display:flex;gap:12px}.cr{justify-self:end;display:flex;gap:12px}
91
+ .banner{position:absolute;left:0;right:0;top:calc(max(12px,env(safe-area-inset-top)) + 50px);display:flex;flex-direction:column;
92
+ align-items:center;gap:8px;padding:0 16px;text-align:center;pointer-events:none}
93
+ .banner>*{pointer-events:auto}
94
+ /* layout="bar": one row \u2013 flashlight \xB7 big album button \xB7 your button */
95
+ :host([layout=bar]) .actions{align-items:center}
96
+ :host([layout=bar]) .torch,:host([layout=bar]) .gallery{padding:0}
97
+ :host([layout=bar]) .torch .t,:host([layout=bar]) .gallery .t{display:none}
98
+ :host([layout=bar]) .torch .ic{width:var(--_bs);height:var(--_bs)}
99
+ :host([layout=bar]) .torch .ic svg{width:30px;height:30px}
100
+ :host([layout=bar]) .gallery .ic{width:var(--kqr-gallery-size,68px);height:var(--kqr-gallery-size,68px);
101
+ border-radius:var(--kqr-gallery-radius,22px);background:var(--kqr-gallery-bg,var(--_accent));
102
+ -webkit-backdrop-filter:none;backdrop-filter:none;box-shadow:0 4px 14px rgba(0,0,0,.25)}
103
+ :host([layout=bar]) .gallery .ic svg{width:32px;height:32px}
104
+ .zoom{display:flex;align-items:center;gap:10px;width:min(86vw,340px)}
105
+ .zoom button .ic{width:30px;height:30px}.zoom button .ic svg{width:16px;height:16px}
106
+ .zoom input{flex:1;accent-color:var(--_accent);height:28px;margin:0}
107
+ .zoom span{min-width:42px;text-align:right;font-variant-numeric:tabular-nums;font-size:12px}
108
+ [hidden]{display:none!important}
109
+ .ring{position:absolute;width:64px;height:64px;margin:-32px 0 0 -32px;border:2px solid #fff;border-radius:50%;
110
+ pointer-events:none;opacity:0}
111
+ .ring.go{animation:kqr-ring .6s ease-out}
112
+ @keyframes kqr-ring{0%{opacity:1;transform:scale(1.4)}100%{opacity:0;transform:scale(.8)}}
113
+ .err{position:absolute;inset:0;display:none;place-items:center;text-align:center;padding:32px;background:var(--kqr-bg,#000)}
114
+ :host([error]) .err{display:grid}
115
+ input[type=file]{display:none}
116
+ @media (prefers-reduced-motion:reduce){.sweep,.scan{animation-duration:6s!important}}
117
+ `,Q=typeof HTMLElement>"u"?class{}:HTMLElement,S=class extends Q{constructor(){super(...arguments);this.labels={};this.scanner=null;this.$={};this.audio=null;this.pointers=new Map;this.pinch=null;this.tapStart=null;this.lastTap=0;this.lastDraw=null;this.torchOn=!1;this.dark=!1;this.dz=1;this.prevOverflow="";this.msgTimer=0;this.stopTimer=0;this.started=!1;this.rejectedAt=-1;this.onResize=()=>this.redraw()}get accept(){return this._accept}set accept(t){this._accept=t,this.scanner?.setAccept(t)}flag(t){return this.hasAttribute(t)&&this.getAttribute(t)!=="false"}attr(t,i){return this.getAttribute(t)??i}get L(){let t=typeof navigator<"u"?navigator.language:"en";return{...P[(this.getAttribute("locale")||t||"en").slice(0,2).toLowerCase()]??P.en,...this.labels}}connectedCallback(){if(window.addEventListener("resize",this.onResize),this.root){this.flag("manual")||this.start();return}this.hasAttribute("theme")||this.setAttribute("theme","wechat"),this.root=this.attachShadow({mode:"open"}),this.root.innerHTML=`
118
+ <style>${D}</style>
119
+ <div class="stage" part="stage"><video part="video" muted playsinline></video><canvas part="candidates"></canvas></div>
120
+ <div class="fx" part="effect">
121
+ <div class="sweep" part="scanline"></div>
122
+ <div class="frame" part="frame"><i></i><i></i><i></i><i></i><div class="scan" part="scanline"></div></div>
123
+ <div class="dot" part="success"></div>
124
+ <div class="ring" part="focus-ring"></div>
125
+ </div>
126
+ <div class="top" part="top">
127
+ <div class="l"><slot name="top-left"><button class="close" part="close"><span class="ic">${R.close}</span></button></slot></div>
128
+ <slot name="top-center"><div class="title" part="title"></div></slot>
129
+ <div class="r"><slot name="top-right"></slot></div>
130
+ </div>
131
+ <div class="banner" part="banner"><slot name="banner"></slot></div>
132
+ <div class="bottom" part="bottom">
133
+ <slot name="hint"><div class="msg" part="hint" role="status" aria-live="polite"></div></slot>
134
+ <button class="torch" part="torch" hidden><span class="ic">${R.torch}</span><span class="t"></span></button>
135
+ <div class="zoom" part="zoom" hidden>
136
+ <button class="zm" aria-label="zoom out"><span class="ic">${R.minus}</span></button>
137
+ <input type="range" min="1" max="8" step="0.05" value="1" aria-label="zoom">
138
+ <button class="zp" aria-label="zoom in"><span class="ic">${R.plus}</span></button>
139
+ <span class="zl">1.0\xD7</span>
140
+ </div>
141
+ <div class="actions" part="actions">
142
+ <div class="cell cl"><slot name="actions-left"></slot></div>
143
+ <div class="cell cc"><slot name="actions-center"></slot></div>
144
+ <div class="cell cr"><slot name="actions-right"><button class="gallery" part="gallery"><span class="ic">${R.image}</span><span class="t"></span></button></slot></div>
145
+ </div>
146
+ <slot name="footer"></slot>
147
+ </div>
148
+ <div class="err" part="error" role="alert"><slot name="error"><div class="et"></div></slot></div>
149
+ <input type="file" accept="image/*">`;let t=n=>this.root.querySelector(n);this.$={stage:t(".stage"),ring:t(".ring"),dot:t(".dot"),msg:t(".msg"),title:t(".title"),zoom:t(".zoom"),range:t(".zoom input"),zl:t(".zl"),torch:t(".torch"),gallery:t(".gallery"),file:t("input[type=file]"),err:t(".et"),close:t(".close"),zm:t(".zm"),zp:t(".zp")},this.video=t("video"),this.canvas=t("canvas"),this.applyLabels(),this.placeButtons(),this.$.gallery.hidden=this.flag("no-gallery"),this.$.close.hidden=this.flag("no-close");let i=(n,s,r)=>n.addEventListener(s,r);i(this.$.close,"click",()=>this.close()),i(this.$.gallery,"click",()=>this.pickImage()),i(this.$.file,"change",()=>this.onFile()),i(this.$.torch,"click",()=>this.toggleTorch()),i(this.$.range,"input",()=>this.scanner?.setZoom(parseFloat(this.$.range.value),!0)),i(this.$.zm,"click",()=>this.zoomStep(-1)),i(this.$.zp,"click",()=>this.zoomStep(1)),i(this.$.stage,"pointerdown",n=>this.pdown(n)),i(this.$.stage,"pointermove",n=>this.pmove(n)),i(this.$.stage,"pointerup",n=>this.pup(n)),i(this.$.stage,"pointercancel",n=>{this.pointers.delete(n.pointerId),this.pinch=null}),this.flag("manual")||this.start()}disconnectedCallback(){window.removeEventListener("resize",this.onResize),this.stop()}attributeChangedCallback(t){this.root&&((t==="locale"||t==="heading")&&this.applyLabels(),t==="torch"&&this.updateTorchButton(),t==="layout"&&(this.placeButtons(),this.updateTorchButton()),t==="formats"&&this.scanner?.setFormats(this.formats),t==="zoom-control"&&this.scanner&&this.onZoom({zoom:this.scanner.zoom,min:this.scanner.zoomMin,max:this.scanner.zoomMax,auto:!1,digital:this.scanner.isDigitalZoom}))}async start(){if(!this.video||this.started)return;this.started=!0,this.hidden=!1,this.removeAttribute("error"),this.removeAttribute("found"),this.$.dot.classList.remove("go"),this.flag("inline")||(this.prevOverflow=document.documentElement.style.overflow,document.documentElement.style.overflow="hidden",this.flag("request-fullscreen")&&this.requestFullscreen?.().catch(()=>{}));let t=this.getAttribute("super-resolution"),i=this.scanner=new T({video:this.video,facingMode:this.getAttribute("facing")||"environment",autoZoom:!this.flag("no-auto-zoom"),maxZoom:parseFloat(this.getAttribute("max-zoom")||"")||8,continuous:this.flag("continuous"),superResolution:t==="off"||t==="false"?!1:t==="webgpu"?"webgpu":"js",...this.getAttribute("onnx-runtime-url")?{onnxRuntimeUrl:this.getAttribute("onnx-runtime-url")}:{},formats:this.formats,accept:this._accept});i.on("result",n=>this.onResult(n)),i.on("reject",n=>this.onReject(n)),i.on("error",n=>this.onError(n)),i.on("zoom",n=>this.onZoom(n)),i.on("hint",n=>{this.lastDraw={hint:n.hint,decoded:n.decoded,vw:n.videoWidth,vh:n.videoHeight},this.redraw()}),i.on("dark",n=>{this.dark=n,this.updateTorchButton(),n&&!this.torchOn?this.say(this.L.dark,0,!0):this.say(this.L.hint)});try{await i.start(),this.updateTorchButton(),this.say(this.L.hint),this.dispatchEvent(new CustomEvent("ready"))}catch{}}stop(){clearTimeout(this.stopTimer),this.scanner?.stop(),this.scanner=null,this.started&&!this.flag("inline")&&(document.documentElement.style.overflow=this.prevOverflow),this.started=!1,this.torchOn=!1,this.audio&&(this.audio.close().catch(()=>{}),this.audio=null)}close(){this.stop(),this.hidden=!0,this.dispatchEvent(new CustomEvent("close"))}get active(){return this.started}resume(){if(!this.started){this.start();return}this.removeAttribute("found"),this.$.dot.classList.remove("go"),this.video.play().catch(()=>{}),this.scanner?.resume(),this.say(this.L.hint)}pickImage(){this.$.file.click()}async toggleTorch(t=!this.torchOn){return this.scanner&&await this.scanner.setTorch(t)?(this.torchOn=t,this.updateTorchButton(),t&&this.say(this.L.hint),!0):!1}get formats(){let t=this.getAttribute("formats");if(!t)return;let i=t.split(/[\s,]+/).filter(n=>I.includes(n));return i.length?i:void 0}onReject(t){this.rejectedAt=performance.now(),t.message&&this.say(t.message,2500,!0),this.dispatchEvent(new CustomEvent("reject",{detail:t,bubbles:!0,composed:!0}))}onResult(t){this.setAttribute("found","");let i=this.flag("continuous");if(!i&&t.source==="camera"&&this.video.pause(),this.showSuccess(t),!this.flag("no-vibrate"))try{navigator.vibrate?.(40)}catch{}this.flag("no-beep")||this.beep();let n=t.source==="camera"&&this.attr("success","dot")!=="none"?380:0;window.setTimeout(()=>this.dispatchEvent(new CustomEvent("scan",{detail:t,bubbles:!0,composed:!0})),n),!i&&!this.flag("keep-camera")?this.stopTimer=window.setTimeout(()=>this.stop(),n+120):i&&setTimeout(()=>{this.removeAttribute("found"),this.$.dot.classList.remove("go")},900)}showSuccess(t){if(this.attr("success","dot")!=="dot"||!t.corners.length)return;let n=this.mapper();if(!n)return;let s=(t.corners[0].x+t.corners[2].x)/2,r=(t.corners[0].y+t.corners[2].y)/2,o=this.$.dot;o.style.left=n.x(s)+"px",o.style.top=n.y(r)+"px",o.classList.remove("go"),o.offsetWidth,o.classList.add("go")}onError(t){let i=this.L,n={"permission-denied":i.permission,"no-camera":i.noCamera,"camera-busy":i.busy,"insecure-context":i.insecure,unsupported:i.unsupported,unknown:t.message}[t.code];this.$.err.textContent=n,this.setAttribute("error",t.code),this.started=!1,this.dispatchEvent(new CustomEvent("error",{detail:t}))}onZoom(t){this.dz=t.digital?t.zoom:1,this.video.style.transition="transform .14s ease-out",this.video.style.transform=t.digital?`scale(${t.zoom})`:"";let i=this.$.range;i.min=String(t.min),i.max=String(t.max),i.value=String(t.zoom),this.$.zoom.hidden=this.attr("zoom-control","none")!=="slider"||t.max<=t.min*1.05,this.$.zl.textContent=t.zoom.toFixed(1)+"\xD7",t.auto&&t.zoom>t.min*1.05&&this.say(this.L.zooming,1200),this.redraw(),this.dispatchEvent(new CustomEvent("zoom",{detail:t}))}zoomStep(t){let i=this.scanner;i&&i.setZoom(i.zoom+t*Math.max(.5,i.zoomMax/8),!0)}placeButtons(){let t=i=>this.root.querySelector(`slot[name=${i}]`);this.getAttribute("layout")==="bar"?(t("actions-left").append(this.$.torch),t("actions-center").append(this.$.gallery)):(this.$.zoom.before(this.$.torch),t("actions-right").append(this.$.gallery))}updateTorchButton(){let t=this.flag("no-torch")?"never":this.attr("torch","auto"),i=!!this.scanner?.canTorch,n=this.getAttribute("layout")==="bar",s=i&&(t==="always"||t==="auto"&&(n||this.dark||this.torchOn));this.$.torch.hidden=!s,this.$.torch.classList.toggle("on",this.torchOn),this.$.torch.querySelector(".t").textContent=this.torchOn?this.L.torchOff:this.L.torchOn}async onFile(){let t=this.$.file,i=t.files?.[0];if(t.value="",!i)return;let n=this.scanner?null:new T({video:this.video,formats:this.formats,accept:this._accept});n?.on("reject",o=>this.onReject(o));let s=this.scanner??n,r=performance.now();try{let o=await s.scanImage(i);o?this.onResult(o):this.rejectedAt<r&&this.say(this.L.noQrInImage,2500,!0)}catch{this.say(this.L.noQrInImage,2500,!0)}finally{n?.stop()}}pdown(t){this.$.stage.setPointerCapture?.(t.pointerId),this.pointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.pointers.size===1?this.tapStart={x:t.clientX,y:t.clientY,t:performance.now()}:(this.tapStart=null,this.pinch={dist:this.pdist(),zoom:this.scanner?.zoom??1})}pmove(t){this.pointers.has(t.pointerId)&&(this.pointers.set(t.pointerId,{x:t.clientX,y:t.clientY}),this.pinch&&this.pointers.size>=2&&this.scanner&&this.scanner.setZoom(this.pinch.zoom*(this.pdist()/this.pinch.dist),!0))}pup(t){this.pointers.delete(t.pointerId),this.pointers.size<2&&(this.pinch=null);let i=this.tapStart;this.tapStart=null;let n=this.scanner;if(!i||!n||Math.hypot(t.clientX-i.x,t.clientY-i.y)>10||performance.now()-i.t>400)return;let s=performance.now();if(s-this.lastTap<300&&n.canZoom){this.lastTap=0;let u=n.zoom>n.zoomMin*1.3?n.zoomMin:Math.min(n.zoomMax,n.zoomMin*2.5);n.setZoom(u,!0);return}this.lastTap=s;let r=this.getBoundingClientRect(),o=this.$.ring;o.style.left=t.clientX-r.left+"px",o.style.top=t.clientY-r.top+"px",o.classList.remove("go"),o.offsetWidth,o.classList.add("go");let c=this.mapper();c&&n.focusAt(Math.min(1,Math.max(0,c.invX(t.clientX-r.left))),Math.min(1,Math.max(0,c.invY(t.clientY-r.top))))}pdist(){let[t,i]=[...this.pointers.values()];return Math.hypot(t.x-i.x,t.y-i.y)||1}mapper(){let t=this.video;if(!t?.videoWidth)return null;let i=this.clientWidth,n=this.clientHeight,s=Math.max(i/t.videoWidth,n/t.videoHeight),r=(i-t.videoWidth*s)/2,o=(n-t.videoHeight*s)/2,c=this.dz;return{x:u=>(u*s+r-i/2)*c+i/2,y:u=>(u*s+o-n/2)*c+n/2,s:s*c,invX:u=>((u-i/2)/c+i/2-r)/s/t.videoWidth,invY:u=>((u-n/2)/c+n/2-o)/s/t.videoHeight}}redraw(){let t=this.canvas;if(!t)return;let i=window.devicePixelRatio||1,n=this.clientWidth,s=this.clientHeight;(t.width!==Math.round(n*i)||t.height!==Math.round(s*i))&&(t.width=Math.round(n*i),t.height=Math.round(s*i));let r=t.getContext("2d");r.setTransform(i,0,0,i,0,0),r.clearRect(0,0,n,s);let o=this.lastDraw,c=this.mapper();if(!o||!o.hint||!c||this.flag("no-candidates")||o.decoded&&this.attr("success","dot")!=="box")return;let u=c.x(o.hint.cx),k=c.y(o.hint.cy),g=Math.max(18,o.hint.size*c.s/2),v=Math.min(16,g*.5),h=getComputedStyle(this).getPropertyValue("--kqr-accent").trim()||"#fff";r.strokeStyle=o.decoded?h:"rgba(255,255,255,.9)",r.lineWidth=o.decoded?3.5:2.5,r.lineCap="round";for(let[d,x]of[[-1,-1],[1,-1],[1,1],[-1,1]]){let y=u+d*g,a=k+x*g;r.beginPath(),r.moveTo(y-d*v,a),r.lineTo(y,a),r.lineTo(y,a-x*v),r.stroke()}}applyLabels(){let t=this.L,i=this.$.gallery.querySelector(".t");i.textContent=t.gallery,this.$.close.setAttribute("aria-label",t.close),this.$.title.textContent=this.getAttribute("heading")??"",this.updateTorchButton(),this.say(t.hint)}say(t,i=0,n=!1){clearTimeout(this.msgTimer);let s=this.$.msg;s&&(s.textContent=t,s.classList.toggle("warn",n),i&&(this.msgTimer=window.setTimeout(()=>{s.textContent=this.L.hint,s.classList.remove("warn")},i)))}beep(){try{let t=window.AudioContext||window.webkitAudioContext,i=this.audio??(this.audio=new t),n=i.createOscillator(),s=i.createGain();n.type="sine",n.frequency.value=1800,s.gain.setValueAtTime(1e-4,i.currentTime),s.gain.exponentialRampToValueAtTime(.25,i.currentTime+.01),s.gain.exponentialRampToValueAtTime(1e-4,i.currentTime+.12),n.connect(s).connect(i.destination),n.start(),n.stop(i.currentTime+.13)}catch{}}};S.observedAttributes=["locale","heading","torch","zoom-control","formats","layout"];var W="kqr-scanner";function it(l=W){typeof customElements<"u"&&!customElements.get(l)&&customElements.define(l,S)}export{z as a,b,T as c,I as d,P as e,et as f,S as g,W as h,it as i};
@@ -0,0 +1 @@
1
+ function J(n,t){let s=t??"";if(n==="micro_qr_code"){let c=parseInt(s.replace(/^M/i,""),10);return c>=1&&c<=4?9+2*c:13}if(n==="rm_qr_code"){let c=/(\d+)\s*x\s*(\d+)/i.exec(s);return c?Math.max(+c[1],+c[2]):43}let x=parseInt(s,10);return x>=1&&x<=40?17+4*x:25}var D=null;function K(n){let t=n.width*n.height;(!D||D.length!==t)&&(D=new Uint8Array(t));let s=D,x=n.data,c=0;for(let r=0,o=0;r<t;r++,o+=4){let u=x[o]*77+x[o+1]*150+x[o+2]*29>>8;s[r]=u,(r&15)===0&&(c+=u)}return{gray:s,luma:c/Math.ceil(t/16)}}function T(n,t=!1){let s=n[0]+n[1]+n[2]+n[3]+n[4];if(s<7)return!1;let x=s/7,c=x*(t?.6:.85);return Math.abs(n[0]-x)<c&&Math.abs(n[1]-x)<c&&Math.abs(n[3]-x)<c&&Math.abs(n[4]-x)<c&&Math.abs(n[2]-3*x)<3*c}var H=null,_=null;function N(n,t,s,x){let r=Math.ceil(t/16),o=Math.ceil(s/16);(!_||_.length!==r*o)&&(_=new Float32Array(r*o));let u=_;for(let i=0;i<o;i++){let b=i*16,a=Math.min(s,b+16);for(let e=0;e<r;e++){let m=e*16,y=Math.min(t,m+16),f=0,p=0;for(let w=b;w<a;w+=2){let R=w*t;for(let A=m;A<y;A+=2)f+=n[R+A],p++}u[i*r+e]=f/p}}let M=Math.max(2,Math.round(t/16/16)),d=r+1,h=new Float32Array(d*(o+1));for(let i=0;i<o;i++){let b=0;for(let a=0;a<r;a++)b+=u[i*r+a],h[(i+1)*d+a+1]=h[i*d+a+1]+b}(!H||H.length!==r*o)&&(H=new Uint8Array(r*o));let l=H;for(let i=0;i<o;i++){let b=Math.max(0,i-M),a=Math.min(o,i+M+1);for(let e=0;e<r;e++){let m=Math.max(0,e-M),y=Math.min(r,e+M+1),f=h[a*d+y]-h[b*d+y]-h[a*d+m]+h[b*d+m];l[i*r+e]=Math.min(255,f/((y-m)*(a-b))*x)}}return{thr:l,bw:r}}function V(n,t,s,x=!1){let{thr:c,bw:r}=N(n,t,s,x?1.1:.9),o=x?(e,m)=>n[m*t+e]>c[(m>>4)*r+(e>>4)]:(e,m)=>n[m*t+e]<c[(m>>4)*r+(e>>4)],u=(e,m,y,f,p)=>{let w=Math.ceil(p*2),R=(I,S,v)=>{let k=[0,0,0],U=I,B=S,P=0;for(let q=0;q<w;q++){if(U+=y*v,B+=f*v,U<0||B<0||U>=t||B>=s)return null;let j=o(U,B);if(P===0)j?k[0]++:(P=1,k[1]++);else if(P===1)j?(P=2,k[2]++):k[1]++;else if(j)k[2]++;else return k}return null},A=R(e,m,-1),F=R(e,m,1);if(!A||!F||A[2]===0||F[2]===0)return null;let C=A[0]+F[0]+1,Q=[A[2],A[1],C,F[1],F[2]];if(!T(Q))return null;let z=Q[0]+Q[1]+Q[2]+Q[3]+Q[4],g=(F[0]-A[0])/2;return{total:z,ox:y*g,oy:f*g}},M=[],d=(e,m,y)=>{for(let f of M){let p=Math.max(f.m,y)*2.5;if(Math.abs(f.x-e)<p&&Math.abs(f.y-m)<p&&Math.abs(f.m-y)<Math.max(f.m,y)*.5){let w=f.n;f.x=(f.x*w+e)/(w+1),f.y=(f.y*w+m)/(w+1),f.m=(f.m*w+y)/(w+1),f.n++;return}}M.length<200&&M.push({x:e,y:m,m:y,n:1})},h=[0,0,0,0,0],l=2;for(let e=l>>1;e<s;e+=l){let m=0,y=o(0,e),f=0;h[0]=h[1]=h[2]=h[3]=h[4]=0;for(let p=1;p<=t;p++){let w=p<t?o(p,e):!y;if(m++,w!==y||p===t){if(h[0]=h[1],h[1]=h[2],h[2]=h[3],h[3]=h[4],h[4]=m,f++,y&&f>=5&&T(h)){let R=h[0]+h[1]+h[2]+h[3]+h[4],A=p-h[4]-h[3]-h[2]/2,F=R/7,C=Math.round(A-.5),Q=u(C,e,0,1,R);if(Q){let z=e+Q.oy,g=u(C,Math.round(z),1,0,R);g&&d(C+g.ox,z,(F+Q.total/7)/2)}}y=w,m=0}}}let i=M.filter(e=>e.n>=2).sort((e,m)=>m.n-e.n).slice(0,14);if(!i.length)return null;let b=null;for(let e=0;e<i.length;e++)for(let m=e+1;m<i.length;m++)for(let y=m+1;y<i.length;y++){let f=[i[e],i[m],i[y]],p=f.map(v=>v.m);if(Math.max(...p)/Math.min(...p)>1.8)continue;let w=(v,k)=>Math.hypot(v.x-k.x,v.y-k.y),R=[[w(f[0],f[1]),0,1],[w(f[0],f[2]),0,2],[w(f[1],f[2]),1,2]];R.sort((v,k)=>k[0]-v[0]);let A=R[0],F=R[1][0],C=R[2][0],Q=Math.abs(F-C)/Math.max(F,C),z=Math.abs(A[0]-Math.SQRT2*((F+C)/2))/A[0];if(Q>.4||z>.3)continue;let g=(p[0]+p[1]+p[2])/3,I=(F+C)/2;if(I<g*6)continue;let S=Q+z;if(!b||S<b.err){let v=f[A[1]],k=f[A[2]];b={err:S,hint:{cx:(v.x+k.x)/2,cy:(v.y+k.y)/2,size:I+7*g,module:g,full:!0}}}}if(b)return b.hint;let a=i[0];if(i.length>=2){let e=i[1],m=Math.hypot(a.x-e.x,a.y-e.y);return{cx:(a.x+e.x)/2,cy:(a.y+e.y)/2,size:m*1.3+7*a.m,module:(a.m+e.m)/2,full:!1}}return{cx:a.x,cy:a.y,size:a.m*29,module:a.m,full:!1}}function Y(n,t,s,x=3){let r=Math.floor(t/8),o=Math.floor(s/8),u=new Float32Array(r*o);for(let a=0;a<o;a++)for(let e=0;e<r;e++){let m=0,y=e*8,f=a*8;for(let p=f;p<f+8;p+=2){let w=p*t;for(let R=y;R<y+8;R+=2){let A=n[w+R];m+=Math.abs(A-n[w+R+1])+Math.abs(A-n[w+t+R])}}u[a*r+e]=m/16}let M=Float32Array.from(u).sort(),d=M[M.length>>1],h=Math.max(7,d*2.5,M[Math.floor(M.length*.6)]*1.5),l=new Int32Array(r*o).fill(-1),i=[],b=[];for(let a=0;a<r*o;a++){if(l[a]!==-1||u[a]<h)continue;let e=0,m=0,y=r,f=o,p=0,w=0;for(b.push(a),l[a]=a;b.length;){let z=b.pop(),g=z%r,I=z/r|0;e++,m+=u[z],g<y&&(y=g),g>p&&(p=g),I<f&&(f=I),I>w&&(w=I);let S=[g>0?z-1:-1,g<r-1?z+1:-1,I>0?z-r:-1,I<o-1?z+r:-1];for(let v of S)v>=0&&l[v]===-1&&u[v]>=h&&(l[v]=a,b.push(v))}let R=p-y+1,A=w-f+1,F=e/(R*A),C=Math.max(R,A)/Math.min(R,A);if(e<4||Math.max(R,A)*8>Math.min(t,s)*.9||C>2.2||F<.4)continue;let Q=Math.max(R,A)*8;i.push({hint:{cx:(y+p+1)*8/2,cy:(f+w+1)*8/2,size:Q,module:Q/29,full:!1},score:F*(m/e)*Math.min(1,e/9)/C})}return i.sort((a,e)=>e.score-a.score).slice(0,x).map(a=>a.hint)}function O(n,t,s,x,c,r){let o=Math.round(x*r),u=Math.round(c*r),M=new Uint8ClampedArray(o*u*4),d=n.data,h=n.width;for(let l=0;l<u;l++){let i=s+(l+.5)/r-.5,b=Math.max(0,Math.min(n.height-1,Math.floor(i))),a=Math.min(n.height-1,b+1),e=i-b;for(let m=0;m<o;m++){let y=t+(m+.5)/r-.5,f=Math.max(0,Math.min(h-1,Math.floor(y))),p=Math.min(h-1,f+1),w=y-f,R=(l*o+m)*4,A=(b*h+f)*4,F=(b*h+p)*4,C=(a*h+f)*4,Q=(a*h+p)*4;for(let z=0;z<3;z++){let g=d[A+z]+(d[F+z]-d[A+z])*w,I=d[C+z]+(d[Q+z]-d[C+z])*w;M[R+z]=g+(I-g)*e}M[R+3]=255}}return{data:M,width:o,height:u}}function Z(n,t,s){let x=0,c=0;for(let r=4;r<s;r+=8){let o=r*t;for(let u=o+1,M=o+t-1;u<M;u++)x+=Math.abs(2*n[u]-n[u-1]-n[u+1]),c++}return c?x/c:0}function $(n){let{width:t,height:s,data:x}=n,c=new Uint8ClampedArray(t*s);for(let o=0,u=0;o<c.length;o++,u+=4)c[o]=x[u]*77+x[u+1]*150+x[u+2]*29>>8;let r=new Uint8ClampedArray(t*s*4);for(let o=0;o<s;o++){let u=o>0?o-1:o,M=o<s-1?o+1:o;for(let d=0;d<t;d++){let h=d>0?d-1:d,l=d<t-1?d+1:d,i=(c[u*t+h]+c[u*t+d]+c[u*t+l]+c[o*t+h]+c[o*t+d]+c[o*t+l]+c[M*t+h]+c[M*t+d]+c[M*t+l])/9,b=(o*t+d)*4;r[b]=r[b+1]=r[b+2]=i,r[b+3]=255}}return{data:r,width:t,height:s}}var G=160;async function X(n,t,s,x,c){let r=await x(n),o=O(r,0,0,r.width,r.height,2),u=o.width/n.width,M=await s.decode(o,t,c);return M?{r:M,k:u}:null}async function W(n,t,s,x,c,r){let o=t.size*(t.full?1.42:1.6)+8*t.module,u=Math.max(0,Math.floor(t.cx-o/2)),M=Math.max(0,Math.floor(t.cy-o/2)),d=Math.min(n.width,Math.ceil(t.cx+o/2)),h=Math.min(n.height,Math.ceil(t.cy+o/2)),l=d-u,i=h-M;if(l<24||i<24)return null;let b=Math.min(4,Math.max(1,4/Math.max(1,t.module)),1600/Math.max(l,i));b=Math.round(b*2)/2;let a=b===1&&l===n.width&&i===n.height?n:O(n,u,M,l,i,b),e=await x.decode(a,s,r);if(e){let m=y=>({x:u+y.x/b,y:M+y.y/b});return{...L(e),corners:e.corners.map(m),luma:0}}if(c&&t.module<4.5&&Math.max(l,i)<=(c.maxSide??G)){let m=O(n,u,M,l,i,1),y=await X(m,s,x,c,r);if(y){let f=p=>({x:u+p.x/y.k,y:M+p.y/y.k});return{...L(y.r),corners:y.r.corners.map(f),luma:0}}}return null}var L=n=>({text:n.text,bytes:n.bytes,format:n.format??"qr_code",version:n.version??"",ecLevel:n.ecLevel??""});function E(n,t){let s=n.corners,x=Math.hypot(s[0].x-s[1].x,s[0].y-s[1].y);return{...L(n),corners:s,hint:{cx:(s[0].x+s[2].x)/2,cy:(s[0].y+s[2].y)/2,size:x,module:x/J(n.format,n.version),full:!0},luma:t}}async function tt(n,t,s,x){let c=!!t.invert,r=t.sr===!1?null:x??null,{gray:o,luma:u}=K(n);if(t.roiOnly){let l=t.upscale&&t.upscale>1?t.upscale:1,i=l>1?O(n,0,0,n.width,n.height,l):n,b=await s.decode(i,c,t.formats);if(b)return E({...b,corners:b.corners.map(a=>({x:a.x/l,y:a.y/l}))},u);if(r&&l>1&&Math.max(n.width,n.height)<=(r.maxSide??G)){let a=await X(n,c,s,r,t.formats);if(a)return E({...a.r,corners:a.r.corners.map(e=>({x:e.x/a.k,y:e.y/a.k}))},u)}return{luma:u}}if(t.hint){let l=await W(n,t.hint,c,s,r,t.formats);if(l)return{...l,hint:t.hint,luma:u}}if(!s.slow||t.thorough){let l=await s.decode(n,c,t.formats);if(l)return E(l,u)}let M=V(o,n.width,n.height,c),d=M?[M]:[];for(let l of Y(o,n.width,n.height)){if(d.length>=3)break;d.some(i=>Math.hypot(i.cx-l.cx,i.cy-l.cy)<Math.max(i.size,l.size)*.6)||d.push(l)}let h=r;for(let l of d){let i=await W(n,l,c,s,h,t.formats);if(i)return{...i,hint:l,luma:u};h&&l.module<4.5&&(h=null)}if((!s.slow||t.thorough)&&(t.thorough||d.some(l=>l.module>=2.5)||Z(o,n.width,n.height)>18)){let l=await s.decode($(n),c,t.formats);if(l)return E(l,u)}return{hint:M??d[0]??null,luma:u}}export{tt as analyze,V as locate,Z as moire,J as symbolModules,Y as textureCandidates};
package/dist/cli.js CHANGED
@@ -4,7 +4,7 @@
4
4
  import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
5
5
  import { dirname, join, relative } from "node:path";
6
6
  import { spawnSync } from "node:child_process";
7
- var VERSION = true ? "0.2.0" : "0.0.0";
7
+ var VERSION = true ? "0.3.0" : "0.0.0";
8
8
  var PKG = "k-qr-scanner";
9
9
  var tty = process.stdout.isTTY && !process.env.NO_COLOR;
10
10
  var c = (code) => (s) => tty ? `\x1B[${code}m${s}\x1B[0m` : s;
@@ -274,7 +274,8 @@ function init(a) {
274
274
  }
275
275
  log(green(`\u2714 created ${shown}`));
276
276
  }
277
- if (fw === "react-native") nativeSetup(a.cwd, !!deps.expo, a.dryRun);
277
+ const capacitor = fw !== "react-native" && !!deps["@capacitor/core"];
278
+ if (fw === "react-native" || capacitor) nativeSetup(a.cwd, fw === "react-native" && !!deps.expo, a.dryRun);
278
279
  log("");
279
280
  log(bold("Next steps"));
280
281
  log(` Use it: ${t.usage}`);
@@ -282,6 +283,8 @@ function init(a) {
282
283
  if (deps.expo) log(` Expo Go works as is. Development / EAS builds: ${dim("npx expo prebuild")} picks up the plugin.`);
283
284
  else log(` iOS: ${dim("cd ios && pod install")}, then rebuild the app.`);
284
285
  log(` Guide: ${cyan("https://github.com/kris-lx/kqrcode/blob/main/docs/REACT_NATIVE.md")}`);
286
+ } else if (capacitor) {
287
+ log(` Capacitor: ${dim("npx cap sync")}, then rebuild the app. Guide: ${cyan("https://github.com/kris-lx/kqrcode/blob/main/docs/MOBILE.md#capacitor")}`);
285
288
  } else log(` Camera access needs ${bold("HTTPS")} (localhost is fine during development).`);
286
289
  log(` Themes, slots and options: ${cyan("https://github.com/kris-lx/kqrcode#readme")}`);
287
290
  return 0;
@@ -289,11 +292,19 @@ function init(a) {
289
292
  var IOS_CAMERA = "Allow $(PRODUCT_NAME) to use the camera to scan QR codes";
290
293
  var ANDROID_CAMERA = '<uses-permission android:name="android.permission.CAMERA" />';
291
294
  function plistFiles(cwd) {
292
- try {
293
- return readdirSync(join(cwd, "ios")).map((x) => `ios/${x}/Info.plist`).filter((f) => existsSync(join(cwd, f)));
294
- } catch {
295
- return [];
295
+ const out = [];
296
+ const dirs = (d) => {
297
+ try {
298
+ return readdirSync(join(cwd, d), { withFileTypes: true }).filter((e) => e.isDirectory() && !/^(Pods|build|DerivedData)$|\.(xcodeproj|xcworkspace|xcassets)$/.test(e.name)).map((e) => `${d}/${e.name}`);
299
+ } catch {
300
+ return [];
301
+ }
302
+ };
303
+ for (const d of dirs("ios")) {
304
+ if (existsSync(join(cwd, d, "Info.plist"))) out.push(`${d}/Info.plist`);
305
+ for (const dd of dirs(d)) if (existsSync(join(cwd, dd, "Info.plist"))) out.push(`${dd}/Info.plist`);
296
306
  }
307
+ return out;
297
308
  }
298
309
  var hasExpoPlugin = (appJson) => !!appJson && appJson.includes(`"${PKG}"`);
299
310
  function nativeSetup(cwd, expo, dryRun) {
@@ -389,9 +400,11 @@ function doctor(a) {
389
400
  if (fw === "vue" || fw === "nuxt") {
390
401
  warn("If you use the raw <kqr-scanner> tag in Vue templates (instead of k-qr-scanner/vue), add it to compilerOptions.isCustomElement");
391
402
  }
392
- if (fw === "react-native") {
393
- if (!d["react-native-webview"]) bad("react-native-webview is missing \u2013 run: " + (d.expo ? "npx expo install react-native-webview" : "npm install react-native-webview"));
394
- else ok("react-native-webview installed");
403
+ const capacitor = fw !== "react-native" && !!d["@capacitor/core"];
404
+ if (capacitor) ok("Capacitor app: checking the native camera permissions");
405
+ if (fw === "react-native" || capacitor) {
406
+ if (fw === "react-native" && !d["react-native-webview"]) bad("react-native-webview is missing \u2013 run: " + (d.expo ? "npx expo install react-native-webview" : "npm install react-native-webview"));
407
+ else if (fw === "react-native") ok("react-native-webview installed");
395
408
  const read = (f) => existsSync(join(a.cwd, f)) ? readFileSync(join(a.cwd, f), "utf8") : null;
396
409
  const appJson = read("app.json") ?? read("app.config.js") ?? read("app.config.ts");
397
410
  const plists = plistFiles(a.cwd).map((f) => read(f));
package/dist/element.d.ts CHANGED
@@ -35,8 +35,9 @@ export declare const THEME_VARS: {
35
35
  readonly '--kqr-frame-size': "frame side, default min(70vmin, 300px)";
36
36
  readonly '--kqr-frame-top': "vertical centre of the frame, default 42%";
37
37
  readonly '--kqr-frame-radius': "default 14px";
38
+ readonly '--kqr-frame-border': "border around the frame, e.g. 1px solid #fff9; default none";
38
39
  readonly '--kqr-corner-size': "default 24px";
39
- readonly '--kqr-corner-width': "default 4px";
40
+ readonly '--kqr-corner-width': "default 4px (0 hides the corners)";
40
41
  readonly '--kqr-scan-duration': "one sweep, default 2.4s";
41
42
  readonly '--kqr-line-width': "scan line thickness, default 3px";
42
43
  readonly '--kqr-text': "text colour, default #fff";
@@ -44,6 +45,9 @@ export declare const THEME_VARS: {
44
45
  readonly '--kqr-button-bg': "round button background, default rgba(40,40,40,.55)";
45
46
  readonly '--kqr-button-size': "default 52px";
46
47
  readonly '--kqr-bg': "background behind the video, default #000";
48
+ readonly '--kqr-gallery-bg': "album button background in layout=\"bar\", default: accent";
49
+ readonly '--kqr-gallery-size': "album button size in layout=\"bar\", default 68px";
50
+ readonly '--kqr-gallery-radius': "album button corner radius in layout=\"bar\", default 22px";
47
51
  };
48
52
  declare const Base: typeof HTMLElement;
49
53
  export declare class KQRScannerElement extends Base {
@@ -106,6 +110,12 @@ export declare class KQRScannerElement extends Base {
106
110
  private onZoom;
107
111
  private zoomStep;
108
112
  /** torch="auto" (default): appear when it is dark, like WeChat · "always" · "never" */
113
+ /**
114
+ * layout="bar": flashlight in the left cell, album as the big center button, slot actions-right free.
115
+ * Default layout: flashlight above the actions, album on the right. The built-in buttons are moved
116
+ * into the fallback content of the matching slot, so a slotted element still replaces them.
117
+ */
118
+ private placeButtons;
109
119
  private updateTorchButton;
110
120
  private onFile;
111
121
  private pdown;
package/dist/emv.d.ts ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * EMVCo merchant-presented QR codes: the payment format behind LAO QR, PromptPay, VietQR, DuitNow,
3
+ * QRIS, SGQR, NETS and many more. `parseEMV` reads one into fields and checks its CRC; `acceptEMV`
4
+ * turns that into an `accept` callback. Pure string code, no dependencies, tree-shakeable.
5
+ *
6
+ * accept: acceptEMV({ currency: 'LAK', message: 'ນີ້ບໍ່ແມ່ນ QR ຈ່າຍເງິນ' })
7
+ * onScan: (r) => { const emv = parseEMV(r.text)!; pay(emv.merchantName, emv.amount); }
8
+ */
9
+ import type { AcceptVerdict, ScanResult } from './scanner';
10
+ /** A merchant account: tags 02–25 (card networks, plain value) or 26–51 (templates). */
11
+ export interface EMVAccount {
12
+ /** Tag number, '02'…'51'. */
13
+ tag: string;
14
+ /** Globally unique identifier (sub-tag 00 of a template: an AID or reverse domain), or the plain value. */
15
+ id: string;
16
+ /** Sub-tags of a template, e.g. { '00': 'A000000677010111', '01': '0066812345678' }. Empty for 02–25. */
17
+ fields: Record<string, string>;
18
+ }
19
+ /** Additional data field template (tag 62). */
20
+ export interface EMVAdditionalData {
21
+ billNumber?: string;
22
+ mobileNumber?: string;
23
+ storeLabel?: string;
24
+ loyaltyNumber?: string;
25
+ referenceLabel?: string;
26
+ customerLabel?: string;
27
+ terminalLabel?: string;
28
+ purpose?: string;
29
+ /** Every sub-tag, including scheme-specific ones. */
30
+ fields: Record<string, string>;
31
+ }
32
+ export interface EMVQR {
33
+ /** The CRC (tag 63) matches the payload. Treat a code with `valid: false` as damaged or altered. */
34
+ valid: boolean;
35
+ /** 'static' (tag 01 = 11, reusable) or 'dynamic' (12, one payment); undefined when absent. */
36
+ initiation?: 'static' | 'dynamic';
37
+ accounts: EMVAccount[];
38
+ /** Merchant category code (tag 52). */
39
+ mcc?: string;
40
+ /** ISO 4217 numeric currency (tag 53), e.g. '418'. */
41
+ currency?: string;
42
+ /** ISO 4217 letters for well-known currencies, e.g. 'LAK'. */
43
+ currencyCode?: string;
44
+ /** Transaction amount (tag 54), as written, e.g. '15000' or '12.50'. */
45
+ amount?: string;
46
+ /** Tip or convenience fee: indicator 01 = ask, 02 = fixed fee, 03 = percentage (tags 55–57). */
47
+ tip?: {
48
+ indicator: string;
49
+ fixed?: string;
50
+ percent?: string;
51
+ };
52
+ /** ISO 3166 country (tag 58), e.g. 'LA'. */
53
+ country?: string;
54
+ merchantName?: string;
55
+ merchantCity?: string;
56
+ postalCode?: string;
57
+ additional?: EMVAdditionalData;
58
+ /** Merchant information in another language (tag 64). */
59
+ language?: {
60
+ preference?: string;
61
+ merchantName?: string;
62
+ merchantCity?: string;
63
+ };
64
+ /** Every top-level tag as written. */
65
+ tags: Record<string, string>;
66
+ }
67
+ /** CRC-16/CCITT-FALSE as EMVCo specifies it, over the UTF-8 bytes; 4 uppercase hex digits. */
68
+ export declare function emvCRC(data: string): string;
69
+ /** Reads an EMVCo merchant-presented QR payload. Returns null when the text is not one. */
70
+ export declare function parseEMV(text: string): EMVQR | null;
71
+ export interface AcceptEMVOptions {
72
+ /** Allowed currencies, numeric ('418') or letters ('LAK'). */
73
+ currency?: string | string[];
74
+ /** Allowed countries, e.g. 'LA'. */
75
+ country?: string | string[];
76
+ /** Accept only codes that carry one of these account ids (AID / GUID, or the value of tags 02–25). */
77
+ accounts?: string[];
78
+ /** Accept only dynamic codes (with a fixed amount for one payment). */
79
+ dynamicOnly?: boolean;
80
+ /** Shown for anything that is not a valid payment code. Default: 'Not a payment QR code'. */
81
+ message?: string;
82
+ /** Your own last check, e.g. ask your server. Same return values as `accept`. */
83
+ check?: (emv: EMVQR, result: ScanResult) => AcceptVerdict | Promise<AcceptVerdict>;
84
+ }
85
+ /**
86
+ * An `accept` callback that lets only valid EMV payment codes through: the CRC must match and the
87
+ * code must meet your options. Anything else is turned down with `message`, and scanning goes on.
88
+ */
89
+ export declare function acceptEMV(options?: AcceptEMVOptions): (result: ScanResult) => AcceptVerdict | Promise<AcceptVerdict>;
package/dist/engine.d.ts CHANGED
@@ -91,6 +91,11 @@ export declare function locate(gray: Uint8Array, w: number, h: number, invert?:
91
91
  * ~3 ms @720p. Returns up to `max` candidates, best first.
92
92
  */
93
93
  export declare function textureCandidates(gray: Uint8Array, w: number, h: number, max?: number): QRHint[];
94
+ /**
95
+ * Fine high-frequency energy (mean |1-D Laplacian| on every 8th row). Camera frames of real scenes score
96
+ * about 5–10; a display filmed up close shows its pixel grid as moiré and scores 20 and more.
97
+ */
98
+ export declare function moire(gray: Uint8Array, w: number, h: number): number;
94
99
  /** ×2 super-resolution hook (WeChat CNN). Output may be (2h-1)×(2w-1). */
95
100
  export type SuperRes = ((img: AnalyzeInput) => Promise<AnalyzeInput>) & {
96
101
  /** largest ROI side worth sending to this backend (JS kernel is ~10× slower than ONNX/WebGPU) */