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

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 (54) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +8 -0
  3. package/dist/camera-trait-45MJTW4K.js +1 -0
  4. package/dist/{capture-session-doc-VXWWQEP4.js → capture-session-doc-QA4DOFRF.js} +1 -1
  5. package/dist/{capture-session-v3-Cs4yV3HJ.d.cts → capture-session-v3-CNL-GX11.d.cts} +1 -1
  6. package/dist/{capture-session-v3-CFSVWYzi.d.ts → capture-session-v3-DaBqN8fO.d.ts} +1 -1
  7. package/dist/chunk-5ZKQHFFW.js +1 -0
  8. package/dist/{chunk-ZPXL26BF.js → chunk-FGOVIGGL.js} +1 -1
  9. package/dist/{chunk-RNJA5GDF.js → chunk-IG466TOP.js} +1 -1
  10. package/dist/{chunk-4GJXUVZK.js → chunk-KHR4U2SZ.js} +1 -1
  11. package/dist/chunk-KZBBB5B2.js +1 -0
  12. package/dist/chunk-NJML6FMD.js +1 -0
  13. package/dist/chunk-TQB3URP2.js +1 -0
  14. package/dist/{chunk-ZO6IHP2I.js → chunk-U6S7SCBY.js} +1 -1
  15. package/dist/{chunk-6K4D3U6Q.js → chunk-W2WD7PR2.js} +1 -1
  16. package/dist/chunk-XCKE2MJL.js +1 -0
  17. package/dist/chunk-ZLWH4RBO.js +1 -0
  18. package/dist/client/index.cjs +1 -1
  19. package/dist/client/index.d.cts +6 -71
  20. package/dist/client/index.d.ts +6 -71
  21. package/dist/client/index.js +1 -1
  22. package/dist/core/index.cjs +1 -1
  23. package/dist/core/index.d.cts +3 -3
  24. package/dist/core/index.d.ts +3 -3
  25. package/dist/core/index.js +1 -1
  26. package/dist/{create-document-capture-FVSQPUF6.js → create-document-capture-GJXBQMTC.js} +1 -1
  27. package/dist/{create-portrait-capture-INDCF65X.js → create-portrait-capture-MOS2D7CL.js} +1 -1
  28. package/dist/{create-verification-1BrMZqPJ.d.cts → create-verification-BBOUYpga.d.cts} +113 -22
  29. package/dist/{create-verification-CuoYJ3kj.d.ts → create-verification-COpe2hxf.d.ts} +113 -22
  30. package/dist/{icao-gate-BSbyqLUh.d.ts → icao-gate-CEGvJR3q.d.ts} +19 -9
  31. package/dist/{icao-gate-D-wePfoV.d.cts → icao-gate-l40OU6x1.d.cts} +19 -9
  32. package/dist/icao-policy-BgI1Y870.d.ts +71 -0
  33. package/dist/icao-policy-C7fIdRzo.d.cts +71 -0
  34. package/dist/index.cjs +1 -1
  35. package/dist/index.d.cts +7 -7
  36. package/dist/index.d.ts +7 -7
  37. package/dist/index.js +1 -1
  38. package/dist/internal/index.cjs +1 -1
  39. package/dist/internal/index.d.cts +6 -6
  40. package/dist/internal/index.d.ts +6 -6
  41. package/dist/internal/index.js +1 -1
  42. package/dist/plan-runner-35655N4Z.js +1 -0
  43. package/dist/print-AYSCRSZB.js +1 -0
  44. package/dist/{types-DPl0hsmI.d.cts → types-Dpfg2cO8.d.cts} +149 -11
  45. package/dist/{types-DPl0hsmI.d.ts → types-Dpfg2cO8.d.ts} +149 -11
  46. package/dist/upload-file-UYXOHCRG.js +1 -0
  47. package/package.json +3 -2
  48. package/sbom.cdx.json +46 -7
  49. package/dist/chunk-5Y3UST3W.js +0 -1
  50. package/dist/chunk-64V55KD7.js +0 -1
  51. package/dist/chunk-JUEOHNVW.js +0 -1
  52. package/dist/chunk-L45YTRJJ.js +0 -1
  53. package/dist/chunk-PLH6ZR6J.js +0 -1
  54. package/dist/plan-runner-WEUIMCYU.js +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,32 @@
1
1
  # @sekyro/web
2
2
 
3
+ ## 0.1.0-rc.20
4
+
5
+ ### Minor Changes
6
+
7
+ - 1005d9e: The document step can take a photo of the document picked from the device. Where the photo comes from is a setting of the step: the hosted session view gains `documents` (`HostedDocumentsView`: `source` `camera`, `upload` or `choice` (`PhotoSource`), `sourcePick` once the person chose under `choice` (`PhotoSourcePick`: `camera` or `upload`), and `uploadOffered`, true when an upload is accepted now). Absent means the camera with no upload offered. Under `camera` no upload is ever offered, even when the step's camera cannot open: the step's source is final. `DocumentSnapshot.photo` (`PhotoSourceState`: `source`, `pick` and `uploadOffered`) tells the UI what to show.
8
+
9
+ `DocumentStepHandle.uploadDocument(file)` sends the picked photo for the face the step asks for and submits `doc_ocr` with `source: "upload"` (new on `DocOcrInput`; a camera photo sends `source: "camera"` when the view has a `documents` block). A JPEG or PNG within 5 MB is sent as picked; a HEIC photo is converted to JPEG on the device where the browser can decode it, and a larger photo is scaled down. It rejects with `RangeError("upload_not_offered")` while `photo.uploadOffered` is false and with `TypeError("unsupported_file")` for any other file. The photo is presigned as a declared upload (`source: "upload"` on the media request, no capture proof). `HostedClient.presign` takes `{ source: "upload" }`, and a repeated `reportCaptureIssue` now resolves when the first send settles.
10
+
11
+ `@sekyro/react` follows the step's source: the camera screen (with "Upload a photo instead" only under `choice` while an upload is offered, never under `camera`), the upload screen at once, or a "Take a photo" / "Upload a photo" choice unless the person already chose for the step.
12
+ - c17645e: The portrait step: an ICAO photo of its own, from the camera or a photo picked from the device, which the server may adjust and the person accepts. The hosted session view's `portrait` gains `source` (`PhotoSource`: `camera`, `upload` or `choice`), `sourcePick` (`PhotoSourcePick`), `uploadOffered`, `fixes`, `fixReview`, `output` (`PortraitOutputFormat`) and `pendingFix` (`HostedPortraitPendingFix`: the original and adjusted photo URLs, the fixes applied and when the URLs expire). `PortraitSnapshot` gains `photo` (`PhotoSourceState`), `pendingFix` and the `review` phase. `CaptureIssueReport.check` gains `portrait`: `@sekyro/react` reports a portrait camera that cannot open as a diagnostic. A step under `camera` never offers an upload, even then.
13
+
14
+ `PortraitStepHandle.uploadPortrait(file)` sends a photo picked from the device (converted on the device like a document upload, presigned as a declared upload without a capture proof) and submits `portrait_icao` with `source: "upload"`; it rejects with `RangeError("upload_not_offered")` while `photo.uploadOffered` is false and with `TypeError("unsupported_file")` for any other file. `PortraitStepHandle.confirmFix(accept)` answers an adjusted photo in the `review` phase (`portrait_icao` with `{ fixReview: { accept } }`, `PortraitFixReviewInput`). A camera photo now sends `source: "camera"` and `capture: { mode }` (new on `PortraitIcaoInput`). `PortraitIcaoReason` gains `portrait_recaptured`, `portrait_morph_suspected`, `portrait_reference_mismatch`, `portrait_declined_fix` and `portrait_fix_review`, and `PortraitFix` names the fixes the server applies.
15
+
16
+ `@sekyro/react` asks "Take a photo" or "Upload a photo" under `choice` unless the person already chose (the upload screen at once under `upload`), shows the adjusted photo next to the original with the fixes in words, "Use this photo" and another photo, and words the new reasons in every language.
17
+
18
+ The face match after an accepted portrait sends no image key: the server compares the liveness capture with the reference, not the portrait.
19
+ - b7e6423: `VerificationResult` no longer carries `personId` or `subjectId` (and `HostedSessionView` no longer has `subjectId`): the hosted session view can be read by anyone holding the link, so it never names the person. Identify the person on your server with the result token's `sub` after you verify the token (the API's `personId` is `per_<sub>`), or with the webhook.
20
+
21
+ ### Patch Changes
22
+
23
+ - 6a53392: Headless flows (`verification.run()`, `verification.liveness()`) now report the capture errors they surface to the session, as `<LivenessCapture>` does, with no code change on your side. A capture bound to no session reports nothing.
24
+ - 1f93754: The device header says when the page runs inside an app's browser (`inApp`), so the dashboard can show how often that happens on an integration. `isInAppBrowser()` is also exported from `@sekyro/web/client`.
25
+ - 6c0141f: `SessionFailureReason` gains `blocked_by_org`: one of the organization's blocks stopped the session. The result screen shows one line asking the person to contact the organization, in every locale. Nothing returns it until blocks are available to the organization.
26
+ - 5994d5d: Retries the service paces are spread out and wait longer when asked. When the service is busy (503 `server_busy` or `request_timeout`), the hosted client waits the `Retry-After` the service sends (2 seconds without one) up to 20 seconds, previously 3, before its one retry. When the model service is unavailable (503 `inference_unavailable`), a submission waits the `Retry-After` (10 seconds without one) up to 20 seconds, previously 30, before each of its three retries. Every such wait is spread by ±25 % (at least 0.5 seconds) so clients do not all come back at the same moment, and the `busy` event's `retryAfterSeconds` is the wait actually taken, so it can have a fraction.
27
+ - 0b01cee: The web SDK sends a device fingerprint for fraud prevention: browser, hardware and camera traits from the ThumbmarkJS library, each hashed in the browser, and the phone model and operating system version on Chromium browsers. It adds the `@thumbmarkjs/thumbmarkjs` dependency, loaded on demand, with no network request of its own. Name device fingerprinting in your privacy notice; see "Device fingerprinting" in the web SDK guide.
28
+ - 5c5f7e3: A code send the server refused no longer moves the number or address a later `send()` without one goes to, nor the local resend cooldown. A resend after a page reload now names no target, so the server sends to the one it kept with the code, instead of failing with an input error.
29
+
3
30
  ## 0.1.0-rc.19
4
31
 
5
32
  ### Minor Changes
package/README.md CHANGED
@@ -38,6 +38,12 @@ Requirements: a secure context (HTTPS or `localhost`), self-hosted detector asse
38
38
  under `/models-v3` (or `assetBaseUrl`), and your page origin in the app's allowed web
39
39
  origins (dashboard: app page → Integration → Platforms → Web).
40
40
 
41
+ Privacy: the SDK collects a device fingerprint for fraud prevention (browser, hardware
42
+ and camera traits, hashed in the browser before they are sent, plus the Chromium phone
43
+ model and operating system version). No permission is asked, the fingerprinting library makes no network
44
+ request of its own, and nothing is stored for it. Name it in your privacy notice; see
45
+ *Device fingerprinting* in the [web SDK guide](https://docs.sekyro.ai/en/web/embedded-sdk).
46
+
41
47
  ## Preload & camera probes
42
48
 
43
49
  Warm the face detector before the user taps Start (on the step before the
@@ -134,3 +140,5 @@ before opening another.
134
140
  Every entry ships ESM + CJS + `.d.ts` (`tsup`). `./core` deliberately does **not**
135
141
  re-export the document scanner (that lives only under `./internal`) nor the worker
136
142
  entry.
143
+
144
+ When the service is busy (503 `server_busy` or `request_timeout`), `HostedClient` retries a call that is safe to repeat once, after the `Retry-After` the service sends (2 seconds without one). When the model service is unavailable (503 `inference_unavailable`), a submission retries up to three times, after the `Retry-After` (10 seconds without one), and emits `busy` with the wait. Both waits are capped at 20 seconds and spread by ±25 % (at least 0.5 seconds) so clients do not all come back at once.
@@ -0,0 +1 @@
1
+ import{a,b,c,d}from"./chunk-TQB3URP2.js";export{a as bounded,c as cameraHash,b as hex16,d as noteCameraTrait};
@@ -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-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
+ 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-U6S7SCBY.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-ZLWH4RBO.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 { aq as ScreenRampReport, k as CaptureProvenance, ao as ScreenRampChallenge, S as ScreenRampColour } from './types-DPl0hsmI.cjs';
1
+ import { aS as ScreenRampReport, aK as CaptureProvenance, aQ as ScreenRampChallenge, aG as ScreenRampColour } from './types-Dpfg2cO8.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+.
@@ -1,4 +1,4 @@
1
- import { aq as ScreenRampReport, k as CaptureProvenance, ao as ScreenRampChallenge, S as ScreenRampColour } from './types-DPl0hsmI.js';
1
+ import { aS as ScreenRampReport, aK as CaptureProvenance, aQ as ScreenRampChallenge, aG as ScreenRampColour } from './types-Dpfg2cO8.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+.
@@ -0,0 +1 @@
1
+ import{c as v,d as V,e as A}from"./chunk-NJML6FMD.js";var j=new Set(["nni_unbound","id_number_unbound","method_required","mobile_required","portrait_required"]);function we(e){return j.has(e)}function be(e,n,t){let i=n.detail;return{check:e,kind:n.kind,...i?.name!==void 0?{name:i.name}:{},...i?.phase!==void 0?{phase:i.phase}:{},...i?.engineKind!==void 0?{engineKind:i.engineKind}:{},attempt:Math.max(0,Math.min(1e3,t))}}function ke(){let e=-1,n="";return{note(t){t==="starting"&&n!=="starting"&&(e+=1),n=t},newHandle(){n=""},noteError(){e<0&&(e=0)},get value(){return e}}}var H=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(H)),$=new Map(Object.entries(H).map(([e,n])=>[n,e]));function ve(e){return I.get(e)??e}function z(e){let n=I.get(e)??$.get(e);return n===void 0?[e]:[e,n]}function T(e){let n=[];for(let t of e)for(let i of z(t))n.includes(i)||n.push(i);return n}var W=new Set(T(["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"])),X={document:"document_photo",nfc:"document_chip",population_registry:"national_number",national_eid:"national_eid"};function p(e){return e.plan?.steps??[]}function O(e){return Math.max(0,e.attempts.max-e.attempts.used)}function G(e){let n=e.plan?.choice;return n!==void 0&&e.plan?.current===n.nodeId?n:null}function Me(e){let n=G(e);if(n?.kind!=="identity_method")return null;let t=n.options.map(o=>X[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 J=new Set(["liveness","face_match"]);function x(e){return e!==void 0&&(e.state==="pending"||e.state==="input_required")}function L(e){return e.status!=="created"&&e.status!=="in_progress"}function E(e){let n=e.plan?.current,t=n==null?void 0:p(e).find(i=>i.id===n);return x(t)?t:void 0}function y(e,n){return p(e).find(t=>t.checkType===n)}function g(e){let n=p(e),t=n.findIndex(i=>i.checkType==="liveness");return n.find((i,o)=>o>t&&i.checkType==="face_match")}function N(e,n){let t=y(n,"liveness")?.state,i=g(n)?.state;return(g(e)?.state??"pending")==="pending"&&(t==="passed"||t==="review")&&i!==void 0&&i!=="pending"&&i!=="skipped"}function M(e,n){let t=new Map(p(e).map(i=>[i.id,i.state]));return p(n).filter(i=>i.checkType==="face_match"&&(t.get(i.id)??"pending")==="pending"&&i.state!=="pending"&&i.state!=="skipped").map(i=>i.id)}var Q=/^[0-9a-f]{24}$/i;function b(e){return Q.test(e)?`ses_${e}`:e}function w(e,n){let t=b(e);return n===void 0?{sessionId:t,status:"unavailable"}:{sessionId:t,status:"unavailable",reason:n}}function _(e,n,t){let i=b(e);return t===void 0?{sessionId:i,status:n}:{sessionId:i,status:n,reason:t}}function Pe(e,n){let{sessionId:t}=e;switch(e.status){case"completed":case"failed":case"review_pending":return ee(e,ne(e));case"expired":return w(t);case"created":case"in_progress":break;default:{let i=e.status;throw new Error(`mapSessionResult: unhandled status ${i}`)}}return ie(e,n)}var Z=new Set([0,1,2,3]);function ee(e,n){return Z.has(e.level)&&(n.level=e.level),typeof e.assurance=="string"&&e.assurance.length>0&&(n.assurance=e.assurance),n}function ne(e){let n=b(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 te(e,n){if(n===void 0)return!1;let t=p(n).find(i=>i.id===e.id);return t!==void 0&&t.attempts.used===e.attempts.used}function ie(e,n){let t=b(e.sessionId),i=p(e).find(s=>J.has(s.checkType)&&s.state==="input_required"&&s.reason!==void 0);if(i?.reason==="mobile_required")return w(t,"mobile_required");if(i?.reason!==void 0){let s=n.autoRetry&&O(i)>0&&(W.has(i.reason)||te(i,n.previous)),d={sessionId:t,status:s?"retry":"rejected",reason:i.reason,attemptsRemaining:O(i)};return i.retakeHint!==void 0&&(d.retakeHint=i.retakeHint),d}let o=E(e);return o===void 0&&p(e).some(s=>s.state==="review")?_(t,"review",h(e,"review")):o?.checkType==="portrait_icao"?w(t,"portrait_required"):w(t)}function h(e,n){let t=p(e).filter(i=>i.state===n&&i.reason!==void 0);return t[n==="failed"?t.length-1:0]?.reason}function K(e,n,t,i,o){return e.presignCapture!==void 0?e.presignCapture(n,t,i,o):e.presign(n,t,i)}function q(e){return{engine:e?.engine,durationMs:e?.clipMs}}var oe=["video/webm","video/mp4"],F="image/jpeg",se=2,re=1e3,ae=1e4,de=3,ue=10,ce=3,le=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),pe=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=g(e);return y(e,"portrait_icao")?.state!=="pending"&&(n!==void 0?x(n):e.capture?.livePhoto?.oneCapture===!0)}var R=class extends Error{constructor(n){super(n),this.name="AttestationError"}};async function D(e,n,t={}){let i=e.uuid(),o=!1,s=!1,d=0,u=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"&&u<de){u+=1;let a=V(r.retryAfterSeconds,ue,e.random??Math.random);e.onBusy?.({attempt:u,retryAfterSeconds:a/1e3}),await e.sleep(a),t.onAttestationInvalid?.(),i=e.uuid();continue}if(le.has(r.code)&&d<se){d+=1;let a=r.retryAfterSeconds!==void 0?r.retryAfterSeconds*1e3:void 0;await e.sleep(a!==void 0?Math.min(a,ae):re);continue}throw r}}var me=new Set(["passed","review","processing","skipped"]);async function Oe(e){let{artifacts:n}=e,t=n.clip,i=A(n.clipMime??"");if(n.degraded==="NO_RECORDER"||t===void 0||!oe.includes(i))return{kind:"unavailable",reason:"no_recorder"};e.client.armCapture?.(2);let o=_e(e,n.keyframe),s=he(e,t,i,o),d=ge(e,o),u=!1,r=new Set,a=!0,m=0;for(;;){if(e.isCancelled())return{kind:"cancelled"};let l=e.getView();if(L(l))return{kind:"settled"};let k=E(l),P=k?.checkType,C=P==="liveness"&&!u?"liveness":P==="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"&&y(l,"liveness")?.requiresMobile===!0)return{kind:"unavailable",reason:"mobile_required"};try{if(C==="liveness"){u=!0;let c=await s();if(e.isCancelled())return{kind:"cancelled"};N(l,c)&&r.add(g(c)?.id);for(let B of M(l,c))r.add(B);await e.applySubmit(c,"liveness");let f=y(e.getView(),"liveness")?.state;a=f===void 0||me.has(f)}else{r.add(k?.id);let c=await d();if(e.isCancelled())return{kind:"cancelled"};for(let f of M(l,c))r.add(f);await e.applySubmit(c,"face_match")}}catch(c){if(e.isCancelled()||c instanceof S)return{kind:"cancelled"};let f=Re(c);if(f.kind!=="resync"||m>=ce)return f;m+=1,await e.refreshView()}}}function _e(e,n){let t=null,i=null,o=()=>t!==null?Promise.resolve(t):(i??(i=(async()=>{let s=await K(e.client,"image",F,n.size,q(e.artifacts));return await e.client.uploadToSpaces(s.uploadUrl,n,F),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 he(e,n,t,i){let o=null,s,d=null;return()=>D(e,async(u,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 K(u,"clip",t,n.size,q(e.artifacts));return await u.uploadToSpaces(l.uploadUrl,n,t),(await u.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(d===null)try{d=await e.getAttestation()}catch(a){throw new R(a instanceof Error?a.message:String(a))}return e.onPhase("checking"),u.submitCheck("liveness",{clipKey:o,attestation:d,captureChannel:e.artifacts.captureChannel,capture:ye(e.artifacts),...s!==null?{faceMatch:s}:{}},{idempotencyKey:r})},{onAttestationInvalid:()=>{d=null}})}function ge(e,n){return()=>D(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 Se)e[t]!==void 0&&(n[t]=e[t]);return n}var Se=["engine","facingMode","mode","formFactor","clipMs","cameraReadyMs","faceAcquireMs","captureMs","screenRamp","provenance"];function Re(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(pe.has(e.code))return{kind:"resync"}}return{kind:"unavailable",reason:"network"}}var U=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="InvalidInputError",this.field=n,this.kind=t}},Y=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="OtpInputError",this.field=n,this.kind=t}};function Fe(e){let n=e?.capture,t=n?.mode;return t==="assisted"||t==="self"||t==="choice"?t:n?.cameraSwitch===!0?"assisted":"self"}function Ke(e,n){return e==="choice"?n??"self":e}export{we as a,be as b,ke as c,Fe as d,Ke as e,ve as f,W as g,X as h,p as i,O as j,G as k,Me as l,x as m,L as n,E as o,y as p,b as q,w as r,Pe as s,K as t,oe as u,se as v,re as w,de as x,ue as y,R as z,D as A,Oe as B,U as C,Y as D};
@@ -1 +1 @@
1
- import{a as F,c as N,d as H,e as U}from"./chunk-FUHDOEBP.js";import{b as J,c as ee,d as te}from"./chunk-POIQGEZM.js";import{b as K,c as B,e as W,g as z,h as R,k,m as q,n as Z}from"./chunk-CQ7SKLMC.js";import{b as O,c as re,d as x,e as ie}from"./chunk-FPXL63KZ.js";import{c as X}from"./chunk-JUEOHNVW.js";import{c as Q,d as Y,f as w,h as j,j as $}from"./chunk-OKWG3PVH.js";var ge=2500,be=1e3,ye=1500,ne=25e5,b=class extends Error{constructor(e,t){super(t??e),this.kind=e}},A=class{constructor(){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.settled=!1}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.hardStopTimer=null,this.graceTimer=null}record(e,t,r){if(this.recorder&&!this.settled)return Promise.reject(new b("generic","record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time"));this.recorder=null,this.clearTimers(),this.chunks=[],this.bytes=0,this.settled=!1,this.stream=e;let i=K();return new Promise((n,a)=>{let s;try{s=new MediaRecorder(e,i?{mimeType:i,videoBitsPerSecond:ne}:{videoBitsPerSecond:ne})}catch{try{s=new MediaRecorder(e)}catch{a(new b("unsupported"));return}}this.recorder=s;let d=c=>{this.settled||(this.settled=!0,this.clearTimers(),c())},u=()=>d(()=>{let c=s.mimeType||i||B,l=new Blob(this.chunks,{type:c});if(l.size===0){a(new b("generic","empty clip"));return}if(R(l)){a(new b("cliptoolarge"));return}n({blob:l,mimeType:c})});if(s.ondataavailable=c=>{c.data&&c.data.size&&(this.chunks.push(c.data),this.bytes+=c.data.size,this.bytes>z&&d(()=>{try{s.state!=="inactive"&&s.stop()}catch{}a(new b("cliptoolarge"))}))},s.onstop=u,s.onerror=()=>d(()=>a(new b("generic"))),r!==void 0){let c=!1;s.onstart=()=>{if(!(c||this.settled)){c=!0;try{r()}catch{}}}}try{s.start(be)}catch{d(()=>a(new b("generic")));return}this.hardStopTimer=setTimeout(()=>{if(this.settled||t?.(),s.state!=="inactive"){try{s.stop()}catch{u()}this.graceTimer=setTimeout(u,ye)}else u()},ge)})}stop(e){this.clearTimers();let t=this.recorder;if(t&&t.state!=="inactive")try{t.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(i=>i.stop()),this.stream=null}};var Be=400,We=2e3,Se=["rose","peach","sand","mint","sky","lilac"],Ee={rose:"rgb(255, 185, 205)",peach:"rgb(245, 193, 159)",sand:"rgb(195, 210, 158)",mint:"rgb(139, 219, 203)",sky:"rgb(140, 214, 249)",lilac:"rgb(208, 197, 249)"};function ze(o){return Ee[o]}var Me=4,_e=4;function Ce(o){if(typeof o!="object"||o===null)return!1;let e=o;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length!==3||!e.colours.every(r=>Se.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==3)return!1;let t=-1;for(let r of e.onsetsMs){if(typeof r!="number"||!Number.isFinite(r)||r<=t||r>=2e3)return!1;t=r}return!0}function ae(o,e){let t=e.now??(()=>performance.now()),r=Ce(o)?o:void 0,i=[],n=null,a=null,s=null,d=!1,u=null,c=p=>{u=p;try{e.paint(p)}catch{}},l=p=>{let m=e.frames?.()??null;return m!==null&&s!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-s:p-(a??p)},f=(p,m,v=0)=>{if(d)return;let E=Math.max(0,p-l(t()));n=setTimeout(()=>{if(n=null,!d){if(v<Me&&l(t())<p-_e){f(p,m,v+1);return}m()}},E)},h=p=>{if(r!==void 0){if(p>=3){f(2e3,()=>c(null));return}f(r.onsetsMs[p],()=>{let m=l(t());if(m>2e3){u!==null&&c(null);return}let v=r.colours[p];c(v);let E=i.length===0?0:i[i.length-1].tMs;i.push({tMs:Math.max(E,Math.round(m)),colour:v}),h(p+1)})}};return{started(p){if(r===void 0||d||a!==null)return;a=p;let m=e.frames?.()??null;s=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),h(0)},stop(){d||(d=!0,n!==null&&clearTimeout(n),n=null,u!==null&&c(null))},report(){return r===void 0?void 0:{nonce:r.nonce,rendered:[...i]}}}}function se(o,e,t=.92){return new Promise((r,i)=>{let n=o.videoWidth,a=o.videoHeight;if(!n||!a){i(new Error("video-not-ready"));return}let s=e.getContext("2d");if(!s){i(new Error("no-2d-context"));return}e.width=n,e.height=a,s.scale(-1,1),s.drawImage(o,-n,0),e.toBlob(d=>d?r(d):i(new Error("empty-keyframe")),"image/jpeg",t)})}var I=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let t=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),t()}))};t();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((t,r)=>t+r,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var Te=Object.freeze({Q_GOOD:.6,RISE_PER_S:.9,FALL_PER_S:.25,CENTER_FALLOFF_IOD_MULTIPLE:1.35,BOX_EYE_OFFSET_FACTOR:.12,IOD_BOX_PROXY_FACTOR:.42,SIZE_IDEAL_MIN:.12,SIZE_IDEAL_MAX:.3,SIZE_HARD_MIN:.08,SIZE_HARD_MAX:.45,ROLL_MAX_DEG:25,MOTION_VELOCITY_IOD_PER_S:.5,MOTION_TAU_S:.4,MOTION_DEADBAND_IOD_PER_S:.1,READY_WINDOW_MS:500,GUIDE_SIZE:.6,GUIDE_CENTERING:.6,GUIDE_POSE:.6,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,GUIDE_MOTION:.5}),S=o=>Math.min(1,Math.max(0,o)),M=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...Te,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:t,quality:r,timestampMs:i}=e,n=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let a={presence:0,centering:0,size:0,pose:0,sharpness:S(r.sharpness),exposure:S(r.exposure),motion:1};if(t!==null){a.presence=1;let c=this.geometryOf(t,e);a.centering=c.centering,a.size=c.size,a.pose=c.pose,a.motion=this.motionOf(c.center,c.iod,i)}else this.lastCenter=null,this.velocityEma=0;let s=Math.min(a.presence,a.centering,a.size,a.pose,a.sharpness,a.exposure,a.motion);this.p=S(this.p+(s>=this.t.Q_GOOD?this.t.RISE_PER_S*s:-this.t.FALL_PER_S*(1-s))*n),this.qWindow.push({at:i,q:s}),this.qWindow=this.qWindow.filter(c=>c.at>=i-this.t.READY_WINDOW_MS);let d=this.qWindow.map(c=>c.q);if(d.length>=3){let c=Math.min(...d),l=d.indexOf(c);d=d.filter((f,h)=>h!==l)}let u=this.p>=1&&d.every(c=>c>=this.t.Q_GOOD);return{at:i,q:s,p:this.p,factors:a,guidanceKey:this.guidanceOf(a,r,s),ready:u,accepted:s>=this.t.Q_GOOD}}geometryOf(e,t){let{box:r,eyes:i}=e,n={x:t.frameWidth/2,y:t.frameHeight/2},a=Math.min(t.frameWidth,t.frameHeight),s=i!==void 0?{x:(i.left.x+i.right.x)/2,y:(i.left.y+i.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},d=i!==void 0?Math.hypot(i.right.x-i.left.x,i.right.y-i.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,u=Math.hypot(s.x-n.x,s.y-n.y),c=d<=0?0:1-S(u/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*d)),l=a>0?d/a:0;this.lastSizeDirection=l<this.t.SIZE_IDEAL_MIN?"far":l>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;l<this.t.SIZE_HARD_MIN||l>this.t.SIZE_HARD_MAX?f=0:l<this.t.SIZE_IDEAL_MIN?f=(l-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):l>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-l)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let h=1;if(i!==void 0){let p=Math.abs(Math.atan2(i.right.y-i.left.y,i.right.x-i.left.x))*180/Math.PI;h=1-S(p/this.t.ROLL_MAX_DEG)}return{center:s,iod:d,centering:c,size:f,pose:h}}motionOf(e,t,r){let i=this.lastCenter;if(this.lastCenter={...e,at:r},i===null||t<=0)return 1;let n=(r-i.at)/1e3;if(n<=0)return 1;let a=Math.hypot(e.x-i.x,e.y-i.y)/t/n;a<=this.t.MOTION_DEADBAND_IOD_PER_S&&(a=0);let s=1-Math.exp(-n/this.t.MOTION_TAU_S);return this.velocityEma=s*a+(1-s)*this.velocityEma,1-S(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,r){if(e.presence<=0)return"fcv3.no_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(t);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(r<this.t.Q_GOOD){let i=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],n=i[0];for(let a of i)e[a[0]]<e[n[0]]&&(n=a);return n[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(O[0]+O[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Re=["size","centering","pose","exposure","sharpness","motion"];function ke(o){if(o.accepted)return null;if(o.factors.presence<=0)return"no_face";let e="size";for(let t of Re)o.factors[t]<o.factors[e]&&(e=t);return e}var _=class{constructor(){this.blocked={};this.acceptedMs=0;this.ticks=0;this.lastAt=null}record(e){let t=this.lastAt===null?0:Math.max(0,e.at-this.lastAt);this.lastAt=e.at,this.ticks+=1;let r=ke(e);if(r===null){this.acceptedMs+=t;return}let i=this.blocked[r]??{count:0,ms:0};i.count+=1,i.ms+=t,this.blocked[r]=i}summary(){let e={};for(let[t,r]of Object.entries(this.blocked))e[t]={count:r.count,ms:Math.round(r.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var Ae=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ie=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^camera2? ?\d+, facing (front|back|external)/i,/facetime/i,/\b(integrated|built-in|builtin) (web)?cam(era)?\b/i,/\b(hd )?web ?cam\b/i,/\([0-9a-f]{4}:[0-9a-f]{4}\)\s*$/i];function De(o){let e=(o??"").trim().toLowerCase();return e.length===0?"unknown":Ae.some(t=>e.includes(t))?"known_virtual":Ie.some(t=>t.test(e))?"platform":"unknown"}function oe(o){if(typeof o!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(o))}catch{return!1}}function we(o=globalThis){return oe(o.navigator?.mediaDevices?.getUserMedia)&&oe(o.MediaStreamTrack?.prototype?.getSettings)}async function Oe(o,e=globalThis){let t=e.crypto?.subtle?.digest;if(typeof t=="function")try{let r=new Uint8Array(await t.call(e.crypto?.subtle,"SHA-256",new TextEncoder().encode(o)));return Array.from(r.subarray(0,8),i=>i.toString(16).padStart(2,"0")).join("")}catch{return}}async function ce(o,e=globalThis){let t={};try{t=typeof o.getSettings=="function"?o.getSettings()??{}:{}}catch{t={}}let r={};if((t.facingMode==="user"||t.facingMode==="environment"||t.facingMode==="left"||t.facingMode==="right")&&(r.facingMode=t.facingMode),typeof t.frameRate=="number"&&Number.isFinite(t.frameRate)&&(r.frameRate=t.frameRate),typeof t.width=="number"&&Number.isFinite(t.width)&&(r.width=t.width),typeof t.height=="number"&&Number.isFinite(t.height)&&(r.height=t.height),typeof t.deviceId=="string"&&t.deviceId.length>0){let n=await Oe(t.deviceId,e);n!==void 0&&(r.deviceIdHash=n)}let i;try{i=o.label}catch{i=void 0}return{trackSettings:r,capabilitiesPresent:typeof o.getCapabilities=="function",labelClass:De(i),prototypesIntact:we(e)}}var P=o=>Math.round(o*100)/100;function le(o){let e=o,t=typeof e?.requestVideoFrameCallback=="function",r=null,i=null,n=0,a=0,s=0,d=0,u=0,c=0,l=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((f,h)=>{if(r=null,!t)return;let p=h.presentationTime;if(i!==null){let m=p-i.presentationTimeMs;a+=1;let v=m-s;s+=v/a,d+=v*(m-s)}typeof h.captureTime=="number"&&Number.isFinite(h.captureTime)&&(u+=p-h.captureTime,c+=1),n+=1,i={mediaTimeMs:h.mediaTime*1e3,presentationTimeMs:p},l()}))};return l(),{latest:()=>i,stats:()=>({n,meanGapMs:a===0?0:P(s),stdGapMs:a<2?0:P(Math.sqrt(d/(a-1))),captureLatencyMs:c===0?null:P(u/c)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function ue(o,e,t){return{...o,rvfc:e,rampPainter:t}}var xe=1e3,G="fcv3.hold_upright",Pe=200,L=4,Ge=600,Le=1e3,de={sharpness:1,exposure:1,meanLuma:128};function Ve(o,e){return e.width=o.videoWidth,e.height=o.videoHeight,e.getContext("2d").drawImage(o,0,0),new Promise((t,r)=>e.toBlob(i=>i?t(i):r(new Error("empty-keyframe")),"image/jpeg",.92))}function Fe(){return N()==="phone"}var pe=class{constructor(e){this.handlers=new Map;this.stateValue="idle";this.attempt=0;this.stream=null;this.detector=null;this.scheduler=null;this.gate=null;this.profiler=null;this.lastGuidanceKey=null;this.positioningStartedAt=0;this.cameraRequestedAt=null;this.cameraReadyAt=null;this.faceAcquiredAt=null;this.captureCompleteAt=null;this.fired=!1;this.carriedDegrade=0;this.carriedMeans=[];this.blockStats=null;this.lastGateSnapshotAt=Number.NEGATIVE_INFINITY;this.uprightGuard=!1;this.trackProvenance=null;this.ramp=null;this.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>r?.delete(t)}emit(e,t){for(let r of[...this.handlers.get(e)??[]])r(t)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:t}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.uprightGuard=(t.isPhone??Fe)(),this.setState("preflight");let r=W();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let i=t.getUserMedia??(u=>navigator.mediaDevices.getUserMedia(u)),n;this.cameraRequestedAt=this.now();try{n=await i(F(H(),this.facing))}catch(u){if(e!==this.attempt)return;this.fail(q(u),{phase:"acquiring",name:k(u)});return}if(X(n),Z(n),e!==this.attempt){for(let u of n.getTracks())u.stop();return}this.stream=n;let a=n.getVideoTracks?.()[0];if(this.trackProvenance=a===void 0?null:ce(a).catch(()=>null),this.facing=U(n)??this.facing,t.video.srcObject=n,await t.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let u={v3AssetBaseUrl:t.v3AssetBaseUrl},c=t.createDetector??(t.createWorker!==void 0&&j()?async()=>{try{return await $.create(t.createWorker(),u)}catch{return w(u)}}:()=>w(u)),l;try{l=await c()}catch(f){e===this.attempt&&this.fail("models",{phase:"models",name:k(f)},f instanceof Q?f.fallbackReason:He(f));return}if(e!==this.attempt){l.destroy();return}this.detector=l,this.options.telemetry?.({type:"detector",tier:l.tier,fallbackReason:l.fallbackReason})}let s=J(),d=t.deviceClass??ee(s);this.profiler=new te(d),this.options.telemetry?.({type:"profile",staticClass:d,activeClass:this.profiler.deviceClass,simd:s.simd}),this.gate=new M(t.thresholds??{}),this.blockStats=new _,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(u=>V=u,()=>{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let t=this.profiler;if(t===null)return;if(this.scheduler!==null){let i=this.scheduler.stats();this.carriedDegrade+=i.degradeCount,i.meanDetectMs>0&&this.carriedMeans.push(i.meanDetectMs),this.scheduler.stop()}let r=new I({cadenceHz:t.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=r,r.start()}async detectTick(e){let{detector:t,gate:r,profiler:i}=this,n=this.options.video;if(e!==this.attempt||t===null||r===null||i===null||this.fired||n.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let a=i.deviceClass,s=this.now(),d=this.options.makeSnapshot?.(n,i.profile.inputWidth)??this.defaultSnapshot(n,i.profile.inputWidth),u=null;try{u=await t.detect(d,n.videoWidth,n.videoHeight)}catch{u=null}if(e!==this.attempt||this.fired)return;i.record(this.now()-s),i.deviceClass!==a&&this.startScheduler(e);let c=u===null?de:this.options.measureQuality?.(n,u.box)??this.defaultQuality(n,u.box),l=r.tick({timestampMs:this.now(),observation:u,quality:c,frameWidth:n.videoWidth,frameHeight:n.videoHeight});l.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=l.at),this.blockStats?.record(l),!l.ready&&l.at-this.lastGateSnapshotAt>=xe&&(this.lastGateSnapshotAt=l.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:l.p,q:l.q,factors:l.factors,attempt:e}),l.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=l.guidanceKey,this.emit("guidance",{key:l.guidanceKey})),l.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=l.at,this.fire(e))}async fire(e){let{options:t}=this,r=this.scheduler;r?.stop(),this.reportGate(!0);let i=r?.stats()??{degradeCount:0,meanDetectMs:0},n=[...this.carriedMeans,...i.meanDetectMs>0?[i.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+i.degradeCount,meanDetectMs:n.length===0?0:n.reduce((g,y)=>g+y,0)/n.length});let a=t.mode??"clip",s=t.rankKeyframes?.()&&V?V.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(a==="photo"){let g=this.watchRotation(e,null),y=await s;if(g(),e!==this.attempt)return;if(y===null){this.fail("generic",{phase:"keyframes"});return}let ve=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:y.blob,previewDataUrl:y.previewDataUrl,...ve});return}this.setState("recording");let d=t.createRecorder?.()??new A,u=this.stream;if(u===null){this.fail("generic",{phase:"recording"});return}let c=le(t.video),l=t.screenRamp?.(),f=l!==void 0,h=ae(l,{paint:g=>{(g===null||e===this.attempt)&&this.emit("ramp",{colour:g})},now:()=>this.now(),frames:c.latest});this.ramp=h;let p=()=>{c.stop(),h.stop(),this.ramp===h&&(this.ramp=null)},m=this.watchRotation(e,d),v=null;s.then(g=>{v=g},()=>{});let E=()=>{e===this.attempt&&v!==null&&this.emit("frozen",{previewDataUrl:v.previewDataUrl})},C,T;try{[C,T]=await Promise.all([d.record(u,E,()=>h.started(this.now())),s])}catch(g){if(m(),p(),e!==this.attempt)return;let y=g.kind;this.fail(y==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:k(g)});return}m();let me=c.stats();if(p(),e!==this.attempt)return;if(R(C.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(T===null){this.fail("generic",{phase:"keyframes"});return}let D=h.report(),fe=await this.provenance(me,f);e===this.attempt&&this.finishCapture({clip:C.blob,clipMimeType:C.mimeType,keyframe:T.blob,previewDataUrl:T.previewDataUrl,...D!==void 0&&D.rendered.length>0?{screenRamp:D}:{},...fe})}async provenance(e,t){let r=this.trackProvenance;if(r===null)return{};let i,n=new Promise(s=>{i=setTimeout(()=>s(null),Le)}),a=await Promise.race([r,n]);return clearTimeout(i),a===null?{}:{provenance:ue(a,e,t)}}isLandscape(){let e=this.options.video;return this.uprightGuard&&e.videoWidth>e.videoHeight}holdUpright(e){this.gate?.reset(),this.emit("checks",{engine:"v3",progress:0,q:0,factors:{presence:0,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==G&&(this.lastGuidanceKey=G,this.emit("guidance",{key:G}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,i=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){s();return}r.videoWidth>0&&this.isLandscape()&&(s(),this.abortRecording(e,t))},n=setInterval(i,Pe);r.addEventListener?.("resize",i);let a=!1;function s(){a||(a=!0,clearInterval(n),r.removeEventListener?.("resize",i))}return s}abortRecording(e,t){if(e!==this.attempt)return;this.attempt+=1;let r=this.attempt;try{t?.stop()}catch{}this.ramp?.stop(),this.ramp=null,this.fired=!1,this.captureCompleteAt=null,this.gate=new M(this.options.thresholds??{}),this.blockStats=new _,this.lastGateSnapshotAt=this.now(),this.lastGuidanceKey=null,this.setState("positioning"),this.positioningStartedAt=this.now(),this.holdUpright(r),this.startScheduler(r)}async collectKeyframes(e){let t=this.options.captureKeyframe??(n=>this.defaultKeyframe(n)),r=Ge/(L-1),i=null;for(let n=0;n<L;n+=1){if(e!==this.attempt)return i;try{let a=await t(this.options.video);(i===null||a.sharpness>i.sharpness)&&(i=a)}catch{}n<L-1&&await Ne(r)}return i}finishCapture(e){this.stopTracks(),this.setState("captured");let t=this.captureTiming();this.emit("artifacts",t===void 0?e:{...e,timing:t})}captureTiming(){let e={},t=(r,i,n)=>{i!==null&&n!==null&&(e[r]=Math.max(0,Math.round(n-i)))};return t("cameraReadyMs",this.cameraRequestedAt,this.cameraReadyAt),t("faceAcquireMs",this.cameraReadyAt,this.faceAcquiredAt),t("captureMs",this.faceAcquiredAt,this.captureCompleteAt),Object.keys(e).length>0?e:void 0}async defaultKeyframe(e){let t=document.createElement("canvas"),r=await(this.facing==="user"?se:Ve)(e,t),i=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:i,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),i=t/Math.max(1,e.videoWidth),n=Math.max(1,Math.round(e.videoWidth*i)),a=Math.max(1,Math.round(e.videoHeight*i)),s=r.getContext("2d");return s===null?e:(r.width!==n&&(r.width=n),r.height!==a&&(r.height=a),s.drawImage(e,0,0,n,a),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,t){let r=he(e,t,96);return r===null?de:{sharpness:x(r),exposure:ie(r),meanLuma:re(r)}}centerSharpness(e){let t=Y(e),r=he(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:x(r)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.ramp?.stop(),this.ramp=null,this.stopTracks()}reportGate(e){let t=this.blockStats,r=this.profiler;if(t===null||r===null)return;let i=t.summary();e&&(this.blockStats=null),i.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...i})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t,r){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:r});let{phase:i,name:n}=t;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:n===void 0?{phase:i}:{phase:i,name:n}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},V;function Ne(o){return new Promise(e=>setTimeout(e,o))}function He(o){return o instanceof Error?o.message:String(o)}function he(o,e,t){try{let r=document.createElement("canvas"),i=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*i)),r.height=Math.max(1,Math.round(e.height*i));let n=r.getContext("2d");return n===null?null:(n.drawImage(o,e.x,e.y,e.width,e.height,0,0,r.width,r.height),n.getImageData(0,0,r.width,r.height))}catch{return null}}export{ge as a,be as b,ye as c,ne as d,b as e,A as f,Be as g,We as h,Se as i,ze as j,se as k,I as l,Te as m,M as n,ke as o,_ as p,xe as q,G as r,Pe as s,L as t,Ge as u,Le as v,pe as w};
1
+ import{a as F,c as N,d as H,e as U}from"./chunk-FUHDOEBP.js";import{b as J,c as ee,d as te}from"./chunk-POIQGEZM.js";import{b as K,c as B,e as W,g as z,h as R,k,m as q,n as Z}from"./chunk-CQ7SKLMC.js";import{b as O,c as re,d as x,e as ie}from"./chunk-FPXL63KZ.js";import{d as X}from"./chunk-ZLWH4RBO.js";import{c as Q,d as Y,f as w,h as j,j as $}from"./chunk-OKWG3PVH.js";var ge=2500,be=1e3,ye=1500,ne=25e5,b=class extends Error{constructor(e,t){super(t??e),this.kind=e}},A=class{constructor(){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.settled=!1}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.hardStopTimer=null,this.graceTimer=null}record(e,t,r){if(this.recorder&&!this.settled)return Promise.reject(new b("generic","record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time"));this.recorder=null,this.clearTimers(),this.chunks=[],this.bytes=0,this.settled=!1,this.stream=e;let i=K();return new Promise((n,a)=>{let s;try{s=new MediaRecorder(e,i?{mimeType:i,videoBitsPerSecond:ne}:{videoBitsPerSecond:ne})}catch{try{s=new MediaRecorder(e)}catch{a(new b("unsupported"));return}}this.recorder=s;let d=c=>{this.settled||(this.settled=!0,this.clearTimers(),c())},u=()=>d(()=>{let c=s.mimeType||i||B,l=new Blob(this.chunks,{type:c});if(l.size===0){a(new b("generic","empty clip"));return}if(R(l)){a(new b("cliptoolarge"));return}n({blob:l,mimeType:c})});if(s.ondataavailable=c=>{c.data&&c.data.size&&(this.chunks.push(c.data),this.bytes+=c.data.size,this.bytes>z&&d(()=>{try{s.state!=="inactive"&&s.stop()}catch{}a(new b("cliptoolarge"))}))},s.onstop=u,s.onerror=()=>d(()=>a(new b("generic"))),r!==void 0){let c=!1;s.onstart=()=>{if(!(c||this.settled)){c=!0;try{r()}catch{}}}}try{s.start(be)}catch{d(()=>a(new b("generic")));return}this.hardStopTimer=setTimeout(()=>{if(this.settled||t?.(),s.state!=="inactive"){try{s.stop()}catch{u()}this.graceTimer=setTimeout(u,ye)}else u()},ge)})}stop(e){this.clearTimers();let t=this.recorder;if(t&&t.state!=="inactive")try{t.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(i=>i.stop()),this.stream=null}};var Be=400,We=2e3,Se=["rose","peach","sand","mint","sky","lilac"],Ee={rose:"rgb(255, 185, 205)",peach:"rgb(245, 193, 159)",sand:"rgb(195, 210, 158)",mint:"rgb(139, 219, 203)",sky:"rgb(140, 214, 249)",lilac:"rgb(208, 197, 249)"};function ze(o){return Ee[o]}var Me=4,_e=4;function Ce(o){if(typeof o!="object"||o===null)return!1;let e=o;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length!==3||!e.colours.every(r=>Se.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==3)return!1;let t=-1;for(let r of e.onsetsMs){if(typeof r!="number"||!Number.isFinite(r)||r<=t||r>=2e3)return!1;t=r}return!0}function ae(o,e){let t=e.now??(()=>performance.now()),r=Ce(o)?o:void 0,i=[],n=null,a=null,s=null,d=!1,u=null,c=p=>{u=p;try{e.paint(p)}catch{}},l=p=>{let m=e.frames?.()??null;return m!==null&&s!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-s:p-(a??p)},f=(p,m,v=0)=>{if(d)return;let E=Math.max(0,p-l(t()));n=setTimeout(()=>{if(n=null,!d){if(v<Me&&l(t())<p-_e){f(p,m,v+1);return}m()}},E)},h=p=>{if(r!==void 0){if(p>=3){f(2e3,()=>c(null));return}f(r.onsetsMs[p],()=>{let m=l(t());if(m>2e3){u!==null&&c(null);return}let v=r.colours[p];c(v);let E=i.length===0?0:i[i.length-1].tMs;i.push({tMs:Math.max(E,Math.round(m)),colour:v}),h(p+1)})}};return{started(p){if(r===void 0||d||a!==null)return;a=p;let m=e.frames?.()??null;s=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),h(0)},stop(){d||(d=!0,n!==null&&clearTimeout(n),n=null,u!==null&&c(null))},report(){return r===void 0?void 0:{nonce:r.nonce,rendered:[...i]}}}}function se(o,e,t=.92){return new Promise((r,i)=>{let n=o.videoWidth,a=o.videoHeight;if(!n||!a){i(new Error("video-not-ready"));return}let s=e.getContext("2d");if(!s){i(new Error("no-2d-context"));return}e.width=n,e.height=a,s.scale(-1,1),s.drawImage(o,-n,0),e.toBlob(d=>d?r(d):i(new Error("empty-keyframe")),"image/jpeg",t)})}var I=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let t=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),t()}))};t();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((t,r)=>t+r,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var Te=Object.freeze({Q_GOOD:.6,RISE_PER_S:.9,FALL_PER_S:.25,CENTER_FALLOFF_IOD_MULTIPLE:1.35,BOX_EYE_OFFSET_FACTOR:.12,IOD_BOX_PROXY_FACTOR:.42,SIZE_IDEAL_MIN:.12,SIZE_IDEAL_MAX:.3,SIZE_HARD_MIN:.08,SIZE_HARD_MAX:.45,ROLL_MAX_DEG:25,MOTION_VELOCITY_IOD_PER_S:.5,MOTION_TAU_S:.4,MOTION_DEADBAND_IOD_PER_S:.1,READY_WINDOW_MS:500,GUIDE_SIZE:.6,GUIDE_CENTERING:.6,GUIDE_POSE:.6,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,GUIDE_MOTION:.5}),S=o=>Math.min(1,Math.max(0,o)),M=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...Te,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:t,quality:r,timestampMs:i}=e,n=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let a={presence:0,centering:0,size:0,pose:0,sharpness:S(r.sharpness),exposure:S(r.exposure),motion:1};if(t!==null){a.presence=1;let c=this.geometryOf(t,e);a.centering=c.centering,a.size=c.size,a.pose=c.pose,a.motion=this.motionOf(c.center,c.iod,i)}else this.lastCenter=null,this.velocityEma=0;let s=Math.min(a.presence,a.centering,a.size,a.pose,a.sharpness,a.exposure,a.motion);this.p=S(this.p+(s>=this.t.Q_GOOD?this.t.RISE_PER_S*s:-this.t.FALL_PER_S*(1-s))*n),this.qWindow.push({at:i,q:s}),this.qWindow=this.qWindow.filter(c=>c.at>=i-this.t.READY_WINDOW_MS);let d=this.qWindow.map(c=>c.q);if(d.length>=3){let c=Math.min(...d),l=d.indexOf(c);d=d.filter((f,h)=>h!==l)}let u=this.p>=1&&d.every(c=>c>=this.t.Q_GOOD);return{at:i,q:s,p:this.p,factors:a,guidanceKey:this.guidanceOf(a,r,s),ready:u,accepted:s>=this.t.Q_GOOD}}geometryOf(e,t){let{box:r,eyes:i}=e,n={x:t.frameWidth/2,y:t.frameHeight/2},a=Math.min(t.frameWidth,t.frameHeight),s=i!==void 0?{x:(i.left.x+i.right.x)/2,y:(i.left.y+i.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},d=i!==void 0?Math.hypot(i.right.x-i.left.x,i.right.y-i.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,u=Math.hypot(s.x-n.x,s.y-n.y),c=d<=0?0:1-S(u/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*d)),l=a>0?d/a:0;this.lastSizeDirection=l<this.t.SIZE_IDEAL_MIN?"far":l>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;l<this.t.SIZE_HARD_MIN||l>this.t.SIZE_HARD_MAX?f=0:l<this.t.SIZE_IDEAL_MIN?f=(l-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):l>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-l)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let h=1;if(i!==void 0){let p=Math.abs(Math.atan2(i.right.y-i.left.y,i.right.x-i.left.x))*180/Math.PI;h=1-S(p/this.t.ROLL_MAX_DEG)}return{center:s,iod:d,centering:c,size:f,pose:h}}motionOf(e,t,r){let i=this.lastCenter;if(this.lastCenter={...e,at:r},i===null||t<=0)return 1;let n=(r-i.at)/1e3;if(n<=0)return 1;let a=Math.hypot(e.x-i.x,e.y-i.y)/t/n;a<=this.t.MOTION_DEADBAND_IOD_PER_S&&(a=0);let s=1-Math.exp(-n/this.t.MOTION_TAU_S);return this.velocityEma=s*a+(1-s)*this.velocityEma,1-S(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,r){if(e.presence<=0)return"fcv3.no_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(t);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(r<this.t.Q_GOOD){let i=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],n=i[0];for(let a of i)e[a[0]]<e[n[0]]&&(n=a);return n[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(O[0]+O[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Re=["size","centering","pose","exposure","sharpness","motion"];function ke(o){if(o.accepted)return null;if(o.factors.presence<=0)return"no_face";let e="size";for(let t of Re)o.factors[t]<o.factors[e]&&(e=t);return e}var _=class{constructor(){this.blocked={};this.acceptedMs=0;this.ticks=0;this.lastAt=null}record(e){let t=this.lastAt===null?0:Math.max(0,e.at-this.lastAt);this.lastAt=e.at,this.ticks+=1;let r=ke(e);if(r===null){this.acceptedMs+=t;return}let i=this.blocked[r]??{count:0,ms:0};i.count+=1,i.ms+=t,this.blocked[r]=i}summary(){let e={};for(let[t,r]of Object.entries(this.blocked))e[t]={count:r.count,ms:Math.round(r.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var Ae=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ie=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^camera2? ?\d+, facing (front|back|external)/i,/facetime/i,/\b(integrated|built-in|builtin) (web)?cam(era)?\b/i,/\b(hd )?web ?cam\b/i,/\([0-9a-f]{4}:[0-9a-f]{4}\)\s*$/i];function De(o){let e=(o??"").trim().toLowerCase();return e.length===0?"unknown":Ae.some(t=>e.includes(t))?"known_virtual":Ie.some(t=>t.test(e))?"platform":"unknown"}function oe(o){if(typeof o!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(o))}catch{return!1}}function we(o=globalThis){return oe(o.navigator?.mediaDevices?.getUserMedia)&&oe(o.MediaStreamTrack?.prototype?.getSettings)}async function Oe(o,e=globalThis){let t=e.crypto?.subtle?.digest;if(typeof t=="function")try{let r=new Uint8Array(await t.call(e.crypto?.subtle,"SHA-256",new TextEncoder().encode(o)));return Array.from(r.subarray(0,8),i=>i.toString(16).padStart(2,"0")).join("")}catch{return}}async function ce(o,e=globalThis){let t={};try{t=typeof o.getSettings=="function"?o.getSettings()??{}:{}}catch{t={}}let r={};if((t.facingMode==="user"||t.facingMode==="environment"||t.facingMode==="left"||t.facingMode==="right")&&(r.facingMode=t.facingMode),typeof t.frameRate=="number"&&Number.isFinite(t.frameRate)&&(r.frameRate=t.frameRate),typeof t.width=="number"&&Number.isFinite(t.width)&&(r.width=t.width),typeof t.height=="number"&&Number.isFinite(t.height)&&(r.height=t.height),typeof t.deviceId=="string"&&t.deviceId.length>0){let n=await Oe(t.deviceId,e);n!==void 0&&(r.deviceIdHash=n)}let i;try{i=o.label}catch{i=void 0}return{trackSettings:r,capabilitiesPresent:typeof o.getCapabilities=="function",labelClass:De(i),prototypesIntact:we(e)}}var P=o=>Math.round(o*100)/100;function le(o){let e=o,t=typeof e?.requestVideoFrameCallback=="function",r=null,i=null,n=0,a=0,s=0,d=0,u=0,c=0,l=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((f,h)=>{if(r=null,!t)return;let p=h.presentationTime;if(i!==null){let m=p-i.presentationTimeMs;a+=1;let v=m-s;s+=v/a,d+=v*(m-s)}typeof h.captureTime=="number"&&Number.isFinite(h.captureTime)&&(u+=p-h.captureTime,c+=1),n+=1,i={mediaTimeMs:h.mediaTime*1e3,presentationTimeMs:p},l()}))};return l(),{latest:()=>i,stats:()=>({n,meanGapMs:a===0?0:P(s),stdGapMs:a<2?0:P(Math.sqrt(d/(a-1))),captureLatencyMs:c===0?null:P(u/c)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function ue(o,e,t){return{...o,rvfc:e,rampPainter:t}}var xe=1e3,G="fcv3.hold_upright",Pe=200,L=4,Ge=600,Le=1e3,de={sharpness:1,exposure:1,meanLuma:128};function Ve(o,e){return e.width=o.videoWidth,e.height=o.videoHeight,e.getContext("2d").drawImage(o,0,0),new Promise((t,r)=>e.toBlob(i=>i?t(i):r(new Error("empty-keyframe")),"image/jpeg",.92))}function Fe(){return N()==="phone"}var pe=class{constructor(e){this.handlers=new Map;this.stateValue="idle";this.attempt=0;this.stream=null;this.detector=null;this.scheduler=null;this.gate=null;this.profiler=null;this.lastGuidanceKey=null;this.positioningStartedAt=0;this.cameraRequestedAt=null;this.cameraReadyAt=null;this.faceAcquiredAt=null;this.captureCompleteAt=null;this.fired=!1;this.carriedDegrade=0;this.carriedMeans=[];this.blockStats=null;this.lastGateSnapshotAt=Number.NEGATIVE_INFINITY;this.uprightGuard=!1;this.trackProvenance=null;this.ramp=null;this.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>r?.delete(t)}emit(e,t){for(let r of[...this.handlers.get(e)??[]])r(t)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:t}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.uprightGuard=(t.isPhone??Fe)(),this.setState("preflight");let r=W();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let i=t.getUserMedia??(u=>navigator.mediaDevices.getUserMedia(u)),n;this.cameraRequestedAt=this.now();try{n=await i(F(H(),this.facing))}catch(u){if(e!==this.attempt)return;this.fail(q(u),{phase:"acquiring",name:k(u)});return}if(X(n),Z(n),e!==this.attempt){for(let u of n.getTracks())u.stop();return}this.stream=n;let a=n.getVideoTracks?.()[0];if(this.trackProvenance=a===void 0?null:ce(a).catch(()=>null),this.facing=U(n)??this.facing,t.video.srcObject=n,await t.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let u={v3AssetBaseUrl:t.v3AssetBaseUrl},c=t.createDetector??(t.createWorker!==void 0&&j()?async()=>{try{return await $.create(t.createWorker(),u)}catch{return w(u)}}:()=>w(u)),l;try{l=await c()}catch(f){e===this.attempt&&this.fail("models",{phase:"models",name:k(f)},f instanceof Q?f.fallbackReason:He(f));return}if(e!==this.attempt){l.destroy();return}this.detector=l,this.options.telemetry?.({type:"detector",tier:l.tier,fallbackReason:l.fallbackReason})}let s=J(),d=t.deviceClass??ee(s);this.profiler=new te(d),this.options.telemetry?.({type:"profile",staticClass:d,activeClass:this.profiler.deviceClass,simd:s.simd}),this.gate=new M(t.thresholds??{}),this.blockStats=new _,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(u=>V=u,()=>{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let t=this.profiler;if(t===null)return;if(this.scheduler!==null){let i=this.scheduler.stats();this.carriedDegrade+=i.degradeCount,i.meanDetectMs>0&&this.carriedMeans.push(i.meanDetectMs),this.scheduler.stop()}let r=new I({cadenceHz:t.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=r,r.start()}async detectTick(e){let{detector:t,gate:r,profiler:i}=this,n=this.options.video;if(e!==this.attempt||t===null||r===null||i===null||this.fired||n.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let a=i.deviceClass,s=this.now(),d=this.options.makeSnapshot?.(n,i.profile.inputWidth)??this.defaultSnapshot(n,i.profile.inputWidth),u=null;try{u=await t.detect(d,n.videoWidth,n.videoHeight)}catch{u=null}if(e!==this.attempt||this.fired)return;i.record(this.now()-s),i.deviceClass!==a&&this.startScheduler(e);let c=u===null?de:this.options.measureQuality?.(n,u.box)??this.defaultQuality(n,u.box),l=r.tick({timestampMs:this.now(),observation:u,quality:c,frameWidth:n.videoWidth,frameHeight:n.videoHeight});l.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=l.at),this.blockStats?.record(l),!l.ready&&l.at-this.lastGateSnapshotAt>=xe&&(this.lastGateSnapshotAt=l.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:l.p,q:l.q,factors:l.factors,attempt:e}),l.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=l.guidanceKey,this.emit("guidance",{key:l.guidanceKey})),l.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=l.at,this.fire(e))}async fire(e){let{options:t}=this,r=this.scheduler;r?.stop(),this.reportGate(!0);let i=r?.stats()??{degradeCount:0,meanDetectMs:0},n=[...this.carriedMeans,...i.meanDetectMs>0?[i.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+i.degradeCount,meanDetectMs:n.length===0?0:n.reduce((g,y)=>g+y,0)/n.length});let a=t.mode??"clip",s=t.rankKeyframes?.()&&V?V.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(a==="photo"){let g=this.watchRotation(e,null),y=await s;if(g(),e!==this.attempt)return;if(y===null){this.fail("generic",{phase:"keyframes"});return}let ve=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:y.blob,previewDataUrl:y.previewDataUrl,...ve});return}this.setState("recording");let d=t.createRecorder?.()??new A,u=this.stream;if(u===null){this.fail("generic",{phase:"recording"});return}let c=le(t.video),l=t.screenRamp?.(),f=l!==void 0,h=ae(l,{paint:g=>{(g===null||e===this.attempt)&&this.emit("ramp",{colour:g})},now:()=>this.now(),frames:c.latest});this.ramp=h;let p=()=>{c.stop(),h.stop(),this.ramp===h&&(this.ramp=null)},m=this.watchRotation(e,d),v=null;s.then(g=>{v=g},()=>{});let E=()=>{e===this.attempt&&v!==null&&this.emit("frozen",{previewDataUrl:v.previewDataUrl})},C,T;try{[C,T]=await Promise.all([d.record(u,E,()=>h.started(this.now())),s])}catch(g){if(m(),p(),e!==this.attempt)return;let y=g.kind;this.fail(y==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:k(g)});return}m();let me=c.stats();if(p(),e!==this.attempt)return;if(R(C.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(T===null){this.fail("generic",{phase:"keyframes"});return}let D=h.report(),fe=await this.provenance(me,f);e===this.attempt&&this.finishCapture({clip:C.blob,clipMimeType:C.mimeType,keyframe:T.blob,previewDataUrl:T.previewDataUrl,...D!==void 0&&D.rendered.length>0?{screenRamp:D}:{},...fe})}async provenance(e,t){let r=this.trackProvenance;if(r===null)return{};let i,n=new Promise(s=>{i=setTimeout(()=>s(null),Le)}),a=await Promise.race([r,n]);return clearTimeout(i),a===null?{}:{provenance:ue(a,e,t)}}isLandscape(){let e=this.options.video;return this.uprightGuard&&e.videoWidth>e.videoHeight}holdUpright(e){this.gate?.reset(),this.emit("checks",{engine:"v3",progress:0,q:0,factors:{presence:0,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==G&&(this.lastGuidanceKey=G,this.emit("guidance",{key:G}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,i=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){s();return}r.videoWidth>0&&this.isLandscape()&&(s(),this.abortRecording(e,t))},n=setInterval(i,Pe);r.addEventListener?.("resize",i);let a=!1;function s(){a||(a=!0,clearInterval(n),r.removeEventListener?.("resize",i))}return s}abortRecording(e,t){if(e!==this.attempt)return;this.attempt+=1;let r=this.attempt;try{t?.stop()}catch{}this.ramp?.stop(),this.ramp=null,this.fired=!1,this.captureCompleteAt=null,this.gate=new M(this.options.thresholds??{}),this.blockStats=new _,this.lastGateSnapshotAt=this.now(),this.lastGuidanceKey=null,this.setState("positioning"),this.positioningStartedAt=this.now(),this.holdUpright(r),this.startScheduler(r)}async collectKeyframes(e){let t=this.options.captureKeyframe??(n=>this.defaultKeyframe(n)),r=Ge/(L-1),i=null;for(let n=0;n<L;n+=1){if(e!==this.attempt)return i;try{let a=await t(this.options.video);(i===null||a.sharpness>i.sharpness)&&(i=a)}catch{}n<L-1&&await Ne(r)}return i}finishCapture(e){this.stopTracks(),this.setState("captured");let t=this.captureTiming();this.emit("artifacts",t===void 0?e:{...e,timing:t})}captureTiming(){let e={},t=(r,i,n)=>{i!==null&&n!==null&&(e[r]=Math.max(0,Math.round(n-i)))};return t("cameraReadyMs",this.cameraRequestedAt,this.cameraReadyAt),t("faceAcquireMs",this.cameraReadyAt,this.faceAcquiredAt),t("captureMs",this.faceAcquiredAt,this.captureCompleteAt),Object.keys(e).length>0?e:void 0}async defaultKeyframe(e){let t=document.createElement("canvas"),r=await(this.facing==="user"?se:Ve)(e,t),i=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:i,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),i=t/Math.max(1,e.videoWidth),n=Math.max(1,Math.round(e.videoWidth*i)),a=Math.max(1,Math.round(e.videoHeight*i)),s=r.getContext("2d");return s===null?e:(r.width!==n&&(r.width=n),r.height!==a&&(r.height=a),s.drawImage(e,0,0,n,a),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,t){let r=he(e,t,96);return r===null?de:{sharpness:x(r),exposure:ie(r),meanLuma:re(r)}}centerSharpness(e){let t=Y(e),r=he(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:x(r)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.ramp?.stop(),this.ramp=null,this.stopTracks()}reportGate(e){let t=this.blockStats,r=this.profiler;if(t===null||r===null)return;let i=t.summary();e&&(this.blockStats=null),i.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...i})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t,r){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:r});let{phase:i,name:n}=t;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:n===void 0?{phase:i}:{phase:i,name:n}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},V;function Ne(o){return new Promise(e=>setTimeout(e,o))}function He(o){return o instanceof Error?o.message:String(o)}function he(o,e,t){try{let r=document.createElement("canvas"),i=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*i)),r.height=Math.max(1,Math.round(e.height*i));let n=r.getContext("2d");return n===null?null:(n.drawImage(o,e.x,e.y,e.width,e.height,0,0,r.width,r.height),n.getImageData(0,0,r.width,r.height))}catch{return null}}export{ge as a,be as b,ye as c,ne as d,b as e,A as f,Be as g,We as h,Se as i,ze as j,se as k,I as l,Te as m,M as n,ke as o,_ as p,xe as q,G as r,Pe as s,L as t,Ge as u,Le as v,pe as w};
@@ -1 +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};
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-W2WD7PR2.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-QA4DOFRF.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-QA4DOFRF.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};
@@ -1 +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};
1
+ 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 ue,d as ce}from"./chunk-CJHMFPL6.js";import{a as se}from"./chunk-RI3E7GBN.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 Ee,B as Te,a as Re,b as Ie,c as Ae,d as ee,e as Oe,f as we,h as D,i as H,j as G,k as Me,l as E,m as K,n as b,o as q,p as x,q as te,r as w,s as N}from"./chunk-5ZKQHFFW.js";import{n as xe}from"./chunk-W2WD7PR2.js";import{a as be}from"./chunk-GT2ZLGF7.js";import{c as Pe,d as X}from"./chunk-FUHDOEBP.js";import{c as z,g as ve,h as Y}from"./chunk-NJML6FMD.js";function Z(e){return e.idNumberBound??e.nniBound}function L(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 it="https://api.sekyro.ai",rt=5e3,st=1500,at=10;function ct(e){return new Promise(t=>setTimeout(t,e))}function ut(){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 i=0;i<16;i+=1)t[i]=Math.floor(Math.random()*256);t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let o=[...t].map(i=>i.toString(16).padStart(2,"0")).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function Qt(e){return dt(e,{})}function dt(e,t){let o=e.apiOrigin??it,i=e.autoRetry??!0,r=e.rearm??"auto",s=t.client??new ve({apiOrigin:o,sessionToken:e.clientToken,fetch:e.fetch}),u=t.sleep??ct,a=t.uuid??ut,l=t.getTurnstileToken??((n,c)=>import("./turnstile-FATNZ4AG.js").then(p=>p.executeTurnstile(n,c))),f=be(),m=null,g=null,d=!1,k=new AbortController,h=null,A=null,U=null,se=()=>Oe(ee(h),U),v=n=>{h=n,f.emit("view",n),m?.onView(n)},_=()=>h!==null?Promise.resolve(h):(A??(A=s.getSession().then(n=>(v(n),n)).finally(()=>{A=null})),A),R=async()=>{let n=await s.getSession();return v(n),n},W=async(n,c)=>{n.plan!==void 0?v(n):await R()},$=null,ae=async n=>{let c=await _();if(!n&&c.consentRecorded)return;let p=await s.recordConsent(e.locale);p.plan!==void 0?v(p):h!==null&&v({...h,consentRecorded:!0})},M=n=>n?.force===!0?ae(!0):($??($=ae(!1).finally(()=>{$=null})),$),J={client:s,ensureConsent:n=>M(n),sleep:u,uuid:a,...t.random!==void 0?{random:t.random}:{},onBusy:n=>{d||f.emit("busy",n)}},ce=!1,ue=null,Q=n=>{if(n.status==="approved"||n.status==="rejected"||n.status==="review"){if(ce)return;ce=!0}ue=JSON.stringify(n),f.emit("result",n)},Ye=n=>{ue!==JSON.stringify(n)&&Q(n)},de=async n=>{let c=h;n&&(c=await R().catch(()=>h));let p=c===null?null:E(c);return p!==null&&!d&&f.emit("method",p),p!==null},le=null,pe=!1,fe=!1,me=()=>Ee(J,(n,c)=>n.submitCheck("population_registry",{},{idempotencyKey:c})),he=n=>Z(n)===!0||L(x(n,"population_registry"))===!0,Ze=async()=>{try{let n=await _();if(b(n)||E(n)!==null||q(n)?.checkType!=="population_registry")return;if(!he(n)&&L(x(n,"population_registry"))===void 0&&(n=await R()),!he(n)){fe=!0;return}await M(),await W(await me(),"population_registry");let c=h===null?void 0:x(h,"population_registry");if(c?.state==="input_required"&&c.reason==="registry_unavailable"&&G(c)>0){if(await u(rt),d)return;await W(await me(),"population_registry")}}catch(n){if(n instanceof z&&(n.code==="check_not_active"||n.code==="step_not_on_path")){await R().catch(()=>{});return}pe=!0;return}h!==null&&b(h)&&Q(N(h,{autoRetry:i}))},Se=()=>(le??(le=Ze()),le),We=async()=>{let c=(await _()).turnstileSiteKey;return c===null?{sandbox:!0}:{channel:"hosted_web",siteKey:c,turnstileToken:await l(c,{signal:k.signal})}},F=n=>{if(d)return;let c=s.reportCaptureIssue;if(c===void 0)return;let p=n.formFactor;try{p??(p=Pe())}catch{}try{Promise.resolve(c.call(s,{...n,...p!==void 0?{formFactor:p}:{}})).catch(()=>{})}catch{}},P=null,ye=Promise.resolve(),V=0,$e=async()=>{let n=await _();for(let c=0;c<at&&!d&&!b(n)&&q(n)===void 0&&H(n).some(p=>p.state==="processing")&&(await u(st),!d);c+=1)n=await R();return n},Je=async(n,c,p)=>{let{capture:C}=n,y=()=>d,B=()=>n.alive&&n.attempt===p,ke=S=>{B()&&C.setFlowState(S)},O=S=>{if(!y()&&(S.status==="unavailable"&&S.reason!==void 0&&!Re(S.reason)&&F({check:"liveness",kind:"unavailable",phase:"upload",engineKind:S.reason,attempt:Math.max(0,n.issues.value)}),Q(S),!!B())){if(S.status==="retry"&&r==="auto"){C.handle.retry();return}C.setFlowState("done")}};if(c.degraded==="NO_RECORDER"){let S=h?.sessionId??(await _().catch(()=>null))?.sessionId??"";O(w(S,"no_recorder"));return}ke("uploading");try{if(await Se(),y())return;let S=await _(),_e;if(!b(S)&&E(S)!==null){await de(!1),O(w(S.sessionId,"method_required"));return}if(!b(S)){if(q(S)?.checkType==="population_registry"){O(w(S.sessionId,fe?"nni_unbound":pe?"network":"registry_unavailable"));return}if(await M(),y())return;_e=h??S;let j=await Te({...J,artifacts:c,getAttestation:We,getView:()=>h??S,refreshView:R,applySubmit:W,onPhase:ke,isCancelled:y,onKeyframePromoted:ot=>{g=ot}});if(y())return;if(j.kind==="unavailable"){O(w(S.sessionId,j.reason));return}if(j.kind==="resync"&&await R(),h!==null&&E(h)!==null){await de(!1),O(w(S.sessionId,"method_required"));return}S=await $e()}O(N(S,{autoRetry:i,previous:_e}))}catch{if(y())return;O(w(h?.sessionId??"","network"))}},Qe=(n,c)=>{let p=n.attempt;V>0&&n.alive&&n.capture.setFlowState("uploading"),V+=1,ye=ye.then(()=>Je(n,c,p)).finally(()=>{V-=1,V===0&&m?.onChainIdle()}).catch(()=>{})},ge=n=>{P?.capture.handle.destroy(),P!==null&&(P.alive=!1);let c=xe(n,m?.captureInternals?.(n)??t.capture,()=>h?.capture?.liveness?.keyframe?.rank===!0,se,()=>h?.capture?.liveness?.screenRamp),p={capture:c,alive:!0,attempt:0,issues:Ae()};P=p,c.handle.on("error",y=>{F(Ie("liveness",y,p.issues.value))}),c.handle.on("state",y=>{p.issues.note(y),y==="starting"&&(p.attempt+=1)}),c.handle.on("captured",y=>{Promise.resolve().then(()=>Qe(p,y))});let C=c.handle;return{get state(){return C.state},get captureMode(){return C.captureMode},get facingMode(){return C.facingMode},on:(y,B)=>C.on(y,B),start:async y=>{if(h===null&&await _().catch(()=>{}),!!p.alive)return C.start(y)},retry:()=>C.retry(),switchCamera:()=>C.switchCamera(),destroy:()=>{p.alive=!1,P===p&&(P=null),C.destroy()}}},je=async()=>{if(d)return null;try{let n=await _();return d?null:E(n)}catch{return null}},Xe=async()=>{if(d)return"self";try{let n=await _();if(d)return"self";let c=ee(n);return c==="choice"?U??c:c}catch{return"self"}},ze=async()=>{if(d)return!1;try{let n=await _();if(d||b(n))return!1;let c=x(n,"liveness");return K(c)&&c?.requiresMobile===!0&&!X()}catch{return!1}},et=async()=>{if(d)return!1;try{let n=await _();return!d&&n.returning===!0}catch{return!1}},tt=async n=>{let c=(await _()).plan?.choice,p=c?.options.find(y=>D[y.service]===n);if(!p)throw new RangeError(`method ${String(n)} is not offered`);let C=await s.choose(c.nodeId,p.id);d||v(C)},Ce=null,nt=()=>(Ce??(Ce=import("./plan-runner-35655N4Z.js").then(n=>{let c=n.createPlanRunner({runtime:J,currentView:()=>h,cameraMode:se,ensureView:_,refreshView:R,ensureConsent:()=>M(),liveness:ge,chainBusy:()=>V>0,destroyed:()=>d,sleep:u,isMobile:X,now:t.now??Date.now,keptFaceKey:()=>g,setView:v,baseCapture:t.capture,emitStep:p=>{d||f.emit("step",p)},emitResult:Ye,reportCaptureIssue:F,documentInternals:t.document,portraitInternals:t.portrait,livePhotoInternals:t.livePhoto,uploadInternals:t.upload});return m=c,c})),Ce);return{consent:()=>M(),startRegistry:Se,methodChoice:je,selectMethod:tt,reportCameraUnavailable:async n=>{await M();let c=s.reportCameraUnavailable;if(c===void 0)throw new TypeError("this client cannot report a missing camera");let p=await c.call(s,n).catch(C=>{if(C instanceof z&&C.code==="check_out_of_order")return s.getSession();throw C});d||v(p)},reportCaptureIssue:F,mobileRequired:ze,captureMode:Xe,chooseCaptureMode:n=>{U=n},get captureChoice(){return U},returning:et,liveness:ge,run:async()=>{if(d)throw new Error("verification destroyed");return(await nt()).run()},currentStep:()=>m?.current()??null,voiceClips:async()=>{if(d)return null;try{let n=await _();return d?null:n.voice??null}catch{return null}},on:(n,c)=>f.on(n,c),destroy:()=>{d=!0,k.abort(),m?.destroy(),P!==null&&(P.alive=!1,P.capture.handle.destroy(),P=null),f.clear()}}}var De=["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 lt=["carte_identite","passport","residence_permit"];function pt(e,t){let o=e.byIssuer?.[t]??e.default;return lt.filter(i=>o==="*"||o.includes(i))}function en(e,t=De){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(i=>pt(e,i).length>0).sort()}function He(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}function tn(e){return/^[A-Z]{2}$/.test(e)?String.fromCodePoint(...[...e].map(t=>127462+t.charCodeAt(0)-65)):""}var un=["national_number","document_photo","national_eid"],ft=new Set(["phone_otp","email_otp","national_eid","document","nfc","population_registry","supplied_identity","summary_confirm","liveness","portrait","face_match","aml_screening","face_dedup","age_estimation"]),mt=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),oe=["document","population_registry","national_eid"],ie=["phone_otp","email_otp"],Ue={identity_method:oe,contact:ie},ht=["population_registry","document"],Fe="platform_unsupported",St=new Set(["prefilled","user_entered","prefilled_or_entered"]),yt={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??yt[e.checkType]??null}function gt(e,t){let o=e.plan?.choice;if(o===void 0||o.locked)return;let i=o.options.find(r=>r.id!==o.selected&&r.available!==!1&&t.includes(r.service));return i===void 0?void 0:{nodeId:o.nodeId,option:i}}function re(e){let t=e.plan,o=t?.choice;if(t===void 0||o===void 0||o.locked||t.current===null||t.current===o.nodeId||b(e))return null;let i=Ue[o.kind]??[...oe,...ie],r=o.options.flatMap(a=>a.available===!1||!i.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=o.selected??r.find(a=>a.service===s)?.id??null;return r.some(a=>a.id!==u)?{nodeId:o.nodeId,kind:o.kind,current:u,options:r}:null}function Be(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function Ct(e){let t=(e.plan?.sections??[]).map(r=>({id:r.id,state:r.state})),o={sessionId:te(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&&(o.branding=e.branding),e.cameraUnavailableHandled===!0&&(o.cameraUnavailableHandled=!0);let i=re(e);return i!==null&&(o.switchable=i),o}function kt(e){let t={attemptsRemaining:G(e),attemptsExhausted:e.attemptsExhausted===!0};return e.reason!==void 0&&(t.reason=e.reason),e.retakeHint!==void 0&&(t.retakeHint=e.retakeHint),t}var Ge={phone_otp:"phone",email_otp:"email"};function _t(e,t){let o=gt(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return o===void 0?void 0:Ge[o.option.service]}function Pt(e,t,o,i){let r=t.checkType==="email_otp",s=(r?t.emailOtp:t.otp)??{},u=r?t.emailOtp?.emailSource:t.otp?.numberSource,a=u!==void 0&&St.has(u)?u:r?"prefilled_or_entered":"user_entered",l=typeof s.sentToMasked=="string"&&s.sentToMasked.length>0,f=s.prefilled===!0,m=_t(e,r?"email_otp":"phone_otp"),g={key:t.checkType,context:o,section:I(t),phase:l?"verify":"send",canSwitch:m!==void 0,...i},d=r?{kind:"email_otp",...g,emailSource:a,needsEmail:a!=="prefilled"&&!f}:{kind:"phone_otp",...g,numberSource:a,needsPhone:a!=="prefilled"&&!f,channels:(t.otp?.channels??[]).filter(k=>k==="whatsapp"||k==="sms")};if(m!==void 0&&(d.switchChannel=m),f&&(d.prefilled=!0),l&&(d.sentToMasked=s.sentToMasked),!r&&t.otp?.channel!==void 0&&(d.channel=t.otp.channel),!r&&Array.isArray(t.phoneCountries)&&(d.phoneCountries=t.phoneCountries.filter(k=>typeof k=="string"&&/^[A-Z]{2}$/.test(k))),!r&&Array.isArray(t.phoneRules)){let k=d.phoneCountries??[];d.phoneRules=t.phoneRules.flatMap(h=>{let A=vt(h);return A!==void 0&&k.includes(A.code)?[A]:[]})}return!r&&t.phoneInternational===!0&&(d.phoneInternational=!0),s.expiresAt!==void 0&&(d.codeExpiresAt=s.expiresAt),s.resendAvailableAt!==void 0&&(d.resendAvailableAt=s.resendAvailableAt),d}var bt=/^[\d[\]\-|()?:^]{1,64}$/;function xt(e){try{return typeof e=="string"&&bt.test(e)&&new RegExp(e)!==null}catch{return!1}}var Ne=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function vt(e){let{code:t,dial:o,trunk:i,lengths:r,formats:s}=e??{};if(typeof t!="string"||typeof o!="string"||!/^\d{1,3}$/.test(o)||i!==void 0&&(typeof i!="string"||!/^\d{1,3}$/.test(i))||!Array.isArray(r)||r.length===0||!r.every(Ne))return;let u={code:t,dial:o,lengths:[...r].sort((a,l)=>a-l)};if(i!==void 0&&(u.trunk=i),s!==void 0){if(!(Array.isArray(s)&&s.length<=8&&s.every(l=>xt(l?.leading)&&Array.isArray(l.groups)&&l.groups.every(Ne)&&r.includes(l.groups.reduce((f,m)=>f+m,0)))))return;u.formats=s.map(l=>({leading:l.leading,groups:[...l.groups]}))}return u}function Rt(e,t,o,i){let r=Z(e)===!0?"bound":L(t)===!0?"document":"typed",s=r==="typed"&&t.state==="input_required"&&t.reason!==void 0&&we(t.reason)==="id_number_recheck",u=Be(re(e)),a=!i.attemptsExhausted&&u.length===1&&u[0]?.service==="document";return{kind:"registry",key:"registry",context:o,section:I(t),state:t.state==="input_required"?"input_required":"pending",source:r,recheck:s,canUseDocument:a,...i}}function It(e,t,o,i){let r=[...t.acceptedSides??[]],s={kind:"document",key:"document",context:o,section:I(t),side:r.includes("recto")?"verso":"recto",acceptedSides:r,documents:He(e),photo:Ke(e.documents),...i};return At(e)&&(s.ageStepUp=!0),s}function Ke(e,t=!0){let o=e?.source==="upload"||e?.source==="choice"?e.source:"camera",i=e?.sourcePick==="camera"||e?.sourcePick==="upload"?e.sourcePick:null;return{source:o,pick:i,uploadOffered:t&&e?.uploadOffered===!0}}function At(e){let t=H(e).find(i=>i.checkType==="age_estimation"),o=t?.reason;return t?.state==="failed"&&(o==="age_uncertain"||o==="age_unavailable")}function Ot(e){let t=x(e,"liveness");return t?.state==="passed"||t?.state==="review"}function Le(e,t,o,i,r){let s=t.icao?.report,u=e.portrait,a=r==="capture"?u?.pendingFix??null:null;a!==null&&(r="review");let l=qe(e);return{kind:"portrait",key:`portrait:${r}`,context:o,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:Y(e),retakeOnly:r==="capture"&&t.state==="input_required"&&l===void 0&&e.capture?.livePhoto?.oneCapture===!0&&Ot(e),photo:Ke(u,r==="capture"),pendingFix:a,...l!==void 0?{captureMode:l}:{},...u?.reuse?.pending===!0?{reuse:!0}:{},...i}}function qe(e){let t=e.portrait?.captureMode;return t==="self"||t==="assisted"||t==="choice"?t:void 0}var ne={minLongSidePx:1280,jpegQuality:.95};function wt(e,t){let o=e.capture?.livePhoto;if(o?.oneCapture!==!0)return null;let i=x(e,"portrait_icao"),r=o.still??ne;return{icao:t==="liveness"&&Y(e)!==null&&qe(e)===void 0&&i!==void 0&&i.state==="pending"&&i.reason===void 0,still:{minLongSidePx:r.minLongSidePx??ne.minLongSidePx,jpegQuality:r.jpegQuality??ne.jpegQuality}}}function Mt(e,t,o,i){let r=t.eid,s=I(t);if(r===void 0||r.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:o,section:s,checkType:"eid_auth",reason:"update_required"};let u=Be(re(e)),a=u.length===1&&ht.includes(u[0]?.service??"")?u[0]:void 0,l=a===void 0?void 0:D[a.service],f=l!==void 0,m={kind:"eid",key:"eid",context:o,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:f,afterPass:r.afterPass==="continue"?"continue":"end",...i};return f&&(m.cameraMethod=l),r.expiresAt!==void 0&&(m.codeExpiresAt=r.expiresAt),r.resendAvailableAt!==void 0&&(m.resendAvailableAt=r.resendAvailableAt),r.resendsRemaining!==void 0&&(m.resendsRemaining=r.resendsRemaining),r.codeAttemptsRemaining!==void 0&&(m.codeAttemptsRemaining=r.codeAttemptsRemaining),m}function Et(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let o=x(e,"portrait_icao");return o!==void 0&&(o.state==="passed"||o.state==="review")?o:null}function Tt(e){return H(e).filter(t=>t.state==="failed").pop()?.attemptsExhausted===!0}function Vt(e,t){let o=e.failureReason,i;o===Fe?i="platform_unsupported":e.status==="expired"?i="expired":e.status==="review_pending"?i="review":e.status==="completed"&&e.outcome==="approved"?i="approved":e.status==="completed"&&e.outcome==="review"?i="review":o==="device_cooldown"?i="cooldown":o!==void 0?i="policy_stop":Tt(e)?i="attempts_exhausted":i="rejected";let r=i==="platform_unsupported"?{sessionId:te(e.sessionId),status:"unavailable"}:N(e,{autoRetry:!1}),s={kind:"result",key:"result",context:t,section:null,display:i,result:r};return o!==void 0&&(s.failureReason=o),e.retryAfter!==void 0&&(s.retryAfter=e.retryAfter),s}function Dt(e,t,o){let i=e.identitySummary;if(i==null)return null;let r={kind:"identity_summary",key:"identity_summary",context:t,section:o??"identity",summaryKind:i.kind==="partial"?"partial":i.kind??"full",source:i.source,portraitAvailable:i.portrait?.available===!0,retakeAvailable:i.retakeAvailable===!0};for(let u of Ht){let a=i[u];typeof a=="string"&&a!==""&&(r[u]=a)}let s=Ve(i);return s!==void 0&&(r.idNumberMasked=s,r.nniMasked=s),r}var Ht=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","expiryDate","retakeTarget"];function T(e,t,o,i){return{kind:"unsupported",key:`unsupported:${o}`,context:e,section:t,checkType:o,reason:i}}function Nt(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function Lt(e,t){let o=Ue[e.kind]??[...oe,...ie],i=Nt(e),r=e.options.flatMap(u=>{if(u.available===!1||!o.includes(u.service))return[];let a={id:u.id,service:u.service};u.nationalEid!=null&&(a.nationalEid=u.nationalEid);let l=(u.channels??[]).filter(f=>f==="whatsapp"||f==="sms");return u.service==="phone_otp"&&l.length>0&&(a.channels=l),[a]});if(r.length===0){let u=e.options.length>0&&e.options.every(a=>a.service==="nfc");return T(t,i,"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:i,options:r.map(l=>D[l.service]),choice:s},a=r.find(l=>l.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:i,options:r.map(u=>Ge[u.service]),selected:null,locked:!1,choice:s}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:i,choice:s}}function dn(e,t={}){let o=Ct(e);if(b(e)||e.failureReason===Fe)return Vt(e,o);let i=e.plan;if(i===void 0||!Array.isArray(i.sections))return T(o,null,"plan","update_required");let r=Me(e);if(r!==null)return Lt(r,o);let s=i.current===null?void 0:i.steps.find(g=>g.id===i.current),u=g=>{let d={kind:"processing",key:"processing",context:o,section:g!==void 0?I(g):i.sections.find(k=>k.state==="current")?.id??null,stalled:!1};return typeof g?.service=="string"&&g.service!==""&&(d.service=g.service),d};if(i.current===null)return u(i.steps.find(g=>g.state==="processing"));if(s===void 0)return T(o,null,"step","update_required");if(!ft.has(s.service))return s.interaction==="server"?u(s):T(o,I(s),s.service,"update_required");if(mt.has(s.service)||!K(s))return u(s);let a=s,l=kt(a),f=a.checkType,m=I(a);switch(f){case"phone_otp":case"email_otp":return Pt(e,a,o,l);case"population_registry":return Rt(e,a,o,l);case"eid_auth":return Mt(e,a,o,l);case"doc_ocr":return It(e,a,o,l);case"identity_confirm":return Dt(e,o,m)??u(a);case"portrait_icao":return Le(e,a,o,l,"capture");case"liveness":case"face_match":{let g=Et(e,a);if(g!==null)return Le(e,g,o,l,"match");let d=a.requiresMobile===!0,k=Y(e);return d&&t.isMobile===!1?{kind:"mobile_required",key:"mobile_required",context:o,section:m,checkType:f}:{kind:"liveness",key:"biometric",context:o,section:m,mode:f==="face_match"?"selfie":"liveness",requiresMobile:d,instructions:k===null?"standard":"icao",icao:k,livePhoto:wt(e,f),...l}}case"nfc_chip":return T(o,m,f,"platform_unsupported");default:return T(o,m,f,"update_required")}}export{it as a,rt as b,st as c,at as d,ut as e,Qt as f,dt as g,De as h,lt as i,pt as j,en as k,He as l,tn as m,un as n,Fe as o,I as p,re as q,Be as r,Et as s,dn as t};
@@ -0,0 +1 @@
1
+ import{a as _,c as y}from"./chunk-ZLWH4RBO.js";var S=["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 x(s){return S.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)}};function f(s,e,n=Math.random){let t=(s??e)*1e3,o=Math.min(Math.max(t,500),2e4),i=Math.round(o*(1+(n()*2-1)*.25));return Math.min(Math.max(i,500),2e4)}var w=6e4,h=4,k=3e4,I=9e5,R=200,P=5,M=400,E=new Set(["server_busy","request_timeout"]),C=2;function l(s){return(s.split(";")[0]??"").trim()}var A={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},v=`@sekyro/web/${_}`,O=v,b=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.reportedIssues=new Map;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let n=e.fetch;this.fetchImpl=(t,o)=>(n??globalThis.fetch).call(globalThis,t,o),this.requestTimeoutMs=e.requestTimeoutMs??k,this.retryAttempts=e.inProgressRetry?.attempts??P,this.retryDelayMs=e.inProgressRetry?.delayMs??M,this.random=e.random??Math.random}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,o=typeof e.attempt=="number"&&Number.isInteger(e.attempt)&&e.attempt>=0&&e.attempt<=1e3?e.attempt:void 0,i=[e.check,o??"",e.kind,n,e.phase??""].join("|"),a=this.reportedIssues.get(i);if(a!==void 0)return a;let d={check:e.check,kind:e.kind,...n!==""?{name:n}:{},...e.phase!==void 0?{phase:e.phase}:{},...t!==void 0?{engineKind:t}:{},...o!==void 0?{attempt:o}:{},...e.formFactor!==void 0?{formFactor:e.formFactor}:{}},r=this.api("POST","/hosted/capture-issue",{body:d,empty:!0}).catch(()=>{this.reportedIssues.delete(i)});return this.reportedIssues.set(i,r),r}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,o={}){let i=await this.ensureSessionId(),a={kind:e,contentType:l(n),contentLength:t,...o.source==="upload"?{source:"upload"}:{}};return this.api("POST",`/sessions/${i}/media`,{body:a})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,n,t,o={}){let i=await this.ensureSessionId(),a=await this.takeCaptureNonce(),d=a===void 0?void 0:{nonce:a,...o.engine!==void 0?{engine:o.engine.slice(0,32)}:{},...o.durationMs!==void 0&&Number.isFinite(o.durationMs)?{captureMs:Math.min(36e5,Math.max(0,Math.round(o.durationMs)))}:{}},r={kind:e,contentType:l(n),contentLength:t,capture:d};return this.api("POST",`/sessions/${i}/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))}}),o=Date.now()+Math.max(0,t.expiresIn)*1e3;for(let i of Array.isArray(t.nonces)?t.nonces:[])typeof i=="string"&&i.length>0&&this.captureNonces.push({nonce:i,expiresAt:o});this.captureNonces=this.captureNonces.slice(-h)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,n,t){let o;try{o=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":l(t)},body:n,signal:AbortSignal.timeout(I)})}catch(i){throw m(i)}if(!o.ok){let i=(await o.text().catch(()=>"")).slice(0,R);throw new c({status:o.status,code:"upload_failed",message:`media upload failed (HTTP ${o.status})${i?`: ${i}`:""}`})}}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 o=await this.ensureSessionId(),i={input:n,forceOutcome:t.forceOutcome};return this.api("POST",`/sessions/${o}/checks/${e}`,{body:i,idempotencyKey:t.idempotencyKey,busyRetry:t.idempotencyKey!==void 0})}async uploadAndSubmit(e,n,t,o={}){let i=l(n.contentType),a=await this.presign(n.kind,i,n.blob.size);await this.uploadToSpaces(a.uploadUrl,n.blob,i);let d=await this.completeMedia(a.key),r={...t,[A[e]]:d.key};return this.submitCheck(e,r,o)}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 o=e==="GET"||t.busyRetry===!0,i=`${this.apiOrigin}/api/v2${n}`,a={"x-session-token":this.sessionToken,"x-sekyro-sdk":O};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(i,{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(T){throw m(T)}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 N(p)}let u=await H(r);if(u.code==="idempotency_in_progress"&&d<this.retryAttempts){this.retryDelayMs>0&&await g(this.retryDelayMs);continue}if(o&&u.status===503&&E.has(u.code)){o=!1,await g(f(u.retryAfterSeconds,C,this.random));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 N(s){return s!==null&&typeof s=="object"&&"success"in s&&"data"in s?s.data:s}async function H(s){let e="unknown_error",n=`request failed (HTTP ${s.status})`,t=Number.NaN,o;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)&&(o=r.details)}}catch{}let i=s.headers.get("retry-after"),a=i===null?Math.floor(t):Number.parseInt(i,10);return new c({status:s.status,code:e,message:n,...Number.isFinite(a)&&a>=0?{retryAfterSeconds:a}:{},details:o})}function g(s){return new Promise(e=>setTimeout(e,s))}function F(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"?"alert":"reject",profile:t||n.profile==="id_document"?"id_document":"selfie"}}function j(s){return{...s.baselineEyeOpenness!==void 0?{baselineEyeOpenness:s.baselineEyeOpenness}:{},criteria:s.verdict??{},...s.backgroundCheck!==void 0?{backgroundCheck:s.backgroundCheck}:{}}}export{S as a,x as b,c,f as d,l as e,v as f,b as g,F as h,j as i};
@@ -0,0 +1 @@
1
+ var u=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],l=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^camera2? ?\d+, facing (front|back|external)/i,/facetime/i,/\b(integrated|built-in|builtin) (web)?cam(era)?\b/i,/\b(hd )?web ?cam\b/i,/\([0-9a-f]{4}:[0-9a-f]{4}\)\s*$/i];function c(n){let e=(n??"").trim().toLowerCase();return e.length===0?"unknown":u.some(t=>e.includes(t))?"known_virtual":l.some(t=>t.test(e))?"platform":"unknown"}var d=1e3;function m(n,e){return new Promise(t=>{let a=setTimeout(()=>t(void 0),e),r=s=>{clearTimeout(a),t(s)};try{n().then(r,()=>r(void 0))}catch{r(void 0)}})}async function f(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify(n)));return Array.from(new Uint8Array(e).subarray(0,8),t=>t.toString(16).padStart(2,"0")).join("")}var i=n=>Array.isArray(n)?[...n].sort():null,o=n=>{let e=n;return e==null?null:[e.min??null,e.max??null]};function p(n){try{return n.getSettings?.().facingMode==="environment"}catch{return!1}}async function g(n){try{if(n.readyState==="ended"||p(n))return;let e={};try{e=n.getCapabilities?.()??{}}catch{}let t=await m(()=>navigator.mediaDevices.enumerateDevices(),d);return await f([o(e.width),o(e.height),o(e.frameRate),i(e.facingMode),i(e.focusMode),i(e.exposureMode),c(n.label),t?.filter(a=>a.kind==="videoinput").length??null])}catch{return}}async function v(n,e){let t=await g(n);t&&e.noteCamera(t)}export{m as a,f as b,g as c,v as d};