@sekyro/web 0.1.0-rc.24 → 0.1.0-rc.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +32 -2
  3. package/dist/{capture-session-doc-RIBBH3M4.js → capture-session-doc-WZMI5XPE.js} +1 -1
  4. package/dist/{capture-session-v3-CPHzDT7E.d.cts → capture-session-v3-BKSjJ6L0.d.cts} +1 -1
  5. package/dist/{capture-session-v3-TUPtnvmu.d.ts → capture-session-v3-C1I_GLC9.d.ts} +1 -1
  6. package/dist/challenge-frame-NUGPTWFP.js +1 -0
  7. package/dist/{chunk-MXWLCDFX.js → chunk-4DEPREJ3.js} +1 -1
  8. package/dist/{chunk-LBH6KGTV.js → chunk-65JZHKVG.js} +1 -1
  9. package/dist/{chunk-FLA42JCK.js → chunk-7MZW3FFH.js} +1 -1
  10. package/dist/chunk-DVTK2DGX.js +1 -0
  11. package/dist/chunk-GPFAPAS6.js +3 -0
  12. package/dist/chunk-HVW2AB35.js +1 -0
  13. package/dist/{chunk-IFLOS5OT.js → chunk-LLX2CKZ3.js} +1 -1
  14. package/dist/chunk-LV23FCYP.js +1 -0
  15. package/dist/{chunk-TDLIXFDT.js → chunk-NFHLJOHW.js} +1 -1
  16. package/dist/{chunk-5YVQIHQA.js → chunk-OVP7FAMJ.js} +1 -1
  17. package/dist/{chunk-XI5FXEKC.js → chunk-XOTKATN6.js} +1 -1
  18. package/dist/chunk-ZCW6PNUX.js +1 -0
  19. package/dist/client/index.cjs +1 -1
  20. package/dist/client/index.d.cts +3 -3
  21. package/dist/client/index.d.ts +3 -3
  22. package/dist/client/index.js +1 -1
  23. package/dist/core/index.cjs +1 -1
  24. package/dist/core/index.d.cts +3 -3
  25. package/dist/core/index.d.ts +3 -3
  26. package/dist/core/index.js +1 -1
  27. package/dist/create-document-capture-OXPLKHOF.js +1 -0
  28. package/dist/{create-verification-acQzNRiB.d.ts → create-verification-7wPXJN_P.d.ts} +287 -120
  29. package/dist/{create-verification-DF60lg8Y.d.cts → create-verification-YeuI7_B0.d.cts} +287 -120
  30. package/dist/{detector-scanic-YCDNLCGV.js → detector-scanic-23DAYT3H.js} +1 -1
  31. package/dist/{icao-gate-CX0chQMM.d.cts → icao-gate-BK8TGaCk.d.ts} +1 -1
  32. package/dist/{icao-gate-VwsQo8Bq.d.ts → icao-gate-pD2dUV3P.d.cts} +1 -1
  33. package/dist/{icao-policy-WnG2OSyp.d.cts → icao-policy-CdR6PFHS.d.cts} +2 -2
  34. package/dist/{icao-policy-B02jDiox.d.ts → icao-policy-qJpZOOOu.d.ts} +2 -2
  35. package/dist/index.cjs +3 -1
  36. package/dist/index.d.cts +9 -9
  37. package/dist/index.d.ts +9 -9
  38. package/dist/index.js +1 -1
  39. package/dist/internal/index.cjs +3 -1
  40. package/dist/internal/index.d.cts +69 -114
  41. package/dist/internal/index.d.ts +69 -114
  42. package/dist/internal/index.js +1 -1
  43. package/dist/plan-runner-EP26JU6A.js +1 -0
  44. package/dist/{types-1s8CQrEN.d.ts → types-DB-cZTSn.d.cts} +156 -29
  45. package/dist/{types-1s8CQrEN.d.cts → types-DB-cZTSn.d.ts} +156 -29
  46. package/dist/upload-file-EGXXM6TQ.js +1 -0
  47. package/package.json +1 -1
  48. package/sbom.cdx.json +10 -10
  49. package/dist/chunk-DMOGKGDS.js +0 -1
  50. package/dist/chunk-IC6TI6GV.js +0 -1
  51. package/dist/chunk-MQBX4DQQ.js +0 -1
  52. package/dist/chunk-QY6TJCOJ.js +0 -1
  53. package/dist/chunk-TDCLQRT4.js +0 -1
  54. package/dist/create-document-capture-XQURFZZK.js +0 -1
  55. package/dist/plan-runner-LDV4PYN7.js +0 -1
  56. package/dist/turnstile-52B3RFXD.js +0 -1
  57. package/dist/upload-file-UYXOHCRG.js +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @sekyro/web
2
2
 
3
+ ## 0.1.0-rc.26
4
+
5
+ ### Minor Changes
6
+
7
+ - 246b0f3: Proof of address and the driver's license. A `poa` step in the flow is the new `proof_of_address` step (`ProofOfAddressStepHandle`): it shows the accepted documents the server resolved for the person's country (`rule`: each kind with its own `maxAgeDays` and `earliestIssueDate`), the name rule and the phase (`document`, or `holder_letter` when the bill is in another person's name). `uploadPages(files)` sends 1 to 3 images or one PDF (the new `document_file` media kind, `application/pdf`), `uploadHolderLetter(files)` sends the holder's letter, and `capturePage({ video })` takes one photo per page on the rear camera. On a desktop an upload step stays on the desktop; a camera step continues on a phone. `drivers_license` joins the accepted document types: two faces on the card frame, no live MRZ reading, offered only when the flow lists it. New types: `PoaKind`, `PoaReason`, `PoaNameMatchMode`, `PoaRuleSource`, `HostedProofOfAddressView`, `HostedPoaRuleView`, `HostedPoaRuleKindView`, `PoaInput`, `ProofOfAddressSnapshot`, `ProofOfAddressStepHandle`, `PageCaptureHandle`; `CheckType` gains `poa`, `MediaKind` gains `document_file`, `IdNumberType` gains `drivers_license` (Mauritania: the 8-digit number; elsewhere 4 to 20 letters or digits). A document photo of a driver's license sends `documentType: "drivers_license"` in the `doc_ocr` input (`DocOcrInput.documentType`), so the server reads it with its document reader. When the view says `proofOfAddress.licenceAddressAccepted`, `useLicenceAddress()` passes the step with the address the driver's license gave (`PoaLicenceInput`, no media).
8
+
9
+ ### Patch Changes
10
+
11
+ - cc7eedb: The challenge frame binds its token to the public session id (`ses_<hex>`), the subject the server checks, instead of the bare id from the session view.
12
+
13
+ ## 0.1.0-rc.25
14
+
15
+ ### Minor Changes
16
+
17
+ - 0d23a56: The liveness attestation now runs in the Sekyro security check frame. `createVerification` asks a hidden frame served from `https://verify.sekyro.ai/challenge` for the token instead of loading Cloudflare Turnstile in your page, and the token is bound to the session and to your page's origin. If your page has a Content-Security-Policy, allow `frame-src https://verify.sekyro.ai`; the `challenges.cloudflare.com` entries in `script-src`, `frame-src` and `connect-src` are no longer needed.
18
+
19
+ - `HostedSessionView.challenge: { url, siteKey } | null` (`HostedChallengeView`) replaces `turnstileSiteKey`.
20
+ - The liveness `attestation` body no longer carries `siteKey`: it is `{ channel: 'hosted_web', turnstileToken }`, or `{ channel: 'hosted_web' }` when no token was obtained.
21
+ - When the frame produces no token, the submission records `input.capture.attestationError`, the SDK reports one `attestation` capture issue, and a result with `reasonCode: 'attestation'` carries `attestationError` (`ChallengeErrorCode`): `challenge_frame_blocked`, `challenge_script_blocked`, `site_key_rejected`, `challenge_failed`, `timeout`, `embedder_opaque` or `aborted`. A blocked frame also prints one console line naming the `frame-src` to allow.
22
+ - Timing is unchanged: the token is fetched when the camera starts, a failed challenge runs once more on a fresh frame, the submission waits at most 30 s for it and is sent without one as the last resort.
23
+ - A challenge that failed earlier (for example the prefetch at camera start on a blocked frame) still sets `input.capture.attestationError` and the result's `attestationError` when the submission's own challenge does not finish within the 30 s wait.
24
+
3
25
  ## 0.1.0-rc.24
4
26
 
5
27
  ### Patch Changes
package/README.md CHANGED
@@ -128,17 +128,47 @@ it again; closing or reloading mid-flow posts `session.cancelled`), so confirm t
128
128
  outcome server-side. Keep one popup per page: call `close()` on the previous handle
129
129
  before opening another.
130
130
 
131
+ ## Attestation
132
+
133
+ Before it submits the liveness capture, `createVerification` obtains an attestation token from the
134
+ Sekyro security check frame: a hidden 1×1 frame served from `https://verify.sekyro.ai/challenge`
135
+ (`HostedSessionView.challenge.url`) that runs the challenge and answers this page only. The token is
136
+ bound to the session and to your page's origin. Nothing from Cloudflare loads in your page, so
137
+ `challenges.cloudflare.com` is no longer needed in your Content-Security-Policy. A page with a CSP
138
+ allows the frame:
139
+
140
+ ```
141
+ frame-src https://verify.sekyro.ai
142
+ ```
143
+
144
+ The SDK fetches the token when the camera starts, waits at most 30 s for it after the uploads finish,
145
+ and runs a failed challenge once more on a fresh frame. Without a token the capture is still
146
+ submitted and the server decides. When the frame produced no token, a result with
147
+ `reasonCode: 'attestation'` carries `attestationError`:
148
+
149
+ | `attestationError` | What happened |
150
+ |---|---|
151
+ | `challenge_frame_blocked` | The frame did not load: add `frame-src https://verify.sekyro.ai` to your CSP (the SDK also prints this once in the console), or a browser extension or proxy blocked it. |
152
+ | `challenge_script_blocked` | The challenge script could not load inside the frame (a network filter between the browser and Cloudflare). |
153
+ | `challenge_failed` | The challenge could not clear this browser. |
154
+ | `timeout` | The challenge did not finish in 30 s. |
155
+ | `site_key_rejected` | The session and the frame disagree on the key (on our side). |
156
+ | `embedder_opaque` | The SDK runs in a document without an origin (a sandboxed frame or a `data:` page). |
157
+
158
+ A result with `reasonCode: 'attestation'` and no `attestationError` means the server refused the
159
+ token: ask the person to reload and try again.
160
+
131
161
  ## Entry points
132
162
 
133
163
  | Export | Contents | Public API |
134
164
  |---|---|---|
135
- | `@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 |
165
+ | `@sekyro/web` | **The partner API**: `createVerification` (consent → early registry → liveness capture → upload → attestation (the security check frame) → `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 |
136
166
  | `@sekyro/web/core` | Framework-free capture: `CaptureSessionV3`, `createDetector`, `FaceGateV3`, frame quality, device profile, `media`/`keyframe`/`messages`/`ClipRecorder` (calibration-pinned v1 port), camera constraints | Yes |
137
167
  | `@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 |
138
168
  | `@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 |
139
169
  | `@sekyro/web/client` | Typed client for the hosted session API: `HostedClient`, error codes, check input/view types | Yes |
140
170
  | `@sekyro/web/popup` | Partner-facing popup/redirect embed (`open`, `SekyroEvent`) | Yes |
141
- | `@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 |
171
+ | `@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, the security check frame client `executeChallenge`), consumed by Sekyro AI's hosted page / `@sekyro/react` only. No semver guarantees; may change in any release | No |
142
172
 
143
173
  Every entry ships ESM + CJS + `.d.ts` (`tsup`). `./core` deliberately does **not**
144
174
  re-export the document scanner (that lives only under `./internal`) nor the worker
@@ -1 +1 @@
1
- import{A as b,B as c,C as d,D as e,E as f,F as g,G as h,H as i,I as j,J as k,z as a}from"./chunk-FLA42JCK.js";import"./chunk-G6LKLN4U.js";import"./chunk-SMKCBUJL.js";import"./chunk-MXWLCDFX.js";import"./chunk-TDLIXFDT.js";import"./chunk-POIQGEZM.js";import"./chunk-CPUECYAJ.js";import"./chunk-FPXL63KZ.js";import"./chunk-IFLOS5OT.js";import"./chunk-DK5YPBDQ.js";export{k as CAPTURE_CANDIDATE_SPACING_MS,j as CAPTURE_EXTRA_CANDIDATES,h as CaptureSessionDoc,c as DOC_BLACK_FRAME_LUMA,d as DOC_BLACK_FRAME_TICKS,e as DOC_CADENCE_HZ,b as DOC_FIRST_FRAME_MS,f as DOC_SHUTTER_DEFAULTS,i as passportBandOf,g as resolveDocShutterTuning,a as warmDocDetector};
1
+ import{A as b,B as c,C as d,D as e,E as f,F as g,G as h,H as i,I as j,J as k,z as a}from"./chunk-7MZW3FFH.js";import"./chunk-G6LKLN4U.js";import"./chunk-SMKCBUJL.js";import"./chunk-4DEPREJ3.js";import"./chunk-NFHLJOHW.js";import"./chunk-POIQGEZM.js";import"./chunk-CPUECYAJ.js";import"./chunk-FPXL63KZ.js";import"./chunk-LLX2CKZ3.js";import"./chunk-DK5YPBDQ.js";export{k as CAPTURE_CANDIDATE_SPACING_MS,j as CAPTURE_EXTRA_CANDIDATES,h as CaptureSessionDoc,c as DOC_BLACK_FRAME_LUMA,d as DOC_BLACK_FRAME_TICKS,e as DOC_CADENCE_HZ,b as DOC_FIRST_FRAME_MS,f as DOC_SHUTTER_DEFAULTS,i as passportBandOf,g as resolveDocShutterTuning,a as warmDocDetector};
@@ -1,4 +1,4 @@
1
- import { a_ as ScreenRampReport, aR as CaptureProvenance, aX as ScreenRampChallenge, aY as ScreenRampPaint } from './types-1s8CQrEN.cjs';
1
+ import { ba as ScreenRampReport, b1 as CaptureProvenance, b7 as ScreenRampChallenge, b8 as ScreenRampPaint } from './types-DB-cZTSn.cjs';
2
2
  import { F as FaceObservation, b as Detector, W as WorkerLike } from './detect-worker-CHqsPJoM.cjs';
3
3
 
4
4
  /** MP4-first ladder: one container (H.264 MP4) covers iOS/macOS Safari + Chrome 130+.
@@ -1,4 +1,4 @@
1
- import { a_ as ScreenRampReport, aR as CaptureProvenance, aX as ScreenRampChallenge, aY as ScreenRampPaint } from './types-1s8CQrEN.js';
1
+ import { ba as ScreenRampReport, b1 as CaptureProvenance, b7 as ScreenRampChallenge, b8 as ScreenRampPaint } from './types-DB-cZTSn.js';
2
2
  import { F as FaceObservation, b as Detector, W as WorkerLike } from './detect-worker-CHqsPJoM.js';
3
3
 
4
4
  /** MP4-first ladder: one container (H.264 MP4) covers iOS/macOS Safari + Chrome 130+.
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e}from"./chunk-HVW2AB35.js";export{c as CHALLENGE_EXECUTE_TIMEOUT_MS,b as CHALLENGE_READY_TIMEOUT_MS,a as ChallengeError,e as executeChallenge,d as resetChallengeFrameForTests};
@@ -1 +1 @@
1
- import{c as x}from"./chunk-TDLIXFDT.js";import{b}from"./chunk-FPXL63KZ.js";var T=480,y=Object.freeze({MIN_AREA_FRAC:.15,EDGE_CLIP_MARGIN_PX:4,STABLE_TICKS:3,IOU_STABLE_MIN:.85,RISE_PER_S:.9,FALL_PER_S:.25,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,ID3_BAND_MIN_WIDTH_FRAC:.55,ID3_BAND_ASPECT_MIN:4,ID3_BAND_ASPECT_MAX:40}),p=e=>Math.min(1,Math.max(0,e));function E(e,o,t){let n=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let s=0;s<4;s++){let r=n[s],c=n[(s+1)%4];i+=r.x*c.y-c.x*r.y}let a=o*t;return a>0?Math.abs(i/2)/a:0}function I(e,o){let t=D(e),n=D(o),i=Math.max(t.x1,n.x1),a=Math.max(t.y1,n.y1),s=Math.min(t.x2,n.x2),r=Math.min(t.y2,n.y2),c=Math.max(0,s-i)*Math.max(0,r-a),u=(t.x2-t.x1)*(t.y2-t.y1),_=(n.x2-n.x1)*(n.y2-n.y1),m=u+_-c;return m>0?c/m:0}function R(e){let o=D(e);return{width:o.x2-o.x1,height:o.y2-o.y1}}function D(e){let o=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft];return{x1:Math.min(...o.map(t=>t.x)),y1:Math.min(...o.map(t=>t.y)),x2:Math.max(...o.map(t=>t.x)),y2:Math.max(...o.map(t=>t.y))}}function M(e){let o=Math.hypot(e.topRight.x-e.topLeft.x,e.topRight.y-e.topLeft.y),t=Math.hypot(e.bottomRight.x-e.bottomLeft.x,e.bottomRight.y-e.bottomLeft.y),n=Math.hypot(e.bottomLeft.x-e.topLeft.x,e.bottomLeft.y-e.topLeft.y),i=Math.hypot(e.bottomRight.x-e.topRight.x,e.bottomRight.y-e.topRight.y),a=(o+t)/2,s=(n+i)/2;return a<=0||s<=0?0:Math.max(a,s)/Math.min(a,s)}var d=class{constructor(o,t={}){this.p=0;this.lastTickAt=null;this.lastQuad=null;this.streak=0;this.format=o,this.t={...y,...t}}reset(){this.p=0,this.lastTickAt=null,this.lastQuad=null,this.streak=0}tick(o){let{quad:t,quality:n,timestampMs:i}=o,a=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let s=null;if(t===null)s="dcv1.no_doc";else if(this.format==="ID-3"){let h=R(t),f=h.height>0?h.width/h.height:0;h.width<this.t.ID3_BAND_MIN_WIDTH_FRAC*o.frameWidth?s="dcv1.come_closer":this.edgeClipped(t,o.frameWidth,o.frameHeight)?s="dcv1.fit_document":(f<this.t.ID3_BAND_ASPECT_MIN||f>this.t.ID3_BAND_ASPECT_MAX)&&(s="dcv1.wrong_shape")}else E(t,o.frameWidth,o.frameHeight)<this.t.MIN_AREA_FRAC?s="dcv1.come_closer":this.edgeClipped(t,o.frameWidth,o.frameHeight)?s="dcv1.fit_document":x(this.format,M(t))||(s="dcv1.wrong_shape");let r=s===null,c=p(n.exposure)>=this.t.GUIDE_EXPOSURE,u=p(n.sharpness)>=this.t.GUIDE_SHARPNESS,_=c&&u;if(r&&_&&t!==null){let h=this.lastQuad===null||I(t,this.lastQuad)>=this.t.IOU_STABLE_MIN;this.streak=h?this.streak+1:1}else this.streak=0;this.lastQuad=t;let m=r&&_;this.p=p(this.p+(m?this.t.RISE_PER_S:-this.t.FALL_PER_S)*a);let A=m&&this.streak>=this.t.STABLE_TICKS,l;if(s!==null)l=s;else if(c)u?l="dcv1.hold_still":l="dcv1.steady";else{let h=(b[0]+b[1])/2;l=n.meanLuma<h?"dcv1.more_light":"dcv1.too_bright"}return{at:i,quad:t,plausible:r,p:this.p,guidanceKey:l,ready:A,stableTicks:this.streak}}edgeClipped(o,t,n){let i=this.t.EDGE_CLIP_MARGIN_PX;return[o.topLeft,o.topRight,o.bottomRight,o.bottomLeft].some(s=>s.x<=i||s.y<=i||s.x>=t-i||s.y>=n-i)}};export{T as a,y as b,E as c,I as d,R as e,d as f};
1
+ import{c as x}from"./chunk-NFHLJOHW.js";import{b}from"./chunk-FPXL63KZ.js";var T=480,y=Object.freeze({MIN_AREA_FRAC:.15,EDGE_CLIP_MARGIN_PX:4,STABLE_TICKS:3,IOU_STABLE_MIN:.85,RISE_PER_S:.9,FALL_PER_S:.25,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,ID3_BAND_MIN_WIDTH_FRAC:.55,ID3_BAND_ASPECT_MIN:4,ID3_BAND_ASPECT_MAX:40}),p=e=>Math.min(1,Math.max(0,e));function E(e,o,t){let n=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let s=0;s<4;s++){let r=n[s],c=n[(s+1)%4];i+=r.x*c.y-c.x*r.y}let a=o*t;return a>0?Math.abs(i/2)/a:0}function I(e,o){let t=D(e),n=D(o),i=Math.max(t.x1,n.x1),a=Math.max(t.y1,n.y1),s=Math.min(t.x2,n.x2),r=Math.min(t.y2,n.y2),c=Math.max(0,s-i)*Math.max(0,r-a),u=(t.x2-t.x1)*(t.y2-t.y1),_=(n.x2-n.x1)*(n.y2-n.y1),m=u+_-c;return m>0?c/m:0}function R(e){let o=D(e);return{width:o.x2-o.x1,height:o.y2-o.y1}}function D(e){let o=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft];return{x1:Math.min(...o.map(t=>t.x)),y1:Math.min(...o.map(t=>t.y)),x2:Math.max(...o.map(t=>t.x)),y2:Math.max(...o.map(t=>t.y))}}function M(e){let o=Math.hypot(e.topRight.x-e.topLeft.x,e.topRight.y-e.topLeft.y),t=Math.hypot(e.bottomRight.x-e.bottomLeft.x,e.bottomRight.y-e.bottomLeft.y),n=Math.hypot(e.bottomLeft.x-e.topLeft.x,e.bottomLeft.y-e.topLeft.y),i=Math.hypot(e.bottomRight.x-e.topRight.x,e.bottomRight.y-e.topRight.y),a=(o+t)/2,s=(n+i)/2;return a<=0||s<=0?0:Math.max(a,s)/Math.min(a,s)}var d=class{constructor(o,t={}){this.p=0;this.lastTickAt=null;this.lastQuad=null;this.streak=0;this.format=o,this.t={...y,...t}}reset(){this.p=0,this.lastTickAt=null,this.lastQuad=null,this.streak=0}tick(o){let{quad:t,quality:n,timestampMs:i}=o,a=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let s=null;if(t===null)s="dcv1.no_doc";else if(this.format==="ID-3"){let h=R(t),f=h.height>0?h.width/h.height:0;h.width<this.t.ID3_BAND_MIN_WIDTH_FRAC*o.frameWidth?s="dcv1.come_closer":this.edgeClipped(t,o.frameWidth,o.frameHeight)?s="dcv1.fit_document":(f<this.t.ID3_BAND_ASPECT_MIN||f>this.t.ID3_BAND_ASPECT_MAX)&&(s="dcv1.wrong_shape")}else E(t,o.frameWidth,o.frameHeight)<this.t.MIN_AREA_FRAC?s="dcv1.come_closer":this.edgeClipped(t,o.frameWidth,o.frameHeight)?s="dcv1.fit_document":x(this.format,M(t))||(s="dcv1.wrong_shape");let r=s===null,c=p(n.exposure)>=this.t.GUIDE_EXPOSURE,u=p(n.sharpness)>=this.t.GUIDE_SHARPNESS,_=c&&u;if(r&&_&&t!==null){let h=this.lastQuad===null||I(t,this.lastQuad)>=this.t.IOU_STABLE_MIN;this.streak=h?this.streak+1:1}else this.streak=0;this.lastQuad=t;let m=r&&_;this.p=p(this.p+(m?this.t.RISE_PER_S:-this.t.FALL_PER_S)*a);let A=m&&this.streak>=this.t.STABLE_TICKS,l;if(s!==null)l=s;else if(c)u?l="dcv1.hold_still":l="dcv1.steady";else{let h=(b[0]+b[1])/2;l=n.meanLuma<h?"dcv1.more_light":"dcv1.too_bright"}return{at:i,quad:t,plausible:r,p:this.p,guidanceKey:l,ready:A,stableTicks:this.streak}}edgeClipped(o,t,n){let i=this.t.EDGE_CLIP_MARGIN_PX;return[o.topLeft,o.topRight,o.bottomRight,o.bottomLeft].some(s=>s.x<=i||s.y<=i||s.x>=t-i||s.y>=n-i)}};export{T as a,y as b,E as c,I as d,R as e,d as f};
@@ -1 +1 @@
1
- import{a as Y,d as ee,e as O,f as te,g as ne}from"./chunk-7QZWBDI5.js";import{C as X,a as j}from"./chunk-5YVQIHQA.js";import{f as Q,l as Z}from"./chunk-CPUECYAJ.js";import{c as $}from"./chunk-TSA6GHUG.js";import{c as J,h as C}from"./chunk-FSSMUAKC.js";var ue=12e4,re=13e4,le=3e3,fe=1200,P=Symbol.for("@sekyro/web.preload.v1");function g(){let e=globalThis;return e[P]??(e[P]=new Map),e[P]}function S(e){let n=(e??J).replace(/\/+$/,"");return n===""?"/":n}function se(e){let n=g(),r=n.get(e);return r===void 0&&(r={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},n.set(e,r)),r}function A(e,n){if(e.status!==n){e.status=n;for(let r of[...e.listeners])r(n)}}var x=e=>C({preferred:["blaze"],v3AssetBaseUrl:e,blazeInitTimeoutMs:ue}),F=x;function Pe(e){F=e??x}function Ae(){for(let e of g().values())e.detector?.destroy();g().clear(),F=x}function pe(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function me(){return navigator.connection?.saveData===!0}function ve(e){let n=window;if(typeof n.requestIdleCallback=="function"){let s=n.requestIdleCallback(e,{timeout:le});return()=>n.cancelIdleCallback?.(s)}let r=setTimeout(e,fe);return()=>clearTimeout(r)}function ge(e,n){let r,s=new Promise(i=>{r=i}),m=!1,d=()=>{},u={promise:s,settle:i=>{m||(m=!0,d(),e.scheduled===u&&(e.scheduled=null),r(i))}};return e.scheduled=u,d=ve(()=>{m||u.settle(I(e,n))}),s}function I(e,n){if((e.status==="loading"||e.status==="ready")&&e.promise!==null)return e.promise;A(e,"loading");let r=new Promise(i=>i(F(n)));e.detectorPromise=r;let s,m=new Promise((i,f)=>{s=setTimeout(()=>{r.then(h=>h.destroy(),()=>{}),f(new Error(`detector preload exceeded ${re} ms`))},re)}),u=Promise.race([r,m]).then(i=>e.detectorPromise!==r?(i.destroy(),e.status):(e.detector=i,A(e,"ready"),"ready"),i=>(e.detectorPromise===r&&(e.detectorPromise=null,e.detector=null,A(e,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",i)),e.status)).finally(()=>clearTimeout(s));return e.promise=u,e.scheduled?.settle(u),u}function we(e={}){if(!pe())return Promise.resolve("idle");let n=S(e.assetBaseUrl),r=se(n);return e.respectSaveData===!0&&me()?Promise.resolve(r.status):(r.status==="loading"||r.status==="ready")&&r.promise!==null?r.promise:e.idle===!0?r.scheduled?.promise??ge(r,n):I(r,n)}function ke(e){return g().get(S(e))?.status??"idle"}function De(e,n){let r=se(S(n));return r.listeners.add(e),()=>{r.listeners.delete(e)}}function _e(e){let n=g().get(S(e));n!==void 0&&(n.scheduled?.settle("idle"),n.detector?.destroy(),n.detector=null,n.detectorPromise=null,n.promise=null,A(n,"idle"))}function he(e){return{get tier(){return e.tier},get fallbackReason(){return e.fallbackReason},detect:(...n)=>e.detect(...n),destroy:()=>{}}}function oe(e){let n=S(e),r=g().get(n);if(!(r===void 0||r.detector===null&&r.detectorPromise===null&&r.scheduled===null))return async()=>{r.scheduled!==null&&I(r,n);let s=r.promise;for(;r.detector===null&&s!==null&&(await s,r.promise!==s);)s=r.promise;return r.detector!==null?he(r.detector):C({v3AssetBaseUrl:n})}}function Ce(e){switch(e){case"fcv3.no_face":case"fcv3.center_face":case"fcv3.straighten":return"center";case"fcv3.come_closer":return"closer";case"fcv3.move_back":return"farther";case"fcv3.more_light":case"fcv3.too_bright":return"light";case"fcv3.hold_still":case"fcv3.steady_camera":return"still";case"fcv3.hold_upright":return"upright";case"fcv3.one_face":return"one_face";default:return null}}function Se(e){switch(e){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";default:return e}}function ie(e){switch(e){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return e;case"backcamera":return"notfound";default:{let n=e;return"generic"}}}function Le(e,n,r){if(r===void 0)return{kind:ie(e),retryable:n};let s=Z(r.name);return{kind:ie(e),retryable:n,detail:{...s!==void 0?{name:s}:{},phase:r.phase,engineKind:e}}}var ye=new Set(["captured","uploading","checking"]);function Ee(e,n={},r,s=()=>"self",m=()=>{},d){let u=n.now??(()=>performance.now()),i=n.canChooseFacing??ee,f="user",h=te(),p=s(),l=Y(),B=!Q(),H=n.engineOptions,ae=H?.createDetector===void 0&&H?.createWorker===void 0?{createDetector:()=>{let t=oe(e.assetBaseUrl);return t!==void 0?t():C({v3AssetBaseUrl:e.assetBaseUrl})}}:{},U={video:e.video,mode:B?"photo":"clip",rankKeyframes:r,facingMode:void 0,v3AssetBaseUrl:e.assetBaseUrl,screenRamp:()=>p==="self"&&l.count("ramp")>0?m():void 0,...n.engineOptions??{},...ae},o=n.createEngine?.(U)??new X(U),v="idle",L=null,y=0,w=!1,k="full",E=null,b=null,D=0,_=0,K=()=>{e.video.videoWidth>0&&e.video.videoHeight>0&&(D=e.video.videoWidth,_=e.video.videoHeight)},V=ne({enabled:e.keepScreenAwake!==!1}),M=t=>{v=t,V.setActive(t==="starting"||t==="gating"||t==="recording"),l.emit("state",t)},R=()=>l.emit("gate",{progress:y,hint:L,faceDetected:w}),G=()=>{let t=o.animations??"full";t!==k&&(k=t,l.emit("profile",{animations:k}))},de=[o.on("statechange",({state:t})=>{let a=Se(t);a==="starting"&&v!=="starting"&&(L=null,y=0,w=!1,E=null,b=null,D=0,_=0),M(a),G(),a==="recording"&&(K(),E=u(),L="hold",y=1,R())}),o.on("checks",t=>{K(),y=t.progress,w=t.factors.presence>0,R(),G()}),o.on("guidance",({key:t})=>{L=Ce(t),R()}),o.on("frozen",({previewDataUrl:t})=>{b=u(),l.emit("frozen",{previewDataUrl:t})}),o.on("ramp",t=>l.emit("ramp",t)),o.on("artifacts",t=>{if(v!=="captured")return;let a=$(),c=t.clipStats,q=c!==void 0?Math.round(c.durationMs):E!==null&&b!==null?Math.max(0,Math.round(b-E)):void 0,N=c!==void 0&&c.frames>1&&c.durationMs>0?Math.round(c.frames*1e4/c.durationMs)/10:void 0;l.emit("captured",{keyframe:t.keyframe,...t.clip!==void 0?{clip:t.clip}:{},...t.clipMimeType!==void 0?{clipMime:t.clipMimeType}:{},width:e.video.videoWidth||D,height:e.video.videoHeight||_,...q!==void 0?{clipMs:q}:{},...c!==void 0?{clipFrames:c.frames}:{},...N!==void 0?{fps:N}:{},...t.clipRetakes!==void 0?{clipRetakes:t.clipRetakes}:{},...t.clipMimeType!==void 0?{codec:j(t.clipMimeType)}:{},captureChannel:a==="desktop"?"desktop":"mobile",formFactor:a,...B?{degraded:"NO_RECORDER"}:{},engine:"v3",facingMode:o.facingMode,mode:p,...t.timing,...t.screenRamp!==void 0?{screenRamp:t.screenRamp}:{},...t.provenance!==void 0?{provenance:t.provenance}:{}})}),o.on("error",({kind:t,retryable:a,detail:c})=>{t==="backcamera"&&ce()||l.emit("error",Le(t,a,c))})],z=!1;function ce(){return T||z||p!=="assisted"||d===void 0||d.session()!=="choice"?!1:(z=!0,d.onModeChange("self"),p="self",f=O("self"),M("mode_switch"),o.restart(f),!0)}let W=async()=>d!==void 0&&d.session()==="choice"&&await i().catch(()=>!1),T=!1;return{handle:{get state(){return v},get captureMode(){return s()},get facingMode(){return o.facingMode??f},on:(t,a)=>l.on(t,a),start:t=>(p=s(),h.facing(p,e.facing),f=h.facing(p,t?.facing),o.start({facingMode:f})),retry:()=>o.retry(),switchCamera:()=>h.refuseSwitch(s()),canSwitchCaptureMode:W,setCaptureMode:async t=>{if(t===s()||!await W()||T||ye.has(v)||d===void 0)return!1;d.onModeChange(t),p=t;let a=O(t);return f=a,v==="idle"||(M("mode_switch"),o.restart(a)),!0},destroy:()=>{T=!0;for(let t of de)t();V.setActive(!1),o.destroy(),l.clear()}},setFlowState:t=>{v!==t&&M(t)}}}function ze(e){return Ee(e).handle}export{ue as a,re as b,Pe as c,Ae as d,we as e,ke as f,De as g,_e as h,oe as i,Ce as j,Se as k,ie as l,Le as m,Ee as n,ze as o};
1
+ import{a as Y,d as ee,e as O,f as te,g as ne}from"./chunk-7QZWBDI5.js";import{C as X,a as j}from"./chunk-OVP7FAMJ.js";import{f as Q,l as Z}from"./chunk-CPUECYAJ.js";import{c as $}from"./chunk-TSA6GHUG.js";import{c as J,h as C}from"./chunk-FSSMUAKC.js";var ue=12e4,re=13e4,le=3e3,fe=1200,P=Symbol.for("@sekyro/web.preload.v1");function g(){let e=globalThis;return e[P]??(e[P]=new Map),e[P]}function S(e){let n=(e??J).replace(/\/+$/,"");return n===""?"/":n}function se(e){let n=g(),r=n.get(e);return r===void 0&&(r={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},n.set(e,r)),r}function A(e,n){if(e.status!==n){e.status=n;for(let r of[...e.listeners])r(n)}}var x=e=>C({preferred:["blaze"],v3AssetBaseUrl:e,blazeInitTimeoutMs:ue}),F=x;function Pe(e){F=e??x}function Ae(){for(let e of g().values())e.detector?.destroy();g().clear(),F=x}function pe(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function me(){return navigator.connection?.saveData===!0}function ve(e){let n=window;if(typeof n.requestIdleCallback=="function"){let s=n.requestIdleCallback(e,{timeout:le});return()=>n.cancelIdleCallback?.(s)}let r=setTimeout(e,fe);return()=>clearTimeout(r)}function ge(e,n){let r,s=new Promise(i=>{r=i}),m=!1,d=()=>{},u={promise:s,settle:i=>{m||(m=!0,d(),e.scheduled===u&&(e.scheduled=null),r(i))}};return e.scheduled=u,d=ve(()=>{m||u.settle(I(e,n))}),s}function I(e,n){if((e.status==="loading"||e.status==="ready")&&e.promise!==null)return e.promise;A(e,"loading");let r=new Promise(i=>i(F(n)));e.detectorPromise=r;let s,m=new Promise((i,f)=>{s=setTimeout(()=>{r.then(h=>h.destroy(),()=>{}),f(new Error(`detector preload exceeded ${re} ms`))},re)}),u=Promise.race([r,m]).then(i=>e.detectorPromise!==r?(i.destroy(),e.status):(e.detector=i,A(e,"ready"),"ready"),i=>(e.detectorPromise===r&&(e.detectorPromise=null,e.detector=null,A(e,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",i)),e.status)).finally(()=>clearTimeout(s));return e.promise=u,e.scheduled?.settle(u),u}function we(e={}){if(!pe())return Promise.resolve("idle");let n=S(e.assetBaseUrl),r=se(n);return e.respectSaveData===!0&&me()?Promise.resolve(r.status):(r.status==="loading"||r.status==="ready")&&r.promise!==null?r.promise:e.idle===!0?r.scheduled?.promise??ge(r,n):I(r,n)}function ke(e){return g().get(S(e))?.status??"idle"}function De(e,n){let r=se(S(n));return r.listeners.add(e),()=>{r.listeners.delete(e)}}function _e(e){let n=g().get(S(e));n!==void 0&&(n.scheduled?.settle("idle"),n.detector?.destroy(),n.detector=null,n.detectorPromise=null,n.promise=null,A(n,"idle"))}function he(e){return{get tier(){return e.tier},get fallbackReason(){return e.fallbackReason},detect:(...n)=>e.detect(...n),destroy:()=>{}}}function oe(e){let n=S(e),r=g().get(n);if(!(r===void 0||r.detector===null&&r.detectorPromise===null&&r.scheduled===null))return async()=>{r.scheduled!==null&&I(r,n);let s=r.promise;for(;r.detector===null&&s!==null&&(await s,r.promise!==s);)s=r.promise;return r.detector!==null?he(r.detector):C({v3AssetBaseUrl:n})}}function Ce(e){switch(e){case"fcv3.no_face":case"fcv3.center_face":case"fcv3.straighten":return"center";case"fcv3.come_closer":return"closer";case"fcv3.move_back":return"farther";case"fcv3.more_light":case"fcv3.too_bright":return"light";case"fcv3.hold_still":case"fcv3.steady_camera":return"still";case"fcv3.hold_upright":return"upright";case"fcv3.one_face":return"one_face";default:return null}}function Se(e){switch(e){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";default:return e}}function ie(e){switch(e){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return e;case"backcamera":return"notfound";default:{let n=e;return"generic"}}}function Le(e,n,r){if(r===void 0)return{kind:ie(e),retryable:n};let s=Z(r.name);return{kind:ie(e),retryable:n,detail:{...s!==void 0?{name:s}:{},phase:r.phase,engineKind:e}}}var ye=new Set(["captured","uploading","checking"]);function Ee(e,n={},r,s=()=>"self",m=()=>{},d){let u=n.now??(()=>performance.now()),i=n.canChooseFacing??ee,f="user",h=te(),p=s(),l=Y(),B=!Q(),H=n.engineOptions,ae=H?.createDetector===void 0&&H?.createWorker===void 0?{createDetector:()=>{let t=oe(e.assetBaseUrl);return t!==void 0?t():C({v3AssetBaseUrl:e.assetBaseUrl})}}:{},U={video:e.video,mode:B?"photo":"clip",rankKeyframes:r,facingMode:void 0,v3AssetBaseUrl:e.assetBaseUrl,screenRamp:()=>p==="self"&&l.count("ramp")>0?m():void 0,...n.engineOptions??{},...ae},o=n.createEngine?.(U)??new X(U),v="idle",L=null,y=0,w=!1,k="full",E=null,b=null,D=0,_=0,K=()=>{e.video.videoWidth>0&&e.video.videoHeight>0&&(D=e.video.videoWidth,_=e.video.videoHeight)},V=ne({enabled:e.keepScreenAwake!==!1}),M=t=>{v=t,V.setActive(t==="starting"||t==="gating"||t==="recording"),l.emit("state",t)},R=()=>l.emit("gate",{progress:y,hint:L,faceDetected:w}),G=()=>{let t=o.animations??"full";t!==k&&(k=t,l.emit("profile",{animations:k}))},de=[o.on("statechange",({state:t})=>{let a=Se(t);a==="starting"&&v!=="starting"&&(L=null,y=0,w=!1,E=null,b=null,D=0,_=0),M(a),G(),a==="recording"&&(K(),E=u(),L="hold",y=1,R())}),o.on("checks",t=>{K(),y=t.progress,w=t.factors.presence>0,R(),G()}),o.on("guidance",({key:t})=>{L=Ce(t),R()}),o.on("frozen",({previewDataUrl:t})=>{b=u(),l.emit("frozen",{previewDataUrl:t})}),o.on("ramp",t=>l.emit("ramp",t)),o.on("artifacts",t=>{if(v!=="captured")return;let a=$(),c=t.clipStats,q=c!==void 0?Math.round(c.durationMs):E!==null&&b!==null?Math.max(0,Math.round(b-E)):void 0,N=c!==void 0&&c.frames>1&&c.durationMs>0?Math.round(c.frames*1e4/c.durationMs)/10:void 0;l.emit("captured",{keyframe:t.keyframe,...t.clip!==void 0?{clip:t.clip}:{},...t.clipMimeType!==void 0?{clipMime:t.clipMimeType}:{},width:e.video.videoWidth||D,height:e.video.videoHeight||_,...q!==void 0?{clipMs:q}:{},...c!==void 0?{clipFrames:c.frames}:{},...N!==void 0?{fps:N}:{},...t.clipRetakes!==void 0?{clipRetakes:t.clipRetakes}:{},...t.clipMimeType!==void 0?{codec:j(t.clipMimeType)}:{},captureChannel:a==="desktop"?"desktop":"mobile",formFactor:a,...B?{degraded:"NO_RECORDER"}:{},engine:"v3",facingMode:o.facingMode,mode:p,...t.timing,...t.screenRamp!==void 0?{screenRamp:t.screenRamp}:{},...t.provenance!==void 0?{provenance:t.provenance}:{}})}),o.on("error",({kind:t,retryable:a,detail:c})=>{t==="backcamera"&&ce()||l.emit("error",Le(t,a,c))})],z=!1;function ce(){return T||z||p!=="assisted"||d===void 0||d.session()!=="choice"?!1:(z=!0,d.onModeChange("self"),p="self",f=O("self"),M("mode_switch"),o.restart(f),!0)}let W=async()=>d!==void 0&&d.session()==="choice"&&await i().catch(()=>!1),T=!1;return{handle:{get state(){return v},get captureMode(){return s()},get facingMode(){return o.facingMode??f},on:(t,a)=>l.on(t,a),start:t=>(p=s(),h.facing(p,e.facing),f=h.facing(p,t?.facing),o.start({facingMode:f})),retry:()=>o.retry(),switchCamera:()=>h.refuseSwitch(s()),canSwitchCaptureMode:W,setCaptureMode:async t=>{if(t===s()||!await W()||T||ye.has(v)||d===void 0)return!1;d.onModeChange(t),p=t;let a=O(t);return f=a,v==="idle"||(M("mode_switch"),o.restart(a)),!0},destroy:()=>{T=!0;for(let t of de)t();V.setActive(!1),o.destroy(),l.clear()}},setFlowState:t=>{v!==t&&M(t)}}}function ze(e){return Ee(e).handle}export{ue as a,re as b,Pe as c,Ae as d,we as e,ke as f,De as g,_e as h,oe as i,Ce as j,Se as k,ie as l,Le as m,Ee as n,ze as o};
@@ -1 +1 @@
1
- import{d as Jt,h as qt,k as te}from"./chunk-G6LKLN4U.js";import{b as $t}from"./chunk-SMKCBUJL.js";import{a as et,b as ee,c as ie,e as mt,f as oe}from"./chunk-MXWLCDFX.js";import{b as Yt,c as Zt}from"./chunk-TDLIXFDT.js";import{b as Vt,c as Xt}from"./chunk-POIQGEZM.js";import{k as Qt,m as Bt,n as Wt,o as Ht,p as Kt,r as ut}from"./chunk-CPUECYAJ.js";import{b as ht,c as dt,d as j,e as jt}from"./chunk-FPXL63KZ.js";import{d as Ut}from"./chunk-IFLOS5OT.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 ne(i){return i.framing==="no_document"?"sensing":i.framing==="too_far"?"too_far":i.framing==="too_close"?"too_close":i.framing==="edge_clipped"?"edge_clipped":i.framing==="wrong_shape"?"wrong_shape":i.framing==="tilted"?"tilted":i.lighting==="too_dark"?"too_dark":i.lighting==="too_bright"?"too_bright":i.glare==="glare"?"glare":i.blur==="blurry"?"blurry":"hold_still"}var ot=class{constructor(t=2600,e=.35){this.windowMs=t;this.decayPerSecond=e;this.votes=[];this.current=it.sensing;this.currentSinceMs=null}reset(){this.votes=[],this.current=it.sensing,this.currentSinceMs=null}force(t,e){return this.votes=[],this.current=it[t],this.currentSinceMs=e,this.current}tick(t,e){if(this.currentSinceMs===null&&(this.currentSinceMs=e),this.votes.push({key:t,atMs:e}),this.votes=this.votes.filter(r=>e-r.atMs<=this.windowMs),e-this.currentSinceMs<this.current.minDurationMs)return this.current;let o=new Map;for(let r of this.votes){let c=(e-r.atMs)/1e3,a=this.decayPerSecond**c;o.set(r.key,(o.get(r.key)??0)+a)}let n=this.current.key,s=-1;for(let[r,c]of o)c>s&&(s=c,n=r);return n!==this.current.key&&(this.current=it[n],this.currentSinceMs=e),this.current}};var Xe=Object.freeze({MAX_AREA_FRAC:.92,TILT_MAX_SIDE_RATIO:1.3,GLARE_MAX_SPECULAR_FRAC:.025});function re(i){let{data:t,width:e,height:o}=i,n=e*o;if(n===0)return 0;let s=0;for(let r=0;r<n;r++){let c=r*4;.299*(t[c]??0)+.587*(t[c+1]??0)+.114*(t[c+2]??0)>=252&&s++}return s/n}function je(i){let t=(a,l)=>Math.hypot(l.x-a.x,l.y-a.y),e=t(i.topLeft,i.topRight),o=t(i.bottomLeft,i.bottomRight),n=t(i.topLeft,i.bottomLeft),s=t(i.topRight,i.bottomRight),r=Math.max(e,o)/Math.max(1e-6,Math.min(e,o)),c=Math.max(n,s)/Math.max(1e-6,Math.min(n,s));return Math.max(r,c)}function ae(i){let t={...ee,...i.thresholds},e=Xe,{quad:o,frameWidth:n,frameHeight:s,measures:r}=i,c=i.format==="ID-3",a="ok";if(o===null)a="no_document";else if(c){let m=mt(o),h=n>0?m.width/n:0,f=m.height>0?m.width/m.height:0;h<t.ID3_BAND_MIN_WIDTH_FRAC?a="too_far":se(o,n,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=ie(o,n,s),h=mt(o),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>e.MAX_AREA_FRAC?a="too_close":se(o,n,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":Zt(i.format,f)?je(o)>e.TILT_MAX_SIDE_RATIO&&(a="tilted"):a="wrong_shape"}let l=r.exposure>=t.GUIDE_EXPOSURE?"ok":r.meanLuma<(ht[0]+ht[1])/2?"too_dark":"too_bright",u=r.sharpness>=t.GUIDE_SHARPNESS?"ok":"blurry",d=r.specularFraction>=e.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 se(i,t,e,o){return[i.topLeft,i.topRight,i.bottomRight,i.bottomLeft].some(s=>s.x<=o||s.y<=o||s.x>=t-o||s.y>=e-o)}var le=Object.freeze({width:1920,height:1080}),Ye=Object.freeze({width:3840,height:2160}),ce=4096,Ze=2560,ue=640,nt=.15,Y=Object.freeze({side:.2,above:.9,below:.3});function E(i){let t=[i.topLeft.x,i.topRight.x,i.bottomRight.x,i.bottomLeft.x],e=[i.topLeft.y,i.topRight.y,i.bottomRight.y,i.bottomLeft.y],o=Math.min(...t),n=Math.min(...e);return{x:o,y:n,width:Math.max(...t)-o,height:Math.max(...e)-n}}function he(i,t){let e=Math.max(0,Math.floor(i.x)),o=Math.max(0,Math.floor(i.y)),n=Math.min(t.width,Math.ceil(i.x+i.width)),s=Math.min(t.height,Math.ceil(i.y+i.height));return n-e<16||s-o<16?null:{x:e,y:o,width:n-e,height:s-o}}function Je(i,t,e){if(i===null||t.width<=0||t.height<=0)return null;let o=E(i);if(o.width<=0||o.height<=0)return null;let n=e==="ID-3"?{x:o.x-o.width*Y.side,y:o.y-o.width*Y.above,width:o.width*(1+2*Y.side),height:o.height+o.width*(Y.above+Y.below)}:{x:o.x-o.width*nt,y:o.y-o.height*nt,width:o.width*(1+2*nt),height:o.height*(1+2*nt)};return he(n,t)}function ft(i,t,e){let o=Math.max(i,t);return o>0?Math.min(1,e/o):1}function pt(i,t,e,o,n=Ze){let s=t.width>0?e.width/t.width:1,r=t.height>0?e.height/t.height:1,c=i===null?null:{topLeft:{x:i.topLeft.x*s,y:i.topLeft.y*r},topRight:{x:i.topRight.x*s,y:i.topRight.y*r},bottomRight:{x:i.bottomRight.x*s,y:i.bottomRight.y*r},bottomLeft:{x:i.bottomLeft.x*s,y:i.bottomLeft.y*r}},a=Je(c,e,o)??{x:0,y:0,width:e.width,height:e.height},l=ft(a.width,a.height,n),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=E(c);m=he({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 de(i,t,e,o=Ye){if(e==="LOW")return null;let n=i?.width?.max,s=i?.height?.max;if(typeof n!="number"||typeof s!="number"||n<=0||s<=0)return null;let r=Math.max(n,s),c=Math.min(n,s),a=Math.min(r,Math.max(o.width,o.height)),l=Math.min(c,Math.min(o.width,o.height));return a<=Math.max(t.width,t.height)?null:{width:{ideal:a},height:{ideal:l}}}function me(i){let t={},e=i?.imageWidth,o=i?.imageHeight;if(typeof e?.max=="number"&&e.max>0){let n=typeof o?.max=="number"&&o.max>0?e.max/o.max:1.3333333333333333,s=n>=1?ce:ce*n,r=Math.min(e.max,Math.floor(s)),c=typeof e.step=="number"&&e.step>0?e.step:1,a=typeof e.min=="number"?e.min:0;r=Math.max(a,a+Math.floor((r-a)/c)*c),t.imageWidth=r}return i?.fillLightMode?.includes("off")===!0&&(t.fillLightMode="off"),t}function fe(i,t){if(i.width<=0||i.height<=0||t.width<=0||t.height<=0)return!1;let e=i.width>i.height,o=t.width>t.height;return e!==o&&i.width!==i.height&&t.width!==t.height?!1:Math.max(i.width,i.height)>=1.2*Math.max(t.width,t.height)}function pe(i,t,e,o){if(e===null)return!1;let n=E(i),s=E(e);if(t.width<=0||o.width<=0)return!1;let r=n.width/t.width,c=s.width/o.width;return c>0&&r>=.6*c&&r<=1.25*c}var ge=3500,qe=.92;function ye(){let i=globalThis.ImageCapture;return typeof i=="function"?i:null}function $e(i){return/AppleWebKit\//.test(i)&&!/(Chrome|Chromium|Edg|OPR)\//.test(i)}function Me(i,t=typeof navigator>"u"?"":navigator.userAgent){return ye()!==null&&!$e(t)&&i!=null&&i.kind==="video"&&i.readyState==="live"}function be(i,t){return new Promise((e,o)=>{let n=setTimeout(()=>o(new Error("takePhoto timed out")),t);i.then(s=>{clearTimeout(n),e(s)},s=>{clearTimeout(n),o(s)})})}function gt(i,t){let e=document.createElement("canvas");return e.width=i,e.height=t,e}function ti(i,t){return new Promise((e,o)=>{i.toBlob(n=>n?e(n):o(new Error("toBlob failed")),"image/jpeg",t)})}async function ke(i,t,e,o,n){let s=gt(e,o),r=gt(1,1);try{let c=s.getContext("2d");if(c===null)throw new Error("2d context unavailable");c.imageSmoothingQuality="high",c.drawImage(i,t.x,t.y,t.width,t.height,0,0,e,o);let a=await ti(s,qe),l=n===null?null:Jt({topLeft:{x:n.x,y:n.y},topRight:{x:n.x+n.width,y:n.y},bottomRight:{x:n.x+n.width,y:n.y+n.height},bottomLeft:{x:n.x,y:n.y+n.height}},{width:e,height:o},{width:e,height:o}),u=qt(s,l),d=ft(e,o,ue);return r.width=Math.max(1,Math.round(e*d)),r.height=Math.max(1,Math.round(o*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 ei(i,t){let e=Math.min(1,t/i.width),o=gt(Math.max(1,Math.round(i.width*e)),Math.max(1,Math.round(i.height*e)));try{let n=o.getContext("2d",{willReadFrequently:!0});return n===null?null:(n.imageSmoothingQuality="high",n.drawImage(i,0,0,o.width,o.height),n.getImageData(0,0,o.width,o.height))}finally{o.width=0,o.height=0}}async function De(i,t,e,o){let n={width:Math.max(1,i.videoWidth),height:Math.max(1,i.videoHeight)},s=pt(t,e,n,o);return{...await ke(i,s.crop,s.width,s.height,s.docRegion),docRegion:s.docRegion,source:"video",width:s.width,height:s.height}}async function xe(i,t,e,o,n){let s=ye();if(s===null)return null;let r=null;try{let c=new s(n.track),a=await be(c.getPhotoCapabilities?.()??Promise.resolve({}),ge).catch(()=>({})),l=await be(c.takePhoto(me(a)),ge);r=await createImageBitmap(l);let u={width:i.videoWidth,height:i.videoHeight};if(!fe(r,u))return null;let d=ei(r,n.detectWidth),m=null;d!==null&&t!==null&&(m=await n.detect(d).catch(()=>null));let h=d??{width:r.width,height:r.height};m!==null&&!pe(m,h,t,e)&&(m=null);let f=pt(m,h,r,o);return{...await ke(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=(i,t,e)=>typeof i=="number"&&Number.isFinite(i)&&i>=t&&i<=e?i:void 0;function Si(i){let t=st,e=i!==null&&typeof i=="object"?i:{},o=e.fillDistanceM!==null&&typeof e.fillDistanceM=="object"?e.fillDistanceM:{},n=(s,r)=>typeof s=="boolean"?s:r;return{width:S(e.width,640,7680)??t.width,height:S(e.height,480,4320)??t.height,lensSelection:n(e.lensSelection,t.lensSelection),continuousFocus:n(e.continuousFocus,t.continuousFocus),refocusBeforePhotoMs:S(e.refocusBeforePhotoMs,0,2e3)??t.refocusBeforePhotoMs,zoomMax:S(e.zoomMax,1,5)??t.zoomMax,zoomNoFocusInfo:S(e.zoomNoFocusInfo,1,5)??t.zoomNoFocusInfo,zoomMinSourcePx:S(e.zoomMinSourcePx,0,8e3)??t.zoomMinSourcePx,fillDistanceM:{id1:S(o.id1,.03,1)??t.fillDistanceM.id1,id3:S(o.id3,.03,1)??t.fillDistanceM.id3},focusMarginFrac:S(e.focusMarginFrac,0,2)??t.focusMarginFrac,stillSharpnessMin:S(e.stillSharpnessMin,0,10)??t.stillSharpnessMin,stillRefusalsMax:S(e.stillRefusalsMax,0,10)??t.stillRefusalsMax,focusFarFillFrac:S(e.focusFarFillFrac,0,1)??t.focusFarFillFrac,noDocFarHintMs:S(e.noDocFarHintMs,0,6e4)??t.noDocFarHintMs,zoomFallbackMs:S(e.zoomFallbackMs,0,12e4)??t.zoomFallbackMs}}var bt="sekyro.doc.camera";function ii(){try{let i=globalThis.localStorage?.getItem(bt);return typeof i=="string"&&i!==""?i:null}catch{return null}}function we(i){try{i===null?globalThis.localStorage?.removeItem(bt):globalThis.localStorage?.setItem(bt,i)}catch{}}var rt=(i,t)=>Array.isArray(i?.focusMode)&&i.focusMode.includes(t);function Mt(i,t,e){if(!rt(i,"single-shot"))return null;let o=n=>Math.min(1,Math.max(0,Number.isFinite(n)?n:.5));return{focusMode:"single-shot",pointsOfInterest:[{x:o(t),y:o(e)}]}}function _i(i,t,e,o){if(!Number.isFinite(i)||!Number.isFinite(t)||e.width<=0||e.height<=0||o.width<=0||o.height<=0)return null;let n=Math.max(e.width/o.width,e.height/o.height),s=o.width*n,r=o.height*n,c=(i-e.left+(s-e.width)/2)/s,a=(t-e.top+(r-e.height)/2)/r;return{x:Math.min(1,Math.max(0,c)),y:Math.min(1,Math.max(0,a))}}function Se(i,t,e,o=st){let n=i?.zoom?.min,s=i?.zoom?.max;if(typeof s!="number"||s<=1)return 1;let r=e==="ID-3"?o.fillDistanceM.id3:o.fillDistanceM.id1,c=i?.focusDistance?.min,a;if(typeof c=="number"&&c>0&&c<1){if(a=c*(1+o.focusMarginFrac)/r,a<=1.05)return 1}else{if(Math.min(t.width,t.height)<o.zoomMinSourcePx)return 1;a=o.zoomNoFocusInfo}let l=Math.min(a,o.zoomMax,s);typeof n=="number"&&(l=Math.max(l,n));let u=i?.zoom?.step;return typeof u=="number"&&u>0&&(l=Math.round(l/u)*u),l>1.01?Number(l.toFixed(2)):1}function yt(i){try{return i.getVideoTracks?.()[0]}catch{return}}function ve(i){if(i!==null)for(let t of i.getTracks())t.stop()}function oi(i){try{let t=yt(i)?.getCapabilities?.();return!Array.isArray(t?.focusMode)||t.focusMode.includes("continuous")}catch{return!0}}async function Te(i){let t=s=>({audio:!1,video:{...s,width:{ideal:i.base.width},height:{ideal:i.base.height}}}),e=s=>i.getUserMedia(t({deviceId:{exact:s}})),o=()=>i.getUserMedia(t({facingMode:{ideal:"environment"}}));if(i.lensSelection){let s=ii();if(s!==null)try{return{stream:await e(s),lens:"stored"}}catch{we(null)}}let n=await o();if(!i.lensSelection||i.enumerateDevices===void 0)return{stream:n,lens:"default"};try{let s=ut(await i.enumerateDevices()).slice(0,3);if(s.length===0)return{stream:n,lens:"default"};let r=null;for(let c of s){let a=n!==null?yt(n)?.getSettings?.().deviceId:void 0;if(n===null||a!==c){ve(n),n=null;try{n=await e(c)}catch{continue}}if(r??(r=c),oi(n))return we(c),{stream:n,lens:"selected"}}if(n!==null&&r!==null&&yt(n)?.getSettings?.().deviceId===r)return{stream:n,lens:"selected"};if(ve(n),n=null,r!==null)try{return{stream:await e(r),lens:"selected"}}catch{}return{stream:await o(),lens:"default"}}catch{return{stream:n??await o(),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}),L=i=>Math.min(1,Math.max(0,i));function Re(i,t,e,o=.06){let n=Math.max(i.width/e,i.height),s=n*e,r=(i.width-s)/2,c=(i.height-n)/2,a=L((t.x-t.width*o-r)/s),l=L((t.y-t.height*o-c)/n),u=L((t.x+t.width*(1+o)-r)/s),d=L((t.y+t.height*(1+o)-c)/n);return{x:a,y:l,width:u-a,height:d-l}}function Fe(i,t,e={}){let o=e.edgePeakFrac??0,{width:n,height:s,data:r}=i;if(n<=0||s<=0)return Z;let c=L(t.x),a=L(t.y),l={x:c,y:a,width:Math.max(0,L(t.x+t.width)-c),height:Math.max(0,L(t.y+t.height)-a)};if(l.width<=0||l.height<=0)return Z;let u=l.x*n,d=l.y*s,m=(l.x+l.width)*n,h=(l.y+l.height)*s,f=(m-u)*.15,g=(h-d)*.15,y=(p,b,R)=>Math.min(R,Math.max(b,p)),D=y(Math.floor(u-f),0,n-1),w=y(Math.floor(d-g),0,s-1),O=y(Math.ceil(m+f),D+1,n),v=y(Math.ceil(h+g),w+1,s),x=Math.max(1,Math.ceil(Math.max(O-D,v-w)/320)),M=Math.floor((O-D+x-1)/x),T=Math.floor((v-w+x-1)/x);if(M<3||T<3)return Z;let k=new Int32Array(M*T);for(let p=0;p<T;p++){let b=w+p*x;for(let R=0;R<M;R++){let F=(b*n+D+R*x)*4;k[p*M+R]=(r[F]??0)*77+(r[F+1]??0)*150+(r[F+2]??0)*29>>8}}let C=(p,b)=>(p-b-.5)/x,_=C(u,D),A=C(m,D),B=C(d,w),U=C(h,w),Dt=(m-u)/x,xt=(h-d)/x,wt=y(Math.ceil(_),0,M-1),Ie=y(Math.floor(A),wt,M-1),vt=y(Math.ceil(B),0,T-1),Ge=y(Math.floor(U),vt,T-1),St=0,Tt=0,W=0,_t=0,Rt=0,H=0;for(let p=vt;p<=Ge;p++)for(let b=wt;b<=Ie;b++){let R=k[p*M+b];if(St+=R,R>=248&&Tt++,W++,b>=1&&b<M-1&&p>=1&&p<T-1){let F=k[p*M+b-1]+k[p*M+b+1]+k[(p-1)*M+b]+k[(p+1)*M+b]-4*R;_t+=F,Rt+=F*F,H++}}let ze=W>0?St/W:0,Ft=W>0?Tt/W:0,Ct=H>0?_t/H:0,Ne=H>0?Math.max(0,Rt/H-Ct*Ct):0,K=new Float64Array(M),V=new Float64Array(T);for(let p=0;p<T;p++)for(let b=1;b<M-1;b++)K[b]=K[b]+Math.abs(k[p*M+b+1]-k[p*M+b-1]);for(let p=1;p<T-1;p++)for(let b=0;b<M;b++)V[p]=V[p]+Math.abs(k[(p+1)*M+b]-k[(p-1)*M+b]);let P=at(K,!0,_,o),I=at(K,!1,A,o),G=at(V,!0,B,o),z=at(V,!1,U,o),At=(I.position-P.position)/Dt,Et=(z.position-G.position)/xt,Qe=Et>0?At/Et:0,Be=((P.position+I.position)/2-(_+A)/2)/Dt,Ue=((G.position+z.position)/2-(B+U)/2)/xt,Lt=_e(K),Ot=_e(V),We=Lt<=0||Ot<=0?0:Math.min(Math.min(P.value,I.value)/Lt,Math.min(G.value,z.value)/Ot),$=(p,b)=>b+(p+.5)*x,Pt=Ft,It=0;{let p=(I.position-P.position)*.06,b=(z.position-G.position)*.06,R=y(Math.ceil(P.position+p),0,M-1),F=y(Math.floor(I.position-p),0,M-1),He=y(Math.ceil(G.position+b),0,T-1),Gt=y(Math.floor(z.position-b),0,T-1),zt=0,tt=0,Nt=0;for(let N=He;N<=Gt;N++)for(let Q=R;Q<=F;Q++){tt++;let X=k[N*M+Q];X>=248&&zt++;let Ke=Q+2<=F?k[N*M+Q+2]:X,Ve=N+2<=Gt?k[(N+2)*M+Q]:X;(Math.abs(Ke-X)>=24||Math.abs(Ve-X)>=24)&&Nt++}tt>=16&&(Pt=zt/tt,It=Nt/tt)}return{brightness:ze,glare:Ft,cardGlare:Pt,sharpness:Ne,fill:At,shape:Qe,content:It,offsetX:Be,offsetY:Ue,edgeConfidence:We,box:{left:$(P.position,D),right:$(I.position,D),top:$(G.position,w),bottom:$(z.position,w)}}}function at(i,t,e,o){let n=i.length,s=Math.max(1,Math.floor(n*.45)),r=t?1:Math.max(1,n-1-s),c=t?Math.min(n-2,s):n-2,a=r;for(let h=r;h<=c;h++)i[h]>i[a]&&(a=h);if(o>0&&o<1){let h=i[a]*o,f=a,g=Math.abs(a-e);for(let y=r;y<=c;y++){let D=i[y];if(D<h||D<(i[y-1]??0)||D<(i[y+1]??0))continue;let w=Math.abs(y-e);w<g&&(f=y,g=w)}a=f}let l=a>0?i[a-1]:0,u=i[a],d=a<n-1?i[a+1]:0,m=l+u+d;return{position:m>0?a+(d-l)/m:a,value:u}}function _e(i){if(i.length<3)return 0;let t=0;for(let e=1;e<i.length-1;e++)t+=i[e];return t/(i.length-2)}function Ce(i){let t=i.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 Ai(i){let t=i!==null&&typeof i=="object"?i:{},e={...J};for(let o of Object.keys(J)){let n=t[o];typeof n=="number"&&Number.isFinite(n)&&n>=0&&n<=1e6&&(e[o]=n)}return e}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,e){let o=this.t,n=o.shapeTolerance<=0||Math.abs(t.shape-1)<=o.shapeTolerance,s=t.edgeConfidence>=o.edgeConfidenceMin&&n&&t.content>=o.contentMin,r=t.fill>=o.fillMin&&t.fill<=o.fillMax,c=Math.abs(t.offsetX)<=o.offsetMax&&Math.abs(t.offsetY)<=o.offsetMax,a=t.cardGlare<=o.glareMax,l=t.sharpness>=o.sharpnessMin,u=this.last;this.last={fill:t.fill,offsetX:t.offsetX,offsetY:t.offsetY,at:e};let d=u!==null&&o.steadyRefMs>0?Math.min(3,Math.max(1,(e-u.at)/o.steadyRefMs)):1,m=s&&a&&l&&t.fill>=o.steadyFillMin&&t.fill<=o.steadyFillMax&&u!==null&&Math.abs(t.fill-u.fill)<=o.steadyFillDelta*d&&Math.abs(t.offsetX-u.offsetX)<=o.steadyOffsetDelta*d&&Math.abs(t.offsetY-u.offsetY)<=o.steadyOffsetDelta*d,h=s&&r&&c&&a&&l,f;if(s?a?t.fill<o.fillMin?f="too_small":t.fill>o.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=e)),this.goodSince??(this.goodSince=e),e-this.goodSince>=o.lockMs)return{detected:s,ready:!0,via:"good",blocker:"locking"};let g=this.steadySince!==null&&e-this.steadySince>=o.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:"locking"}}if(this.goodSince=null,m){this.steadySince??(this.steadySince=e);let g=e-this.steadySince>=o.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 q=null;async function ni(i){return q===null&&(q=(await import("./detector-scanic-YCDNLCGV.js")).detectQuad),q(i)}async function si(i){let t=$t(i);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 ji(){q===null&&import("./detector-scanic-YCDNLCGV.js").then(i=>{q=i.detectQuad}).catch(()=>{})}var Ae=4e3,ri=2,Ee=3,ai=Object.freeze({LOW:3,MID:5,HIGH:6}),kt=Object.freeze({manualShutterMs:6e3,detectedNoLockMs:1950});function Yi(i){let t=i!==null&&typeof i=="object"?i:{},e=(o,n,s)=>typeof o=="number"&&Number.isFinite(o)&&o>=n&&o<=s?o:void 0;return{manualShutterMs:e(t.manualShutterMs,1e3,6e4)??kt.manualShutterMs,detectedNoLockMs:e(t.steadyMs,300,3e4)!==void 0?t.steadyMs+(e(t.lockMs,0,1e4)??450):kt.detectedNoLockMs}}var Le=class i{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=i.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 ot;this.lastFeedbackKey=null;this.lastQuad=null;this.lastDetect=null;this.frameWatch=null;this.reopened=!1;this.lit=!1;this.blackTicks=0;this.offEnded=null;this.opts=t,this.gate=new oe(t.format??"ID-1",t.thresholds);let e=t.deviceClass??Xt(Vt());this.deviceClass=e,this.camera=t.camera??st,this.shutterTuning=t.shutter??kt,this.guideTuning=t.guideLock??J,this.guideLock=new ct(this.guideTuning),this.cadenceMs=1e3/ai[e]}on(t,e){let o=this.handlers.get(t);return o||(o=new Set,this.handlers.set(t,o)),o.add(e),()=>o?.delete(e)}emit(t,e){for(let o of[...this.handlers.get(t)??[]])o(e)}async start(){let t=this.state==="error"?this.resumePlayback():null,e=++this.attempt;if(this.clearFrameWatch(),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.lit=!1,this.blackTicks=0,t!==null&&await t&&e===this.attempt){this.setState("positioning"),this.scheduleTick(e),this.watchFrames(e);return}if(e===this.attempt){this.releaseStream(),Ht(),this.setState("preflight");try{let o=this.opts.getUserMedia??(r=>navigator.mediaDevices.getUserMedia(r));this.setState("acquiring");let n=this.opts.enumerateDevices??(this.opts.getUserMedia===void 0&&typeof navigator<"u"&&navigator.mediaDevices?.enumerateDevices?()=>navigator.mediaDevices.enumerateDevices():void 0),s=await Te({getUserMedia:o,...n!==void 0?{enumerateDevices:n}:{},lensSelection:this.camera.lensSelection,base:le});if(e!==this.attempt){for(let r of s.stream.getTracks())r.stop();return}if(this.stream=s.stream,Ut(this.stream),Wt(this.stream),this.watchEnded(e),this.opts.upgradeResolution!==!1&&await this.upgradeResolution(),e!==this.attempt||(await this.applyFocusAndZoom(),e!==this.attempt)||(this.opts.video.srcObject=this.stream,await this.opts.video.play().catch(()=>{}),e!==this.attempt))return;this.setState("positioning"),this.scheduleTick(e),this.watchFrames(e)}catch(o){if(e!==this.attempt)return;let n=Bt(o),s=Qt(o);this.setState("error"),this.emit("error",{kind:n,retryable:!0,detail:s===void 0?{phase:"acquiring"}:{phase:"acquiring",name:s}})}}}resumePlayback(){let t=this.opts.video,e=this.videoTrack();if(this.stream===null||e===null||e.readyState!=="live"||t.srcObject!==this.stream)return null;try{return Promise.resolve(t.play()).then(()=>this.framesNow(),()=>!1)}catch{return null}}framesNow(){let t=this.opts.video;return this.opts.hasFrames!==void 0?this.opts.hasFrames(t):!t.paused&&t.readyState>=2&&t.videoWidth>0}watchFrames(t){let e=this.opts.firstFrameMs??Ae;e<=0||(this.clearFrameWatch(),this.frameWatch=setTimeout(()=>{if(this.frameWatch=null,!(t!==this.attempt||this.state!=="positioning")){if(this.framesNow()&&this.blackTicks<Ee){this.reopened=!1;return}this.cameraDead(t)}},e))}clearFrameWatch(){this.frameWatch!==null&&clearTimeout(this.frameWatch),this.frameWatch=null}watchEnded(t){this.offEnded?.(),this.offEnded=null;let e=this.videoTrack();if(e===null||typeof e.addEventListener!="function")return;let o=()=>{t===this.attempt&&(this.state==="positioning"||this.state==="acquiring")&&this.cameraDead(t)};e.addEventListener("ended",o),this.offEnded=()=>e.removeEventListener?.("ended",o)}cameraDead(t){if(t!==this.attempt)return;let e=this.videoTrack(),o=e!==null&&e.readyState==="live"&&!e.muted&&this.opts.video.paused&&!this.framesNow();if(!o&&!this.reopened){this.reopened=!0,this.start();return}this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.clearFrameWatch(),o||this.releaseStream(),this.reopened=!1,this.setState("error"),this.emit("error",{kind:"generic",retryable:!0,detail:{phase:"acquiring"}})}releaseStream(){if(this.offEnded?.(),this.offEnded=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject!==null&&this.opts.video.srcObject!==void 0&&(this.opts.video.srcObject=null)}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,e=this.lastDetect?.width??Math.max(1,t.videoWidth),o=this.lastDetect?.height??Math.max(1,t.videoHeight),n=this.lastQuad??this.lastGuideQuad??{topLeft:{x:0,y:0},topRight:{x:e,y:0},bottomRight:{x:e,y:o},bottomLeft:{x:0,y:o}},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:n,{width:e,height:o,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 e=(this.opts.format??"ID-1")==="ID-3"||this.opts.side==="single"?"single":this.opts.side==="verso"?"verso":"recto",o=t.report(e,this.stats.via,(this.opts.now??(()=>performance.now()))());return o===null?{}:{ocr:o}}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 e=t.width/Math.max(1,t.height),o=this.opts.guide;if(o!==void 0&&o.viewAspect>0){let c={width:o.viewAspect,height:1},a={x:o.rect.x*o.viewAspect,y:o.rect.y,width:o.rect.width*o.viewAspect,height:o.rect.height};return Re(c,a,e,0)}let n=Yt(this.opts.format??"ID-1").center,s=.86,r=s*e/n;return r>.84&&(r=.84,s=r*n/e),{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=i.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 e=this.videoTrack();if(e===null||this.zoom<=1)return;let o=this.focusCaps(),n=typeof o?.zoom?.min=="number"?Math.max(o.zoom.min,1):1;this.zoom=n,this.stats.zoomFallbackAtMs=Math.round(t-(this.positioningSince??t)),this.guideLock.reset(),this.gate.reset(),e.applyConstraints({advanced:[{zoom:n}]}).catch(()=>{})}offerShutter(t,e){this.shutterOffered||(this.shutterOffered=!0,this.stats.shutterAtMs=Math.round(e-(this.positioningSince??e)),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.clearFrameWatch(),this.offEnded?.(),this.offEnded=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 e=t.getSettings?.()??{},o=de(t.getCapabilities?.(),{width:e.width??0,height:e.height??0},this.deviceClass,{width:this.camera.width,height:this.camera.height});o!==null&&await t.applyConstraints(o)}catch{}}focusCaps(){try{return this.videoTrack()?.getCapabilities?.()??null}catch{return null}}async applyFocusAndZoom(){let t=this.videoTrack();if(t===null)return;let e=this.focusCaps();this.camera.continuousFocus&&rt(e,"continuous")&&await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{});let o={width:0,height:0};try{let s=t.getSettings?.()??{};o={width:s.width??0,height:s.height??0}}catch{}let n=Se(e,o,this.opts.format??"ID-1",this.camera);if(n>1)try{await t.applyConstraints({advanced:[{zoom:n}]}),this.zoom=n}catch{this.zoom=1}}async focusAt(t,e){let o=this.videoTrack(),n=Mt(this.focusCaps(),t,e);if(!(o===null||n===null))try{await o.applyConstraints({advanced:[n]}),(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,e){let o=this.camera.refocusBeforePhotoMs,n=this.videoTrack();if(o<=0||n===null||e.width<=0||e.height<=0)return;let s=E(t),r=Mt(this.focusCaps(),(s.x+s.width/2)/e.width,(s.y+s.height/2)/e.height);if(r!==null)try{await n.applyConstraints({advanced:[r]});let c=this.opts.setTimer??setTimeout;await new Promise(a=>{c(()=>a(),o)})}catch{}}videoTrack(){try{return this.stream?.getVideoTracks?.()[0]??null}catch{return null}}async takeStill(t,e,o){if(this.opts.captureStill!==void 0)return this.opts.captureStill(this.opts.video,t,e);let n=this.opts.format??"ID-1",s=this.videoTrack();if(o&&this.opts.photoCapture!==!1&&this.deviceClass!=="LOW"&&!this.torchOn&&s!==null&&Me(s)){await this.refocusOn(t,e);let r=await xe(this.opts.video,t,e,n,{track:s,detect:this.detector(),detectWidth:et});if(this.restoreContinuous(),r!==null)return r}return De(this.opts.video,t,e,n)}detector(){return this.opts.detect??((this.opts.format??"ID-1")==="ID-3"?si:ni)}setState(t){this.state=t,this.emit("statechange",{state:t})}scheduleTick(t){let e=this.opts.setTimer??setTimeout;this.timer=e(()=>{this.tick(t)},this.cadenceMs)}async tick(t){if(t!==this.attempt||this.state!=="positioning"||this.capturing)return;let e=this.opts.now??(()=>performance.now()),o=this.opts.grabDetectFrame??Pe,n=this.detector(),s=o(this.opts.video,et);if(s===null){this.scheduleTick(t);return}if(!this.lit){if(dt(s)>ri)this.lit=!0,this.blackTicks=0;else if(++this.blackTicks>=Ee&&this.frameWatch===null&&(this.opts.firstFrameMs??Ae)>0){this.cameraDead(t);return}}let r=null;try{r=await n(s)}catch{r=null}if(t!==this.attempt)return;let c=r!==null?lt(s,r):s,a=e(),l={sharpness:j(c),exposure:jt(c),meanLuma:dt(c),specularFraction:re(c)},u=ae({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"?Fe(s,this.guideRegion(s),{edgePeakFrac:this.guideTuning.edgePeakFrac}):Z,f=this.guideLock.tick(h,a);this.lastGuideQuad=f.detected?Ce(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 _=u.lighting!=="ok"?u.lighting:u.glare!=="ok"?"glare":u.blur!=="ok"?"blurry":"steadying";y.qualityBlockers[_]=(y.qualityBlockers[_]??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<=fi?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 O=a-(this.lastSeenAt??this.positioningSince);this.zoom>1&&this.camera.zoomFallbackMs>0&&O>=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=ne(u);u.framing!=="ok"&&f.detected&&(v=mi(f.blocker,h.brightness<this.guideTuning.darkBrightness)),v==="blurry"&&r!==null&&li(r,s,this.opts.format??"ID-1")>=this.camera.focusFarFillFrac&&(v="focus_far"),v==="sensing"&&this.zoom>1&&this.camera.noDocFarHintMs>0&&O>=this.camera.noDocFarHintMs&&(v="focus_far");let x=this.feedback.tick(v,a);if(x.key!==this.lastFeedbackKey&&(this.lastFeedbackKey=x.key,this.emit("feedback",x)),d.guidanceKey!==this.lastGuidance&&(this.lastGuidance=d.guidanceKey,this.emit("guidance",{key:d.guidanceKey})),this.capturing)return;let M=g?.suspendQuality!==!0,T=M&&d.ready&&r!==null,k=M&&f.ready&&this.lastGuideQuad!==null,C=this.lastOcrReady;if(C!==null&&this.opts.autoCapture!==!1){let _=this.feedback.force("processing",a);this.lastFeedbackKey=_.key,this.emit("feedback",_);let A=j(lt(s,C.quad));await this.fire(t,C.quad,{width:s.width,height:s.height,tickSharpness:A},C.via);return}if((T||k)&&this.opts.autoCapture!==!1){let _=this.feedback.force("processing",a);this.lastFeedbackKey=_.key,this.emit("feedback",_);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,e,o,n){this.capturing=!0;let s=this.opts.grabDetectFrame??Pe,r=this.opts.setTimer??setTimeout,c={width:o.width,height:o.height};try{let a={still:await this.takeStill(e,c,!0),sharpness:o.tickSharpness};if(t!==this.attempt)return;let l=a.still.source==="photo"?0:ui;for(let m=0;m<l;m++){if(await new Promise(g=>{r(()=>g(),hi)}),t!==this.attempt)return;let h=s(this.opts.video,et);if(h===null)continue;let f=j(lt(h,e));if(f>a.sharpness*di){let g=await this.takeStill(e,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&&n!=="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,(n==="text_lock"||n==="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=n,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=n==="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,(n==="text_lock"||n==="live_mrz")&&this.opts.ocr?.rearmFace(),this.scheduleTick(t)}}ocrTick(t,e,o,n,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,D;m&&e!==null?D=ci(E(e),g,y,l,u):D=te(f,c.bandTop,u);let w=m?s.glare==="ok":o.cardGlare<=this.guideTuning.glareMax,O=m?s.blur==="ok":o.sharpness>=this.guideTuning.sharpnessMin,v=c.tick({atMs:r,video:a,mrzFace:m||this.opts.side==="verso"||this.opts.side==="single",present:m||e!==null||n,card:f,band:D,portrait:u>l,glareOk:w,sharpOk:O});if(v.ready&&v.via!==void 0){let x=m?e??Oe(h,t):this.lastGuideQuad??Oe(h,t);this.lastOcrReady={quad:x,via:v.via}}else this.lastOcrReady=null;return v}};function ci(i,t,e,o,n){let s=Math.min(o,i.width*1.06*t),r=Math.min(n,Math.max(i.height*1.6*e,s/5)),c=(i.y+i.height/2)*e,a=Math.max(0,Math.min(o-s,(i.x-i.width*.03)*t)),l=Math.max(0,Math.min(n-r,c-r/2));return{x:a,y:l,w:s,h:r}}function Oe(i,t){let e=i.x*t.width,o=i.y*t.height,n=(i.x+i.width)*t.width,s=(i.y+i.height)*t.height;return{topLeft:{x:e,y:o},topRight:{x:n,y:o},bottomRight:{x:n,y:s},bottomLeft:{x:e,y:s}}}function li(i,t,e){let o=E(i);return t.width<=0||t.height<=0?0:e==="ID-3"?o.width/t.width:o.width*o.height/(t.width*t.height)}var ui=2,hi=260,di=1.08;function Pe(i,t){let e=i.videoWidth,o=i.videoHeight;if(e===0||o===0)return null;let n=Math.min(1,t/e),s=Math.round(e*n),r=Math.round(o*n),c=document.createElement("canvas");c.width=s,c.height=r;let a=c.getContext("2d",{willReadFrequently:!0});return a===null?null:(e/Math.max(1,s)>4&&(a.imageSmoothingQuality="high"),a.drawImage(i,0,0,s,r),a.getImageData(0,0,s,r))}function lt(i,t){let e=[t.topLeft.x,t.topRight.x,t.bottomRight.x,t.bottomLeft.x],o=[t.topLeft.y,t.topRight.y,t.bottomRight.y,t.bottomLeft.y],n=Math.max(0,Math.floor(Math.min(...e))),s=Math.max(0,Math.floor(Math.min(...o))),r=Math.min(i.width,Math.ceil(Math.max(...e))),c=Math.min(i.height,Math.ceil(Math.max(...o))),a=Math.max(1,r-n),l=Math.max(1,c-s),u=new Uint8ClampedArray(a*l*4);for(let d=0;d<l;d++){let m=((s+d)*i.width+n)*4;u.set(i.data.subarray(m,m+a*4),d*a*4)}return{data:u,width:a,height:l,colorSpace:i.colorSpace}}function mi(i,t){return i==="glare"?"glare":i==="too_small"?"too_far":i==="too_big"?"too_close":t?"too_dark":i==="blurry"?"blurry":i==="off_center"?"edge_clipped":i==="no_card"?"sensing":"hold_still"}var fi=1200;export{it as a,ne as b,ot as c,Xe as d,re as e,je as f,ae as g,st as h,Si as i,bt as j,ii as k,we as l,rt as m,Mt as n,_i as o,Se as p,oi as q,Te as r,Z as s,Re as t,Fe as u,Ce as v,J as w,Ai as x,ct as y,ji as z,Ae as A,ri as B,Ee as C,ai as D,kt as E,Yi as F,Le as G,ci as H,ui as I,hi as J};
1
+ import{d as Jt,h as qt,k as te}from"./chunk-G6LKLN4U.js";import{b as $t}from"./chunk-SMKCBUJL.js";import{a as et,b as ee,c as ie,e as mt,f as oe}from"./chunk-4DEPREJ3.js";import{b as Yt,c as Zt}from"./chunk-NFHLJOHW.js";import{b as Vt,c as Xt}from"./chunk-POIQGEZM.js";import{k as Qt,m as Bt,n as Wt,o as Ht,p as Kt,r as ut}from"./chunk-CPUECYAJ.js";import{b as ht,c as dt,d as j,e as jt}from"./chunk-FPXL63KZ.js";import{d as Ut}from"./chunk-LLX2CKZ3.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 ne(i){return i.framing==="no_document"?"sensing":i.framing==="too_far"?"too_far":i.framing==="too_close"?"too_close":i.framing==="edge_clipped"?"edge_clipped":i.framing==="wrong_shape"?"wrong_shape":i.framing==="tilted"?"tilted":i.lighting==="too_dark"?"too_dark":i.lighting==="too_bright"?"too_bright":i.glare==="glare"?"glare":i.blur==="blurry"?"blurry":"hold_still"}var ot=class{constructor(t=2600,e=.35){this.windowMs=t;this.decayPerSecond=e;this.votes=[];this.current=it.sensing;this.currentSinceMs=null}reset(){this.votes=[],this.current=it.sensing,this.currentSinceMs=null}force(t,e){return this.votes=[],this.current=it[t],this.currentSinceMs=e,this.current}tick(t,e){if(this.currentSinceMs===null&&(this.currentSinceMs=e),this.votes.push({key:t,atMs:e}),this.votes=this.votes.filter(r=>e-r.atMs<=this.windowMs),e-this.currentSinceMs<this.current.minDurationMs)return this.current;let o=new Map;for(let r of this.votes){let c=(e-r.atMs)/1e3,a=this.decayPerSecond**c;o.set(r.key,(o.get(r.key)??0)+a)}let n=this.current.key,s=-1;for(let[r,c]of o)c>s&&(s=c,n=r);return n!==this.current.key&&(this.current=it[n],this.currentSinceMs=e),this.current}};var Xe=Object.freeze({MAX_AREA_FRAC:.92,TILT_MAX_SIDE_RATIO:1.3,GLARE_MAX_SPECULAR_FRAC:.025});function re(i){let{data:t,width:e,height:o}=i,n=e*o;if(n===0)return 0;let s=0;for(let r=0;r<n;r++){let c=r*4;.299*(t[c]??0)+.587*(t[c+1]??0)+.114*(t[c+2]??0)>=252&&s++}return s/n}function je(i){let t=(a,l)=>Math.hypot(l.x-a.x,l.y-a.y),e=t(i.topLeft,i.topRight),o=t(i.bottomLeft,i.bottomRight),n=t(i.topLeft,i.bottomLeft),s=t(i.topRight,i.bottomRight),r=Math.max(e,o)/Math.max(1e-6,Math.min(e,o)),c=Math.max(n,s)/Math.max(1e-6,Math.min(n,s));return Math.max(r,c)}function ae(i){let t={...ee,...i.thresholds},e=Xe,{quad:o,frameWidth:n,frameHeight:s,measures:r}=i,c=i.format==="ID-3",a="ok";if(o===null)a="no_document";else if(c){let m=mt(o),h=n>0?m.width/n:0,f=m.height>0?m.width/m.height:0;h<t.ID3_BAND_MIN_WIDTH_FRAC?a="too_far":se(o,n,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=ie(o,n,s),h=mt(o),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>e.MAX_AREA_FRAC?a="too_close":se(o,n,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":Zt(i.format,f)?je(o)>e.TILT_MAX_SIDE_RATIO&&(a="tilted"):a="wrong_shape"}let l=r.exposure>=t.GUIDE_EXPOSURE?"ok":r.meanLuma<(ht[0]+ht[1])/2?"too_dark":"too_bright",u=r.sharpness>=t.GUIDE_SHARPNESS?"ok":"blurry",d=r.specularFraction>=e.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 se(i,t,e,o){return[i.topLeft,i.topRight,i.bottomRight,i.bottomLeft].some(s=>s.x<=o||s.y<=o||s.x>=t-o||s.y>=e-o)}var le=Object.freeze({width:1920,height:1080}),Ye=Object.freeze({width:3840,height:2160}),ce=4096,Ze=2560,ue=640,nt=.15,Y=Object.freeze({side:.2,above:.9,below:.3});function E(i){let t=[i.topLeft.x,i.topRight.x,i.bottomRight.x,i.bottomLeft.x],e=[i.topLeft.y,i.topRight.y,i.bottomRight.y,i.bottomLeft.y],o=Math.min(...t),n=Math.min(...e);return{x:o,y:n,width:Math.max(...t)-o,height:Math.max(...e)-n}}function he(i,t){let e=Math.max(0,Math.floor(i.x)),o=Math.max(0,Math.floor(i.y)),n=Math.min(t.width,Math.ceil(i.x+i.width)),s=Math.min(t.height,Math.ceil(i.y+i.height));return n-e<16||s-o<16?null:{x:e,y:o,width:n-e,height:s-o}}function Je(i,t,e){if(i===null||t.width<=0||t.height<=0)return null;let o=E(i);if(o.width<=0||o.height<=0)return null;let n=e==="ID-3"?{x:o.x-o.width*Y.side,y:o.y-o.width*Y.above,width:o.width*(1+2*Y.side),height:o.height+o.width*(Y.above+Y.below)}:{x:o.x-o.width*nt,y:o.y-o.height*nt,width:o.width*(1+2*nt),height:o.height*(1+2*nt)};return he(n,t)}function ft(i,t,e){let o=Math.max(i,t);return o>0?Math.min(1,e/o):1}function pt(i,t,e,o,n=Ze){let s=t.width>0?e.width/t.width:1,r=t.height>0?e.height/t.height:1,c=i===null?null:{topLeft:{x:i.topLeft.x*s,y:i.topLeft.y*r},topRight:{x:i.topRight.x*s,y:i.topRight.y*r},bottomRight:{x:i.bottomRight.x*s,y:i.bottomRight.y*r},bottomLeft:{x:i.bottomLeft.x*s,y:i.bottomLeft.y*r}},a=Je(c,e,o)??{x:0,y:0,width:e.width,height:e.height},l=ft(a.width,a.height,n),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=E(c);m=he({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 de(i,t,e,o=Ye){if(e==="LOW")return null;let n=i?.width?.max,s=i?.height?.max;if(typeof n!="number"||typeof s!="number"||n<=0||s<=0)return null;let r=Math.max(n,s),c=Math.min(n,s),a=Math.min(r,Math.max(o.width,o.height)),l=Math.min(c,Math.min(o.width,o.height));return a<=Math.max(t.width,t.height)?null:{width:{ideal:a},height:{ideal:l}}}function me(i){let t={},e=i?.imageWidth,o=i?.imageHeight;if(typeof e?.max=="number"&&e.max>0){let n=typeof o?.max=="number"&&o.max>0?e.max/o.max:1.3333333333333333,s=n>=1?ce:ce*n,r=Math.min(e.max,Math.floor(s)),c=typeof e.step=="number"&&e.step>0?e.step:1,a=typeof e.min=="number"?e.min:0;r=Math.max(a,a+Math.floor((r-a)/c)*c),t.imageWidth=r}return i?.fillLightMode?.includes("off")===!0&&(t.fillLightMode="off"),t}function fe(i,t){if(i.width<=0||i.height<=0||t.width<=0||t.height<=0)return!1;let e=i.width>i.height,o=t.width>t.height;return e!==o&&i.width!==i.height&&t.width!==t.height?!1:Math.max(i.width,i.height)>=1.2*Math.max(t.width,t.height)}function pe(i,t,e,o){if(e===null)return!1;let n=E(i),s=E(e);if(t.width<=0||o.width<=0)return!1;let r=n.width/t.width,c=s.width/o.width;return c>0&&r>=.6*c&&r<=1.25*c}var ge=3500,qe=.92;function ye(){let i=globalThis.ImageCapture;return typeof i=="function"?i:null}function $e(i){return/AppleWebKit\//.test(i)&&!/(Chrome|Chromium|Edg|OPR)\//.test(i)}function Me(i,t=typeof navigator>"u"?"":navigator.userAgent){return ye()!==null&&!$e(t)&&i!=null&&i.kind==="video"&&i.readyState==="live"}function be(i,t){return new Promise((e,o)=>{let n=setTimeout(()=>o(new Error("takePhoto timed out")),t);i.then(s=>{clearTimeout(n),e(s)},s=>{clearTimeout(n),o(s)})})}function gt(i,t){let e=document.createElement("canvas");return e.width=i,e.height=t,e}function ti(i,t){return new Promise((e,o)=>{i.toBlob(n=>n?e(n):o(new Error("toBlob failed")),"image/jpeg",t)})}async function ke(i,t,e,o,n){let s=gt(e,o),r=gt(1,1);try{let c=s.getContext("2d");if(c===null)throw new Error("2d context unavailable");c.imageSmoothingQuality="high",c.drawImage(i,t.x,t.y,t.width,t.height,0,0,e,o);let a=await ti(s,qe),l=n===null?null:Jt({topLeft:{x:n.x,y:n.y},topRight:{x:n.x+n.width,y:n.y},bottomRight:{x:n.x+n.width,y:n.y+n.height},bottomLeft:{x:n.x,y:n.y+n.height}},{width:e,height:o},{width:e,height:o}),u=qt(s,l),d=ft(e,o,ue);return r.width=Math.max(1,Math.round(e*d)),r.height=Math.max(1,Math.round(o*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 ei(i,t){let e=Math.min(1,t/i.width),o=gt(Math.max(1,Math.round(i.width*e)),Math.max(1,Math.round(i.height*e)));try{let n=o.getContext("2d",{willReadFrequently:!0});return n===null?null:(n.imageSmoothingQuality="high",n.drawImage(i,0,0,o.width,o.height),n.getImageData(0,0,o.width,o.height))}finally{o.width=0,o.height=0}}async function De(i,t,e,o){let n={width:Math.max(1,i.videoWidth),height:Math.max(1,i.videoHeight)},s=pt(t,e,n,o);return{...await ke(i,s.crop,s.width,s.height,s.docRegion),docRegion:s.docRegion,source:"video",width:s.width,height:s.height}}async function xe(i,t,e,o,n){let s=ye();if(s===null)return null;let r=null;try{let c=new s(n.track),a=await be(c.getPhotoCapabilities?.()??Promise.resolve({}),ge).catch(()=>({})),l=await be(c.takePhoto(me(a)),ge);r=await createImageBitmap(l);let u={width:i.videoWidth,height:i.videoHeight};if(!fe(r,u))return null;let d=ei(r,n.detectWidth),m=null;d!==null&&t!==null&&(m=await n.detect(d).catch(()=>null));let h=d??{width:r.width,height:r.height};m!==null&&!pe(m,h,t,e)&&(m=null);let f=pt(m,h,r,o);return{...await ke(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=(i,t,e)=>typeof i=="number"&&Number.isFinite(i)&&i>=t&&i<=e?i:void 0;function Si(i){let t=st,e=i!==null&&typeof i=="object"?i:{},o=e.fillDistanceM!==null&&typeof e.fillDistanceM=="object"?e.fillDistanceM:{},n=(s,r)=>typeof s=="boolean"?s:r;return{width:S(e.width,640,7680)??t.width,height:S(e.height,480,4320)??t.height,lensSelection:n(e.lensSelection,t.lensSelection),continuousFocus:n(e.continuousFocus,t.continuousFocus),refocusBeforePhotoMs:S(e.refocusBeforePhotoMs,0,2e3)??t.refocusBeforePhotoMs,zoomMax:S(e.zoomMax,1,5)??t.zoomMax,zoomNoFocusInfo:S(e.zoomNoFocusInfo,1,5)??t.zoomNoFocusInfo,zoomMinSourcePx:S(e.zoomMinSourcePx,0,8e3)??t.zoomMinSourcePx,fillDistanceM:{id1:S(o.id1,.03,1)??t.fillDistanceM.id1,id3:S(o.id3,.03,1)??t.fillDistanceM.id3},focusMarginFrac:S(e.focusMarginFrac,0,2)??t.focusMarginFrac,stillSharpnessMin:S(e.stillSharpnessMin,0,10)??t.stillSharpnessMin,stillRefusalsMax:S(e.stillRefusalsMax,0,10)??t.stillRefusalsMax,focusFarFillFrac:S(e.focusFarFillFrac,0,1)??t.focusFarFillFrac,noDocFarHintMs:S(e.noDocFarHintMs,0,6e4)??t.noDocFarHintMs,zoomFallbackMs:S(e.zoomFallbackMs,0,12e4)??t.zoomFallbackMs}}var bt="sekyro.doc.camera";function ii(){try{let i=globalThis.localStorage?.getItem(bt);return typeof i=="string"&&i!==""?i:null}catch{return null}}function we(i){try{i===null?globalThis.localStorage?.removeItem(bt):globalThis.localStorage?.setItem(bt,i)}catch{}}var rt=(i,t)=>Array.isArray(i?.focusMode)&&i.focusMode.includes(t);function Mt(i,t,e){if(!rt(i,"single-shot"))return null;let o=n=>Math.min(1,Math.max(0,Number.isFinite(n)?n:.5));return{focusMode:"single-shot",pointsOfInterest:[{x:o(t),y:o(e)}]}}function _i(i,t,e,o){if(!Number.isFinite(i)||!Number.isFinite(t)||e.width<=0||e.height<=0||o.width<=0||o.height<=0)return null;let n=Math.max(e.width/o.width,e.height/o.height),s=o.width*n,r=o.height*n,c=(i-e.left+(s-e.width)/2)/s,a=(t-e.top+(r-e.height)/2)/r;return{x:Math.min(1,Math.max(0,c)),y:Math.min(1,Math.max(0,a))}}function Se(i,t,e,o=st){let n=i?.zoom?.min,s=i?.zoom?.max;if(typeof s!="number"||s<=1)return 1;let r=e==="ID-3"?o.fillDistanceM.id3:o.fillDistanceM.id1,c=i?.focusDistance?.min,a;if(typeof c=="number"&&c>0&&c<1){if(a=c*(1+o.focusMarginFrac)/r,a<=1.05)return 1}else{if(Math.min(t.width,t.height)<o.zoomMinSourcePx)return 1;a=o.zoomNoFocusInfo}let l=Math.min(a,o.zoomMax,s);typeof n=="number"&&(l=Math.max(l,n));let u=i?.zoom?.step;return typeof u=="number"&&u>0&&(l=Math.round(l/u)*u),l>1.01?Number(l.toFixed(2)):1}function yt(i){try{return i.getVideoTracks?.()[0]}catch{return}}function ve(i){if(i!==null)for(let t of i.getTracks())t.stop()}function oi(i){try{let t=yt(i)?.getCapabilities?.();return!Array.isArray(t?.focusMode)||t.focusMode.includes("continuous")}catch{return!0}}async function Te(i){let t=s=>({audio:!1,video:{...s,width:{ideal:i.base.width},height:{ideal:i.base.height}}}),e=s=>i.getUserMedia(t({deviceId:{exact:s}})),o=()=>i.getUserMedia(t({facingMode:{ideal:"environment"}}));if(i.lensSelection){let s=ii();if(s!==null)try{return{stream:await e(s),lens:"stored"}}catch{we(null)}}let n=await o();if(!i.lensSelection||i.enumerateDevices===void 0)return{stream:n,lens:"default"};try{let s=ut(await i.enumerateDevices()).slice(0,3);if(s.length===0)return{stream:n,lens:"default"};let r=null;for(let c of s){let a=n!==null?yt(n)?.getSettings?.().deviceId:void 0;if(n===null||a!==c){ve(n),n=null;try{n=await e(c)}catch{continue}}if(r??(r=c),oi(n))return we(c),{stream:n,lens:"selected"}}if(n!==null&&r!==null&&yt(n)?.getSettings?.().deviceId===r)return{stream:n,lens:"selected"};if(ve(n),n=null,r!==null)try{return{stream:await e(r),lens:"selected"}}catch{}return{stream:await o(),lens:"default"}}catch{return{stream:n??await o(),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}),L=i=>Math.min(1,Math.max(0,i));function Re(i,t,e,o=.06){let n=Math.max(i.width/e,i.height),s=n*e,r=(i.width-s)/2,c=(i.height-n)/2,a=L((t.x-t.width*o-r)/s),l=L((t.y-t.height*o-c)/n),u=L((t.x+t.width*(1+o)-r)/s),d=L((t.y+t.height*(1+o)-c)/n);return{x:a,y:l,width:u-a,height:d-l}}function Fe(i,t,e={}){let o=e.edgePeakFrac??0,{width:n,height:s,data:r}=i;if(n<=0||s<=0)return Z;let c=L(t.x),a=L(t.y),l={x:c,y:a,width:Math.max(0,L(t.x+t.width)-c),height:Math.max(0,L(t.y+t.height)-a)};if(l.width<=0||l.height<=0)return Z;let u=l.x*n,d=l.y*s,m=(l.x+l.width)*n,h=(l.y+l.height)*s,f=(m-u)*.15,g=(h-d)*.15,y=(p,b,R)=>Math.min(R,Math.max(b,p)),D=y(Math.floor(u-f),0,n-1),w=y(Math.floor(d-g),0,s-1),O=y(Math.ceil(m+f),D+1,n),v=y(Math.ceil(h+g),w+1,s),x=Math.max(1,Math.ceil(Math.max(O-D,v-w)/320)),M=Math.floor((O-D+x-1)/x),T=Math.floor((v-w+x-1)/x);if(M<3||T<3)return Z;let k=new Int32Array(M*T);for(let p=0;p<T;p++){let b=w+p*x;for(let R=0;R<M;R++){let F=(b*n+D+R*x)*4;k[p*M+R]=(r[F]??0)*77+(r[F+1]??0)*150+(r[F+2]??0)*29>>8}}let C=(p,b)=>(p-b-.5)/x,_=C(u,D),A=C(m,D),B=C(d,w),U=C(h,w),Dt=(m-u)/x,xt=(h-d)/x,wt=y(Math.ceil(_),0,M-1),Ie=y(Math.floor(A),wt,M-1),vt=y(Math.ceil(B),0,T-1),Ge=y(Math.floor(U),vt,T-1),St=0,Tt=0,W=0,_t=0,Rt=0,H=0;for(let p=vt;p<=Ge;p++)for(let b=wt;b<=Ie;b++){let R=k[p*M+b];if(St+=R,R>=248&&Tt++,W++,b>=1&&b<M-1&&p>=1&&p<T-1){let F=k[p*M+b-1]+k[p*M+b+1]+k[(p-1)*M+b]+k[(p+1)*M+b]-4*R;_t+=F,Rt+=F*F,H++}}let ze=W>0?St/W:0,Ft=W>0?Tt/W:0,Ct=H>0?_t/H:0,Ne=H>0?Math.max(0,Rt/H-Ct*Ct):0,K=new Float64Array(M),V=new Float64Array(T);for(let p=0;p<T;p++)for(let b=1;b<M-1;b++)K[b]=K[b]+Math.abs(k[p*M+b+1]-k[p*M+b-1]);for(let p=1;p<T-1;p++)for(let b=0;b<M;b++)V[p]=V[p]+Math.abs(k[(p+1)*M+b]-k[(p-1)*M+b]);let P=at(K,!0,_,o),I=at(K,!1,A,o),G=at(V,!0,B,o),z=at(V,!1,U,o),At=(I.position-P.position)/Dt,Et=(z.position-G.position)/xt,Qe=Et>0?At/Et:0,Be=((P.position+I.position)/2-(_+A)/2)/Dt,Ue=((G.position+z.position)/2-(B+U)/2)/xt,Lt=_e(K),Ot=_e(V),We=Lt<=0||Ot<=0?0:Math.min(Math.min(P.value,I.value)/Lt,Math.min(G.value,z.value)/Ot),$=(p,b)=>b+(p+.5)*x,Pt=Ft,It=0;{let p=(I.position-P.position)*.06,b=(z.position-G.position)*.06,R=y(Math.ceil(P.position+p),0,M-1),F=y(Math.floor(I.position-p),0,M-1),He=y(Math.ceil(G.position+b),0,T-1),Gt=y(Math.floor(z.position-b),0,T-1),zt=0,tt=0,Nt=0;for(let N=He;N<=Gt;N++)for(let Q=R;Q<=F;Q++){tt++;let X=k[N*M+Q];X>=248&&zt++;let Ke=Q+2<=F?k[N*M+Q+2]:X,Ve=N+2<=Gt?k[(N+2)*M+Q]:X;(Math.abs(Ke-X)>=24||Math.abs(Ve-X)>=24)&&Nt++}tt>=16&&(Pt=zt/tt,It=Nt/tt)}return{brightness:ze,glare:Ft,cardGlare:Pt,sharpness:Ne,fill:At,shape:Qe,content:It,offsetX:Be,offsetY:Ue,edgeConfidence:We,box:{left:$(P.position,D),right:$(I.position,D),top:$(G.position,w),bottom:$(z.position,w)}}}function at(i,t,e,o){let n=i.length,s=Math.max(1,Math.floor(n*.45)),r=t?1:Math.max(1,n-1-s),c=t?Math.min(n-2,s):n-2,a=r;for(let h=r;h<=c;h++)i[h]>i[a]&&(a=h);if(o>0&&o<1){let h=i[a]*o,f=a,g=Math.abs(a-e);for(let y=r;y<=c;y++){let D=i[y];if(D<h||D<(i[y-1]??0)||D<(i[y+1]??0))continue;let w=Math.abs(y-e);w<g&&(f=y,g=w)}a=f}let l=a>0?i[a-1]:0,u=i[a],d=a<n-1?i[a+1]:0,m=l+u+d;return{position:m>0?a+(d-l)/m:a,value:u}}function _e(i){if(i.length<3)return 0;let t=0;for(let e=1;e<i.length-1;e++)t+=i[e];return t/(i.length-2)}function Ce(i){let t=i.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 Ai(i){let t=i!==null&&typeof i=="object"?i:{},e={...J};for(let o of Object.keys(J)){let n=t[o];typeof n=="number"&&Number.isFinite(n)&&n>=0&&n<=1e6&&(e[o]=n)}return e}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,e){let o=this.t,n=o.shapeTolerance<=0||Math.abs(t.shape-1)<=o.shapeTolerance,s=t.edgeConfidence>=o.edgeConfidenceMin&&n&&t.content>=o.contentMin,r=t.fill>=o.fillMin&&t.fill<=o.fillMax,c=Math.abs(t.offsetX)<=o.offsetMax&&Math.abs(t.offsetY)<=o.offsetMax,a=t.cardGlare<=o.glareMax,l=t.sharpness>=o.sharpnessMin,u=this.last;this.last={fill:t.fill,offsetX:t.offsetX,offsetY:t.offsetY,at:e};let d=u!==null&&o.steadyRefMs>0?Math.min(3,Math.max(1,(e-u.at)/o.steadyRefMs)):1,m=s&&a&&l&&t.fill>=o.steadyFillMin&&t.fill<=o.steadyFillMax&&u!==null&&Math.abs(t.fill-u.fill)<=o.steadyFillDelta*d&&Math.abs(t.offsetX-u.offsetX)<=o.steadyOffsetDelta*d&&Math.abs(t.offsetY-u.offsetY)<=o.steadyOffsetDelta*d,h=s&&r&&c&&a&&l,f;if(s?a?t.fill<o.fillMin?f="too_small":t.fill>o.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=e)),this.goodSince??(this.goodSince=e),e-this.goodSince>=o.lockMs)return{detected:s,ready:!0,via:"good",blocker:"locking"};let g=this.steadySince!==null&&e-this.steadySince>=o.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:"locking"}}if(this.goodSince=null,m){this.steadySince??(this.steadySince=e);let g=e-this.steadySince>=o.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 q=null;async function ni(i){return q===null&&(q=(await import("./detector-scanic-23DAYT3H.js")).detectQuad),q(i)}async function si(i){let t=$t(i);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 ji(){q===null&&import("./detector-scanic-23DAYT3H.js").then(i=>{q=i.detectQuad}).catch(()=>{})}var Ae=4e3,ri=2,Ee=3,ai=Object.freeze({LOW:3,MID:5,HIGH:6}),kt=Object.freeze({manualShutterMs:6e3,detectedNoLockMs:1950});function Yi(i){let t=i!==null&&typeof i=="object"?i:{},e=(o,n,s)=>typeof o=="number"&&Number.isFinite(o)&&o>=n&&o<=s?o:void 0;return{manualShutterMs:e(t.manualShutterMs,1e3,6e4)??kt.manualShutterMs,detectedNoLockMs:e(t.steadyMs,300,3e4)!==void 0?t.steadyMs+(e(t.lockMs,0,1e4)??450):kt.detectedNoLockMs}}var Le=class i{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=i.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 ot;this.lastFeedbackKey=null;this.lastQuad=null;this.lastDetect=null;this.frameWatch=null;this.reopened=!1;this.lit=!1;this.blackTicks=0;this.offEnded=null;this.opts=t,this.gate=new oe(t.format??"ID-1",t.thresholds);let e=t.deviceClass??Xt(Vt());this.deviceClass=e,this.camera=t.camera??st,this.shutterTuning=t.shutter??kt,this.guideTuning=t.guideLock??J,this.guideLock=new ct(this.guideTuning),this.cadenceMs=1e3/ai[e]}on(t,e){let o=this.handlers.get(t);return o||(o=new Set,this.handlers.set(t,o)),o.add(e),()=>o?.delete(e)}emit(t,e){for(let o of[...this.handlers.get(t)??[]])o(e)}async start(){let t=this.state==="error"?this.resumePlayback():null,e=++this.attempt;if(this.clearFrameWatch(),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.lit=!1,this.blackTicks=0,t!==null&&await t&&e===this.attempt){this.setState("positioning"),this.scheduleTick(e),this.watchFrames(e);return}if(e===this.attempt){this.releaseStream(),Ht(),this.setState("preflight");try{let o=this.opts.getUserMedia??(r=>navigator.mediaDevices.getUserMedia(r));this.setState("acquiring");let n=this.opts.enumerateDevices??(this.opts.getUserMedia===void 0&&typeof navigator<"u"&&navigator.mediaDevices?.enumerateDevices?()=>navigator.mediaDevices.enumerateDevices():void 0),s=await Te({getUserMedia:o,...n!==void 0?{enumerateDevices:n}:{},lensSelection:this.camera.lensSelection,base:le});if(e!==this.attempt){for(let r of s.stream.getTracks())r.stop();return}if(this.stream=s.stream,Ut(this.stream),Wt(this.stream),this.watchEnded(e),this.opts.upgradeResolution!==!1&&await this.upgradeResolution(),e!==this.attempt||(await this.applyFocusAndZoom(),e!==this.attempt)||(this.opts.video.srcObject=this.stream,await this.opts.video.play().catch(()=>{}),e!==this.attempt))return;this.setState("positioning"),this.scheduleTick(e),this.watchFrames(e)}catch(o){if(e!==this.attempt)return;let n=Bt(o),s=Qt(o);this.setState("error"),this.emit("error",{kind:n,retryable:!0,detail:s===void 0?{phase:"acquiring"}:{phase:"acquiring",name:s}})}}}resumePlayback(){let t=this.opts.video,e=this.videoTrack();if(this.stream===null||e===null||e.readyState!=="live"||t.srcObject!==this.stream)return null;try{return Promise.resolve(t.play()).then(()=>this.framesNow(),()=>!1)}catch{return null}}framesNow(){let t=this.opts.video;return this.opts.hasFrames!==void 0?this.opts.hasFrames(t):!t.paused&&t.readyState>=2&&t.videoWidth>0}watchFrames(t){let e=this.opts.firstFrameMs??Ae;e<=0||(this.clearFrameWatch(),this.frameWatch=setTimeout(()=>{if(this.frameWatch=null,!(t!==this.attempt||this.state!=="positioning")){if(this.framesNow()&&this.blackTicks<Ee){this.reopened=!1;return}this.cameraDead(t)}},e))}clearFrameWatch(){this.frameWatch!==null&&clearTimeout(this.frameWatch),this.frameWatch=null}watchEnded(t){this.offEnded?.(),this.offEnded=null;let e=this.videoTrack();if(e===null||typeof e.addEventListener!="function")return;let o=()=>{t===this.attempt&&(this.state==="positioning"||this.state==="acquiring")&&this.cameraDead(t)};e.addEventListener("ended",o),this.offEnded=()=>e.removeEventListener?.("ended",o)}cameraDead(t){if(t!==this.attempt)return;let e=this.videoTrack(),o=e!==null&&e.readyState==="live"&&!e.muted&&this.opts.video.paused&&!this.framesNow();if(!o&&!this.reopened){this.reopened=!0,this.start();return}this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.clearFrameWatch(),o||this.releaseStream(),this.reopened=!1,this.setState("error"),this.emit("error",{kind:"generic",retryable:!0,detail:{phase:"acquiring"}})}releaseStream(){if(this.offEnded?.(),this.offEnded=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject!==null&&this.opts.video.srcObject!==void 0&&(this.opts.video.srcObject=null)}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,e=this.lastDetect?.width??Math.max(1,t.videoWidth),o=this.lastDetect?.height??Math.max(1,t.videoHeight),n=this.lastQuad??this.lastGuideQuad??{topLeft:{x:0,y:0},topRight:{x:e,y:0},bottomRight:{x:e,y:o},bottomLeft:{x:0,y:o}},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:n,{width:e,height:o,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 e=(this.opts.format??"ID-1")==="ID-3"||this.opts.side==="single"?"single":this.opts.side==="verso"?"verso":"recto",o=t.report(e,this.stats.via,(this.opts.now??(()=>performance.now()))());return o===null?{}:{ocr:o}}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 e=t.width/Math.max(1,t.height),o=this.opts.guide;if(o!==void 0&&o.viewAspect>0){let c={width:o.viewAspect,height:1},a={x:o.rect.x*o.viewAspect,y:o.rect.y,width:o.rect.width*o.viewAspect,height:o.rect.height};return Re(c,a,e,0)}let n=Yt(this.opts.format??"ID-1").center,s=.86,r=s*e/n;return r>.84&&(r=.84,s=r*n/e),{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=i.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 e=this.videoTrack();if(e===null||this.zoom<=1)return;let o=this.focusCaps(),n=typeof o?.zoom?.min=="number"?Math.max(o.zoom.min,1):1;this.zoom=n,this.stats.zoomFallbackAtMs=Math.round(t-(this.positioningSince??t)),this.guideLock.reset(),this.gate.reset(),e.applyConstraints({advanced:[{zoom:n}]}).catch(()=>{})}offerShutter(t,e){this.shutterOffered||(this.shutterOffered=!0,this.stats.shutterAtMs=Math.round(e-(this.positioningSince??e)),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.clearFrameWatch(),this.offEnded?.(),this.offEnded=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 e=t.getSettings?.()??{},o=de(t.getCapabilities?.(),{width:e.width??0,height:e.height??0},this.deviceClass,{width:this.camera.width,height:this.camera.height});o!==null&&await t.applyConstraints(o)}catch{}}focusCaps(){try{return this.videoTrack()?.getCapabilities?.()??null}catch{return null}}async applyFocusAndZoom(){let t=this.videoTrack();if(t===null)return;let e=this.focusCaps();this.camera.continuousFocus&&rt(e,"continuous")&&await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{});let o={width:0,height:0};try{let s=t.getSettings?.()??{};o={width:s.width??0,height:s.height??0}}catch{}let n=Se(e,o,this.opts.format??"ID-1",this.camera);if(n>1)try{await t.applyConstraints({advanced:[{zoom:n}]}),this.zoom=n}catch{this.zoom=1}}async focusAt(t,e){let o=this.videoTrack(),n=Mt(this.focusCaps(),t,e);if(!(o===null||n===null))try{await o.applyConstraints({advanced:[n]}),(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,e){let o=this.camera.refocusBeforePhotoMs,n=this.videoTrack();if(o<=0||n===null||e.width<=0||e.height<=0)return;let s=E(t),r=Mt(this.focusCaps(),(s.x+s.width/2)/e.width,(s.y+s.height/2)/e.height);if(r!==null)try{await n.applyConstraints({advanced:[r]});let c=this.opts.setTimer??setTimeout;await new Promise(a=>{c(()=>a(),o)})}catch{}}videoTrack(){try{return this.stream?.getVideoTracks?.()[0]??null}catch{return null}}async takeStill(t,e,o){if(this.opts.captureStill!==void 0)return this.opts.captureStill(this.opts.video,t,e);let n=this.opts.format??"ID-1",s=this.videoTrack();if(o&&this.opts.photoCapture!==!1&&this.deviceClass!=="LOW"&&!this.torchOn&&s!==null&&Me(s)){await this.refocusOn(t,e);let r=await xe(this.opts.video,t,e,n,{track:s,detect:this.detector(),detectWidth:et});if(this.restoreContinuous(),r!==null)return r}return De(this.opts.video,t,e,n)}detector(){return this.opts.detect??((this.opts.format??"ID-1")==="ID-3"?si:ni)}setState(t){this.state=t,this.emit("statechange",{state:t})}scheduleTick(t){let e=this.opts.setTimer??setTimeout;this.timer=e(()=>{this.tick(t)},this.cadenceMs)}async tick(t){if(t!==this.attempt||this.state!=="positioning"||this.capturing)return;let e=this.opts.now??(()=>performance.now()),o=this.opts.grabDetectFrame??Pe,n=this.detector(),s=o(this.opts.video,et);if(s===null){this.scheduleTick(t);return}if(!this.lit){if(dt(s)>ri)this.lit=!0,this.blackTicks=0;else if(++this.blackTicks>=Ee&&this.frameWatch===null&&(this.opts.firstFrameMs??Ae)>0){this.cameraDead(t);return}}let r=null;try{r=await n(s)}catch{r=null}if(t!==this.attempt)return;let c=r!==null?lt(s,r):s,a=e(),l={sharpness:j(c),exposure:jt(c),meanLuma:dt(c),specularFraction:re(c)},u=ae({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"?Fe(s,this.guideRegion(s),{edgePeakFrac:this.guideTuning.edgePeakFrac}):Z,f=this.guideLock.tick(h,a);this.lastGuideQuad=f.detected?Ce(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 _=u.lighting!=="ok"?u.lighting:u.glare!=="ok"?"glare":u.blur!=="ok"?"blurry":"steadying";y.qualityBlockers[_]=(y.qualityBlockers[_]??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<=fi?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 O=a-(this.lastSeenAt??this.positioningSince);this.zoom>1&&this.camera.zoomFallbackMs>0&&O>=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=ne(u);u.framing!=="ok"&&f.detected&&(v=mi(f.blocker,h.brightness<this.guideTuning.darkBrightness)),v==="blurry"&&r!==null&&li(r,s,this.opts.format??"ID-1")>=this.camera.focusFarFillFrac&&(v="focus_far"),v==="sensing"&&this.zoom>1&&this.camera.noDocFarHintMs>0&&O>=this.camera.noDocFarHintMs&&(v="focus_far");let x=this.feedback.tick(v,a);if(x.key!==this.lastFeedbackKey&&(this.lastFeedbackKey=x.key,this.emit("feedback",x)),d.guidanceKey!==this.lastGuidance&&(this.lastGuidance=d.guidanceKey,this.emit("guidance",{key:d.guidanceKey})),this.capturing)return;let M=g?.suspendQuality!==!0,T=M&&d.ready&&r!==null,k=M&&f.ready&&this.lastGuideQuad!==null,C=this.lastOcrReady;if(C!==null&&this.opts.autoCapture!==!1){let _=this.feedback.force("processing",a);this.lastFeedbackKey=_.key,this.emit("feedback",_);let A=j(lt(s,C.quad));await this.fire(t,C.quad,{width:s.width,height:s.height,tickSharpness:A},C.via);return}if((T||k)&&this.opts.autoCapture!==!1){let _=this.feedback.force("processing",a);this.lastFeedbackKey=_.key,this.emit("feedback",_);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,e,o,n){this.capturing=!0;let s=this.opts.grabDetectFrame??Pe,r=this.opts.setTimer??setTimeout,c={width:o.width,height:o.height};try{let a={still:await this.takeStill(e,c,!0),sharpness:o.tickSharpness};if(t!==this.attempt)return;let l=a.still.source==="photo"?0:ui;for(let m=0;m<l;m++){if(await new Promise(g=>{r(()=>g(),hi)}),t!==this.attempt)return;let h=s(this.opts.video,et);if(h===null)continue;let f=j(lt(h,e));if(f>a.sharpness*di){let g=await this.takeStill(e,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&&n!=="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,(n==="text_lock"||n==="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=n,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=n==="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,(n==="text_lock"||n==="live_mrz")&&this.opts.ocr?.rearmFace(),this.scheduleTick(t)}}ocrTick(t,e,o,n,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,D;m&&e!==null?D=ci(E(e),g,y,l,u):D=te(f,c.bandTop,u);let w=m?s.glare==="ok":o.cardGlare<=this.guideTuning.glareMax,O=m?s.blur==="ok":o.sharpness>=this.guideTuning.sharpnessMin,v=c.tick({atMs:r,video:a,mrzFace:m||this.opts.side==="verso"||this.opts.side==="single",present:m||e!==null||n,card:f,band:D,portrait:u>l,glareOk:w,sharpOk:O});if(v.ready&&v.via!==void 0){let x=m?e??Oe(h,t):this.lastGuideQuad??Oe(h,t);this.lastOcrReady={quad:x,via:v.via}}else this.lastOcrReady=null;return v}};function ci(i,t,e,o,n){let s=Math.min(o,i.width*1.06*t),r=Math.min(n,Math.max(i.height*1.6*e,s/5)),c=(i.y+i.height/2)*e,a=Math.max(0,Math.min(o-s,(i.x-i.width*.03)*t)),l=Math.max(0,Math.min(n-r,c-r/2));return{x:a,y:l,w:s,h:r}}function Oe(i,t){let e=i.x*t.width,o=i.y*t.height,n=(i.x+i.width)*t.width,s=(i.y+i.height)*t.height;return{topLeft:{x:e,y:o},topRight:{x:n,y:o},bottomRight:{x:n,y:s},bottomLeft:{x:e,y:s}}}function li(i,t,e){let o=E(i);return t.width<=0||t.height<=0?0:e==="ID-3"?o.width/t.width:o.width*o.height/(t.width*t.height)}var ui=2,hi=260,di=1.08;function Pe(i,t){let e=i.videoWidth,o=i.videoHeight;if(e===0||o===0)return null;let n=Math.min(1,t/e),s=Math.round(e*n),r=Math.round(o*n),c=document.createElement("canvas");c.width=s,c.height=r;let a=c.getContext("2d",{willReadFrequently:!0});return a===null?null:(e/Math.max(1,s)>4&&(a.imageSmoothingQuality="high"),a.drawImage(i,0,0,s,r),a.getImageData(0,0,s,r))}function lt(i,t){let e=[t.topLeft.x,t.topRight.x,t.bottomRight.x,t.bottomLeft.x],o=[t.topLeft.y,t.topRight.y,t.bottomRight.y,t.bottomLeft.y],n=Math.max(0,Math.floor(Math.min(...e))),s=Math.max(0,Math.floor(Math.min(...o))),r=Math.min(i.width,Math.ceil(Math.max(...e))),c=Math.min(i.height,Math.ceil(Math.max(...o))),a=Math.max(1,r-n),l=Math.max(1,c-s),u=new Uint8ClampedArray(a*l*4);for(let d=0;d<l;d++){let m=((s+d)*i.width+n)*4;u.set(i.data.subarray(m,m+a*4),d*a*4)}return{data:u,width:a,height:l,colorSpace:i.colorSpace}}function mi(i,t){return i==="glare"?"glare":i==="too_small"?"too_far":i==="too_big"?"too_close":t?"too_dark":i==="blurry"?"blurry":i==="off_center"?"edge_clipped":i==="no_card"?"sensing":"hold_still"}var fi=1200;export{it as a,ne as b,ot as c,Xe as d,re as e,je as f,ae as g,st as h,Si as i,bt as j,ii as k,we as l,rt as m,Mt as n,_i as o,Se as p,oi as q,Te as r,Z as s,Re as t,Fe as u,Ce as v,J as w,Ai as x,ct as y,ji as z,Ae as A,ri as B,Ee as C,ai as D,kt as E,Yi as F,Le as G,ci as H,ui as I,hi as J};
@@ -0,0 +1 @@
1
+ import{A as Re,D as w,E as j,d as K,e as ge,f as ye,g as be,i as _e,j as ee,l as q,m as te,o as Ce,p as Pe,t as ke}from"./chunk-ZCW6PNUX.js";import{c as me,d as he,e as Se}from"./chunk-FPXL63KZ.js";import{c as F,h as Q,i as Me}from"./chunk-XOTKATN6.js";var Ae=["AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AS","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CW","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IR","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","XK","YE","YT","ZA","ZM","ZW"];var qe=["carte_identite","passport","residence_permit","drivers_license"],Qe=["carte_identite","passport","residence_permit"];function Je(e,t){let o=e.byIssuer?.[t]??e.default;return qe.filter(s=>o==="*"?Qe.includes(s):o.includes(s))}function zt(e,t=Ae){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(s=>Je(e,s).length>0).sort()}function Ee(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}var ze=640,Xe=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),Ie=6,ve=1500,Oe={sharpness:1,exposure:1,meanLuma:128},Te=null;function et(e,t){try{Te??(Te=document.createElement("canvas"));let o=Te,s=96/Math.max(1,t.width);o.width=Math.max(1,Math.round(t.width*s)),o.height=Math.max(1,Math.round(t.height*s));let i=o.getContext("2d");if(i===null)return Oe;i.drawImage(e,t.x,t.y,t.width,t.height,0,0,o.width,o.height);let c=i.getImageData(0,0,o.width,o.height);return{sharpness:he(c),exposure:Se(c),meanLuma:me(c)}}catch{return Oe}}async function tt(e,t){let o=e.source;return"convertToBlob"in o?o.convertToBlob({type:"image/jpeg",quality:t}):new Promise((s,i)=>{o.toBlob(c=>c===null?i(new Error("encode failed")):s(c),"image/jpeg",t)})}function on(e,t={}){let o=t.now??(()=>performance.now()),s=t.setTimer??((f,_)=>setTimeout(f,_)),i=t.clearTimer??(f=>clearTimeout(f)),c=t.encode??tt,d=t.quality??et,u=e.tuningVersion??null,p=new Set,S=!1,y=e.video??null,M=null,m=t.grabFrame??null,b=null,v=1e3/Ie,E=null,I=null,O=!1,L=!1,D=Number.NEGATIVE_INFINITY,A=null,G=0,V=null,B=null,z=Promise.all([import("./icao-gate-T3BTOKFJ.js"),import("./icao-tuning-4ETMF53W.js"),import("./create-portrait-capture-5VGYZUOK.js"),import("./landmarker-KB7LVXAU.js"),import("./background-monitor-A7FKJOAG.js")]).then(async([f,_,R,x,T])=>{let k=_.resolveIcaoTuning(e.tuning,e.tuningVersion??void 0);k.background.required&&(I=T.createBackgroundMonitor({tuning:k.backgroundCheck,assetBaseUrl:e.assetBaseUrl??"/models-v3",...t.createSegmenter!==void 0?{createSegmenter:t.createSegmenter}:{},now:o})),M=f.createIcaoGate(k,{policy:e.policy??"reject"}),m??(m=R.defaultGrabber()),b=R.observe,v=1e3/Math.min(Ie,k.cadenceHz);let n=(t.createLandmarker??x.createFaceLandmarker)(e.assetBaseUrl??"/models-v3"),r=await new Promise((a,l)=>{let h=setTimeout(()=>{l(new Error("landmarker init timeout")),n.then(g=>g.close(),()=>{})},x.LANDMARKER_INIT_TIMEOUT_MS);n.then(g=>{clearTimeout(h),a(g)},g=>{clearTimeout(h),l(g)})});S?r.close():E=r}).catch(()=>{O=!0}),H=f=>{for(let _ of p)_({holding:L||O,update:f})},Y=()=>{if(A=null,!(S||E===null||M===null||m===null||b===null||y===null)){if(o()-D>ve){H(null);return}try{let f=m(y,ze);if(f!==null){let _=Math.max(o(),G+1);G=_;let R=E.detect(f.source,_),x=y.videoWidth||f.width,T=y.videoHeight||f.height,k=b(R,f,x,T);k.geometry!==null&&I!==null&&(k.backgroundCheck=I.measure(f,k.geometry.box,x,T));let n=M.push(k,o());L=n.ready,H(n)}}catch{}A=s(Y,v)}},Z=()=>{let f=o()-D>ve;D=o(),f&&(M?.reset(),L=!1,V=null,B=null),A===null&&E!==null&&!S&&(A=s(Y,0))},X=()=>{let f=m===null||y===null?null:m(y,null);if(f===null||M===null||Math.max(f.width,f.height)<e.still.minLongSidePx)return Promise.resolve(null);let _=M.summary();return c(f,e.still.jpegQuality).then(R=>({image:R,width:f.width,height:f.height,gate:_}),()=>null)},W=null;return{engineOptions:{measureQuality:(f,_)=>{y=f,Z();let R=d(f,_);return L||O?R:{...R,sharpness:0}},telemetry:f=>{if(f.type!=="fired"||S)return;V=X();let _=W;_!==null&&V.then(R=>R===null?void 0:_(R).catch(()=>{})),L=!1,A!==null&&i(A),A=null,D=Number.NEGATIVE_INFINITY}},decorate:f=>{let _=new WeakMap,R=new Map,x=r=>{let a=_.get(r);return a===void 0&&(a=(async()=>{let l=await ke(f,"image","image/jpeg",r.image.size,{engine:"portrait"});return await f.uploadToSpaces(l.uploadUrl,r.image,"image/jpeg"),(await f.completeMedia(l.key)).key})(),a.catch(()=>_.delete(r)),_.set(r,a)),a};W=x;let T=async r=>{let a;try{a=await x(r)}catch(l){let h=l?.code;if(typeof h=="string"&&Xe.has(h))throw l;return null}return{media:{portrait:a},gate:Me(r.gate),...u!==null?{tuningVersion:u}:{}}},k=f.submitCheck.bind(f),n=(async(r,a,l)=>{if(r!=="liveness")return k(r,a,l);let h=l?.idempotencyKey,g=h===void 0?void 0:R.get(h);if(g===void 0){let pe=V;g=pe===null?Promise.resolve(null):pe.then(fe=>fe===null?null:T(fe)),h!==void 0&&(R.set(h,g),g.catch(()=>R.delete(h)))}let C=await g;if(C===null)return k("liveness",a,l);let P=await k("liveness",{...a,portraitIcao:C},l);return B=C,P});return new Proxy(f,{get(r,a){if(a==="submitCheck")return n;let l=Reflect.get(r,a);return typeof l=="function"?l.bind(r):l}})},onGate:f=>(p.add(f),()=>p.delete(f)),lastPortraitInput:()=>B,destroy:()=>{S=!0,V=null,B=null,A!==null&&i(A),A=null,p.clear(),z.then(()=>{E?.close(),E=null,I?.close(),I=null})}}}function xe(e){return e.idNumberBound??e.nniBound}function we(e){return e===void 0?void 0:e.idNumberFromDocument??e.nniFromDocument}function Ne(e){let t=e.idNumberMasked??e.nniMasked;return typeof t=="string"&&t!==""?t:void 0}var Le=Object.freeze({nni_invalid:"id_number_invalid",nni_not_found:"registry_record_not_found",nni_recheck:"id_number_recheck",document_nni_mismatch:"document_id_number_mismatch",nni_locked:"id_number_locked",nni_unbound:"id_number_unbound",missing_nni:"missing_id_number",registry_needs_nni_source:"registry_needs_id_number_source"}),nt=new Map(Object.entries(Le)),an=new Map(Object.entries(Le).map(([e,t])=>[t,e]));function Ve(e){return nt.get(e)??e}var ot=new Set(["phone_otp","email_otp","national_eid","document","nfc","population_registry","supplied_identity","summary_confirm","liveness","portrait","face_match","aml_screening","face_dedup","age_estimation","proof_of_address"]),it=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),oe=["document","population_registry","national_eid"],ie=["phone_otp","email_otp"],Ge={identity_method:oe,contact:ie},rt=["population_registry","document"],re="platform_unsupported",st=new Set(["prefilled","user_entered","prefilled_or_entered"]),at={phone_otp:"contact",email_otp:"contact",eid_auth:"identity",doc_ocr:"identity",nfc_chip:"identity",population_registry:"identity",liveness:"live_photo",portrait_icao:"live_photo",face_match:"live_photo",poa:"documents"};function N(e){return e.section??at[e.checkType]??null}function se(e,t){let o=e.plan?.choice;if(o===void 0||o.locked)return;let s=o.options.find(i=>i.id!==o.selected&&i.available!==!1&&t.includes(i.service));return s===void 0?void 0:{nodeId:o.nodeId,option:s}}function ae(e){let t=e.plan,o=t?.choice;if(t===void 0||o===void 0||o.locked||t.current===null||t.current===o.nodeId||ee(e))return null;let s=Ge[o.kind]??[...oe,...ie],i=o.options.flatMap(u=>u.available===!1||!s.includes(u.service)?[]:[u.nationalEid!=null?{id:u.id,service:u.service,nationalEid:u.nationalEid}:{id:u.id,service:u.service}]),c=t.steps.find(u=>u.id===t.current)?.service,d=o.selected??i.find(u=>u.service===c)?.id??null;return i.some(u=>u.id!==d)?{nodeId:o.nodeId,kind:o.kind,current:d,options:i}:null}function Be(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function ct(e){let t=e.simulation;if(typeof t!="object"||t===null)return;let{otpCode:o,skipCapture:s}=t;return typeof o=="string"&&o!==""&&typeof s=="boolean"?{otpCode:o,skipCapture:s}:void 0}function ut(e){let t=(e.plan?.sections??[]).map(d=>({id:d.id,state:d.state})),o={sessionId:te(e.sessionId),orgName:e.orgName,sandbox:e.sandbox===!0,returning:e.returning===!0,consentRecorded:e.consentRecorded,expiresAt:e.expiresAt,sections:t.map(d=>d.id),progress:t,purpose:e.purpose??"identity"};e.branding!==void 0&&(o.branding=e.branding),e.cameraUnavailableHandled===!0&&(o.cameraUnavailableHandled=!0);let s=ct(e);s!==void 0&&(o.simulation=s);let i=e.testerGate;i?.offered===!0&&typeof i.attemptsLeft=="number"&&i.attemptsLeft>0&&(o.testerGate={attemptsLeft:i.attemptsLeft});let c=ae(e);return c!==null&&(o.switchable=c),o}function dt(e){let t={attemptsRemaining:ye(e),attemptsExhausted:e.attempts.used>=e.attempts.max};return e.reason!==void 0&&(t.reason=e.reason),e.retakeHint!==void 0&&(t.retakeHint=e.retakeHint),t}var Ue={phone_otp:"phone",email_otp:"email"};function lt(e,t){let o=se(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return o===void 0?void 0:Ue[o.option.service]}function pt(e,t,o,s){let i=t.checkType==="email_otp",c=(i?t.emailOtp:t.otp)??{},d=i?t.emailOtp?.emailSource:t.otp?.numberSource,u=d!==void 0&&st.has(d)?d:i?"prefilled_or_entered":"user_entered",p=typeof c.sentToMasked=="string"&&c.sentToMasked.length>0,S=c.prefilled===!0,y=lt(e,i?"email_otp":"phone_otp"),M={key:t.checkType,context:o,section:N(t),phase:p?"verify":"send",canSwitch:y!==void 0,...s},m=i?{kind:"email_otp",...M,emailSource:u,needsEmail:u!=="prefilled"&&!S}:{kind:"phone_otp",...M,numberSource:u,needsPhone:u!=="prefilled"&&!S,channels:(t.otp?.channels??[]).filter(b=>b==="whatsapp"||b==="sms")};if(y!==void 0&&(m.switchChannel=y),S&&(m.prefilled=!0),p&&(m.sentToMasked=c.sentToMasked),!i&&t.otp?.channel!==void 0&&(m.channel=t.otp.channel),!i&&Array.isArray(t.phoneCountries)&&(m.phoneCountries=t.phoneCountries.filter(b=>typeof b=="string"&&/^[A-Z]{2}$/.test(b))),!i&&Array.isArray(t.phoneRules)){let b=m.phoneCountries??[];m.phoneRules=t.phoneRules.flatMap(v=>{let E=ht(v);return E!==void 0&&b.includes(E.code)?[E]:[]})}return!i&&t.phoneInternational===!0&&(m.phoneInternational=!0),c.expiresAt!==void 0&&(m.codeExpiresAt=c.expiresAt),c.resendAvailableAt!==void 0&&(m.resendAvailableAt=c.resendAvailableAt),m}var ft=/^[\d[\]\-|()?:^]{1,64}$/;function mt(e){try{return typeof e=="string"&&ft.test(e)&&new RegExp(e)!==null}catch{return!1}}var De=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function ht(e){let{code:t,dial:o,trunk:s,lengths:i,formats:c}=e??{};if(typeof t!="string"||typeof o!="string"||!/^\d{1,3}$/.test(o)||s!==void 0&&(typeof s!="string"||!/^\d{1,3}$/.test(s))||!Array.isArray(i)||i.length===0||!i.every(De))return;let d={code:t,dial:o,lengths:[...i].sort((u,p)=>u-p)};if(s!==void 0&&(d.trunk=s),c!==void 0){if(!(Array.isArray(c)&&c.length<=8&&c.every(p=>mt(p?.leading)&&Array.isArray(p.groups)&&p.groups.every(De)&&i.includes(p.groups.reduce((S,y)=>S+y,0)))))return;d.formats=c.map(p=>({leading:p.leading,groups:[...p.groups]}))}return d}function St(e,t,o,s){let i=xe(e)===!0?"bound":we(t)===!0?"document":"typed",c=i==="typed"&&t.state==="input_required"&&t.reason!==void 0&&Ve(t.reason)==="id_number_recheck",d=Be(ae(e)),u=!s.attemptsExhausted&&d.length===1&&d[0]?.service==="document";return{kind:"registry",key:"registry",context:o,section:N(t),state:t.state==="input_required"?"input_required":"pending",source:i,recheck:c,canUseDocument:u,...s}}function gt(e,t,o,s,i){let c=[...t.acceptedSides??[]],d={kind:"document",key:"document",context:o,section:N(t),side:c.includes("recto")?"verso":"recto",acceptedSides:c,documents:Ee(e),photo:ue(ce(e.documents),i),...s};return e.detectedCountry!==void 0&&(d.detectedCountry=e.detectedCountry),_t(e)&&(d.ageStepUp=!0),d}function ce(e,t=!0){let o=e?.source==="upload"||e?.source==="choice"?e.source:"camera",s=e?.sourcePick==="camera"||e?.sourcePick==="upload"?e.sourcePick:null;return{source:o,pick:s,uploadOffered:t&&e?.uploadOffered===!0}}function ue(e,t){return t?{...e,cameraOnPhone:!0}:e}var yt=10*1024*1024;function bt(e,t,o,s,i){let c=e.proofOfAddress,d=c?.pdf?.maxBytes,u=c?.phase==="holder_letter"?"holder_letter":"document";return{kind:"proof_of_address",key:"proof_of_address",context:o,section:N(t),phase:u,rule:c?.rule??{country:null,countryFrom:"global",source:"preset_global",kinds:[]},nameMatch:c?.nameMatch??"exact_person",photo:ue(ce(c),i),maxPages:3,pdf:{maxBytes:typeof d=="number"&&d>0?d:yt,maxPages:3},licenceAddressAccepted:u==="document"&&c?.licenceAddressAccepted===!0,...s}}function _t(e){let t=ge(e).find(s=>s.checkType==="age_estimation"),o=t?.reason;return t?.state==="failed"&&(o==="age_uncertain"||o==="age_unavailable")}function Ct(e){let t=q(e,"liveness");return t?.state==="passed"||t?.state==="review"}function He(e,t,o,s,i,c=!1){let d=t.icao?.report,u=e.portrait,p=i==="capture"?u?.pendingFix??null:null;p!==null&&(i="review");let S=Fe(e);return{kind:"portrait",key:`portrait:${i}`,context:o,section:N(t),phase:i,report:Array.isArray(d)?d:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:Q(e),retakeOnly:i==="capture"&&t.state==="input_required"&&S===void 0&&e.capture?.livePhoto?.oneCapture===!0&&Ct(e),photo:ue(ce(u,i==="capture"),c&&i==="capture"),pendingFix:p,...S!==void 0?{captureMode:S}:{},...u?.reuse?.pending===!0?{reuse:!0}:{},...s}}function Fe(e){let t=e.portrait?.captureMode;return t==="self"||t==="assisted"||t==="choice"?t:void 0}var ne={minLongSidePx:1280,jpegQuality:.95};function Pt(e,t){let o=e.capture?.livePhoto;if(o?.oneCapture!==!0)return null;let s=q(e,"portrait_icao"),i=o.still??ne;return{icao:t==="liveness"&&Q(e)!==null&&Fe(e)===void 0&&s!==void 0&&s.state==="pending"&&s.reason===void 0,still:{minLongSidePx:i.minLongSidePx??ne.minLongSidePx,jpegQuality:i.jpegQuality??ne.jpegQuality}}}function kt(e,t,o,s){let i=t.eid,c=N(t);if(i===void 0||i.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:o,section:c,checkType:"eid_auth",reason:"update_required"};let d=Be(ae(e)),u=d.length===1&&rt.includes(d[0]?.service??"")?d[0]:void 0,p=u===void 0?void 0:K[u.service],S=p!==void 0,y={kind:"eid",key:"eid",context:o,section:c,provider:i.provider,providerName:i.providerName,country:i.country,challenge:"app_code",phase:i.awaiting==="code"?"code":"identifier",identifierBound:i.identifierBound===!0,canUseCamera:S,afterPass:i.afterPass==="continue"?"continue":"end",...s};return S&&(y.cameraMethod=p),i.expiresAt!==void 0&&(y.codeExpiresAt=i.expiresAt),i.resendAvailableAt!==void 0&&(y.resendAvailableAt=i.resendAvailableAt),i.resendsRemaining!==void 0&&(y.resendsRemaining=i.resendsRemaining),i.codeAttemptsRemaining!==void 0&&(y.codeAttemptsRemaining=i.codeAttemptsRemaining),y}function Rt(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let o=q(e,"portrait_icao");return o!==void 0&&(o.state==="passed"||o.state==="review")?o:null}var Mt={rejected:"rejected",inconclusive:"inconclusive",unavailable:"unavailable",abandoned:"expired",not_opened:"expired",cancelled:"expired",superseded:"expired",policy:"policy"};function At(e){return e.reasonCode===re?"platform_unsupported":e.status==="review_pending"?"review":e.status==="verified"?"verified":e.reasonCode==="device_cooldown"?"cooldown":e.reasonCode==="starter_credit_claimed"?"policy":(e.status==="not_verified"&&e.reason!==void 0?Mt[e.reason]:void 0)??"rejected"}function Et(e,t){let o=At(e),s=o==="platform_unsupported"?{sessionId:te(e.sessionId),status:"unavailable",reasonCode:re}:Ce(e,{autoRetry:!1}),i={kind:"result",key:"result",context:t,section:null,display:o,result:s};return e.status==="not_verified"&&e.reason!==void 0&&(i.reason=e.reason),e.reasonCode!==void 0&&(i.reasonCode=e.reasonCode),e.status==="not_verified"&&e.step!==void 0&&(i.step=e.step),e.retryAfter!==void 0&&(i.retryAfter=e.retryAfter),i}function It(e,t,o){let s=e.identitySummary;if(s==null)return null;let i={kind:"identity_summary",key:"identity_summary",context:t,section:o??"identity",summaryKind:s.kind==="partial"?"partial":s.kind??"full",source:s.source,portraitAvailable:s.portrait?.available===!0,retakeAvailable:s.retakeAvailable===!0};for(let d of vt){let u=s[d];typeof u=="string"&&u!==""&&(i[d]=u)}let c=Ne(s);return c!==void 0&&(i.idNumberMasked=c,i.nniMasked=c),i}var vt=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","expiryDate","retakeTarget"];function U(e,t,o,s){return{kind:"unsupported",key:`unsupported:${o}`,context:e,section:t,checkType:o,reason:s}}function Ot(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function Tt(e,t){let o=Ge[e.kind]??[...oe,...ie],s=Ot(e),i=e.options.flatMap(d=>{if(d.available===!1||!o.includes(d.service))return[];let u={id:d.id,service:d.service};d.nationalEid!=null&&(u.nationalEid=d.nationalEid);let p=(d.channels??[]).filter(S=>S==="whatsapp"||S==="sms");return d.service==="phone_otp"&&p.length>0&&(u.channels=p),[u]});if(i.length===0){let d=e.options.length>0&&e.options.every(u=>u.service==="nfc");return U(t,s,"choice",d?"platform_unsupported":"update_required")}let c={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:i};if(e.kind==="identity_method"){let d={kind:"method",key:"method",context:t,section:s,options:i.map(p=>K[p.service]),choice:c},u=i.find(p=>p.nationalEid!==void 0)?.nationalEid;return u!==void 0&&(d.nationalEid=u),d}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:s,options:i.map(d=>Ue[d.service]),selected:null,locked:!1,choice:c}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:s,choice:c}}function J(e,t={}){let o=ut(e);if(ee(e)||e.reasonCode===re)return Et(e,o);let s=e.plan;if(s===void 0||!Array.isArray(s.sections))return U(o,null,"plan","update_required");let i=be(e);if(i!==null)return Tt(i,o);let c=s.current===null?void 0:s.steps.find(m=>m.id===s.current),d=m=>{let b={kind:"processing",key:"processing",context:o,section:m!==void 0?N(m):s.sections.find(v=>v.state==="current")?.id??null,stalled:!1};return typeof m?.service=="string"&&m.service!==""&&(b.service=m.service),b};if(s.current===null)return d(s.steps.find(m=>m.state==="processing"));if(c===void 0)return U(o,null,"step","update_required");if(!ot.has(c.service))return c.interaction==="server"?d(c):U(o,N(c),c.service,"update_required");if(it.has(c.service)||!_e(c))return d(c);let u=c,p=dt(u),S=u.checkType,y=N(u),M=t.isMobile===!1?Pe(e,u):null;if(M==="phone")return{kind:"mobile_required",key:"mobile_required",context:o,section:y,checkType:S};switch(S){case"phone_otp":case"email_otp":return pt(e,u,o,p);case"population_registry":return St(e,u,o,p);case"eid_auth":return kt(e,u,o,p);case"doc_ocr":return gt(e,u,o,p,M==="upload_or_phone");case"identity_confirm":return It(e,o,y)??d(u);case"portrait_icao":return He(e,u,o,p,"capture",M==="upload_or_phone");case"liveness":case"face_match":{let m=Rt(e,u);if(m!==null)return He(e,m,o,p,"match");let b=u.requiresMobile===!0,v=Q(e);return{kind:"liveness",key:"biometric",context:o,section:y,mode:S==="face_match"?"selfie":"liveness",requiresMobile:b,instructions:v===null?"standard":"icao",icao:v,livePhoto:Pt(e,S),...p}}case"poa":return bt(e,u,o,p,M==="upload_or_phone");case"nfc_chip":return U(o,y,S,"platform_unsupported");default:return U(o,y,S,"update_required")}}var xt=/^[A-Z0-9][A-Z0-9 -]{0,39}$/,wt=Object.freeze({normalize:e=>e.trim().toUpperCase().replace(/\s+/g," "),check:e=>xt.test(e),registrySources:Object.freeze([]),describe:"number must be 1 to 40 letters, digits, spaces or hyphens"}),Nt=/^[A-Z0-9]{4,20}$/,Ke=e=>e.trim().toUpperCase().replace(/[\s-]+/g,""),je=Object.freeze({normalize:Ke,check:e=>Nt.test(Ke(e)),registrySources:Object.freeze([]),describe:"number must be 4 to 20 letters or digits"});function Lt(e){return typeof e=="string"&&/^\d{10}$/.test(e)&&Number(e)%97===1}var Vt=Object.freeze({normalize:e=>e.trim(),check:e=>Lt(e),registrySources:Object.freeze(["MR.anrpts"]),describe:"number must be the 10-digit Mauritanian national ID number with a valid check digit"}),Dt=Object.freeze({...je,check:e=>/^\d{8}$/.test(e.trim()),describe:"number must be the 8-digit Mauritanian driver's license number"}),Ht=Object.freeze({"MR:national_id":Vt,"MR:drivers_license":Dt});function de(e,t){return Ht[`${e.toUpperCase()}:${t}`]??(t==="drivers_license"?je:wt)}var Gt=Object.freeze({MRT:"MR"});function Ye(e,t){let o=e.trim().toUpperCase();return de(Gt[o]??o,t)}function Ze(e){let t=Ye(e.issuingCountry,e.type);return t.check(t.normalize(e.number))}function We(e){return de("MR","national_id").check(e)}function le(e){let t="";for(let o of e){let s=o.codePointAt(0)??0;s>=1632&&s<=1641?t+=String(s-1632):s>=1776&&s<=1785?t+=String(s-1776):o!==" "&&o!=="-"&&o!==" "&&(t+=o)}return t}var Bt=[1e3,2e3,4e3,8e3,15e3],Ut=3e4,Ft=/^\+[1-9]\d{6,14}$/,Kt=/^\d{6}$/,jt=/^\d{6}$/,Yt=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,$e=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order","identity_confirm_required","identity_confirm_locked","choice_locked","choice_option_unavailable","choice_not_found","step_not_on_path","check_not_active"]),Zt={simulatedCapture:!0},Wt=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]);function Mn(e){let t=!1,o=null,s="",i=!1,c=!1,d=!1,u={},p={},S=new Set,y=!1,M=!1,m=null,b="idle",v=new Map,E=new Map,I=(n,r,a)=>{let l=`${n}.${r}`,h=v.get(l);if(h!==void 0)return h;let g=E.get(n),C=(g===void 0?a():g.then(a)).finally(()=>{v.delete(l)});v.set(l,C);let P=C.then(()=>{},()=>{});return E.set(n,P),P.then(()=>{E.get(n)===P&&E.delete(n)}),C},O=async(n,r,a)=>{await e.ensureConsent();let l;try{l=await Re(e.runtime,r)}catch(g){if(g instanceof F&&$e.has(g.code)){await e.refreshView();return}throw g}if(a?.(l),e.destroyed())return;let h=l;h.plan!==void 0&&e.setView!==void 0?e.setView(h):await e.refreshView()},L=async n=>{await e.ensureConsent();let r;try{try{r=await n(e.runtime.client)}catch(a){if(!(a instanceof F)||a.code!=="consent_required")throw a;await e.runtime.ensureConsent({force:!0}),r=await n(e.runtime.client)}}catch(a){if(a instanceof F&&$e.has(a.code)){await e.refreshView();return}throw a}e.destroyed()||(r!==void 0&&e.setView!==void 0?e.setView(r):await e.refreshView())},D=(n,r)=>I("choice",`${n}:${r}`,()=>L(a=>a.choose(n,r))),A=(n,r)=>n.options.some(a=>a.id===r)?D(n.nodeId,r):Promise.reject(new RangeError(`option ${String(r)} is not offered`)),G=(n,r)=>{let a=e.currentView(),l=a===null?void 0:se(a,n);return l===void 0?Promise.reject(new RangeError(`the ${r} is not offered`)):D(l.nodeId,l.option.id)},V=n=>I("identity",n,()=>L(r=>r.confirmIdentity===void 0?Promise.reject(new Error("identity confirmation is not available in this build")):r.confirmIdentity(n))),B=(n,r)=>{let a=n.kind,l=a==="phone_otp",h=l?"phone":"email",g={action:"send"};if(l?n.needsPhone:n.needsEmail){let C=r[h]??p[a],P=l?C?.replace(/[\s().-]/g,""):C?.trim();if(P!==void 0||n.phase!=="verify"){if(P===void 0||!(l?Ft:Yt).test(P))return Promise.reject(l?new w("phone","format"):new j("email","format"));g[h]=P}}if(l){let C=n.channels,P=r.channel??(C.length===1?C[0]:void 0);if(C.length>0){if(P===void 0)return Promise.reject(new j("channel","required"));if(!C.includes(P))return Promise.reject(new j("channel","unavailable"))}P!==void 0&&(g.channel=P),g.phoneRules=1}return I(a,"send",()=>O(a,(C,P)=>C.submitCheck(a,g,{idempotencyKey:P}),C=>{qt(C,a)||(u[a]=e.now(),g[h]!==void 0&&(p[a]=g[h]))}))},z=(n,r)=>Kt.test(r)?I(n,"verify",()=>O(n,(a,l)=>a.submitCheck(n,{action:"verify",code:r},{idempotencyKey:l}))):Promise.reject(new w("code","format")),H=(n,r)=>I("eid_auth",n,()=>O("eid_auth",(a,l)=>a.submitCheck("eid_auth",r,{idempotencyKey:l}))),Y=(n,r)=>{if(n.identifierBound)return H("start",{action:"start"});let a=le(r??"");if(n.country==="MR"){if(!/^\d{10}$/.test(a))return Promise.reject(new w("nni","format"));if(!We(a))return Promise.reject(new w("nni","check_digit"))}else if(a==="")return Promise.reject(new w("nni","format"));return H("start",{action:"start",identifier:a})},Z=(n,r,a)=>{if(n.source!=="typed")return Promise.reject(new RangeError("this session already holds the ID number"));let l=le(r);return/^\d{10}$/.test(l)?Ze({type:"national_id",issuingCountry:"MR",number:l})?I("population_registry","submitIdNumber",()=>O("population_registry",(h,g)=>h.submitCheck("population_registry",{idNumber:l,nni:l},{idempotencyKey:g}),()=>{m=`\u2022\u2022\u2022\u2022\u2022\u2022${l.slice(-4)}`})):Promise.reject(new w(a,"check_digit")):Promise.reject(new w(a,"format"))},X=n=>(e.stopCameras?.(),I(n,"skipCapture",()=>O(n,(r,a)=>r.submitCheck(n,Zt,{idempotencyKey:a}),()=>{(n==="liveness"||n==="portrait_icao")&&(y=!0)}))),W=n=>{if(n.kind==="result"||n.context.simulation?.skipCapture!==!0)return n;let r=$t(n);return r===null?n:{...n,skipCapture:()=>X(r)}},$=n=>((n.kind==="document"||n.kind==="portrait"||n.kind==="proof_of_address")&&n.photo?.cameraOnPhone===!0&&(n.refresh=async()=>{await e.refreshView()}),n),f=n=>{switch(n.kind){case"phone_otp":case"email_otp":{let r={...n,send:(l={})=>B(n,l),verify:l=>z(n.kind,l),switchTo:()=>n.canSwitch&&n.switchChannel!==void 0?G([n.switchChannel==="email"?"email_otp":"phone_otp"],"other contact option"):Promise.reject(new RangeError("this session has no other contact option"))},a=u[n.kind];return r.resendAvailableAt===void 0&&a!==void 0&&(r.resendAvailableAt=new Date(a+Ut).toISOString()),r}case"eid":return{...n,start:r=>Y(n,r),verify:r=>jt.test(r)?H("verify",{action:"verify",code:r}):Promise.reject(new w("code","format")),resend:()=>n.resendsRemaining===0?Promise.reject(new RangeError("no new code can be sent for this session")):H("resend",{action:"resend"}),useCamera:()=>n.canUseCamera&&n.cameraMethod!==void 0?G(n.cameraMethod==="document_photo"?["document"]:["population_registry"],"camera path"):Promise.reject(new RangeError("the camera path is not offered"))};case"method":return{...n,select:r=>{let a=n.choice.options.find(l=>K[l.service]===r);return a!==void 0?A(n.choice,a.id):Promise.reject(new RangeError(`method ${String(r)} is not offered`))},choose:r=>A(n.choice,r)};case"choice":return{...n,choose:r=>A(n.choice,r)};case"registry":return{...n,submitIdNumber:r=>Z(n,r,"idNumber"),submitNni:r=>Z(n,r,"nni"),confirm:()=>I("population_registry","confirm",()=>O("population_registry",(r,a)=>r.submitCheck("population_registry",{},{idempotencyKey:a}))),useDocument:()=>n.canUseDocument?G(["document"],"document method"):Promise.reject(new RangeError("the document method is not offered"))};case"document":return e.bindDocument!==void 0?$(e.bindDocument(n,k)):{...n,issuer:null,documentType:null,captureSide:null,selectDocument:()=>{throw new Error("document capture is not available in this build")},capture:()=>{throw new Error("document capture is not available in this build")},uploadDocument:()=>Promise.reject(new Error("document upload is not available in this build"))};case"portrait":return e.bindPortrait!==void 0?$(e.bindPortrait(n,k)):{...n,uploadFailed:!1,resubmit:()=>Promise.resolve(),capture:()=>{throw new Error("portrait capture is not available in this build")},uploadPortrait:()=>Promise.reject(new Error("portrait upload is not available in this build")),confirmFix:()=>Promise.reject(new Error("portrait review is not available in this build"))};case"proof_of_address":return e.bindProofOfAddress!==void 0?$(e.bindProofOfAddress(n,k)):{...n,uploadPages:()=>Promise.reject(new Error("proof of address upload is not available in this build")),uploadHolderLetter:()=>Promise.reject(new Error("proof of address upload is not available in this build")),capturePage:()=>{throw new Error("proof of address capture is not available in this build")}};case"contact_choice":return{...n,select:r=>{let a=r==="phone"?"phone_otp":r==="email"?"email_otp":void 0,l=n.choice.options.find(h=>h.service===a);return l!==void 0?A(n.choice,l.id):Promise.reject(new RangeError(`contact ${String(r)} is not offered`))},choose:r=>A(n.choice,r)};case"identity_summary":return{...n,...n.idNumberMasked===void 0&&n.summaryKind==="partial"&&m!==null?{idNumberMasked:m,nniMasked:m}:{},portrait:async()=>{let r=e.runtime.client;if(!n.portraitAvailable||r.identityPortrait===void 0)return null;try{return await r.identityPortrait()}catch{return null}},confirm:()=>V("confirm"),retake:()=>n.retakeAvailable?V("retake"):Promise.reject(new RangeError("no retake is left"))};case"liveness":return{...n,capture:r=>e.liveness(r),onLivePhoto:r=>n.livePhoto?.icao===!0&&e.onLivePhoto!==void 0?e.onLivePhoto(r):()=>{}};case"mobile_required":case"processing":return{...n,refresh:async()=>{i=!1,await e.refreshView()}};case"unsupported":case"result":return{...n};default:{let r=n;throw new Error(`runner: unhandled step ${JSON.stringify(r)}`)}}},_=n=>W(f(n)),R=async()=>{if(!c){c=!0;try{for(let n of Bt){if(await e.sleep(n),!t||e.destroyed())return;let r=await e.refreshView().catch(()=>null);if(r!==null&&J(r,{isMobile:e.isMobile()}).kind!=="processing")return}i=!0,k()}finally{c=!1}}},x=n=>{if(n.kind!=="liveness"||n.mode!=="selfie")return null;let r={kind:"processing",key:"processing",context:n.context,section:n.section,stalled:!1};if(b==="inflight")return r;if(!M||b==="done")return null;let a=e.keptFaceKey?.()??null;return a===null?null:(b="inflight",O("face_match",(l,h)=>l.submitCheck("face_match",{imageKey:a},{idempotencyKey:h}),()=>{b="done"}).then(()=>{b==="inflight"&&(b="done",k())},()=>{b="done",k()}),r)},T=(n,r=!1)=>{if(!t||e.destroyed()||e.chainBusy())return;let a=J(n,{isMobile:e.isMobile()});a.kind==="registry"&&a.recheck&&(M=!0,b="idle"),a=x(a)??a,a.kind==="processing"?a.stalled=i:i=!1;let l=_(a),h=a.kind==="result"?void 0:a.context.switchable,g=h===void 0?l:{...l,chooseOption:P=>A({nodeId:h.nodeId,kind:h.kind,selected:h.current,options:h.options},P)},C=JSON.stringify(g);a.kind==="registry"&&a.source==="document"&&a.state==="pending"&&!S.has("registry")&&(S.add("registry"),g.confirm().catch(P=>{(!(P instanceof F)||Wt.has(P.code))&&S.delete("registry")})),!(!r&&C===s)&&(s=C,o=g,e.emitStep(g),a.kind==="processing"&&!i&&b!=="inflight"&&R(),a.kind==="result"&&!d&&(d=!0,e.emitResult(a.result)))};function k(){let n=e.currentView();n!==null&&T(n,!0)}return{run:async()=>{if(e.destroyed())throw new Error("verification destroyed");t=!0;let n=await e.ensureView();return o===null&&T(n),o??_(J(n,{isMobile:e.isMobile()}))},current:()=>o,onView:n=>T(n),onChainIdle:()=>{let n=e.currentView();n!==null&&T(n)},republish:k,submit:O,faceProbeSkipped:()=>y}}function $t(e){switch(e.kind){case"document":return"doc_ocr";case"liveness":return e.mode==="selfie"?"face_match":"liveness";case"portrait":return e.phase==="capture"?"portrait_icao":null;case"proof_of_address":return"poa";case"mobile_required":return e.checkType;case"unsupported":return e.checkType==="nfc_chip"?"nfc_chip":null;default:return null}}function qt(e,t){let o=e,s=o?.plan?.steps??o?.steps;return Array.isArray(s)?s.some(i=>i.checkType===t&&typeof i.reason=="string"):!1}export{Je as a,zt as b,Ie as c,ve as d,on as e,Fe as f,J as g,Bt as h,Ut as i,Mn as j};
@@ -0,0 +1,3 @@
1
+ import{A as Qe,B as Xe,C as ze,a as Ge,b as Ke,c as qe,d as q,e as Q,f as X,g as Ye,h as L,i as We,j as A,k as U,l as I,m as H,n as D,o as Y,p as W,q as z,r as je,s as $e,t as Ze,u as Je}from"./chunk-ZCW6PNUX.js";import{n as Ue}from"./chunk-65JZHKVG.js";import{a as Le}from"./chunk-7QZWBDI5.js";import{c as de,e as Fe,g as Be,h as ee}from"./chunk-XOTKATN6.js";import{c as Ne,d as ue}from"./chunk-TSA6GHUG.js";function te(e){return e.idNumberBound??e.nniBound}function j(e){return e===void 0?void 0:e.idNumberFromDocument??e.nniFromDocument}function et(e){let t=e.idNumberMasked??e.nniMasked;return typeof t=="string"&&t!==""?t:void 0}var Rt="https://api.sekyro.ai",At=5e3,Ot=24e4,wt=3e4,It=1500,Mt=10;function tt(e){return e instanceof Error&&e.name==="ChallengeError"&&e.code||"challenge_failed"}function vt(e){return new Promise(t=>setTimeout(t,e))}function Et(){let e=globalThis.crypto;if(e!==void 0&&typeof e.randomUUID=="function")return e.randomUUID();let t=new Uint8Array(16);if(e!==void 0&&typeof e.getRandomValues=="function")e.getRandomValues(t);else for(let r=0;r<16;r+=1)t[r]=Math.floor(Math.random()*256);t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let o=[...t].map(r=>r.toString(16).padStart(2,"0")).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function wn(e){return Tt(e,{})}function Tt(e,t){let o=e.apiOrigin??Rt,r=e.autoRetry??!0,i=e.rearm??"auto",s=t.client??new Be({apiOrigin:o,sessionToken:e.clientToken,fetch:e.fetch}),u=t.sleep??vt,c=t.uuid??Et,p=t.getChallengeToken??((n,a)=>import("./challenge-frame-NUGPTWFP.js").then(d=>d.executeChallenge({frameUrl:n.url,siteKey:n.siteKey,action:"liveness",subject:a.subject,signal:a.signal}))),S=Le(),g=null,x=null,l=!1,C=new AbortController,f=null,V=null,$=null,Z=()=>$??je(f),ge=()=>$e(z(f),Z()),O=n=>{f=n,S.emit("view",n),g?.onView(n)},_=()=>f!==null?Promise.resolve(f):(V??(V=s.getSession().then(n=>(O(n),n)).finally(()=>{V=null})),V),w=async()=>{let n=await s.getSession();return O(n),n},ne=async(n,a)=>{n.plan!==void 0?O(n):await w()},oe=null,Ce=async n=>{let a=await _();if(n||!a.consentRecorded){let d=await s.recordConsent(e.locale);d.plan!==void 0?O(d):f!==null&&O({...f,consentRecorded:!0})}ve(a)},v=n=>n?.force===!0?Ce(!0):(oe??(oe=Ce(!1).finally(()=>{oe=null})),oe),ie={client:s,ensureConsent:n=>v(n),sleep:u,uuid:c,...t.random!==void 0?{random:t.random}:{},onBusy:n=>{l||S.emit("busy",n)}},_e=!1,ke=null,re=n=>{if(n.status==="verified"||n.status==="not_verified"||n.status==="review"){if(_e)return;_e=!0}ke=JSON.stringify(n),S.emit("result",n)},pt=n=>{ke!==JSON.stringify(n)&&re(n)},Pe=async n=>{let a=f;n&&(a=await w().catch(()=>f));let d=a===null?null:L(a);return d!==null&&!l&&S.emit("method",d),d!==null},be=null,xe=!1,Re=!1,Ae=()=>Qe(ie,(n,a)=>n.submitCheck("population_registry",{},{idempotencyKey:a})),Oe=n=>te(n)===!0||j(I(n,"population_registry"))===!0,ft=async()=>{try{let n=await _();if(A(n)||L(n)!==null||U(n)?.checkType!=="population_registry")return;if(!Oe(n)&&j(I(n,"population_registry"))===void 0&&(n=await w()),!Oe(n)){Re=!0;return}await v(),await ne(await Ae(),"population_registry");let a=f===null?void 0:I(f,"population_registry");if(a?.state==="input_required"&&a.reason==="registry_unavailable"&&X(a)>0){if(await u(At),l)return;await ne(await Ae(),"population_registry")}}catch(n){if(n instanceof de&&(n.code==="check_not_active"||n.code==="step_not_on_path")){await w().catch(()=>{});return}xe=!0;return}f!==null&&A(f)&&re(Y(f,{autoRetry:r}))},we=()=>(be??(be=ft()),be),se=t.now??Date.now,N=null,B,ae,Ie=(n,a)=>`${n.url}
2
+ ${n.siteKey}
3
+ ${a}`,ce=(n,a)=>{let d=p(n,{signal:C.signal,subject:a});return d.then(()=>{ae=void 0},m=>{let h=tt(m);l||h==="aborted"||(ae=h,G({check:"attestation",kind:"unavailable",engineKind:h}))}),d},Me=(n,a)=>n!==null&&n.key===a&&se()-n.at<Ot,ve=n=>{let a=n?.challenge??null;if(n===null||a===null||l)return;let d=Ie(a,H(n.sessionId));if(Me(N,d))return;let m=ce(a,H(n.sessionId));m.catch(()=>{}),N={key:d,at:se(),token:m}},mt=async(n,a)=>{let d=Ie(n,a),m=N;N=null;let h=Me(m,d),b=h?m.at:se(),E=h?m.token.catch(()=>ce(n,a)):ce(n,a);E.catch(()=>{});let P,y=new Promise(R=>{P=setTimeout(()=>R("late"),wt)});try{let R=await Promise.race([E.then(T=>({token:T}),T=>({error:tt(T)})),y]);return R==="late"&&!l&&N===null&&(N={key:d,at:b,token:E}),R}finally{clearTimeout(P)}},Ee=async()=>{B=void 0;let n=await _(),a=n.challenge;if(a==null)return{};let d=await mt(a,H(n.sessionId));return d!=="late"&&"token"in d?{channel:"hosted_web",turnstileToken:d.token}:(B=d!=="late"?d.error:ae,{channel:"hosted_web"})},ht=()=>B,G=n=>{if(l)return;let a=s.reportCaptureIssue;if(a===void 0)return;let d=n.formFactor;try{d??(d=Ne())}catch{}try{Promise.resolve(a.call(s,{...n,...d!==void 0?{formFactor:d}:{}})).catch(()=>{})}catch{}},k=null,Te=Promise.resolve(),K=0,St=async()=>{let n=await _();for(let a=0;a<Mt&&!l&&!A(n)&&U(n)===void 0&&Q(n).some(d=>d.state==="processing")&&(await u(It),!l);a+=1)n=await w();return n},yt=async(n,a,d)=>{let{capture:m}=n,h=()=>l,b=()=>n.alive&&n.attempt===d,E=y=>{b()&&m.setFlowState(y)},P=y=>{if(!h()&&(y.status==="unavailable"&&y.reasonCode!==void 0&&!Ge(y.reasonCode)&&G({check:"liveness",kind:"unavailable",phase:"upload",engineKind:y.reasonCode,attempt:Math.max(0,n.issues.value)}),re(y),!!b())){if(y.status==="retry"&&i==="auto"){m.handle.retry();return}m.setFlowState("done")}};if(a.degraded==="NO_RECORDER"){let y=f?.sessionId??(await _().catch(()=>null))?.sessionId??"";P(D(y,"no_recorder"));return}E("uploading");try{if(await we(),h())return;let y=await _(),R;if(!A(y)&&L(y)!==null){await Pe(!1),P(D(y.sessionId,"method_required"));return}if(!A(y)){if(U(y)?.checkType==="population_registry"){P(D(y.sessionId,Re?"nni_unbound":xe?"network":"registry_unavailable"));return}if(await v(),h())return;R=f??y;let T=await Xe({...ie,artifacts:a,getAttestation:Ee,attestationError:ht,getView:()=>f??y,refreshView:w,applySubmit:ne,onPhase:E,isCancelled:h,onKeyframePromoted:J=>{x=J}});if(h())return;if(T.kind==="unavailable"){let J=D(y.sessionId,T.reason),De=T.reason==="attestation"?B:void 0;P(De!==void 0?{...J,attestationError:De}:J);return}if(T.kind==="resync"&&await w(),f!==null&&L(f)!==null){await Pe(!1),P(D(y.sessionId,"method_required"));return}y=await St()}P(Y(y,{autoRetry:r,previous:R}))}catch{if(h())return;P(D(f?.sessionId??"","network"))}},gt=(n,a)=>{let d=n.attempt;K>0&&n.alive&&n.capture.setFlowState("uploading"),K+=1,Te=Te.then(()=>yt(n,a,d)).finally(()=>{K-=1,K===0&&g?.onChainIdle()}).catch(()=>{})},Ve=n=>{k?.capture.handle.destroy(),k!==null&&(k.alive=!1);let a=Ue(n,g?.captureInternals?.(n)??t.capture,()=>f?.capture?.liveness?.keyframe?.rank===!0,ge,()=>f?.capture?.liveness?.screenRamp,{session:()=>z(f),onModeChange:h=>{$=h}}),d={capture:a,alive:!0,attempt:0,issues:qe()};k=d,a.handle.on("error",h=>{G(Ke("liveness",h,d.issues.value))}),a.handle.on("state",h=>{if(d.issues.note(h),h==="starting"){d.attempt+=1,ve(f);let b=f===null?void 0:U(f)?.checkType;(b==="liveness"||b==="face_match")&&v().catch(()=>{})}}),a.handle.on("captured",h=>{Promise.resolve().then(()=>gt(d,h))});let m=a.handle;return{get state(){return m.state},get captureMode(){return m.captureMode},get facingMode(){return m.facingMode},on:(h,b)=>m.on(h,b),start:async h=>{if(f===null&&await _().catch(()=>{}),!!d.alive)return m.start(h)},retry:()=>m.retry(),switchCamera:()=>m.switchCamera(),canSwitchCaptureMode:()=>m.canSwitchCaptureMode(),setCaptureMode:h=>m.setCaptureMode(h),destroy:()=>{d.alive=!1,k===d&&(k=null),m.destroy()}}},Ct=async()=>{if(l)return null;try{let n=await _();return l?null:L(n)}catch{return null}},_t=async()=>{if(l)return"self";try{let n=await _();if(l)return"self";let a=z(n);return a==="choice"?Z()??a:a}catch{return"self"}},kt=async()=>{if(l)return!1;try{let n=await _();return l||A(n)||ue()?!1:W(n,U(n))==="phone"||W(n,I(n,"liveness"))==="phone"}catch{return!1}},Pt=async()=>{if(l)return!1;try{let n=await _();return!l&&n.returning===!0}catch{return!1}},bt=async n=>{let a=(await _()).plan?.choice,d=a?.options.find(h=>q[h.service]===n);if(!d)throw new RangeError(`method ${String(n)} is not offered`);let m=await s.choose(a.nodeId,d.id);l||O(m)},He=null,xt=()=>(He??(He=import("./plan-runner-EP26JU6A.js").then(n=>{let a=n.createPlanRunner({runtime:ie,currentView:()=>f,cameraMode:ge,captureModeSwitch:{pick:Z,choose:d=>{$=d}},ensureView:_,refreshView:w,ensureConsent:()=>v(),liveness:Ve,stopLiveness:()=>{k!==null&&(k.alive=!1,k.capture.handle.destroy(),k=null)},chainBusy:()=>K>0,destroyed:()=>l,sleep:u,isMobile:ue,now:t.now??Date.now,keptFaceKey:()=>x,setView:O,baseCapture:t.capture,emitStep:d=>{l||S.emit("step",d)},emitResult:pt,reportCaptureIssue:G,documentInternals:t.document,portraitInternals:t.portrait,livePhotoInternals:t.livePhoto,uploadInternals:t.upload,pageCameraInternals:t.pageCamera});return g=a,a})),He);return{consent:()=>v(),startRegistry:we,methodChoice:Ct,selectMethod:bt,reportCameraUnavailable:async n=>{await v();let a=s.reportCameraUnavailable;if(a===void 0)throw new TypeError("this client cannot report a missing camera");let d=await a.call(s,n).catch(m=>{if(m instanceof de&&m.code==="check_out_of_order")return s.getSession();throw m});l||O(d)},reportCaptureIssue:G,testerGate:async n=>{let a=s.testerGate;if(a===void 0)throw new TypeError("this client cannot run the tester gate");let d=n.clip,m=Fe(n.clipMime??"");if(d===void 0||!Je.includes(m))throw new TypeError("the capture has no clip");await v();let h=await Ze(s,"clip",m,d.size,{engine:n.engine,durationMs:n.clipMs});await s.uploadToSpaces(h.uploadUrl,d,m);let{key:b}=await s.completeMedia(h.key),E=await Ee(),P=await a.call(s,{clipKey:b,attestation:E,captureChannel:n.captureChannel,capture:{...ze(n),attestationError:B}}),{bound:y,...R}=P;return l||(R.plan!==void 0?O(R):await w()),{bound:y===!0}},mobileRequired:kt,captureMode:_t,chooseCaptureMode:n=>{$=n},get captureChoice(){return Z()},returning:Pt,liveness:Ve,run:async()=>{if(l)throw new Error("verification destroyed");return(await xt()).run()},currentStep:()=>g?.current()??null,voiceClips:async()=>{if(l)return null;try{let n=await _();return l?null:n.voice??null}catch{return null}},on:(n,a)=>S.on(n,a),destroy:()=>{l=!0,C.abort(),g?.destroy(),k!==null&&(k.alive=!1,k.capture.handle.destroy(),k=null),S.clear()}}}var nt=["AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AS","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CW","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IR","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","XK","YE","YT","ZA","ZM","ZW"];var Vt=["carte_identite","passport","residence_permit","drivers_license"],Ht=["carte_identite","passport","residence_permit"];function Dt(e,t){let o=e.byIssuer?.[t]??e.default;return Vt.filter(r=>o==="*"?Ht.includes(r):o.includes(r))}function En(e,t=nt){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(r=>Dt(e,r).length>0).sort()}function ot(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}function Tn(e){return/^[A-Z]{2}$/.test(e)?String.fromCodePoint(...[...e].map(t=>127462+t.charCodeAt(0)-65)):""}var it=Object.freeze({nni_invalid:"id_number_invalid",nni_not_found:"registry_record_not_found",nni_recheck:"id_number_recheck",document_nni_mismatch:"document_id_number_mismatch",nni_locked:"id_number_locked",nni_unbound:"id_number_unbound",missing_nni:"missing_id_number",registry_needs_nni_source:"registry_needs_id_number_source"}),Nt=new Map(Object.entries(it)),Hn=new Map(Object.entries(it).map(([e,t])=>[t,e]));function rt(e){return Nt.get(e)??e}var Kn=["national_number","document_photo","national_eid"],Lt=new Set(["phone_otp","email_otp","national_eid","document","nfc","population_registry","supplied_identity","summary_confirm","liveness","portrait","face_match","aml_screening","face_dedup","age_estimation","proof_of_address"]),Ut=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),pe=["document","population_registry","national_eid"],fe=["phone_otp","email_otp"],ct={identity_method:pe,contact:fe},Ft=["population_registry","document"],me="platform_unsupported",Bt=new Set(["prefilled","user_entered","prefilled_or_entered"]),Gt={phone_otp:"contact",email_otp:"contact",eid_auth:"identity",doc_ocr:"identity",nfc_chip:"identity",population_registry:"identity",liveness:"live_photo",portrait_icao:"live_photo",face_match:"live_photo",poa:"documents"};function M(e){return e.section??Gt[e.checkType]??null}function Kt(e,t){let o=e.plan?.choice;if(o===void 0||o.locked)return;let r=o.options.find(i=>i.id!==o.selected&&i.available!==!1&&t.includes(i.service));return r===void 0?void 0:{nodeId:o.nodeId,option:r}}function he(e){let t=e.plan,o=t?.choice;if(t===void 0||o===void 0||o.locked||t.current===null||t.current===o.nodeId||A(e))return null;let r=ct[o.kind]??[...pe,...fe],i=o.options.flatMap(c=>c.available===!1||!r.includes(c.service)?[]:[c.nationalEid!=null?{id:c.id,service:c.service,nationalEid:c.nationalEid}:{id:c.id,service:c.service}]),s=t.steps.find(c=>c.id===t.current)?.service,u=o.selected??i.find(c=>c.service===s)?.id??null;return i.some(c=>c.id!==u)?{nodeId:o.nodeId,kind:o.kind,current:u,options:i}:null}function ut(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function qt(e){let t=e.simulation;if(typeof t!="object"||t===null)return;let{otpCode:o,skipCapture:r}=t;return typeof o=="string"&&o!==""&&typeof r=="boolean"?{otpCode:o,skipCapture:r}:void 0}function Yt(e){let t=(e.plan?.sections??[]).map(u=>({id:u.id,state:u.state})),o={sessionId:H(e.sessionId),orgName:e.orgName,sandbox:e.sandbox===!0,returning:e.returning===!0,consentRecorded:e.consentRecorded,expiresAt:e.expiresAt,sections:t.map(u=>u.id),progress:t,purpose:e.purpose??"identity"};e.branding!==void 0&&(o.branding=e.branding),e.cameraUnavailableHandled===!0&&(o.cameraUnavailableHandled=!0);let r=qt(e);r!==void 0&&(o.simulation=r);let i=e.testerGate;i?.offered===!0&&typeof i.attemptsLeft=="number"&&i.attemptsLeft>0&&(o.testerGate={attemptsLeft:i.attemptsLeft});let s=he(e);return s!==null&&(o.switchable=s),o}function Wt(e){let t={attemptsRemaining:X(e),attemptsExhausted:e.attempts.used>=e.attempts.max};return e.reason!==void 0&&(t.reason=e.reason),e.retakeHint!==void 0&&(t.retakeHint=e.retakeHint),t}var dt={phone_otp:"phone",email_otp:"email"};function jt(e,t){let o=Kt(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return o===void 0?void 0:dt[o.option.service]}function $t(e,t,o,r){let i=t.checkType==="email_otp",s=(i?t.emailOtp:t.otp)??{},u=i?t.emailOtp?.emailSource:t.otp?.numberSource,c=u!==void 0&&Bt.has(u)?u:i?"prefilled_or_entered":"user_entered",p=typeof s.sentToMasked=="string"&&s.sentToMasked.length>0,S=s.prefilled===!0,g=jt(e,i?"email_otp":"phone_otp"),x={key:t.checkType,context:o,section:M(t),phase:p?"verify":"send",canSwitch:g!==void 0,...r},l=i?{kind:"email_otp",...x,emailSource:c,needsEmail:c!=="prefilled"&&!S}:{kind:"phone_otp",...x,numberSource:c,needsPhone:c!=="prefilled"&&!S,channels:(t.otp?.channels??[]).filter(C=>C==="whatsapp"||C==="sms")};if(g!==void 0&&(l.switchChannel=g),S&&(l.prefilled=!0),p&&(l.sentToMasked=s.sentToMasked),!i&&t.otp?.channel!==void 0&&(l.channel=t.otp.channel),!i&&Array.isArray(t.phoneCountries)&&(l.phoneCountries=t.phoneCountries.filter(C=>typeof C=="string"&&/^[A-Z]{2}$/.test(C))),!i&&Array.isArray(t.phoneRules)){let C=l.phoneCountries??[];l.phoneRules=t.phoneRules.flatMap(f=>{let V=Qt(f);return V!==void 0&&C.includes(V.code)?[V]:[]})}return!i&&t.phoneInternational===!0&&(l.phoneInternational=!0),s.expiresAt!==void 0&&(l.codeExpiresAt=s.expiresAt),s.resendAvailableAt!==void 0&&(l.resendAvailableAt=s.resendAvailableAt),l}var Zt=/^[\d[\]\-|()?:^]{1,64}$/;function Jt(e){try{return typeof e=="string"&&Zt.test(e)&&new RegExp(e)!==null}catch{return!1}}var st=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function Qt(e){let{code:t,dial:o,trunk:r,lengths:i,formats:s}=e??{};if(typeof t!="string"||typeof o!="string"||!/^\d{1,3}$/.test(o)||r!==void 0&&(typeof r!="string"||!/^\d{1,3}$/.test(r))||!Array.isArray(i)||i.length===0||!i.every(st))return;let u={code:t,dial:o,lengths:[...i].sort((c,p)=>c-p)};if(r!==void 0&&(u.trunk=r),s!==void 0){if(!(Array.isArray(s)&&s.length<=8&&s.every(p=>Jt(p?.leading)&&Array.isArray(p.groups)&&p.groups.every(st)&&i.includes(p.groups.reduce((S,g)=>S+g,0)))))return;u.formats=s.map(p=>({leading:p.leading,groups:[...p.groups]}))}return u}function Xt(e,t,o,r){let i=te(e)===!0?"bound":j(t)===!0?"document":"typed",s=i==="typed"&&t.state==="input_required"&&t.reason!==void 0&&rt(t.reason)==="id_number_recheck",u=ut(he(e)),c=!r.attemptsExhausted&&u.length===1&&u[0]?.service==="document";return{kind:"registry",key:"registry",context:o,section:M(t),state:t.state==="input_required"?"input_required":"pending",source:i,recheck:s,canUseDocument:c,...r}}function zt(e,t,o,r,i){let s=[...t.acceptedSides??[]],u={kind:"document",key:"document",context:o,section:M(t),side:s.includes("recto")?"verso":"recto",acceptedSides:s,documents:ot(e),photo:ye(Se(e.documents),i),...r};return e.detectedCountry!==void 0&&(u.detectedCountry=e.detectedCountry),nn(e)&&(u.ageStepUp=!0),u}function Se(e,t=!0){let o=e?.source==="upload"||e?.source==="choice"?e.source:"camera",r=e?.sourcePick==="camera"||e?.sourcePick==="upload"?e.sourcePick:null;return{source:o,pick:r,uploadOffered:t&&e?.uploadOffered===!0}}function ye(e,t){return t?{...e,cameraOnPhone:!0}:e}var en=10*1024*1024;function tn(e,t,o,r,i){let s=e.proofOfAddress,u=s?.pdf?.maxBytes,c=s?.phase==="holder_letter"?"holder_letter":"document";return{kind:"proof_of_address",key:"proof_of_address",context:o,section:M(t),phase:c,rule:s?.rule??{country:null,countryFrom:"global",source:"preset_global",kinds:[]},nameMatch:s?.nameMatch??"exact_person",photo:ye(Se(s),i),maxPages:3,pdf:{maxBytes:typeof u=="number"&&u>0?u:en,maxPages:3},licenceAddressAccepted:c==="document"&&s?.licenceAddressAccepted===!0,...r}}function nn(e){let t=Q(e).find(r=>r.checkType==="age_estimation"),o=t?.reason;return t?.state==="failed"&&(o==="age_uncertain"||o==="age_unavailable")}function on(e){let t=I(e,"liveness");return t?.state==="passed"||t?.state==="review"}function at(e,t,o,r,i,s=!1){let u=t.icao?.report,c=e.portrait,p=i==="capture"?c?.pendingFix??null:null;p!==null&&(i="review");let S=lt(e);return{kind:"portrait",key:`portrait:${i}`,context:o,section:M(t),phase:i,report:Array.isArray(u)?u:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:ee(e),retakeOnly:i==="capture"&&t.state==="input_required"&&S===void 0&&e.capture?.livePhoto?.oneCapture===!0&&on(e),photo:ye(Se(c,i==="capture"),s&&i==="capture"),pendingFix:p,...S!==void 0?{captureMode:S}:{},...c?.reuse?.pending===!0?{reuse:!0}:{},...r}}function lt(e){let t=e.portrait?.captureMode;return t==="self"||t==="assisted"||t==="choice"?t:void 0}var le={minLongSidePx:1280,jpegQuality:.95};function rn(e,t){let o=e.capture?.livePhoto;if(o?.oneCapture!==!0)return null;let r=I(e,"portrait_icao"),i=o.still??le;return{icao:t==="liveness"&&ee(e)!==null&&lt(e)===void 0&&r!==void 0&&r.state==="pending"&&r.reason===void 0,still:{minLongSidePx:i.minLongSidePx??le.minLongSidePx,jpegQuality:i.jpegQuality??le.jpegQuality}}}function sn(e,t,o,r){let i=t.eid,s=M(t);if(i===void 0||i.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:o,section:s,checkType:"eid_auth",reason:"update_required"};let u=ut(he(e)),c=u.length===1&&Ft.includes(u[0]?.service??"")?u[0]:void 0,p=c===void 0?void 0:q[c.service],S=p!==void 0,g={kind:"eid",key:"eid",context:o,section:s,provider:i.provider,providerName:i.providerName,country:i.country,challenge:"app_code",phase:i.awaiting==="code"?"code":"identifier",identifierBound:i.identifierBound===!0,canUseCamera:S,afterPass:i.afterPass==="continue"?"continue":"end",...r};return S&&(g.cameraMethod=p),i.expiresAt!==void 0&&(g.codeExpiresAt=i.expiresAt),i.resendAvailableAt!==void 0&&(g.resendAvailableAt=i.resendAvailableAt),i.resendsRemaining!==void 0&&(g.resendsRemaining=i.resendsRemaining),i.codeAttemptsRemaining!==void 0&&(g.codeAttemptsRemaining=i.codeAttemptsRemaining),g}function an(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let o=I(e,"portrait_icao");return o!==void 0&&(o.state==="passed"||o.state==="review")?o:null}var cn={rejected:"rejected",inconclusive:"inconclusive",unavailable:"unavailable",abandoned:"expired",not_opened:"expired",cancelled:"expired",superseded:"expired",policy:"policy"};function un(e){return e.reasonCode===me?"platform_unsupported":e.status==="review_pending"?"review":e.status==="verified"?"verified":e.reasonCode==="device_cooldown"?"cooldown":e.reasonCode==="starter_credit_claimed"?"policy":(e.status==="not_verified"&&e.reason!==void 0?cn[e.reason]:void 0)??"rejected"}function dn(e,t){let o=un(e),r=o==="platform_unsupported"?{sessionId:H(e.sessionId),status:"unavailable",reasonCode:me}:Y(e,{autoRetry:!1}),i={kind:"result",key:"result",context:t,section:null,display:o,result:r};return e.status==="not_verified"&&e.reason!==void 0&&(i.reason=e.reason),e.reasonCode!==void 0&&(i.reasonCode=e.reasonCode),e.status==="not_verified"&&e.step!==void 0&&(i.step=e.step),e.retryAfter!==void 0&&(i.retryAfter=e.retryAfter),i}function ln(e,t,o){let r=e.identitySummary;if(r==null)return null;let i={kind:"identity_summary",key:"identity_summary",context:t,section:o??"identity",summaryKind:r.kind==="partial"?"partial":r.kind??"full",source:r.source,portraitAvailable:r.portrait?.available===!0,retakeAvailable:r.retakeAvailable===!0};for(let u of pn){let c=r[u];typeof c=="string"&&c!==""&&(i[u]=c)}let s=et(r);return s!==void 0&&(i.idNumberMasked=s,i.nniMasked=s),i}var pn=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","expiryDate","retakeTarget"];function F(e,t,o,r){return{kind:"unsupported",key:`unsupported:${o}`,context:e,section:t,checkType:o,reason:r}}function fn(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function mn(e,t){let o=ct[e.kind]??[...pe,...fe],r=fn(e),i=e.options.flatMap(u=>{if(u.available===!1||!o.includes(u.service))return[];let c={id:u.id,service:u.service};u.nationalEid!=null&&(c.nationalEid=u.nationalEid);let p=(u.channels??[]).filter(S=>S==="whatsapp"||S==="sms");return u.service==="phone_otp"&&p.length>0&&(c.channels=p),[c]});if(i.length===0){let u=e.options.length>0&&e.options.every(c=>c.service==="nfc");return F(t,r,"choice",u?"platform_unsupported":"update_required")}let s={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:i};if(e.kind==="identity_method"){let u={kind:"method",key:"method",context:t,section:r,options:i.map(p=>q[p.service]),choice:s},c=i.find(p=>p.nationalEid!==void 0)?.nationalEid;return c!==void 0&&(u.nationalEid=c),u}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:r,options:i.map(u=>dt[u.service]),selected:null,locked:!1,choice:s}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:r,choice:s}}function qn(e,t={}){let o=Yt(e);if(A(e)||e.reasonCode===me)return dn(e,o);let r=e.plan;if(r===void 0||!Array.isArray(r.sections))return F(o,null,"plan","update_required");let i=Ye(e);if(i!==null)return mn(i,o);let s=r.current===null?void 0:r.steps.find(l=>l.id===r.current),u=l=>{let C={kind:"processing",key:"processing",context:o,section:l!==void 0?M(l):r.sections.find(f=>f.state==="current")?.id??null,stalled:!1};return typeof l?.service=="string"&&l.service!==""&&(C.service=l.service),C};if(r.current===null)return u(r.steps.find(l=>l.state==="processing"));if(s===void 0)return F(o,null,"step","update_required");if(!Lt.has(s.service))return s.interaction==="server"?u(s):F(o,M(s),s.service,"update_required");if(Ut.has(s.service)||!We(s))return u(s);let c=s,p=Wt(c),S=c.checkType,g=M(c),x=t.isMobile===!1?W(e,c):null;if(x==="phone")return{kind:"mobile_required",key:"mobile_required",context:o,section:g,checkType:S};switch(S){case"phone_otp":case"email_otp":return $t(e,c,o,p);case"population_registry":return Xt(e,c,o,p);case"eid_auth":return sn(e,c,o,p);case"doc_ocr":return zt(e,c,o,p,x==="upload_or_phone");case"identity_confirm":return ln(e,o,g)??u(c);case"portrait_icao":return at(e,c,o,p,"capture",x==="upload_or_phone");case"liveness":case"face_match":{let l=an(e,c);if(l!==null)return at(e,l,o,p,"match");let C=c.requiresMobile===!0,f=ee(e);return{kind:"liveness",key:"biometric",context:o,section:g,mode:S==="face_match"?"selfie":"liveness",requiresMobile:C,instructions:f===null?"standard":"icao",icao:f,livePhoto:rn(e,S),...p}}case"poa":return tn(e,c,o,p,x==="upload_or_phone");case"nfc_chip":return F(o,g,S,"platform_unsupported");default:return F(o,g,S,"update_required")}}export{Rt as a,At as b,It as c,Mt as d,Et as e,wn as f,Tt as g,nt as h,Vt as i,Dt as j,En as k,ot as l,Tn as m,Kn as n,me as o,M as p,he as q,ut as r,an as s,qn as t};
@@ -0,0 +1 @@
1
+ var b=new Set(["challenge_frame_blocked","challenge_script_blocked","site_key_rejected","challenge_failed","timeout","embedder_opaque"]),i=class extends Error{constructor(n,r){super(`Sekyro challenge failed: ${n}${r!==void 0?` (${r})`:""}`),this.name="ChallengeError",this.code=n,r!==void 0&&(this.detail=r)}},p=1e4,E=3e4,_="sekyro.challenge.",v="position:fixed;width:1px;height:1px;inset-block-start:0;inset-inline-start:0;opacity:0;pointer-events:none;border:0",c=null,g=Promise.resolve();function A(){u(),g=Promise.resolve(),m=!1}function d(){return new i("aborted")}function k(){let e=globalThis.crypto;return e!==void 0&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function y(e){return new URL(e,document.baseURI).origin}function u(){let e=c;if(e!==null){c=null,window.removeEventListener("message",e.listener),e.iframe.remove();for(let n of e.waiters.values())n.reject(new i("challenge_frame_blocked"));e.waiters.clear()}}function C(e,n){if(n.source!==e.iframe.contentWindow||n.origin!==e.origin)return;let r=n.data;if(typeof r!="object"||r===null)return;let t=r;if(typeof t.type!="string"||!t.type.startsWith(_)||t.v!==1)return;if(t.type==="sekyro.challenge.ready"){e.isReady=!0,e.onReady?.();return}if(typeof t.id!="string")return;let a=e.waiters.get(t.id);if(a!==void 0){if(t.type==="sekyro.challenge.token"&&typeof t.token=="string"&&t.token!=="")e.waiters.delete(t.id),a.resolve(t.token);else if(t.type==="sekyro.challenge.error"){e.waiters.delete(t.id);let o=typeof t.code=="string"&&b.has(t.code)?t.code:"challenge_failed",s=typeof t.detail=="string"||typeof t.detail=="number"?String(t.detail).slice(0,32):void 0;a.reject(new i(o,s))}}}function M(e){if(c!==null&&c.url===e)return c;u();let n=document.createElement("iframe");n.setAttribute("title","Security check"),n.setAttribute("aria-hidden","true"),n.setAttribute("tabindex","-1"),n.setAttribute("referrerpolicy","no-referrer"),n.setAttribute("style",v);let r={url:e,origin:y(e),iframe:n,isReady:!1,onReady:null,waiters:new Map,listener:t=>C(r,t)};return window.addEventListener("message",r.listener),n.src=e,document.body.appendChild(n),c=r,r}function x(e,n,r){return e.isReady?Promise.resolve():new Promise((t,a)=>{let o=()=>{clearTimeout(l),r?.removeEventListener("abort",s),e.onReady=null},s=()=>{o(),a(d())},l=setTimeout(()=>{o(),a(new i("challenge_frame_blocked"))},n);r?.addEventListener("abort",s,{once:!0}),e.onReady=()=>{o(),t()}})}async function h(e){let n=e.signal;if(n?.aborted)throw d();let r=M(e.frameUrl);await x(r,e.readyTimeoutMs??p,n);let t=r.iframe.contentWindow;if(t===null)throw new i("challenge_frame_blocked");let a=e.timeoutMs??E,o=k(),s,l;try{return await new Promise((w,f)=>{r.waiters.set(o,{resolve:w,reject:f}),s=setTimeout(()=>f(new i("timeout")),a),n!==void 0&&(l=()=>f(d()),n.addEventListener("abort",l,{once:!0})),t.postMessage({type:"sekyro.challenge.request",v:1,id:o,siteKey:e.siteKey,action:e.action,subject:e.subject},r.origin)})}finally{clearTimeout(s),n!==void 0&&l!==void 0&&n.removeEventListener("abort",l),r.waiters.delete(o)}}var m=!1;function R(e,n){if(m)return;let r;if(n==="challenge_frame_blocked"){let t=e;try{t=y(e)}catch{}r=`Sekyro: the security check frame could not load. Allow \`frame-src ${t}\` in your Content-Security-Policy.`}else if(n==="embedder_opaque")r="Sekyro: the security check needs a page with an origin. Do not run the SDK in a sandboxed or data: document.";else return;m=!0,console.warn(r)}async function S(e){if(globalThis.origin==="null")throw new i("embedder_opaque");if(e.signal?.aborted)throw d();try{return await h(e)}catch(n){if(u(),e.signal?.aborted||n instanceof i&&n.code==="aborted")throw d();try{return await h(e)}catch(r){throw u(),e.signal?.aborted?d():r instanceof i?r:new i("challenge_failed")}}}function T(e){let n=()=>S(e).catch(t=>{throw t instanceof i&&R(e.frameUrl,t.code),t}),r=g.then(n,n);return g=r.catch(()=>{}),r}export{i as a,p as b,E as c,A as d,T as e};
@@ -1 +1 @@
1
- var f="0.1.0-rc.24";var T=/FBAN|FBAV|FB_IAB|FBIOS|MessengerForiOS|Instagram|WhatsApp|musical_ly|BytedanceWebview|TikTok|Snapchat|\bLine\/|LinkedInApp|Pinterest|MicroMessenger|; wv\)/i;function p(t){let e=t??(typeof navigator>"u"?"":String(navigator.userAgent??""));return T.test(e)}var h="sekyro.did",P=1e4,v=()=>globalThis.process?.versions?.node,y;function b(){let t=globalThis.crypto;try{if(typeof t?.randomUUID=="function")return t.randomUUID()}catch{}try{if(typeof t?.getRandomValues=="function"){let e=t.getRandomValues(new Uint8Array(16));return Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}}catch{}}function I(){try{let t=localStorage.getItem(h);if(t)return t;let e=b();return e!==void 0&&localStorage.setItem(h,e),e}catch{return y??(y=b()),y}}async function w(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,r=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),i=await t.digest("SHA-256",new TextEncoder().encode(r));return Array.from(new Uint8Array(i),o=>o.toString(16).padStart(2,"0")).join("").slice(0,32)}function k(){try{let t=Number(navigator.maxTouchPoints);return Number.isFinite(t)&&t>=0?{touch:Math.min(64,Math.trunc(t))}:{}}catch{return{}}}function x(t){let e=new TextEncoder().encode(t),r="";for(let i of e)r+=String.fromCharCode(i);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function A(t){let e,r,i,o,a,l,u=()=>l?.readyState==="live",_=()=>{a!==void 0||!globalThis.crypto?.subtle||v()||u()||(a=Promise.race([import("./print-SEWS3VHQ.js"),new Promise(n=>setTimeout(n,P))]).then(n=>n?.computePrint(u)).then(n=>{n==="busy"?a=void 0:o=n}).catch(()=>{}))};return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(n){n&&(e=n.slice(0,128))},noteCamera(n){r=n},noteCameraTrack(n){l=n},async deviceHeader(){try{i??(i=w().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let g=await i,m=I(),S={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...m?[{kind:"web_local",value:m.slice(0,128)}]:[],...g?[{kind:"web_fp",value:g}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...k(),...e?{cameraLabel:e}:{},...n.length?{signals:n}:{},...o?{print:{v:2,...o,...r?{camera:r}:{}}}:{},...p()?{inApp:!0}:{}},C=x(JSON.stringify(S));return _(),C}catch{return}},printReady(){return a??Promise.resolve()}}}var s=Symbol.for("sekyro.web.clientContext"),c=globalThis,d=c[s]??(c[s]=A({sdk:`@sekyro/web@${f}`}));function M(t){try{let e=t.getVideoTracks?.()[0];if(e){if(d.noteCameraLabel(e.label),d.noteCameraTrack(e),v())return;import("./camera-trait-V4UAOPIQ.js").then(r=>r.noteCameraTrait(e,d)).catch(()=>{})}}catch{}}export{f as a,p as b,d as c,M as d};
1
+ var f="0.1.0-rc.26";var T=/FBAN|FBAV|FB_IAB|FBIOS|MessengerForiOS|Instagram|WhatsApp|musical_ly|BytedanceWebview|TikTok|Snapchat|\bLine\/|LinkedInApp|Pinterest|MicroMessenger|; wv\)/i;function p(t){let e=t??(typeof navigator>"u"?"":String(navigator.userAgent??""));return T.test(e)}var h="sekyro.did",P=1e4,v=()=>globalThis.process?.versions?.node,y;function b(){let t=globalThis.crypto;try{if(typeof t?.randomUUID=="function")return t.randomUUID()}catch{}try{if(typeof t?.getRandomValues=="function"){let e=t.getRandomValues(new Uint8Array(16));return Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}}catch{}}function I(){try{let t=localStorage.getItem(h);if(t)return t;let e=b();return e!==void 0&&localStorage.setItem(h,e),e}catch{return y??(y=b()),y}}async function w(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,r=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),i=await t.digest("SHA-256",new TextEncoder().encode(r));return Array.from(new Uint8Array(i),o=>o.toString(16).padStart(2,"0")).join("").slice(0,32)}function k(){try{let t=Number(navigator.maxTouchPoints);return Number.isFinite(t)&&t>=0?{touch:Math.min(64,Math.trunc(t))}:{}}catch{return{}}}function x(t){let e=new TextEncoder().encode(t),r="";for(let i of e)r+=String.fromCharCode(i);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function A(t){let e,r,i,o,a,l,u=()=>l?.readyState==="live",_=()=>{a!==void 0||!globalThis.crypto?.subtle||v()||u()||(a=Promise.race([import("./print-SEWS3VHQ.js"),new Promise(n=>setTimeout(n,P))]).then(n=>n?.computePrint(u)).then(n=>{n==="busy"?a=void 0:o=n}).catch(()=>{}))};return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(n){n&&(e=n.slice(0,128))},noteCamera(n){r=n},noteCameraTrack(n){l=n},async deviceHeader(){try{i??(i=w().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let g=await i,m=I(),S={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...m?[{kind:"web_local",value:m.slice(0,128)}]:[],...g?[{kind:"web_fp",value:g}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...k(),...e?{cameraLabel:e}:{},...n.length?{signals:n}:{},...o?{print:{v:2,...o,...r?{camera:r}:{}}}:{},...p()?{inApp:!0}:{}},C=x(JSON.stringify(S));return _(),C}catch{return}},printReady(){return a??Promise.resolve()}}}var s=Symbol.for("sekyro.web.clientContext"),c=globalThis,d=c[s]??(c[s]=A({sdk:`@sekyro/web@${f}`}));function M(t){try{let e=t.getVideoTracks?.()[0];if(e){if(d.noteCameraLabel(e.label),d.noteCameraTrack(e),v())return;import("./camera-trait-V4UAOPIQ.js").then(r=>r.noteCameraTrait(e,d)).catch(()=>{})}}catch{}}export{f as a,p as b,d as c,M as d};