@sekyro/web 0.1.0-rc.29 → 0.1.0-rc.30

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 (34) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +6 -5
  3. package/dist/{capture-session-doc-YC4CT2EQ.js → capture-session-doc-ESEZJBQM.js} +1 -1
  4. package/dist/{challenge-frame-5GG4NDF5.js → challenge-frame-YAQJ5YMB.js} +1 -1
  5. package/dist/{chunk-WOVWAJD4.js → chunk-3LMJ4335.js} +1 -1
  6. package/dist/{chunk-34IITQFB.js → chunk-7252SFZ6.js} +1 -1
  7. package/dist/{chunk-IA5M34P7.js → chunk-A7QFTU6M.js} +1 -1
  8. package/dist/chunk-CMXN4SOZ.js +1 -0
  9. package/dist/{chunk-XIKMTHHH.js → chunk-KA43AAM7.js} +1 -1
  10. package/dist/{chunk-6AH7FXVC.js → chunk-ODI4A5K4.js} +1 -1
  11. package/dist/chunk-OEQJ62CC.js +3 -0
  12. package/dist/{chunk-AL6LIOLW.js → chunk-S5BUCUZ4.js} +1 -1
  13. package/dist/{chunk-CKHBGAUA.js → chunk-SLKRT74K.js} +1 -1
  14. package/dist/{chunk-BF7CLNFA.js → chunk-UTPUHE4J.js} +1 -1
  15. package/dist/client/index.cjs +1 -1
  16. package/dist/client/index.js +1 -1
  17. package/dist/core/index.cjs +1 -1
  18. package/dist/core/index.js +1 -1
  19. package/dist/{create-document-capture-O64FR2DA.js → create-document-capture-V7XCRRDV.js} +1 -1
  20. package/dist/{create-verification-DzPluhA3.d.cts → create-verification-CGBe2yLE.d.cts} +12 -7
  21. package/dist/{create-verification-BvldYuLZ.d.ts → create-verification-aoY2QoRx.d.ts} +12 -7
  22. package/dist/index.cjs +2 -2
  23. package/dist/index.d.cts +2 -2
  24. package/dist/index.d.ts +2 -2
  25. package/dist/index.js +1 -1
  26. package/dist/internal/index.cjs +2 -2
  27. package/dist/internal/index.d.cts +2 -2
  28. package/dist/internal/index.d.ts +2 -2
  29. package/dist/internal/index.js +1 -1
  30. package/dist/{plan-runner-WGMNUBWJ.js → plan-runner-IXCKR4DB.js} +1 -1
  31. package/package.json +1 -1
  32. package/sbom.cdx.json +19 -19
  33. package/dist/chunk-EVIGRYOX.js +0 -3
  34. package/dist/chunk-FVWFAO45.js +0 -1
@@ -1 +1 @@
1
- import{c as f}from"./chunk-TSA6GHUG.js";import{a as h,c as y}from"./chunk-IA5M34P7.js";var k=["session_token_invalid","session_token_required","session_token_session_mismatch","session_not_found","rate_limit_exceeded","consent_required","session_not_active","check_not_found","check_already_finalized","check_out_of_order","check_type_unsupported","force_outcome_forbidden","attestation_invalid","platform_unregistered","app_attest_invalid","too_many_challenges","inference_unavailable","mobile_required","nni_locked","document_nni_mismatch","media_content_type_not_allowed","media_too_large","media_key_invalid","media_key_forbidden","media_not_found","media_unreadable","media_session_invalid","idempotency_key_collision","idempotency_in_progress","idempotency_key_required","validation_error","internal_error","unknown_error","upload_failed","network_error","timeout","nfc_outcome_not_accepted","identity_confirm_required","identity_confirm_locked","choice_not_found","choice_locked","choice_option_unavailable","step_not_on_path","check_not_active","sekyro_app_not_allowed","sekyro_app_unverified","id_number_locked","document_id_number_mismatch","simulated_capture_forbidden","native_app_required"];function K(t){return k.includes(t)}var c=class extends Error{constructor(e){super(e.message),this.name="HostedApiError",this.status=e.status,this.code=e.code,e.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=e.retryAfterSeconds),e.details&&(this.details=e.details)}};function _(t,e,s=Math.random){let n=(t??e)*1e3,o=Math.min(Math.max(n,500),2e4),i=Math.round(o*(1+(s()*2-1)*.25));return Math.min(Math.max(i,500),2e4)}var R=6e4,b=4,I=3e4,M=9e5,E=200,P=5,C=400,A=new Set(["server_busy","request_timeout"]),v=2;function l(t){return(t.split(";")[0]??"").trim()}var O={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},N=`@sekyro/web/${h}`,H=N,g=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.reportedIssues=new Map;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let s=e.fetch;this.fetchImpl=(n,o)=>(s??globalThis.fetch).call(globalThis,n,o),this.requestTimeoutMs=e.requestTimeoutMs??I,this.retryAttempts=e.inProgressRetry?.attempts??P,this.retryDelayMs=e.inProgressRetry?.delayMs??C,this.random=e.random??Math.random}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e},busyRetry:!0})}async reportCameraUnavailable(e){return this.api("POST","/hosted/camera-unavailable",{body:{cause:e}})}async testerGate(e){return this.api("POST","/hosted/tester-gate",{body:{input:e}})}async reportCaptureIssue(e){let s=typeof e.name=="string"?e.name.replace(/[^A-Za-z]/g,"").slice(0,40):"",n=typeof e.engineKind=="string"&&/^[a-z_]{1,32}$/.test(e.engineKind)?e.engineKind:void 0,o=typeof e.attempt=="number"&&Number.isInteger(e.attempt)&&e.attempt>=0&&e.attempt<=1e3?e.attempt:void 0,i=[e.check,o??"",e.kind,s,e.phase??""].join("|"),a=this.reportedIssues.get(i);if(a!==void 0)return a;let d={check:e.check,kind:e.kind,...s!==""?{name:s}:{},...e.phase!==void 0?{phase:e.phase}:{},...n!==void 0?{engineKind:n}:{},...o!==void 0?{attempt:o}:{},...e.formFactor!==void 0?{formFactor:e.formFactor}:{},...typeof e.detail=="string"&&/^\d{1,10}$/.test(e.detail)?{detail:e.detail}:{},...T(e.challengeMs)?{challengeMs:e.challengeMs}:{},...T(e.readyMs)?{readyMs:e.readyMs}:{},...e.inApp===!0?{inApp:!0}:{}},r=this.api("POST","/hosted/capture-issue",{body:d,empty:!0}).catch(()=>{this.reportedIssues.delete(i)});return this.reportedIssues.set(i,r),r}async choose(e,s){let n=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:s},busyRetry:!0});return this.sessionId=n.sessionId,n}async confirmIdentity(e){return this.api("POST","/hosted/identity/confirm",{body:{decision:e}})}async identityPortrait(){return this.api("GET","/hosted/identity/portrait",{blob:!0})}async presign(e,s,n,o={}){let i=await this.ensureSessionId(),a={kind:e,contentType:l(s),contentLength:n,...o.source==="upload"?{source:"upload"}:{}};return this.api("POST",`/sessions/${i}/media`,{body:a})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,s,n,o={}){let i=await this.ensureSessionId(),a=await this.takeCaptureNonce(),d=a===void 0?void 0:{nonce:a,...o.engine!==void 0?{engine:o.engine.slice(0,32)}:{},...o.durationMs!==void 0&&Number.isFinite(o.durationMs)?{captureMs:Math.min(36e5,Math.max(0,Math.round(o.durationMs)))}:{}},r={kind:e,contentType:l(s),contentLength:n,capture:d};return this.api("POST",`/sessions/${i}/media`,{body:r})}async takeCaptureNonce(){let e=()=>{let s=Date.now();return this.captureNonces=this.captureNonces.filter(n=>n.expiresAt-R>s),this.captureNonces.shift()?.nonce};for(let s=0;s<2;s++){let n=e();if(n!==void 0)return n;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let s=await this.ensureSessionId(),n=await this.api("POST",`/sessions/${s}/media/capture-nonces`,{body:{count:Math.min(b,Math.max(1,e))}}),o=Date.now()+Math.max(0,n.expiresIn)*1e3;for(let i of Array.isArray(n.nonces)?n.nonces:[])typeof i=="string"&&i.length>0&&this.captureNonces.push({nonce:i,expiresAt:o});this.captureNonces=this.captureNonces.slice(-b)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,s,n){let o;try{o=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":l(n)},body:s,signal:AbortSignal.timeout(M)})}catch(i){throw m(i)}if(!o.ok){let i=(await o.text().catch(()=>"")).slice(0,E);throw new c({status:o.status,code:"upload_failed",message:`media upload failed (HTTP ${o.status})${i?`: ${i}`:""}`})}}async completeMedia(e){let s=await this.ensureSessionId();return this.api("POST",`/sessions/${s}/media/complete`,{body:{key:e}})}async submitCheck(e,s,n={}){let o=await this.ensureSessionId(),i={input:s,forceOutcome:n.forceOutcome};return this.api("POST",`/sessions/${o}/checks/${e}`,{body:i,idempotencyKey:n.idempotencyKey,busyRetry:n.idempotencyKey!==void 0})}async uploadAndSubmit(e,s,n,o={}){let i=l(s.contentType),a=await this.presign(s.kind,i,s.blob.size);await this.uploadToSpaces(a.uploadUrl,s.blob,i);let d=await this.completeMedia(a.key),r={...n,[O[e]]:d.key};return this.submitCheck(e,r,o)}async ensureSessionId(){return this.sessionId!==null?this.sessionId:(this.bootstrap??(this.bootstrap=this.getSession().finally(()=>{this.bootstrap=null})),(await this.bootstrap).sessionId)}async api(e,s,n={}){let o=e==="GET"||n.busyRetry===!0,i=`${this.apiOrigin}/api/v2${s}`,a={"x-session-token":this.sessionToken,"x-sekyro-sdk":H};n.body!==void 0&&(a["content-type"]="application/json"),n.idempotencyKey!==void 0&&(a["x-idempotency-key"]=n.idempotencyKey);try{let d=y.timezone();d!==void 0&&(a["sekyro-client-timezone"]=d)}catch{}a["sekyro-client-form-factor"]=f();try{let d=await y.deviceHeader();d!==void 0&&(a["sekyro-client-device"]=d)}catch{}for(let d=0;;d++){let r;try{r=await this.fetchImpl(i,{method:e,headers:a,...n.body!==void 0?{body:JSON.stringify(n.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(p){throw m(p)}if(r.ok){if(n.empty===!0)return;if(n.blob===!0)try{return await r.blob()}catch(w){throw m(w)}let p;try{p=await r.json()}catch{throw new c({status:r.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${r.status})`})}return x(p)}let u=await D(r);if(u.code==="idempotency_in_progress"&&d<this.retryAttempts){this.retryDelayMs>0&&await S(this.retryDelayMs);continue}if(o&&u.status===503&&A.has(u.code)){o=!1,await S(_(u.retryAfterSeconds,v,this.random));continue}throw u}}};function T(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=6e5}function m(t){if((typeof t=="object"&&t!==null?t.name:void 0)==="TimeoutError")return new c({status:0,code:"timeout",message:"request timed out"});let s=t instanceof Error?t.message:String(t);return new c({status:0,code:"network_error",message:`network request failed: ${s}`})}function x(t){return t!==null&&typeof t=="object"&&"success"in t&&"data"in t?t.data:t}async function D(t){let e="unknown_error",s=`request failed (HTTP ${t.status})`,n=Number.NaN,o;try{let d=await t.json();if(d!==null&&typeof d=="object"){let r=d;typeof r.code=="string"&&r.code.length>0&&(e=r.code),typeof r.message=="string"&&r.message.length>0&&(s=r.message),typeof r.retryAfterSeconds=="number"&&(n=r.retryAfterSeconds),Array.isArray(r.details?.issues)?o=r.details:Array.isArray(r.details?.errors)&&(o={...r.details,issues:[]})}}catch{}let i=t.headers.get("retry-after"),a=i===null?Math.floor(n):Number.parseInt(i,10);return new c({status:t.status,code:e,message:s,...Number.isFinite(a)&&a>=0?{retryAfterSeconds:a}:{},details:o})}function S(t){return new Promise(e=>setTimeout(e,t))}function j(t){let e=t?.portrait,s=e?.icao,n=e?.purpose==="id_document";return s==null?n?{policy:"reject",profile:"id_document"}:null:{policy:s.policy==="alert"?"alert":"reject",profile:n||s.profile==="id_document"?"id_document":"selfie"}}function B(t){return{...t.baselineEyeOpenness!==void 0?{baselineEyeOpenness:t.baselineEyeOpenness}:{},...t.baselineEyeOpennessLeft!==void 0&&t.baselineEyeOpennessRight!==void 0?{baselineEyeOpennessLeft:t.baselineEyeOpennessLeft,baselineEyeOpennessRight:t.baselineEyeOpennessRight}:{},criteria:t.verdict??{},...t.backgroundCheck!==void 0?{backgroundCheck:t.backgroundCheck}:{}}}export{k as a,K as b,c,_ as d,l as e,N as f,g,j as h,B as i};
1
+ import{c as f}from"./chunk-TSA6GHUG.js";import{a as h,c as y}from"./chunk-A7QFTU6M.js";var k=["session_token_invalid","session_token_required","session_token_session_mismatch","session_not_found","rate_limit_exceeded","consent_required","session_not_active","check_not_found","check_already_finalized","check_out_of_order","check_type_unsupported","force_outcome_forbidden","attestation_invalid","platform_unregistered","app_attest_invalid","too_many_challenges","inference_unavailable","mobile_required","nni_locked","document_nni_mismatch","media_content_type_not_allowed","media_too_large","media_key_invalid","media_key_forbidden","media_not_found","media_unreadable","media_session_invalid","idempotency_key_collision","idempotency_in_progress","idempotency_key_required","validation_error","internal_error","unknown_error","upload_failed","network_error","timeout","nfc_outcome_not_accepted","identity_confirm_required","identity_confirm_locked","choice_not_found","choice_locked","choice_option_unavailable","step_not_on_path","check_not_active","sekyro_app_not_allowed","sekyro_app_unverified","id_number_locked","document_id_number_mismatch","simulated_capture_forbidden","native_app_required"];function K(t){return k.includes(t)}var c=class extends Error{constructor(e){super(e.message),this.name="HostedApiError",this.status=e.status,this.code=e.code,e.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=e.retryAfterSeconds),e.details&&(this.details=e.details)}};function _(t,e,s=Math.random){let n=(t??e)*1e3,o=Math.min(Math.max(n,500),2e4),i=Math.round(o*(1+(s()*2-1)*.25));return Math.min(Math.max(i,500),2e4)}var R=6e4,b=4,I=3e4,M=9e5,E=200,P=5,C=400,A=new Set(["server_busy","request_timeout"]),v=2;function l(t){return(t.split(";")[0]??"").trim()}var O={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},N=`@sekyro/web/${h}`,H=N,g=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.reportedIssues=new Map;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let s=e.fetch;this.fetchImpl=(n,o)=>(s??globalThis.fetch).call(globalThis,n,o),this.requestTimeoutMs=e.requestTimeoutMs??I,this.retryAttempts=e.inProgressRetry?.attempts??P,this.retryDelayMs=e.inProgressRetry?.delayMs??C,this.random=e.random??Math.random}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e},busyRetry:!0})}async reportCameraUnavailable(e){return this.api("POST","/hosted/camera-unavailable",{body:{cause:e}})}async testerGate(e){return this.api("POST","/hosted/tester-gate",{body:{input:e}})}async reportCaptureIssue(e){let s=typeof e.name=="string"?e.name.replace(/[^A-Za-z]/g,"").slice(0,40):"",n=typeof e.engineKind=="string"&&/^[a-z_]{1,32}$/.test(e.engineKind)?e.engineKind:void 0,o=typeof e.attempt=="number"&&Number.isInteger(e.attempt)&&e.attempt>=0&&e.attempt<=1e3?e.attempt:void 0,i=[e.check,o??"",e.kind,s,e.phase??""].join("|"),a=this.reportedIssues.get(i);if(a!==void 0)return a;let d={check:e.check,kind:e.kind,...s!==""?{name:s}:{},...e.phase!==void 0?{phase:e.phase}:{},...n!==void 0?{engineKind:n}:{},...o!==void 0?{attempt:o}:{},...e.formFactor!==void 0?{formFactor:e.formFactor}:{},...typeof e.detail=="string"&&/^\d{1,10}$/.test(e.detail)?{detail:e.detail}:{},...T(e.challengeMs)?{challengeMs:e.challengeMs}:{},...T(e.readyMs)?{readyMs:e.readyMs}:{},...e.inApp===!0?{inApp:!0}:{}},r=this.api("POST","/hosted/capture-issue",{body:d,empty:!0}).catch(()=>{this.reportedIssues.delete(i)});return this.reportedIssues.set(i,r),r}async choose(e,s){let n=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:s},busyRetry:!0});return this.sessionId=n.sessionId,n}async confirmIdentity(e){return this.api("POST","/hosted/identity/confirm",{body:{decision:e}})}async identityPortrait(){return this.api("GET","/hosted/identity/portrait",{blob:!0})}async presign(e,s,n,o={}){let i=await this.ensureSessionId(),a={kind:e,contentType:l(s),contentLength:n,...o.source==="upload"?{source:"upload"}:{}};return this.api("POST",`/sessions/${i}/media`,{body:a})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,s,n,o={}){let i=await this.ensureSessionId(),a=await this.takeCaptureNonce(),d=a===void 0?void 0:{nonce:a,...o.engine!==void 0?{engine:o.engine.slice(0,32)}:{},...o.durationMs!==void 0&&Number.isFinite(o.durationMs)?{captureMs:Math.min(36e5,Math.max(0,Math.round(o.durationMs)))}:{}},r={kind:e,contentType:l(s),contentLength:n,capture:d};return this.api("POST",`/sessions/${i}/media`,{body:r})}async takeCaptureNonce(){let e=()=>{let s=Date.now();return this.captureNonces=this.captureNonces.filter(n=>n.expiresAt-R>s),this.captureNonces.shift()?.nonce};for(let s=0;s<2;s++){let n=e();if(n!==void 0)return n;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let s=await this.ensureSessionId(),n=await this.api("POST",`/sessions/${s}/media/capture-nonces`,{body:{count:Math.min(b,Math.max(1,e))}}),o=Date.now()+Math.max(0,n.expiresIn)*1e3;for(let i of Array.isArray(n.nonces)?n.nonces:[])typeof i=="string"&&i.length>0&&this.captureNonces.push({nonce:i,expiresAt:o});this.captureNonces=this.captureNonces.slice(-b)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,s,n){let o;try{o=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":l(n)},body:s,signal:AbortSignal.timeout(M)})}catch(i){throw m(i)}if(!o.ok){let i=(await o.text().catch(()=>"")).slice(0,E);throw new c({status:o.status,code:"upload_failed",message:`media upload failed (HTTP ${o.status})${i?`: ${i}`:""}`})}}async completeMedia(e){let s=await this.ensureSessionId();return this.api("POST",`/sessions/${s}/media/complete`,{body:{key:e}})}async submitCheck(e,s,n={}){let o=await this.ensureSessionId(),i={input:s,forceOutcome:n.forceOutcome};return this.api("POST",`/sessions/${o}/checks/${e}`,{body:i,idempotencyKey:n.idempotencyKey,busyRetry:n.idempotencyKey!==void 0})}async uploadAndSubmit(e,s,n,o={}){let i=l(s.contentType),a=await this.presign(s.kind,i,s.blob.size);await this.uploadToSpaces(a.uploadUrl,s.blob,i);let d=await this.completeMedia(a.key),r={...n,[O[e]]:d.key};return this.submitCheck(e,r,o)}async ensureSessionId(){return this.sessionId!==null?this.sessionId:(this.bootstrap??(this.bootstrap=this.getSession().finally(()=>{this.bootstrap=null})),(await this.bootstrap).sessionId)}async api(e,s,n={}){let o=e==="GET"||n.busyRetry===!0,i=`${this.apiOrigin}/api/v2${s}`,a={"x-session-token":this.sessionToken,"x-sekyro-sdk":H};n.body!==void 0&&(a["content-type"]="application/json"),n.idempotencyKey!==void 0&&(a["x-idempotency-key"]=n.idempotencyKey);try{let d=y.timezone();d!==void 0&&(a["sekyro-client-timezone"]=d)}catch{}a["sekyro-client-form-factor"]=f();try{let d=await y.deviceHeader();d!==void 0&&(a["sekyro-client-device"]=d)}catch{}for(let d=0;;d++){let r;try{r=await this.fetchImpl(i,{method:e,headers:a,...n.body!==void 0?{body:JSON.stringify(n.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(p){throw m(p)}if(r.ok){if(n.empty===!0)return;if(n.blob===!0)try{return await r.blob()}catch(w){throw m(w)}let p;try{p=await r.json()}catch{throw new c({status:r.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${r.status})`})}return x(p)}let u=await D(r);if(u.code==="idempotency_in_progress"&&d<this.retryAttempts){this.retryDelayMs>0&&await S(this.retryDelayMs);continue}if(o&&u.status===503&&A.has(u.code)){o=!1,await S(_(u.retryAfterSeconds,v,this.random));continue}throw u}}};function T(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=6e5}function m(t){if((typeof t=="object"&&t!==null?t.name:void 0)==="TimeoutError")return new c({status:0,code:"timeout",message:"request timed out"});let s=t instanceof Error?t.message:String(t);return new c({status:0,code:"network_error",message:`network request failed: ${s}`})}function x(t){return t!==null&&typeof t=="object"&&"success"in t&&"data"in t?t.data:t}async function D(t){let e="unknown_error",s=`request failed (HTTP ${t.status})`,n=Number.NaN,o;try{let d=await t.json();if(d!==null&&typeof d=="object"){let r=d;typeof r.code=="string"&&r.code.length>0&&(e=r.code),typeof r.message=="string"&&r.message.length>0&&(s=r.message),typeof r.retryAfterSeconds=="number"&&(n=r.retryAfterSeconds),Array.isArray(r.details?.issues)?o=r.details:Array.isArray(r.details?.errors)&&(o={...r.details,issues:[]})}}catch{}let i=t.headers.get("retry-after"),a=i===null?Math.floor(n):Number.parseInt(i,10);return new c({status:t.status,code:e,message:s,...Number.isFinite(a)&&a>=0?{retryAfterSeconds:a}:{},details:o})}function S(t){return new Promise(e=>setTimeout(e,t))}function j(t){let e=t?.portrait,s=e?.icao,n=e?.purpose==="id_document";return s==null?n?{policy:"reject",profile:"id_document"}:null:{policy:s.policy==="alert"?"alert":"reject",profile:n||s.profile==="id_document"?"id_document":"selfie"}}function B(t){return{...t.baselineEyeOpenness!==void 0?{baselineEyeOpenness:t.baselineEyeOpenness}:{},...t.baselineEyeOpennessLeft!==void 0&&t.baselineEyeOpennessRight!==void 0?{baselineEyeOpennessLeft:t.baselineEyeOpennessLeft,baselineEyeOpennessRight:t.baselineEyeOpennessRight}:{},criteria:t.verdict??{},...t.backgroundCheck!==void 0?{backgroundCheck:t.backgroundCheck}:{}}}export{k as a,K as b,c,_ as d,l as e,N as f,g,j as h,B as i};
@@ -0,0 +1,3 @@
1
+ import{B as tt,C as nt,D as ot,E as rt,a as je,b as Ye,c as $e,d as K,e as z,f as ee,g as We,h as L,i as Qe,j as R,k as D,l as M,m as U,n as N,o as j,p as Ze,q as Y,r as te,s as Je,t as Xe,u as ze,v as et}from"./chunk-UTPUHE4J.js";import{n as qe}from"./chunk-7252SFZ6.js";import{a as Be}from"./chunk-7QZWBDI5.js";import{c as fe,e as Ge,g as Ke,h as ne}from"./chunk-ODI4A5K4.js";import{c as De,d as pe}from"./chunk-TSA6GHUG.js";import{b as Ue}from"./chunk-A7QFTU6M.js";function oe(e){return e.idNumberBound??e.nniBound}function $(e){return e===void 0?void 0:e.idNumberFromDocument??e.nniFromDocument}function it(e){let t=e.idNumberMasked??e.nniMasked;return typeof t=="string"&&t!==""?t:void 0}var Ht="https://api.sekyro.ai",Lt=5e3,Dt=24e4,Ut=12e4,Bt=3,qt=3e3,Gt=1500,Kt=10;function st(e){return e instanceof Error&&e.name==="ChallengeError"&&e.code||"challenge_failed"}var at=new Set(["aborted","embedder_opaque","site_key_rejected"]);function jt(e){return new Promise(t=>setTimeout(t,e))}function Yt(){let e=globalThis.crypto;if(e!==void 0&&typeof e.randomUUID=="function")return e.randomUUID();let t=new Uint8Array(16);if(e!==void 0&&typeof e.getRandomValues=="function")e.getRandomValues(t);else for(let i=0;i<16;i+=1)t[i]=Math.floor(Math.random()*256);t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let n=[...t].map(i=>i.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function so(e){return $t(e,{})}function $t(e,t){let n=e.apiOrigin??Ht,i=e.autoRetry??!0,o=e.rearm??"auto",s=t.client??new Ke({apiOrigin:n,sessionToken:e.clientToken,fetch:e.fetch}),a=t.sleep??jt,c=t.uuid??Yt,f=t.getChallengeToken??((r,u)=>import("./challenge-frame-YAQJ5YMB.js").then(l=>l.executeChallenge({frameUrl:r.url,siteKey:r.siteKey,action:"liveness",subject:u.subject,signal:u.signal}))),g=Be(),S=null,P=null,d=!1,k=new AbortController,m=null,T=null,W=null,Q=()=>W??Je(m),ke=()=>Xe(te(m),Q()),I=r=>{m=r,g.emit("view",r),S?.onView(r)},b=()=>m!==null?Promise.resolve(m):(T??(T=s.getSession().then(r=>(I(r),r)).finally(()=>{T=null})),T),O=async()=>{let r=await s.getSession();return I(r),r},ie=async(r,u)=>{r.plan!==void 0?I(r):await O()},se=null,be=async r=>{let u=await b();if(r||!u.consentRecorded){let l=await s.recordConsent(e.locale);l.plan!==void 0?I(l):m!==null&&I({...m,consentRecorded:!0})}Ve(u)},V=r=>r?.force===!0?be(!0):(se??(se=be(!1).finally(()=>{se=null})),se),ae={client:s,ensureConsent:r=>V(r),sleep:a,uuid:c,...t.random!==void 0?{random:t.random}:{},onBusy:r=>{d||g.emit("busy",r)}},xe=!1,Ae=null,ue=r=>{if(r.status==="verified"||r.status==="not_verified"||r.status==="review"){if(xe)return;xe=!0}Ae=JSON.stringify(r),g.emit("result",r)},xt=r=>{Ae!==JSON.stringify(r)&&ue(r)},we=async r=>{let u=m;r&&(u=await O().catch(()=>m));let l=u===null?null:L(u);return l!==null&&!d&&g.emit("method",l),l!==null},Pe=null,Re=!1,Ie=!1,Oe=()=>nt(ae,(r,u)=>r.submitCheck("population_registry",{},{idempotencyKey:u})),Ee=r=>oe(r)===!0||$(M(r,"population_registry"))===!0,At=async()=>{try{let r=await b();if(R(r)||L(r)!==null||D(r)?.checkType!=="population_registry")return;if(!Ee(r)&&$(M(r,"population_registry"))===void 0&&(r=await O()),!Ee(r)){Ie=!0;return}await V(),await ie(await Oe(),"population_registry");let u=m===null?void 0:M(m,"population_registry");if(u?.state==="input_required"&&u.reason==="registry_unavailable"&&ee(u)>0){if(await a(Lt),d)return;await ie(await Oe(),"population_registry")}}catch(r){if(r instanceof fe&&(r.code==="check_not_active"||r.code==="step_not_on_path")){await O().catch(()=>{});return}Re=!0;return}m!==null&&R(m)&&ue(j(m,{autoRetry:i}))},Me=()=>(Pe??(Pe=At()),Pe),Z=t.now??Date.now,H=null,B,ce,wt=0,de=(r,u)=>`${r.url}
2
+ ${r.siteKey}
3
+ ${u}`,le=(r,u)=>{let l=Z(),h=f(r,{signal:k.signal,subject:u}),p={key:de(r,u),at:l,token:h};return h.then(()=>{p.issuedAt=Z(),ce=void 0},C=>{let w=st(C);if(p.failed=w,d||w==="aborted")return;ce=w;let{detail:A,readyMs:y}=C;q({check:"attestation",kind:"unavailable",engineKind:w,attempt:wt++,challengeMs:Z()-l,readyMs:y,detail:A,inApp:Ue()})}),h.catch(()=>{}),p},ve=(r,u)=>r!==null&&r.key===u&&(r.issuedAt===void 0||Z()-r.issuedAt<Dt),Ve=(r,u={})=>{let l=r?.challenge??null;if(r===null||l===null||d)return;let h=U(r.sessionId),p=H;(u.replaceFailed===!0&&p?.failed!==void 0&&!at.has(p.failed)||!ve(p,de(l,h)))&&(H=le(l,h))},Pt=async(r,u)=>{let l=de(r,u),h=H;H=null;let p=ve(h,l)?h:le(r,u),C=p===h?0:1,w,A=new Promise(y=>{w=setTimeout(()=>y("late"),Ut)});try{for(;;){let y=await Promise.race([p.token.then(E=>({token:E}),E=>({error:st(E)})),A]);if(y==="late")return!d&&H===null&&(H=p),{error:ce??"timeout"};if("token"in y||d||at.has(y.error)||C>=Bt||C>0&&await Promise.race([a(qt*C),A])==="late")return y;if(d)return{error:"aborted"};C+=1,p=le(r,u)}}finally{clearTimeout(w)}},Te=async()=>{B=void 0;let r=await b(),u=r.challenge;if(u==null)return{};let l=await Pt(u,U(r.sessionId));if("token"in l)return{channel:"hosted_web",turnstileToken:l.token};if(B=l.error,r.simulation!==void 0)return{channel:"hosted_web"};throw new tt(l.error)},Rt=()=>B,q=r=>{if(d)return;let u=s.reportCaptureIssue;if(u===void 0)return;let l=r.formFactor;try{l??(l=De())}catch{}try{Promise.resolve(u.call(s,{...r,...l!==void 0?{formFactor:l}:{}})).catch(()=>{})}catch{}},x=null,Ne=Promise.resolve(),G=0,It=async()=>{let r=await b();for(let u=0;u<Kt&&!d&&!R(r)&&D(r)===void 0&&z(r).some(l=>l.state==="processing")&&(await a(Gt),!d);u+=1)r=await O();return r},Ot=async(r,u,l)=>{let{capture:h}=r,p=()=>d,C=()=>r.alive&&r.attempt===l,w=y=>{C()&&h.setFlowState(y)},A=y=>{if(!p()&&(y.status==="unavailable"&&y.reasonCode!==void 0&&!je(y.reasonCode)&&q({check:"liveness",kind:"unavailable",phase:"upload",engineKind:y.reasonCode,attempt:Math.max(0,r.issues.value)}),ue(y),!!C())){if(y.status==="retry"&&o==="auto"){h.handle.retry();return}h.setFlowState("done")}};if(u.degraded==="NO_RECORDER"){let y=m?.sessionId??(await b().catch(()=>null))?.sessionId??"";A(N(y,"no_recorder"));return}w("uploading");try{if(await Me(),p())return;let y=await b(),E;if(!R(y)&&L(y)!==null){await we(!1),A(N(y.sessionId,"method_required"));return}if(!R(y)){if(D(y)?.checkType==="population_registry"){A(N(y.sessionId,Ie?"nni_unbound":Re?"network":"registry_unavailable"));return}if(await V(),p())return;E=m??y;let J=await ot({...ae,artifacts:u,getAttestation:Te,attestationError:Rt,getView:()=>m??y,refreshView:O,applySubmit:ie,onPhase:w,isCancelled:p,onKeyframePromoted:X=>{P=X}});if(p())return;if(J.kind==="unavailable"){let X=N(y.sessionId,J.reason),Le=J.reason==="attestation"?B:void 0;A(Le!==void 0?{...X,attestationError:Le}:X);return}if(J.kind==="resync"&&await O(),m!==null&&L(m)!==null){await we(!1),A(N(y.sessionId,"method_required"));return}y=await It()}A(j(y,{autoRetry:i,previous:E}))}catch{if(p())return;A(N(m?.sessionId??"","network"))}},Et=(r,u)=>{let l=r.attempt;G>0&&r.alive&&r.capture.setFlowState("uploading"),G+=1,Ne=Ne.then(()=>Ot(r,u,l)).finally(()=>{G-=1,G===0&&S?.onChainIdle()}).catch(()=>{})},Fe=r=>{x?.capture.handle.destroy(),x!==null&&(x.alive=!1);let u=qe(r,S?.captureInternals?.(r)??t.capture,()=>m?.capture?.liveness?.keyframe?.rank===!0,ke,()=>m?.capture?.liveness?.screenRamp,{session:()=>te(m),onModeChange:p=>{W=p}}),l={capture:u,alive:!0,attempt:0,issues:$e()};x=l,u.handle.on("error",p=>{q(Ye("liveness",p,l.issues.value))}),u.handle.on("state",p=>{if(l.issues.note(p),p==="starting"){l.attempt+=1,Ve(m,{replaceFailed:!0});let C=m===null?void 0:D(m)?.checkType;(C==="liveness"||C==="face_match")&&V().catch(()=>{})}}),u.handle.on("captured",p=>{Promise.resolve().then(()=>Et(l,p))});let h=u.handle;return{get state(){return h.state},get captureMode(){return h.captureMode},get facingMode(){return h.facingMode},on:(p,C)=>h.on(p,C),start:async p=>{if(m===null&&await b().catch(()=>{}),!!l.alive)return h.start(p)},retry:()=>h.retry(),switchCamera:()=>h.switchCamera(),canSwitchCaptureMode:()=>h.canSwitchCaptureMode(),setCaptureMode:p=>h.setCaptureMode(p),destroy:()=>{l.alive=!1,x===l&&(x=null),h.destroy()}}},Mt=async()=>{if(d)return null;try{let r=await b();return d?null:L(r)}catch{return null}},vt=async()=>{if(d)return"self";try{let r=await b();if(d)return"self";let u=te(r);return u==="choice"?Q()??u:u}catch{return"self"}},Vt=async()=>{if(d)return!1;try{let r=await b();return d||R(r)||pe()?!1:Y(r,D(r))==="phone"||Y(r,M(r,"liveness"))==="phone"}catch{return!1}},Tt=async()=>{if(d)return!1;try{let r=await b();return!d&&r.returning===!0}catch{return!1}},Nt=async r=>{let u=(await b()).plan?.choice,l=u?.options.find(p=>K[p.service]===r);if(!l)throw new RangeError(`method ${String(r)} is not offered`);let h=await s.choose(u.nodeId,l.id);d||I(h)},He=null,Ft=()=>(He??(He=import("./plan-runner-IXCKR4DB.js").then(r=>{let u=r.createPlanRunner({runtime:ae,currentView:()=>m,cameraMode:ke,captureModeSwitch:{pick:Q,choose:l=>{W=l}},ensureView:b,refreshView:O,ensureConsent:()=>V(),liveness:Fe,stopLiveness:()=>{x!==null&&(x.alive=!1,x.capture.handle.destroy(),x=null)},chainBusy:()=>G>0,destroyed:()=>d,sleep:a,isMobile:pe,now:t.now??Date.now,keptFaceKey:()=>P,setView:I,baseCapture:t.capture,emitStep:l=>{d||g.emit("step",l)},emitResult:xt,reportCaptureIssue:q,documentInternals:t.document,portraitInternals:t.portrait,livePhotoInternals:t.livePhoto,uploadInternals:t.upload,pageCameraInternals:t.pageCamera});return S=u,u})),He);return{consent:()=>V(),startRegistry:Me,methodChoice:Mt,selectMethod:Nt,reportCameraUnavailable:async r=>{await V();let u=s.reportCameraUnavailable;if(u===void 0)throw new TypeError("this client cannot report a missing camera");let l=await u.call(s,r).catch(h=>{if(h instanceof fe&&h.code==="check_out_of_order")return s.getSession();throw h});d||I(l)},reportCaptureIssue:q,testerGate:async r=>{let u=s.testerGate;if(u===void 0)throw new TypeError("this client cannot run the tester gate");let l=r.clip,h=Ge(r.clipMime??"");if(l===void 0||!et.includes(h))throw new TypeError("the capture has no clip");await V();let p=await ze(s,"clip",h,l.size,{engine:r.engine,durationMs:r.clipMs});await s.uploadToSpaces(p.uploadUrl,l,h);let{key:C}=await s.completeMedia(p.key),w=await Te(),A=await u.call(s,{clipKey:C,attestation:w,captureChannel:r.captureChannel,capture:{...rt(r),attestationError:B}}),{bound:y,...E}=A;return d||(E.plan!==void 0?I(E):await O()),{bound:y===!0}},mobileRequired:Vt,captureMode:vt,chooseCaptureMode:r=>{W=r},get captureChoice(){return Q()},returning:Tt,liveness:Fe,run:async()=>{if(d)throw new Error("verification destroyed");return(await Ft()).run()},currentStep:()=>S?.current()??null,voiceClips:async()=>{if(d)return null;try{let r=await b();return d?null:r.voice??null}catch{return null}},on:(r,u)=>g.on(r,u),destroy:()=>{d=!0,k.abort(),S?.destroy(),x!==null&&(x.alive=!1,x.capture.handle.destroy(),x=null),g.clear()}}}var ut=["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 Wt=["carte_identite","passport","residence_permit","drivers_license"],Qt=["carte_identite","passport","residence_permit"];function Zt(e,t){let n=e.byIssuer?.[t]??e.default;return Wt.filter(i=>n==="*"?Qt.includes(i):n.includes(i))}function lo(e,t=ut){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(i=>Zt(e,i).length>0).sort()}function ct(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}function po(e){return/^[A-Z]{2}$/.test(e)?String.fromCodePoint(...[...e].map(t=>127462+t.charCodeAt(0)-65)):""}var _={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"},Jt=new Set(["full_name","birth_date","email","phone","address","country","occupation"]),Xt=new Set(["short_text","long_text","single_choice","multiple_choice","yes_no","date","number"]),zt=new Set(["ar","fa","he","ur"]);function dt(e){return zt.has(e.split("-")[0]?.toLowerCase()??"")?"rtl":"ltr"}function lt(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 o of t.questions)if(!en(o))return null;for(let o of n)if(!tn(o))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 en(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"&&Jt.has(t.field):t.kind!=="custom"||typeof t.type!="string"||!Xt.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 tn(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 nn=/^(\d{4})-(\d{2})-(\d{2})$/;function on(e){if(typeof e!="string")return!1;let t=nn.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>=_.dateMin&&e<=_.dateMax}function rn(e){return typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<_.number&&Math.round(e*100)/100===e}function pt(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&&sn(n))return!0}return!1}function sn(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 an=/^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$/,un=/^\+[1-9]\d{6,14}$/,ft=/^[A-Z]{2}$/,cn=e=>e===void 0||typeof e=="string"&&e.trim()===""||Array.isArray(e)&&e.length===0;function dn(e=Date.now()){return new Date(e).toISOString().slice(0,10)}function mo(e,t,n=dn()){let i=[];for(let o of e.questions){let s=t.answers[o.id];if(cn(s)){o.required&&i.push({id:o.id,code:"required"});continue}let a=o.kind==="field"?ln(o.field,s,n):fn(o,s,n);a!==null&&i.push({id:o.id,...a})}for(let o of e.consents)o.required&&t.consents[o.id]!==!0&&i.push({id:o.id,code:"consent_required"});return i}function re(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}}:pt(i)?{code:"card_number"}:null}function mt(e,t,n={}){return on(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 ln(e,t,n){switch(e){case"full_name":return re(t,_.fullName,_.fullNameMin);case"occupation":return re(t,_.occupation);case"birth_date":return mt(t,n,{period:"past"});case"email":return typeof t=="string"&&t.trim().length<=_.email&&an.test(t.trim())?null:{code:"email_invalid"};case"phone":return typeof t=="string"&&un.test(t)?null:{code:"phone_invalid"};case"country":return typeof t=="string"&&ft.test(t)?null:{code:"choice_invalid"};case"address":return pn(t)?null:{code:"address_invalid"};default:return null}}function pn(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"&&ft.test(t.country)&&typeof t.city=="string"&&t.city.trim()!==""&&t.city.trim().length<=_.city&&n.length>=1&&n.length<=_.addressLines&&n.every(i=>i.trim().length<=_.addressLine&&!pt(i))&&(t.postcode===void 0||typeof t.postcode=="string"&&t.postcode.trim().length<=_.postcode)}function fn(e,t,n){let i=new Set((e.choices??[]).map(o=>o.value));switch(e.type){case"short_text":return re(t,_.shortText);case"long_text":return re(t,_.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(o=>i.has(o))?null:{code:"choice_invalid"};case"yes_no":return typeof t=="boolean"?null:{code:"choice_invalid"};case"date":{let o=e.options??{};return mt(t,n,{...typeof o.min=="string"?{min:o.min}:{},...typeof o.max=="string"?{max:o.max}:{},...o.period==="past"||o.period==="future"?{period:o.period}:{}})}case"number":{if(typeof t!="number"||!Number.isFinite(t)||Math.abs(t)>=_.number)return{code:"number_invalid"};let o=e.options??{};return o.integer===!0&&!Number.isInteger(t)?{code:"number_not_integer"}:rn(t)?typeof o.min=="number"&&t<o.min?{code:"number_too_small",params:{min:o.min}}:typeof o.max=="number"&&t>o.max?{code:"number_too_large",params:{max:o.max}}:null:{code:"number_decimals"}}default:return null}}var ho={full_name:_.fullName,occupation:_.occupation,email:_.email,short_text:_.shortText,long_text:_.longText};var ht=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"}),mn=new Map(Object.entries(ht)),go=new Map(Object.entries(ht).map(([e,t])=>[t,e]));function yt(e){return mn.get(e)??e}var Po=["national_number","document_photo","national_eid"],hn=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"]),yn=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),he=["document","population_registry","national_eid"],ye=["phone_otp","email_otp"],_t={identity_method:he,contact:ye},gn=["population_registry","document"],ge="platform_unsupported",Sn=new Set(["prefilled","user_entered","prefilled_or_entered"]),_n={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 v(e){return e.section??_n[e.checkType]??null}function Cn(e,t){let n=e.plan?.choice;if(n===void 0||n.locked)return;let i=n.options.find(o=>o.id!==n.selected&&o.available!==!1&&t.includes(o.service));return i===void 0?void 0:{nodeId:n.nodeId,option:i}}function Se(e){let t=e.plan,n=t?.choice;if(t===void 0||n===void 0||n.locked||t.current===null||t.current===n.nodeId||R(e))return null;let i=_t[n.kind]??[...he,...ye],o=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}]),s=t.steps.find(c=>c.id===t.current)?.service,a=n.selected??o.find(c=>c.service===s)?.id??null;return o.some(c=>c.id!==a)?{nodeId:n.nodeId,kind:n.kind,current:a,options:o}:null}function Ct(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function kn(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 o=Ze(e);return o!==void 0?{otpCode:n,skipCapture:i,reason:o}:{otpCode:n,skipCapture:i}}function bn(e){let t=(e.plan?.sections??[]).map(a=>({id:a.id,state:a.state})),n={sessionId:U(e.sessionId),orgName:e.orgName,sandbox:e.sandbox===!0,returning:e.returning===!0,consentRecorded:e.consentRecorded,expiresAt:e.expiresAt,sections:t.map(a=>a.id),progress:t,purpose:e.purpose??"identity"};e.branding!==void 0&&(n.branding=e.branding),e.cameraUnavailableHandled===!0&&(n.cameraUnavailableHandled=!0);let i=kn(e);i!==void 0&&(n.simulation=i);let o=e.testerGate;o?.offered===!0&&typeof o.attemptsLeft=="number"&&o.attemptsLeft>0&&(n.testerGate={attemptsLeft:o.attemptsLeft});let s=Se(e);return s!==null&&(n.switchable=s),n}function xn(e){let t={attemptsRemaining:ee(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 kt={phone_otp:"phone",email_otp:"email"};function An(e,t){let n=Cn(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return n===void 0?void 0:kt[n.option.service]}function wn(e,t,n,i){let o=t.checkType==="email_otp",s=(o?t.emailOtp:t.otp)??{},a=o?t.emailOtp?.emailSource:t.otp?.numberSource,c=a!==void 0&&Sn.has(a)?a:o?"prefilled_or_entered":"user_entered",f=typeof s.sentToMasked=="string"&&s.sentToMasked.length>0,g=s.prefilled===!0,S=An(e,o?"email_otp":"phone_otp"),P={key:t.checkType,context:n,section:v(t),phase:f?"verify":"send",canSwitch:S!==void 0,...i},d=o?{kind:"email_otp",...P,emailSource:c,needsEmail:c!=="prefilled"&&!g}:{kind:"phone_otp",...P,numberSource:c,needsPhone:c!=="prefilled"&&!g,channels:(t.otp?.channels??[]).filter(k=>k==="whatsapp"||k==="sms")};if(S!==void 0&&(d.switchChannel=S),g&&(d.prefilled=!0),f&&(d.sentToMasked=s.sentToMasked),!o&&t.otp?.channel!==void 0&&(d.channel=t.otp.channel),!o&&Array.isArray(t.phoneCountries)&&(d.phoneCountries=t.phoneCountries.filter(k=>typeof k=="string"&&/^[A-Z]{2}$/.test(k))),!o&&Array.isArray(t.phoneRules)){let k=d.phoneCountries??[];d.phoneRules=t.phoneRules.flatMap(m=>{let T=In(m);return T!==void 0&&k.includes(T.code)?[T]:[]})}return!o&&t.phoneInternational===!0&&(d.phoneInternational=!0),s.expiresAt!==void 0&&(d.codeExpiresAt=s.expiresAt),s.resendAvailableAt!==void 0&&(d.resendAvailableAt=s.resendAvailableAt),d}var Pn=/^[\d[\]\-|()?:^]{1,64}$/;function Rn(e){try{return typeof e=="string"&&Pn.test(e)&&new RegExp(e)!==null}catch{return!1}}var gt=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function In(e){let{code:t,dial:n,trunk:i,lengths:o,formats:s}=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(o)||o.length===0||!o.every(gt))return;let a={code:t,dial:n,lengths:[...o].sort((c,f)=>c-f)};if(i!==void 0&&(a.trunk=i),s!==void 0){if(!(Array.isArray(s)&&s.length<=8&&s.every(f=>Rn(f?.leading)&&Array.isArray(f.groups)&&f.groups.every(gt)&&o.includes(f.groups.reduce((g,S)=>g+S,0)))))return;a.formats=s.map(f=>({leading:f.leading,groups:[...f.groups]}))}return a}function On(e,t,n,i){let o=oe(e)===!0?"bound":$(t)===!0?"document":"typed",s=o==="typed"&&t.state==="input_required"&&t.reason!==void 0&&yt(t.reason)==="id_number_recheck",a=Ct(Se(e)),c=!i.attemptsExhausted&&a.length===1&&a[0]?.service==="document";return{kind:"registry",key:"registry",context:n,section:v(t),state:t.state==="input_required"?"input_required":"pending",source:o,recheck:s,canUseDocument:c,...i}}function En(e,t,n,i,o){let s=[...t.acceptedSides??[]],a={kind:"document",key:"document",context:n,section:v(t),side:s.includes("recto")?"verso":"recto",acceptedSides:s,documents:ct(e),photo:Ce(_e(e.documents),o),...i};return e.detectedCountry!==void 0&&(a.detectedCountry=e.detectedCountry),Vn(e)&&(a.ageStepUp=!0),a}function _e(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 Ce(e,t){return t?{...e,cameraOnPhone:!0}:e}var Mn=10*1024*1024;function vn(e,t,n,i,o){let s=e.proofOfAddress,a=s?.pdf?.maxBytes,c=s?.phase==="holder_letter"?"holder_letter":"document";return{kind:"proof_of_address",key:"proof_of_address",context:n,section:v(t),phase:c,rule:s?.rule??{country:null,countryFrom:"global",source:"preset_global",kinds:[]},nameMatch:s?.nameMatch??"exact_person",photo:Ce(_e(s),o),maxPages:3,pdf:{maxBytes:typeof a=="number"&&a>0?a:Mn,maxPages:3},licenceAddressAccepted:c==="document"&&s?.licenceAddressAccepted===!0,...i}}function Vn(e){let t=z(e).find(i=>i.checkType==="age_estimation"),n=t?.reason;return t?.state==="failed"&&(n==="age_uncertain"||n==="age_unavailable")}function Tn(e){let t=M(e,"liveness");return t?.state==="passed"||t?.state==="review"}function St(e,t,n,i,o,s=!1){let a=t.icao?.report,c=e.portrait,f=o==="capture"?c?.pendingFix??null:null;f!==null&&(o="review");let g=bt(e);return{kind:"portrait",key:`portrait:${o}`,context:n,section:v(t),phase:o,report:Array.isArray(a)?a:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:ne(e),retakeOnly:o==="capture"&&t.state==="input_required"&&g===void 0&&e.capture?.livePhoto?.oneCapture===!0&&Tn(e),photo:Ce(_e(c,o==="capture"),s&&o==="capture"),pendingFix:f,...g!==void 0?{captureMode:g}:{},...c?.reuse?.pending===!0?{reuse:!0}:{},...i}}function bt(e){let t=e.portrait?.captureMode;return t==="self"||t==="assisted"||t==="choice"?t:void 0}var me={minLongSidePx:1280,jpegQuality:.95};function Nn(e,t){let n=e.capture?.livePhoto;if(n?.oneCapture!==!0)return null;let i=M(e,"portrait_icao"),o=n.still??me;return{icao:t==="liveness"&&ne(e)!==null&&bt(e)===void 0&&i!==void 0&&i.state==="pending"&&i.reason===void 0,still:{minLongSidePx:o.minLongSidePx??me.minLongSidePx,jpegQuality:o.jpegQuality??me.jpegQuality}}}function Fn(e,t,n,i){let o=t.eid,s=v(t);if(o===void 0||o.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:n,section:s,checkType:"eid_auth",reason:"update_required"};let a=Ct(Se(e)),c=a.length===1&&gn.includes(a[0]?.service??"")?a[0]:void 0,f=c===void 0?void 0:K[c.service],g=f!==void 0,S={kind:"eid",key:"eid",context:n,section:s,provider:o.provider,providerName:o.providerName,country:o.country,challenge:"app_code",phase:o.awaiting==="code"?"code":"identifier",identifierBound:o.identifierBound===!0,canUseCamera:g,afterPass:o.afterPass==="continue"?"continue":"end",...i};return g&&(S.cameraMethod=f),o.expiresAt!==void 0&&(S.codeExpiresAt=o.expiresAt),o.resendAvailableAt!==void 0&&(S.resendAvailableAt=o.resendAvailableAt),o.resendsRemaining!==void 0&&(S.resendsRemaining=o.resendsRemaining),o.codeAttemptsRemaining!==void 0&&(S.codeAttemptsRemaining=o.codeAttemptsRemaining),S}function Hn(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let n=M(e,"portrait_icao");return n!==void 0&&(n.state==="passed"||n.state==="review")?n:null}var Ln={rejected:"rejected",inconclusive:"inconclusive",unavailable:"unavailable",abandoned:"expired",not_opened:"expired",cancelled:"expired",superseded:"expired",policy:"policy"};function Dn(e){return e.reasonCode===ge?"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?Ln[e.reason]:void 0)??"rejected"}function Un(e,t){let n=Dn(e),i=n==="platform_unsupported"?{sessionId:U(e.sessionId),status:"unavailable",reasonCode:ge}:j(e,{autoRetry:!1}),o={kind:"result",key:"result",context:t,section:null,display:n,result:i};return e.status==="not_verified"&&e.reason!==void 0&&(o.reason=e.reason),e.reasonCode!==void 0&&(o.reasonCode=e.reasonCode),e.status==="not_verified"&&e.step!==void 0&&(o.step=e.step),e.retryAfter!==void 0&&(o.retryAfter=e.retryAfter),o}function Bn(e,t,n){let i=e.identitySummary;if(i==null)return null;let o={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 a of qn){let c=i[a];typeof c=="string"&&c!==""&&(o[a]=c)}let s=it(i);return s!==void 0&&(o.idNumberMasked=s,o.nniMasked=s),o}var qn=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","expiryDate","retakeTarget"];function F(e,t,n,i){return{kind:"unsupported",key:`unsupported:${n}`,context:e,section:t,checkType:n,reason:i}}function Gn(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function Kn(e,t){let n=_t[e.kind]??[...he,...ye],i=Gn(e),o=e.options.flatMap(a=>{if(a.available===!1||!n.includes(a.service))return[];let c={id:a.id,service:a.service};a.nationalEid!=null&&(c.nationalEid=a.nationalEid);let f=(a.channels??[]).filter(g=>g==="whatsapp"||g==="sms");return a.service==="phone_otp"&&f.length>0&&(c.channels=f),[c]});if(o.length===0){let a=e.options.length>0&&e.options.every(c=>c.service==="nfc");return F(t,i,"choice",a?"platform_unsupported":"update_required")}let s={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:o};if(e.kind==="identity_method"){let a={kind:"method",key:"method",context:t,section:i,options:o.map(f=>K[f.service]),choice:s},c=o.find(f=>f.nationalEid!==void 0)?.nationalEid;return c!==void 0&&(a.nationalEid=c),a}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:i,options:o.map(a=>kt[a.service]),selected:null,locked:!1,choice:s}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:i,choice:s}}function jn(e,t,n,i){let o=e.nativeApp,s=typeof o=="object"&&o!==null?o:{},a={sekyroApp:s.sekyroApp===!0};return typeof s.link=="string"&&s.link!==""&&(a.link=s.link),a.sekyroApp&&typeof s.sekyroAppLink=="string"&&s.sekyroAppLink.startsWith("sekyro://")&&(a.sekyroAppLink=s.sekyroAppLink),{kind:"native_app_required",key:`native_app_required:${i}`,context:t,section:n,checkType:i,nativeApp:a}}function Ro(e,t={}){let n=bn(e);if(R(e)||e.reasonCode===ge)return Un(e,n);let i=e.plan;if(i===void 0||!Array.isArray(i.sections))return F(n,null,"plan","update_required");let o=We(e);if(o!==null)return Kn(o,n);let s=i.current===null?void 0:i.steps.find(d=>d.id===i.current),a=d=>{let k={kind:"processing",key:"processing",context:n,section:d!==void 0?v(d):i.sections.find(m=>m.state==="current")?.id??null,stalled:!1};return typeof d?.service=="string"&&d.service!==""&&(k.service=d.service),k};if(i.current===null)return a(i.steps.find(d=>d.state==="processing"));if(s===void 0)return F(n,null,"step","update_required");if(!hn.has(s.service))return s.interaction==="server"?a(s):F(n,v(s),s.service,"update_required");if(yn.has(s.service)||!Qe(s))return a(s);let c=s,f=xn(c),g=c.checkType,S=v(c);if(c.requiresNativeApp===!0)return jn(e,n,S,g);let P=t.isMobile===!1?Y(e,c):null;if(P==="phone")return{kind:"mobile_required",key:"mobile_required",context:n,section:S,checkType:g};switch(g){case"phone_otp":case"email_otp":return wn(e,c,n,f);case"population_registry":return On(e,c,n,f);case"eid_auth":return Fn(e,c,n,f);case"doc_ocr":return En(e,c,n,f,P==="upload_or_phone");case"identity_confirm":return Bn(e,n,S)??a(c);case"portrait_icao":return St(e,c,n,f,"capture",P==="upload_or_phone");case"liveness":case"face_match":{let d=Hn(e,c);if(d!==null)return St(e,d,n,f,"match");let k=c.requiresMobile===!0,m=ne(e);return{kind:"liveness",key:"biometric",context:n,section:S,mode:g==="face_match"?"selfie":"liveness",requiresMobile:k,instructions:m===null?"standard":"icao",icao:m,livePhoto:Nn(e,g),...f}}case"poa":return vn(e,c,n,f,P==="upload_or_phone");case"form":{let d=lt(c.form);return d===null?F(n,S,g,"update_required"):{kind:"form",key:"form",context:n,section:S,form:d,dir:dt(d.locale),...f}}case"nfc_chip":return F(n,S,g,"platform_unsupported");default:return F(n,S,g,"update_required")}}export{Ht as a,Lt as b,Gt as c,Kt as d,Yt as e,so as f,$t as g,ut as h,Wt as i,Zt as j,lo as k,ct as l,po as m,_ as n,dt as o,on as p,rn as q,pt as r,dn as s,mo as t,Po as u,ge as v,v as w,Se as x,Ct as y,Hn as z,Ro as A};
@@ -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-IA5M34P7.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-A7QFTU6M.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 +1 @@
1
- import{d as re,h as Re,i as ve,j as Le,l as Te}from"./chunk-G6LKLN4U.js";import{a as ne,e as Ce,g as xe}from"./chunk-VVUQ4PFU.js";import{m as j}from"./chunk-34IITQFB.js";import{a as we,g as ke}from"./chunk-7QZWBDI5.js";import{k as te}from"./chunk-CPUECYAJ.js";function _e(e,t){let n=new Set(e.flatMap(r=>r.sides.filter(i=>i[t]!==null).map(i=>i.side)));return n.size===1?[...n][0]:null}function ot(e){let t=Ce.find(r=>r.docType===e),n=t.mrz==="none"?null:t.mrz==="td3"?"single":"verso";return{sides:t.sides,format:xe(e),mrz:t.mrz==="none"?"none":"required",mrzSide:n,barcodeSide:null,portraitSide:t.portraitSide}}function Pe(e,t){if(t.length===0)return ot(e);let n=t.some(s=>s.sides.length>1),r=new Set(t.map(s=>s.format)),i=r.size===1?[...r][0]:"card",c=t.filter(s=>s.sides.some(p=>p.mrz!==null)).length,u=t.find(s=>s.sides.length>1===n)?.sides.find(s=>s.portrait)?.side;return{sides:n?["recto","verso"]:["single"],format:i,mrz:c===t.length?"required":c===0?"none":"optional",mrzSide:_e(t,"mrz"),barcodeSide:_e(t,"barcode"),portraitSide:u??(n?"recto":"single")}}function Ee(e,t){if(e===void 0)return[];let n=e.toUpperCase();return Object.prototype.hasOwnProperty.call(ne,n)?ne[n]?.[t]??[]:[]}async function Oe(e,t,n){return await e(t)?n:n==="recto"?"verso":"recto"}var at={low:{maxLongEdge:1920,payloadTargetBytes:7e5,qMin:.7,qMax:.92},mid:{maxLongEdge:2240,payloadTargetBytes:12e5,qMin:.7,qMax:.92},good:{maxLongEdge:2560,payloadTargetBytes:16e5,qMin:.7,qMax:.92}};function it(e){let{deviceMemory:t,effectiveType:n,saveData:r,downlinkMbps:i,sourceLongEdge:c}=e,u=r===!0||n==="slow-2g"||n==="2g"||i!=null&&i>0&&i<1,s=t!=null&&t<=2,p=n==="4g"||i!=null&&i>=5,d=t!=null&&t>=6,M;u||s?M="low":p&&d?M="good":M="mid";let f=at[M],_=c&&c>0?Math.min(f.maxLongEdge,c):f.maxLongEdge;return{tier:M,...f,maxLongEdge:_}}function Ae(e){let t={};try{let n=navigator;typeof n.deviceMemory=="number"&&(t.deviceMemory=n.deviceMemory);let r=n.connection;r&&(t.effectiveType=r.effectiveType,t.saveData=r.saveData,t.downlinkMbps=r.downlink)}catch{}return typeof e=="number"&&e>0&&(t.sourceLongEdge=e),it(t)}function st(e,t,n){let r=Math.min(1,Math.max(0,(e-.28)/.21999999999999997)),i=(t+n)/2;return Math.max(t,n-r*(n-i))}function ut(e,t,n){let r=Math.max(e,t),i=r>0?Math.min(1,n/r):1;return{width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(t*i))}}async function ct(e,t){let n=t.startQ,r=await e(n);for(let i=0;i<4&&!(r.size<=t.budgetBytes||n<=t.qMin);i++)n=Math.max(t.qMin,n-.08),r=await e(n);return{blob:r,quality:n}}async function Be(e,t,n,r,i){if(t<=0||n<=0)return null;let{width:c,height:u}=ut(t,n,r.maxLongEdge),s=document.createElement("canvas");s.width=c,s.height=u;let p=s.getContext("2d");if(!p)return null;p.drawImage(e,0,0,c,u);let d=k=>new Promise((S,x)=>{s.toBlob(l=>l?S(l):x(new Error("canvas toBlob returned null")),"image/jpeg",k)}),M=st(i,r.qMin,r.qMax),{blob:f,quality:_}=await ct(d,{startQ:M,qMin:r.qMin,budgetBytes:r.payloadTargetBytes}).finally(()=>{s.width=0,s.height=0});if(f.size>5242880)throw new Error("encoded document exceeds the 5242880-byte media cap");return{blob:f,quality:_,width:c,height:u}}async function oe(e){let t=Ae(Math.max(e.width,e.height)),n=await Be(e,e.width,e.height,t,.5);if(n===null)throw new Error("canvas encode unavailable");return{blob:n.blob,width:n.width,height:n.height}}async function Et(e){let t=await createImageBitmap(e);try{return await oe(t)}finally{t.close()}}var At=250,Bt=.6,It=1800,Ft=6e3,Wt=2e3,Ie=.16;function ie(e,t){return{layout:e,phase:"framing",captured:{},pending:[],lastCaptureAt:t,lastReportAt:t,manualShutter:!1,restPhase:"framing",readSides:[],needFlip:!1,flipped:!1,flipTimeoutSpent:!1,timeoutCapture:!1,lastShotByTimeout:!1}}var Fe=e=>e==="recto"?"verso":"recto",We=e=>e.phase==="framing"||e.phase==="locking"||e.phase==="flipCue"||e.phase==="reaskRecto",se=e=>(e.captured.recto!==void 0?1:0)+(e.captured.verso!==void 0?1:0)+e.pending.length;function ae(e,t){return e.lastCaptureAt>=0&&e.lastReportAt>=0?e:{...e,lastCaptureAt:e.lastCaptureAt<0?t:e.lastCaptureAt,lastReportAt:e.lastReportAt<0?t:e.lastReportAt}}function lt(e,t,n){if(e.phase==="result")return{...e,lastReportAt:n};let r=!t.present||e.captureArea!==void 0&&t.areaFrac<.6*e.captureArea,{flipped:i,awaySince:c}=e;r&&(c=c??n),c!==void 0&&n-c>=250&&(i=!0),r||(c=void 0);let u=e.flipTimeoutSpent&&!(i&&!e.flipped),s={...e,lastReportAt:n,flipped:i,awaySince:c,flipTimeoutSpent:u,lastArea:t.areaFrac};if(!We(e))return s;if(e.needFlip&&!i){if(!t.ready)return{...s,phase:e.restPhase,goodSince:void 0};let p=e.lastShot!==void 0&&e.pending.includes(e.lastShot);if(u||p)return{...s,goodSince:void 0,phase:e.restPhase};let d=e.goodSince??n;return n-d>=1800?{...s,goodSince:d,phase:"capturing",flipTimeoutSpent:!0,timeoutCapture:!0}:{...s,goodSince:d,phase:e.restPhase}}return t.ready?{...s,phase:"capturing",goodSince:e.goodSince??n}:{...s,goodSince:void 0,phase:t.locking?"locking":e.restPhase}}function dt(e,t){if(!We(e)||e.manualShutter)return e;let n=t-e.lastReportAt>=2e3,r=t-e.lastCaptureAt>=6e3;return n||r?{...e,manualShutter:!0}:e}function mt(e,t,n){let r=e.layout==="singlePage",i=r?{recto:t}:e.captured,c=r?[]:[...e.pending,t],u={...e,captured:i,pending:c,lastShot:t,lastCaptureAt:n,lastReportAt:-1,manualShutter:!1,goodSince:void 0,notice:void 0,awaySince:void 0,flipped:!1,lastShotByTimeout:e.timeoutCapture,timeoutCapture:!1,captureArea:e.lastArea};return r||se({captured:i,pending:c})>=2?{...u,phase:"reading",restPhase:"framing",current:void 0,needFlip:!1}:{...u,phase:"flipCue",restPhase:"flipCue",current:void 0,needFlip:!0}}function ze(e,t,n){return e.pending.includes(t)?{...e,pending:e.pending.filter(r=>r!==t),lastShot:e.lastShot===t?void 0:e.lastShot,phase:e.phase==="capturing"?e.phase:"flipCue",restPhase:"flipCue",current:Fe(n),needFlip:!0,flipTimeoutSpent:!0,goodSince:void 0,manualShutter:!0,notice:"same_face",lastCaptureAt:-1,lastReportAt:-1}:e}function pt(e,t,n){if(!e.pending.includes(t))return e;if(e.captured[n]!==void 0)return ze(e,t,n);let r=e.pending.filter(p=>p!==t),i={...e,pending:r,captured:{...e.captured,[n]:t}};if(se(i)!==1||e.layout==="singlePage")return i;let c=Fe(n),u=c==="recto"&&e.restPhase==="reaskRecto"?"reaskRecto":"flipCue",s=e.phase==="flipCue"||e.phase==="reaskRecto"||e.phase==="framing";return{...i,restPhase:u,current:c,phase:s?u:e.phase}}function ft(e,t){let n=t.id??e.captured[t.side],r={...e.captured};(t.id===void 0||r[t.side]===t.id)&&delete r[t.side];let i=e.pending.filter(d=>d!==n),c=e.layout==="twoSided"&&se({captured:r,pending:i})>0,u=e.lastShotByTimeout||n===e.lastShot!==e.flipped,s=c&&!u,p=s?t.side==="recto"?"reaskRecto":"flipCue":"framing";return{...e,captured:r,pending:i,readSides:e.readSides.filter(d=>d!==t.side),lastShot:e.lastShot===n?void 0:e.lastShot,notice:t.issue,goodSince:void 0,manualShutter:!1,phase:p,restPhase:p,current:t.side,needFlip:s,flipped:!1,flipTimeoutSpent:!1,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1}}function Ue(e,t){switch(t.type){case"report":return lt(ae(e,t.at),t.report,t.at);case"tick":return dt(ae(e,t.at),t.at);case"captured":return mt(ae(e,t.at),t.id,t.at);case"captureFailed":return{...e,phase:e.restPhase,goodSince:void 0,lastCaptureAt:t.at,manualShutter:!0,timeoutCapture:!1};case"classified":return pt(e,t.id,t.side);case"duplicate":return ze(e,t.id,t.side);case"readOk":{let n=e.readSides.includes(t.side)?e.readSides:[...e.readSides,t.side],r=["recto","verso"].filter(c=>e.captured[c]!==void 0),i=e.phase==="reading"&&e.pending.length===0&&r.every(c=>n.includes(c));return{...e,readSides:n,flipTimeoutSpent:!1,phase:i?"result":e.phase}}case"readFailed":return ft(e,t);case"clockRestart":return e.lastCaptureAt<0&&e.lastReportAt<0&&e.awaySince===void 0?e:{...e,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1};case"retake":return{...ie(e.layout,-1),lastCaptureAt:-1,lastReportAt:-1};default:return e}}function gt(e,t,n=!1){let r=e(t);return r===null?"recto":!n||r.y+r.height/2>=t.height/2?"verso":"recto"}async function ht(e,t=!1){let{detectMrzBand:n}=await import("./mrz-band-VYHOTDHY.js");return gt(n,e,t)}async function ue(e,t=480,n,r=n!=null){let i=n??{x:0,y:0,width:e.width,height:e.height},c=Math.max(1,Math.round(i.height/i.width*t)),u=document.createElement("canvas");u.width=t,u.height=c;try{let s=u.getContext("2d");return s===null?"recto":(s.drawImage(e,i.x,i.y,i.width,i.height,0,0,t,c),await ht(s.getImageData(0,0,t,c),r))}finally{u.width=0,u.height=0}}async function Ut(e,t=480){try{let n=await createImageBitmap(e),r=Math.max(1,Math.round(n.height/n.width*t)),i=document.createElement("canvas");i.width=t,i.height=r;let c=i.getContext("2d");return c===null?(n.close(),null):(c.drawImage(n,0,0,t,r),n.close(),c.getImageData(0,0,t,r))}catch{return null}}var ce=(e,t,n)=>Math.min(n,Math.max(t,Math.round(e))),$=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function Ne(e,t,n,r){let i=r.decode??(p=>createImageBitmap(p)),c=async()=>e.stillRead(await i(t),r.region??[0,0,1,1],r.detectorLimit),u;try{u=await c()}catch{try{await new Promise(p=>setTimeout(p,r.retryMs??300)),u=await c()}catch{return null}}let s=u.mrzBox;return s===void 0?null:{engine:r.engine,source:"live_mrz",format:n.format,lineCount:ce(n.lineCount,2,3),checkDigitsValid:!0,stillConfirmed:u.valid&&u.digest===n.digest,band:[$(s[0]),$(s[1]),$(Math.min(s[2],1-s[0])),$(Math.min(s[3],1-s[1]))],digest:n.digest,framesToValid:ce(n.framesToValid,1,1e3),msToValid:ce(n.msToValid,0,12e4)}}function Gt(e){let t=null;return e?.then(n=>{t=n}),()=>t}var bt=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]),yt=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,7,1,5,0,6,64,11,11]);function Ge(e,t=globalThis){let n=t.WebAssembly?.validate;if(typeof n!="function")return{ok:!1,reason:"simd"};try{if(!n.call(t.WebAssembly,bt)||!n.call(t.WebAssembly,yt))return{ok:!1,reason:"simd"}}catch{return{ok:!1,reason:"simd"}}if(typeof t.Worker!="function")return{ok:!1,reason:"worker"};if(typeof t.createImageBitmap!="function")return{ok:!1,reason:"bitmap"};let r=t.navigator?.deviceMemory;return typeof r=="number"&&r<e.minDeviceMemoryGb?{ok:!1,reason:"memory"}:{ok:!0}}function qe(e=globalThis){let t=e.navigator?.connection;return t?.saveData===!0||["slow-2g","2g","3g"].includes(t?.effectiveType??"")}var E=class extends Error{constructor(t){super(t),this.name="OcrEngineError",this.code=t}};function He(){let e=t=>(t.close(),Promise.reject(new E("unsupported")));return{ready:Promise.resolve("unsupported"),busy:!1,bandRead:e,stillRead:e,layoutRead:e,dispose:()=>{}}}function Xe(e){let t;try{if(e.createWorker)t=e.createWorker();else if(e.workerUrl!==void 0)t=new Worker(e.workerUrl,{type:"module",name:"sekyro-ocr"});else return He()}catch{return He()}let n=new Map,r=0,i=!1,c=!1,u=!1;t.addEventListener("message",l=>{let h=l.data,R=n.get(h.id);R&&(n.delete(h.id),R.resolve(h))});let s=()=>{for(let l of n.values())l.reject(new E("error"));n.clear(),d()};t.addEventListener("error",s),t.addEventListener("messageerror",s);function p(l,h=[]){if(i)return Promise.reject(new E("disposed"));let R=++r;return new Promise((B,A)=>{n.set(R,{resolve:B,reject:A});try{t.postMessage({...l,id:R},h)}catch{n.delete(R),A(new E("error"))}})}function d(){if(!i){i=!0;try{t.postMessage({id:++r,kind:"dispose"})}catch{}t.terminate();for(let l of n.values())l.reject(new E("disposed"));n.clear()}}let M=(async()=>{let l=await p({kind:"init",baseUrl:e.baseUrl,salt:e.salt,detectorLimit:e.tuning.detectorLimit,maxDownloadMs:e.tuning.maxDownloadMs});if(l.kind==="failed")return l.reason;if(l.kind!=="ready")return"error";let h=await p({kind:"warmup"});return h.kind!=="ready"?"error":{warmupMs:h.warmupMs,downloadMs:l.downloadMs,cached:l.cached}})().catch(()=>"error"),f,_=new Promise(l=>{f=setTimeout(()=>l("timeout"),e.tuning.loadTimeoutMs)}),k=Promise.race([M,_]).then(l=>(clearTimeout(f),typeof l=="string"?d():u=!0,i&&typeof l!="string"?"error":l));(e.page===void 0?globalThis.addEventListener?globalThis:null:e.page)?.addEventListener("pagehide",d,{once:!0});async function x(l,h,R){if(i)throw h.close(),new E("disposed");if(!u)throw h.close(),new E("not_ready");if(c)throw h.close(),new E("busy");c=!0;let B;try{let A=new Promise((X,W)=>{B=setTimeout(()=>{W(new E("timeout")),d()},e.tuning.readTimeoutMs??1e4)}),O=await Promise.race([p(l,[h]),A]);if(O.kind===R){let{id:X,...W}=O;return W}throw new E(O.kind==="error"?O.code:O.kind==="failed"?O.reason:"error")}finally{clearTimeout(B),c=!1}}return{ready:k,get busy(){return c},bandRead:(l,h=e.tuning.detectorLimit)=>x({kind:"band",bitmap:l,detectorLimit:h},l,"band"),stillRead:(l,h,R=e.tuning.detectorLimit)=>x({kind:"still",bitmap:l,region:h,detectorLimit:R},l,"band"),layoutRead:(l,h)=>x({kind:"layout",bitmap:l,detectorLimit:h},l,"layout"),dispose:d}}var H="sekyro-ocr-1",le=e=>e!==null&&typeof e=="object"?e:{},T=(e,t,n,r)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:r,Ye=(e,t)=>typeof e=="boolean"?e:t,Ve=e=>{let t=typeof e=="string"?/^sekyro-ocr-(\d{1,4})$/.exec(e):null;return t?Number(t[1]):Number.POSITIVE_INFINITY};function Qe(e,t={}){let n=le(e),r=le(n.liveMrz),i=le(n.frontLock),c=Ve(t.engine??H),u=t.mode==="off",s=l=>l.enabled===!0?l.arm==="live"?"live":"control":null,p=s(r),d=s(i),M=(l,h)=>!u&&h==="live"&&Ve(l.minEngine??H)<=c,f=Le,_=M(r,p)?{detectorLimit:T(r.detectorLimit,320,1600,f.detectorLimit),bandMaxWidthPx:T(r.bandMaxWidthPx,320,4096,f.bandMaxWidthPx),minBandWidthPx:T(r.minBandWidthPx,0,4096,f.minBandWidthPx),bandTop:T(r.bandTop,0,.95,f.bandTop),minIntervalMs:T(r.minIntervalMs,0,5e3,f.minIntervalMs),stableReads:Math.round(T(r.stableReads,1,10,f.stableReads)),profileReads:Math.round(T(r.profileReads,1,100,f.profileReads)),maxReadMs:T(r.maxReadMs,50,6e4,f.maxReadMs),searchTimeoutMs:T(r.searchTimeoutMs,1e3,12e4,f.searchTimeoutMs),hint:Ye(r.hint,!0),stillConfirm:Ye(r.stillConfirm,!0)}:null,k=ve,S=(l,h,R)=>T(i[l],h,R,k[l]),x=M(i,d)?{minLines:Math.round(S("minLines",1,50)),fillMin:S("fillMin",0,1),fillMax:S("fillMax",0,2),offsetMax:S("offsetMax",0,1),steadyFillDelta:S("steadyFillDelta",0,1),steadyOffsetDelta:S("steadyOffsetDelta",0,1),layoutShiftMax:S("layoutShiftMax",0,1),lineCountDelta:Math.round(S("lineCountDelta",0,50)),lockMs:S("lockMs",0,3e4),steadyMs:S("steadyMs",0,3e4),minFrames:Math.round(S("minFrames",1,100)),minIntervalMs:S("minIntervalMs",0,5e3),maxWidthPx:S("maxWidthPx",160,2048),detectorLimit:S("detectorLimit",320,1600),searchTimeoutMs:S("searchTimeoutMs",1e3,12e4)}:null;return{enabled:_!==null||x!==null,liveMrz:_,textLock:x,liveMrzArm:p,frontLockArm:d,load:{detectorLimit:_?.detectorLimit??x?.detectorLimit??f.detectorLimit,loadTimeoutMs:T(r.loadTimeoutMs,1e3,12e4,2e4),maxDownloadMs:T(r.maxDownloadMs,1e3,12e4,2e4),minDeviceMemoryGb:T(r.minDeviceMemoryGb,0,64,2)},reportSampleRate:T(r.reportSampleRate,0,1,1)}}function Ke(e,t){return e.enabled?!(t.probe??Ge)({minDeviceMemoryGb:e.load.minDeviceMemoryGb}).ok||(t.slow??qe)()?{ok:!1,reason:"unsupported"}:{ok:!0,engine:Xe({baseUrl:t.baseUrl,salt:t.salt,tuning:{detectorLimit:e.load.detectorLimit,maxDownloadMs:e.load.maxDownloadMs,loadTimeoutMs:e.load.loadTimeoutMs},...t.workerUrl!==void 0?{workerUrl:t.workerUrl}:{},...t.createWorker!==void 0?{createWorker:t.createWorker}:{},...t.page!==void 0?{page:t.page}:{}})}:{ok:!1,reason:"off"}}function St(e=typeof navigator<"u"?navigator.userAgent:""){return/SamsungBrowser\//.test(e)?"samsung":/Firefox\/|FxiOS\//.test(e)?"firefox":/Chrome\/|CriOS\/|Chromium\//.test(e)&&!/Edg\/|OPR\//.test(e)?"chrome":/Safari\//.test(e)&&/Version\/|Mobile\//.test(e)&&!/Chrome\/|CriOS\//.test(e)?"safari":"other"}var F=e=>e===void 0||!Number.isFinite(e)?void 0:Math.min(6e5,Math.max(0,Math.round(e))),de=(e,t,n)=>e===void 0||!Number.isFinite(e)?void 0:Math.min(n,Math.max(t,Math.round(e)));function je(e){let t=e.assist??null,n=e.load!==null&&e.load!==void 0&&typeof e.load=="object"?e.load:null,r=typeof e.load=="string"?e.load:null,i=t!==null?t.outcome:r==="unsupported"||r==="download"||r==="integrity"?r:r==="error"||r==="timeout"?"error":"off",c={kind:"live_mrz",platform:"web",engine:e.engine??H,arm:e.arm,capture:e.capture,outcome:i,reads:de(t?.reads??0,0,1e4)??0,browser:e.browser??St()},u=(s,p)=>{p!==void 0&&(c[s]=p)};return u("format",t?.format),u("framesToValid",de(t?.framesToValid,1,1e4)),u("msToValid",F(t?.msToValid)),u("framesToLock",de(t?.framesToLock,1,1e4)),u("msToLock",F(t?.msToLock)),u("msToCapture",F(e.msToCapture)),u("readP50Ms",F(t?.readP50Ms)),u("readP90Ms",F(t?.readP90Ms)),u("deviceClass",t?.deviceClass),n!==null&&(u("warmupMs",F(n.warmupMs)),u("downloadMs",F(n.downloadMs)),u("cached",n.cached)),u("stillConfirmed",e.stillConfirmed),u("typeMismatch",e.typeMismatch),c}function me(e,t){return e===void 0?!1:t==="passport"?e!=="TD3":e==="TD3"}var Mt=2;async function Dt(e){let t=await import("./capture-session-doc-YC4CT2EQ.js");return new t.CaptureSessionDoc(e)}function wt(e){return{topLeft:{x:e.x,y:e.y},topRight:{x:e.x+e.width,y:e.y},bottomRight:{x:e.x+e.width,y:e.y+e.height},bottomLeft:{x:e.x,y:e.y+e.height}}}function kt(e,t,n){let r=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let c=0;c<r.length;c+=1){let u=r[c],s=r[(c+1)%r.length];i+=u.x*s.y-s.x*u.y}return t>0&&n>0?Math.abs(i)/2/(t*n):0}function ln(){import("./capture-session-doc-YC4CT2EQ.js").then(e=>e.warmDocDetector()).catch(()=>{})}function dn(e){return Ct(e,{}).handle}function Ct(e,t){let n=we(),r=ke({enabled:e.keepScreenAwake!==!1}),i=t.decode??(o=>createImageBitmap(o)),c=t.blurRefuseSharpnessMax??.16,u=t.now??(()=>performance.now()),s=Pe(e.documentType,t.catalogCapture===!0?Ee(e.issuer,e.documentType):[]),p=s.sides.length===1||e.side==="single",d=ie(p?"singlePage":"twoSided",u());if(!p&&(e.side==="recto"||e.side==="verso")){let o=e.side==="recto"?"verso":"recto";d={...d,captured:{[o]:"server"},readSides:[o],current:e.side,phase:"flipCue",restPhase:"flipCue"}}let M="idle",f=null,_=null,k=!0,S=0,x=0,l=!1,h=!1,R="",B=null,A,O=null,X=[],W=s.mrz==="none",$e=s.barcodeSide==="recto"||s.barcodeSide==="verso"?s.barcodeSide:null,N=W&&!p?t.barcode?.side??$e:null,pe=e.barcodeAssetBaseUrl??t.barcode?.assetBaseUrl,fe=null,ge=()=>N===null||pe===void 0||t.barcode?.seen!==void 0?Promise.resolve(null):(fe??(fe=import("./barcode-detect-C5IOXMKI.js").then(o=>o.loadBarcodeDetect(pe)).catch(()=>null)),fe),Je=async(o,a)=>{if(N===null)return null;let m=N==="recto"?"verso":"recto";try{let g=t.barcode?.seen;if(g!==void 0)return await g(o)?N:m;let[L,D]=await Promise.all([ge(),a()]);if(L===null||D===null)return null;let w=Math.min(1600,D.width),y=document.createElement("canvas");y.width=w,y.height=Math.max(1,Math.round(D.height/D.width*w));try{let b=y.getContext("2d");return b===null?null:(b.drawImage(D,0,0,y.width,y.height),await Oe(L,b.getImageData(0,0,y.width,y.height),N))}finally{y.width=0,y.height=0}}catch{return null}},C=t.webOcr!==void 0&&!W?Qe(t.webOcr.captureDocument,{mode:e.liveMrz?.mode??"auto"}):null,G=null,z=C===null||!C.enabled?"off":null,Y=null,V=null,he=new WeakMap,J="";if(C!==null&&C.enabled&&t.webOcr!==void 0){let o=t.webOcr,a=Ke(C,{baseUrl:e.liveMrz?.assetBaseUrl??o.baseUrl,salt:o.salt,...e.liveMrz?.workerUrl!==void 0?{workerUrl:e.liveMrz.workerUrl}:{},...o.createWorker!==void 0?{createWorker:o.createWorker}:{}});if(a.ok){G=a.engine;let m=new Te({textLock:C.textLock,liveMrz:C.liveMrz});Y=m;let g=a.engine;g.ready.then(L=>{z=L,typeof L!="string"&&k&&m.setEngine(g)})}else z=a.reason}let U=o=>{let a=JSON.stringify(o);a!==J&&(J=a,n.emit("mrz",o))},be=(o,a)=>{let m=t.webOcr?.reports;if(m===void 0||C===null||o===void 0)return;let g=o.format==="ID-3"||o.side==="single"?"single":o.side==="verso"?"verso":"recto",L=g!=="recto"?C.liveMrzArm??C.frontLockArm:C.frontLockArm;if(L===null||Math.random()>=C.reportSampleRate)return;let D=o.via==="live_mrz"?V:null,w=()=>{let y=D?.value??null;m([je({arm:L,capture:g,assist:o.ocr??null,load:L==="control"?"off":z,...o.msToCapture!==void 0?{msToCapture:o.msToCapture}:{},...y!==null&&y.stillConfirmed!==void 0?{stillConfirmed:y.stillConfirmed}:{},...a!==void 0?{typeMismatch:me(a.format,s.format==="ID-3"?"passport":"card")}:{}})])};D!==null&&D.value===null?Promise.race([D.promise,new Promise(y=>setTimeout(y,3e3))]).then(w):w()},I=o=>{!k||o===M||(M=o,r.setActive(o==="starting"||o==="scanning"),n.emit("state",o))},Ze=(o,a)=>a===void 0?null:p?"single":o.captured.recto===a?"recto":o.captured.verso===a?"verso":null,et=o=>({phase:o.phase,captured:p?o.captured.recto!==void 0?["single"]:[]:["recto","verso"].filter(a=>o.captured[a]!==void 0),expected:p?null:o.current??null,notice:o.notice??null,lastShot:Ze(o,o.lastShot),manualShutter:o.manualShutter,torchAvailable:f?.torchAvailable()??!1,torch:h}),ye=()=>{let o=f;o!==null&&o.captureNow().catch(()=>v({type:"captureFailed",at:u()}))};function v(o){if(!k)return;let a=d;d=Ue(d,o),d.phase==="capturing"&&a.phase!=="capturing"&&Promise.resolve().then(ye),d.phase==="result"&&a.phase!=="result"&&(I("done"),Se());let m=et(d),g=JSON.stringify(m);g!==R&&(R=g,n.emit("scan",m))}function Se(){O!==null&&clearInterval(O),O=null;for(let o of X.splice(0))o();f?.destroy(),f=null,r.setActive(!1)}let Me=()=>f?.captureReport?.(),Z=!1,De=(o,a)=>{if(!(o===void 0||t.onFaceReport===void 0))try{t.onFaceReport(o,a)}catch{}},Q=o=>{J="",!(f===null||d.phase==="reading"||d.phase==="result")&&(Z=!1,f.rearm(p?"single":d.current??o))},tt=async(o,a,m,g)=>{if(V=null,g!==void 0&&G!==null&&C?.liveMrz?.hint===!0){let b={promise:Ne(G,o,g,{engine:H,detectorLimit:C.liveMrz.detectorLimit}).catch(()=>null),value:null};b.promise.then(P=>{b.value=P}),V=b}g!==void 0&&me(g.format,s.format==="ID-3"?"passport":"card")&&U({state:"mismatch",format:g.format});let L=Me();De(L,"captured"),Z=!0,be(L,g);let D=m===void 0?B:m===null?null:{quad:wt(m),frameWidth:0,frameHeight:0,inStill:!0},w={decoded:null},y=()=>(w.decoded??(w.decoded=Promise.resolve().then(()=>i(o)).catch(()=>null)),w.decoded);try{await nt(o,a,D,y,V)}finally{w.decoded!==null&&(await w.decoded)?.close()}},nt=async(o,a,m,g,L)=>{let D=`shot-${S+=1}`;if(v({type:"captured",id:D,at:u()}),e.haptics!==!1)try{globalThis.navigator?.vibrate?.(30)}catch{}if(!l&&c>0){let b=await(t.measureSharpness!==void 0?t.measureSharpness(o,m):g().then(P=>P===null?-1:Re(P,re(m?.quad??null,m?.inStill===!0?P:{width:m?.frameWidth??0,height:m?.frameHeight??0},P)))).catch(()=>-1);if(!k)return;if(Number.isFinite(b)&&b>=0&&b<c){l=!0;let P=p?"recto":d.current??(d.captured.recto===void 0?"recto":"verso");v({type:"readFailed",side:P,id:D,issue:"blurry"}),Q(P);return}}l=!1;let w;if(p)w="single";else{let b=d.current,q=(t.classify===void 0?await Je(o,g):null)??await(t.classify!==void 0?t.classify(o):g().then(K=>K===null?b??"recto":m?.inStill===!0?ue(K,480,null,!0):ue(K,480,re(m?.quad??null,{width:m?.frameWidth??0,height:m?.frameHeight??0},K)))).catch(()=>b??"recto");if(!k)return;if(d.captured[q]!==void 0&&x<Mt){x+=1,v({type:"duplicate",id:D,side:q}),Q(q==="recto"?"verso":"recto");return}w=d.captured[q]!==void 0&&b!==void 0?b:q,x=0,v({type:"classified",id:D,side:w})}let y=w==="verso"?"verso":"recto";try{let b=t.encode!==void 0?await t.encode(o):await g().then(P=>{if(P===null)throw new Error("the still could not be decoded");return oe(P)});if(!k)return;L!==null&&he.set(b.blob,L),n.emit("captured",{image:b.blob,side:w,documentType:e.documentType,...e.issuer!==void 0?{issuer:e.issuer}:{},width:b.width,height:b.height,previewDataUrl:a}),t.deferRead!==!0&&v({type:"readOk",side:y})}catch(b){v({type:"readFailed",side:y,id:D,issue:"technical"}),n.emit("error",j("generic",!0,{phase:"keyframes",name:te(b)}))}Q(y==="recto"?"verso":"recto")},rt=o=>{X.push(o.on("statechange",({state:a})=>{a==="preflight"||a==="acquiring"?I("starting"):a==="positioning"?I("scanning"):a==="captured"?I("captured"):a==="error"&&I("error")}),o.on("feedback",({key:a,reticle:m})=>n.emit("feedback",{key:a,reticle:m})),o.on("checks",a=>{n.emit("gate",{progress:a.p,quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight,...a.guide!==void 0?{guide:{detected:a.guide.detected,fill:a.guide.fill,offsetX:a.guide.offsetX??0,offsetY:a.guide.offsetY??0}}:{}});let m=a.ocr?.mrz;m!==void 0&&(m.state==="fallback"?U({state:"fallback",reason:m.reason}):m.state==="valid"?U({state:"valid",format:m.format}):m.state==="reading"?U({state:"reading",...m.format?{format:m.format}:{},...m.coach?{coach:m.coach}:{}}):U({state:"searching"}));let g=a.quad===null?0:kt(a.quad,a.frameWidth,a.frameHeight);B=a.quad===null?null:{quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight},v({type:"report",report:{present:a.quad!==null&&a.plausible||a.guide?.detected===!0,ready:a.ready===!0,locking:a.p>=.5,areaFrac:g},at:u()})}),o.on("error",({kind:a,retryable:m,detail:g})=>n.emit("error",j(a,m,g))),o.on("artifacts",a=>{tt(a.keyframe,a.previewDataUrl,a.docRegion,a.liveMrz)}))},ee=()=>(_??(_=(async()=>{if(k){if(ge(),f===null){let o;try{o=await(t.createEngine??Dt)({...t.engineOptions??{},...A!==void 0?{guide:A}:{},video:e.video,format:s.format,side:p?"single":e.side??"recto",autoCapture:!1,...Y!==null?{ocr:Y}:{}})}catch(m){I("error"),n.emit("error",j("models",!0,{phase:"models",name:te(m)}));return}if(!k){o.destroy();return}f=o,rt(o);let a=t.tickMs??500;a>0&&(O=setInterval(()=>v({type:"tick",at:u()}),a))}v({type:"clockRestart"}),C!==null&&C.liveMrzArm==="live"&&(z==="unsupported"||z==="off")&&U({state:"fallback",reason:z}),await f.start()}})().finally(()=>{_=null})),_);return{handle:{get state(){return M},on:(o,a)=>n.on(o,a),start:ee,retry:()=>{if(f===null&&d.phase==="result"){v({type:"retake"}),x=0,l=!1,ee();return}if(f!==null&&M!=="error"){v({type:"retake"}),x=0,l=!1,f.rearm(p?"single":void 0);return}ee()},setSide:o=>{p||o==="single"||(d.current!==o&&(d={...d,current:o}),v({type:"clockRestart"}),d.phase!=="reading"&&d.phase!=="result"&&f?.rearm(o))},shutter:ye,focusAt:(o,a)=>{f?.focusAt?.(o,a)},setGuide:o=>{A=o,f?.setGuide?.(o)},setTorch:o=>{h=o,f?.setTorch(o),v({type:"tick",at:u()})},destroy:()=>{if(k&&f!==null&&M!=="done"){let o=Me();!Z&&o!==void 0&&o.ticks>0&&De(o,"abandoned"),be(o,void 0)}k=!1,Se(),Y?.setEngine(null),G?.dispose(),G=null,n.clear()}},setFlowState:o=>{(d.phase==="reading"||d.phase==="result")&&I(o==="done"&&d.phase!=="result"?"scanning":o)},settle:(o,a)=>{let m=o==="verso"?"verso":"recto";v(a.ok?{type:"readOk",side:m}:{type:"readFailed",side:m,issue:a.issue}),a.ok||Q(m)},takeDeviceRead:o=>he.get(o.image)?.value??null}}export{Et as a,At as b,Bt as c,It as d,Ft as e,Wt as f,Ie as g,ie as h,Ue as i,gt as j,ht as k,Ut as l,Ne as m,Gt as n,H as o,Qe as p,Ke as q,St as r,je as s,me as t,Mt as u,ln as v,dn as w,Ct as x};
1
+ import{d as re,h as Re,i as ve,j as Le,l as Te}from"./chunk-G6LKLN4U.js";import{a as ne,e as Ce,g as xe}from"./chunk-VVUQ4PFU.js";import{m as j}from"./chunk-7252SFZ6.js";import{a as we,g as ke}from"./chunk-7QZWBDI5.js";import{k as te}from"./chunk-CPUECYAJ.js";function _e(e,t){let n=new Set(e.flatMap(r=>r.sides.filter(i=>i[t]!==null).map(i=>i.side)));return n.size===1?[...n][0]:null}function ot(e){let t=Ce.find(r=>r.docType===e),n=t.mrz==="none"?null:t.mrz==="td3"?"single":"verso";return{sides:t.sides,format:xe(e),mrz:t.mrz==="none"?"none":"required",mrzSide:n,barcodeSide:null,portraitSide:t.portraitSide}}function Pe(e,t){if(t.length===0)return ot(e);let n=t.some(s=>s.sides.length>1),r=new Set(t.map(s=>s.format)),i=r.size===1?[...r][0]:"card",c=t.filter(s=>s.sides.some(p=>p.mrz!==null)).length,u=t.find(s=>s.sides.length>1===n)?.sides.find(s=>s.portrait)?.side;return{sides:n?["recto","verso"]:["single"],format:i,mrz:c===t.length?"required":c===0?"none":"optional",mrzSide:_e(t,"mrz"),barcodeSide:_e(t,"barcode"),portraitSide:u??(n?"recto":"single")}}function Ee(e,t){if(e===void 0)return[];let n=e.toUpperCase();return Object.prototype.hasOwnProperty.call(ne,n)?ne[n]?.[t]??[]:[]}async function Oe(e,t,n){return await e(t)?n:n==="recto"?"verso":"recto"}var at={low:{maxLongEdge:1920,payloadTargetBytes:7e5,qMin:.7,qMax:.92},mid:{maxLongEdge:2240,payloadTargetBytes:12e5,qMin:.7,qMax:.92},good:{maxLongEdge:2560,payloadTargetBytes:16e5,qMin:.7,qMax:.92}};function it(e){let{deviceMemory:t,effectiveType:n,saveData:r,downlinkMbps:i,sourceLongEdge:c}=e,u=r===!0||n==="slow-2g"||n==="2g"||i!=null&&i>0&&i<1,s=t!=null&&t<=2,p=n==="4g"||i!=null&&i>=5,d=t!=null&&t>=6,M;u||s?M="low":p&&d?M="good":M="mid";let f=at[M],_=c&&c>0?Math.min(f.maxLongEdge,c):f.maxLongEdge;return{tier:M,...f,maxLongEdge:_}}function Ae(e){let t={};try{let n=navigator;typeof n.deviceMemory=="number"&&(t.deviceMemory=n.deviceMemory);let r=n.connection;r&&(t.effectiveType=r.effectiveType,t.saveData=r.saveData,t.downlinkMbps=r.downlink)}catch{}return typeof e=="number"&&e>0&&(t.sourceLongEdge=e),it(t)}function st(e,t,n){let r=Math.min(1,Math.max(0,(e-.28)/.21999999999999997)),i=(t+n)/2;return Math.max(t,n-r*(n-i))}function ut(e,t,n){let r=Math.max(e,t),i=r>0?Math.min(1,n/r):1;return{width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(t*i))}}async function ct(e,t){let n=t.startQ,r=await e(n);for(let i=0;i<4&&!(r.size<=t.budgetBytes||n<=t.qMin);i++)n=Math.max(t.qMin,n-.08),r=await e(n);return{blob:r,quality:n}}async function Be(e,t,n,r,i){if(t<=0||n<=0)return null;let{width:c,height:u}=ut(t,n,r.maxLongEdge),s=document.createElement("canvas");s.width=c,s.height=u;let p=s.getContext("2d");if(!p)return null;p.drawImage(e,0,0,c,u);let d=k=>new Promise((S,x)=>{s.toBlob(l=>l?S(l):x(new Error("canvas toBlob returned null")),"image/jpeg",k)}),M=st(i,r.qMin,r.qMax),{blob:f,quality:_}=await ct(d,{startQ:M,qMin:r.qMin,budgetBytes:r.payloadTargetBytes}).finally(()=>{s.width=0,s.height=0});if(f.size>5242880)throw new Error("encoded document exceeds the 5242880-byte media cap");return{blob:f,quality:_,width:c,height:u}}async function oe(e){let t=Ae(Math.max(e.width,e.height)),n=await Be(e,e.width,e.height,t,.5);if(n===null)throw new Error("canvas encode unavailable");return{blob:n.blob,width:n.width,height:n.height}}async function Et(e){let t=await createImageBitmap(e);try{return await oe(t)}finally{t.close()}}var At=250,Bt=.6,It=1800,Ft=6e3,Wt=2e3,Ie=.16;function ie(e,t){return{layout:e,phase:"framing",captured:{},pending:[],lastCaptureAt:t,lastReportAt:t,manualShutter:!1,restPhase:"framing",readSides:[],needFlip:!1,flipped:!1,flipTimeoutSpent:!1,timeoutCapture:!1,lastShotByTimeout:!1}}var Fe=e=>e==="recto"?"verso":"recto",We=e=>e.phase==="framing"||e.phase==="locking"||e.phase==="flipCue"||e.phase==="reaskRecto",se=e=>(e.captured.recto!==void 0?1:0)+(e.captured.verso!==void 0?1:0)+e.pending.length;function ae(e,t){return e.lastCaptureAt>=0&&e.lastReportAt>=0?e:{...e,lastCaptureAt:e.lastCaptureAt<0?t:e.lastCaptureAt,lastReportAt:e.lastReportAt<0?t:e.lastReportAt}}function lt(e,t,n){if(e.phase==="result")return{...e,lastReportAt:n};let r=!t.present||e.captureArea!==void 0&&t.areaFrac<.6*e.captureArea,{flipped:i,awaySince:c}=e;r&&(c=c??n),c!==void 0&&n-c>=250&&(i=!0),r||(c=void 0);let u=e.flipTimeoutSpent&&!(i&&!e.flipped),s={...e,lastReportAt:n,flipped:i,awaySince:c,flipTimeoutSpent:u,lastArea:t.areaFrac};if(!We(e))return s;if(e.needFlip&&!i){if(!t.ready)return{...s,phase:e.restPhase,goodSince:void 0};let p=e.lastShot!==void 0&&e.pending.includes(e.lastShot);if(u||p)return{...s,goodSince:void 0,phase:e.restPhase};let d=e.goodSince??n;return n-d>=1800?{...s,goodSince:d,phase:"capturing",flipTimeoutSpent:!0,timeoutCapture:!0}:{...s,goodSince:d,phase:e.restPhase}}return t.ready?{...s,phase:"capturing",goodSince:e.goodSince??n}:{...s,goodSince:void 0,phase:t.locking?"locking":e.restPhase}}function dt(e,t){if(!We(e)||e.manualShutter)return e;let n=t-e.lastReportAt>=2e3,r=t-e.lastCaptureAt>=6e3;return n||r?{...e,manualShutter:!0}:e}function mt(e,t,n){let r=e.layout==="singlePage",i=r?{recto:t}:e.captured,c=r?[]:[...e.pending,t],u={...e,captured:i,pending:c,lastShot:t,lastCaptureAt:n,lastReportAt:-1,manualShutter:!1,goodSince:void 0,notice:void 0,awaySince:void 0,flipped:!1,lastShotByTimeout:e.timeoutCapture,timeoutCapture:!1,captureArea:e.lastArea};return r||se({captured:i,pending:c})>=2?{...u,phase:"reading",restPhase:"framing",current:void 0,needFlip:!1}:{...u,phase:"flipCue",restPhase:"flipCue",current:void 0,needFlip:!0}}function ze(e,t,n){return e.pending.includes(t)?{...e,pending:e.pending.filter(r=>r!==t),lastShot:e.lastShot===t?void 0:e.lastShot,phase:e.phase==="capturing"?e.phase:"flipCue",restPhase:"flipCue",current:Fe(n),needFlip:!0,flipTimeoutSpent:!0,goodSince:void 0,manualShutter:!0,notice:"same_face",lastCaptureAt:-1,lastReportAt:-1}:e}function pt(e,t,n){if(!e.pending.includes(t))return e;if(e.captured[n]!==void 0)return ze(e,t,n);let r=e.pending.filter(p=>p!==t),i={...e,pending:r,captured:{...e.captured,[n]:t}};if(se(i)!==1||e.layout==="singlePage")return i;let c=Fe(n),u=c==="recto"&&e.restPhase==="reaskRecto"?"reaskRecto":"flipCue",s=e.phase==="flipCue"||e.phase==="reaskRecto"||e.phase==="framing";return{...i,restPhase:u,current:c,phase:s?u:e.phase}}function ft(e,t){let n=t.id??e.captured[t.side],r={...e.captured};(t.id===void 0||r[t.side]===t.id)&&delete r[t.side];let i=e.pending.filter(d=>d!==n),c=e.layout==="twoSided"&&se({captured:r,pending:i})>0,u=e.lastShotByTimeout||n===e.lastShot!==e.flipped,s=c&&!u,p=s?t.side==="recto"?"reaskRecto":"flipCue":"framing";return{...e,captured:r,pending:i,readSides:e.readSides.filter(d=>d!==t.side),lastShot:e.lastShot===n?void 0:e.lastShot,notice:t.issue,goodSince:void 0,manualShutter:!1,phase:p,restPhase:p,current:t.side,needFlip:s,flipped:!1,flipTimeoutSpent:!1,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1}}function Ue(e,t){switch(t.type){case"report":return lt(ae(e,t.at),t.report,t.at);case"tick":return dt(ae(e,t.at),t.at);case"captured":return mt(ae(e,t.at),t.id,t.at);case"captureFailed":return{...e,phase:e.restPhase,goodSince:void 0,lastCaptureAt:t.at,manualShutter:!0,timeoutCapture:!1};case"classified":return pt(e,t.id,t.side);case"duplicate":return ze(e,t.id,t.side);case"readOk":{let n=e.readSides.includes(t.side)?e.readSides:[...e.readSides,t.side],r=["recto","verso"].filter(c=>e.captured[c]!==void 0),i=e.phase==="reading"&&e.pending.length===0&&r.every(c=>n.includes(c));return{...e,readSides:n,flipTimeoutSpent:!1,phase:i?"result":e.phase}}case"readFailed":return ft(e,t);case"clockRestart":return e.lastCaptureAt<0&&e.lastReportAt<0&&e.awaySince===void 0?e:{...e,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1};case"retake":return{...ie(e.layout,-1),lastCaptureAt:-1,lastReportAt:-1};default:return e}}function gt(e,t,n=!1){let r=e(t);return r===null?"recto":!n||r.y+r.height/2>=t.height/2?"verso":"recto"}async function ht(e,t=!1){let{detectMrzBand:n}=await import("./mrz-band-VYHOTDHY.js");return gt(n,e,t)}async function ue(e,t=480,n,r=n!=null){let i=n??{x:0,y:0,width:e.width,height:e.height},c=Math.max(1,Math.round(i.height/i.width*t)),u=document.createElement("canvas");u.width=t,u.height=c;try{let s=u.getContext("2d");return s===null?"recto":(s.drawImage(e,i.x,i.y,i.width,i.height,0,0,t,c),await ht(s.getImageData(0,0,t,c),r))}finally{u.width=0,u.height=0}}async function Ut(e,t=480){try{let n=await createImageBitmap(e),r=Math.max(1,Math.round(n.height/n.width*t)),i=document.createElement("canvas");i.width=t,i.height=r;let c=i.getContext("2d");return c===null?(n.close(),null):(c.drawImage(n,0,0,t,r),n.close(),c.getImageData(0,0,t,r))}catch{return null}}var ce=(e,t,n)=>Math.min(n,Math.max(t,Math.round(e))),$=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function Ne(e,t,n,r){let i=r.decode??(p=>createImageBitmap(p)),c=async()=>e.stillRead(await i(t),r.region??[0,0,1,1],r.detectorLimit),u;try{u=await c()}catch{try{await new Promise(p=>setTimeout(p,r.retryMs??300)),u=await c()}catch{return null}}let s=u.mrzBox;return s===void 0?null:{engine:r.engine,source:"live_mrz",format:n.format,lineCount:ce(n.lineCount,2,3),checkDigitsValid:!0,stillConfirmed:u.valid&&u.digest===n.digest,band:[$(s[0]),$(s[1]),$(Math.min(s[2],1-s[0])),$(Math.min(s[3],1-s[1]))],digest:n.digest,framesToValid:ce(n.framesToValid,1,1e3),msToValid:ce(n.msToValid,0,12e4)}}function Gt(e){let t=null;return e?.then(n=>{t=n}),()=>t}var bt=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]),yt=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,7,1,5,0,6,64,11,11]);function Ge(e,t=globalThis){let n=t.WebAssembly?.validate;if(typeof n!="function")return{ok:!1,reason:"simd"};try{if(!n.call(t.WebAssembly,bt)||!n.call(t.WebAssembly,yt))return{ok:!1,reason:"simd"}}catch{return{ok:!1,reason:"simd"}}if(typeof t.Worker!="function")return{ok:!1,reason:"worker"};if(typeof t.createImageBitmap!="function")return{ok:!1,reason:"bitmap"};let r=t.navigator?.deviceMemory;return typeof r=="number"&&r<e.minDeviceMemoryGb?{ok:!1,reason:"memory"}:{ok:!0}}function qe(e=globalThis){let t=e.navigator?.connection;return t?.saveData===!0||["slow-2g","2g","3g"].includes(t?.effectiveType??"")}var E=class extends Error{constructor(t){super(t),this.name="OcrEngineError",this.code=t}};function He(){let e=t=>(t.close(),Promise.reject(new E("unsupported")));return{ready:Promise.resolve("unsupported"),busy:!1,bandRead:e,stillRead:e,layoutRead:e,dispose:()=>{}}}function Xe(e){let t;try{if(e.createWorker)t=e.createWorker();else if(e.workerUrl!==void 0)t=new Worker(e.workerUrl,{type:"module",name:"sekyro-ocr"});else return He()}catch{return He()}let n=new Map,r=0,i=!1,c=!1,u=!1;t.addEventListener("message",l=>{let h=l.data,R=n.get(h.id);R&&(n.delete(h.id),R.resolve(h))});let s=()=>{for(let l of n.values())l.reject(new E("error"));n.clear(),d()};t.addEventListener("error",s),t.addEventListener("messageerror",s);function p(l,h=[]){if(i)return Promise.reject(new E("disposed"));let R=++r;return new Promise((B,A)=>{n.set(R,{resolve:B,reject:A});try{t.postMessage({...l,id:R},h)}catch{n.delete(R),A(new E("error"))}})}function d(){if(!i){i=!0;try{t.postMessage({id:++r,kind:"dispose"})}catch{}t.terminate();for(let l of n.values())l.reject(new E("disposed"));n.clear()}}let M=(async()=>{let l=await p({kind:"init",baseUrl:e.baseUrl,salt:e.salt,detectorLimit:e.tuning.detectorLimit,maxDownloadMs:e.tuning.maxDownloadMs});if(l.kind==="failed")return l.reason;if(l.kind!=="ready")return"error";let h=await p({kind:"warmup"});return h.kind!=="ready"?"error":{warmupMs:h.warmupMs,downloadMs:l.downloadMs,cached:l.cached}})().catch(()=>"error"),f,_=new Promise(l=>{f=setTimeout(()=>l("timeout"),e.tuning.loadTimeoutMs)}),k=Promise.race([M,_]).then(l=>(clearTimeout(f),typeof l=="string"?d():u=!0,i&&typeof l!="string"?"error":l));(e.page===void 0?globalThis.addEventListener?globalThis:null:e.page)?.addEventListener("pagehide",d,{once:!0});async function x(l,h,R){if(i)throw h.close(),new E("disposed");if(!u)throw h.close(),new E("not_ready");if(c)throw h.close(),new E("busy");c=!0;let B;try{let A=new Promise((X,W)=>{B=setTimeout(()=>{W(new E("timeout")),d()},e.tuning.readTimeoutMs??1e4)}),O=await Promise.race([p(l,[h]),A]);if(O.kind===R){let{id:X,...W}=O;return W}throw new E(O.kind==="error"?O.code:O.kind==="failed"?O.reason:"error")}finally{clearTimeout(B),c=!1}}return{ready:k,get busy(){return c},bandRead:(l,h=e.tuning.detectorLimit)=>x({kind:"band",bitmap:l,detectorLimit:h},l,"band"),stillRead:(l,h,R=e.tuning.detectorLimit)=>x({kind:"still",bitmap:l,region:h,detectorLimit:R},l,"band"),layoutRead:(l,h)=>x({kind:"layout",bitmap:l,detectorLimit:h},l,"layout"),dispose:d}}var H="sekyro-ocr-1",le=e=>e!==null&&typeof e=="object"?e:{},T=(e,t,n,r)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:r,Ye=(e,t)=>typeof e=="boolean"?e:t,Ve=e=>{let t=typeof e=="string"?/^sekyro-ocr-(\d{1,4})$/.exec(e):null;return t?Number(t[1]):Number.POSITIVE_INFINITY};function Qe(e,t={}){let n=le(e),r=le(n.liveMrz),i=le(n.frontLock),c=Ve(t.engine??H),u=t.mode==="off",s=l=>l.enabled===!0?l.arm==="live"?"live":"control":null,p=s(r),d=s(i),M=(l,h)=>!u&&h==="live"&&Ve(l.minEngine??H)<=c,f=Le,_=M(r,p)?{detectorLimit:T(r.detectorLimit,320,1600,f.detectorLimit),bandMaxWidthPx:T(r.bandMaxWidthPx,320,4096,f.bandMaxWidthPx),minBandWidthPx:T(r.minBandWidthPx,0,4096,f.minBandWidthPx),bandTop:T(r.bandTop,0,.95,f.bandTop),minIntervalMs:T(r.minIntervalMs,0,5e3,f.minIntervalMs),stableReads:Math.round(T(r.stableReads,1,10,f.stableReads)),profileReads:Math.round(T(r.profileReads,1,100,f.profileReads)),maxReadMs:T(r.maxReadMs,50,6e4,f.maxReadMs),searchTimeoutMs:T(r.searchTimeoutMs,1e3,12e4,f.searchTimeoutMs),hint:Ye(r.hint,!0),stillConfirm:Ye(r.stillConfirm,!0)}:null,k=ve,S=(l,h,R)=>T(i[l],h,R,k[l]),x=M(i,d)?{minLines:Math.round(S("minLines",1,50)),fillMin:S("fillMin",0,1),fillMax:S("fillMax",0,2),offsetMax:S("offsetMax",0,1),steadyFillDelta:S("steadyFillDelta",0,1),steadyOffsetDelta:S("steadyOffsetDelta",0,1),layoutShiftMax:S("layoutShiftMax",0,1),lineCountDelta:Math.round(S("lineCountDelta",0,50)),lockMs:S("lockMs",0,3e4),steadyMs:S("steadyMs",0,3e4),minFrames:Math.round(S("minFrames",1,100)),minIntervalMs:S("minIntervalMs",0,5e3),maxWidthPx:S("maxWidthPx",160,2048),detectorLimit:S("detectorLimit",320,1600),searchTimeoutMs:S("searchTimeoutMs",1e3,12e4)}:null;return{enabled:_!==null||x!==null,liveMrz:_,textLock:x,liveMrzArm:p,frontLockArm:d,load:{detectorLimit:_?.detectorLimit??x?.detectorLimit??f.detectorLimit,loadTimeoutMs:T(r.loadTimeoutMs,1e3,12e4,2e4),maxDownloadMs:T(r.maxDownloadMs,1e3,12e4,2e4),minDeviceMemoryGb:T(r.minDeviceMemoryGb,0,64,2)},reportSampleRate:T(r.reportSampleRate,0,1,1)}}function Ke(e,t){return e.enabled?!(t.probe??Ge)({minDeviceMemoryGb:e.load.minDeviceMemoryGb}).ok||(t.slow??qe)()?{ok:!1,reason:"unsupported"}:{ok:!0,engine:Xe({baseUrl:t.baseUrl,salt:t.salt,tuning:{detectorLimit:e.load.detectorLimit,maxDownloadMs:e.load.maxDownloadMs,loadTimeoutMs:e.load.loadTimeoutMs},...t.workerUrl!==void 0?{workerUrl:t.workerUrl}:{},...t.createWorker!==void 0?{createWorker:t.createWorker}:{},...t.page!==void 0?{page:t.page}:{}})}:{ok:!1,reason:"off"}}function St(e=typeof navigator<"u"?navigator.userAgent:""){return/SamsungBrowser\//.test(e)?"samsung":/Firefox\/|FxiOS\//.test(e)?"firefox":/Chrome\/|CriOS\/|Chromium\//.test(e)&&!/Edg\/|OPR\//.test(e)?"chrome":/Safari\//.test(e)&&/Version\/|Mobile\//.test(e)&&!/Chrome\/|CriOS\//.test(e)?"safari":"other"}var F=e=>e===void 0||!Number.isFinite(e)?void 0:Math.min(6e5,Math.max(0,Math.round(e))),de=(e,t,n)=>e===void 0||!Number.isFinite(e)?void 0:Math.min(n,Math.max(t,Math.round(e)));function je(e){let t=e.assist??null,n=e.load!==null&&e.load!==void 0&&typeof e.load=="object"?e.load:null,r=typeof e.load=="string"?e.load:null,i=t!==null?t.outcome:r==="unsupported"||r==="download"||r==="integrity"?r:r==="error"||r==="timeout"?"error":"off",c={kind:"live_mrz",platform:"web",engine:e.engine??H,arm:e.arm,capture:e.capture,outcome:i,reads:de(t?.reads??0,0,1e4)??0,browser:e.browser??St()},u=(s,p)=>{p!==void 0&&(c[s]=p)};return u("format",t?.format),u("framesToValid",de(t?.framesToValid,1,1e4)),u("msToValid",F(t?.msToValid)),u("framesToLock",de(t?.framesToLock,1,1e4)),u("msToLock",F(t?.msToLock)),u("msToCapture",F(e.msToCapture)),u("readP50Ms",F(t?.readP50Ms)),u("readP90Ms",F(t?.readP90Ms)),u("deviceClass",t?.deviceClass),n!==null&&(u("warmupMs",F(n.warmupMs)),u("downloadMs",F(n.downloadMs)),u("cached",n.cached)),u("stillConfirmed",e.stillConfirmed),u("typeMismatch",e.typeMismatch),c}function me(e,t){return e===void 0?!1:t==="passport"?e!=="TD3":e==="TD3"}var Mt=2;async function Dt(e){let t=await import("./capture-session-doc-ESEZJBQM.js");return new t.CaptureSessionDoc(e)}function wt(e){return{topLeft:{x:e.x,y:e.y},topRight:{x:e.x+e.width,y:e.y},bottomRight:{x:e.x+e.width,y:e.y+e.height},bottomLeft:{x:e.x,y:e.y+e.height}}}function kt(e,t,n){let r=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let c=0;c<r.length;c+=1){let u=r[c],s=r[(c+1)%r.length];i+=u.x*s.y-s.x*u.y}return t>0&&n>0?Math.abs(i)/2/(t*n):0}function ln(){import("./capture-session-doc-ESEZJBQM.js").then(e=>e.warmDocDetector()).catch(()=>{})}function dn(e){return Ct(e,{}).handle}function Ct(e,t){let n=we(),r=ke({enabled:e.keepScreenAwake!==!1}),i=t.decode??(o=>createImageBitmap(o)),c=t.blurRefuseSharpnessMax??.16,u=t.now??(()=>performance.now()),s=Pe(e.documentType,t.catalogCapture===!0?Ee(e.issuer,e.documentType):[]),p=s.sides.length===1||e.side==="single",d=ie(p?"singlePage":"twoSided",u());if(!p&&(e.side==="recto"||e.side==="verso")){let o=e.side==="recto"?"verso":"recto";d={...d,captured:{[o]:"server"},readSides:[o],current:e.side,phase:"flipCue",restPhase:"flipCue"}}let M="idle",f=null,_=null,k=!0,S=0,x=0,l=!1,h=!1,R="",B=null,A,O=null,X=[],W=s.mrz==="none",$e=s.barcodeSide==="recto"||s.barcodeSide==="verso"?s.barcodeSide:null,N=W&&!p?t.barcode?.side??$e:null,pe=e.barcodeAssetBaseUrl??t.barcode?.assetBaseUrl,fe=null,ge=()=>N===null||pe===void 0||t.barcode?.seen!==void 0?Promise.resolve(null):(fe??(fe=import("./barcode-detect-C5IOXMKI.js").then(o=>o.loadBarcodeDetect(pe)).catch(()=>null)),fe),Je=async(o,a)=>{if(N===null)return null;let m=N==="recto"?"verso":"recto";try{let g=t.barcode?.seen;if(g!==void 0)return await g(o)?N:m;let[L,D]=await Promise.all([ge(),a()]);if(L===null||D===null)return null;let w=Math.min(1600,D.width),y=document.createElement("canvas");y.width=w,y.height=Math.max(1,Math.round(D.height/D.width*w));try{let b=y.getContext("2d");return b===null?null:(b.drawImage(D,0,0,y.width,y.height),await Oe(L,b.getImageData(0,0,y.width,y.height),N))}finally{y.width=0,y.height=0}}catch{return null}},C=t.webOcr!==void 0&&!W?Qe(t.webOcr.captureDocument,{mode:e.liveMrz?.mode??"auto"}):null,G=null,z=C===null||!C.enabled?"off":null,Y=null,V=null,he=new WeakMap,J="";if(C!==null&&C.enabled&&t.webOcr!==void 0){let o=t.webOcr,a=Ke(C,{baseUrl:e.liveMrz?.assetBaseUrl??o.baseUrl,salt:o.salt,...e.liveMrz?.workerUrl!==void 0?{workerUrl:e.liveMrz.workerUrl}:{},...o.createWorker!==void 0?{createWorker:o.createWorker}:{}});if(a.ok){G=a.engine;let m=new Te({textLock:C.textLock,liveMrz:C.liveMrz});Y=m;let g=a.engine;g.ready.then(L=>{z=L,typeof L!="string"&&k&&m.setEngine(g)})}else z=a.reason}let U=o=>{let a=JSON.stringify(o);a!==J&&(J=a,n.emit("mrz",o))},be=(o,a)=>{let m=t.webOcr?.reports;if(m===void 0||C===null||o===void 0)return;let g=o.format==="ID-3"||o.side==="single"?"single":o.side==="verso"?"verso":"recto",L=g!=="recto"?C.liveMrzArm??C.frontLockArm:C.frontLockArm;if(L===null||Math.random()>=C.reportSampleRate)return;let D=o.via==="live_mrz"?V:null,w=()=>{let y=D?.value??null;m([je({arm:L,capture:g,assist:o.ocr??null,load:L==="control"?"off":z,...o.msToCapture!==void 0?{msToCapture:o.msToCapture}:{},...y!==null&&y.stillConfirmed!==void 0?{stillConfirmed:y.stillConfirmed}:{},...a!==void 0?{typeMismatch:me(a.format,s.format==="ID-3"?"passport":"card")}:{}})])};D!==null&&D.value===null?Promise.race([D.promise,new Promise(y=>setTimeout(y,3e3))]).then(w):w()},I=o=>{!k||o===M||(M=o,r.setActive(o==="starting"||o==="scanning"),n.emit("state",o))},Ze=(o,a)=>a===void 0?null:p?"single":o.captured.recto===a?"recto":o.captured.verso===a?"verso":null,et=o=>({phase:o.phase,captured:p?o.captured.recto!==void 0?["single"]:[]:["recto","verso"].filter(a=>o.captured[a]!==void 0),expected:p?null:o.current??null,notice:o.notice??null,lastShot:Ze(o,o.lastShot),manualShutter:o.manualShutter,torchAvailable:f?.torchAvailable()??!1,torch:h}),ye=()=>{let o=f;o!==null&&o.captureNow().catch(()=>v({type:"captureFailed",at:u()}))};function v(o){if(!k)return;let a=d;d=Ue(d,o),d.phase==="capturing"&&a.phase!=="capturing"&&Promise.resolve().then(ye),d.phase==="result"&&a.phase!=="result"&&(I("done"),Se());let m=et(d),g=JSON.stringify(m);g!==R&&(R=g,n.emit("scan",m))}function Se(){O!==null&&clearInterval(O),O=null;for(let o of X.splice(0))o();f?.destroy(),f=null,r.setActive(!1)}let Me=()=>f?.captureReport?.(),Z=!1,De=(o,a)=>{if(!(o===void 0||t.onFaceReport===void 0))try{t.onFaceReport(o,a)}catch{}},Q=o=>{J="",!(f===null||d.phase==="reading"||d.phase==="result")&&(Z=!1,f.rearm(p?"single":d.current??o))},tt=async(o,a,m,g)=>{if(V=null,g!==void 0&&G!==null&&C?.liveMrz?.hint===!0){let b={promise:Ne(G,o,g,{engine:H,detectorLimit:C.liveMrz.detectorLimit}).catch(()=>null),value:null};b.promise.then(P=>{b.value=P}),V=b}g!==void 0&&me(g.format,s.format==="ID-3"?"passport":"card")&&U({state:"mismatch",format:g.format});let L=Me();De(L,"captured"),Z=!0,be(L,g);let D=m===void 0?B:m===null?null:{quad:wt(m),frameWidth:0,frameHeight:0,inStill:!0},w={decoded:null},y=()=>(w.decoded??(w.decoded=Promise.resolve().then(()=>i(o)).catch(()=>null)),w.decoded);try{await nt(o,a,D,y,V)}finally{w.decoded!==null&&(await w.decoded)?.close()}},nt=async(o,a,m,g,L)=>{let D=`shot-${S+=1}`;if(v({type:"captured",id:D,at:u()}),e.haptics!==!1)try{globalThis.navigator?.vibrate?.(30)}catch{}if(!l&&c>0){let b=await(t.measureSharpness!==void 0?t.measureSharpness(o,m):g().then(P=>P===null?-1:Re(P,re(m?.quad??null,m?.inStill===!0?P:{width:m?.frameWidth??0,height:m?.frameHeight??0},P)))).catch(()=>-1);if(!k)return;if(Number.isFinite(b)&&b>=0&&b<c){l=!0;let P=p?"recto":d.current??(d.captured.recto===void 0?"recto":"verso");v({type:"readFailed",side:P,id:D,issue:"blurry"}),Q(P);return}}l=!1;let w;if(p)w="single";else{let b=d.current,q=(t.classify===void 0?await Je(o,g):null)??await(t.classify!==void 0?t.classify(o):g().then(K=>K===null?b??"recto":m?.inStill===!0?ue(K,480,null,!0):ue(K,480,re(m?.quad??null,{width:m?.frameWidth??0,height:m?.frameHeight??0},K)))).catch(()=>b??"recto");if(!k)return;if(d.captured[q]!==void 0&&x<Mt){x+=1,v({type:"duplicate",id:D,side:q}),Q(q==="recto"?"verso":"recto");return}w=d.captured[q]!==void 0&&b!==void 0?b:q,x=0,v({type:"classified",id:D,side:w})}let y=w==="verso"?"verso":"recto";try{let b=t.encode!==void 0?await t.encode(o):await g().then(P=>{if(P===null)throw new Error("the still could not be decoded");return oe(P)});if(!k)return;L!==null&&he.set(b.blob,L),n.emit("captured",{image:b.blob,side:w,documentType:e.documentType,...e.issuer!==void 0?{issuer:e.issuer}:{},width:b.width,height:b.height,previewDataUrl:a}),t.deferRead!==!0&&v({type:"readOk",side:y})}catch(b){v({type:"readFailed",side:y,id:D,issue:"technical"}),n.emit("error",j("generic",!0,{phase:"keyframes",name:te(b)}))}Q(y==="recto"?"verso":"recto")},rt=o=>{X.push(o.on("statechange",({state:a})=>{a==="preflight"||a==="acquiring"?I("starting"):a==="positioning"?I("scanning"):a==="captured"?I("captured"):a==="error"&&I("error")}),o.on("feedback",({key:a,reticle:m})=>n.emit("feedback",{key:a,reticle:m})),o.on("checks",a=>{n.emit("gate",{progress:a.p,quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight,...a.guide!==void 0?{guide:{detected:a.guide.detected,fill:a.guide.fill,offsetX:a.guide.offsetX??0,offsetY:a.guide.offsetY??0}}:{}});let m=a.ocr?.mrz;m!==void 0&&(m.state==="fallback"?U({state:"fallback",reason:m.reason}):m.state==="valid"?U({state:"valid",format:m.format}):m.state==="reading"?U({state:"reading",...m.format?{format:m.format}:{},...m.coach?{coach:m.coach}:{}}):U({state:"searching"}));let g=a.quad===null?0:kt(a.quad,a.frameWidth,a.frameHeight);B=a.quad===null?null:{quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight},v({type:"report",report:{present:a.quad!==null&&a.plausible||a.guide?.detected===!0,ready:a.ready===!0,locking:a.p>=.5,areaFrac:g},at:u()})}),o.on("error",({kind:a,retryable:m,detail:g})=>n.emit("error",j(a,m,g))),o.on("artifacts",a=>{tt(a.keyframe,a.previewDataUrl,a.docRegion,a.liveMrz)}))},ee=()=>(_??(_=(async()=>{if(k){if(ge(),f===null){let o;try{o=await(t.createEngine??Dt)({...t.engineOptions??{},...A!==void 0?{guide:A}:{},video:e.video,format:s.format,side:p?"single":e.side??"recto",autoCapture:!1,...Y!==null?{ocr:Y}:{}})}catch(m){I("error"),n.emit("error",j("models",!0,{phase:"models",name:te(m)}));return}if(!k){o.destroy();return}f=o,rt(o);let a=t.tickMs??500;a>0&&(O=setInterval(()=>v({type:"tick",at:u()}),a))}v({type:"clockRestart"}),C!==null&&C.liveMrzArm==="live"&&(z==="unsupported"||z==="off")&&U({state:"fallback",reason:z}),await f.start()}})().finally(()=>{_=null})),_);return{handle:{get state(){return M},on:(o,a)=>n.on(o,a),start:ee,retry:()=>{if(f===null&&d.phase==="result"){v({type:"retake"}),x=0,l=!1,ee();return}if(f!==null&&M!=="error"){v({type:"retake"}),x=0,l=!1,f.rearm(p?"single":void 0);return}ee()},setSide:o=>{p||o==="single"||(d.current!==o&&(d={...d,current:o}),v({type:"clockRestart"}),d.phase!=="reading"&&d.phase!=="result"&&f?.rearm(o))},shutter:ye,focusAt:(o,a)=>{f?.focusAt?.(o,a)},setGuide:o=>{A=o,f?.setGuide?.(o)},setTorch:o=>{h=o,f?.setTorch(o),v({type:"tick",at:u()})},destroy:()=>{if(k&&f!==null&&M!=="done"){let o=Me();!Z&&o!==void 0&&o.ticks>0&&De(o,"abandoned"),be(o,void 0)}k=!1,Se(),Y?.setEngine(null),G?.dispose(),G=null,n.clear()}},setFlowState:o=>{(d.phase==="reading"||d.phase==="result")&&I(o==="done"&&d.phase!=="result"?"scanning":o)},settle:(o,a)=>{let m=o==="verso"?"verso":"recto";v(a.ok?{type:"readOk",side:m}:{type:"readFailed",side:m,issue:a.issue}),a.ok||Q(m)},takeDeviceRead:o=>he.get(o.image)?.value??null}}export{Et as a,At as b,Bt as c,It as d,Ft as e,Wt as f,Ie as g,ie as h,Ue as i,gt as j,ht as k,Ut as l,Ne as m,Gt as n,H as o,Qe as p,Ke as q,St as r,je as s,me as t,Mt as u,ln as v,dn as w,Ct as x};
@@ -1 +1 @@
1
- import{c as P,d as H,e as A}from"./chunk-6AH7FXVC.js";var z=new Set(["nni_unbound","id_number_unbound","method_required","mobile_required","portrait_required"]);function Ce(e){return z.has(e)}function be(e,n,t){let i=n.detail;return{check:e,kind:n.kind,...i?.name!==void 0?{name:i.name}:{},...i?.phase!==void 0?{phase:i.phase}:{},...i?.engineKind!==void 0?{engineKind:i.engineKind}:{},attempt:Math.max(0,Math.min(1e3,t))}}function ve(){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 xe(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 g(e){return e!==void 0&&(e.state==="pending"||e.state==="input_required")}function T(e){return e.status!=="created"&&e.status!=="in_progress"}function V(e){let n=e.plan?.current,t=n==null?void 0:f(e).find(i=>i.id===n);return g(t)?t:void 0}function _(e,n){return f(e).find(t=>t.checkType===n)}function y(e){let n=f(e),t=n.findIndex(i=>i.checkType==="liveness");return n.find((i,r)=>r>t&&i.checkType==="face_match")}function O(e,n){let t=_(n,"liveness")?.state,i=y(n)?.state;return(y(e)?.state??"pending")==="pending"&&(t==="passed"||t==="review")&&i!==void 0&&i!=="pending"&&i!=="skipped"}function M(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 C(e,n){let t=R(e);return n===void 0?{sessionId:t,status:"unavailable"}:{sessionId:t,status:"unavailable",reasonCode:n}}function F(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,F(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 C(t,"mobile_required");if(i?.reason!==void 0){if(i.result==="unavailable")return C(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=V(e);return r===void 0&&f(e).some(o=>o.state==="review")?F(t,"review",L(e,"review")):r?.checkType==="portrait_icao"?C(t,"portrait_required"):C(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"]),w=class extends Error{constructor(){super("verification destroyed"),this.name="FlowCancelledError"}};function me(e){let n=y(e);return _(e,"portrait_icao")?.state!=="pending"&&(n!==void 0?g(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,l=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"&&l<de){l+=1;let a=H(s.retryAfterSeconds,ce,e.random??Math.random);e.onBusy?.({attempt:l,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 Te(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=Se(e,t,i,r),u=ye(e,r),l=!1,s=new Set,a=!0,k=0;for(;;){if(e.isCancelled())return{kind:"cancelled"};let p=e.getView();if(T(p))return{kind:"settled"};let d=V(p),S=d?.checkType,v=S==="liveness"&&!l?"liveness":S==="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"){l=!0;let c=await o();if(e.isCancelled())return{kind:"cancelled"};O(p,c)&&s.add(y(c)?.id);for(let Y of M(p,c))s.add(Y);await e.applySubmit(c,"liveness");let m=_(e.getView(),"liveness")?.state;a=m===void 0||he.has(m)}else{s.add(d?.id);let c=await u();if(e.isCancelled())return{kind:"cancelled"};for(let m of M(p,c))s.add(m);await e.applySubmit(c,"face_match")}}catch(c){if(e.isCancelled()||c instanceof w)return{kind:"cancelled"};let m=we(c);if(m.kind!=="resync"||k>=le)return m;k+=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 Se(e,n,t,i){let r=null,o,u=null,l=0,s;return()=>D(e,async(a,k)=>{if(r===null||o===void 0){if(e.isCancelled())throw new w;o===void 0&&!me(e.getView())&&(o=null),e.onPhase("uploading");let[p,d]=await Promise.all([r!==null?Promise.resolve(r):(async()=>{let S=await K(a,"clip",t,n.size,q(e.artifacts));return await a.uploadToSpaces(S.uploadUrl,n,t),(await a.completeMedia(S.key)).key})(),o!==void 0?Promise.resolve(o===null?null:o.imageKey):i.attempt()]);r=p,o===void 0&&(o=d===null?null:{imageKey:d})}if(u===null){let p=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))}l=Math.round(performance.now()-p)}return e.onPhase("checking"),a.submitCheck("liveness",{clipKey:r,attestation:u,captureChannel:e.artifacts.captureChannel,capture:{...ge(e.artifacts),attestationMs:l,attestationError:s},...o!==null?{faceMatch:o}:{}},{idempotencyKey:k})},{onAttestationInvalid:()=>{u=null}})}function ye(e,n){return()=>D(e,async(t,i)=>{if(n.current()===null){if(e.isCancelled())throw new w;e.onPhase("uploading")}let r=await n.ensure();return e.onPhase("checking"),t.submitCheck("face_match",{imageKey:r},{idempotencyKey:i})})}function ge(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 we(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 Fe="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 qe(e,n){if(n===void 0||!g(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 ke(e){let n=e?.capture,t=n?.mode;return t==="assisted"||t==="self"||t==="choice"?t:n?.cameraSwitch===!0?"assisted":"self"}function Ue(e){let n=e?.capture?.pick;return ke(e)==="choice"&&(n==="self"||n==="assisted")?n:null}function Be(e,n,t=null){return e==="choice"?n??t??"self":e}var Ye={"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{Ce as a,be as b,ve as c,j as d,f as e,x as f,W as g,xe as h,g as i,T as j,V as k,_ as l,R as m,C as n,Ve as o,Q as p,qe as q,ke as r,Ue as s,Be 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,Te as D,ge as E,Fe as F,U as G,Ye as H,B as I,$ as J};
1
+ import{c as P,d as H,e as A}from"./chunk-ODI4A5K4.js";var z=new Set(["nni_unbound","id_number_unbound","method_required","mobile_required","portrait_required"]);function Ce(e){return z.has(e)}function be(e,n,t){let i=n.detail;return{check:e,kind:n.kind,...i?.name!==void 0?{name:i.name}:{},...i?.phase!==void 0?{phase:i.phase}:{},...i?.engineKind!==void 0?{engineKind:i.engineKind}:{},attempt:Math.max(0,Math.min(1e3,t))}}function ve(){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 xe(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 g(e){return e!==void 0&&(e.state==="pending"||e.state==="input_required")}function T(e){return e.status!=="created"&&e.status!=="in_progress"}function V(e){let n=e.plan?.current,t=n==null?void 0:f(e).find(i=>i.id===n);return g(t)?t:void 0}function _(e,n){return f(e).find(t=>t.checkType===n)}function y(e){let n=f(e),t=n.findIndex(i=>i.checkType==="liveness");return n.find((i,r)=>r>t&&i.checkType==="face_match")}function O(e,n){let t=_(n,"liveness")?.state,i=y(n)?.state;return(y(e)?.state??"pending")==="pending"&&(t==="passed"||t==="review")&&i!==void 0&&i!=="pending"&&i!=="skipped"}function M(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 C(e,n){let t=R(e);return n===void 0?{sessionId:t,status:"unavailable"}:{sessionId:t,status:"unavailable",reasonCode:n}}function F(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,F(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 C(t,"mobile_required");if(i?.reason!==void 0){if(i.result==="unavailable")return C(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=V(e);return r===void 0&&f(e).some(o=>o.state==="review")?F(t,"review",L(e,"review")):r?.checkType==="portrait_icao"?C(t,"portrait_required"):C(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"]),w=class extends Error{constructor(){super("verification destroyed"),this.name="FlowCancelledError"}};function me(e){let n=y(e);return _(e,"portrait_icao")?.state!=="pending"&&(n!==void 0?g(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,l=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"&&l<de){l+=1;let a=H(s.retryAfterSeconds,ce,e.random??Math.random);e.onBusy?.({attempt:l,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 Te(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=Se(e,t,i,r),u=ye(e,r),l=!1,s=new Set,a=!0,k=0;for(;;){if(e.isCancelled())return{kind:"cancelled"};let p=e.getView();if(T(p))return{kind:"settled"};let d=V(p),S=d?.checkType,v=S==="liveness"&&!l?"liveness":S==="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"){l=!0;let c=await o();if(e.isCancelled())return{kind:"cancelled"};O(p,c)&&s.add(y(c)?.id);for(let Y of M(p,c))s.add(Y);await e.applySubmit(c,"liveness");let m=_(e.getView(),"liveness")?.state;a=m===void 0||he.has(m)}else{s.add(d?.id);let c=await u();if(e.isCancelled())return{kind:"cancelled"};for(let m of M(p,c))s.add(m);await e.applySubmit(c,"face_match")}}catch(c){if(e.isCancelled()||c instanceof w)return{kind:"cancelled"};let m=we(c);if(m.kind!=="resync"||k>=le)return m;k+=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 Se(e,n,t,i){let r=null,o,u=null,l=0,s;return()=>D(e,async(a,k)=>{if(r===null||o===void 0){if(e.isCancelled())throw new w;o===void 0&&!me(e.getView())&&(o=null),e.onPhase("uploading");let[p,d]=await Promise.all([r!==null?Promise.resolve(r):(async()=>{let S=await K(a,"clip",t,n.size,q(e.artifacts));return await a.uploadToSpaces(S.uploadUrl,n,t),(await a.completeMedia(S.key)).key})(),o!==void 0?Promise.resolve(o===null?null:o.imageKey):i.attempt()]);r=p,o===void 0&&(o=d===null?null:{imageKey:d})}if(u===null){let p=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))}l=Math.round(performance.now()-p)}return e.onPhase("checking"),a.submitCheck("liveness",{clipKey:r,attestation:u,captureChannel:e.artifacts.captureChannel,capture:{...ge(e.artifacts),attestationMs:l,attestationError:s},...o!==null?{faceMatch:o}:{}},{idempotencyKey:k})},{onAttestationInvalid:()=>{u=null}})}function ye(e,n){return()=>D(e,async(t,i)=>{if(n.current()===null){if(e.isCancelled())throw new w;e.onPhase("uploading")}let r=await n.ensure();return e.onPhase("checking"),t.submitCheck("face_match",{imageKey:r},{idempotencyKey:i})})}function ge(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 we(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 Fe="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 qe(e,n){if(n===void 0||!g(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 ke(e){let n=e?.capture,t=n?.mode;return t==="assisted"||t==="self"||t==="choice"?t:n?.cameraSwitch===!0?"assisted":"self"}function Ue(e){let n=e?.capture?.pick;return ke(e)==="choice"&&(n==="self"||n==="assisted")?n:null}function Be(e,n,t=null){return e==="choice"?n??t??"self":e}var Ye={"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{Ce as a,be as b,ve as c,j as d,f as e,x as f,W as g,xe as h,g as i,T as j,V as k,_ as l,R as m,C as n,Ve as o,Q as p,qe as q,ke as r,Ue as s,Be 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,Te as D,ge as E,Fe as F,U as G,Ye as H,B as I,$ as J};