@sekyro/web 0.1.0-rc.8 → 0.1.0-rc.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/README.md +54 -61
- package/dist/{capture-session-doc-YBE3UMJJ.js → capture-session-doc-QQHDBZG4.js} +1 -1
- package/dist/{chunk-YPG7CB4O.js → chunk-4Q7EMVP7.js} +1 -1
- package/dist/{chunk-RNRFHUJA.js → chunk-56GT33O3.js} +1 -1
- package/dist/{chunk-DQWW4OCK.js → chunk-EVVGQSNJ.js} +1 -1
- package/dist/chunk-F5ST423J.js +1 -0
- package/dist/chunk-GBTZIKGZ.js +1 -0
- package/dist/chunk-H6HC7B77.js +1 -0
- package/dist/{chunk-LQ7C44JG.js → chunk-LUHNRNTO.js} +1 -1
- package/dist/{chunk-RVHAKRAI.js → chunk-WRKUWIJW.js} +1 -1
- package/dist/chunk-ZUHTYCY4.js +1 -0
- package/dist/client/index.cjs +1 -1
- package/dist/client/index.d.cts +26 -4
- package/dist/client/index.d.ts +26 -4
- package/dist/client/index.js +1 -1
- package/dist/core/index.cjs +1 -1
- package/dist/core/index.js +1 -1
- package/dist/create-document-capture-DWRNFXA2.js +1 -0
- package/dist/{create-verification-DoFpgzok.d.cts → create-verification-BS2qbe75.d.cts} +101 -16
- package/dist/{create-verification-C0AVIcVW.d.ts → create-verification-CCR-CwVQ.d.ts} +101 -16
- package/dist/{icao-gate-D8qm1O2t.d.cts → icao-gate-DKbWXP51.d.cts} +104 -39
- package/dist/{icao-gate-D8qm1O2t.d.ts → icao-gate-DKbWXP51.d.ts} +104 -39
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/internal/index.cjs +1 -1
- package/dist/internal/index.d.cts +11 -20
- package/dist/internal/index.d.ts +11 -20
- package/dist/internal/index.js +1 -1
- package/dist/{plan-runner-UBK4B4CG.js → plan-runner-X4YW3INX.js} +1 -1
- package/package.json +1 -1
- package/sbom.cdx.json +7 -7
- package/dist/chunk-4RS2YIL4.js +0 -1
- package/dist/chunk-MY6EXEL2.js +0 -1
- package/dist/chunk-XLN5OT25.js +0 -1
- package/dist/chunk-YDQBVWXG.js +0 -1
- package/dist/create-document-capture-T4APHJMY.js +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# @sekyro/web
|
|
2
2
|
|
|
3
|
+
## 0.1.0-rc.9
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 8dbdcf3: Sekyro flows: the SDK renders the flow plan of the hosted view (`HostedSessionView.plan`, `flow`), never the flat step list.
|
|
8
|
+
|
|
9
|
+
- New types `HostedPlanView` (`current`, `choice`, `steps`, `sections`), `PlanChoiceView` / `PlanChoiceOption` (with the optional `nationalEid` provider), `PlanStepView` (node id, `service`, `attempts { used, max }` and today's per-type extras), `PlanSectionView`, `HostedFlowRef`; `NfcStepView.mrz`; `StepSection` gains `screening`.
|
|
10
|
+
- **Breaking:** `HostedSessionView.steps`, `methodChoice` and `otpChoice` are removed, and so are `HostedClient.selectMethod()` / `selectContact()` (`POST /hosted/method`, `/hosted/contact`). Use `HostedClient.choose(nodeId, option)` (`POST /hosted/choice`, returns the view). `OtpChoiceView` is deprecated.
|
|
11
|
+
- The step model follows `plan.current`: the choice screen when it is `plan.choice` (`method` for the identity method and `contact_choice` for the contact, as before, plus a new `choice` step for other kinds; every choice step carries `choice` and a `choose(optionId)` action), else the current step by its service (an unknown service, or an active session without a plan, is `unsupported` / `update_required`; server-run services show `processing`). Step ids are node ids (`n_live.icao` is the ICAO portrait). Attempts come from `attempts { used, max }`. The summary is the `summary_confirm` step. Progress: `StepContext.progress` (`plan.sections` with `done | current | upcoming`).
|
|
12
|
+
- In-lane switches follow the open choice (C4 rule §5 item 6): `StepContext.switchable` (`InLaneSwitch`: the choice's options, the lane taken) and `chooseOption(optionId)` on the step handles while it is open. With exactly one other option the screen's direct switch is set (`canSwitch` phone ⇄ email, `canUseDocument` registry → document, `canUseCamera` eID → camera path), at any time, no longer after a failure only; with two or more, offer « Use another option ».
|
|
13
|
+
- `HostedApiError.details` (`HostedErrorDetails`: `issues[]`, `fields`) carries the flow errors' machine-readable details.
|
|
14
|
+
- The liveness submission bundles the face-match keyframe only when no ICAO portrait follows (the ICAO still is then the probe). `409 choice_locked`, `choice_option_unavailable`, `choice_not_found` and `step_not_on_path` re-read the view.
|
|
15
|
+
- Every submission, `choose()`, identity confirm and consent answer is the hosted view (`submitCheck()` / `uploadAndSubmit()` now return `HostedSessionView`; `recordConsent()` returns `HostedConsentView` = the view + `alreadyRecorded`) and is rendered without a re-read.
|
|
16
|
+
- `verification.methodChoice()` / `selectMethod()` and the `method` event keep working over `plan.choice` (`document` → `document_photo`, `nfc` → `document_chip`, `population_registry` → `national_number`, `national_eid` → `national_eid`).
|
|
17
|
+
|
|
3
18
|
## 0.1.0-rc.8
|
|
4
19
|
|
|
5
20
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -1,15 +1,24 @@
|
|
|
1
1
|
# @sekyro/web
|
|
2
2
|
|
|
3
3
|
Browser SDK for [Sekyro AI](https://sekyro.ai) identity verification: liveness capture
|
|
4
|
-
(v3 engine), the
|
|
5
|
-
|
|
4
|
+
(v3 engine), the step runner that renders any Sekyro flow headless
|
|
5
|
+
(`verification.run()`), the document scanner, the typed hosted-verification client
|
|
6
|
+
and the hosted-flow popup embed. Framework-free; pair it with `@sekyro/react` for
|
|
7
|
+
ready-made `<LivenessCapture>` and `<SekyroVerification>` components.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @sekyro/web@next
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Use of the SDK is governed by the [Sekyro AI SDK License](https://sekyro.ai/legal/sdk-license)
|
|
14
|
+
(summarised in `LICENSE`) and your Sekyro AI customer agreement.
|
|
6
15
|
|
|
7
16
|
```ts
|
|
8
17
|
import { createVerification } from "@sekyro/web";
|
|
9
18
|
|
|
10
19
|
const v = createVerification({ clientToken, locale: "ar" }); // token from your server (@sekyro/node)
|
|
11
20
|
v.on("result", ({ status, reason }) => {
|
|
12
|
-
// approved | rejected | review | retry | unavailable
|
|
21
|
+
// approved | rejected | review | retry | unavailable: for display;
|
|
13
22
|
// the verdict that counts is read server-side (sessions.get + webhooks).
|
|
14
23
|
});
|
|
15
24
|
const cap = v.liveness({ video }); // your <video playsinline muted>
|
|
@@ -19,15 +28,15 @@ void v.startRegistry();
|
|
|
19
28
|
await cap.start();
|
|
20
29
|
```
|
|
21
30
|
|
|
22
|
-
**Read the [
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
31
|
+
**Read the [web SDK guide](https://docs.sekyro.ai/en/web/embedded-sdk)** for the full integration:
|
|
32
|
+
flows and session creation, every step of a flow headless (`verification.run()`),
|
|
33
|
+
results, webhooks, allowed web origins, CSP, model assets (`assetBaseUrl`), reason
|
|
34
|
+
codes, billing. Hosted-flow embed only? See *Hosted popup* below and the
|
|
35
|
+
[quickstart](https://docs.sekyro.ai/en/getting-started/quickstart).
|
|
26
36
|
|
|
27
37
|
Requirements: a secure context (HTTPS or `localhost`), self-hosted detector assets
|
|
28
|
-
under `/models-v3` (or `assetBaseUrl`), and your page origin
|
|
29
|
-
|
|
30
|
-
> Release candidate (`npm i @sekyro/web@next`). Formerly `@ibtikar/identity-web-sdk` (internal).
|
|
38
|
+
under `/models-v3` (or `assetBaseUrl`), and your page origin in the app's allowed web
|
|
39
|
+
origins (dashboard: app page → Integration → Platforms → Web).
|
|
31
40
|
|
|
32
41
|
## Preload & camera probes
|
|
33
42
|
|
|
@@ -50,8 +59,8 @@ await cap.start({ facing: "user" }); // reuses the warm detector automatically
|
|
|
50
59
|
```
|
|
51
60
|
|
|
52
61
|
- `preloadLivenessAssets` is idempotent per `assetBaseUrl` and resolves the settled
|
|
53
|
-
status: `'ready'`, `'failed'` (call it again to retry), or `'idle'
|
|
54
|
-
preloaded (SSR, no camera API, Data
|
|
62
|
+
status: `'ready'`, `'failed'` (call it again to retry), or `'idle'`: nothing was
|
|
63
|
+
preloaded (SSR, no camera API, Data Saver with `respectSaveData`), so start
|
|
55
64
|
normally. `idle: true` defers the load to browser idle time; a capture that
|
|
56
65
|
starts meanwhile begins it at once.
|
|
57
66
|
- The preload warms the blaze (MediaPipe) tier with a generous deadline. Every
|
|
@@ -69,17 +78,47 @@ await cap.start({ facing: "user" }); // reuses the warm detector automatically
|
|
|
69
78
|
- `keepScreenAwake` (capture option, default `true`) holds a Screen Wake Lock while
|
|
70
79
|
the camera is live (`starting` / `gating` / `recording`), released on `captured`,
|
|
71
80
|
`error` and `destroy()`, re-taken on `retry()` and when the page is visible again.
|
|
72
|
-
Best
|
|
81
|
+
Best effort: unsupported or refused requests never affect the capture. In an
|
|
73
82
|
iframe, allow it: `<iframe allow="camera; screen-wake-lock">`. Pass `false` to
|
|
74
83
|
never request it.
|
|
75
84
|
|
|
85
|
+
## Hosted popup
|
|
86
|
+
|
|
87
|
+
`openHosted(hostedUrl, { mode, onEvent })` opens the hosted flow (the session's
|
|
88
|
+
`hostedUrl`) in a popup (`mode: "popup"`) or navigates this tab to it
|
|
89
|
+
(`mode: "redirect"`). A blocked popup returns `{ error: "popup_blocked" }`: fall back
|
|
90
|
+
to `mode: "redirect"` yourself.
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
import { openHosted } from "@sekyro/web";
|
|
94
|
+
|
|
95
|
+
const popup = openHosted(hostedUrl, {
|
|
96
|
+
mode: "popup",
|
|
97
|
+
onEvent: ({ event, sessionId }) => {
|
|
98
|
+
// session.completed | session.failed | session.review_pending | session.expired | session.cancelled
|
|
99
|
+
// A hint only: read the session on your server (sessions.get) before deciding.
|
|
100
|
+
},
|
|
101
|
+
});
|
|
102
|
+
if ("error" in popup) window.location.assign(hostedUrl);
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Events carry `{ source: "sekyro", version: 1, event, sessionId }` and nothing else (no
|
|
106
|
+
scores, no personal data). The hosted page posts them only to the **first** allowed web
|
|
107
|
+
origin of the app (dashboard: app page → Integration → Platforms → Web), so open the
|
|
108
|
+
popup from a page on that origin. The listener accepts a message only from that popup
|
|
109
|
+
window and the hosted page's origin. Events can repeat (a reload after a terminal state posts
|
|
110
|
+
it again; closing or reloading mid-flow posts `session.cancelled`), so confirm the
|
|
111
|
+
outcome server-side. Keep one popup per page: call `close()` on the previous handle
|
|
112
|
+
before opening another.
|
|
113
|
+
|
|
76
114
|
## Entry points
|
|
77
115
|
|
|
78
116
|
| Export | Contents | Public API |
|
|
79
117
|
|---|---|---|
|
|
80
|
-
| `@sekyro/web` | **The partner API
|
|
118
|
+
| `@sekyro/web` | **The partner API**: `createVerification` (consent → early registry → liveness capture → upload → Turnstile attestation → `liveness` + `face_match` → `result`, and `run()`, the step runner for every step of the session's flow), `createLivenessCapture` (standalone capture handle), `createDocumentCapture` (standalone document scanner), `openHosted` (popup/redirect embed) and the contract types. Surface pinned by `etc/sekyro-web.api.md` (api-extractor) | Yes |
|
|
81
119
|
| `@sekyro/web/core` | Framework-free capture: `CaptureSessionV3`, `createDetector`, `FaceGateV3`, frame quality, device profile, `media`/`keyframe`/`messages`/`ClipRecorder` (calibration-pinned v1 port), camera constraints | Yes |
|
|
82
|
-
| `@sekyro/web/core/v3/detect-worker` | Standalone detection-worker entry
|
|
120
|
+
| `@sekyro/web/core/v3/detect-worker` | Standalone detection-worker entry: construct with `new Worker(new URL('@sekyro/web/core/v3/detect-worker', import.meta.url))` so its worker-scope auto-install never rides a main-thread bundle | Yes |
|
|
121
|
+
| `@sekyro/web/core/ocr/worker` (+ `worker.bundle.js`) | The live MRZ reader's Web Worker: pass `new URL('@sekyro/web/core/ocr/worker', import.meta.url)` as `liveMrz.workerUrl`, or copy the self-contained `dist/core/ocr/worker.bundle.js` to your static folder | Yes |
|
|
83
122
|
| `@sekyro/web/client` | Typed client for the hosted session API: `HostedClient`, error codes, check input/view types | Yes |
|
|
84
123
|
| `@sekyro/web/popup` | Partner-facing popup/redirect embed (`open`, `SekyroEvent`) | Yes |
|
|
85
124
|
| `@sekyro/web/internal` | **Not public.** Document scanner (doc catalog, `DocGateV1`, MRZ band, frame analysis, feedback aggregator, `CaptureSessionDoc`) + gate-debug geometry constants + the verification internals (`createVerificationInternal` / `createLivenessCaptureInternal` seams, `runLivenessFlow`, `runSubmission`, result mapping, Turnstile loader), consumed by Sekyro AI's hosted page / `@sekyro/react` only. No semver guarantees; may change in any release | No |
|
|
@@ -87,49 +126,3 @@ await cap.start({ facing: "user" }); // reuses the warm detector automatically
|
|
|
87
126
|
Every entry ships ESM + CJS + `.d.ts` (`tsup`). `./core` deliberately does **not**
|
|
88
127
|
re-export the document scanner (that lives only under `./internal`) nor the worker
|
|
89
128
|
entry.
|
|
90
|
-
|
|
91
|
-
## Calibration pin — do not "improve" `src/core/`
|
|
92
|
-
|
|
93
|
-
`src/core/media.ts`, `keyframe.ts`, and `messages.ts` are **byte-identical ports** of
|
|
94
|
-
v1's `kyc-ibtikar/lib/faceCaptureV2/*`. The only allowed delta is the 3-line port
|
|
95
|
-
header block (two comment lines + one blank separator line) prepended to each file.
|
|
96
|
-
`src/core/clip-recorder.ts` is the de-hooked `useClipRecorder` with identical
|
|
97
|
-
constants and behavior (`CLIP_MS=2500`, `TIMESLICE_MS=1000`, `STOP_GRACE_MS=1500`,
|
|
98
|
-
`VIDEO_BPS=2_500_000`, `MAX_CLIP_BYTES=8MiB`, mime ladder, guarded double construction,
|
|
99
|
-
incremental cap enforcement, stop-grace finalize, single-settle, stop-all-tracks).
|
|
100
|
-
|
|
101
|
-
The FAS-CLIP liveness model was calibrated on clips produced by exactly this v1
|
|
102
|
-
pipeline (spec §6 / risk 1). Any drift silently invalidates the calibration.
|
|
103
|
-
`test/port-parity.test.ts` enforces this in two layers: a sha256 checksum pin against
|
|
104
|
-
the committed `test/port-manifest.json` that runs **everywhere, CI included**, and a
|
|
105
|
-
byte-level comparison against the real v1 sources that runs on every dev machine with
|
|
106
|
-
the `kyc-ibtikar/` checkout alongside (that layer self-skips in CI, where the
|
|
107
|
-
gitignored v1 checkout is absent — and it also verifies the manifest itself matches
|
|
108
|
-
header + v1 bytes, so the manifest cannot drift). Do NOT edit `src/core/` without a
|
|
109
|
-
calibration re-validation; if a re-validated change ever lands, regenerate the
|
|
110
|
-
manifest hashes alongside it.
|
|
111
|
-
|
|
112
|
-
The parity test resolves the v1 checkout as `../../kyc-ibtikar/lib/faceCaptureV2`
|
|
113
|
-
from the package root, so this package must stay **two levels below the repo root**
|
|
114
|
-
(`packages/sekyro-web`).
|
|
115
|
-
|
|
116
|
-
Note: v1's `upload.ts` is intentionally NOT ported — uploading is the typed client's
|
|
117
|
-
job in v2 (`HostedClient.uploadAndSubmit`).
|
|
118
|
-
|
|
119
|
-
## Develop
|
|
120
|
-
|
|
121
|
-
```bash
|
|
122
|
-
npm ci
|
|
123
|
-
npm run build # tsup → dist/ (ESM + CJS + d.ts per entry)
|
|
124
|
-
npm test # vitest (jsdom)
|
|
125
|
-
npm run typecheck # tsc --noEmit
|
|
126
|
-
npm run api:check # api-extractor: fails when the ROOT public surface drifts from etc/sekyro-web.api.md
|
|
127
|
-
npm run api:report # regenerate etc/sekyro-web.api.md after an intentional, reviewed API change
|
|
128
|
-
```
|
|
129
|
-
|
|
130
|
-
The api-extractor report covers the root `.` entry only (the partner contract); the
|
|
131
|
-
subpath entries (`./core`, `./client`, `./popup`) are not reported. `npm run build` must
|
|
132
|
-
precede `api:check` (it reads `dist/index.d.ts`).
|
|
133
|
-
|
|
134
|
-
Standalone package: own lockfile, no workspace wiring. `identity-hosted` consumes it
|
|
135
|
-
via `"@sekyro/web": "file:../packages/sekyro-web"` and needs `dist/` built first.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as a,D as b,E as c,F as d,G as e,H as f,I as g,J as h}from"./chunk-
|
|
1
|
+
import{C as a,D as b,E as c,F as d,G as e,H as f,I as g,J as h}from"./chunk-4Q7EMVP7.js";import"./chunk-SMKCBUJL.js";import"./chunk-MXWLCDFX.js";import"./chunk-G6LKLN4U.js";import"./chunk-TDLIXFDT.js";import"./chunk-POIQGEZM.js";import"./chunk-FHJ7HO3M.js";import"./chunk-FPXL63KZ.js";import"./chunk-LUHNRNTO.js";import"./chunk-DK5YPBDQ.js";export{h as CAPTURE_CANDIDATE_SPACING_MS,g as CAPTURE_EXTRA_CANDIDATES,e as CaptureSessionDoc,b as DOC_CADENCE_HZ,c as DOC_SHUTTER_DEFAULTS,f as passportBandOf,d as resolveDocShutterTuning,a as warmDocDetector};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as jt}from"./chunk-SMKCBUJL.js";import{a as et,b as Zt,c as Jt,e as ht,f as $t}from"./chunk-MXWLCDFX.js";import{d as Wt,h as Xt,k as Yt}from"./chunk-G6LKLN4U.js";import{b as Kt,c as Vt}from"./chunk-TDLIXFDT.js";import{b as Qt,c as Bt}from"./chunk-POIQGEZM.js";import{d as zt}from"./chunk-FHJ7HO3M.js";import{b as ut,c as Ut,d as j,e as Ht}from"./chunk-FPXL63KZ.js";import{b as Nt}from"./chunk-LQ7C44JG.js";var it=Object.freeze({sensing:{key:"sensing",reticle:"searching",minDurationMs:900},too_far:{key:"too_far",reticle:"coaching",minDurationMs:1400},too_close:{key:"too_close",reticle:"coaching",minDurationMs:1400},edge_clipped:{key:"edge_clipped",reticle:"coaching",minDurationMs:1400},wrong_shape:{key:"wrong_shape",reticle:"coaching",minDurationMs:1400},tilted:{key:"tilted",reticle:"coaching",minDurationMs:1400},too_dark:{key:"too_dark",reticle:"coaching",minDurationMs:1400},too_bright:{key:"too_bright",reticle:"coaching",minDurationMs:1400},blurry:{key:"blurry",reticle:"coaching",minDurationMs:1400},focus_far:{key:"focus_far",reticle:"coaching",minDurationMs:1600},glare:{key:"glare",reticle:"coaching",minDurationMs:1400},hold_still:{key:"hold_still",reticle:"locking",minDurationMs:900},processing:{key:"processing",reticle:"processing",minDurationMs:800},side_captured:{key:"side_captured",reticle:"flip",minDurationMs:2600},captured:{key:"captured",reticle:"done",minDurationMs:800}});function qt(e){return e.framing==="no_document"?"sensing":e.framing==="too_far"?"too_far":e.framing==="too_close"?"too_close":e.framing==="edge_clipped"?"edge_clipped":e.framing==="wrong_shape"?"wrong_shape":e.framing==="tilted"?"tilted":e.lighting==="too_dark"?"too_dark":e.lighting==="too_bright"?"too_bright":e.glare==="glare"?"glare":e.blur==="blurry"?"blurry":"hold_still"}var nt=class{constructor(t=2600,n=.35){this.windowMs=t;this.decayPerSecond=n;this.votes=[];this.current=it.sensing;this.currentSinceMs=null}reset(){this.votes=[],this.current=it.sensing,this.currentSinceMs=null}force(t,n){return this.votes=[],this.current=it[t],this.currentSinceMs=n,this.current}tick(t,n){if(this.currentSinceMs===null&&(this.currentSinceMs=n),this.votes.push({key:t,atMs:n}),this.votes=this.votes.filter(r=>n-r.atMs<=this.windowMs),n-this.currentSinceMs<this.current.minDurationMs)return this.current;let i=new Map;for(let r of this.votes){let c=(n-r.atMs)/1e3,a=this.decayPerSecond**c;i.set(r.key,(i.get(r.key)??0)+a)}let o=this.current.key,s=-1;for(let[r,c]of i)c>s&&(s=c,o=r);return o!==this.current.key&&(this.current=it[o],this.currentSinceMs=n),this.current}};var Qe=Object.freeze({MAX_AREA_FRAC:.92,TILT_MAX_SIDE_RATIO:1.3,GLARE_MAX_SPECULAR_FRAC:.025});function ee(e){let{data:t,width:n,height:i}=e,o=n*i;if(o===0)return 0;let s=0;for(let r=0;r<o;r++){let c=r*4;.299*(t[c]??0)+.587*(t[c+1]??0)+.114*(t[c+2]??0)>=252&&s++}return s/o}function Be(e){let t=(a,l)=>Math.hypot(l.x-a.x,l.y-a.y),n=t(e.topLeft,e.topRight),i=t(e.bottomLeft,e.bottomRight),o=t(e.topLeft,e.bottomLeft),s=t(e.topRight,e.bottomRight),r=Math.max(n,i)/Math.max(1e-6,Math.min(n,i)),c=Math.max(o,s)/Math.max(1e-6,Math.min(o,s));return Math.max(r,c)}function ie(e){let t={...Zt,...e.thresholds},n=Qe,{quad:i,frameWidth:o,frameHeight:s,measures:r}=e,c=e.format==="ID-3",a="ok";if(i===null)a="no_document";else if(c){let m=ht(i),h=o>0?m.width/o:0,f=m.height>0?m.width/m.height:0;h<t.ID3_BAND_MIN_WIDTH_FRAC?a="too_far":te(i,o,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":(f<t.ID3_BAND_ASPECT_MIN||f>t.ID3_BAND_ASPECT_MAX)&&(a="wrong_shape")}else{let m=Jt(i,o,s),h=ht(i),f=Math.max(h.width,h.height)/Math.max(1e-6,Math.min(h.width,h.height));m<t.MIN_AREA_FRAC?a="too_far":m>n.MAX_AREA_FRAC?a="too_close":te(i,o,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":Vt(e.format,f)?Be(i)>n.TILT_MAX_SIDE_RATIO&&(a="tilted"):a="wrong_shape"}let l=r.exposure>=t.GUIDE_EXPOSURE?"ok":r.meanLuma<(ut[0]+ut[1])/2?"too_dark":"too_bright",u=r.sharpness>=t.GUIDE_SHARPNESS?"ok":"blurry",d=r.specularFraction>=n.GLARE_MAX_SPECULAR_FRAC?"glare":"ok";return{framing:a,lighting:l,blur:u,glare:d,acceptable:a==="ok"&&l==="ok"&&u==="ok"&&d==="ok"}}function te(e,t,n,i){return[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft].some(s=>s.x<=i||s.y<=i||s.x>=t-i||s.y>=n-i)}var oe=Object.freeze({width:1920,height:1080}),Ue=Object.freeze({width:3840,height:2160}),ne=4096,He=2560,se=640,ot=.15,Y=Object.freeze({side:.2,above:.9,below:.3});function L(e){let t=[e.topLeft.x,e.topRight.x,e.bottomRight.x,e.bottomLeft.x],n=[e.topLeft.y,e.topRight.y,e.bottomRight.y,e.bottomLeft.y],i=Math.min(...t),o=Math.min(...n);return{x:i,y:o,width:Math.max(...t)-i,height:Math.max(...n)-o}}function re(e,t){let n=Math.max(0,Math.floor(e.x)),i=Math.max(0,Math.floor(e.y)),o=Math.min(t.width,Math.ceil(e.x+e.width)),s=Math.min(t.height,Math.ceil(e.y+e.height));return o-n<16||s-i<16?null:{x:n,y:i,width:o-n,height:s-i}}function Ke(e,t,n){if(e===null||t.width<=0||t.height<=0)return null;let i=L(e);if(i.width<=0||i.height<=0)return null;let o=n==="ID-3"?{x:i.x-i.width*Y.side,y:i.y-i.width*Y.above,width:i.width*(1+2*Y.side),height:i.height+i.width*(Y.above+Y.below)}:{x:i.x-i.width*ot,y:i.y-i.height*ot,width:i.width*(1+2*ot),height:i.height*(1+2*ot)};return re(o,t)}function dt(e,t,n){let i=Math.max(e,t);return i>0?Math.min(1,n/i):1}function mt(e,t,n,i,o=He){let s=t.width>0?n.width/t.width:1,r=t.height>0?n.height/t.height:1,c=e===null?null:{topLeft:{x:e.topLeft.x*s,y:e.topLeft.y*r},topRight:{x:e.topRight.x*s,y:e.topRight.y*r},bottomRight:{x:e.bottomRight.x*s,y:e.bottomRight.y*r},bottomLeft:{x:e.bottomLeft.x*s,y:e.bottomLeft.y*r}},a=Ke(c,n,i)??{x:0,y:0,width:n.width,height:n.height},l=dt(a.width,a.height,o),u=Math.max(1,Math.round(a.width*l)),d=Math.max(1,Math.round(a.height*l)),m=null;if(c!==null){let h=L(c);m=re({x:(h.x-a.x)*l,y:(h.y-a.y)*l,width:h.width*l,height:h.height*l},{width:u,height:d})}return{crop:a,width:u,height:d,docRegion:m}}function ae(e,t,n,i=Ue){if(n==="LOW")return null;let o=e?.width?.max,s=e?.height?.max;if(typeof o!="number"||typeof s!="number"||o<=0||s<=0)return null;let r=Math.max(o,s),c=Math.min(o,s),a=Math.min(r,Math.max(i.width,i.height)),l=Math.min(c,Math.min(i.width,i.height));return a<=Math.max(t.width,t.height)?null:{width:{ideal:a},height:{ideal:l}}}function ce(e){let t={},n=e?.imageWidth,i=e?.imageHeight;if(typeof n?.max=="number"&&n.max>0){let o=typeof i?.max=="number"&&i.max>0?n.max/i.max:1.3333333333333333,s=o>=1?ne:ne*o,r=Math.min(n.max,Math.floor(s)),c=typeof n.step=="number"&&n.step>0?n.step:1,a=typeof n.min=="number"?n.min:0;r=Math.max(a,a+Math.floor((r-a)/c)*c),t.imageWidth=r}return e?.fillLightMode?.includes("off")===!0&&(t.fillLightMode="off"),t}function le(e,t){if(e.width<=0||e.height<=0||t.width<=0||t.height<=0)return!1;let n=e.width>e.height,i=t.width>t.height;return n!==i&&e.width!==e.height&&t.width!==t.height?!1:Math.max(e.width,e.height)>=1.2*Math.max(t.width,t.height)}function ue(e,t,n,i){if(n===null)return!1;let o=L(e),s=L(n);if(t.width<=0||i.width<=0)return!1;let r=o.width/t.width,c=s.width/i.width;return c>0&&r>=.6*c&&r<=1.25*c}var he=3500,Ve=.92;function me(){let e=globalThis.ImageCapture;return typeof e=="function"?e:null}function We(e){return/AppleWebKit\//.test(e)&&!/(Chrome|Chromium|Edg|OPR)\//.test(e)}function fe(e,t=typeof navigator>"u"?"":navigator.userAgent){return me()!==null&&!We(t)&&e!=null&&e.kind==="video"&&e.readyState==="live"}function de(e,t){return new Promise((n,i)=>{let o=setTimeout(()=>i(new Error("takePhoto timed out")),t);e.then(s=>{clearTimeout(o),n(s)},s=>{clearTimeout(o),i(s)})})}function ft(e,t){let n=document.createElement("canvas");return n.width=e,n.height=t,n}function Xe(e,t){return new Promise((n,i)=>{e.toBlob(o=>o?n(o):i(new Error("toBlob failed")),"image/jpeg",t)})}async function pe(e,t,n,i,o){let s=ft(n,i),r=ft(1,1);try{let c=s.getContext("2d");if(c===null)throw new Error("2d context unavailable");c.imageSmoothingQuality="high",c.drawImage(e,t.x,t.y,t.width,t.height,0,0,n,i);let a=await Xe(s,Ve),l=o===null?null:Wt({topLeft:{x:o.x,y:o.y},topRight:{x:o.x+o.width,y:o.y},bottomRight:{x:o.x+o.width,y:o.y+o.height},bottomLeft:{x:o.x,y:o.y+o.height}},{width:n,height:i},{width:n,height:i}),u=Xt(s,l),d=dt(n,i,se);return r.width=Math.max(1,Math.round(n*d)),r.height=Math.max(1,Math.round(i*d)),r.getContext("2d")?.drawImage(s,0,0,r.width,r.height),{blob:a,previewDataUrl:r.toDataURL("image/jpeg",.85),sharpness:u}}finally{s.width=0,s.height=0,r.width=0,r.height=0}}function je(e,t){let n=Math.min(1,t/e.width),i=ft(Math.max(1,Math.round(e.width*n)),Math.max(1,Math.round(e.height*n)));try{let o=i.getContext("2d",{willReadFrequently:!0});return o===null?null:(o.imageSmoothingQuality="high",o.drawImage(e,0,0,i.width,i.height),o.getImageData(0,0,i.width,i.height))}finally{i.width=0,i.height=0}}async function ge(e,t,n,i){let o={width:Math.max(1,e.videoWidth),height:Math.max(1,e.videoHeight)},s=mt(t,n,o,i);return{...await pe(e,s.crop,s.width,s.height,s.docRegion),docRegion:s.docRegion,source:"video",width:s.width,height:s.height}}async function be(e,t,n,i,o){let s=me();if(s===null)return null;let r=null;try{let c=new s(o.track),a=await de(c.getPhotoCapabilities?.()??Promise.resolve({}),he).catch(()=>({})),l=await de(c.takePhoto(ce(a)),he);r=await createImageBitmap(l);let u={width:e.videoWidth,height:e.videoHeight};if(!le(r,u))return null;let d=je(r,o.detectWidth),m=null;d!==null&&t!==null&&(m=await o.detect(d).catch(()=>null));let h=d??{width:r.width,height:r.height};m!==null&&!ue(m,h,t,n)&&(m=null);let f=mt(m,h,r,i);return{...await pe(r,f.crop,f.width,f.height,f.docRegion),docRegion:f.docRegion,source:"photo",width:f.width,height:f.height}}catch{return null}finally{r?.close()}}var st=Object.freeze({width:3840,height:2160,lensSelection:!0,continuousFocus:!0,refocusBeforePhotoMs:350,zoomMax:2,zoomNoFocusInfo:1.5,zoomMinSourcePx:2160,fillDistanceM:Object.freeze({id1:.11,id3:.15}),focusMarginFrac:.2,stillSharpnessMin:.16,stillRefusalsMax:2,focusFarFillFrac:.45,noDocFarHintMs:1500,zoomFallbackMs:8e3}),S=(e,t,n)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:void 0;function ki(e){let t=st,n=e!==null&&typeof e=="object"?e:{},i=n.fillDistanceM!==null&&typeof n.fillDistanceM=="object"?n.fillDistanceM:{},o=(s,r)=>typeof s=="boolean"?s:r;return{width:S(n.width,640,7680)??t.width,height:S(n.height,480,4320)??t.height,lensSelection:o(n.lensSelection,t.lensSelection),continuousFocus:o(n.continuousFocus,t.continuousFocus),refocusBeforePhotoMs:S(n.refocusBeforePhotoMs,0,2e3)??t.refocusBeforePhotoMs,zoomMax:S(n.zoomMax,1,5)??t.zoomMax,zoomNoFocusInfo:S(n.zoomNoFocusInfo,1,5)??t.zoomNoFocusInfo,zoomMinSourcePx:S(n.zoomMinSourcePx,0,8e3)??t.zoomMinSourcePx,fillDistanceM:{id1:S(i.id1,.03,1)??t.fillDistanceM.id1,id3:S(i.id3,.03,1)??t.fillDistanceM.id3},focusMarginFrac:S(n.focusMarginFrac,0,2)??t.focusMarginFrac,stillSharpnessMin:S(n.stillSharpnessMin,0,10)??t.stillSharpnessMin,stillRefusalsMax:S(n.stillRefusalsMax,0,10)??t.stillRefusalsMax,focusFarFillFrac:S(n.focusFarFillFrac,0,1)??t.focusFarFillFrac,noDocFarHintMs:S(n.noDocFarHintMs,0,6e4)??t.noDocFarHintMs,zoomFallbackMs:S(n.zoomFallbackMs,0,12e4)??t.zoomFallbackMs}}function Ye(e){let t=e.toLowerCase();return t===""?"unknown":/front|facing front|user|selfie|face ?time/.test(t)?"front":/ultra|0\.5x|wide angle/.test(t)?"ultra":/tele|zoom|periscope|[2-9]x/.test(t)?"tele":/depth|tof|infrared|\bir\b|truedepth|lidar|macro|monochrome|mono\b/.test(t)?"depth":/dual|triple/.test(t)?"virtual":/back|rear|environment|facing back|arrière|خلفية/.test(t)?"main":"unknown"}function Ze(e){let t=/camera2?\s*(\d+)/i.exec(e);return t?Number(t[1]):Number.POSITIVE_INFINITY}function Je(e){let t={main:0,virtual:1,ultra:9,tele:9,depth:9,front:9,unknown:9};return e.filter(n=>(n.kind===void 0||n.kind==="videoinput")&&n.deviceId!=="").map((n,i)=>({id:n.deviceId,kind:Ye(n.label),index:Ze(n.label),i})).filter(n=>t[n.kind]<9).sort((n,i)=>t[n.kind]-t[i.kind]||n.index-i.index||n.i-i.i).map(n=>n.id)}var pt="sekyro.doc.camera";function $e(){try{let e=globalThis.localStorage?.getItem(pt);return typeof e=="string"&&e!==""?e:null}catch{return null}}function ye(e){try{e===null?globalThis.localStorage?.removeItem(pt):globalThis.localStorage?.setItem(pt,e)}catch{}}var rt=(e,t)=>Array.isArray(e?.focusMode)&&e.focusMode.includes(t);function bt(e,t,n){if(!rt(e,"single-shot"))return null;let i=o=>Math.min(1,Math.max(0,Number.isFinite(o)?o:.5));return{focusMode:"single-shot",pointsOfInterest:[{x:i(t),y:i(n)}]}}function xi(e,t,n,i){if(!Number.isFinite(e)||!Number.isFinite(t)||n.width<=0||n.height<=0||i.width<=0||i.height<=0)return null;let o=Math.max(n.width/i.width,n.height/i.height),s=i.width*o,r=i.height*o,c=(e-n.left+(s-n.width)/2)/s,a=(t-n.top+(r-n.height)/2)/r;return{x:Math.min(1,Math.max(0,c)),y:Math.min(1,Math.max(0,a))}}function ke(e,t,n,i=st){let o=e?.zoom?.min,s=e?.zoom?.max;if(typeof s!="number"||s<=1)return 1;let r=n==="ID-3"?i.fillDistanceM.id3:i.fillDistanceM.id1,c=e?.focusDistance?.min,a;if(typeof c=="number"&&c>0&&c<1){if(a=c*(1+i.focusMarginFrac)/r,a<=1.05)return 1}else{if(Math.min(t.width,t.height)<i.zoomMinSourcePx)return 1;a=i.zoomNoFocusInfo}let l=Math.min(a,i.zoomMax,s);typeof o=="number"&&(l=Math.max(l,o));let u=e?.zoom?.step;return typeof u=="number"&&u>0&&(l=Math.round(l/u)*u),l>1.01?Number(l.toFixed(2)):1}function gt(e){try{return e.getVideoTracks?.()[0]}catch{return}}function Me(e){if(e!==null)for(let t of e.getTracks())t.stop()}function qe(e){try{let t=gt(e)?.getCapabilities?.();return!Array.isArray(t?.focusMode)||t.focusMode.includes("continuous")}catch{return!0}}var ti=3;async function xe(e){let t=s=>({audio:!1,video:{...s,width:{ideal:e.base.width},height:{ideal:e.base.height}}}),n=s=>e.getUserMedia(t({deviceId:{exact:s}})),i=()=>e.getUserMedia(t({facingMode:{ideal:"environment"}}));if(e.lensSelection){let s=$e();if(s!==null)try{return{stream:await n(s),lens:"stored"}}catch{ye(null)}}let o=await i();if(!e.lensSelection||e.enumerateDevices===void 0)return{stream:o,lens:"default"};try{let s=Je(await e.enumerateDevices()).slice(0,ti);if(s.length===0)return{stream:o,lens:"default"};let r=null;for(let c of s){let a=o!==null?gt(o)?.getSettings?.().deviceId:void 0;if(o===null||a!==c){Me(o),o=null;try{o=await n(c)}catch{continue}}if(r??(r=c),qe(o))return ye(c),{stream:o,lens:"selected"}}if(o!==null&&r!==null&>(o)?.getSettings?.().deviceId===r)return{stream:o,lens:"selected"};if(Me(o),o=null,r!==null)try{return{stream:await n(r),lens:"selected"}}catch{}return{stream:await i(),lens:"default"}}catch{return{stream:o??await i(),lens:"default"}}}var Z=Object.freeze({brightness:0,glare:0,cardGlare:0,sharpness:0,fill:0,shape:0,content:0,offsetX:0,offsetY:0,edgeConfidence:0,box:null}),I=e=>Math.min(1,Math.max(0,e));function we(e,t,n,i=.06){let o=Math.max(e.width/n,e.height),s=o*n,r=(e.width-s)/2,c=(e.height-o)/2,a=I((t.x-t.width*i-r)/s),l=I((t.y-t.height*i-c)/o),u=I((t.x+t.width*(1+i)-r)/s),d=I((t.y+t.height*(1+i)-c)/o);return{x:a,y:l,width:u-a,height:d-l}}function ve(e,t,n={}){let i=n.edgePeakFrac??0,{width:o,height:s,data:r}=e;if(o<=0||s<=0)return Z;let c=I(t.x),a=I(t.y),l={x:c,y:a,width:Math.max(0,I(t.x+t.width)-c),height:Math.max(0,I(t.y+t.height)-a)};if(l.width<=0||l.height<=0)return Z;let u=l.x*o,d=l.y*s,m=(l.x+l.width)*o,h=(l.y+l.height)*s,f=(m-u)*.15,g=(h-d)*.15,y=(p,b,T)=>Math.min(T,Math.max(b,p)),x=y(Math.floor(u-f),0,o-1),w=y(Math.floor(d-g),0,s-1),E=y(Math.ceil(m+f),x+1,o),v=y(Math.ceil(h+g),w+1,s),D=Math.max(1,Math.ceil(Math.max(E-x,v-w)/320)),M=Math.floor((E-x+D-1)/D),_=Math.floor((v-w+D-1)/D);if(M<3||_<3)return Z;let k=new Int32Array(M*_);for(let p=0;p<_;p++){let b=w+p*D;for(let T=0;T<M;T++){let C=(b*o+x+T*D)*4;k[p*M+T]=(r[C]??0)*77+(r[C+1]??0)*150+(r[C+2]??0)*29>>8}}let F=(p,b)=>(p-b-.5)/D,R=F(u,x),A=F(m,x),B=F(d,w),U=F(h,w),Mt=(m-u)/D,kt=(h-d)/D,xt=y(Math.ceil(R),0,M-1),Ce=y(Math.floor(A),xt,M-1),Dt=y(Math.ceil(B),0,_-1),Fe=y(Math.floor(U),Dt,_-1),wt=0,vt=0,H=0,St=0,_t=0,K=0;for(let p=Dt;p<=Fe;p++)for(let b=xt;b<=Ce;b++){let T=k[p*M+b];if(wt+=T,T>=248&&vt++,H++,b>=1&&b<M-1&&p>=1&&p<_-1){let C=k[p*M+b-1]+k[p*M+b+1]+k[(p-1)*M+b]+k[(p+1)*M+b]-4*T;St+=C,_t+=C*C,K++}}let Ae=H>0?wt/H:0,Rt=H>0?vt/H:0,Tt=K>0?St/K:0,Le=K>0?Math.max(0,_t/K-Tt*Tt):0,V=new Float64Array(M),W=new Float64Array(_);for(let p=0;p<_;p++)for(let b=1;b<M-1;b++)V[b]=V[b]+Math.abs(k[p*M+b+1]-k[p*M+b-1]);for(let p=1;p<_-1;p++)for(let b=0;b<M;b++)W[p]=W[p]+Math.abs(k[(p+1)*M+b]-k[(p-1)*M+b]);let O=at(V,!0,R,i),P=at(V,!1,A,i),G=at(W,!0,B,i),z=at(W,!1,U,i),Ct=(P.position-O.position)/Mt,Ft=(z.position-G.position)/kt,Ie=Ft>0?Ct/Ft:0,Ee=((O.position+P.position)/2-(R+A)/2)/Mt,Oe=((G.position+z.position)/2-(B+U)/2)/kt,At=De(V),Lt=De(W),Pe=At<=0||Lt<=0?0:Math.min(Math.min(O.value,P.value)/At,Math.min(G.value,z.value)/Lt),q=(p,b)=>b+(p+.5)*D,It=Rt,Et=0;{let p=(P.position-O.position)*.06,b=(z.position-G.position)*.06,T=y(Math.ceil(O.position+p),0,M-1),C=y(Math.floor(P.position-p),0,M-1),Ge=y(Math.ceil(G.position+b),0,_-1),Ot=y(Math.floor(z.position-b),0,_-1),Pt=0,tt=0,Gt=0;for(let N=Ge;N<=Ot;N++)for(let Q=T;Q<=C;Q++){tt++;let X=k[N*M+Q];X>=248&&Pt++;let ze=Q+2<=C?k[N*M+Q+2]:X,Ne=N+2<=Ot?k[(N+2)*M+Q]:X;(Math.abs(ze-X)>=24||Math.abs(Ne-X)>=24)&&Gt++}tt>=16&&(It=Pt/tt,Et=Gt/tt)}return{brightness:Ae,glare:Rt,cardGlare:It,sharpness:Le,fill:Ct,shape:Ie,content:Et,offsetX:Ee,offsetY:Oe,edgeConfidence:Pe,box:{left:q(O.position,x),right:q(P.position,x),top:q(G.position,w),bottom:q(z.position,w)}}}function at(e,t,n,i){let o=e.length,s=Math.max(1,Math.floor(o*.45)),r=t?1:Math.max(1,o-1-s),c=t?Math.min(o-2,s):o-2,a=r;for(let h=r;h<=c;h++)e[h]>e[a]&&(a=h);if(i>0&&i<1){let h=e[a]*i,f=a,g=Math.abs(a-n);for(let y=r;y<=c;y++){let x=e[y];if(x<h||x<(e[y-1]??0)||x<(e[y+1]??0))continue;let w=Math.abs(y-n);w<g&&(f=y,g=w)}a=f}let l=a>0?e[a-1]:0,u=e[a],d=a<o-1?e[a+1]:0,m=l+u+d;return{position:m>0?a+(d-l)/m:a,value:u}}function De(e){if(e.length<3)return 0;let t=0;for(let n=1;n<e.length-1;n++)t+=e[n];return t/(e.length-2)}function Se(e){let t=e.box;return t===null||t.right-t.left<4||t.bottom-t.top<4?null:{topLeft:{x:t.left,y:t.top},topRight:{x:t.right,y:t.top},bottomRight:{x:t.right,y:t.bottom},bottomLeft:{x:t.left,y:t.bottom}}}var J=Object.freeze({fillMin:.82,fillMax:1.06,offsetMax:.06,glareMax:.025,sharpnessMin:180,edgeConfidenceMin:1.6,darkBrightness:70,lockMs:450,steadyMs:900,steadyFillMin:.45,steadyFillMax:1.3,steadyFillDelta:.06,steadyOffsetDelta:.04,steadyRefMs:100,edgePeakFrac:.4,shapeTolerance:.2,contentMin:.1});function wi(e){let t=e!==null&&typeof e=="object"?e:{},n={...J};for(let i of Object.keys(J)){let o=t[i];typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1e6&&(n[i]=o)}return n}var ct=class{constructor(t=J){this.t=t;this.goodSince=null;this.steadySince=null;this.last=null}reset(){this.goodSince=null,this.steadySince=null,this.last=null}tick(t,n){let i=this.t,o=i.shapeTolerance<=0||Math.abs(t.shape-1)<=i.shapeTolerance,s=t.edgeConfidence>=i.edgeConfidenceMin&&o&&t.content>=i.contentMin,r=t.fill>=i.fillMin&&t.fill<=i.fillMax,c=Math.abs(t.offsetX)<=i.offsetMax&&Math.abs(t.offsetY)<=i.offsetMax,a=t.cardGlare<=i.glareMax,l=t.sharpness>=i.sharpnessMin,u=this.last;this.last={fill:t.fill,offsetX:t.offsetX,offsetY:t.offsetY,at:n};let d=u!==null&&i.steadyRefMs>0?Math.min(3,Math.max(1,(n-u.at)/i.steadyRefMs)):1,m=s&&a&&l&&t.fill>=i.steadyFillMin&&t.fill<=i.steadyFillMax&&u!==null&&Math.abs(t.fill-u.fill)<=i.steadyFillDelta*d&&Math.abs(t.offsetX-u.offsetX)<=i.steadyOffsetDelta*d&&Math.abs(t.offsetY-u.offsetY)<=i.steadyOffsetDelta*d,h=s&&r&&c&&a&&l,f;if(s?a?t.fill<i.fillMin?f="too_small":t.fill>i.fillMax?f="too_big":l?c?f="locking":f="off_center":f="blurry":f="glare":f="no_card",h){if(m&&(this.steadySince??(this.steadySince=n)),this.goodSince??(this.goodSince=n),n-this.goodSince>=i.lockMs)return{detected:s,ready:!0,via:"good",blocker:"locking"};let g=this.steadySince!==null&&n-this.steadySince>=i.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:"locking"}}if(this.goodSince=null,m){this.steadySince??(this.steadySince=n);let g=n-this.steadySince>=i.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:g?"locking":"steadying"}}return this.steadySince=null,{detected:s,ready:!1,via:null,blocker:f}}};var $=null;async function ei(e){return $===null&&($=(await import("./detector-scanic-YCDNLCGV.js")).detectQuad),$(e)}async function ii(e){let t=jt(e);return t===null?null:{topLeft:{x:t.x,y:t.y},topRight:{x:t.x+t.width,y:t.y},bottomRight:{x:t.x+t.width,y:t.y+t.height},bottomLeft:{x:t.x,y:t.y+t.height}}}function Ni(){$===null&&import("./detector-scanic-YCDNLCGV.js").then(e=>{$=e.detectQuad}).catch(()=>{})}var ni=Object.freeze({LOW:3,MID:5,HIGH:6}),yt=Object.freeze({manualShutterMs:6e3,detectedNoLockMs:1950});function Qi(e){let t=e!==null&&typeof e=="object"?e:{},n=(i,o,s)=>typeof i=="number"&&Number.isFinite(i)&&i>=o&&i<=s?i:void 0;return{manualShutterMs:n(t.manualShutterMs,1e3,6e4)??yt.manualShutterMs,detectedNoLockMs:n(t.steadyMs,300,3e4)!==void 0?t.steadyMs+(n(t.lockMs,0,1e4)??450):yt.detectedNoLockMs}}var _e=class e{constructor(t){this.torchOn=!1;this.stillRefusals=0;this.zoom=1;this.positioningSince=null;this.detectedSince=null;this.lastSeenAt=null;this.lastGuideQuad=null;this.lastOcrReady=null;this.shutterOffered=!1;this.stats=e.freshStats();this.handlers=new Map;this.stream=null;this.timer=null;this.state="idle";this.lastGuidance=null;this.attempt=0;this.capturing=!1;this.feedback=new nt;this.lastFeedbackKey=null;this.lastQuad=null;this.lastDetect=null;this.opts=t,this.gate=new $t(t.format??"ID-1",t.thresholds);let n=t.deviceClass??Bt(Qt());this.deviceClass=n,this.camera=t.camera??st,this.shutterTuning=t.shutter??yt,this.guideTuning=t.guideLock??J,this.guideLock=new ct(this.guideTuning),this.cadenceMs=1e3/ni[n]}on(t,n){let i=this.handlers.get(t);return i||(i=new Set,this.handlers.set(t,i)),i.add(n),()=>i?.delete(n)}emit(t,n){for(let i of[...this.handlers.get(t)??[]])i(n)}async start(){let t=++this.attempt;this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.setState("preflight");try{let n=this.opts.getUserMedia??(s=>navigator.mediaDevices.getUserMedia(s));this.setState("acquiring");let i=this.opts.enumerateDevices??(this.opts.getUserMedia===void 0&&typeof navigator<"u"&&navigator.mediaDevices?.enumerateDevices?()=>navigator.mediaDevices.enumerateDevices():void 0),o=await xe({getUserMedia:n,...i!==void 0?{enumerateDevices:i}:{},lensSelection:this.camera.lensSelection,base:oe});if(this.stream=o.stream,Nt(this.stream),t!==this.attempt){for(let s of this.stream.getTracks())s.stop();return}if(this.opts.upgradeResolution!==!1&&await this.upgradeResolution(),t!==this.attempt||(await this.applyFocusAndZoom(),t!==this.attempt))return;this.opts.video.srcObject=this.stream,await this.opts.video.play().catch(()=>{}),this.setState("positioning"),this.scheduleTick(t)}catch(n){let i=zt(n);this.setState("error"),this.emit("error",{kind:i,retryable:!0})}}rearm(t){t!==void 0&&(this.opts.side=t),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.stillRefusals=0,this.state==="captured"&&(this.setState("positioning"),this.scheduleTick(this.attempt))}async captureNow(){if(this.state!=="positioning"||this.capturing)return;let t=this.opts.video,n=this.lastDetect?.width??Math.max(1,t.videoWidth),i=this.lastDetect?.height??Math.max(1,t.videoHeight),o=this.lastQuad??this.lastGuideQuad??{topLeft:{x:0,y:0},topRight:{x:n,y:0},bottomRight:{x:n,y:i},bottomLeft:{x:0,y:i}},s=(this.opts.now??(()=>performance.now()))(),r=this.feedback.force("processing",s);this.lastFeedbackKey=r.key,this.emit("feedback",r),await this.fire(this.attempt,this.lastOcrReady!==null?this.lastOcrReady.quad:o,{width:n,height:i,tickSharpness:this.lastDetect?.tickSharpness??0},this.lastOcrReady?.via??"manual")}captureReport(){let t=this.stats;return{...this.opts.side!==void 0?{side:this.opts.side}:{},format:this.opts.format??"ID-1",deviceClass:this.deviceClass,video:{width:this.opts.video.videoWidth||0,height:this.opts.video.videoHeight||0},zoom:this.zoom,...t.zoomFallbackAtMs!==void 0?{zoomFallbackAtMs:t.zoomFallbackAtMs}:{},...t.msToCapture!==void 0?{msToCapture:t.msToCapture}:{},...t.via!==void 0?{via:t.via}:{},...t.shutterAtMs!==void 0?{shutterAtMs:t.shutterAtMs}:{},...t.shutterReason!==void 0?{shutterReason:t.shutterReason}:{},ticks:t.ticks,quadFraming:{...t.quadFraming},qualityBlockers:{...t.qualityBlockers},guideBlockers:{...t.guideBlockers},stillRefusals:t.stillRefusals,...this.ocrReport()}}ocrReport(){let t=this.opts.ocr;if(t===void 0)return{};let n=(this.opts.format??"ID-1")==="ID-3"||this.opts.side==="single"?"single":this.opts.side==="verso"?"verso":"recto",i=t.report(n,this.stats.via,(this.opts.now??(()=>performance.now()))());return i===null?{}:{ocr:i}}static freshStats(){return{ticks:0,quadFraming:{},qualityBlockers:{},guideBlockers:{},stillRefusals:0}}setGuide(t){t===void 0?delete this.opts.guide:this.opts.guide=t,this.guideLock.reset()}guideRegion(t){let n=t.width/Math.max(1,t.height),i=this.opts.guide;if(i!==void 0&&i.viewAspect>0){let c={width:i.viewAspect,height:1},a={x:i.rect.x*i.viewAspect,y:i.rect.y,width:i.rect.width*i.viewAspect,height:i.rect.height};return we(c,a,n,0)}let o=Kt(this.opts.format??"ID-1").center,s=.86,r=s*n/o;return r>.84&&(r=.84,s=r*o/n),{x:(1-s)/2,y:(1-r)/2,width:s,height:r}}resetSide(){this.positioningSince=null,this.detectedSince=null,this.lastSeenAt=null,this.guideLock.reset(),this.lastGuideQuad=null,this.lastOcrReady=null,this.opts.ocr?.reset(),this.stats=e.freshStats(),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}withdrawShutter(){this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}zoomFallback(t){let n=this.videoTrack();if(n===null||this.zoom<=1)return;let i=this.focusCaps(),o=typeof i?.zoom?.min=="number"?Math.max(i.zoom.min,1):1;this.zoom=o,this.stats.zoomFallbackAtMs=Math.round(t-(this.positioningSince??t)),this.guideLock.reset(),this.gate.reset(),n.applyConstraints({advanced:[{zoom:o}]}).catch(()=>{})}offerShutter(t,n){this.shutterOffered||(this.shutterOffered=!0,this.stats.shutterAtMs=Math.round(n-(this.positioningSince??n)),this.stats.shutterReason=t,this.emit("shutter",{available:!0,reason:t}))}torchAvailable(){try{return this.stream?.getVideoTracks?.()[0]?.getCapabilities?.()?.torch===!0}catch{return!1}}async setTorch(t){this.torchOn=t;try{await this.stream?.getVideoTracks?.()[0]?.applyConstraints({advanced:[{torch:t}]})}catch{}}destroy(){if(this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject=null}async upgradeResolution(){try{let t=this.stream?.getVideoTracks?.()[0];if(t===void 0)return;let n=t.getSettings?.()??{},i=ae(t.getCapabilities?.(),{width:n.width??0,height:n.height??0},this.deviceClass,{width:this.camera.width,height:this.camera.height});i!==null&&await t.applyConstraints(i)}catch{}}focusCaps(){try{return this.videoTrack()?.getCapabilities?.()??null}catch{return null}}async applyFocusAndZoom(){let t=this.videoTrack();if(t===null)return;let n=this.focusCaps();this.camera.continuousFocus&&rt(n,"continuous")&&await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{});let i={width:0,height:0};try{let s=t.getSettings?.()??{};i={width:s.width??0,height:s.height??0}}catch{}let o=ke(n,i,this.opts.format??"ID-1",this.camera);if(o>1)try{await t.applyConstraints({advanced:[{zoom:o}]}),this.zoom=o}catch{this.zoom=1}}async focusAt(t,n){let i=this.videoTrack(),o=bt(this.focusCaps(),t,n);if(!(i===null||o===null))try{await i.applyConstraints({advanced:[o]}),(this.opts.setTimer??setTimeout)(()=>{this.restoreContinuous()},1500)}catch{}}async restoreContinuous(){let t=this.videoTrack();t===null||!this.camera.continuousFocus||!rt(this.focusCaps(),"continuous")||await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})}async refocusOn(t,n){let i=this.camera.refocusBeforePhotoMs,o=this.videoTrack();if(i<=0||o===null||n.width<=0||n.height<=0)return;let s=L(t),r=bt(this.focusCaps(),(s.x+s.width/2)/n.width,(s.y+s.height/2)/n.height);if(r!==null)try{await o.applyConstraints({advanced:[r]});let c=this.opts.setTimer??setTimeout;await new Promise(a=>{c(()=>a(),i)})}catch{}}videoTrack(){try{return this.stream?.getVideoTracks?.()[0]??null}catch{return null}}async takeStill(t,n,i){if(this.opts.captureStill!==void 0)return this.opts.captureStill(this.opts.video,t,n);let o=this.opts.format??"ID-1",s=this.videoTrack();if(i&&this.opts.photoCapture!==!1&&this.deviceClass!=="LOW"&&!this.torchOn&&s!==null&&fe(s)){await this.refocusOn(t,n);let r=await be(this.opts.video,t,n,o,{track:s,detect:this.detector(),detectWidth:et});if(this.restoreContinuous(),r!==null)return r}return ge(this.opts.video,t,n,o)}detector(){return this.opts.detect??((this.opts.format??"ID-1")==="ID-3"?ii:ei)}setState(t){this.state=t,this.emit("statechange",{state:t})}scheduleTick(t){let n=this.opts.setTimer??setTimeout;this.timer=n(()=>{this.tick(t)},this.cadenceMs)}async tick(t){if(t!==this.attempt||this.state!=="positioning"||this.capturing)return;let n=this.opts.now??(()=>performance.now()),i=this.opts.grabDetectFrame??Te,o=this.detector(),s=i(this.opts.video,et);if(s===null){this.scheduleTick(t);return}let r=null;try{r=await o(s)}catch{r=null}if(t!==this.attempt)return;let c=r!==null?lt(s,r):s,a=n(),l={sharpness:j(c),exposure:Ht(c),meanLuma:Ut(c),specularFraction:ee(c)},u=ie({format:this.opts.format??"ID-1",quad:r,frameWidth:s.width,frameHeight:s.height,measures:l,...this.opts.thresholds!==void 0?{thresholds:this.opts.thresholds}:{}}),d=this.gate.tick({timestampMs:a,quad:r,quality:l,frameWidth:s.width,frameHeight:s.height}),h=(this.opts.format??"ID-1")!=="ID-3"?ve(s,this.guideRegion(s),{edgePeakFrac:this.guideTuning.edgePeakFrac}):Z,f=this.guideLock.tick(h,a);this.lastGuideQuad=f.detected?Se(h):null;let g=this.capturing?null:this.ocrTick(s,r,h,f.detected,u,a);this.positioningSince??(this.positioningSince=a);let y=this.stats;if(y.ticks+=1,y.quadFraming[u.framing]=(y.quadFraming[u.framing]??0)+1,u.framing==="ok"&&!d.ready){let R=u.lighting!=="ok"?u.lighting:u.glare!=="ok"?"glare":u.blur!=="ok"?"blurry":"steadying";y.qualityBlockers[R]=(y.qualityBlockers[R]??0)+1}y.guideBlockers[f.blocker]=(y.guideBlockers[f.blocker]??0)+1,r!==null||f.detected?(this.detectedSince??(this.detectedSince=a),this.lastSeenAt=a):this.detectedSince=null,this.lastSeenAt!==null&&a-this.lastSeenAt<=ui?a-this.positioningSince>=this.shutterTuning.manualShutterMs?this.offerShutter("timeout",a):g?.suspendQuality!==!0&&this.detectedSince!==null&&a-this.detectedSince>=this.shutterTuning.detectedNoLockMs&&this.offerShutter("detected_no_lock",a):this.withdrawShutter();let E=a-(this.lastSeenAt??this.positioningSince);this.zoom>1&&this.camera.zoomFallbackMs>0&&E>=this.camera.zoomFallbackMs&&this.zoomFallback(a),this.emit("checks",{engine:"docv1",p:d.p,plausible:d.plausible,stableTicks:d.stableTicks,quad:d.quad,frameWidth:s.width,frameHeight:s.height,analysis:u,ready:g?.suspendQuality!==!0&&(d.ready&&r!==null||f.ready&&this.lastGuideQuad!==null)||this.lastOcrReady!==null,guide:{detected:f.detected,blocker:f.blocker,fill:h.fill,shape:h.shape,content:h.content,offsetX:h.offsetX,offsetY:h.offsetY},...g!==null&&g.mode!=="off"?{ocr:{mode:g.mode,...g.mrz?{mrz:g.mrz}:{},...g.lock?{lock:g.lock}:{}}}:g?.mrz?{ocr:{mode:g.mode,mrz:g.mrz}}:{}}),this.lastQuad=d.plausible?r:null,this.lastDetect={width:s.width,height:s.height,tickSharpness:l.sharpness};let v=qt(u);u.framing!=="ok"&&f.detected&&(v=li(f.blocker,h.brightness<this.guideTuning.darkBrightness)),v==="blurry"&&r!==null&&si(r,s,this.opts.format??"ID-1")>=this.camera.focusFarFillFrac&&(v="focus_far"),v==="sensing"&&this.zoom>1&&this.camera.noDocFarHintMs>0&&E>=this.camera.noDocFarHintMs&&(v="focus_far");let D=this.feedback.tick(v,a);if(D.key!==this.lastFeedbackKey&&(this.lastFeedbackKey=D.key,this.emit("feedback",D)),d.guidanceKey!==this.lastGuidance&&(this.lastGuidance=d.guidanceKey,this.emit("guidance",{key:d.guidanceKey})),this.capturing)return;let M=g?.suspendQuality!==!0,_=M&&d.ready&&r!==null,k=M&&f.ready&&this.lastGuideQuad!==null,F=this.lastOcrReady;if(F!==null&&this.opts.autoCapture!==!1){let R=this.feedback.force("processing",a);this.lastFeedbackKey=R.key,this.emit("feedback",R);let A=j(lt(s,F.quad));await this.fire(t,F.quad,{width:s.width,height:s.height,tickSharpness:A},F.via);return}if((_||k)&&this.opts.autoCapture!==!1){let R=this.feedback.force("processing",a);this.lastFeedbackKey=R.key,this.emit("feedback",R);let A=k?this.lastGuideQuad:r,B=k?f.via==="steady"?"guide_steady":"guide_good":"quad",U=k?j(lt(s,A)):l.sharpness;await this.fire(t,A,{width:s.width,height:s.height,tickSharpness:U},B);return}this.scheduleTick(t)}async fire(t,n,i,o){this.capturing=!0;let s=this.opts.grabDetectFrame??Te,r=this.opts.setTimer??setTimeout,c={width:i.width,height:i.height};try{let a={still:await this.takeStill(n,c,!0),sharpness:i.tickSharpness};if(t!==this.attempt)return;let l=a.still.source==="photo"?0:ri;for(let m=0;m<l;m++){if(await new Promise(g=>{r(()=>g(),ai)}),t!==this.attempt)return;let h=s(this.opts.video,et);if(h===null)continue;let f=j(lt(h,n));if(f>a.sharpness*ci){let g=await this.takeStill(n,c,!1);if(t!==this.attempt)return;a={still:g,sharpness:f}}}if(t!==this.attempt)return;let u=a.still.sharpness;if(this.opts.autoCapture!==!1&&o!=="manual"&&typeof u=="number"&&u>=0&&u<this.camera.stillSharpnessMin&&this.stillRefusals<this.camera.stillRefusalsMax){this.stillRefusals+=1,this.stats.stillRefusals+=1,this.guideLock.reset(),this.lastOcrReady=null,(o==="text_lock"||o==="live_mrz")&&this.opts.ocr?.rearmFace();let m=(this.opts.now??(()=>performance.now()))(),h=this.feedback.force("focus_far",m);this.lastFeedbackKey=h.key,this.emit("feedback",h),this.capturing=!1,this.gate.reset(),this.scheduleTick(t);return}this.stillRefusals=0;let d=(this.opts.now??(()=>performance.now()))();this.stats.via=o,this.stats.msToCapture=Math.round(d-(this.positioningSince??d)),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1})),this.setState("captured"),this.emit("artifacts",{keyframe:a.still.blob,previewDataUrl:a.still.previewDataUrl,...this.opts.side!==void 0?{side:this.opts.side}:{},...a.still.docRegion!==void 0?{docRegion:a.still.docRegion}:{},...(()=>{let m=o==="live_mrz"?this.opts.ocr?.liveCapture():null;return m?{liveMrz:m}:{}})()})}catch{if(t!==this.attempt)return;this.capturing=!1,this.gate.reset(),this.guideLock.reset(),this.lastOcrReady=null,(o==="text_lock"||o==="live_mrz")&&this.opts.ocr?.rearmFace(),this.scheduleTick(t)}}ocrTick(t,n,i,o,s,r){let c=this.opts.ocr,a=this.opts.video;if(c===void 0||!c.hasEngine)return this.lastOcrReady=null,null;let l=a.videoWidth,u=a.videoHeight;if(l<=0||u<=0||t.width<=0||t.height<=0)return null;let m=(this.opts.format??"ID-1")==="ID-3",h=this.guideRegion(t),f={x:h.x*l,y:h.y*u,w:h.width*l,h:h.height*u},g=l/t.width,y=u/t.height,x;m&&n!==null?x=oi(L(n),g,y,l,u):x=Yt(f,c.bandTop,u);let w=m?s.glare==="ok":i.cardGlare<=this.guideTuning.glareMax,E=m?s.blur==="ok":i.sharpness>=this.guideTuning.sharpnessMin,v=c.tick({atMs:r,video:a,mrzFace:m||this.opts.side==="verso"||this.opts.side==="single",present:m||n!==null||o,card:f,band:x,portrait:u>l,glareOk:w,sharpOk:E});if(v.ready&&v.via!==void 0){let D=m?n??Re(h,t):this.lastGuideQuad??Re(h,t);this.lastOcrReady={quad:D,via:v.via}}else this.lastOcrReady=null;return v}};function oi(e,t,n,i,o){let s=Math.min(i,e.width*1.06*t),r=Math.min(o,Math.max(e.height*1.6*n,s/5)),c=(e.y+e.height/2)*n,a=Math.max(0,Math.min(i-s,(e.x-e.width*.03)*t)),l=Math.max(0,Math.min(o-r,c-r/2));return{x:a,y:l,w:s,h:r}}function Re(e,t){let n=e.x*t.width,i=e.y*t.height,o=(e.x+e.width)*t.width,s=(e.y+e.height)*t.height;return{topLeft:{x:n,y:i},topRight:{x:o,y:i},bottomRight:{x:o,y:s},bottomLeft:{x:n,y:s}}}function si(e,t,n){let i=L(e);return t.width<=0||t.height<=0?0:n==="ID-3"?i.width/t.width:i.width*i.height/(t.width*t.height)}var ri=2,ai=260,ci=1.08;function Te(e,t){let n=e.videoWidth,i=e.videoHeight;if(n===0||i===0)return null;let o=Math.min(1,t/n),s=Math.round(n*o),r=Math.round(i*o),c=document.createElement("canvas");c.width=s,c.height=r;let a=c.getContext("2d",{willReadFrequently:!0});return a===null?null:(n/Math.max(1,s)>4&&(a.imageSmoothingQuality="high"),a.drawImage(e,0,0,s,r),a.getImageData(0,0,s,r))}function lt(e,t){let n=[t.topLeft.x,t.topRight.x,t.bottomRight.x,t.bottomLeft.x],i=[t.topLeft.y,t.topRight.y,t.bottomRight.y,t.bottomLeft.y],o=Math.max(0,Math.floor(Math.min(...n))),s=Math.max(0,Math.floor(Math.min(...i))),r=Math.min(e.width,Math.ceil(Math.max(...n))),c=Math.min(e.height,Math.ceil(Math.max(...i))),a=Math.max(1,r-o),l=Math.max(1,c-s),u=new Uint8ClampedArray(a*l*4);for(let d=0;d<l;d++){let m=((s+d)*e.width+o)*4;u.set(e.data.subarray(m,m+a*4),d*a*4)}return{data:u,width:a,height:l,colorSpace:e.colorSpace}}function li(e,t){return e==="glare"?"glare":e==="too_small"?"too_far":e==="too_big"?"too_close":t?"too_dark":e==="blurry"?"blurry":e==="off_center"?"edge_clipped":e==="no_card"?"sensing":"hold_still"}var ui=1200;export{it as a,qt as b,nt as c,Qe as d,ee as e,Be as f,ie as g,st as h,ki as i,Ye as j,Je as k,pt as l,$e as m,ye as n,rt as o,bt as p,xi as q,ke as r,qe as s,ti as t,xe as u,Z as v,we as w,ve as x,Se as y,J as z,wi as A,ct as B,Ni as C,ni as D,yt as E,Qi as F,_e as G,oi as H,ri as I,ai as J};
|
|
1
|
+
import{b as jt}from"./chunk-SMKCBUJL.js";import{a as et,b as Zt,c as Jt,e as ht,f as $t}from"./chunk-MXWLCDFX.js";import{d as Wt,h as Xt,k as Yt}from"./chunk-G6LKLN4U.js";import{b as Kt,c as Vt}from"./chunk-TDLIXFDT.js";import{b as Qt,c as Bt}from"./chunk-POIQGEZM.js";import{d as zt}from"./chunk-FHJ7HO3M.js";import{b as ut,c as Ut,d as j,e as Ht}from"./chunk-FPXL63KZ.js";import{b as Nt}from"./chunk-LUHNRNTO.js";var it=Object.freeze({sensing:{key:"sensing",reticle:"searching",minDurationMs:900},too_far:{key:"too_far",reticle:"coaching",minDurationMs:1400},too_close:{key:"too_close",reticle:"coaching",minDurationMs:1400},edge_clipped:{key:"edge_clipped",reticle:"coaching",minDurationMs:1400},wrong_shape:{key:"wrong_shape",reticle:"coaching",minDurationMs:1400},tilted:{key:"tilted",reticle:"coaching",minDurationMs:1400},too_dark:{key:"too_dark",reticle:"coaching",minDurationMs:1400},too_bright:{key:"too_bright",reticle:"coaching",minDurationMs:1400},blurry:{key:"blurry",reticle:"coaching",minDurationMs:1400},focus_far:{key:"focus_far",reticle:"coaching",minDurationMs:1600},glare:{key:"glare",reticle:"coaching",minDurationMs:1400},hold_still:{key:"hold_still",reticle:"locking",minDurationMs:900},processing:{key:"processing",reticle:"processing",minDurationMs:800},side_captured:{key:"side_captured",reticle:"flip",minDurationMs:2600},captured:{key:"captured",reticle:"done",minDurationMs:800}});function qt(e){return e.framing==="no_document"?"sensing":e.framing==="too_far"?"too_far":e.framing==="too_close"?"too_close":e.framing==="edge_clipped"?"edge_clipped":e.framing==="wrong_shape"?"wrong_shape":e.framing==="tilted"?"tilted":e.lighting==="too_dark"?"too_dark":e.lighting==="too_bright"?"too_bright":e.glare==="glare"?"glare":e.blur==="blurry"?"blurry":"hold_still"}var nt=class{constructor(t=2600,n=.35){this.windowMs=t;this.decayPerSecond=n;this.votes=[];this.current=it.sensing;this.currentSinceMs=null}reset(){this.votes=[],this.current=it.sensing,this.currentSinceMs=null}force(t,n){return this.votes=[],this.current=it[t],this.currentSinceMs=n,this.current}tick(t,n){if(this.currentSinceMs===null&&(this.currentSinceMs=n),this.votes.push({key:t,atMs:n}),this.votes=this.votes.filter(r=>n-r.atMs<=this.windowMs),n-this.currentSinceMs<this.current.minDurationMs)return this.current;let i=new Map;for(let r of this.votes){let c=(n-r.atMs)/1e3,a=this.decayPerSecond**c;i.set(r.key,(i.get(r.key)??0)+a)}let o=this.current.key,s=-1;for(let[r,c]of i)c>s&&(s=c,o=r);return o!==this.current.key&&(this.current=it[o],this.currentSinceMs=n),this.current}};var Qe=Object.freeze({MAX_AREA_FRAC:.92,TILT_MAX_SIDE_RATIO:1.3,GLARE_MAX_SPECULAR_FRAC:.025});function ee(e){let{data:t,width:n,height:i}=e,o=n*i;if(o===0)return 0;let s=0;for(let r=0;r<o;r++){let c=r*4;.299*(t[c]??0)+.587*(t[c+1]??0)+.114*(t[c+2]??0)>=252&&s++}return s/o}function Be(e){let t=(a,l)=>Math.hypot(l.x-a.x,l.y-a.y),n=t(e.topLeft,e.topRight),i=t(e.bottomLeft,e.bottomRight),o=t(e.topLeft,e.bottomLeft),s=t(e.topRight,e.bottomRight),r=Math.max(n,i)/Math.max(1e-6,Math.min(n,i)),c=Math.max(o,s)/Math.max(1e-6,Math.min(o,s));return Math.max(r,c)}function ie(e){let t={...Zt,...e.thresholds},n=Qe,{quad:i,frameWidth:o,frameHeight:s,measures:r}=e,c=e.format==="ID-3",a="ok";if(i===null)a="no_document";else if(c){let m=ht(i),h=o>0?m.width/o:0,f=m.height>0?m.width/m.height:0;h<t.ID3_BAND_MIN_WIDTH_FRAC?a="too_far":te(i,o,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":(f<t.ID3_BAND_ASPECT_MIN||f>t.ID3_BAND_ASPECT_MAX)&&(a="wrong_shape")}else{let m=Jt(i,o,s),h=ht(i),f=Math.max(h.width,h.height)/Math.max(1e-6,Math.min(h.width,h.height));m<t.MIN_AREA_FRAC?a="too_far":m>n.MAX_AREA_FRAC?a="too_close":te(i,o,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":Vt(e.format,f)?Be(i)>n.TILT_MAX_SIDE_RATIO&&(a="tilted"):a="wrong_shape"}let l=r.exposure>=t.GUIDE_EXPOSURE?"ok":r.meanLuma<(ut[0]+ut[1])/2?"too_dark":"too_bright",u=r.sharpness>=t.GUIDE_SHARPNESS?"ok":"blurry",d=r.specularFraction>=n.GLARE_MAX_SPECULAR_FRAC?"glare":"ok";return{framing:a,lighting:l,blur:u,glare:d,acceptable:a==="ok"&&l==="ok"&&u==="ok"&&d==="ok"}}function te(e,t,n,i){return[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft].some(s=>s.x<=i||s.y<=i||s.x>=t-i||s.y>=n-i)}var oe=Object.freeze({width:1920,height:1080}),Ue=Object.freeze({width:3840,height:2160}),ne=4096,He=2560,se=640,ot=.15,Y=Object.freeze({side:.2,above:.9,below:.3});function L(e){let t=[e.topLeft.x,e.topRight.x,e.bottomRight.x,e.bottomLeft.x],n=[e.topLeft.y,e.topRight.y,e.bottomRight.y,e.bottomLeft.y],i=Math.min(...t),o=Math.min(...n);return{x:i,y:o,width:Math.max(...t)-i,height:Math.max(...n)-o}}function re(e,t){let n=Math.max(0,Math.floor(e.x)),i=Math.max(0,Math.floor(e.y)),o=Math.min(t.width,Math.ceil(e.x+e.width)),s=Math.min(t.height,Math.ceil(e.y+e.height));return o-n<16||s-i<16?null:{x:n,y:i,width:o-n,height:s-i}}function Ke(e,t,n){if(e===null||t.width<=0||t.height<=0)return null;let i=L(e);if(i.width<=0||i.height<=0)return null;let o=n==="ID-3"?{x:i.x-i.width*Y.side,y:i.y-i.width*Y.above,width:i.width*(1+2*Y.side),height:i.height+i.width*(Y.above+Y.below)}:{x:i.x-i.width*ot,y:i.y-i.height*ot,width:i.width*(1+2*ot),height:i.height*(1+2*ot)};return re(o,t)}function dt(e,t,n){let i=Math.max(e,t);return i>0?Math.min(1,n/i):1}function mt(e,t,n,i,o=He){let s=t.width>0?n.width/t.width:1,r=t.height>0?n.height/t.height:1,c=e===null?null:{topLeft:{x:e.topLeft.x*s,y:e.topLeft.y*r},topRight:{x:e.topRight.x*s,y:e.topRight.y*r},bottomRight:{x:e.bottomRight.x*s,y:e.bottomRight.y*r},bottomLeft:{x:e.bottomLeft.x*s,y:e.bottomLeft.y*r}},a=Ke(c,n,i)??{x:0,y:0,width:n.width,height:n.height},l=dt(a.width,a.height,o),u=Math.max(1,Math.round(a.width*l)),d=Math.max(1,Math.round(a.height*l)),m=null;if(c!==null){let h=L(c);m=re({x:(h.x-a.x)*l,y:(h.y-a.y)*l,width:h.width*l,height:h.height*l},{width:u,height:d})}return{crop:a,width:u,height:d,docRegion:m}}function ae(e,t,n,i=Ue){if(n==="LOW")return null;let o=e?.width?.max,s=e?.height?.max;if(typeof o!="number"||typeof s!="number"||o<=0||s<=0)return null;let r=Math.max(o,s),c=Math.min(o,s),a=Math.min(r,Math.max(i.width,i.height)),l=Math.min(c,Math.min(i.width,i.height));return a<=Math.max(t.width,t.height)?null:{width:{ideal:a},height:{ideal:l}}}function ce(e){let t={},n=e?.imageWidth,i=e?.imageHeight;if(typeof n?.max=="number"&&n.max>0){let o=typeof i?.max=="number"&&i.max>0?n.max/i.max:1.3333333333333333,s=o>=1?ne:ne*o,r=Math.min(n.max,Math.floor(s)),c=typeof n.step=="number"&&n.step>0?n.step:1,a=typeof n.min=="number"?n.min:0;r=Math.max(a,a+Math.floor((r-a)/c)*c),t.imageWidth=r}return e?.fillLightMode?.includes("off")===!0&&(t.fillLightMode="off"),t}function le(e,t){if(e.width<=0||e.height<=0||t.width<=0||t.height<=0)return!1;let n=e.width>e.height,i=t.width>t.height;return n!==i&&e.width!==e.height&&t.width!==t.height?!1:Math.max(e.width,e.height)>=1.2*Math.max(t.width,t.height)}function ue(e,t,n,i){if(n===null)return!1;let o=L(e),s=L(n);if(t.width<=0||i.width<=0)return!1;let r=o.width/t.width,c=s.width/i.width;return c>0&&r>=.6*c&&r<=1.25*c}var he=3500,Ve=.92;function me(){let e=globalThis.ImageCapture;return typeof e=="function"?e:null}function We(e){return/AppleWebKit\//.test(e)&&!/(Chrome|Chromium|Edg|OPR)\//.test(e)}function fe(e,t=typeof navigator>"u"?"":navigator.userAgent){return me()!==null&&!We(t)&&e!=null&&e.kind==="video"&&e.readyState==="live"}function de(e,t){return new Promise((n,i)=>{let o=setTimeout(()=>i(new Error("takePhoto timed out")),t);e.then(s=>{clearTimeout(o),n(s)},s=>{clearTimeout(o),i(s)})})}function ft(e,t){let n=document.createElement("canvas");return n.width=e,n.height=t,n}function Xe(e,t){return new Promise((n,i)=>{e.toBlob(o=>o?n(o):i(new Error("toBlob failed")),"image/jpeg",t)})}async function pe(e,t,n,i,o){let s=ft(n,i),r=ft(1,1);try{let c=s.getContext("2d");if(c===null)throw new Error("2d context unavailable");c.imageSmoothingQuality="high",c.drawImage(e,t.x,t.y,t.width,t.height,0,0,n,i);let a=await Xe(s,Ve),l=o===null?null:Wt({topLeft:{x:o.x,y:o.y},topRight:{x:o.x+o.width,y:o.y},bottomRight:{x:o.x+o.width,y:o.y+o.height},bottomLeft:{x:o.x,y:o.y+o.height}},{width:n,height:i},{width:n,height:i}),u=Xt(s,l),d=dt(n,i,se);return r.width=Math.max(1,Math.round(n*d)),r.height=Math.max(1,Math.round(i*d)),r.getContext("2d")?.drawImage(s,0,0,r.width,r.height),{blob:a,previewDataUrl:r.toDataURL("image/jpeg",.85),sharpness:u}}finally{s.width=0,s.height=0,r.width=0,r.height=0}}function je(e,t){let n=Math.min(1,t/e.width),i=ft(Math.max(1,Math.round(e.width*n)),Math.max(1,Math.round(e.height*n)));try{let o=i.getContext("2d",{willReadFrequently:!0});return o===null?null:(o.imageSmoothingQuality="high",o.drawImage(e,0,0,i.width,i.height),o.getImageData(0,0,i.width,i.height))}finally{i.width=0,i.height=0}}async function ge(e,t,n,i){let o={width:Math.max(1,e.videoWidth),height:Math.max(1,e.videoHeight)},s=mt(t,n,o,i);return{...await pe(e,s.crop,s.width,s.height,s.docRegion),docRegion:s.docRegion,source:"video",width:s.width,height:s.height}}async function be(e,t,n,i,o){let s=me();if(s===null)return null;let r=null;try{let c=new s(o.track),a=await de(c.getPhotoCapabilities?.()??Promise.resolve({}),he).catch(()=>({})),l=await de(c.takePhoto(ce(a)),he);r=await createImageBitmap(l);let u={width:e.videoWidth,height:e.videoHeight};if(!le(r,u))return null;let d=je(r,o.detectWidth),m=null;d!==null&&t!==null&&(m=await o.detect(d).catch(()=>null));let h=d??{width:r.width,height:r.height};m!==null&&!ue(m,h,t,n)&&(m=null);let f=mt(m,h,r,i);return{...await pe(r,f.crop,f.width,f.height,f.docRegion),docRegion:f.docRegion,source:"photo",width:f.width,height:f.height}}catch{return null}finally{r?.close()}}var st=Object.freeze({width:3840,height:2160,lensSelection:!0,continuousFocus:!0,refocusBeforePhotoMs:350,zoomMax:2,zoomNoFocusInfo:1.5,zoomMinSourcePx:2160,fillDistanceM:Object.freeze({id1:.11,id3:.15}),focusMarginFrac:.2,stillSharpnessMin:.16,stillRefusalsMax:2,focusFarFillFrac:.45,noDocFarHintMs:1500,zoomFallbackMs:8e3}),S=(e,t,n)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:void 0;function ki(e){let t=st,n=e!==null&&typeof e=="object"?e:{},i=n.fillDistanceM!==null&&typeof n.fillDistanceM=="object"?n.fillDistanceM:{},o=(s,r)=>typeof s=="boolean"?s:r;return{width:S(n.width,640,7680)??t.width,height:S(n.height,480,4320)??t.height,lensSelection:o(n.lensSelection,t.lensSelection),continuousFocus:o(n.continuousFocus,t.continuousFocus),refocusBeforePhotoMs:S(n.refocusBeforePhotoMs,0,2e3)??t.refocusBeforePhotoMs,zoomMax:S(n.zoomMax,1,5)??t.zoomMax,zoomNoFocusInfo:S(n.zoomNoFocusInfo,1,5)??t.zoomNoFocusInfo,zoomMinSourcePx:S(n.zoomMinSourcePx,0,8e3)??t.zoomMinSourcePx,fillDistanceM:{id1:S(i.id1,.03,1)??t.fillDistanceM.id1,id3:S(i.id3,.03,1)??t.fillDistanceM.id3},focusMarginFrac:S(n.focusMarginFrac,0,2)??t.focusMarginFrac,stillSharpnessMin:S(n.stillSharpnessMin,0,10)??t.stillSharpnessMin,stillRefusalsMax:S(n.stillRefusalsMax,0,10)??t.stillRefusalsMax,focusFarFillFrac:S(n.focusFarFillFrac,0,1)??t.focusFarFillFrac,noDocFarHintMs:S(n.noDocFarHintMs,0,6e4)??t.noDocFarHintMs,zoomFallbackMs:S(n.zoomFallbackMs,0,12e4)??t.zoomFallbackMs}}function Ye(e){let t=e.toLowerCase();return t===""?"unknown":/front|facing front|user|selfie|face ?time/.test(t)?"front":/ultra|0\.5x|wide angle/.test(t)?"ultra":/tele|zoom|periscope|[2-9]x/.test(t)?"tele":/depth|tof|infrared|\bir\b|truedepth|lidar|macro|monochrome|mono\b/.test(t)?"depth":/dual|triple/.test(t)?"virtual":/back|rear|environment|facing back|arrière|خلفية/.test(t)?"main":"unknown"}function Ze(e){let t=/camera2?\s*(\d+)/i.exec(e);return t?Number(t[1]):Number.POSITIVE_INFINITY}function Je(e){let t={main:0,virtual:1,ultra:9,tele:9,depth:9,front:9,unknown:9};return e.filter(n=>(n.kind===void 0||n.kind==="videoinput")&&n.deviceId!=="").map((n,i)=>({id:n.deviceId,kind:Ye(n.label),index:Ze(n.label),i})).filter(n=>t[n.kind]<9).sort((n,i)=>t[n.kind]-t[i.kind]||n.index-i.index||n.i-i.i).map(n=>n.id)}var pt="sekyro.doc.camera";function $e(){try{let e=globalThis.localStorage?.getItem(pt);return typeof e=="string"&&e!==""?e:null}catch{return null}}function ye(e){try{e===null?globalThis.localStorage?.removeItem(pt):globalThis.localStorage?.setItem(pt,e)}catch{}}var rt=(e,t)=>Array.isArray(e?.focusMode)&&e.focusMode.includes(t);function bt(e,t,n){if(!rt(e,"single-shot"))return null;let i=o=>Math.min(1,Math.max(0,Number.isFinite(o)?o:.5));return{focusMode:"single-shot",pointsOfInterest:[{x:i(t),y:i(n)}]}}function xi(e,t,n,i){if(!Number.isFinite(e)||!Number.isFinite(t)||n.width<=0||n.height<=0||i.width<=0||i.height<=0)return null;let o=Math.max(n.width/i.width,n.height/i.height),s=i.width*o,r=i.height*o,c=(e-n.left+(s-n.width)/2)/s,a=(t-n.top+(r-n.height)/2)/r;return{x:Math.min(1,Math.max(0,c)),y:Math.min(1,Math.max(0,a))}}function ke(e,t,n,i=st){let o=e?.zoom?.min,s=e?.zoom?.max;if(typeof s!="number"||s<=1)return 1;let r=n==="ID-3"?i.fillDistanceM.id3:i.fillDistanceM.id1,c=e?.focusDistance?.min,a;if(typeof c=="number"&&c>0&&c<1){if(a=c*(1+i.focusMarginFrac)/r,a<=1.05)return 1}else{if(Math.min(t.width,t.height)<i.zoomMinSourcePx)return 1;a=i.zoomNoFocusInfo}let l=Math.min(a,i.zoomMax,s);typeof o=="number"&&(l=Math.max(l,o));let u=e?.zoom?.step;return typeof u=="number"&&u>0&&(l=Math.round(l/u)*u),l>1.01?Number(l.toFixed(2)):1}function gt(e){try{return e.getVideoTracks?.()[0]}catch{return}}function Me(e){if(e!==null)for(let t of e.getTracks())t.stop()}function qe(e){try{let t=gt(e)?.getCapabilities?.();return!Array.isArray(t?.focusMode)||t.focusMode.includes("continuous")}catch{return!0}}var ti=3;async function xe(e){let t=s=>({audio:!1,video:{...s,width:{ideal:e.base.width},height:{ideal:e.base.height}}}),n=s=>e.getUserMedia(t({deviceId:{exact:s}})),i=()=>e.getUserMedia(t({facingMode:{ideal:"environment"}}));if(e.lensSelection){let s=$e();if(s!==null)try{return{stream:await n(s),lens:"stored"}}catch{ye(null)}}let o=await i();if(!e.lensSelection||e.enumerateDevices===void 0)return{stream:o,lens:"default"};try{let s=Je(await e.enumerateDevices()).slice(0,ti);if(s.length===0)return{stream:o,lens:"default"};let r=null;for(let c of s){let a=o!==null?gt(o)?.getSettings?.().deviceId:void 0;if(o===null||a!==c){Me(o),o=null;try{o=await n(c)}catch{continue}}if(r??(r=c),qe(o))return ye(c),{stream:o,lens:"selected"}}if(o!==null&&r!==null&>(o)?.getSettings?.().deviceId===r)return{stream:o,lens:"selected"};if(Me(o),o=null,r!==null)try{return{stream:await n(r),lens:"selected"}}catch{}return{stream:await i(),lens:"default"}}catch{return{stream:o??await i(),lens:"default"}}}var Z=Object.freeze({brightness:0,glare:0,cardGlare:0,sharpness:0,fill:0,shape:0,content:0,offsetX:0,offsetY:0,edgeConfidence:0,box:null}),I=e=>Math.min(1,Math.max(0,e));function we(e,t,n,i=.06){let o=Math.max(e.width/n,e.height),s=o*n,r=(e.width-s)/2,c=(e.height-o)/2,a=I((t.x-t.width*i-r)/s),l=I((t.y-t.height*i-c)/o),u=I((t.x+t.width*(1+i)-r)/s),d=I((t.y+t.height*(1+i)-c)/o);return{x:a,y:l,width:u-a,height:d-l}}function ve(e,t,n={}){let i=n.edgePeakFrac??0,{width:o,height:s,data:r}=e;if(o<=0||s<=0)return Z;let c=I(t.x),a=I(t.y),l={x:c,y:a,width:Math.max(0,I(t.x+t.width)-c),height:Math.max(0,I(t.y+t.height)-a)};if(l.width<=0||l.height<=0)return Z;let u=l.x*o,d=l.y*s,m=(l.x+l.width)*o,h=(l.y+l.height)*s,f=(m-u)*.15,g=(h-d)*.15,y=(p,b,T)=>Math.min(T,Math.max(b,p)),x=y(Math.floor(u-f),0,o-1),w=y(Math.floor(d-g),0,s-1),E=y(Math.ceil(m+f),x+1,o),v=y(Math.ceil(h+g),w+1,s),D=Math.max(1,Math.ceil(Math.max(E-x,v-w)/320)),M=Math.floor((E-x+D-1)/D),_=Math.floor((v-w+D-1)/D);if(M<3||_<3)return Z;let k=new Int32Array(M*_);for(let p=0;p<_;p++){let b=w+p*D;for(let T=0;T<M;T++){let C=(b*o+x+T*D)*4;k[p*M+T]=(r[C]??0)*77+(r[C+1]??0)*150+(r[C+2]??0)*29>>8}}let F=(p,b)=>(p-b-.5)/D,R=F(u,x),A=F(m,x),B=F(d,w),U=F(h,w),Mt=(m-u)/D,kt=(h-d)/D,xt=y(Math.ceil(R),0,M-1),Ce=y(Math.floor(A),xt,M-1),Dt=y(Math.ceil(B),0,_-1),Fe=y(Math.floor(U),Dt,_-1),wt=0,vt=0,H=0,St=0,_t=0,K=0;for(let p=Dt;p<=Fe;p++)for(let b=xt;b<=Ce;b++){let T=k[p*M+b];if(wt+=T,T>=248&&vt++,H++,b>=1&&b<M-1&&p>=1&&p<_-1){let C=k[p*M+b-1]+k[p*M+b+1]+k[(p-1)*M+b]+k[(p+1)*M+b]-4*T;St+=C,_t+=C*C,K++}}let Ae=H>0?wt/H:0,Rt=H>0?vt/H:0,Tt=K>0?St/K:0,Le=K>0?Math.max(0,_t/K-Tt*Tt):0,V=new Float64Array(M),W=new Float64Array(_);for(let p=0;p<_;p++)for(let b=1;b<M-1;b++)V[b]=V[b]+Math.abs(k[p*M+b+1]-k[p*M+b-1]);for(let p=1;p<_-1;p++)for(let b=0;b<M;b++)W[p]=W[p]+Math.abs(k[(p+1)*M+b]-k[(p-1)*M+b]);let O=at(V,!0,R,i),P=at(V,!1,A,i),G=at(W,!0,B,i),z=at(W,!1,U,i),Ct=(P.position-O.position)/Mt,Ft=(z.position-G.position)/kt,Ie=Ft>0?Ct/Ft:0,Ee=((O.position+P.position)/2-(R+A)/2)/Mt,Oe=((G.position+z.position)/2-(B+U)/2)/kt,At=De(V),Lt=De(W),Pe=At<=0||Lt<=0?0:Math.min(Math.min(O.value,P.value)/At,Math.min(G.value,z.value)/Lt),q=(p,b)=>b+(p+.5)*D,It=Rt,Et=0;{let p=(P.position-O.position)*.06,b=(z.position-G.position)*.06,T=y(Math.ceil(O.position+p),0,M-1),C=y(Math.floor(P.position-p),0,M-1),Ge=y(Math.ceil(G.position+b),0,_-1),Ot=y(Math.floor(z.position-b),0,_-1),Pt=0,tt=0,Gt=0;for(let N=Ge;N<=Ot;N++)for(let Q=T;Q<=C;Q++){tt++;let X=k[N*M+Q];X>=248&&Pt++;let ze=Q+2<=C?k[N*M+Q+2]:X,Ne=N+2<=Ot?k[(N+2)*M+Q]:X;(Math.abs(ze-X)>=24||Math.abs(Ne-X)>=24)&&Gt++}tt>=16&&(It=Pt/tt,Et=Gt/tt)}return{brightness:Ae,glare:Rt,cardGlare:It,sharpness:Le,fill:Ct,shape:Ie,content:Et,offsetX:Ee,offsetY:Oe,edgeConfidence:Pe,box:{left:q(O.position,x),right:q(P.position,x),top:q(G.position,w),bottom:q(z.position,w)}}}function at(e,t,n,i){let o=e.length,s=Math.max(1,Math.floor(o*.45)),r=t?1:Math.max(1,o-1-s),c=t?Math.min(o-2,s):o-2,a=r;for(let h=r;h<=c;h++)e[h]>e[a]&&(a=h);if(i>0&&i<1){let h=e[a]*i,f=a,g=Math.abs(a-n);for(let y=r;y<=c;y++){let x=e[y];if(x<h||x<(e[y-1]??0)||x<(e[y+1]??0))continue;let w=Math.abs(y-n);w<g&&(f=y,g=w)}a=f}let l=a>0?e[a-1]:0,u=e[a],d=a<o-1?e[a+1]:0,m=l+u+d;return{position:m>0?a+(d-l)/m:a,value:u}}function De(e){if(e.length<3)return 0;let t=0;for(let n=1;n<e.length-1;n++)t+=e[n];return t/(e.length-2)}function Se(e){let t=e.box;return t===null||t.right-t.left<4||t.bottom-t.top<4?null:{topLeft:{x:t.left,y:t.top},topRight:{x:t.right,y:t.top},bottomRight:{x:t.right,y:t.bottom},bottomLeft:{x:t.left,y:t.bottom}}}var J=Object.freeze({fillMin:.82,fillMax:1.06,offsetMax:.06,glareMax:.025,sharpnessMin:180,edgeConfidenceMin:1.6,darkBrightness:70,lockMs:450,steadyMs:900,steadyFillMin:.45,steadyFillMax:1.3,steadyFillDelta:.06,steadyOffsetDelta:.04,steadyRefMs:100,edgePeakFrac:.4,shapeTolerance:.2,contentMin:.1});function wi(e){let t=e!==null&&typeof e=="object"?e:{},n={...J};for(let i of Object.keys(J)){let o=t[i];typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1e6&&(n[i]=o)}return n}var ct=class{constructor(t=J){this.t=t;this.goodSince=null;this.steadySince=null;this.last=null}reset(){this.goodSince=null,this.steadySince=null,this.last=null}tick(t,n){let i=this.t,o=i.shapeTolerance<=0||Math.abs(t.shape-1)<=i.shapeTolerance,s=t.edgeConfidence>=i.edgeConfidenceMin&&o&&t.content>=i.contentMin,r=t.fill>=i.fillMin&&t.fill<=i.fillMax,c=Math.abs(t.offsetX)<=i.offsetMax&&Math.abs(t.offsetY)<=i.offsetMax,a=t.cardGlare<=i.glareMax,l=t.sharpness>=i.sharpnessMin,u=this.last;this.last={fill:t.fill,offsetX:t.offsetX,offsetY:t.offsetY,at:n};let d=u!==null&&i.steadyRefMs>0?Math.min(3,Math.max(1,(n-u.at)/i.steadyRefMs)):1,m=s&&a&&l&&t.fill>=i.steadyFillMin&&t.fill<=i.steadyFillMax&&u!==null&&Math.abs(t.fill-u.fill)<=i.steadyFillDelta*d&&Math.abs(t.offsetX-u.offsetX)<=i.steadyOffsetDelta*d&&Math.abs(t.offsetY-u.offsetY)<=i.steadyOffsetDelta*d,h=s&&r&&c&&a&&l,f;if(s?a?t.fill<i.fillMin?f="too_small":t.fill>i.fillMax?f="too_big":l?c?f="locking":f="off_center":f="blurry":f="glare":f="no_card",h){if(m&&(this.steadySince??(this.steadySince=n)),this.goodSince??(this.goodSince=n),n-this.goodSince>=i.lockMs)return{detected:s,ready:!0,via:"good",blocker:"locking"};let g=this.steadySince!==null&&n-this.steadySince>=i.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:"locking"}}if(this.goodSince=null,m){this.steadySince??(this.steadySince=n);let g=n-this.steadySince>=i.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:g?"locking":"steadying"}}return this.steadySince=null,{detected:s,ready:!1,via:null,blocker:f}}};var $=null;async function ei(e){return $===null&&($=(await import("./detector-scanic-YCDNLCGV.js")).detectQuad),$(e)}async function ii(e){let t=jt(e);return t===null?null:{topLeft:{x:t.x,y:t.y},topRight:{x:t.x+t.width,y:t.y},bottomRight:{x:t.x+t.width,y:t.y+t.height},bottomLeft:{x:t.x,y:t.y+t.height}}}function Ni(){$===null&&import("./detector-scanic-YCDNLCGV.js").then(e=>{$=e.detectQuad}).catch(()=>{})}var ni=Object.freeze({LOW:3,MID:5,HIGH:6}),yt=Object.freeze({manualShutterMs:6e3,detectedNoLockMs:1950});function Qi(e){let t=e!==null&&typeof e=="object"?e:{},n=(i,o,s)=>typeof i=="number"&&Number.isFinite(i)&&i>=o&&i<=s?i:void 0;return{manualShutterMs:n(t.manualShutterMs,1e3,6e4)??yt.manualShutterMs,detectedNoLockMs:n(t.steadyMs,300,3e4)!==void 0?t.steadyMs+(n(t.lockMs,0,1e4)??450):yt.detectedNoLockMs}}var _e=class e{constructor(t){this.torchOn=!1;this.stillRefusals=0;this.zoom=1;this.positioningSince=null;this.detectedSince=null;this.lastSeenAt=null;this.lastGuideQuad=null;this.lastOcrReady=null;this.shutterOffered=!1;this.stats=e.freshStats();this.handlers=new Map;this.stream=null;this.timer=null;this.state="idle";this.lastGuidance=null;this.attempt=0;this.capturing=!1;this.feedback=new nt;this.lastFeedbackKey=null;this.lastQuad=null;this.lastDetect=null;this.opts=t,this.gate=new $t(t.format??"ID-1",t.thresholds);let n=t.deviceClass??Bt(Qt());this.deviceClass=n,this.camera=t.camera??st,this.shutterTuning=t.shutter??yt,this.guideTuning=t.guideLock??J,this.guideLock=new ct(this.guideTuning),this.cadenceMs=1e3/ni[n]}on(t,n){let i=this.handlers.get(t);return i||(i=new Set,this.handlers.set(t,i)),i.add(n),()=>i?.delete(n)}emit(t,n){for(let i of[...this.handlers.get(t)??[]])i(n)}async start(){let t=++this.attempt;this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.setState("preflight");try{let n=this.opts.getUserMedia??(s=>navigator.mediaDevices.getUserMedia(s));this.setState("acquiring");let i=this.opts.enumerateDevices??(this.opts.getUserMedia===void 0&&typeof navigator<"u"&&navigator.mediaDevices?.enumerateDevices?()=>navigator.mediaDevices.enumerateDevices():void 0),o=await xe({getUserMedia:n,...i!==void 0?{enumerateDevices:i}:{},lensSelection:this.camera.lensSelection,base:oe});if(this.stream=o.stream,Nt(this.stream),t!==this.attempt){for(let s of this.stream.getTracks())s.stop();return}if(this.opts.upgradeResolution!==!1&&await this.upgradeResolution(),t!==this.attempt||(await this.applyFocusAndZoom(),t!==this.attempt))return;this.opts.video.srcObject=this.stream,await this.opts.video.play().catch(()=>{}),this.setState("positioning"),this.scheduleTick(t)}catch(n){let i=zt(n);this.setState("error"),this.emit("error",{kind:i,retryable:!0})}}rearm(t){t!==void 0&&(this.opts.side=t),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.stillRefusals=0,this.state==="captured"&&(this.setState("positioning"),this.scheduleTick(this.attempt))}async captureNow(){if(this.state!=="positioning"||this.capturing)return;let t=this.opts.video,n=this.lastDetect?.width??Math.max(1,t.videoWidth),i=this.lastDetect?.height??Math.max(1,t.videoHeight),o=this.lastQuad??this.lastGuideQuad??{topLeft:{x:0,y:0},topRight:{x:n,y:0},bottomRight:{x:n,y:i},bottomLeft:{x:0,y:i}},s=(this.opts.now??(()=>performance.now()))(),r=this.feedback.force("processing",s);this.lastFeedbackKey=r.key,this.emit("feedback",r),await this.fire(this.attempt,this.lastOcrReady!==null?this.lastOcrReady.quad:o,{width:n,height:i,tickSharpness:this.lastDetect?.tickSharpness??0},this.lastOcrReady?.via??"manual")}captureReport(){let t=this.stats;return{...this.opts.side!==void 0?{side:this.opts.side}:{},format:this.opts.format??"ID-1",deviceClass:this.deviceClass,video:{width:this.opts.video.videoWidth||0,height:this.opts.video.videoHeight||0},zoom:this.zoom,...t.zoomFallbackAtMs!==void 0?{zoomFallbackAtMs:t.zoomFallbackAtMs}:{},...t.msToCapture!==void 0?{msToCapture:t.msToCapture}:{},...t.via!==void 0?{via:t.via}:{},...t.shutterAtMs!==void 0?{shutterAtMs:t.shutterAtMs}:{},...t.shutterReason!==void 0?{shutterReason:t.shutterReason}:{},ticks:t.ticks,quadFraming:{...t.quadFraming},qualityBlockers:{...t.qualityBlockers},guideBlockers:{...t.guideBlockers},stillRefusals:t.stillRefusals,...this.ocrReport()}}ocrReport(){let t=this.opts.ocr;if(t===void 0)return{};let n=(this.opts.format??"ID-1")==="ID-3"||this.opts.side==="single"?"single":this.opts.side==="verso"?"verso":"recto",i=t.report(n,this.stats.via,(this.opts.now??(()=>performance.now()))());return i===null?{}:{ocr:i}}static freshStats(){return{ticks:0,quadFraming:{},qualityBlockers:{},guideBlockers:{},stillRefusals:0}}setGuide(t){t===void 0?delete this.opts.guide:this.opts.guide=t,this.guideLock.reset()}guideRegion(t){let n=t.width/Math.max(1,t.height),i=this.opts.guide;if(i!==void 0&&i.viewAspect>0){let c={width:i.viewAspect,height:1},a={x:i.rect.x*i.viewAspect,y:i.rect.y,width:i.rect.width*i.viewAspect,height:i.rect.height};return we(c,a,n,0)}let o=Kt(this.opts.format??"ID-1").center,s=.86,r=s*n/o;return r>.84&&(r=.84,s=r*o/n),{x:(1-s)/2,y:(1-r)/2,width:s,height:r}}resetSide(){this.positioningSince=null,this.detectedSince=null,this.lastSeenAt=null,this.guideLock.reset(),this.lastGuideQuad=null,this.lastOcrReady=null,this.opts.ocr?.reset(),this.stats=e.freshStats(),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}withdrawShutter(){this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}zoomFallback(t){let n=this.videoTrack();if(n===null||this.zoom<=1)return;let i=this.focusCaps(),o=typeof i?.zoom?.min=="number"?Math.max(i.zoom.min,1):1;this.zoom=o,this.stats.zoomFallbackAtMs=Math.round(t-(this.positioningSince??t)),this.guideLock.reset(),this.gate.reset(),n.applyConstraints({advanced:[{zoom:o}]}).catch(()=>{})}offerShutter(t,n){this.shutterOffered||(this.shutterOffered=!0,this.stats.shutterAtMs=Math.round(n-(this.positioningSince??n)),this.stats.shutterReason=t,this.emit("shutter",{available:!0,reason:t}))}torchAvailable(){try{return this.stream?.getVideoTracks?.()[0]?.getCapabilities?.()?.torch===!0}catch{return!1}}async setTorch(t){this.torchOn=t;try{await this.stream?.getVideoTracks?.()[0]?.applyConstraints({advanced:[{torch:t}]})}catch{}}destroy(){if(this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject=null}async upgradeResolution(){try{let t=this.stream?.getVideoTracks?.()[0];if(t===void 0)return;let n=t.getSettings?.()??{},i=ae(t.getCapabilities?.(),{width:n.width??0,height:n.height??0},this.deviceClass,{width:this.camera.width,height:this.camera.height});i!==null&&await t.applyConstraints(i)}catch{}}focusCaps(){try{return this.videoTrack()?.getCapabilities?.()??null}catch{return null}}async applyFocusAndZoom(){let t=this.videoTrack();if(t===null)return;let n=this.focusCaps();this.camera.continuousFocus&&rt(n,"continuous")&&await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{});let i={width:0,height:0};try{let s=t.getSettings?.()??{};i={width:s.width??0,height:s.height??0}}catch{}let o=ke(n,i,this.opts.format??"ID-1",this.camera);if(o>1)try{await t.applyConstraints({advanced:[{zoom:o}]}),this.zoom=o}catch{this.zoom=1}}async focusAt(t,n){let i=this.videoTrack(),o=bt(this.focusCaps(),t,n);if(!(i===null||o===null))try{await i.applyConstraints({advanced:[o]}),(this.opts.setTimer??setTimeout)(()=>{this.restoreContinuous()},1500)}catch{}}async restoreContinuous(){let t=this.videoTrack();t===null||!this.camera.continuousFocus||!rt(this.focusCaps(),"continuous")||await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})}async refocusOn(t,n){let i=this.camera.refocusBeforePhotoMs,o=this.videoTrack();if(i<=0||o===null||n.width<=0||n.height<=0)return;let s=L(t),r=bt(this.focusCaps(),(s.x+s.width/2)/n.width,(s.y+s.height/2)/n.height);if(r!==null)try{await o.applyConstraints({advanced:[r]});let c=this.opts.setTimer??setTimeout;await new Promise(a=>{c(()=>a(),i)})}catch{}}videoTrack(){try{return this.stream?.getVideoTracks?.()[0]??null}catch{return null}}async takeStill(t,n,i){if(this.opts.captureStill!==void 0)return this.opts.captureStill(this.opts.video,t,n);let o=this.opts.format??"ID-1",s=this.videoTrack();if(i&&this.opts.photoCapture!==!1&&this.deviceClass!=="LOW"&&!this.torchOn&&s!==null&&fe(s)){await this.refocusOn(t,n);let r=await be(this.opts.video,t,n,o,{track:s,detect:this.detector(),detectWidth:et});if(this.restoreContinuous(),r!==null)return r}return ge(this.opts.video,t,n,o)}detector(){return this.opts.detect??((this.opts.format??"ID-1")==="ID-3"?ii:ei)}setState(t){this.state=t,this.emit("statechange",{state:t})}scheduleTick(t){let n=this.opts.setTimer??setTimeout;this.timer=n(()=>{this.tick(t)},this.cadenceMs)}async tick(t){if(t!==this.attempt||this.state!=="positioning"||this.capturing)return;let n=this.opts.now??(()=>performance.now()),i=this.opts.grabDetectFrame??Te,o=this.detector(),s=i(this.opts.video,et);if(s===null){this.scheduleTick(t);return}let r=null;try{r=await o(s)}catch{r=null}if(t!==this.attempt)return;let c=r!==null?lt(s,r):s,a=n(),l={sharpness:j(c),exposure:Ht(c),meanLuma:Ut(c),specularFraction:ee(c)},u=ie({format:this.opts.format??"ID-1",quad:r,frameWidth:s.width,frameHeight:s.height,measures:l,...this.opts.thresholds!==void 0?{thresholds:this.opts.thresholds}:{}}),d=this.gate.tick({timestampMs:a,quad:r,quality:l,frameWidth:s.width,frameHeight:s.height}),h=(this.opts.format??"ID-1")!=="ID-3"?ve(s,this.guideRegion(s),{edgePeakFrac:this.guideTuning.edgePeakFrac}):Z,f=this.guideLock.tick(h,a);this.lastGuideQuad=f.detected?Se(h):null;let g=this.capturing?null:this.ocrTick(s,r,h,f.detected,u,a);this.positioningSince??(this.positioningSince=a);let y=this.stats;if(y.ticks+=1,y.quadFraming[u.framing]=(y.quadFraming[u.framing]??0)+1,u.framing==="ok"&&!d.ready){let R=u.lighting!=="ok"?u.lighting:u.glare!=="ok"?"glare":u.blur!=="ok"?"blurry":"steadying";y.qualityBlockers[R]=(y.qualityBlockers[R]??0)+1}y.guideBlockers[f.blocker]=(y.guideBlockers[f.blocker]??0)+1,r!==null||f.detected?(this.detectedSince??(this.detectedSince=a),this.lastSeenAt=a):this.detectedSince=null,this.lastSeenAt!==null&&a-this.lastSeenAt<=ui?a-this.positioningSince>=this.shutterTuning.manualShutterMs?this.offerShutter("timeout",a):g?.suspendQuality!==!0&&this.detectedSince!==null&&a-this.detectedSince>=this.shutterTuning.detectedNoLockMs&&this.offerShutter("detected_no_lock",a):this.withdrawShutter();let E=a-(this.lastSeenAt??this.positioningSince);this.zoom>1&&this.camera.zoomFallbackMs>0&&E>=this.camera.zoomFallbackMs&&this.zoomFallback(a),this.emit("checks",{engine:"docv1",p:d.p,plausible:d.plausible,stableTicks:d.stableTicks,quad:d.quad,frameWidth:s.width,frameHeight:s.height,analysis:u,ready:g?.suspendQuality!==!0&&(d.ready&&r!==null||f.ready&&this.lastGuideQuad!==null)||this.lastOcrReady!==null,guide:{detected:f.detected,blocker:f.blocker,fill:h.fill,shape:h.shape,content:h.content,offsetX:h.offsetX,offsetY:h.offsetY},...g!==null&&g.mode!=="off"?{ocr:{mode:g.mode,...g.mrz?{mrz:g.mrz}:{},...g.lock?{lock:g.lock}:{}}}:g?.mrz?{ocr:{mode:g.mode,mrz:g.mrz}}:{}}),this.lastQuad=d.plausible?r:null,this.lastDetect={width:s.width,height:s.height,tickSharpness:l.sharpness};let v=qt(u);u.framing!=="ok"&&f.detected&&(v=li(f.blocker,h.brightness<this.guideTuning.darkBrightness)),v==="blurry"&&r!==null&&si(r,s,this.opts.format??"ID-1")>=this.camera.focusFarFillFrac&&(v="focus_far"),v==="sensing"&&this.zoom>1&&this.camera.noDocFarHintMs>0&&E>=this.camera.noDocFarHintMs&&(v="focus_far");let D=this.feedback.tick(v,a);if(D.key!==this.lastFeedbackKey&&(this.lastFeedbackKey=D.key,this.emit("feedback",D)),d.guidanceKey!==this.lastGuidance&&(this.lastGuidance=d.guidanceKey,this.emit("guidance",{key:d.guidanceKey})),this.capturing)return;let M=g?.suspendQuality!==!0,_=M&&d.ready&&r!==null,k=M&&f.ready&&this.lastGuideQuad!==null,F=this.lastOcrReady;if(F!==null&&this.opts.autoCapture!==!1){let R=this.feedback.force("processing",a);this.lastFeedbackKey=R.key,this.emit("feedback",R);let A=j(lt(s,F.quad));await this.fire(t,F.quad,{width:s.width,height:s.height,tickSharpness:A},F.via);return}if((_||k)&&this.opts.autoCapture!==!1){let R=this.feedback.force("processing",a);this.lastFeedbackKey=R.key,this.emit("feedback",R);let A=k?this.lastGuideQuad:r,B=k?f.via==="steady"?"guide_steady":"guide_good":"quad",U=k?j(lt(s,A)):l.sharpness;await this.fire(t,A,{width:s.width,height:s.height,tickSharpness:U},B);return}this.scheduleTick(t)}async fire(t,n,i,o){this.capturing=!0;let s=this.opts.grabDetectFrame??Te,r=this.opts.setTimer??setTimeout,c={width:i.width,height:i.height};try{let a={still:await this.takeStill(n,c,!0),sharpness:i.tickSharpness};if(t!==this.attempt)return;let l=a.still.source==="photo"?0:ri;for(let m=0;m<l;m++){if(await new Promise(g=>{r(()=>g(),ai)}),t!==this.attempt)return;let h=s(this.opts.video,et);if(h===null)continue;let f=j(lt(h,n));if(f>a.sharpness*ci){let g=await this.takeStill(n,c,!1);if(t!==this.attempt)return;a={still:g,sharpness:f}}}if(t!==this.attempt)return;let u=a.still.sharpness;if(this.opts.autoCapture!==!1&&o!=="manual"&&typeof u=="number"&&u>=0&&u<this.camera.stillSharpnessMin&&this.stillRefusals<this.camera.stillRefusalsMax){this.stillRefusals+=1,this.stats.stillRefusals+=1,this.guideLock.reset(),this.lastOcrReady=null,(o==="text_lock"||o==="live_mrz")&&this.opts.ocr?.rearmFace();let m=(this.opts.now??(()=>performance.now()))(),h=this.feedback.force("focus_far",m);this.lastFeedbackKey=h.key,this.emit("feedback",h),this.capturing=!1,this.gate.reset(),this.scheduleTick(t);return}this.stillRefusals=0;let d=(this.opts.now??(()=>performance.now()))();this.stats.via=o,this.stats.msToCapture=Math.round(d-(this.positioningSince??d)),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1})),this.setState("captured"),this.emit("artifacts",{keyframe:a.still.blob,previewDataUrl:a.still.previewDataUrl,...this.opts.side!==void 0?{side:this.opts.side}:{},...a.still.docRegion!==void 0?{docRegion:a.still.docRegion}:{},...(()=>{let m=o==="live_mrz"?this.opts.ocr?.liveCapture():null;return m?{liveMrz:m}:{}})()})}catch{if(t!==this.attempt)return;this.capturing=!1,this.gate.reset(),this.guideLock.reset(),this.lastOcrReady=null,(o==="text_lock"||o==="live_mrz")&&this.opts.ocr?.rearmFace(),this.scheduleTick(t)}}ocrTick(t,n,i,o,s,r){let c=this.opts.ocr,a=this.opts.video;if(c===void 0||!c.hasEngine)return this.lastOcrReady=null,null;let l=a.videoWidth,u=a.videoHeight;if(l<=0||u<=0||t.width<=0||t.height<=0)return null;let m=(this.opts.format??"ID-1")==="ID-3",h=this.guideRegion(t),f={x:h.x*l,y:h.y*u,w:h.width*l,h:h.height*u},g=l/t.width,y=u/t.height,x;m&&n!==null?x=oi(L(n),g,y,l,u):x=Yt(f,c.bandTop,u);let w=m?s.glare==="ok":i.cardGlare<=this.guideTuning.glareMax,E=m?s.blur==="ok":i.sharpness>=this.guideTuning.sharpnessMin,v=c.tick({atMs:r,video:a,mrzFace:m||this.opts.side==="verso"||this.opts.side==="single",present:m||n!==null||o,card:f,band:x,portrait:u>l,glareOk:w,sharpOk:E});if(v.ready&&v.via!==void 0){let D=m?n??Re(h,t):this.lastGuideQuad??Re(h,t);this.lastOcrReady={quad:D,via:v.via}}else this.lastOcrReady=null;return v}};function oi(e,t,n,i,o){let s=Math.min(i,e.width*1.06*t),r=Math.min(o,Math.max(e.height*1.6*n,s/5)),c=(e.y+e.height/2)*n,a=Math.max(0,Math.min(i-s,(e.x-e.width*.03)*t)),l=Math.max(0,Math.min(o-r,c-r/2));return{x:a,y:l,w:s,h:r}}function Re(e,t){let n=e.x*t.width,i=e.y*t.height,o=(e.x+e.width)*t.width,s=(e.y+e.height)*t.height;return{topLeft:{x:n,y:i},topRight:{x:o,y:i},bottomRight:{x:o,y:s},bottomLeft:{x:n,y:s}}}function si(e,t,n){let i=L(e);return t.width<=0||t.height<=0?0:n==="ID-3"?i.width/t.width:i.width*i.height/(t.width*t.height)}var ri=2,ai=260,ci=1.08;function Te(e,t){let n=e.videoWidth,i=e.videoHeight;if(n===0||i===0)return null;let o=Math.min(1,t/n),s=Math.round(n*o),r=Math.round(i*o),c=document.createElement("canvas");c.width=s,c.height=r;let a=c.getContext("2d",{willReadFrequently:!0});return a===null?null:(n/Math.max(1,s)>4&&(a.imageSmoothingQuality="high"),a.drawImage(e,0,0,s,r),a.getImageData(0,0,s,r))}function lt(e,t){let n=[t.topLeft.x,t.topRight.x,t.bottomRight.x,t.bottomLeft.x],i=[t.topLeft.y,t.topRight.y,t.bottomRight.y,t.bottomLeft.y],o=Math.max(0,Math.floor(Math.min(...n))),s=Math.max(0,Math.floor(Math.min(...i))),r=Math.min(e.width,Math.ceil(Math.max(...n))),c=Math.min(e.height,Math.ceil(Math.max(...i))),a=Math.max(1,r-o),l=Math.max(1,c-s),u=new Uint8ClampedArray(a*l*4);for(let d=0;d<l;d++){let m=((s+d)*e.width+o)*4;u.set(e.data.subarray(m,m+a*4),d*a*4)}return{data:u,width:a,height:l,colorSpace:e.colorSpace}}function li(e,t){return e==="glare"?"glare":e==="too_small"?"too_far":e==="too_big"?"too_close":t?"too_dark":e==="blurry"?"blurry":e==="off_center"?"edge_clipped":e==="no_card"?"sensing":"hold_still"}var ui=1200;export{it as a,qt as b,nt as c,Qe as d,ee as e,Be as f,ie as g,st as h,ki as i,Ye as j,Je as k,pt as l,$e as m,ye as n,rt as o,bt as p,xi as q,ke as r,qe as s,ti as t,xe as u,Z as v,we as w,ve as x,Se as y,J as z,wi as A,ct as B,Ni as C,ni as D,yt as E,Qi as F,_e as G,oi as H,ri as I,ai as J};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as j,h as be,i as he,j as ye,l as Se}from"./chunk-G6LKLN4U.js";import{f as ge}from"./chunk-TDLIXFDT.js";import{l as fe}from"./chunk-RVHAKRAI.js";import{a as me,b as pe}from"./chunk-7V2M6Y2W.js";var Ge={low:{maxLongEdge:1920,payloadTargetBytes:7e5,qMin:.7,qMax:.92},mid:{maxLongEdge:2240,payloadTargetBytes:12e5,qMin:.7,qMax:.92},good:{maxLongEdge:2560,payloadTargetBytes:16e5,qMin:.7,qMax:.92}};function qe(e){let{deviceMemory:t,effectiveType:n,saveData:r,downlinkMbps:i,sourceLongEdge:l}=e,s=r===!0||n==="slow-2g"||n==="2g"||i!=null&&i>0&&i<1,u=t!=null&&t<=2,c=n==="4g"||i!=null&&i>=5,f=t!=null&&t>=6,p;s||u?p="low":c&&f?p="good":p="mid";let b=Ge[p],S=l&&l>0?Math.min(b.maxLongEdge,l):b.maxLongEdge;return{tier:p,...b,maxLongEdge:S}}function Me(e){let t={};try{let n=navigator;typeof n.deviceMemory=="number"&&(t.deviceMemory=n.deviceMemory);let r=n.connection;r&&(t.effectiveType=r.effectiveType,t.saveData=r.saveData,t.downlinkMbps=r.downlink)}catch{}return typeof e=="number"&&e>0&&(t.sourceLongEdge=e),qe(t)}function He(e,t,n){let r=Math.min(1,Math.max(0,(e-.28)/.21999999999999997)),i=(t+n)/2;return Math.max(t,n-r*(n-i))}function Xe(e,t,n){let r=Math.max(e,t),i=r>0?Math.min(1,n/r):1;return{width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(t*i))}}async function Ve(e,t){let n=t.startQ,r=await e(n);for(let i=0;i<4&&!(r.size<=t.budgetBytes||n<=t.qMin);i++)n=Math.max(t.qMin,n-.08),r=await e(n);return{blob:r,quality:n}}async function ke(e,t,n,r,i){if(t<=0||n<=0)return null;let{width:l,height:s}=Xe(t,n,r.maxLongEdge),u=document.createElement("canvas");u.width=l,u.height=s;let c=u.getContext("2d");if(!c)return null;c.drawImage(e,0,0,l,s);let f=I=>new Promise((h,w)=>{u.toBlob(d=>d?h(d):w(new Error("canvas toBlob returned null")),"image/jpeg",I)}),p=He(i,r.qMin,r.qMax),{blob:b,quality:S}=await Ve(f,{startQ:p,qMin:r.qMin,budgetBytes:r.payloadTargetBytes}).finally(()=>{u.width=0,u.height=0});if(b.size>5242880)throw new Error("encoded document exceeds the 5242880-byte media cap");return{blob:b,quality:S,width:l,height:s}}async function $(e){let t=Me(Math.max(e.width,e.height)),n=await ke(e,e.width,e.height,t,.5);if(n===null)throw new Error("canvas encode unavailable");return{blob:n.blob,width:n.width,height:n.height}}async function dt(e){let t=await createImageBitmap(e);try{return await $(t)}finally{t.close()}}var pt=250,ft=.6,gt=1800,bt=6e3,ht=2e3,De=.16;function Z(e,t){return{layout:e,phase:"framing",captured:{},pending:[],lastCaptureAt:t,lastReportAt:t,manualShutter:!1,restPhase:"framing",readSides:[],needFlip:!1,flipped:!1,flipTimeoutSpent:!1,timeoutCapture:!1,lastShotByTimeout:!1}}var we=e=>e==="recto"?"verso":"recto",Ce=e=>e.phase==="framing"||e.phase==="locking"||e.phase==="flipCue"||e.phase==="reaskRecto",ee=e=>(e.captured.recto!==void 0?1:0)+(e.captured.verso!==void 0?1:0)+e.pending.length;function J(e,t){return e.lastCaptureAt>=0&&e.lastReportAt>=0?e:{...e,lastCaptureAt:e.lastCaptureAt<0?t:e.lastCaptureAt,lastReportAt:e.lastReportAt<0?t:e.lastReportAt}}function Ye(e,t,n){if(e.phase==="result")return{...e,lastReportAt:n};let r=!t.present||e.captureArea!==void 0&&t.areaFrac<.6*e.captureArea,{flipped:i,awaySince:l}=e;r&&(l=l??n),l!==void 0&&n-l>=250&&(i=!0),r||(l=void 0);let s=e.flipTimeoutSpent&&!(i&&!e.flipped),u={...e,lastReportAt:n,flipped:i,awaySince:l,flipTimeoutSpent:s,lastArea:t.areaFrac};if(!Ce(e))return u;if(e.needFlip&&!i){if(!t.ready)return{...u,phase:e.restPhase,goodSince:void 0};let c=e.lastShot!==void 0&&e.pending.includes(e.lastShot);if(s||c)return{...u,goodSince:void 0,phase:e.restPhase};let f=e.goodSince??n;return n-f>=1800?{...u,goodSince:f,phase:"capturing",flipTimeoutSpent:!0,timeoutCapture:!0}:{...u,goodSince:f,phase:e.restPhase}}return t.ready?{...u,phase:"capturing",goodSince:e.goodSince??n}:{...u,goodSince:void 0,phase:t.locking?"locking":e.restPhase}}function Qe(e,t){if(!Ce(e)||e.manualShutter)return e;let n=t-e.lastReportAt>=2e3,r=t-e.lastCaptureAt>=6e3;return n||r?{...e,manualShutter:!0}:e}function Ke(e,t,n){let r=e.layout==="singlePage",i=r?{recto:t}:e.captured,l=r?[]:[...e.pending,t],s={...e,captured:i,pending:l,lastShot:t,lastCaptureAt:n,lastReportAt:-1,manualShutter:!1,goodSince:void 0,notice:void 0,awaySince:void 0,flipped:!1,lastShotByTimeout:e.timeoutCapture,timeoutCapture:!1,captureArea:e.lastArea};return r||ee({captured:i,pending:l})>=2?{...s,phase:"reading",restPhase:"framing",current:void 0,needFlip:!1}:{...s,phase:"flipCue",restPhase:"flipCue",current:void 0,needFlip:!0}}function Re(e,t,n){return e.pending.includes(t)?{...e,pending:e.pending.filter(r=>r!==t),lastShot:e.lastShot===t?void 0:e.lastShot,phase:e.phase==="capturing"?e.phase:"flipCue",restPhase:"flipCue",current:we(n),needFlip:!0,flipTimeoutSpent:!0,goodSince:void 0,manualShutter:!0,notice:"same_face",lastCaptureAt:-1,lastReportAt:-1}:e}function je(e,t,n){if(!e.pending.includes(t))return e;if(e.captured[n]!==void 0)return Re(e,t,n);let r=e.pending.filter(c=>c!==t),i={...e,pending:r,captured:{...e.captured,[n]:t}};if(ee(i)!==1||e.layout==="singlePage")return i;let l=we(n),s=l==="recto"&&e.restPhase==="reaskRecto"?"reaskRecto":"flipCue",u=e.phase==="flipCue"||e.phase==="reaskRecto"||e.phase==="framing";return{...i,restPhase:s,current:l,phase:u?s:e.phase}}function $e(e,t){let n=t.id??e.captured[t.side],r={...e.captured};(t.id===void 0||r[t.side]===t.id)&&delete r[t.side];let i=e.pending.filter(f=>f!==n),l=e.layout==="twoSided"&&ee({captured:r,pending:i})>0,s=e.lastShotByTimeout||n===e.lastShot!==e.flipped,u=l&&!s,c=u?t.side==="recto"?"reaskRecto":"flipCue":"framing";return{...e,captured:r,pending:i,readSides:e.readSides.filter(f=>f!==t.side),lastShot:e.lastShot===n?void 0:e.lastShot,notice:t.issue,goodSince:void 0,manualShutter:!1,phase:c,restPhase:c,current:t.side,needFlip:u,flipped:!1,flipTimeoutSpent:!1,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1}}function xe(e,t){switch(t.type){case"report":return Ye(J(e,t.at),t.report,t.at);case"tick":return Qe(J(e,t.at),t.at);case"captured":return Ke(J(e,t.at),t.id,t.at);case"captureFailed":return{...e,phase:e.restPhase,goodSince:void 0,lastCaptureAt:t.at,manualShutter:!0,timeoutCapture:!1};case"classified":return je(e,t.id,t.side);case"duplicate":return Re(e,t.id,t.side);case"readOk":{let n=e.readSides.includes(t.side)?e.readSides:[...e.readSides,t.side],r=["recto","verso"].filter(l=>e.captured[l]!==void 0),i=e.phase==="reading"&&e.pending.length===0&&r.every(l=>n.includes(l));return{...e,readSides:n,flipTimeoutSpent:!1,phase:i?"result":e.phase}}case"readFailed":return $e(e,t);case"clockRestart":return e.lastCaptureAt<0&&e.lastReportAt<0&&e.awaySince===void 0?e:{...e,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1};case"retake":return{...Z(e.layout,-1),lastCaptureAt:-1,lastReportAt:-1};default:return e}}function Je(e,t,n=!1){let r=e(t);return r===null?"recto":!n||r.y+r.height/2>=t.height/2?"verso":"recto"}async function Ze(e,t=!1){let{detectMrzBand:n}=await import("./mrz-band-VYHOTDHY.js");return Je(n,e,t)}async function te(e,t=480,n,r=n!=null){let i=n??{x:0,y:0,width:e.width,height:e.height},l=Math.max(1,Math.round(i.height/i.width*t)),s=document.createElement("canvas");s.width=t,s.height=l;try{let u=s.getContext("2d");return u===null?"recto":(u.drawImage(e,i.x,i.y,i.width,i.height,0,0,t,l),await Ze(u.getImageData(0,0,t,l),r))}finally{s.width=0,s.height=0}}async function St(e,t=480){try{let n=await createImageBitmap(e),r=Math.max(1,Math.round(n.height/n.width*t)),i=document.createElement("canvas");i.width=t,i.height=r;let l=i.getContext("2d");return l===null?(n.close(),null):(l.drawImage(n,0,0,t,r),n.close(),l.getImageData(0,0,t,r))}catch{return null}}var ne=(e,t,n)=>Math.min(n,Math.max(t,Math.round(e))),V=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function ve(e,t,n,r){let i=r.decode??(c=>createImageBitmap(c)),l=async()=>e.stillRead(await i(t),r.region??[0,0,1,1],r.detectorLimit),s;try{s=await l()}catch{try{await new Promise(c=>setTimeout(c,r.retryMs??300)),s=await l()}catch{return null}}let u=s.mrzBox;return u===void 0?null:{engine:r.engine,source:"live_mrz",format:n.format,lineCount:ne(n.lineCount,2,3),checkDigitsValid:!0,stillConfirmed:s.valid&&s.digest===n.digest,band:[V(u[0]),V(u[1]),V(Math.min(u[2],1-u[0])),V(Math.min(u[3],1-u[1]))],digest:n.digest,framesToValid:ne(n.framesToValid,1,1e3),msToValid:ne(n.msToValid,0,12e4)}}function kt(e){let t=null;return e?.then(n=>{t=n}),()=>t}var et=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]),tt=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,7,1,5,0,6,64,11,11]);function Le(e,t=globalThis){let n=t.WebAssembly?.validate;if(typeof n!="function")return{ok:!1,reason:"simd"};try{if(!n.call(t.WebAssembly,et)||!n.call(t.WebAssembly,tt))return{ok:!1,reason:"simd"}}catch{return{ok:!1,reason:"simd"}}if(typeof t.Worker!="function")return{ok:!1,reason:"worker"};if(typeof t.createImageBitmap!="function")return{ok:!1,reason:"bitmap"};let r=t.navigator?.deviceMemory;return typeof r=="number"&&r<e.minDeviceMemoryGb?{ok:!1,reason:"memory"}:{ok:!0}}function _e(e=globalThis){let t=e.navigator?.connection;return t?.saveData===!0||["slow-2g","2g","3g"].includes(t?.effectiveType??"")}var T=class extends Error{constructor(t){super(t),this.name="OcrEngineError",this.code=t}};function Te(){let e=t=>(t.close(),Promise.reject(new T("unsupported")));return{ready:Promise.resolve("unsupported"),busy:!1,bandRead:e,stillRead:e,layoutRead:e,dispose:()=>{}}}function Ee(e){let t;try{if(e.createWorker)t=e.createWorker();else if(e.workerUrl!==void 0)t=new Worker(e.workerUrl,{type:"module",name:"sekyro-ocr"});else return Te()}catch{return Te()}let n=new Map,r=0,i=!1,l=!1,s=!1;t.addEventListener("message",d=>{let g=d.data,C=n.get(g.id);C&&(n.delete(g.id),C.resolve(g))});let u=()=>{for(let d of n.values())d.reject(new T("error"));n.clear(),f()};t.addEventListener("error",u),t.addEventListener("messageerror",u);function c(d,g=[]){if(i)return Promise.reject(new T("disposed"));let C=++r;return new Promise((B,O)=>{n.set(C,{resolve:B,reject:O});try{t.postMessage({...d,id:C},g)}catch{n.delete(C),O(new T("error"))}})}function f(){if(!i){i=!0;try{t.postMessage({id:++r,kind:"dispose"})}catch{}t.terminate();for(let d of n.values())d.reject(new T("disposed"));n.clear()}}let p=(async()=>{let d=await c({kind:"init",baseUrl:e.baseUrl,salt:e.salt,detectorLimit:e.tuning.detectorLimit,maxDownloadMs:e.tuning.maxDownloadMs});if(d.kind==="failed")return d.reason;if(d.kind!=="ready")return"error";let g=await c({kind:"warmup"});return g.kind!=="ready"?"error":{warmupMs:g.warmupMs,downloadMs:d.downloadMs,cached:d.cached}})().catch(()=>"error"),b,S=new Promise(d=>{b=setTimeout(()=>d("timeout"),e.tuning.loadTimeoutMs)}),I=Promise.race([p,S]).then(d=>(clearTimeout(b),typeof d=="string"?f():s=!0,i&&typeof d!="string"?"error":d));(e.page===void 0?globalThis.addEventListener?globalThis:null:e.page)?.addEventListener("pagehide",f,{once:!0});async function w(d,g,C){if(i)throw g.close(),new T("disposed");if(!s)throw g.close(),new T("not_ready");if(l)throw g.close(),new T("busy");l=!0;let B;try{let O=new Promise((M,A)=>{B=setTimeout(()=>{A(new T("timeout")),f()},e.tuning.readTimeoutMs??1e4)}),P=await Promise.race([c(d,[g]),O]);if(P.kind===C){let{id:M,...A}=P;return A}throw new T(P.kind==="error"?P.code:P.kind==="failed"?P.reason:"error")}finally{clearTimeout(B),l=!1}}return{ready:I,get busy(){return l},bandRead:(d,g=e.tuning.detectorLimit)=>w({kind:"band",bitmap:d,detectorLimit:g},d,"band"),stillRead:(d,g,C=e.tuning.detectorLimit)=>w({kind:"still",bitmap:d,region:g,detectorLimit:C},d,"band"),layoutRead:(d,g)=>w({kind:"layout",bitmap:d,detectorLimit:g},d,"layout"),dispose:f}}var U="sekyro-ocr-1",re=e=>e!==null&&typeof e=="object"?e:{},v=(e,t,n,r)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:r,Oe=(e,t)=>typeof e=="boolean"?e:t,Pe=e=>{let t=typeof e=="string"?/^sekyro-ocr-(\d{1,4})$/.exec(e):null;return t?Number(t[1]):Number.POSITIVE_INFINITY};function Ae(e,t={}){let n=re(e),r=re(n.liveMrz),i=re(n.frontLock),l=Pe(t.engine??U),s=t.mode==="off",u=d=>d.enabled===!0?d.arm==="live"?"live":"control":null,c=u(r),f=u(i),p=(d,g)=>!s&&g==="live"&&Pe(d.minEngine??U)<=l,b=ye,S=p(r,c)?{detectorLimit:v(r.detectorLimit,320,1600,b.detectorLimit),bandMaxWidthPx:v(r.bandMaxWidthPx,320,4096,b.bandMaxWidthPx),minBandWidthPx:v(r.minBandWidthPx,0,4096,b.minBandWidthPx),bandTop:v(r.bandTop,0,.95,b.bandTop),minIntervalMs:v(r.minIntervalMs,0,5e3,b.minIntervalMs),stableReads:Math.round(v(r.stableReads,1,10,b.stableReads)),profileReads:Math.round(v(r.profileReads,1,100,b.profileReads)),maxReadMs:v(r.maxReadMs,50,6e4,b.maxReadMs),searchTimeoutMs:v(r.searchTimeoutMs,1e3,12e4,b.searchTimeoutMs),hint:Oe(r.hint,!0),stillConfirm:Oe(r.stillConfirm,!0)}:null,I=he,h=(d,g,C)=>v(i[d],g,C,I[d]),w=p(i,f)?{minLines:Math.round(h("minLines",1,50)),fillMin:h("fillMin",0,1),fillMax:h("fillMax",0,2),offsetMax:h("offsetMax",0,1),steadyFillDelta:h("steadyFillDelta",0,1),steadyOffsetDelta:h("steadyOffsetDelta",0,1),layoutShiftMax:h("layoutShiftMax",0,1),lineCountDelta:Math.round(h("lineCountDelta",0,50)),lockMs:h("lockMs",0,3e4),steadyMs:h("steadyMs",0,3e4),minFrames:Math.round(h("minFrames",1,100)),minIntervalMs:h("minIntervalMs",0,5e3),maxWidthPx:h("maxWidthPx",160,2048),detectorLimit:h("detectorLimit",320,1600),searchTimeoutMs:h("searchTimeoutMs",1e3,12e4)}:null;return{enabled:S!==null||w!==null,liveMrz:S,textLock:w,liveMrzArm:c,frontLockArm:f,load:{detectorLimit:S?.detectorLimit??w?.detectorLimit??b.detectorLimit,loadTimeoutMs:v(r.loadTimeoutMs,1e3,12e4,2e4),maxDownloadMs:v(r.maxDownloadMs,1e3,12e4,2e4),minDeviceMemoryGb:v(r.minDeviceMemoryGb,0,64,2)},reportSampleRate:v(r.reportSampleRate,0,1,1)}}function Be(e,t){return e.enabled?!(t.probe??Le)({minDeviceMemoryGb:e.load.minDeviceMemoryGb}).ok||(t.slow??_e)()?{ok:!1,reason:"unsupported"}:{ok:!0,engine:Ee({baseUrl:t.baseUrl,salt:t.salt,tuning:{detectorLimit:e.load.detectorLimit,maxDownloadMs:e.load.maxDownloadMs,loadTimeoutMs:e.load.loadTimeoutMs},...t.workerUrl!==void 0?{workerUrl:t.workerUrl}:{},...t.createWorker!==void 0?{createWorker:t.createWorker}:{},...t.page!==void 0?{page:t.page}:{}})}:{ok:!1,reason:"off"}}function nt(e=typeof navigator<"u"?navigator.userAgent:""){return/SamsungBrowser\//.test(e)?"samsung":/Firefox\/|FxiOS\//.test(e)?"firefox":/Chrome\/|CriOS\/|Chromium\//.test(e)&&!/Edg\/|OPR\//.test(e)?"chrome":/Safari\//.test(e)&&/Version\/|Mobile\//.test(e)&&!/Chrome\/|CriOS\//.test(e)?"safari":"other"}var W=e=>e===void 0||!Number.isFinite(e)?void 0:Math.min(6e5,Math.max(0,Math.round(e))),oe=(e,t,n)=>e===void 0||!Number.isFinite(e)?void 0:Math.min(n,Math.max(t,Math.round(e)));function Ie(e){let t=e.assist??null,n=e.load!==null&&e.load!==void 0&&typeof e.load=="object"?e.load:null,r=typeof e.load=="string"?e.load:null,i=t!==null?t.outcome:r==="unsupported"||r==="download"||r==="integrity"?r:r==="error"||r==="timeout"?"error":"off",l={kind:"live_mrz",platform:"web",engine:e.engine??U,arm:e.arm,capture:e.capture,outcome:i,reads:oe(t?.reads??0,0,1e4)??0,browser:e.browser??nt()},s=(u,c)=>{c!==void 0&&(l[u]=c)};return s("format",t?.format),s("framesToValid",oe(t?.framesToValid,1,1e4)),s("msToValid",W(t?.msToValid)),s("framesToLock",oe(t?.framesToLock,1,1e4)),s("msToLock",W(t?.msToLock)),s("msToCapture",W(e.msToCapture)),s("readP50Ms",W(t?.readP50Ms)),s("readP90Ms",W(t?.readP90Ms)),s("deviceClass",t?.deviceClass),n!==null&&(s("warmupMs",W(n.warmupMs)),s("downloadMs",W(n.downloadMs)),s("cached",n.cached)),s("stillConfirmed",e.stillConfirmed),s("typeMismatch",e.typeMismatch),l}function ae(e,t){return e===void 0?!1:t==="passport"?e!=="TD3":e==="TD3"}var rt=2;async function ot(e){let t=await import("./capture-session-doc-YBE3UMJJ.js");return new t.CaptureSessionDoc(e)}function at(e){return{topLeft:{x:e.x,y:e.y},topRight:{x:e.x+e.width,y:e.y},bottomRight:{x:e.x+e.width,y:e.y+e.height},bottomLeft:{x:e.x,y:e.y+e.height}}}function it(e,t,n){let r=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let l=0;l<r.length;l+=1){let s=r[l],u=r[(l+1)%r.length];i+=s.x*u.y-u.x*s.y}return t>0&&n>0?Math.abs(i)/2/(t*n):0}function Nt(){import("./capture-session-doc-YBE3UMJJ.js").then(e=>e.warmDocDetector()).catch(()=>{})}function Ut(e){return st(e,{}).handle}function st(e,t){let n=me(),r=pe({enabled:e.keepScreenAwake!==!1}),i=t.decode??(o=>createImageBitmap(o)),l=t.blurRefuseSharpnessMax??.16,s=t.now??(()=>performance.now()),u=e.documentType==="passport"||e.side==="single",c=Z(u?"singlePage":"twoSided",s());if(!u&&(e.side==="recto"||e.side==="verso")){let o=e.side==="recto"?"verso":"recto";c={...c,captured:{[o]:"server"},readSides:[o],current:e.side,phase:"flipCue",restPhase:"flipCue"}}let f="idle",p=null,b=null,S=!0,I=0,h=0,w=!1,d=!1,g="",C=null,B,O=null,P=[],M=t.webOcr!==void 0?Ae(t.webOcr.captureDocument,{mode:e.liveMrz?.mode??"auto"}):null,A=null,F=M===null||!M.enabled?"off":null,G=null,q=null,ie=new WeakMap,Y="";if(M!==null&&M.enabled&&t.webOcr!==void 0){let o=t.webOcr,a=Be(M,{baseUrl:e.liveMrz?.assetBaseUrl??o.baseUrl,salt:o.salt,...e.liveMrz?.workerUrl!==void 0?{workerUrl:e.liveMrz.workerUrl}:{},...o.createWorker!==void 0?{createWorker:o.createWorker}:{}});if(a.ok){A=a.engine;let m=new Se({textLock:M.textLock,liveMrz:M.liveMrz});G=m;let y=a.engine;y.ready.then(L=>{F=L,typeof L!="string"&&S&&m.setEngine(y)})}else F=a.reason}let z=o=>{let a=JSON.stringify(o);a!==Y&&(Y=a,n.emit("mrz",o))},se=(o,a)=>{let m=t.webOcr?.reports;if(m===void 0||M===null||o===void 0)return;let y=o.format==="ID-3"||o.side==="single"?"single":o.side==="verso"?"verso":"recto",L=y!=="recto"?M.liveMrzArm??M.frontLockArm:M.frontLockArm;if(L===null||Math.random()>=M.reportSampleRate)return;let _=o.via==="live_mrz"?q:null,x=()=>{let E=_?.value??null;m([Ie({arm:L,capture:y,assist:o.ocr??null,load:L==="control"?"off":F,...o.msToCapture!==void 0?{msToCapture:o.msToCapture}:{},...E!==null&&E.stillConfirmed!==void 0?{stillConfirmed:E.stillConfirmed}:{},...a!==void 0?{typeMismatch:ae(a.format,e.documentType==="passport"?"passport":"card")}:{}})])};_!==null&&_.value===null?Promise.race([_.promise,new Promise(E=>setTimeout(E,3e3))]).then(x):x()},N=o=>{!S||o===f||(f=o,r.setActive(o==="starting"||o==="scanning"),n.emit("state",o))},We=(o,a)=>a===void 0?null:u?"single":o.captured.recto===a?"recto":o.captured.verso===a?"verso":null,Fe=o=>({phase:o.phase,captured:u?o.captured.recto!==void 0?["single"]:[]:["recto","verso"].filter(a=>o.captured[a]!==void 0),expected:u?null:o.current??null,notice:o.notice??null,lastShot:We(o,o.lastShot),manualShutter:o.manualShutter,torchAvailable:p?.torchAvailable()??!1,torch:d}),ue=()=>{let o=p;o!==null&&o.captureNow().catch(()=>R({type:"captureFailed",at:s()}))};function R(o){if(!S)return;let a=c;c=xe(c,o),c.phase==="capturing"&&a.phase!=="capturing"&&Promise.resolve().then(ue),c.phase==="result"&&a.phase!=="result"&&(N("done"),le());let m=Fe(c),y=JSON.stringify(m);y!==g&&(g=y,n.emit("scan",m))}function le(){O!==null&&clearInterval(O),O=null;for(let o of P.splice(0))o();p?.destroy(),p=null,r.setActive(!1)}let ce=()=>p?.captureReport?.(),Q=!1,de=(o,a)=>{if(!(o===void 0||t.onFaceReport===void 0))try{t.onFaceReport(o,a)}catch{}},H=o=>{Y="",!(p===null||c.phase==="reading"||c.phase==="result")&&(Q=!1,p.rearm(u?"single":c.current??o))},ze=async(o,a,m,y)=>{if(q=null,y!==void 0&&A!==null&&M?.liveMrz?.hint===!0){let D={promise:ve(A,o,y,{engine:U,detectorLimit:M.liveMrz.detectorLimit}).catch(()=>null),value:null};D.promise.then(k=>{D.value=k}),q=D}y!==void 0&&ae(y.format,e.documentType==="passport"?"passport":"card")&&z({state:"mismatch",format:y.format});let L=ce();de(L,"captured"),Q=!0,se(L,y);let _=m===void 0?C:m===null?null:{quad:at(m),frameWidth:0,frameHeight:0,inStill:!0},x={decoded:null},E=()=>(x.decoded??(x.decoded=Promise.resolve().then(()=>i(o)).catch(()=>null)),x.decoded);try{await Ne(o,a,_,E,q)}finally{x.decoded!==null&&(await x.decoded)?.close()}},Ne=async(o,a,m,y,L)=>{let _=`shot-${I+=1}`;if(R({type:"captured",id:_,at:s()}),e.haptics!==!1)try{globalThis.navigator?.vibrate?.(30)}catch{}if(!w&&l>0){let D=await(t.measureSharpness!==void 0?t.measureSharpness(o,m):y().then(k=>k===null?-1:be(k,j(m?.quad??null,m?.inStill===!0?k:{width:m?.frameWidth??0,height:m?.frameHeight??0},k)))).catch(()=>-1);if(!S)return;if(Number.isFinite(D)&&D>=0&&D<l){w=!0;let k=u?"recto":c.current??(c.captured.recto===void 0?"recto":"verso");R({type:"readFailed",side:k,id:_,issue:"blurry"}),H(k);return}}w=!1;let x;if(u)x="single";else{let D=c.current,k=await(t.classify!==void 0?t.classify(o):y().then(X=>X===null?D??"recto":m?.inStill===!0?te(X,480,null,!0):te(X,480,j(m?.quad??null,{width:m?.frameWidth??0,height:m?.frameHeight??0},X)))).catch(()=>D??"recto");if(!S)return;if(c.captured[k]!==void 0&&h<rt){h+=1,R({type:"duplicate",id:_,side:k}),H(k==="recto"?"verso":"recto");return}x=c.captured[k]!==void 0&&D!==void 0?D:k,h=0,R({type:"classified",id:_,side:x})}let E=x==="verso"?"verso":"recto";try{let D=t.encode!==void 0?await t.encode(o):await y().then(k=>{if(k===null)throw new Error("the still could not be decoded");return $(k)});if(!S)return;L!==null&&ie.set(D.blob,L),n.emit("captured",{image:D.blob,side:x,documentType:e.documentType,...e.issuer!==void 0?{issuer:e.issuer}:{},width:D.width,height:D.height,previewDataUrl:a}),t.deferRead!==!0&&R({type:"readOk",side:E})}catch{R({type:"readFailed",side:E,id:_,issue:"technical"}),n.emit("error",{kind:"generic",retryable:!0})}H(E==="recto"?"verso":"recto")},Ue=o=>{P.push(o.on("statechange",({state:a})=>{a==="preflight"||a==="acquiring"?N("starting"):a==="positioning"?N("scanning"):a==="captured"?N("captured"):a==="error"&&N("error")}),o.on("feedback",({key:a,reticle:m})=>n.emit("feedback",{key:a,reticle:m})),o.on("checks",a=>{n.emit("gate",{progress:a.p,quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight,...a.guide!==void 0?{guide:{detected:a.guide.detected,fill:a.guide.fill,offsetX:a.guide.offsetX??0,offsetY:a.guide.offsetY??0}}:{}});let m=a.ocr?.mrz;m!==void 0&&(m.state==="fallback"?z({state:"fallback",reason:m.reason}):m.state==="valid"?z({state:"valid",format:m.format}):m.state==="reading"?z({state:"reading",...m.format?{format:m.format}:{},...m.coach?{coach:m.coach}:{}}):z({state:"searching"}));let y=a.quad===null?0:it(a.quad,a.frameWidth,a.frameHeight);C=a.quad===null?null:{quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight},R({type:"report",report:{present:a.quad!==null&&a.plausible||a.guide?.detected===!0,ready:a.ready===!0,locking:a.p>=.5,areaFrac:y},at:s()})}),o.on("error",({kind:a,retryable:m})=>n.emit("error",{kind:fe(a),retryable:m})),o.on("artifacts",a=>{ze(a.keyframe,a.previewDataUrl,a.docRegion,a.liveMrz)}))},K=()=>(b??(b=(async()=>{if(S){if(p===null){let o=await(t.createEngine??ot)({...t.engineOptions??{},...B!==void 0?{guide:B}:{},video:e.video,format:ge(e.documentType),side:u?"single":e.side??"recto",autoCapture:!1,...G!==null?{ocr:G}:{}});if(!S){o.destroy();return}p=o,Ue(o);let a=t.tickMs??500;a>0&&(O=setInterval(()=>R({type:"tick",at:s()}),a))}R({type:"clockRestart"}),M!==null&&M.liveMrzArm==="live"&&(F==="unsupported"||F==="off")&&z({state:"fallback",reason:F}),await p.start()}})().finally(()=>{b=null})),b);return{handle:{get state(){return f},on:(o,a)=>n.on(o,a),start:K,retry:()=>{if(p===null&&c.phase==="result"){R({type:"retake"}),h=0,w=!1,K();return}if(p!==null&&f!=="error"){R({type:"retake"}),h=0,w=!1,p.rearm(u?"single":void 0);return}K()},setSide:o=>{u||o==="single"||(c.current!==o&&(c={...c,current:o}),R({type:"clockRestart"}),c.phase!=="reading"&&c.phase!=="result"&&p?.rearm(o))},shutter:ue,focusAt:(o,a)=>{p?.focusAt?.(o,a)},setGuide:o=>{B=o,p?.setGuide?.(o)},setTorch:o=>{d=o,p?.setTorch(o),R({type:"tick",at:s()})},destroy:()=>{if(S&&p!==null&&f!=="done"){let o=ce();!Q&&o!==void 0&&o.ticks>0&&de(o,"abandoned"),se(o,void 0)}S=!1,le(),G?.setEngine(null),A?.dispose(),A=null,n.clear()}},setFlowState:o=>{(c.phase==="reading"||c.phase==="result")&&N(o==="done"&&c.phase!=="result"?"scanning":o)},settle:(o,a)=>{let m=o==="verso"?"verso":"recto";R(a.ok?{type:"readOk",side:m}:{type:"readFailed",side:m,issue:a.issue}),a.ok||H(m)},takeDeviceRead:o=>ie.get(o.image)?.value??null}}export{dt as a,pt as b,ft as c,gt as d,bt as e,ht as f,De as g,Z as h,xe as i,Je as j,Ze as k,St as l,ve as m,kt as n,U as o,Ae as p,Be as q,nt as r,Ie as s,ae as t,rt as u,Nt as v,Ut as w,st as x};
|
|
1
|
+
import{d as j,h as be,i as he,j as ye,l as Se}from"./chunk-G6LKLN4U.js";import{f as ge}from"./chunk-TDLIXFDT.js";import{l as fe}from"./chunk-WRKUWIJW.js";import{a as me,b as pe}from"./chunk-7V2M6Y2W.js";var Ge={low:{maxLongEdge:1920,payloadTargetBytes:7e5,qMin:.7,qMax:.92},mid:{maxLongEdge:2240,payloadTargetBytes:12e5,qMin:.7,qMax:.92},good:{maxLongEdge:2560,payloadTargetBytes:16e5,qMin:.7,qMax:.92}};function qe(e){let{deviceMemory:t,effectiveType:n,saveData:r,downlinkMbps:i,sourceLongEdge:l}=e,s=r===!0||n==="slow-2g"||n==="2g"||i!=null&&i>0&&i<1,u=t!=null&&t<=2,c=n==="4g"||i!=null&&i>=5,f=t!=null&&t>=6,p;s||u?p="low":c&&f?p="good":p="mid";let b=Ge[p],S=l&&l>0?Math.min(b.maxLongEdge,l):b.maxLongEdge;return{tier:p,...b,maxLongEdge:S}}function Me(e){let t={};try{let n=navigator;typeof n.deviceMemory=="number"&&(t.deviceMemory=n.deviceMemory);let r=n.connection;r&&(t.effectiveType=r.effectiveType,t.saveData=r.saveData,t.downlinkMbps=r.downlink)}catch{}return typeof e=="number"&&e>0&&(t.sourceLongEdge=e),qe(t)}function He(e,t,n){let r=Math.min(1,Math.max(0,(e-.28)/.21999999999999997)),i=(t+n)/2;return Math.max(t,n-r*(n-i))}function Xe(e,t,n){let r=Math.max(e,t),i=r>0?Math.min(1,n/r):1;return{width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(t*i))}}async function Ve(e,t){let n=t.startQ,r=await e(n);for(let i=0;i<4&&!(r.size<=t.budgetBytes||n<=t.qMin);i++)n=Math.max(t.qMin,n-.08),r=await e(n);return{blob:r,quality:n}}async function ke(e,t,n,r,i){if(t<=0||n<=0)return null;let{width:l,height:s}=Xe(t,n,r.maxLongEdge),u=document.createElement("canvas");u.width=l,u.height=s;let c=u.getContext("2d");if(!c)return null;c.drawImage(e,0,0,l,s);let f=I=>new Promise((h,w)=>{u.toBlob(d=>d?h(d):w(new Error("canvas toBlob returned null")),"image/jpeg",I)}),p=He(i,r.qMin,r.qMax),{blob:b,quality:S}=await Ve(f,{startQ:p,qMin:r.qMin,budgetBytes:r.payloadTargetBytes}).finally(()=>{u.width=0,u.height=0});if(b.size>5242880)throw new Error("encoded document exceeds the 5242880-byte media cap");return{blob:b,quality:S,width:l,height:s}}async function $(e){let t=Me(Math.max(e.width,e.height)),n=await ke(e,e.width,e.height,t,.5);if(n===null)throw new Error("canvas encode unavailable");return{blob:n.blob,width:n.width,height:n.height}}async function dt(e){let t=await createImageBitmap(e);try{return await $(t)}finally{t.close()}}var pt=250,ft=.6,gt=1800,bt=6e3,ht=2e3,De=.16;function Z(e,t){return{layout:e,phase:"framing",captured:{},pending:[],lastCaptureAt:t,lastReportAt:t,manualShutter:!1,restPhase:"framing",readSides:[],needFlip:!1,flipped:!1,flipTimeoutSpent:!1,timeoutCapture:!1,lastShotByTimeout:!1}}var we=e=>e==="recto"?"verso":"recto",Ce=e=>e.phase==="framing"||e.phase==="locking"||e.phase==="flipCue"||e.phase==="reaskRecto",ee=e=>(e.captured.recto!==void 0?1:0)+(e.captured.verso!==void 0?1:0)+e.pending.length;function J(e,t){return e.lastCaptureAt>=0&&e.lastReportAt>=0?e:{...e,lastCaptureAt:e.lastCaptureAt<0?t:e.lastCaptureAt,lastReportAt:e.lastReportAt<0?t:e.lastReportAt}}function Ye(e,t,n){if(e.phase==="result")return{...e,lastReportAt:n};let r=!t.present||e.captureArea!==void 0&&t.areaFrac<.6*e.captureArea,{flipped:i,awaySince:l}=e;r&&(l=l??n),l!==void 0&&n-l>=250&&(i=!0),r||(l=void 0);let s=e.flipTimeoutSpent&&!(i&&!e.flipped),u={...e,lastReportAt:n,flipped:i,awaySince:l,flipTimeoutSpent:s,lastArea:t.areaFrac};if(!Ce(e))return u;if(e.needFlip&&!i){if(!t.ready)return{...u,phase:e.restPhase,goodSince:void 0};let c=e.lastShot!==void 0&&e.pending.includes(e.lastShot);if(s||c)return{...u,goodSince:void 0,phase:e.restPhase};let f=e.goodSince??n;return n-f>=1800?{...u,goodSince:f,phase:"capturing",flipTimeoutSpent:!0,timeoutCapture:!0}:{...u,goodSince:f,phase:e.restPhase}}return t.ready?{...u,phase:"capturing",goodSince:e.goodSince??n}:{...u,goodSince:void 0,phase:t.locking?"locking":e.restPhase}}function Qe(e,t){if(!Ce(e)||e.manualShutter)return e;let n=t-e.lastReportAt>=2e3,r=t-e.lastCaptureAt>=6e3;return n||r?{...e,manualShutter:!0}:e}function Ke(e,t,n){let r=e.layout==="singlePage",i=r?{recto:t}:e.captured,l=r?[]:[...e.pending,t],s={...e,captured:i,pending:l,lastShot:t,lastCaptureAt:n,lastReportAt:-1,manualShutter:!1,goodSince:void 0,notice:void 0,awaySince:void 0,flipped:!1,lastShotByTimeout:e.timeoutCapture,timeoutCapture:!1,captureArea:e.lastArea};return r||ee({captured:i,pending:l})>=2?{...s,phase:"reading",restPhase:"framing",current:void 0,needFlip:!1}:{...s,phase:"flipCue",restPhase:"flipCue",current:void 0,needFlip:!0}}function Re(e,t,n){return e.pending.includes(t)?{...e,pending:e.pending.filter(r=>r!==t),lastShot:e.lastShot===t?void 0:e.lastShot,phase:e.phase==="capturing"?e.phase:"flipCue",restPhase:"flipCue",current:we(n),needFlip:!0,flipTimeoutSpent:!0,goodSince:void 0,manualShutter:!0,notice:"same_face",lastCaptureAt:-1,lastReportAt:-1}:e}function je(e,t,n){if(!e.pending.includes(t))return e;if(e.captured[n]!==void 0)return Re(e,t,n);let r=e.pending.filter(c=>c!==t),i={...e,pending:r,captured:{...e.captured,[n]:t}};if(ee(i)!==1||e.layout==="singlePage")return i;let l=we(n),s=l==="recto"&&e.restPhase==="reaskRecto"?"reaskRecto":"flipCue",u=e.phase==="flipCue"||e.phase==="reaskRecto"||e.phase==="framing";return{...i,restPhase:s,current:l,phase:u?s:e.phase}}function $e(e,t){let n=t.id??e.captured[t.side],r={...e.captured};(t.id===void 0||r[t.side]===t.id)&&delete r[t.side];let i=e.pending.filter(f=>f!==n),l=e.layout==="twoSided"&&ee({captured:r,pending:i})>0,s=e.lastShotByTimeout||n===e.lastShot!==e.flipped,u=l&&!s,c=u?t.side==="recto"?"reaskRecto":"flipCue":"framing";return{...e,captured:r,pending:i,readSides:e.readSides.filter(f=>f!==t.side),lastShot:e.lastShot===n?void 0:e.lastShot,notice:t.issue,goodSince:void 0,manualShutter:!1,phase:c,restPhase:c,current:t.side,needFlip:u,flipped:!1,flipTimeoutSpent:!1,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1}}function xe(e,t){switch(t.type){case"report":return Ye(J(e,t.at),t.report,t.at);case"tick":return Qe(J(e,t.at),t.at);case"captured":return Ke(J(e,t.at),t.id,t.at);case"captureFailed":return{...e,phase:e.restPhase,goodSince:void 0,lastCaptureAt:t.at,manualShutter:!0,timeoutCapture:!1};case"classified":return je(e,t.id,t.side);case"duplicate":return Re(e,t.id,t.side);case"readOk":{let n=e.readSides.includes(t.side)?e.readSides:[...e.readSides,t.side],r=["recto","verso"].filter(l=>e.captured[l]!==void 0),i=e.phase==="reading"&&e.pending.length===0&&r.every(l=>n.includes(l));return{...e,readSides:n,flipTimeoutSpent:!1,phase:i?"result":e.phase}}case"readFailed":return $e(e,t);case"clockRestart":return e.lastCaptureAt<0&&e.lastReportAt<0&&e.awaySince===void 0?e:{...e,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1};case"retake":return{...Z(e.layout,-1),lastCaptureAt:-1,lastReportAt:-1};default:return e}}function Je(e,t,n=!1){let r=e(t);return r===null?"recto":!n||r.y+r.height/2>=t.height/2?"verso":"recto"}async function Ze(e,t=!1){let{detectMrzBand:n}=await import("./mrz-band-VYHOTDHY.js");return Je(n,e,t)}async function te(e,t=480,n,r=n!=null){let i=n??{x:0,y:0,width:e.width,height:e.height},l=Math.max(1,Math.round(i.height/i.width*t)),s=document.createElement("canvas");s.width=t,s.height=l;try{let u=s.getContext("2d");return u===null?"recto":(u.drawImage(e,i.x,i.y,i.width,i.height,0,0,t,l),await Ze(u.getImageData(0,0,t,l),r))}finally{s.width=0,s.height=0}}async function St(e,t=480){try{let n=await createImageBitmap(e),r=Math.max(1,Math.round(n.height/n.width*t)),i=document.createElement("canvas");i.width=t,i.height=r;let l=i.getContext("2d");return l===null?(n.close(),null):(l.drawImage(n,0,0,t,r),n.close(),l.getImageData(0,0,t,r))}catch{return null}}var ne=(e,t,n)=>Math.min(n,Math.max(t,Math.round(e))),V=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function ve(e,t,n,r){let i=r.decode??(c=>createImageBitmap(c)),l=async()=>e.stillRead(await i(t),r.region??[0,0,1,1],r.detectorLimit),s;try{s=await l()}catch{try{await new Promise(c=>setTimeout(c,r.retryMs??300)),s=await l()}catch{return null}}let u=s.mrzBox;return u===void 0?null:{engine:r.engine,source:"live_mrz",format:n.format,lineCount:ne(n.lineCount,2,3),checkDigitsValid:!0,stillConfirmed:s.valid&&s.digest===n.digest,band:[V(u[0]),V(u[1]),V(Math.min(u[2],1-u[0])),V(Math.min(u[3],1-u[1]))],digest:n.digest,framesToValid:ne(n.framesToValid,1,1e3),msToValid:ne(n.msToValid,0,12e4)}}function kt(e){let t=null;return e?.then(n=>{t=n}),()=>t}var et=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]),tt=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,7,1,5,0,6,64,11,11]);function Le(e,t=globalThis){let n=t.WebAssembly?.validate;if(typeof n!="function")return{ok:!1,reason:"simd"};try{if(!n.call(t.WebAssembly,et)||!n.call(t.WebAssembly,tt))return{ok:!1,reason:"simd"}}catch{return{ok:!1,reason:"simd"}}if(typeof t.Worker!="function")return{ok:!1,reason:"worker"};if(typeof t.createImageBitmap!="function")return{ok:!1,reason:"bitmap"};let r=t.navigator?.deviceMemory;return typeof r=="number"&&r<e.minDeviceMemoryGb?{ok:!1,reason:"memory"}:{ok:!0}}function _e(e=globalThis){let t=e.navigator?.connection;return t?.saveData===!0||["slow-2g","2g","3g"].includes(t?.effectiveType??"")}var T=class extends Error{constructor(t){super(t),this.name="OcrEngineError",this.code=t}};function Te(){let e=t=>(t.close(),Promise.reject(new T("unsupported")));return{ready:Promise.resolve("unsupported"),busy:!1,bandRead:e,stillRead:e,layoutRead:e,dispose:()=>{}}}function Ee(e){let t;try{if(e.createWorker)t=e.createWorker();else if(e.workerUrl!==void 0)t=new Worker(e.workerUrl,{type:"module",name:"sekyro-ocr"});else return Te()}catch{return Te()}let n=new Map,r=0,i=!1,l=!1,s=!1;t.addEventListener("message",d=>{let g=d.data,C=n.get(g.id);C&&(n.delete(g.id),C.resolve(g))});let u=()=>{for(let d of n.values())d.reject(new T("error"));n.clear(),f()};t.addEventListener("error",u),t.addEventListener("messageerror",u);function c(d,g=[]){if(i)return Promise.reject(new T("disposed"));let C=++r;return new Promise((B,O)=>{n.set(C,{resolve:B,reject:O});try{t.postMessage({...d,id:C},g)}catch{n.delete(C),O(new T("error"))}})}function f(){if(!i){i=!0;try{t.postMessage({id:++r,kind:"dispose"})}catch{}t.terminate();for(let d of n.values())d.reject(new T("disposed"));n.clear()}}let p=(async()=>{let d=await c({kind:"init",baseUrl:e.baseUrl,salt:e.salt,detectorLimit:e.tuning.detectorLimit,maxDownloadMs:e.tuning.maxDownloadMs});if(d.kind==="failed")return d.reason;if(d.kind!=="ready")return"error";let g=await c({kind:"warmup"});return g.kind!=="ready"?"error":{warmupMs:g.warmupMs,downloadMs:d.downloadMs,cached:d.cached}})().catch(()=>"error"),b,S=new Promise(d=>{b=setTimeout(()=>d("timeout"),e.tuning.loadTimeoutMs)}),I=Promise.race([p,S]).then(d=>(clearTimeout(b),typeof d=="string"?f():s=!0,i&&typeof d!="string"?"error":d));(e.page===void 0?globalThis.addEventListener?globalThis:null:e.page)?.addEventListener("pagehide",f,{once:!0});async function w(d,g,C){if(i)throw g.close(),new T("disposed");if(!s)throw g.close(),new T("not_ready");if(l)throw g.close(),new T("busy");l=!0;let B;try{let O=new Promise((M,A)=>{B=setTimeout(()=>{A(new T("timeout")),f()},e.tuning.readTimeoutMs??1e4)}),P=await Promise.race([c(d,[g]),O]);if(P.kind===C){let{id:M,...A}=P;return A}throw new T(P.kind==="error"?P.code:P.kind==="failed"?P.reason:"error")}finally{clearTimeout(B),l=!1}}return{ready:I,get busy(){return l},bandRead:(d,g=e.tuning.detectorLimit)=>w({kind:"band",bitmap:d,detectorLimit:g},d,"band"),stillRead:(d,g,C=e.tuning.detectorLimit)=>w({kind:"still",bitmap:d,region:g,detectorLimit:C},d,"band"),layoutRead:(d,g)=>w({kind:"layout",bitmap:d,detectorLimit:g},d,"layout"),dispose:f}}var U="sekyro-ocr-1",re=e=>e!==null&&typeof e=="object"?e:{},v=(e,t,n,r)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:r,Oe=(e,t)=>typeof e=="boolean"?e:t,Pe=e=>{let t=typeof e=="string"?/^sekyro-ocr-(\d{1,4})$/.exec(e):null;return t?Number(t[1]):Number.POSITIVE_INFINITY};function Ae(e,t={}){let n=re(e),r=re(n.liveMrz),i=re(n.frontLock),l=Pe(t.engine??U),s=t.mode==="off",u=d=>d.enabled===!0?d.arm==="live"?"live":"control":null,c=u(r),f=u(i),p=(d,g)=>!s&&g==="live"&&Pe(d.minEngine??U)<=l,b=ye,S=p(r,c)?{detectorLimit:v(r.detectorLimit,320,1600,b.detectorLimit),bandMaxWidthPx:v(r.bandMaxWidthPx,320,4096,b.bandMaxWidthPx),minBandWidthPx:v(r.minBandWidthPx,0,4096,b.minBandWidthPx),bandTop:v(r.bandTop,0,.95,b.bandTop),minIntervalMs:v(r.minIntervalMs,0,5e3,b.minIntervalMs),stableReads:Math.round(v(r.stableReads,1,10,b.stableReads)),profileReads:Math.round(v(r.profileReads,1,100,b.profileReads)),maxReadMs:v(r.maxReadMs,50,6e4,b.maxReadMs),searchTimeoutMs:v(r.searchTimeoutMs,1e3,12e4,b.searchTimeoutMs),hint:Oe(r.hint,!0),stillConfirm:Oe(r.stillConfirm,!0)}:null,I=he,h=(d,g,C)=>v(i[d],g,C,I[d]),w=p(i,f)?{minLines:Math.round(h("minLines",1,50)),fillMin:h("fillMin",0,1),fillMax:h("fillMax",0,2),offsetMax:h("offsetMax",0,1),steadyFillDelta:h("steadyFillDelta",0,1),steadyOffsetDelta:h("steadyOffsetDelta",0,1),layoutShiftMax:h("layoutShiftMax",0,1),lineCountDelta:Math.round(h("lineCountDelta",0,50)),lockMs:h("lockMs",0,3e4),steadyMs:h("steadyMs",0,3e4),minFrames:Math.round(h("minFrames",1,100)),minIntervalMs:h("minIntervalMs",0,5e3),maxWidthPx:h("maxWidthPx",160,2048),detectorLimit:h("detectorLimit",320,1600),searchTimeoutMs:h("searchTimeoutMs",1e3,12e4)}:null;return{enabled:S!==null||w!==null,liveMrz:S,textLock:w,liveMrzArm:c,frontLockArm:f,load:{detectorLimit:S?.detectorLimit??w?.detectorLimit??b.detectorLimit,loadTimeoutMs:v(r.loadTimeoutMs,1e3,12e4,2e4),maxDownloadMs:v(r.maxDownloadMs,1e3,12e4,2e4),minDeviceMemoryGb:v(r.minDeviceMemoryGb,0,64,2)},reportSampleRate:v(r.reportSampleRate,0,1,1)}}function Be(e,t){return e.enabled?!(t.probe??Le)({minDeviceMemoryGb:e.load.minDeviceMemoryGb}).ok||(t.slow??_e)()?{ok:!1,reason:"unsupported"}:{ok:!0,engine:Ee({baseUrl:t.baseUrl,salt:t.salt,tuning:{detectorLimit:e.load.detectorLimit,maxDownloadMs:e.load.maxDownloadMs,loadTimeoutMs:e.load.loadTimeoutMs},...t.workerUrl!==void 0?{workerUrl:t.workerUrl}:{},...t.createWorker!==void 0?{createWorker:t.createWorker}:{},...t.page!==void 0?{page:t.page}:{}})}:{ok:!1,reason:"off"}}function nt(e=typeof navigator<"u"?navigator.userAgent:""){return/SamsungBrowser\//.test(e)?"samsung":/Firefox\/|FxiOS\//.test(e)?"firefox":/Chrome\/|CriOS\/|Chromium\//.test(e)&&!/Edg\/|OPR\//.test(e)?"chrome":/Safari\//.test(e)&&/Version\/|Mobile\//.test(e)&&!/Chrome\/|CriOS\//.test(e)?"safari":"other"}var W=e=>e===void 0||!Number.isFinite(e)?void 0:Math.min(6e5,Math.max(0,Math.round(e))),oe=(e,t,n)=>e===void 0||!Number.isFinite(e)?void 0:Math.min(n,Math.max(t,Math.round(e)));function Ie(e){let t=e.assist??null,n=e.load!==null&&e.load!==void 0&&typeof e.load=="object"?e.load:null,r=typeof e.load=="string"?e.load:null,i=t!==null?t.outcome:r==="unsupported"||r==="download"||r==="integrity"?r:r==="error"||r==="timeout"?"error":"off",l={kind:"live_mrz",platform:"web",engine:e.engine??U,arm:e.arm,capture:e.capture,outcome:i,reads:oe(t?.reads??0,0,1e4)??0,browser:e.browser??nt()},s=(u,c)=>{c!==void 0&&(l[u]=c)};return s("format",t?.format),s("framesToValid",oe(t?.framesToValid,1,1e4)),s("msToValid",W(t?.msToValid)),s("framesToLock",oe(t?.framesToLock,1,1e4)),s("msToLock",W(t?.msToLock)),s("msToCapture",W(e.msToCapture)),s("readP50Ms",W(t?.readP50Ms)),s("readP90Ms",W(t?.readP90Ms)),s("deviceClass",t?.deviceClass),n!==null&&(s("warmupMs",W(n.warmupMs)),s("downloadMs",W(n.downloadMs)),s("cached",n.cached)),s("stillConfirmed",e.stillConfirmed),s("typeMismatch",e.typeMismatch),l}function ae(e,t){return e===void 0?!1:t==="passport"?e!=="TD3":e==="TD3"}var rt=2;async function ot(e){let t=await import("./capture-session-doc-QQHDBZG4.js");return new t.CaptureSessionDoc(e)}function at(e){return{topLeft:{x:e.x,y:e.y},topRight:{x:e.x+e.width,y:e.y},bottomRight:{x:e.x+e.width,y:e.y+e.height},bottomLeft:{x:e.x,y:e.y+e.height}}}function it(e,t,n){let r=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let l=0;l<r.length;l+=1){let s=r[l],u=r[(l+1)%r.length];i+=s.x*u.y-u.x*s.y}return t>0&&n>0?Math.abs(i)/2/(t*n):0}function Nt(){import("./capture-session-doc-QQHDBZG4.js").then(e=>e.warmDocDetector()).catch(()=>{})}function Ut(e){return st(e,{}).handle}function st(e,t){let n=me(),r=pe({enabled:e.keepScreenAwake!==!1}),i=t.decode??(o=>createImageBitmap(o)),l=t.blurRefuseSharpnessMax??.16,s=t.now??(()=>performance.now()),u=e.documentType==="passport"||e.side==="single",c=Z(u?"singlePage":"twoSided",s());if(!u&&(e.side==="recto"||e.side==="verso")){let o=e.side==="recto"?"verso":"recto";c={...c,captured:{[o]:"server"},readSides:[o],current:e.side,phase:"flipCue",restPhase:"flipCue"}}let f="idle",p=null,b=null,S=!0,I=0,h=0,w=!1,d=!1,g="",C=null,B,O=null,P=[],M=t.webOcr!==void 0?Ae(t.webOcr.captureDocument,{mode:e.liveMrz?.mode??"auto"}):null,A=null,F=M===null||!M.enabled?"off":null,G=null,q=null,ie=new WeakMap,Y="";if(M!==null&&M.enabled&&t.webOcr!==void 0){let o=t.webOcr,a=Be(M,{baseUrl:e.liveMrz?.assetBaseUrl??o.baseUrl,salt:o.salt,...e.liveMrz?.workerUrl!==void 0?{workerUrl:e.liveMrz.workerUrl}:{},...o.createWorker!==void 0?{createWorker:o.createWorker}:{}});if(a.ok){A=a.engine;let m=new Se({textLock:M.textLock,liveMrz:M.liveMrz});G=m;let y=a.engine;y.ready.then(L=>{F=L,typeof L!="string"&&S&&m.setEngine(y)})}else F=a.reason}let z=o=>{let a=JSON.stringify(o);a!==Y&&(Y=a,n.emit("mrz",o))},se=(o,a)=>{let m=t.webOcr?.reports;if(m===void 0||M===null||o===void 0)return;let y=o.format==="ID-3"||o.side==="single"?"single":o.side==="verso"?"verso":"recto",L=y!=="recto"?M.liveMrzArm??M.frontLockArm:M.frontLockArm;if(L===null||Math.random()>=M.reportSampleRate)return;let _=o.via==="live_mrz"?q:null,x=()=>{let E=_?.value??null;m([Ie({arm:L,capture:y,assist:o.ocr??null,load:L==="control"?"off":F,...o.msToCapture!==void 0?{msToCapture:o.msToCapture}:{},...E!==null&&E.stillConfirmed!==void 0?{stillConfirmed:E.stillConfirmed}:{},...a!==void 0?{typeMismatch:ae(a.format,e.documentType==="passport"?"passport":"card")}:{}})])};_!==null&&_.value===null?Promise.race([_.promise,new Promise(E=>setTimeout(E,3e3))]).then(x):x()},N=o=>{!S||o===f||(f=o,r.setActive(o==="starting"||o==="scanning"),n.emit("state",o))},We=(o,a)=>a===void 0?null:u?"single":o.captured.recto===a?"recto":o.captured.verso===a?"verso":null,Fe=o=>({phase:o.phase,captured:u?o.captured.recto!==void 0?["single"]:[]:["recto","verso"].filter(a=>o.captured[a]!==void 0),expected:u?null:o.current??null,notice:o.notice??null,lastShot:We(o,o.lastShot),manualShutter:o.manualShutter,torchAvailable:p?.torchAvailable()??!1,torch:d}),ue=()=>{let o=p;o!==null&&o.captureNow().catch(()=>R({type:"captureFailed",at:s()}))};function R(o){if(!S)return;let a=c;c=xe(c,o),c.phase==="capturing"&&a.phase!=="capturing"&&Promise.resolve().then(ue),c.phase==="result"&&a.phase!=="result"&&(N("done"),le());let m=Fe(c),y=JSON.stringify(m);y!==g&&(g=y,n.emit("scan",m))}function le(){O!==null&&clearInterval(O),O=null;for(let o of P.splice(0))o();p?.destroy(),p=null,r.setActive(!1)}let ce=()=>p?.captureReport?.(),Q=!1,de=(o,a)=>{if(!(o===void 0||t.onFaceReport===void 0))try{t.onFaceReport(o,a)}catch{}},H=o=>{Y="",!(p===null||c.phase==="reading"||c.phase==="result")&&(Q=!1,p.rearm(u?"single":c.current??o))},ze=async(o,a,m,y)=>{if(q=null,y!==void 0&&A!==null&&M?.liveMrz?.hint===!0){let D={promise:ve(A,o,y,{engine:U,detectorLimit:M.liveMrz.detectorLimit}).catch(()=>null),value:null};D.promise.then(k=>{D.value=k}),q=D}y!==void 0&&ae(y.format,e.documentType==="passport"?"passport":"card")&&z({state:"mismatch",format:y.format});let L=ce();de(L,"captured"),Q=!0,se(L,y);let _=m===void 0?C:m===null?null:{quad:at(m),frameWidth:0,frameHeight:0,inStill:!0},x={decoded:null},E=()=>(x.decoded??(x.decoded=Promise.resolve().then(()=>i(o)).catch(()=>null)),x.decoded);try{await Ne(o,a,_,E,q)}finally{x.decoded!==null&&(await x.decoded)?.close()}},Ne=async(o,a,m,y,L)=>{let _=`shot-${I+=1}`;if(R({type:"captured",id:_,at:s()}),e.haptics!==!1)try{globalThis.navigator?.vibrate?.(30)}catch{}if(!w&&l>0){let D=await(t.measureSharpness!==void 0?t.measureSharpness(o,m):y().then(k=>k===null?-1:be(k,j(m?.quad??null,m?.inStill===!0?k:{width:m?.frameWidth??0,height:m?.frameHeight??0},k)))).catch(()=>-1);if(!S)return;if(Number.isFinite(D)&&D>=0&&D<l){w=!0;let k=u?"recto":c.current??(c.captured.recto===void 0?"recto":"verso");R({type:"readFailed",side:k,id:_,issue:"blurry"}),H(k);return}}w=!1;let x;if(u)x="single";else{let D=c.current,k=await(t.classify!==void 0?t.classify(o):y().then(X=>X===null?D??"recto":m?.inStill===!0?te(X,480,null,!0):te(X,480,j(m?.quad??null,{width:m?.frameWidth??0,height:m?.frameHeight??0},X)))).catch(()=>D??"recto");if(!S)return;if(c.captured[k]!==void 0&&h<rt){h+=1,R({type:"duplicate",id:_,side:k}),H(k==="recto"?"verso":"recto");return}x=c.captured[k]!==void 0&&D!==void 0?D:k,h=0,R({type:"classified",id:_,side:x})}let E=x==="verso"?"verso":"recto";try{let D=t.encode!==void 0?await t.encode(o):await y().then(k=>{if(k===null)throw new Error("the still could not be decoded");return $(k)});if(!S)return;L!==null&&ie.set(D.blob,L),n.emit("captured",{image:D.blob,side:x,documentType:e.documentType,...e.issuer!==void 0?{issuer:e.issuer}:{},width:D.width,height:D.height,previewDataUrl:a}),t.deferRead!==!0&&R({type:"readOk",side:E})}catch{R({type:"readFailed",side:E,id:_,issue:"technical"}),n.emit("error",{kind:"generic",retryable:!0})}H(E==="recto"?"verso":"recto")},Ue=o=>{P.push(o.on("statechange",({state:a})=>{a==="preflight"||a==="acquiring"?N("starting"):a==="positioning"?N("scanning"):a==="captured"?N("captured"):a==="error"&&N("error")}),o.on("feedback",({key:a,reticle:m})=>n.emit("feedback",{key:a,reticle:m})),o.on("checks",a=>{n.emit("gate",{progress:a.p,quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight,...a.guide!==void 0?{guide:{detected:a.guide.detected,fill:a.guide.fill,offsetX:a.guide.offsetX??0,offsetY:a.guide.offsetY??0}}:{}});let m=a.ocr?.mrz;m!==void 0&&(m.state==="fallback"?z({state:"fallback",reason:m.reason}):m.state==="valid"?z({state:"valid",format:m.format}):m.state==="reading"?z({state:"reading",...m.format?{format:m.format}:{},...m.coach?{coach:m.coach}:{}}):z({state:"searching"}));let y=a.quad===null?0:it(a.quad,a.frameWidth,a.frameHeight);C=a.quad===null?null:{quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight},R({type:"report",report:{present:a.quad!==null&&a.plausible||a.guide?.detected===!0,ready:a.ready===!0,locking:a.p>=.5,areaFrac:y},at:s()})}),o.on("error",({kind:a,retryable:m})=>n.emit("error",{kind:fe(a),retryable:m})),o.on("artifacts",a=>{ze(a.keyframe,a.previewDataUrl,a.docRegion,a.liveMrz)}))},K=()=>(b??(b=(async()=>{if(S){if(p===null){let o=await(t.createEngine??ot)({...t.engineOptions??{},...B!==void 0?{guide:B}:{},video:e.video,format:ge(e.documentType),side:u?"single":e.side??"recto",autoCapture:!1,...G!==null?{ocr:G}:{}});if(!S){o.destroy();return}p=o,Ue(o);let a=t.tickMs??500;a>0&&(O=setInterval(()=>R({type:"tick",at:s()}),a))}R({type:"clockRestart"}),M!==null&&M.liveMrzArm==="live"&&(F==="unsupported"||F==="off")&&z({state:"fallback",reason:F}),await p.start()}})().finally(()=>{b=null})),b);return{handle:{get state(){return f},on:(o,a)=>n.on(o,a),start:K,retry:()=>{if(p===null&&c.phase==="result"){R({type:"retake"}),h=0,w=!1,K();return}if(p!==null&&f!=="error"){R({type:"retake"}),h=0,w=!1,p.rearm(u?"single":void 0);return}K()},setSide:o=>{u||o==="single"||(c.current!==o&&(c={...c,current:o}),R({type:"clockRestart"}),c.phase!=="reading"&&c.phase!=="result"&&p?.rearm(o))},shutter:ue,focusAt:(o,a)=>{p?.focusAt?.(o,a)},setGuide:o=>{B=o,p?.setGuide?.(o)},setTorch:o=>{d=o,p?.setTorch(o),R({type:"tick",at:s()})},destroy:()=>{if(S&&p!==null&&f!=="done"){let o=ce();!Q&&o!==void 0&&o.ticks>0&&de(o,"abandoned"),se(o,void 0)}S=!1,le(),G?.setEngine(null),A?.dispose(),A=null,n.clear()}},setFlowState:o=>{(c.phase==="reading"||c.phase==="result")&&N(o==="done"&&c.phase!=="result"?"scanning":o)},settle:(o,a)=>{let m=o==="verso"?"verso":"recto";R(a.ok?{type:"readOk",side:m}:{type:"readFailed",side:m,issue:a.issue}),a.ok||H(m)},takeDeviceRead:o=>ie.get(o.image)?.value??null}}export{dt as a,pt as b,ft as c,gt as d,bt as e,ht as f,De as g,Z as h,xe as i,Je as j,Ze as k,St as l,ve as m,kt as n,U as o,Ae as p,Be as q,nt as r,Ie as s,ae as t,rt as u,Nt as v,Ut as w,st as x};
|