@sekyro/web 0.1.0-rc.38 → 0.1.0-rc.39

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 (47) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/{capture-session-doc-MGDYUASI.js → capture-session-doc-J4MIDQOS.js} +1 -1
  3. package/dist/{capture-session-v3-Z2KI_2p9.d.ts → capture-session-v3-BnRN9WuV.d.ts} +1 -1
  4. package/dist/{capture-session-v3-Dz-AQW52.d.cts → capture-session-v3-DjWqEJG0.d.cts} +1 -1
  5. package/dist/chunk-26XZRWBD.js +3 -0
  6. package/dist/chunk-3565JBSZ.js +1 -0
  7. package/dist/{chunk-TOISWBOX.js → chunk-3WQJI7UL.js} +1 -1
  8. package/dist/{chunk-PBWIMNSN.js → chunk-7FGOUBAN.js} +1 -1
  9. package/dist/{chunk-5AR5GTEJ.js → chunk-BRLQIJYF.js} +1 -1
  10. package/dist/{chunk-COZXZAD5.js → chunk-HMOOVRKA.js} +1 -1
  11. package/dist/{chunk-QTOMWAS6.js → chunk-P5OIQXVM.js} +1 -1
  12. package/dist/{chunk-TQQK7464.js → chunk-PNOGF72U.js} +1 -1
  13. package/dist/{chunk-IAKYKPL6.js → chunk-TGSMTRG5.js} +1 -1
  14. package/dist/{chunk-VMHFHHPP.js → chunk-UKYJYZZS.js} +1 -1
  15. package/dist/{chunk-XDB7L5KS.js → chunk-WI7GAUCH.js} +1 -1
  16. package/dist/client/index.cjs +1 -1
  17. package/dist/client/index.d.cts +3 -3
  18. package/dist/client/index.d.ts +3 -3
  19. package/dist/client/index.js +1 -1
  20. package/dist/core/index.cjs +1 -1
  21. package/dist/core/index.d.cts +3 -3
  22. package/dist/core/index.d.ts +3 -3
  23. package/dist/core/index.js +1 -1
  24. package/dist/create-document-capture-SMEKDBGF.js +1 -0
  25. package/dist/{create-verification-BG6A2iyO.d.cts → create-verification-BSOb3N6w.d.cts} +27 -4
  26. package/dist/{create-verification-2Qm_K28Y.d.ts → create-verification-C6Hoh_0h.d.ts} +27 -4
  27. package/dist/{detector-scanic-JC25DD3A.js → detector-scanic-P2RTEQUV.js} +1 -1
  28. package/dist/{icao-gate-QqtNED0V.d.ts → icao-gate-Bux2CcJc.d.ts} +1 -1
  29. package/dist/{icao-gate-Dyb0wGO3.d.cts → icao-gate-C-fkVe6r.d.cts} +1 -1
  30. package/dist/{icao-policy-iIBtqhbf.d.cts → icao-policy-B_daycJk.d.cts} +2 -2
  31. package/dist/{icao-policy-DsaRylAQ.d.ts → icao-policy-C5XcEwqj.d.ts} +2 -2
  32. package/dist/index.cjs +2 -2
  33. package/dist/index.d.cts +7 -7
  34. package/dist/index.d.ts +7 -7
  35. package/dist/index.js +1 -1
  36. package/dist/internal/index.cjs +2 -2
  37. package/dist/internal/index.d.cts +6 -6
  38. package/dist/internal/index.d.ts +6 -6
  39. package/dist/internal/index.js +1 -1
  40. package/dist/{plan-runner-NWK4LZFI.js → plan-runner-ZVYJ3UI3.js} +1 -1
  41. package/dist/{types-Cy_SJtPf.d.cts → types-BUnFqG97.d.cts} +11 -1
  42. package/dist/{types-Cy_SJtPf.d.ts → types-BUnFqG97.d.ts} +11 -1
  43. package/package.json +1 -1
  44. package/sbom.cdx.json +19 -19
  45. package/dist/chunk-C4XDRRU5.js +0 -1
  46. package/dist/chunk-IOCOIZKE.js +0 -3
  47. package/dist/create-document-capture-KISF6XD3.js +0 -1
@@ -1 +1 @@
1
- var g="0.1.0-rc.38";var T=/FBAN|FBAV|FB_IAB|FBIOS|MessengerForiOS|Instagram|WhatsApp|musical_ly|BytedanceWebview|TikTok|Snapchat|\bLine\/|LinkedInApp|Pinterest|MicroMessenger|; wv\)/i;function p(t){let e=t??(typeof navigator>"u"?"":String(navigator.userAgent??""));return T.test(e)}var h="sekyro.did",P=1e4,v=()=>globalThis.process?.versions?.node,y;function b(){let t=globalThis.crypto;try{if(typeof t?.randomUUID=="function")return t.randomUUID()}catch{}try{if(typeof t?.getRandomValues=="function"){let e=t.getRandomValues(new Uint8Array(16));return Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}}catch{}}function I(){try{let t=localStorage.getItem(h);if(t)return t;let e=b();return e!==void 0&&localStorage.setItem(h,e),e}catch{return y??(y=b()),y}}async function w(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,r=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),i=await t.digest("SHA-256",new TextEncoder().encode(r));return Array.from(new Uint8Array(i),o=>o.toString(16).padStart(2,"0")).join("").slice(0,32)}function k(){try{let t=Number(navigator.maxTouchPoints);return Number.isFinite(t)&&t>=0?{touch:Math.min(64,Math.trunc(t))}:{}}catch{return{}}}function x(t){let e=new TextEncoder().encode(t),r="";for(let i of e)r+=String.fromCharCode(i);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function A(t){let e,r,i,o,a,l,u=()=>l?.readyState==="live",_=()=>{a!==void 0||!globalThis.crypto?.subtle||v()||u()||(a=Promise.race([import("./print-DCYX3CZD.js"),new Promise(n=>setTimeout(n,P))]).then(n=>n?.computePrint(u)).then(n=>{n==="busy"?a=void 0:o=n}).catch(()=>{}))};return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(n){n&&(e=n.slice(0,128))},noteCamera(n){r=n},noteCameraTrack(n){l=n},async deviceHeader(){try{i??(i=w().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let m=await i,f=I(),S={v:1,platform:"web",sdk:t.sdk.slice(0,64),caps:["session_proof"],rampAtArm:!0,ids:[...f?[{kind:"web_local",value:f.slice(0,128)}]:[],...m?[{kind:"web_fp",value:m}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...k(),...e?{cameraLabel:e}:{},...n.length?{signals:n}:{},...o?{print:{v:2,...o,...r?{camera:r}:{}}}:{},...p()?{inApp:!0}:{}},C=x(JSON.stringify(S));return _(),C}catch{return}},printReady(){return a??Promise.resolve()}}}var s=Symbol.for("sekyro.web.clientContext"),c=globalThis,d=c[s]??(c[s]=A({sdk:`@sekyro/web@${g}`}));function M(t){try{let e=t.getVideoTracks?.()[0];if(e){if(d.noteCameraLabel(e.label),d.noteCameraTrack(e),v())return;import("./camera-trait-DELAK3YN.js").then(r=>r.noteCameraTrait(e,d)).catch(()=>{})}}catch{}}export{g as a,p as b,d as c,M as d};
1
+ var g="0.1.0-rc.39";var T=/FBAN|FBAV|FB_IAB|FBIOS|MessengerForiOS|Instagram|WhatsApp|musical_ly|BytedanceWebview|TikTok|Snapchat|\bLine\/|LinkedInApp|Pinterest|MicroMessenger|; wv\)/i;function p(t){let e=t??(typeof navigator>"u"?"":String(navigator.userAgent??""));return T.test(e)}var h="sekyro.did",P=1e4,v=()=>globalThis.process?.versions?.node,y;function b(){let t=globalThis.crypto;try{if(typeof t?.randomUUID=="function")return t.randomUUID()}catch{}try{if(typeof t?.getRandomValues=="function"){let e=t.getRandomValues(new Uint8Array(16));return Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}}catch{}}function I(){try{let t=localStorage.getItem(h);if(t)return t;let e=b();return e!==void 0&&localStorage.setItem(h,e),e}catch{return y??(y=b()),y}}async function w(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,r=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),i=await t.digest("SHA-256",new TextEncoder().encode(r));return Array.from(new Uint8Array(i),o=>o.toString(16).padStart(2,"0")).join("").slice(0,32)}function k(){try{let t=Number(navigator.maxTouchPoints);return Number.isFinite(t)&&t>=0?{touch:Math.min(64,Math.trunc(t))}:{}}catch{return{}}}function x(t){let e=new TextEncoder().encode(t),r="";for(let i of e)r+=String.fromCharCode(i);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function A(t){let e,r,i,o,a,l,u=()=>l?.readyState==="live",_=()=>{a!==void 0||!globalThis.crypto?.subtle||v()||u()||(a=Promise.race([import("./print-DCYX3CZD.js"),new Promise(n=>setTimeout(n,P))]).then(n=>n?.computePrint(u)).then(n=>{n==="busy"?a=void 0:o=n}).catch(()=>{}))};return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(n){n&&(e=n.slice(0,128))},noteCamera(n){r=n},noteCameraTrack(n){l=n},async deviceHeader(){try{i??(i=w().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let m=await i,f=I(),S={v:1,platform:"web",sdk:t.sdk.slice(0,64),caps:["session_proof"],rampAtArm:!0,ids:[...f?[{kind:"web_local",value:f.slice(0,128)}]:[],...m?[{kind:"web_fp",value:m}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...k(),...e?{cameraLabel:e}:{},...n.length?{signals:n}:{},...o?{print:{v:2,...o,...r?{camera:r}:{}}}:{},...p()?{inApp:!0}:{}},C=x(JSON.stringify(S));return _(),C}catch{return}},printReady(){return a??Promise.resolve()}}}var s=Symbol.for("sekyro.web.clientContext"),c=globalThis,d=c[s]??(c[s]=A({sdk:`@sekyro/web@${g}`}));function M(t){try{let e=t.getVideoTracks?.()[0];if(e){if(d.noteCameraLabel(e.label),d.noteCameraTrack(e),v())return;import("./camera-trait-DELAK3YN.js").then(r=>r.noteCameraTrait(e,d)).catch(()=>{})}}catch{}}export{g as a,p as b,d as c,M as d};
@@ -1 +1 @@
1
- import{a as re,d as ne,e as B,f as se,g as oe}from"./chunk-7QZWBDI5.js";import{A as te,a as X}from"./chunk-PBWIMNSN.js";import{f as j,l as J}from"./chunk-CPUECYAJ.js";import{c as Z}from"./chunk-TSA6GHUG.js";import{c as ee,h as L}from"./chunk-FSSMUAKC.js";var ve=12e4,ie=13e4,ge=3e3,he=1200,D=Symbol.for("@sekyro/web.preload.v1");function h(){let e=globalThis;return e[D]??(e[D]=new Map),e[D]}function b(e){let r=(e??ee).replace(/\/+$/,"");return r===""?"/":r}function ae(e){let r=h(),n=r.get(e);return n===void 0&&(n={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},r.set(e,n)),n}function k(e,r){if(e.status!==r){e.status=r;for(let n of[...e.listeners])n(r)}}var K=e=>L({preferred:["blaze"],v3AssetBaseUrl:e,blazeInitTimeoutMs:ve}),H=K;function Te(e){H=e??K}function Oe(){for(let e of h().values())e.detector?.destroy();h().clear(),H=K}function Ce(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function Se(){return navigator.connection?.saveData===!0}function Ee(e){let r=window;if(typeof r.requestIdleCallback=="function"){let s=r.requestIdleCallback(e,{timeout:ge});return()=>r.cancelIdleCallback?.(s)}let n=setTimeout(e,he);return()=>clearTimeout(n)}function ye(e,r){let n,s=new Promise(d=>{n=d}),m=!1,u=()=>{},c={promise:s,settle:d=>{m||(m=!0,u(),e.scheduled===c&&(e.scheduled=null),n(d))}};return e.scheduled=c,u=Ee(()=>{m||c.settle(U(e,r))}),s}function U(e,r){if((e.status==="loading"||e.status==="ready")&&e.promise!==null)return e.promise;k(e,"loading");let n=new Promise(d=>d(H(r)));e.detectorPromise=n;let s,m=new Promise((d,f)=>{s=setTimeout(()=>{n.then(C=>C.destroy(),()=>{}),f(new Error(`detector preload exceeded ${ie} ms`))},ie)}),c=Promise.race([n,m]).then(d=>e.detectorPromise!==n?(d.destroy(),e.status):(e.detector=d,k(e,"ready"),"ready"),d=>(e.detectorPromise===n&&(e.detectorPromise=null,e.detector=null,k(e,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",d)),e.status)).finally(()=>clearTimeout(s));return e.promise=c,e.scheduled?.settle(c),c}function xe(e={}){if(!Ce())return Promise.resolve("idle");let r=b(e.assetBaseUrl),n=ae(r);return e.respectSaveData===!0&&Se()?Promise.resolve(n.status):(n.status==="loading"||n.status==="ready")&&n.promise!==null?n.promise:e.idle===!0?n.scheduled?.promise??ye(n,r):U(n,r)}function Fe(e){return h().get(b(e))?.status??"idle"}function Ie(e,r){let n=ae(b(r));return n.listeners.add(e),()=>{n.listeners.delete(e)}}function Be(e){let r=h().get(b(e));r!==void 0&&(r.scheduled?.settle("idle"),r.detector?.destroy(),r.detector=null,r.detectorPromise=null,r.promise=null,k(r,"idle"))}function Le(e){return{get tier(){return e.tier},get fallbackReason(){return e.fallbackReason},detect:(...r)=>e.detect(...r),destroy:()=>{}}}function de(e){let r=b(e),n=h().get(r);if(!(n===void 0||n.detector===null&&n.detectorPromise===null&&n.scheduled===null))return async()=>{n.scheduled!==null&&U(n,r);let s=n.promise;for(;n.detector===null&&s!==null&&(await s,n.promise!==s);)s=n.promise;return n.detector!==null?Le(n.detector):L({v3AssetBaseUrl:r})}}var be=new Set(["inuse","overconstrained","notfound"]),Me=[500,1500];function Ae(e){switch(e){case"fcv3.no_face":case"fcv3.center_face":case"fcv3.straighten":return"center";case"fcv3.come_closer":return"closer";case"fcv3.move_back":return"farther";case"fcv3.more_light":case"fcv3.too_bright":return"light";case"fcv3.hold_still":case"fcv3.steady_camera":return"still";case"fcv3.hold_upright":return"upright";case"fcv3.one_face":return"one_face";default:return null}}function Pe(e){switch(e){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";default:return e}}function ue(e){switch(e){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return e;case"backcamera":return"notfound";default:{let r=e;return"generic"}}}function we(e,r,n){if(n===void 0)return{kind:ue(e),retryable:r};let s=J(n.name);return{kind:ue(e),retryable:r,detail:{...s!==void 0?{name:s}:{},phase:n.phase,engineKind:e}}}var _e=new Set(["captured","uploading","checking"]);function De(e,r={},n,s=()=>"self",m=()=>{},u){let c=r.now??(()=>performance.now()),d=r.canChooseFacing??ne,f="user",C=se(),p=s(),l=re(),V=!j(),G=r.engineOptions,ce=G?.createDetector===void 0&&G?.createWorker===void 0?{createDetector:()=>{let t=de(e.assetBaseUrl);return t!==void 0?t():L({v3AssetBaseUrl:e.assetBaseUrl})}}:{},z={video:e.video,mode:V?"photo":"clip",rankKeyframes:n,facingMode:void 0,v3AssetBaseUrl:e.assetBaseUrl,screenRamp:()=>p==="self"&&l.count("ramp")>0?m():void 0,...r.engineOptions??{},...ce},a=r.createEngine?.(z)??new te(z),v="idle",M=null,A=0,R=!1,T="full",P=null,w=null,O=0,x=0,W=()=>{e.video.videoWidth>0&&e.video.videoHeight>0&&(O=e.video.videoWidth,x=e.video.videoHeight)},q=oe({enabled:e.keepScreenAwake!==!1}),S=t=>{v=t,q.setActive(t==="starting"||t==="gating"||t==="recording"),l.emit("state",t)},F=()=>l.emit("gate",{progress:A,hint:M,faceDetected:R}),I=()=>{let t=a.animations??"full";t!==T&&(T=t,l.emit("profile",{animations:T}))},g=0,_=null,le=r.schedule??((t,o)=>{let i=setTimeout(t,o);return()=>clearTimeout(i)}),E=()=>{_?.(),_=null},fe=(t,o)=>{if(y||!be.has(t)||o?.phase!=="acquiring")return!1;let i=Me[g];return i===void 0?!1:(g+=1,E(),_=le(()=>{_=null,y||a.retry()},i),!0)},pe=[a.on("statechange",({state:t})=>{if(t==="error")return;let o=Pe(t);o==="gating"&&(g=0),o==="starting"&&v!=="starting"&&(M=null,A=0,R=!1,P=null,w=null,O=0,x=0),S(o),I(),o==="recording"&&(W(),P=c(),M="hold",A=1,F())}),a.on("checks",t=>{W(),A=t.progress,R=t.factors.presence>0,F(),I()}),a.on("guidance",({key:t})=>{M=Ae(t),F()}),a.on("frozen",({previewDataUrl:t})=>{w=c(),l.emit("frozen",{previewDataUrl:t})}),a.on("ramp",t=>l.emit("ramp",t)),a.on("artifacts",t=>{if(v!=="captured")return;let o=Z(),i=t.clipStats,Q=i!==void 0?Math.round(i.durationMs):P!==null&&w!==null?Math.max(0,Math.round(w-P)):void 0,Y=i!==void 0&&i.frames>1&&i.durationMs>0?Math.round(i.frames*1e4/i.durationMs)/10:void 0;l.emit("captured",{keyframe:t.keyframe,...t.clip!==void 0?{clip:t.clip}:{},...t.clipMimeType!==void 0?{clipMime:t.clipMimeType}:{},width:e.video.videoWidth||O,height:e.video.videoHeight||x,...Q!==void 0?{clipMs:Q}:{},...i!==void 0?{clipFrames:i.frames}:{},...Y!==void 0?{fps:Y}:{},...t.clipRetakes!==void 0?{clipRetakes:t.clipRetakes}:{},...t.clipMimeType!==void 0?{codec:X(t.clipMimeType)}:{},captureChannel:o==="desktop"?"desktop":"mobile",formFactor:o,...V?{degraded:"NO_RECORDER"}:{},engine:"v3",facingMode:a.facingMode,mode:p,...t.timing,...t.screenRamp!==void 0?{screenRamp:t.screenRamp}:{},...t.provenance!==void 0?{provenance:t.provenance}:{}})}),a.on("error",({kind:t,retryable:o,detail:i})=>{t==="backcamera"&&me()||fe(t,i)||(S("error"),I(),l.emit("error",we(t,o,i)))})],N=!1;function me(){return y||N||p!=="assisted"||u===void 0||u.session()!=="choice"?!1:(N=!0,u.onModeChange("self"),p="self",f=B("self"),S("mode_switch"),a.restart(f),!0)}let $=async()=>u!==void 0&&u.session()==="choice"&&await d().catch(()=>!1),y=!1;return{handle:{get state(){return v},get captureMode(){return s()},get facingMode(){return a.facingMode??f},on:(t,o)=>l.on(t,o),start:t=>(p=s(),C.facing(p,e.facing),f=C.facing(p,t?.facing),E(),g=0,a.start({facingMode:f})),retry:()=>{E(),g=0,a.retry()},switchCamera:()=>C.refuseSwitch(s()),canSwitchCaptureMode:$,setCaptureMode:async t=>{if(t===s()||!await $()||y||_e.has(v)||u===void 0)return!1;u.onModeChange(t),p=t;let o=B(t);return f=o,v==="idle"||(S("mode_switch"),E(),g=0,a.restart(o)),!0},destroy:()=>{y=!0,E();for(let t of pe)t();q.setActive(!1),a.destroy(),l.clear()}},setFlowState:t=>{v!==t&&S(t)}}}function Ze(e){return De(e).handle}export{ve as a,ie as b,Te as c,Oe as d,xe as e,Fe as f,Ie as g,Be as h,de as i,Ae as j,Pe as k,ue as l,we as m,De as n,Ze as o};
1
+ import{a as re,d as ne,e as B,f as se,g as oe}from"./chunk-7QZWBDI5.js";import{A as te,a as X}from"./chunk-7FGOUBAN.js";import{f as j,l as J}from"./chunk-CPUECYAJ.js";import{c as Z}from"./chunk-TSA6GHUG.js";import{c as ee,h as L}from"./chunk-FSSMUAKC.js";var ve=12e4,ie=13e4,ge=3e3,he=1200,D=Symbol.for("@sekyro/web.preload.v1");function h(){let e=globalThis;return e[D]??(e[D]=new Map),e[D]}function b(e){let r=(e??ee).replace(/\/+$/,"");return r===""?"/":r}function ae(e){let r=h(),n=r.get(e);return n===void 0&&(n={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},r.set(e,n)),n}function k(e,r){if(e.status!==r){e.status=r;for(let n of[...e.listeners])n(r)}}var K=e=>L({preferred:["blaze"],v3AssetBaseUrl:e,blazeInitTimeoutMs:ve}),H=K;function Te(e){H=e??K}function Oe(){for(let e of h().values())e.detector?.destroy();h().clear(),H=K}function Ce(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function Se(){return navigator.connection?.saveData===!0}function Ee(e){let r=window;if(typeof r.requestIdleCallback=="function"){let s=r.requestIdleCallback(e,{timeout:ge});return()=>r.cancelIdleCallback?.(s)}let n=setTimeout(e,he);return()=>clearTimeout(n)}function ye(e,r){let n,s=new Promise(d=>{n=d}),m=!1,u=()=>{},c={promise:s,settle:d=>{m||(m=!0,u(),e.scheduled===c&&(e.scheduled=null),n(d))}};return e.scheduled=c,u=Ee(()=>{m||c.settle(U(e,r))}),s}function U(e,r){if((e.status==="loading"||e.status==="ready")&&e.promise!==null)return e.promise;k(e,"loading");let n=new Promise(d=>d(H(r)));e.detectorPromise=n;let s,m=new Promise((d,f)=>{s=setTimeout(()=>{n.then(C=>C.destroy(),()=>{}),f(new Error(`detector preload exceeded ${ie} ms`))},ie)}),c=Promise.race([n,m]).then(d=>e.detectorPromise!==n?(d.destroy(),e.status):(e.detector=d,k(e,"ready"),"ready"),d=>(e.detectorPromise===n&&(e.detectorPromise=null,e.detector=null,k(e,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",d)),e.status)).finally(()=>clearTimeout(s));return e.promise=c,e.scheduled?.settle(c),c}function xe(e={}){if(!Ce())return Promise.resolve("idle");let r=b(e.assetBaseUrl),n=ae(r);return e.respectSaveData===!0&&Se()?Promise.resolve(n.status):(n.status==="loading"||n.status==="ready")&&n.promise!==null?n.promise:e.idle===!0?n.scheduled?.promise??ye(n,r):U(n,r)}function Fe(e){return h().get(b(e))?.status??"idle"}function Ie(e,r){let n=ae(b(r));return n.listeners.add(e),()=>{n.listeners.delete(e)}}function Be(e){let r=h().get(b(e));r!==void 0&&(r.scheduled?.settle("idle"),r.detector?.destroy(),r.detector=null,r.detectorPromise=null,r.promise=null,k(r,"idle"))}function Le(e){return{get tier(){return e.tier},get fallbackReason(){return e.fallbackReason},detect:(...r)=>e.detect(...r),destroy:()=>{}}}function de(e){let r=b(e),n=h().get(r);if(!(n===void 0||n.detector===null&&n.detectorPromise===null&&n.scheduled===null))return async()=>{n.scheduled!==null&&U(n,r);let s=n.promise;for(;n.detector===null&&s!==null&&(await s,n.promise!==s);)s=n.promise;return n.detector!==null?Le(n.detector):L({v3AssetBaseUrl:r})}}var be=new Set(["inuse","overconstrained","notfound"]),Me=[500,1500];function Ae(e){switch(e){case"fcv3.no_face":case"fcv3.center_face":case"fcv3.straighten":return"center";case"fcv3.come_closer":return"closer";case"fcv3.move_back":return"farther";case"fcv3.more_light":case"fcv3.too_bright":return"light";case"fcv3.hold_still":case"fcv3.steady_camera":return"still";case"fcv3.hold_upright":return"upright";case"fcv3.one_face":return"one_face";default:return null}}function Pe(e){switch(e){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";default:return e}}function ue(e){switch(e){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return e;case"backcamera":return"notfound";default:{let r=e;return"generic"}}}function we(e,r,n){if(n===void 0)return{kind:ue(e),retryable:r};let s=J(n.name);return{kind:ue(e),retryable:r,detail:{...s!==void 0?{name:s}:{},phase:n.phase,engineKind:e}}}var _e=new Set(["captured","uploading","checking"]);function De(e,r={},n,s=()=>"self",m=()=>{},u){let c=r.now??(()=>performance.now()),d=r.canChooseFacing??ne,f="user",C=se(),p=s(),l=re(),V=!j(),G=r.engineOptions,ce=G?.createDetector===void 0&&G?.createWorker===void 0?{createDetector:()=>{let t=de(e.assetBaseUrl);return t!==void 0?t():L({v3AssetBaseUrl:e.assetBaseUrl})}}:{},z={video:e.video,mode:V?"photo":"clip",rankKeyframes:n,facingMode:void 0,v3AssetBaseUrl:e.assetBaseUrl,screenRamp:()=>p==="self"&&l.count("ramp")>0?m():void 0,...r.engineOptions??{},...ce},a=r.createEngine?.(z)??new te(z),v="idle",M=null,A=0,R=!1,T="full",P=null,w=null,O=0,x=0,W=()=>{e.video.videoWidth>0&&e.video.videoHeight>0&&(O=e.video.videoWidth,x=e.video.videoHeight)},q=oe({enabled:e.keepScreenAwake!==!1}),S=t=>{v=t,q.setActive(t==="starting"||t==="gating"||t==="recording"),l.emit("state",t)},F=()=>l.emit("gate",{progress:A,hint:M,faceDetected:R}),I=()=>{let t=a.animations??"full";t!==T&&(T=t,l.emit("profile",{animations:T}))},g=0,_=null,le=r.schedule??((t,o)=>{let i=setTimeout(t,o);return()=>clearTimeout(i)}),E=()=>{_?.(),_=null},fe=(t,o)=>{if(y||!be.has(t)||o?.phase!=="acquiring")return!1;let i=Me[g];return i===void 0?!1:(g+=1,E(),_=le(()=>{_=null,y||a.retry()},i),!0)},pe=[a.on("statechange",({state:t})=>{if(t==="error")return;let o=Pe(t);o==="gating"&&(g=0),o==="starting"&&v!=="starting"&&(M=null,A=0,R=!1,P=null,w=null,O=0,x=0),S(o),I(),o==="recording"&&(W(),P=c(),M="hold",A=1,F())}),a.on("checks",t=>{W(),A=t.progress,R=t.factors.presence>0,F(),I()}),a.on("guidance",({key:t})=>{M=Ae(t),F()}),a.on("frozen",({previewDataUrl:t})=>{w=c(),l.emit("frozen",{previewDataUrl:t})}),a.on("ramp",t=>l.emit("ramp",t)),a.on("artifacts",t=>{if(v!=="captured")return;let o=Z(),i=t.clipStats,Q=i!==void 0?Math.round(i.durationMs):P!==null&&w!==null?Math.max(0,Math.round(w-P)):void 0,Y=i!==void 0&&i.frames>1&&i.durationMs>0?Math.round(i.frames*1e4/i.durationMs)/10:void 0;l.emit("captured",{keyframe:t.keyframe,...t.clip!==void 0?{clip:t.clip}:{},...t.clipMimeType!==void 0?{clipMime:t.clipMimeType}:{},width:e.video.videoWidth||O,height:e.video.videoHeight||x,...Q!==void 0?{clipMs:Q}:{},...i!==void 0?{clipFrames:i.frames}:{},...Y!==void 0?{fps:Y}:{},...t.clipRetakes!==void 0?{clipRetakes:t.clipRetakes}:{},...t.clipMimeType!==void 0?{codec:X(t.clipMimeType)}:{},captureChannel:o==="desktop"?"desktop":"mobile",formFactor:o,...V?{degraded:"NO_RECORDER"}:{},engine:"v3",facingMode:a.facingMode,mode:p,...t.timing,...t.screenRamp!==void 0?{screenRamp:t.screenRamp}:{},...t.provenance!==void 0?{provenance:t.provenance}:{}})}),a.on("error",({kind:t,retryable:o,detail:i})=>{t==="backcamera"&&me()||fe(t,i)||(S("error"),I(),l.emit("error",we(t,o,i)))})],N=!1;function me(){return y||N||p!=="assisted"||u===void 0||u.session()!=="choice"?!1:(N=!0,u.onModeChange("self"),p="self",f=B("self"),S("mode_switch"),a.restart(f),!0)}let $=async()=>u!==void 0&&u.session()==="choice"&&await d().catch(()=>!1),y=!1;return{handle:{get state(){return v},get captureMode(){return s()},get facingMode(){return a.facingMode??f},on:(t,o)=>l.on(t,o),start:t=>(p=s(),C.facing(p,e.facing),f=C.facing(p,t?.facing),E(),g=0,a.start({facingMode:f})),retry:()=>{E(),g=0,a.retry()},switchCamera:()=>C.refuseSwitch(s()),canSwitchCaptureMode:$,setCaptureMode:async t=>{if(t===s()||!await $()||y||_e.has(v)||u===void 0)return!1;u.onModeChange(t),p=t;let o=B(t);return f=o,v==="idle"||(S("mode_switch"),E(),g=0,a.restart(o)),!0},destroy:()=>{y=!0,E();for(let t of pe)t();q.setActive(!1),a.destroy(),l.clear()}},setFlowState:t=>{v!==t&&S(t)}}}function Ze(e){return De(e).handle}export{ve as a,ie as b,Te as c,Oe as d,xe as e,Fe as f,Ie as g,Be as h,de as i,Ae as j,Pe as k,ue as l,we as m,De as n,Ze as o};
@@ -1 +1 @@
1
- import{c as g}from"./chunk-U5TL63CG.js";import{c as _}from"./chunk-TSA6GHUG.js";import{a as b,c as y}from"./chunk-COZXZAD5.js";var I=["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 q(i){return I.includes(i)}var u=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(i,e,n=Math.random){let t=(i??e)*1e3,s=Math.min(Math.max(t,500),2e4),o=Math.round(s*(1+(n()*2-1)*.25));return Math.min(Math.max(o,500),2e4)}var w=6e4,h=4,E=3e4,P=9e5,M=200,C=5,A=400,v=new Set(["server_busy","request_timeout"]),O=20,N=60,H=600,x=2;function l(i){return(i.split(";")[0]??"").trim()}var D={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},U=`@sekyro/web/${b}`,K=U,S=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.reportedIssues=new Map;this.issueReports=0;this.issuesPausedUntil=0;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let n=e.fetch;this.fetchImpl=(t,s)=>(n??globalThis.fetch).call(globalThis,t,s),this.requestTimeoutMs=e.requestTimeoutMs??E,this.retryAttempts=e.inProgressRetry?.attempts??C,this.retryDelayMs=e.inProgressRetry?.delayMs??A,this.random=e.random??Math.random,this.clientLocale=e.locale}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){let n=await this.api("POST","/hosted/consent",{body:{locale:e},busyRetry:!0}),t=this.captureHold;return this.captureHold=void 0,t&&this.armCapture(t),n}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 n=typeof e.name=="string"?e.name.replace(/[^A-Za-z]/g,"").slice(0,40):"",t=typeof e.engineKind=="string"&&/^[a-z_]{1,32}$/.test(e.engineKind)?e.engineKind:void 0,s=typeof e.attempt=="number"&&Number.isInteger(e.attempt)&&e.attempt>=0&&e.attempt<=1e3?e.attempt:void 0,o=e.check==="attestation"?s??"":"",r=[e.check,o,e.kind,n,e.phase??"",t??""].join("|"),c=this.reportedIssues.get(r);if(c!==void 0)return c;if(Date.now()<this.issuesPausedUntil||this.issueReports>=O)return;let a={check:e.check,kind:e.kind,...n!==""?{name:n}:{},...e.phase!==void 0?{phase:e.phase}:{},...t!==void 0?{engineKind:t}:{},...s!==void 0?{attempt:s}:{},...e.formFactor!==void 0?{formFactor:e.formFactor}:{},...typeof e.detail=="string"&&/^\d{1,10}$/.test(e.detail)?{detail:e.detail}:{},...k(e.challengeMs)?{challengeMs:e.challengeMs}:{},...k(e.readyMs)?{readyMs:e.readyMs}:{},...e.inApp===!0?{inApp:!0}:{}};this.issueReports+=1;let p=this.api("POST","/hosted/capture-issue",{body:a,empty:!0}).catch(d=>{if(d instanceof u&&d.status===429){let m=Math.min(Math.max(d.retryAfterSeconds??N,0),H);this.issuesPausedUntil=Math.max(this.issuesPausedUntil,Date.now()+m*1e3);return}(!(d instanceof u)||d.status===0||d.status>=500)&&this.reportedIssues.delete(r)});return this.reportedIssues.set(r,p),p}async choose(e,n){let t=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:n},busyRetry:!0});return this.sessionId=t.sessionId,t}async confirmIdentity(e){return this.api("POST","/hosted/identity/confirm",{body:{decision:e}})}async identityPortrait(){return this.api("GET","/hosted/identity/portrait",{blob:!0})}async presign(e,n,t,s={}){let o=await this.ensureSessionId(),r={kind:e,contentType:l(n),contentLength:t,...s.source==="upload"?{source:"upload"}:{}};return this.api("POST",`/sessions/${o}/media`,{body:r})}armCapture(e=2){let n=Date.now();this.captureNonces.filter(t=>t.expiresAt-w>n).length>=e||(this.captureHold===void 0?this.fillCaptureNonces(e,e):this.captureHold=Math.max(this.captureHold,e))}async armRamp(){try{let e=await this.ensureSessionId(),n=await this.api("POST",`/sessions/${e}/media/capture-nonces`,{body:{count:2,ramp:!0}}),t=Date.now(),s=g(n.screenRamp)?n.screenRamp:void 0,o=t+Math.max(0,n.expiresIn)*1e3;for(let c of Array.isArray(n.nonces)?n.nonces:[])typeof c!="string"||c.length===0||this.captureNonces.push({nonce:c,expiresAt:o,...s!==void 0?{arm:s.nonce}:{}});this.captureNonces=this.captureNonces.slice(-h),this.captureHold=void 0;let r=typeof n.rampExpiresIn=="number"&&n.rampExpiresIn>0?n.rampExpiresIn:0;return{...s!==void 0?{challenge:s}:{},expiresAt:t+r*1e3}}catch{return}}async presignCapture(e,n,t,s={}){let o=await this.ensureSessionId(),r=await this.takeCaptureNonce(s.arm),c=r===void 0?void 0:{nonce:r,...s.engine!==void 0?{engine:s.engine.slice(0,32)}:{},...s.durationMs!==void 0&&Number.isFinite(s.durationMs)?{captureMs:Math.min(36e5,Math.max(0,Math.round(s.durationMs)))}:{}},a={kind:e,contentType:l(n),contentLength:t,capture:c};return this.api("POST",`/sessions/${o}/media`,{body:a})}async takeCaptureNonce(e){let n=()=>{let t=Date.now();this.captureNonces=this.captureNonces.filter(o=>o.expiresAt-w>t);let s=this.captureNonces.findIndex(o=>o.arm===e);return this.captureNonces.splice(s<0?0:s,1)[0]?.nonce};for(let t=0;t<2;t++){let s=n();if(s!==void 0)return s;await this.fillCaptureNonces(1)}return n()}fillCaptureNonces(e,n=0){return this.captureFetch??(this.captureFetch=(async()=>{try{let t=await this.ensureSessionId(),s=await this.api("POST",`/sessions/${t}/media/capture-nonces`,{body:{count:Math.min(h,Math.max(1,e))}}),o=Date.now()+Math.max(0,s.expiresIn)*1e3;for(let r of Array.isArray(s.nonces)?s.nonces:[])typeof r=="string"&&r.length>0&&this.captureNonces.push({nonce:r,expiresAt:o});this.captureNonces=this.captureNonces.slice(-h),this.captureHold=void 0}catch(t){t instanceof u&&t.code==="consent_required"&&(this.captureHold=Math.max(this.captureHold??0,n))}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,n,t){let s;try{s=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":l(t)},body:n,signal:AbortSignal.timeout(P)})}catch(o){throw f(o)}if(!s.ok){let o=(await s.text().catch(()=>"")).slice(0,M);throw new u({status:s.status,code:"upload_failed",message:`media upload failed (HTTP ${s.status})${o?`: ${o}`:""}`})}}async completeMedia(e){let n=await this.ensureSessionId();return this.api("POST",`/sessions/${n}/media/complete`,{body:{key:e}})}async submitCheck(e,n,t={}){let s=await this.ensureSessionId(),o={input:n,forceOutcome:t.forceOutcome};return this.api("POST",`/sessions/${s}/checks/${e}`,{body:o,idempotencyKey:t.idempotencyKey,...t.browserCheckToken!==void 0?{browserCheckToken:t.browserCheckToken}:{},busyRetry:t.idempotencyKey!==void 0})}async uploadAndSubmit(e,n,t,s={}){let o=l(n.contentType),r=await this.presign(n.kind,o,n.blob.size);await this.uploadToSpaces(r.uploadUrl,n.blob,o);let c=await this.completeMedia(r.key),a={...t,[D[e]]:c.key};return this.submitCheck(e,a,s)}async ensureSessionId(){return this.sessionId!==null?this.sessionId:(this.bootstrap??(this.bootstrap=this.getSession().finally(()=>{this.bootstrap=null})),(await this.bootstrap).sessionId)}async api(e,n,t={}){let s=e==="GET"||t.busyRetry===!0,o=`${this.apiOrigin}/api/v2${n}`,r={"x-session-token":this.sessionToken,"x-sekyro-sdk":K};t.body!==void 0&&(r["content-type"]="application/json"),t.idempotencyKey!==void 0&&(r["x-idempotency-key"]=t.idempotencyKey),t.browserCheckToken!==void 0&&(r["sekyro-browser-check"]=t.browserCheckToken),this.clientLocale!==void 0&&(r["sekyro-client-locale"]=this.clientLocale);try{let c=y.timezone();c!==void 0&&(r["sekyro-client-timezone"]=c)}catch{}r["sekyro-client-form-factor"]=_();try{let c=await y.deviceHeader();c!==void 0&&(r["sekyro-client-device"]=c)}catch{}for(let c=0;;c++){let a;try{a=await this.fetchImpl(o,{method:e,headers:r,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(d){throw f(d)}if(a.ok){if(t.empty===!0)return;if(t.blob===!0)try{return await a.blob()}catch(m){throw f(m)}let d;try{d=await a.json()}catch{throw new u({status:a.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${a.status})`})}return L(d)}let p=await V(a);if(p.code==="idempotency_in_progress"&&c<this.retryAttempts){this.retryDelayMs>0&&await R(this.retryDelayMs);continue}if(s&&p.status===503&&v.has(p.code)){s=!1,await R(T(p.retryAfterSeconds,x,this.random));continue}throw p}}};function k(i){return typeof i=="number"&&Number.isInteger(i)&&i>=0&&i<=6e5}function f(i){if((typeof i=="object"&&i!==null?i.name:void 0)==="TimeoutError")return new u({status:0,code:"timeout",message:"request timed out"});let n=i instanceof Error?i.message:String(i);return new u({status:0,code:"network_error",message:`network request failed: ${n}`})}function L(i){return i!==null&&typeof i=="object"&&"success"in i&&"data"in i?i.data:i}async function V(i){let e="unknown_error",n=`request failed (HTTP ${i.status})`,t=Number.NaN,s;try{let c=await i.json();if(c!==null&&typeof c=="object"){let a=c;typeof a.code=="string"&&a.code.length>0&&(e=a.code),typeof a.message=="string"&&a.message.length>0&&(n=a.message),typeof a.retryAfterSeconds=="number"&&(t=a.retryAfterSeconds),Array.isArray(a.details?.issues)?s=a.details:Array.isArray(a.details?.errors)&&(s={...a.details,issues:[]})}}catch{}let o=i.headers.get("retry-after"),r=o===null?Math.floor(t):Number.parseInt(o,10);return new u({status:i.status,code:e,message:n,...Number.isFinite(r)&&r>=0?{retryAfterSeconds:r}:{},details:s})}function R(i){return new Promise(e=>setTimeout(e,i))}function J(i){let e=i?.portrait,n=e?.icao,t=e?.purpose==="id_document";return n==null?t?{policy:"reject",profile:"id_document"}:null:{policy:n.policy==="alert"?"alert":"reject",profile:t||n.profile==="id_document"?"id_document":"selfie"}}function Q(i){return{...i.baselineEyeOpenness!==void 0?{baselineEyeOpenness:i.baselineEyeOpenness}:{},...i.baselineEyeOpennessLeft!==void 0&&i.baselineEyeOpennessRight!==void 0?{baselineEyeOpennessLeft:i.baselineEyeOpennessLeft,baselineEyeOpennessRight:i.baselineEyeOpennessRight}:{},criteria:i.verdict??{},...i.backgroundCheck!==void 0?{backgroundCheck:i.backgroundCheck}:{}}}export{I as a,q as b,u as c,T as d,l as e,U as f,S as g,J as h,Q as i};
1
+ import{c as g}from"./chunk-U5TL63CG.js";import{c as _}from"./chunk-TSA6GHUG.js";import{a as b,c as y}from"./chunk-HMOOVRKA.js";var I=["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 q(i){return I.includes(i)}var u=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(i,e,n=Math.random){let t=(i??e)*1e3,s=Math.min(Math.max(t,500),2e4),o=Math.round(s*(1+(n()*2-1)*.25));return Math.min(Math.max(o,500),2e4)}var w=6e4,h=4,E=3e4,P=9e5,M=200,C=5,A=400,v=new Set(["server_busy","request_timeout"]),O=20,N=60,H=600,x=2;function l(i){return(i.split(";")[0]??"").trim()}var D={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},U=`@sekyro/web/${b}`,K=U,S=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.reportedIssues=new Map;this.issueReports=0;this.issuesPausedUntil=0;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let n=e.fetch;this.fetchImpl=(t,s)=>(n??globalThis.fetch).call(globalThis,t,s),this.requestTimeoutMs=e.requestTimeoutMs??E,this.retryAttempts=e.inProgressRetry?.attempts??C,this.retryDelayMs=e.inProgressRetry?.delayMs??A,this.random=e.random??Math.random,this.clientLocale=e.locale}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){let n=await this.api("POST","/hosted/consent",{body:{locale:e},busyRetry:!0}),t=this.captureHold;return this.captureHold=void 0,t&&this.armCapture(t),n}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 n=typeof e.name=="string"?e.name.replace(/[^A-Za-z]/g,"").slice(0,40):"",t=typeof e.engineKind=="string"&&/^[a-z_]{1,32}$/.test(e.engineKind)?e.engineKind:void 0,s=typeof e.attempt=="number"&&Number.isInteger(e.attempt)&&e.attempt>=0&&e.attempt<=1e3?e.attempt:void 0,o=e.check==="attestation"?s??"":"",r=[e.check,o,e.kind,n,e.phase??"",t??""].join("|"),c=this.reportedIssues.get(r);if(c!==void 0)return c;if(Date.now()<this.issuesPausedUntil||this.issueReports>=O)return;let a={check:e.check,kind:e.kind,...n!==""?{name:n}:{},...e.phase!==void 0?{phase:e.phase}:{},...t!==void 0?{engineKind:t}:{},...s!==void 0?{attempt:s}:{},...e.formFactor!==void 0?{formFactor:e.formFactor}:{},...typeof e.detail=="string"&&/^\d{1,10}$/.test(e.detail)?{detail:e.detail}:{},...k(e.challengeMs)?{challengeMs:e.challengeMs}:{},...k(e.readyMs)?{readyMs:e.readyMs}:{},...e.inApp===!0?{inApp:!0}:{}};this.issueReports+=1;let p=this.api("POST","/hosted/capture-issue",{body:a,empty:!0}).catch(d=>{if(d instanceof u&&d.status===429){let m=Math.min(Math.max(d.retryAfterSeconds??N,0),H);this.issuesPausedUntil=Math.max(this.issuesPausedUntil,Date.now()+m*1e3);return}(!(d instanceof u)||d.status===0||d.status>=500)&&this.reportedIssues.delete(r)});return this.reportedIssues.set(r,p),p}async choose(e,n){let t=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:n},busyRetry:!0});return this.sessionId=t.sessionId,t}async confirmIdentity(e){return this.api("POST","/hosted/identity/confirm",{body:{decision:e}})}async identityPortrait(){return this.api("GET","/hosted/identity/portrait",{blob:!0})}async presign(e,n,t,s={}){let o=await this.ensureSessionId(),r={kind:e,contentType:l(n),contentLength:t,...s.source==="upload"?{source:"upload"}:{}};return this.api("POST",`/sessions/${o}/media`,{body:r})}armCapture(e=2){let n=Date.now();this.captureNonces.filter(t=>t.expiresAt-w>n).length>=e||(this.captureHold===void 0?this.fillCaptureNonces(e,e):this.captureHold=Math.max(this.captureHold,e))}async armRamp(){try{let e=await this.ensureSessionId(),n=await this.api("POST",`/sessions/${e}/media/capture-nonces`,{body:{count:2,ramp:!0}}),t=Date.now(),s=g(n.screenRamp)?n.screenRamp:void 0,o=t+Math.max(0,n.expiresIn)*1e3;for(let c of Array.isArray(n.nonces)?n.nonces:[])typeof c!="string"||c.length===0||this.captureNonces.push({nonce:c,expiresAt:o,...s!==void 0?{arm:s.nonce}:{}});this.captureNonces=this.captureNonces.slice(-h),this.captureHold=void 0;let r=typeof n.rampExpiresIn=="number"&&n.rampExpiresIn>0?n.rampExpiresIn:0;return{...s!==void 0?{challenge:s}:{},expiresAt:t+r*1e3}}catch{return}}async presignCapture(e,n,t,s={}){let o=await this.ensureSessionId(),r=await this.takeCaptureNonce(s.arm),c=r===void 0?void 0:{nonce:r,...s.engine!==void 0?{engine:s.engine.slice(0,32)}:{},...s.durationMs!==void 0&&Number.isFinite(s.durationMs)?{captureMs:Math.min(36e5,Math.max(0,Math.round(s.durationMs)))}:{}},a={kind:e,contentType:l(n),contentLength:t,capture:c};return this.api("POST",`/sessions/${o}/media`,{body:a})}async takeCaptureNonce(e){let n=()=>{let t=Date.now();this.captureNonces=this.captureNonces.filter(o=>o.expiresAt-w>t);let s=this.captureNonces.findIndex(o=>o.arm===e);return this.captureNonces.splice(s<0?0:s,1)[0]?.nonce};for(let t=0;t<2;t++){let s=n();if(s!==void 0)return s;await this.fillCaptureNonces(1)}return n()}fillCaptureNonces(e,n=0){return this.captureFetch??(this.captureFetch=(async()=>{try{let t=await this.ensureSessionId(),s=await this.api("POST",`/sessions/${t}/media/capture-nonces`,{body:{count:Math.min(h,Math.max(1,e))}}),o=Date.now()+Math.max(0,s.expiresIn)*1e3;for(let r of Array.isArray(s.nonces)?s.nonces:[])typeof r=="string"&&r.length>0&&this.captureNonces.push({nonce:r,expiresAt:o});this.captureNonces=this.captureNonces.slice(-h),this.captureHold=void 0}catch(t){t instanceof u&&t.code==="consent_required"&&(this.captureHold=Math.max(this.captureHold??0,n))}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,n,t){let s;try{s=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":l(t)},body:n,signal:AbortSignal.timeout(P)})}catch(o){throw f(o)}if(!s.ok){let o=(await s.text().catch(()=>"")).slice(0,M);throw new u({status:s.status,code:"upload_failed",message:`media upload failed (HTTP ${s.status})${o?`: ${o}`:""}`})}}async completeMedia(e){let n=await this.ensureSessionId();return this.api("POST",`/sessions/${n}/media/complete`,{body:{key:e}})}async submitCheck(e,n,t={}){let s=await this.ensureSessionId(),o={input:n,forceOutcome:t.forceOutcome};return this.api("POST",`/sessions/${s}/checks/${e}`,{body:o,idempotencyKey:t.idempotencyKey,...t.browserCheckToken!==void 0?{browserCheckToken:t.browserCheckToken}:{},busyRetry:t.idempotencyKey!==void 0})}async uploadAndSubmit(e,n,t,s={}){let o=l(n.contentType),r=await this.presign(n.kind,o,n.blob.size);await this.uploadToSpaces(r.uploadUrl,n.blob,o);let c=await this.completeMedia(r.key),a={...t,[D[e]]:c.key};return this.submitCheck(e,a,s)}async ensureSessionId(){return this.sessionId!==null?this.sessionId:(this.bootstrap??(this.bootstrap=this.getSession().finally(()=>{this.bootstrap=null})),(await this.bootstrap).sessionId)}async api(e,n,t={}){let s=e==="GET"||t.busyRetry===!0,o=`${this.apiOrigin}/api/v2${n}`,r={"x-session-token":this.sessionToken,"x-sekyro-sdk":K};t.body!==void 0&&(r["content-type"]="application/json"),t.idempotencyKey!==void 0&&(r["x-idempotency-key"]=t.idempotencyKey),t.browserCheckToken!==void 0&&(r["sekyro-browser-check"]=t.browserCheckToken),this.clientLocale!==void 0&&(r["sekyro-client-locale"]=this.clientLocale);try{let c=y.timezone();c!==void 0&&(r["sekyro-client-timezone"]=c)}catch{}r["sekyro-client-form-factor"]=_();try{let c=await y.deviceHeader();c!==void 0&&(r["sekyro-client-device"]=c)}catch{}for(let c=0;;c++){let a;try{a=await this.fetchImpl(o,{method:e,headers:r,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(d){throw f(d)}if(a.ok){if(t.empty===!0)return;if(t.blob===!0)try{return await a.blob()}catch(m){throw f(m)}let d;try{d=await a.json()}catch{throw new u({status:a.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${a.status})`})}return L(d)}let p=await V(a);if(p.code==="idempotency_in_progress"&&c<this.retryAttempts){this.retryDelayMs>0&&await R(this.retryDelayMs);continue}if(s&&p.status===503&&v.has(p.code)){s=!1,await R(T(p.retryAfterSeconds,x,this.random));continue}throw p}}};function k(i){return typeof i=="number"&&Number.isInteger(i)&&i>=0&&i<=6e5}function f(i){if((typeof i=="object"&&i!==null?i.name:void 0)==="TimeoutError")return new u({status:0,code:"timeout",message:"request timed out"});let n=i instanceof Error?i.message:String(i);return new u({status:0,code:"network_error",message:`network request failed: ${n}`})}function L(i){return i!==null&&typeof i=="object"&&"success"in i&&"data"in i?i.data:i}async function V(i){let e="unknown_error",n=`request failed (HTTP ${i.status})`,t=Number.NaN,s;try{let c=await i.json();if(c!==null&&typeof c=="object"){let a=c;typeof a.code=="string"&&a.code.length>0&&(e=a.code),typeof a.message=="string"&&a.message.length>0&&(n=a.message),typeof a.retryAfterSeconds=="number"&&(t=a.retryAfterSeconds),Array.isArray(a.details?.issues)?s=a.details:Array.isArray(a.details?.errors)&&(s={...a.details,issues:[]})}}catch{}let o=i.headers.get("retry-after"),r=o===null?Math.floor(t):Number.parseInt(o,10);return new u({status:i.status,code:e,message:n,...Number.isFinite(r)&&r>=0?{retryAfterSeconds:r}:{},details:s})}function R(i){return new Promise(e=>setTimeout(e,i))}function J(i){let e=i?.portrait,n=e?.icao,t=e?.purpose==="id_document";return n==null?t?{policy:"reject",profile:"id_document"}:null:{policy:n.policy==="alert"?"alert":"reject",profile:t||n.profile==="id_document"?"id_document":"selfie"}}function Q(i){return{...i.baselineEyeOpenness!==void 0?{baselineEyeOpenness:i.baselineEyeOpenness}:{},...i.baselineEyeOpennessLeft!==void 0&&i.baselineEyeOpennessRight!==void 0?{baselineEyeOpennessLeft:i.baselineEyeOpennessLeft,baselineEyeOpennessRight:i.baselineEyeOpennessRight}:{},criteria:i.verdict??{},...i.backgroundCheck!==void 0?{backgroundCheck:i.backgroundCheck}:{}}}export{I as a,q as b,u as c,T as d,l as e,U as f,S as g,J as h,Q as i};
@@ -1 +1 @@
1
- import{d as qt,h as $t,k as ee}from"./chunk-MQHTFHSN.js";import{b as te}from"./chunk-SMKCBUJL.js";import{a as et,b as ie,c as oe,e as mt,f as ne}from"./chunk-TOISWBOX.js";import{c as Zt,d as Jt}from"./chunk-5AR5GTEJ.js";import{b as Xt,c as jt}from"./chunk-POIQGEZM.js";import{k as Bt,m as Ut,n as Ht,o as Kt,p as Vt,r as ut}from"./chunk-CPUECYAJ.js";import{b as ht,c as dt,d as j,e as Yt}from"./chunk-FPXL63KZ.js";import{d as Wt}from"./chunk-COZXZAD5.js";var it=Object.freeze({sensing:{key:"sensing",reticle:"searching",minDurationMs:900},too_far:{key:"too_far",reticle:"coaching",minDurationMs:1400},too_close:{key:"too_close",reticle:"coaching",minDurationMs:1400},edge_clipped:{key:"edge_clipped",reticle:"coaching",minDurationMs:1400},wrong_shape:{key:"wrong_shape",reticle:"coaching",minDurationMs:1400},tilted:{key:"tilted",reticle:"coaching",minDurationMs:1400},too_dark:{key:"too_dark",reticle:"coaching",minDurationMs:1400},too_bright:{key:"too_bright",reticle:"coaching",minDurationMs:1400},blurry:{key:"blurry",reticle:"coaching",minDurationMs:1400},focus_far:{key:"focus_far",reticle:"coaching",minDurationMs:1600},glare:{key:"glare",reticle:"coaching",minDurationMs:1400},hold_still:{key:"hold_still",reticle:"locking",minDurationMs:900},processing:{key:"processing",reticle:"processing",minDurationMs:800},side_captured:{key:"side_captured",reticle:"flip",minDurationMs:2600},captured:{key:"captured",reticle:"done",minDurationMs:800}});function se(i){return i.framing==="no_document"?"sensing":i.framing==="too_far"?"too_far":i.framing==="too_close"?"too_close":i.framing==="edge_clipped"?"edge_clipped":i.framing==="wrong_shape"?"wrong_shape":i.framing==="tilted"?"tilted":i.lighting==="too_dark"?"too_dark":i.lighting==="too_bright"?"too_bright":i.glare==="glare"?"glare":i.blur==="blurry"?"blurry":"hold_still"}var ot=class{constructor(t=2600,e=.35){this.windowMs=t;this.decayPerSecond=e;this.votes=[];this.current=it.sensing;this.currentSinceMs=null}reset(){this.votes=[],this.current=it.sensing,this.currentSinceMs=null}force(t,e){return this.votes=[],this.current=it[t],this.currentSinceMs=e,this.current}tick(t,e){if(this.currentSinceMs===null&&(this.currentSinceMs=e),this.votes.push({key:t,atMs:e}),this.votes=this.votes.filter(r=>e-r.atMs<=this.windowMs),e-this.currentSinceMs<this.current.minDurationMs)return this.current;let o=new Map;for(let r of this.votes){let c=(e-r.atMs)/1e3,a=this.decayPerSecond**c;o.set(r.key,(o.get(r.key)??0)+a)}let n=this.current.key,s=-1;for(let[r,c]of o)c>s&&(s=c,n=r);return n!==this.current.key&&(this.current=it[n],this.currentSinceMs=e),this.current}};var je=Object.freeze({MAX_AREA_FRAC:.92,TILT_MAX_SIDE_RATIO:1.3,GLARE_MAX_SPECULAR_FRAC:.025});function ae(i){let{data:t,width:e,height:o}=i,n=e*o;if(n===0)return 0;let s=0;for(let r=0;r<n;r++){let c=r*4;.299*(t[c]??0)+.587*(t[c+1]??0)+.114*(t[c+2]??0)>=252&&s++}return s/n}function Ye(i){let t=(a,l)=>Math.hypot(l.x-a.x,l.y-a.y),e=t(i.topLeft,i.topRight),o=t(i.bottomLeft,i.bottomRight),n=t(i.topLeft,i.bottomLeft),s=t(i.topRight,i.bottomRight),r=Math.max(e,o)/Math.max(1e-6,Math.min(e,o)),c=Math.max(n,s)/Math.max(1e-6,Math.min(n,s));return Math.max(r,c)}function ce(i){let t={...ie,...i.thresholds},e=je,{quad:o,frameWidth:n,frameHeight:s,measures:r}=i,c=i.format==="ID-3",a="ok";if(o===null)a="no_document";else if(c){let m=mt(o),h=n>0?m.width/n:0,f=m.height>0?m.width/m.height:0;h<t.ID3_BAND_MIN_WIDTH_FRAC?a="too_far":re(o,n,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":(f<t.ID3_BAND_ASPECT_MIN||f>t.ID3_BAND_ASPECT_MAX)&&(a="wrong_shape")}else{let m=oe(o,n,s),h=mt(o),f=Math.max(h.width,h.height)/Math.max(1e-6,Math.min(h.width,h.height));m<t.MIN_AREA_FRAC?a="too_far":m>e.MAX_AREA_FRAC?a="too_close":re(o,n,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":Jt(i.format,f)?Ye(o)>e.TILT_MAX_SIDE_RATIO&&(a="tilted"):a="wrong_shape"}let l=r.exposure>=t.GUIDE_EXPOSURE?"ok":r.meanLuma<(ht[0]+ht[1])/2?"too_dark":"too_bright",u=r.sharpness>=t.GUIDE_SHARPNESS?"ok":"blurry",d=r.specularFraction>=e.GLARE_MAX_SPECULAR_FRAC?"glare":"ok";return{framing:a,lighting:l,blur:u,glare:d,acceptable:a==="ok"&&l==="ok"&&u==="ok"&&d==="ok"}}function re(i,t,e,o){return[i.topLeft,i.topRight,i.bottomRight,i.bottomLeft].some(s=>s.x<=o||s.y<=o||s.x>=t-o||s.y>=e-o)}var ue=Object.freeze({width:1920,height:1080}),Ze=Object.freeze({width:3840,height:2160}),le=4096,Je=2560,he=640,nt=.15,Y=Object.freeze({side:.2,above:.9,below:.3});function E(i){let t=[i.topLeft.x,i.topRight.x,i.bottomRight.x,i.bottomLeft.x],e=[i.topLeft.y,i.topRight.y,i.bottomRight.y,i.bottomLeft.y],o=Math.min(...t),n=Math.min(...e);return{x:o,y:n,width:Math.max(...t)-o,height:Math.max(...e)-n}}function de(i,t){let e=Math.max(0,Math.floor(i.x)),o=Math.max(0,Math.floor(i.y)),n=Math.min(t.width,Math.ceil(i.x+i.width)),s=Math.min(t.height,Math.ceil(i.y+i.height));return n-e<16||s-o<16?null:{x:e,y:o,width:n-e,height:s-o}}function qe(i,t,e){if(i===null||t.width<=0||t.height<=0)return null;let o=E(i);if(o.width<=0||o.height<=0)return null;let n=e==="ID-3"?{x:o.x-o.width*Y.side,y:o.y-o.width*Y.above,width:o.width*(1+2*Y.side),height:o.height+o.width*(Y.above+Y.below)}:{x:o.x-o.width*nt,y:o.y-o.height*nt,width:o.width*(1+2*nt),height:o.height*(1+2*nt)};return de(n,t)}function pt(i,t,e){let o=Math.max(i,t);return o>0?Math.min(1,e/o):1}function gt(i,t,e,o,n=Je){let s=t.width>0?e.width/t.width:1,r=t.height>0?e.height/t.height:1,c=i===null?null:{topLeft:{x:i.topLeft.x*s,y:i.topLeft.y*r},topRight:{x:i.topRight.x*s,y:i.topRight.y*r},bottomRight:{x:i.bottomRight.x*s,y:i.bottomRight.y*r},bottomLeft:{x:i.bottomLeft.x*s,y:i.bottomLeft.y*r}},a=qe(c,e,o)??{x:0,y:0,width:e.width,height:e.height},l=pt(a.width,a.height,n),u=Math.max(1,Math.round(a.width*l)),d=Math.max(1,Math.round(a.height*l)),m=null;if(c!==null){let h=E(c);m=de({x:(h.x-a.x)*l,y:(h.y-a.y)*l,width:h.width*l,height:h.height*l},{width:u,height:d})}return{crop:a,width:u,height:d,docRegion:m}}var $e=960,ft=[{width:1920,height:1080},{width:2560,height:1440}];function ti(i){let t=Number.isFinite(i)&&i>0?Math.min(1,i):.85;return ft.find(e=>e.height*t>=$e)??ft[ft.length-1]}function me(i,t,e,o=Ze,n){if(e==="LOW")return null;let s=n===void 0?null:ti(n.fill),r=s!==null&&Math.max(s.width,s.height)>Math.max(o.width,o.height)?s:o,c=i?.width?.max,a=i?.height?.max;if(typeof c!="number"||typeof a!="number"||c<=0||a<=0)return null;let l=Math.max(c,a),u=Math.min(c,a),d=Math.min(l,Math.max(r.width,r.height)),m=Math.min(u,Math.min(r.width,r.height));return d<=Math.max(t.width,t.height)?null:{width:{ideal:d},height:{ideal:m}}}function fe(i){let t={},e=i?.imageWidth,o=i?.imageHeight;if(typeof e?.max=="number"&&e.max>0){let n=typeof o?.max=="number"&&o.max>0?e.max/o.max:1.3333333333333333,s=n>=1?le:le*n,r=Math.min(e.max,Math.floor(s)),c=typeof e.step=="number"&&e.step>0?e.step:1,a=typeof e.min=="number"?e.min:0;r=Math.max(a,a+Math.floor((r-a)/c)*c),t.imageWidth=r}return i?.fillLightMode?.includes("off")===!0&&(t.fillLightMode="off"),t}function pe(i,t){if(i.width<=0||i.height<=0||t.width<=0||t.height<=0)return!1;let e=i.width>i.height,o=t.width>t.height;return e!==o&&i.width!==i.height&&t.width!==t.height?!1:Math.max(i.width,i.height)>=1.2*Math.max(t.width,t.height)}function ge(i,t,e,o){if(e===null)return!1;let n=E(i),s=E(e);if(t.width<=0||o.width<=0)return!1;let r=n.width/t.width,c=s.width/o.width;return c>0&&r>=.6*c&&r<=1.25*c}var be=3500,ei=.92;function Me(){let i=globalThis.ImageCapture;return typeof i=="function"?i:null}function ii(i){return/AppleWebKit\//.test(i)&&!/(Chrome|Chromium|Edg|OPR)\//.test(i)}function ke(i,t=typeof navigator>"u"?"":navigator.userAgent){return Me()!==null&&!ii(t)&&i!=null&&i.kind==="video"&&i.readyState==="live"}function ye(i,t){return new Promise((e,o)=>{let n=setTimeout(()=>o(new Error("takePhoto timed out")),t);i.then(s=>{clearTimeout(n),e(s)},s=>{clearTimeout(n),o(s)})})}function bt(i,t){let e=document.createElement("canvas");return e.width=i,e.height=t,e}function oi(i,t){return new Promise((e,o)=>{i.toBlob(n=>n?e(n):o(new Error("toBlob failed")),"image/jpeg",t)})}async function xe(i,t,e,o,n){let s=bt(e,o),r=bt(1,1);try{let c=s.getContext("2d");if(c===null)throw new Error("2d context unavailable");c.imageSmoothingQuality="high",c.drawImage(i,t.x,t.y,t.width,t.height,0,0,e,o);let a=await oi(s,ei),l=n===null?null:qt({topLeft:{x:n.x,y:n.y},topRight:{x:n.x+n.width,y:n.y},bottomRight:{x:n.x+n.width,y:n.y+n.height},bottomLeft:{x:n.x,y:n.y+n.height}},{width:e,height:o},{width:e,height:o}),u=$t(s,l),d=pt(e,o,he);return r.width=Math.max(1,Math.round(e*d)),r.height=Math.max(1,Math.round(o*d)),r.getContext("2d")?.drawImage(s,0,0,r.width,r.height),{blob:a,previewDataUrl:r.toDataURL("image/jpeg",.85),sharpness:u}}finally{s.width=0,s.height=0,r.width=0,r.height=0}}function ni(i,t){let e=Math.min(1,t/i.width),o=bt(Math.max(1,Math.round(i.width*e)),Math.max(1,Math.round(i.height*e)));try{let n=o.getContext("2d",{willReadFrequently:!0});return n===null?null:(n.imageSmoothingQuality="high",n.drawImage(i,0,0,o.width,o.height),n.getImageData(0,0,o.width,o.height))}finally{o.width=0,o.height=0}}async function De(i,t,e,o){let n={width:Math.max(1,i.videoWidth),height:Math.max(1,i.videoHeight)},s=gt(t,e,n,o);return{...await xe(i,s.crop,s.width,s.height,s.docRegion),docRegion:s.docRegion,source:"video",width:s.width,height:s.height}}async function we(i,t,e,o,n){let s=Me();if(s===null)return null;let r=null;try{let c=new s(n.track),a=await ye(c.getPhotoCapabilities?.()??Promise.resolve({}),be).catch(()=>({})),l=await ye(c.takePhoto(fe(a)),be);r=await createImageBitmap(l);let u={width:i.videoWidth,height:i.videoHeight};if(!pe(r,u))return null;let d=ni(r,n.detectWidth),m=null;d!==null&&t!==null&&(m=await n.detect(d).catch(()=>null));let h=d??{width:r.width,height:r.height};m!==null&&!ge(m,h,t,e)&&(m=null);let f=gt(m,h,r,o);return{...await xe(r,f.crop,f.width,f.height,f.docRegion),docRegion:f.docRegion,source:"photo",width:f.width,height:f.height}}catch{return null}finally{r?.close()}}var st=Object.freeze({width:3840,height:2160,lensSelection:!0,continuousFocus:!0,refocusBeforePhotoMs:350,zoomMax:2,zoomNoFocusInfo:1.5,zoomMinSourcePx:2160,fillDistanceM:Object.freeze({id1:.11,id3:.15}),focusMarginFrac:.2,stillSharpnessMin:.16,stillRefusalsMax:2,focusFarFillFrac:.45,noDocFarHintMs:1500,zoomFallbackMs:8e3}),S=(i,t,e)=>typeof i=="number"&&Number.isFinite(i)&&i>=t&&i<=e?i:void 0;function Ri(i){let t=st,e=i!==null&&typeof i=="object"?i:{},o=e.fillDistanceM!==null&&typeof e.fillDistanceM=="object"?e.fillDistanceM:{},n=(s,r)=>typeof s=="boolean"?s:r;return{width:S(e.width,640,7680)??t.width,height:S(e.height,480,4320)??t.height,lensSelection:n(e.lensSelection,t.lensSelection),continuousFocus:n(e.continuousFocus,t.continuousFocus),refocusBeforePhotoMs:S(e.refocusBeforePhotoMs,0,2e3)??t.refocusBeforePhotoMs,zoomMax:S(e.zoomMax,1,5)??t.zoomMax,zoomNoFocusInfo:S(e.zoomNoFocusInfo,1,5)??t.zoomNoFocusInfo,zoomMinSourcePx:S(e.zoomMinSourcePx,0,8e3)??t.zoomMinSourcePx,fillDistanceM:{id1:S(o.id1,.03,1)??t.fillDistanceM.id1,id3:S(o.id3,.03,1)??t.fillDistanceM.id3},focusMarginFrac:S(e.focusMarginFrac,0,2)??t.focusMarginFrac,stillSharpnessMin:S(e.stillSharpnessMin,0,10)??t.stillSharpnessMin,stillRefusalsMax:S(e.stillRefusalsMax,0,10)??t.stillRefusalsMax,focusFarFillFrac:S(e.focusFarFillFrac,0,1)??t.focusFarFillFrac,noDocFarHintMs:S(e.noDocFarHintMs,0,6e4)??t.noDocFarHintMs,zoomFallbackMs:S(e.zoomFallbackMs,0,12e4)??t.zoomFallbackMs}}var yt="sekyro.doc.camera";function si(){try{let i=globalThis.localStorage?.getItem(yt);return typeof i=="string"&&i!==""?i:null}catch{return null}}function ve(i){try{i===null?globalThis.localStorage?.removeItem(yt):globalThis.localStorage?.setItem(yt,i)}catch{}}var rt=(i,t)=>Array.isArray(i?.focusMode)&&i.focusMode.includes(t);function kt(i,t,e){if(!rt(i,"single-shot"))return null;let o=n=>Math.min(1,Math.max(0,Number.isFinite(n)?n:.5));return{focusMode:"single-shot",pointsOfInterest:[{x:o(t),y:o(e)}]}}function Ci(i,t,e,o){if(!Number.isFinite(i)||!Number.isFinite(t)||e.width<=0||e.height<=0||o.width<=0||o.height<=0)return null;let n=Math.max(e.width/o.width,e.height/o.height),s=o.width*n,r=o.height*n,c=(i-e.left+(s-e.width)/2)/s,a=(t-e.top+(r-e.height)/2)/r;return{x:Math.min(1,Math.max(0,c)),y:Math.min(1,Math.max(0,a))}}function _e(i,t,e,o=st){let n=i?.zoom?.min,s=i?.zoom?.max;if(typeof s!="number"||s<=1)return 1;let r=e==="ID-3"?o.fillDistanceM.id3:o.fillDistanceM.id1,c=i?.focusDistance?.min,a;if(typeof c=="number"&&c>0&&c<1){if(a=c*(1+o.focusMarginFrac)/r,a<=1.05)return 1}else{if(Math.min(t.width,t.height)<o.zoomMinSourcePx)return 1;a=o.zoomNoFocusInfo}let l=Math.min(a,o.zoomMax,s);typeof n=="number"&&(l=Math.max(l,n));let u=i?.zoom?.step;return typeof u=="number"&&u>0&&(l=Math.round(l/u)*u),l>1.01?Number(l.toFixed(2)):1}function Mt(i){try{return i.getVideoTracks?.()[0]}catch{return}}function Se(i){if(i!==null)for(let t of i.getTracks())t.stop()}function ri(i){try{let t=Mt(i)?.getCapabilities?.();return!Array.isArray(t?.focusMode)||t.focusMode.includes("continuous")}catch{return!0}}async function Te(i){let t=s=>({audio:!1,video:{...s,width:{ideal:i.base.width},height:{ideal:i.base.height}}}),e=s=>i.getUserMedia(t({deviceId:{exact:s}})),o=()=>i.getUserMedia(t({facingMode:{ideal:"environment"}}));if(i.lensSelection){let s=si();if(s!==null)try{return{stream:await e(s),lens:"stored"}}catch{ve(null)}}let n=await o();if(!i.lensSelection||i.enumerateDevices===void 0)return{stream:n,lens:"default"};try{let s=ut(await i.enumerateDevices()).slice(0,3);if(s.length===0)return{stream:n,lens:"default"};let r=null;for(let c of s){let a=n!==null?Mt(n)?.getSettings?.().deviceId:void 0;if(n===null||a!==c){Se(n),n=null;try{n=await e(c)}catch{continue}}if(r??(r=c),ri(n))return ve(c),{stream:n,lens:"selected"}}if(n!==null&&r!==null&&Mt(n)?.getSettings?.().deviceId===r)return{stream:n,lens:"selected"};if(Se(n),n=null,r!==null)try{return{stream:await e(r),lens:"selected"}}catch{}return{stream:await o(),lens:"default"}}catch{return{stream:n??await o(),lens:"default"}}}var Z=Object.freeze({brightness:0,glare:0,cardGlare:0,sharpness:0,fill:0,shape:0,content:0,offsetX:0,offsetY:0,edgeConfidence:0,box:null}),L=i=>Math.min(1,Math.max(0,i));function Fe(i,t,e,o=.06){let n=Math.max(i.width/e,i.height),s=n*e,r=(i.width-s)/2,c=(i.height-n)/2,a=L((t.x-t.width*o-r)/s),l=L((t.y-t.height*o-c)/n),u=L((t.x+t.width*(1+o)-r)/s),d=L((t.y+t.height*(1+o)-c)/n);return{x:a,y:l,width:u-a,height:d-l}}function Ce(i,t,e={}){let o=e.edgePeakFrac??0,{width:n,height:s,data:r}=i;if(n<=0||s<=0)return Z;let c=L(t.x),a=L(t.y),l={x:c,y:a,width:Math.max(0,L(t.x+t.width)-c),height:Math.max(0,L(t.y+t.height)-a)};if(l.width<=0||l.height<=0)return Z;let u=l.x*n,d=l.y*s,m=(l.x+l.width)*n,h=(l.y+l.height)*s,f=(m-u)*.15,g=(h-d)*.15,y=(p,b,R)=>Math.min(R,Math.max(b,p)),x=y(Math.floor(u-f),0,n-1),w=y(Math.floor(d-g),0,s-1),O=y(Math.ceil(m+f),x+1,n),v=y(Math.ceil(h+g),w+1,s),D=Math.max(1,Math.ceil(Math.max(O-x,v-w)/320)),M=Math.floor((O-x+D-1)/D),_=Math.floor((v-w+D-1)/D);if(M<3||_<3)return Z;let k=new Int32Array(M*_);for(let p=0;p<_;p++){let b=w+p*D;for(let R=0;R<M;R++){let F=(b*n+x+R*D)*4;k[p*M+R]=(r[F]??0)*77+(r[F+1]??0)*150+(r[F+2]??0)*29>>8}}let C=(p,b)=>(p-b-.5)/D,T=C(u,x),A=C(m,x),B=C(d,w),U=C(h,w),Dt=(m-u)/D,wt=(h-d)/D,vt=y(Math.ceil(T),0,M-1),Ge=y(Math.floor(A),vt,M-1),St=y(Math.ceil(B),0,_-1),ze=y(Math.floor(U),St,_-1),_t=0,Tt=0,W=0,Rt=0,Ft=0,H=0;for(let p=St;p<=ze;p++)for(let b=vt;b<=Ge;b++){let R=k[p*M+b];if(_t+=R,R>=248&&Tt++,W++,b>=1&&b<M-1&&p>=1&&p<_-1){let F=k[p*M+b-1]+k[p*M+b+1]+k[(p-1)*M+b]+k[(p+1)*M+b]-4*R;Rt+=F,Ft+=F*F,H++}}let Ne=W>0?_t/W:0,Ct=W>0?Tt/W:0,At=H>0?Rt/H:0,Qe=H>0?Math.max(0,Ft/H-At*At):0,K=new Float64Array(M),V=new Float64Array(_);for(let p=0;p<_;p++)for(let b=1;b<M-1;b++)K[b]=K[b]+Math.abs(k[p*M+b+1]-k[p*M+b-1]);for(let p=1;p<_-1;p++)for(let b=0;b<M;b++)V[p]=V[p]+Math.abs(k[(p+1)*M+b]-k[(p-1)*M+b]);let I=at(K,!0,T,o),P=at(K,!1,A,o),G=at(V,!0,B,o),z=at(V,!1,U,o),Et=(P.position-I.position)/Dt,Lt=(z.position-G.position)/wt,Be=Lt>0?Et/Lt:0,Ue=((I.position+P.position)/2-(T+A)/2)/Dt,We=((G.position+z.position)/2-(B+U)/2)/wt,Ot=Re(K),It=Re(V),He=Ot<=0||It<=0?0:Math.min(Math.min(I.value,P.value)/Ot,Math.min(G.value,z.value)/It),$=(p,b)=>b+(p+.5)*D,Pt=Ct,Gt=0;{let p=(P.position-I.position)*.06,b=(z.position-G.position)*.06,R=y(Math.ceil(I.position+p),0,M-1),F=y(Math.floor(P.position-p),0,M-1),Ke=y(Math.ceil(G.position+b),0,_-1),zt=y(Math.floor(z.position-b),0,_-1),Nt=0,tt=0,Qt=0;for(let N=Ke;N<=zt;N++)for(let Q=R;Q<=F;Q++){tt++;let X=k[N*M+Q];X>=248&&Nt++;let Ve=Q+2<=F?k[N*M+Q+2]:X,Xe=N+2<=zt?k[(N+2)*M+Q]:X;(Math.abs(Ve-X)>=24||Math.abs(Xe-X)>=24)&&Qt++}tt>=16&&(Pt=Nt/tt,Gt=Qt/tt)}return{brightness:Ne,glare:Ct,cardGlare:Pt,sharpness:Qe,fill:Et,shape:Be,content:Gt,offsetX:Ue,offsetY:We,edgeConfidence:He,box:{left:$(I.position,x),right:$(P.position,x),top:$(G.position,w),bottom:$(z.position,w)}}}function at(i,t,e,o){let n=i.length,s=Math.max(1,Math.floor(n*.45)),r=t?1:Math.max(1,n-1-s),c=t?Math.min(n-2,s):n-2,a=r;for(let h=r;h<=c;h++)i[h]>i[a]&&(a=h);if(o>0&&o<1){let h=i[a]*o,f=a,g=Math.abs(a-e);for(let y=r;y<=c;y++){let x=i[y];if(x<h||x<(i[y-1]??0)||x<(i[y+1]??0))continue;let w=Math.abs(y-e);w<g&&(f=y,g=w)}a=f}let l=a>0?i[a-1]:0,u=i[a],d=a<n-1?i[a+1]:0,m=l+u+d;return{position:m>0?a+(d-l)/m:a,value:u}}function Re(i){if(i.length<3)return 0;let t=0;for(let e=1;e<i.length-1;e++)t+=i[e];return t/(i.length-2)}function Ae(i){let t=i.box;return t===null||t.right-t.left<4||t.bottom-t.top<4?null:{topLeft:{x:t.left,y:t.top},topRight:{x:t.right,y:t.top},bottomRight:{x:t.right,y:t.bottom},bottomLeft:{x:t.left,y:t.bottom}}}var J=Object.freeze({fillMin:.82,fillMax:1.06,offsetMax:.06,glareMax:.025,sharpnessMin:180,edgeConfidenceMin:1.6,darkBrightness:70,lockMs:450,steadyMs:900,steadyFillMin:.45,steadyFillMax:1.3,steadyFillDelta:.06,steadyOffsetDelta:.04,steadyRefMs:100,edgePeakFrac:.4,shapeTolerance:.2,contentMin:.1});function Oi(i){let t=i!==null&&typeof i=="object"?i:{},e={...J};for(let o of Object.keys(J)){let n=t[o];typeof n=="number"&&Number.isFinite(n)&&n>=0&&n<=1e6&&(e[o]=n)}return e}var ct=class{constructor(t=J){this.t=t;this.goodSince=null;this.steadySince=null;this.last=null}reset(){this.goodSince=null,this.steadySince=null,this.last=null}tick(t,e){let o=this.t,n=o.shapeTolerance<=0||Math.abs(t.shape-1)<=o.shapeTolerance,s=t.edgeConfidence>=o.edgeConfidenceMin&&n&&t.content>=o.contentMin,r=t.fill>=o.fillMin&&t.fill<=o.fillMax,c=Math.abs(t.offsetX)<=o.offsetMax&&Math.abs(t.offsetY)<=o.offsetMax,a=t.cardGlare<=o.glareMax,l=t.sharpness>=o.sharpnessMin,u=this.last;this.last={fill:t.fill,offsetX:t.offsetX,offsetY:t.offsetY,at:e};let d=u!==null&&o.steadyRefMs>0?Math.min(3,Math.max(1,(e-u.at)/o.steadyRefMs)):1,m=s&&a&&l&&t.fill>=o.steadyFillMin&&t.fill<=o.steadyFillMax&&u!==null&&Math.abs(t.fill-u.fill)<=o.steadyFillDelta*d&&Math.abs(t.offsetX-u.offsetX)<=o.steadyOffsetDelta*d&&Math.abs(t.offsetY-u.offsetY)<=o.steadyOffsetDelta*d,h=s&&r&&c&&a&&l,f;if(s?a?t.fill<o.fillMin?f="too_small":t.fill>o.fillMax?f="too_big":l?c?f="locking":f="off_center":f="blurry":f="glare":f="no_card",h){if(m&&(this.steadySince??(this.steadySince=e)),this.goodSince??(this.goodSince=e),e-this.goodSince>=o.lockMs)return{detected:s,ready:!0,via:"good",blocker:"locking"};let g=this.steadySince!==null&&e-this.steadySince>=o.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:"locking"}}if(this.goodSince=null,m){this.steadySince??(this.steadySince=e);let g=e-this.steadySince>=o.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:g?"locking":"steadying"}}return this.steadySince=null,{detected:s,ready:!1,via:null,blocker:f}}};var q=null;async function ai(i){return q===null&&(q=(await import("./detector-scanic-JC25DD3A.js")).detectQuad),q(i)}async function ci(i){let t=te(i);return t===null?null:{topLeft:{x:t.x,y:t.y},topRight:{x:t.x+t.width,y:t.y},bottomRight:{x:t.x+t.width,y:t.y+t.height},bottomLeft:{x:t.x,y:t.y+t.height}}}function Ji(){q===null&&import("./detector-scanic-JC25DD3A.js").then(i=>{q=i.detectQuad}).catch(()=>{})}var Ee=4e3,li=2,Le=3,ui=Object.freeze({LOW:3,MID:5,HIGH:6}),xt=Object.freeze({manualShutterMs:6e3,detectedNoLockMs:1950});function qi(i){let t=i!==null&&typeof i=="object"?i:{},e=(o,n,s)=>typeof o=="number"&&Number.isFinite(o)&&o>=n&&o<=s?o:void 0;return{manualShutterMs:e(t.manualShutterMs,1e3,6e4)??xt.manualShutterMs,detectedNoLockMs:e(t.steadyMs,300,3e4)!==void 0?t.steadyMs+(e(t.lockMs,0,1e4)??450):xt.detectedNoLockMs}}var Oe=class i{constructor(t){this.torchOn=!1;this.stillRefusals=0;this.zoom=1;this.positioningSince=null;this.detectedSince=null;this.lastSeenAt=null;this.lastGuideQuad=null;this.lastOcrReady=null;this.shutterOffered=!1;this.stats=i.freshStats();this.handlers=new Map;this.stream=null;this.timer=null;this.state="idle";this.lastGuidance=null;this.attempt=0;this.capturing=!1;this.feedback=new ot;this.lastFeedbackKey=null;this.lastQuad=null;this.lastDetect=null;this.frameWatch=null;this.reopened=!1;this.lit=!1;this.blackTicks=0;this.offEnded=null;this.opts=t,this.gate=new ne(t.format??"ID-1",t.thresholds);let e=t.deviceClass??jt(Xt());this.deviceClass=e,this.camera=t.camera??st,this.shutterTuning=t.shutter??xt,this.guideTuning=t.guideLock??J,this.guideLock=new ct(this.guideTuning),this.cadenceMs=1e3/ui[e]}on(t,e){let o=this.handlers.get(t);return o||(o=new Set,this.handlers.set(t,o)),o.add(e),()=>o?.delete(e)}emit(t,e){for(let o of[...this.handlers.get(t)??[]])o(e)}async start(){let t=this.state==="error"?this.resumePlayback():null,e=++this.attempt;if(this.clearFrameWatch(),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.lit=!1,this.blackTicks=0,t!==null&&await t&&e===this.attempt){this.setState("positioning"),this.scheduleTick(e),this.watchFrames(e);return}if(e===this.attempt){this.releaseStream(),Kt(),this.setState("preflight");try{let o=this.opts.getUserMedia??(r=>navigator.mediaDevices.getUserMedia(r));this.setState("acquiring");let n=this.opts.enumerateDevices??(this.opts.getUserMedia===void 0&&typeof navigator<"u"&&navigator.mediaDevices?.enumerateDevices?()=>navigator.mediaDevices.enumerateDevices():void 0),s=await Te({getUserMedia:o,...n!==void 0?{enumerateDevices:n}:{},lensSelection:this.camera.lensSelection,base:ue});if(e!==this.attempt){for(let r of s.stream.getTracks())r.stop();return}if(this.stream=s.stream,Wt(this.stream),Ht(this.stream),this.watchEnded(e),this.opts.upgradeResolution!==!1&&await this.upgradeResolution(),e!==this.attempt||(await this.applyFocusAndZoom(),e!==this.attempt)||(this.opts.video.srcObject=this.stream,await this.opts.video.play().catch(()=>{}),e!==this.attempt))return;this.setState("positioning"),this.scheduleTick(e),this.watchFrames(e)}catch(o){if(e!==this.attempt)return;let n=Ut(o),s=Bt(o);this.setState("error"),this.emit("error",{kind:n,retryable:!0,detail:s===void 0?{phase:"acquiring"}:{phase:"acquiring",name:s}})}}}resumePlayback(){let t=this.opts.video,e=this.videoTrack();if(this.stream===null||e===null||e.readyState!=="live"||t.srcObject!==this.stream)return null;try{return Promise.resolve(t.play()).then(()=>this.framesNow(),()=>!1)}catch{return null}}framesNow(){let t=this.opts.video;return this.opts.hasFrames!==void 0?this.opts.hasFrames(t):!t.paused&&t.readyState>=2&&t.videoWidth>0}watchFrames(t){let e=this.opts.firstFrameMs??Ee;e<=0||(this.clearFrameWatch(),this.frameWatch=setTimeout(()=>{if(this.frameWatch=null,!(t!==this.attempt||this.state!=="positioning")){if(this.framesNow()&&this.blackTicks<Le){this.reopened=!1;return}this.cameraDead(t)}},e))}clearFrameWatch(){this.frameWatch!==null&&clearTimeout(this.frameWatch),this.frameWatch=null}watchEnded(t){this.offEnded?.(),this.offEnded=null;let e=this.videoTrack();if(e===null||typeof e.addEventListener!="function")return;let o=()=>{t===this.attempt&&(this.state==="positioning"||this.state==="acquiring")&&this.cameraDead(t)};e.addEventListener("ended",o),this.offEnded=()=>e.removeEventListener?.("ended",o)}cameraDead(t){if(t!==this.attempt)return;let e=this.videoTrack(),o=e!==null&&e.readyState==="live"&&!e.muted&&this.opts.video.paused&&!this.framesNow();if(!o&&!this.reopened){this.reopened=!0,this.start();return}this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.clearFrameWatch(),o||this.releaseStream(),this.reopened=!1,this.setState("error"),this.emit("error",{kind:"generic",retryable:!0,detail:{phase:"acquiring"}})}releaseStream(){if(this.offEnded?.(),this.offEnded=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject!==null&&this.opts.video.srcObject!==void 0&&(this.opts.video.srcObject=null)}rearm(t){t!==void 0&&(this.opts.side=t),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.stillRefusals=0,this.state==="captured"&&(this.setState("positioning"),this.scheduleTick(this.attempt))}async captureNow(){if(this.state!=="positioning"||this.capturing)return;let t=this.opts.video,e=this.lastDetect?.width??Math.max(1,t.videoWidth),o=this.lastDetect?.height??Math.max(1,t.videoHeight),n=this.lastQuad??this.lastGuideQuad??{topLeft:{x:0,y:0},topRight:{x:e,y:0},bottomRight:{x:e,y:o},bottomLeft:{x:0,y:o}},s=(this.opts.now??(()=>performance.now()))(),r=this.feedback.force("processing",s);this.lastFeedbackKey=r.key,this.emit("feedback",r),await this.fire(this.attempt,this.lastOcrReady!==null?this.lastOcrReady.quad:n,{width:e,height:o,tickSharpness:this.lastDetect?.tickSharpness??0},this.lastOcrReady?.via??"manual")}captureReport(){let t=this.stats;return{...this.opts.side!==void 0?{side:this.opts.side}:{},format:this.opts.format??"ID-1",deviceClass:this.deviceClass,video:{width:this.opts.video.videoWidth||0,height:this.opts.video.videoHeight||0},zoom:this.zoom,...t.zoomFallbackAtMs!==void 0?{zoomFallbackAtMs:t.zoomFallbackAtMs}:{},...t.msToCapture!==void 0?{msToCapture:t.msToCapture}:{},...t.via!==void 0?{via:t.via}:{},...t.shutterAtMs!==void 0?{shutterAtMs:t.shutterAtMs}:{},...t.shutterReason!==void 0?{shutterReason:t.shutterReason}:{},ticks:t.ticks,quadFraming:{...t.quadFraming},qualityBlockers:{...t.qualityBlockers},guideBlockers:{...t.guideBlockers},stillRefusals:t.stillRefusals,...this.ocrReport()}}ocrReport(){let t=this.opts.ocr;if(t===void 0)return{};let e=(this.opts.format??"ID-1")==="ID-3"||this.opts.side==="single"?"single":this.opts.side==="verso"?"verso":"recto",o=t.report(e,this.stats.via,(this.opts.now??(()=>performance.now()))());return o===null?{}:{ocr:o}}static freshStats(){return{ticks:0,quadFraming:{},qualityBlockers:{},guideBlockers:{},stillRefusals:0}}setGuide(t){t===void 0?delete this.opts.guide:this.opts.guide=t,this.guideLock.reset()}guideRegion(t){let e=t.width/Math.max(1,t.height),o=this.opts.guide;if(o!==void 0&&o.viewAspect>0){let c={width:o.viewAspect,height:1},a={x:o.rect.x*o.viewAspect,y:o.rect.y,width:o.rect.width*o.viewAspect,height:o.rect.height};return Fe(c,a,e,0)}let n=Zt(this.opts.format??"ID-1").center,s=.86,r=s*e/n;return r>.84&&(r=.84,s=r*n/e),{x:(1-s)/2,y:(1-r)/2,width:s,height:r}}resetSide(){this.positioningSince=null,this.detectedSince=null,this.lastSeenAt=null,this.guideLock.reset(),this.lastGuideQuad=null,this.lastOcrReady=null,this.opts.ocr?.reset(),this.stats=i.freshStats(),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}withdrawShutter(){this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}zoomFallback(t){let e=this.videoTrack();if(e===null||this.zoom<=1)return;let o=this.focusCaps(),n=typeof o?.zoom?.min=="number"?Math.max(o.zoom.min,1):1;this.zoom=n,this.stats.zoomFallbackAtMs=Math.round(t-(this.positioningSince??t)),this.guideLock.reset(),this.gate.reset(),e.applyConstraints({advanced:[{zoom:n}]}).catch(()=>{})}offerShutter(t,e){this.shutterOffered||(this.shutterOffered=!0,this.stats.shutterAtMs=Math.round(e-(this.positioningSince??e)),this.stats.shutterReason=t,this.emit("shutter",{available:!0,reason:t}))}torchAvailable(){try{return this.stream?.getVideoTracks?.()[0]?.getCapabilities?.()?.torch===!0}catch{return!1}}async setTorch(t){this.torchOn=t;try{await this.stream?.getVideoTracks?.()[0]?.applyConstraints({advanced:[{torch:t}]})}catch{}}destroy(){if(this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.clearFrameWatch(),this.offEnded?.(),this.offEnded=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject=null}async upgradeResolution(){try{let t=this.stream?.getVideoTracks?.()[0];if(t===void 0)return;let e=t.getSettings?.()??{},o=me(t.getCapabilities?.(),{width:e.width??0,height:e.height??0},this.deviceClass,{width:this.camera.width,height:this.camera.height},this.opts.ocr?.liveMrzOn===!0?{fill:this.guideRegion({width:1080,height:1920}).width}:void 0);o!==null&&await t.applyConstraints(o)}catch{}}focusCaps(){try{return this.videoTrack()?.getCapabilities?.()??null}catch{return null}}async applyFocusAndZoom(){let t=this.videoTrack();if(t===null)return;let e=this.focusCaps();this.camera.continuousFocus&&rt(e,"continuous")&&await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{});let o={width:0,height:0};try{let s=t.getSettings?.()??{};o={width:s.width??0,height:s.height??0}}catch{}let n=_e(e,o,this.opts.format??"ID-1",this.camera);if(n>1)try{await t.applyConstraints({advanced:[{zoom:n}]}),this.zoom=n}catch{this.zoom=1}}async focusAt(t,e){let o=this.videoTrack(),n=kt(this.focusCaps(),t,e);if(!(o===null||n===null))try{await o.applyConstraints({advanced:[n]}),(this.opts.setTimer??setTimeout)(()=>{this.restoreContinuous()},1500)}catch{}}async restoreContinuous(){let t=this.videoTrack();t===null||!this.camera.continuousFocus||!rt(this.focusCaps(),"continuous")||await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})}async refocusOn(t,e){let o=this.camera.refocusBeforePhotoMs,n=this.videoTrack();if(o<=0||n===null||e.width<=0||e.height<=0)return;let s=E(t),r=kt(this.focusCaps(),(s.x+s.width/2)/e.width,(s.y+s.height/2)/e.height);if(r!==null)try{await n.applyConstraints({advanced:[r]});let c=this.opts.setTimer??setTimeout;await new Promise(a=>{c(()=>a(),o)})}catch{}}videoTrack(){try{return this.stream?.getVideoTracks?.()[0]??null}catch{return null}}async takeStill(t,e,o){if(this.opts.captureStill!==void 0)return this.opts.captureStill(this.opts.video,t,e);let n=this.opts.format??"ID-1",s=this.videoTrack();if(o&&this.opts.photoCapture!==!1&&this.deviceClass!=="LOW"&&!this.torchOn&&s!==null&&ke(s)){await this.refocusOn(t,e);let r=await we(this.opts.video,t,e,n,{track:s,detect:this.detector(),detectWidth:et});if(this.restoreContinuous(),r!==null)return r}return De(this.opts.video,t,e,n)}detector(){return this.opts.detect??((this.opts.format??"ID-1")==="ID-3"?ci:ai)}setState(t){this.state=t,this.emit("statechange",{state:t})}scheduleTick(t){let e=this.opts.setTimer??setTimeout;this.timer=e(()=>{this.tick(t)},this.cadenceMs)}async tick(t){if(t!==this.attempt||this.state!=="positioning"||this.capturing)return;let e=this.opts.now??(()=>performance.now()),o=this.opts.grabDetectFrame??Pe,n=this.detector(),s=o(this.opts.video,et);if(s===null){this.scheduleTick(t);return}if(!this.lit){if(dt(s)>li)this.lit=!0,this.blackTicks=0;else if(++this.blackTicks>=Le&&this.frameWatch===null&&(this.opts.firstFrameMs??Ee)>0){this.cameraDead(t);return}}let r=null;try{r=await n(s)}catch{r=null}if(t!==this.attempt)return;let c=r!==null?lt(s,r):s,a=e(),l={sharpness:j(c),exposure:Yt(c),meanLuma:dt(c),specularFraction:ae(c)},u=ce({format:this.opts.format??"ID-1",quad:r,frameWidth:s.width,frameHeight:s.height,measures:l,...this.opts.thresholds!==void 0?{thresholds:this.opts.thresholds}:{}}),d=this.gate.tick({timestampMs:a,quad:r,quality:l,frameWidth:s.width,frameHeight:s.height}),h=(this.opts.format??"ID-1")!=="ID-3"?Ce(s,this.guideRegion(s),{edgePeakFrac:this.guideTuning.edgePeakFrac}):Z,f=this.guideLock.tick(h,a);this.lastGuideQuad=f.detected?Ae(h):null;let g=this.capturing?null:this.ocrTick(s,r,h,f.detected,u,a);this.positioningSince??(this.positioningSince=a);let y=this.stats;if(y.ticks+=1,y.quadFraming[u.framing]=(y.quadFraming[u.framing]??0)+1,u.framing==="ok"&&!d.ready){let T=u.lighting!=="ok"?u.lighting:u.glare!=="ok"?"glare":u.blur!=="ok"?"blurry":"steadying";y.qualityBlockers[T]=(y.qualityBlockers[T]??0)+1}y.guideBlockers[f.blocker]=(y.guideBlockers[f.blocker]??0)+1,r!==null||f.detected?(this.detectedSince??(this.detectedSince=a),this.lastSeenAt=a):this.detectedSince=null,this.lastSeenAt!==null&&a-this.lastSeenAt<=bi?a-this.positioningSince>=this.shutterTuning.manualShutterMs?this.offerShutter("timeout",a):g?.suspendQuality!==!0&&this.detectedSince!==null&&a-this.detectedSince>=this.shutterTuning.detectedNoLockMs&&this.offerShutter("detected_no_lock",a):this.withdrawShutter();let O=a-(this.lastSeenAt??this.positioningSince);this.zoom>1&&this.camera.zoomFallbackMs>0&&O>=this.camera.zoomFallbackMs&&this.zoomFallback(a),this.emit("checks",{engine:"docv1",p:d.p,plausible:d.plausible,stableTicks:d.stableTicks,quad:d.quad,frameWidth:s.width,frameHeight:s.height,analysis:u,ready:g?.suspendQuality!==!0&&(d.ready&&r!==null||f.ready&&this.lastGuideQuad!==null)||this.lastOcrReady!==null,guide:{detected:f.detected,blocker:f.blocker,fill:h.fill,shape:h.shape,content:h.content,offsetX:h.offsetX,offsetY:h.offsetY},...g!==null&&g.mode!=="off"?{ocr:{mode:g.mode,...g.mrz?{mrz:g.mrz}:{},...g.lock?{lock:g.lock}:{}}}:g?.mrz?{ocr:{mode:g.mode,mrz:g.mrz}}:{}}),this.lastQuad=d.plausible?r:null,this.lastDetect={width:s.width,height:s.height,tickSharpness:l.sharpness};let v=se(u);u.framing!=="ok"&&f.detected&&(v=gi(f.blocker,h.brightness<this.guideTuning.darkBrightness)),v==="blurry"&&r!==null&&di(r,s,this.opts.format??"ID-1")>=this.camera.focusFarFillFrac&&(v="focus_far"),v==="sensing"&&this.zoom>1&&this.camera.noDocFarHintMs>0&&O>=this.camera.noDocFarHintMs&&(v="focus_far");let D=this.feedback.tick(v,a);if(D.key!==this.lastFeedbackKey&&(this.lastFeedbackKey=D.key,this.emit("feedback",D)),d.guidanceKey!==this.lastGuidance&&(this.lastGuidance=d.guidanceKey,this.emit("guidance",{key:d.guidanceKey})),this.capturing)return;let M=g?.suspendQuality!==!0,_=M&&d.ready&&r!==null,k=M&&f.ready&&this.lastGuideQuad!==null,C=this.lastOcrReady;if(C!==null&&this.opts.autoCapture!==!1){let T=this.feedback.force("processing",a);this.lastFeedbackKey=T.key,this.emit("feedback",T);let A=j(lt(s,C.quad));await this.fire(t,C.quad,{width:s.width,height:s.height,tickSharpness:A},C.via);return}if((_||k)&&this.opts.autoCapture!==!1){let T=this.feedback.force("processing",a);this.lastFeedbackKey=T.key,this.emit("feedback",T);let A=k?this.lastGuideQuad:r,B=k?f.via==="steady"?"guide_steady":"guide_good":"quad",U=k?j(lt(s,A)):l.sharpness;await this.fire(t,A,{width:s.width,height:s.height,tickSharpness:U},B);return}this.scheduleTick(t)}async fire(t,e,o,n){this.capturing=!0;let s=this.opts.grabDetectFrame??Pe,r=this.opts.setTimer??setTimeout,c={width:o.width,height:o.height};try{let a={still:await this.takeStill(e,c,!0),sharpness:o.tickSharpness};if(t!==this.attempt)return;let l=a.still.source==="photo"||this.deviceClass==="LOW"?0:mi;for(let m=0;m<l;m++){if(await new Promise(g=>{r(()=>g(),fi)}),t!==this.attempt)return;let h=s(this.opts.video,et);if(h===null)continue;let f=j(lt(h,e));if(f>a.sharpness*pi){let g=await this.takeStill(e,c,!1);if(t!==this.attempt)return;a={still:g,sharpness:f}}}if(t!==this.attempt)return;let u=a.still.sharpness;if(this.opts.autoCapture!==!1&&n!=="manual"&&typeof u=="number"&&u>=0&&u<this.camera.stillSharpnessMin&&this.stillRefusals<this.camera.stillRefusalsMax){this.stillRefusals+=1,this.stats.stillRefusals+=1,this.guideLock.reset(),this.lastOcrReady=null,(n==="text_lock"||n==="live_mrz")&&this.opts.ocr?.rearmFace();let m=(this.opts.now??(()=>performance.now()))(),h=this.feedback.force("focus_far",m);this.lastFeedbackKey=h.key,this.emit("feedback",h),this.capturing=!1,this.gate.reset(),this.scheduleTick(t);return}this.stillRefusals=0;let d=(this.opts.now??(()=>performance.now()))();this.stats.via=n,this.stats.msToCapture=Math.round(d-(this.positioningSince??d)),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1})),this.setState("captured"),this.emit("artifacts",{keyframe:a.still.blob,previewDataUrl:a.still.previewDataUrl,...this.opts.side!==void 0?{side:this.opts.side}:{},...a.still.docRegion!==void 0?{docRegion:a.still.docRegion}:{},...(()=>{let m=n==="live_mrz"?this.opts.ocr?.liveCapture():null;return m?{liveMrz:m}:{}})()})}catch{if(t!==this.attempt)return;this.capturing=!1,this.gate.reset(),this.guideLock.reset(),this.lastOcrReady=null,(n==="text_lock"||n==="live_mrz")&&this.opts.ocr?.rearmFace(),this.scheduleTick(t)}}ocrTick(t,e,o,n,s,r){let c=this.opts.ocr,a=this.opts.video;if(c===void 0||!c.hasEngine)return this.lastOcrReady=null,null;let l=a.videoWidth,u=a.videoHeight;if(l<=0||u<=0||t.width<=0||t.height<=0)return null;let m=(this.opts.format??"ID-1")==="ID-3",h=this.guideRegion(t),f={x:h.x*l,y:h.y*u,w:h.width*l,h:h.height*u},g=l/t.width,y=u/t.height,x;m&&e!==null?x=hi(E(e),g,y,l,u):x=ee(f,c.bandTop,u);let w=m?s.glare==="ok":o.cardGlare<=this.guideTuning.glareMax,O=m?s.blur==="ok":o.sharpness>=this.guideTuning.sharpnessMin,v=c.tick({atMs:r,video:a,mrzFace:m||this.opts.side==="verso"||this.opts.side==="single",present:m||e!==null||n,card:f,band:x,portrait:u>l,glareOk:w,sharpOk:O});if(v.ready&&v.via!==void 0){let D=m?e??Ie(h,t):this.lastGuideQuad??Ie(h,t);this.lastOcrReady={quad:D,via:v.via}}else this.lastOcrReady=null;return v}};function hi(i,t,e,o,n){let s=Math.min(o,i.width*1.06*t),r=Math.min(n,Math.max(i.height*1.6*e,s/5)),c=(i.y+i.height/2)*e,a=Math.max(0,Math.min(o-s,(i.x-i.width*.03)*t)),l=Math.max(0,Math.min(n-r,c-r/2));return{x:a,y:l,w:s,h:r}}function Ie(i,t){let e=i.x*t.width,o=i.y*t.height,n=(i.x+i.width)*t.width,s=(i.y+i.height)*t.height;return{topLeft:{x:e,y:o},topRight:{x:n,y:o},bottomRight:{x:n,y:s},bottomLeft:{x:e,y:s}}}function di(i,t,e){let o=E(i);return t.width<=0||t.height<=0?0:e==="ID-3"?o.width/t.width:o.width*o.height/(t.width*t.height)}var mi=2,fi=260,pi=1.08;function Pe(i,t){let e=i.videoWidth,o=i.videoHeight;if(e===0||o===0)return null;let n=Math.min(1,t/e),s=Math.round(e*n),r=Math.round(o*n),c=document.createElement("canvas");c.width=s,c.height=r;let a=c.getContext("2d",{willReadFrequently:!0});return a===null?null:(e/Math.max(1,s)>4&&(a.imageSmoothingQuality="high"),a.drawImage(i,0,0,s,r),a.getImageData(0,0,s,r))}function lt(i,t){let e=[t.topLeft.x,t.topRight.x,t.bottomRight.x,t.bottomLeft.x],o=[t.topLeft.y,t.topRight.y,t.bottomRight.y,t.bottomLeft.y],n=Math.max(0,Math.floor(Math.min(...e))),s=Math.max(0,Math.floor(Math.min(...o))),r=Math.min(i.width,Math.ceil(Math.max(...e))),c=Math.min(i.height,Math.ceil(Math.max(...o))),a=Math.max(1,r-n),l=Math.max(1,c-s),u=new Uint8ClampedArray(a*l*4);for(let d=0;d<l;d++){let m=((s+d)*i.width+n)*4;u.set(i.data.subarray(m,m+a*4),d*a*4)}return{data:u,width:a,height:l,colorSpace:i.colorSpace}}function gi(i,t){return i==="glare"?"glare":i==="too_small"?"too_far":i==="too_big"?"too_close":t?"too_dark":i==="blurry"?"blurry":i==="off_center"?"edge_clipped":i==="no_card"?"sensing":"hold_still"}var bi=1200;export{it as a,se as b,ot as c,je as d,ae as e,Ye as f,ce as g,st as h,Ri as i,yt as j,si as k,ve as l,rt as m,kt as n,Ci as o,_e as p,ri as q,Te as r,Z as s,Fe as t,Ce as u,Ae as v,J as w,Oi as x,ct as y,Ji as z,Ee as A,li as B,Le as C,ui as D,xt as E,qi as F,Oe as G,hi as H,mi as I,fi as J};
1
+ import{d as qt,h as $t,k as ee}from"./chunk-MQHTFHSN.js";import{b as te}from"./chunk-SMKCBUJL.js";import{a as et,b as ie,c as oe,e as mt,f as ne}from"./chunk-3WQJI7UL.js";import{c as Zt,d as Jt}from"./chunk-BRLQIJYF.js";import{b as Xt,c as jt}from"./chunk-POIQGEZM.js";import{k as Bt,m as Ut,n as Ht,o as Kt,p as Vt,r as ut}from"./chunk-CPUECYAJ.js";import{b as ht,c as dt,d as j,e as Yt}from"./chunk-FPXL63KZ.js";import{d as Wt}from"./chunk-HMOOVRKA.js";var it=Object.freeze({sensing:{key:"sensing",reticle:"searching",minDurationMs:900},too_far:{key:"too_far",reticle:"coaching",minDurationMs:1400},too_close:{key:"too_close",reticle:"coaching",minDurationMs:1400},edge_clipped:{key:"edge_clipped",reticle:"coaching",minDurationMs:1400},wrong_shape:{key:"wrong_shape",reticle:"coaching",minDurationMs:1400},tilted:{key:"tilted",reticle:"coaching",minDurationMs:1400},too_dark:{key:"too_dark",reticle:"coaching",minDurationMs:1400},too_bright:{key:"too_bright",reticle:"coaching",minDurationMs:1400},blurry:{key:"blurry",reticle:"coaching",minDurationMs:1400},focus_far:{key:"focus_far",reticle:"coaching",minDurationMs:1600},glare:{key:"glare",reticle:"coaching",minDurationMs:1400},hold_still:{key:"hold_still",reticle:"locking",minDurationMs:900},processing:{key:"processing",reticle:"processing",minDurationMs:800},side_captured:{key:"side_captured",reticle:"flip",minDurationMs:2600},captured:{key:"captured",reticle:"done",minDurationMs:800}});function se(i){return i.framing==="no_document"?"sensing":i.framing==="too_far"?"too_far":i.framing==="too_close"?"too_close":i.framing==="edge_clipped"?"edge_clipped":i.framing==="wrong_shape"?"wrong_shape":i.framing==="tilted"?"tilted":i.lighting==="too_dark"?"too_dark":i.lighting==="too_bright"?"too_bright":i.glare==="glare"?"glare":i.blur==="blurry"?"blurry":"hold_still"}var ot=class{constructor(t=2600,e=.35){this.windowMs=t;this.decayPerSecond=e;this.votes=[];this.current=it.sensing;this.currentSinceMs=null}reset(){this.votes=[],this.current=it.sensing,this.currentSinceMs=null}force(t,e){return this.votes=[],this.current=it[t],this.currentSinceMs=e,this.current}tick(t,e){if(this.currentSinceMs===null&&(this.currentSinceMs=e),this.votes.push({key:t,atMs:e}),this.votes=this.votes.filter(r=>e-r.atMs<=this.windowMs),e-this.currentSinceMs<this.current.minDurationMs)return this.current;let o=new Map;for(let r of this.votes){let c=(e-r.atMs)/1e3,a=this.decayPerSecond**c;o.set(r.key,(o.get(r.key)??0)+a)}let n=this.current.key,s=-1;for(let[r,c]of o)c>s&&(s=c,n=r);return n!==this.current.key&&(this.current=it[n],this.currentSinceMs=e),this.current}};var je=Object.freeze({MAX_AREA_FRAC:.92,TILT_MAX_SIDE_RATIO:1.3,GLARE_MAX_SPECULAR_FRAC:.025});function ae(i){let{data:t,width:e,height:o}=i,n=e*o;if(n===0)return 0;let s=0;for(let r=0;r<n;r++){let c=r*4;.299*(t[c]??0)+.587*(t[c+1]??0)+.114*(t[c+2]??0)>=252&&s++}return s/n}function Ye(i){let t=(a,l)=>Math.hypot(l.x-a.x,l.y-a.y),e=t(i.topLeft,i.topRight),o=t(i.bottomLeft,i.bottomRight),n=t(i.topLeft,i.bottomLeft),s=t(i.topRight,i.bottomRight),r=Math.max(e,o)/Math.max(1e-6,Math.min(e,o)),c=Math.max(n,s)/Math.max(1e-6,Math.min(n,s));return Math.max(r,c)}function ce(i){let t={...ie,...i.thresholds},e=je,{quad:o,frameWidth:n,frameHeight:s,measures:r}=i,c=i.format==="ID-3",a="ok";if(o===null)a="no_document";else if(c){let m=mt(o),h=n>0?m.width/n:0,f=m.height>0?m.width/m.height:0;h<t.ID3_BAND_MIN_WIDTH_FRAC?a="too_far":re(o,n,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":(f<t.ID3_BAND_ASPECT_MIN||f>t.ID3_BAND_ASPECT_MAX)&&(a="wrong_shape")}else{let m=oe(o,n,s),h=mt(o),f=Math.max(h.width,h.height)/Math.max(1e-6,Math.min(h.width,h.height));m<t.MIN_AREA_FRAC?a="too_far":m>e.MAX_AREA_FRAC?a="too_close":re(o,n,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":Jt(i.format,f)?Ye(o)>e.TILT_MAX_SIDE_RATIO&&(a="tilted"):a="wrong_shape"}let l=r.exposure>=t.GUIDE_EXPOSURE?"ok":r.meanLuma<(ht[0]+ht[1])/2?"too_dark":"too_bright",u=r.sharpness>=t.GUIDE_SHARPNESS?"ok":"blurry",d=r.specularFraction>=e.GLARE_MAX_SPECULAR_FRAC?"glare":"ok";return{framing:a,lighting:l,blur:u,glare:d,acceptable:a==="ok"&&l==="ok"&&u==="ok"&&d==="ok"}}function re(i,t,e,o){return[i.topLeft,i.topRight,i.bottomRight,i.bottomLeft].some(s=>s.x<=o||s.y<=o||s.x>=t-o||s.y>=e-o)}var ue=Object.freeze({width:1920,height:1080}),Ze=Object.freeze({width:3840,height:2160}),le=4096,Je=2560,he=640,nt=.15,Y=Object.freeze({side:.2,above:.9,below:.3});function E(i){let t=[i.topLeft.x,i.topRight.x,i.bottomRight.x,i.bottomLeft.x],e=[i.topLeft.y,i.topRight.y,i.bottomRight.y,i.bottomLeft.y],o=Math.min(...t),n=Math.min(...e);return{x:o,y:n,width:Math.max(...t)-o,height:Math.max(...e)-n}}function de(i,t){let e=Math.max(0,Math.floor(i.x)),o=Math.max(0,Math.floor(i.y)),n=Math.min(t.width,Math.ceil(i.x+i.width)),s=Math.min(t.height,Math.ceil(i.y+i.height));return n-e<16||s-o<16?null:{x:e,y:o,width:n-e,height:s-o}}function qe(i,t,e){if(i===null||t.width<=0||t.height<=0)return null;let o=E(i);if(o.width<=0||o.height<=0)return null;let n=e==="ID-3"?{x:o.x-o.width*Y.side,y:o.y-o.width*Y.above,width:o.width*(1+2*Y.side),height:o.height+o.width*(Y.above+Y.below)}:{x:o.x-o.width*nt,y:o.y-o.height*nt,width:o.width*(1+2*nt),height:o.height*(1+2*nt)};return de(n,t)}function pt(i,t,e){let o=Math.max(i,t);return o>0?Math.min(1,e/o):1}function gt(i,t,e,o,n=Je){let s=t.width>0?e.width/t.width:1,r=t.height>0?e.height/t.height:1,c=i===null?null:{topLeft:{x:i.topLeft.x*s,y:i.topLeft.y*r},topRight:{x:i.topRight.x*s,y:i.topRight.y*r},bottomRight:{x:i.bottomRight.x*s,y:i.bottomRight.y*r},bottomLeft:{x:i.bottomLeft.x*s,y:i.bottomLeft.y*r}},a=qe(c,e,o)??{x:0,y:0,width:e.width,height:e.height},l=pt(a.width,a.height,n),u=Math.max(1,Math.round(a.width*l)),d=Math.max(1,Math.round(a.height*l)),m=null;if(c!==null){let h=E(c);m=de({x:(h.x-a.x)*l,y:(h.y-a.y)*l,width:h.width*l,height:h.height*l},{width:u,height:d})}return{crop:a,width:u,height:d,docRegion:m}}var $e=960,ft=[{width:1920,height:1080},{width:2560,height:1440}];function ti(i){let t=Number.isFinite(i)&&i>0?Math.min(1,i):.85;return ft.find(e=>e.height*t>=$e)??ft[ft.length-1]}function me(i,t,e,o=Ze,n){if(e==="LOW")return null;let s=n===void 0?null:ti(n.fill),r=s!==null&&Math.max(s.width,s.height)>Math.max(o.width,o.height)?s:o,c=i?.width?.max,a=i?.height?.max;if(typeof c!="number"||typeof a!="number"||c<=0||a<=0)return null;let l=Math.max(c,a),u=Math.min(c,a),d=Math.min(l,Math.max(r.width,r.height)),m=Math.min(u,Math.min(r.width,r.height));return d<=Math.max(t.width,t.height)?null:{width:{ideal:d},height:{ideal:m}}}function fe(i){let t={},e=i?.imageWidth,o=i?.imageHeight;if(typeof e?.max=="number"&&e.max>0){let n=typeof o?.max=="number"&&o.max>0?e.max/o.max:1.3333333333333333,s=n>=1?le:le*n,r=Math.min(e.max,Math.floor(s)),c=typeof e.step=="number"&&e.step>0?e.step:1,a=typeof e.min=="number"?e.min:0;r=Math.max(a,a+Math.floor((r-a)/c)*c),t.imageWidth=r}return i?.fillLightMode?.includes("off")===!0&&(t.fillLightMode="off"),t}function pe(i,t){if(i.width<=0||i.height<=0||t.width<=0||t.height<=0)return!1;let e=i.width>i.height,o=t.width>t.height;return e!==o&&i.width!==i.height&&t.width!==t.height?!1:Math.max(i.width,i.height)>=1.2*Math.max(t.width,t.height)}function ge(i,t,e,o){if(e===null)return!1;let n=E(i),s=E(e);if(t.width<=0||o.width<=0)return!1;let r=n.width/t.width,c=s.width/o.width;return c>0&&r>=.6*c&&r<=1.25*c}var be=3500,ei=.92;function Me(){let i=globalThis.ImageCapture;return typeof i=="function"?i:null}function ii(i){return/AppleWebKit\//.test(i)&&!/(Chrome|Chromium|Edg|OPR)\//.test(i)}function ke(i,t=typeof navigator>"u"?"":navigator.userAgent){return Me()!==null&&!ii(t)&&i!=null&&i.kind==="video"&&i.readyState==="live"}function ye(i,t){return new Promise((e,o)=>{let n=setTimeout(()=>o(new Error("takePhoto timed out")),t);i.then(s=>{clearTimeout(n),e(s)},s=>{clearTimeout(n),o(s)})})}function bt(i,t){let e=document.createElement("canvas");return e.width=i,e.height=t,e}function oi(i,t){return new Promise((e,o)=>{i.toBlob(n=>n?e(n):o(new Error("toBlob failed")),"image/jpeg",t)})}async function xe(i,t,e,o,n){let s=bt(e,o),r=bt(1,1);try{let c=s.getContext("2d");if(c===null)throw new Error("2d context unavailable");c.imageSmoothingQuality="high",c.drawImage(i,t.x,t.y,t.width,t.height,0,0,e,o);let a=await oi(s,ei),l=n===null?null:qt({topLeft:{x:n.x,y:n.y},topRight:{x:n.x+n.width,y:n.y},bottomRight:{x:n.x+n.width,y:n.y+n.height},bottomLeft:{x:n.x,y:n.y+n.height}},{width:e,height:o},{width:e,height:o}),u=$t(s,l),d=pt(e,o,he);return r.width=Math.max(1,Math.round(e*d)),r.height=Math.max(1,Math.round(o*d)),r.getContext("2d")?.drawImage(s,0,0,r.width,r.height),{blob:a,previewDataUrl:r.toDataURL("image/jpeg",.85),sharpness:u}}finally{s.width=0,s.height=0,r.width=0,r.height=0}}function ni(i,t){let e=Math.min(1,t/i.width),o=bt(Math.max(1,Math.round(i.width*e)),Math.max(1,Math.round(i.height*e)));try{let n=o.getContext("2d",{willReadFrequently:!0});return n===null?null:(n.imageSmoothingQuality="high",n.drawImage(i,0,0,o.width,o.height),n.getImageData(0,0,o.width,o.height))}finally{o.width=0,o.height=0}}async function De(i,t,e,o){let n={width:Math.max(1,i.videoWidth),height:Math.max(1,i.videoHeight)},s=gt(t,e,n,o);return{...await xe(i,s.crop,s.width,s.height,s.docRegion),docRegion:s.docRegion,source:"video",width:s.width,height:s.height}}async function we(i,t,e,o,n){let s=Me();if(s===null)return null;let r=null;try{let c=new s(n.track),a=await ye(c.getPhotoCapabilities?.()??Promise.resolve({}),be).catch(()=>({})),l=await ye(c.takePhoto(fe(a)),be);r=await createImageBitmap(l);let u={width:i.videoWidth,height:i.videoHeight};if(!pe(r,u))return null;let d=ni(r,n.detectWidth),m=null;d!==null&&t!==null&&(m=await n.detect(d).catch(()=>null));let h=d??{width:r.width,height:r.height};m!==null&&!ge(m,h,t,e)&&(m=null);let f=gt(m,h,r,o);return{...await xe(r,f.crop,f.width,f.height,f.docRegion),docRegion:f.docRegion,source:"photo",width:f.width,height:f.height}}catch{return null}finally{r?.close()}}var st=Object.freeze({width:3840,height:2160,lensSelection:!0,continuousFocus:!0,refocusBeforePhotoMs:350,zoomMax:2,zoomNoFocusInfo:1.5,zoomMinSourcePx:2160,fillDistanceM:Object.freeze({id1:.11,id3:.15}),focusMarginFrac:.2,stillSharpnessMin:.16,stillRefusalsMax:2,focusFarFillFrac:.45,noDocFarHintMs:1500,zoomFallbackMs:8e3}),S=(i,t,e)=>typeof i=="number"&&Number.isFinite(i)&&i>=t&&i<=e?i:void 0;function Ri(i){let t=st,e=i!==null&&typeof i=="object"?i:{},o=e.fillDistanceM!==null&&typeof e.fillDistanceM=="object"?e.fillDistanceM:{},n=(s,r)=>typeof s=="boolean"?s:r;return{width:S(e.width,640,7680)??t.width,height:S(e.height,480,4320)??t.height,lensSelection:n(e.lensSelection,t.lensSelection),continuousFocus:n(e.continuousFocus,t.continuousFocus),refocusBeforePhotoMs:S(e.refocusBeforePhotoMs,0,2e3)??t.refocusBeforePhotoMs,zoomMax:S(e.zoomMax,1,5)??t.zoomMax,zoomNoFocusInfo:S(e.zoomNoFocusInfo,1,5)??t.zoomNoFocusInfo,zoomMinSourcePx:S(e.zoomMinSourcePx,0,8e3)??t.zoomMinSourcePx,fillDistanceM:{id1:S(o.id1,.03,1)??t.fillDistanceM.id1,id3:S(o.id3,.03,1)??t.fillDistanceM.id3},focusMarginFrac:S(e.focusMarginFrac,0,2)??t.focusMarginFrac,stillSharpnessMin:S(e.stillSharpnessMin,0,10)??t.stillSharpnessMin,stillRefusalsMax:S(e.stillRefusalsMax,0,10)??t.stillRefusalsMax,focusFarFillFrac:S(e.focusFarFillFrac,0,1)??t.focusFarFillFrac,noDocFarHintMs:S(e.noDocFarHintMs,0,6e4)??t.noDocFarHintMs,zoomFallbackMs:S(e.zoomFallbackMs,0,12e4)??t.zoomFallbackMs}}var yt="sekyro.doc.camera";function si(){try{let i=globalThis.localStorage?.getItem(yt);return typeof i=="string"&&i!==""?i:null}catch{return null}}function ve(i){try{i===null?globalThis.localStorage?.removeItem(yt):globalThis.localStorage?.setItem(yt,i)}catch{}}var rt=(i,t)=>Array.isArray(i?.focusMode)&&i.focusMode.includes(t);function kt(i,t,e){if(!rt(i,"single-shot"))return null;let o=n=>Math.min(1,Math.max(0,Number.isFinite(n)?n:.5));return{focusMode:"single-shot",pointsOfInterest:[{x:o(t),y:o(e)}]}}function Ci(i,t,e,o){if(!Number.isFinite(i)||!Number.isFinite(t)||e.width<=0||e.height<=0||o.width<=0||o.height<=0)return null;let n=Math.max(e.width/o.width,e.height/o.height),s=o.width*n,r=o.height*n,c=(i-e.left+(s-e.width)/2)/s,a=(t-e.top+(r-e.height)/2)/r;return{x:Math.min(1,Math.max(0,c)),y:Math.min(1,Math.max(0,a))}}function _e(i,t,e,o=st){let n=i?.zoom?.min,s=i?.zoom?.max;if(typeof s!="number"||s<=1)return 1;let r=e==="ID-3"?o.fillDistanceM.id3:o.fillDistanceM.id1,c=i?.focusDistance?.min,a;if(typeof c=="number"&&c>0&&c<1){if(a=c*(1+o.focusMarginFrac)/r,a<=1.05)return 1}else{if(Math.min(t.width,t.height)<o.zoomMinSourcePx)return 1;a=o.zoomNoFocusInfo}let l=Math.min(a,o.zoomMax,s);typeof n=="number"&&(l=Math.max(l,n));let u=i?.zoom?.step;return typeof u=="number"&&u>0&&(l=Math.round(l/u)*u),l>1.01?Number(l.toFixed(2)):1}function Mt(i){try{return i.getVideoTracks?.()[0]}catch{return}}function Se(i){if(i!==null)for(let t of i.getTracks())t.stop()}function ri(i){try{let t=Mt(i)?.getCapabilities?.();return!Array.isArray(t?.focusMode)||t.focusMode.includes("continuous")}catch{return!0}}async function Te(i){let t=s=>({audio:!1,video:{...s,width:{ideal:i.base.width},height:{ideal:i.base.height}}}),e=s=>i.getUserMedia(t({deviceId:{exact:s}})),o=()=>i.getUserMedia(t({facingMode:{ideal:"environment"}}));if(i.lensSelection){let s=si();if(s!==null)try{return{stream:await e(s),lens:"stored"}}catch{ve(null)}}let n=await o();if(!i.lensSelection||i.enumerateDevices===void 0)return{stream:n,lens:"default"};try{let s=ut(await i.enumerateDevices()).slice(0,3);if(s.length===0)return{stream:n,lens:"default"};let r=null;for(let c of s){let a=n!==null?Mt(n)?.getSettings?.().deviceId:void 0;if(n===null||a!==c){Se(n),n=null;try{n=await e(c)}catch{continue}}if(r??(r=c),ri(n))return ve(c),{stream:n,lens:"selected"}}if(n!==null&&r!==null&&Mt(n)?.getSettings?.().deviceId===r)return{stream:n,lens:"selected"};if(Se(n),n=null,r!==null)try{return{stream:await e(r),lens:"selected"}}catch{}return{stream:await o(),lens:"default"}}catch{return{stream:n??await o(),lens:"default"}}}var Z=Object.freeze({brightness:0,glare:0,cardGlare:0,sharpness:0,fill:0,shape:0,content:0,offsetX:0,offsetY:0,edgeConfidence:0,box:null}),L=i=>Math.min(1,Math.max(0,i));function Fe(i,t,e,o=.06){let n=Math.max(i.width/e,i.height),s=n*e,r=(i.width-s)/2,c=(i.height-n)/2,a=L((t.x-t.width*o-r)/s),l=L((t.y-t.height*o-c)/n),u=L((t.x+t.width*(1+o)-r)/s),d=L((t.y+t.height*(1+o)-c)/n);return{x:a,y:l,width:u-a,height:d-l}}function Ce(i,t,e={}){let o=e.edgePeakFrac??0,{width:n,height:s,data:r}=i;if(n<=0||s<=0)return Z;let c=L(t.x),a=L(t.y),l={x:c,y:a,width:Math.max(0,L(t.x+t.width)-c),height:Math.max(0,L(t.y+t.height)-a)};if(l.width<=0||l.height<=0)return Z;let u=l.x*n,d=l.y*s,m=(l.x+l.width)*n,h=(l.y+l.height)*s,f=(m-u)*.15,g=(h-d)*.15,y=(p,b,R)=>Math.min(R,Math.max(b,p)),x=y(Math.floor(u-f),0,n-1),w=y(Math.floor(d-g),0,s-1),O=y(Math.ceil(m+f),x+1,n),v=y(Math.ceil(h+g),w+1,s),D=Math.max(1,Math.ceil(Math.max(O-x,v-w)/320)),M=Math.floor((O-x+D-1)/D),_=Math.floor((v-w+D-1)/D);if(M<3||_<3)return Z;let k=new Int32Array(M*_);for(let p=0;p<_;p++){let b=w+p*D;for(let R=0;R<M;R++){let F=(b*n+x+R*D)*4;k[p*M+R]=(r[F]??0)*77+(r[F+1]??0)*150+(r[F+2]??0)*29>>8}}let C=(p,b)=>(p-b-.5)/D,T=C(u,x),A=C(m,x),B=C(d,w),U=C(h,w),Dt=(m-u)/D,wt=(h-d)/D,vt=y(Math.ceil(T),0,M-1),Ge=y(Math.floor(A),vt,M-1),St=y(Math.ceil(B),0,_-1),ze=y(Math.floor(U),St,_-1),_t=0,Tt=0,W=0,Rt=0,Ft=0,H=0;for(let p=St;p<=ze;p++)for(let b=vt;b<=Ge;b++){let R=k[p*M+b];if(_t+=R,R>=248&&Tt++,W++,b>=1&&b<M-1&&p>=1&&p<_-1){let F=k[p*M+b-1]+k[p*M+b+1]+k[(p-1)*M+b]+k[(p+1)*M+b]-4*R;Rt+=F,Ft+=F*F,H++}}let Ne=W>0?_t/W:0,Ct=W>0?Tt/W:0,At=H>0?Rt/H:0,Qe=H>0?Math.max(0,Ft/H-At*At):0,K=new Float64Array(M),V=new Float64Array(_);for(let p=0;p<_;p++)for(let b=1;b<M-1;b++)K[b]=K[b]+Math.abs(k[p*M+b+1]-k[p*M+b-1]);for(let p=1;p<_-1;p++)for(let b=0;b<M;b++)V[p]=V[p]+Math.abs(k[(p+1)*M+b]-k[(p-1)*M+b]);let I=at(K,!0,T,o),P=at(K,!1,A,o),G=at(V,!0,B,o),z=at(V,!1,U,o),Et=(P.position-I.position)/Dt,Lt=(z.position-G.position)/wt,Be=Lt>0?Et/Lt:0,Ue=((I.position+P.position)/2-(T+A)/2)/Dt,We=((G.position+z.position)/2-(B+U)/2)/wt,Ot=Re(K),It=Re(V),He=Ot<=0||It<=0?0:Math.min(Math.min(I.value,P.value)/Ot,Math.min(G.value,z.value)/It),$=(p,b)=>b+(p+.5)*D,Pt=Ct,Gt=0;{let p=(P.position-I.position)*.06,b=(z.position-G.position)*.06,R=y(Math.ceil(I.position+p),0,M-1),F=y(Math.floor(P.position-p),0,M-1),Ke=y(Math.ceil(G.position+b),0,_-1),zt=y(Math.floor(z.position-b),0,_-1),Nt=0,tt=0,Qt=0;for(let N=Ke;N<=zt;N++)for(let Q=R;Q<=F;Q++){tt++;let X=k[N*M+Q];X>=248&&Nt++;let Ve=Q+2<=F?k[N*M+Q+2]:X,Xe=N+2<=zt?k[(N+2)*M+Q]:X;(Math.abs(Ve-X)>=24||Math.abs(Xe-X)>=24)&&Qt++}tt>=16&&(Pt=Nt/tt,Gt=Qt/tt)}return{brightness:Ne,glare:Ct,cardGlare:Pt,sharpness:Qe,fill:Et,shape:Be,content:Gt,offsetX:Ue,offsetY:We,edgeConfidence:He,box:{left:$(I.position,x),right:$(P.position,x),top:$(G.position,w),bottom:$(z.position,w)}}}function at(i,t,e,o){let n=i.length,s=Math.max(1,Math.floor(n*.45)),r=t?1:Math.max(1,n-1-s),c=t?Math.min(n-2,s):n-2,a=r;for(let h=r;h<=c;h++)i[h]>i[a]&&(a=h);if(o>0&&o<1){let h=i[a]*o,f=a,g=Math.abs(a-e);for(let y=r;y<=c;y++){let x=i[y];if(x<h||x<(i[y-1]??0)||x<(i[y+1]??0))continue;let w=Math.abs(y-e);w<g&&(f=y,g=w)}a=f}let l=a>0?i[a-1]:0,u=i[a],d=a<n-1?i[a+1]:0,m=l+u+d;return{position:m>0?a+(d-l)/m:a,value:u}}function Re(i){if(i.length<3)return 0;let t=0;for(let e=1;e<i.length-1;e++)t+=i[e];return t/(i.length-2)}function Ae(i){let t=i.box;return t===null||t.right-t.left<4||t.bottom-t.top<4?null:{topLeft:{x:t.left,y:t.top},topRight:{x:t.right,y:t.top},bottomRight:{x:t.right,y:t.bottom},bottomLeft:{x:t.left,y:t.bottom}}}var J=Object.freeze({fillMin:.82,fillMax:1.06,offsetMax:.06,glareMax:.025,sharpnessMin:180,edgeConfidenceMin:1.6,darkBrightness:70,lockMs:450,steadyMs:900,steadyFillMin:.45,steadyFillMax:1.3,steadyFillDelta:.06,steadyOffsetDelta:.04,steadyRefMs:100,edgePeakFrac:.4,shapeTolerance:.2,contentMin:.1});function Oi(i){let t=i!==null&&typeof i=="object"?i:{},e={...J};for(let o of Object.keys(J)){let n=t[o];typeof n=="number"&&Number.isFinite(n)&&n>=0&&n<=1e6&&(e[o]=n)}return e}var ct=class{constructor(t=J){this.t=t;this.goodSince=null;this.steadySince=null;this.last=null}reset(){this.goodSince=null,this.steadySince=null,this.last=null}tick(t,e){let o=this.t,n=o.shapeTolerance<=0||Math.abs(t.shape-1)<=o.shapeTolerance,s=t.edgeConfidence>=o.edgeConfidenceMin&&n&&t.content>=o.contentMin,r=t.fill>=o.fillMin&&t.fill<=o.fillMax,c=Math.abs(t.offsetX)<=o.offsetMax&&Math.abs(t.offsetY)<=o.offsetMax,a=t.cardGlare<=o.glareMax,l=t.sharpness>=o.sharpnessMin,u=this.last;this.last={fill:t.fill,offsetX:t.offsetX,offsetY:t.offsetY,at:e};let d=u!==null&&o.steadyRefMs>0?Math.min(3,Math.max(1,(e-u.at)/o.steadyRefMs)):1,m=s&&a&&l&&t.fill>=o.steadyFillMin&&t.fill<=o.steadyFillMax&&u!==null&&Math.abs(t.fill-u.fill)<=o.steadyFillDelta*d&&Math.abs(t.offsetX-u.offsetX)<=o.steadyOffsetDelta*d&&Math.abs(t.offsetY-u.offsetY)<=o.steadyOffsetDelta*d,h=s&&r&&c&&a&&l,f;if(s?a?t.fill<o.fillMin?f="too_small":t.fill>o.fillMax?f="too_big":l?c?f="locking":f="off_center":f="blurry":f="glare":f="no_card",h){if(m&&(this.steadySince??(this.steadySince=e)),this.goodSince??(this.goodSince=e),e-this.goodSince>=o.lockMs)return{detected:s,ready:!0,via:"good",blocker:"locking"};let g=this.steadySince!==null&&e-this.steadySince>=o.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:"locking"}}if(this.goodSince=null,m){this.steadySince??(this.steadySince=e);let g=e-this.steadySince>=o.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:g?"locking":"steadying"}}return this.steadySince=null,{detected:s,ready:!1,via:null,blocker:f}}};var q=null;async function ai(i){return q===null&&(q=(await import("./detector-scanic-P2RTEQUV.js")).detectQuad),q(i)}async function ci(i){let t=te(i);return t===null?null:{topLeft:{x:t.x,y:t.y},topRight:{x:t.x+t.width,y:t.y},bottomRight:{x:t.x+t.width,y:t.y+t.height},bottomLeft:{x:t.x,y:t.y+t.height}}}function Ji(){q===null&&import("./detector-scanic-P2RTEQUV.js").then(i=>{q=i.detectQuad}).catch(()=>{})}var Ee=4e3,li=2,Le=3,ui=Object.freeze({LOW:3,MID:5,HIGH:6}),xt=Object.freeze({manualShutterMs:6e3,detectedNoLockMs:1950});function qi(i){let t=i!==null&&typeof i=="object"?i:{},e=(o,n,s)=>typeof o=="number"&&Number.isFinite(o)&&o>=n&&o<=s?o:void 0;return{manualShutterMs:e(t.manualShutterMs,1e3,6e4)??xt.manualShutterMs,detectedNoLockMs:e(t.steadyMs,300,3e4)!==void 0?t.steadyMs+(e(t.lockMs,0,1e4)??450):xt.detectedNoLockMs}}var Oe=class i{constructor(t){this.torchOn=!1;this.stillRefusals=0;this.zoom=1;this.positioningSince=null;this.detectedSince=null;this.lastSeenAt=null;this.lastGuideQuad=null;this.lastOcrReady=null;this.shutterOffered=!1;this.stats=i.freshStats();this.handlers=new Map;this.stream=null;this.timer=null;this.state="idle";this.lastGuidance=null;this.attempt=0;this.capturing=!1;this.feedback=new ot;this.lastFeedbackKey=null;this.lastQuad=null;this.lastDetect=null;this.frameWatch=null;this.reopened=!1;this.lit=!1;this.blackTicks=0;this.offEnded=null;this.opts=t,this.gate=new ne(t.format??"ID-1",t.thresholds);let e=t.deviceClass??jt(Xt());this.deviceClass=e,this.camera=t.camera??st,this.shutterTuning=t.shutter??xt,this.guideTuning=t.guideLock??J,this.guideLock=new ct(this.guideTuning),this.cadenceMs=1e3/ui[e]}on(t,e){let o=this.handlers.get(t);return o||(o=new Set,this.handlers.set(t,o)),o.add(e),()=>o?.delete(e)}emit(t,e){for(let o of[...this.handlers.get(t)??[]])o(e)}async start(){let t=this.state==="error"?this.resumePlayback():null,e=++this.attempt;if(this.clearFrameWatch(),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.lit=!1,this.blackTicks=0,t!==null&&await t&&e===this.attempt){this.setState("positioning"),this.scheduleTick(e),this.watchFrames(e);return}if(e===this.attempt){this.releaseStream(),Kt(),this.setState("preflight");try{let o=this.opts.getUserMedia??(r=>navigator.mediaDevices.getUserMedia(r));this.setState("acquiring");let n=this.opts.enumerateDevices??(this.opts.getUserMedia===void 0&&typeof navigator<"u"&&navigator.mediaDevices?.enumerateDevices?()=>navigator.mediaDevices.enumerateDevices():void 0),s=await Te({getUserMedia:o,...n!==void 0?{enumerateDevices:n}:{},lensSelection:this.camera.lensSelection,base:ue});if(e!==this.attempt){for(let r of s.stream.getTracks())r.stop();return}if(this.stream=s.stream,Wt(this.stream),Ht(this.stream),this.watchEnded(e),this.opts.upgradeResolution!==!1&&await this.upgradeResolution(),e!==this.attempt||(await this.applyFocusAndZoom(),e!==this.attempt)||(this.opts.video.srcObject=this.stream,await this.opts.video.play().catch(()=>{}),e!==this.attempt))return;this.setState("positioning"),this.scheduleTick(e),this.watchFrames(e)}catch(o){if(e!==this.attempt)return;let n=Ut(o),s=Bt(o);this.setState("error"),this.emit("error",{kind:n,retryable:!0,detail:s===void 0?{phase:"acquiring"}:{phase:"acquiring",name:s}})}}}resumePlayback(){let t=this.opts.video,e=this.videoTrack();if(this.stream===null||e===null||e.readyState!=="live"||t.srcObject!==this.stream)return null;try{return Promise.resolve(t.play()).then(()=>this.framesNow(),()=>!1)}catch{return null}}framesNow(){let t=this.opts.video;return this.opts.hasFrames!==void 0?this.opts.hasFrames(t):!t.paused&&t.readyState>=2&&t.videoWidth>0}watchFrames(t){let e=this.opts.firstFrameMs??Ee;e<=0||(this.clearFrameWatch(),this.frameWatch=setTimeout(()=>{if(this.frameWatch=null,!(t!==this.attempt||this.state!=="positioning")){if(this.framesNow()&&this.blackTicks<Le){this.reopened=!1;return}this.cameraDead(t)}},e))}clearFrameWatch(){this.frameWatch!==null&&clearTimeout(this.frameWatch),this.frameWatch=null}watchEnded(t){this.offEnded?.(),this.offEnded=null;let e=this.videoTrack();if(e===null||typeof e.addEventListener!="function")return;let o=()=>{t===this.attempt&&(this.state==="positioning"||this.state==="acquiring")&&this.cameraDead(t)};e.addEventListener("ended",o),this.offEnded=()=>e.removeEventListener?.("ended",o)}cameraDead(t){if(t!==this.attempt)return;let e=this.videoTrack(),o=e!==null&&e.readyState==="live"&&!e.muted&&this.opts.video.paused&&!this.framesNow();if(!o&&!this.reopened){this.reopened=!0,this.start();return}this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.clearFrameWatch(),o||this.releaseStream(),this.reopened=!1,this.setState("error"),this.emit("error",{kind:"generic",retryable:!0,detail:{phase:"acquiring"}})}releaseStream(){if(this.offEnded?.(),this.offEnded=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject!==null&&this.opts.video.srcObject!==void 0&&(this.opts.video.srcObject=null)}rearm(t){t!==void 0&&(this.opts.side=t),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.stillRefusals=0,this.state==="captured"&&(this.setState("positioning"),this.scheduleTick(this.attempt))}async captureNow(){if(this.state!=="positioning"||this.capturing)return;let t=this.opts.video,e=this.lastDetect?.width??Math.max(1,t.videoWidth),o=this.lastDetect?.height??Math.max(1,t.videoHeight),n=this.lastQuad??this.lastGuideQuad??{topLeft:{x:0,y:0},topRight:{x:e,y:0},bottomRight:{x:e,y:o},bottomLeft:{x:0,y:o}},s=(this.opts.now??(()=>performance.now()))(),r=this.feedback.force("processing",s);this.lastFeedbackKey=r.key,this.emit("feedback",r),await this.fire(this.attempt,this.lastOcrReady!==null?this.lastOcrReady.quad:n,{width:e,height:o,tickSharpness:this.lastDetect?.tickSharpness??0},this.lastOcrReady?.via??"manual")}captureReport(){let t=this.stats;return{...this.opts.side!==void 0?{side:this.opts.side}:{},format:this.opts.format??"ID-1",deviceClass:this.deviceClass,video:{width:this.opts.video.videoWidth||0,height:this.opts.video.videoHeight||0},zoom:this.zoom,...t.zoomFallbackAtMs!==void 0?{zoomFallbackAtMs:t.zoomFallbackAtMs}:{},...t.msToCapture!==void 0?{msToCapture:t.msToCapture}:{},...t.via!==void 0?{via:t.via}:{},...t.shutterAtMs!==void 0?{shutterAtMs:t.shutterAtMs}:{},...t.shutterReason!==void 0?{shutterReason:t.shutterReason}:{},ticks:t.ticks,quadFraming:{...t.quadFraming},qualityBlockers:{...t.qualityBlockers},guideBlockers:{...t.guideBlockers},stillRefusals:t.stillRefusals,...this.ocrReport()}}ocrReport(){let t=this.opts.ocr;if(t===void 0)return{};let e=(this.opts.format??"ID-1")==="ID-3"||this.opts.side==="single"?"single":this.opts.side==="verso"?"verso":"recto",o=t.report(e,this.stats.via,(this.opts.now??(()=>performance.now()))());return o===null?{}:{ocr:o}}static freshStats(){return{ticks:0,quadFraming:{},qualityBlockers:{},guideBlockers:{},stillRefusals:0}}setGuide(t){t===void 0?delete this.opts.guide:this.opts.guide=t,this.guideLock.reset()}guideRegion(t){let e=t.width/Math.max(1,t.height),o=this.opts.guide;if(o!==void 0&&o.viewAspect>0){let c={width:o.viewAspect,height:1},a={x:o.rect.x*o.viewAspect,y:o.rect.y,width:o.rect.width*o.viewAspect,height:o.rect.height};return Fe(c,a,e,0)}let n=Zt(this.opts.format??"ID-1").center,s=.86,r=s*e/n;return r>.84&&(r=.84,s=r*n/e),{x:(1-s)/2,y:(1-r)/2,width:s,height:r}}resetSide(){this.positioningSince=null,this.detectedSince=null,this.lastSeenAt=null,this.guideLock.reset(),this.lastGuideQuad=null,this.lastOcrReady=null,this.opts.ocr?.reset(),this.stats=i.freshStats(),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}withdrawShutter(){this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}zoomFallback(t){let e=this.videoTrack();if(e===null||this.zoom<=1)return;let o=this.focusCaps(),n=typeof o?.zoom?.min=="number"?Math.max(o.zoom.min,1):1;this.zoom=n,this.stats.zoomFallbackAtMs=Math.round(t-(this.positioningSince??t)),this.guideLock.reset(),this.gate.reset(),e.applyConstraints({advanced:[{zoom:n}]}).catch(()=>{})}offerShutter(t,e){this.shutterOffered||(this.shutterOffered=!0,this.stats.shutterAtMs=Math.round(e-(this.positioningSince??e)),this.stats.shutterReason=t,this.emit("shutter",{available:!0,reason:t}))}torchAvailable(){try{return this.stream?.getVideoTracks?.()[0]?.getCapabilities?.()?.torch===!0}catch{return!1}}async setTorch(t){this.torchOn=t;try{await this.stream?.getVideoTracks?.()[0]?.applyConstraints({advanced:[{torch:t}]})}catch{}}destroy(){if(this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.clearFrameWatch(),this.offEnded?.(),this.offEnded=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject=null}async upgradeResolution(){try{let t=this.stream?.getVideoTracks?.()[0];if(t===void 0)return;let e=t.getSettings?.()??{},o=me(t.getCapabilities?.(),{width:e.width??0,height:e.height??0},this.deviceClass,{width:this.camera.width,height:this.camera.height},this.opts.ocr?.liveMrzOn===!0?{fill:this.guideRegion({width:1080,height:1920}).width}:void 0);o!==null&&await t.applyConstraints(o)}catch{}}focusCaps(){try{return this.videoTrack()?.getCapabilities?.()??null}catch{return null}}async applyFocusAndZoom(){let t=this.videoTrack();if(t===null)return;let e=this.focusCaps();this.camera.continuousFocus&&rt(e,"continuous")&&await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{});let o={width:0,height:0};try{let s=t.getSettings?.()??{};o={width:s.width??0,height:s.height??0}}catch{}let n=_e(e,o,this.opts.format??"ID-1",this.camera);if(n>1)try{await t.applyConstraints({advanced:[{zoom:n}]}),this.zoom=n}catch{this.zoom=1}}async focusAt(t,e){let o=this.videoTrack(),n=kt(this.focusCaps(),t,e);if(!(o===null||n===null))try{await o.applyConstraints({advanced:[n]}),(this.opts.setTimer??setTimeout)(()=>{this.restoreContinuous()},1500)}catch{}}async restoreContinuous(){let t=this.videoTrack();t===null||!this.camera.continuousFocus||!rt(this.focusCaps(),"continuous")||await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})}async refocusOn(t,e){let o=this.camera.refocusBeforePhotoMs,n=this.videoTrack();if(o<=0||n===null||e.width<=0||e.height<=0)return;let s=E(t),r=kt(this.focusCaps(),(s.x+s.width/2)/e.width,(s.y+s.height/2)/e.height);if(r!==null)try{await n.applyConstraints({advanced:[r]});let c=this.opts.setTimer??setTimeout;await new Promise(a=>{c(()=>a(),o)})}catch{}}videoTrack(){try{return this.stream?.getVideoTracks?.()[0]??null}catch{return null}}async takeStill(t,e,o){if(this.opts.captureStill!==void 0)return this.opts.captureStill(this.opts.video,t,e);let n=this.opts.format??"ID-1",s=this.videoTrack();if(o&&this.opts.photoCapture!==!1&&this.deviceClass!=="LOW"&&!this.torchOn&&s!==null&&ke(s)){await this.refocusOn(t,e);let r=await we(this.opts.video,t,e,n,{track:s,detect:this.detector(),detectWidth:et});if(this.restoreContinuous(),r!==null)return r}return De(this.opts.video,t,e,n)}detector(){return this.opts.detect??((this.opts.format??"ID-1")==="ID-3"?ci:ai)}setState(t){this.state=t,this.emit("statechange",{state:t})}scheduleTick(t){let e=this.opts.setTimer??setTimeout;this.timer=e(()=>{this.tick(t)},this.cadenceMs)}async tick(t){if(t!==this.attempt||this.state!=="positioning"||this.capturing)return;let e=this.opts.now??(()=>performance.now()),o=this.opts.grabDetectFrame??Pe,n=this.detector(),s=o(this.opts.video,et);if(s===null){this.scheduleTick(t);return}if(!this.lit){if(dt(s)>li)this.lit=!0,this.blackTicks=0;else if(++this.blackTicks>=Le&&this.frameWatch===null&&(this.opts.firstFrameMs??Ee)>0){this.cameraDead(t);return}}let r=null;try{r=await n(s)}catch{r=null}if(t!==this.attempt)return;let c=r!==null?lt(s,r):s,a=e(),l={sharpness:j(c),exposure:Yt(c),meanLuma:dt(c),specularFraction:ae(c)},u=ce({format:this.opts.format??"ID-1",quad:r,frameWidth:s.width,frameHeight:s.height,measures:l,...this.opts.thresholds!==void 0?{thresholds:this.opts.thresholds}:{}}),d=this.gate.tick({timestampMs:a,quad:r,quality:l,frameWidth:s.width,frameHeight:s.height}),h=(this.opts.format??"ID-1")!=="ID-3"?Ce(s,this.guideRegion(s),{edgePeakFrac:this.guideTuning.edgePeakFrac}):Z,f=this.guideLock.tick(h,a);this.lastGuideQuad=f.detected?Ae(h):null;let g=this.capturing?null:this.ocrTick(s,r,h,f.detected,u,a);this.positioningSince??(this.positioningSince=a);let y=this.stats;if(y.ticks+=1,y.quadFraming[u.framing]=(y.quadFraming[u.framing]??0)+1,u.framing==="ok"&&!d.ready){let T=u.lighting!=="ok"?u.lighting:u.glare!=="ok"?"glare":u.blur!=="ok"?"blurry":"steadying";y.qualityBlockers[T]=(y.qualityBlockers[T]??0)+1}y.guideBlockers[f.blocker]=(y.guideBlockers[f.blocker]??0)+1,r!==null||f.detected?(this.detectedSince??(this.detectedSince=a),this.lastSeenAt=a):this.detectedSince=null,this.lastSeenAt!==null&&a-this.lastSeenAt<=bi?a-this.positioningSince>=this.shutterTuning.manualShutterMs?this.offerShutter("timeout",a):g?.suspendQuality!==!0&&this.detectedSince!==null&&a-this.detectedSince>=this.shutterTuning.detectedNoLockMs&&this.offerShutter("detected_no_lock",a):this.withdrawShutter();let O=a-(this.lastSeenAt??this.positioningSince);this.zoom>1&&this.camera.zoomFallbackMs>0&&O>=this.camera.zoomFallbackMs&&this.zoomFallback(a),this.emit("checks",{engine:"docv1",p:d.p,plausible:d.plausible,stableTicks:d.stableTicks,quad:d.quad,frameWidth:s.width,frameHeight:s.height,analysis:u,ready:g?.suspendQuality!==!0&&(d.ready&&r!==null||f.ready&&this.lastGuideQuad!==null)||this.lastOcrReady!==null,guide:{detected:f.detected,blocker:f.blocker,fill:h.fill,shape:h.shape,content:h.content,offsetX:h.offsetX,offsetY:h.offsetY},...g!==null&&g.mode!=="off"?{ocr:{mode:g.mode,...g.mrz?{mrz:g.mrz}:{},...g.lock?{lock:g.lock}:{}}}:g?.mrz?{ocr:{mode:g.mode,mrz:g.mrz}}:{}}),this.lastQuad=d.plausible?r:null,this.lastDetect={width:s.width,height:s.height,tickSharpness:l.sharpness};let v=se(u);u.framing!=="ok"&&f.detected&&(v=gi(f.blocker,h.brightness<this.guideTuning.darkBrightness)),v==="blurry"&&r!==null&&di(r,s,this.opts.format??"ID-1")>=this.camera.focusFarFillFrac&&(v="focus_far"),v==="sensing"&&this.zoom>1&&this.camera.noDocFarHintMs>0&&O>=this.camera.noDocFarHintMs&&(v="focus_far");let D=this.feedback.tick(v,a);if(D.key!==this.lastFeedbackKey&&(this.lastFeedbackKey=D.key,this.emit("feedback",D)),d.guidanceKey!==this.lastGuidance&&(this.lastGuidance=d.guidanceKey,this.emit("guidance",{key:d.guidanceKey})),this.capturing)return;let M=g?.suspendQuality!==!0,_=M&&d.ready&&r!==null,k=M&&f.ready&&this.lastGuideQuad!==null,C=this.lastOcrReady;if(C!==null&&this.opts.autoCapture!==!1){let T=this.feedback.force("processing",a);this.lastFeedbackKey=T.key,this.emit("feedback",T);let A=j(lt(s,C.quad));await this.fire(t,C.quad,{width:s.width,height:s.height,tickSharpness:A},C.via);return}if((_||k)&&this.opts.autoCapture!==!1){let T=this.feedback.force("processing",a);this.lastFeedbackKey=T.key,this.emit("feedback",T);let A=k?this.lastGuideQuad:r,B=k?f.via==="steady"?"guide_steady":"guide_good":"quad",U=k?j(lt(s,A)):l.sharpness;await this.fire(t,A,{width:s.width,height:s.height,tickSharpness:U},B);return}this.scheduleTick(t)}async fire(t,e,o,n){this.capturing=!0;let s=this.opts.grabDetectFrame??Pe,r=this.opts.setTimer??setTimeout,c={width:o.width,height:o.height};try{let a={still:await this.takeStill(e,c,!0),sharpness:o.tickSharpness};if(t!==this.attempt)return;let l=a.still.source==="photo"||this.deviceClass==="LOW"?0:mi;for(let m=0;m<l;m++){if(await new Promise(g=>{r(()=>g(),fi)}),t!==this.attempt)return;let h=s(this.opts.video,et);if(h===null)continue;let f=j(lt(h,e));if(f>a.sharpness*pi){let g=await this.takeStill(e,c,!1);if(t!==this.attempt)return;a={still:g,sharpness:f}}}if(t!==this.attempt)return;let u=a.still.sharpness;if(this.opts.autoCapture!==!1&&n!=="manual"&&typeof u=="number"&&u>=0&&u<this.camera.stillSharpnessMin&&this.stillRefusals<this.camera.stillRefusalsMax){this.stillRefusals+=1,this.stats.stillRefusals+=1,this.guideLock.reset(),this.lastOcrReady=null,(n==="text_lock"||n==="live_mrz")&&this.opts.ocr?.rearmFace();let m=(this.opts.now??(()=>performance.now()))(),h=this.feedback.force("focus_far",m);this.lastFeedbackKey=h.key,this.emit("feedback",h),this.capturing=!1,this.gate.reset(),this.scheduleTick(t);return}this.stillRefusals=0;let d=(this.opts.now??(()=>performance.now()))();this.stats.via=n,this.stats.msToCapture=Math.round(d-(this.positioningSince??d)),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1})),this.setState("captured"),this.emit("artifacts",{keyframe:a.still.blob,previewDataUrl:a.still.previewDataUrl,...this.opts.side!==void 0?{side:this.opts.side}:{},...a.still.docRegion!==void 0?{docRegion:a.still.docRegion}:{},...(()=>{let m=n==="live_mrz"?this.opts.ocr?.liveCapture():null;return m?{liveMrz:m}:{}})()})}catch{if(t!==this.attempt)return;this.capturing=!1,this.gate.reset(),this.guideLock.reset(),this.lastOcrReady=null,(n==="text_lock"||n==="live_mrz")&&this.opts.ocr?.rearmFace(),this.scheduleTick(t)}}ocrTick(t,e,o,n,s,r){let c=this.opts.ocr,a=this.opts.video;if(c===void 0||!c.hasEngine)return this.lastOcrReady=null,null;let l=a.videoWidth,u=a.videoHeight;if(l<=0||u<=0||t.width<=0||t.height<=0)return null;let m=(this.opts.format??"ID-1")==="ID-3",h=this.guideRegion(t),f={x:h.x*l,y:h.y*u,w:h.width*l,h:h.height*u},g=l/t.width,y=u/t.height,x;m&&e!==null?x=hi(E(e),g,y,l,u):x=ee(f,c.bandTop,u);let w=m?s.glare==="ok":o.cardGlare<=this.guideTuning.glareMax,O=m?s.blur==="ok":o.sharpness>=this.guideTuning.sharpnessMin,v=c.tick({atMs:r,video:a,mrzFace:m||this.opts.side==="verso"||this.opts.side==="single",present:m||e!==null||n,card:f,band:x,portrait:u>l,glareOk:w,sharpOk:O});if(v.ready&&v.via!==void 0){let D=m?e??Ie(h,t):this.lastGuideQuad??Ie(h,t);this.lastOcrReady={quad:D,via:v.via}}else this.lastOcrReady=null;return v}};function hi(i,t,e,o,n){let s=Math.min(o,i.width*1.06*t),r=Math.min(n,Math.max(i.height*1.6*e,s/5)),c=(i.y+i.height/2)*e,a=Math.max(0,Math.min(o-s,(i.x-i.width*.03)*t)),l=Math.max(0,Math.min(n-r,c-r/2));return{x:a,y:l,w:s,h:r}}function Ie(i,t){let e=i.x*t.width,o=i.y*t.height,n=(i.x+i.width)*t.width,s=(i.y+i.height)*t.height;return{topLeft:{x:e,y:o},topRight:{x:n,y:o},bottomRight:{x:n,y:s},bottomLeft:{x:e,y:s}}}function di(i,t,e){let o=E(i);return t.width<=0||t.height<=0?0:e==="ID-3"?o.width/t.width:o.width*o.height/(t.width*t.height)}var mi=2,fi=260,pi=1.08;function Pe(i,t){let e=i.videoWidth,o=i.videoHeight;if(e===0||o===0)return null;let n=Math.min(1,t/e),s=Math.round(e*n),r=Math.round(o*n),c=document.createElement("canvas");c.width=s,c.height=r;let a=c.getContext("2d",{willReadFrequently:!0});return a===null?null:(e/Math.max(1,s)>4&&(a.imageSmoothingQuality="high"),a.drawImage(i,0,0,s,r),a.getImageData(0,0,s,r))}function lt(i,t){let e=[t.topLeft.x,t.topRight.x,t.bottomRight.x,t.bottomLeft.x],o=[t.topLeft.y,t.topRight.y,t.bottomRight.y,t.bottomLeft.y],n=Math.max(0,Math.floor(Math.min(...e))),s=Math.max(0,Math.floor(Math.min(...o))),r=Math.min(i.width,Math.ceil(Math.max(...e))),c=Math.min(i.height,Math.ceil(Math.max(...o))),a=Math.max(1,r-n),l=Math.max(1,c-s),u=new Uint8ClampedArray(a*l*4);for(let d=0;d<l;d++){let m=((s+d)*i.width+n)*4;u.set(i.data.subarray(m,m+a*4),d*a*4)}return{data:u,width:a,height:l,colorSpace:i.colorSpace}}function gi(i,t){return i==="glare"?"glare":i==="too_small"?"too_far":i==="too_big"?"too_close":t?"too_dark":i==="blurry"?"blurry":i==="off_center"?"edge_clipped":i==="no_card"?"sensing":"hold_still"}var bi=1200;export{it as a,se as b,ot as c,je as d,ae as e,Ye as f,ce as g,st as h,Ri as i,yt as j,si as k,ve as l,rt as m,kt as n,Ci as o,_e as p,ri as q,Te as r,Z as s,Fe as t,Ce as u,Ae as v,J as w,Oi as x,ct as y,Ji as z,Ee as A,li as B,Le as C,ui as D,xt as E,qi as F,Oe as G,hi as H,mi as I,fi as J};
@@ -1 +1 @@
1
- import{c as P,d as H,e as A}from"./chunk-TQQK7464.js";var z=new Set(["nni_unbound","id_number_unbound","method_required","mobile_required","portrait_required"]);function be(e){return z.has(e)}function ve(e,n,t){let i=n.detail;return{check:e,kind:n.kind,...i?.name!==void 0?{name:i.name}:{},...i?.phase!==void 0?{phase:i.phase}:{},...i?.engineKind!==void 0?{engineKind:i.engineKind}:{},attempt:Math.max(0,Math.min(1e3,t))}}function Pe(){let e=-1,n="";return{note(t){t==="starting"&&n!=="starting"&&(e+=1),n=t},newHandle(){n=""},noteError(){e<0&&(e=0)},get value(){return e}}}var j={document:"document_photo",nfc:"document_chip",population_registry:"national_number",national_eid:"national_eid"};function f(e){return e.plan?.steps??[]}function x(e){return Math.max(0,e.attempts.max-e.attempts.used)}function W(e){let n=e.plan?.choice;return n!==void 0&&e.plan?.current===n.nodeId?n:null}function Me(e){let n=W(e);if(n?.kind!=="identity_method")return null;let t=n.options.map(r=>j[r.service]).filter(r=>r!==void 0),i=n.options.find(r=>r.nationalEid)?.nationalEid;return i?{available:!0,selected:null,options:t,nationalEid:i}:{available:!0,selected:null,options:t}}var G=new Set(["liveness","face_match"]);function y(e){return e!==void 0&&(e.state==="pending"||e.state==="input_required")}function T(e){return e.status!=="created"&&e.status!=="in_progress"}function M(e){let n=e.plan?.current,t=n==null?void 0:f(e).find(i=>i.id===n);return y(t)?t:void 0}function _(e,n){return f(e).find(t=>t.checkType===n)}function S(e){let n=f(e),t=n.findIndex(i=>i.checkType==="liveness");return n.find((i,r)=>r>t&&i.checkType==="face_match")}function F(e,n){let t=_(n,"liveness")?.state,i=S(n)?.state;return(S(e)?.state??"pending")==="pending"&&(t==="passed"||t==="review")&&i!==void 0&&i!=="pending"&&i!=="skipped"}function V(e,n){let t=new Map(f(e).map(i=>[i.id,i.state]));return f(n).filter(i=>i.checkType==="face_match"&&(t.get(i.id)??"pending")==="pending"&&i.state!=="pending"&&i.state!=="skipped").map(i=>i.id)}var X=/^[0-9a-f]{24}$/i;function R(e){return X.test(e)?`ses_${e}`:e}function w(e,n){let t=R(e);return n===void 0?{sessionId:t,status:"unavailable"}:{sessionId:t,status:"unavailable",reasonCode:n}}function O(e,n,t){let i=R(e);return t===void 0?{sessionId:i,status:n}:{sessionId:i,status:n,reasonCode:t}}function Ve(e,n){let t=Z(e,n),i=Q(e);return i!==void 0&&(t.sandbox={simulated:!0,reason:i}),t}var J=new Set(["no_testers","tester_gate_not_used","tester_gate_missed"]);function Q(e){if(e.sandbox!==!0)return;let n=e.simulation?.reason;return J.has(n)?n:void 0}function Z(e,n){let t=R(e.sessionId);switch(e.status){case"created":case"in_progress":return re(e,n);case"verified":return b(e,{sessionId:t,status:"verified"});case"review_pending":return b(e,O(t,"review",L(e,"review")));case"not_verified":return b(e,ne(e));default:return b(e,{sessionId:t,status:"not_verified"})}}var ee=new Set([0,1,2,3]);function b(e,n){return ee.has(e.level)&&(n.level=e.level),typeof e.assurance=="string"&&e.assurance.length>0&&(n.assurance=e.assurance),n}function ne(e){let n={sessionId:R(e.sessionId),status:"not_verified"};return e.reason!==void 0&&(n.reason=e.reason),e.reasonCode!==void 0&&(n.reasonCode=e.reasonCode),e.reasonCode==="device_cooldown"&&e.retryAfter!==void 0&&(n.retryAfter=e.retryAfter),n}function te(e){return e==="rejected"?"rejected":e==="unavailable"?"unavailable":"inconclusive"}function ie(e,n){if(n===void 0)return!1;let t=f(n).find(i=>i.id===e.id);return t!==void 0&&t.attempts.used===e.attempts.used}function re(e,n){let t=R(e.sessionId),i=f(e).find(o=>G.has(o.checkType)&&o.state==="input_required"&&o.reason!==void 0);if(i?.reason==="mobile_required")return w(t,"mobile_required");if(i?.reason!==void 0){if(i.result==="unavailable")return w(t,i.reason);let u=n.autoRetry&&(x(i)>0||ie(i,n.previous))?{sessionId:t,status:"retry",reasonCode:i.reason,attemptsRemaining:x(i)}:{sessionId:t,status:"not_verified",reason:te(i.result),reasonCode:i.reason,attemptsRemaining:x(i)};return i.retakeHint!==void 0&&(u.retakeHint=i.retakeHint),u}let r=M(e);return r===void 0&&f(e).some(o=>o.state==="review")?O(t,"review",L(e,"review")):r?.checkType==="portrait_icao"?w(t,"portrait_required"):w(t)}function L(e,n){return f(e).find(t=>t.state===n&&t.reason!==void 0)?.reason}function K(e,n,t,i,r){return e.presignCapture!==void 0?e.presignCapture(n,t,i,r):e.presign(n,t,i)}function q(e){return{engine:e?.engine,durationMs:e?.clipMs,arm:e?.screenRamp?.nonce}}var oe=["video/webm","video/mp4"],N="image/jpeg",se=2,ae=1e3,ue=1e4,de=3,ce=10,le=3,pe=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),fe=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order","identity_confirm_required","check_not_active","step_not_on_path","native_app_required"]),k=class extends Error{constructor(){super("verification destroyed"),this.name="FlowCancelledError"}};function me(e){let n=S(e);return _(e,"portrait_icao")?.state!=="pending"&&(n!==void 0?y(n):e.capture?.livePhoto?.oneCapture===!0)}var h=class extends Error{constructor(n){super(n),this.name="AttestationError"}},E=class extends h{constructor(n){super(`no attestation token: ${n}`),this.name="AttestationUnavailableError",this.code=n}};async function D(e,n,t={}){let i=e.uuid(),r=!1,o=!1,u=0,p=0;for(;;)try{return await n(e.client,i)}catch(s){if(s instanceof h){if(o||s instanceof E)throw s;o=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(!(s instanceof P))throw s;if(s.code==="consent_required"&&!r){r=!0,await e.ensureConsent({force:!0}),i=e.uuid();continue}if(s.code==="attestation_invalid"&&!o){o=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(s.code==="inference_unavailable"&&p<de){p+=1;let a=H(s.retryAfterSeconds,ce,e.random??Math.random);e.onBusy?.({attempt:p,retryAfterSeconds:a/1e3}),await e.sleep(a),t.onAttestationInvalid?.(),i=e.uuid();continue}if(pe.has(s.code)&&u<se){u+=1;let a=s.retryAfterSeconds!==void 0?s.retryAfterSeconds*1e3:void 0;await e.sleep(a!==void 0?Math.min(a,ue):ae);continue}throw s}}var he=new Set(["passed","review","processing","skipped"]);async function Fe(e){let{artifacts:n}=e,t=n.clip,i=A(n.clipMime??"");if(n.degraded==="NO_RECORDER"||t===void 0||!oe.includes(i))return{kind:"unavailable",reason:"no_recorder"};e.client.armCapture?.(2);let r=_e(e,n.keyframe),o=ge(e,t,i,r),u=Se(e,r),p=!1,s=new Set,a=!0,C=0;for(;;){if(e.isCancelled())return{kind:"cancelled"};let c=e.getView();if(T(c))return{kind:"settled"};let d=M(c),g=d?.checkType,v=g==="liveness"&&!p?"liveness":g==="face_match"&&!s.has(d?.id)&&s.size<2&&a?"face_match":null;if(v===null)return{kind:"settled"};if(v==="liveness"&&n.captureChannel==="desktop")return{kind:"unavailable",reason:"mobile_required"};try{if(v==="liveness"){p=!0;let l=await o();if(e.isCancelled())return{kind:"cancelled"};F(c,l)&&s.add(S(l)?.id);for(let Y of V(c,l))s.add(Y);await e.applySubmit(l,"liveness");let m=_(e.getView(),"liveness")?.state;a=m===void 0||he.has(m)}else{s.add(d?.id);let l=await u();if(e.isCancelled())return{kind:"cancelled"};for(let m of V(c,l))s.add(m);await e.applySubmit(l,"face_match")}}catch(l){if(e.isCancelled()||l instanceof k)return{kind:"cancelled"};let m=Ce(l);if(m.kind!=="resync"||C>=le)return m;C+=1,await e.refreshView()}}}function _e(e,n){let t=null,i=null,r=()=>t!==null?Promise.resolve(t):(i??(i=(async()=>{let o=await K(e.client,"image",N,n.size,q(e.artifacts));return await e.client.uploadToSpaces(o.uploadUrl,n,N),t=(await e.client.completeMedia(o.key)).key,e.onKeyframePromoted?.(t),t})().finally(()=>{i=null})),i);return{ensure:r,attempt:()=>r().catch(()=>null),current:()=>t}}function ge(e,n,t,i){let r=e.clipKeys?.get()??null,o,u=null,p=0,s;return()=>D(e,async(a,C)=>{if(r===null||o===void 0){if(e.isCancelled())throw new k;o===void 0&&!me(e.getView())&&(o=null),e.onPhase("uploading");let[c,d]=await Promise.all([r!==null?Promise.resolve(r):(async()=>{let g=await K(a,"clip",t,n.size,q(e.artifacts));return await a.uploadToSpaces(g.uploadUrl,n,t),(await a.completeMedia(g.key)).key})(),o!==void 0?Promise.resolve(o===null?null:o.imageKey):i.attempt()]);r=c,e.clipKeys?.set(c),o===void 0&&(o=d===null?null:{imageKey:d})}if(u===null){let c=performance.now();try{u=await e.getAttestation(),s=e.attestationError?.()}catch(d){throw d instanceof h?d:new h(d instanceof Error?d.message:String(d))}p=Math.round(performance.now()-c)}return e.onPhase("checking"),a.submitCheck("liveness",{clipKey:r,attestation:u,captureChannel:e.artifacts.captureChannel,capture:{...ye(e.artifacts),attestationMs:p,attestationError:s,...ke(e.attestationFacts?.())},...o!==null?{faceMatch:o}:{}},{idempotencyKey:C})},{onAttestationInvalid:()=>{u=null}})}function Se(e,n){return()=>D(e,async(t,i)=>{if(n.current()===null){if(e.isCancelled())throw new k;e.onPhase("uploading")}let r=await n.ensure();return e.onPhase("checking"),t.submitCheck("face_match",{imageKey:r},{idempotencyKey:i})})}function ye(e){let n={width:e.width,height:e.height};for(let t of Re)e[t]!==void 0&&(n[t]=e[t]);return n}var Re=["engine","facingMode","mode","formFactor","clipMs","clipFrames","fps","clipRetakes","codec","cameraReadyMs","faceAcquireMs","captureMs","screenRamp","provenance"];function ke(e){return e===void 0?{}:{attestationChecks:e.checks,...e.challengeMs!==void 0?{attestationChallengeMs:e.challengeMs}:{}}}function Ce(e){if(e instanceof h)return{kind:"unavailable",reason:"attestation"};if(e instanceof P){if(e.code==="attestation_invalid")return{kind:"unavailable",reason:"attestation"};if(e.code==="inference_unavailable")return{kind:"unavailable",reason:"inference_unavailable"};if(e.code==="mobile_required")return{kind:"unavailable",reason:"mobile_required"};if(fe.has(e.code))return{kind:"resync"}}return{kind:"unavailable",reason:"network"}}var Le="form_answers_invalid",U=class extends Error{constructor(n,t){super(`form answers refused (${n.map(i=>`${i.id}: ${i.code}`).join(", ")})`),this.name="FormAnswersError",this.issues=n,this.source=t}};var B=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="InvalidInputError",this.field=n,this.kind=t}},$=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="OtpInputError",this.field=n,this.kind=t}};function I(e){return e?.source==="upload"?null:e?.source==="choice"&&e.sourcePick!=="camera"?"upload_or_phone":"phone"}function De(e,n){if(n===void 0||!y(n)||n.requiresMobile!==!0)return null;switch(n.checkType){case"liveness":return"phone";case"face_match":{if(n.reason!==void 0)return"phone";let t=_(e,"portrait_icao");return t?.state==="passed"||t?.state==="review"?null:"phone"}case"doc_ocr":return I(e.documents);case"poa":return I(e.proofOfAddress);case"portrait_icao":{let t=e.portrait;return t?.pendingFix!==void 0||t?.reuse?.pending===!0?null:I(t)}default:return null}}function we(e){let n=e?.capture,t=n?.mode;return t==="assisted"||t==="self"||t==="choice"?t:n?.cameraSwitch===!0?"assisted":"self"}function Be(e){let n=e?.capture?.pick;return we(e)==="choice"&&(n==="self"||n==="assisted")?n:null}function $e(e,n,t=null){return e==="choice"?n??t??"self":e}var ze={"MR:drivers_license":{normalize:"upper_no_space_or_hyphen",pattern:"^[0-9]{8}$",check:null,registrySources:[],describe:"number must be the 8-digit Mauritanian driver's license number"},"MR:national_id":{normalize:"trim",pattern:"^[0-9]{10}$",check:"mr_nni_mod97",registrySources:["MR.anrpts"],describe:"number must be the 10-digit Mauritanian national ID number with a valid check digit"}};export{be as a,ve as b,Pe as c,j as d,f as e,x as f,W as g,Me as h,y as i,T as j,M as k,_ as l,R as m,w as n,Ve as o,Q as p,De as q,we as r,Be as s,$e as t,K as u,oe as v,se as w,ae as x,de as y,ce as z,h as A,E as B,D as C,Fe as D,ye as E,Le as F,U as G,ze as H,B as I,$ as J};
1
+ import{c as P,d as A,e as H}from"./chunk-PNOGF72U.js";var z=new Set(["nni_unbound","id_number_unbound","method_required","mobile_required","portrait_required"]);function Ce(e){return z.has(e)}function ve(e,n,t){let i=n.detail;return{check:e,kind:n.kind,...i?.name!==void 0?{name:i.name}:{},...i?.phase!==void 0?{phase:i.phase}:{},...i?.engineKind!==void 0?{engineKind:i.engineKind}:{},attempt:Math.max(0,Math.min(1e3,t))}}function Pe(){let e=-1,n="";return{note(t){t==="starting"&&n!=="starting"&&(e+=1),n=t},newHandle(){n=""},noteError(){e<0&&(e=0)},get value(){return e}}}var j={document:"document_photo",nfc:"document_chip",population_registry:"national_number",national_eid:"national_eid"};function f(e){return e.plan?.steps??[]}function x(e){return Math.max(0,e.attempts.max-e.attempts.used)}function J(e){let n=e.plan?.choice;return n!==void 0&&e.plan?.current===n.nodeId?n:null}function Me(e){let n=J(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 W=new Set(["liveness","face_match"]);function S(e){return e!==void 0&&(e.state==="pending"||e.state==="input_required")}function T(e){return e.status!=="created"&&e.status!=="in_progress"}function M(e){let n=e.plan?.current,t=n==null?void 0:f(e).find(i=>i.id===n);return S(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 F(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 V(e,n){let t=new Map(f(e).map(i=>[i.id,i.state]));return f(n).filter(i=>i.checkType==="face_match"&&(t.get(i.id)??"pending")==="pending"&&i.state!=="pending"&&i.state!=="skipped").map(i=>i.id)}var G=/^[0-9a-f]{24}$/i;function R(e){return G.test(e)?`ses_${e}`:e}function w(e,n){let t=R(e);return n===void 0?{sessionId:t,status:"unavailable"}:{sessionId:t,status:"unavailable",reasonCode:n}}function O(e,n,t){let i=R(e);return t===void 0?{sessionId:i,status:n}:{sessionId:i,status:n,reasonCode:t}}function Ve(e,n){let t=Q(e,n),i=Z(e);return i!==void 0&&(t.sandbox={simulated:!0,reason:i}),t}var X=new Set(["no_testers","tester_gate_not_used","tester_gate_missed"]);function Z(e){if(e.sandbox!==!0)return;let n=e.simulation?.reason;return X.has(n)?n:void 0}function Q(e,n){let t=R(e.sessionId);switch(e.status){case"created":case"in_progress":return re(e,n);case"verified":return C(e,{sessionId:t,status:"verified"});case"review_pending":return C(e,O(t,"review",L(e,"review")));case"not_verified":return C(e,ne(e));default:return C(e,{sessionId:t,status:"not_verified"})}}var ee=new Set([0,1,2,3]);function C(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=>W.has(o.checkType)&&o.state==="input_required"&&o.reason!==void 0);if(i?.reason==="mobile_required")return w(t,"mobile_required");if(i?.reason!==void 0){if(i.result==="unavailable")return w(t,i.reason);let u=n.autoRetry&&(x(i)>0||ie(i,n.previous))?{sessionId:t,status:"retry",reasonCode:i.reason,attemptsRemaining:x(i)}:{sessionId:t,status:"not_verified",reason:te(i.result),reasonCode:i.reason,attemptsRemaining:x(i)};return i.retakeHint!==void 0&&(u.retakeHint=i.retakeHint),u}let r=M(e);return r===void 0&&f(e).some(o=>o.state==="review")?O(t,"review",L(e,"review")):r?.checkType==="portrait_icao"?w(t,"portrait_required"):w(t)}function L(e,n){return f(e).find(t=>t.state===n&&t.reason!==void 0)?.reason}function K(e,n,t,i,r){return e.presignCapture!==void 0?e.presignCapture(n,t,i,r):e.presign(n,t,i)}function q(e){return{engine:e?.engine,durationMs:e?.clipMs,arm:e?.screenRamp?.nonce}}var oe=["video/webm","video/mp4"],N="image/jpeg",se=2,ae=1e3,ue=1e4,de=3,ce=10,le=3,pe=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),fe=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order","identity_confirm_required","check_not_active","step_not_on_path","native_app_required"]),k=class extends Error{constructor(){super("verification destroyed"),this.name="FlowCancelledError"}};function me(e){let n=y(e);return _(e,"portrait_icao")?.state!=="pending"&&(n!==void 0?S(n):e.capture?.livePhoto?.oneCapture===!0)}var h=class extends Error{constructor(n){super(n),this.name="AttestationError"}},E=class extends h{constructor(n){super(`no attestation token: ${n}`),this.name="AttestationUnavailableError",this.code=n}};async function D(e,n,t={}){let i=e.uuid(),r=!1,o=!1,u=0,p=0;for(;;)try{return await n(e.client,i)}catch(s){if(s instanceof h){if(o||s instanceof E)throw s;o=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(!(s instanceof P))throw s;if(s.code==="consent_required"&&!r){r=!0,await e.ensureConsent({force:!0}),i=e.uuid();continue}if(s.code==="attestation_invalid"&&!o){o=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(s.code==="inference_unavailable"&&p<de){p+=1;let a=A(s.retryAfterSeconds,ce,e.random??Math.random);e.onBusy?.({attempt:p,retryAfterSeconds:a/1e3}),await e.sleep(a),t.onAttestationInvalid?.(),i=e.uuid();continue}if(pe.has(s.code)&&u<se){u+=1;let a=s.retryAfterSeconds!==void 0?s.retryAfterSeconds*1e3:void 0;await e.sleep(a!==void 0?Math.min(a,ue):ae);continue}throw s}}var he=new Set(["passed","review","processing","skipped"]);async function Fe(e){let{artifacts:n}=e,t=n.clip,i=H(n.clipMime??"");if(n.degraded==="NO_RECORDER"||t===void 0||!oe.includes(i))return{kind:"unavailable",reason:"no_recorder"};e.client.armCapture?.(2);let r=_e(e,n.keyframe),o=ge(e,t,i,r),u=ye(e,r),p=!1,s=new Set,a=!0,b=0;for(;;){if(e.isCancelled())return{kind:"cancelled"};let c=e.getView();if(T(c))return{kind:"settled"};let d=M(c),g=d?.checkType,v=g==="liveness"&&!p?"liveness":g==="face_match"&&!s.has(d?.id)&&s.size<2&&a?"face_match":null;if(v===null)return{kind:"settled"};if(v==="liveness"&&n.captureChannel==="desktop")return{kind:"unavailable",reason:"mobile_required"};try{if(v==="liveness"){p=!0;let l=await o();if(e.isCancelled())return{kind:"cancelled"};F(c,l)&&s.add(y(l)?.id);for(let Y of V(c,l))s.add(Y);await e.applySubmit(l,"liveness");let m=_(e.getView(),"liveness")?.state;a=m===void 0||he.has(m)}else{s.add(d?.id);let l=await u();if(e.isCancelled())return{kind:"cancelled"};for(let m of V(c,l))s.add(m);await e.applySubmit(l,"face_match")}}catch(l){if(e.isCancelled()||l instanceof k)return{kind:"cancelled"};let m=be(l);if(m.kind!=="resync"||b>=le)return m;b+=1,await e.refreshView()}}}function _e(e,n){let t=null,i=null,r=()=>t!==null?Promise.resolve(t):(i??(i=(async()=>{let o=await K(e.client,"image",N,n.size,q(e.artifacts));return await e.client.uploadToSpaces(o.uploadUrl,n,N),t=(await e.client.completeMedia(o.key)).key,e.onKeyframePromoted?.(t),t})().finally(()=>{i=null})),i);return{ensure:r,attempt:()=>r().catch(()=>null),current:()=>t}}function ge(e,n,t,i){let r=e.clipKeys?.get()??null,o,u=null,p=0,s;return()=>D(e,async(a,b)=>{if(r===null||o===void 0){if(e.isCancelled())throw new k;o===void 0&&!me(e.getView())&&(o=null),e.onPhase("uploading");let[c,d]=await Promise.all([r!==null?Promise.resolve(r):(async()=>{let g=await K(a,"clip",t,n.size,q(e.artifacts));return await a.uploadToSpaces(g.uploadUrl,n,t),(await a.completeMedia(g.key)).key})(),o!==void 0?Promise.resolve(o===null?null:o.imageKey):i.attempt()]);r=c,e.clipKeys?.set(c),o===void 0&&(o=d===null?null:{imageKey:d})}if(u===null){let c=performance.now();try{u=await e.getAttestation(),s=e.attestationError?.()}catch(d){throw d instanceof h?d:new h(d instanceof Error?d.message:String(d))}p=Math.round(performance.now()-c)}return e.onPhase("checking"),a.submitCheck("liveness",{clipKey:r,attestation:u,captureChannel:e.artifacts.captureChannel,capture:{...Se(e.artifacts),attestationMs:p,attestationError:s,...ke(e.attestationFacts?.())},...o!==null?{faceMatch:o}:{}},{idempotencyKey:b})},{onAttestationInvalid:()=>{u=null}})}function ye(e,n){return()=>D(e,async(t,i)=>{if(n.current()===null){if(e.isCancelled())throw new k;e.onPhase("uploading")}let r=await n.ensure();return e.onPhase("checking"),t.submitCheck("face_match",{imageKey:r},{idempotencyKey:i})})}function Se(e){let n={width:e.width,height:e.height};for(let t of Re)e[t]!==void 0&&(n[t]=e[t]);return n}var Re=["engine","facingMode","mode","formFactor","clipMs","clipFrames","fps","clipRetakes","codec","cameraReadyMs","faceAcquireMs","captureMs","screenRamp","provenance"];function ke(e){return e===void 0?{}:{attestationChecks:e.checks,...e.challengeMs!==void 0?{attestationChallengeMs:e.challengeMs}:{}}}function be(e){if(e instanceof h)return{kind:"unavailable",reason:"attestation"};if(e instanceof P){if(e.code==="attestation_invalid")return{kind:"unavailable",reason:"attestation"};if(e.code==="inference_unavailable")return{kind:"unavailable",reason:"inference_unavailable"};if(e.code==="mobile_required")return{kind:"unavailable",reason:"mobile_required"};if(fe.has(e.code))return{kind:"resync"}}return{kind:"unavailable",reason:"network"}}var Le="form_answers_invalid",U=class extends Error{constructor(n,t){super(`form answers refused (${n.map(i=>`${i.id}: ${i.code}`).join(", ")})`),this.name="FormAnswersError",this.issues=n,this.source=t}};var B=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="InvalidInputError",this.field=n,this.kind=t}},$=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="OtpInputError",this.field=n,this.kind=t}};function I(e){return e?.source==="upload"?null:e?.source==="choice"&&e.sourcePick!=="camera"?"upload_or_phone":"phone"}function De(e,n){if(n===void 0||!S(n)||n.requiresMobile!==!0)return null;switch(n.checkType){case"liveness":return"phone";case"face_match":{if(n.reason!==void 0)return"phone";let t=_(e,"portrait_icao");return t?.state==="passed"||t?.state==="review"?null:"phone"}case"doc_ocr":return I(e.documents);case"poa":return I(e.proofOfAddress);case"portrait_icao":{let t=e.portrait;return t?.pendingFix!==void 0||t?.reuse?.pending===!0?null:I(t)}default:return null}}function we(e){let n=e?.capture,t=n?.mode;return t==="assisted"||t==="self"||t==="choice"?t:n?.cameraSwitch===!0?"assisted":"self"}function Be(e){let n=e?.capture?.pick;return we(e)==="choice"&&(n==="self"||n==="assisted")?n:null}function $e(e,n,t=null){return e==="choice"?n??t??"self":e}var ze={"JP:drivers_license":{normalize:"upper_no_space_or_hyphen",pattern:"^[0-9]{12}$",check:null,registrySources:[],describe:"number must be the 12-digit Japanese driving licence number"},"JP:residence_permit":{normalize:"upper_no_space_or_hyphen",pattern:"^[A-Z]{2}[0-9]{8}[A-Z]{2}$",check:null,registrySources:[],describe:"number must be the 12-character residence card number: two letters, eight digits, two letters"},"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,ve as b,Pe as c,j as d,f as e,x as f,J as g,Me as h,S as i,T as j,M as k,_ as l,R as m,w as n,Ve as o,Z as p,De as q,we as r,Be as s,$e as t,K as u,oe as v,se as w,ae as x,de as y,ce as z,h as A,E as B,D as C,Fe as D,Se as E,Le as F,U as G,ze as H,B as I,$ as J};
@@ -1 +1 @@
1
- import{d as ae,h as _e,i as Ae,j as Be,l as Ie}from"./chunk-MQHTFHSN.js";import{a as oe,e as Te,g as Le}from"./chunk-5AR5GTEJ.js";import{m as J}from"./chunk-QTOMWAS6.js";import{a as Re,g as Pe}from"./chunk-7QZWBDI5.js";import{k as re}from"./chunk-CPUECYAJ.js";import{d as Oe,g as Ee}from"./chunk-WNBEOK5Q.js";function Fe(e,t){let n=new Set(e.flatMap(o=>o.sides.filter(i=>i[t]!==null).map(i=>i.side)));return n.size===1?[...n][0]:null}function pt(e){let t=Te.find(o=>o.docType===e),n=t.mrz==="none"?null:t.mrz==="td3"?"single":"verso";return{sides:t.sides,format:Le(e),mrz:t.mrz==="none"?"none":"required",mrzSide:n,barcodeSide:null,portraitSide:t.portraitSide,scripts:null}}function ft(e){let t=[];for(let n of e)for(let o of n.sides){if(!Array.isArray(o.scripts))return null;for(let i of o.scripts)t.includes(i)||t.push(i)}return t}function We(e,t){if(t.length===0)return pt(e);let n=t.some(u=>u.sides.length>1),o=new Set(t.map(u=>u.format)),i=o.size===1?[...o][0]:"card",l=t.filter(u=>u.sides.some(m=>m.mrz!==null)).length,s=t.find(u=>u.sides.length>1===n)?.sides.find(u=>u.portrait)?.side;return{sides:n?["recto","verso"]:["single"],format:i,mrz:l===t.length?"required":l===0?"none":"optional",mrzSide:Fe(t,"mrz"),barcodeSide:Fe(t,"barcode"),portraitSide:s??(n?"recto":"single"),scripts:ft(t)}}function ze(e,t){if(e===void 0)return[];let n=e.toUpperCase();return Object.prototype.hasOwnProperty.call(oe,n)?oe[n]?.[t]??[]:[]}async function Ue(e,t,n){return await e(t)?n:n==="recto"?"verso":"recto"}function Ne(e,t,n){return e!==t&&t==="verso"&&n.recto!==void 0&&n.verso===void 0?"verso":e}var gt={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 ht(e){let{deviceMemory:t,effectiveType:n,saveData:o,downlinkMbps:i,sourceLongEdge:l}=e,s=o===!0||n==="slow-2g"||n==="2g"||i!=null&&i>0&&i<1,u=t!=null&&t<=2,m=n==="4g"||i!=null&&i>=5,c=t!=null&&t>=6,b;s||u?b="low":m&&c?b="good":b="mid";let f=gt[b],L=l&&l>0?Math.min(f.maxLongEdge,l):f.maxLongEdge;return{tier:b,...f,maxLongEdge:L}}function Ge(e){let t={};try{let n=navigator;typeof n.deviceMemory=="number"&&(t.deviceMemory=n.deviceMemory);let o=n.connection;o&&(t.effectiveType=o.effectiveType,t.saveData=o.saveData,t.downlinkMbps=o.downlink)}catch{}return typeof e=="number"&&e>0&&(t.sourceLongEdge=e),ht(t)}function bt(e,t,n){let o=Math.min(1,Math.max(0,(e-.28)/.21999999999999997)),i=(t+n)/2;return Math.max(t,n-o*(n-i))}function St(e,t,n){let o=Math.max(e,t),i=o>0?Math.min(1,n/o):1;return{width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(t*i))}}async function yt(e,t){let n=t.startQ,o=await e(n);for(let i=0;i<4&&!(o.size<=t.budgetBytes||n<=t.qMin);i++)n=Math.max(t.qMin,n-.08),o=await e(n);return{blob:o,quality:n}}async function qe(e,t,n,o,i){if(t<=0||n<=0)return null;let{width:l,height:s}=St(t,n,o.maxLongEdge),u=document.createElement("canvas");u.width=l,u.height=s;let m=u.getContext("2d");if(!m)return null;m.drawImage(e,0,0,l,s);let c=k=>new Promise((S,v)=>{u.toBlob(p=>p?S(p):v(new Error("canvas toBlob returned null")),"image/jpeg",k)}),b=bt(i,o.qMin,o.qMax),{blob:f,quality:L}=await yt(c,{startQ:b,qMin:o.qMin,budgetBytes:o.payloadTargetBytes}).finally(()=>{u.width=0,u.height=0});if(f.size>5242880)throw new Error("encoded document exceeds the 5242880-byte media cap");return{blob:f,quality:L,width:l,height:s}}async function ie(e){let t=Ge(Math.max(e.width,e.height)),n=await qe(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 Ht(e){let t=await createImageBitmap(e);try{return await ie(t)}finally{t.close()}}var Yt=250,Vt=.6,Qt=1800,Kt=6e3,jt=2e3,He=.16;function ue(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 Xe=e=>e==="recto"?"verso":"recto",Ye=e=>e.phase==="framing"||e.phase==="locking"||e.phase==="flipCue"||e.phase==="reaskRecto",le=e=>(e.captured.recto!==void 0?1:0)+(e.captured.verso!==void 0?1:0)+e.pending.length;function se(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 Mt(e,t,n){if(e.phase==="result")return{...e,lastReportAt:n};let o=!t.present||e.captureArea!==void 0&&t.areaFrac<.6*e.captureArea,{flipped:i,awaySince:l}=e;o&&(l=l??n),l!==void 0&&n-l>=250&&(i=!0),o||(l=void 0);let s=e.flipTimeoutSpent&&!(i&&!e.flipped),u=e.notice==="same_face"&&i&&!e.flipped?void 0:e.notice,m={...e,lastReportAt:n,flipped:i,awaySince:l,flipTimeoutSpent:s,notice:u,lastArea:t.areaFrac};if(!Ye(e))return m;if(e.needFlip&&!i){if(!t.ready)return{...m,phase:e.restPhase,goodSince:void 0};let c=e.lastShot!==void 0&&e.pending.includes(e.lastShot);if(s||c)return{...m,goodSince:void 0,phase:e.restPhase};let b=e.goodSince??n;return n-b>=1800?{...m,goodSince:b,phase:"capturing",flipTimeoutSpent:!0,timeoutCapture:!0}:{...m,goodSince:b,phase:e.restPhase}}return t.ready?{...m,phase:"capturing",goodSince:e.goodSince??n}:{...m,goodSince:void 0,phase:t.locking?"locking":e.restPhase}}function Dt(e,t){if(!Ye(e)||e.manualShutter)return e;let n=t-e.lastReportAt>=2e3,o=t-e.lastCaptureAt>=6e3;return n||o?{...e,manualShutter:!0}:e}function wt(e,t,n){let o=e.layout==="singlePage",i=o?{recto:t}:e.captured,l=o?[]:[...e.pending,t],s={...e,captured:i,pending:l,lastShot:t,lastCaptureAt:n,lastReportAt:-1,manualShutter:!1,goodSince:void 0,notice:void 0,awaySince:void 0,flipped:!1,lastShotByTimeout:e.timeoutCapture,timeoutCapture:!1,captureArea:e.lastArea};return o||le({captured:i,pending:l})>=2?{...s,phase:"reading",restPhase:"framing",current:void 0,needFlip:!1}:{...s,phase:"flipCue",restPhase:"flipCue",current:void 0,needFlip:!0}}function Ve(e,t,n){return e.pending.includes(t)?{...e,pending:e.pending.filter(o=>o!==t),lastShot:e.lastShot===t?void 0:e.lastShot,phase:e.phase==="capturing"?e.phase:"flipCue",restPhase:"flipCue",current:Xe(n),needFlip:!0,flipTimeoutSpent:!1,goodSince:void 0,manualShutter:!0,notice:"same_face",lastCaptureAt:-1,lastReportAt:-1}:e}function kt(e,t,n){if(!e.pending.includes(t))return e;if(e.captured[n]!==void 0)return Ve(e,t,n);let o=e.pending.filter(m=>m!==t),i={...e,pending:o,captured:{...e.captured,[n]:t}};if(le(i)!==1||e.layout==="singlePage")return i;let l=Xe(n),s=l==="recto"&&e.restPhase==="reaskRecto"?"reaskRecto":"flipCue",u=e.phase==="flipCue"||e.phase==="reaskRecto"||e.phase==="framing";return{...i,restPhase:s,current:l,phase:u?s:e.phase}}function Ct(e,t){let n=t.id??e.captured[t.side],o={...e.captured};(t.id===void 0||o[t.side]===t.id)&&delete o[t.side];let i=e.pending.filter(c=>c!==n),l=e.layout==="twoSided"&&le({captured:o,pending:i})>0,s=e.lastShotByTimeout||n===e.lastShot!==e.flipped,u=l&&!s,m=u?t.side==="recto"?"reaskRecto":"flipCue":"framing";return{...e,captured:o,pending:i,readSides:e.readSides.filter(c=>c!==t.side),lastShot:e.lastShot===n?void 0:e.lastShot,notice:t.issue,goodSince:void 0,manualShutter:!1,phase:m,restPhase:m,current:t.side,needFlip:u,flipped:!1,flipTimeoutSpent:!1,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1}}function Qe(e,t){switch(t.type){case"report":return Mt(se(e,t.at),t.report,t.at);case"tick":return Dt(se(e,t.at),t.at);case"captured":return wt(se(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 kt(e,t.id,t.side);case"duplicate":return Ve(e,t.id,t.side);case"readOk":{let n=e.readSides.includes(t.side)?e.readSides:[...e.readSides,t.side],o=["recto","verso"].filter(l=>e.captured[l]!==void 0),i=e.phase==="reading"&&e.pending.length===0&&o.every(l=>n.includes(l));return{...e,readSides:n,flipTimeoutSpent:!1,phase:i?"result":e.phase}}case"readFailed":return Ct(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{...ue(e.layout,-1),lastCaptureAt:-1,lastReportAt:-1};default:return e}}function xt(e,t,n=!1){let o=e(t);return o===null?"recto":!n||o.y+o.height/2>=t.height/2?"verso":"recto"}async function vt(e,t=!1){let{detectMrzBand:n}=await import("./mrz-band-VYHOTDHY.js");return xt(n,e,t)}async function ce(e,t=480,n,o=n!=null){let i=n??{x:0,y:0,width:e.width,height:e.height},l=Math.max(1,Math.round(i.height/i.width*t)),s=document.createElement("canvas");s.width=t,s.height=l;try{let u=s.getContext("2d");return u===null?"recto":(u.drawImage(e,i.x,i.y,i.width,i.height,0,0,t,l),await vt(u.getImageData(0,0,t,l),o))}finally{s.width=0,s.height=0}}async function Jt(e,t=480){try{let n=await createImageBitmap(e),o=Math.max(1,Math.round(n.height/n.width*t)),i=document.createElement("canvas");i.width=t,i.height=o;let l=i.getContext("2d");return l===null?(n.close(),null):(l.drawImage(n,0,0,t,o),n.close(),l.getImageData(0,0,t,o))}catch{return null}}var de=(e,t,n)=>Math.min(n,Math.max(t,Math.round(e))),Z=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function Ke(e,t,n,o){let i=o.decode??(m=>createImageBitmap(m)),l=async()=>e.stillRead(await i(t),o.region??[0,0,1,1],o.detectorLimit),s;try{s=await l()}catch{try{await new Promise(m=>setTimeout(m,o.retryMs??300)),s=await l()}catch{return null}}let u=s.mrzBox;return u===void 0?null:{engine:o.engine,source:"live_mrz",format:n.format,lineCount:de(n.lineCount,2,3),checkDigitsValid:!0,stillConfirmed:s.valid&&s.digest===n.digest,band:[Z(u[0]),Z(u[1]),Z(Math.min(u[2],1-u[0])),Z(Math.min(u[3],1-u[1]))],digest:n.digest,framesToValid:de(n.framesToValid,1,1e3),msToValid:de(n.msToValid,0,12e4)}}function en(e){let t=null;return e?.then(n=>{t=n}),()=>t}var Rt=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]),Pt=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 je(e=globalThis){let t=e.WebAssembly?.validate;if(typeof t!="function")return{ok:!1,reason:"simd"};try{if(!t.call(e.WebAssembly,Rt)||!t.call(e.WebAssembly,Pt))return{ok:!1,reason:"simd"}}catch{return{ok:!1,reason:"simd"}}return typeof e.Worker!="function"?{ok:!1,reason:"worker"}:typeof e.createImageBitmap!="function"?{ok:!1,reason:"bitmap"}:{ok:!0}}function $e(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 Je(){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 Ze(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 Je()}catch{return Je()}let n=new Map,o=0,i=!1,l=!1,s=!1;t.addEventListener("message",p=>{let g=p.data,M=n.get(g.id);M&&(n.delete(g.id),M.resolve(g))});let u=()=>{for(let p of n.values())p.reject(new E("error"));n.clear(),c()};t.addEventListener("error",u),t.addEventListener("messageerror",u);function m(p,g=[]){if(i)return Promise.reject(new E("disposed"));let M=++o;return new Promise((I,z)=>{n.set(M,{resolve:I,reject:z});try{t.postMessage({...p,id:M},g)}catch{n.delete(M),z(new E("error"))}})}function c(){if(!i){i=!0;try{t.postMessage({id:++o,kind:"dispose"})}catch{}t.terminate();for(let p of n.values())p.reject(new E("disposed"));n.clear()}}let b=(async()=>{let p=await m({kind:"init",baseUrl:e.baseUrl,salt:e.salt,detectorLimit:e.tuning.detectorLimit,maxDownloadMs:e.tuning.maxDownloadMs});if(p.kind==="failed")return p.reason;if(p.kind!=="ready")return"error";let g=await m({kind:"warmup"});if(g.kind!=="ready")return"error";let M=g.benchMs??g.warmupMs,I=e.deviceMemoryGb===void 0?Ee():e.deviceMemoryGb;return{warmupMs:g.warmupMs,downloadMs:p.downloadMs,cached:p.cached,benchMs:M,tier:Oe(M,I)}})().catch(()=>"error"),f,L=new Promise(p=>{f=setTimeout(()=>p("timeout"),e.tuning.loadTimeoutMs)}),k=Promise.race([b,L]).then(p=>(clearTimeout(f),typeof p=="string"?c():s=!0,i&&typeof p!="string"?"error":p));(e.page===void 0?globalThis.addEventListener?globalThis:null:e.page)?.addEventListener("pagehide",c,{once:!0});async function v(p,g,M){if(i)throw g.close(),new E("disposed");if(!s)throw g.close(),new E("not_ready");if(l)throw g.close(),new E("busy");l=!0;let I;try{let z=new Promise((N,G)=>{I=setTimeout(()=>{G(new E("timeout")),c()},e.tuning.readTimeoutMs??1e4)}),B=await Promise.race([m(p,[g]),z]);if(B.kind===M){let{id:N,...G}=B;return G}throw new E(B.kind==="error"?B.code:B.kind==="failed"?B.reason:"error")}finally{clearTimeout(I),l=!1}}return{ready:k,get busy(){return l},bandRead:(p,g=e.tuning.detectorLimit)=>v({kind:"band",bitmap:p,detectorLimit:g},p,"band"),stillRead:(p,g,M=e.tuning.detectorLimit)=>v({kind:"still",bitmap:p,region:g,detectorLimit:M},p,"band"),layoutRead:(p,g)=>v({kind:"layout",bitmap:p,detectorLimit:g},p,"layout"),dispose:c}}var V="sekyro-ocr-1",me=e=>e!==null&&typeof e=="object"?e:{},O=(e,t,n,o)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:o,et=(e,t)=>typeof e=="boolean"?e:t,tt=e=>{let t=typeof e=="string"?/^sekyro-ocr-(\d{1,4})$/.exec(e):null;return t?Number(t[1]):Number.POSITIVE_INFINITY};function nt(e,t={}){let n=me(e),o=me(n.liveMrz),i=me(n.frontLock),l=tt(t.engine??V),s=t.mode==="off",u=p=>p.enabled===!0?p.arm==="live"?"live":"control":null,m=u(o),c=u(i),b=(p,g)=>!s&&g==="live"&&tt(p.minEngine??V)<=l,f=Be,L=b(o,m)?{detectorLimit:O(o.detectorLimit,320,1600,f.detectorLimit),bandMaxWidthPx:O(o.bandMaxWidthPx,320,4096,f.bandMaxWidthPx),minBandWidthPx:O(o.minBandWidthPx,0,4096,f.minBandWidthPx),bandTop:O(o.bandTop,0,.95,f.bandTop),minIntervalMs:O(o.minIntervalMs,0,5e3,f.minIntervalMs),stableReads:Math.round(O(o.stableReads,1,10,f.stableReads)),profileReads:Math.round(O(o.profileReads,1,100,f.profileReads)),maxReadMs:O(o.maxReadMs,50,6e4,f.maxReadMs),searchTimeoutMs:O(o.searchTimeoutMs,1e3,12e4,f.searchTimeoutMs),hint:et(o.hint,!0),stillConfirm:et(o.stillConfirm,!0)}:null,k=Ae,S=(p,g,M)=>O(i[p],g,M,k[p]),v=b(i,c)?{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:L!==null||v!==null,liveMrz:L,textLock:v,liveMrzArm:m,frontLockArm:c,load:{detectorLimit:L?.detectorLimit??v?.detectorLimit??f.detectorLimit,loadTimeoutMs:O(o.loadTimeoutMs,1e3,12e4,2e4),maxDownloadMs:O(o.maxDownloadMs,1e3,12e4,2e4)},reportSampleRate:O(o.reportSampleRate,0,1,1)}}function rt(e,t){return e.enabled?!(t.probe??je)().ok||(t.slow??$e)()?{ok:!1,reason:"unsupported"}:{ok:!0,engine:Ze({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}:{},...t.deviceMemoryGb!==void 0?{deviceMemoryGb:t.deviceMemoryGb}:{}})}:{ok:!1,reason:"off"}}function Tt(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 W=e=>e===void 0||!Number.isFinite(e)?void 0:Math.min(6e5,Math.max(0,Math.round(e))),pe=(e,t,n)=>e===void 0||!Number.isFinite(e)?void 0:Math.min(n,Math.max(t,Math.round(e)));function ot(e){let t=e.assist??null,n=e.load!==null&&e.load!==void 0&&typeof e.load=="object"?e.load:null,o=typeof e.load=="string"?e.load:null,i=t!==null?t.outcome:o==="unsupported"||o==="download"||o==="integrity"?o:o==="error"||o==="timeout"?"error":"off",l={kind:"live_mrz",platform:"web",engine:e.engine??V,arm:e.arm,capture:e.capture,outcome:i,reads:pe(t?.reads??0,0,1e4)??0,browser:e.browser??Tt()},s=(u,m)=>{m!==void 0&&(l[u]=m)};return s("format",t?.format),s("framesToValid",pe(t?.framesToValid,1,1e4)),s("msToValid",W(t?.msToValid)),s("framesToLock",pe(t?.framesToLock,1,1e4)),s("msToLock",W(t?.msToLock)),s("msToCapture",W(e.msToCapture)),s("readP50Ms",W(t?.readP50Ms)),s("readP90Ms",W(t?.readP90Ms)),s("deviceClass",t?.deviceClass),n!==null&&(s("warmupMs",W(n.warmupMs)),s("downloadMs",W(n.downloadMs)),s("cached",n.cached),s("tier",n.tier),s("benchMs",W(n.benchMs))),s("stillConfirmed",e.stillConfirmed),s("typeMismatch",e.typeMismatch),l}function fe(e,t){return e===void 0?!1:t==="passport"?e!=="TD3":e==="TD3"}var Lt=2,_t=1500;async function Ot(e){let t=await import("./capture-session-doc-MGDYUASI.js");return new t.CaptureSessionDoc(e)}function Et(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 At(e,t,n){let o=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let l=0;l<o.length;l+=1){let s=o[l],u=o[(l+1)%o.length];i+=s.x*u.y-u.x*s.y}return t>0&&n>0?Math.abs(i)/2/(t*n):0}function kn(){import("./capture-session-doc-MGDYUASI.js").then(e=>e.warmDocDetector()).catch(()=>{})}function Cn(e){return Bt(e,{}).handle}function Bt(e,t){let n=Re(),o=Pe({enabled:e.keepScreenAwake!==!1}),i=t.decode??(r=>createImageBitmap(r)),l=t.blurRefuseSharpnessMax??.16,s=t.now??(()=>performance.now()),u=We(e.documentType,t.catalogCapture===!0?t.captureSeries??ze(e.issuer,e.documentType):[]),m=u.sides.length===1||e.side==="single",c=ue(m?"singlePage":"twoSided",s());if(!m&&(e.side==="recto"||e.side==="verso")){let r=e.side==="recto"?"verso":"recto";c={...c,captured:{[r]:"server"},readSides:[r],current:e.side,phase:"flipCue",restPhase:"flipCue"}}let b="idle",f=null,L=null,k=!0,S=0,v=0,p=null,g=!1,M=!1,I="",z=null,B,N=null,G=[],ge=u.mrz==="none",at=u.barcodeSide==="recto"||u.barcodeSide==="verso"?u.barcodeSide:null,q=ge&&!m?t.barcode?.side??at:null,he=e.barcodeAssetBaseUrl??t.barcode?.assetBaseUrl,be=null,Se=()=>q===null||he===void 0||t.barcode?.seen!==void 0?Promise.resolve(null):(be??(be=import("./barcode-detect-C5IOXMKI.js").then(r=>r.loadBarcodeDetect(he)).catch(()=>null)),be),it=(r,a)=>{if(q===null)return Promise.resolve(null);let d,h=new Promise(D=>{d=setTimeout(()=>D(null),t.barcode?.budgetMs??_t)});return Promise.race([st(r,a,q),h]).finally(()=>clearTimeout(d))},st=async(r,a,d)=>{let h=d==="recto"?"verso":"recto";try{let D=t.barcode?.seen;if(D!==void 0)return await D(r)?d:h;let[_,x]=await Promise.all([Se(),a()]);if(_===null||x===null)return null;let y=Math.min(1600,x.width),w=document.createElement("canvas");w.width=y,w.height=Math.max(1,Math.round(x.height/x.width*y));try{let A=w.getContext("2d");return A===null?null:(A.drawImage(x,0,0,w.width,w.height),await Ue(_,A.getImageData(0,0,w.width,w.height),d))}finally{w.width=0,w.height=0}}catch{return null}},C=t.webOcr!==void 0&&!ge?nt(t.webOcr.captureDocument,{mode:e.liveMrz?.mode??"auto"}):null,X=null,F=C===null||!C.enabled?"off":null,Q=null,K=null,ye=new WeakMap,ee="";if(C!==null&&C.enabled&&t.webOcr!==void 0){let r=t.webOcr,a=rt(C,{baseUrl:e.liveMrz?.assetBaseUrl??r.baseUrl,salt:r.salt,...e.liveMrz?.workerUrl!==void 0?{workerUrl:e.liveMrz.workerUrl}:{},...r.createWorker!==void 0?{createWorker:r.createWorker}:{}});if(a.ok){X=a.engine;let d=new Ie({textLock:C.textLock,liveMrz:C.liveMrz});Q=d;let h=a.engine;h.ready.then(D=>{F=D,typeof D!="string"&&k&&d.setEngine(h,D.tier)})}else F=a.reason}let H=r=>{let a=JSON.stringify(r);a!==ee&&(ee=a,n.emit("mrz",r))},Me=(r,a)=>{let d=t.webOcr?.reports;if(d===void 0||C===null||r===void 0)return;let h=r.format==="ID-3"||r.side==="single"?"single":r.side==="verso"?"verso":"recto",D=h!=="recto"?C.liveMrzArm??C.frontLockArm:C.frontLockArm;if(D===null||Math.random()>=C.reportSampleRate)return;let _=r.via==="live_mrz"?K:null,x=()=>{let y=_?.value??null;d([ot({arm:D,capture:h,assist:r.ocr??null,load:D==="control"?"off":F,...r.msToCapture!==void 0?{msToCapture:r.msToCapture}:{},...y!==null&&y.stillConfirmed!==void 0?{stillConfirmed:y.stillConfirmed}:{},...a!==void 0?{typeMismatch:fe(a.format,u.format==="ID-3"?"passport":"card")}:{}})])};_!==null&&_.value===null?Promise.race([_.promise,new Promise(y=>setTimeout(y,3e3))]).then(x):x()},U=r=>{!k||r===b||(b=r,o.setActive(r==="starting"||r==="scanning"),n.emit("state",r))},ut=(r,a)=>a===void 0?null:m?"single":r.captured.recto===a?"recto":r.captured.verso===a?"verso":null,lt=r=>({phase:r.phase,captured:m?r.captured.recto!==void 0?["single"]:[]:["recto","verso"].filter(a=>r.captured[a]!==void 0),expected:m?null:r.current??null,notice:r.notice??null,lastShot:ut(r,r.lastShot),manualShutter:r.manualShutter,torchAvailable:f?.torchAvailable()??!1,torch:M}),De=()=>{let r=f;r!==null&&r.captureNow().catch(()=>R({type:"captureFailed",at:s()}))};function R(r){if(!k)return;let a=c;c=Qe(c,r),c.phase==="capturing"&&a.phase!=="capturing"&&Promise.resolve().then(De),c.phase==="result"&&a.phase!=="result"&&(U("done"),we());let d=lt(c),h=JSON.stringify(d);h!==I&&(I=h,n.emit("scan",d))}function we(){N!==null&&clearInterval(N),N=null;for(let r of G.splice(0))r();f?.destroy(),f=null,o.setActive(!1)}let ke=()=>f?.captureReport?.(),te=!1,Ce=(r,a)=>{if(!(r===void 0||t.onFaceReport===void 0))try{t.onFaceReport(r,a)}catch{}},j=r=>{ee="",!(f===null||c.phase==="reading"||c.phase==="result")&&(te=!1,p=m?"single":c.current??r,f.rearm(p))},ct=async(r,a,d,h)=>{K=null;let D=F!==null&&typeof F=="object"&&F.tier==="low";if(h!==void 0&&X!==null&&C?.liveMrz?.hint===!0&&!D){let A={promise:Ke(X,r,h,{engine:V,detectorLimit:C.liveMrz.detectorLimit}).catch(()=>null),value:null};A.promise.then(P=>{A.value=P}),K=A}h!==void 0&&fe(h.format,u.format==="ID-3"?"passport":"card")&&H({state:"mismatch",format:h.format});let _=ke();Ce(_,"captured"),te=!0,Me(_,h);let x=d===void 0?z:d===null?null:{quad:Et(d),frameWidth:0,frameHeight:0,inStill:!0},y={decoded:null},w=()=>(y.decoded??(y.decoded=Promise.resolve().then(()=>i(r)).catch(()=>null)),y.decoded);try{await dt(r,a,x,w,K,h)}finally{y.decoded!==null&&(await y.decoded)?.close()}},dt=async(r,a,d,h,D,_)=>{let x=`shot-${S+=1}`,y=c.current;if(R({type:"captured",id:x,at:s()}),e.haptics!==!1)try{globalThis.navigator?.vibrate?.(30)}catch{}if(!g&&l>0){let P=await(t.measureSharpness!==void 0?t.measureSharpness(r,d):h().then(T=>T===null?-1:_e(T,ae(d?.quad??null,d?.inStill===!0?T:{width:d?.frameWidth??0,height:d?.frameHeight??0},T)))).catch(()=>-1);if(!k)return;if(Number.isFinite(P)&&P>=0&&P<l){g=!0;let T=m?"recto":c.current??(c.captured.recto===void 0?"recto":"verso");R({type:"readFailed",side:T,id:x,issue:"blurry"}),j(T);return}}g=!1;let w;if(m)w="single";else{let P=_!==void 0&&_.format!=="TD3"&&(u.mrzSide==="recto"||u.mrzSide==="verso")?u.mrzSide:null,T=P===null&&t.classify===void 0?await it(r,h):null,xe=T===null||q===null?T:Ne(T,q,c.captured),Y=P??xe??(xe===null&&q!==null&&y!==void 0?y:null)??await(t.classify!==void 0?t.classify(r):h().then($=>$===null?y??"recto":d?.inStill===!0?ce($,480,null,!0):ce($,480,ae(d?.quad??null,{width:d?.frameWidth??0,height:d?.frameHeight??0},$)))).catch(()=>y??"recto");if(!k)return;if(c.captured[Y]!==void 0&&v<Lt){v+=1,R({type:"duplicate",id:x,side:Y}),j(Y==="recto"?"verso":"recto");return}let ve=c.captured.recto===void 0?"recto":c.captured.verso===void 0?"verso":void 0;w=c.captured[Y]!==void 0&&ve!==void 0?ve:Y,v=0,R({type:"classified",id:x,side:w})}let A=w==="verso"?"verso":"recto";try{let P=t.encode!==void 0?await t.encode(r):await h().then(T=>{if(T===null)throw new Error("the still could not be decoded");return ie(T)});if(!k)return;D!==null&&ye.set(P.blob,D),n.emit("captured",{image:P.blob,side:w,documentType:e.documentType,...e.issuer!==void 0?{issuer:e.issuer}:{},width:P.width,height:P.height,previewDataUrl:a}),t.deferRead!==!0&&R({type:"readOk",side:A})}catch(P){R({type:"readFailed",side:A,id:x,issue:"technical"}),n.emit("error",J("generic",!0,{phase:"keyframes",name:re(P)}))}j(A==="recto"?"verso":"recto")},mt=r=>{G.push(r.on("statechange",({state:a})=>{a==="preflight"||a==="acquiring"?U("starting"):a==="positioning"?U("scanning"):a==="captured"?U("captured"):a==="error"&&U("error")}),r.on("feedback",({key:a,reticle:d})=>n.emit("feedback",{key:a,reticle:d})),r.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 d=a.ocr?.mrz;d!==void 0&&(d.state==="fallback"?H({state:"fallback",reason:d.reason}):d.state==="valid"?H({state:"valid",format:d.format}):d.state==="reading"?H({state:"reading",...d.format?{format:d.format}:{},...d.coach?{coach:d.coach}:{}}):H({state:"searching"}));let h=a.quad===null?0:At(a.quad,a.frameWidth,a.frameHeight);z=a.quad===null?null:{quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight},R({type:"report",report:{present:a.quad!==null&&a.plausible||a.guide?.detected===!0,ready:a.ready===!0,locking:a.p>=.5,areaFrac:h},at:s()})}),r.on("error",({kind:a,retryable:d,detail:h})=>n.emit("error",J(a,d,h))),r.on("artifacts",a=>{ct(a.keyframe,a.previewDataUrl,a.docRegion,a.liveMrz)}))},ne=()=>(L??(L=(async()=>{if(k){if(Se(),f===null){let r;try{r=await(t.createEngine??Ot)({...t.engineOptions??{},...B!==void 0?{guide:B}:{},video:e.video,format:u.format,side:m?"single":e.side??"recto",autoCapture:!1,...Q!==null?{ocr:Q}:{}})}catch(d){U("error"),n.emit("error",J("models",!0,{phase:"models",name:re(d)}));return}if(!k){r.destroy();return}f=r,p=m?"single":e.side??"recto",mt(r);let a=t.tickMs??500;a>0&&(N=setInterval(()=>R({type:"tick",at:s()}),a))}R({type:"clockRestart"}),C!==null&&C.liveMrzArm==="live"&&(F==="unsupported"||F==="off")&&H({state:"fallback",reason:F}),await f.start()}})().finally(()=>{L=null})),L);return{handle:{get state(){return b},on:(r,a)=>n.on(r,a),start:ne,retry:()=>{if(f===null&&c.phase==="result"){R({type:"retake"}),v=0,g=!1,ne();return}if(f!==null&&b!=="error"){R({type:"retake"}),v=0,g=!1,p=m?"single":null,f.rearm(m?"single":void 0);return}ne()},setSide:r=>{m||r==="single"||f!==null&&c.current===r&&p===r&&c.phase!=="reading"&&c.phase!=="result"||(c.current!==r&&(c={...c,current:r}),R({type:"clockRestart"}),c.phase!=="reading"&&c.phase!=="result"&&f!==null&&(p=r,f.rearm(r)))},shutter:De,focusAt:(r,a)=>{f?.focusAt?.(r,a)},setGuide:r=>{B=r,f?.setGuide?.(r)},setTorch:r=>{M=r,f?.setTorch(r),R({type:"tick",at:s()})},destroy:()=>{if(k&&f!==null&&b!=="done"){let r=ke();!te&&r!==void 0&&r.ticks>0&&Ce(r,"abandoned"),Me(r,void 0)}k=!1,we(),Q?.setEngine(null),X?.dispose(),X=null,n.clear()}},plan:u,setFlowState:r=>{(c.phase==="reading"||c.phase==="result")&&U(r==="done"&&c.phase!=="result"?"scanning":r)},settle:(r,a)=>{let d=r==="verso"?"verso":"recto";R(a.ok?{type:"readOk",side:d}:{type:"readFailed",side:d,issue:a.issue}),a.ok||j(d)},takeDeviceRead:r=>ye.get(r.image)?.value??null}}export{Ht as a,Yt as b,Vt as c,Qt as d,Kt as e,jt as f,He as g,ue as h,Qe as i,xt as j,vt as k,Jt as l,Ke as m,en as n,V as o,nt as p,rt as q,Tt as r,ot as s,fe as t,Lt as u,_t as v,kn as w,Cn as x,Bt as y};
1
+ import{d as ae,h as _e,i as Ae,j as Be,l as Ie}from"./chunk-MQHTFHSN.js";import{a as oe,e as Te,g as Le}from"./chunk-BRLQIJYF.js";import{m as J}from"./chunk-P5OIQXVM.js";import{a as Re,g as Pe}from"./chunk-7QZWBDI5.js";import{k as re}from"./chunk-CPUECYAJ.js";import{d as Oe,g as Ee}from"./chunk-WNBEOK5Q.js";function Fe(e,t){let n=new Set(e.flatMap(o=>o.sides.filter(i=>i[t]!==null).map(i=>i.side)));return n.size===1?[...n][0]:null}function pt(e){let t=Te.find(o=>o.docType===e),n=t.mrz==="none"?null:t.mrz==="td3"?"single":"verso";return{sides:t.sides,format:Le(e),mrz:t.mrz==="none"?"none":"required",mrzSide:n,barcodeSide:null,portraitSide:t.portraitSide,scripts:null}}function ft(e){let t=[];for(let n of e)for(let o of n.sides){if(!Array.isArray(o.scripts))return null;for(let i of o.scripts)t.includes(i)||t.push(i)}return t}function We(e,t){if(t.length===0)return pt(e);let n=t.some(u=>u.sides.length>1),o=new Set(t.map(u=>u.format)),i=o.size===1?[...o][0]:"card",l=t.filter(u=>u.sides.some(m=>m.mrz!==null)).length,s=t.find(u=>u.sides.length>1===n)?.sides.find(u=>u.portrait)?.side;return{sides:n?["recto","verso"]:["single"],format:i,mrz:l===t.length?"required":l===0?"none":"optional",mrzSide:Fe(t,"mrz"),barcodeSide:Fe(t,"barcode"),portraitSide:s??(n?"recto":"single"),scripts:ft(t)}}function ze(e,t){if(e===void 0)return[];let n=e.toUpperCase();return Object.prototype.hasOwnProperty.call(oe,n)?oe[n]?.[t]??[]:[]}async function Ue(e,t,n){return await e(t)?n:n==="recto"?"verso":"recto"}function Ne(e,t,n){return e!==t&&t==="verso"&&n.recto!==void 0&&n.verso===void 0?"verso":e}var gt={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 ht(e){let{deviceMemory:t,effectiveType:n,saveData:o,downlinkMbps:i,sourceLongEdge:l}=e,s=o===!0||n==="slow-2g"||n==="2g"||i!=null&&i>0&&i<1,u=t!=null&&t<=2,m=n==="4g"||i!=null&&i>=5,c=t!=null&&t>=6,b;s||u?b="low":m&&c?b="good":b="mid";let f=gt[b],L=l&&l>0?Math.min(f.maxLongEdge,l):f.maxLongEdge;return{tier:b,...f,maxLongEdge:L}}function Ge(e){let t={};try{let n=navigator;typeof n.deviceMemory=="number"&&(t.deviceMemory=n.deviceMemory);let o=n.connection;o&&(t.effectiveType=o.effectiveType,t.saveData=o.saveData,t.downlinkMbps=o.downlink)}catch{}return typeof e=="number"&&e>0&&(t.sourceLongEdge=e),ht(t)}function bt(e,t,n){let o=Math.min(1,Math.max(0,(e-.28)/.21999999999999997)),i=(t+n)/2;return Math.max(t,n-o*(n-i))}function St(e,t,n){let o=Math.max(e,t),i=o>0?Math.min(1,n/o):1;return{width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(t*i))}}async function yt(e,t){let n=t.startQ,o=await e(n);for(let i=0;i<4&&!(o.size<=t.budgetBytes||n<=t.qMin);i++)n=Math.max(t.qMin,n-.08),o=await e(n);return{blob:o,quality:n}}async function qe(e,t,n,o,i){if(t<=0||n<=0)return null;let{width:l,height:s}=St(t,n,o.maxLongEdge),u=document.createElement("canvas");u.width=l,u.height=s;let m=u.getContext("2d");if(!m)return null;m.drawImage(e,0,0,l,s);let c=k=>new Promise((S,v)=>{u.toBlob(p=>p?S(p):v(new Error("canvas toBlob returned null")),"image/jpeg",k)}),b=bt(i,o.qMin,o.qMax),{blob:f,quality:L}=await yt(c,{startQ:b,qMin:o.qMin,budgetBytes:o.payloadTargetBytes}).finally(()=>{u.width=0,u.height=0});if(f.size>5242880)throw new Error("encoded document exceeds the 5242880-byte media cap");return{blob:f,quality:L,width:l,height:s}}async function ie(e){let t=Ge(Math.max(e.width,e.height)),n=await qe(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 Ht(e){let t=await createImageBitmap(e);try{return await ie(t)}finally{t.close()}}var Yt=250,Vt=.6,Qt=1800,Kt=6e3,jt=2e3,He=.16;function ue(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 Xe=e=>e==="recto"?"verso":"recto",Ye=e=>e.phase==="framing"||e.phase==="locking"||e.phase==="flipCue"||e.phase==="reaskRecto",le=e=>(e.captured.recto!==void 0?1:0)+(e.captured.verso!==void 0?1:0)+e.pending.length;function se(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 Mt(e,t,n){if(e.phase==="result")return{...e,lastReportAt:n};let o=!t.present||e.captureArea!==void 0&&t.areaFrac<.6*e.captureArea,{flipped:i,awaySince:l}=e;o&&(l=l??n),l!==void 0&&n-l>=250&&(i=!0),o||(l=void 0);let s=e.flipTimeoutSpent&&!(i&&!e.flipped),u=e.notice==="same_face"&&i&&!e.flipped?void 0:e.notice,m={...e,lastReportAt:n,flipped:i,awaySince:l,flipTimeoutSpent:s,notice:u,lastArea:t.areaFrac};if(!Ye(e))return m;if(e.needFlip&&!i){if(!t.ready)return{...m,phase:e.restPhase,goodSince:void 0};let c=e.lastShot!==void 0&&e.pending.includes(e.lastShot);if(s||c)return{...m,goodSince:void 0,phase:e.restPhase};let b=e.goodSince??n;return n-b>=1800?{...m,goodSince:b,phase:"capturing",flipTimeoutSpent:!0,timeoutCapture:!0}:{...m,goodSince:b,phase:e.restPhase}}return t.ready?{...m,phase:"capturing",goodSince:e.goodSince??n}:{...m,goodSince:void 0,phase:t.locking?"locking":e.restPhase}}function Dt(e,t){if(!Ye(e)||e.manualShutter)return e;let n=t-e.lastReportAt>=2e3,o=t-e.lastCaptureAt>=6e3;return n||o?{...e,manualShutter:!0}:e}function wt(e,t,n){let o=e.layout==="singlePage",i=o?{recto:t}:e.captured,l=o?[]:[...e.pending,t],s={...e,captured:i,pending:l,lastShot:t,lastCaptureAt:n,lastReportAt:-1,manualShutter:!1,goodSince:void 0,notice:void 0,awaySince:void 0,flipped:!1,lastShotByTimeout:e.timeoutCapture,timeoutCapture:!1,captureArea:e.lastArea};return o||le({captured:i,pending:l})>=2?{...s,phase:"reading",restPhase:"framing",current:void 0,needFlip:!1}:{...s,phase:"flipCue",restPhase:"flipCue",current:void 0,needFlip:!0}}function Ve(e,t,n){return e.pending.includes(t)?{...e,pending:e.pending.filter(o=>o!==t),lastShot:e.lastShot===t?void 0:e.lastShot,phase:e.phase==="capturing"?e.phase:"flipCue",restPhase:"flipCue",current:Xe(n),needFlip:!0,flipTimeoutSpent:!1,goodSince:void 0,manualShutter:!0,notice:"same_face",lastCaptureAt:-1,lastReportAt:-1}:e}function kt(e,t,n){if(!e.pending.includes(t))return e;if(e.captured[n]!==void 0)return Ve(e,t,n);let o=e.pending.filter(m=>m!==t),i={...e,pending:o,captured:{...e.captured,[n]:t}};if(le(i)!==1||e.layout==="singlePage")return i;let l=Xe(n),s=l==="recto"&&e.restPhase==="reaskRecto"?"reaskRecto":"flipCue",u=e.phase==="flipCue"||e.phase==="reaskRecto"||e.phase==="framing";return{...i,restPhase:s,current:l,phase:u?s:e.phase}}function Ct(e,t){let n=t.id??e.captured[t.side],o={...e.captured};(t.id===void 0||o[t.side]===t.id)&&delete o[t.side];let i=e.pending.filter(c=>c!==n),l=e.layout==="twoSided"&&le({captured:o,pending:i})>0,s=e.lastShotByTimeout||n===e.lastShot!==e.flipped,u=l&&!s,m=u?t.side==="recto"?"reaskRecto":"flipCue":"framing";return{...e,captured:o,pending:i,readSides:e.readSides.filter(c=>c!==t.side),lastShot:e.lastShot===n?void 0:e.lastShot,notice:t.issue,goodSince:void 0,manualShutter:!1,phase:m,restPhase:m,current:t.side,needFlip:u,flipped:!1,flipTimeoutSpent:!1,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1}}function Qe(e,t){switch(t.type){case"report":return Mt(se(e,t.at),t.report,t.at);case"tick":return Dt(se(e,t.at),t.at);case"captured":return wt(se(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 kt(e,t.id,t.side);case"duplicate":return Ve(e,t.id,t.side);case"readOk":{let n=e.readSides.includes(t.side)?e.readSides:[...e.readSides,t.side],o=["recto","verso"].filter(l=>e.captured[l]!==void 0),i=e.phase==="reading"&&e.pending.length===0&&o.every(l=>n.includes(l));return{...e,readSides:n,flipTimeoutSpent:!1,phase:i?"result":e.phase}}case"readFailed":return Ct(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{...ue(e.layout,-1),lastCaptureAt:-1,lastReportAt:-1};default:return e}}function xt(e,t,n=!1){let o=e(t);return o===null?"recto":!n||o.y+o.height/2>=t.height/2?"verso":"recto"}async function vt(e,t=!1){let{detectMrzBand:n}=await import("./mrz-band-VYHOTDHY.js");return xt(n,e,t)}async function ce(e,t=480,n,o=n!=null){let i=n??{x:0,y:0,width:e.width,height:e.height},l=Math.max(1,Math.round(i.height/i.width*t)),s=document.createElement("canvas");s.width=t,s.height=l;try{let u=s.getContext("2d");return u===null?"recto":(u.drawImage(e,i.x,i.y,i.width,i.height,0,0,t,l),await vt(u.getImageData(0,0,t,l),o))}finally{s.width=0,s.height=0}}async function Jt(e,t=480){try{let n=await createImageBitmap(e),o=Math.max(1,Math.round(n.height/n.width*t)),i=document.createElement("canvas");i.width=t,i.height=o;let l=i.getContext("2d");return l===null?(n.close(),null):(l.drawImage(n,0,0,t,o),n.close(),l.getImageData(0,0,t,o))}catch{return null}}var de=(e,t,n)=>Math.min(n,Math.max(t,Math.round(e))),Z=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function Ke(e,t,n,o){let i=o.decode??(m=>createImageBitmap(m)),l=async()=>e.stillRead(await i(t),o.region??[0,0,1,1],o.detectorLimit),s;try{s=await l()}catch{try{await new Promise(m=>setTimeout(m,o.retryMs??300)),s=await l()}catch{return null}}let u=s.mrzBox;return u===void 0?null:{engine:o.engine,source:"live_mrz",format:n.format,lineCount:de(n.lineCount,2,3),checkDigitsValid:!0,stillConfirmed:s.valid&&s.digest===n.digest,band:[Z(u[0]),Z(u[1]),Z(Math.min(u[2],1-u[0])),Z(Math.min(u[3],1-u[1]))],digest:n.digest,framesToValid:de(n.framesToValid,1,1e3),msToValid:de(n.msToValid,0,12e4)}}function en(e){let t=null;return e?.then(n=>{t=n}),()=>t}var Rt=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]),Pt=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 je(e=globalThis){let t=e.WebAssembly?.validate;if(typeof t!="function")return{ok:!1,reason:"simd"};try{if(!t.call(e.WebAssembly,Rt)||!t.call(e.WebAssembly,Pt))return{ok:!1,reason:"simd"}}catch{return{ok:!1,reason:"simd"}}return typeof e.Worker!="function"?{ok:!1,reason:"worker"}:typeof e.createImageBitmap!="function"?{ok:!1,reason:"bitmap"}:{ok:!0}}function $e(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 Je(){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 Ze(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 Je()}catch{return Je()}let n=new Map,o=0,i=!1,l=!1,s=!1;t.addEventListener("message",p=>{let g=p.data,M=n.get(g.id);M&&(n.delete(g.id),M.resolve(g))});let u=()=>{for(let p of n.values())p.reject(new E("error"));n.clear(),c()};t.addEventListener("error",u),t.addEventListener("messageerror",u);function m(p,g=[]){if(i)return Promise.reject(new E("disposed"));let M=++o;return new Promise((I,z)=>{n.set(M,{resolve:I,reject:z});try{t.postMessage({...p,id:M},g)}catch{n.delete(M),z(new E("error"))}})}function c(){if(!i){i=!0;try{t.postMessage({id:++o,kind:"dispose"})}catch{}t.terminate();for(let p of n.values())p.reject(new E("disposed"));n.clear()}}let b=(async()=>{let p=await m({kind:"init",baseUrl:e.baseUrl,salt:e.salt,detectorLimit:e.tuning.detectorLimit,maxDownloadMs:e.tuning.maxDownloadMs});if(p.kind==="failed")return p.reason;if(p.kind!=="ready")return"error";let g=await m({kind:"warmup"});if(g.kind!=="ready")return"error";let M=g.benchMs??g.warmupMs,I=e.deviceMemoryGb===void 0?Ee():e.deviceMemoryGb;return{warmupMs:g.warmupMs,downloadMs:p.downloadMs,cached:p.cached,benchMs:M,tier:Oe(M,I)}})().catch(()=>"error"),f,L=new Promise(p=>{f=setTimeout(()=>p("timeout"),e.tuning.loadTimeoutMs)}),k=Promise.race([b,L]).then(p=>(clearTimeout(f),typeof p=="string"?c():s=!0,i&&typeof p!="string"?"error":p));(e.page===void 0?globalThis.addEventListener?globalThis:null:e.page)?.addEventListener("pagehide",c,{once:!0});async function v(p,g,M){if(i)throw g.close(),new E("disposed");if(!s)throw g.close(),new E("not_ready");if(l)throw g.close(),new E("busy");l=!0;let I;try{let z=new Promise((N,G)=>{I=setTimeout(()=>{G(new E("timeout")),c()},e.tuning.readTimeoutMs??1e4)}),B=await Promise.race([m(p,[g]),z]);if(B.kind===M){let{id:N,...G}=B;return G}throw new E(B.kind==="error"?B.code:B.kind==="failed"?B.reason:"error")}finally{clearTimeout(I),l=!1}}return{ready:k,get busy(){return l},bandRead:(p,g=e.tuning.detectorLimit)=>v({kind:"band",bitmap:p,detectorLimit:g},p,"band"),stillRead:(p,g,M=e.tuning.detectorLimit)=>v({kind:"still",bitmap:p,region:g,detectorLimit:M},p,"band"),layoutRead:(p,g)=>v({kind:"layout",bitmap:p,detectorLimit:g},p,"layout"),dispose:c}}var V="sekyro-ocr-1",me=e=>e!==null&&typeof e=="object"?e:{},O=(e,t,n,o)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:o,et=(e,t)=>typeof e=="boolean"?e:t,tt=e=>{let t=typeof e=="string"?/^sekyro-ocr-(\d{1,4})$/.exec(e):null;return t?Number(t[1]):Number.POSITIVE_INFINITY};function nt(e,t={}){let n=me(e),o=me(n.liveMrz),i=me(n.frontLock),l=tt(t.engine??V),s=t.mode==="off",u=p=>p.enabled===!0?p.arm==="live"?"live":"control":null,m=u(o),c=u(i),b=(p,g)=>!s&&g==="live"&&tt(p.minEngine??V)<=l,f=Be,L=b(o,m)?{detectorLimit:O(o.detectorLimit,320,1600,f.detectorLimit),bandMaxWidthPx:O(o.bandMaxWidthPx,320,4096,f.bandMaxWidthPx),minBandWidthPx:O(o.minBandWidthPx,0,4096,f.minBandWidthPx),bandTop:O(o.bandTop,0,.95,f.bandTop),minIntervalMs:O(o.minIntervalMs,0,5e3,f.minIntervalMs),stableReads:Math.round(O(o.stableReads,1,10,f.stableReads)),profileReads:Math.round(O(o.profileReads,1,100,f.profileReads)),maxReadMs:O(o.maxReadMs,50,6e4,f.maxReadMs),searchTimeoutMs:O(o.searchTimeoutMs,1e3,12e4,f.searchTimeoutMs),hint:et(o.hint,!0),stillConfirm:et(o.stillConfirm,!0)}:null,k=Ae,S=(p,g,M)=>O(i[p],g,M,k[p]),v=b(i,c)?{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:L!==null||v!==null,liveMrz:L,textLock:v,liveMrzArm:m,frontLockArm:c,load:{detectorLimit:L?.detectorLimit??v?.detectorLimit??f.detectorLimit,loadTimeoutMs:O(o.loadTimeoutMs,1e3,12e4,2e4),maxDownloadMs:O(o.maxDownloadMs,1e3,12e4,2e4)},reportSampleRate:O(o.reportSampleRate,0,1,1)}}function rt(e,t){return e.enabled?!(t.probe??je)().ok||(t.slow??$e)()?{ok:!1,reason:"unsupported"}:{ok:!0,engine:Ze({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}:{},...t.deviceMemoryGb!==void 0?{deviceMemoryGb:t.deviceMemoryGb}:{}})}:{ok:!1,reason:"off"}}function Tt(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 W=e=>e===void 0||!Number.isFinite(e)?void 0:Math.min(6e5,Math.max(0,Math.round(e))),pe=(e,t,n)=>e===void 0||!Number.isFinite(e)?void 0:Math.min(n,Math.max(t,Math.round(e)));function ot(e){let t=e.assist??null,n=e.load!==null&&e.load!==void 0&&typeof e.load=="object"?e.load:null,o=typeof e.load=="string"?e.load:null,i=t!==null?t.outcome:o==="unsupported"||o==="download"||o==="integrity"?o:o==="error"||o==="timeout"?"error":"off",l={kind:"live_mrz",platform:"web",engine:e.engine??V,arm:e.arm,capture:e.capture,outcome:i,reads:pe(t?.reads??0,0,1e4)??0,browser:e.browser??Tt()},s=(u,m)=>{m!==void 0&&(l[u]=m)};return s("format",t?.format),s("framesToValid",pe(t?.framesToValid,1,1e4)),s("msToValid",W(t?.msToValid)),s("framesToLock",pe(t?.framesToLock,1,1e4)),s("msToLock",W(t?.msToLock)),s("msToCapture",W(e.msToCapture)),s("readP50Ms",W(t?.readP50Ms)),s("readP90Ms",W(t?.readP90Ms)),s("deviceClass",t?.deviceClass),n!==null&&(s("warmupMs",W(n.warmupMs)),s("downloadMs",W(n.downloadMs)),s("cached",n.cached),s("tier",n.tier),s("benchMs",W(n.benchMs))),s("stillConfirmed",e.stillConfirmed),s("typeMismatch",e.typeMismatch),l}function fe(e,t){return e===void 0?!1:t==="passport"?e!=="TD3":e==="TD3"}var Lt=2,_t=1500;async function Ot(e){let t=await import("./capture-session-doc-J4MIDQOS.js");return new t.CaptureSessionDoc(e)}function Et(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 At(e,t,n){let o=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let l=0;l<o.length;l+=1){let s=o[l],u=o[(l+1)%o.length];i+=s.x*u.y-u.x*s.y}return t>0&&n>0?Math.abs(i)/2/(t*n):0}function kn(){import("./capture-session-doc-J4MIDQOS.js").then(e=>e.warmDocDetector()).catch(()=>{})}function Cn(e){return Bt(e,{}).handle}function Bt(e,t){let n=Re(),o=Pe({enabled:e.keepScreenAwake!==!1}),i=t.decode??(r=>createImageBitmap(r)),l=t.blurRefuseSharpnessMax??.16,s=t.now??(()=>performance.now()),u=We(e.documentType,t.catalogCapture===!0?t.captureSeries??ze(e.issuer,e.documentType):[]),m=u.sides.length===1||e.side==="single",c=ue(m?"singlePage":"twoSided",s());if(!m&&(e.side==="recto"||e.side==="verso")){let r=e.side==="recto"?"verso":"recto";c={...c,captured:{[r]:"server"},readSides:[r],current:e.side,phase:"flipCue",restPhase:"flipCue"}}let b="idle",f=null,L=null,k=!0,S=0,v=0,p=null,g=!1,M=!1,I="",z=null,B,N=null,G=[],ge=u.mrz==="none",at=u.barcodeSide==="recto"||u.barcodeSide==="verso"?u.barcodeSide:null,q=ge&&!m?t.barcode?.side??at:null,he=e.barcodeAssetBaseUrl??t.barcode?.assetBaseUrl,be=null,Se=()=>q===null||he===void 0||t.barcode?.seen!==void 0?Promise.resolve(null):(be??(be=import("./barcode-detect-C5IOXMKI.js").then(r=>r.loadBarcodeDetect(he)).catch(()=>null)),be),it=(r,a)=>{if(q===null)return Promise.resolve(null);let d,h=new Promise(D=>{d=setTimeout(()=>D(null),t.barcode?.budgetMs??_t)});return Promise.race([st(r,a,q),h]).finally(()=>clearTimeout(d))},st=async(r,a,d)=>{let h=d==="recto"?"verso":"recto";try{let D=t.barcode?.seen;if(D!==void 0)return await D(r)?d:h;let[_,x]=await Promise.all([Se(),a()]);if(_===null||x===null)return null;let y=Math.min(1600,x.width),w=document.createElement("canvas");w.width=y,w.height=Math.max(1,Math.round(x.height/x.width*y));try{let A=w.getContext("2d");return A===null?null:(A.drawImage(x,0,0,w.width,w.height),await Ue(_,A.getImageData(0,0,w.width,w.height),d))}finally{w.width=0,w.height=0}}catch{return null}},C=t.webOcr!==void 0&&!ge?nt(t.webOcr.captureDocument,{mode:e.liveMrz?.mode??"auto"}):null,X=null,F=C===null||!C.enabled?"off":null,Q=null,K=null,ye=new WeakMap,ee="";if(C!==null&&C.enabled&&t.webOcr!==void 0){let r=t.webOcr,a=rt(C,{baseUrl:e.liveMrz?.assetBaseUrl??r.baseUrl,salt:r.salt,...e.liveMrz?.workerUrl!==void 0?{workerUrl:e.liveMrz.workerUrl}:{},...r.createWorker!==void 0?{createWorker:r.createWorker}:{}});if(a.ok){X=a.engine;let d=new Ie({textLock:C.textLock,liveMrz:C.liveMrz});Q=d;let h=a.engine;h.ready.then(D=>{F=D,typeof D!="string"&&k&&d.setEngine(h,D.tier)})}else F=a.reason}let H=r=>{let a=JSON.stringify(r);a!==ee&&(ee=a,n.emit("mrz",r))},Me=(r,a)=>{let d=t.webOcr?.reports;if(d===void 0||C===null||r===void 0)return;let h=r.format==="ID-3"||r.side==="single"?"single":r.side==="verso"?"verso":"recto",D=h!=="recto"?C.liveMrzArm??C.frontLockArm:C.frontLockArm;if(D===null||Math.random()>=C.reportSampleRate)return;let _=r.via==="live_mrz"?K:null,x=()=>{let y=_?.value??null;d([ot({arm:D,capture:h,assist:r.ocr??null,load:D==="control"?"off":F,...r.msToCapture!==void 0?{msToCapture:r.msToCapture}:{},...y!==null&&y.stillConfirmed!==void 0?{stillConfirmed:y.stillConfirmed}:{},...a!==void 0?{typeMismatch:fe(a.format,u.format==="ID-3"?"passport":"card")}:{}})])};_!==null&&_.value===null?Promise.race([_.promise,new Promise(y=>setTimeout(y,3e3))]).then(x):x()},U=r=>{!k||r===b||(b=r,o.setActive(r==="starting"||r==="scanning"),n.emit("state",r))},ut=(r,a)=>a===void 0?null:m?"single":r.captured.recto===a?"recto":r.captured.verso===a?"verso":null,lt=r=>({phase:r.phase,captured:m?r.captured.recto!==void 0?["single"]:[]:["recto","verso"].filter(a=>r.captured[a]!==void 0),expected:m?null:r.current??null,notice:r.notice??null,lastShot:ut(r,r.lastShot),manualShutter:r.manualShutter,torchAvailable:f?.torchAvailable()??!1,torch:M}),De=()=>{let r=f;r!==null&&r.captureNow().catch(()=>R({type:"captureFailed",at:s()}))};function R(r){if(!k)return;let a=c;c=Qe(c,r),c.phase==="capturing"&&a.phase!=="capturing"&&Promise.resolve().then(De),c.phase==="result"&&a.phase!=="result"&&(U("done"),we());let d=lt(c),h=JSON.stringify(d);h!==I&&(I=h,n.emit("scan",d))}function we(){N!==null&&clearInterval(N),N=null;for(let r of G.splice(0))r();f?.destroy(),f=null,o.setActive(!1)}let ke=()=>f?.captureReport?.(),te=!1,Ce=(r,a)=>{if(!(r===void 0||t.onFaceReport===void 0))try{t.onFaceReport(r,a)}catch{}},j=r=>{ee="",!(f===null||c.phase==="reading"||c.phase==="result")&&(te=!1,p=m?"single":c.current??r,f.rearm(p))},ct=async(r,a,d,h)=>{K=null;let D=F!==null&&typeof F=="object"&&F.tier==="low";if(h!==void 0&&X!==null&&C?.liveMrz?.hint===!0&&!D){let A={promise:Ke(X,r,h,{engine:V,detectorLimit:C.liveMrz.detectorLimit}).catch(()=>null),value:null};A.promise.then(P=>{A.value=P}),K=A}h!==void 0&&fe(h.format,u.format==="ID-3"?"passport":"card")&&H({state:"mismatch",format:h.format});let _=ke();Ce(_,"captured"),te=!0,Me(_,h);let x=d===void 0?z:d===null?null:{quad:Et(d),frameWidth:0,frameHeight:0,inStill:!0},y={decoded:null},w=()=>(y.decoded??(y.decoded=Promise.resolve().then(()=>i(r)).catch(()=>null)),y.decoded);try{await dt(r,a,x,w,K,h)}finally{y.decoded!==null&&(await y.decoded)?.close()}},dt=async(r,a,d,h,D,_)=>{let x=`shot-${S+=1}`,y=c.current;if(R({type:"captured",id:x,at:s()}),e.haptics!==!1)try{globalThis.navigator?.vibrate?.(30)}catch{}if(!g&&l>0){let P=await(t.measureSharpness!==void 0?t.measureSharpness(r,d):h().then(T=>T===null?-1:_e(T,ae(d?.quad??null,d?.inStill===!0?T:{width:d?.frameWidth??0,height:d?.frameHeight??0},T)))).catch(()=>-1);if(!k)return;if(Number.isFinite(P)&&P>=0&&P<l){g=!0;let T=m?"recto":c.current??(c.captured.recto===void 0?"recto":"verso");R({type:"readFailed",side:T,id:x,issue:"blurry"}),j(T);return}}g=!1;let w;if(m)w="single";else{let P=_!==void 0&&_.format!=="TD3"&&(u.mrzSide==="recto"||u.mrzSide==="verso")?u.mrzSide:null,T=P===null&&t.classify===void 0?await it(r,h):null,xe=T===null||q===null?T:Ne(T,q,c.captured),Y=P??xe??(xe===null&&q!==null&&y!==void 0?y:null)??await(t.classify!==void 0?t.classify(r):h().then($=>$===null?y??"recto":d?.inStill===!0?ce($,480,null,!0):ce($,480,ae(d?.quad??null,{width:d?.frameWidth??0,height:d?.frameHeight??0},$)))).catch(()=>y??"recto");if(!k)return;if(c.captured[Y]!==void 0&&v<Lt){v+=1,R({type:"duplicate",id:x,side:Y}),j(Y==="recto"?"verso":"recto");return}let ve=c.captured.recto===void 0?"recto":c.captured.verso===void 0?"verso":void 0;w=c.captured[Y]!==void 0&&ve!==void 0?ve:Y,v=0,R({type:"classified",id:x,side:w})}let A=w==="verso"?"verso":"recto";try{let P=t.encode!==void 0?await t.encode(r):await h().then(T=>{if(T===null)throw new Error("the still could not be decoded");return ie(T)});if(!k)return;D!==null&&ye.set(P.blob,D),n.emit("captured",{image:P.blob,side:w,documentType:e.documentType,...e.issuer!==void 0?{issuer:e.issuer}:{},width:P.width,height:P.height,previewDataUrl:a}),t.deferRead!==!0&&R({type:"readOk",side:A})}catch(P){R({type:"readFailed",side:A,id:x,issue:"technical"}),n.emit("error",J("generic",!0,{phase:"keyframes",name:re(P)}))}j(A==="recto"?"verso":"recto")},mt=r=>{G.push(r.on("statechange",({state:a})=>{a==="preflight"||a==="acquiring"?U("starting"):a==="positioning"?U("scanning"):a==="captured"?U("captured"):a==="error"&&U("error")}),r.on("feedback",({key:a,reticle:d})=>n.emit("feedback",{key:a,reticle:d})),r.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 d=a.ocr?.mrz;d!==void 0&&(d.state==="fallback"?H({state:"fallback",reason:d.reason}):d.state==="valid"?H({state:"valid",format:d.format}):d.state==="reading"?H({state:"reading",...d.format?{format:d.format}:{},...d.coach?{coach:d.coach}:{}}):H({state:"searching"}));let h=a.quad===null?0:At(a.quad,a.frameWidth,a.frameHeight);z=a.quad===null?null:{quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight},R({type:"report",report:{present:a.quad!==null&&a.plausible||a.guide?.detected===!0,ready:a.ready===!0,locking:a.p>=.5,areaFrac:h},at:s()})}),r.on("error",({kind:a,retryable:d,detail:h})=>n.emit("error",J(a,d,h))),r.on("artifacts",a=>{ct(a.keyframe,a.previewDataUrl,a.docRegion,a.liveMrz)}))},ne=()=>(L??(L=(async()=>{if(k){if(Se(),f===null){let r;try{r=await(t.createEngine??Ot)({...t.engineOptions??{},...B!==void 0?{guide:B}:{},video:e.video,format:u.format,side:m?"single":e.side??"recto",autoCapture:!1,...Q!==null?{ocr:Q}:{}})}catch(d){U("error"),n.emit("error",J("models",!0,{phase:"models",name:re(d)}));return}if(!k){r.destroy();return}f=r,p=m?"single":e.side??"recto",mt(r);let a=t.tickMs??500;a>0&&(N=setInterval(()=>R({type:"tick",at:s()}),a))}R({type:"clockRestart"}),C!==null&&C.liveMrzArm==="live"&&(F==="unsupported"||F==="off")&&H({state:"fallback",reason:F}),await f.start()}})().finally(()=>{L=null})),L);return{handle:{get state(){return b},on:(r,a)=>n.on(r,a),start:ne,retry:()=>{if(f===null&&c.phase==="result"){R({type:"retake"}),v=0,g=!1,ne();return}if(f!==null&&b!=="error"){R({type:"retake"}),v=0,g=!1,p=m?"single":null,f.rearm(m?"single":void 0);return}ne()},setSide:r=>{m||r==="single"||f!==null&&c.current===r&&p===r&&c.phase!=="reading"&&c.phase!=="result"||(c.current!==r&&(c={...c,current:r}),R({type:"clockRestart"}),c.phase!=="reading"&&c.phase!=="result"&&f!==null&&(p=r,f.rearm(r)))},shutter:De,focusAt:(r,a)=>{f?.focusAt?.(r,a)},setGuide:r=>{B=r,f?.setGuide?.(r)},setTorch:r=>{M=r,f?.setTorch(r),R({type:"tick",at:s()})},destroy:()=>{if(k&&f!==null&&b!=="done"){let r=ke();!te&&r!==void 0&&r.ticks>0&&Ce(r,"abandoned"),Me(r,void 0)}k=!1,we(),Q?.setEngine(null),X?.dispose(),X=null,n.clear()}},plan:u,setFlowState:r=>{(c.phase==="reading"||c.phase==="result")&&U(r==="done"&&c.phase!=="result"?"scanning":r)},settle:(r,a)=>{let d=r==="verso"?"verso":"recto";R(a.ok?{type:"readOk",side:d}:{type:"readFailed",side:d,issue:a.issue}),a.ok||j(d)},takeDeviceRead:r=>ye.get(r.image)?.value??null}}export{Ht as a,Yt as b,Vt as c,Qt as d,Kt as e,jt as f,He as g,ue as h,Qe as i,xt as j,vt as k,Jt as l,Ke as m,en as n,V as o,nt as p,rt as q,Tt as r,ot as s,fe as t,Lt as u,_t as v,kn as w,Cn as x,Bt as y};