@sekyro/web 0.1.0-rc.18 → 0.1.0-rc.19

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 (55) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +1 -2
  3. package/dist/{capture-session-doc-IE5VPYWC.js → capture-session-doc-VXWWQEP4.js} +1 -1
  4. package/dist/{capture-session-v3-Dxus1Se9.d.ts → capture-session-v3-CFSVWYzi.d.ts} +13 -2
  5. package/dist/{capture-session-v3-DyUA2uCL.d.cts → capture-session-v3-Cs4yV3HJ.d.cts} +13 -2
  6. package/dist/chunk-4GJXUVZK.js +1 -0
  7. package/dist/chunk-5Y3UST3W.js +1 -0
  8. package/dist/{chunk-JDTZK3A7.js → chunk-64V55KD7.js} +1 -1
  9. package/dist/chunk-6K4D3U6Q.js +1 -0
  10. package/dist/chunk-CQ7SKLMC.js +1 -0
  11. package/dist/{chunk-DNB3R4PI.js → chunk-JUEOHNVW.js} +1 -1
  12. package/dist/chunk-L45YTRJJ.js +1 -0
  13. package/dist/chunk-PLH6ZR6J.js +1 -0
  14. package/dist/chunk-RNJA5GDF.js +1 -0
  15. package/dist/chunk-ZO6IHP2I.js +1 -0
  16. package/dist/chunk-ZPXL26BF.js +1 -0
  17. package/dist/client/index.cjs +1 -1
  18. package/dist/client/index.d.cts +4 -4
  19. package/dist/client/index.d.ts +4 -4
  20. package/dist/client/index.js +1 -1
  21. package/dist/core/index.cjs +1 -1
  22. package/dist/core/index.d.cts +3 -3
  23. package/dist/core/index.d.ts +3 -3
  24. package/dist/core/index.js +1 -1
  25. package/dist/create-document-capture-FVSQPUF6.js +1 -0
  26. package/dist/create-portrait-capture-INDCF65X.js +1 -0
  27. package/dist/{create-verification-DiH7QRdv.d.cts → create-verification-1BrMZqPJ.d.cts} +67 -15
  28. package/dist/{create-verification-C_fx3n4A.d.ts → create-verification-CuoYJ3kj.d.ts} +67 -15
  29. package/dist/{icao-gate-5FzqyitT.d.ts → icao-gate-BSbyqLUh.d.ts} +25 -9
  30. package/dist/{icao-gate-C-lfjEpH.d.cts → icao-gate-D-wePfoV.d.cts} +25 -9
  31. package/dist/index.cjs +1 -1
  32. package/dist/index.d.cts +6 -6
  33. package/dist/index.d.ts +6 -6
  34. package/dist/index.js +1 -1
  35. package/dist/internal/index.cjs +1 -1
  36. package/dist/internal/index.d.cts +6 -6
  37. package/dist/internal/index.d.ts +6 -6
  38. package/dist/internal/index.js +1 -1
  39. package/dist/plan-runner-WEUIMCYU.js +1 -0
  40. package/dist/{types-CKgMWVnP.d.cts → types-DPl0hsmI.d.cts} +29 -5
  41. package/dist/{types-CKgMWVnP.d.ts → types-DPl0hsmI.d.ts} +29 -5
  42. package/package.json +1 -1
  43. package/sbom.cdx.json +7 -7
  44. package/dist/chunk-2BFYVMUU.js +0 -1
  45. package/dist/chunk-D42NBRSV.js +0 -1
  46. package/dist/chunk-G2HL2ZWH.js +0 -1
  47. package/dist/chunk-G6MU3B5V.js +0 -1
  48. package/dist/chunk-KBKCYDZQ.js +0 -1
  49. package/dist/chunk-OG4QAJ3M.js +0 -1
  50. package/dist/chunk-SVNAHPQU.js +0 -1
  51. package/dist/chunk-VCUOPQFA.js +0 -1
  52. package/dist/chunk-ZMO2ZQAS.js +0 -1
  53. package/dist/create-document-capture-35HFVNC3.js +0 -1
  54. package/dist/create-portrait-capture-53XBURNT.js +0 -1
  55. package/dist/plan-runner-YXTOSPDP.js +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # @sekyro/web
2
2
 
3
+ ## 0.1.0-rc.19
4
+
5
+ ### Minor Changes
6
+
7
+ - 5c480f8: Age check (selfie) copy. A document step reached because the selfie could not settle the person's age carries `ageStepUp: true`, and `<SekyroVerification>` shows "We could not confirm your age from the selfie. Continue with an ID document." on the first document screen the person sees, in all six locales. A session stopped with `underage_estimated` ends on "This service is for people who have reached its minimum age." in all six locales, instead of the generic rejection. New string keys: `doc.ageStepUp` and `reasons.underage_estimated`.
8
+
9
+ ### Patch Changes
10
+
11
+ - 61f92b1: Capture failures leave a diagnostic trace. A capture error now carries an optional `detail`: the step that was running (`phase`), the thrown error's `name` (never its message) and the engine's own kind before the public collapse (`engineKind`). A camera that Android Chrome reports as `AbortError` (held by a call or another app) is now `inuse`, and a `SecurityError` is `permission`. `Verification.reportCaptureIssue()` records a shown capture failure on the session (`POST /hosted/capture-issue`); it never changes the session, never bills and never counts as an attempt. `<LivenessCapture>` and the document step of `<SekyroVerification>` report the errors they show.
12
+
13
+ The result screen explains an owner check refused because the same person already earned the starting credit (`failureReason: "starter_credit_claimed"`, hosted owner checks only), in every SDK language.
14
+ - 4555bac: A flow can let the person choose how the face video is filmed. When the session's capture mode is `choice`, the person picks once, before the first camera step, between filming themselves and having an agent film them; the pick holds for the whole session, including the portrait camera. `@sekyro/web`: `Verification.chooseCaptureMode(mode)` records the pick, `captureChoice` reads it, `captureMode()` returns `"choice"` until a pick and the pick after, and the pick is sent with the capture (`input.capture.mode`). `CaptureMode` gains `"choice"` and the new `ResolvedCaptureMode` is `"self" | "assisted"`. The portrait still is encoded at the camera's full size. `@sekyro/react`: `<LivenessCapture>` and `<PortraitCapture>` show the new `CaptureModePicker` when the session is `choice` and nobody has picked yet, in every SDK language.
15
+ - c8ec50f: The hosted client retries once when the API answers 503 `server_busy` or `request_timeout`: it waits the `Retry-After` delay (at most 3 s), then repeats the call. Only calls that are safe to repeat retry: `getSession`, `identityPortrait`, `recordConsent`, `choose`, and `submitCheck` with an idempotency key. A second busy answer reaches the page as before.
16
+
3
17
  ## 0.1.0-rc.18
4
18
 
5
19
  ### Minor Changes
package/README.md CHANGED
@@ -67,8 +67,7 @@ await cap.start({ facing: "user" }); // reuses the warm detector automatically
67
67
  capture created afterwards with the same `assetBaseUrl` uses it without any extra
68
68
  wiring, and destroying a capture never frees it; call
69
69
  `releaseLivenessAssets(assetBaseUrl)` when the user leaves the flow (never while a
70
- capture is mounted). Without a preload the capture loads the detector itself, as
71
- before.
70
+ capture is mounted). Without a preload the capture loads the detector itself.
72
71
  - `getLivenessAssetsStatus` / `subscribeLivenessAssets` follow the
73
72
  `useSyncExternalStore` contract (no emit on subscribe). `subscribeCameraPermission`
74
73
  emits the current state first, then every change; `queryCameraPermission` is the
@@ -1 +1 @@
1
- import{C as a,D as b,E as c,F as d,G as e,H as f,I as g,J as h,K as i,L as j,M as k}from"./chunk-D42NBRSV.js";import"./chunk-SMKCBUJL.js";import"./chunk-MXWLCDFX.js";import"./chunk-G6LKLN4U.js";import"./chunk-TDLIXFDT.js";import"./chunk-POIQGEZM.js";import"./chunk-2BFYVMUU.js";import"./chunk-FPXL63KZ.js";import"./chunk-DNB3R4PI.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{C as a,D as b,E as c,F as d,G as e,H as f,I as g,J as h,K as i,L as j,M as k}from"./chunk-ZO6IHP2I.js";import"./chunk-SMKCBUJL.js";import"./chunk-MXWLCDFX.js";import"./chunk-G6LKLN4U.js";import"./chunk-TDLIXFDT.js";import"./chunk-POIQGEZM.js";import"./chunk-CQ7SKLMC.js";import"./chunk-FPXL63KZ.js";import"./chunk-JUEOHNVW.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 { ao as ScreenRampReport, j as CaptureProvenance, am as ScreenRampChallenge, S as ScreenRampColour } from './types-CKgMWVnP.js';
1
+ import { aq as ScreenRampReport, k as CaptureProvenance, ao as ScreenRampChallenge, S as ScreenRampColour } from './types-DPl0hsmI.js';
2
2
  import { F as FaceObservation, b as Detector, W as WorkerLike } from './detect-worker-DclNxkZT.js';
3
3
 
4
4
  /** MP4-first ladder: one container (H.264 MP4) covers iOS/macOS Safari + Chrome 130+.
@@ -323,6 +323,15 @@ declare class DeviceProfiler {
323
323
  record(detectMs: number): DeviceClass;
324
324
  }
325
325
 
326
+ /** Where a capture failed: the engine step that was running. */
327
+ type CaptureErrorPhase = "preflight" | "acquiring" | "models" | "recording" | "keyframes" | "upload";
328
+ /** Engine-side failure detail (the public handle adds the engine kind). */
329
+ interface EngineErrorDetail {
330
+ phase: CaptureErrorPhase;
331
+ /** The thrown error's `name` only, sanitised by {@link errorNameOf}. */
332
+ name?: string;
333
+ }
334
+
326
335
  /** Why a gate tick did not advance: no face, or the weakest gate check. */
327
336
  type GateBlockReason = "no_face" | Exclude<V3GateFactor, "presence">;
328
337
  interface GateBlockEntry {
@@ -384,9 +393,11 @@ interface CaptureSessionV3Events {
384
393
  key: string;
385
394
  };
386
395
  artifacts: CaptureArtifacts;
396
+ /** `detail`: where the attempt failed and the thrown error's name (never its message). */
387
397
  error: {
388
398
  kind: CaptureErrorKind;
389
399
  retryable: boolean;
400
+ detail?: EngineErrorDetail;
390
401
  };
391
402
  /** v3-only, CHROME-only (no data flows here): fires the instant the clip
392
403
  * recording window ends — BEFORE the blob finalizes (iOS onstop can lag up
@@ -613,4 +624,4 @@ declare class CaptureSessionV3 {
613
624
  private now;
614
625
  }
615
626
 
616
- export { isClipTooLarge as $, MIME_CANDIDATES as A, type V3GateFactor as B, type CameraErrorKind as C, DEFAULT_CLIP_MIME as D, type EscalationClipArtifact as E, FaceGateV3 as F, GATE_SNAPSHOT_MS as G, HOLD_UPRIGHT_KEY as H, type V3GateQuality as I, type V3GateThresholds as J, KEYFRAME_CANDIDATES as K, type V3GateTick as L, MAX_CLIP_BYTES as M, type V3GateTickInput as N, type V3TelemetryEvent as O, PROVENANCE_WAIT_MS as P, V3_GATE_DEFAULTS as Q, VIDEO_BPS as R, STOP_GRACE_MS as S, TIMESLICE_MS as T, UPRIGHT_WATCH_MS as U, type V3ChecksPayload as V, blockReasonOf as W, buildLivenessV2FormData as X, cameraPreflight as Y, classifyDevice as Z, extForMime as _, CLIP_MS as a, isMediaRecorderSupported as a0, mapGetUserMediaError as a1, pickMimeType as a2, probeDevice as a3, type CaptureArtifacts as b, type CaptureErrorKind as c, type CaptureSessionEvents as d, CaptureSessionV3 as e, type CaptureSessionV3Events as f, type CaptureSessionV3Options as g, type CaptureSessionV3StartOptions as h, type CaptureState as i, type CaptureTiming as j, ClipError as k, type ClipErrorKind as l, ClipRecorder as m, type ClipResult as n, DEVICE_PROFILES as o, type DeviceClass as p, type DeviceProbe as q, type DeviceProfile as r, DeviceProfiler as s, type EscalationHook as t, type GateBlockEntry as u, type GateBlockReason as v, GateBlockStats as w, type GateBlockSummary as x, type GateChecks as y, KEYFRAME_WINDOW_MS as z };
627
+ export { isClipTooLarge as $, MIME_CANDIDATES as A, type V3GateFactor as B, type CameraErrorKind as C, DEFAULT_CLIP_MIME as D, type EscalationClipArtifact as E, FaceGateV3 as F, GATE_SNAPSHOT_MS as G, HOLD_UPRIGHT_KEY as H, type V3GateQuality as I, type V3GateThresholds as J, KEYFRAME_CANDIDATES as K, type V3GateTick as L, MAX_CLIP_BYTES as M, type V3GateTickInput as N, type V3TelemetryEvent as O, PROVENANCE_WAIT_MS as P, V3_GATE_DEFAULTS as Q, VIDEO_BPS as R, STOP_GRACE_MS as S, TIMESLICE_MS as T, UPRIGHT_WATCH_MS as U, type V3ChecksPayload as V, blockReasonOf as W, buildLivenessV2FormData as X, cameraPreflight as Y, classifyDevice as Z, extForMime as _, CLIP_MS as a, isMediaRecorderSupported as a0, mapGetUserMediaError as a1, pickMimeType as a2, probeDevice as a3, type EngineErrorDetail as a4, type CaptureArtifacts as b, type CaptureErrorKind as c, type CaptureSessionEvents as d, CaptureSessionV3 as e, type CaptureSessionV3Events as f, type CaptureSessionV3Options as g, type CaptureSessionV3StartOptions as h, type CaptureState as i, type CaptureTiming as j, ClipError as k, type ClipErrorKind as l, ClipRecorder as m, type ClipResult as n, DEVICE_PROFILES as o, type DeviceClass as p, type DeviceProbe as q, type DeviceProfile as r, DeviceProfiler as s, type EscalationHook as t, type GateBlockEntry as u, type GateBlockReason as v, GateBlockStats as w, type GateBlockSummary as x, type GateChecks as y, KEYFRAME_WINDOW_MS as z };
@@ -1,4 +1,4 @@
1
- import { ao as ScreenRampReport, j as CaptureProvenance, am as ScreenRampChallenge, S as ScreenRampColour } from './types-CKgMWVnP.cjs';
1
+ import { aq as ScreenRampReport, k as CaptureProvenance, ao as ScreenRampChallenge, S as ScreenRampColour } from './types-DPl0hsmI.cjs';
2
2
  import { F as FaceObservation, b as Detector, W as WorkerLike } from './detect-worker-DclNxkZT.cjs';
3
3
 
4
4
  /** MP4-first ladder: one container (H.264 MP4) covers iOS/macOS Safari + Chrome 130+.
@@ -323,6 +323,15 @@ declare class DeviceProfiler {
323
323
  record(detectMs: number): DeviceClass;
324
324
  }
325
325
 
326
+ /** Where a capture failed: the engine step that was running. */
327
+ type CaptureErrorPhase = "preflight" | "acquiring" | "models" | "recording" | "keyframes" | "upload";
328
+ /** Engine-side failure detail (the public handle adds the engine kind). */
329
+ interface EngineErrorDetail {
330
+ phase: CaptureErrorPhase;
331
+ /** The thrown error's `name` only, sanitised by {@link errorNameOf}. */
332
+ name?: string;
333
+ }
334
+
326
335
  /** Why a gate tick did not advance: no face, or the weakest gate check. */
327
336
  type GateBlockReason = "no_face" | Exclude<V3GateFactor, "presence">;
328
337
  interface GateBlockEntry {
@@ -384,9 +393,11 @@ interface CaptureSessionV3Events {
384
393
  key: string;
385
394
  };
386
395
  artifacts: CaptureArtifacts;
396
+ /** `detail`: where the attempt failed and the thrown error's name (never its message). */
387
397
  error: {
388
398
  kind: CaptureErrorKind;
389
399
  retryable: boolean;
400
+ detail?: EngineErrorDetail;
390
401
  };
391
402
  /** v3-only, CHROME-only (no data flows here): fires the instant the clip
392
403
  * recording window ends — BEFORE the blob finalizes (iOS onstop can lag up
@@ -613,4 +624,4 @@ declare class CaptureSessionV3 {
613
624
  private now;
614
625
  }
615
626
 
616
- export { isClipTooLarge as $, MIME_CANDIDATES as A, type V3GateFactor as B, type CameraErrorKind as C, DEFAULT_CLIP_MIME as D, type EscalationClipArtifact as E, FaceGateV3 as F, GATE_SNAPSHOT_MS as G, HOLD_UPRIGHT_KEY as H, type V3GateQuality as I, type V3GateThresholds as J, KEYFRAME_CANDIDATES as K, type V3GateTick as L, MAX_CLIP_BYTES as M, type V3GateTickInput as N, type V3TelemetryEvent as O, PROVENANCE_WAIT_MS as P, V3_GATE_DEFAULTS as Q, VIDEO_BPS as R, STOP_GRACE_MS as S, TIMESLICE_MS as T, UPRIGHT_WATCH_MS as U, type V3ChecksPayload as V, blockReasonOf as W, buildLivenessV2FormData as X, cameraPreflight as Y, classifyDevice as Z, extForMime as _, CLIP_MS as a, isMediaRecorderSupported as a0, mapGetUserMediaError as a1, pickMimeType as a2, probeDevice as a3, type CaptureArtifacts as b, type CaptureErrorKind as c, type CaptureSessionEvents as d, CaptureSessionV3 as e, type CaptureSessionV3Events as f, type CaptureSessionV3Options as g, type CaptureSessionV3StartOptions as h, type CaptureState as i, type CaptureTiming as j, ClipError as k, type ClipErrorKind as l, ClipRecorder as m, type ClipResult as n, DEVICE_PROFILES as o, type DeviceClass as p, type DeviceProbe as q, type DeviceProfile as r, DeviceProfiler as s, type EscalationHook as t, type GateBlockEntry as u, type GateBlockReason as v, GateBlockStats as w, type GateBlockSummary as x, type GateChecks as y, KEYFRAME_WINDOW_MS as z };
627
+ export { isClipTooLarge as $, MIME_CANDIDATES as A, type V3GateFactor as B, type CameraErrorKind as C, DEFAULT_CLIP_MIME as D, type EscalationClipArtifact as E, FaceGateV3 as F, GATE_SNAPSHOT_MS as G, HOLD_UPRIGHT_KEY as H, type V3GateQuality as I, type V3GateThresholds as J, KEYFRAME_CANDIDATES as K, type V3GateTick as L, MAX_CLIP_BYTES as M, type V3GateTickInput as N, type V3TelemetryEvent as O, PROVENANCE_WAIT_MS as P, V3_GATE_DEFAULTS as Q, VIDEO_BPS as R, STOP_GRACE_MS as S, TIMESLICE_MS as T, UPRIGHT_WATCH_MS as U, type V3ChecksPayload as V, blockReasonOf as W, buildLivenessV2FormData as X, cameraPreflight as Y, classifyDevice as Z, extForMime as _, CLIP_MS as a, isMediaRecorderSupported as a0, mapGetUserMediaError as a1, pickMimeType as a2, probeDevice as a3, type EngineErrorDetail as a4, type CaptureArtifacts as b, type CaptureErrorKind as c, type CaptureSessionEvents as d, CaptureSessionV3 as e, type CaptureSessionV3Events as f, type CaptureSessionV3Options as g, type CaptureSessionV3StartOptions as h, type CaptureState as i, type CaptureTiming as j, ClipError as k, type ClipErrorKind as l, ClipRecorder as m, type ClipResult as n, DEVICE_PROFILES as o, type DeviceClass as p, type DeviceProbe as q, type DeviceProfile as r, DeviceProfiler as s, type EscalationHook as t, type GateBlockEntry as u, type GateBlockReason as v, GateBlockStats as w, type GateBlockSummary as x, type GateChecks as y, KEYFRAME_WINDOW_MS as z };
@@ -0,0 +1 @@
1
+ import{a as ue,d as ce}from"./chunk-CJHMFPL6.js";import{a as se}from"./chunk-RI3E7GBN.js";import{a as B,e as re,g as ae,m as oe}from"./chunk-7ZCZY3ZP.js";import{b as ie}from"./chunk-BPE5NSQ2.js";import{a as ee,d as te,e as ne}from"./chunk-GT2ZLGF7.js";import{e as X}from"./chunk-FUHDOEBP.js";import{m as $,n as Z}from"./chunk-CQ7SKLMC.js";var xe=250,be=180,we=96;function le(n){let{data:t,width:e,height:r}=n,a=new Uint8Array(e*r);for(let o=0,u=0;o<a.length;o+=1,u+=4)a[o]=Math.round(.299*(t[u]??0)+.587*(t[u+1]??0)+.114*(t[u+2]??0));return{data:a,width:e,height:r}}function q(n,t){return{x0:Math.max(0,Math.floor(n.x)),y0:Math.max(0,Math.floor(n.y)),x1:Math.min(t.width,Math.ceil(n.x+n.width)),y1:Math.min(t.height,Math.ceil(n.y+n.height))}}function T(n,t,e){let r=q(t,n),a=e===void 0?null:q(e,n),o=0,u=0,s=0,d=0;for(let c=r.y0;c<r.y1;c+=1)for(let y=r.x0;y<r.x1;y+=1){if(a!==null&&y>=a.x0&&y<a.x1&&c>=a.y0&&c<a.y1)continue;let M=n.data[c*n.width+y];o+=1,u+=M,s+=M*M,M>=xe&&(d+=1)}if(o===0)return{mean:0,sd:0,clipped:0,count:0};let m=u/o;return{mean:m,sd:Math.sqrt(Math.max(0,s/o-m*m)),clipped:d/o,count:o}}function me(n){let{box:t}=n,r=(n.leftEye.y+n.rightEye.y)/2-.1*t.height,a=t.y+.85*t.height;return{x:t.x+.15*t.width,y:r,width:.7*t.width,height:Math.max(1,a-r)}}function ve(n,t){let e=me(t),r=T(n,e);if(r.count===0)return null;let a=Math.min(Math.max(t.nose.x,e.x+1),e.x+e.width-1),o=T(n,{x:e.x,y:e.y,width:a-e.x,height:e.height}),u=T(n,{x:a,y:e.y,width:e.x+e.width-a,height:e.height}),s=u.mean>0?o.mean/u.mean:o.mean>0?Number.POSITIVE_INFINITY:1;return{faceLuma:r.mean,halfRatio:s,clipped:r.clipped}}function Ce(n,t){let e=0,r=0;for(let a of[t.leftEyeBox,t.rightEyeBox]){let o=a.width*.15,u=a.height*.5,s=T(n,{x:a.x-o,y:a.y-u,width:a.width+2*o,height:a.height+2*u});e+=s.count,r+=s.clipped*s.count}return e===0?null:r/e}function Pe(n,t){let e=re(t),{box:r}=t,a={x:r.x-.2*r.width,y:e.y,width:1.4*r.width,height:r.y+r.height-e.y},o=0,u=0,s=0;for(let m of[e.x,e.x+.8*e.width]){let c=T(n,{x:m,y:e.y+.04*e.height,width:.2*e.width,height:.25*e.height},a);o+=c.count,u+=c.mean*c.count,s+=(c.sd*c.sd+c.mean*c.mean)*c.count}if(o===0)return null;let d=u/o;return{luma:d,sd:Math.sqrt(Math.max(0,s/o-d*d)),count:o}}function ke(n,t){let e=q(me(t),n),r=Math.max(1,Math.floor(Math.max(e.x1-e.x0,e.y1-e.y0)/we)),a=(m,c)=>n.data[c*n.width+m],o=0,u=0,s=0;for(let m=e.y0+r;m<e.y1-r;m+=r)for(let c=e.x0+r;c<e.x1-r;c+=r){let y=a(c,m-r)+a(c-r,m)+a(c+r,m)+a(c,m+r)-4*a(c,m);o+=1,u+=y,s+=y*y}if(o===0)return null;let d=u/o;return Math.min(1,Math.max(0,s/o-d*d)/be)}function de(n,t){return{lighting:ve(n,t),eyeSpecular:Ce(n,t),background:Pe(n,t),sharpness:ke(n,t)}}var Me="/models-v3",Le=640,Se=.92;function N(n){return{width:n.videoWidth||0,height:n.videoHeight||0}}function W(n,t){if(typeof document<"u"){let e=document.createElement("canvas");return e.width=n,e.height=t,e}return typeof OffscreenCanvas=="function"?new OffscreenCanvas(n,t):null}function Fe(){let n=null;return(t,e)=>{let{width:r,height:a}=N(t);if(r===0||a===0)return null;let o=e===null?1:Math.min(1,e/Math.max(r,a)),u=Math.round(r*o),s=Math.round(a*o),d;e===null?d=W(u,s):((n===null||n.width!==u||n.height!==s)&&(n=W(u,s)),d=n);let m=d?.getContext("2d",{willReadFrequently:!0});if(d==null||m==null)return null;m.drawImage(t,0,0,u,s);let c=null;try{c=m.getImageData(0,0,u,s)}catch{c=null}return{source:d,width:u,height:s,pixels:c}}}async function Te(n,t,e,r){let a=Math.round(e*t.width/t.height),o=W(a,e),u=o?.getContext("2d");if(o==null||u==null)throw new Error("canvas unavailable");return u.fillStyle="#fff",u.fillRect(0,0,a,e),u.drawImage(n.source,t.x,t.y,t.width,t.height,0,0,a,e),"convertToBlob"in o?o.convertToBlob({type:"image/jpeg",quality:r}):new Promise((s,d)=>{o.toBlob(m=>m===null?d(new Error("encode failed")):s(m),"image/jpeg",r)})}var Y=class extends Error{};function Ee(n,t,e){return new Promise((r,a)=>{let o=setTimeout(()=>{a(new Y(`init exceeded ${t}ms`)),n.then(e,()=>{})},t);n.then(u=>{clearTimeout(o),r(u)},u=>{clearTimeout(o),a(u)})})}function Ie(n){let t=$(n),e=t==="overconstrained"?"generic":t;return{kind:e,retryable:e!=="insecure"&&e!=="unsupported"}}function Re(n,t,e,r){let a=n.length===1?n[0]:void 0,o=a===void 0?null:B(a.landmarks,e,r),u=null;if(a!==void 0&&t.pixels!==null){let s=B(a.landmarks,t.width,t.height),d=le(t.pixels);s!==null&&(u=de(d,s))}return{frameWidth:e,frameHeight:r,faces:n.length,geometry:o,matrix:a?.matrix??null,blendshapes:a?.blendshapes??null,stats:u}}function ze(n,t={},e=()=>"self"){let r=ie(n.tuning,n.tuningVersion),a=ee(),o=t.now??(()=>performance.now()),u=t.setTimer??((i,l)=>setTimeout(i,l)),s=t.clearTimer??(i=>clearTimeout(i)),d=t.grabFrame??Fe(),m=t.encodeRegion??Te,c=t.getUserMedia??(i=>navigator.mediaDevices.getUserMedia(i)),y=t.createLandmarker??ce,M=n.assetBaseUrl??Me,j=ne({enabled:n.keepScreenAwake!==!1}),L=oe(r,{policy:n.policy??"reject"}),b=n.video,K=se({tuning:r.backgroundCheck,assetBaseUrl:M,...t.createSegmenter!==void 0?{createSegmenter:t.createSegmenter}:{},now:o}),h="idle",C=null,x=null,E=null,G=!1,f=!1,g=0,z=0,A=[],w="user",O=!1,he=t.canChooseFacing??te,S=i=>{h===i||f||(h=i,j.setActive(i==="starting"||i==="gating"),a.emit("state",i))},U=()=>{E!==null&&s(E),E=null},I=()=>{U();for(let i of C?.getTracks()??[])i.stop();C=null;try{b.srcObject=null}catch{}},H=i=>{I(),S("error"),a.emit("error",i)},J=()=>{let i=Math.max(o(),z+1);return z=i,i},fe=async i=>{let l=d(b,null),{width:P,height:k}=l??N(b);if(l===null||x===null){L.reset();return}let p=x.detect(l.source,J()),v=(p.length===1?p:A.length===1?A:[])[0],F=v===void 0?null:B(v.landmarks,P,k);if(F===null){L.reset();return}let R=ae(F,P,k,{margin:r.cropMargin,minWidth:r.resolution.minWidth,minHeight:r.resolution.minHeight}),V=Math.max(r.resolution.minHeight,R.height),ye=await m(l,R,V,Se);if(f||i!==g)return;let Q={image:ye,width:Math.round(V*R.width/R.height),height:V,gate:L.summary()};r.tuningVersion!==null&&(Q.tuningVersion=r.tuningVersion),U(),S("captured"),a.emit("captured",Q)},_=async i=>{if(!(f||i!==g||h!=="gating"||x===null)){if(!G){G=!0;try{let l=d(b,Le);if(l!==null){let{width:P,height:k}=N(b),p=x.detect(l.source,J());A=p;let v=Re(p,l,P||l.width,k||l.height);v.geometry!==null&&r.background.required&&(v.backgroundCheck=K.measure(l,v.geometry.box,P||l.width,k||l.height));let F=L.push(v,o());if(f||i!==g||(a.emit("gate",F),F.ready&&(await fe(i),h!=="gating")))return}}catch{}finally{G=!1}}!f&&i===g&&h==="gating"&&(E=u(()=>{_(i)},1e3/r.cadenceHz))}},ge=()=>Ee(y(M),2e4,i=>i.close()),pe=async i=>{if(e()!=="assisted")return"user";let l=i??(O?void 0:n.facing);if(l!==void 0)return l;if(O)return w;try{return await he()?"environment":"user"}catch{return"user"}},D=async i=>{if(f||h==="starting"||h==="gating")return;g+=1;let l=g;L.reset(),S("starting");let P=await pe(i?.facing);if(f||l!==g)return;if(C!==null&&P!==w&&I(),w=P,O=!0,C===null&&t.getUserMedia===void 0&&(typeof navigator>"u"||typeof navigator.mediaDevices?.getUserMedia!="function")){H({kind:typeof window<"u"&&window.isSecureContext===!1?"insecure":"unsupported",retryable:!1});return}let k=x!==null?Promise.resolve(x):ge();k.catch(()=>{});try{if(C===null){let p=await c({video:{facingMode:w,width:{ideal:r.camera.width},height:{ideal:r.camera.height}},audio:!1});if(f||l!==g){for(let v of p.getTracks())v.stop();return}C=p,Z(p),w=X(p)??w,b.srcObject=C,b.muted=!0,b.playsInline=!0,await b.play().catch(()=>{})}}catch(p){!f&&l===g&&H(Ie(p));return}try{x=await k}catch{!f&&l===g&&H({kind:"generic",retryable:!0});return}f||l!==g||(S("gating"),_(l))};return{handle:{get state(){return h},get captureMode(){return e()},get facingMode(){return w},on:(i,l)=>a.on(i,l),start:D,retry:()=>{if(!f){if(C!==null&&x!==null&&h!=="error"){g+=1;let i=g;U(),L.reset(),S("gating"),_(i);return}h="idle",D()}},switchCamera:()=>{if(f||e()!=="assisted"||h!=="idle"&&h!=="starting"&&h!=="gating"&&h!=="error")return!1;let i=w==="user"?"environment":"user";return g+=1,I(),w=i,h="idle",D({facing:i}),!0},destroy:()=>{f||(g+=1,I(),j.setActive(!1),f=!0,x?.close(),x=null,K.close(),a.clear())}},setFlowState:i=>{(h==="captured"||h==="uploading"||h==="checking"||h==="done"&&i==="done")&&S(i)}}}function Je(){import("@mediapipe/tasks-vision").catch(()=>{})}export{xe as a,be as b,le as c,T as d,ve as e,Ce as f,Pe as g,ke as h,de as i,Le as j,Se as k,Fe as l,Re as m,ze as n,Je as o};
@@ -0,0 +1 @@
1
+ import{a as f,b as y}from"./chunk-JUEOHNVW.js";var T=["session_token_invalid","session_token_required","session_token_session_mismatch","session_not_found","rate_limit_exceeded","consent_required","session_not_active","check_not_found","check_already_finalized","check_out_of_order","check_type_unsupported","force_outcome_forbidden","attestation_invalid","platform_unregistered","app_attest_invalid","too_many_challenges","inference_unavailable","mobile_required","nni_locked","document_nni_mismatch","media_content_type_not_allowed","media_too_large","media_key_invalid","media_key_forbidden","media_not_found","media_unreadable","media_session_invalid","idempotency_key_collision","idempotency_in_progress","idempotency_key_required","validation_error","internal_error","unknown_error","upload_failed","network_error","timeout","nfc_outcome_not_accepted","identity_confirm_required","identity_confirm_locked","choice_not_found","choice_locked","choice_option_unavailable","step_not_on_path","check_not_active","sekyro_app_not_allowed","sekyro_app_unverified","id_number_locked","document_id_number_mismatch"];function H(s){return T.includes(s)}var c=class extends Error{constructor(e){super(e.message),this.name="HostedApiError",this.status=e.status,this.code=e.code,e.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=e.retryAfterSeconds),e.details&&(this.details=e.details)}};var w=6e4,h=4,S=3e4,k=9e5,P=200,C=5,I=400,E=new Set(["server_busy","request_timeout"]),R=3e3;function l(s){return(s.split(";")[0]??"").trim()}var v={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},M=`@sekyro/web/${f}`,A=M,_=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.reportedIssues=new Set;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let n=e.fetch;this.fetchImpl=(t,i)=>(n??globalThis.fetch).call(globalThis,t,i),this.requestTimeoutMs=e.requestTimeoutMs??S,this.retryAttempts=e.inProgressRetry?.attempts??C,this.retryDelayMs=e.inProgressRetry?.delayMs??I}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e},busyRetry:!0})}async reportCameraUnavailable(e){return this.api("POST","/hosted/camera-unavailable",{body:{cause:e}})}async reportCaptureIssue(e){let n=typeof e.name=="string"?e.name.replace(/[^A-Za-z]/g,"").slice(0,40):"",t=typeof e.engineKind=="string"&&/^[a-z_]{1,32}$/.test(e.engineKind)?e.engineKind:void 0,i=typeof e.attempt=="number"&&Number.isInteger(e.attempt)&&e.attempt>=0&&e.attempt<=1e3?e.attempt:void 0,o=[e.check,i??"",e.kind,n,e.phase??""].join("|");if(this.reportedIssues.has(o))return;this.reportedIssues.add(o);let a={check:e.check,kind:e.kind,...n!==""?{name:n}:{},...e.phase!==void 0?{phase:e.phase}:{},...t!==void 0?{engineKind:t}:{},...i!==void 0?{attempt:i}:{},...e.formFactor!==void 0?{formFactor:e.formFactor}:{}};try{await this.api("POST","/hosted/capture-issue",{body:a,empty:!0})}catch{}}async choose(e,n){let t=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:n},busyRetry:!0});return this.sessionId=t.sessionId,t}async confirmIdentity(e){return this.api("POST","/hosted/identity/confirm",{body:{decision:e}})}async identityPortrait(){return this.api("GET","/hosted/identity/portrait",{blob:!0})}async presign(e,n,t){let i=await this.ensureSessionId(),o={kind:e,contentType:l(n),contentLength:t};return this.api("POST",`/sessions/${i}/media`,{body:o})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,n,t,i={}){let o=await this.ensureSessionId(),a=await this.takeCaptureNonce(),d=a===void 0?void 0:{nonce:a,...i.engine!==void 0?{engine:i.engine.slice(0,32)}:{},...i.durationMs!==void 0&&Number.isFinite(i.durationMs)?{captureMs:Math.min(36e5,Math.max(0,Math.round(i.durationMs)))}:{}},r={kind:e,contentType:l(n),contentLength:t,capture:d};return this.api("POST",`/sessions/${o}/media`,{body:r})}async takeCaptureNonce(){let e=()=>{let n=Date.now();return this.captureNonces=this.captureNonces.filter(t=>t.expiresAt-w>n),this.captureNonces.shift()?.nonce};for(let n=0;n<2;n++){let t=e();if(t!==void 0)return t;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let n=await this.ensureSessionId(),t=await this.api("POST",`/sessions/${n}/media/capture-nonces`,{body:{count:Math.min(h,Math.max(1,e))}}),i=Date.now()+Math.max(0,t.expiresIn)*1e3;for(let o of Array.isArray(t.nonces)?t.nonces:[])typeof o=="string"&&o.length>0&&this.captureNonces.push({nonce:o,expiresAt:i});this.captureNonces=this.captureNonces.slice(-h)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,n,t){let i;try{i=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":l(t)},body:n,signal:AbortSignal.timeout(k)})}catch(o){throw m(o)}if(!i.ok){let o=(await i.text().catch(()=>"")).slice(0,P);throw new c({status:i.status,code:"upload_failed",message:`media upload failed (HTTP ${i.status})${o?`: ${o}`:""}`})}}async completeMedia(e){let n=await this.ensureSessionId();return this.api("POST",`/sessions/${n}/media/complete`,{body:{key:e}})}async submitCheck(e,n,t={}){let i=await this.ensureSessionId(),o={input:n,forceOutcome:t.forceOutcome};return this.api("POST",`/sessions/${i}/checks/${e}`,{body:o,idempotencyKey:t.idempotencyKey,busyRetry:t.idempotencyKey!==void 0})}async uploadAndSubmit(e,n,t,i={}){let o=l(n.contentType),a=await this.presign(n.kind,o,n.blob.size);await this.uploadToSpaces(a.uploadUrl,n.blob,o);let d=await this.completeMedia(a.key),r={...t,[v[e]]:d.key};return this.submitCheck(e,r,i)}async ensureSessionId(){return this.sessionId!==null?this.sessionId:(this.bootstrap??(this.bootstrap=this.getSession().finally(()=>{this.bootstrap=null})),(await this.bootstrap).sessionId)}async api(e,n,t={}){let i=e==="GET"||t.busyRetry===!0,o=`${this.apiOrigin}/api/v2${n}`,a={"x-session-token":this.sessionToken,"x-sekyro-sdk":A};t.body!==void 0&&(a["content-type"]="application/json"),t.idempotencyKey!==void 0&&(a["x-idempotency-key"]=t.idempotencyKey);try{let d=y.timezone();d!==void 0&&(a["sekyro-client-timezone"]=d)}catch{}try{let d=await y.deviceHeader();d!==void 0&&(a["sekyro-client-device"]=d)}catch{}for(let d=0;;d++){let r;try{r=await this.fetchImpl(o,{method:e,headers:a,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(p){throw m(p)}if(r.ok){if(t.empty===!0)return;if(t.blob===!0)try{return await r.blob()}catch(b){throw m(b)}let p;try{p=await r.json()}catch{throw new c({status:r.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${r.status})`})}return O(p)}let u=await N(r);if(u.code==="idempotency_in_progress"&&d<this.retryAttempts){this.retryDelayMs>0&&await g(this.retryDelayMs);continue}if(i&&u.status===503&&E.has(u.code)){i=!1,await g(Math.min((u.retryAfterSeconds??2)*1e3,R));continue}throw u}}};function m(s){if((typeof s=="object"&&s!==null?s.name:void 0)==="TimeoutError")return new c({status:0,code:"timeout",message:"request timed out"});let n=s instanceof Error?s.message:String(s);return new c({status:0,code:"network_error",message:`network request failed: ${n}`})}function O(s){return s!==null&&typeof s=="object"&&"success"in s&&"data"in s?s.data:s}async function N(s){let e="unknown_error",n=`request failed (HTTP ${s.status})`,t=Number.NaN,i;try{let d=await s.json();if(d!==null&&typeof d=="object"){let r=d;typeof r.code=="string"&&r.code.length>0&&(e=r.code),typeof r.message=="string"&&r.message.length>0&&(n=r.message),typeof r.retryAfterSeconds=="number"&&(t=r.retryAfterSeconds),Array.isArray(r.details?.issues)&&(i=r.details)}}catch{}let o=s.headers.get("retry-after"),a=o===null?Math.floor(t):Number.parseInt(o,10);return new c({status:s.status,code:e,message:n,...Number.isFinite(a)&&a>=0?{retryAfterSeconds:a}:{},details:i})}function g(s){return new Promise(e=>setTimeout(e,s))}function q(s){let e=s?.portrait,n=e?.icao,t=e?.purpose==="id_document";return n==null?t?{policy:"reject",profile:"id_document"}:null:{policy:n.policy==="alert"&&!t?"alert":"reject",profile:t||n.profile==="id_document"?"id_document":"selfie"}}function $(s){return{...s.baselineEyeOpenness!==void 0?{baselineEyeOpenness:s.baselineEyeOpenness}:{},criteria:s.verdict??{},...s.backgroundCheck!==void 0?{backgroundCheck:s.backgroundCheck}:{}}}export{T as a,H as b,c,l as d,M as e,_ as f,q as g,$ as h};
@@ -1 +1 @@
1
- import{c as v,d as M}from"./chunk-ZMO2ZQAS.js";var A=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",sandbox_nni_not_seeded:"sandbox_id_number_not_seeded",missing_nni:"missing_id_number",registry_needs_nni_source:"registry_needs_id_number_source"}),I=new Map(Object.entries(A)),j=new Map(Object.entries(A).map(([e,n])=>[n,e]));function Re(e){return I.get(e)??e}function B(e){let n=I.get(e)??j.get(e);return n===void 0?[e]:[e,n]}function H(e){let n=[];for(let t of e)for(let i of B(t))n.includes(i)||n.push(i);return n}var $=new Set(H(["no_face","media_unreadable","clip_too_short","no_face_source","side_missing","unreadable","registry_unavailable","otp_mismatch","otp_expired","otp_send_failed","document_type_not_accepted","age_unverifiable","nationality_unreadable","liveness_inconclusive","match_inconclusive","document_authenticity","probe_not_from_liveness","capture_back_camera","capture_not_upright","chip_read_failed","chip_access_denied","chip_parse_failed","icao_pose","icao_eyes","icao_mouth","icao_occlusion","icao_lighting","icao_background","icao_resolution","portrait_not_from_liveness","nni_recheck","device_integrity_failed","eid_identifier_invalid","eid_code_invalid","eid_code_expired","eid_unavailable","eid_resend_too_soon"])),z={document:"document_photo",nfc:"document_chip",population_registry:"national_number",national_eid:"national_eid"};function f(e){return e.plan?.steps??[]}function T(e){return Math.max(0,e.attempts.max-e.attempts.used)}function W(e){let n=e.plan?.choice;return n!==void 0&&e.plan?.current===n.nodeId?n:null}function ke(e){let n=W(e);if(n?.kind!=="identity_method")return null;let t=n.options.map(o=>z[o.service]).filter(o=>o!==void 0),i=n.options.find(o=>o.nationalEid)?.nationalEid;return i?{available:!0,selected:null,options:t,nationalEid:i}:{available:!0,selected:null,options:t}}var X=new Set(["liveness","face_match"]);function E(e){return e!==void 0&&(e.state==="pending"||e.state==="input_required")}function O(e){return e.status!=="created"&&e.status!=="in_progress"}function x(e){let n=e.plan?.current,t=n==null?void 0:f(e).find(i=>i.id===n);return E(t)?t:void 0}function g(e,n){return f(e).find(t=>t.checkType===n)}function y(e){let n=f(e),t=n.findIndex(i=>i.checkType==="liveness");return n.find((i,o)=>o>t&&i.checkType==="face_match")}function L(e,n){let t=g(n,"liveness")?.state,i=y(n)?.state;return(y(e)?.state??"pending")==="pending"&&(t==="passed"||t==="review")&&i!==void 0&&i!=="pending"&&i!=="skipped"}function P(e,n){let t=new Map(f(e).map(i=>[i.id,i.state]));return f(n).filter(i=>i.checkType==="face_match"&&(t.get(i.id)??"pending")==="pending"&&i.state!=="pending"&&i.state!=="skipped").map(i=>i.id)}var G=/^[0-9a-f]{24}$/i;function w(e){return G.test(e)?`ses_${e}`:e}function b(e,n){let t=w(e);return n===void 0?{sessionId:t,status:"unavailable"}:{sessionId:t,status:"unavailable",reason:n}}function _(e,n,t){let i=w(e);return t===void 0?{sessionId:i,status:n}:{sessionId:i,status:n,reason:t}}function Ce(e,n){let{sessionId:t}=e;switch(e.status){case"completed":case"failed":case"review_pending":return Q(e,Z(e));case"expired":return b(t);case"created":case"in_progress":break;default:{let i=e.status;throw new Error(`mapSessionResult: unhandled status ${i}`)}}return ne(e,n)}var J=new Set([0,1,2,3]);function Q(e,n){if(J.has(e.level)&&(n.level=e.level),typeof e.assurance=="string"&&e.assurance.length>0&&(n.assurance=e.assurance),typeof e.subjectId=="string"&&e.subjectId.length>0){n.subjectId=e.subjectId;let t=/^([0-9a-f]{24})$/i.exec(e.subjectId)?.[1];t!==void 0&&(n.personId=`per_${t.toLowerCase()}`)}return n}function Z(e){let n=w(e.sessionId);switch(e.status){case"completed":return e.outcome==="approved"?{sessionId:n,status:"approved"}:e.outcome==="review"?_(n,"review",h(e,"review")):_(n,"rejected",h(e,"failed"));case"failed":{let t=_(n,"rejected",e.failureReason??h(e,"failed"));return e.failureReason==="device_cooldown"&&e.retryAfter!==void 0&&(t.retryAfter=e.retryAfter),t}default:return _(n,"review",h(e,"review"))}}function ee(e,n){if(n===void 0)return!1;let t=f(n).find(i=>i.id===e.id);return t!==void 0&&t.attempts.used===e.attempts.used}function ne(e,n){let t=w(e.sessionId),i=f(e).find(s=>X.has(s.checkType)&&s.state==="input_required"&&s.reason!==void 0);if(i?.reason==="mobile_required")return b(t,"mobile_required");if(i?.reason!==void 0){let s=n.autoRetry&&T(i)>0&&($.has(i.reason)||ee(i,n.previous)),c={sessionId:t,status:s?"retry":"rejected",reason:i.reason,attemptsRemaining:T(i)};return i.retakeHint!==void 0&&(c.retakeHint=i.retakeHint),c}let o=x(e);return o===void 0&&f(e).some(s=>s.state==="review")?_(t,"review",h(e,"review")):o?.checkType==="portrait_icao"?b(t,"portrait_required"):b(t)}function h(e,n){let t=f(e).filter(i=>i.state===n&&i.reason!==void 0);return t[n==="failed"?t.length-1:0]?.reason}function F(e,n,t,i,o){return e.presignCapture!==void 0?e.presignCapture(n,t,i,o):e.presign(n,t,i)}function K(e){return{engine:e?.engine,durationMs:e?.clipMs}}var te=["video/webm","video/mp4"],N="image/jpeg",ie=2,oe=1e3,se=1e4,re=3,ae=10,ce=30,de=3,ue=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),le=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order","identity_confirm_required","check_not_active","step_not_on_path"]),S=class extends Error{constructor(){super("verification destroyed"),this.name="FlowCancelledError"}};function fe(e){let n=y(e);return g(e,"portrait_icao")?.state!=="pending"&&(n!==void 0?E(n):e.capture?.livePhoto?.oneCapture===!0)}var R=class extends Error{constructor(n){super(n),this.name="AttestationError"}};async function q(e,n,t={}){let i=e.uuid(),o=!1,s=!1,c=0,d=0;for(;;)try{return await n(e.client,i)}catch(r){if(r instanceof R){if(s)throw r;s=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(!(r instanceof v))throw r;if(r.code==="consent_required"&&!o){o=!0,await e.ensureConsent({force:!0}),i=e.uuid();continue}if(r.code==="attestation_invalid"&&!s){s=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(r.code==="inference_unavailable"&&d<re){d+=1;let a=Math.min(r.retryAfterSeconds??ae,ce);e.onBusy?.({attempt:d,retryAfterSeconds:a}),await e.sleep(a*1e3),t.onAttestationInvalid?.(),i=e.uuid();continue}if(ue.has(r.code)&&c<ie){c+=1;let a=r.retryAfterSeconds!==void 0?r.retryAfterSeconds*1e3:void 0;await e.sleep(a!==void 0?Math.min(a,se):oe);continue}throw r}}var pe=new Set(["passed","review","processing","skipped"]);async function Ve(e){let{artifacts:n}=e,t=n.clip,i=M(n.clipMime??"");if(n.degraded==="NO_RECORDER"||t===void 0||!te.includes(i))return{kind:"unavailable",reason:"no_recorder"};e.client.armCapture?.(2);let o=me(e,n.keyframe),s=_e(e,t,i,o),c=he(e,o),d=!1,r=new Set,a=!0,m=0;for(;;){if(e.isCancelled())return{kind:"cancelled"};let l=e.getView();if(O(l))return{kind:"settled"};let k=x(l),V=k?.checkType,C=V==="liveness"&&!d?"liveness":V==="face_match"&&!r.has(k?.id)&&r.size<2&&a?"face_match":null;if(C===null)return{kind:"settled"};if(C==="liveness"&&n.captureChannel==="desktop"&&g(l,"liveness")?.requiresMobile===!0)return{kind:"unavailable",reason:"mobile_required"};try{if(C==="liveness"){d=!0;let u=await s();if(e.isCancelled())return{kind:"cancelled"};L(l,u)&&r.add(y(u)?.id);for(let Y of P(l,u))r.add(Y);await e.applySubmit(u,"liveness");let p=g(e.getView(),"liveness")?.state;a=p===void 0||pe.has(p)}else{r.add(k?.id);let u=await c();if(e.isCancelled())return{kind:"cancelled"};for(let p of P(l,u))r.add(p);await e.applySubmit(u,"face_match")}}catch(u){if(e.isCancelled()||u instanceof S)return{kind:"cancelled"};let p=Se(u);if(p.kind!=="resync"||m>=de)return p;m+=1,await e.refreshView()}}}function me(e,n){let t=null,i=null,o=()=>t!==null?Promise.resolve(t):(i??(i=(async()=>{let s=await F(e.client,"image",N,n.size,K(e.artifacts));return await e.client.uploadToSpaces(s.uploadUrl,n,N),t=(await e.client.completeMedia(s.key)).key,e.onKeyframePromoted?.(t),t})().finally(()=>{i=null})),i);return{ensure:o,attempt:()=>o().catch(()=>null),current:()=>t}}function _e(e,n,t,i){let o=null,s,c=null;return()=>q(e,async(d,r)=>{if(o===null||s===void 0){if(e.isCancelled())throw new S;s===void 0&&!fe(e.getView())&&(s=null),e.onPhase("uploading");let[a,m]=await Promise.all([o!==null?Promise.resolve(o):(async()=>{let l=await F(d,"clip",t,n.size,K(e.artifacts));return await d.uploadToSpaces(l.uploadUrl,n,t),(await d.completeMedia(l.key)).key})(),s!==void 0?Promise.resolve(s===null?null:s.imageKey):i.attempt()]);o=a,s===void 0&&(s=m===null?null:{imageKey:m})}if(c===null)try{c=await e.getAttestation()}catch(a){throw new R(a instanceof Error?a.message:String(a))}return e.onPhase("checking"),d.submitCheck("liveness",{clipKey:o,attestation:c,captureChannel:e.artifacts.captureChannel,capture:ye(e.artifacts),...s!==null?{faceMatch:s}:{}},{idempotencyKey:r})},{onAttestationInvalid:()=>{c=null}})}function he(e,n){return()=>q(e,async(t,i)=>{if(n.current()===null){if(e.isCancelled())throw new S;e.onPhase("uploading")}let o=await n.ensure();return e.onPhase("checking"),t.submitCheck("face_match",{imageKey:o},{idempotencyKey:i})})}function ye(e){let n={width:e.width,height:e.height};for(let t of ge)e[t]!==void 0&&(n[t]=e[t]);return n}var ge=["engine","facingMode","mode","formFactor","clipMs","cameraReadyMs","faceAcquireMs","captureMs","screenRamp","provenance"];function Se(e){if(e instanceof R)return{kind:"unavailable",reason:"attestation"};if(e instanceof v){if(e.code==="attestation_invalid")return{kind:"unavailable",reason:"attestation"};if(e.code==="inference_unavailable")return{kind:"unavailable",reason:"inference_unavailable"};if(e.code==="mobile_required")return{kind:"unavailable",reason:"mobile_required"};if(le.has(e.code))return{kind:"resync"}}return{kind:"unavailable",reason:"network"}}var D=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="InvalidInputError",this.field=n,this.kind=t}},U=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="OtpInputError",this.field=n,this.kind=t}};function Ie(e){let n=e?.capture;return n?.mode==="assisted"||n?.mode==="self"?n.mode:n?.cameraSwitch===!0?"assisted":"self"}export{Ie as a,Re as b,$ as c,z as d,f as e,T as f,W as g,ke as h,E as i,O as j,x as k,g as l,w as m,b as n,Ce as o,F as p,te as q,ie as r,oe as s,re as t,ae as u,R as v,q as w,Ve as x,D as y,U as z};
1
+ import{c as v,d as V}from"./chunk-5Y3UST3W.js";var A=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",sandbox_nni_not_seeded:"sandbox_id_number_not_seeded",missing_nni:"missing_id_number",registry_needs_nni_source:"registry_needs_id_number_source"}),I=new Map(Object.entries(A)),j=new Map(Object.entries(A).map(([e,n])=>[n,e]));function Re(e){return I.get(e)??e}function B(e){let n=I.get(e)??j.get(e);return n===void 0?[e]:[e,n]}function H(e){let n=[];for(let t of e)for(let i of B(t))n.includes(i)||n.push(i);return n}var $=new Set(H(["no_face","media_unreadable","clip_too_short","no_face_source","side_missing","unreadable","registry_unavailable","otp_mismatch","otp_expired","otp_send_failed","document_type_not_accepted","age_unverifiable","nationality_unreadable","liveness_inconclusive","match_inconclusive","document_authenticity","probe_not_from_liveness","capture_back_camera","capture_not_upright","chip_read_failed","chip_access_denied","chip_parse_failed","icao_pose","icao_eyes","icao_mouth","icao_occlusion","icao_lighting","icao_background","icao_resolution","portrait_not_from_liveness","nni_recheck","device_integrity_failed","eid_identifier_invalid","eid_code_invalid","eid_code_expired","eid_unavailable","eid_resend_too_soon"])),z={document:"document_photo",nfc:"document_chip",population_registry:"national_number",national_eid:"national_eid"};function f(e){return e.plan?.steps??[]}function T(e){return Math.max(0,e.attempts.max-e.attempts.used)}function W(e){let n=e.plan?.choice;return n!==void 0&&e.plan?.current===n.nodeId?n:null}function ke(e){let n=W(e);if(n?.kind!=="identity_method")return null;let t=n.options.map(o=>z[o.service]).filter(o=>o!==void 0),i=n.options.find(o=>o.nationalEid)?.nationalEid;return i?{available:!0,selected:null,options:t,nationalEid:i}:{available:!0,selected:null,options:t}}var X=new Set(["liveness","face_match"]);function E(e){return e!==void 0&&(e.state==="pending"||e.state==="input_required")}function O(e){return e.status!=="created"&&e.status!=="in_progress"}function x(e){let n=e.plan?.current,t=n==null?void 0:f(e).find(i=>i.id===n);return E(t)?t:void 0}function g(e,n){return f(e).find(t=>t.checkType===n)}function y(e){let n=f(e),t=n.findIndex(i=>i.checkType==="liveness");return n.find((i,o)=>o>t&&i.checkType==="face_match")}function L(e,n){let t=g(n,"liveness")?.state,i=y(n)?.state;return(y(e)?.state??"pending")==="pending"&&(t==="passed"||t==="review")&&i!==void 0&&i!=="pending"&&i!=="skipped"}function P(e,n){let t=new Map(f(e).map(i=>[i.id,i.state]));return f(n).filter(i=>i.checkType==="face_match"&&(t.get(i.id)??"pending")==="pending"&&i.state!=="pending"&&i.state!=="skipped").map(i=>i.id)}var G=/^[0-9a-f]{24}$/i;function w(e){return G.test(e)?`ses_${e}`:e}function b(e,n){let t=w(e);return n===void 0?{sessionId:t,status:"unavailable"}:{sessionId:t,status:"unavailable",reason:n}}function _(e,n,t){let i=w(e);return t===void 0?{sessionId:i,status:n}:{sessionId:i,status:n,reason:t}}function Ce(e,n){let{sessionId:t}=e;switch(e.status){case"completed":case"failed":case"review_pending":return Q(e,Z(e));case"expired":return b(t);case"created":case"in_progress":break;default:{let i=e.status;throw new Error(`mapSessionResult: unhandled status ${i}`)}}return ne(e,n)}var J=new Set([0,1,2,3]);function Q(e,n){if(J.has(e.level)&&(n.level=e.level),typeof e.assurance=="string"&&e.assurance.length>0&&(n.assurance=e.assurance),typeof e.subjectId=="string"&&e.subjectId.length>0){n.subjectId=e.subjectId;let t=/^([0-9a-f]{24})$/i.exec(e.subjectId)?.[1];t!==void 0&&(n.personId=`per_${t.toLowerCase()}`)}return n}function Z(e){let n=w(e.sessionId);switch(e.status){case"completed":return e.outcome==="approved"?{sessionId:n,status:"approved"}:e.outcome==="review"?_(n,"review",h(e,"review")):_(n,"rejected",h(e,"failed"));case"failed":{let t=_(n,"rejected",e.failureReason??h(e,"failed"));return e.failureReason==="device_cooldown"&&e.retryAfter!==void 0&&(t.retryAfter=e.retryAfter),t}default:return _(n,"review",h(e,"review"))}}function ee(e,n){if(n===void 0)return!1;let t=f(n).find(i=>i.id===e.id);return t!==void 0&&t.attempts.used===e.attempts.used}function ne(e,n){let t=w(e.sessionId),i=f(e).find(s=>X.has(s.checkType)&&s.state==="input_required"&&s.reason!==void 0);if(i?.reason==="mobile_required")return b(t,"mobile_required");if(i?.reason!==void 0){let s=n.autoRetry&&T(i)>0&&($.has(i.reason)||ee(i,n.previous)),c={sessionId:t,status:s?"retry":"rejected",reason:i.reason,attemptsRemaining:T(i)};return i.retakeHint!==void 0&&(c.retakeHint=i.retakeHint),c}let o=x(e);return o===void 0&&f(e).some(s=>s.state==="review")?_(t,"review",h(e,"review")):o?.checkType==="portrait_icao"?b(t,"portrait_required"):b(t)}function h(e,n){let t=f(e).filter(i=>i.state===n&&i.reason!==void 0);return t[n==="failed"?t.length-1:0]?.reason}function F(e,n,t,i,o){return e.presignCapture!==void 0?e.presignCapture(n,t,i,o):e.presign(n,t,i)}function K(e){return{engine:e?.engine,durationMs:e?.clipMs}}var te=["video/webm","video/mp4"],N="image/jpeg",ie=2,oe=1e3,se=1e4,re=3,ae=10,ce=30,de=3,ue=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),le=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order","identity_confirm_required","check_not_active","step_not_on_path"]),S=class extends Error{constructor(){super("verification destroyed"),this.name="FlowCancelledError"}};function fe(e){let n=y(e);return g(e,"portrait_icao")?.state!=="pending"&&(n!==void 0?E(n):e.capture?.livePhoto?.oneCapture===!0)}var R=class extends Error{constructor(n){super(n),this.name="AttestationError"}};async function q(e,n,t={}){let i=e.uuid(),o=!1,s=!1,c=0,d=0;for(;;)try{return await n(e.client,i)}catch(r){if(r instanceof R){if(s)throw r;s=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(!(r instanceof v))throw r;if(r.code==="consent_required"&&!o){o=!0,await e.ensureConsent({force:!0}),i=e.uuid();continue}if(r.code==="attestation_invalid"&&!s){s=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(r.code==="inference_unavailable"&&d<re){d+=1;let a=Math.min(r.retryAfterSeconds??ae,ce);e.onBusy?.({attempt:d,retryAfterSeconds:a}),await e.sleep(a*1e3),t.onAttestationInvalid?.(),i=e.uuid();continue}if(ue.has(r.code)&&c<ie){c+=1;let a=r.retryAfterSeconds!==void 0?r.retryAfterSeconds*1e3:void 0;await e.sleep(a!==void 0?Math.min(a,se):oe);continue}throw r}}var pe=new Set(["passed","review","processing","skipped"]);async function Me(e){let{artifacts:n}=e,t=n.clip,i=V(n.clipMime??"");if(n.degraded==="NO_RECORDER"||t===void 0||!te.includes(i))return{kind:"unavailable",reason:"no_recorder"};e.client.armCapture?.(2);let o=me(e,n.keyframe),s=_e(e,t,i,o),c=he(e,o),d=!1,r=new Set,a=!0,m=0;for(;;){if(e.isCancelled())return{kind:"cancelled"};let l=e.getView();if(O(l))return{kind:"settled"};let k=x(l),M=k?.checkType,C=M==="liveness"&&!d?"liveness":M==="face_match"&&!r.has(k?.id)&&r.size<2&&a?"face_match":null;if(C===null)return{kind:"settled"};if(C==="liveness"&&n.captureChannel==="desktop"&&g(l,"liveness")?.requiresMobile===!0)return{kind:"unavailable",reason:"mobile_required"};try{if(C==="liveness"){d=!0;let u=await s();if(e.isCancelled())return{kind:"cancelled"};L(l,u)&&r.add(y(u)?.id);for(let Y of P(l,u))r.add(Y);await e.applySubmit(u,"liveness");let p=g(e.getView(),"liveness")?.state;a=p===void 0||pe.has(p)}else{r.add(k?.id);let u=await c();if(e.isCancelled())return{kind:"cancelled"};for(let p of P(l,u))r.add(p);await e.applySubmit(u,"face_match")}}catch(u){if(e.isCancelled()||u instanceof S)return{kind:"cancelled"};let p=Se(u);if(p.kind!=="resync"||m>=de)return p;m+=1,await e.refreshView()}}}function me(e,n){let t=null,i=null,o=()=>t!==null?Promise.resolve(t):(i??(i=(async()=>{let s=await F(e.client,"image",N,n.size,K(e.artifacts));return await e.client.uploadToSpaces(s.uploadUrl,n,N),t=(await e.client.completeMedia(s.key)).key,e.onKeyframePromoted?.(t),t})().finally(()=>{i=null})),i);return{ensure:o,attempt:()=>o().catch(()=>null),current:()=>t}}function _e(e,n,t,i){let o=null,s,c=null;return()=>q(e,async(d,r)=>{if(o===null||s===void 0){if(e.isCancelled())throw new S;s===void 0&&!fe(e.getView())&&(s=null),e.onPhase("uploading");let[a,m]=await Promise.all([o!==null?Promise.resolve(o):(async()=>{let l=await F(d,"clip",t,n.size,K(e.artifacts));return await d.uploadToSpaces(l.uploadUrl,n,t),(await d.completeMedia(l.key)).key})(),s!==void 0?Promise.resolve(s===null?null:s.imageKey):i.attempt()]);o=a,s===void 0&&(s=m===null?null:{imageKey:m})}if(c===null)try{c=await e.getAttestation()}catch(a){throw new R(a instanceof Error?a.message:String(a))}return e.onPhase("checking"),d.submitCheck("liveness",{clipKey:o,attestation:c,captureChannel:e.artifacts.captureChannel,capture:ye(e.artifacts),...s!==null?{faceMatch:s}:{}},{idempotencyKey:r})},{onAttestationInvalid:()=>{c=null}})}function he(e,n){return()=>q(e,async(t,i)=>{if(n.current()===null){if(e.isCancelled())throw new S;e.onPhase("uploading")}let o=await n.ensure();return e.onPhase("checking"),t.submitCheck("face_match",{imageKey:o},{idempotencyKey:i})})}function ye(e){let n={width:e.width,height:e.height};for(let t of ge)e[t]!==void 0&&(n[t]=e[t]);return n}var ge=["engine","facingMode","mode","formFactor","clipMs","cameraReadyMs","faceAcquireMs","captureMs","screenRamp","provenance"];function Se(e){if(e instanceof R)return{kind:"unavailable",reason:"attestation"};if(e instanceof v){if(e.code==="attestation_invalid")return{kind:"unavailable",reason:"attestation"};if(e.code==="inference_unavailable")return{kind:"unavailable",reason:"inference_unavailable"};if(e.code==="mobile_required")return{kind:"unavailable",reason:"mobile_required"};if(le.has(e.code))return{kind:"resync"}}return{kind:"unavailable",reason:"network"}}var D=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="InvalidInputError",this.field=n,this.kind=t}},U=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="OtpInputError",this.field=n,this.kind=t}};function Ie(e){let n=e?.capture,t=n?.mode;return t==="assisted"||t==="self"||t==="choice"?t:n?.cameraSwitch===!0?"assisted":"self"}function He(e,n){return e==="choice"?n??"self":e}export{Ie as a,He as b,Re as c,$ as d,z as e,f,T as g,W as h,ke as i,E as j,O as k,x as l,g as m,w as n,b as o,Ce as p,F as q,te as r,ie as s,oe as t,re as u,ae as v,R as w,q as x,Me as y,D as z,U as A};
@@ -0,0 +1 @@
1
+ import{a as Z,d as j,e as J}from"./chunk-GT2ZLGF7.js";import{w as Q}from"./chunk-ZPXL26BF.js";import{c as q}from"./chunk-FUHDOEBP.js";import{f as G,l as N}from"./chunk-CQ7SKLMC.js";import{a as $,f as v}from"./chunk-OKWG3PVH.js";var se=12e4,X=13e4,oe=3e3,ie=1200,P=Symbol.for("@sekyro/web.preload.v1");function p(){let e=globalThis;return e[P]??(e[P]=new Map),e[P]}function g(e){let t=(e??$).replace(/\/+$/,"");return t===""?"/":t}function Y(e){let t=p(),r=t.get(e);return r===void 0&&(r={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},t.set(e,r)),r}function A(e,t){if(e.status!==t){e.status=t;for(let r of[...e.listeners])r(t)}}var T=e=>v({preferred:["blaze"],v3AssetBaseUrl:e,blazeInitTimeoutMs:se}),x=T;function Se(e){x=e??T}function Ce(){for(let e of p().values())e.detector?.destroy();p().clear(),x=T}function ae(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function ce(){return navigator.connection?.saveData===!0}function de(e){let t=window;if(typeof t.requestIdleCallback=="function"){let s=t.requestIdleCallback(e,{timeout:oe});return()=>t.cancelIdleCallback?.(s)}let r=setTimeout(e,ie);return()=>clearTimeout(r)}function ue(e,t){let r,s=new Promise(o=>{r=o}),u=!1,f=()=>{},d={promise:s,settle:o=>{u||(u=!0,f(),e.scheduled===d&&(e.scheduled=null),r(o))}};return e.scheduled=d,f=de(()=>{u||d.settle(I(e,t))}),s}function I(e,t){if((e.status==="loading"||e.status==="ready")&&e.promise!==null)return e.promise;A(e,"loading");let r=new Promise(o=>o(x(t)));e.detectorPromise=r;let s,u=new Promise((o,h)=>{s=setTimeout(()=>{r.then(S=>S.destroy(),()=>{}),h(new Error(`detector preload exceeded ${X} ms`))},X)}),d=Promise.race([r,u]).then(o=>e.detectorPromise!==r?(o.destroy(),e.status):(e.detector=o,A(e,"ready"),"ready"),o=>(e.detectorPromise===r&&(e.detectorPromise=null,e.detector=null,A(e,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",o)),e.status)).finally(()=>clearTimeout(s));return e.promise=d,e.scheduled?.settle(d),d}function Le(e={}){if(!ae())return Promise.resolve("idle");let t=g(e.assetBaseUrl),r=Y(t);return e.respectSaveData===!0&&ce()?Promise.resolve(r.status):(r.status==="loading"||r.status==="ready")&&r.promise!==null?r.promise:e.idle===!0?r.scheduled?.promise??ue(r,t):I(r,t)}function Ee(e){return p().get(g(e))?.status??"idle"}function ye(e,t){let r=Y(g(t));return r.listeners.add(e),()=>{r.listeners.delete(e)}}function be(e){let t=p().get(g(e));t!==void 0&&(t.scheduled?.settle("idle"),t.detector?.destroy(),t.detector=null,t.detectorPromise=null,t.promise=null,A(t,"idle"))}function le(e){return{get tier(){return e.tier},get fallbackReason(){return e.fallbackReason},detect:(...t)=>e.detect(...t),destroy:()=>{}}}function ee(e){let t=g(e),r=p().get(t);if(!(r===void 0||r.detector===null&&r.detectorPromise===null&&r.scheduled===null))return async()=>{r.scheduled!==null&&I(r,t);let s=r.promise;for(;r.detector===null&&s!==null&&(await s,r.promise!==s);)s=r.promise;return r.detector!==null?le(r.detector):v({v3AssetBaseUrl:t})}}function fe(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";default:return null}}function pe(e){switch(e){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";default:return e}}function te(e){switch(e){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return e;default:{let t=e;return"generic"}}}function me(e,t,r){if(r===void 0)return{kind:te(e),retryable:t};let s=N(r.name);return{kind:te(e),retryable:t,detail:{...s!==void 0?{name:s}:{},phase:r.phase,engineKind:e}}}function ve(e,t={},r,s=()=>"self",u=()=>{}){let f=t.now??(()=>performance.now()),d=t.canChooseFacing??j,o="user",h=!1,S=n=>(n==="environment"&&!h&&(h=!0,console.warn('[@sekyro/web] facing "environment" ignored: this capture is a self capture (the person films themselves), which uses the front camera only. The back camera is for assisted capture, set in the flow.')),"user"),D=!1,m=s(),c=Z(),H=!G(),U=t.engineOptions,re=U?.createDetector===void 0&&U?.createWorker===void 0?{createDetector:()=>{let n=ee(e.assetBaseUrl);return n!==void 0?n():v({v3AssetBaseUrl:e.assetBaseUrl})}}:{},B={video:e.video,mode:H?"photo":"clip",rankKeyframes:r,facingMode:void 0,v3AssetBaseUrl:e.assetBaseUrl,screenRamp:()=>m==="self"&&c.count("ramp")>0?u():void 0,...t.engineOptions??{},...re},i=t.createEngine?.(B)??new Q(B),C="idle",L=null,E=0,k=!1,M="full",y=null,b=null,_=0,F=0,K=()=>{e.video.videoWidth>0&&e.video.videoHeight>0&&(_=e.video.videoWidth,F=e.video.videoHeight)},V=J({enabled:e.keepScreenAwake!==!1}),z=n=>{C=n,V.setActive(n==="starting"||n==="gating"||n==="recording"),c.emit("state",n)},O=()=>c.emit("gate",{progress:E,hint:L,faceDetected:k}),W=()=>{let n=i.animations??"full";n!==M&&(M=n,c.emit("profile",{animations:M}))},ne=[i.on("statechange",({state:n})=>{let a=pe(n);a==="starting"&&C!=="starting"&&(L=null,E=0,k=!1,y=null,b=null,_=0,F=0),z(a),W(),a==="recording"&&(K(),y=f(),L="hold",E=1,O())}),i.on("checks",n=>{K(),E=n.progress,k=n.factors.presence>0,O(),W()}),i.on("guidance",({key:n})=>{L=fe(n),O()}),i.on("frozen",({previewDataUrl:n})=>{b=f(),c.emit("frozen",{previewDataUrl:n})}),i.on("ramp",n=>c.emit("ramp",n)),i.on("artifacts",n=>{let a=q(),l=y!==null&&b!==null?Math.max(0,Math.round(b-y)):void 0;c.emit("captured",{keyframe:n.keyframe,...n.clip!==void 0?{clip:n.clip}:{},...n.clipMimeType!==void 0?{clipMime:n.clipMimeType}:{},width:e.video.videoWidth||_,height:e.video.videoHeight||F,...l!==void 0?{clipMs:l}:{},captureChannel:a==="desktop"?"desktop":"mobile",formFactor:a,...H?{degraded:"NO_RECORDER"}:{},engine:"v3",facingMode:i.facingMode,mode:m,...n.timing,...n.screenRamp!==void 0?{screenRamp:n.screenRamp}:{},...n.provenance!==void 0?{provenance:n.provenance}:{}})}),i.on("error",({kind:n,retryable:a,detail:l})=>{c.emit("error",me(n,a,l))})];return{handle:{get state(){return C},get captureMode(){return s()},get facingMode(){return i.facingMode??o},on:(n,a)=>c.on(n,a),start:n=>{if(m=s(),m==="self")return S(e.facing),S(n?.facing),D=!0,o="user",i.start({facingMode:"user"});let a=!D;D=!0;let l=n?.facing??(a?e.facing:void 0),R=w=>(o=w,i.start({facingMode:w}));return l!==void 0?R(l):a?d().then(w=>R(w?"environment":"user"),()=>R("user")):i.start({})},retry:()=>i.retry(),switchCamera:()=>s()!=="assisted"?!1:(m="assisted",o=o==="user"?"environment":"user",i.switchCamera(),!0),destroy:()=>{for(let n of ne)n();V.setActive(!1),i.destroy(),c.clear()}},setFlowState:n=>{C!==n&&z(n)}}}function Te(e){return ve(e).handle}export{se as a,X as b,Se as c,Ce as d,Le as e,Ee as f,ye as g,be as h,ee as i,fe as j,pe as k,te as l,me as m,ve as n,Te as o};
@@ -0,0 +1 @@
1
+ var m=["video/mp4;codecs=avc1.42E01E,mp4a.40.2","video/mp4;codecs=avc1.42E01E","video/mp4","video/webm;codecs=vp9,opus","video/webm;codecs=vp9","video/webm;codecs=vp8,opus","video/webm;codecs=vp8","video/webm"];function S(){let e=globalThis.MediaRecorder;return!e||typeof e.isTypeSupported!="function"?"":m.find(r=>e.isTypeSupported(r))??""}var l="video/webm";function f(e){if(e instanceof TypeError)return"insecure";switch(e?.name??""){case"NotAllowedError":case"PermissionDeniedError":return"permission";case"NotFoundError":case"DevicesNotFoundError":return"notfound";case"NotReadableError":case"TrackStartError":return"inuse";case"OverconstrainedError":case"ConstraintNotSatisfiedError":return"overconstrained";default:return"generic"}}function b(){let e=globalThis;if(typeof e.window<"u"&&e.window.isSecureContext===!1)return"INSECURE_CONTEXT";let r=e.navigator?.mediaDevices;return!r||typeof r.getUserMedia!="function"?"UNSUPPORTED":"OK"}function v(){let e=globalThis.MediaRecorder;return typeof e<"u"&&typeof e.isTypeSupported=="function"}var E=8*1024*1024;function T(e){return e.size>E}function u(e){let r=(e||"").toLowerCase();return r.startsWith("image/jpeg")?"jpg":r.startsWith("video/mp4")?"mp4":(r.startsWith("video/webm"),"webm")}function k(e){let{token:r,clip:n,keyframe:o}=e,c=e.ts??Date.now(),p=n.type||l,d=o.type||"image/jpeg",t=new FormData;return t.append("token",r),t.append("clip",new File([n],`liveness-${c}.${u(p)}`,{type:p})),t.append("keyframe",new File([o],`keyframe-${c}.${u(d)}`,{type:d})),t}var w=40;function y(e){if(e===null||typeof e!="object"&&typeof e!="function")return;let r;try{r=e.name}catch{return}return g(r)}function g(e){if(typeof e!="string")return;let r=e.replace(/[^A-Za-z]/g,"").slice(0,w);return r===""?void 0:r}function C(e){let r=f(e);if(r!=="generic")return r;switch(y(e)){case"AbortError":return"inuse";case"SecurityError":return"permission";default:return r}}var i=Symbol.for("sekyro.web.cameraStreams"),a=globalThis,s=a[i]??(a[i]=new Set);function N(e){try{s.add(e)}catch{}}function R(e){let r=0;for(let n of[...s])if(n!==e){s.delete(n);try{for(let o of n.getTracks())o.readyState!=="ended"&&(o.stop(),r+=1)}catch{}}return r}export{m as a,S as b,l as c,f as d,b as e,v as f,E as g,T as h,u as i,k as j,y as k,g as l,C as m,N as n,R as o};
@@ -1 +1 @@
1
- var c="0.1.0-rc.18";var d="sekyro.did",l;function g(){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 f(){try{let t=localStorage.getItem(d);if(t)return t;let e=g();return e!==void 0&&localStorage.setItem(d,e),e}catch{return l??(l=g()),l}}async function m(){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]),n=await t.digest("SHA-256",new TextEncoder().encode(r));return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("").slice(0,32)}function p(t){let e=new TextEncoder().encode(t),r="";for(let n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function y(t){let e,r;return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(n){n&&(e=n.slice(0,128))},async deviceHeader(){try{r??(r=m().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let i=await r,s=f(),u={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...s?[{kind:"web_local",value:s.slice(0,128)}]:[],...i?[{kind:"web_fp",value:i}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...e?{cameraLabel:e}:{},...n.length?{signals:n}:{}};return p(JSON.stringify(u))}catch{return}}}}var o=Symbol.for("sekyro.web.clientContext"),a=globalThis,b=a[o]??(a[o]=y({sdk:`@sekyro/web@${c}`}));function C(t){try{let e=t.getVideoTracks?.()[0];e&&b.noteCameraLabel(e.label)}catch{}}export{c as a,b,C as c};
1
+ var c="0.1.0-rc.19";var d="sekyro.did",l;function g(){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 f(){try{let t=localStorage.getItem(d);if(t)return t;let e=g();return e!==void 0&&localStorage.setItem(d,e),e}catch{return l??(l=g()),l}}async function m(){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]),n=await t.digest("SHA-256",new TextEncoder().encode(r));return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("").slice(0,32)}function p(t){let e=new TextEncoder().encode(t),r="";for(let n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function y(t){let e,r;return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(n){n&&(e=n.slice(0,128))},async deviceHeader(){try{r??(r=m().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let i=await r,s=f(),u={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...s?[{kind:"web_local",value:s.slice(0,128)}]:[],...i?[{kind:"web_fp",value:i}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...e?{cameraLabel:e}:{},...n.length?{signals:n}:{}};return p(JSON.stringify(u))}catch{return}}}}var o=Symbol.for("sekyro.web.clientContext"),a=globalThis,b=a[o]??(a[o]=y({sdk:`@sekyro/web@${c}`}));function C(t){try{let e=t.getVideoTracks?.()[0];e&&b.noteCameraLabel(e.label)}catch{}}export{c as a,b,C as c};
@@ -0,0 +1 @@
1
+ import{a as z,b as xe,c as ve,e as V,f as D,g as B,h as Ie,i as E,j as F,k as b,l as G,m as R,n as ee,o as w,p as H,x as Ae,y as we}from"./chunk-64V55KD7.js";import{n as Pe}from"./chunk-6K4D3U6Q.js";import{a as be}from"./chunk-GT2ZLGF7.js";import{c as ke,d as j}from"./chunk-FUHDOEBP.js";import{c as X,f as Re,g as K}from"./chunk-5Y3UST3W.js";function q(e){return e.idNumberBound??e.nniBound}function N(e){return e===void 0?void 0:e.idNumberFromDocument??e.nniFromDocument}function Oe(e){let t=e.idNumberMasked??e.nniMasked;return typeof t=="string"&&t!==""?t:void 0}var Xe="https://api.sekyro.ai",ze=5e3,et=1500,tt=10;function nt(e){return new Promise(t=>setTimeout(t,e))}function it(){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 o=0;o<16;o+=1)t[o]=Math.floor(Math.random()*256);t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let i=[...t].map(o=>o.toString(16).padStart(2,"0")).join("");return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}function Kt(e){return ot(e,{})}function ot(e,t){let i=e.apiOrigin??Xe,o=e.autoRetry??!0,r=e.rearm??"auto",s=t.client??new Re({apiOrigin:i,sessionToken:e.clientToken,fetch:e.fetch}),u=t.sleep??nt,a=t.uuid??it,p=t.getTurnstileToken??((n,c)=>import("./turnstile-FATNZ4AG.js").then(l=>l.executeTurnstile(n,c))),S=be(),h=null,m=null,d=!1,P=new AbortController,f=null,Y=null,L=null,re=()=>xe(z(f),L),x=n=>{f=n,S.emit("view",n),h?.onView(n)},_=()=>f!==null?Promise.resolve(f):(Y??(Y=s.getSession().then(n=>(x(n),n)).finally(()=>{Y=null})),Y),v=async()=>{let n=await s.getSession();return x(n),n},Z=async(n,c)=>{n.plan!==void 0?x(n):await v()},W=null,se=async n=>{let c=await _();if(!n&&c.consentRecorded)return;let l=await s.recordConsent(e.locale);l.plan!==void 0?x(l):f!==null&&x({...f,consentRecorded:!0})},O=n=>n?.force===!0?se(!0):(W??(W=se(!1).finally(()=>{W=null})),W),$={client:s,ensureConsent:n=>O(n),sleep:u,uuid:a,onBusy:n=>{d||S.emit("busy",n)}},ae=!1,ce=null,J=n=>{if(n.status==="approved"||n.status==="rejected"||n.status==="review"){if(ae)return;ae=!0}ce=JSON.stringify(n),S.emit("result",n)},Ue=n=>{ce!==JSON.stringify(n)&&J(n)},ue=async n=>{let c=f;n&&(c=await v().catch(()=>f));let l=c===null?null:E(c);return l!==null&&!d&&S.emit("method",l),l!==null},de=null,le=!1,pe=!1,fe=()=>Ae($,(n,c)=>n.submitCheck("population_registry",{},{idempotencyKey:c})),me=n=>q(n)===!0||N(R(n,"population_registry"))===!0,Be=async()=>{try{let n=await _();if(b(n)||E(n)!==null||G(n)?.checkType!=="population_registry")return;if(!me(n)&&N(R(n,"population_registry"))===void 0&&(n=await v()),!me(n)){pe=!0;return}await O(),await Z(await fe(),"population_registry");let c=f===null?void 0:R(f,"population_registry");if(c?.state==="input_required"&&c.reason==="registry_unavailable"&&B(c)>0){if(await u(ze),d)return;await Z(await fe(),"population_registry")}}catch(n){if(n instanceof X&&(n.code==="check_not_active"||n.code==="step_not_on_path")){await v().catch(()=>{});return}le=!0;return}f!==null&&b(f)&&J(H(f,{autoRetry:o}))},he=()=>(de??(de=Be()),de),Fe=async()=>{let c=(await _()).turnstileSiteKey;return c===null?{sandbox:!0}:{channel:"hosted_web",siteKey:c,turnstileToken:await p(c,{signal:P.signal})}},k=null,Se=Promise.resolve(),T=0,Ge=async()=>{let n=await _();for(let c=0;c<tt&&!d&&!b(n)&&G(n)===void 0&&D(n).some(l=>l.state==="processing")&&(await u(et),!d);c+=1)n=await v();return n},Ke=async(n,c,l)=>{let{capture:g}=n,C=()=>d,U=()=>n.alive&&n.attempt===l,Ce=y=>{U()&&g.setFlowState(y)},A=y=>{if(!C()&&(J(y),!!U())){if(y.status==="retry"&&r==="auto"){g.handle.retry();return}g.setFlowState("done")}};if(c.degraded==="NO_RECORDER"){let y=f?.sessionId??(await _().catch(()=>null))?.sessionId??"";A(w(y,"no_recorder"));return}Ce("uploading");try{if(await he(),C())return;let y=await _(),_e;if(!b(y)&&E(y)!==null){await ue(!1),A(w(y.sessionId,"method_required"));return}if(!b(y)){if(G(y)?.checkType==="population_registry"){A(w(y.sessionId,pe?"nni_unbound":le?"network":"registry_unavailable"));return}if(await O(),C())return;_e=f??y;let Q=await we({...$,artifacts:c,getAttestation:Fe,getView:()=>f??y,refreshView:v,applySubmit:Z,onPhase:Ce,isCancelled:C,onKeyframePromoted:je=>{m=je}});if(C())return;if(Q.kind==="unavailable"){A(w(y.sessionId,Q.reason));return}if(Q.kind==="resync"&&await v(),f!==null&&E(f)!==null){await ue(!1),A(w(y.sessionId,"method_required"));return}y=await Ge()}A(H(y,{autoRetry:o,previous:_e}))}catch{if(C())return;A(w(f?.sessionId??"","network"))}},qe=(n,c)=>{let l=n.attempt;T>0&&n.alive&&n.capture.setFlowState("uploading"),T+=1,Se=Se.then(()=>Ke(n,c,l)).finally(()=>{T-=1,T===0&&h?.onChainIdle()}).catch(()=>{})},ye=n=>{k?.capture.handle.destroy(),k!==null&&(k.alive=!1);let c=Pe(n,h?.captureInternals?.(n)??t.capture,()=>f?.capture?.liveness?.keyframe?.rank===!0,re,()=>f?.capture?.liveness?.screenRamp),l={capture:c,alive:!0,attempt:0};k=l,c.handle.on("state",C=>{C==="starting"&&(l.attempt+=1)}),c.handle.on("captured",C=>{Promise.resolve().then(()=>qe(l,C))});let g=c.handle;return{get state(){return g.state},get captureMode(){return g.captureMode},get facingMode(){return g.facingMode},on:(C,U)=>g.on(C,U),start:async C=>{if(f===null&&await _().catch(()=>{}),!!l.alive)return g.start(C)},retry:()=>g.retry(),switchCamera:()=>g.switchCamera(),destroy:()=>{l.alive=!1,k===l&&(k=null),g.destroy()}}},Ye=async()=>{if(d)return null;try{let n=await _();return d?null:E(n)}catch{return null}},Ze=async()=>{if(d)return"self";try{let n=await _();if(d)return"self";let c=z(n);return c==="choice"?L??c:c}catch{return"self"}},We=async()=>{if(d)return!1;try{let n=await _();if(d||b(n))return!1;let c=R(n,"liveness");return F(c)&&c?.requiresMobile===!0&&!j()}catch{return!1}},$e=async()=>{if(d)return!1;try{let n=await _();return!d&&n.returning===!0}catch{return!1}},Je=async n=>{let c=(await _()).plan?.choice,l=c?.options.find(C=>V[C.service]===n);if(!l)throw new RangeError(`method ${String(n)} is not offered`);let g=await s.choose(c.nodeId,l.id);d||x(g)},ge=null,Qe=()=>(ge??(ge=import("./plan-runner-WEUIMCYU.js").then(n=>{let c=n.createPlanRunner({runtime:$,currentView:()=>f,cameraMode:re,ensureView:_,refreshView:v,ensureConsent:()=>O(),liveness:ye,chainBusy:()=>T>0,destroyed:()=>d,sleep:u,isMobile:j,now:t.now??Date.now,keptFaceKey:()=>m,setView:x,baseCapture:t.capture,emitStep:l=>{d||S.emit("step",l)},emitResult:Ue,documentInternals:t.document,portraitInternals:t.portrait,livePhotoInternals:t.livePhoto});return h=c,c})),ge);return{consent:()=>O(),startRegistry:he,methodChoice:Ye,selectMethod:Je,reportCameraUnavailable:async n=>{await O();let c=s.reportCameraUnavailable;if(c===void 0)throw new TypeError("this client cannot report a missing camera");let l=await c.call(s,n).catch(g=>{if(g instanceof X&&g.code==="check_out_of_order")return s.getSession();throw g});d||x(l)},reportCaptureIssue:n=>{if(d)return;let c=s.reportCaptureIssue;if(c===void 0)return;let l=n.formFactor;try{l??(l=ke())}catch{}c.call(s,{...n,...l!==void 0?{formFactor:l}:{}}).catch(()=>{})},mobileRequired:We,captureMode:Ze,chooseCaptureMode:n=>{L=n},get captureChoice(){return L},returning:$e,liveness:ye,run:async()=>{if(d)throw new Error("verification destroyed");return(await Qe()).run()},currentStep:()=>h?.current()??null,voiceClips:async()=>{if(d)return null;try{let n=await _();return d?null:n.voice??null}catch{return null}},on:(n,c)=>S.on(n,c),destroy:()=>{d=!0,P.abort(),h?.destroy(),k!==null&&(k.alive=!1,k.capture.handle.destroy(),k=null),S.clear()}}}var Ee=["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 rt=["carte_identite","passport","residence_permit"];function st(e,t){let i=e.byIssuer?.[t]??e.default;return rt.filter(o=>i==="*"||i.includes(o))}function Wt(e,t=Ee){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(o=>st(e,o).length>0).sort()}function Me(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}function $t(e){return/^[A-Z]{2}$/.test(e)?String.fromCodePoint(...[...e].map(t=>127462+t.charCodeAt(0)-65)):""}var tn=["national_number","document_photo","national_eid"],at=new Set(["phone_otp","email_otp","national_eid","document","nfc","population_registry","supplied_identity","summary_confirm","liveness","face_match","aml_screening","face_dedup","age_estimation"]),ct=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),ne=["document","population_registry","national_eid"],ie=["phone_otp","email_otp"],De={identity_method:ne,contact:ie},ut=["population_registry","document"],He="platform_unsupported",dt=new Set(["prefilled","user_entered","prefilled_or_entered"]),lt={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"};function I(e){return e.section??lt[e.checkType]??null}function pt(e,t){let i=e.plan?.choice;if(i===void 0||i.locked)return;let o=i.options.find(r=>r.id!==i.selected&&r.available!==!1&&t.includes(r.service));return o===void 0?void 0:{nodeId:i.nodeId,option:o}}function oe(e){let t=e.plan,i=t?.choice;if(t===void 0||i===void 0||i.locked||t.current===null||t.current===i.nodeId||b(e))return null;let o=De[i.kind]??[...ne,...ie],r=i.options.flatMap(a=>a.available===!1||!o.includes(a.service)?[]:[a.nationalEid!=null?{id:a.id,service:a.service,nationalEid:a.nationalEid}:{id:a.id,service:a.service}]),s=t.steps.find(a=>a.id===t.current)?.service,u=i.selected??r.find(a=>a.service===s)?.id??null;return r.some(a=>a.id!==u)?{nodeId:i.nodeId,kind:i.kind,current:u,options:r}:null}function Ne(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function ft(e){let t=(e.plan?.sections??[]).map(r=>({id:r.id,state:r.state})),i={sessionId:ee(e.sessionId),orgName:e.orgName,returning:e.returning===!0,consentRecorded:e.consentRecorded,expiresAt:e.expiresAt,sections:t.map(r=>r.id),progress:t,purpose:e.purpose??"identity"};e.branding!==void 0&&(i.branding=e.branding),e.cameraUnavailableHandled===!0&&(i.cameraUnavailableHandled=!0);let o=oe(e);return o!==null&&(i.switchable=o),i}function mt(e){let t={attemptsRemaining:B(e),attemptsExhausted:e.attemptsExhausted===!0};return e.reason!==void 0&&(t.reason=e.reason),e.retakeHint!==void 0&&(t.retakeHint=e.retakeHint),t}var Le={phone_otp:"phone",email_otp:"email"};function ht(e,t){let i=pt(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return i===void 0?void 0:Le[i.option.service]}function St(e,t,i,o){let r=t.checkType==="email_otp",s=(r?t.emailOtp:t.otp)??{},u=r?t.emailOtp?.emailSource:t.otp?.numberSource,a=u!==void 0&&dt.has(u)?u:r?"prefilled_or_entered":"user_entered",p=typeof s.sentToMasked=="string"&&s.sentToMasked.length>0,S=ht(e,r?"email_otp":"phone_otp"),h={key:t.checkType,context:i,section:I(t),phase:p?"verify":"send",canSwitch:S!==void 0,...o},m=r?{kind:"email_otp",...h,emailSource:a,needsEmail:a!=="prefilled"}:{kind:"phone_otp",...h,numberSource:a,needsPhone:a!=="prefilled",channels:(t.otp?.channels??[]).filter(d=>d==="whatsapp"||d==="sms")};if(S!==void 0&&(m.switchChannel=S),p&&(m.sentToMasked=s.sentToMasked),!r&&t.otp?.channel!==void 0&&(m.channel=t.otp.channel),!r&&Array.isArray(t.phoneCountries)&&(m.phoneCountries=t.phoneCountries.filter(d=>typeof d=="string"&&/^[A-Z]{2}$/.test(d))),!r&&Array.isArray(t.phoneRules)){let d=m.phoneCountries??[];m.phoneRules=t.phoneRules.flatMap(P=>{let f=Ct(P);return f!==void 0&&d.includes(f.code)?[f]:[]})}return!r&&t.phoneInternational===!0&&(m.phoneInternational=!0),s.expiresAt!==void 0&&(m.codeExpiresAt=s.expiresAt),s.resendAvailableAt!==void 0&&(m.resendAvailableAt=s.resendAvailableAt),m}var yt=/^[\d[\]\-|()?:^]{1,64}$/;function gt(e){try{return typeof e=="string"&&yt.test(e)&&new RegExp(e)!==null}catch{return!1}}var Te=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function Ct(e){let{code:t,dial:i,trunk:o,lengths:r,formats:s}=e??{};if(typeof t!="string"||typeof i!="string"||!/^\d{1,3}$/.test(i)||o!==void 0&&(typeof o!="string"||!/^\d{1,3}$/.test(o))||!Array.isArray(r)||r.length===0||!r.every(Te))return;let u={code:t,dial:i,lengths:[...r].sort((a,p)=>a-p)};if(o!==void 0&&(u.trunk=o),s!==void 0){if(!(Array.isArray(s)&&s.length<=8&&s.every(p=>gt(p?.leading)&&Array.isArray(p.groups)&&p.groups.every(Te)&&r.includes(p.groups.reduce((S,h)=>S+h,0)))))return;u.formats=s.map(p=>({leading:p.leading,groups:[...p.groups]}))}return u}function _t(e,t,i,o){let r=q(e)===!0?"bound":N(t)===!0?"document":"typed",s=r==="typed"&&t.state==="input_required"&&t.reason!==void 0&&ve(t.reason)==="id_number_recheck",u=Ne(oe(e)),a=!o.attemptsExhausted&&u.length===1&&u[0]?.service==="document";return{kind:"registry",key:"registry",context:i,section:I(t),state:t.state==="input_required"?"input_required":"pending",source:r,recheck:s,canUseDocument:a,...o}}function kt(e,t,i,o){let r=[...t.acceptedSides??[]],s={kind:"document",key:"document",context:i,section:I(t),side:r.includes("recto")?"verso":"recto",acceptedSides:r,documents:Me(e),...o};return bt(e)&&(s.ageStepUp=!0),s}function bt(e){let t=D(e).find(o=>o.checkType==="age_estimation"),i=t?.reason;return t?.state==="failed"&&(i==="age_uncertain"||i==="age_unavailable")}function Pt(e){let t=R(e,"liveness");return t?.state==="passed"||t?.state==="review"}function Ve(e,t,i,o,r){let s=t.icao?.report;return{kind:"portrait",key:`portrait:${r}`,context:i,section:I(t),phase:r,report:Array.isArray(s)?s:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:K(e),retakeOnly:r==="capture"&&t.state==="input_required"&&e.capture?.livePhoto?.oneCapture===!0&&Pt(e),...o}}var te={minLongSidePx:1280,jpegQuality:.95};function Rt(e,t){let i=e.capture?.livePhoto;if(i?.oneCapture!==!0)return null;let o=R(e,"portrait_icao"),r=i.still??te;return{icao:t==="liveness"&&K(e)!==null&&o!==void 0&&o.state==="pending"&&o.reason===void 0,still:{minLongSidePx:r.minLongSidePx??te.minLongSidePx,jpegQuality:r.jpegQuality??te.jpegQuality}}}function xt(e,t,i,o){let r=t.eid,s=I(t);if(r===void 0||r.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:i,section:s,checkType:"eid_auth",reason:"update_required"};let u=Ne(oe(e)),a=u.length===1&&ut.includes(u[0]?.service??"")?u[0]:void 0,p=a===void 0?void 0:V[a.service],S=p!==void 0,h={kind:"eid",key:"eid",context:i,section:s,provider:r.provider,providerName:r.providerName,country:r.country,challenge:"app_code",phase:r.awaiting==="code"?"code":"identifier",identifierBound:r.identifierBound===!0,canUseCamera:S,afterPass:r.afterPass==="continue"?"continue":"end",...o};return S&&(h.cameraMethod=p),r.expiresAt!==void 0&&(h.codeExpiresAt=r.expiresAt),r.resendAvailableAt!==void 0&&(h.resendAvailableAt=r.resendAvailableAt),r.resendsRemaining!==void 0&&(h.resendsRemaining=r.resendsRemaining),r.codeAttemptsRemaining!==void 0&&(h.codeAttemptsRemaining=r.codeAttemptsRemaining),h}function vt(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let i=R(e,"portrait_icao");return i!==void 0&&(i.state==="passed"||i.state==="review")?i:null}function It(e){return D(e).filter(t=>t.state==="failed").pop()?.attemptsExhausted===!0}function At(e,t){let i=e.failureReason,o;i===He?o="platform_unsupported":e.status==="expired"?o="expired":e.status==="review_pending"?o="review":e.status==="completed"&&e.outcome==="approved"?o="approved":e.status==="completed"&&e.outcome==="review"?o="review":i==="device_cooldown"?o="cooldown":i!==void 0?o="policy_stop":It(e)?o="attempts_exhausted":o="rejected";let r=o==="platform_unsupported"?{sessionId:ee(e.sessionId),status:"unavailable"}:H(e,{autoRetry:!1}),s={kind:"result",key:"result",context:t,section:null,display:o,result:r};return i!==void 0&&(s.failureReason=i),e.retryAfter!==void 0&&(s.retryAfter=e.retryAfter),s}function wt(e,t,i){let o=e.identitySummary;if(o==null)return null;let r={kind:"identity_summary",key:"identity_summary",context:t,section:i??"identity",summaryKind:o.kind==="partial"?"partial":o.kind??"full",source:o.source,portraitAvailable:o.portrait?.available===!0,retakeAvailable:o.retakeAvailable===!0};for(let u of Ot){let a=o[u];typeof a=="string"&&a!==""&&(r[u]=a)}let s=Oe(o);return s!==void 0&&(r.idNumberMasked=s,r.nniMasked=s),r}var Ot=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","expiryDate","retakeTarget"];function M(e,t,i,o){return{kind:"unsupported",key:`unsupported:${i}`,context:e,section:t,checkType:i,reason:o}}function Et(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function Mt(e,t){let i=De[e.kind]??[...ne,...ie],o=Et(e),r=e.options.flatMap(u=>{if(u.available===!1||!i.includes(u.service))return[];let a={id:u.id,service:u.service};return u.nationalEid!=null&&(a.nationalEid=u.nationalEid),[a]});if(r.length===0){let u=e.options.length>0&&e.options.every(a=>a.service==="nfc");return M(t,o,"choice",u?"platform_unsupported":"update_required")}let s={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:r};if(e.kind==="identity_method"){let u={kind:"method",key:"method",context:t,section:o,options:r.map(p=>V[p.service]),choice:s},a=r.find(p=>p.nationalEid!==void 0)?.nationalEid;return a!==void 0&&(u.nationalEid=a),u}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:o,options:r.map(u=>Le[u.service]),selected:null,locked:!1,choice:s}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:o,choice:s}}function nn(e,t={}){let i=ft(e);if(b(e)||e.failureReason===He)return At(e,i);let o=e.plan;if(o===void 0||!Array.isArray(o.sections))return M(i,null,"plan","update_required");let r=Ie(e);if(r!==null)return Mt(r,i);let s=o.current===null?void 0:o.steps.find(m=>m.id===o.current),u=m=>{let d={kind:"processing",key:"processing",context:i,section:m!==void 0?I(m):o.sections.find(P=>P.state==="current")?.id??null,stalled:!1};return typeof m?.service=="string"&&m.service!==""&&(d.service=m.service),d};if(o.current===null)return u(o.steps.find(m=>m.state==="processing"));if(s===void 0)return M(i,null,"step","update_required");if(!at.has(s.service))return s.interaction==="server"?u(s):M(i,I(s),s.service,"update_required");if(ct.has(s.service)||!F(s))return u(s);let a=s,p=mt(a),S=a.checkType,h=I(a);switch(S){case"phone_otp":case"email_otp":return St(e,a,i,p);case"population_registry":return _t(e,a,i,p);case"eid_auth":return xt(e,a,i,p);case"doc_ocr":return kt(e,a,i,p);case"identity_confirm":return wt(e,i,h)??u(a);case"portrait_icao":return Ve(e,a,i,p,"capture");case"liveness":case"face_match":{let m=vt(e,a);if(m!==null)return Ve(e,m,i,p,"match");let d=a.requiresMobile===!0,P=K(e);return d&&t.isMobile===!1?{kind:"mobile_required",key:"mobile_required",context:i,section:h,checkType:S}:{kind:"liveness",key:"biometric",context:i,section:h,mode:S==="face_match"?"selfie":"liveness",requiresMobile:d,instructions:P===null?"standard":"icao",icao:P,livePhoto:Rt(e,S),...p}}case"nfc_chip":return M(i,h,S,"platform_unsupported");default:return M(i,h,S,"update_required")}}export{Xe as a,ze as b,et as c,tt as d,it as e,Kt as f,ot as g,Ee as h,rt as i,st as j,Wt as k,Me as l,$t as m,tn as n,He as o,I as p,oe as q,Ne as r,vt as s,nn as t};
@@ -0,0 +1 @@
1
+ import{A as Z,e as K,f as X,g as fe,h as he,j as Se,k as ee,m as Q,n as te,p as ge,q as ye,x as be,z as O}from"./chunk-64V55KD7.js";import{c as le,d as pe,e as me}from"./chunk-FPXL63KZ.js";import{c as F,g as $,h as _e}from"./chunk-5Y3UST3W.js";var Ce=["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 Ke=["carte_identite","passport","residence_permit"];function Ze(e,t){let i=e.byIssuer?.[t]??e.default;return Ke.filter(r=>i==="*"||i.includes(r))}function Vt(e,t=Ce){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(r=>Ze(e,r).length>0).sort()}function Pe(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}var Ye=640,je=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),ke=6,Re=1500,Me={sharpness:1,exposure:1,meanLuma:128},Ee=null;function We(e,t){try{Ee??(Ee=document.createElement("canvas"));let i=Ee,r=96/Math.max(1,t.width);i.width=Math.max(1,Math.round(t.width*r)),i.height=Math.max(1,Math.round(t.height*r));let s=i.getContext("2d");if(s===null)return Me;s.drawImage(e,t.x,t.y,t.width,t.height,0,0,i.width,i.height);let c=s.getImageData(0,0,i.width,i.height);return{sharpness:pe(c),exposure:me(c),meanLuma:le(c)}}catch{return Me}}async function Qe(e,t){let i=e.source;return"convertToBlob"in i?i.convertToBlob({type:"image/jpeg",quality:t}):new Promise((r,s)=>{i.toBlob(c=>c===null?s(new Error("encode failed")):r(c),"image/jpeg",t)})}function Ut(e,t={}){let i=t.now??(()=>performance.now()),r=t.setTimer??((l,n)=>setTimeout(l,n)),s=t.clearTimer??(l=>clearTimeout(l)),c=t.encode??Qe,p=t.quality??We,u=e.tuningVersion??null,h=new Set,C=!1,b=e.video??null,S=null,y=t.grabFrame??null,k=null,A=1e3/ke,R=null,E=null,L=!1,w=!1,I=Number.NEGATIVE_INFINITY,M=null,H=0,x=null,V=null,D=Promise.all([import("./icao-gate-PWBMKRGC.js"),import("./icao-tuning-4GGVX6B4.js"),import("./create-portrait-capture-INDCF65X.js"),import("./landmarker-KB7LVXAU.js"),import("./background-monitor-A7FKJOAG.js")]).then(async([l,n,o,a,d])=>{let f=n.resolveIcaoTuning(e.tuning,e.tuningVersion??void 0);f.background.required&&(E=d.createBackgroundMonitor({tuning:f.backgroundCheck,assetBaseUrl:e.assetBaseUrl??"/models-v3",...t.createSegmenter!==void 0?{createSegmenter:t.createSegmenter}:{},now:i})),S=l.createIcaoGate(f,{policy:e.policy??"reject"}),y??(y=o.defaultGrabber()),k=o.observe,A=1e3/Math.min(ke,f.cadenceHz);let _=(t.createLandmarker??a.createFaceLandmarker)(e.assetBaseUrl??"/models-v3"),g=await new Promise((m,P)=>{let v=setTimeout(()=>{P(new Error("landmarker init timeout")),_.then(T=>T.close(),()=>{})},a.LANDMARKER_INIT_TIMEOUT_MS);_.then(T=>{clearTimeout(v),m(T)},T=>{clearTimeout(v),P(T)})});C?g.close():R=g}).catch(()=>{L=!0}),Y=l=>{for(let n of h)n({holding:w||L,update:l})},B=()=>{if(M=null,!(C||R===null||S===null||y===null||k===null||b===null)){if(i()-I>Re){Y(null);return}try{let l=y(b,Ye);if(l!==null){let n=Math.max(i(),H+1);H=n;let o=R.detect(l.source,n),a=b.videoWidth||l.width,d=b.videoHeight||l.height,f=k(o,l,a,d);f.geometry!==null&&E!==null&&(f.backgroundCheck=E.measure(l,f.geometry.box,a,d));let _=S.push(f,i());w=_.ready,Y(_)}}catch{}M=r(B,A)}},j=()=>{let l=i()-I>Re;I=i(),l&&(S?.reset(),w=!1,x=null,V=null),M===null&&R!==null&&!C&&(M=r(B,0))},J=()=>{let l=y===null||b===null?null:y(b,null);if(l===null||S===null||Math.max(l.width,l.height)<e.still.minLongSidePx)return Promise.resolve(null);let n=S.summary();return c(l,e.still.jpegQuality).then(o=>({image:o,width:l.width,height:l.height,gate:n}),()=>null)},W=null;return{engineOptions:{measureQuality:(l,n)=>{b=l,j();let o=p(l,n);return w||L?o:{...o,sharpness:0}},telemetry:l=>{if(l.type!=="fired"||C)return;x=J();let n=W;n!==null&&x.then(o=>o===null?void 0:n(o).catch(()=>{})),w=!1,M!==null&&s(M),M=null,I=Number.NEGATIVE_INFINITY}},decorate:l=>{let n=new WeakMap,o=new Map,a=g=>{let m=n.get(g);return m===void 0&&(m=(async()=>{let P=await ye(l,"image","image/jpeg",g.image.size,{engine:"portrait"});return await l.uploadToSpaces(P.uploadUrl,g.image,"image/jpeg"),(await l.completeMedia(P.key)).key})(),m.catch(()=>n.delete(g)),n.set(g,m)),m};W=a;let d=async g=>{let m;try{m=await a(g)}catch(P){let v=P?.code;if(typeof v=="string"&&je.has(v))throw P;return null}return{media:{portrait:m},gate:_e(g.gate),...u!==null?{tuningVersion:u}:{}}},f=l.submitCheck.bind(l),_=(async(g,m,P)=>{if(g!=="liveness")return f(g,m,P);let v=P?.idempotencyKey,T=v===void 0?void 0:o.get(v);if(T===void 0){let ue=x;T=ue===null?Promise.resolve(null):ue.then(de=>de===null?null:d(de)),v!==void 0&&(o.set(v,T),T.catch(()=>o.delete(v)))}let z=await T;if(z===null)return f("liveness",m,P);let Fe=await f("liveness",{...m,portraitIcao:z},P);return V=z,Fe});return new Proxy(l,{get(g,m){if(m==="submitCheck")return _;let P=Reflect.get(g,m);return typeof P=="function"?P.bind(g):P}})},onGate:l=>(h.add(l),()=>h.delete(l)),lastPortraitInput:()=>V,destroy:()=>{C=!0,x=null,V=null,M!==null&&s(M),M=null,h.clear(),D.then(()=>{R?.close(),R=null,E?.close(),E=null})}}}function Ae(e){return e.idNumberBound??e.nniBound}function Ie(e){return e===void 0?void 0:e.idNumberFromDocument??e.nniFromDocument}function ve(e){let t=e.idNumberMasked??e.nniMasked;return typeof t=="string"&&t!==""?t:void 0}var Te=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",sandbox_nni_not_seeded:"sandbox_id_number_not_seeded",missing_nni:"missing_id_number",registry_needs_nni_source:"registry_needs_id_number_source"}),$e=new Map(Object.entries(Te)),Zt=new Map(Object.entries(Te).map(([e,t])=>[t,e]));function Oe(e){return $e.get(e)??e}var qe=new Set(["phone_otp","email_otp","national_eid","document","nfc","population_registry","supplied_identity","summary_confirm","liveness","face_match","aml_screening","face_dedup","age_estimation"]),Je=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),ie=["document","population_registry","national_eid"],oe=["phone_otp","email_otp"],xe={identity_method:ie,contact:oe},ze=["population_registry","document"],Le="platform_unsupported",Xe=new Set(["prefilled","user_entered","prefilled_or_entered"]),et={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"};function N(e){return e.section??et[e.checkType]??null}function re(e,t){let i=e.plan?.choice;if(i===void 0||i.locked)return;let r=i.options.find(s=>s.id!==i.selected&&s.available!==!1&&t.includes(s.service));return r===void 0?void 0:{nodeId:i.nodeId,option:r}}function se(e){let t=e.plan,i=t?.choice;if(t===void 0||i===void 0||i.locked||t.current===null||t.current===i.nodeId||ee(e))return null;let r=xe[i.kind]??[...ie,...oe],s=i.options.flatMap(u=>u.available===!1||!r.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,p=i.selected??s.find(u=>u.service===c)?.id??null;return s.some(u=>u.id!==p)?{nodeId:i.nodeId,kind:i.kind,current:p,options:s}:null}function Ve(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function tt(e){let t=(e.plan?.sections??[]).map(s=>({id:s.id,state:s.state})),i={sessionId:te(e.sessionId),orgName:e.orgName,returning:e.returning===!0,consentRecorded:e.consentRecorded,expiresAt:e.expiresAt,sections:t.map(s=>s.id),progress:t,purpose:e.purpose??"identity"};e.branding!==void 0&&(i.branding=e.branding),e.cameraUnavailableHandled===!0&&(i.cameraUnavailableHandled=!0);let r=se(e);return r!==null&&(i.switchable=r),i}function nt(e){let t={attemptsRemaining:fe(e),attemptsExhausted:e.attemptsExhausted===!0};return e.reason!==void 0&&(t.reason=e.reason),e.retakeHint!==void 0&&(t.retakeHint=e.retakeHint),t}var De={phone_otp:"phone",email_otp:"email"};function it(e,t){let i=re(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return i===void 0?void 0:De[i.option.service]}function ot(e,t,i,r){let s=t.checkType==="email_otp",c=(s?t.emailOtp:t.otp)??{},p=s?t.emailOtp?.emailSource:t.otp?.numberSource,u=p!==void 0&&Xe.has(p)?p:s?"prefilled_or_entered":"user_entered",h=typeof c.sentToMasked=="string"&&c.sentToMasked.length>0,C=it(e,s?"email_otp":"phone_otp"),b={key:t.checkType,context:i,section:N(t),phase:h?"verify":"send",canSwitch:C!==void 0,...r},S=s?{kind:"email_otp",...b,emailSource:u,needsEmail:u!=="prefilled"}:{kind:"phone_otp",...b,numberSource:u,needsPhone:u!=="prefilled",channels:(t.otp?.channels??[]).filter(y=>y==="whatsapp"||y==="sms")};if(C!==void 0&&(S.switchChannel=C),h&&(S.sentToMasked=c.sentToMasked),!s&&t.otp?.channel!==void 0&&(S.channel=t.otp.channel),!s&&Array.isArray(t.phoneCountries)&&(S.phoneCountries=t.phoneCountries.filter(y=>typeof y=="string"&&/^[A-Z]{2}$/.test(y))),!s&&Array.isArray(t.phoneRules)){let y=S.phoneCountries??[];S.phoneRules=t.phoneRules.flatMap(k=>{let A=at(k);return A!==void 0&&y.includes(A.code)?[A]:[]})}return!s&&t.phoneInternational===!0&&(S.phoneInternational=!0),c.expiresAt!==void 0&&(S.codeExpiresAt=c.expiresAt),c.resendAvailableAt!==void 0&&(S.resendAvailableAt=c.resendAvailableAt),S}var rt=/^[\d[\]\-|()?:^]{1,64}$/;function st(e){try{return typeof e=="string"&&rt.test(e)&&new RegExp(e)!==null}catch{return!1}}var we=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function at(e){let{code:t,dial:i,trunk:r,lengths:s,formats:c}=e??{};if(typeof t!="string"||typeof i!="string"||!/^\d{1,3}$/.test(i)||r!==void 0&&(typeof r!="string"||!/^\d{1,3}$/.test(r))||!Array.isArray(s)||s.length===0||!s.every(we))return;let p={code:t,dial:i,lengths:[...s].sort((u,h)=>u-h)};if(r!==void 0&&(p.trunk=r),c!==void 0){if(!(Array.isArray(c)&&c.length<=8&&c.every(h=>st(h?.leading)&&Array.isArray(h.groups)&&h.groups.every(we)&&s.includes(h.groups.reduce((C,b)=>C+b,0)))))return;p.formats=c.map(h=>({leading:h.leading,groups:[...h.groups]}))}return p}function ct(e,t,i,r){let s=Ae(e)===!0?"bound":Ie(t)===!0?"document":"typed",c=s==="typed"&&t.state==="input_required"&&t.reason!==void 0&&Oe(t.reason)==="id_number_recheck",p=Ve(se(e)),u=!r.attemptsExhausted&&p.length===1&&p[0]?.service==="document";return{kind:"registry",key:"registry",context:i,section:N(t),state:t.state==="input_required"?"input_required":"pending",source:s,recheck:c,canUseDocument:u,...r}}function ut(e,t,i,r){let s=[...t.acceptedSides??[]],c={kind:"document",key:"document",context:i,section:N(t),side:s.includes("recto")?"verso":"recto",acceptedSides:s,documents:Pe(e),...r};return dt(e)&&(c.ageStepUp=!0),c}function dt(e){let t=X(e).find(r=>r.checkType==="age_estimation"),i=t?.reason;return t?.state==="failed"&&(i==="age_uncertain"||i==="age_unavailable")}function lt(e){let t=Q(e,"liveness");return t?.state==="passed"||t?.state==="review"}function Ne(e,t,i,r,s){let c=t.icao?.report;return{kind:"portrait",key:`portrait:${s}`,context:i,section:N(t),phase:s,report:Array.isArray(c)?c:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:$(e),retakeOnly:s==="capture"&&t.state==="input_required"&&e.capture?.livePhoto?.oneCapture===!0&&lt(e),...r}}var ne={minLongSidePx:1280,jpegQuality:.95};function pt(e,t){let i=e.capture?.livePhoto;if(i?.oneCapture!==!0)return null;let r=Q(e,"portrait_icao"),s=i.still??ne;return{icao:t==="liveness"&&$(e)!==null&&r!==void 0&&r.state==="pending"&&r.reason===void 0,still:{minLongSidePx:s.minLongSidePx??ne.minLongSidePx,jpegQuality:s.jpegQuality??ne.jpegQuality}}}function mt(e,t,i,r){let s=t.eid,c=N(t);if(s===void 0||s.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:i,section:c,checkType:"eid_auth",reason:"update_required"};let p=Ve(se(e)),u=p.length===1&&ze.includes(p[0]?.service??"")?p[0]:void 0,h=u===void 0?void 0:K[u.service],C=h!==void 0,b={kind:"eid",key:"eid",context:i,section:c,provider:s.provider,providerName:s.providerName,country:s.country,challenge:"app_code",phase:s.awaiting==="code"?"code":"identifier",identifierBound:s.identifierBound===!0,canUseCamera:C,afterPass:s.afterPass==="continue"?"continue":"end",...r};return C&&(b.cameraMethod=h),s.expiresAt!==void 0&&(b.codeExpiresAt=s.expiresAt),s.resendAvailableAt!==void 0&&(b.resendAvailableAt=s.resendAvailableAt),s.resendsRemaining!==void 0&&(b.resendsRemaining=s.resendsRemaining),s.codeAttemptsRemaining!==void 0&&(b.codeAttemptsRemaining=s.codeAttemptsRemaining),b}function ft(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let i=Q(e,"portrait_icao");return i!==void 0&&(i.state==="passed"||i.state==="review")?i:null}function ht(e){return X(e).filter(t=>t.state==="failed").pop()?.attemptsExhausted===!0}function St(e,t){let i=e.failureReason,r;i===Le?r="platform_unsupported":e.status==="expired"?r="expired":e.status==="review_pending"?r="review":e.status==="completed"&&e.outcome==="approved"?r="approved":e.status==="completed"&&e.outcome==="review"?r="review":i==="device_cooldown"?r="cooldown":i!==void 0?r="policy_stop":ht(e)?r="attempts_exhausted":r="rejected";let s=r==="platform_unsupported"?{sessionId:te(e.sessionId),status:"unavailable"}:ge(e,{autoRetry:!1}),c={kind:"result",key:"result",context:t,section:null,display:r,result:s};return i!==void 0&&(c.failureReason=i),e.retryAfter!==void 0&&(c.retryAfter=e.retryAfter),c}function gt(e,t,i){let r=e.identitySummary;if(r==null)return null;let s={kind:"identity_summary",key:"identity_summary",context:t,section:i??"identity",summaryKind:r.kind==="partial"?"partial":r.kind??"full",source:r.source,portraitAvailable:r.portrait?.available===!0,retakeAvailable:r.retakeAvailable===!0};for(let p of yt){let u=r[p];typeof u=="string"&&u!==""&&(s[p]=u)}let c=ve(r);return c!==void 0&&(s.idNumberMasked=c,s.nniMasked=c),s}var yt=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","expiryDate","retakeTarget"];function G(e,t,i,r){return{kind:"unsupported",key:`unsupported:${i}`,context:e,section:t,checkType:i,reason:r}}function bt(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function _t(e,t){let i=xe[e.kind]??[...ie,...oe],r=bt(e),s=e.options.flatMap(p=>{if(p.available===!1||!i.includes(p.service))return[];let u={id:p.id,service:p.service};return p.nationalEid!=null&&(u.nationalEid=p.nationalEid),[u]});if(s.length===0){let p=e.options.length>0&&e.options.every(u=>u.service==="nfc");return G(t,r,"choice",p?"platform_unsupported":"update_required")}let c={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:s};if(e.kind==="identity_method"){let p={kind:"method",key:"method",context:t,section:r,options:s.map(h=>K[h.service]),choice:c},u=s.find(h=>h.nationalEid!==void 0)?.nationalEid;return u!==void 0&&(p.nationalEid=u),p}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:r,options:s.map(p=>De[p.service]),selected:null,locked:!1,choice:c}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:r,choice:c}}function q(e,t={}){let i=tt(e);if(ee(e)||e.failureReason===Le)return St(e,i);let r=e.plan;if(r===void 0||!Array.isArray(r.sections))return G(i,null,"plan","update_required");let s=he(e);if(s!==null)return _t(s,i);let c=r.current===null?void 0:r.steps.find(S=>S.id===r.current),p=S=>{let y={kind:"processing",key:"processing",context:i,section:S!==void 0?N(S):r.sections.find(k=>k.state==="current")?.id??null,stalled:!1};return typeof S?.service=="string"&&S.service!==""&&(y.service=S.service),y};if(r.current===null)return p(r.steps.find(S=>S.state==="processing"));if(c===void 0)return G(i,null,"step","update_required");if(!qe.has(c.service))return c.interaction==="server"?p(c):G(i,N(c),c.service,"update_required");if(Je.has(c.service)||!Se(c))return p(c);let u=c,h=nt(u),C=u.checkType,b=N(u);switch(C){case"phone_otp":case"email_otp":return ot(e,u,i,h);case"population_registry":return ct(e,u,i,h);case"eid_auth":return mt(e,u,i,h);case"doc_ocr":return ut(e,u,i,h);case"identity_confirm":return gt(e,i,b)??p(u);case"portrait_icao":return Ne(e,u,i,h,"capture");case"liveness":case"face_match":{let S=ft(e,u);if(S!==null)return Ne(e,S,i,h,"match");let y=u.requiresMobile===!0,k=$(e);return y&&t.isMobile===!1?{kind:"mobile_required",key:"mobile_required",context:i,section:b,checkType:C}:{kind:"liveness",key:"biometric",context:i,section:b,mode:C==="face_match"?"selfie":"liveness",requiresMobile:y,instructions:k===null?"standard":"icao",icao:k,livePhoto:pt(e,C),...h}}case"nfc_chip":return G(i,b,C,"platform_unsupported");default:return G(i,b,C,"update_required")}}var Ct=/^[A-Z0-9][A-Z0-9 -]{0,39}$/,Pt=Object.freeze({normalize:e=>e.trim().toUpperCase().replace(/\s+/g," "),check:e=>Ct.test(e),registrySources:Object.freeze([]),describe:"number must be 1 to 40 letters, digits, spaces or hyphens"});function kt(e){return typeof e=="string"&&/^\d{10}$/.test(e)&&Number(e)%97===1}var Rt=Object.freeze({normalize:e=>e.trim(),check:e=>kt(e),registrySources:Object.freeze(["MR.anrpts"]),describe:"number must be the 10-digit Mauritanian national ID number with a valid check digit"}),Mt=Object.freeze({"MR:national_id":Rt});function ae(e,t){return Mt[`${e.toUpperCase()}:${t}`]??Pt}var Et=Object.freeze({MRT:"MR"});function Ge(e,t){let i=e.trim().toUpperCase();return ae(Et[i]??i,t)}function He(e){let t=Ge(e.issuingCountry,e.type);return t.check(t.normalize(e.number))}function Be(e){return ae("MR","national_id").check(e)}function ce(e){let t="";for(let i of e){let r=i.codePointAt(0)??0;r>=1632&&r<=1641?t+=String(r-1632):r>=1776&&r<=1785?t+=String(r-1776):i!==" "&&i!=="-"&&i!==" "&&(t+=i)}return t}var At=[1e3,2e3,4e3,8e3,15e3],It=3e4,vt=/^\+[1-9]\d{6,14}$/,Tt=/^\d{6}$/,Ot=/^\d{6}$/,wt=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,Ue=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"]),Nt=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]);function cn(e){let t=!1,i=null,r="",s=!1,c=!1,p=!1,u={},h={},C=new Set,b=!1,S=null,y="idle",k=new Map,A=new Map,R=(n,o,a)=>{let d=`${n}.${o}`,f=k.get(d);if(f!==void 0)return f;let _=A.get(n),g=(_===void 0?a():_.then(a)).finally(()=>{k.delete(d)});k.set(d,g);let m=g.then(()=>{},()=>{});return A.set(n,m),m.then(()=>{A.get(n)===m&&A.delete(n)}),g},E=async(n,o,a)=>{await e.ensureConsent();let d;try{d=await be(e.runtime,o)}catch(_){if(_ instanceof F&&Ue.has(_.code)){await e.refreshView();return}throw _}if(a?.(),e.destroyed())return;let f=d;f.plan!==void 0&&e.setView!==void 0?e.setView(f):await e.refreshView()},L=async n=>{await e.ensureConsent();let o;try{try{o=await n(e.runtime.client)}catch(a){if(!(a instanceof F)||a.code!=="consent_required")throw a;await e.runtime.ensureConsent({force:!0}),o=await n(e.runtime.client)}}catch(a){if(a instanceof F&&Ue.has(a.code)){await e.refreshView();return}throw a}e.destroyed()||(o!==void 0&&e.setView!==void 0?e.setView(o):await e.refreshView())},w=(n,o)=>R("choice",`${n}:${o}`,()=>L(a=>a.choose(n,o))),I=(n,o)=>n.options.some(a=>a.id===o)?w(n.nodeId,o):Promise.reject(new RangeError(`option ${String(o)} is not offered`)),M=(n,o)=>{let a=e.currentView(),d=a===null?void 0:re(a,n);return d===void 0?Promise.reject(new RangeError(`the ${o} is not offered`)):w(d.nodeId,d.option.id)},H=n=>R("identity",n,()=>L(o=>o.confirmIdentity===void 0?Promise.reject(new Error("identity confirmation is not available in this build")):o.confirmIdentity(n))),x=(n,o)=>{let a=n.kind,d=a==="phone_otp",f=d?"phone":"email",_={action:"send"};if(d?n.needsPhone:n.needsEmail){let g=o[f]??h[a],m=d?g?.replace(/[\s().-]/g,""):g?.trim();if(m===void 0||!(d?vt:wt).test(m))return Promise.reject(d?new O("phone","format"):new Z("email","format"));_[f]=m}if(d){let g=n.channels,m=o.channel??(g.length===1?g[0]:void 0);if(g.length>0){if(m===void 0)return Promise.reject(new Z("channel","required"));if(!g.includes(m))return Promise.reject(new Z("channel","unavailable"))}m!==void 0&&(_.channel=m),_.phoneRules=1}return R(a,"send",()=>E(a,(g,m)=>g.submitCheck(a,_,{idempotencyKey:m}),()=>{u[a]=e.now(),_[f]!==void 0&&(h[a]=_[f])}))},V=(n,o)=>Tt.test(o)?R(n,"verify",()=>E(n,(a,d)=>a.submitCheck(n,{action:"verify",code:o},{idempotencyKey:d}))):Promise.reject(new O("code","format")),D=(n,o)=>R("eid_auth",n,()=>E("eid_auth",(a,d)=>a.submitCheck("eid_auth",o,{idempotencyKey:d}))),Y=(n,o)=>{if(n.identifierBound)return D("start",{action:"start"});let a=ce(o??"");if(n.country==="MR"){if(!/^\d{10}$/.test(a))return Promise.reject(new O("nni","format"));if(!Be(a))return Promise.reject(new O("nni","check_digit"))}else if(a==="")return Promise.reject(new O("nni","format"));return D("start",{action:"start",identifier:a})},B=(n,o,a)=>{if(n.source!=="typed")return Promise.reject(new RangeError("this session already holds the ID number"));let d=ce(o);return/^\d{10}$/.test(d)?He({type:"national_id",issuingCountry:"MR",number:d})?R("population_registry","submitIdNumber",()=>E("population_registry",(f,_)=>f.submitCheck("population_registry",{idNumber:d,nni:d},{idempotencyKey:_}),()=>{S=`\u2022\u2022\u2022\u2022\u2022\u2022${d.slice(-4)}`})):Promise.reject(new O(a,"check_digit")):Promise.reject(new O(a,"format"))},j=n=>{switch(n.kind){case"phone_otp":case"email_otp":{let o={...n,send:(d={})=>x(n,d),verify:d=>V(n.kind,d),switchTo:()=>n.canSwitch&&n.switchChannel!==void 0?M([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 o.resendAvailableAt===void 0&&a!==void 0&&(o.resendAvailableAt=new Date(a+It).toISOString()),o}case"eid":return{...n,start:o=>Y(n,o),verify:o=>Ot.test(o)?D("verify",{action:"verify",code:o}):Promise.reject(new O("code","format")),resend:()=>n.resendsRemaining===0?Promise.reject(new RangeError("no new code can be sent for this session")):D("resend",{action:"resend"}),useCamera:()=>n.canUseCamera&&n.cameraMethod!==void 0?M(n.cameraMethod==="document_photo"?["document"]:["population_registry"],"camera path"):Promise.reject(new RangeError("the camera path is not offered"))};case"method":return{...n,select:o=>{let a=n.choice.options.find(d=>K[d.service]===o);return a!==void 0?I(n.choice,a.id):Promise.reject(new RangeError(`method ${String(o)} is not offered`))},choose:o=>I(n.choice,o)};case"choice":return{...n,choose:o=>I(n.choice,o)};case"registry":return{...n,submitIdNumber:o=>B(n,o,"idNumber"),submitNni:o=>B(n,o,"nni"),confirm:()=>R("population_registry","confirm",()=>E("population_registry",(o,a)=>o.submitCheck("population_registry",{},{idempotencyKey:a}))),useDocument:()=>n.canUseDocument?M(["document"],"document method"):Promise.reject(new RangeError("the document method is not offered"))};case"document":return e.bindDocument!==void 0?e.bindDocument(n,l):{...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")}};case"portrait":return e.bindPortrait!==void 0?e.bindPortrait(n,l):{...n,uploadFailed:!1,resubmit:()=>Promise.resolve(),capture:()=>{throw new Error("portrait capture is not available in this build")}};case"contact_choice":return{...n,select:o=>{let a=o==="phone"?"phone_otp":o==="email"?"email_otp":void 0,d=n.choice.options.find(f=>f.service===a);return d!==void 0?I(n.choice,d.id):Promise.reject(new RangeError(`contact ${String(o)} is not offered`))},choose:o=>I(n.choice,o)};case"identity_summary":return{...n,...n.idNumberMasked===void 0&&n.summaryKind==="partial"&&S!==null?{idNumberMasked:S,nniMasked:S}:{},portrait:async()=>{let o=e.runtime.client;if(!n.portraitAvailable||o.identityPortrait===void 0)return null;try{return await o.identityPortrait()}catch{return null}},confirm:()=>H("confirm"),retake:()=>n.retakeAvailable?H("retake"):Promise.reject(new RangeError("no retake is left"))};case"liveness":return{...n,capture:o=>e.liveness(o),onLivePhoto:o=>n.livePhoto?.icao===!0&&e.onLivePhoto!==void 0?e.onLivePhoto(o):()=>{}};case"mobile_required":case"processing":return{...n,refresh:async()=>{s=!1,await e.refreshView()}};case"unsupported":case"result":return{...n};default:{let o=n;throw new Error(`runner: unhandled step ${JSON.stringify(o)}`)}}},J=async()=>{if(!c){c=!0;try{for(let n of At){if(await e.sleep(n),!t||e.destroyed())return;let o=await e.refreshView().catch(()=>null);if(o!==null&&q(o,{isMobile:e.isMobile()}).kind!=="processing")return}s=!0,l()}finally{c=!1}}},W=n=>{if(n.kind!=="liveness"||n.mode!=="selfie")return null;let o={kind:"processing",key:"processing",context:n.context,section:n.section,stalled:!1};if(y==="inflight")return o;if(!b||y==="done")return null;let a=e.keptFaceKey?.()??null;return a===null?null:(y="inflight",E("face_match",(d,f)=>d.submitCheck("face_match",{imageKey:a},{idempotencyKey:f}),()=>{y="done"}).then(()=>{y==="inflight"&&(y="done",l())},()=>{y="done",l()}),o)},U=(n,o=!1)=>{if(!t||e.destroyed()||e.chainBusy())return;let a=q(n,{isMobile:e.isMobile()});a.kind==="registry"&&a.recheck&&(b=!0,y="idle"),a=W(a)??a,a.kind==="processing"?a.stalled=s:s=!1;let d=j(a),f=a.kind==="result"?void 0:a.context.switchable,_=f===void 0?d:{...d,chooseOption:m=>I({nodeId:f.nodeId,kind:f.kind,selected:f.current,options:f.options},m)},g=JSON.stringify(_);a.kind==="registry"&&a.source==="document"&&a.state==="pending"&&!C.has("registry")&&(C.add("registry"),_.confirm().catch(m=>{(!(m instanceof F)||Nt.has(m.code))&&C.delete("registry")})),!(!o&&g===r)&&(r=g,i=_,e.emitStep(_),a.kind==="processing"&&!s&&y!=="inflight"&&J(),a.kind==="result"&&!p&&(p=!0,e.emitResult(a.result)))};function l(){let n=e.currentView();n!==null&&U(n,!0)}return{run:async()=>{if(e.destroyed())throw new Error("verification destroyed");t=!0;let n=await e.ensureView();return i===null&&U(n),i??j(q(n,{isMobile:e.isMobile()}))},current:()=>i,onView:n=>U(n),onChainIdle:()=>{let n=e.currentView();n!==null&&U(n)},republish:l,submit:E}}export{Ze as a,Vt as b,ke as c,Re as d,Ut as e,q as f,At as g,It as h,cn as i};
@@ -0,0 +1 @@
1
+ import{d as J,h as he,i as ye,j as Se,l as Me}from"./chunk-G6LKLN4U.js";import{f as be}from"./chunk-TDLIXFDT.js";import{m as V}from"./chunk-6K4D3U6Q.js";import{a as fe,e as ge}from"./chunk-GT2ZLGF7.js";import{k as $}from"./chunk-CQ7SKLMC.js";var qe={low:{maxLongEdge:1920,payloadTargetBytes:7e5,qMin:.7,qMax:.92},mid:{maxLongEdge:2240,payloadTargetBytes:12e5,qMin:.7,qMax:.92},good:{maxLongEdge:2560,payloadTargetBytes:16e5,qMin:.7,qMax:.92}};function He(e){let{deviceMemory:t,effectiveType:n,saveData:r,downlinkMbps:i,sourceLongEdge:l}=e,s=r===!0||n==="slow-2g"||n==="2g"||i!=null&&i>0&&i<1,u=t!=null&&t<=2,c=n==="4g"||i!=null&&i>=5,f=t!=null&&t>=6,p;s||u?p="low":c&&f?p="good":p="mid";let b=qe[p],S=l&&l>0?Math.min(b.maxLongEdge,l):b.maxLongEdge;return{tier:p,...b,maxLongEdge:S}}function ke(e){let t={};try{let n=navigator;typeof n.deviceMemory=="number"&&(t.deviceMemory=n.deviceMemory);let r=n.connection;r&&(t.effectiveType=r.effectiveType,t.saveData=r.saveData,t.downlinkMbps=r.downlink)}catch{}return typeof e=="number"&&e>0&&(t.sourceLongEdge=e),He(t)}function Xe(e,t,n){let r=Math.min(1,Math.max(0,(e-.28)/.21999999999999997)),i=(t+n)/2;return Math.max(t,n-r*(n-i))}function Ve(e,t,n){let r=Math.max(e,t),i=r>0?Math.min(1,n/r):1;return{width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(t*i))}}async function Ye(e,t){let n=t.startQ,r=await e(n);for(let i=0;i<4&&!(r.size<=t.budgetBytes||n<=t.qMin);i++)n=Math.max(t.qMin,n-.08),r=await e(n);return{blob:r,quality:n}}async function De(e,t,n,r,i){if(t<=0||n<=0)return null;let{width:l,height:s}=Ve(t,n,r.maxLongEdge),u=document.createElement("canvas");u.width=l,u.height=s;let c=u.getContext("2d");if(!c)return null;c.drawImage(e,0,0,l,s);let f=I=>new Promise((h,w)=>{u.toBlob(d=>d?h(d):w(new Error("canvas toBlob returned null")),"image/jpeg",I)}),p=Xe(i,r.qMin,r.qMax),{blob:b,quality:S}=await Ye(f,{startQ:p,qMin:r.qMin,budgetBytes:r.payloadTargetBytes}).finally(()=>{u.width=0,u.height=0});if(b.size>5242880)throw new Error("encoded document exceeds the 5242880-byte media cap");return{blob:b,quality:S,width:l,height:s}}async function Z(e){let t=ke(Math.max(e.width,e.height)),n=await De(e,e.width,e.height,t,.5);if(n===null)throw new Error("canvas encode unavailable");return{blob:n.blob,width:n.width,height:n.height}}async function mt(e){let t=await createImageBitmap(e);try{return await Z(t)}finally{t.close()}}var ft=250,gt=.6,bt=1800,ht=6e3,yt=2e3,we=.16;function te(e,t){return{layout:e,phase:"framing",captured:{},pending:[],lastCaptureAt:t,lastReportAt:t,manualShutter:!1,restPhase:"framing",readSides:[],needFlip:!1,flipped:!1,flipTimeoutSpent:!1,timeoutCapture:!1,lastShotByTimeout:!1}}var Ce=e=>e==="recto"?"verso":"recto",Re=e=>e.phase==="framing"||e.phase==="locking"||e.phase==="flipCue"||e.phase==="reaskRecto",ne=e=>(e.captured.recto!==void 0?1:0)+(e.captured.verso!==void 0?1:0)+e.pending.length;function ee(e,t){return e.lastCaptureAt>=0&&e.lastReportAt>=0?e:{...e,lastCaptureAt:e.lastCaptureAt<0?t:e.lastCaptureAt,lastReportAt:e.lastReportAt<0?t:e.lastReportAt}}function Qe(e,t,n){if(e.phase==="result")return{...e,lastReportAt:n};let r=!t.present||e.captureArea!==void 0&&t.areaFrac<.6*e.captureArea,{flipped:i,awaySince:l}=e;r&&(l=l??n),l!==void 0&&n-l>=250&&(i=!0),r||(l=void 0);let s=e.flipTimeoutSpent&&!(i&&!e.flipped),u={...e,lastReportAt:n,flipped:i,awaySince:l,flipTimeoutSpent:s,lastArea:t.areaFrac};if(!Re(e))return u;if(e.needFlip&&!i){if(!t.ready)return{...u,phase:e.restPhase,goodSince:void 0};let c=e.lastShot!==void 0&&e.pending.includes(e.lastShot);if(s||c)return{...u,goodSince:void 0,phase:e.restPhase};let f=e.goodSince??n;return n-f>=1800?{...u,goodSince:f,phase:"capturing",flipTimeoutSpent:!0,timeoutCapture:!0}:{...u,goodSince:f,phase:e.restPhase}}return t.ready?{...u,phase:"capturing",goodSince:e.goodSince??n}:{...u,goodSince:void 0,phase:t.locking?"locking":e.restPhase}}function Ke(e,t){if(!Re(e)||e.manualShutter)return e;let n=t-e.lastReportAt>=2e3,r=t-e.lastCaptureAt>=6e3;return n||r?{...e,manualShutter:!0}:e}function je(e,t,n){let r=e.layout==="singlePage",i=r?{recto:t}:e.captured,l=r?[]:[...e.pending,t],s={...e,captured:i,pending:l,lastShot:t,lastCaptureAt:n,lastReportAt:-1,manualShutter:!1,goodSince:void 0,notice:void 0,awaySince:void 0,flipped:!1,lastShotByTimeout:e.timeoutCapture,timeoutCapture:!1,captureArea:e.lastArea};return r||ne({captured:i,pending:l})>=2?{...s,phase:"reading",restPhase:"framing",current:void 0,needFlip:!1}:{...s,phase:"flipCue",restPhase:"flipCue",current:void 0,needFlip:!0}}function xe(e,t,n){return e.pending.includes(t)?{...e,pending:e.pending.filter(r=>r!==t),lastShot:e.lastShot===t?void 0:e.lastShot,phase:e.phase==="capturing"?e.phase:"flipCue",restPhase:"flipCue",current:Ce(n),needFlip:!0,flipTimeoutSpent:!0,goodSince:void 0,manualShutter:!0,notice:"same_face",lastCaptureAt:-1,lastReportAt:-1}:e}function $e(e,t,n){if(!e.pending.includes(t))return e;if(e.captured[n]!==void 0)return xe(e,t,n);let r=e.pending.filter(c=>c!==t),i={...e,pending:r,captured:{...e.captured,[n]:t}};if(ne(i)!==1||e.layout==="singlePage")return i;let l=Ce(n),s=l==="recto"&&e.restPhase==="reaskRecto"?"reaskRecto":"flipCue",u=e.phase==="flipCue"||e.phase==="reaskRecto"||e.phase==="framing";return{...i,restPhase:s,current:l,phase:u?s:e.phase}}function Je(e,t){let n=t.id??e.captured[t.side],r={...e.captured};(t.id===void 0||r[t.side]===t.id)&&delete r[t.side];let i=e.pending.filter(f=>f!==n),l=e.layout==="twoSided"&&ne({captured:r,pending:i})>0,s=e.lastShotByTimeout||n===e.lastShot!==e.flipped,u=l&&!s,c=u?t.side==="recto"?"reaskRecto":"flipCue":"framing";return{...e,captured:r,pending:i,readSides:e.readSides.filter(f=>f!==t.side),lastShot:e.lastShot===n?void 0:e.lastShot,notice:t.issue,goodSince:void 0,manualShutter:!1,phase:c,restPhase:c,current:t.side,needFlip:u,flipped:!1,flipTimeoutSpent:!1,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1}}function ve(e,t){switch(t.type){case"report":return Qe(ee(e,t.at),t.report,t.at);case"tick":return Ke(ee(e,t.at),t.at);case"captured":return je(ee(e,t.at),t.id,t.at);case"captureFailed":return{...e,phase:e.restPhase,goodSince:void 0,lastCaptureAt:t.at,manualShutter:!0,timeoutCapture:!1};case"classified":return $e(e,t.id,t.side);case"duplicate":return xe(e,t.id,t.side);case"readOk":{let n=e.readSides.includes(t.side)?e.readSides:[...e.readSides,t.side],r=["recto","verso"].filter(l=>e.captured[l]!==void 0),i=e.phase==="reading"&&e.pending.length===0&&r.every(l=>n.includes(l));return{...e,readSides:n,flipTimeoutSpent:!1,phase:i?"result":e.phase}}case"readFailed":return Je(e,t);case"clockRestart":return e.lastCaptureAt<0&&e.lastReportAt<0&&e.awaySince===void 0?e:{...e,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1};case"retake":return{...te(e.layout,-1),lastCaptureAt:-1,lastReportAt:-1};default:return e}}function Ze(e,t,n=!1){let r=e(t);return r===null?"recto":!n||r.y+r.height/2>=t.height/2?"verso":"recto"}async function et(e,t=!1){let{detectMrzBand:n}=await import("./mrz-band-VYHOTDHY.js");return Ze(n,e,t)}async function re(e,t=480,n,r=n!=null){let i=n??{x:0,y:0,width:e.width,height:e.height},l=Math.max(1,Math.round(i.height/i.width*t)),s=document.createElement("canvas");s.width=t,s.height=l;try{let u=s.getContext("2d");return u===null?"recto":(u.drawImage(e,i.x,i.y,i.width,i.height,0,0,t,l),await et(u.getImageData(0,0,t,l),r))}finally{s.width=0,s.height=0}}async function Mt(e,t=480){try{let n=await createImageBitmap(e),r=Math.max(1,Math.round(n.height/n.width*t)),i=document.createElement("canvas");i.width=t,i.height=r;let l=i.getContext("2d");return l===null?(n.close(),null):(l.drawImage(n,0,0,t,r),n.close(),l.getImageData(0,0,t,r))}catch{return null}}var oe=(e,t,n)=>Math.min(n,Math.max(t,Math.round(e))),Y=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function Le(e,t,n,r){let i=r.decode??(c=>createImageBitmap(c)),l=async()=>e.stillRead(await i(t),r.region??[0,0,1,1],r.detectorLimit),s;try{s=await l()}catch{try{await new Promise(c=>setTimeout(c,r.retryMs??300)),s=await l()}catch{return null}}let u=s.mrzBox;return u===void 0?null:{engine:r.engine,source:"live_mrz",format:n.format,lineCount:oe(n.lineCount,2,3),checkDigitsValid:!0,stillConfirmed:s.valid&&s.digest===n.digest,band:[Y(u[0]),Y(u[1]),Y(Math.min(u[2],1-u[0])),Y(Math.min(u[3],1-u[1]))],digest:n.digest,framesToValid:oe(n.framesToValid,1,1e3),msToValid:oe(n.msToValid,0,12e4)}}function Dt(e){let t=null;return e?.then(n=>{t=n}),()=>t}var tt=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]),nt=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,7,1,5,0,6,64,11,11]);function _e(e,t=globalThis){let n=t.WebAssembly?.validate;if(typeof n!="function")return{ok:!1,reason:"simd"};try{if(!n.call(t.WebAssembly,tt)||!n.call(t.WebAssembly,nt))return{ok:!1,reason:"simd"}}catch{return{ok:!1,reason:"simd"}}if(typeof t.Worker!="function")return{ok:!1,reason:"worker"};if(typeof t.createImageBitmap!="function")return{ok:!1,reason:"bitmap"};let r=t.navigator?.deviceMemory;return typeof r=="number"&&r<e.minDeviceMemoryGb?{ok:!1,reason:"memory"}:{ok:!0}}function Te(e=globalThis){let t=e.navigator?.connection;return t?.saveData===!0||["slow-2g","2g","3g"].includes(t?.effectiveType??"")}var T=class extends Error{constructor(t){super(t),this.name="OcrEngineError",this.code=t}};function Ee(){let e=t=>(t.close(),Promise.reject(new T("unsupported")));return{ready:Promise.resolve("unsupported"),busy:!1,bandRead:e,stillRead:e,layoutRead:e,dispose:()=>{}}}function Oe(e){let t;try{if(e.createWorker)t=e.createWorker();else if(e.workerUrl!==void 0)t=new Worker(e.workerUrl,{type:"module",name:"sekyro-ocr"});else return Ee()}catch{return Ee()}let n=new Map,r=0,i=!1,l=!1,s=!1;t.addEventListener("message",d=>{let g=d.data,C=n.get(g.id);C&&(n.delete(g.id),C.resolve(g))});let u=()=>{for(let d of n.values())d.reject(new T("error"));n.clear(),f()};t.addEventListener("error",u),t.addEventListener("messageerror",u);function c(d,g=[]){if(i)return Promise.reject(new T("disposed"));let C=++r;return new Promise((B,O)=>{n.set(C,{resolve:B,reject:O});try{t.postMessage({...d,id:C},g)}catch{n.delete(C),O(new T("error"))}})}function f(){if(!i){i=!0;try{t.postMessage({id:++r,kind:"dispose"})}catch{}t.terminate();for(let d of n.values())d.reject(new T("disposed"));n.clear()}}let p=(async()=>{let d=await c({kind:"init",baseUrl:e.baseUrl,salt:e.salt,detectorLimit:e.tuning.detectorLimit,maxDownloadMs:e.tuning.maxDownloadMs});if(d.kind==="failed")return d.reason;if(d.kind!=="ready")return"error";let g=await c({kind:"warmup"});return g.kind!=="ready"?"error":{warmupMs:g.warmupMs,downloadMs:d.downloadMs,cached:d.cached}})().catch(()=>"error"),b,S=new Promise(d=>{b=setTimeout(()=>d("timeout"),e.tuning.loadTimeoutMs)}),I=Promise.race([p,S]).then(d=>(clearTimeout(b),typeof d=="string"?f():s=!0,i&&typeof d!="string"?"error":d));(e.page===void 0?globalThis.addEventListener?globalThis:null:e.page)?.addEventListener("pagehide",f,{once:!0});async function w(d,g,C){if(i)throw g.close(),new T("disposed");if(!s)throw g.close(),new T("not_ready");if(l)throw g.close(),new T("busy");l=!0;let B;try{let O=new Promise((k,A)=>{B=setTimeout(()=>{A(new T("timeout")),f()},e.tuning.readTimeoutMs??1e4)}),P=await Promise.race([c(d,[g]),O]);if(P.kind===C){let{id:k,...A}=P;return A}throw new T(P.kind==="error"?P.code:P.kind==="failed"?P.reason:"error")}finally{clearTimeout(B),l=!1}}return{ready:I,get busy(){return l},bandRead:(d,g=e.tuning.detectorLimit)=>w({kind:"band",bitmap:d,detectorLimit:g},d,"band"),stillRead:(d,g,C=e.tuning.detectorLimit)=>w({kind:"still",bitmap:d,region:g,detectorLimit:C},d,"band"),layoutRead:(d,g)=>w({kind:"layout",bitmap:d,detectorLimit:g},d,"layout"),dispose:f}}var U="sekyro-ocr-1",ae=e=>e!==null&&typeof e=="object"?e:{},v=(e,t,n,r)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:r,Pe=(e,t)=>typeof e=="boolean"?e:t,Ae=e=>{let t=typeof e=="string"?/^sekyro-ocr-(\d{1,4})$/.exec(e):null;return t?Number(t[1]):Number.POSITIVE_INFINITY};function Be(e,t={}){let n=ae(e),r=ae(n.liveMrz),i=ae(n.frontLock),l=Ae(t.engine??U),s=t.mode==="off",u=d=>d.enabled===!0?d.arm==="live"?"live":"control":null,c=u(r),f=u(i),p=(d,g)=>!s&&g==="live"&&Ae(d.minEngine??U)<=l,b=Se,S=p(r,c)?{detectorLimit:v(r.detectorLimit,320,1600,b.detectorLimit),bandMaxWidthPx:v(r.bandMaxWidthPx,320,4096,b.bandMaxWidthPx),minBandWidthPx:v(r.minBandWidthPx,0,4096,b.minBandWidthPx),bandTop:v(r.bandTop,0,.95,b.bandTop),minIntervalMs:v(r.minIntervalMs,0,5e3,b.minIntervalMs),stableReads:Math.round(v(r.stableReads,1,10,b.stableReads)),profileReads:Math.round(v(r.profileReads,1,100,b.profileReads)),maxReadMs:v(r.maxReadMs,50,6e4,b.maxReadMs),searchTimeoutMs:v(r.searchTimeoutMs,1e3,12e4,b.searchTimeoutMs),hint:Pe(r.hint,!0),stillConfirm:Pe(r.stillConfirm,!0)}:null,I=ye,h=(d,g,C)=>v(i[d],g,C,I[d]),w=p(i,f)?{minLines:Math.round(h("minLines",1,50)),fillMin:h("fillMin",0,1),fillMax:h("fillMax",0,2),offsetMax:h("offsetMax",0,1),steadyFillDelta:h("steadyFillDelta",0,1),steadyOffsetDelta:h("steadyOffsetDelta",0,1),layoutShiftMax:h("layoutShiftMax",0,1),lineCountDelta:Math.round(h("lineCountDelta",0,50)),lockMs:h("lockMs",0,3e4),steadyMs:h("steadyMs",0,3e4),minFrames:Math.round(h("minFrames",1,100)),minIntervalMs:h("minIntervalMs",0,5e3),maxWidthPx:h("maxWidthPx",160,2048),detectorLimit:h("detectorLimit",320,1600),searchTimeoutMs:h("searchTimeoutMs",1e3,12e4)}:null;return{enabled:S!==null||w!==null,liveMrz:S,textLock:w,liveMrzArm:c,frontLockArm:f,load:{detectorLimit:S?.detectorLimit??w?.detectorLimit??b.detectorLimit,loadTimeoutMs:v(r.loadTimeoutMs,1e3,12e4,2e4),maxDownloadMs:v(r.maxDownloadMs,1e3,12e4,2e4),minDeviceMemoryGb:v(r.minDeviceMemoryGb,0,64,2)},reportSampleRate:v(r.reportSampleRate,0,1,1)}}function Ie(e,t){return e.enabled?!(t.probe??_e)({minDeviceMemoryGb:e.load.minDeviceMemoryGb}).ok||(t.slow??Te)()?{ok:!1,reason:"unsupported"}:{ok:!0,engine:Oe({baseUrl:t.baseUrl,salt:t.salt,tuning:{detectorLimit:e.load.detectorLimit,maxDownloadMs:e.load.maxDownloadMs,loadTimeoutMs:e.load.loadTimeoutMs},...t.workerUrl!==void 0?{workerUrl:t.workerUrl}:{},...t.createWorker!==void 0?{createWorker:t.createWorker}:{},...t.page!==void 0?{page:t.page}:{}})}:{ok:!1,reason:"off"}}function rt(e=typeof navigator<"u"?navigator.userAgent:""){return/SamsungBrowser\//.test(e)?"samsung":/Firefox\/|FxiOS\//.test(e)?"firefox":/Chrome\/|CriOS\/|Chromium\//.test(e)&&!/Edg\/|OPR\//.test(e)?"chrome":/Safari\//.test(e)&&/Version\/|Mobile\//.test(e)&&!/Chrome\/|CriOS\//.test(e)?"safari":"other"}var F=e=>e===void 0||!Number.isFinite(e)?void 0:Math.min(6e5,Math.max(0,Math.round(e))),ie=(e,t,n)=>e===void 0||!Number.isFinite(e)?void 0:Math.min(n,Math.max(t,Math.round(e)));function We(e){let t=e.assist??null,n=e.load!==null&&e.load!==void 0&&typeof e.load=="object"?e.load:null,r=typeof e.load=="string"?e.load:null,i=t!==null?t.outcome:r==="unsupported"||r==="download"||r==="integrity"?r:r==="error"||r==="timeout"?"error":"off",l={kind:"live_mrz",platform:"web",engine:e.engine??U,arm:e.arm,capture:e.capture,outcome:i,reads:ie(t?.reads??0,0,1e4)??0,browser:e.browser??rt()},s=(u,c)=>{c!==void 0&&(l[u]=c)};return s("format",t?.format),s("framesToValid",ie(t?.framesToValid,1,1e4)),s("msToValid",F(t?.msToValid)),s("framesToLock",ie(t?.framesToLock,1,1e4)),s("msToLock",F(t?.msToLock)),s("msToCapture",F(e.msToCapture)),s("readP50Ms",F(t?.readP50Ms)),s("readP90Ms",F(t?.readP90Ms)),s("deviceClass",t?.deviceClass),n!==null&&(s("warmupMs",F(n.warmupMs)),s("downloadMs",F(n.downloadMs)),s("cached",n.cached)),s("stillConfirmed",e.stillConfirmed),s("typeMismatch",e.typeMismatch),l}function se(e,t){return e===void 0?!1:t==="passport"?e!=="TD3":e==="TD3"}var ot=2;async function at(e){let t=await import("./capture-session-doc-VXWWQEP4.js");return new t.CaptureSessionDoc(e)}function it(e){return{topLeft:{x:e.x,y:e.y},topRight:{x:e.x+e.width,y:e.y},bottomRight:{x:e.x+e.width,y:e.y+e.height},bottomLeft:{x:e.x,y:e.y+e.height}}}function st(e,t,n){let r=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let l=0;l<r.length;l+=1){let s=r[l],u=r[(l+1)%r.length];i+=s.x*u.y-u.x*s.y}return t>0&&n>0?Math.abs(i)/2/(t*n):0}function Gt(){import("./capture-session-doc-VXWWQEP4.js").then(e=>e.warmDocDetector()).catch(()=>{})}function qt(e){return ut(e,{}).handle}function ut(e,t){let n=fe(),r=ge({enabled:e.keepScreenAwake!==!1}),i=t.decode??(o=>createImageBitmap(o)),l=t.blurRefuseSharpnessMax??.16,s=t.now??(()=>performance.now()),u=e.documentType==="passport"||e.side==="single",c=te(u?"singlePage":"twoSided",s());if(!u&&(e.side==="recto"||e.side==="verso")){let o=e.side==="recto"?"verso":"recto";c={...c,captured:{[o]:"server"},readSides:[o],current:e.side,phase:"flipCue",restPhase:"flipCue"}}let f="idle",p=null,b=null,S=!0,I=0,h=0,w=!1,d=!1,g="",C=null,B,O=null,P=[],k=t.webOcr!==void 0?Be(t.webOcr.captureDocument,{mode:e.liveMrz?.mode??"auto"}):null,A=null,z=k===null||!k.enabled?"off":null,G=null,q=null,ue=new WeakMap,Q="";if(k!==null&&k.enabled&&t.webOcr!==void 0){let o=t.webOcr,a=Ie(k,{baseUrl:e.liveMrz?.assetBaseUrl??o.baseUrl,salt:o.salt,...e.liveMrz?.workerUrl!==void 0?{workerUrl:e.liveMrz.workerUrl}:{},...o.createWorker!==void 0?{createWorker:o.createWorker}:{}});if(a.ok){A=a.engine;let m=new Me({textLock:k.textLock,liveMrz:k.liveMrz});G=m;let y=a.engine;y.ready.then(L=>{z=L,typeof L!="string"&&S&&m.setEngine(y)})}else z=a.reason}let N=o=>{let a=JSON.stringify(o);a!==Q&&(Q=a,n.emit("mrz",o))},le=(o,a)=>{let m=t.webOcr?.reports;if(m===void 0||k===null||o===void 0)return;let y=o.format==="ID-3"||o.side==="single"?"single":o.side==="verso"?"verso":"recto",L=y!=="recto"?k.liveMrzArm??k.frontLockArm:k.frontLockArm;if(L===null||Math.random()>=k.reportSampleRate)return;let _=o.via==="live_mrz"?q:null,x=()=>{let E=_?.value??null;m([We({arm:L,capture:y,assist:o.ocr??null,load:L==="control"?"off":z,...o.msToCapture!==void 0?{msToCapture:o.msToCapture}:{},...E!==null&&E.stillConfirmed!==void 0?{stillConfirmed:E.stillConfirmed}:{},...a!==void 0?{typeMismatch:se(a.format,e.documentType==="passport"?"passport":"card")}:{}})])};_!==null&&_.value===null?Promise.race([_.promise,new Promise(E=>setTimeout(E,3e3))]).then(x):x()},W=o=>{!S||o===f||(f=o,r.setActive(o==="starting"||o==="scanning"),n.emit("state",o))},Fe=(o,a)=>a===void 0?null:u?"single":o.captured.recto===a?"recto":o.captured.verso===a?"verso":null,ze=o=>({phase:o.phase,captured:u?o.captured.recto!==void 0?["single"]:[]:["recto","verso"].filter(a=>o.captured[a]!==void 0),expected:u?null:o.current??null,notice:o.notice??null,lastShot:Fe(o,o.lastShot),manualShutter:o.manualShutter,torchAvailable:p?.torchAvailable()??!1,torch:d}),ce=()=>{let o=p;o!==null&&o.captureNow().catch(()=>R({type:"captureFailed",at:s()}))};function R(o){if(!S)return;let a=c;c=ve(c,o),c.phase==="capturing"&&a.phase!=="capturing"&&Promise.resolve().then(ce),c.phase==="result"&&a.phase!=="result"&&(W("done"),de());let m=ze(c),y=JSON.stringify(m);y!==g&&(g=y,n.emit("scan",m))}function de(){O!==null&&clearInterval(O),O=null;for(let o of P.splice(0))o();p?.destroy(),p=null,r.setActive(!1)}let me=()=>p?.captureReport?.(),K=!1,pe=(o,a)=>{if(!(o===void 0||t.onFaceReport===void 0))try{t.onFaceReport(o,a)}catch{}},H=o=>{Q="",!(p===null||c.phase==="reading"||c.phase==="result")&&(K=!1,p.rearm(u?"single":c.current??o))},Ne=async(o,a,m,y)=>{if(q=null,y!==void 0&&A!==null&&k?.liveMrz?.hint===!0){let M={promise:Le(A,o,y,{engine:U,detectorLimit:k.liveMrz.detectorLimit}).catch(()=>null),value:null};M.promise.then(D=>{M.value=D}),q=M}y!==void 0&&se(y.format,e.documentType==="passport"?"passport":"card")&&N({state:"mismatch",format:y.format});let L=me();pe(L,"captured"),K=!0,le(L,y);let _=m===void 0?C:m===null?null:{quad:it(m),frameWidth:0,frameHeight:0,inStill:!0},x={decoded:null},E=()=>(x.decoded??(x.decoded=Promise.resolve().then(()=>i(o)).catch(()=>null)),x.decoded);try{await Ue(o,a,_,E,q)}finally{x.decoded!==null&&(await x.decoded)?.close()}},Ue=async(o,a,m,y,L)=>{let _=`shot-${I+=1}`;if(R({type:"captured",id:_,at:s()}),e.haptics!==!1)try{globalThis.navigator?.vibrate?.(30)}catch{}if(!w&&l>0){let M=await(t.measureSharpness!==void 0?t.measureSharpness(o,m):y().then(D=>D===null?-1:he(D,J(m?.quad??null,m?.inStill===!0?D:{width:m?.frameWidth??0,height:m?.frameHeight??0},D)))).catch(()=>-1);if(!S)return;if(Number.isFinite(M)&&M>=0&&M<l){w=!0;let D=u?"recto":c.current??(c.captured.recto===void 0?"recto":"verso");R({type:"readFailed",side:D,id:_,issue:"blurry"}),H(D);return}}w=!1;let x;if(u)x="single";else{let M=c.current,D=await(t.classify!==void 0?t.classify(o):y().then(X=>X===null?M??"recto":m?.inStill===!0?re(X,480,null,!0):re(X,480,J(m?.quad??null,{width:m?.frameWidth??0,height:m?.frameHeight??0},X)))).catch(()=>M??"recto");if(!S)return;if(c.captured[D]!==void 0&&h<ot){h+=1,R({type:"duplicate",id:_,side:D}),H(D==="recto"?"verso":"recto");return}x=c.captured[D]!==void 0&&M!==void 0?M:D,h=0,R({type:"classified",id:_,side:x})}let E=x==="verso"?"verso":"recto";try{let M=t.encode!==void 0?await t.encode(o):await y().then(D=>{if(D===null)throw new Error("the still could not be decoded");return Z(D)});if(!S)return;L!==null&&ue.set(M.blob,L),n.emit("captured",{image:M.blob,side:x,documentType:e.documentType,...e.issuer!==void 0?{issuer:e.issuer}:{},width:M.width,height:M.height,previewDataUrl:a}),t.deferRead!==!0&&R({type:"readOk",side:E})}catch(M){R({type:"readFailed",side:E,id:_,issue:"technical"}),n.emit("error",V("generic",!0,{phase:"keyframes",name:$(M)}))}H(E==="recto"?"verso":"recto")},Ge=o=>{P.push(o.on("statechange",({state:a})=>{a==="preflight"||a==="acquiring"?W("starting"):a==="positioning"?W("scanning"):a==="captured"?W("captured"):a==="error"&&W("error")}),o.on("feedback",({key:a,reticle:m})=>n.emit("feedback",{key:a,reticle:m})),o.on("checks",a=>{n.emit("gate",{progress:a.p,quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight,...a.guide!==void 0?{guide:{detected:a.guide.detected,fill:a.guide.fill,offsetX:a.guide.offsetX??0,offsetY:a.guide.offsetY??0}}:{}});let m=a.ocr?.mrz;m!==void 0&&(m.state==="fallback"?N({state:"fallback",reason:m.reason}):m.state==="valid"?N({state:"valid",format:m.format}):m.state==="reading"?N({state:"reading",...m.format?{format:m.format}:{},...m.coach?{coach:m.coach}:{}}):N({state:"searching"}));let y=a.quad===null?0:st(a.quad,a.frameWidth,a.frameHeight);C=a.quad===null?null:{quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight},R({type:"report",report:{present:a.quad!==null&&a.plausible||a.guide?.detected===!0,ready:a.ready===!0,locking:a.p>=.5,areaFrac:y},at:s()})}),o.on("error",({kind:a,retryable:m,detail:y})=>n.emit("error",V(a,m,y))),o.on("artifacts",a=>{Ne(a.keyframe,a.previewDataUrl,a.docRegion,a.liveMrz)}))},j=()=>(b??(b=(async()=>{if(S){if(p===null){let o;try{o=await(t.createEngine??at)({...t.engineOptions??{},...B!==void 0?{guide:B}:{},video:e.video,format:be(e.documentType),side:u?"single":e.side??"recto",autoCapture:!1,...G!==null?{ocr:G}:{}})}catch(m){W("error"),n.emit("error",V("models",!0,{phase:"models",name:$(m)}));return}if(!S){o.destroy();return}p=o,Ge(o);let a=t.tickMs??500;a>0&&(O=setInterval(()=>R({type:"tick",at:s()}),a))}R({type:"clockRestart"}),k!==null&&k.liveMrzArm==="live"&&(z==="unsupported"||z==="off")&&N({state:"fallback",reason:z}),await p.start()}})().finally(()=>{b=null})),b);return{handle:{get state(){return f},on:(o,a)=>n.on(o,a),start:j,retry:()=>{if(p===null&&c.phase==="result"){R({type:"retake"}),h=0,w=!1,j();return}if(p!==null&&f!=="error"){R({type:"retake"}),h=0,w=!1,p.rearm(u?"single":void 0);return}j()},setSide:o=>{u||o==="single"||(c.current!==o&&(c={...c,current:o}),R({type:"clockRestart"}),c.phase!=="reading"&&c.phase!=="result"&&p?.rearm(o))},shutter:ce,focusAt:(o,a)=>{p?.focusAt?.(o,a)},setGuide:o=>{B=o,p?.setGuide?.(o)},setTorch:o=>{d=o,p?.setTorch(o),R({type:"tick",at:s()})},destroy:()=>{if(S&&p!==null&&f!=="done"){let o=me();!K&&o!==void 0&&o.ticks>0&&pe(o,"abandoned"),le(o,void 0)}S=!1,de(),G?.setEngine(null),A?.dispose(),A=null,n.clear()}},setFlowState:o=>{(c.phase==="reading"||c.phase==="result")&&W(o==="done"&&c.phase!=="result"?"scanning":o)},settle:(o,a)=>{let m=o==="verso"?"verso":"recto";R(a.ok?{type:"readOk",side:m}:{type:"readFailed",side:m,issue:a.issue}),a.ok||H(m)},takeDeviceRead:o=>ue.get(o.image)?.value??null}}export{mt as a,ft as b,gt as c,bt as d,ht as e,yt as f,we as g,te as h,ve as i,Ze as j,et as k,Mt as l,Le as m,Dt as n,U as o,Be as p,Ie as q,rt as r,We as s,se as t,ot as u,Gt as v,qt as w,ut as x};