@sekyro/web 0.1.0-rc.31 → 0.1.0-rc.33

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 (52) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +1 -0
  3. package/dist/{capture-session-doc-2LIRRKFX.js → capture-session-doc-FAMDLRRZ.js} +1 -1
  4. package/dist/{capture-session-v3-XtBrXpoW.d.cts → capture-session-v3-BS2Rl4Kp.d.cts} +1 -1
  5. package/dist/{capture-session-v3-Fbj-X2Ij.d.ts → capture-session-v3-CYh0Jmyf.d.ts} +1 -1
  6. package/dist/{challenge-frame-YAQJ5YMB.js → challenge-frame-YBTLAQ5G.js} +1 -1
  7. package/dist/{chunk-TN4JWBFJ.js → chunk-65YTEYLU.js} +1 -1
  8. package/dist/chunk-B5H5ED6O.js +1 -0
  9. package/dist/{chunk-GXL6ZD4I.js → chunk-C4WK5D33.js} +1 -1
  10. package/dist/{chunk-3K3A7O7J.js → chunk-G2BD6INN.js} +1 -1
  11. package/dist/{chunk-SUANHBF4.js → chunk-HFRU66NW.js} +1 -1
  12. package/dist/{chunk-XFDWFJLY.js → chunk-IUNPV67T.js} +1 -1
  13. package/dist/chunk-MJKHDXCU.js +1 -0
  14. package/dist/{chunk-MD4YXLPK.js → chunk-NO22WG7R.js} +1 -1
  15. package/dist/{chunk-6Z4MIKGF.js → chunk-W6Y2335Q.js} +1 -1
  16. package/dist/chunk-YDG77RHN.js +1 -0
  17. package/dist/{chunk-2MX4J26D.js → chunk-YL2B72KC.js} +2 -2
  18. package/dist/chunk-ZVD6VHM2.js +1 -0
  19. package/dist/client/index.cjs +1 -1
  20. package/dist/client/index.d.cts +3 -3
  21. package/dist/client/index.d.ts +3 -3
  22. package/dist/client/index.js +1 -1
  23. package/dist/core/index.cjs +1 -1
  24. package/dist/core/index.d.cts +3 -3
  25. package/dist/core/index.d.ts +3 -3
  26. package/dist/core/index.js +1 -1
  27. package/dist/create-document-capture-WFTNVMCE.js +1 -0
  28. package/dist/{create-verification-lXGU3ac4.d.cts → create-verification-BAoA5Z9o.d.cts} +10 -5
  29. package/dist/{create-verification-RdG6qv51.d.ts → create-verification-C1Svvmup.d.ts} +10 -5
  30. package/dist/{detector-scanic-KMAVOHGF.js → detector-scanic-S4PB2RNW.js} +1 -1
  31. package/dist/{icao-gate-Cp1C4IEZ.d.ts → icao-gate-BBStoG81.d.ts} +11 -3
  32. package/dist/{icao-gate-DVNkPclI.d.cts → icao-gate-C731iewN.d.cts} +11 -3
  33. package/dist/{icao-policy-CcrwfsVr.d.ts → icao-policy-Dy5Z1vSp.d.ts} +2 -2
  34. package/dist/{icao-policy-c2Ykm9r2.d.cts → icao-policy-R7Jk5qF_.d.cts} +2 -2
  35. package/dist/index.cjs +2 -2
  36. package/dist/index.d.cts +7 -7
  37. package/dist/index.d.ts +7 -7
  38. package/dist/index.js +1 -1
  39. package/dist/internal/index.cjs +2 -2
  40. package/dist/internal/index.d.cts +6 -6
  41. package/dist/internal/index.d.ts +6 -6
  42. package/dist/internal/index.js +1 -1
  43. package/dist/{plan-runner-T2ZTSBI4.js → plan-runner-LSQTIO6L.js} +1 -1
  44. package/dist/{types-B47mZ5TT.d.cts → types-BjzuJVOc.d.cts} +5 -2
  45. package/dist/{types-B47mZ5TT.d.ts → types-BjzuJVOc.d.ts} +5 -2
  46. package/package.json +1 -1
  47. package/sbom.cdx.json +19 -19
  48. package/dist/chunk-6ERQTXMY.js +0 -1
  49. package/dist/chunk-CMXN4SOZ.js +0 -1
  50. package/dist/chunk-OUC57KMS.js +0 -1
  51. package/dist/chunk-R3JMNYW5.js +0 -1
  52. package/dist/create-document-capture-X35M4UAK.js +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # @sekyro/web
2
2
 
3
+ ## 0.1.0-rc.33
4
+
5
+ ### Patch Changes
6
+
7
+ - b61c1b7: A browser check refused because the phone's date and time are wrong now reads `clock_wrong` (a new `ChallengeErrorCode`, kept with Cloudflare's code in `detail`) instead of `challenge_failed`, so the page can tell the person what to fix. It is never a reason to skip the check: the SDK keeps running fresh checks, and `retry()` on the capture handle checks again with the same video once the clock is fixed.
8
+
9
+ ## 0.1.0-rc.32
10
+
11
+ ### Minor Changes
12
+
13
+ - 18265a3: A neutral end for suspected fraud. When a session fails in a way the page does not explain (a fraud-grade failure, or a stop by an automatic block), the session view and the result handed to your client say `status: "not_verified"`, `reason: "rejected"` and the new view-only `reasonCode: "identity_not_verified"` (`SessionFailureReason`), with no `retryAfter`. The code is never stored and never appears in the partner API or webhooks: read the session's real outcome on your server. `@sekyro/react` shows the rejected title and "We couldn't verify your identity. Contact {org} for help." (without an organization name: "Contact the organization that sent you this link for help."), in six languages (`reasons.identity_not_verified`, `session.result.identityNotVerified`).
14
+
15
+ ### Patch Changes
16
+
17
+ - 7a73651: A blocked camera no longer floods your session with capture-issue reports: each distinct failure (check, kind, error name, phase) is reported once per session whatever the attempt, a report refused with 429 is never sent again, no report is sent before its `Retry-After` has passed, and a session sends at most 20. A camera that is busy, cannot meet the constraints or is not found while opening is tried again twice (after 0.5 s and 1.5 s) before its error shows; a refused permission (`NotAllowedError`, `SecurityError`) is never retried by itself.
18
+
3
19
  ## 0.1.0-rc.31
4
20
 
5
21
  ### Patch Changes
package/README.md CHANGED
@@ -162,6 +162,7 @@ The check is needed once per session, plus once for every code sent by SMS, What
162
162
  | `challenge_frame_blocked` | The frame did not load: add `frame-src https://verify.sekyro.ai` to your CSP (the SDK also prints this once in the console), or a browser extension or proxy blocked it. |
163
163
  | `challenge_script_blocked` | The check's script could not load inside the frame (a network filter on the person's connection). |
164
164
  | `challenge_failed` | The check could not clear this browser. |
165
+ | `clock_wrong` | The phone's date and time are wrong. The person sets them to automatic and tries again; `retry()` checks again with the same video. |
165
166
  | `timeout` | The check did not finish in 120 s. |
166
167
  | `site_key_rejected` | The session and the frame disagree on the key (on our side). |
167
168
  | `embedder_opaque` | The SDK runs in a document without an origin (a sandboxed frame or a `data:` page). |
@@ -1 +1 @@
1
- import{A as b,B as c,C as d,D as e,E as f,F as g,G as h,H as i,I as j,J as k,z as a}from"./chunk-XFDWFJLY.js";import"./chunk-G6LKLN4U.js";import"./chunk-SMKCBUJL.js";import"./chunk-GXL6ZD4I.js";import"./chunk-R3JMNYW5.js";import"./chunk-POIQGEZM.js";import"./chunk-CPUECYAJ.js";import"./chunk-FPXL63KZ.js";import"./chunk-MD4YXLPK.js";import"./chunk-DK5YPBDQ.js";export{k as CAPTURE_CANDIDATE_SPACING_MS,j as CAPTURE_EXTRA_CANDIDATES,h as CaptureSessionDoc,c as DOC_BLACK_FRAME_LUMA,d as DOC_BLACK_FRAME_TICKS,e as DOC_CADENCE_HZ,b as DOC_FIRST_FRAME_MS,f as DOC_SHUTTER_DEFAULTS,i as passportBandOf,g as resolveDocShutterTuning,a as warmDocDetector};
1
+ import{A as b,B as c,C as d,D as e,E as f,F as g,G as h,H as i,I as j,J as k,z as a}from"./chunk-IUNPV67T.js";import"./chunk-G6LKLN4U.js";import"./chunk-SMKCBUJL.js";import"./chunk-C4WK5D33.js";import"./chunk-MJKHDXCU.js";import"./chunk-POIQGEZM.js";import"./chunk-CPUECYAJ.js";import"./chunk-FPXL63KZ.js";import"./chunk-NO22WG7R.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 { br as ScreenRampReport, bi as CaptureProvenance, bo as ScreenRampChallenge, bp as ScreenRampPaint } from './types-B47mZ5TT.cjs';
1
+ import { br as ScreenRampReport, bi as CaptureProvenance, bo as ScreenRampChallenge, bp as ScreenRampPaint } from './types-BjzuJVOc.cjs';
2
2
  import { F as FaceObservation, b as Detector, W as WorkerLike } from './detect-worker-CHqsPJoM.cjs';
3
3
 
4
4
  /** MP4-first ladder: one container (H.264 MP4) covers iOS/macOS Safari + Chrome 130+.
@@ -1,4 +1,4 @@
1
- import { br as ScreenRampReport, bi as CaptureProvenance, bo as ScreenRampChallenge, bp as ScreenRampPaint } from './types-B47mZ5TT.js';
1
+ import { br as ScreenRampReport, bi as CaptureProvenance, bo as ScreenRampChallenge, bp as ScreenRampPaint } from './types-BjzuJVOc.js';
2
2
  import { F as FaceObservation, b as Detector, W as WorkerLike } from './detect-worker-CHqsPJoM.js';
3
3
 
4
4
  /** MP4-first ladder: one container (H.264 MP4) covers iOS/macOS Safari + Chrome 130+.
@@ -1 +1 @@
1
- import{a,b,c,d,e}from"./chunk-CMXN4SOZ.js";export{c as CHALLENGE_EXECUTE_TIMEOUT_MS,b as CHALLENGE_READY_TIMEOUT_MS,a as ChallengeError,e as executeChallenge,d as resetChallengeFrameForTests};
1
+ import{a,b,c,d,e}from"./chunk-ZVD6VHM2.js";export{c as CHALLENGE_EXECUTE_TIMEOUT_MS,b as CHALLENGE_READY_TIMEOUT_MS,a as ChallengeError,e as executeChallenge,d as resetChallengeFrameForTests};
@@ -1 +1 @@
1
- import{a as ne,b as ie}from"./chunk-SX7TUC3V.js";import{b as ce,c as ue,d as de}from"./chunk-POIQGEZM.js";import{a as Y,c as j,e as $,g as J,h as A,k as R,m as ee,n as re}from"./chunk-CPUECYAJ.js";import{b as L,c as pe,d as F,e as me}from"./chunk-FPXL63KZ.js";import{a as z,c as X,d as Z,e as Q}from"./chunk-TSA6GHUG.js";import{d as te}from"./chunk-MD4YXLPK.js";import{e as ae,f as se,h as G,j as oe,l as le}from"./chunk-FSSMUAKC.js";var Ie=[...Y.filter(i=>i.startsWith("video/mp4")),"video/webm;codecs=h264","video/webm;codecs=avc1","video/webm;codecs=vp8","video/webm;codecs=vp9","video/webm"],he=new Set;function De(i){let e=/(?:Chrome|Chromium)\/(\d+)\./.exec(i??"");return e?Number(e[1]):null}function fe(i=Oe(),e=globalThis.navigator?.userAgent){if(i===void 0)return"";let t=De(e)===126;for(let r of Ie)if(!(he.has(r)||t&&r.startsWith("video/mp4")))try{if(i(r))return r}catch{}return""}function V(i){i!==""&&he.add(i)}function ge(i){return i.replace(/^video\/x-matroska/i,"video/webm")}function ut(i){let e=/codecs=["']?([^,;"']+)/i.exec(i);return e?e[1].trim():i.split(";")[0].trim()}function Oe(){let i=globalThis.MediaRecorder;return i&&typeof i.isTypeSupported=="function"?e=>i.isTypeSupported(e):void 0}var U=2500,Pe=1e3,xe=1500,ve=25e5,Ge=100,Le=700,Fe=20,Ve=1500,N=null;function Ne(){return N??(N=import("./clip-inspect-DLJXVKV6.js").catch(i=>{throw N=null,i})),N.catch(()=>null)}var S=class extends Error{constructor(e,t){super(t??e),this.kind=e}},Ue=100;function H(i,e){return i.stats===void 0?!1:i.stats===null?!0:i.stats.durationMs<e-Ue}function be(i,e){return i.stats?e.stats?i.stats.durationMs>e.stats.durationMs:!0:!1}var I=class{constructor(e={}){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.pollTimer=null;this.settled=!1;this.now=e.now??(()=>globalThis.performance?.now?.()??Date.now())}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.pollTimer&&clearInterval(this.pollTimer),this.hardStopTimer=null,this.graceTimer=null,this.pollTimer=null}record(e,t,r,n=U,a){let s=fe(),o=Ne();return this.recordRaw(e,t,r,n,a,s).then(c=>He(c,o),c=>{throw c instanceof S&&(c.requestedMimeType=s),c})}recordRaw(e,t,r,n,a,s){return this.recorder&&!this.settled?Promise.reject(new S("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,new Promise((o,c)=>{let l;try{l=new MediaRecorder(e,s?{mimeType:s,videoBitsPerSecond:ve}:{videoBitsPerSecond:ve})}catch{try{l=new MediaRecorder(e)}catch{c(new S("unsupported"));return}}this.recorder=l;let d=h=>{this.settled||(this.settled=!0,this.clearTimers(),h())},u=()=>d(()=>{let h=ge(l.mimeType||s||j),b=new Blob(this.chunks,{type:h});if(b.size===0){c(new S("generic","empty clip"));return}if(A(b)){c(new S("cliptoolarge"));return}o({blob:b,mimeType:h,requestedMimeType:s})});l.ondataavailable=h=>{h.data&&h.data.size&&(this.chunks.push(h.data),this.bytes+=h.data.size,this.bytes>J&&d(()=>{try{l.state!=="inactive"&&l.stop()}catch{}c(new S("cliptoolarge"))}))},l.onstop=u,l.onerror=()=>d(()=>c(new S("generic")));let f=this.now();if(r!==void 0||a!==void 0){let h=!1;l.onstart=()=>{if(!(h||this.settled)&&(h=!0,f=this.now(),r!==void 0))try{r()}catch{}}}try{l.start(Pe)}catch{d(()=>c(new S("generic")));return}let g=()=>{if(this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=null,this.settled||t?.(),l.state!=="inactive"){try{l.stop()}catch{u()}this.graceTimer=setTimeout(u,xe)}else u()},p=this.now();if(a===void 0){this.hardStopTimer=setTimeout(g,n);return}let m=null,y=!1;this.hardStopTimer=setTimeout(g,n+Le),this.pollTimer=setInterval(()=>{if(this.settled||y)return;let h=null;try{h=a.latest()}catch{h=null}let b=h?.presentationTimeMs;b!==void 0&&Number.isFinite(b)&&b>=f&&m===null&&(m=b);let C=m!==null&&b!==void 0&&b-m>=n,E=m===null&&this.now()-p>=n;if(!(!C&&!E)){if(y=!0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,E){g();return}this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=setTimeout(g,Ge)}},Fe)}))}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(n=>n.stop()),this.stream=null}};async function He(i,e){let t,r=new Promise(l=>{t=setTimeout(()=>l(null),Ve)}),n=await Promise.race([e,r]);if(clearTimeout(t),n===null)return i;let a;try{a=await n.blobBytes(i.blob)}catch{return{...i,stats:null}}let s=n.inspectClipBytes(a);if(s?.container!=="webm")return{...i,stats:s};let o=n.withWebmDuration(a,s.durationMs);if(o===null)return{...i,stats:s};let c=n.inspectClipBytes(o);return c===null||c.frames!==s.frames||c.durationMs!==s.durationMs?{...i,stats:s}:{...i,blob:new Blob([o],{type:i.blob.type}),stats:s}}var Ke=["magenta","yellow","green","blue"];var Be={magenta:"rgb(255, 72, 150)",yellow:"rgb(255, 190, 0)",green:"rgb(0, 238, 175)",blue:"rgb(25, 150, 255)",dark:"rgb(0, 0, 0)"};function ft(i){return Be[i]}var We=4,qe=4,D=i=>typeof i=="number"&&Number.isFinite(i);function O(i){if(typeof i!="object"||i===null)return!1;let e=i;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length<1||e.colours.length>8||!e.colours.every(r=>Ke.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==e.colours.length)return!1;let t=-1;for(let r of e.onsetsMs){if(!D(r)||r<0||r<=t)return!1;t=r}return!(!D(e.holdMs)||e.holdMs<=0||!D(e.endMs)||e.endMs<=t||!D(e.clipMs)||e.clipMs<e.endMs||e.clipMs>8e3)}function ye(i,e){return O(i)?Math.max(e,Math.ceil(i.clipMs)):e}function Me(i,e){let t=e.now??(()=>performance.now()),r=O(i)?i:void 0,n=[],a=null,s=null,o=null,c=!1,l=null,d=p=>{l=p;try{e.paint(p)}catch{}},u=p=>{let m=e.frames?.()??null;return m!==null&&o!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-o:p-(s??p)},f=(p,m,y=0)=>{if(c)return;let h=Math.max(0,p-u(t()));a=setTimeout(()=>{if(a=null,!c){if(y<We&&u(t())<p-qe){f(p,m,y+1);return}m()}},h)},g=p=>{if(r===void 0)return;let m=r.endMs;if(p>=r.colours.length){f(m,()=>d(null));return}let y=r.onsetsMs[p],h=p+1<r.onsetsMs.length?r.onsetsMs[p+1]:m;f(y,()=>{let b=u(t());if(b>m){l!==null&&d(null);return}let C=r.colours[p];d(C);let E=n.length===0?0:n[n.length-1].tMs;n.push({tMs:Math.max(E,Math.round(b)),colour:C});let M=y+r.holdMs;if(M<h){f(M,()=>{if(u(t())>m){l!==null&&d(null);return}d("dark"),g(p+1)});return}g(p+1)})};return{started(p){if(r===void 0||c||s!==null)return;s=p;let m=e.frames?.()??null;o=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),g(0)},stop(){c||(c=!0,a!==null&&clearTimeout(a),a=null,l!==null&&d(null))},report(){return r===void 0?void 0:{nonce:r.nonce,rendered:[...n]}}}}function Se(i,e,t=.92){return new Promise((r,n)=>{let a=i.videoWidth,s=i.videoHeight;if(!a||!s){n(new Error("video-not-ready"));return}let o=e.getContext("2d");if(!o){n(new Error("no-2d-context"));return}e.width=a,e.height=s,o.scale(-1,1),o.drawImage(i,-a,0),e.toBlob(c=>c?r(c):n(new Error("empty-keyframe")),"image/jpeg",t)})}var P=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 ze=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}),_=i=>Math.min(1,Math.max(0,i)),k=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...ze,...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:n}=e,a=this.lastTickAt===null?0:Math.max(0,(n-this.lastTickAt)/1e3);this.lastTickAt=n;let s={presence:0,single:1,centering:0,size:0,pose:0,sharpness:_(r.sharpness),exposure:_(r.exposure),motion:1};if(t!==null){s.presence=1,s.single=(t.extraFaces??0)>0?0:1;let d=this.geometryOf(t,e);s.centering=d.centering,s.size=d.size,s.pose=d.pose,s.motion=this.motionOf(d.center,d.iod,n)}else this.lastCenter=null,this.velocityEma=0;let o=Math.min(s.presence,s.single,s.centering,s.size,s.pose,s.sharpness,s.exposure,s.motion);this.p=_(this.p+(o>=this.t.Q_GOOD?this.t.RISE_PER_S*o:-this.t.FALL_PER_S*(1-o))*a),this.qWindow.push({at:n,q:o}),this.qWindow=this.qWindow.filter(d=>d.at>=n-this.t.READY_WINDOW_MS);let c=this.qWindow.map(d=>d.q);if(c.length>=3){let d=Math.min(...c),u=c.indexOf(d);c=c.filter((f,g)=>g!==u)}let l=this.p>=1&&c.every(d=>d>=this.t.Q_GOOD);return{at:n,q:o,p:this.p,factors:s,guidanceKey:this.guidanceOf(s,r,o),ready:l,accepted:o>=this.t.Q_GOOD}}geometryOf(e,t){let{box:r,eyes:n}=e,a={x:t.frameWidth/2,y:t.frameHeight/2},s=Math.min(t.frameWidth,t.frameHeight),o=n!==void 0?{x:(n.left.x+n.right.x)/2,y:(n.left.y+n.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},c=n!==void 0?Math.hypot(n.right.x-n.left.x,n.right.y-n.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,l=Math.hypot(o.x-a.x,o.y-a.y),d=c<=0?0:1-_(l/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*c)),u=s>0?c/s:0;this.lastSizeDirection=u<this.t.SIZE_IDEAL_MIN?"far":u>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;u<this.t.SIZE_HARD_MIN||u>this.t.SIZE_HARD_MAX?f=0:u<this.t.SIZE_IDEAL_MIN?f=(u-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):u>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-u)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let g=1;if(n!==void 0){let p=Math.abs(Math.atan2(n.right.y-n.left.y,n.right.x-n.left.x))*180/Math.PI;g=1-_(p/this.t.ROLL_MAX_DEG)}return{center:o,iod:c,centering:d,size:f,pose:g}}motionOf(e,t,r){let n=this.lastCenter;if(this.lastCenter={...e,at:r},n===null||t<=0)return 1;let a=(r-n.at)/1e3;if(a<=0)return 1;let s=Math.hypot(e.x-n.x,e.y-n.y)/t/a;s<=this.t.MOTION_DEADBAND_IOD_PER_S&&(s=0);let o=1-Math.exp(-a/this.t.MOTION_TAU_S);return this.velocityEma=o*s+(1-o)*this.velocityEma,1-_(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,r){if(e.presence<=0)return"fcv3.no_face";if(e.single<=0)return"fcv3.one_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 n=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],a=n[0];for(let s of n)e[s[0]]<e[a[0]]&&(a=s);return a[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(L[0]+L[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Xe=["single","size","centering","pose","exposure","sharpness","motion"];function Ze(i){if(i.accepted)return null;if(i.factors.presence<=0)return"no_face";let e="single";for(let t of Xe)i.factors[t]<i.factors[e]&&(e=t);return e}var w=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=Ze(e);if(r===null){this.acceptedMs+=t;return}let n=this.blocked[r]??{count:0,ms:0};n.count+=1,n.ms+=t,this.blocked[r]=n}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 Qe=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ye=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^caméra (avant|arrière)\b/i,/^cámara (frontal|trasera|delantera)\b/i,/^câmera (frontal|traseira)\b/i,/^(front|rück)kamera\b/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 je(i){let e=(i??"").trim().toLowerCase();return e.length===0?"unknown":Qe.some(t=>e.includes(t))?"known_virtual":Ye.some(t=>t.test(e))?"platform":"unknown"}function Te(i){if(typeof i!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(i))}catch{return!1}}function $e(i=globalThis){return Te(i.navigator?.mediaDevices?.getUserMedia)&&Te(i.MediaStreamTrack?.prototype?.getSettings)}async function Je(i,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(i)));return Array.from(r.subarray(0,8),n=>n.toString(16).padStart(2,"0")).join("")}catch{return}}async function Ce(i,e=globalThis){let t={};try{t=typeof i.getSettings=="function"?i.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 a=await Je(t.deviceId,e);a!==void 0&&(r.deviceIdHash=a)}let n;try{n=i.label}catch{n=void 0}return{trackSettings:r,capabilitiesPresent:typeof i.getCapabilities=="function",labelClass:je(n),prototypesIntact:$e(e)}}var K=i=>Math.round(i*100)/100;function Ee(i){let e=i,t=typeof e?.requestVideoFrameCallback=="function",r=null,n=null,a=0,s=0,o=0,c=0,l=0,d=0,u=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((f,g)=>{if(r=null,!t)return;let p=g.presentationTime;if(n!==null){let m=p-n.presentationTimeMs;s+=1;let y=m-o;o+=y/s,c+=y*(m-o)}typeof g.captureTime=="number"&&Number.isFinite(g.captureTime)&&(l+=p-g.captureTime,d+=1),a+=1,n={mediaTimeMs:g.mediaTime*1e3,presentationTimeMs:p},u()}))};return u(),{latest:()=>n,stats:()=>({n:a,meanGapMs:s===0?0:K(o),stdGapMs:s<2?0:K(Math.sqrt(c/(s-1))),captureLatencyMs:d===0?null:K(l/d)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function _e(i,e,t){return{...i,rvfc:e,rampPainter:t}}var et=1e3,B="fcv3.hold_upright",tt=200,W=4,rt=600,nt=1e3,Re={sharpness:1,exposure:1,meanLuma:128};function it(i,e){return e.width=i.videoWidth,e.height=i.videoHeight,e.getContext("2d").drawImage(i,0,0),new Promise((t,r)=>e.toBlob(n=>n?t(n):r(new Error("empty-keyframe")),"image/jpeg",.92))}function at(){return X()==="phone"}var ke=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()}restart(e){this.facing=e,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??at)(),this.setState("preflight");let r=$();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let n=t.getUserMedia??(l=>navigator.mediaDevices.getUserMedia(l)),a;this.cameraRequestedAt=this.now();try{let{facingMode:l,...d}=z(Z(),this.facing).video;a=await ie(this.facing,d,{getUserMedia:n,enumerateDevices:lt(t)})}catch(l){if(e!==this.attempt)return;if(l instanceof ne){this.fail("backcamera",{phase:"acquiring",name:R(l)});return}this.fail(ee(l),{phase:"acquiring",name:R(l)});return}if(te(a),re(a),e!==this.attempt){for(let l of a.getTracks())l.stop();return}this.stream=a;let s=a.getVideoTracks?.()[0];if(this.trackProvenance=s===void 0?null:Ce(s).catch(()=>null),this.facing=Q(a)??this.facing,t.video.srcObject=a,await t.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let l={v3AssetBaseUrl:t.v3AssetBaseUrl},d=t.createDetector??(t.createWorker!==void 0&&oe()?async()=>{try{return await le.create(t.createWorker(),l)}catch{return G(l)}}:()=>G(l)),u;try{u=await d()}catch(f){e===this.attempt&&this.fail("models",{phase:"models",name:R(f)},f instanceof ae?f.fallbackReason:ot(f));return}if(e!==this.attempt){u.destroy();return}this.detector=u,this.options.telemetry?.({type:"detector",tier:u.tier,fallbackReason:u.fallbackReason})}let o=ce(),c=t.deviceClass??ue(o);this.profiler=new de(c),this.options.telemetry?.({type:"profile",staticClass:c,activeClass:this.profiler.deviceClass,simd:o.simd}),this.gate=new k(t.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(l=>q=l,()=>{}),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 n=this.scheduler.stats();this.carriedDegrade+=n.degradeCount,n.meanDetectMs>0&&this.carriedMeans.push(n.meanDetectMs),this.scheduler.stop()}let r=new P({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:n}=this,a=this.options.video;if(e!==this.attempt||t===null||r===null||n===null||this.fired||a.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let s=n.deviceClass,o=this.now(),c=this.options.makeSnapshot?.(a,n.profile.inputWidth)??this.defaultSnapshot(a,n.profile.inputWidth),l=null;try{l=await t.detect(c,a.videoWidth,a.videoHeight)}catch{l=null}if(e!==this.attempt||this.fired)return;n.record(this.now()-o),n.deviceClass!==s&&this.startScheduler(e);let d=l===null?Re:this.options.measureQuality?.(a,l.box)??this.defaultQuality(a,l.box),u=r.tick({timestampMs:this.now(),observation:l,quality:d,frameWidth:a.videoWidth,frameHeight:a.videoHeight});u.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=u.at),this.blockStats?.record(u),!u.ready&&u.at-this.lastGateSnapshotAt>=et&&(this.lastGateSnapshotAt=u.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:u.p,q:u.q,factors:u.factors,attempt:e}),u.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=u.guidanceKey,this.emit("guidance",{key:u.guidanceKey})),u.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=u.at,this.fire(e))}async fire(e){let{options:t}=this,r=this.scheduler;r?.stop(),this.reportGate(!0);let n=r?.stats()??{degradeCount:0,meanDetectMs:0},a=[...this.carriedMeans,...n.meanDetectMs>0?[n.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+n.degradeCount,meanDetectMs:a.length===0?0:a.reduce((M,v)=>M+v,0)/a.length});let s=t.mode??"clip",o=t.rankKeyframes?.()&&q?q.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(s==="photo"){let M=this.watchRotation(e,null),v=await o;if(M(),e!==this.attempt)return;if(v===null){this.fail("generic",{phase:"keyframes"});return}let x=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:v.blob,previewDataUrl:v.previewDataUrl,...x});return}this.setState("recording");let c=this.stream;if(c===null){this.fail("generic",{phase:"recording"});return}let l=t.screenRamp?.(),d=O(l),u=null;o.then(M=>{u=M},()=>{});let f=()=>{e===this.attempt&&u!==null&&this.emit("frozen",{previewDataUrl:u.previewDataUrl})},g=ye(l,U),p=null,m,y=0;try{let M=this.recordTake(e,c,l,g,void 0).then(T=>T,T=>({failed:T})),[v,x]=await Promise.all([M,o]);if(m=x,e!==this.attempt)return;if("failed"in v){if(v.failed.kind==="cliptoolarge")throw v.failed;V(v.failed.requestedMimeType??"")}else p=v,H(v.clip,g)?v.clip.stats===null&&V(v.clip.requestedMimeType??""):f();if(p===null||H(p.clip,g)){y=1,t.telemetry?.({type:"clip_retake",reason:p===null?"error":p.clip.stats===null?"unreadable":"short"});let T=null;try{T=await this.recordTake(e,c,l,g,f)}catch(Ae){if(p===null)throw Ae}if(e!==this.attempt)return;T!==null&&(p===null||be(T.clip,p.clip))&&(p=T),T===null&&f()}}catch(M){if(e!==this.attempt)return;let v=M.kind;this.fail(v==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:R(M)});return}if(p===null){this.fail("recorder",{phase:"recording"});return}let{clip:h,rvfc:b,report:C}=p;if(A(h.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(m===null){this.fail("generic",{phase:"keyframes"});return}let E=await this.provenance(b,d);e===this.attempt&&this.finishCapture({clip:h.blob,clipMimeType:h.mimeType,...h.stats?{clipStats:h.stats}:{},clipRetakes:y,keyframe:m.blob,previewDataUrl:m.previewDataUrl,...C!==void 0&&C.rendered.length>0?{screenRamp:C}:{},...E})}async recordTake(e,t,r,n,a){let s=this.options.createRecorder?.()??new I({now:()=>this.now()}),o=Ee(this.options.video),c=Me(r,{paint:u=>{(u===null||e===this.attempt)&&this.emit("ramp",{colour:u})},now:()=>this.now(),frames:o.latest});this.ramp=c;let l=()=>{o.stop(),c.stop(),this.ramp===c&&(this.ramp=null)},d=this.watchRotation(e,s);try{return{clip:await s.record(t,a,()=>c.started(this.now()),n,o),rvfc:o.stats(),report:c.report()}}finally{d(),l()}}async provenance(e,t){let r=this.trackProvenance;if(r===null)return{};let n,a=new Promise(o=>{n=setTimeout(()=>o(null),nt)}),s=await Promise.race([r,a]);return clearTimeout(n),s===null?{}:{provenance:_e(s,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,single:1,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==B&&(this.lastGuidanceKey=B,this.emit("guidance",{key:B}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,n=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){o();return}r.videoWidth>0&&this.isLandscape()&&(o(),this.abortRecording(e,t))},a=setInterval(n,tt);r.addEventListener?.("resize",n);let s=!1;function o(){s||(s=!0,clearInterval(a),r.removeEventListener?.("resize",n))}return o}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 k(this.options.thresholds??{}),this.blockStats=new w,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??(a=>this.defaultKeyframe(a)),r=rt/(W-1),n=null;for(let a=0;a<W;a+=1){if(e!==this.attempt)return n;try{let s=await t(this.options.video);(n===null||s.sharpness>n.sharpness)&&(n=s)}catch{}a<W-1&&await st(r)}return n}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,n,a)=>{n!==null&&a!==null&&(e[r]=Math.max(0,Math.round(a-n)))};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:it)(e,t),n=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:n,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),n=t/Math.max(1,e.videoWidth),a=Math.max(1,Math.round(e.videoWidth*n)),s=Math.max(1,Math.round(e.videoHeight*n)),o=r.getContext("2d");return o===null?e:(r.width!==a&&(r.width=a),r.height!==s&&(r.height=s),o.drawImage(e,0,0,a,s),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,t){let r=we(e,t,96);return r===null?Re:{sharpness:F(r),exposure:me(r),meanLuma:pe(r)}}centerSharpness(e){let t=se(e),r=we(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:F(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 n=t.summary();e&&(this.blockStats=null),n.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...n})}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:n,name:a}=t;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:a===void 0?{phase:n}:{phase:n,name:a}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},q;function st(i){return new Promise(e=>setTimeout(e,i))}function ot(i){return i instanceof Error?i.message:String(i)}function we(i,e,t){try{let r=document.createElement("canvas"),n=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*n)),r.height=Math.max(1,Math.round(e.height*n));let a=r.getContext("2d");return a===null?null:(a.drawImage(i,e.x,e.y,e.width,e.height,0,0,r.width,r.height),a.getImageData(0,0,r.width,r.height))}catch{return null}}function lt(i){if(i.enumerateDevices!==void 0)return i.enumerateDevices;if(i.getUserMedia===void 0&&!(typeof navigator>"u"||typeof navigator.mediaDevices?.enumerateDevices!="function"))return()=>navigator.mediaDevices.enumerateDevices()}export{ut as a,U as b,Pe as c,xe as d,ve as e,Ge as f,Le as g,Fe as h,Ve as i,S as j,Ue as k,H as l,be as m,I as n,Ke as o,ft as p,Se as q,P as r,ze as s,k as t,Ze as u,w as v,et as w,B as x,tt as y,W as z,rt as A,nt as B,ke as C};
1
+ import{a as ne,b as ie}from"./chunk-SX7TUC3V.js";import{b as ce,c as ue,d as de}from"./chunk-POIQGEZM.js";import{a as Y,c as j,e as $,g as J,h as A,k as R,m as ee,n as re}from"./chunk-CPUECYAJ.js";import{b as L,c as pe,d as F,e as me}from"./chunk-FPXL63KZ.js";import{a as z,c as X,d as Z,e as Q}from"./chunk-TSA6GHUG.js";import{d as te}from"./chunk-NO22WG7R.js";import{e as ae,f as se,h as G,j as oe,l as le}from"./chunk-FSSMUAKC.js";var Ie=[...Y.filter(i=>i.startsWith("video/mp4")),"video/webm;codecs=h264","video/webm;codecs=avc1","video/webm;codecs=vp8","video/webm;codecs=vp9","video/webm"],he=new Set;function De(i){let e=/(?:Chrome|Chromium)\/(\d+)\./.exec(i??"");return e?Number(e[1]):null}function fe(i=Oe(),e=globalThis.navigator?.userAgent){if(i===void 0)return"";let t=De(e)===126;for(let r of Ie)if(!(he.has(r)||t&&r.startsWith("video/mp4")))try{if(i(r))return r}catch{}return""}function V(i){i!==""&&he.add(i)}function ge(i){return i.replace(/^video\/x-matroska/i,"video/webm")}function ut(i){let e=/codecs=["']?([^,;"']+)/i.exec(i);return e?e[1].trim():i.split(";")[0].trim()}function Oe(){let i=globalThis.MediaRecorder;return i&&typeof i.isTypeSupported=="function"?e=>i.isTypeSupported(e):void 0}var U=2500,Pe=1e3,xe=1500,ve=25e5,Ge=100,Le=700,Fe=20,Ve=1500,N=null;function Ne(){return N??(N=import("./clip-inspect-DLJXVKV6.js").catch(i=>{throw N=null,i})),N.catch(()=>null)}var S=class extends Error{constructor(e,t){super(t??e),this.kind=e}},Ue=100;function H(i,e){return i.stats===void 0?!1:i.stats===null?!0:i.stats.durationMs<e-Ue}function be(i,e){return i.stats?e.stats?i.stats.durationMs>e.stats.durationMs:!0:!1}var I=class{constructor(e={}){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.pollTimer=null;this.settled=!1;this.now=e.now??(()=>globalThis.performance?.now?.()??Date.now())}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.pollTimer&&clearInterval(this.pollTimer),this.hardStopTimer=null,this.graceTimer=null,this.pollTimer=null}record(e,t,r,n=U,a){let s=fe(),o=Ne();return this.recordRaw(e,t,r,n,a,s).then(c=>He(c,o),c=>{throw c instanceof S&&(c.requestedMimeType=s),c})}recordRaw(e,t,r,n,a,s){return this.recorder&&!this.settled?Promise.reject(new S("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,new Promise((o,c)=>{let l;try{l=new MediaRecorder(e,s?{mimeType:s,videoBitsPerSecond:ve}:{videoBitsPerSecond:ve})}catch{try{l=new MediaRecorder(e)}catch{c(new S("unsupported"));return}}this.recorder=l;let d=h=>{this.settled||(this.settled=!0,this.clearTimers(),h())},u=()=>d(()=>{let h=ge(l.mimeType||s||j),b=new Blob(this.chunks,{type:h});if(b.size===0){c(new S("generic","empty clip"));return}if(A(b)){c(new S("cliptoolarge"));return}o({blob:b,mimeType:h,requestedMimeType:s})});l.ondataavailable=h=>{h.data&&h.data.size&&(this.chunks.push(h.data),this.bytes+=h.data.size,this.bytes>J&&d(()=>{try{l.state!=="inactive"&&l.stop()}catch{}c(new S("cliptoolarge"))}))},l.onstop=u,l.onerror=()=>d(()=>c(new S("generic")));let f=this.now();if(r!==void 0||a!==void 0){let h=!1;l.onstart=()=>{if(!(h||this.settled)&&(h=!0,f=this.now(),r!==void 0))try{r()}catch{}}}try{l.start(Pe)}catch{d(()=>c(new S("generic")));return}let g=()=>{if(this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=null,this.settled||t?.(),l.state!=="inactive"){try{l.stop()}catch{u()}this.graceTimer=setTimeout(u,xe)}else u()},p=this.now();if(a===void 0){this.hardStopTimer=setTimeout(g,n);return}let m=null,y=!1;this.hardStopTimer=setTimeout(g,n+Le),this.pollTimer=setInterval(()=>{if(this.settled||y)return;let h=null;try{h=a.latest()}catch{h=null}let b=h?.presentationTimeMs;b!==void 0&&Number.isFinite(b)&&b>=f&&m===null&&(m=b);let C=m!==null&&b!==void 0&&b-m>=n,E=m===null&&this.now()-p>=n;if(!(!C&&!E)){if(y=!0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,E){g();return}this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=setTimeout(g,Ge)}},Fe)}))}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(n=>n.stop()),this.stream=null}};async function He(i,e){let t,r=new Promise(l=>{t=setTimeout(()=>l(null),Ve)}),n=await Promise.race([e,r]);if(clearTimeout(t),n===null)return i;let a;try{a=await n.blobBytes(i.blob)}catch{return{...i,stats:null}}let s=n.inspectClipBytes(a);if(s?.container!=="webm")return{...i,stats:s};let o=n.withWebmDuration(a,s.durationMs);if(o===null)return{...i,stats:s};let c=n.inspectClipBytes(o);return c===null||c.frames!==s.frames||c.durationMs!==s.durationMs?{...i,stats:s}:{...i,blob:new Blob([o],{type:i.blob.type}),stats:s}}var Ke=["magenta","yellow","green","blue"];var Be={magenta:"rgb(255, 72, 150)",yellow:"rgb(255, 190, 0)",green:"rgb(0, 238, 175)",blue:"rgb(25, 150, 255)",dark:"rgb(0, 0, 0)"};function ft(i){return Be[i]}var We=4,qe=4,D=i=>typeof i=="number"&&Number.isFinite(i);function O(i){if(typeof i!="object"||i===null)return!1;let e=i;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length<1||e.colours.length>8||!e.colours.every(r=>Ke.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==e.colours.length)return!1;let t=-1;for(let r of e.onsetsMs){if(!D(r)||r<0||r<=t)return!1;t=r}return!(!D(e.holdMs)||e.holdMs<=0||!D(e.endMs)||e.endMs<=t||!D(e.clipMs)||e.clipMs<e.endMs||e.clipMs>8e3)}function ye(i,e){return O(i)?Math.max(e,Math.ceil(i.clipMs)):e}function Me(i,e){let t=e.now??(()=>performance.now()),r=O(i)?i:void 0,n=[],a=null,s=null,o=null,c=!1,l=null,d=p=>{l=p;try{e.paint(p)}catch{}},u=p=>{let m=e.frames?.()??null;return m!==null&&o!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-o:p-(s??p)},f=(p,m,y=0)=>{if(c)return;let h=Math.max(0,p-u(t()));a=setTimeout(()=>{if(a=null,!c){if(y<We&&u(t())<p-qe){f(p,m,y+1);return}m()}},h)},g=p=>{if(r===void 0)return;let m=r.endMs;if(p>=r.colours.length){f(m,()=>d(null));return}let y=r.onsetsMs[p],h=p+1<r.onsetsMs.length?r.onsetsMs[p+1]:m;f(y,()=>{let b=u(t());if(b>m){l!==null&&d(null);return}let C=r.colours[p];d(C);let E=n.length===0?0:n[n.length-1].tMs;n.push({tMs:Math.max(E,Math.round(b)),colour:C});let M=y+r.holdMs;if(M<h){f(M,()=>{if(u(t())>m){l!==null&&d(null);return}d("dark"),g(p+1)});return}g(p+1)})};return{started(p){if(r===void 0||c||s!==null)return;s=p;let m=e.frames?.()??null;o=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),g(0)},stop(){c||(c=!0,a!==null&&clearTimeout(a),a=null,l!==null&&d(null))},report(){return r===void 0?void 0:{nonce:r.nonce,rendered:[...n]}}}}function Se(i,e,t=.92){return new Promise((r,n)=>{let a=i.videoWidth,s=i.videoHeight;if(!a||!s){n(new Error("video-not-ready"));return}let o=e.getContext("2d");if(!o){n(new Error("no-2d-context"));return}e.width=a,e.height=s,o.scale(-1,1),o.drawImage(i,-a,0),e.toBlob(c=>c?r(c):n(new Error("empty-keyframe")),"image/jpeg",t)})}var P=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 ze=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}),_=i=>Math.min(1,Math.max(0,i)),k=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...ze,...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:n}=e,a=this.lastTickAt===null?0:Math.max(0,(n-this.lastTickAt)/1e3);this.lastTickAt=n;let s={presence:0,single:1,centering:0,size:0,pose:0,sharpness:_(r.sharpness),exposure:_(r.exposure),motion:1};if(t!==null){s.presence=1,s.single=(t.extraFaces??0)>0?0:1;let d=this.geometryOf(t,e);s.centering=d.centering,s.size=d.size,s.pose=d.pose,s.motion=this.motionOf(d.center,d.iod,n)}else this.lastCenter=null,this.velocityEma=0;let o=Math.min(s.presence,s.single,s.centering,s.size,s.pose,s.sharpness,s.exposure,s.motion);this.p=_(this.p+(o>=this.t.Q_GOOD?this.t.RISE_PER_S*o:-this.t.FALL_PER_S*(1-o))*a),this.qWindow.push({at:n,q:o}),this.qWindow=this.qWindow.filter(d=>d.at>=n-this.t.READY_WINDOW_MS);let c=this.qWindow.map(d=>d.q);if(c.length>=3){let d=Math.min(...c),u=c.indexOf(d);c=c.filter((f,g)=>g!==u)}let l=this.p>=1&&c.every(d=>d>=this.t.Q_GOOD);return{at:n,q:o,p:this.p,factors:s,guidanceKey:this.guidanceOf(s,r,o),ready:l,accepted:o>=this.t.Q_GOOD}}geometryOf(e,t){let{box:r,eyes:n}=e,a={x:t.frameWidth/2,y:t.frameHeight/2},s=Math.min(t.frameWidth,t.frameHeight),o=n!==void 0?{x:(n.left.x+n.right.x)/2,y:(n.left.y+n.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},c=n!==void 0?Math.hypot(n.right.x-n.left.x,n.right.y-n.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,l=Math.hypot(o.x-a.x,o.y-a.y),d=c<=0?0:1-_(l/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*c)),u=s>0?c/s:0;this.lastSizeDirection=u<this.t.SIZE_IDEAL_MIN?"far":u>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;u<this.t.SIZE_HARD_MIN||u>this.t.SIZE_HARD_MAX?f=0:u<this.t.SIZE_IDEAL_MIN?f=(u-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):u>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-u)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let g=1;if(n!==void 0){let p=Math.abs(Math.atan2(n.right.y-n.left.y,n.right.x-n.left.x))*180/Math.PI;g=1-_(p/this.t.ROLL_MAX_DEG)}return{center:o,iod:c,centering:d,size:f,pose:g}}motionOf(e,t,r){let n=this.lastCenter;if(this.lastCenter={...e,at:r},n===null||t<=0)return 1;let a=(r-n.at)/1e3;if(a<=0)return 1;let s=Math.hypot(e.x-n.x,e.y-n.y)/t/a;s<=this.t.MOTION_DEADBAND_IOD_PER_S&&(s=0);let o=1-Math.exp(-a/this.t.MOTION_TAU_S);return this.velocityEma=o*s+(1-o)*this.velocityEma,1-_(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,r){if(e.presence<=0)return"fcv3.no_face";if(e.single<=0)return"fcv3.one_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 n=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],a=n[0];for(let s of n)e[s[0]]<e[a[0]]&&(a=s);return a[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(L[0]+L[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Xe=["single","size","centering","pose","exposure","sharpness","motion"];function Ze(i){if(i.accepted)return null;if(i.factors.presence<=0)return"no_face";let e="single";for(let t of Xe)i.factors[t]<i.factors[e]&&(e=t);return e}var w=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=Ze(e);if(r===null){this.acceptedMs+=t;return}let n=this.blocked[r]??{count:0,ms:0};n.count+=1,n.ms+=t,this.blocked[r]=n}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 Qe=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ye=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^caméra (avant|arrière)\b/i,/^cámara (frontal|trasera|delantera)\b/i,/^câmera (frontal|traseira)\b/i,/^(front|rück)kamera\b/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 je(i){let e=(i??"").trim().toLowerCase();return e.length===0?"unknown":Qe.some(t=>e.includes(t))?"known_virtual":Ye.some(t=>t.test(e))?"platform":"unknown"}function Te(i){if(typeof i!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(i))}catch{return!1}}function $e(i=globalThis){return Te(i.navigator?.mediaDevices?.getUserMedia)&&Te(i.MediaStreamTrack?.prototype?.getSettings)}async function Je(i,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(i)));return Array.from(r.subarray(0,8),n=>n.toString(16).padStart(2,"0")).join("")}catch{return}}async function Ce(i,e=globalThis){let t={};try{t=typeof i.getSettings=="function"?i.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 a=await Je(t.deviceId,e);a!==void 0&&(r.deviceIdHash=a)}let n;try{n=i.label}catch{n=void 0}return{trackSettings:r,capabilitiesPresent:typeof i.getCapabilities=="function",labelClass:je(n),prototypesIntact:$e(e)}}var K=i=>Math.round(i*100)/100;function Ee(i){let e=i,t=typeof e?.requestVideoFrameCallback=="function",r=null,n=null,a=0,s=0,o=0,c=0,l=0,d=0,u=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((f,g)=>{if(r=null,!t)return;let p=g.presentationTime;if(n!==null){let m=p-n.presentationTimeMs;s+=1;let y=m-o;o+=y/s,c+=y*(m-o)}typeof g.captureTime=="number"&&Number.isFinite(g.captureTime)&&(l+=p-g.captureTime,d+=1),a+=1,n={mediaTimeMs:g.mediaTime*1e3,presentationTimeMs:p},u()}))};return u(),{latest:()=>n,stats:()=>({n:a,meanGapMs:s===0?0:K(o),stdGapMs:s<2?0:K(Math.sqrt(c/(s-1))),captureLatencyMs:d===0?null:K(l/d)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function _e(i,e,t){return{...i,rvfc:e,rampPainter:t}}var et=1e3,B="fcv3.hold_upright",tt=200,W=4,rt=600,nt=1e3,Re={sharpness:1,exposure:1,meanLuma:128};function it(i,e){return e.width=i.videoWidth,e.height=i.videoHeight,e.getContext("2d").drawImage(i,0,0),new Promise((t,r)=>e.toBlob(n=>n?t(n):r(new Error("empty-keyframe")),"image/jpeg",.92))}function at(){return X()==="phone"}var ke=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()}restart(e){this.facing=e,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??at)(),this.setState("preflight");let r=$();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let n=t.getUserMedia??(l=>navigator.mediaDevices.getUserMedia(l)),a;this.cameraRequestedAt=this.now();try{let{facingMode:l,...d}=z(Z(),this.facing).video;a=await ie(this.facing,d,{getUserMedia:n,enumerateDevices:lt(t)})}catch(l){if(e!==this.attempt)return;if(l instanceof ne){this.fail("backcamera",{phase:"acquiring",name:R(l)});return}this.fail(ee(l),{phase:"acquiring",name:R(l)});return}if(te(a),re(a),e!==this.attempt){for(let l of a.getTracks())l.stop();return}this.stream=a;let s=a.getVideoTracks?.()[0];if(this.trackProvenance=s===void 0?null:Ce(s).catch(()=>null),this.facing=Q(a)??this.facing,t.video.srcObject=a,await t.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let l={v3AssetBaseUrl:t.v3AssetBaseUrl},d=t.createDetector??(t.createWorker!==void 0&&oe()?async()=>{try{return await le.create(t.createWorker(),l)}catch{return G(l)}}:()=>G(l)),u;try{u=await d()}catch(f){e===this.attempt&&this.fail("models",{phase:"models",name:R(f)},f instanceof ae?f.fallbackReason:ot(f));return}if(e!==this.attempt){u.destroy();return}this.detector=u,this.options.telemetry?.({type:"detector",tier:u.tier,fallbackReason:u.fallbackReason})}let o=ce(),c=t.deviceClass??ue(o);this.profiler=new de(c),this.options.telemetry?.({type:"profile",staticClass:c,activeClass:this.profiler.deviceClass,simd:o.simd}),this.gate=new k(t.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(l=>q=l,()=>{}),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 n=this.scheduler.stats();this.carriedDegrade+=n.degradeCount,n.meanDetectMs>0&&this.carriedMeans.push(n.meanDetectMs),this.scheduler.stop()}let r=new P({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:n}=this,a=this.options.video;if(e!==this.attempt||t===null||r===null||n===null||this.fired||a.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let s=n.deviceClass,o=this.now(),c=this.options.makeSnapshot?.(a,n.profile.inputWidth)??this.defaultSnapshot(a,n.profile.inputWidth),l=null;try{l=await t.detect(c,a.videoWidth,a.videoHeight)}catch{l=null}if(e!==this.attempt||this.fired)return;n.record(this.now()-o),n.deviceClass!==s&&this.startScheduler(e);let d=l===null?Re:this.options.measureQuality?.(a,l.box)??this.defaultQuality(a,l.box),u=r.tick({timestampMs:this.now(),observation:l,quality:d,frameWidth:a.videoWidth,frameHeight:a.videoHeight});u.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=u.at),this.blockStats?.record(u),!u.ready&&u.at-this.lastGateSnapshotAt>=et&&(this.lastGateSnapshotAt=u.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:u.p,q:u.q,factors:u.factors,attempt:e}),u.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=u.guidanceKey,this.emit("guidance",{key:u.guidanceKey})),u.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=u.at,this.fire(e))}async fire(e){let{options:t}=this,r=this.scheduler;r?.stop(),this.reportGate(!0);let n=r?.stats()??{degradeCount:0,meanDetectMs:0},a=[...this.carriedMeans,...n.meanDetectMs>0?[n.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+n.degradeCount,meanDetectMs:a.length===0?0:a.reduce((M,v)=>M+v,0)/a.length});let s=t.mode??"clip",o=t.rankKeyframes?.()&&q?q.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(s==="photo"){let M=this.watchRotation(e,null),v=await o;if(M(),e!==this.attempt)return;if(v===null){this.fail("generic",{phase:"keyframes"});return}let x=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:v.blob,previewDataUrl:v.previewDataUrl,...x});return}this.setState("recording");let c=this.stream;if(c===null){this.fail("generic",{phase:"recording"});return}let l=t.screenRamp?.(),d=O(l),u=null;o.then(M=>{u=M},()=>{});let f=()=>{e===this.attempt&&u!==null&&this.emit("frozen",{previewDataUrl:u.previewDataUrl})},g=ye(l,U),p=null,m,y=0;try{let M=this.recordTake(e,c,l,g,void 0).then(T=>T,T=>({failed:T})),[v,x]=await Promise.all([M,o]);if(m=x,e!==this.attempt)return;if("failed"in v){if(v.failed.kind==="cliptoolarge")throw v.failed;V(v.failed.requestedMimeType??"")}else p=v,H(v.clip,g)?v.clip.stats===null&&V(v.clip.requestedMimeType??""):f();if(p===null||H(p.clip,g)){y=1,t.telemetry?.({type:"clip_retake",reason:p===null?"error":p.clip.stats===null?"unreadable":"short"});let T=null;try{T=await this.recordTake(e,c,l,g,f)}catch(Ae){if(p===null)throw Ae}if(e!==this.attempt)return;T!==null&&(p===null||be(T.clip,p.clip))&&(p=T),T===null&&f()}}catch(M){if(e!==this.attempt)return;let v=M.kind;this.fail(v==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:R(M)});return}if(p===null){this.fail("recorder",{phase:"recording"});return}let{clip:h,rvfc:b,report:C}=p;if(A(h.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(m===null){this.fail("generic",{phase:"keyframes"});return}let E=await this.provenance(b,d);e===this.attempt&&this.finishCapture({clip:h.blob,clipMimeType:h.mimeType,...h.stats?{clipStats:h.stats}:{},clipRetakes:y,keyframe:m.blob,previewDataUrl:m.previewDataUrl,...C!==void 0&&C.rendered.length>0?{screenRamp:C}:{},...E})}async recordTake(e,t,r,n,a){let s=this.options.createRecorder?.()??new I({now:()=>this.now()}),o=Ee(this.options.video),c=Me(r,{paint:u=>{(u===null||e===this.attempt)&&this.emit("ramp",{colour:u})},now:()=>this.now(),frames:o.latest});this.ramp=c;let l=()=>{o.stop(),c.stop(),this.ramp===c&&(this.ramp=null)},d=this.watchRotation(e,s);try{return{clip:await s.record(t,a,()=>c.started(this.now()),n,o),rvfc:o.stats(),report:c.report()}}finally{d(),l()}}async provenance(e,t){let r=this.trackProvenance;if(r===null)return{};let n,a=new Promise(o=>{n=setTimeout(()=>o(null),nt)}),s=await Promise.race([r,a]);return clearTimeout(n),s===null?{}:{provenance:_e(s,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,single:1,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==B&&(this.lastGuidanceKey=B,this.emit("guidance",{key:B}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,n=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){o();return}r.videoWidth>0&&this.isLandscape()&&(o(),this.abortRecording(e,t))},a=setInterval(n,tt);r.addEventListener?.("resize",n);let s=!1;function o(){s||(s=!0,clearInterval(a),r.removeEventListener?.("resize",n))}return o}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 k(this.options.thresholds??{}),this.blockStats=new w,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??(a=>this.defaultKeyframe(a)),r=rt/(W-1),n=null;for(let a=0;a<W;a+=1){if(e!==this.attempt)return n;try{let s=await t(this.options.video);(n===null||s.sharpness>n.sharpness)&&(n=s)}catch{}a<W-1&&await st(r)}return n}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,n,a)=>{n!==null&&a!==null&&(e[r]=Math.max(0,Math.round(a-n)))};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:it)(e,t),n=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:n,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),n=t/Math.max(1,e.videoWidth),a=Math.max(1,Math.round(e.videoWidth*n)),s=Math.max(1,Math.round(e.videoHeight*n)),o=r.getContext("2d");return o===null?e:(r.width!==a&&(r.width=a),r.height!==s&&(r.height=s),o.drawImage(e,0,0,a,s),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,t){let r=we(e,t,96);return r===null?Re:{sharpness:F(r),exposure:me(r),meanLuma:pe(r)}}centerSharpness(e){let t=se(e),r=we(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:F(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 n=t.summary();e&&(this.blockStats=null),n.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...n})}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:n,name:a}=t;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:a===void 0?{phase:n}:{phase:n,name:a}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},q;function st(i){return new Promise(e=>setTimeout(e,i))}function ot(i){return i instanceof Error?i.message:String(i)}function we(i,e,t){try{let r=document.createElement("canvas"),n=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*n)),r.height=Math.max(1,Math.round(e.height*n));let a=r.getContext("2d");return a===null?null:(a.drawImage(i,e.x,e.y,e.width,e.height,0,0,r.width,r.height),a.getImageData(0,0,r.width,r.height))}catch{return null}}function lt(i){if(i.enumerateDevices!==void 0)return i.enumerateDevices;if(i.getUserMedia===void 0&&!(typeof navigator>"u"||typeof navigator.mediaDevices?.enumerateDevices!="function"))return()=>navigator.mediaDevices.enumerateDevices()}export{ut as a,U as b,Pe as c,xe as d,ve as e,Ge as f,Le as g,Fe as h,Ve as i,S as j,Ue as k,H as l,be as m,I as n,Ke as o,ft as p,Se as q,P as r,ze as s,k as t,Ze as u,w as v,et as w,B as x,tt as y,W as z,rt as A,nt as B,ke as C};
@@ -0,0 +1 @@
1
+ import{a as re,d as ne,e as B,f as se,g as oe}from"./chunk-7QZWBDI5.js";import{C as te,a as X}from"./chunk-65YTEYLU.js";import{f as j,l as J}from"./chunk-CPUECYAJ.js";import{c as Z}from"./chunk-TSA6GHUG.js";import{c as ee,h as L}from"./chunk-FSSMUAKC.js";var ve=12e4,ie=13e4,ge=3e3,he=1200,D=Symbol.for("@sekyro/web.preload.v1");function h(){let e=globalThis;return e[D]??(e[D]=new Map),e[D]}function b(e){let r=(e??ee).replace(/\/+$/,"");return r===""?"/":r}function ae(e){let r=h(),n=r.get(e);return n===void 0&&(n={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},r.set(e,n)),n}function k(e,r){if(e.status!==r){e.status=r;for(let n of[...e.listeners])n(r)}}var K=e=>L({preferred:["blaze"],v3AssetBaseUrl:e,blazeInitTimeoutMs:ve}),H=K;function Te(e){H=e??K}function Oe(){for(let e of h().values())e.detector?.destroy();h().clear(),H=K}function Ce(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function Se(){return navigator.connection?.saveData===!0}function Ee(e){let r=window;if(typeof r.requestIdleCallback=="function"){let s=r.requestIdleCallback(e,{timeout:ge});return()=>r.cancelIdleCallback?.(s)}let n=setTimeout(e,he);return()=>clearTimeout(n)}function ye(e,r){let n,s=new Promise(d=>{n=d}),m=!1,u=()=>{},c={promise:s,settle:d=>{m||(m=!0,u(),e.scheduled===c&&(e.scheduled=null),n(d))}};return e.scheduled=c,u=Ee(()=>{m||c.settle(U(e,r))}),s}function U(e,r){if((e.status==="loading"||e.status==="ready")&&e.promise!==null)return e.promise;k(e,"loading");let n=new Promise(d=>d(H(r)));e.detectorPromise=n;let s,m=new Promise((d,f)=>{s=setTimeout(()=>{n.then(C=>C.destroy(),()=>{}),f(new Error(`detector preload exceeded ${ie} ms`))},ie)}),c=Promise.race([n,m]).then(d=>e.detectorPromise!==n?(d.destroy(),e.status):(e.detector=d,k(e,"ready"),"ready"),d=>(e.detectorPromise===n&&(e.detectorPromise=null,e.detector=null,k(e,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",d)),e.status)).finally(()=>clearTimeout(s));return e.promise=c,e.scheduled?.settle(c),c}function xe(e={}){if(!Ce())return Promise.resolve("idle");let r=b(e.assetBaseUrl),n=ae(r);return e.respectSaveData===!0&&Se()?Promise.resolve(n.status):(n.status==="loading"||n.status==="ready")&&n.promise!==null?n.promise:e.idle===!0?n.scheduled?.promise??ye(n,r):U(n,r)}function Fe(e){return h().get(b(e))?.status??"idle"}function Ie(e,r){let n=ae(b(r));return n.listeners.add(e),()=>{n.listeners.delete(e)}}function Be(e){let r=h().get(b(e));r!==void 0&&(r.scheduled?.settle("idle"),r.detector?.destroy(),r.detector=null,r.detectorPromise=null,r.promise=null,k(r,"idle"))}function Le(e){return{get tier(){return e.tier},get fallbackReason(){return e.fallbackReason},detect:(...r)=>e.detect(...r),destroy:()=>{}}}function de(e){let r=b(e),n=h().get(r);if(!(n===void 0||n.detector===null&&n.detectorPromise===null&&n.scheduled===null))return async()=>{n.scheduled!==null&&U(n,r);let s=n.promise;for(;n.detector===null&&s!==null&&(await s,n.promise!==s);)s=n.promise;return n.detector!==null?Le(n.detector):L({v3AssetBaseUrl:r})}}var be=new Set(["inuse","overconstrained","notfound"]),Me=[500,1500];function Ae(e){switch(e){case"fcv3.no_face":case"fcv3.center_face":case"fcv3.straighten":return"center";case"fcv3.come_closer":return"closer";case"fcv3.move_back":return"farther";case"fcv3.more_light":case"fcv3.too_bright":return"light";case"fcv3.hold_still":case"fcv3.steady_camera":return"still";case"fcv3.hold_upright":return"upright";case"fcv3.one_face":return"one_face";default:return null}}function Pe(e){switch(e){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";default:return e}}function ue(e){switch(e){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return e;case"backcamera":return"notfound";default:{let r=e;return"generic"}}}function we(e,r,n){if(n===void 0)return{kind:ue(e),retryable:r};let s=J(n.name);return{kind:ue(e),retryable:r,detail:{...s!==void 0?{name:s}:{},phase:n.phase,engineKind:e}}}var _e=new Set(["captured","uploading","checking"]);function De(e,r={},n,s=()=>"self",m=()=>{},u){let c=r.now??(()=>performance.now()),d=r.canChooseFacing??ne,f="user",C=se(),p=s(),l=re(),V=!j(),G=r.engineOptions,ce=G?.createDetector===void 0&&G?.createWorker===void 0?{createDetector:()=>{let t=de(e.assetBaseUrl);return t!==void 0?t():L({v3AssetBaseUrl:e.assetBaseUrl})}}:{},z={video:e.video,mode:V?"photo":"clip",rankKeyframes:n,facingMode:void 0,v3AssetBaseUrl:e.assetBaseUrl,screenRamp:()=>p==="self"&&l.count("ramp")>0?m():void 0,...r.engineOptions??{},...ce},a=r.createEngine?.(z)??new te(z),v="idle",M=null,A=0,R=!1,T="full",P=null,w=null,O=0,x=0,W=()=>{e.video.videoWidth>0&&e.video.videoHeight>0&&(O=e.video.videoWidth,x=e.video.videoHeight)},q=oe({enabled:e.keepScreenAwake!==!1}),S=t=>{v=t,q.setActive(t==="starting"||t==="gating"||t==="recording"),l.emit("state",t)},F=()=>l.emit("gate",{progress:A,hint:M,faceDetected:R}),I=()=>{let t=a.animations??"full";t!==T&&(T=t,l.emit("profile",{animations:T}))},g=0,_=null,le=r.schedule??((t,o)=>{let i=setTimeout(t,o);return()=>clearTimeout(i)}),E=()=>{_?.(),_=null},fe=(t,o)=>{if(y||!be.has(t)||o?.phase!=="acquiring")return!1;let i=Me[g];return i===void 0?!1:(g+=1,E(),_=le(()=>{_=null,y||a.retry()},i),!0)},pe=[a.on("statechange",({state:t})=>{if(t==="error")return;let o=Pe(t);o==="gating"&&(g=0),o==="starting"&&v!=="starting"&&(M=null,A=0,R=!1,P=null,w=null,O=0,x=0),S(o),I(),o==="recording"&&(W(),P=c(),M="hold",A=1,F())}),a.on("checks",t=>{W(),A=t.progress,R=t.factors.presence>0,F(),I()}),a.on("guidance",({key:t})=>{M=Ae(t),F()}),a.on("frozen",({previewDataUrl:t})=>{w=c(),l.emit("frozen",{previewDataUrl:t})}),a.on("ramp",t=>l.emit("ramp",t)),a.on("artifacts",t=>{if(v!=="captured")return;let o=Z(),i=t.clipStats,Q=i!==void 0?Math.round(i.durationMs):P!==null&&w!==null?Math.max(0,Math.round(w-P)):void 0,Y=i!==void 0&&i.frames>1&&i.durationMs>0?Math.round(i.frames*1e4/i.durationMs)/10:void 0;l.emit("captured",{keyframe:t.keyframe,...t.clip!==void 0?{clip:t.clip}:{},...t.clipMimeType!==void 0?{clipMime:t.clipMimeType}:{},width:e.video.videoWidth||O,height:e.video.videoHeight||x,...Q!==void 0?{clipMs:Q}:{},...i!==void 0?{clipFrames:i.frames}:{},...Y!==void 0?{fps:Y}:{},...t.clipRetakes!==void 0?{clipRetakes:t.clipRetakes}:{},...t.clipMimeType!==void 0?{codec:X(t.clipMimeType)}:{},captureChannel:o==="desktop"?"desktop":"mobile",formFactor:o,...V?{degraded:"NO_RECORDER"}:{},engine:"v3",facingMode:a.facingMode,mode:p,...t.timing,...t.screenRamp!==void 0?{screenRamp:t.screenRamp}:{},...t.provenance!==void 0?{provenance:t.provenance}:{}})}),a.on("error",({kind:t,retryable:o,detail:i})=>{t==="backcamera"&&me()||fe(t,i)||(S("error"),I(),l.emit("error",we(t,o,i)))})],N=!1;function me(){return y||N||p!=="assisted"||u===void 0||u.session()!=="choice"?!1:(N=!0,u.onModeChange("self"),p="self",f=B("self"),S("mode_switch"),a.restart(f),!0)}let $=async()=>u!==void 0&&u.session()==="choice"&&await d().catch(()=>!1),y=!1;return{handle:{get state(){return v},get captureMode(){return s()},get facingMode(){return a.facingMode??f},on:(t,o)=>l.on(t,o),start:t=>(p=s(),C.facing(p,e.facing),f=C.facing(p,t?.facing),E(),g=0,a.start({facingMode:f})),retry:()=>{E(),g=0,a.retry()},switchCamera:()=>C.refuseSwitch(s()),canSwitchCaptureMode:$,setCaptureMode:async t=>{if(t===s()||!await $()||y||_e.has(v)||u===void 0)return!1;u.onModeChange(t),p=t;let o=B(t);return f=o,v==="idle"||(S("mode_switch"),E(),g=0,a.restart(o)),!0},destroy:()=>{y=!0,E();for(let t of pe)t();q.setActive(!1),a.destroy(),l.clear()}},setFlowState:t=>{v!==t&&S(t)}}}function Ze(e){return De(e).handle}export{ve as a,ie as b,Te as c,Oe as d,xe as e,Fe as f,Ie as g,Be as h,de as i,Ae as j,Pe as k,ue as l,we as m,De as n,Ze as o};
@@ -1 +1 @@
1
- import{d as x}from"./chunk-R3JMNYW5.js";import{b}from"./chunk-FPXL63KZ.js";var T=480,y=Object.freeze({MIN_AREA_FRAC:.15,EDGE_CLIP_MARGIN_PX:4,STABLE_TICKS:3,IOU_STABLE_MIN:.85,RISE_PER_S:.9,FALL_PER_S:.25,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,ID3_BAND_MIN_WIDTH_FRAC:.55,ID3_BAND_ASPECT_MIN:4,ID3_BAND_ASPECT_MAX:40}),p=e=>Math.min(1,Math.max(0,e));function E(e,o,t){let n=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let s=0;s<4;s++){let r=n[s],c=n[(s+1)%4];i+=r.x*c.y-c.x*r.y}let a=o*t;return a>0?Math.abs(i/2)/a:0}function I(e,o){let t=D(e),n=D(o),i=Math.max(t.x1,n.x1),a=Math.max(t.y1,n.y1),s=Math.min(t.x2,n.x2),r=Math.min(t.y2,n.y2),c=Math.max(0,s-i)*Math.max(0,r-a),u=(t.x2-t.x1)*(t.y2-t.y1),_=(n.x2-n.x1)*(n.y2-n.y1),m=u+_-c;return m>0?c/m:0}function R(e){let o=D(e);return{width:o.x2-o.x1,height:o.y2-o.y1}}function D(e){let o=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft];return{x1:Math.min(...o.map(t=>t.x)),y1:Math.min(...o.map(t=>t.y)),x2:Math.max(...o.map(t=>t.x)),y2:Math.max(...o.map(t=>t.y))}}function M(e){let o=Math.hypot(e.topRight.x-e.topLeft.x,e.topRight.y-e.topLeft.y),t=Math.hypot(e.bottomRight.x-e.bottomLeft.x,e.bottomRight.y-e.bottomLeft.y),n=Math.hypot(e.bottomLeft.x-e.topLeft.x,e.bottomLeft.y-e.topLeft.y),i=Math.hypot(e.bottomRight.x-e.topRight.x,e.bottomRight.y-e.topRight.y),a=(o+t)/2,s=(n+i)/2;return a<=0||s<=0?0:Math.max(a,s)/Math.min(a,s)}var d=class{constructor(o,t={}){this.p=0;this.lastTickAt=null;this.lastQuad=null;this.streak=0;this.format=o,this.t={...y,...t}}reset(){this.p=0,this.lastTickAt=null,this.lastQuad=null,this.streak=0}tick(o){let{quad:t,quality:n,timestampMs:i}=o,a=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let s=null;if(t===null)s="dcv1.no_doc";else if(this.format==="ID-3"){let h=R(t),f=h.height>0?h.width/h.height:0;h.width<this.t.ID3_BAND_MIN_WIDTH_FRAC*o.frameWidth?s="dcv1.come_closer":this.edgeClipped(t,o.frameWidth,o.frameHeight)?s="dcv1.fit_document":(f<this.t.ID3_BAND_ASPECT_MIN||f>this.t.ID3_BAND_ASPECT_MAX)&&(s="dcv1.wrong_shape")}else E(t,o.frameWidth,o.frameHeight)<this.t.MIN_AREA_FRAC?s="dcv1.come_closer":this.edgeClipped(t,o.frameWidth,o.frameHeight)?s="dcv1.fit_document":x(this.format,M(t))||(s="dcv1.wrong_shape");let r=s===null,c=p(n.exposure)>=this.t.GUIDE_EXPOSURE,u=p(n.sharpness)>=this.t.GUIDE_SHARPNESS,_=c&&u;if(r&&_&&t!==null){let h=this.lastQuad===null||I(t,this.lastQuad)>=this.t.IOU_STABLE_MIN;this.streak=h?this.streak+1:1}else this.streak=0;this.lastQuad=t;let m=r&&_;this.p=p(this.p+(m?this.t.RISE_PER_S:-this.t.FALL_PER_S)*a);let A=m&&this.streak>=this.t.STABLE_TICKS,l;if(s!==null)l=s;else if(c)u?l="dcv1.hold_still":l="dcv1.steady";else{let h=(b[0]+b[1])/2;l=n.meanLuma<h?"dcv1.more_light":"dcv1.too_bright"}return{at:i,quad:t,plausible:r,p:this.p,guidanceKey:l,ready:A,stableTicks:this.streak}}edgeClipped(o,t,n){let i=this.t.EDGE_CLIP_MARGIN_PX;return[o.topLeft,o.topRight,o.bottomRight,o.bottomLeft].some(s=>s.x<=i||s.y<=i||s.x>=t-i||s.y>=n-i)}};export{T as a,y as b,E as c,I as d,R as e,d as f};
1
+ import{d as x}from"./chunk-MJKHDXCU.js";import{b}from"./chunk-FPXL63KZ.js";var T=480,y=Object.freeze({MIN_AREA_FRAC:.15,EDGE_CLIP_MARGIN_PX:4,STABLE_TICKS:3,IOU_STABLE_MIN:.85,RISE_PER_S:.9,FALL_PER_S:.25,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,ID3_BAND_MIN_WIDTH_FRAC:.55,ID3_BAND_ASPECT_MIN:4,ID3_BAND_ASPECT_MAX:40}),p=e=>Math.min(1,Math.max(0,e));function E(e,o,t){let n=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let s=0;s<4;s++){let r=n[s],c=n[(s+1)%4];i+=r.x*c.y-c.x*r.y}let a=o*t;return a>0?Math.abs(i/2)/a:0}function I(e,o){let t=D(e),n=D(o),i=Math.max(t.x1,n.x1),a=Math.max(t.y1,n.y1),s=Math.min(t.x2,n.x2),r=Math.min(t.y2,n.y2),c=Math.max(0,s-i)*Math.max(0,r-a),u=(t.x2-t.x1)*(t.y2-t.y1),_=(n.x2-n.x1)*(n.y2-n.y1),m=u+_-c;return m>0?c/m:0}function R(e){let o=D(e);return{width:o.x2-o.x1,height:o.y2-o.y1}}function D(e){let o=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft];return{x1:Math.min(...o.map(t=>t.x)),y1:Math.min(...o.map(t=>t.y)),x2:Math.max(...o.map(t=>t.x)),y2:Math.max(...o.map(t=>t.y))}}function M(e){let o=Math.hypot(e.topRight.x-e.topLeft.x,e.topRight.y-e.topLeft.y),t=Math.hypot(e.bottomRight.x-e.bottomLeft.x,e.bottomRight.y-e.bottomLeft.y),n=Math.hypot(e.bottomLeft.x-e.topLeft.x,e.bottomLeft.y-e.topLeft.y),i=Math.hypot(e.bottomRight.x-e.topRight.x,e.bottomRight.y-e.topRight.y),a=(o+t)/2,s=(n+i)/2;return a<=0||s<=0?0:Math.max(a,s)/Math.min(a,s)}var d=class{constructor(o,t={}){this.p=0;this.lastTickAt=null;this.lastQuad=null;this.streak=0;this.format=o,this.t={...y,...t}}reset(){this.p=0,this.lastTickAt=null,this.lastQuad=null,this.streak=0}tick(o){let{quad:t,quality:n,timestampMs:i}=o,a=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let s=null;if(t===null)s="dcv1.no_doc";else if(this.format==="ID-3"){let h=R(t),f=h.height>0?h.width/h.height:0;h.width<this.t.ID3_BAND_MIN_WIDTH_FRAC*o.frameWidth?s="dcv1.come_closer":this.edgeClipped(t,o.frameWidth,o.frameHeight)?s="dcv1.fit_document":(f<this.t.ID3_BAND_ASPECT_MIN||f>this.t.ID3_BAND_ASPECT_MAX)&&(s="dcv1.wrong_shape")}else E(t,o.frameWidth,o.frameHeight)<this.t.MIN_AREA_FRAC?s="dcv1.come_closer":this.edgeClipped(t,o.frameWidth,o.frameHeight)?s="dcv1.fit_document":x(this.format,M(t))||(s="dcv1.wrong_shape");let r=s===null,c=p(n.exposure)>=this.t.GUIDE_EXPOSURE,u=p(n.sharpness)>=this.t.GUIDE_SHARPNESS,_=c&&u;if(r&&_&&t!==null){let h=this.lastQuad===null||I(t,this.lastQuad)>=this.t.IOU_STABLE_MIN;this.streak=h?this.streak+1:1}else this.streak=0;this.lastQuad=t;let m=r&&_;this.p=p(this.p+(m?this.t.RISE_PER_S:-this.t.FALL_PER_S)*a);let A=m&&this.streak>=this.t.STABLE_TICKS,l;if(s!==null)l=s;else if(c)u?l="dcv1.hold_still":l="dcv1.steady";else{let h=(b[0]+b[1])/2;l=n.meanLuma<h?"dcv1.more_light":"dcv1.too_bright"}return{at:i,quad:t,plausible:r,p:this.p,guidanceKey:l,ready:A,stableTicks:this.streak}}edgeClipped(o,t,n){let i=this.t.EDGE_CLIP_MARGIN_PX;return[o.topLeft,o.topRight,o.bottomRight,o.bottomLeft].some(s=>s.x<=i||s.y<=i||s.x>=t-i||s.y>=n-i)}};export{T as a,y as b,E as c,I as d,R as e,d as f};
@@ -1 +1 @@
1
- import{C as Me,F as ve,G as ie,H as Te,I as N,J as Y,d as q,e as Ce,f as Pe,g as Ae,i as Re,j as re,l as $,m as oe,o as we,p as xe,q as Ee,u as Ie}from"./chunk-SUANHBF4.js";import{c as _e,d as be,e as ke}from"./chunk-FPXL63KZ.js";import{c as j,h as J,i as Oe}from"./chunk-OUC57KMS.js";var Ne=["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 ut=["carte_identite","passport","residence_permit","drivers_license"],ct=["carte_identite","passport","residence_permit"];function dt(e,t){let n=e.byIssuer?.[t]??e.default;return ut.filter(i=>n==="*"?ct.includes(i):n.includes(i))}function Nn(e,t=Ne){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(i=>dt(e,i).length>0).sort()}function Le(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}var lt=640,pt=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),Ve=6,Fe=1500,He={sharpness:1,exposure:1,meanLuma:128},De=null;function ft(e,t){try{De??(De=document.createElement("canvas"));let n=De,i=96/Math.max(1,t.width);n.width=Math.max(1,Math.round(t.width*i)),n.height=Math.max(1,Math.round(t.height*i));let r=n.getContext("2d");if(r===null)return He;r.drawImage(e,t.x,t.y,t.width,t.height,0,0,n.width,n.height);let a=r.getImageData(0,0,n.width,n.height);return{sharpness:be(a),exposure:ke(a),meanLuma:_e(a)}}catch{return He}}async function mt(e,t){let n=e.source;return"convertToBlob"in n?n.convertToBlob({type:"image/jpeg",quality:t}):new Promise((i,r)=>{n.toBlob(a=>a===null?r(new Error("encode failed")):i(a),"image/jpeg",t)})}function Dn(e,t={}){let n=t.now??(()=>performance.now()),i=t.setTimer??((m,k)=>setTimeout(m,k)),r=t.clearTimer??(m=>clearTimeout(m)),a=t.encode??mt,d=t.quality??ft,c=e.tuningVersion??null,p=new Set,S=!1,g=e.video??null,w=null,h=t.grabFrame??null,y=null,O=1e3/Ve,E=null,I=null,v=!1,V=!1,D=Number.NEGATIVE_INFINITY,x=null,U=0,F=null,K=null,te=Promise.all([import("./icao-gate-T3BTOKFJ.js"),import("./icao-tuning-4ETMF53W.js"),import("./create-portrait-capture-5VGYZUOK.js"),import("./landmarker-KB7LVXAU.js"),import("./background-monitor-A7FKJOAG.js")]).then(async([m,k,A,T,H])=>{let R=k.resolveIcaoTuning(e.tuning,e.tuningVersion??void 0);R.background.required&&(I=H.createBackgroundMonitor({tuning:R.backgroundCheck,assetBaseUrl:e.assetBaseUrl??"/models-v3",...t.createSegmenter!==void 0?{createSegmenter:t.createSegmenter}:{},now:n})),w=m.createIcaoGate(R,{policy:e.policy??"reject"}),h??(h=A.defaultGrabber()),y=A.observe,O=1e3/Math.min(Ve,R.cadenceHz);let M=(t.createLandmarker??T.createFaceLandmarker)(e.assetBaseUrl??"/models-v3"),o=await new Promise((s,u)=>{let l=setTimeout(()=>{u(new Error("landmarker init timeout")),M.then(f=>f.close(),()=>{})},T.LANDMARKER_INIT_TIMEOUT_MS);M.then(f=>{clearTimeout(l),s(f)},f=>{clearTimeout(l),u(f)})});S?o.close():E=o}).catch(()=>{v=!0}),Z=m=>{for(let k of p)k({holding:V||v,update:m})},G=()=>{if(x=null,!(S||E===null||w===null||h===null||y===null||g===null)){if(n()-D>Fe){Z(null);return}try{let m=h(g,lt);if(m!==null){let k=Math.max(n(),U+1);U=k;let A=E.detect(m.source,k),T=g.videoWidth||m.width,H=g.videoHeight||m.height,R=y(A,m,T,H);R.geometry!==null&&I!==null&&(R.backgroundCheck=I.measure(m,R.geometry.box,T,H));let M=w.push(R,n());V=M.ready,Z(M)}}catch{}x=i(G,O)}},ne=()=>{let m=n()-D>Fe;D=n(),m&&(w?.reset(),V=!1,F=null,K=null),x===null&&E!==null&&!S&&(x=i(G,0))},W=()=>{let m=h===null||g===null?null:h(g,null);if(m===null||w===null||Math.max(m.width,m.height)<e.still.minLongSidePx)return Promise.resolve(null);let k=w.summary();return a(m,e.still.jpegQuality).then(A=>({image:A,width:m.width,height:m.height,gate:k}),()=>null)},Q=null;return{engineOptions:{measureQuality:(m,k)=>{g=m,ne();let A=d(m,k);return V||v?A:{...A,sharpness:0}},telemetry:m=>{if(m.type!=="fired"||S)return;F=W();let k=Q;k!==null&&F.then(A=>A===null?void 0:k(A).catch(()=>{})),V=!1,x!==null&&r(x),x=null,D=Number.NEGATIVE_INFINITY}},decorate:m=>{let k=new WeakMap,A=new Map,T=o=>{let s=k.get(o);return s===void 0&&(s=(async()=>{let u=await Ie(m,"image","image/jpeg",o.image.size,{engine:"portrait"});return await m.uploadToSpaces(u.uploadUrl,o.image,"image/jpeg"),(await m.completeMedia(u.key)).key})(),s.catch(()=>k.delete(o)),k.set(o,s)),s};Q=T;let H=async o=>{let s;try{s=await T(o)}catch(u){let l=u?.code;if(typeof l=="string"&&pt.has(l))throw u;return null}return{media:{portrait:s},gate:Oe(o.gate),...c!==null?{tuningVersion:c}:{}}},R=m.submitCheck.bind(m),M=(async(o,s,u)=>{if(o!=="liveness")return R(o,s,u);let l=u?.idempotencyKey,f=l===void 0?void 0:A.get(l);if(f===void 0){let b=F;f=b===null?Promise.resolve(null):b.then(ye=>ye===null?null:H(ye)),l!==void 0&&(A.set(l,f),f.catch(()=>A.delete(l)))}let _=await f;if(_===null)return R("liveness",s,u);let P=await R("liveness",{...s,portraitIcao:_},u);return K=_,P});return new Proxy(m,{get(o,s){if(s==="submitCheck")return M;let u=Reflect.get(o,s);return typeof u=="function"?u.bind(o):u}})},onGate:m=>(p.add(m),()=>p.delete(m)),lastPortraitInput:()=>K,destroy:()=>{S=!0,F=null,K=null,x!==null&&r(x),x=null,p.clear(),te.then(()=>{E?.close(),E=null,I?.close(),I=null})}}}function Ge(e){return e.idNumberBound??e.nniBound}function Be(e){return e===void 0?void 0:e.idNumberFromDocument??e.nniFromDocument}function Ue(e){let t=e.idNumberMasked??e.nniMasked;return typeof t=="string"&&t!==""?t:void 0}var Ke=Object.freeze({nni_invalid:"id_number_invalid",nni_not_found:"registry_record_not_found",nni_recheck:"id_number_recheck",document_nni_mismatch:"document_id_number_mismatch",nni_locked:"id_number_locked",nni_unbound:"id_number_unbound",missing_nni:"missing_id_number",registry_needs_nni_source:"registry_needs_id_number_source"}),ht=new Map(Object.entries(Ke)),Un=new Map(Object.entries(Ke).map(([e,t])=>[t,e]));function je(e){return ht.get(e)??e}var C={fullNameMin:2,fullName:200,email:254,occupation:120,shortText:120,longText:1e3,addressLine:120,addressLines:4,city:80,postcode:16,number:1e12,dateMin:"1900-01-01",dateMax:"2100-12-31"},St=new Set(["full_name","birth_date","email","phone","address","country","occupation"]),gt=new Set(["short_text","long_text","single_choice","multiple_choice","yes_no","date","number"]),yt=new Set(["ar","fa","he","ur"]);function qe(e){return yt.has(e.split("-")[0]?.toLowerCase()??"")?"rtl":"ltr"}function Ye(e){if(typeof e!="object"||e===null)return null;let t=e;if(typeof t.locale!="string"||!Array.isArray(t.questions)||t.questions.length===0)return null;let n=t.consents??[];if(!Array.isArray(n))return null;for(let r of t.questions)if(!_t(r))return null;for(let r of n)if(!bt(r))return null;let i={locale:t.locale,questions:t.questions,consents:n};return typeof t.title=="string"&&t.title.trim()!==""&&(i.title=t.title),typeof t.intro=="string"&&t.intro.trim()!==""&&(i.intro=t.intro),typeof t.prefill=="object"&&t.prefill!==null&&!Array.isArray(t.prefill)&&(i.prefill=t.prefill),i}function _t(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id!="string"||typeof t.required!="boolean"?!1:t.kind==="field"?typeof t.field=="string"&&St.has(t.field):t.kind!=="custom"||typeof t.type!="string"||!gt.has(t.type)||typeof t.label!="string"?!1:t.type==="single_choice"||t.type==="multiple_choice"?Array.isArray(t.choices)&&t.choices.length>=2&&t.choices.every(n=>typeof n=="object"&&n!==null&&typeof n.value=="string"&&typeof n.label=="string"):!0}function bt(e){if(typeof e!="object"||e===null)return!1;let t=e;if(typeof t.id!="string"||typeof t.required!="boolean"||typeof t.text!="string")return!1;if(t.link===void 0)return!0;let n=t.link;return typeof n=="object"&&n!==null&&typeof n.url=="string"&&/^https:\/\//.test(n.url)&&typeof n.label=="string"}var kt=/^(\d{4})-(\d{2})-(\d{2})$/;function Ct(e){if(typeof e!="string")return!1;let t=kt.exec(e);return t===null?!1:new Date(Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3]))).toISOString().slice(0,10)===e&&e>=C.dateMin&&e<=C.dateMax}function Pt(e){return typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<C.number&&Math.round(e*100)/100===e}function Ze(e){for(let t of e.matchAll(/\d[\d -]{11,}\d/g)){let n=t[0].replace(/[ -]/g,"");if(n.length>=13&&n.length<=19&&At(n))return!0}return!1}function At(e){let t=0;for(let n=0;n<e.length;n++){let i=Number(e[e.length-1-n]);n%2===1&&(i*=2,i>9&&(i-=9)),t+=i}return t%10===0}var Rt=/^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$/,wt=/^\+[1-9]\d{6,14}$/,We=/^[A-Z]{2}$/,xt=e=>e===void 0||typeof e=="string"&&e.trim()===""||Array.isArray(e)&&e.length===0;function Qe(e=Date.now()){return new Date(e).toISOString().slice(0,10)}function X(e,t,n=Qe()){let i=[];for(let r of e.questions){let a=t.answers[r.id];if(xt(a)){r.required&&i.push({id:r.id,code:"required"});continue}let d=r.kind==="field"?Et(r.field,a,n):Mt(r,a,n);d!==null&&i.push({id:r.id,...d})}for(let r of e.consents)r.required&&t.consents[r.id]!==!0&&i.push({id:r.id,code:"consent_required"});return i}function z(e,t,n=1){if(typeof e!="string")return{code:"required"};let i=e.trim();return[...i].length>t?{code:"too_long",params:{max:t}}:[...i].length<n?{code:"too_short",params:{min:n}}:Ze(i)?{code:"card_number"}:null}function $e(e,t,n={}){return Ct(e)?n.period==="past"&&e>=t?{code:"date_not_past"}:n.period==="future"&&e<=t?{code:"date_not_future"}:n.min!==void 0&&e<n.min?{code:"date_too_early",params:{date:n.min}}:n.max!==void 0&&e>n.max?{code:"date_too_late",params:{date:n.max}}:null:{code:"date_invalid"}}function Et(e,t,n){switch(e){case"full_name":return z(t,C.fullName,C.fullNameMin);case"occupation":return z(t,C.occupation);case"birth_date":return $e(t,n,{period:"past"});case"email":return typeof t=="string"&&t.trim().length<=C.email&&Rt.test(t.trim())?null:{code:"email_invalid"};case"phone":return typeof t=="string"&&wt.test(t)?null:{code:"phone_invalid"};case"country":return typeof t=="string"&&We.test(t)?null:{code:"choice_invalid"};case"address":return It(t)?null:{code:"address_invalid"};default:return null}}function It(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e,n=Array.isArray(t.lines)?t.lines.filter(i=>typeof i=="string"&&i.trim()!==""):[];return typeof t.country=="string"&&We.test(t.country)&&typeof t.city=="string"&&t.city.trim()!==""&&t.city.trim().length<=C.city&&n.length>=1&&n.length<=C.addressLines&&n.every(i=>i.trim().length<=C.addressLine&&!Ze(i))&&(t.postcode===void 0||typeof t.postcode=="string"&&t.postcode.trim().length<=C.postcode)}function Mt(e,t,n){let i=new Set((e.choices??[]).map(r=>r.value));switch(e.type){case"short_text":return z(t,C.shortText);case"long_text":return z(t,C.longText);case"single_choice":return typeof t=="string"&&i.has(t)?null:{code:"choice_invalid"};case"multiple_choice":return Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(r=>i.has(r))?null:{code:"choice_invalid"};case"yes_no":return typeof t=="boolean"?null:{code:"choice_invalid"};case"date":{let r=e.options??{};return $e(t,n,{...typeof r.min=="string"?{min:r.min}:{},...typeof r.max=="string"?{max:r.max}:{},...r.period==="past"||r.period==="future"?{period:r.period}:{}})}case"number":{if(typeof t!="number"||!Number.isFinite(t)||Math.abs(t)>=C.number)return{code:"number_invalid"};let r=e.options??{};return r.integer===!0&&!Number.isInteger(t)?{code:"number_not_integer"}:Pt(t)?typeof r.min=="number"&&t<r.min?{code:"number_too_small",params:{min:r.min}}:typeof r.max=="number"&&t>r.max?{code:"number_too_large",params:{max:r.max}}:null:{code:"number_decimals"}}default:return null}}function Je(e,t,n,i=Qe()){let r=e?.errors;return Array.isArray(r)?r.flatMap(a=>{if(typeof a!="object"||a===null)return[];let{id:d,code:c}=a;return typeof d!="string"||typeof c!="string"?[]:[vt(d,c,t,n)]}):X(t,n,i)}var Ot={full_name:C.fullName,occupation:C.occupation,email:C.email,short_text:C.shortText,long_text:C.longText};function vt(e,t,n,i){let r=n.questions.find(p=>p.id===e),a=r===void 0?void 0:r.kind==="field"?r.field:r.type,d=i.answers[e],c=r!==void 0&&r.kind==="custom"?r.options??{}:{};switch(t){case"required":case"card_number":return{id:e,code:t};case"consent_required":return{id:e,code:"consent_required"};case"too_short":return{id:e,code:t,params:{min:a==="full_name"?C.fullNameMin:1}};case"too_long":{let p=a===void 0?void 0:Ot[a];return p===void 0?{id:e,code:t}:{id:e,code:t,params:{max:p}}}case"not_a_choice":return{id:e,code:"choice_invalid"};case"not_in_past":return{id:e,code:"date_not_past"};case"not_in_future":return{id:e,code:"date_not_future"};case"not_an_integer":return{id:e,code:"number_not_integer"};case"out_of_range":return Tt(e,a,d,c);case"invalid":return r===void 0?n.consents.some(p=>p.id===e)?{id:e,code:"consent_required"}:{id:e,code:t}:{id:e,code:Nt(a,d)};default:return{id:e,code:t}}}function Tt(e,t,n,i){if(t==="date"){let c=typeof i.min=="string"?i.min:void 0,p=typeof i.max=="string"?i.max:void 0;return p!==void 0&&(c===void 0||typeof n=="string"&&n>p)?{id:e,code:"date_too_late",params:{date:p}}:c!==void 0?{id:e,code:"date_too_early",params:{date:c}}:{id:e,code:"date_invalid"}}let r=typeof i.min=="number"?i.min:void 0,a=typeof i.max=="number"?i.max:void 0;return a!==void 0&&(r===void 0||typeof n=="number"&&n>a)?{id:e,code:"number_too_large",params:{max:a}}:r!==void 0?{id:e,code:"number_too_small",params:{min:r}}:{id:e,code:"number_invalid"}}function Nt(e,t){switch(e){case"email":return"email_invalid";case"phone":return"phone_invalid";case"birth_date":case"date":return"date_invalid";case"number":return typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<C.number?"number_decimals":"number_invalid";case"address":return"address_invalid";case"full_name":case"occupation":case"short_text":case"long_text":return"required";default:return"choice_invalid"}}var Lt=new Set(["phone_otp","email_otp","national_eid","document","nfc","population_registry","supplied_identity","summary_confirm","liveness","portrait","face_match","aml_screening","face_dedup","age_estimation","proof_of_address","form"]),Vt=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),ae=["document","population_registry","national_eid"],ue=["phone_otp","email_otp"],et={identity_method:ae,contact:ue},Ft=["population_registry","document"],ce="platform_unsupported",Ht=new Set(["prefilled","user_entered","prefilled_or_entered"]),Dt={phone_otp:"contact",email_otp:"contact",eid_auth:"identity",doc_ocr:"identity",nfc_chip:"identity",population_registry:"identity",liveness:"live_photo",portrait_icao:"live_photo",face_match:"live_photo",poa:"documents",form:"form"};function L(e){return e.section??Dt[e.checkType]??null}function de(e,t){let n=e.plan?.choice;if(n===void 0||n.locked)return;let i=n.options.find(r=>r.id!==n.selected&&r.available!==!1&&t.includes(r.service));return i===void 0?void 0:{nodeId:n.nodeId,option:i}}function le(e){let t=e.plan,n=t?.choice;if(t===void 0||n===void 0||n.locked||t.current===null||t.current===n.nodeId||re(e))return null;let i=et[n.kind]??[...ae,...ue],r=n.options.flatMap(c=>c.available===!1||!i.includes(c.service)?[]:[c.nationalEid!=null?{id:c.id,service:c.service,nationalEid:c.nationalEid}:{id:c.id,service:c.service}]),a=t.steps.find(c=>c.id===t.current)?.service,d=n.selected??r.find(c=>c.service===a)?.id??null;return r.some(c=>c.id!==d)?{nodeId:n.nodeId,kind:n.kind,current:d,options:r}:null}function tt(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function Gt(e){let t=e.simulation;if(typeof t!="object"||t===null)return;let{otpCode:n,skipCapture:i}=t;if(typeof n!="string"||n===""||typeof i!="boolean")return;let r=xe(e);return r!==void 0?{otpCode:n,skipCapture:i,reason:r}:{otpCode:n,skipCapture:i}}function Bt(e){let t=(e.plan?.sections??[]).map(d=>({id:d.id,state:d.state})),n={sessionId:oe(e.sessionId),orgName:e.orgName,sandbox:e.sandbox===!0,returning:e.returning===!0,consentRecorded:e.consentRecorded,expiresAt:e.expiresAt,sections:t.map(d=>d.id),progress:t,purpose:e.purpose??"identity"};e.branding!==void 0&&(n.branding=e.branding),e.cameraUnavailableHandled===!0&&(n.cameraUnavailableHandled=!0);let i=Gt(e);i!==void 0&&(n.simulation=i);let r=e.testerGate;r?.offered===!0&&typeof r.attemptsLeft=="number"&&r.attemptsLeft>0&&(n.testerGate={attemptsLeft:r.attemptsLeft});let a=le(e);return a!==null&&(n.switchable=a),n}function Ut(e){let t={attemptsRemaining:Pe(e),attemptsExhausted:e.attempts.used>=e.attempts.max};return e.reason!==void 0&&(t.reason=e.reason),e.retakeHint!==void 0&&(t.retakeHint=e.retakeHint),t}var nt={phone_otp:"phone",email_otp:"email"};function Kt(e,t){let n=de(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return n===void 0?void 0:nt[n.option.service]}function jt(e,t,n,i){let r=t.checkType==="email_otp",a=(r?t.emailOtp:t.otp)??{},d=r?t.emailOtp?.emailSource:t.otp?.numberSource,c=d!==void 0&&Ht.has(d)?d:r?"prefilled_or_entered":"user_entered",p=typeof a.sentToMasked=="string"&&a.sentToMasked.length>0,S=a.prefilled===!0,g=Kt(e,r?"email_otp":"phone_otp"),w={key:t.checkType,context:n,section:L(t),phase:p?"verify":"send",canSwitch:g!==void 0,...i},h=r?{kind:"email_otp",...w,emailSource:c,needsEmail:c!=="prefilled"&&!S}:{kind:"phone_otp",...w,numberSource:c,needsPhone:c!=="prefilled"&&!S,channels:(t.otp?.channels??[]).filter(y=>y==="whatsapp"||y==="sms")};if(g!==void 0&&(h.switchChannel=g),S&&(h.prefilled=!0),p&&(h.sentToMasked=a.sentToMasked),!r&&t.otp?.channel!==void 0&&(h.channel=t.otp.channel),!r&&Array.isArray(t.phoneCountries)&&(h.phoneCountries=t.phoneCountries.filter(y=>typeof y=="string"&&/^[A-Z]{2}$/.test(y))),!r&&Array.isArray(t.phoneRules)){let y=h.phoneCountries??[];h.phoneRules=t.phoneRules.flatMap(O=>{let E=Zt(O);return E!==void 0&&y.includes(E.code)?[E]:[]})}return!r&&t.phoneInternational===!0&&(h.phoneInternational=!0),a.expiresAt!==void 0&&(h.codeExpiresAt=a.expiresAt),a.resendAvailableAt!==void 0&&(h.resendAvailableAt=a.resendAvailableAt),h}var qt=/^[\d[\]\-|()?:^]{1,64}$/;function Yt(e){try{return typeof e=="string"&&qt.test(e)&&new RegExp(e)!==null}catch{return!1}}var ze=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function Zt(e){let{code:t,dial:n,trunk:i,lengths:r,formats:a}=e??{};if(typeof t!="string"||typeof n!="string"||!/^\d{1,3}$/.test(n)||i!==void 0&&(typeof i!="string"||!/^\d{1,3}$/.test(i))||!Array.isArray(r)||r.length===0||!r.every(ze))return;let d={code:t,dial:n,lengths:[...r].sort((c,p)=>c-p)};if(i!==void 0&&(d.trunk=i),a!==void 0){if(!(Array.isArray(a)&&a.length<=8&&a.every(p=>Yt(p?.leading)&&Array.isArray(p.groups)&&p.groups.every(ze)&&r.includes(p.groups.reduce((S,g)=>S+g,0)))))return;d.formats=a.map(p=>({leading:p.leading,groups:[...p.groups]}))}return d}function Wt(e,t,n,i){let r=Ge(e)===!0?"bound":Be(t)===!0?"document":"typed",a=r==="typed"&&t.state==="input_required"&&t.reason!==void 0&&je(t.reason)==="id_number_recheck",d=tt(le(e)),c=!i.attemptsExhausted&&d.length===1&&d[0]?.service==="document";return{kind:"registry",key:"registry",context:n,section:L(t),state:t.state==="input_required"?"input_required":"pending",source:r,recheck:a,canUseDocument:c,...i}}function Qt(e,t,n,i,r){let a=[...t.acceptedSides??[]],d={kind:"document",key:"document",context:n,section:L(t),side:a.includes("recto")?"verso":"recto",acceptedSides:a,documents:Le(e),photo:fe(pe(e.documents),r),...i};return e.detectedCountry!==void 0&&(d.detectedCountry=e.detectedCountry),zt(e)&&(d.ageStepUp=!0),d}function pe(e,t=!0){let n=e?.source==="upload"||e?.source==="choice"?e.source:"camera",i=e?.sourcePick==="camera"||e?.sourcePick==="upload"?e.sourcePick:null;return{source:n,pick:i,uploadOffered:t&&e?.uploadOffered===!0}}function fe(e,t){return t?{...e,cameraOnPhone:!0}:e}var $t=10*1024*1024;function Jt(e,t,n,i,r){let a=e.proofOfAddress,d=a?.pdf?.maxBytes,c=a?.phase==="holder_letter"?"holder_letter":"document";return{kind:"proof_of_address",key:"proof_of_address",context:n,section:L(t),phase:c,rule:a?.rule??{country:null,countryFrom:"global",source:"preset_global",kinds:[]},nameMatch:a?.nameMatch??"exact_person",photo:fe(pe(a),r),maxPages:3,pdf:{maxBytes:typeof d=="number"&&d>0?d:$t,maxPages:3},licenceAddressAccepted:c==="document"&&a?.licenceAddressAccepted===!0,...i}}function zt(e){let t=Ce(e).find(i=>i.checkType==="age_estimation"),n=t?.reason;return t?.state==="failed"&&(n==="age_uncertain"||n==="age_unavailable")}function Xt(e){let t=$(e,"liveness");return t?.state==="passed"||t?.state==="review"}function Xe(e,t,n,i,r,a=!1){let d=t.icao?.report,c=e.portrait,p=r==="capture"?c?.pendingFix??null:null;p!==null&&(r="review");let S=rt(e);return{kind:"portrait",key:`portrait:${r}`,context:n,section:L(t),phase:r,report:Array.isArray(d)?d:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:J(e),retakeOnly:r==="capture"&&t.state==="input_required"&&S===void 0&&e.capture?.livePhoto?.oneCapture===!0&&Xt(e),photo:fe(pe(c,r==="capture"),a&&r==="capture"),pendingFix:p,...S!==void 0?{captureMode:S}:{},...c?.reuse?.pending===!0?{reuse:!0}:{},...i}}function rt(e){let t=e.portrait?.captureMode;return t==="self"||t==="assisted"||t==="choice"?t:void 0}var se={minLongSidePx:1280,jpegQuality:.95};function en(e,t){let n=e.capture?.livePhoto;if(n?.oneCapture!==!0)return null;let i=$(e,"portrait_icao"),r=n.still??se;return{icao:t==="liveness"&&J(e)!==null&&rt(e)===void 0&&i!==void 0&&i.state==="pending"&&i.reason===void 0,still:{minLongSidePx:r.minLongSidePx??se.minLongSidePx,jpegQuality:r.jpegQuality??se.jpegQuality}}}function tn(e,t,n,i){let r=t.eid,a=L(t);if(r===void 0||r.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:n,section:a,checkType:"eid_auth",reason:"update_required"};let d=tt(le(e)),c=d.length===1&&Ft.includes(d[0]?.service??"")?d[0]:void 0,p=c===void 0?void 0:q[c.service],S=p!==void 0,g={kind:"eid",key:"eid",context:n,section:a,provider:r.provider,providerName:r.providerName,country:r.country,challenge:"app_code",phase:r.awaiting==="code"?"code":"identifier",identifierBound:r.identifierBound===!0,canUseCamera:S,afterPass:r.afterPass==="continue"?"continue":"end",...i};return S&&(g.cameraMethod=p),r.expiresAt!==void 0&&(g.codeExpiresAt=r.expiresAt),r.resendAvailableAt!==void 0&&(g.resendAvailableAt=r.resendAvailableAt),r.resendsRemaining!==void 0&&(g.resendsRemaining=r.resendsRemaining),r.codeAttemptsRemaining!==void 0&&(g.codeAttemptsRemaining=r.codeAttemptsRemaining),g}function nn(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let n=$(e,"portrait_icao");return n!==void 0&&(n.state==="passed"||n.state==="review")?n:null}var rn={rejected:"rejected",inconclusive:"inconclusive",unavailable:"unavailable",abandoned:"expired",not_opened:"expired",cancelled:"expired",superseded:"expired",policy:"policy"};function on(e){return e.reasonCode===ce?"platform_unsupported":e.status==="review_pending"?"review":e.status==="verified"?"verified":e.reasonCode==="device_cooldown"?"cooldown":e.reasonCode==="starter_credit_claimed"?"policy":(e.status==="not_verified"&&e.reason!==void 0?rn[e.reason]:void 0)??"rejected"}function sn(e,t){let n=on(e),i=n==="platform_unsupported"?{sessionId:oe(e.sessionId),status:"unavailable",reasonCode:ce}:we(e,{autoRetry:!1}),r={kind:"result",key:"result",context:t,section:null,display:n,result:i};return e.status==="not_verified"&&e.reason!==void 0&&(r.reason=e.reason),e.reasonCode!==void 0&&(r.reasonCode=e.reasonCode),e.status==="not_verified"&&e.step!==void 0&&(r.step=e.step),e.retryAfter!==void 0&&(r.retryAfter=e.retryAfter),r}function an(e,t,n){let i=e.identitySummary;if(i==null)return null;let r={kind:"identity_summary",key:"identity_summary",context:t,section:n??"identity",summaryKind:i.kind==="partial"?"partial":i.kind??"full",source:i.source,portraitAvailable:i.portrait?.available===!0,retakeAvailable:i.retakeAvailable===!0};for(let d of un){let c=i[d];typeof c=="string"&&c!==""&&(r[d]=c)}let a=Ue(i);return a!==void 0&&(r.idNumberMasked=a,r.nniMasked=a),r}var un=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","expiryDate","retakeTarget"];function B(e,t,n,i){return{kind:"unsupported",key:`unsupported:${n}`,context:e,section:t,checkType:n,reason:i}}function cn(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function dn(e,t){let n=et[e.kind]??[...ae,...ue],i=cn(e),r=e.options.flatMap(d=>{if(d.available===!1||!n.includes(d.service))return[];let c={id:d.id,service:d.service};d.nationalEid!=null&&(c.nationalEid=d.nationalEid);let p=(d.channels??[]).filter(S=>S==="whatsapp"||S==="sms");return d.service==="phone_otp"&&p.length>0&&(c.channels=p),[c]});if(r.length===0){let d=e.options.length>0&&e.options.every(c=>c.service==="nfc");return B(t,i,"choice",d?"platform_unsupported":"update_required")}let a={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:r};if(e.kind==="identity_method"){let d={kind:"method",key:"method",context:t,section:i,options:r.map(p=>q[p.service]),choice:a},c=r.find(p=>p.nationalEid!==void 0)?.nationalEid;return c!==void 0&&(d.nationalEid=c),d}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:i,options:r.map(d=>nt[d.service]),selected:null,locked:!1,choice:a}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:i,choice:a}}function ln(e,t,n,i){let r=e.nativeApp,a=typeof r=="object"&&r!==null?r:{},d={sekyroApp:a.sekyroApp===!0};return typeof a.link=="string"&&a.link!==""&&(d.link=a.link),d.sekyroApp&&typeof a.sekyroAppLink=="string"&&a.sekyroAppLink.startsWith("sekyro://")&&(d.sekyroAppLink=a.sekyroAppLink),{kind:"native_app_required",key:`native_app_required:${i}`,context:t,section:n,checkType:i,nativeApp:d}}function ee(e,t={}){let n=Bt(e);if(re(e)||e.reasonCode===ce)return sn(e,n);let i=e.plan;if(i===void 0||!Array.isArray(i.sections))return B(n,null,"plan","update_required");let r=Ae(e);if(r!==null)return dn(r,n);let a=i.current===null?void 0:i.steps.find(h=>h.id===i.current),d=h=>{let y={kind:"processing",key:"processing",context:n,section:h!==void 0?L(h):i.sections.find(O=>O.state==="current")?.id??null,stalled:!1};return typeof h?.service=="string"&&h.service!==""&&(y.service=h.service),y};if(i.current===null)return d(i.steps.find(h=>h.state==="processing"));if(a===void 0)return B(n,null,"step","update_required");if(!Lt.has(a.service))return a.interaction==="server"?d(a):B(n,L(a),a.service,"update_required");if(Vt.has(a.service)||!Re(a))return d(a);let c=a,p=Ut(c),S=c.checkType,g=L(c);if(c.requiresNativeApp===!0)return ln(e,n,g,S);let w=t.isMobile===!1?Ee(e,c):null;if(w==="phone")return{kind:"mobile_required",key:"mobile_required",context:n,section:g,checkType:S};switch(S){case"phone_otp":case"email_otp":return jt(e,c,n,p);case"population_registry":return Wt(e,c,n,p);case"eid_auth":return tn(e,c,n,p);case"doc_ocr":return Qt(e,c,n,p,w==="upload_or_phone");case"identity_confirm":return an(e,n,g)??d(c);case"portrait_icao":return Xe(e,c,n,p,"capture",w==="upload_or_phone");case"liveness":case"face_match":{let h=nn(e,c);if(h!==null)return Xe(e,h,n,p,"match");let y=c.requiresMobile===!0,O=J(e);return{kind:"liveness",key:"biometric",context:n,section:g,mode:S==="face_match"?"selfie":"liveness",requiresMobile:y,instructions:O===null?"standard":"icao",icao:O,livePhoto:en(e,S),...p}}case"poa":return Jt(e,c,n,p,w==="upload_or_phone");case"form":{let h=Ye(c.form);return h===null?B(n,g,S,"update_required"):{kind:"form",key:"form",context:n,section:g,form:h,dir:qe(h.locale),...p}}case"nfc_chip":return B(n,g,S,"platform_unsupported");default:return B(n,g,S,"update_required")}}var pn=/^[A-Z0-9][A-Z0-9 -]{0,39}$/,fn=Object.freeze({normalize:e=>e.trim().toUpperCase().replace(/\s+/g," "),check:e=>pn.test(e),registrySources:Object.freeze([]),describe:"number must be 1 to 40 letters, digits, spaces or hyphens"}),mn=/^[A-Z0-9]{4,20}$/,me=e=>e.trim().toUpperCase().replace(/[\s-]+/g,""),hn=Object.freeze({normalize:me,check:e=>mn.test(me(e)),registrySources:Object.freeze([]),describe:"number must be 4 to 20 letters or digits"});function Sn(e){return typeof e=="string"&&/^\d{10}$/.test(e)&&Number(e)%97===1}var gn={trim:e=>e.trim(),upper_single_space:e=>e.trim().toUpperCase().replace(/\s+/g," "),upper_no_space_or_hyphen:me},yn={mr_nni_mod97:e=>Sn(e)};function _n(e){let t=new RegExp(e.pattern,"u"),n=e.check===null?void 0:yn[e.check];return Object.freeze({normalize:gn[e.normalize],check:i=>t.test(i.trim())&&(n===void 0||n(i)),registrySources:Object.freeze([...e.registrySources]),describe:e.describe})}var bn=Object.freeze(Object.fromEntries(Object.entries(Te).map(([e,t])=>[e,_n(t)])));function he(e,t){return bn[`${e.toUpperCase()}:${t}`]??(t==="drivers_license"?hn:fn)}var kn=Object.freeze({MRT:"MR"});function ot(e,t){let n=e.trim().toUpperCase();return he(kn[n]??n,t)}function it(e){let t=ot(e.issuingCountry,e.type);return t.check(t.normalize(e.number))}function st(e){return he("MR","national_id").check(e)}function Se(e){let t="";for(let n of e){let i=n.codePointAt(0)??0;i>=1632&&i<=1641?t+=String(i-1632):i>=1776&&i<=1785?t+=String(i-1776):n!==" "&&n!=="-"&&n!==" "&&(t+=n)}return t}var Cn=[1e3,2e3,4e3,8e3,15e3],Pn=3e4,An=/^\+[1-9]\d{6,14}$/,Rn=/^\d{6}$/,wn=/^\d{6}$/,xn=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,at=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order","identity_confirm_required","identity_confirm_locked","choice_locked","choice_option_unavailable","choice_not_found","step_not_on_path","check_not_active","native_app_required"]),En={simulatedCapture:!0},In=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]);function lr(e){let t=!1,n=null,i="",r=!1,a=!1,d=!1,c={},p={},S=new Set,g=!1,w=!1,h=null,y="idle",O=new Map,E=new Map,I=(o,s,u)=>{let l=`${o}.${s}`,f=O.get(l);if(f!==void 0)return f;let _=E.get(o),P=(_===void 0?u():_.then(u)).finally(()=>{O.delete(l)});O.set(l,P);let b=P.then(()=>{},()=>{});return E.set(o,b),b.then(()=>{E.get(o)===b&&E.delete(o)}),P},v=async(o,s,u)=>{await e.ensureConsent();let l;try{l=await Me(e.runtime,s)}catch(_){if(_ instanceof j&&at.has(_.code)){await e.refreshView();return}throw _}if(u?.(l),e.destroyed())return;let f=l;f.plan!==void 0&&e.setView!==void 0?e.setView(f):await e.refreshView()},V=async o=>{await e.ensureConsent();let s;try{try{s=await o(e.runtime.client)}catch(u){if(!(u instanceof j)||u.code!=="consent_required")throw u;await e.runtime.ensureConsent({force:!0}),s=await o(e.runtime.client)}}catch(u){if(u instanceof j&&at.has(u.code)){await e.refreshView();return}throw u}e.destroyed()||(s!==void 0&&e.setView!==void 0?e.setView(s):await e.refreshView())},D=(o,s)=>I("choice",`${o}:${s}`,()=>V(u=>u.choose(o,s))),x=(o,s)=>o.options.some(u=>u.id===s)?D(o.nodeId,s):Promise.reject(new RangeError(`option ${String(s)} is not offered`)),U=(o,s)=>{let u=e.currentView(),l=u===null?void 0:de(u,o);return l===void 0?Promise.reject(new RangeError(`the ${s} is not offered`)):D(l.nodeId,l.option.id)},F=o=>I("identity",o,()=>V(s=>s.confirmIdentity===void 0?Promise.reject(new Error("identity confirmation is not available in this build")):s.confirmIdentity(o))),K=(o,s)=>{let u=X(o.form,s);if(u.length>0)return Promise.reject(new ie(u,"client"));let l={answers:{...s.answers},consents:{}};for(let f of o.form.consents)l.consents[f.id]=s.consents[f.id]===!0;return I("form","submit",()=>v("form",(f,_)=>f.submitCheck("form",l,{idempotencyKey:_})).catch(f=>{throw f instanceof j&&f.code===ve?new ie(Je(f.details,o.form,l),"server"):f}))},te=(o,s)=>{let u=o.kind,l=u==="phone_otp",f=l?"phone":"email",_={action:"send"};if(l?o.needsPhone:o.needsEmail){let P=s[f]??p[u],b=l?P?.replace(/[\s().-]/g,""):P?.trim();if(b!==void 0||o.phase!=="verify"){if(b===void 0||!(l?An:xn).test(b))return Promise.reject(l?new N("phone","format"):new Y("email","format"));_[f]=b}}if(l){let P=o.channels,b=s.channel??(P.length===1?P[0]:void 0);if(P.length>0){if(b===void 0)return Promise.reject(new Y("channel","required"));if(!P.includes(b))return Promise.reject(new Y("channel","unavailable"))}b!==void 0&&(_.channel=b),_.phoneRules=1}return I(u,"send",()=>v(u,(P,b)=>P.submitCheck(u,_,{idempotencyKey:b}),P=>{On(P,u)||(c[u]=e.now(),_[f]!==void 0&&(p[u]=_[f]))}))},Z=(o,s)=>Rn.test(s)?I(o,"verify",()=>v(o,(u,l)=>u.submitCheck(o,{action:"verify",code:s},{idempotencyKey:l}))):Promise.reject(new N("code","format")),G=(o,s)=>I("eid_auth",o,()=>v("eid_auth",(u,l)=>u.submitCheck("eid_auth",s,{idempotencyKey:l}))),ne=(o,s)=>{if(o.identifierBound)return G("start",{action:"start"});let u=Se(s??"");if(o.country==="MR"){if(!/^\d{10}$/.test(u))return Promise.reject(new N("nni","format"));if(!st(u))return Promise.reject(new N("nni","check_digit"))}else if(u==="")return Promise.reject(new N("nni","format"));return G("start",{action:"start",identifier:u})},W=(o,s,u)=>{if(o.source!=="typed")return Promise.reject(new RangeError("this session already holds the ID number"));let l=Se(s);return/^\d{10}$/.test(l)?it({type:"national_id",issuingCountry:"MR",number:l})?I("population_registry","submitIdNumber",()=>v("population_registry",(f,_)=>f.submitCheck("population_registry",{idNumber:l,nni:l},{idempotencyKey:_}),()=>{h=`\u2022\u2022\u2022\u2022\u2022\u2022${l.slice(-4)}`})):Promise.reject(new N(u,"check_digit")):Promise.reject(new N(u,"format"))},Q=o=>(e.stopCameras?.(),I(o,"skipCapture",()=>v(o,(s,u)=>s.submitCheck(o,En,{idempotencyKey:u}),()=>{(o==="liveness"||o==="portrait_icao")&&(g=!0)}))),ge=o=>{if(o.kind==="result"||o.context.simulation?.skipCapture!==!0)return o;let s=Mn(o);return s===null?o:{...o,skipCapture:()=>Q(s)}},m=o=>((o.kind==="document"||o.kind==="portrait"||o.kind==="proof_of_address")&&o.photo?.cameraOnPhone===!0&&(o.refresh=async()=>{await e.refreshView()}),o),k=o=>{switch(o.kind){case"phone_otp":case"email_otp":{let s={...o,send:(l={})=>te(o,l),verify:l=>Z(o.kind,l),switchTo:()=>o.canSwitch&&o.switchChannel!==void 0?U([o.switchChannel==="email"?"email_otp":"phone_otp"],"other contact option"):Promise.reject(new RangeError("this session has no other contact option"))},u=c[o.kind];return s.resendAvailableAt===void 0&&u!==void 0&&(s.resendAvailableAt=new Date(u+Pn).toISOString()),s}case"eid":return{...o,start:s=>ne(o,s),verify:s=>wn.test(s)?G("verify",{action:"verify",code:s}):Promise.reject(new N("code","format")),resend:()=>o.resendsRemaining===0?Promise.reject(new RangeError("no new code can be sent for this session")):G("resend",{action:"resend"}),useCamera:()=>o.canUseCamera&&o.cameraMethod!==void 0?U(o.cameraMethod==="document_photo"?["document"]:["population_registry"],"camera path"):Promise.reject(new RangeError("the camera path is not offered"))};case"method":return{...o,select:s=>{let u=o.choice.options.find(l=>q[l.service]===s);return u!==void 0?x(o.choice,u.id):Promise.reject(new RangeError(`method ${String(s)} is not offered`))},choose:s=>x(o.choice,s)};case"choice":return{...o,choose:s=>x(o.choice,s)};case"registry":return{...o,submitIdNumber:s=>W(o,s,"idNumber"),submitNni:s=>W(o,s,"nni"),confirm:()=>I("population_registry","confirm",()=>v("population_registry",(s,u)=>s.submitCheck("population_registry",{},{idempotencyKey:u}))),useDocument:()=>o.canUseDocument?U(["document"],"document method"):Promise.reject(new RangeError("the document method is not offered"))};case"document":return e.bindDocument!==void 0?m(e.bindDocument(o,M)):{...o,issuer:null,documentType:null,captureSide:null,selectDocument:()=>{throw new Error("document capture is not available in this build")},capture:()=>{throw new Error("document capture is not available in this build")},uploadDocument:()=>Promise.reject(new Error("document upload is not available in this build"))};case"portrait":return e.bindPortrait!==void 0?m(e.bindPortrait(o,M)):{...o,uploadFailed:!1,resubmit:()=>Promise.resolve(),capture:()=>{throw new Error("portrait capture is not available in this build")},uploadPortrait:()=>Promise.reject(new Error("portrait upload is not available in this build")),confirmFix:()=>Promise.reject(new Error("portrait review is not available in this build"))};case"proof_of_address":return e.bindProofOfAddress!==void 0?m(e.bindProofOfAddress(o,M)):{...o,uploadPages:()=>Promise.reject(new Error("proof of address upload is not available in this build")),uploadHolderLetter:()=>Promise.reject(new Error("proof of address upload is not available in this build")),capturePage:()=>{throw new Error("proof of address capture is not available in this build")}};case"form":return{...o,validate:s=>X(o.form,s),submit:s=>K(o,s)};case"contact_choice":return{...o,select:s=>{let u=s==="phone"?"phone_otp":s==="email"?"email_otp":void 0,l=o.choice.options.find(f=>f.service===u);return l!==void 0?x(o.choice,l.id):Promise.reject(new RangeError(`contact ${String(s)} is not offered`))},choose:s=>x(o.choice,s)};case"identity_summary":return{...o,...o.idNumberMasked===void 0&&o.summaryKind==="partial"&&h!==null?{idNumberMasked:h,nniMasked:h}:{},portrait:async()=>{let s=e.runtime.client;if(!o.portraitAvailable||s.identityPortrait===void 0)return null;try{return await s.identityPortrait()}catch{return null}},confirm:()=>F("confirm"),retake:()=>o.retakeAvailable?F("retake"):Promise.reject(new RangeError("no retake is left"))};case"liveness":return{...o,capture:s=>e.liveness(s),onLivePhoto:s=>o.livePhoto?.icao===!0&&e.onLivePhoto!==void 0?e.onLivePhoto(s):()=>{}};case"mobile_required":case"native_app_required":case"processing":return{...o,refresh:async()=>{r=!1,await e.refreshView()}};case"unsupported":case"result":return{...o};default:{let s=o;throw new Error(`runner: unhandled step ${JSON.stringify(s)}`)}}},A=o=>ge(k(o)),T=async()=>{if(!a){a=!0;try{for(let o of Cn){if(await e.sleep(o),!t||e.destroyed())return;let s=await e.refreshView().catch(()=>null);if(s!==null&&ee(s,{isMobile:e.isMobile()}).kind!=="processing")return}r=!0,M()}finally{a=!1}}},H=o=>{if(o.kind!=="liveness"||o.mode!=="selfie")return null;let s={kind:"processing",key:"processing",context:o.context,section:o.section,stalled:!1};if(y==="inflight")return s;if(!w||y==="done")return null;let u=e.keptFaceKey?.()??null;return u===null?null:(y="inflight",v("face_match",(l,f)=>l.submitCheck("face_match",{imageKey:u},{idempotencyKey:f}),()=>{y="done"}).then(()=>{y==="inflight"&&(y="done",M())},()=>{y="done",M()}),s)},R=(o,s=!1)=>{if(!t||e.destroyed()||e.chainBusy())return;let u=ee(o,{isMobile:e.isMobile()});u.kind==="registry"&&u.recheck&&(w=!0,y="idle"),u=H(u)??u,u.kind==="processing"?u.stalled=r:r=!1;let l=A(u),f=u.kind==="result"?void 0:u.context.switchable,_=f===void 0?l:{...l,chooseOption:b=>x({nodeId:f.nodeId,kind:f.kind,selected:f.current,options:f.options},b)},P=JSON.stringify(_);u.kind==="registry"&&u.source==="document"&&u.state==="pending"&&!S.has("registry")&&(S.add("registry"),_.confirm().catch(b=>{(!(b instanceof j)||In.has(b.code))&&S.delete("registry")})),!(!s&&P===i)&&(i=P,n=_,e.emitStep(_),u.kind==="processing"&&!r&&y!=="inflight"&&T(),u.kind==="result"&&!d&&(d=!0,e.emitResult(u.result)))};function M(){let o=e.currentView();o!==null&&R(o,!0)}return{run:async()=>{if(e.destroyed())throw new Error("verification destroyed");t=!0;let o=await e.ensureView();return n===null&&R(o),n??A(ee(o,{isMobile:e.isMobile()}))},current:()=>n,onView:o=>R(o),onChainIdle:()=>{let o=e.currentView();o!==null&&R(o)},republish:M,submit:v,faceProbeSkipped:()=>g}}function Mn(e){switch(e.kind){case"document":return"doc_ocr";case"liveness":return e.mode==="selfie"?"face_match":"liveness";case"portrait":return e.phase==="capture"?"portrait_icao":null;case"proof_of_address":return"poa";case"mobile_required":case"native_app_required":return e.checkType;case"unsupported":return e.checkType==="nfc_chip"?"nfc_chip":null;default:return null}}function On(e,t){let n=e,i=n?.plan?.steps??n?.steps;return Array.isArray(i)?i.some(r=>r.checkType===t&&typeof r.reason=="string"):!1}export{dt as a,Nn as b,Ve as c,Fe as d,Dn as e,rt as f,ee as g,Cn as h,Pn as i,lr as j};
1
+ import{C as Me,F as ve,G as ie,H as Te,I as N,J as Y,d as q,e as Ce,f as Pe,g as Ae,i as Re,j as re,l as $,m as oe,o as we,p as xe,q as Ee,u as Ie}from"./chunk-HFRU66NW.js";import{c as _e,d as be,e as ke}from"./chunk-FPXL63KZ.js";import{c as j,h as J,i as Oe}from"./chunk-YDG77RHN.js";var Ne=["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 ut=["carte_identite","passport","residence_permit","drivers_license"],ct=["carte_identite","passport","residence_permit"];function dt(e,t){let n=e.byIssuer?.[t]??e.default;return ut.filter(i=>n==="*"?ct.includes(i):n.includes(i))}function Nn(e,t=Ne){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(i=>dt(e,i).length>0).sort()}function Le(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}var lt=640,pt=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),Ve=6,Fe=1500,He={sharpness:1,exposure:1,meanLuma:128},De=null;function ft(e,t){try{De??(De=document.createElement("canvas"));let n=De,i=96/Math.max(1,t.width);n.width=Math.max(1,Math.round(t.width*i)),n.height=Math.max(1,Math.round(t.height*i));let r=n.getContext("2d");if(r===null)return He;r.drawImage(e,t.x,t.y,t.width,t.height,0,0,n.width,n.height);let a=r.getImageData(0,0,n.width,n.height);return{sharpness:be(a),exposure:ke(a),meanLuma:_e(a)}}catch{return He}}async function mt(e,t){let n=e.source;return"convertToBlob"in n?n.convertToBlob({type:"image/jpeg",quality:t}):new Promise((i,r)=>{n.toBlob(a=>a===null?r(new Error("encode failed")):i(a),"image/jpeg",t)})}function Dn(e,t={}){let n=t.now??(()=>performance.now()),i=t.setTimer??((m,k)=>setTimeout(m,k)),r=t.clearTimer??(m=>clearTimeout(m)),a=t.encode??mt,d=t.quality??ft,c=e.tuningVersion??null,p=new Set,S=!1,g=e.video??null,w=null,h=t.grabFrame??null,y=null,O=1e3/Ve,E=null,I=null,v=!1,V=!1,D=Number.NEGATIVE_INFINITY,x=null,U=0,F=null,K=null,te=Promise.all([import("./icao-gate-T3BTOKFJ.js"),import("./icao-tuning-4ETMF53W.js"),import("./create-portrait-capture-5VGYZUOK.js"),import("./landmarker-KB7LVXAU.js"),import("./background-monitor-A7FKJOAG.js")]).then(async([m,k,A,T,H])=>{let R=k.resolveIcaoTuning(e.tuning,e.tuningVersion??void 0);R.background.required&&(I=H.createBackgroundMonitor({tuning:R.backgroundCheck,assetBaseUrl:e.assetBaseUrl??"/models-v3",...t.createSegmenter!==void 0?{createSegmenter:t.createSegmenter}:{},now:n})),w=m.createIcaoGate(R,{policy:e.policy??"reject"}),h??(h=A.defaultGrabber()),y=A.observe,O=1e3/Math.min(Ve,R.cadenceHz);let M=(t.createLandmarker??T.createFaceLandmarker)(e.assetBaseUrl??"/models-v3"),o=await new Promise((s,u)=>{let l=setTimeout(()=>{u(new Error("landmarker init timeout")),M.then(f=>f.close(),()=>{})},T.LANDMARKER_INIT_TIMEOUT_MS);M.then(f=>{clearTimeout(l),s(f)},f=>{clearTimeout(l),u(f)})});S?o.close():E=o}).catch(()=>{v=!0}),Z=m=>{for(let k of p)k({holding:V||v,update:m})},G=()=>{if(x=null,!(S||E===null||w===null||h===null||y===null||g===null)){if(n()-D>Fe){Z(null);return}try{let m=h(g,lt);if(m!==null){let k=Math.max(n(),U+1);U=k;let A=E.detect(m.source,k),T=g.videoWidth||m.width,H=g.videoHeight||m.height,R=y(A,m,T,H);R.geometry!==null&&I!==null&&(R.backgroundCheck=I.measure(m,R.geometry.box,T,H));let M=w.push(R,n());V=M.ready,Z(M)}}catch{}x=i(G,O)}},ne=()=>{let m=n()-D>Fe;D=n(),m&&(w?.reset(),V=!1,F=null,K=null),x===null&&E!==null&&!S&&(x=i(G,0))},W=()=>{let m=h===null||g===null?null:h(g,null);if(m===null||w===null||Math.max(m.width,m.height)<e.still.minLongSidePx)return Promise.resolve(null);let k=w.summary();return a(m,e.still.jpegQuality).then(A=>({image:A,width:m.width,height:m.height,gate:k}),()=>null)},Q=null;return{engineOptions:{measureQuality:(m,k)=>{g=m,ne();let A=d(m,k);return V||v?A:{...A,sharpness:0}},telemetry:m=>{if(m.type!=="fired"||S)return;F=W();let k=Q;k!==null&&F.then(A=>A===null?void 0:k(A).catch(()=>{})),V=!1,x!==null&&r(x),x=null,D=Number.NEGATIVE_INFINITY}},decorate:m=>{let k=new WeakMap,A=new Map,T=o=>{let s=k.get(o);return s===void 0&&(s=(async()=>{let u=await Ie(m,"image","image/jpeg",o.image.size,{engine:"portrait"});return await m.uploadToSpaces(u.uploadUrl,o.image,"image/jpeg"),(await m.completeMedia(u.key)).key})(),s.catch(()=>k.delete(o)),k.set(o,s)),s};Q=T;let H=async o=>{let s;try{s=await T(o)}catch(u){let l=u?.code;if(typeof l=="string"&&pt.has(l))throw u;return null}return{media:{portrait:s},gate:Oe(o.gate),...c!==null?{tuningVersion:c}:{}}},R=m.submitCheck.bind(m),M=(async(o,s,u)=>{if(o!=="liveness")return R(o,s,u);let l=u?.idempotencyKey,f=l===void 0?void 0:A.get(l);if(f===void 0){let b=F;f=b===null?Promise.resolve(null):b.then(ye=>ye===null?null:H(ye)),l!==void 0&&(A.set(l,f),f.catch(()=>A.delete(l)))}let _=await f;if(_===null)return R("liveness",s,u);let P=await R("liveness",{...s,portraitIcao:_},u);return K=_,P});return new Proxy(m,{get(o,s){if(s==="submitCheck")return M;let u=Reflect.get(o,s);return typeof u=="function"?u.bind(o):u}})},onGate:m=>(p.add(m),()=>p.delete(m)),lastPortraitInput:()=>K,destroy:()=>{S=!0,F=null,K=null,x!==null&&r(x),x=null,p.clear(),te.then(()=>{E?.close(),E=null,I?.close(),I=null})}}}function Ge(e){return e.idNumberBound??e.nniBound}function Be(e){return e===void 0?void 0:e.idNumberFromDocument??e.nniFromDocument}function Ue(e){let t=e.idNumberMasked??e.nniMasked;return typeof t=="string"&&t!==""?t:void 0}var Ke=Object.freeze({nni_invalid:"id_number_invalid",nni_not_found:"registry_record_not_found",nni_recheck:"id_number_recheck",document_nni_mismatch:"document_id_number_mismatch",nni_locked:"id_number_locked",nni_unbound:"id_number_unbound",missing_nni:"missing_id_number",registry_needs_nni_source:"registry_needs_id_number_source"}),ht=new Map(Object.entries(Ke)),Un=new Map(Object.entries(Ke).map(([e,t])=>[t,e]));function je(e){return ht.get(e)??e}var C={fullNameMin:2,fullName:200,email:254,occupation:120,shortText:120,longText:1e3,addressLine:120,addressLines:4,city:80,postcode:16,number:1e12,dateMin:"1900-01-01",dateMax:"2100-12-31"},St=new Set(["full_name","birth_date","email","phone","address","country","occupation"]),gt=new Set(["short_text","long_text","single_choice","multiple_choice","yes_no","date","number"]),yt=new Set(["ar","fa","he","ur"]);function qe(e){return yt.has(e.split("-")[0]?.toLowerCase()??"")?"rtl":"ltr"}function Ye(e){if(typeof e!="object"||e===null)return null;let t=e;if(typeof t.locale!="string"||!Array.isArray(t.questions)||t.questions.length===0)return null;let n=t.consents??[];if(!Array.isArray(n))return null;for(let r of t.questions)if(!_t(r))return null;for(let r of n)if(!bt(r))return null;let i={locale:t.locale,questions:t.questions,consents:n};return typeof t.title=="string"&&t.title.trim()!==""&&(i.title=t.title),typeof t.intro=="string"&&t.intro.trim()!==""&&(i.intro=t.intro),typeof t.prefill=="object"&&t.prefill!==null&&!Array.isArray(t.prefill)&&(i.prefill=t.prefill),i}function _t(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id!="string"||typeof t.required!="boolean"?!1:t.kind==="field"?typeof t.field=="string"&&St.has(t.field):t.kind!=="custom"||typeof t.type!="string"||!gt.has(t.type)||typeof t.label!="string"?!1:t.type==="single_choice"||t.type==="multiple_choice"?Array.isArray(t.choices)&&t.choices.length>=2&&t.choices.every(n=>typeof n=="object"&&n!==null&&typeof n.value=="string"&&typeof n.label=="string"):!0}function bt(e){if(typeof e!="object"||e===null)return!1;let t=e;if(typeof t.id!="string"||typeof t.required!="boolean"||typeof t.text!="string")return!1;if(t.link===void 0)return!0;let n=t.link;return typeof n=="object"&&n!==null&&typeof n.url=="string"&&/^https:\/\//.test(n.url)&&typeof n.label=="string"}var kt=/^(\d{4})-(\d{2})-(\d{2})$/;function Ct(e){if(typeof e!="string")return!1;let t=kt.exec(e);return t===null?!1:new Date(Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3]))).toISOString().slice(0,10)===e&&e>=C.dateMin&&e<=C.dateMax}function Pt(e){return typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<C.number&&Math.round(e*100)/100===e}function Ze(e){for(let t of e.matchAll(/\d[\d -]{11,}\d/g)){let n=t[0].replace(/[ -]/g,"");if(n.length>=13&&n.length<=19&&At(n))return!0}return!1}function At(e){let t=0;for(let n=0;n<e.length;n++){let i=Number(e[e.length-1-n]);n%2===1&&(i*=2,i>9&&(i-=9)),t+=i}return t%10===0}var Rt=/^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$/,wt=/^\+[1-9]\d{6,14}$/,We=/^[A-Z]{2}$/,xt=e=>e===void 0||typeof e=="string"&&e.trim()===""||Array.isArray(e)&&e.length===0;function Qe(e=Date.now()){return new Date(e).toISOString().slice(0,10)}function X(e,t,n=Qe()){let i=[];for(let r of e.questions){let a=t.answers[r.id];if(xt(a)){r.required&&i.push({id:r.id,code:"required"});continue}let d=r.kind==="field"?Et(r.field,a,n):Mt(r,a,n);d!==null&&i.push({id:r.id,...d})}for(let r of e.consents)r.required&&t.consents[r.id]!==!0&&i.push({id:r.id,code:"consent_required"});return i}function z(e,t,n=1){if(typeof e!="string")return{code:"required"};let i=e.trim();return[...i].length>t?{code:"too_long",params:{max:t}}:[...i].length<n?{code:"too_short",params:{min:n}}:Ze(i)?{code:"card_number"}:null}function $e(e,t,n={}){return Ct(e)?n.period==="past"&&e>=t?{code:"date_not_past"}:n.period==="future"&&e<=t?{code:"date_not_future"}:n.min!==void 0&&e<n.min?{code:"date_too_early",params:{date:n.min}}:n.max!==void 0&&e>n.max?{code:"date_too_late",params:{date:n.max}}:null:{code:"date_invalid"}}function Et(e,t,n){switch(e){case"full_name":return z(t,C.fullName,C.fullNameMin);case"occupation":return z(t,C.occupation);case"birth_date":return $e(t,n,{period:"past"});case"email":return typeof t=="string"&&t.trim().length<=C.email&&Rt.test(t.trim())?null:{code:"email_invalid"};case"phone":return typeof t=="string"&&wt.test(t)?null:{code:"phone_invalid"};case"country":return typeof t=="string"&&We.test(t)?null:{code:"choice_invalid"};case"address":return It(t)?null:{code:"address_invalid"};default:return null}}function It(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e,n=Array.isArray(t.lines)?t.lines.filter(i=>typeof i=="string"&&i.trim()!==""):[];return typeof t.country=="string"&&We.test(t.country)&&typeof t.city=="string"&&t.city.trim()!==""&&t.city.trim().length<=C.city&&n.length>=1&&n.length<=C.addressLines&&n.every(i=>i.trim().length<=C.addressLine&&!Ze(i))&&(t.postcode===void 0||typeof t.postcode=="string"&&t.postcode.trim().length<=C.postcode)}function Mt(e,t,n){let i=new Set((e.choices??[]).map(r=>r.value));switch(e.type){case"short_text":return z(t,C.shortText);case"long_text":return z(t,C.longText);case"single_choice":return typeof t=="string"&&i.has(t)?null:{code:"choice_invalid"};case"multiple_choice":return Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(r=>i.has(r))?null:{code:"choice_invalid"};case"yes_no":return typeof t=="boolean"?null:{code:"choice_invalid"};case"date":{let r=e.options??{};return $e(t,n,{...typeof r.min=="string"?{min:r.min}:{},...typeof r.max=="string"?{max:r.max}:{},...r.period==="past"||r.period==="future"?{period:r.period}:{}})}case"number":{if(typeof t!="number"||!Number.isFinite(t)||Math.abs(t)>=C.number)return{code:"number_invalid"};let r=e.options??{};return r.integer===!0&&!Number.isInteger(t)?{code:"number_not_integer"}:Pt(t)?typeof r.min=="number"&&t<r.min?{code:"number_too_small",params:{min:r.min}}:typeof r.max=="number"&&t>r.max?{code:"number_too_large",params:{max:r.max}}:null:{code:"number_decimals"}}default:return null}}function Je(e,t,n,i=Qe()){let r=e?.errors;return Array.isArray(r)?r.flatMap(a=>{if(typeof a!="object"||a===null)return[];let{id:d,code:c}=a;return typeof d!="string"||typeof c!="string"?[]:[vt(d,c,t,n)]}):X(t,n,i)}var Ot={full_name:C.fullName,occupation:C.occupation,email:C.email,short_text:C.shortText,long_text:C.longText};function vt(e,t,n,i){let r=n.questions.find(p=>p.id===e),a=r===void 0?void 0:r.kind==="field"?r.field:r.type,d=i.answers[e],c=r!==void 0&&r.kind==="custom"?r.options??{}:{};switch(t){case"required":case"card_number":return{id:e,code:t};case"consent_required":return{id:e,code:"consent_required"};case"too_short":return{id:e,code:t,params:{min:a==="full_name"?C.fullNameMin:1}};case"too_long":{let p=a===void 0?void 0:Ot[a];return p===void 0?{id:e,code:t}:{id:e,code:t,params:{max:p}}}case"not_a_choice":return{id:e,code:"choice_invalid"};case"not_in_past":return{id:e,code:"date_not_past"};case"not_in_future":return{id:e,code:"date_not_future"};case"not_an_integer":return{id:e,code:"number_not_integer"};case"out_of_range":return Tt(e,a,d,c);case"invalid":return r===void 0?n.consents.some(p=>p.id===e)?{id:e,code:"consent_required"}:{id:e,code:t}:{id:e,code:Nt(a,d)};default:return{id:e,code:t}}}function Tt(e,t,n,i){if(t==="date"){let c=typeof i.min=="string"?i.min:void 0,p=typeof i.max=="string"?i.max:void 0;return p!==void 0&&(c===void 0||typeof n=="string"&&n>p)?{id:e,code:"date_too_late",params:{date:p}}:c!==void 0?{id:e,code:"date_too_early",params:{date:c}}:{id:e,code:"date_invalid"}}let r=typeof i.min=="number"?i.min:void 0,a=typeof i.max=="number"?i.max:void 0;return a!==void 0&&(r===void 0||typeof n=="number"&&n>a)?{id:e,code:"number_too_large",params:{max:a}}:r!==void 0?{id:e,code:"number_too_small",params:{min:r}}:{id:e,code:"number_invalid"}}function Nt(e,t){switch(e){case"email":return"email_invalid";case"phone":return"phone_invalid";case"birth_date":case"date":return"date_invalid";case"number":return typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<C.number?"number_decimals":"number_invalid";case"address":return"address_invalid";case"full_name":case"occupation":case"short_text":case"long_text":return"required";default:return"choice_invalid"}}var Lt=new Set(["phone_otp","email_otp","national_eid","document","nfc","population_registry","supplied_identity","summary_confirm","liveness","portrait","face_match","aml_screening","face_dedup","age_estimation","proof_of_address","form"]),Vt=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),ae=["document","population_registry","national_eid"],ue=["phone_otp","email_otp"],et={identity_method:ae,contact:ue},Ft=["population_registry","document"],ce="platform_unsupported",Ht=new Set(["prefilled","user_entered","prefilled_or_entered"]),Dt={phone_otp:"contact",email_otp:"contact",eid_auth:"identity",doc_ocr:"identity",nfc_chip:"identity",population_registry:"identity",liveness:"live_photo",portrait_icao:"live_photo",face_match:"live_photo",poa:"documents",form:"form"};function L(e){return e.section??Dt[e.checkType]??null}function de(e,t){let n=e.plan?.choice;if(n===void 0||n.locked)return;let i=n.options.find(r=>r.id!==n.selected&&r.available!==!1&&t.includes(r.service));return i===void 0?void 0:{nodeId:n.nodeId,option:i}}function le(e){let t=e.plan,n=t?.choice;if(t===void 0||n===void 0||n.locked||t.current===null||t.current===n.nodeId||re(e))return null;let i=et[n.kind]??[...ae,...ue],r=n.options.flatMap(c=>c.available===!1||!i.includes(c.service)?[]:[c.nationalEid!=null?{id:c.id,service:c.service,nationalEid:c.nationalEid}:{id:c.id,service:c.service}]),a=t.steps.find(c=>c.id===t.current)?.service,d=n.selected??r.find(c=>c.service===a)?.id??null;return r.some(c=>c.id!==d)?{nodeId:n.nodeId,kind:n.kind,current:d,options:r}:null}function tt(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function Gt(e){let t=e.simulation;if(typeof t!="object"||t===null)return;let{otpCode:n,skipCapture:i}=t;if(typeof n!="string"||n===""||typeof i!="boolean")return;let r=xe(e);return r!==void 0?{otpCode:n,skipCapture:i,reason:r}:{otpCode:n,skipCapture:i}}function Bt(e){let t=(e.plan?.sections??[]).map(d=>({id:d.id,state:d.state})),n={sessionId:oe(e.sessionId),orgName:e.orgName,sandbox:e.sandbox===!0,returning:e.returning===!0,consentRecorded:e.consentRecorded,expiresAt:e.expiresAt,sections:t.map(d=>d.id),progress:t,purpose:e.purpose??"identity"};e.branding!==void 0&&(n.branding=e.branding),e.cameraUnavailableHandled===!0&&(n.cameraUnavailableHandled=!0);let i=Gt(e);i!==void 0&&(n.simulation=i);let r=e.testerGate;r?.offered===!0&&typeof r.attemptsLeft=="number"&&r.attemptsLeft>0&&(n.testerGate={attemptsLeft:r.attemptsLeft});let a=le(e);return a!==null&&(n.switchable=a),n}function Ut(e){let t={attemptsRemaining:Pe(e),attemptsExhausted:e.attempts.used>=e.attempts.max};return e.reason!==void 0&&(t.reason=e.reason),e.retakeHint!==void 0&&(t.retakeHint=e.retakeHint),t}var nt={phone_otp:"phone",email_otp:"email"};function Kt(e,t){let n=de(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return n===void 0?void 0:nt[n.option.service]}function jt(e,t,n,i){let r=t.checkType==="email_otp",a=(r?t.emailOtp:t.otp)??{},d=r?t.emailOtp?.emailSource:t.otp?.numberSource,c=d!==void 0&&Ht.has(d)?d:r?"prefilled_or_entered":"user_entered",p=typeof a.sentToMasked=="string"&&a.sentToMasked.length>0,S=a.prefilled===!0,g=Kt(e,r?"email_otp":"phone_otp"),w={key:t.checkType,context:n,section:L(t),phase:p?"verify":"send",canSwitch:g!==void 0,...i},h=r?{kind:"email_otp",...w,emailSource:c,needsEmail:c!=="prefilled"&&!S}:{kind:"phone_otp",...w,numberSource:c,needsPhone:c!=="prefilled"&&!S,channels:(t.otp?.channels??[]).filter(y=>y==="whatsapp"||y==="sms")};if(g!==void 0&&(h.switchChannel=g),S&&(h.prefilled=!0),p&&(h.sentToMasked=a.sentToMasked),!r&&t.otp?.channel!==void 0&&(h.channel=t.otp.channel),!r&&Array.isArray(t.phoneCountries)&&(h.phoneCountries=t.phoneCountries.filter(y=>typeof y=="string"&&/^[A-Z]{2}$/.test(y))),!r&&Array.isArray(t.phoneRules)){let y=h.phoneCountries??[];h.phoneRules=t.phoneRules.flatMap(O=>{let E=Zt(O);return E!==void 0&&y.includes(E.code)?[E]:[]})}return!r&&t.phoneInternational===!0&&(h.phoneInternational=!0),a.expiresAt!==void 0&&(h.codeExpiresAt=a.expiresAt),a.resendAvailableAt!==void 0&&(h.resendAvailableAt=a.resendAvailableAt),h}var qt=/^[\d[\]\-|()?:^]{1,64}$/;function Yt(e){try{return typeof e=="string"&&qt.test(e)&&new RegExp(e)!==null}catch{return!1}}var ze=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function Zt(e){let{code:t,dial:n,trunk:i,lengths:r,formats:a}=e??{};if(typeof t!="string"||typeof n!="string"||!/^\d{1,3}$/.test(n)||i!==void 0&&(typeof i!="string"||!/^\d{1,3}$/.test(i))||!Array.isArray(r)||r.length===0||!r.every(ze))return;let d={code:t,dial:n,lengths:[...r].sort((c,p)=>c-p)};if(i!==void 0&&(d.trunk=i),a!==void 0){if(!(Array.isArray(a)&&a.length<=8&&a.every(p=>Yt(p?.leading)&&Array.isArray(p.groups)&&p.groups.every(ze)&&r.includes(p.groups.reduce((S,g)=>S+g,0)))))return;d.formats=a.map(p=>({leading:p.leading,groups:[...p.groups]}))}return d}function Wt(e,t,n,i){let r=Ge(e)===!0?"bound":Be(t)===!0?"document":"typed",a=r==="typed"&&t.state==="input_required"&&t.reason!==void 0&&je(t.reason)==="id_number_recheck",d=tt(le(e)),c=!i.attemptsExhausted&&d.length===1&&d[0]?.service==="document";return{kind:"registry",key:"registry",context:n,section:L(t),state:t.state==="input_required"?"input_required":"pending",source:r,recheck:a,canUseDocument:c,...i}}function Qt(e,t,n,i,r){let a=[...t.acceptedSides??[]],d={kind:"document",key:"document",context:n,section:L(t),side:a.includes("recto")?"verso":"recto",acceptedSides:a,documents:Le(e),photo:fe(pe(e.documents),r),...i};return e.detectedCountry!==void 0&&(d.detectedCountry=e.detectedCountry),zt(e)&&(d.ageStepUp=!0),d}function pe(e,t=!0){let n=e?.source==="upload"||e?.source==="choice"?e.source:"camera",i=e?.sourcePick==="camera"||e?.sourcePick==="upload"?e.sourcePick:null;return{source:n,pick:i,uploadOffered:t&&e?.uploadOffered===!0}}function fe(e,t){return t?{...e,cameraOnPhone:!0}:e}var $t=10*1024*1024;function Jt(e,t,n,i,r){let a=e.proofOfAddress,d=a?.pdf?.maxBytes,c=a?.phase==="holder_letter"?"holder_letter":"document";return{kind:"proof_of_address",key:"proof_of_address",context:n,section:L(t),phase:c,rule:a?.rule??{country:null,countryFrom:"global",source:"preset_global",kinds:[]},nameMatch:a?.nameMatch??"exact_person",photo:fe(pe(a),r),maxPages:3,pdf:{maxBytes:typeof d=="number"&&d>0?d:$t,maxPages:3},licenceAddressAccepted:c==="document"&&a?.licenceAddressAccepted===!0,...i}}function zt(e){let t=Ce(e).find(i=>i.checkType==="age_estimation"),n=t?.reason;return t?.state==="failed"&&(n==="age_uncertain"||n==="age_unavailable")}function Xt(e){let t=$(e,"liveness");return t?.state==="passed"||t?.state==="review"}function Xe(e,t,n,i,r,a=!1){let d=t.icao?.report,c=e.portrait,p=r==="capture"?c?.pendingFix??null:null;p!==null&&(r="review");let S=rt(e);return{kind:"portrait",key:`portrait:${r}`,context:n,section:L(t),phase:r,report:Array.isArray(d)?d:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:J(e),retakeOnly:r==="capture"&&t.state==="input_required"&&S===void 0&&e.capture?.livePhoto?.oneCapture===!0&&Xt(e),photo:fe(pe(c,r==="capture"),a&&r==="capture"),pendingFix:p,...S!==void 0?{captureMode:S}:{},...c?.reuse?.pending===!0?{reuse:!0}:{},...i}}function rt(e){let t=e.portrait?.captureMode;return t==="self"||t==="assisted"||t==="choice"?t:void 0}var se={minLongSidePx:1280,jpegQuality:.95};function en(e,t){let n=e.capture?.livePhoto;if(n?.oneCapture!==!0)return null;let i=$(e,"portrait_icao"),r=n.still??se;return{icao:t==="liveness"&&J(e)!==null&&rt(e)===void 0&&i!==void 0&&i.state==="pending"&&i.reason===void 0,still:{minLongSidePx:r.minLongSidePx??se.minLongSidePx,jpegQuality:r.jpegQuality??se.jpegQuality}}}function tn(e,t,n,i){let r=t.eid,a=L(t);if(r===void 0||r.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:n,section:a,checkType:"eid_auth",reason:"update_required"};let d=tt(le(e)),c=d.length===1&&Ft.includes(d[0]?.service??"")?d[0]:void 0,p=c===void 0?void 0:q[c.service],S=p!==void 0,g={kind:"eid",key:"eid",context:n,section:a,provider:r.provider,providerName:r.providerName,country:r.country,challenge:"app_code",phase:r.awaiting==="code"?"code":"identifier",identifierBound:r.identifierBound===!0,canUseCamera:S,afterPass:r.afterPass==="continue"?"continue":"end",...i};return S&&(g.cameraMethod=p),r.expiresAt!==void 0&&(g.codeExpiresAt=r.expiresAt),r.resendAvailableAt!==void 0&&(g.resendAvailableAt=r.resendAvailableAt),r.resendsRemaining!==void 0&&(g.resendsRemaining=r.resendsRemaining),r.codeAttemptsRemaining!==void 0&&(g.codeAttemptsRemaining=r.codeAttemptsRemaining),g}function nn(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let n=$(e,"portrait_icao");return n!==void 0&&(n.state==="passed"||n.state==="review")?n:null}var rn={rejected:"rejected",inconclusive:"inconclusive",unavailable:"unavailable",abandoned:"expired",not_opened:"expired",cancelled:"expired",superseded:"expired",policy:"policy"};function on(e){return e.reasonCode===ce?"platform_unsupported":e.status==="review_pending"?"review":e.status==="verified"?"verified":e.reasonCode==="device_cooldown"?"cooldown":e.reasonCode==="starter_credit_claimed"?"policy":(e.status==="not_verified"&&e.reason!==void 0?rn[e.reason]:void 0)??"rejected"}function sn(e,t){let n=on(e),i=n==="platform_unsupported"?{sessionId:oe(e.sessionId),status:"unavailable",reasonCode:ce}:we(e,{autoRetry:!1}),r={kind:"result",key:"result",context:t,section:null,display:n,result:i};return e.status==="not_verified"&&e.reason!==void 0&&(r.reason=e.reason),e.reasonCode!==void 0&&(r.reasonCode=e.reasonCode),e.status==="not_verified"&&e.step!==void 0&&(r.step=e.step),e.retryAfter!==void 0&&(r.retryAfter=e.retryAfter),r}function an(e,t,n){let i=e.identitySummary;if(i==null)return null;let r={kind:"identity_summary",key:"identity_summary",context:t,section:n??"identity",summaryKind:i.kind==="partial"?"partial":i.kind??"full",source:i.source,portraitAvailable:i.portrait?.available===!0,retakeAvailable:i.retakeAvailable===!0};for(let d of un){let c=i[d];typeof c=="string"&&c!==""&&(r[d]=c)}let a=Ue(i);return a!==void 0&&(r.idNumberMasked=a,r.nniMasked=a),r}var un=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","expiryDate","retakeTarget"];function B(e,t,n,i){return{kind:"unsupported",key:`unsupported:${n}`,context:e,section:t,checkType:n,reason:i}}function cn(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function dn(e,t){let n=et[e.kind]??[...ae,...ue],i=cn(e),r=e.options.flatMap(d=>{if(d.available===!1||!n.includes(d.service))return[];let c={id:d.id,service:d.service};d.nationalEid!=null&&(c.nationalEid=d.nationalEid);let p=(d.channels??[]).filter(S=>S==="whatsapp"||S==="sms");return d.service==="phone_otp"&&p.length>0&&(c.channels=p),[c]});if(r.length===0){let d=e.options.length>0&&e.options.every(c=>c.service==="nfc");return B(t,i,"choice",d?"platform_unsupported":"update_required")}let a={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:r};if(e.kind==="identity_method"){let d={kind:"method",key:"method",context:t,section:i,options:r.map(p=>q[p.service]),choice:a},c=r.find(p=>p.nationalEid!==void 0)?.nationalEid;return c!==void 0&&(d.nationalEid=c),d}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:i,options:r.map(d=>nt[d.service]),selected:null,locked:!1,choice:a}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:i,choice:a}}function ln(e,t,n,i){let r=e.nativeApp,a=typeof r=="object"&&r!==null?r:{},d={sekyroApp:a.sekyroApp===!0};return typeof a.link=="string"&&a.link!==""&&(d.link=a.link),d.sekyroApp&&typeof a.sekyroAppLink=="string"&&a.sekyroAppLink.startsWith("sekyro://")&&(d.sekyroAppLink=a.sekyroAppLink),{kind:"native_app_required",key:`native_app_required:${i}`,context:t,section:n,checkType:i,nativeApp:d}}function ee(e,t={}){let n=Bt(e);if(re(e)||e.reasonCode===ce)return sn(e,n);let i=e.plan;if(i===void 0||!Array.isArray(i.sections))return B(n,null,"plan","update_required");let r=Ae(e);if(r!==null)return dn(r,n);let a=i.current===null?void 0:i.steps.find(h=>h.id===i.current),d=h=>{let y={kind:"processing",key:"processing",context:n,section:h!==void 0?L(h):i.sections.find(O=>O.state==="current")?.id??null,stalled:!1};return typeof h?.service=="string"&&h.service!==""&&(y.service=h.service),y};if(i.current===null)return d(i.steps.find(h=>h.state==="processing"));if(a===void 0)return B(n,null,"step","update_required");if(!Lt.has(a.service))return a.interaction==="server"?d(a):B(n,L(a),a.service,"update_required");if(Vt.has(a.service)||!Re(a))return d(a);let c=a,p=Ut(c),S=c.checkType,g=L(c);if(c.requiresNativeApp===!0)return ln(e,n,g,S);let w=t.isMobile===!1?Ee(e,c):null;if(w==="phone")return{kind:"mobile_required",key:"mobile_required",context:n,section:g,checkType:S};switch(S){case"phone_otp":case"email_otp":return jt(e,c,n,p);case"population_registry":return Wt(e,c,n,p);case"eid_auth":return tn(e,c,n,p);case"doc_ocr":return Qt(e,c,n,p,w==="upload_or_phone");case"identity_confirm":return an(e,n,g)??d(c);case"portrait_icao":return Xe(e,c,n,p,"capture",w==="upload_or_phone");case"liveness":case"face_match":{let h=nn(e,c);if(h!==null)return Xe(e,h,n,p,"match");let y=c.requiresMobile===!0,O=J(e);return{kind:"liveness",key:"biometric",context:n,section:g,mode:S==="face_match"?"selfie":"liveness",requiresMobile:y,instructions:O===null?"standard":"icao",icao:O,livePhoto:en(e,S),...p}}case"poa":return Jt(e,c,n,p,w==="upload_or_phone");case"form":{let h=Ye(c.form);return h===null?B(n,g,S,"update_required"):{kind:"form",key:"form",context:n,section:g,form:h,dir:qe(h.locale),...p}}case"nfc_chip":return B(n,g,S,"platform_unsupported");default:return B(n,g,S,"update_required")}}var pn=/^[A-Z0-9][A-Z0-9 -]{0,39}$/,fn=Object.freeze({normalize:e=>e.trim().toUpperCase().replace(/\s+/g," "),check:e=>pn.test(e),registrySources:Object.freeze([]),describe:"number must be 1 to 40 letters, digits, spaces or hyphens"}),mn=/^[A-Z0-9]{4,20}$/,me=e=>e.trim().toUpperCase().replace(/[\s-]+/g,""),hn=Object.freeze({normalize:me,check:e=>mn.test(me(e)),registrySources:Object.freeze([]),describe:"number must be 4 to 20 letters or digits"});function Sn(e){return typeof e=="string"&&/^\d{10}$/.test(e)&&Number(e)%97===1}var gn={trim:e=>e.trim(),upper_single_space:e=>e.trim().toUpperCase().replace(/\s+/g," "),upper_no_space_or_hyphen:me},yn={mr_nni_mod97:e=>Sn(e)};function _n(e){let t=new RegExp(e.pattern,"u"),n=e.check===null?void 0:yn[e.check];return Object.freeze({normalize:gn[e.normalize],check:i=>t.test(i.trim())&&(n===void 0||n(i)),registrySources:Object.freeze([...e.registrySources]),describe:e.describe})}var bn=Object.freeze(Object.fromEntries(Object.entries(Te).map(([e,t])=>[e,_n(t)])));function he(e,t){return bn[`${e.toUpperCase()}:${t}`]??(t==="drivers_license"?hn:fn)}var kn=Object.freeze({MRT:"MR"});function ot(e,t){let n=e.trim().toUpperCase();return he(kn[n]??n,t)}function it(e){let t=ot(e.issuingCountry,e.type);return t.check(t.normalize(e.number))}function st(e){return he("MR","national_id").check(e)}function Se(e){let t="";for(let n of e){let i=n.codePointAt(0)??0;i>=1632&&i<=1641?t+=String(i-1632):i>=1776&&i<=1785?t+=String(i-1776):n!==" "&&n!=="-"&&n!==" "&&(t+=n)}return t}var Cn=[1e3,2e3,4e3,8e3,15e3],Pn=3e4,An=/^\+[1-9]\d{6,14}$/,Rn=/^\d{6}$/,wn=/^\d{6}$/,xn=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,at=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order","identity_confirm_required","identity_confirm_locked","choice_locked","choice_option_unavailable","choice_not_found","step_not_on_path","check_not_active","native_app_required"]),En={simulatedCapture:!0},In=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]);function lr(e){let t=!1,n=null,i="",r=!1,a=!1,d=!1,c={},p={},S=new Set,g=!1,w=!1,h=null,y="idle",O=new Map,E=new Map,I=(o,s,u)=>{let l=`${o}.${s}`,f=O.get(l);if(f!==void 0)return f;let _=E.get(o),P=(_===void 0?u():_.then(u)).finally(()=>{O.delete(l)});O.set(l,P);let b=P.then(()=>{},()=>{});return E.set(o,b),b.then(()=>{E.get(o)===b&&E.delete(o)}),P},v=async(o,s,u)=>{await e.ensureConsent();let l;try{l=await Me(e.runtime,s)}catch(_){if(_ instanceof j&&at.has(_.code)){await e.refreshView();return}throw _}if(u?.(l),e.destroyed())return;let f=l;f.plan!==void 0&&e.setView!==void 0?e.setView(f):await e.refreshView()},V=async o=>{await e.ensureConsent();let s;try{try{s=await o(e.runtime.client)}catch(u){if(!(u instanceof j)||u.code!=="consent_required")throw u;await e.runtime.ensureConsent({force:!0}),s=await o(e.runtime.client)}}catch(u){if(u instanceof j&&at.has(u.code)){await e.refreshView();return}throw u}e.destroyed()||(s!==void 0&&e.setView!==void 0?e.setView(s):await e.refreshView())},D=(o,s)=>I("choice",`${o}:${s}`,()=>V(u=>u.choose(o,s))),x=(o,s)=>o.options.some(u=>u.id===s)?D(o.nodeId,s):Promise.reject(new RangeError(`option ${String(s)} is not offered`)),U=(o,s)=>{let u=e.currentView(),l=u===null?void 0:de(u,o);return l===void 0?Promise.reject(new RangeError(`the ${s} is not offered`)):D(l.nodeId,l.option.id)},F=o=>I("identity",o,()=>V(s=>s.confirmIdentity===void 0?Promise.reject(new Error("identity confirmation is not available in this build")):s.confirmIdentity(o))),K=(o,s)=>{let u=X(o.form,s);if(u.length>0)return Promise.reject(new ie(u,"client"));let l={answers:{...s.answers},consents:{}};for(let f of o.form.consents)l.consents[f.id]=s.consents[f.id]===!0;return I("form","submit",()=>v("form",(f,_)=>f.submitCheck("form",l,{idempotencyKey:_})).catch(f=>{throw f instanceof j&&f.code===ve?new ie(Je(f.details,o.form,l),"server"):f}))},te=(o,s)=>{let u=o.kind,l=u==="phone_otp",f=l?"phone":"email",_={action:"send"};if(l?o.needsPhone:o.needsEmail){let P=s[f]??p[u],b=l?P?.replace(/[\s().-]/g,""):P?.trim();if(b!==void 0||o.phase!=="verify"){if(b===void 0||!(l?An:xn).test(b))return Promise.reject(l?new N("phone","format"):new Y("email","format"));_[f]=b}}if(l){let P=o.channels,b=s.channel??(P.length===1?P[0]:void 0);if(P.length>0){if(b===void 0)return Promise.reject(new Y("channel","required"));if(!P.includes(b))return Promise.reject(new Y("channel","unavailable"))}b!==void 0&&(_.channel=b),_.phoneRules=1}return I(u,"send",()=>v(u,(P,b)=>P.submitCheck(u,_,{idempotencyKey:b}),P=>{On(P,u)||(c[u]=e.now(),_[f]!==void 0&&(p[u]=_[f]))}))},Z=(o,s)=>Rn.test(s)?I(o,"verify",()=>v(o,(u,l)=>u.submitCheck(o,{action:"verify",code:s},{idempotencyKey:l}))):Promise.reject(new N("code","format")),G=(o,s)=>I("eid_auth",o,()=>v("eid_auth",(u,l)=>u.submitCheck("eid_auth",s,{idempotencyKey:l}))),ne=(o,s)=>{if(o.identifierBound)return G("start",{action:"start"});let u=Se(s??"");if(o.country==="MR"){if(!/^\d{10}$/.test(u))return Promise.reject(new N("nni","format"));if(!st(u))return Promise.reject(new N("nni","check_digit"))}else if(u==="")return Promise.reject(new N("nni","format"));return G("start",{action:"start",identifier:u})},W=(o,s,u)=>{if(o.source!=="typed")return Promise.reject(new RangeError("this session already holds the ID number"));let l=Se(s);return/^\d{10}$/.test(l)?it({type:"national_id",issuingCountry:"MR",number:l})?I("population_registry","submitIdNumber",()=>v("population_registry",(f,_)=>f.submitCheck("population_registry",{idNumber:l,nni:l},{idempotencyKey:_}),()=>{h=`\u2022\u2022\u2022\u2022\u2022\u2022${l.slice(-4)}`})):Promise.reject(new N(u,"check_digit")):Promise.reject(new N(u,"format"))},Q=o=>(e.stopCameras?.(),I(o,"skipCapture",()=>v(o,(s,u)=>s.submitCheck(o,En,{idempotencyKey:u}),()=>{(o==="liveness"||o==="portrait_icao")&&(g=!0)}))),ge=o=>{if(o.kind==="result"||o.context.simulation?.skipCapture!==!0)return o;let s=Mn(o);return s===null?o:{...o,skipCapture:()=>Q(s)}},m=o=>((o.kind==="document"||o.kind==="portrait"||o.kind==="proof_of_address")&&o.photo?.cameraOnPhone===!0&&(o.refresh=async()=>{await e.refreshView()}),o),k=o=>{switch(o.kind){case"phone_otp":case"email_otp":{let s={...o,send:(l={})=>te(o,l),verify:l=>Z(o.kind,l),switchTo:()=>o.canSwitch&&o.switchChannel!==void 0?U([o.switchChannel==="email"?"email_otp":"phone_otp"],"other contact option"):Promise.reject(new RangeError("this session has no other contact option"))},u=c[o.kind];return s.resendAvailableAt===void 0&&u!==void 0&&(s.resendAvailableAt=new Date(u+Pn).toISOString()),s}case"eid":return{...o,start:s=>ne(o,s),verify:s=>wn.test(s)?G("verify",{action:"verify",code:s}):Promise.reject(new N("code","format")),resend:()=>o.resendsRemaining===0?Promise.reject(new RangeError("no new code can be sent for this session")):G("resend",{action:"resend"}),useCamera:()=>o.canUseCamera&&o.cameraMethod!==void 0?U(o.cameraMethod==="document_photo"?["document"]:["population_registry"],"camera path"):Promise.reject(new RangeError("the camera path is not offered"))};case"method":return{...o,select:s=>{let u=o.choice.options.find(l=>q[l.service]===s);return u!==void 0?x(o.choice,u.id):Promise.reject(new RangeError(`method ${String(s)} is not offered`))},choose:s=>x(o.choice,s)};case"choice":return{...o,choose:s=>x(o.choice,s)};case"registry":return{...o,submitIdNumber:s=>W(o,s,"idNumber"),submitNni:s=>W(o,s,"nni"),confirm:()=>I("population_registry","confirm",()=>v("population_registry",(s,u)=>s.submitCheck("population_registry",{},{idempotencyKey:u}))),useDocument:()=>o.canUseDocument?U(["document"],"document method"):Promise.reject(new RangeError("the document method is not offered"))};case"document":return e.bindDocument!==void 0?m(e.bindDocument(o,M)):{...o,issuer:null,documentType:null,captureSide:null,selectDocument:()=>{throw new Error("document capture is not available in this build")},capture:()=>{throw new Error("document capture is not available in this build")},uploadDocument:()=>Promise.reject(new Error("document upload is not available in this build"))};case"portrait":return e.bindPortrait!==void 0?m(e.bindPortrait(o,M)):{...o,uploadFailed:!1,resubmit:()=>Promise.resolve(),capture:()=>{throw new Error("portrait capture is not available in this build")},uploadPortrait:()=>Promise.reject(new Error("portrait upload is not available in this build")),confirmFix:()=>Promise.reject(new Error("portrait review is not available in this build"))};case"proof_of_address":return e.bindProofOfAddress!==void 0?m(e.bindProofOfAddress(o,M)):{...o,uploadPages:()=>Promise.reject(new Error("proof of address upload is not available in this build")),uploadHolderLetter:()=>Promise.reject(new Error("proof of address upload is not available in this build")),capturePage:()=>{throw new Error("proof of address capture is not available in this build")}};case"form":return{...o,validate:s=>X(o.form,s),submit:s=>K(o,s)};case"contact_choice":return{...o,select:s=>{let u=s==="phone"?"phone_otp":s==="email"?"email_otp":void 0,l=o.choice.options.find(f=>f.service===u);return l!==void 0?x(o.choice,l.id):Promise.reject(new RangeError(`contact ${String(s)} is not offered`))},choose:s=>x(o.choice,s)};case"identity_summary":return{...o,...o.idNumberMasked===void 0&&o.summaryKind==="partial"&&h!==null?{idNumberMasked:h,nniMasked:h}:{},portrait:async()=>{let s=e.runtime.client;if(!o.portraitAvailable||s.identityPortrait===void 0)return null;try{return await s.identityPortrait()}catch{return null}},confirm:()=>F("confirm"),retake:()=>o.retakeAvailable?F("retake"):Promise.reject(new RangeError("no retake is left"))};case"liveness":return{...o,capture:s=>e.liveness(s),onLivePhoto:s=>o.livePhoto?.icao===!0&&e.onLivePhoto!==void 0?e.onLivePhoto(s):()=>{}};case"mobile_required":case"native_app_required":case"processing":return{...o,refresh:async()=>{r=!1,await e.refreshView()}};case"unsupported":case"result":return{...o};default:{let s=o;throw new Error(`runner: unhandled step ${JSON.stringify(s)}`)}}},A=o=>ge(k(o)),T=async()=>{if(!a){a=!0;try{for(let o of Cn){if(await e.sleep(o),!t||e.destroyed())return;let s=await e.refreshView().catch(()=>null);if(s!==null&&ee(s,{isMobile:e.isMobile()}).kind!=="processing")return}r=!0,M()}finally{a=!1}}},H=o=>{if(o.kind!=="liveness"||o.mode!=="selfie")return null;let s={kind:"processing",key:"processing",context:o.context,section:o.section,stalled:!1};if(y==="inflight")return s;if(!w||y==="done")return null;let u=e.keptFaceKey?.()??null;return u===null?null:(y="inflight",v("face_match",(l,f)=>l.submitCheck("face_match",{imageKey:u},{idempotencyKey:f}),()=>{y="done"}).then(()=>{y==="inflight"&&(y="done",M())},()=>{y="done",M()}),s)},R=(o,s=!1)=>{if(!t||e.destroyed()||e.chainBusy())return;let u=ee(o,{isMobile:e.isMobile()});u.kind==="registry"&&u.recheck&&(w=!0,y="idle"),u=H(u)??u,u.kind==="processing"?u.stalled=r:r=!1;let l=A(u),f=u.kind==="result"?void 0:u.context.switchable,_=f===void 0?l:{...l,chooseOption:b=>x({nodeId:f.nodeId,kind:f.kind,selected:f.current,options:f.options},b)},P=JSON.stringify(_);u.kind==="registry"&&u.source==="document"&&u.state==="pending"&&!S.has("registry")&&(S.add("registry"),_.confirm().catch(b=>{(!(b instanceof j)||In.has(b.code))&&S.delete("registry")})),!(!s&&P===i)&&(i=P,n=_,e.emitStep(_),u.kind==="processing"&&!r&&y!=="inflight"&&T(),u.kind==="result"&&!d&&(d=!0,e.emitResult(u.result)))};function M(){let o=e.currentView();o!==null&&R(o,!0)}return{run:async()=>{if(e.destroyed())throw new Error("verification destroyed");t=!0;let o=await e.ensureView();return n===null&&R(o),n??A(ee(o,{isMobile:e.isMobile()}))},current:()=>n,onView:o=>R(o),onChainIdle:()=>{let o=e.currentView();o!==null&&R(o)},republish:M,submit:v,faceProbeSkipped:()=>g}}function Mn(e){switch(e.kind){case"document":return"doc_ocr";case"liveness":return e.mode==="selfie"?"face_match":"liveness";case"portrait":return e.phase==="capture"?"portrait_icao":null;case"proof_of_address":return"poa";case"mobile_required":case"native_app_required":return e.checkType;case"unsupported":return e.checkType==="nfc_chip"?"nfc_chip":null;default:return null}}function On(e,t){let n=e,i=n?.plan?.steps??n?.steps;return Array.isArray(i)?i.some(r=>r.checkType===t&&typeof r.reason=="string"):!1}export{dt as a,Nn as b,Ve as c,Fe as d,Dn as e,rt as f,ee as g,Cn as h,Pn as i,lr as j};
@@ -1 +1 @@
1
- import{c as P,d as H,e as A}from"./chunk-OUC57KMS.js";var z=new Set(["nni_unbound","id_number_unbound","method_required","mobile_required","portrait_required"]);function be(e){return z.has(e)}function ve(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 Pe(){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 j={document:"document_photo",nfc:"document_chip",population_registry:"national_number",national_eid:"national_eid"};function f(e){return e.plan?.steps??[]}function x(e){return Math.max(0,e.attempts.max-e.attempts.used)}function W(e){let n=e.plan?.choice;return n!==void 0&&e.plan?.current===n.nodeId?n:null}function Me(e){let n=W(e);if(n?.kind!=="identity_method")return null;let t=n.options.map(r=>j[r.service]).filter(r=>r!==void 0),i=n.options.find(r=>r.nationalEid)?.nationalEid;return i?{available:!0,selected:null,options:t,nationalEid:i}:{available:!0,selected:null,options:t}}var G=new Set(["liveness","face_match"]);function y(e){return e!==void 0&&(e.state==="pending"||e.state==="input_required")}function T(e){return e.status!=="created"&&e.status!=="in_progress"}function M(e){let n=e.plan?.current,t=n==null?void 0:f(e).find(i=>i.id===n);return y(t)?t:void 0}function _(e,n){return f(e).find(t=>t.checkType===n)}function S(e){let n=f(e),t=n.findIndex(i=>i.checkType==="liveness");return n.find((i,r)=>r>t&&i.checkType==="face_match")}function F(e,n){let t=_(n,"liveness")?.state,i=S(n)?.state;return(S(e)?.state??"pending")==="pending"&&(t==="passed"||t==="review")&&i!==void 0&&i!=="pending"&&i!=="skipped"}function V(e,n){let t=new Map(f(e).map(i=>[i.id,i.state]));return f(n).filter(i=>i.checkType==="face_match"&&(t.get(i.id)??"pending")==="pending"&&i.state!=="pending"&&i.state!=="skipped").map(i=>i.id)}var X=/^[0-9a-f]{24}$/i;function R(e){return X.test(e)?`ses_${e}`:e}function w(e,n){let t=R(e);return n===void 0?{sessionId:t,status:"unavailable"}:{sessionId:t,status:"unavailable",reasonCode:n}}function O(e,n,t){let i=R(e);return t===void 0?{sessionId:i,status:n}:{sessionId:i,status:n,reasonCode:t}}function Ve(e,n){let t=Z(e,n),i=Q(e);return i!==void 0&&(t.sandbox={simulated:!0,reason:i}),t}var J=new Set(["no_testers","tester_gate_not_used","tester_gate_missed"]);function Q(e){if(e.sandbox!==!0)return;let n=e.simulation?.reason;return J.has(n)?n:void 0}function Z(e,n){let t=R(e.sessionId);switch(e.status){case"created":case"in_progress":return re(e,n);case"verified":return b(e,{sessionId:t,status:"verified"});case"review_pending":return b(e,O(t,"review",L(e,"review")));case"not_verified":return b(e,ne(e));default:return b(e,{sessionId:t,status:"not_verified"})}}var ee=new Set([0,1,2,3]);function b(e,n){return ee.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={sessionId:R(e.sessionId),status:"not_verified"};return e.reason!==void 0&&(n.reason=e.reason),e.reasonCode!==void 0&&(n.reasonCode=e.reasonCode),e.reasonCode==="device_cooldown"&&e.retryAfter!==void 0&&(n.retryAfter=e.retryAfter),n}function te(e){return e==="rejected"?"rejected":e==="unavailable"?"unavailable":"inconclusive"}function ie(e,n){if(n===void 0)return!1;let t=f(n).find(i=>i.id===e.id);return t!==void 0&&t.attempts.used===e.attempts.used}function re(e,n){let t=R(e.sessionId),i=f(e).find(o=>G.has(o.checkType)&&o.state==="input_required"&&o.reason!==void 0);if(i?.reason==="mobile_required")return w(t,"mobile_required");if(i?.reason!==void 0){if(i.result==="unavailable")return w(t,i.reason);let u=n.autoRetry&&(x(i)>0||ie(i,n.previous))?{sessionId:t,status:"retry",reasonCode:i.reason,attemptsRemaining:x(i)}:{sessionId:t,status:"not_verified",reason:te(i.result),reasonCode:i.reason,attemptsRemaining:x(i)};return i.retakeHint!==void 0&&(u.retakeHint=i.retakeHint),u}let r=M(e);return r===void 0&&f(e).some(o=>o.state==="review")?O(t,"review",L(e,"review")):r?.checkType==="portrait_icao"?w(t,"portrait_required"):w(t)}function L(e,n){return f(e).find(t=>t.state===n&&t.reason!==void 0)?.reason}function K(e,n,t,i,r){return e.presignCapture!==void 0?e.presignCapture(n,t,i,r):e.presign(n,t,i)}function q(e){return{engine:e?.engine,durationMs:e?.clipMs}}var oe=["video/webm","video/mp4"],N="image/jpeg",se=2,ae=1e3,ue=1e4,de=3,ce=10,le=3,pe=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),fe=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","native_app_required"]),k=class extends Error{constructor(){super("verification destroyed"),this.name="FlowCancelledError"}};function me(e){let n=S(e);return _(e,"portrait_icao")?.state!=="pending"&&(n!==void 0?y(n):e.capture?.livePhoto?.oneCapture===!0)}var h=class extends Error{constructor(n){super(n),this.name="AttestationError"}},E=class extends h{constructor(n){super(`no attestation token: ${n}`),this.name="AttestationUnavailableError",this.code=n}};async function D(e,n,t={}){let i=e.uuid(),r=!1,o=!1,u=0,p=0;for(;;)try{return await n(e.client,i)}catch(s){if(s instanceof h){if(o||s instanceof E)throw s;o=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(!(s instanceof P))throw s;if(s.code==="consent_required"&&!r){r=!0,await e.ensureConsent({force:!0}),i=e.uuid();continue}if(s.code==="attestation_invalid"&&!o){o=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(s.code==="inference_unavailable"&&p<de){p+=1;let a=H(s.retryAfterSeconds,ce,e.random??Math.random);e.onBusy?.({attempt:p,retryAfterSeconds:a/1e3}),await e.sleep(a),t.onAttestationInvalid?.(),i=e.uuid();continue}if(pe.has(s.code)&&u<se){u+=1;let a=s.retryAfterSeconds!==void 0?s.retryAfterSeconds*1e3:void 0;await e.sleep(a!==void 0?Math.min(a,ue):ae);continue}throw s}}var he=new Set(["passed","review","processing","skipped"]);async function Fe(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 r=_e(e,n.keyframe),o=ge(e,t,i,r),u=Se(e,r),p=!1,s=new Set,a=!0,C=0;for(;;){if(e.isCancelled())return{kind:"cancelled"};let c=e.getView();if(T(c))return{kind:"settled"};let d=M(c),g=d?.checkType,v=g==="liveness"&&!p?"liveness":g==="face_match"&&!s.has(d?.id)&&s.size<2&&a?"face_match":null;if(v===null)return{kind:"settled"};if(v==="liveness"&&n.captureChannel==="desktop")return{kind:"unavailable",reason:"mobile_required"};try{if(v==="liveness"){p=!0;let l=await o();if(e.isCancelled())return{kind:"cancelled"};F(c,l)&&s.add(S(l)?.id);for(let Y of V(c,l))s.add(Y);await e.applySubmit(l,"liveness");let m=_(e.getView(),"liveness")?.state;a=m===void 0||he.has(m)}else{s.add(d?.id);let l=await u();if(e.isCancelled())return{kind:"cancelled"};for(let m of V(c,l))s.add(m);await e.applySubmit(l,"face_match")}}catch(l){if(e.isCancelled()||l instanceof k)return{kind:"cancelled"};let m=Ce(l);if(m.kind!=="resync"||C>=le)return m;C+=1,await e.refreshView()}}}function _e(e,n){let t=null,i=null,r=()=>t!==null?Promise.resolve(t):(i??(i=(async()=>{let o=await K(e.client,"image",N,n.size,q(e.artifacts));return await e.client.uploadToSpaces(o.uploadUrl,n,N),t=(await e.client.completeMedia(o.key)).key,e.onKeyframePromoted?.(t),t})().finally(()=>{i=null})),i);return{ensure:r,attempt:()=>r().catch(()=>null),current:()=>t}}function ge(e,n,t,i){let r=e.clipKeys?.get()??null,o,u=null,p=0,s;return()=>D(e,async(a,C)=>{if(r===null||o===void 0){if(e.isCancelled())throw new k;o===void 0&&!me(e.getView())&&(o=null),e.onPhase("uploading");let[c,d]=await Promise.all([r!==null?Promise.resolve(r):(async()=>{let g=await K(a,"clip",t,n.size,q(e.artifacts));return await a.uploadToSpaces(g.uploadUrl,n,t),(await a.completeMedia(g.key)).key})(),o!==void 0?Promise.resolve(o===null?null:o.imageKey):i.attempt()]);r=c,e.clipKeys?.set(c),o===void 0&&(o=d===null?null:{imageKey:d})}if(u===null){let c=performance.now();try{u=await e.getAttestation(),s=e.attestationError?.()}catch(d){throw d instanceof h?d:new h(d instanceof Error?d.message:String(d))}p=Math.round(performance.now()-c)}return e.onPhase("checking"),a.submitCheck("liveness",{clipKey:r,attestation:u,captureChannel:e.artifacts.captureChannel,capture:{...ye(e.artifacts),attestationMs:p,attestationError:s,...ke(e.attestationFacts?.())},...o!==null?{faceMatch:o}:{}},{idempotencyKey:C})},{onAttestationInvalid:()=>{u=null}})}function Se(e,n){return()=>D(e,async(t,i)=>{if(n.current()===null){if(e.isCancelled())throw new k;e.onPhase("uploading")}let r=await n.ensure();return e.onPhase("checking"),t.submitCheck("face_match",{imageKey:r},{idempotencyKey:i})})}function ye(e){let n={width:e.width,height:e.height};for(let t of Re)e[t]!==void 0&&(n[t]=e[t]);return n}var Re=["engine","facingMode","mode","formFactor","clipMs","clipFrames","fps","clipRetakes","codec","cameraReadyMs","faceAcquireMs","captureMs","screenRamp","provenance"];function ke(e){return e===void 0?{}:{attestationChecks:e.checks,...e.challengeMs!==void 0?{attestationChallengeMs:e.challengeMs}:{}}}function Ce(e){if(e instanceof h)return{kind:"unavailable",reason:"attestation"};if(e instanceof P){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(fe.has(e.code))return{kind:"resync"}}return{kind:"unavailable",reason:"network"}}var Le="form_answers_invalid",U=class extends Error{constructor(n,t){super(`form answers refused (${n.map(i=>`${i.id}: ${i.code}`).join(", ")})`),this.name="FormAnswersError",this.issues=n,this.source=t}};var B=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="InvalidInputError",this.field=n,this.kind=t}},$=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="OtpInputError",this.field=n,this.kind=t}};function I(e){return e?.source==="upload"?null:e?.source==="choice"&&e.sourcePick!=="camera"?"upload_or_phone":"phone"}function De(e,n){if(n===void 0||!y(n)||n.requiresMobile!==!0)return null;switch(n.checkType){case"liveness":return"phone";case"face_match":{if(n.reason!==void 0)return"phone";let t=_(e,"portrait_icao");return t?.state==="passed"||t?.state==="review"?null:"phone"}case"doc_ocr":return I(e.documents);case"poa":return I(e.proofOfAddress);case"portrait_icao":{let t=e.portrait;return t?.pendingFix!==void 0||t?.reuse?.pending===!0?null:I(t)}default:return null}}function we(e){let n=e?.capture,t=n?.mode;return t==="assisted"||t==="self"||t==="choice"?t:n?.cameraSwitch===!0?"assisted":"self"}function Be(e){let n=e?.capture?.pick;return we(e)==="choice"&&(n==="self"||n==="assisted")?n:null}function $e(e,n,t=null){return e==="choice"?n??t??"self":e}var ze={"MR:drivers_license":{normalize:"upper_no_space_or_hyphen",pattern:"^[0-9]{8}$",check:null,registrySources:[],describe:"number must be the 8-digit Mauritanian driver's license number"},"MR:national_id":{normalize:"trim",pattern:"^[0-9]{10}$",check:"mr_nni_mod97",registrySources:["MR.anrpts"],describe:"number must be the 10-digit Mauritanian national ID number with a valid check digit"}};export{be as a,ve as b,Pe as c,j as d,f as e,x as f,W as g,Me as h,y as i,T as j,M as k,_ as l,R as m,w as n,Ve as o,Q as p,De as q,we as r,Be as s,$e as t,K as u,oe as v,se as w,ae as x,de as y,ce as z,h as A,E as B,D as C,Fe as D,ye as E,Le as F,U as G,ze as H,B as I,$ as J};
1
+ import{c as P,d as H,e as A}from"./chunk-YDG77RHN.js";var z=new Set(["nni_unbound","id_number_unbound","method_required","mobile_required","portrait_required"]);function be(e){return z.has(e)}function ve(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 Pe(){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 j={document:"document_photo",nfc:"document_chip",population_registry:"national_number",national_eid:"national_eid"};function f(e){return e.plan?.steps??[]}function x(e){return Math.max(0,e.attempts.max-e.attempts.used)}function W(e){let n=e.plan?.choice;return n!==void 0&&e.plan?.current===n.nodeId?n:null}function Me(e){let n=W(e);if(n?.kind!=="identity_method")return null;let t=n.options.map(r=>j[r.service]).filter(r=>r!==void 0),i=n.options.find(r=>r.nationalEid)?.nationalEid;return i?{available:!0,selected:null,options:t,nationalEid:i}:{available:!0,selected:null,options:t}}var G=new Set(["liveness","face_match"]);function y(e){return e!==void 0&&(e.state==="pending"||e.state==="input_required")}function T(e){return e.status!=="created"&&e.status!=="in_progress"}function M(e){let n=e.plan?.current,t=n==null?void 0:f(e).find(i=>i.id===n);return y(t)?t:void 0}function _(e,n){return f(e).find(t=>t.checkType===n)}function S(e){let n=f(e),t=n.findIndex(i=>i.checkType==="liveness");return n.find((i,r)=>r>t&&i.checkType==="face_match")}function F(e,n){let t=_(n,"liveness")?.state,i=S(n)?.state;return(S(e)?.state??"pending")==="pending"&&(t==="passed"||t==="review")&&i!==void 0&&i!=="pending"&&i!=="skipped"}function V(e,n){let t=new Map(f(e).map(i=>[i.id,i.state]));return f(n).filter(i=>i.checkType==="face_match"&&(t.get(i.id)??"pending")==="pending"&&i.state!=="pending"&&i.state!=="skipped").map(i=>i.id)}var X=/^[0-9a-f]{24}$/i;function R(e){return X.test(e)?`ses_${e}`:e}function w(e,n){let t=R(e);return n===void 0?{sessionId:t,status:"unavailable"}:{sessionId:t,status:"unavailable",reasonCode:n}}function O(e,n,t){let i=R(e);return t===void 0?{sessionId:i,status:n}:{sessionId:i,status:n,reasonCode:t}}function Ve(e,n){let t=Z(e,n),i=Q(e);return i!==void 0&&(t.sandbox={simulated:!0,reason:i}),t}var J=new Set(["no_testers","tester_gate_not_used","tester_gate_missed"]);function Q(e){if(e.sandbox!==!0)return;let n=e.simulation?.reason;return J.has(n)?n:void 0}function Z(e,n){let t=R(e.sessionId);switch(e.status){case"created":case"in_progress":return re(e,n);case"verified":return b(e,{sessionId:t,status:"verified"});case"review_pending":return b(e,O(t,"review",L(e,"review")));case"not_verified":return b(e,ne(e));default:return b(e,{sessionId:t,status:"not_verified"})}}var ee=new Set([0,1,2,3]);function b(e,n){return ee.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={sessionId:R(e.sessionId),status:"not_verified"};return e.reason!==void 0&&(n.reason=e.reason),e.reasonCode!==void 0&&(n.reasonCode=e.reasonCode),e.reasonCode==="device_cooldown"&&e.retryAfter!==void 0&&(n.retryAfter=e.retryAfter),n}function te(e){return e==="rejected"?"rejected":e==="unavailable"?"unavailable":"inconclusive"}function ie(e,n){if(n===void 0)return!1;let t=f(n).find(i=>i.id===e.id);return t!==void 0&&t.attempts.used===e.attempts.used}function re(e,n){let t=R(e.sessionId),i=f(e).find(o=>G.has(o.checkType)&&o.state==="input_required"&&o.reason!==void 0);if(i?.reason==="mobile_required")return w(t,"mobile_required");if(i?.reason!==void 0){if(i.result==="unavailable")return w(t,i.reason);let u=n.autoRetry&&(x(i)>0||ie(i,n.previous))?{sessionId:t,status:"retry",reasonCode:i.reason,attemptsRemaining:x(i)}:{sessionId:t,status:"not_verified",reason:te(i.result),reasonCode:i.reason,attemptsRemaining:x(i)};return i.retakeHint!==void 0&&(u.retakeHint=i.retakeHint),u}let r=M(e);return r===void 0&&f(e).some(o=>o.state==="review")?O(t,"review",L(e,"review")):r?.checkType==="portrait_icao"?w(t,"portrait_required"):w(t)}function L(e,n){return f(e).find(t=>t.state===n&&t.reason!==void 0)?.reason}function K(e,n,t,i,r){return e.presignCapture!==void 0?e.presignCapture(n,t,i,r):e.presign(n,t,i)}function q(e){return{engine:e?.engine,durationMs:e?.clipMs}}var oe=["video/webm","video/mp4"],N="image/jpeg",se=2,ae=1e3,ue=1e4,de=3,ce=10,le=3,pe=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),fe=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","native_app_required"]),k=class extends Error{constructor(){super("verification destroyed"),this.name="FlowCancelledError"}};function me(e){let n=S(e);return _(e,"portrait_icao")?.state!=="pending"&&(n!==void 0?y(n):e.capture?.livePhoto?.oneCapture===!0)}var h=class extends Error{constructor(n){super(n),this.name="AttestationError"}},E=class extends h{constructor(n){super(`no attestation token: ${n}`),this.name="AttestationUnavailableError",this.code=n}};async function D(e,n,t={}){let i=e.uuid(),r=!1,o=!1,u=0,p=0;for(;;)try{return await n(e.client,i)}catch(s){if(s instanceof h){if(o||s instanceof E)throw s;o=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(!(s instanceof P))throw s;if(s.code==="consent_required"&&!r){r=!0,await e.ensureConsent({force:!0}),i=e.uuid();continue}if(s.code==="attestation_invalid"&&!o){o=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(s.code==="inference_unavailable"&&p<de){p+=1;let a=H(s.retryAfterSeconds,ce,e.random??Math.random);e.onBusy?.({attempt:p,retryAfterSeconds:a/1e3}),await e.sleep(a),t.onAttestationInvalid?.(),i=e.uuid();continue}if(pe.has(s.code)&&u<se){u+=1;let a=s.retryAfterSeconds!==void 0?s.retryAfterSeconds*1e3:void 0;await e.sleep(a!==void 0?Math.min(a,ue):ae);continue}throw s}}var he=new Set(["passed","review","processing","skipped"]);async function Fe(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 r=_e(e,n.keyframe),o=ge(e,t,i,r),u=Se(e,r),p=!1,s=new Set,a=!0,C=0;for(;;){if(e.isCancelled())return{kind:"cancelled"};let c=e.getView();if(T(c))return{kind:"settled"};let d=M(c),g=d?.checkType,v=g==="liveness"&&!p?"liveness":g==="face_match"&&!s.has(d?.id)&&s.size<2&&a?"face_match":null;if(v===null)return{kind:"settled"};if(v==="liveness"&&n.captureChannel==="desktop")return{kind:"unavailable",reason:"mobile_required"};try{if(v==="liveness"){p=!0;let l=await o();if(e.isCancelled())return{kind:"cancelled"};F(c,l)&&s.add(S(l)?.id);for(let Y of V(c,l))s.add(Y);await e.applySubmit(l,"liveness");let m=_(e.getView(),"liveness")?.state;a=m===void 0||he.has(m)}else{s.add(d?.id);let l=await u();if(e.isCancelled())return{kind:"cancelled"};for(let m of V(c,l))s.add(m);await e.applySubmit(l,"face_match")}}catch(l){if(e.isCancelled()||l instanceof k)return{kind:"cancelled"};let m=Ce(l);if(m.kind!=="resync"||C>=le)return m;C+=1,await e.refreshView()}}}function _e(e,n){let t=null,i=null,r=()=>t!==null?Promise.resolve(t):(i??(i=(async()=>{let o=await K(e.client,"image",N,n.size,q(e.artifacts));return await e.client.uploadToSpaces(o.uploadUrl,n,N),t=(await e.client.completeMedia(o.key)).key,e.onKeyframePromoted?.(t),t})().finally(()=>{i=null})),i);return{ensure:r,attempt:()=>r().catch(()=>null),current:()=>t}}function ge(e,n,t,i){let r=e.clipKeys?.get()??null,o,u=null,p=0,s;return()=>D(e,async(a,C)=>{if(r===null||o===void 0){if(e.isCancelled())throw new k;o===void 0&&!me(e.getView())&&(o=null),e.onPhase("uploading");let[c,d]=await Promise.all([r!==null?Promise.resolve(r):(async()=>{let g=await K(a,"clip",t,n.size,q(e.artifacts));return await a.uploadToSpaces(g.uploadUrl,n,t),(await a.completeMedia(g.key)).key})(),o!==void 0?Promise.resolve(o===null?null:o.imageKey):i.attempt()]);r=c,e.clipKeys?.set(c),o===void 0&&(o=d===null?null:{imageKey:d})}if(u===null){let c=performance.now();try{u=await e.getAttestation(),s=e.attestationError?.()}catch(d){throw d instanceof h?d:new h(d instanceof Error?d.message:String(d))}p=Math.round(performance.now()-c)}return e.onPhase("checking"),a.submitCheck("liveness",{clipKey:r,attestation:u,captureChannel:e.artifacts.captureChannel,capture:{...ye(e.artifacts),attestationMs:p,attestationError:s,...ke(e.attestationFacts?.())},...o!==null?{faceMatch:o}:{}},{idempotencyKey:C})},{onAttestationInvalid:()=>{u=null}})}function Se(e,n){return()=>D(e,async(t,i)=>{if(n.current()===null){if(e.isCancelled())throw new k;e.onPhase("uploading")}let r=await n.ensure();return e.onPhase("checking"),t.submitCheck("face_match",{imageKey:r},{idempotencyKey:i})})}function ye(e){let n={width:e.width,height:e.height};for(let t of Re)e[t]!==void 0&&(n[t]=e[t]);return n}var Re=["engine","facingMode","mode","formFactor","clipMs","clipFrames","fps","clipRetakes","codec","cameraReadyMs","faceAcquireMs","captureMs","screenRamp","provenance"];function ke(e){return e===void 0?{}:{attestationChecks:e.checks,...e.challengeMs!==void 0?{attestationChallengeMs:e.challengeMs}:{}}}function Ce(e){if(e instanceof h)return{kind:"unavailable",reason:"attestation"};if(e instanceof P){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(fe.has(e.code))return{kind:"resync"}}return{kind:"unavailable",reason:"network"}}var Le="form_answers_invalid",U=class extends Error{constructor(n,t){super(`form answers refused (${n.map(i=>`${i.id}: ${i.code}`).join(", ")})`),this.name="FormAnswersError",this.issues=n,this.source=t}};var B=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="InvalidInputError",this.field=n,this.kind=t}},$=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="OtpInputError",this.field=n,this.kind=t}};function I(e){return e?.source==="upload"?null:e?.source==="choice"&&e.sourcePick!=="camera"?"upload_or_phone":"phone"}function De(e,n){if(n===void 0||!y(n)||n.requiresMobile!==!0)return null;switch(n.checkType){case"liveness":return"phone";case"face_match":{if(n.reason!==void 0)return"phone";let t=_(e,"portrait_icao");return t?.state==="passed"||t?.state==="review"?null:"phone"}case"doc_ocr":return I(e.documents);case"poa":return I(e.proofOfAddress);case"portrait_icao":{let t=e.portrait;return t?.pendingFix!==void 0||t?.reuse?.pending===!0?null:I(t)}default:return null}}function we(e){let n=e?.capture,t=n?.mode;return t==="assisted"||t==="self"||t==="choice"?t:n?.cameraSwitch===!0?"assisted":"self"}function Be(e){let n=e?.capture?.pick;return we(e)==="choice"&&(n==="self"||n==="assisted")?n:null}function $e(e,n,t=null){return e==="choice"?n??t??"self":e}var ze={"MR:drivers_license":{normalize:"upper_no_space_or_hyphen",pattern:"^[0-9]{8}$",check:null,registrySources:[],describe:"number must be the 8-digit Mauritanian driver's license number"},"MR:national_id":{normalize:"trim",pattern:"^[0-9]{10}$",check:"mr_nni_mod97",registrySources:["MR.anrpts"],describe:"number must be the 10-digit Mauritanian national ID number with a valid check digit"}};export{be as a,ve as b,Pe as c,j as d,f as e,x as f,W as g,Me as h,y as i,T as j,M as k,_ as l,R as m,w as n,Ve as o,Q as p,De as q,we as r,Be as s,$e as t,K as u,oe as v,se as w,ae as x,de as y,ce as z,h as A,E as B,D as C,Fe as D,ye as E,Le as F,U as G,ze as H,B as I,$ as J};