@sekyro/web 0.1.0-rc.27 → 0.1.0-rc.28

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 (46) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +4 -1
  3. package/dist/{capture-session-doc-FRBI7OKF.js → capture-session-doc-LUA4Y7PZ.js} +1 -1
  4. package/dist/{capture-session-v3-DZmmTeDY.d.cts → capture-session-v3-ClByT4KN.d.cts} +1 -1
  5. package/dist/{capture-session-v3-CjaciYJQ.d.ts → capture-session-v3-IjQwKfLS.d.ts} +1 -1
  6. package/dist/chunk-CUBNJXZN.js +1 -0
  7. package/dist/{chunk-U3JUGEIW.js → chunk-FSXWIMSG.js} +1 -1
  8. package/dist/{chunk-C5FD3ADY.js → chunk-J7D3S5ZJ.js} +1 -1
  9. package/dist/{chunk-HLV2XYHX.js → chunk-KLEARRAD.js} +1 -1
  10. package/dist/chunk-MJUOZH3U.js +1 -0
  11. package/dist/chunk-MOOWUPOZ.js +1 -0
  12. package/dist/{chunk-Y5ZLVLCU.js → chunk-QP23DM4Z.js} +1 -1
  13. package/dist/chunk-R4IQTGF5.js +3 -0
  14. package/dist/{chunk-VXHK5YC6.js → chunk-THQWX6EH.js} +1 -1
  15. package/dist/client/index.cjs +1 -1
  16. package/dist/client/index.d.cts +3 -3
  17. package/dist/client/index.d.ts +3 -3
  18. package/dist/client/index.js +1 -1
  19. package/dist/core/index.cjs +1 -1
  20. package/dist/core/index.d.cts +3 -3
  21. package/dist/core/index.d.ts +3 -3
  22. package/dist/core/index.js +1 -1
  23. package/dist/{create-document-capture-2YBCDEUB.js → create-document-capture-ZTJKSEJB.js} +1 -1
  24. package/dist/{create-verification-CnsFqT2E.d.cts → create-verification-BN7ebjC2.d.cts} +8 -3
  25. package/dist/{create-verification-ClZ9Nvop.d.ts → create-verification-C4FMWIix.d.ts} +8 -3
  26. package/dist/{icao-gate-DWexlqVW.d.ts → icao-gate-CYb-35iH.d.ts} +1 -1
  27. package/dist/{icao-gate-Dfpj4nT4.d.cts → icao-gate-CjbKCatx.d.cts} +1 -1
  28. package/dist/{icao-policy-BnXH_-WM.d.cts → icao-policy-CAZZYEJ6.d.cts} +2 -2
  29. package/dist/{icao-policy-eLrX6Twc.d.ts → icao-policy-D4AZivI8.d.ts} +2 -2
  30. package/dist/index.cjs +2 -2
  31. package/dist/index.d.cts +7 -7
  32. package/dist/index.d.ts +7 -7
  33. package/dist/index.js +1 -1
  34. package/dist/internal/index.cjs +2 -2
  35. package/dist/internal/index.d.cts +6 -6
  36. package/dist/internal/index.d.ts +6 -6
  37. package/dist/internal/index.js +1 -1
  38. package/dist/{plan-runner-KQM7I4MR.js → plan-runner-INQLWFGS.js} +1 -1
  39. package/dist/{types-BGUwaKjk.d.cts → types-CgHWIEZj.d.cts} +22 -1
  40. package/dist/{types-BGUwaKjk.d.ts → types-CgHWIEZj.d.ts} +22 -1
  41. package/package.json +1 -1
  42. package/sbom.cdx.json +10 -10
  43. package/dist/chunk-3XVIDHFY.js +0 -3
  44. package/dist/chunk-SDDM5ZTK.js +0 -1
  45. package/dist/chunk-ZCOWTM46.js +0 -1
  46. package/dist/chunk-ZCZ2E2YN.js +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # @sekyro/web
2
2
 
3
+ ## 0.1.0-rc.28
4
+
5
+ ### Minor Changes
6
+
7
+ - 14faf9e: The result says when a Sandbox session ran on simulated test data. `VerificationResult.sandbox` is `{ simulated: true, reason }`, the same object as on `GET /sessions/{id}` and the session webhooks. `reason` is `no_testers` (your organization has no active Sandbox tester), `tester_gate_not_used` (nobody ran the tester check at the start of the session) or `tester_gate_missed` (the tester check ran and recognized nobody). No real check ran on such a session. The field is absent in Live and on a Sandbox session an enrolled tester ran. The hosted view's `simulation` block carries the same `reason`, so a step's `context.simulation.reason` is there for your own result screen. The new types `SandboxSimulation` and `SandboxSimulatedReason` are exported.
8
+
9
+ ### Patch Changes
10
+
11
+ - 94565f2: `provenance.rampPainter` is now `true` only when the screen ramp challenge is one this client can render. Before, any challenge handed to the engine set it, so a challenge of another version's shape painted nothing and still reported a painter; the backend then recorded the capture as a ramp that went missing instead of a client that cannot paint it. No API change.
12
+
3
13
  ## 0.1.0-rc.27
4
14
 
5
15
  ### Minor Changes
package/README.md CHANGED
@@ -24,6 +24,8 @@ v.on("result", ({ status, reason, reasonCode }) => {
24
24
  // not_verified says why in `reason` (rejected, inconclusive, unavailable, abandoned,
25
25
  // not_opened, policy, cancelled, superseded) and the detail in `reasonCode`.
26
26
  // The verdict that counts is read server-side (sessions.get + webhooks).
27
+ // In the Sandbox, the result also carries `sandbox: { simulated: true, reason }`
28
+ // when the session ran on test data because no enrolled tester ran it.
27
29
  });
28
30
  const cap = v.liveness({ video }); // your <video playsinline muted>
29
31
  cap.on("gate", ({ progress, hint }) => {/* ring 0..1, hint code */});
@@ -96,7 +98,8 @@ await cap.start({ facing: "user" }); // reuses the warm detector automatically
96
98
  the camera is live (`starting` / `gating` / `recording`), released on `captured`,
97
99
  `error` and `destroy()`, re-taken on `retry()` and when the page is visible again.
98
100
  Best effort: unsupported or refused requests never affect the capture. In an
99
- iframe, allow it: `<iframe allow="camera; screen-wake-lock">`. Pass `false` to
101
+ iframe, allow it: `<iframe allow="camera; screen-wake-lock; ch-ua-model; ch-ua-platform-version">`
102
+ (the two `ch-ua-*` entries let the SDK read the phone model on Android Chrome). Pass `false` to
100
103
  never request it.
101
104
 
102
105
  ## Hosted popup
@@ -1 +1 @@
1
- import{A as b,B as c,C as d,D as e,E as f,F as g,G as h,H as i,I as j,J as k,z as a}from"./chunk-HLV2XYHX.js";import"./chunk-G6LKLN4U.js";import"./chunk-SMKCBUJL.js";import"./chunk-4DEPREJ3.js";import"./chunk-NFHLJOHW.js";import"./chunk-POIQGEZM.js";import"./chunk-CPUECYAJ.js";import"./chunk-FPXL63KZ.js";import"./chunk-U3JUGEIW.js";import"./chunk-DK5YPBDQ.js";export{k as CAPTURE_CANDIDATE_SPACING_MS,j as CAPTURE_EXTRA_CANDIDATES,h as CaptureSessionDoc,c as DOC_BLACK_FRAME_LUMA,d as DOC_BLACK_FRAME_TICKS,e as DOC_CADENCE_HZ,b as DOC_FIRST_FRAME_MS,f as DOC_SHUTTER_DEFAULTS,i as passportBandOf,g as resolveDocShutterTuning,a as warmDocDetector};
1
+ import{A as b,B as c,C as d,D as e,E as f,F as g,G as h,H as i,I as j,J as k,z as a}from"./chunk-KLEARRAD.js";import"./chunk-G6LKLN4U.js";import"./chunk-SMKCBUJL.js";import"./chunk-4DEPREJ3.js";import"./chunk-NFHLJOHW.js";import"./chunk-POIQGEZM.js";import"./chunk-CPUECYAJ.js";import"./chunk-FPXL63KZ.js";import"./chunk-FSXWIMSG.js";import"./chunk-DK5YPBDQ.js";export{k as CAPTURE_CANDIDATE_SPACING_MS,j as CAPTURE_EXTRA_CANDIDATES,h as CaptureSessionDoc,c as DOC_BLACK_FRAME_LUMA,d as DOC_BLACK_FRAME_TICKS,e as DOC_CADENCE_HZ,b as DOC_FIRST_FRAME_MS,f as DOC_SHUTTER_DEFAULTS,i as passportBandOf,g as resolveDocShutterTuning,a as warmDocDetector};
@@ -1,4 +1,4 @@
1
- import { ba as ScreenRampReport, b1 as CaptureProvenance, b7 as ScreenRampChallenge, b8 as ScreenRampPaint } from './types-BGUwaKjk.cjs';
1
+ import { bc as ScreenRampReport, b3 as CaptureProvenance, b9 as ScreenRampChallenge, ba as ScreenRampPaint } from './types-CgHWIEZj.cjs';
2
2
  import { F as FaceObservation, b as Detector, W as WorkerLike } from './detect-worker-CHqsPJoM.cjs';
3
3
 
4
4
  /** MP4-first ladder: one container (H.264 MP4) covers iOS/macOS Safari + Chrome 130+.
@@ -1,4 +1,4 @@
1
- import { ba as ScreenRampReport, b1 as CaptureProvenance, b7 as ScreenRampChallenge, b8 as ScreenRampPaint } from './types-BGUwaKjk.js';
1
+ import { bc as ScreenRampReport, b3 as CaptureProvenance, b9 as ScreenRampChallenge, ba as ScreenRampPaint } from './types-CgHWIEZj.js';
2
2
  import { F as FaceObservation, b as Detector, W as WorkerLike } from './detect-worker-CHqsPJoM.js';
3
3
 
4
4
  /** MP4-first ladder: one container (H.264 MP4) covers iOS/macOS Safari + Chrome 130+.
@@ -0,0 +1 @@
1
+ import{B as Me,E as w,F as j,d as K,e as ge,f as ye,g as be,i as _e,j as ee,l as q,m as te,o as Ce,p as Pe,q as ke,u as Re}from"./chunk-MJUOZH3U.js";import{c as me,d as he,e as Se}from"./chunk-FPXL63KZ.js";import{c as F,h as Q,i as Ae}from"./chunk-J7D3S5ZJ.js";var Ee=["AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AS","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CW","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IR","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","XK","YE","YT","ZA","ZM","ZW"];var Qe=["carte_identite","passport","residence_permit","drivers_license"],Je=["carte_identite","passport","residence_permit"];function ze(e,t){let o=e.byIssuer?.[t]??e.default;return Qe.filter(s=>o==="*"?Je.includes(s):o.includes(s))}function Xt(e,t=Ee){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(s=>ze(e,s).length>0).sort()}function Ie(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}var Xe=640,et=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),ve=6,Oe=1500,Te={sharpness:1,exposure:1,meanLuma:128},xe=null;function tt(e,t){try{xe??(xe=document.createElement("canvas"));let o=xe,s=96/Math.max(1,t.width);o.width=Math.max(1,Math.round(t.width*s)),o.height=Math.max(1,Math.round(t.height*s));let i=o.getContext("2d");if(i===null)return Te;i.drawImage(e,t.x,t.y,t.width,t.height,0,0,o.width,o.height);let c=i.getImageData(0,0,o.width,o.height);return{sharpness:he(c),exposure:Se(c),meanLuma:me(c)}}catch{return Te}}async function nt(e,t){let o=e.source;return"convertToBlob"in o?o.convertToBlob({type:"image/jpeg",quality:t}):new Promise((s,i)=>{o.toBlob(c=>c===null?i(new Error("encode failed")):s(c),"image/jpeg",t)})}function rn(e,t={}){let o=t.now??(()=>performance.now()),s=t.setTimer??((f,_)=>setTimeout(f,_)),i=t.clearTimer??(f=>clearTimeout(f)),c=t.encode??nt,d=t.quality??tt,u=e.tuningVersion??null,p=new Set,S=!1,y=e.video??null,M=null,m=t.grabFrame??null,b=null,v=1e3/ve,E=null,I=null,O=!1,L=!1,D=Number.NEGATIVE_INFINITY,A=null,G=0,V=null,B=null,z=Promise.all([import("./icao-gate-T3BTOKFJ.js"),import("./icao-tuning-4ETMF53W.js"),import("./create-portrait-capture-5VGYZUOK.js"),import("./landmarker-KB7LVXAU.js"),import("./background-monitor-A7FKJOAG.js")]).then(async([f,_,R,x,T])=>{let k=_.resolveIcaoTuning(e.tuning,e.tuningVersion??void 0);k.background.required&&(I=T.createBackgroundMonitor({tuning:k.backgroundCheck,assetBaseUrl:e.assetBaseUrl??"/models-v3",...t.createSegmenter!==void 0?{createSegmenter:t.createSegmenter}:{},now:o})),M=f.createIcaoGate(k,{policy:e.policy??"reject"}),m??(m=R.defaultGrabber()),b=R.observe,v=1e3/Math.min(ve,k.cadenceHz);let n=(t.createLandmarker??x.createFaceLandmarker)(e.assetBaseUrl??"/models-v3"),r=await new Promise((a,l)=>{let h=setTimeout(()=>{l(new Error("landmarker init timeout")),n.then(g=>g.close(),()=>{})},x.LANDMARKER_INIT_TIMEOUT_MS);n.then(g=>{clearTimeout(h),a(g)},g=>{clearTimeout(h),l(g)})});S?r.close():E=r}).catch(()=>{O=!0}),H=f=>{for(let _ of p)_({holding:L||O,update:f})},Y=()=>{if(A=null,!(S||E===null||M===null||m===null||b===null||y===null)){if(o()-D>Oe){H(null);return}try{let f=m(y,Xe);if(f!==null){let _=Math.max(o(),G+1);G=_;let R=E.detect(f.source,_),x=y.videoWidth||f.width,T=y.videoHeight||f.height,k=b(R,f,x,T);k.geometry!==null&&I!==null&&(k.backgroundCheck=I.measure(f,k.geometry.box,x,T));let n=M.push(k,o());L=n.ready,H(n)}}catch{}A=s(Y,v)}},Z=()=>{let f=o()-D>Oe;D=o(),f&&(M?.reset(),L=!1,V=null,B=null),A===null&&E!==null&&!S&&(A=s(Y,0))},X=()=>{let f=m===null||y===null?null:m(y,null);if(f===null||M===null||Math.max(f.width,f.height)<e.still.minLongSidePx)return Promise.resolve(null);let _=M.summary();return c(f,e.still.jpegQuality).then(R=>({image:R,width:f.width,height:f.height,gate:_}),()=>null)},W=null;return{engineOptions:{measureQuality:(f,_)=>{y=f,Z();let R=d(f,_);return L||O?R:{...R,sharpness:0}},telemetry:f=>{if(f.type!=="fired"||S)return;V=X();let _=W;_!==null&&V.then(R=>R===null?void 0:_(R).catch(()=>{})),L=!1,A!==null&&i(A),A=null,D=Number.NEGATIVE_INFINITY}},decorate:f=>{let _=new WeakMap,R=new Map,x=r=>{let a=_.get(r);return a===void 0&&(a=(async()=>{let l=await Re(f,"image","image/jpeg",r.image.size,{engine:"portrait"});return await f.uploadToSpaces(l.uploadUrl,r.image,"image/jpeg"),(await f.completeMedia(l.key)).key})(),a.catch(()=>_.delete(r)),_.set(r,a)),a};W=x;let T=async r=>{let a;try{a=await x(r)}catch(l){let h=l?.code;if(typeof h=="string"&&et.has(h))throw l;return null}return{media:{portrait:a},gate:Ae(r.gate),...u!==null?{tuningVersion:u}:{}}},k=f.submitCheck.bind(f),n=(async(r,a,l)=>{if(r!=="liveness")return k(r,a,l);let h=l?.idempotencyKey,g=h===void 0?void 0:R.get(h);if(g===void 0){let pe=V;g=pe===null?Promise.resolve(null):pe.then(fe=>fe===null?null:T(fe)),h!==void 0&&(R.set(h,g),g.catch(()=>R.delete(h)))}let C=await g;if(C===null)return k("liveness",a,l);let P=await k("liveness",{...a,portraitIcao:C},l);return B=C,P});return new Proxy(f,{get(r,a){if(a==="submitCheck")return n;let l=Reflect.get(r,a);return typeof l=="function"?l.bind(r):l}})},onGate:f=>(p.add(f),()=>p.delete(f)),lastPortraitInput:()=>B,destroy:()=>{S=!0,V=null,B=null,A!==null&&i(A),A=null,p.clear(),z.then(()=>{E?.close(),E=null,I?.close(),I=null})}}}function we(e){return e.idNumberBound??e.nniBound}function Ne(e){return e===void 0?void 0:e.idNumberFromDocument??e.nniFromDocument}function Le(e){let t=e.idNumberMasked??e.nniMasked;return typeof t=="string"&&t!==""?t:void 0}var Ve=Object.freeze({nni_invalid:"id_number_invalid",nni_not_found:"registry_record_not_found",nni_recheck:"id_number_recheck",document_nni_mismatch:"document_id_number_mismatch",nni_locked:"id_number_locked",nni_unbound:"id_number_unbound",missing_nni:"missing_id_number",registry_needs_nni_source:"registry_needs_id_number_source"}),ot=new Map(Object.entries(Ve)),cn=new Map(Object.entries(Ve).map(([e,t])=>[t,e]));function De(e){return ot.get(e)??e}var it=new Set(["phone_otp","email_otp","national_eid","document","nfc","population_registry","supplied_identity","summary_confirm","liveness","portrait","face_match","aml_screening","face_dedup","age_estimation","proof_of_address"]),rt=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),oe=["document","population_registry","national_eid"],ie=["phone_otp","email_otp"],Be={identity_method:oe,contact:ie},st=["population_registry","document"],re="platform_unsupported",at=new Set(["prefilled","user_entered","prefilled_or_entered"]),ct={phone_otp:"contact",email_otp:"contact",eid_auth:"identity",doc_ocr:"identity",nfc_chip:"identity",population_registry:"identity",liveness:"live_photo",portrait_icao:"live_photo",face_match:"live_photo",poa:"documents"};function N(e){return e.section??ct[e.checkType]??null}function se(e,t){let o=e.plan?.choice;if(o===void 0||o.locked)return;let s=o.options.find(i=>i.id!==o.selected&&i.available!==!1&&t.includes(i.service));return s===void 0?void 0:{nodeId:o.nodeId,option:s}}function ae(e){let t=e.plan,o=t?.choice;if(t===void 0||o===void 0||o.locked||t.current===null||t.current===o.nodeId||ee(e))return null;let s=Be[o.kind]??[...oe,...ie],i=o.options.flatMap(u=>u.available===!1||!s.includes(u.service)?[]:[u.nationalEid!=null?{id:u.id,service:u.service,nationalEid:u.nationalEid}:{id:u.id,service:u.service}]),c=t.steps.find(u=>u.id===t.current)?.service,d=o.selected??i.find(u=>u.service===c)?.id??null;return i.some(u=>u.id!==d)?{nodeId:o.nodeId,kind:o.kind,current:d,options:i}:null}function Ue(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function ut(e){let t=e.simulation;if(typeof t!="object"||t===null)return;let{otpCode:o,skipCapture:s}=t;if(typeof o!="string"||o===""||typeof s!="boolean")return;let i=Pe(e);return i!==void 0?{otpCode:o,skipCapture:s,reason:i}:{otpCode:o,skipCapture:s}}function dt(e){let t=(e.plan?.sections??[]).map(d=>({id:d.id,state:d.state})),o={sessionId:te(e.sessionId),orgName:e.orgName,sandbox:e.sandbox===!0,returning:e.returning===!0,consentRecorded:e.consentRecorded,expiresAt:e.expiresAt,sections:t.map(d=>d.id),progress:t,purpose:e.purpose??"identity"};e.branding!==void 0&&(o.branding=e.branding),e.cameraUnavailableHandled===!0&&(o.cameraUnavailableHandled=!0);let s=ut(e);s!==void 0&&(o.simulation=s);let i=e.testerGate;i?.offered===!0&&typeof i.attemptsLeft=="number"&&i.attemptsLeft>0&&(o.testerGate={attemptsLeft:i.attemptsLeft});let c=ae(e);return c!==null&&(o.switchable=c),o}function lt(e){let t={attemptsRemaining:ye(e),attemptsExhausted:e.attempts.used>=e.attempts.max};return e.reason!==void 0&&(t.reason=e.reason),e.retakeHint!==void 0&&(t.retakeHint=e.retakeHint),t}var Fe={phone_otp:"phone",email_otp:"email"};function pt(e,t){let o=se(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return o===void 0?void 0:Fe[o.option.service]}function ft(e,t,o,s){let i=t.checkType==="email_otp",c=(i?t.emailOtp:t.otp)??{},d=i?t.emailOtp?.emailSource:t.otp?.numberSource,u=d!==void 0&&at.has(d)?d:i?"prefilled_or_entered":"user_entered",p=typeof c.sentToMasked=="string"&&c.sentToMasked.length>0,S=c.prefilled===!0,y=pt(e,i?"email_otp":"phone_otp"),M={key:t.checkType,context:o,section:N(t),phase:p?"verify":"send",canSwitch:y!==void 0,...s},m=i?{kind:"email_otp",...M,emailSource:u,needsEmail:u!=="prefilled"&&!S}:{kind:"phone_otp",...M,numberSource:u,needsPhone:u!=="prefilled"&&!S,channels:(t.otp?.channels??[]).filter(b=>b==="whatsapp"||b==="sms")};if(y!==void 0&&(m.switchChannel=y),S&&(m.prefilled=!0),p&&(m.sentToMasked=c.sentToMasked),!i&&t.otp?.channel!==void 0&&(m.channel=t.otp.channel),!i&&Array.isArray(t.phoneCountries)&&(m.phoneCountries=t.phoneCountries.filter(b=>typeof b=="string"&&/^[A-Z]{2}$/.test(b))),!i&&Array.isArray(t.phoneRules)){let b=m.phoneCountries??[];m.phoneRules=t.phoneRules.flatMap(v=>{let E=St(v);return E!==void 0&&b.includes(E.code)?[E]:[]})}return!i&&t.phoneInternational===!0&&(m.phoneInternational=!0),c.expiresAt!==void 0&&(m.codeExpiresAt=c.expiresAt),c.resendAvailableAt!==void 0&&(m.resendAvailableAt=c.resendAvailableAt),m}var mt=/^[\d[\]\-|()?:^]{1,64}$/;function ht(e){try{return typeof e=="string"&&mt.test(e)&&new RegExp(e)!==null}catch{return!1}}var He=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function St(e){let{code:t,dial:o,trunk:s,lengths:i,formats:c}=e??{};if(typeof t!="string"||typeof o!="string"||!/^\d{1,3}$/.test(o)||s!==void 0&&(typeof s!="string"||!/^\d{1,3}$/.test(s))||!Array.isArray(i)||i.length===0||!i.every(He))return;let d={code:t,dial:o,lengths:[...i].sort((u,p)=>u-p)};if(s!==void 0&&(d.trunk=s),c!==void 0){if(!(Array.isArray(c)&&c.length<=8&&c.every(p=>ht(p?.leading)&&Array.isArray(p.groups)&&p.groups.every(He)&&i.includes(p.groups.reduce((S,y)=>S+y,0)))))return;d.formats=c.map(p=>({leading:p.leading,groups:[...p.groups]}))}return d}function gt(e,t,o,s){let i=we(e)===!0?"bound":Ne(t)===!0?"document":"typed",c=i==="typed"&&t.state==="input_required"&&t.reason!==void 0&&De(t.reason)==="id_number_recheck",d=Ue(ae(e)),u=!s.attemptsExhausted&&d.length===1&&d[0]?.service==="document";return{kind:"registry",key:"registry",context:o,section:N(t),state:t.state==="input_required"?"input_required":"pending",source:i,recheck:c,canUseDocument:u,...s}}function yt(e,t,o,s,i){let c=[...t.acceptedSides??[]],d={kind:"document",key:"document",context:o,section:N(t),side:c.includes("recto")?"verso":"recto",acceptedSides:c,documents:Ie(e),photo:ue(ce(e.documents),i),...s};return e.detectedCountry!==void 0&&(d.detectedCountry=e.detectedCountry),Ct(e)&&(d.ageStepUp=!0),d}function ce(e,t=!0){let o=e?.source==="upload"||e?.source==="choice"?e.source:"camera",s=e?.sourcePick==="camera"||e?.sourcePick==="upload"?e.sourcePick:null;return{source:o,pick:s,uploadOffered:t&&e?.uploadOffered===!0}}function ue(e,t){return t?{...e,cameraOnPhone:!0}:e}var bt=10*1024*1024;function _t(e,t,o,s,i){let c=e.proofOfAddress,d=c?.pdf?.maxBytes,u=c?.phase==="holder_letter"?"holder_letter":"document";return{kind:"proof_of_address",key:"proof_of_address",context:o,section:N(t),phase:u,rule:c?.rule??{country:null,countryFrom:"global",source:"preset_global",kinds:[]},nameMatch:c?.nameMatch??"exact_person",photo:ue(ce(c),i),maxPages:3,pdf:{maxBytes:typeof d=="number"&&d>0?d:bt,maxPages:3},licenceAddressAccepted:u==="document"&&c?.licenceAddressAccepted===!0,...s}}function Ct(e){let t=ge(e).find(s=>s.checkType==="age_estimation"),o=t?.reason;return t?.state==="failed"&&(o==="age_uncertain"||o==="age_unavailable")}function Pt(e){let t=q(e,"liveness");return t?.state==="passed"||t?.state==="review"}function Ge(e,t,o,s,i,c=!1){let d=t.icao?.report,u=e.portrait,p=i==="capture"?u?.pendingFix??null:null;p!==null&&(i="review");let S=Ke(e);return{kind:"portrait",key:`portrait:${i}`,context:o,section:N(t),phase:i,report:Array.isArray(d)?d:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:Q(e),retakeOnly:i==="capture"&&t.state==="input_required"&&S===void 0&&e.capture?.livePhoto?.oneCapture===!0&&Pt(e),photo:ue(ce(u,i==="capture"),c&&i==="capture"),pendingFix:p,...S!==void 0?{captureMode:S}:{},...u?.reuse?.pending===!0?{reuse:!0}:{},...s}}function Ke(e){let t=e.portrait?.captureMode;return t==="self"||t==="assisted"||t==="choice"?t:void 0}var ne={minLongSidePx:1280,jpegQuality:.95};function kt(e,t){let o=e.capture?.livePhoto;if(o?.oneCapture!==!0)return null;let s=q(e,"portrait_icao"),i=o.still??ne;return{icao:t==="liveness"&&Q(e)!==null&&Ke(e)===void 0&&s!==void 0&&s.state==="pending"&&s.reason===void 0,still:{minLongSidePx:i.minLongSidePx??ne.minLongSidePx,jpegQuality:i.jpegQuality??ne.jpegQuality}}}function Rt(e,t,o,s){let i=t.eid,c=N(t);if(i===void 0||i.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:o,section:c,checkType:"eid_auth",reason:"update_required"};let d=Ue(ae(e)),u=d.length===1&&st.includes(d[0]?.service??"")?d[0]:void 0,p=u===void 0?void 0:K[u.service],S=p!==void 0,y={kind:"eid",key:"eid",context:o,section:c,provider:i.provider,providerName:i.providerName,country:i.country,challenge:"app_code",phase:i.awaiting==="code"?"code":"identifier",identifierBound:i.identifierBound===!0,canUseCamera:S,afterPass:i.afterPass==="continue"?"continue":"end",...s};return S&&(y.cameraMethod=p),i.expiresAt!==void 0&&(y.codeExpiresAt=i.expiresAt),i.resendAvailableAt!==void 0&&(y.resendAvailableAt=i.resendAvailableAt),i.resendsRemaining!==void 0&&(y.resendsRemaining=i.resendsRemaining),i.codeAttemptsRemaining!==void 0&&(y.codeAttemptsRemaining=i.codeAttemptsRemaining),y}function Mt(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let o=q(e,"portrait_icao");return o!==void 0&&(o.state==="passed"||o.state==="review")?o:null}var At={rejected:"rejected",inconclusive:"inconclusive",unavailable:"unavailable",abandoned:"expired",not_opened:"expired",cancelled:"expired",superseded:"expired",policy:"policy"};function Et(e){return e.reasonCode===re?"platform_unsupported":e.status==="review_pending"?"review":e.status==="verified"?"verified":e.reasonCode==="device_cooldown"?"cooldown":e.reasonCode==="starter_credit_claimed"?"policy":(e.status==="not_verified"&&e.reason!==void 0?At[e.reason]:void 0)??"rejected"}function It(e,t){let o=Et(e),s=o==="platform_unsupported"?{sessionId:te(e.sessionId),status:"unavailable",reasonCode:re}:Ce(e,{autoRetry:!1}),i={kind:"result",key:"result",context:t,section:null,display:o,result:s};return e.status==="not_verified"&&e.reason!==void 0&&(i.reason=e.reason),e.reasonCode!==void 0&&(i.reasonCode=e.reasonCode),e.status==="not_verified"&&e.step!==void 0&&(i.step=e.step),e.retryAfter!==void 0&&(i.retryAfter=e.retryAfter),i}function vt(e,t,o){let s=e.identitySummary;if(s==null)return null;let i={kind:"identity_summary",key:"identity_summary",context:t,section:o??"identity",summaryKind:s.kind==="partial"?"partial":s.kind??"full",source:s.source,portraitAvailable:s.portrait?.available===!0,retakeAvailable:s.retakeAvailable===!0};for(let d of Ot){let u=s[d];typeof u=="string"&&u!==""&&(i[d]=u)}let c=Le(s);return c!==void 0&&(i.idNumberMasked=c,i.nniMasked=c),i}var Ot=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","expiryDate","retakeTarget"];function U(e,t,o,s){return{kind:"unsupported",key:`unsupported:${o}`,context:e,section:t,checkType:o,reason:s}}function Tt(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function xt(e,t){let o=Be[e.kind]??[...oe,...ie],s=Tt(e),i=e.options.flatMap(d=>{if(d.available===!1||!o.includes(d.service))return[];let u={id:d.id,service:d.service};d.nationalEid!=null&&(u.nationalEid=d.nationalEid);let p=(d.channels??[]).filter(S=>S==="whatsapp"||S==="sms");return d.service==="phone_otp"&&p.length>0&&(u.channels=p),[u]});if(i.length===0){let d=e.options.length>0&&e.options.every(u=>u.service==="nfc");return U(t,s,"choice",d?"platform_unsupported":"update_required")}let c={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:i};if(e.kind==="identity_method"){let d={kind:"method",key:"method",context:t,section:s,options:i.map(p=>K[p.service]),choice:c},u=i.find(p=>p.nationalEid!==void 0)?.nationalEid;return u!==void 0&&(d.nationalEid=u),d}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:s,options:i.map(d=>Fe[d.service]),selected:null,locked:!1,choice:c}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:s,choice:c}}function J(e,t={}){let o=dt(e);if(ee(e)||e.reasonCode===re)return It(e,o);let s=e.plan;if(s===void 0||!Array.isArray(s.sections))return U(o,null,"plan","update_required");let i=be(e);if(i!==null)return xt(i,o);let c=s.current===null?void 0:s.steps.find(m=>m.id===s.current),d=m=>{let b={kind:"processing",key:"processing",context:o,section:m!==void 0?N(m):s.sections.find(v=>v.state==="current")?.id??null,stalled:!1};return typeof m?.service=="string"&&m.service!==""&&(b.service=m.service),b};if(s.current===null)return d(s.steps.find(m=>m.state==="processing"));if(c===void 0)return U(o,null,"step","update_required");if(!it.has(c.service))return c.interaction==="server"?d(c):U(o,N(c),c.service,"update_required");if(rt.has(c.service)||!_e(c))return d(c);let u=c,p=lt(u),S=u.checkType,y=N(u),M=t.isMobile===!1?ke(e,u):null;if(M==="phone")return{kind:"mobile_required",key:"mobile_required",context:o,section:y,checkType:S};switch(S){case"phone_otp":case"email_otp":return ft(e,u,o,p);case"population_registry":return gt(e,u,o,p);case"eid_auth":return Rt(e,u,o,p);case"doc_ocr":return yt(e,u,o,p,M==="upload_or_phone");case"identity_confirm":return vt(e,o,y)??d(u);case"portrait_icao":return Ge(e,u,o,p,"capture",M==="upload_or_phone");case"liveness":case"face_match":{let m=Mt(e,u);if(m!==null)return Ge(e,m,o,p,"match");let b=u.requiresMobile===!0,v=Q(e);return{kind:"liveness",key:"biometric",context:o,section:y,mode:S==="face_match"?"selfie":"liveness",requiresMobile:b,instructions:v===null?"standard":"icao",icao:v,livePhoto:kt(e,S),...p}}case"poa":return _t(e,u,o,p,M==="upload_or_phone");case"nfc_chip":return U(o,y,S,"platform_unsupported");default:return U(o,y,S,"update_required")}}var wt=/^[A-Z0-9][A-Z0-9 -]{0,39}$/,Nt=Object.freeze({normalize:e=>e.trim().toUpperCase().replace(/\s+/g," "),check:e=>wt.test(e),registrySources:Object.freeze([]),describe:"number must be 1 to 40 letters, digits, spaces or hyphens"}),Lt=/^[A-Z0-9]{4,20}$/,je=e=>e.trim().toUpperCase().replace(/[\s-]+/g,""),Ye=Object.freeze({normalize:je,check:e=>Lt.test(je(e)),registrySources:Object.freeze([]),describe:"number must be 4 to 20 letters or digits"});function Vt(e){return typeof e=="string"&&/^\d{10}$/.test(e)&&Number(e)%97===1}var Dt=Object.freeze({normalize:e=>e.trim(),check:e=>Vt(e),registrySources:Object.freeze(["MR.anrpts"]),describe:"number must be the 10-digit Mauritanian national ID number with a valid check digit"}),Ht=Object.freeze({...Ye,check:e=>/^\d{8}$/.test(e.trim()),describe:"number must be the 8-digit Mauritanian driver's license number"}),Gt=Object.freeze({"MR:national_id":Dt,"MR:drivers_license":Ht});function de(e,t){return Gt[`${e.toUpperCase()}:${t}`]??(t==="drivers_license"?Ye:Nt)}var Bt=Object.freeze({MRT:"MR"});function Ze(e,t){let o=e.trim().toUpperCase();return de(Bt[o]??o,t)}function We(e){let t=Ze(e.issuingCountry,e.type);return t.check(t.normalize(e.number))}function $e(e){return de("MR","national_id").check(e)}function le(e){let t="";for(let o of e){let s=o.codePointAt(0)??0;s>=1632&&s<=1641?t+=String(s-1632):s>=1776&&s<=1785?t+=String(s-1776):o!==" "&&o!=="-"&&o!==" "&&(t+=o)}return t}var Ut=[1e3,2e3,4e3,8e3,15e3],Ft=3e4,Kt=/^\+[1-9]\d{6,14}$/,jt=/^\d{6}$/,Yt=/^\d{6}$/,Zt=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,qe=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order","identity_confirm_required","identity_confirm_locked","choice_locked","choice_option_unavailable","choice_not_found","step_not_on_path","check_not_active"]),Wt={simulatedCapture:!0},$t=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]);function An(e){let t=!1,o=null,s="",i=!1,c=!1,d=!1,u={},p={},S=new Set,y=!1,M=!1,m=null,b="idle",v=new Map,E=new Map,I=(n,r,a)=>{let l=`${n}.${r}`,h=v.get(l);if(h!==void 0)return h;let g=E.get(n),C=(g===void 0?a():g.then(a)).finally(()=>{v.delete(l)});v.set(l,C);let P=C.then(()=>{},()=>{});return E.set(n,P),P.then(()=>{E.get(n)===P&&E.delete(n)}),C},O=async(n,r,a)=>{await e.ensureConsent();let l;try{l=await Me(e.runtime,r)}catch(g){if(g instanceof F&&qe.has(g.code)){await e.refreshView();return}throw g}if(a?.(l),e.destroyed())return;let h=l;h.plan!==void 0&&e.setView!==void 0?e.setView(h):await e.refreshView()},L=async n=>{await e.ensureConsent();let r;try{try{r=await n(e.runtime.client)}catch(a){if(!(a instanceof F)||a.code!=="consent_required")throw a;await e.runtime.ensureConsent({force:!0}),r=await n(e.runtime.client)}}catch(a){if(a instanceof F&&qe.has(a.code)){await e.refreshView();return}throw a}e.destroyed()||(r!==void 0&&e.setView!==void 0?e.setView(r):await e.refreshView())},D=(n,r)=>I("choice",`${n}:${r}`,()=>L(a=>a.choose(n,r))),A=(n,r)=>n.options.some(a=>a.id===r)?D(n.nodeId,r):Promise.reject(new RangeError(`option ${String(r)} is not offered`)),G=(n,r)=>{let a=e.currentView(),l=a===null?void 0:se(a,n);return l===void 0?Promise.reject(new RangeError(`the ${r} is not offered`)):D(l.nodeId,l.option.id)},V=n=>I("identity",n,()=>L(r=>r.confirmIdentity===void 0?Promise.reject(new Error("identity confirmation is not available in this build")):r.confirmIdentity(n))),B=(n,r)=>{let a=n.kind,l=a==="phone_otp",h=l?"phone":"email",g={action:"send"};if(l?n.needsPhone:n.needsEmail){let C=r[h]??p[a],P=l?C?.replace(/[\s().-]/g,""):C?.trim();if(P!==void 0||n.phase!=="verify"){if(P===void 0||!(l?Kt:Zt).test(P))return Promise.reject(l?new w("phone","format"):new j("email","format"));g[h]=P}}if(l){let C=n.channels,P=r.channel??(C.length===1?C[0]:void 0);if(C.length>0){if(P===void 0)return Promise.reject(new j("channel","required"));if(!C.includes(P))return Promise.reject(new j("channel","unavailable"))}P!==void 0&&(g.channel=P),g.phoneRules=1}return I(a,"send",()=>O(a,(C,P)=>C.submitCheck(a,g,{idempotencyKey:P}),C=>{Qt(C,a)||(u[a]=e.now(),g[h]!==void 0&&(p[a]=g[h]))}))},z=(n,r)=>jt.test(r)?I(n,"verify",()=>O(n,(a,l)=>a.submitCheck(n,{action:"verify",code:r},{idempotencyKey:l}))):Promise.reject(new w("code","format")),H=(n,r)=>I("eid_auth",n,()=>O("eid_auth",(a,l)=>a.submitCheck("eid_auth",r,{idempotencyKey:l}))),Y=(n,r)=>{if(n.identifierBound)return H("start",{action:"start"});let a=le(r??"");if(n.country==="MR"){if(!/^\d{10}$/.test(a))return Promise.reject(new w("nni","format"));if(!$e(a))return Promise.reject(new w("nni","check_digit"))}else if(a==="")return Promise.reject(new w("nni","format"));return H("start",{action:"start",identifier:a})},Z=(n,r,a)=>{if(n.source!=="typed")return Promise.reject(new RangeError("this session already holds the ID number"));let l=le(r);return/^\d{10}$/.test(l)?We({type:"national_id",issuingCountry:"MR",number:l})?I("population_registry","submitIdNumber",()=>O("population_registry",(h,g)=>h.submitCheck("population_registry",{idNumber:l,nni:l},{idempotencyKey:g}),()=>{m=`\u2022\u2022\u2022\u2022\u2022\u2022${l.slice(-4)}`})):Promise.reject(new w(a,"check_digit")):Promise.reject(new w(a,"format"))},X=n=>(e.stopCameras?.(),I(n,"skipCapture",()=>O(n,(r,a)=>r.submitCheck(n,Wt,{idempotencyKey:a}),()=>{(n==="liveness"||n==="portrait_icao")&&(y=!0)}))),W=n=>{if(n.kind==="result"||n.context.simulation?.skipCapture!==!0)return n;let r=qt(n);return r===null?n:{...n,skipCapture:()=>X(r)}},$=n=>((n.kind==="document"||n.kind==="portrait"||n.kind==="proof_of_address")&&n.photo?.cameraOnPhone===!0&&(n.refresh=async()=>{await e.refreshView()}),n),f=n=>{switch(n.kind){case"phone_otp":case"email_otp":{let r={...n,send:(l={})=>B(n,l),verify:l=>z(n.kind,l),switchTo:()=>n.canSwitch&&n.switchChannel!==void 0?G([n.switchChannel==="email"?"email_otp":"phone_otp"],"other contact option"):Promise.reject(new RangeError("this session has no other contact option"))},a=u[n.kind];return r.resendAvailableAt===void 0&&a!==void 0&&(r.resendAvailableAt=new Date(a+Ft).toISOString()),r}case"eid":return{...n,start:r=>Y(n,r),verify:r=>Yt.test(r)?H("verify",{action:"verify",code:r}):Promise.reject(new w("code","format")),resend:()=>n.resendsRemaining===0?Promise.reject(new RangeError("no new code can be sent for this session")):H("resend",{action:"resend"}),useCamera:()=>n.canUseCamera&&n.cameraMethod!==void 0?G(n.cameraMethod==="document_photo"?["document"]:["population_registry"],"camera path"):Promise.reject(new RangeError("the camera path is not offered"))};case"method":return{...n,select:r=>{let a=n.choice.options.find(l=>K[l.service]===r);return a!==void 0?A(n.choice,a.id):Promise.reject(new RangeError(`method ${String(r)} is not offered`))},choose:r=>A(n.choice,r)};case"choice":return{...n,choose:r=>A(n.choice,r)};case"registry":return{...n,submitIdNumber:r=>Z(n,r,"idNumber"),submitNni:r=>Z(n,r,"nni"),confirm:()=>I("population_registry","confirm",()=>O("population_registry",(r,a)=>r.submitCheck("population_registry",{},{idempotencyKey:a}))),useDocument:()=>n.canUseDocument?G(["document"],"document method"):Promise.reject(new RangeError("the document method is not offered"))};case"document":return e.bindDocument!==void 0?$(e.bindDocument(n,k)):{...n,issuer:null,documentType:null,captureSide:null,selectDocument:()=>{throw new Error("document capture is not available in this build")},capture:()=>{throw new Error("document capture is not available in this build")},uploadDocument:()=>Promise.reject(new Error("document upload is not available in this build"))};case"portrait":return e.bindPortrait!==void 0?$(e.bindPortrait(n,k)):{...n,uploadFailed:!1,resubmit:()=>Promise.resolve(),capture:()=>{throw new Error("portrait capture is not available in this build")},uploadPortrait:()=>Promise.reject(new Error("portrait upload is not available in this build")),confirmFix:()=>Promise.reject(new Error("portrait review is not available in this build"))};case"proof_of_address":return e.bindProofOfAddress!==void 0?$(e.bindProofOfAddress(n,k)):{...n,uploadPages:()=>Promise.reject(new Error("proof of address upload is not available in this build")),uploadHolderLetter:()=>Promise.reject(new Error("proof of address upload is not available in this build")),capturePage:()=>{throw new Error("proof of address capture is not available in this build")}};case"contact_choice":return{...n,select:r=>{let a=r==="phone"?"phone_otp":r==="email"?"email_otp":void 0,l=n.choice.options.find(h=>h.service===a);return l!==void 0?A(n.choice,l.id):Promise.reject(new RangeError(`contact ${String(r)} is not offered`))},choose:r=>A(n.choice,r)};case"identity_summary":return{...n,...n.idNumberMasked===void 0&&n.summaryKind==="partial"&&m!==null?{idNumberMasked:m,nniMasked:m}:{},portrait:async()=>{let r=e.runtime.client;if(!n.portraitAvailable||r.identityPortrait===void 0)return null;try{return await r.identityPortrait()}catch{return null}},confirm:()=>V("confirm"),retake:()=>n.retakeAvailable?V("retake"):Promise.reject(new RangeError("no retake is left"))};case"liveness":return{...n,capture:r=>e.liveness(r),onLivePhoto:r=>n.livePhoto?.icao===!0&&e.onLivePhoto!==void 0?e.onLivePhoto(r):()=>{}};case"mobile_required":case"processing":return{...n,refresh:async()=>{i=!1,await e.refreshView()}};case"unsupported":case"result":return{...n};default:{let r=n;throw new Error(`runner: unhandled step ${JSON.stringify(r)}`)}}},_=n=>W(f(n)),R=async()=>{if(!c){c=!0;try{for(let n of Ut){if(await e.sleep(n),!t||e.destroyed())return;let r=await e.refreshView().catch(()=>null);if(r!==null&&J(r,{isMobile:e.isMobile()}).kind!=="processing")return}i=!0,k()}finally{c=!1}}},x=n=>{if(n.kind!=="liveness"||n.mode!=="selfie")return null;let r={kind:"processing",key:"processing",context:n.context,section:n.section,stalled:!1};if(b==="inflight")return r;if(!M||b==="done")return null;let a=e.keptFaceKey?.()??null;return a===null?null:(b="inflight",O("face_match",(l,h)=>l.submitCheck("face_match",{imageKey:a},{idempotencyKey:h}),()=>{b="done"}).then(()=>{b==="inflight"&&(b="done",k())},()=>{b="done",k()}),r)},T=(n,r=!1)=>{if(!t||e.destroyed()||e.chainBusy())return;let a=J(n,{isMobile:e.isMobile()});a.kind==="registry"&&a.recheck&&(M=!0,b="idle"),a=x(a)??a,a.kind==="processing"?a.stalled=i:i=!1;let l=_(a),h=a.kind==="result"?void 0:a.context.switchable,g=h===void 0?l:{...l,chooseOption:P=>A({nodeId:h.nodeId,kind:h.kind,selected:h.current,options:h.options},P)},C=JSON.stringify(g);a.kind==="registry"&&a.source==="document"&&a.state==="pending"&&!S.has("registry")&&(S.add("registry"),g.confirm().catch(P=>{(!(P instanceof F)||$t.has(P.code))&&S.delete("registry")})),!(!r&&C===s)&&(s=C,o=g,e.emitStep(g),a.kind==="processing"&&!i&&b!=="inflight"&&R(),a.kind==="result"&&!d&&(d=!0,e.emitResult(a.result)))};function k(){let n=e.currentView();n!==null&&T(n,!0)}return{run:async()=>{if(e.destroyed())throw new Error("verification destroyed");t=!0;let n=await e.ensureView();return o===null&&T(n),o??_(J(n,{isMobile:e.isMobile()}))},current:()=>o,onView:n=>T(n),onChainIdle:()=>{let n=e.currentView();n!==null&&T(n)},republish:k,submit:O,faceProbeSkipped:()=>y}}function qt(e){switch(e.kind){case"document":return"doc_ocr";case"liveness":return e.mode==="selfie"?"face_match":"liveness";case"portrait":return e.phase==="capture"?"portrait_icao":null;case"proof_of_address":return"poa";case"mobile_required":return e.checkType;case"unsupported":return e.checkType==="nfc_chip"?"nfc_chip":null;default:return null}}function Qt(e,t){let o=e,s=o?.plan?.steps??o?.steps;return Array.isArray(s)?s.some(i=>i.checkType===t&&typeof i.reason=="string"):!1}export{ze as a,Xt as b,ve as c,Oe as d,rn as e,Ke as f,J as g,Ut as h,Ft as i,An as j};
@@ -1 +1 @@
1
- var f="0.1.0-rc.27";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-SEWS3VHQ.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 g=await i,m=I(),S={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...m?[{kind:"web_local",value:m.slice(0,128)}]:[],...g?[{kind:"web_fp",value:g}]:[]],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@${f}`}));function M(t){try{let e=t.getVideoTracks?.()[0];if(e){if(d.noteCameraLabel(e.label),d.noteCameraTrack(e),v())return;import("./camera-trait-V4UAOPIQ.js").then(r=>r.noteCameraTrait(e,d)).catch(()=>{})}}catch{}}export{f as a,p as b,d as c,M as d};
1
+ var f="0.1.0-rc.28";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-SEWS3VHQ.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 g=await i,m=I(),S={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...m?[{kind:"web_local",value:m.slice(0,128)}]:[],...g?[{kind:"web_fp",value:g}]:[]],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@${f}`}));function M(t){try{let e=t.getVideoTracks?.()[0];if(e){if(d.noteCameraLabel(e.label),d.noteCameraTrack(e),v())return;import("./camera-trait-V4UAOPIQ.js").then(r=>r.noteCameraTrait(e,d)).catch(()=>{})}}catch{}}export{f as a,p as b,d as c,M as d};
@@ -1 +1 @@
1
- import{c as f}from"./chunk-TSA6GHUG.js";import{a as h,c as y}from"./chunk-U3JUGEIW.js";var w=["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"];function D(s){return w.includes(s)}var c=class extends Error{constructor(e){super(e.message),this.name="HostedApiError",this.status=e.status,this.code=e.code,e.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=e.retryAfterSeconds),e.details&&(this.details=e.details)}};function _(s,e,n=Math.random){let t=(s??e)*1e3,o=Math.min(Math.max(t,500),2e4),i=Math.round(o*(1+(n()*2-1)*.25));return Math.min(Math.max(i,500),2e4)}var k=6e4,b=4,R=3e4,I=9e5,P=200,E=5,M=400,C=new Set(["server_busy","request_timeout"]),A=2;function l(s){return(s.split(";")[0]??"").trim()}var O={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},v=`@sekyro/web/${h}`,N=v,g=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.reportedIssues=new Map;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let n=e.fetch;this.fetchImpl=(t,o)=>(n??globalThis.fetch).call(globalThis,t,o),this.requestTimeoutMs=e.requestTimeoutMs??R,this.retryAttempts=e.inProgressRetry?.attempts??E,this.retryDelayMs=e.inProgressRetry?.delayMs??M,this.random=e.random??Math.random}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e},busyRetry:!0})}async reportCameraUnavailable(e){return this.api("POST","/hosted/camera-unavailable",{body:{cause:e}})}async 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,o=typeof e.attempt=="number"&&Number.isInteger(e.attempt)&&e.attempt>=0&&e.attempt<=1e3?e.attempt:void 0,i=[e.check,o??"",e.kind,n,e.phase??""].join("|"),a=this.reportedIssues.get(i);if(a!==void 0)return a;let d={check:e.check,kind:e.kind,...n!==""?{name:n}:{},...e.phase!==void 0?{phase:e.phase}:{},...t!==void 0?{engineKind:t}:{},...o!==void 0?{attempt:o}:{},...e.formFactor!==void 0?{formFactor:e.formFactor}:{}},r=this.api("POST","/hosted/capture-issue",{body:d,empty:!0}).catch(()=>{this.reportedIssues.delete(i)});return this.reportedIssues.set(i,r),r}async choose(e,n){let t=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:n},busyRetry:!0});return this.sessionId=t.sessionId,t}async confirmIdentity(e){return this.api("POST","/hosted/identity/confirm",{body:{decision:e}})}async identityPortrait(){return this.api("GET","/hosted/identity/portrait",{blob:!0})}async presign(e,n,t,o={}){let i=await this.ensureSessionId(),a={kind:e,contentType:l(n),contentLength:t,...o.source==="upload"?{source:"upload"}:{}};return this.api("POST",`/sessions/${i}/media`,{body:a})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,n,t,o={}){let i=await this.ensureSessionId(),a=await this.takeCaptureNonce(),d=a===void 0?void 0:{nonce:a,...o.engine!==void 0?{engine:o.engine.slice(0,32)}:{},...o.durationMs!==void 0&&Number.isFinite(o.durationMs)?{captureMs:Math.min(36e5,Math.max(0,Math.round(o.durationMs)))}:{}},r={kind:e,contentType:l(n),contentLength:t,capture:d};return this.api("POST",`/sessions/${i}/media`,{body:r})}async takeCaptureNonce(){let e=()=>{let n=Date.now();return this.captureNonces=this.captureNonces.filter(t=>t.expiresAt-k>n),this.captureNonces.shift()?.nonce};for(let n=0;n<2;n++){let t=e();if(t!==void 0)return t;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let n=await this.ensureSessionId(),t=await this.api("POST",`/sessions/${n}/media/capture-nonces`,{body:{count:Math.min(b,Math.max(1,e))}}),o=Date.now()+Math.max(0,t.expiresIn)*1e3;for(let i of Array.isArray(t.nonces)?t.nonces:[])typeof i=="string"&&i.length>0&&this.captureNonces.push({nonce:i,expiresAt:o});this.captureNonces=this.captureNonces.slice(-b)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,n,t){let o;try{o=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":l(t)},body:n,signal:AbortSignal.timeout(I)})}catch(i){throw m(i)}if(!o.ok){let i=(await o.text().catch(()=>"")).slice(0,P);throw new c({status:o.status,code:"upload_failed",message:`media upload failed (HTTP ${o.status})${i?`: ${i}`:""}`})}}async completeMedia(e){let n=await this.ensureSessionId();return this.api("POST",`/sessions/${n}/media/complete`,{body:{key:e}})}async submitCheck(e,n,t={}){let o=await this.ensureSessionId(),i={input:n,forceOutcome:t.forceOutcome};return this.api("POST",`/sessions/${o}/checks/${e}`,{body:i,idempotencyKey:t.idempotencyKey,busyRetry:t.idempotencyKey!==void 0})}async uploadAndSubmit(e,n,t,o={}){let i=l(n.contentType),a=await this.presign(n.kind,i,n.blob.size);await this.uploadToSpaces(a.uploadUrl,n.blob,i);let d=await this.completeMedia(a.key),r={...t,[O[e]]:d.key};return this.submitCheck(e,r,o)}async ensureSessionId(){return this.sessionId!==null?this.sessionId:(this.bootstrap??(this.bootstrap=this.getSession().finally(()=>{this.bootstrap=null})),(await this.bootstrap).sessionId)}async api(e,n,t={}){let o=e==="GET"||t.busyRetry===!0,i=`${this.apiOrigin}/api/v2${n}`,a={"x-session-token":this.sessionToken,"x-sekyro-sdk":N};t.body!==void 0&&(a["content-type"]="application/json"),t.idempotencyKey!==void 0&&(a["x-idempotency-key"]=t.idempotencyKey);try{let d=y.timezone();d!==void 0&&(a["sekyro-client-timezone"]=d)}catch{}a["sekyro-client-form-factor"]=f();try{let d=await y.deviceHeader();d!==void 0&&(a["sekyro-client-device"]=d)}catch{}for(let d=0;;d++){let r;try{r=await this.fetchImpl(i,{method:e,headers:a,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(p){throw m(p)}if(r.ok){if(t.empty===!0)return;if(t.blob===!0)try{return await r.blob()}catch(S){throw m(S)}let p;try{p=await r.json()}catch{throw new c({status:r.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${r.status})`})}return H(p)}let u=await x(r);if(u.code==="idempotency_in_progress"&&d<this.retryAttempts){this.retryDelayMs>0&&await T(this.retryDelayMs);continue}if(o&&u.status===503&&C.has(u.code)){o=!1,await T(_(u.retryAfterSeconds,A,this.random));continue}throw u}}};function m(s){if((typeof s=="object"&&s!==null?s.name:void 0)==="TimeoutError")return new c({status:0,code:"timeout",message:"request timed out"});let n=s instanceof Error?s.message:String(s);return new c({status:0,code:"network_error",message:`network request failed: ${n}`})}function H(s){return s!==null&&typeof s=="object"&&"success"in s&&"data"in s?s.data:s}async function x(s){let e="unknown_error",n=`request failed (HTTP ${s.status})`,t=Number.NaN,o;try{let d=await s.json();if(d!==null&&typeof d=="object"){let r=d;typeof r.code=="string"&&r.code.length>0&&(e=r.code),typeof r.message=="string"&&r.message.length>0&&(n=r.message),typeof r.retryAfterSeconds=="number"&&(t=r.retryAfterSeconds),Array.isArray(r.details?.issues)&&(o=r.details)}}catch{}let i=s.headers.get("retry-after"),a=i===null?Math.floor(t):Number.parseInt(i,10);return new c({status:s.status,code:e,message:n,...Number.isFinite(a)&&a>=0?{retryAfterSeconds:a}:{},details:o})}function T(s){return new Promise(e=>setTimeout(e,s))}function L(s){let e=s?.portrait,n=e?.icao,t=e?.purpose==="id_document";return n==null?t?{policy:"reject",profile:"id_document"}:null:{policy:n.policy==="alert"?"alert":"reject",profile:t||n.profile==="id_document"?"id_document":"selfie"}}function j(s){return{...s.baselineEyeOpenness!==void 0?{baselineEyeOpenness:s.baselineEyeOpenness}:{},...s.baselineEyeOpennessLeft!==void 0&&s.baselineEyeOpennessRight!==void 0?{baselineEyeOpennessLeft:s.baselineEyeOpennessLeft,baselineEyeOpennessRight:s.baselineEyeOpennessRight}:{},criteria:s.verdict??{},...s.backgroundCheck!==void 0?{backgroundCheck:s.backgroundCheck}:{}}}export{w as a,D as b,c,_ as d,l as e,v as f,g,L as h,j as i};
1
+ import{c as f}from"./chunk-TSA6GHUG.js";import{a as h,c as y}from"./chunk-FSXWIMSG.js";var w=["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"];function D(s){return w.includes(s)}var c=class extends Error{constructor(e){super(e.message),this.name="HostedApiError",this.status=e.status,this.code=e.code,e.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=e.retryAfterSeconds),e.details&&(this.details=e.details)}};function _(s,e,n=Math.random){let t=(s??e)*1e3,o=Math.min(Math.max(t,500),2e4),i=Math.round(o*(1+(n()*2-1)*.25));return Math.min(Math.max(i,500),2e4)}var k=6e4,b=4,R=3e4,I=9e5,P=200,E=5,M=400,C=new Set(["server_busy","request_timeout"]),A=2;function l(s){return(s.split(";")[0]??"").trim()}var O={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},v=`@sekyro/web/${h}`,N=v,g=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.reportedIssues=new Map;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let n=e.fetch;this.fetchImpl=(t,o)=>(n??globalThis.fetch).call(globalThis,t,o),this.requestTimeoutMs=e.requestTimeoutMs??R,this.retryAttempts=e.inProgressRetry?.attempts??E,this.retryDelayMs=e.inProgressRetry?.delayMs??M,this.random=e.random??Math.random}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e},busyRetry:!0})}async reportCameraUnavailable(e){return this.api("POST","/hosted/camera-unavailable",{body:{cause:e}})}async 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,o=typeof e.attempt=="number"&&Number.isInteger(e.attempt)&&e.attempt>=0&&e.attempt<=1e3?e.attempt:void 0,i=[e.check,o??"",e.kind,n,e.phase??""].join("|"),a=this.reportedIssues.get(i);if(a!==void 0)return a;let d={check:e.check,kind:e.kind,...n!==""?{name:n}:{},...e.phase!==void 0?{phase:e.phase}:{},...t!==void 0?{engineKind:t}:{},...o!==void 0?{attempt:o}:{},...e.formFactor!==void 0?{formFactor:e.formFactor}:{}},r=this.api("POST","/hosted/capture-issue",{body:d,empty:!0}).catch(()=>{this.reportedIssues.delete(i)});return this.reportedIssues.set(i,r),r}async choose(e,n){let t=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:n},busyRetry:!0});return this.sessionId=t.sessionId,t}async confirmIdentity(e){return this.api("POST","/hosted/identity/confirm",{body:{decision:e}})}async identityPortrait(){return this.api("GET","/hosted/identity/portrait",{blob:!0})}async presign(e,n,t,o={}){let i=await this.ensureSessionId(),a={kind:e,contentType:l(n),contentLength:t,...o.source==="upload"?{source:"upload"}:{}};return this.api("POST",`/sessions/${i}/media`,{body:a})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,n,t,o={}){let i=await this.ensureSessionId(),a=await this.takeCaptureNonce(),d=a===void 0?void 0:{nonce:a,...o.engine!==void 0?{engine:o.engine.slice(0,32)}:{},...o.durationMs!==void 0&&Number.isFinite(o.durationMs)?{captureMs:Math.min(36e5,Math.max(0,Math.round(o.durationMs)))}:{}},r={kind:e,contentType:l(n),contentLength:t,capture:d};return this.api("POST",`/sessions/${i}/media`,{body:r})}async takeCaptureNonce(){let e=()=>{let n=Date.now();return this.captureNonces=this.captureNonces.filter(t=>t.expiresAt-k>n),this.captureNonces.shift()?.nonce};for(let n=0;n<2;n++){let t=e();if(t!==void 0)return t;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let n=await this.ensureSessionId(),t=await this.api("POST",`/sessions/${n}/media/capture-nonces`,{body:{count:Math.min(b,Math.max(1,e))}}),o=Date.now()+Math.max(0,t.expiresIn)*1e3;for(let i of Array.isArray(t.nonces)?t.nonces:[])typeof i=="string"&&i.length>0&&this.captureNonces.push({nonce:i,expiresAt:o});this.captureNonces=this.captureNonces.slice(-b)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,n,t){let o;try{o=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":l(t)},body:n,signal:AbortSignal.timeout(I)})}catch(i){throw m(i)}if(!o.ok){let i=(await o.text().catch(()=>"")).slice(0,P);throw new c({status:o.status,code:"upload_failed",message:`media upload failed (HTTP ${o.status})${i?`: ${i}`:""}`})}}async completeMedia(e){let n=await this.ensureSessionId();return this.api("POST",`/sessions/${n}/media/complete`,{body:{key:e}})}async submitCheck(e,n,t={}){let o=await this.ensureSessionId(),i={input:n,forceOutcome:t.forceOutcome};return this.api("POST",`/sessions/${o}/checks/${e}`,{body:i,idempotencyKey:t.idempotencyKey,busyRetry:t.idempotencyKey!==void 0})}async uploadAndSubmit(e,n,t,o={}){let i=l(n.contentType),a=await this.presign(n.kind,i,n.blob.size);await this.uploadToSpaces(a.uploadUrl,n.blob,i);let d=await this.completeMedia(a.key),r={...t,[O[e]]:d.key};return this.submitCheck(e,r,o)}async ensureSessionId(){return this.sessionId!==null?this.sessionId:(this.bootstrap??(this.bootstrap=this.getSession().finally(()=>{this.bootstrap=null})),(await this.bootstrap).sessionId)}async api(e,n,t={}){let o=e==="GET"||t.busyRetry===!0,i=`${this.apiOrigin}/api/v2${n}`,a={"x-session-token":this.sessionToken,"x-sekyro-sdk":N};t.body!==void 0&&(a["content-type"]="application/json"),t.idempotencyKey!==void 0&&(a["x-idempotency-key"]=t.idempotencyKey);try{let d=y.timezone();d!==void 0&&(a["sekyro-client-timezone"]=d)}catch{}a["sekyro-client-form-factor"]=f();try{let d=await y.deviceHeader();d!==void 0&&(a["sekyro-client-device"]=d)}catch{}for(let d=0;;d++){let r;try{r=await this.fetchImpl(i,{method:e,headers:a,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(p){throw m(p)}if(r.ok){if(t.empty===!0)return;if(t.blob===!0)try{return await r.blob()}catch(S){throw m(S)}let p;try{p=await r.json()}catch{throw new c({status:r.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${r.status})`})}return H(p)}let u=await x(r);if(u.code==="idempotency_in_progress"&&d<this.retryAttempts){this.retryDelayMs>0&&await T(this.retryDelayMs);continue}if(o&&u.status===503&&C.has(u.code)){o=!1,await T(_(u.retryAfterSeconds,A,this.random));continue}throw u}}};function m(s){if((typeof s=="object"&&s!==null?s.name:void 0)==="TimeoutError")return new c({status:0,code:"timeout",message:"request timed out"});let n=s instanceof Error?s.message:String(s);return new c({status:0,code:"network_error",message:`network request failed: ${n}`})}function H(s){return s!==null&&typeof s=="object"&&"success"in s&&"data"in s?s.data:s}async function x(s){let e="unknown_error",n=`request failed (HTTP ${s.status})`,t=Number.NaN,o;try{let d=await s.json();if(d!==null&&typeof d=="object"){let r=d;typeof r.code=="string"&&r.code.length>0&&(e=r.code),typeof r.message=="string"&&r.message.length>0&&(n=r.message),typeof r.retryAfterSeconds=="number"&&(t=r.retryAfterSeconds),Array.isArray(r.details?.issues)&&(o=r.details)}}catch{}let i=s.headers.get("retry-after"),a=i===null?Math.floor(t):Number.parseInt(i,10);return new c({status:s.status,code:e,message:n,...Number.isFinite(a)&&a>=0?{retryAfterSeconds:a}:{},details:o})}function T(s){return new Promise(e=>setTimeout(e,s))}function L(s){let e=s?.portrait,n=e?.icao,t=e?.purpose==="id_document";return n==null?t?{policy:"reject",profile:"id_document"}:null:{policy:n.policy==="alert"?"alert":"reject",profile:t||n.profile==="id_document"?"id_document":"selfie"}}function j(s){return{...s.baselineEyeOpenness!==void 0?{baselineEyeOpenness:s.baselineEyeOpenness}:{},...s.baselineEyeOpennessLeft!==void 0&&s.baselineEyeOpennessRight!==void 0?{baselineEyeOpennessLeft:s.baselineEyeOpennessLeft,baselineEyeOpennessRight:s.baselineEyeOpennessRight}:{},criteria:s.verdict??{},...s.backgroundCheck!==void 0?{backgroundCheck:s.backgroundCheck}:{}}}export{w as a,D as b,c,_ as d,l as e,v as f,g,L as h,j as i};
@@ -1 +1 @@
1
- import{d as Jt,h as qt,k as te}from"./chunk-G6LKLN4U.js";import{b as $t}from"./chunk-SMKCBUJL.js";import{a as et,b as ee,c as ie,e as mt,f as oe}from"./chunk-4DEPREJ3.js";import{b as Yt,c as Zt}from"./chunk-NFHLJOHW.js";import{b as Vt,c as Xt}from"./chunk-POIQGEZM.js";import{k as Qt,m as Bt,n as Wt,o as Ht,p as Kt,r as ut}from"./chunk-CPUECYAJ.js";import{b as ht,c as dt,d as j,e as jt}from"./chunk-FPXL63KZ.js";import{d as Ut}from"./chunk-U3JUGEIW.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 ne(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 Xe=Object.freeze({MAX_AREA_FRAC:.92,TILT_MAX_SIDE_RATIO:1.3,GLARE_MAX_SPECULAR_FRAC:.025});function re(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 je(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 ae(i){let t={...ee,...i.thresholds},e=Xe,{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":se(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=ie(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":se(o,n,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":Zt(i.format,f)?je(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 se(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 le=Object.freeze({width:1920,height:1080}),Ye=Object.freeze({width:3840,height:2160}),ce=4096,Ze=2560,ue=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 he(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 Je(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 he(n,t)}function ft(i,t,e){let o=Math.max(i,t);return o>0?Math.min(1,e/o):1}function pt(i,t,e,o,n=Ze){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=Je(c,e,o)??{x:0,y:0,width:e.width,height:e.height},l=ft(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=he({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}}function de(i,t,e,o=Ye){if(e==="LOW")return null;let n=i?.width?.max,s=i?.height?.max;if(typeof n!="number"||typeof s!="number"||n<=0||s<=0)return null;let r=Math.max(n,s),c=Math.min(n,s),a=Math.min(r,Math.max(o.width,o.height)),l=Math.min(c,Math.min(o.width,o.height));return a<=Math.max(t.width,t.height)?null:{width:{ideal:a},height:{ideal:l}}}function me(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?ce:ce*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 fe(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 pe(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 ge=3500,qe=.92;function ye(){let i=globalThis.ImageCapture;return typeof i=="function"?i:null}function $e(i){return/AppleWebKit\//.test(i)&&!/(Chrome|Chromium|Edg|OPR)\//.test(i)}function Me(i,t=typeof navigator>"u"?"":navigator.userAgent){return ye()!==null&&!$e(t)&&i!=null&&i.kind==="video"&&i.readyState==="live"}function be(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 gt(i,t){let e=document.createElement("canvas");return e.width=i,e.height=t,e}function ti(i,t){return new Promise((e,o)=>{i.toBlob(n=>n?e(n):o(new Error("toBlob failed")),"image/jpeg",t)})}async function ke(i,t,e,o,n){let s=gt(e,o),r=gt(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 ti(s,qe),l=n===null?null:Jt({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=qt(s,l),d=ft(e,o,ue);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 ei(i,t){let e=Math.min(1,t/i.width),o=gt(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=pt(t,e,n,o);return{...await ke(i,s.crop,s.width,s.height,s.docRegion),docRegion:s.docRegion,source:"video",width:s.width,height:s.height}}async function xe(i,t,e,o,n){let s=ye();if(s===null)return null;let r=null;try{let c=new s(n.track),a=await be(c.getPhotoCapabilities?.()??Promise.resolve({}),ge).catch(()=>({})),l=await be(c.takePhoto(me(a)),ge);r=await createImageBitmap(l);let u={width:i.videoWidth,height:i.videoHeight};if(!fe(r,u))return null;let d=ei(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&&!pe(m,h,t,e)&&(m=null);let f=pt(m,h,r,o);return{...await ke(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 Si(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 bt="sekyro.doc.camera";function ii(){try{let i=globalThis.localStorage?.getItem(bt);return typeof i=="string"&&i!==""?i:null}catch{return null}}function we(i){try{i===null?globalThis.localStorage?.removeItem(bt):globalThis.localStorage?.setItem(bt,i)}catch{}}var rt=(i,t)=>Array.isArray(i?.focusMode)&&i.focusMode.includes(t);function Mt(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 _i(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 Se(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 yt(i){try{return i.getVideoTracks?.()[0]}catch{return}}function ve(i){if(i!==null)for(let t of i.getTracks())t.stop()}function oi(i){try{let t=yt(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=ii();if(s!==null)try{return{stream:await e(s),lens:"stored"}}catch{we(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?yt(n)?.getSettings?.().deviceId:void 0;if(n===null||a!==c){ve(n),n=null;try{n=await e(c)}catch{continue}}if(r??(r=c),oi(n))return we(c),{stream:n,lens:"selected"}}if(n!==null&&r!==null&&yt(n)?.getSettings?.().deviceId===r)return{stream:n,lens:"selected"};if(ve(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 Re(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 Fe(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)),D=y(Math.floor(u-f),0,n-1),w=y(Math.floor(d-g),0,s-1),O=y(Math.ceil(m+f),D+1,n),v=y(Math.ceil(h+g),w+1,s),x=Math.max(1,Math.ceil(Math.max(O-D,v-w)/320)),M=Math.floor((O-D+x-1)/x),T=Math.floor((v-w+x-1)/x);if(M<3||T<3)return Z;let k=new Int32Array(M*T);for(let p=0;p<T;p++){let b=w+p*x;for(let R=0;R<M;R++){let F=(b*n+D+R*x)*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)/x,_=C(u,D),A=C(m,D),B=C(d,w),U=C(h,w),Dt=(m-u)/x,xt=(h-d)/x,wt=y(Math.ceil(_),0,M-1),Ie=y(Math.floor(A),wt,M-1),vt=y(Math.ceil(B),0,T-1),Ge=y(Math.floor(U),vt,T-1),St=0,Tt=0,W=0,_t=0,Rt=0,H=0;for(let p=vt;p<=Ge;p++)for(let b=wt;b<=Ie;b++){let R=k[p*M+b];if(St+=R,R>=248&&Tt++,W++,b>=1&&b<M-1&&p>=1&&p<T-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;_t+=F,Rt+=F*F,H++}}let ze=W>0?St/W:0,Ft=W>0?Tt/W:0,Ct=H>0?_t/H:0,Ne=H>0?Math.max(0,Rt/H-Ct*Ct):0,K=new Float64Array(M),V=new Float64Array(T);for(let p=0;p<T;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<T-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 P=at(K,!0,_,o),I=at(K,!1,A,o),G=at(V,!0,B,o),z=at(V,!1,U,o),At=(I.position-P.position)/Dt,Et=(z.position-G.position)/xt,Qe=Et>0?At/Et:0,Be=((P.position+I.position)/2-(_+A)/2)/Dt,Ue=((G.position+z.position)/2-(B+U)/2)/xt,Lt=_e(K),Ot=_e(V),We=Lt<=0||Ot<=0?0:Math.min(Math.min(P.value,I.value)/Lt,Math.min(G.value,z.value)/Ot),$=(p,b)=>b+(p+.5)*x,Pt=Ft,It=0;{let p=(I.position-P.position)*.06,b=(z.position-G.position)*.06,R=y(Math.ceil(P.position+p),0,M-1),F=y(Math.floor(I.position-p),0,M-1),He=y(Math.ceil(G.position+b),0,T-1),Gt=y(Math.floor(z.position-b),0,T-1),zt=0,tt=0,Nt=0;for(let N=He;N<=Gt;N++)for(let Q=R;Q<=F;Q++){tt++;let X=k[N*M+Q];X>=248&&zt++;let Ke=Q+2<=F?k[N*M+Q+2]:X,Ve=N+2<=Gt?k[(N+2)*M+Q]:X;(Math.abs(Ke-X)>=24||Math.abs(Ve-X)>=24)&&Nt++}tt>=16&&(Pt=zt/tt,It=Nt/tt)}return{brightness:ze,glare:Ft,cardGlare:Pt,sharpness:Ne,fill:At,shape:Qe,content:It,offsetX:Be,offsetY:Ue,edgeConfidence:We,box:{left:$(P.position,D),right:$(I.position,D),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 D=i[y];if(D<h||D<(i[y-1]??0)||D<(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 _e(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 Ce(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 Ai(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 ni(i){return q===null&&(q=(await import("./detector-scanic-23DAYT3H.js")).detectQuad),q(i)}async function si(i){let t=$t(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-23DAYT3H.js").then(i=>{q=i.detectQuad}).catch(()=>{})}var Ae=4e3,ri=2,Ee=3,ai=Object.freeze({LOW:3,MID:5,HIGH:6}),kt=Object.freeze({manualShutterMs:6e3,detectedNoLockMs:1950});function Yi(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)??kt.manualShutterMs,detectedNoLockMs:e(t.steadyMs,300,3e4)!==void 0?t.steadyMs+(e(t.lockMs,0,1e4)??450):kt.detectedNoLockMs}}var Le=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 oe(t.format??"ID-1",t.thresholds);let e=t.deviceClass??Xt(Vt());this.deviceClass=e,this.camera=t.camera??st,this.shutterTuning=t.shutter??kt,this.guideTuning=t.guideLock??J,this.guideLock=new ct(this.guideTuning),this.cadenceMs=1e3/ai[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(),Ht(),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:le});if(e!==this.attempt){for(let r of s.stream.getTracks())r.stop();return}if(this.stream=s.stream,Ut(this.stream),Wt(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=Bt(o),s=Qt(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??Ae;e<=0||(this.clearFrameWatch(),this.frameWatch=setTimeout(()=>{if(this.frameWatch=null,!(t!==this.attempt||this.state!=="positioning")){if(this.framesNow()&&this.blackTicks<Ee){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 Re(c,a,e,0)}let n=Yt(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=de(t.getCapabilities?.(),{width:e.width??0,height:e.height??0},this.deviceClass,{width:this.camera.width,height:this.camera.height});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=Se(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=Mt(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=Mt(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&&Me(s)){await this.refocusOn(t,e);let r=await xe(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"?si:ni)}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)>ri)this.lit=!0,this.blackTicks=0;else if(++this.blackTicks>=Ee&&this.frameWatch===null&&(this.opts.firstFrameMs??Ae)>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:jt(c),meanLuma:dt(c),specularFraction:re(c)},u=ae({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"?Fe(s,this.guideRegion(s),{edgePeakFrac:this.guideTuning.edgePeakFrac}):Z,f=this.guideLock.tick(h,a);this.lastGuideQuad=f.detected?Ce(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 _=u.lighting!=="ok"?u.lighting:u.glare!=="ok"?"glare":u.blur!=="ok"?"blurry":"steadying";y.qualityBlockers[_]=(y.qualityBlockers[_]??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<=fi?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=ne(u);u.framing!=="ok"&&f.detected&&(v=mi(f.blocker,h.brightness<this.guideTuning.darkBrightness)),v==="blurry"&&r!==null&&li(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 x=this.feedback.tick(v,a);if(x.key!==this.lastFeedbackKey&&(this.lastFeedbackKey=x.key,this.emit("feedback",x)),d.guidanceKey!==this.lastGuidance&&(this.lastGuidance=d.guidanceKey,this.emit("guidance",{key:d.guidanceKey})),this.capturing)return;let M=g?.suspendQuality!==!0,T=M&&d.ready&&r!==null,k=M&&f.ready&&this.lastGuideQuad!==null,C=this.lastOcrReady;if(C!==null&&this.opts.autoCapture!==!1){let _=this.feedback.force("processing",a);this.lastFeedbackKey=_.key,this.emit("feedback",_);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((T||k)&&this.opts.autoCapture!==!1){let _=this.feedback.force("processing",a);this.lastFeedbackKey=_.key,this.emit("feedback",_);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"?0:ui;for(let m=0;m<l;m++){if(await new Promise(g=>{r(()=>g(),hi)}),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*di){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,D;m&&e!==null?D=ci(E(e),g,y,l,u):D=te(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:D,portrait:u>l,glareOk:w,sharpOk:O});if(v.ready&&v.via!==void 0){let x=m?e??Oe(h,t):this.lastGuideQuad??Oe(h,t);this.lastOcrReady={quad:x,via:v.via}}else this.lastOcrReady=null;return v}};function ci(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 Oe(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 li(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 ui=2,hi=260,di=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 mi(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 fi=1200;export{it as a,ne as b,ot as c,Xe as d,re as e,je as f,ae as g,st as h,Si as i,bt as j,ii as k,we as l,rt as m,Mt as n,_i as o,Se as p,oi as q,Te as r,Z as s,Re as t,Fe as u,Ce as v,J as w,Ai as x,ct as y,ji as z,Ae as A,ri as B,Ee as C,ai as D,kt as E,Yi as F,Le as G,ci as H,ui as I,hi as J};
1
+ import{d as Jt,h as qt,k as te}from"./chunk-G6LKLN4U.js";import{b as $t}from"./chunk-SMKCBUJL.js";import{a as et,b as ee,c as ie,e as mt,f as oe}from"./chunk-4DEPREJ3.js";import{b as Yt,c as Zt}from"./chunk-NFHLJOHW.js";import{b as Vt,c as Xt}from"./chunk-POIQGEZM.js";import{k as Qt,m as Bt,n as Wt,o as Ht,p as Kt,r as ut}from"./chunk-CPUECYAJ.js";import{b as ht,c as dt,d as j,e as jt}from"./chunk-FPXL63KZ.js";import{d as Ut}from"./chunk-FSXWIMSG.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 ne(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 Xe=Object.freeze({MAX_AREA_FRAC:.92,TILT_MAX_SIDE_RATIO:1.3,GLARE_MAX_SPECULAR_FRAC:.025});function re(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 je(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 ae(i){let t={...ee,...i.thresholds},e=Xe,{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":se(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=ie(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":se(o,n,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":Zt(i.format,f)?je(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 se(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 le=Object.freeze({width:1920,height:1080}),Ye=Object.freeze({width:3840,height:2160}),ce=4096,Ze=2560,ue=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 he(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 Je(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 he(n,t)}function ft(i,t,e){let o=Math.max(i,t);return o>0?Math.min(1,e/o):1}function pt(i,t,e,o,n=Ze){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=Je(c,e,o)??{x:0,y:0,width:e.width,height:e.height},l=ft(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=he({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}}function de(i,t,e,o=Ye){if(e==="LOW")return null;let n=i?.width?.max,s=i?.height?.max;if(typeof n!="number"||typeof s!="number"||n<=0||s<=0)return null;let r=Math.max(n,s),c=Math.min(n,s),a=Math.min(r,Math.max(o.width,o.height)),l=Math.min(c,Math.min(o.width,o.height));return a<=Math.max(t.width,t.height)?null:{width:{ideal:a},height:{ideal:l}}}function me(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?ce:ce*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 fe(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 pe(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 ge=3500,qe=.92;function ye(){let i=globalThis.ImageCapture;return typeof i=="function"?i:null}function $e(i){return/AppleWebKit\//.test(i)&&!/(Chrome|Chromium|Edg|OPR)\//.test(i)}function Me(i,t=typeof navigator>"u"?"":navigator.userAgent){return ye()!==null&&!$e(t)&&i!=null&&i.kind==="video"&&i.readyState==="live"}function be(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 gt(i,t){let e=document.createElement("canvas");return e.width=i,e.height=t,e}function ti(i,t){return new Promise((e,o)=>{i.toBlob(n=>n?e(n):o(new Error("toBlob failed")),"image/jpeg",t)})}async function ke(i,t,e,o,n){let s=gt(e,o),r=gt(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 ti(s,qe),l=n===null?null:Jt({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=qt(s,l),d=ft(e,o,ue);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 ei(i,t){let e=Math.min(1,t/i.width),o=gt(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=pt(t,e,n,o);return{...await ke(i,s.crop,s.width,s.height,s.docRegion),docRegion:s.docRegion,source:"video",width:s.width,height:s.height}}async function xe(i,t,e,o,n){let s=ye();if(s===null)return null;let r=null;try{let c=new s(n.track),a=await be(c.getPhotoCapabilities?.()??Promise.resolve({}),ge).catch(()=>({})),l=await be(c.takePhoto(me(a)),ge);r=await createImageBitmap(l);let u={width:i.videoWidth,height:i.videoHeight};if(!fe(r,u))return null;let d=ei(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&&!pe(m,h,t,e)&&(m=null);let f=pt(m,h,r,o);return{...await ke(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 Si(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 bt="sekyro.doc.camera";function ii(){try{let i=globalThis.localStorage?.getItem(bt);return typeof i=="string"&&i!==""?i:null}catch{return null}}function we(i){try{i===null?globalThis.localStorage?.removeItem(bt):globalThis.localStorage?.setItem(bt,i)}catch{}}var rt=(i,t)=>Array.isArray(i?.focusMode)&&i.focusMode.includes(t);function Mt(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 _i(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 Se(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 yt(i){try{return i.getVideoTracks?.()[0]}catch{return}}function ve(i){if(i!==null)for(let t of i.getTracks())t.stop()}function oi(i){try{let t=yt(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=ii();if(s!==null)try{return{stream:await e(s),lens:"stored"}}catch{we(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?yt(n)?.getSettings?.().deviceId:void 0;if(n===null||a!==c){ve(n),n=null;try{n=await e(c)}catch{continue}}if(r??(r=c),oi(n))return we(c),{stream:n,lens:"selected"}}if(n!==null&&r!==null&&yt(n)?.getSettings?.().deviceId===r)return{stream:n,lens:"selected"};if(ve(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 Re(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 Fe(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)),D=y(Math.floor(u-f),0,n-1),w=y(Math.floor(d-g),0,s-1),O=y(Math.ceil(m+f),D+1,n),v=y(Math.ceil(h+g),w+1,s),x=Math.max(1,Math.ceil(Math.max(O-D,v-w)/320)),M=Math.floor((O-D+x-1)/x),T=Math.floor((v-w+x-1)/x);if(M<3||T<3)return Z;let k=new Int32Array(M*T);for(let p=0;p<T;p++){let b=w+p*x;for(let R=0;R<M;R++){let F=(b*n+D+R*x)*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)/x,_=C(u,D),A=C(m,D),B=C(d,w),U=C(h,w),Dt=(m-u)/x,xt=(h-d)/x,wt=y(Math.ceil(_),0,M-1),Ie=y(Math.floor(A),wt,M-1),vt=y(Math.ceil(B),0,T-1),Ge=y(Math.floor(U),vt,T-1),St=0,Tt=0,W=0,_t=0,Rt=0,H=0;for(let p=vt;p<=Ge;p++)for(let b=wt;b<=Ie;b++){let R=k[p*M+b];if(St+=R,R>=248&&Tt++,W++,b>=1&&b<M-1&&p>=1&&p<T-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;_t+=F,Rt+=F*F,H++}}let ze=W>0?St/W:0,Ft=W>0?Tt/W:0,Ct=H>0?_t/H:0,Ne=H>0?Math.max(0,Rt/H-Ct*Ct):0,K=new Float64Array(M),V=new Float64Array(T);for(let p=0;p<T;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<T-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 P=at(K,!0,_,o),I=at(K,!1,A,o),G=at(V,!0,B,o),z=at(V,!1,U,o),At=(I.position-P.position)/Dt,Et=(z.position-G.position)/xt,Qe=Et>0?At/Et:0,Be=((P.position+I.position)/2-(_+A)/2)/Dt,Ue=((G.position+z.position)/2-(B+U)/2)/xt,Lt=_e(K),Ot=_e(V),We=Lt<=0||Ot<=0?0:Math.min(Math.min(P.value,I.value)/Lt,Math.min(G.value,z.value)/Ot),$=(p,b)=>b+(p+.5)*x,Pt=Ft,It=0;{let p=(I.position-P.position)*.06,b=(z.position-G.position)*.06,R=y(Math.ceil(P.position+p),0,M-1),F=y(Math.floor(I.position-p),0,M-1),He=y(Math.ceil(G.position+b),0,T-1),Gt=y(Math.floor(z.position-b),0,T-1),zt=0,tt=0,Nt=0;for(let N=He;N<=Gt;N++)for(let Q=R;Q<=F;Q++){tt++;let X=k[N*M+Q];X>=248&&zt++;let Ke=Q+2<=F?k[N*M+Q+2]:X,Ve=N+2<=Gt?k[(N+2)*M+Q]:X;(Math.abs(Ke-X)>=24||Math.abs(Ve-X)>=24)&&Nt++}tt>=16&&(Pt=zt/tt,It=Nt/tt)}return{brightness:ze,glare:Ft,cardGlare:Pt,sharpness:Ne,fill:At,shape:Qe,content:It,offsetX:Be,offsetY:Ue,edgeConfidence:We,box:{left:$(P.position,D),right:$(I.position,D),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 D=i[y];if(D<h||D<(i[y-1]??0)||D<(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 _e(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 Ce(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 Ai(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 ni(i){return q===null&&(q=(await import("./detector-scanic-23DAYT3H.js")).detectQuad),q(i)}async function si(i){let t=$t(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-23DAYT3H.js").then(i=>{q=i.detectQuad}).catch(()=>{})}var Ae=4e3,ri=2,Ee=3,ai=Object.freeze({LOW:3,MID:5,HIGH:6}),kt=Object.freeze({manualShutterMs:6e3,detectedNoLockMs:1950});function Yi(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)??kt.manualShutterMs,detectedNoLockMs:e(t.steadyMs,300,3e4)!==void 0?t.steadyMs+(e(t.lockMs,0,1e4)??450):kt.detectedNoLockMs}}var Le=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 oe(t.format??"ID-1",t.thresholds);let e=t.deviceClass??Xt(Vt());this.deviceClass=e,this.camera=t.camera??st,this.shutterTuning=t.shutter??kt,this.guideTuning=t.guideLock??J,this.guideLock=new ct(this.guideTuning),this.cadenceMs=1e3/ai[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(),Ht(),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:le});if(e!==this.attempt){for(let r of s.stream.getTracks())r.stop();return}if(this.stream=s.stream,Ut(this.stream),Wt(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=Bt(o),s=Qt(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??Ae;e<=0||(this.clearFrameWatch(),this.frameWatch=setTimeout(()=>{if(this.frameWatch=null,!(t!==this.attempt||this.state!=="positioning")){if(this.framesNow()&&this.blackTicks<Ee){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 Re(c,a,e,0)}let n=Yt(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=de(t.getCapabilities?.(),{width:e.width??0,height:e.height??0},this.deviceClass,{width:this.camera.width,height:this.camera.height});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=Se(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=Mt(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=Mt(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&&Me(s)){await this.refocusOn(t,e);let r=await xe(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"?si:ni)}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)>ri)this.lit=!0,this.blackTicks=0;else if(++this.blackTicks>=Ee&&this.frameWatch===null&&(this.opts.firstFrameMs??Ae)>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:jt(c),meanLuma:dt(c),specularFraction:re(c)},u=ae({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"?Fe(s,this.guideRegion(s),{edgePeakFrac:this.guideTuning.edgePeakFrac}):Z,f=this.guideLock.tick(h,a);this.lastGuideQuad=f.detected?Ce(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 _=u.lighting!=="ok"?u.lighting:u.glare!=="ok"?"glare":u.blur!=="ok"?"blurry":"steadying";y.qualityBlockers[_]=(y.qualityBlockers[_]??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<=fi?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=ne(u);u.framing!=="ok"&&f.detected&&(v=mi(f.blocker,h.brightness<this.guideTuning.darkBrightness)),v==="blurry"&&r!==null&&li(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 x=this.feedback.tick(v,a);if(x.key!==this.lastFeedbackKey&&(this.lastFeedbackKey=x.key,this.emit("feedback",x)),d.guidanceKey!==this.lastGuidance&&(this.lastGuidance=d.guidanceKey,this.emit("guidance",{key:d.guidanceKey})),this.capturing)return;let M=g?.suspendQuality!==!0,T=M&&d.ready&&r!==null,k=M&&f.ready&&this.lastGuideQuad!==null,C=this.lastOcrReady;if(C!==null&&this.opts.autoCapture!==!1){let _=this.feedback.force("processing",a);this.lastFeedbackKey=_.key,this.emit("feedback",_);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((T||k)&&this.opts.autoCapture!==!1){let _=this.feedback.force("processing",a);this.lastFeedbackKey=_.key,this.emit("feedback",_);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"?0:ui;for(let m=0;m<l;m++){if(await new Promise(g=>{r(()=>g(),hi)}),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*di){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,D;m&&e!==null?D=ci(E(e),g,y,l,u):D=te(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:D,portrait:u>l,glareOk:w,sharpOk:O});if(v.ready&&v.via!==void 0){let x=m?e??Oe(h,t):this.lastGuideQuad??Oe(h,t);this.lastOcrReady={quad:x,via:v.via}}else this.lastOcrReady=null;return v}};function ci(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 Oe(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 li(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 ui=2,hi=260,di=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 mi(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 fi=1200;export{it as a,ne as b,ot as c,Xe as d,re as e,je as f,ae as g,st as h,Si as i,bt as j,ii as k,we as l,rt as m,Mt as n,_i as o,Se as p,oi as q,Te as r,Z as s,Re as t,Fe as u,Ce as v,J as w,Ai as x,ct as y,ji as z,Ae as A,ri as B,Ee as C,ai as D,kt as E,Yi as F,Le as G,ci as H,ui as I,hi as J};
@@ -0,0 +1 @@
1
+ import{c as P,d as H,e as A}from"./chunk-J7D3S5ZJ.js";var Y=new Set(["nni_unbound","id_number_unbound","method_required","mobile_required","portrait_required"]);function Re(e){return Y.has(e)}function Ce(e,n,t){let i=n.detail;return{check:e,kind:n.kind,...i?.name!==void 0?{name:i.name}:{},...i?.phase!==void 0?{phase:i.phase}:{},...i?.engineKind!==void 0?{engineKind:i.engineKind}:{},attempt:Math.max(0,Math.min(1e3,t))}}function ke(){let e=-1,n="";return{note(t){t==="starting"&&n!=="starting"&&(e+=1),n=t},newHandle(){n=""},noteError(){e<0&&(e=0)},get value(){return e}}}var $={document:"document_photo",nfc:"document_chip",population_registry:"national_number",national_eid:"national_eid"};function p(e){return e.plan?.steps??[]}function V(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 ve(e){let n=j(e);if(n?.kind!=="identity_method")return null;let t=n.options.map(o=>$[o.service]).filter(o=>o!==void 0),i=n.options.find(o=>o.nationalEid)?.nationalEid;return i?{available:!0,selected:null,options:t,nationalEid:i}:{available:!0,selected:null,options:t}}var z=new Set(["liveness","face_match"]);function _(e){return e!==void 0&&(e.state==="pending"||e.state==="input_required")}function I(e){return e.status!=="created"&&e.status!=="in_progress"}function x(e){let n=e.plan?.current,t=n==null?void 0:p(e).find(i=>i.id===n);return _(t)?t:void 0}function h(e,n){return p(e).find(t=>t.checkType===n)}function y(e){let n=p(e),t=n.findIndex(i=>i.checkType==="liveness");return n.find((i,o)=>o>t&&i.checkType==="face_match")}function T(e,n){let t=h(n,"liveness")?.state,i=y(n)?.state;return(y(e)?.state??"pending")==="pending"&&(t==="passed"||t==="review")&&i!==void 0&&i!=="pending"&&i!=="skipped"}function M(e,n){let t=new Map(p(e).map(i=>[i.id,i.state]));return p(n).filter(i=>i.checkType==="face_match"&&(t.get(i.id)??"pending")==="pending"&&i.state!=="pending"&&i.state!=="skipped").map(i=>i.id)}var G=/^[0-9a-f]{24}$/i;function g(e){return G.test(e)?`ses_${e}`:e}function k(e,n){let t=g(e);return n===void 0?{sessionId:t,status:"unavailable"}:{sessionId:t,status:"unavailable",reasonCode:n}}function O(e,n,t){let i=g(e);return t===void 0?{sessionId:i,status:n}:{sessionId:i,status:n,reasonCode:t}}function Pe(e,n){let t=J(e,n),i=X(e);return i!==void 0&&(t.sandbox={simulated:!0,reason:i}),t}var W=new Set(["no_testers","tester_gate_not_used","tester_gate_missed"]);function X(e){if(e.sandbox!==!0)return;let n=e.simulation?.reason;return W.has(n)?n:void 0}function J(e,n){let t=g(e.sessionId);switch(e.status){case"created":case"in_progress":return te(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,Z(e));default:return b(e,{sessionId:t,status:"not_verified"})}}var Q=new Set([0,1,2,3]);function b(e,n){return Q.has(e.level)&&(n.level=e.level),typeof e.assurance=="string"&&e.assurance.length>0&&(n.assurance=e.assurance),n}function Z(e){let n={sessionId:g(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 ee(e){return e==="rejected"?"rejected":e==="unavailable"?"unavailable":"inconclusive"}function ne(e,n){if(n===void 0)return!1;let t=p(n).find(i=>i.id===e.id);return t!==void 0&&t.attempts.used===e.attempts.used}function te(e,n){let t=g(e.sessionId),i=p(e).find(r=>z.has(r.checkType)&&r.state==="input_required"&&r.reason!==void 0);if(i?.reason==="mobile_required")return k(t,"mobile_required");if(i?.reason!==void 0){if(i.result==="unavailable")return k(t,i.reason);let u=n.autoRetry&&(V(i)>0||ne(i,n.previous))?{sessionId:t,status:"retry",reasonCode:i.reason,attemptsRemaining:V(i)}:{sessionId:t,status:"not_verified",reason:ee(i.result),reasonCode:i.reason,attemptsRemaining:V(i)};return i.retakeHint!==void 0&&(u.retakeHint=i.retakeHint),u}let o=x(e);return o===void 0&&p(e).some(r=>r.state==="review")?O(t,"review",L(e,"review")):o?.checkType==="portrait_icao"?k(t,"portrait_required"):k(t)}function L(e,n){return p(e).find(t=>t.state===n&&t.reason!==void 0)?.reason}function K(e,n,t,i,o){return e.presignCapture!==void 0?e.presignCapture(n,t,i,o):e.presign(n,t,i)}function N(e){return{engine:e?.engine,durationMs:e?.clipMs}}var ie=["video/webm","video/mp4"],F="image/jpeg",oe=2,re=1e3,se=1e4,ae=3,ue=10,de=3,ce=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),le=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order","identity_confirm_required","check_not_active","step_not_on_path"]),w=class extends Error{constructor(){super("verification destroyed"),this.name="FlowCancelledError"}};function fe(e){let n=y(e);return h(e,"portrait_icao")?.state!=="pending"&&(n!==void 0?_(n):e.capture?.livePhoto?.oneCapture===!0)}var R=class extends Error{constructor(n){super(n),this.name="AttestationError"}};async function q(e,n,t={}){let i=e.uuid(),o=!1,r=!1,u=0,l=0;for(;;)try{return await n(e.client,i)}catch(s){if(s instanceof R){if(r)throw s;r=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(!(s instanceof P))throw s;if(s.code==="consent_required"&&!o){o=!0,await e.ensureConsent({force:!0}),i=e.uuid();continue}if(s.code==="attestation_invalid"&&!r){r=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(s.code==="inference_unavailable"&&l<ae){l+=1;let a=H(s.retryAfterSeconds,ue,e.random??Math.random);e.onBusy?.({attempt:l,retryAfterSeconds:a/1e3}),await e.sleep(a),t.onAttestationInvalid?.(),i=e.uuid();continue}if(ce.has(s.code)&&u<oe){u+=1;let a=s.retryAfterSeconds!==void 0?s.retryAfterSeconds*1e3:void 0;await e.sleep(a!==void 0?Math.min(a,se):re);continue}throw s}}var pe=new Set(["passed","review","processing","skipped"]);async function Ae(e){let{artifacts:n}=e,t=n.clip,i=A(n.clipMime??"");if(n.degraded==="NO_RECORDER"||t===void 0||!ie.includes(i))return{kind:"unavailable",reason:"no_recorder"};e.client.armCapture?.(2);let o=me(e,n.keyframe),r=he(e,t,i,o),u=Se(e,o),l=!1,s=new Set,a=!0,C=0;for(;;){if(e.isCancelled())return{kind:"cancelled"};let f=e.getView();if(I(f))return{kind:"settled"};let d=x(f),S=d?.checkType,v=S==="liveness"&&!l?"liveness":S==="face_match"&&!s.has(d?.id)&&s.size<2&&a?"face_match":null;if(v===null)return{kind:"settled"};if(v==="liveness"&&n.captureChannel==="desktop")return{kind:"unavailable",reason:"mobile_required"};try{if(v==="liveness"){l=!0;let c=await r();if(e.isCancelled())return{kind:"cancelled"};T(f,c)&&s.add(y(c)?.id);for(let D of M(f,c))s.add(D);await e.applySubmit(c,"liveness");let m=h(e.getView(),"liveness")?.state;a=m===void 0||pe.has(m)}else{s.add(d?.id);let c=await u();if(e.isCancelled())return{kind:"cancelled"};for(let m of M(f,c))s.add(m);await e.applySubmit(c,"face_match")}}catch(c){if(e.isCancelled()||c instanceof w)return{kind:"cancelled"};let m=ge(c);if(m.kind!=="resync"||C>=de)return m;C+=1,await e.refreshView()}}}function me(e,n){let t=null,i=null,o=()=>t!==null?Promise.resolve(t):(i??(i=(async()=>{let r=await K(e.client,"image",F,n.size,N(e.artifacts));return await e.client.uploadToSpaces(r.uploadUrl,n,F),t=(await e.client.completeMedia(r.key)).key,e.onKeyframePromoted?.(t),t})().finally(()=>{i=null})),i);return{ensure:o,attempt:()=>o().catch(()=>null),current:()=>t}}function he(e,n,t,i){let o=null,r,u=null,l=0,s;return()=>q(e,async(a,C)=>{if(o===null||r===void 0){if(e.isCancelled())throw new w;r===void 0&&!fe(e.getView())&&(r=null),e.onPhase("uploading");let[f,d]=await Promise.all([o!==null?Promise.resolve(o):(async()=>{let S=await K(a,"clip",t,n.size,N(e.artifacts));return await a.uploadToSpaces(S.uploadUrl,n,t),(await a.completeMedia(S.key)).key})(),r!==void 0?Promise.resolve(r===null?null:r.imageKey):i.attempt()]);o=f,r===void 0&&(r=d===null?null:{imageKey:d})}if(u===null){let f=performance.now();try{u=await e.getAttestation(),s=e.attestationError?.()}catch(d){throw new R(d instanceof Error?d.message:String(d))}l=Math.round(performance.now()-f)}return e.onPhase("checking"),a.submitCheck("liveness",{clipKey:o,attestation:u,captureChannel:e.artifacts.captureChannel,capture:{...ye(e.artifacts),attestationMs:l,attestationError:s},...r!==null?{faceMatch:r}:{}},{idempotencyKey:C})},{onAttestationInvalid:()=>{u=null}})}function Se(e,n){return()=>q(e,async(t,i)=>{if(n.current()===null){if(e.isCancelled())throw new w;e.onPhase("uploading")}let o=await n.ensure();return e.onPhase("checking"),t.submitCheck("face_match",{imageKey:o},{idempotencyKey:i})})}function ye(e){let n={width:e.width,height:e.height};for(let t of _e)e[t]!==void 0&&(n[t]=e[t]);return n}var _e=["engine","facingMode","mode","formFactor","clipMs","clipFrames","fps","clipRetakes","codec","cameraReadyMs","faceAcquireMs","captureMs","screenRamp","provenance"];function ge(e){if(e instanceof R)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(le.has(e.code))return{kind:"resync"}}return{kind:"unavailable",reason:"network"}}var U=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="InvalidInputError",this.field=n,this.kind=t}},B=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="OtpInputError",this.field=n,this.kind=t}};function E(e){return e?.source==="upload"?null:e?.source==="choice"&&e.sourcePick!=="camera"?"upload_or_phone":"phone"}function Le(e,n){if(n===void 0||!_(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=h(e,"portrait_icao");return t?.state==="passed"||t?.state==="review"?null:"phone"}case"doc_ocr":return E(e.documents);case"poa":return E(e.proofOfAddress);case"portrait_icao":{let t=e.portrait;return t?.pendingFix!==void 0||t?.reuse?.pending===!0?null:E(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 Ke(e){let n=e?.capture?.pick;return we(e)==="choice"&&(n==="self"||n==="assisted")?n:null}function Ne(e,n,t=null){return e==="choice"?n??t??"self":e}export{Re as a,Ce as b,ke as c,$ as d,p as e,V as f,j as g,ve as h,_ as i,I as j,x as k,h as l,g as m,k as n,Pe as o,X as p,Le as q,we as r,Ke as s,Ne as t,K as u,ie as v,oe as w,re as x,ae as y,ue as z,R as A,q as B,Ae as C,ye as D,U as E,B as F};
@@ -0,0 +1 @@
1
+ import{a as ne,b as ie}from"./chunk-SX7TUC3V.js";import{b as ce,c as ue,d as de}from"./chunk-POIQGEZM.js";import{a as Y,c as j,e as $,g as J,h as A,k as R,m as ee,n as re}from"./chunk-CPUECYAJ.js";import{b as L,c as pe,d as F,e as me}from"./chunk-FPXL63KZ.js";import{a as z,c as X,d as Z,e as Q}from"./chunk-TSA6GHUG.js";import{d as te}from"./chunk-FSXWIMSG.js";import{e as ae,f as se,h as G,j as oe,l as le}from"./chunk-FSSMUAKC.js";var Ie=[...Y.filter(i=>i.startsWith("video/mp4")),"video/webm;codecs=h264","video/webm;codecs=avc1","video/webm;codecs=vp8","video/webm;codecs=vp9","video/webm"],he=new Set;function De(i){let e=/(?:Chrome|Chromium)\/(\d+)\./.exec(i??"");return e?Number(e[1]):null}function fe(i=Oe(),e=globalThis.navigator?.userAgent){if(i===void 0)return"";let t=De(e)===126;for(let r of Ie)if(!(he.has(r)||t&&r.startsWith("video/mp4")))try{if(i(r))return r}catch{}return""}function V(i){i!==""&&he.add(i)}function ge(i){return i.replace(/^video\/x-matroska/i,"video/webm")}function ut(i){let e=/codecs=["']?([^,;"']+)/i.exec(i);return e?e[1].trim():i.split(";")[0].trim()}function Oe(){let i=globalThis.MediaRecorder;return i&&typeof i.isTypeSupported=="function"?e=>i.isTypeSupported(e):void 0}var U=2500,Pe=1e3,xe=1500,ve=25e5,Ge=100,Le=700,Fe=20,Ve=1500,N=null;function Ne(){return N??(N=import("./clip-inspect-DLJXVKV6.js").catch(i=>{throw N=null,i})),N.catch(()=>null)}var S=class extends Error{constructor(e,t){super(t??e),this.kind=e}},Ue=100;function H(i,e){return i.stats===void 0?!1:i.stats===null?!0:i.stats.durationMs<e-Ue}function be(i,e){return i.stats?e.stats?i.stats.durationMs>e.stats.durationMs:!0:!1}var I=class{constructor(e={}){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.pollTimer=null;this.settled=!1;this.now=e.now??(()=>globalThis.performance?.now?.()??Date.now())}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.pollTimer&&clearInterval(this.pollTimer),this.hardStopTimer=null,this.graceTimer=null,this.pollTimer=null}record(e,t,r,n=U,a){let s=fe(),o=Ne();return this.recordRaw(e,t,r,n,a,s).then(c=>He(c,o),c=>{throw c instanceof S&&(c.requestedMimeType=s),c})}recordRaw(e,t,r,n,a,s){return this.recorder&&!this.settled?Promise.reject(new S("generic","record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time")):(this.recorder=null,this.clearTimers(),this.chunks=[],this.bytes=0,this.settled=!1,this.stream=e,new Promise((o,c)=>{let l;try{l=new MediaRecorder(e,s?{mimeType:s,videoBitsPerSecond:ve}:{videoBitsPerSecond:ve})}catch{try{l=new MediaRecorder(e)}catch{c(new S("unsupported"));return}}this.recorder=l;let d=h=>{this.settled||(this.settled=!0,this.clearTimers(),h())},u=()=>d(()=>{let h=ge(l.mimeType||s||j),b=new Blob(this.chunks,{type:h});if(b.size===0){c(new S("generic","empty clip"));return}if(A(b)){c(new S("cliptoolarge"));return}o({blob:b,mimeType:h,requestedMimeType:s})});l.ondataavailable=h=>{h.data&&h.data.size&&(this.chunks.push(h.data),this.bytes+=h.data.size,this.bytes>J&&d(()=>{try{l.state!=="inactive"&&l.stop()}catch{}c(new S("cliptoolarge"))}))},l.onstop=u,l.onerror=()=>d(()=>c(new S("generic")));let f=this.now();if(r!==void 0||a!==void 0){let h=!1;l.onstart=()=>{if(!(h||this.settled)&&(h=!0,f=this.now(),r!==void 0))try{r()}catch{}}}try{l.start(Pe)}catch{d(()=>c(new S("generic")));return}let g=()=>{if(this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=null,this.settled||t?.(),l.state!=="inactive"){try{l.stop()}catch{u()}this.graceTimer=setTimeout(u,xe)}else u()},p=this.now();if(a===void 0){this.hardStopTimer=setTimeout(g,n);return}let m=null,y=!1;this.hardStopTimer=setTimeout(g,n+Le),this.pollTimer=setInterval(()=>{if(this.settled||y)return;let h=null;try{h=a.latest()}catch{h=null}let b=h?.presentationTimeMs;b!==void 0&&Number.isFinite(b)&&b>=f&&m===null&&(m=b);let C=m!==null&&b!==void 0&&b-m>=n,E=m===null&&this.now()-p>=n;if(!(!C&&!E)){if(y=!0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,E){g();return}this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=setTimeout(g,Ge)}},Fe)}))}stop(e){this.clearTimers();let t=this.recorder;if(t&&t.state!=="inactive")try{t.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(n=>n.stop()),this.stream=null}};async function He(i,e){let t,r=new Promise(l=>{t=setTimeout(()=>l(null),Ve)}),n=await Promise.race([e,r]);if(clearTimeout(t),n===null)return i;let a;try{a=await n.blobBytes(i.blob)}catch{return{...i,stats:null}}let s=n.inspectClipBytes(a);if(s?.container!=="webm")return{...i,stats:s};let o=n.withWebmDuration(a,s.durationMs);if(o===null)return{...i,stats:s};let c=n.inspectClipBytes(o);return c===null||c.frames!==s.frames||c.durationMs!==s.durationMs?{...i,stats:s}:{...i,blob:new Blob([o],{type:i.blob.type}),stats:s}}var Ke=["magenta","yellow","green","blue"];var Be={magenta:"rgb(255, 72, 150)",yellow:"rgb(255, 190, 0)",green:"rgb(0, 238, 175)",blue:"rgb(25, 150, 255)",dark:"rgb(0, 0, 0)"};function ft(i){return Be[i]}var We=4,qe=4,D=i=>typeof i=="number"&&Number.isFinite(i);function O(i){if(typeof i!="object"||i===null)return!1;let e=i;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length<1||e.colours.length>8||!e.colours.every(r=>Ke.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==e.colours.length)return!1;let t=-1;for(let r of e.onsetsMs){if(!D(r)||r<0||r<=t)return!1;t=r}return!(!D(e.holdMs)||e.holdMs<=0||!D(e.endMs)||e.endMs<=t||!D(e.clipMs)||e.clipMs<e.endMs||e.clipMs>8e3)}function ye(i,e){return O(i)?Math.max(e,Math.ceil(i.clipMs)):e}function Me(i,e){let t=e.now??(()=>performance.now()),r=O(i)?i:void 0,n=[],a=null,s=null,o=null,c=!1,l=null,d=p=>{l=p;try{e.paint(p)}catch{}},u=p=>{let m=e.frames?.()??null;return m!==null&&o!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-o:p-(s??p)},f=(p,m,y=0)=>{if(c)return;let h=Math.max(0,p-u(t()));a=setTimeout(()=>{if(a=null,!c){if(y<We&&u(t())<p-qe){f(p,m,y+1);return}m()}},h)},g=p=>{if(r===void 0)return;let m=r.endMs;if(p>=r.colours.length){f(m,()=>d(null));return}let y=r.onsetsMs[p],h=p+1<r.onsetsMs.length?r.onsetsMs[p+1]:m;f(y,()=>{let b=u(t());if(b>m){l!==null&&d(null);return}let C=r.colours[p];d(C);let E=n.length===0?0:n[n.length-1].tMs;n.push({tMs:Math.max(E,Math.round(b)),colour:C});let M=y+r.holdMs;if(M<h){f(M,()=>{if(u(t())>m){l!==null&&d(null);return}d("dark"),g(p+1)});return}g(p+1)})};return{started(p){if(r===void 0||c||s!==null)return;s=p;let m=e.frames?.()??null;o=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),g(0)},stop(){c||(c=!0,a!==null&&clearTimeout(a),a=null,l!==null&&d(null))},report(){return r===void 0?void 0:{nonce:r.nonce,rendered:[...n]}}}}function Se(i,e,t=.92){return new Promise((r,n)=>{let a=i.videoWidth,s=i.videoHeight;if(!a||!s){n(new Error("video-not-ready"));return}let o=e.getContext("2d");if(!o){n(new Error("no-2d-context"));return}e.width=a,e.height=s,o.scale(-1,1),o.drawImage(i,-a,0),e.toBlob(c=>c?r(c):n(new Error("empty-keyframe")),"image/jpeg",t)})}var P=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let t=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),t()}))};t();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((t,r)=>t+r,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var ze=Object.freeze({Q_GOOD:.6,RISE_PER_S:.9,FALL_PER_S:.25,CENTER_FALLOFF_IOD_MULTIPLE:1.35,BOX_EYE_OFFSET_FACTOR:.12,IOD_BOX_PROXY_FACTOR:.42,SIZE_IDEAL_MIN:.12,SIZE_IDEAL_MAX:.3,SIZE_HARD_MIN:.08,SIZE_HARD_MAX:.45,ROLL_MAX_DEG:25,MOTION_VELOCITY_IOD_PER_S:.5,MOTION_TAU_S:.4,MOTION_DEADBAND_IOD_PER_S:.1,READY_WINDOW_MS:500,GUIDE_SIZE:.6,GUIDE_CENTERING:.6,GUIDE_POSE:.6,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,GUIDE_MOTION:.5}),_=i=>Math.min(1,Math.max(0,i)),k=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...ze,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:t,quality:r,timestampMs:n}=e,a=this.lastTickAt===null?0:Math.max(0,(n-this.lastTickAt)/1e3);this.lastTickAt=n;let s={presence:0,single:1,centering:0,size:0,pose:0,sharpness:_(r.sharpness),exposure:_(r.exposure),motion:1};if(t!==null){s.presence=1,s.single=(t.extraFaces??0)>0?0:1;let d=this.geometryOf(t,e);s.centering=d.centering,s.size=d.size,s.pose=d.pose,s.motion=this.motionOf(d.center,d.iod,n)}else this.lastCenter=null,this.velocityEma=0;let o=Math.min(s.presence,s.single,s.centering,s.size,s.pose,s.sharpness,s.exposure,s.motion);this.p=_(this.p+(o>=this.t.Q_GOOD?this.t.RISE_PER_S*o:-this.t.FALL_PER_S*(1-o))*a),this.qWindow.push({at:n,q:o}),this.qWindow=this.qWindow.filter(d=>d.at>=n-this.t.READY_WINDOW_MS);let c=this.qWindow.map(d=>d.q);if(c.length>=3){let d=Math.min(...c),u=c.indexOf(d);c=c.filter((f,g)=>g!==u)}let l=this.p>=1&&c.every(d=>d>=this.t.Q_GOOD);return{at:n,q:o,p:this.p,factors:s,guidanceKey:this.guidanceOf(s,r,o),ready:l,accepted:o>=this.t.Q_GOOD}}geometryOf(e,t){let{box:r,eyes:n}=e,a={x:t.frameWidth/2,y:t.frameHeight/2},s=Math.min(t.frameWidth,t.frameHeight),o=n!==void 0?{x:(n.left.x+n.right.x)/2,y:(n.left.y+n.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},c=n!==void 0?Math.hypot(n.right.x-n.left.x,n.right.y-n.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,l=Math.hypot(o.x-a.x,o.y-a.y),d=c<=0?0:1-_(l/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*c)),u=s>0?c/s:0;this.lastSizeDirection=u<this.t.SIZE_IDEAL_MIN?"far":u>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;u<this.t.SIZE_HARD_MIN||u>this.t.SIZE_HARD_MAX?f=0:u<this.t.SIZE_IDEAL_MIN?f=(u-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):u>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-u)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let g=1;if(n!==void 0){let p=Math.abs(Math.atan2(n.right.y-n.left.y,n.right.x-n.left.x))*180/Math.PI;g=1-_(p/this.t.ROLL_MAX_DEG)}return{center:o,iod:c,centering:d,size:f,pose:g}}motionOf(e,t,r){let n=this.lastCenter;if(this.lastCenter={...e,at:r},n===null||t<=0)return 1;let a=(r-n.at)/1e3;if(a<=0)return 1;let s=Math.hypot(e.x-n.x,e.y-n.y)/t/a;s<=this.t.MOTION_DEADBAND_IOD_PER_S&&(s=0);let o=1-Math.exp(-a/this.t.MOTION_TAU_S);return this.velocityEma=o*s+(1-o)*this.velocityEma,1-_(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,r){if(e.presence<=0)return"fcv3.no_face";if(e.single<=0)return"fcv3.one_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(t);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(r<this.t.Q_GOOD){let n=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],a=n[0];for(let s of n)e[s[0]]<e[a[0]]&&(a=s);return a[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(L[0]+L[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Xe=["single","size","centering","pose","exposure","sharpness","motion"];function Ze(i){if(i.accepted)return null;if(i.factors.presence<=0)return"no_face";let e="single";for(let t of Xe)i.factors[t]<i.factors[e]&&(e=t);return e}var w=class{constructor(){this.blocked={};this.acceptedMs=0;this.ticks=0;this.lastAt=null}record(e){let t=this.lastAt===null?0:Math.max(0,e.at-this.lastAt);this.lastAt=e.at,this.ticks+=1;let r=Ze(e);if(r===null){this.acceptedMs+=t;return}let n=this.blocked[r]??{count:0,ms:0};n.count+=1,n.ms+=t,this.blocked[r]=n}summary(){let e={};for(let[t,r]of Object.entries(this.blocked))e[t]={count:r.count,ms:Math.round(r.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var Qe=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ye=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^caméra (avant|arrière)\b/i,/^cámara (frontal|trasera|delantera)\b/i,/^câmera (frontal|traseira)\b/i,/^(front|rück)kamera\b/i,/^الكاميرا (الأمامية|الخلفية)/,/^camera2? ?\d+, facing (front|back|external)/i,/facetime/i,/\b(integrated|built-in|builtin) (web)?cam(era)?\b/i,/\b(hd )?web ?cam\b/i,/\([0-9a-f]{4}:[0-9a-f]{4}\)\s*$/i];function je(i){let e=(i??"").trim().toLowerCase();return e.length===0?"unknown":Qe.some(t=>e.includes(t))?"known_virtual":Ye.some(t=>t.test(e))?"platform":"unknown"}function Te(i){if(typeof i!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(i))}catch{return!1}}function $e(i=globalThis){return Te(i.navigator?.mediaDevices?.getUserMedia)&&Te(i.MediaStreamTrack?.prototype?.getSettings)}async function Je(i,e=globalThis){let t=e.crypto?.subtle?.digest;if(typeof t=="function")try{let r=new Uint8Array(await t.call(e.crypto?.subtle,"SHA-256",new TextEncoder().encode(i)));return Array.from(r.subarray(0,8),n=>n.toString(16).padStart(2,"0")).join("")}catch{return}}async function Ce(i,e=globalThis){let t={};try{t=typeof i.getSettings=="function"?i.getSettings()??{}:{}}catch{t={}}let r={};if((t.facingMode==="user"||t.facingMode==="environment"||t.facingMode==="left"||t.facingMode==="right")&&(r.facingMode=t.facingMode),typeof t.frameRate=="number"&&Number.isFinite(t.frameRate)&&(r.frameRate=t.frameRate),typeof t.width=="number"&&Number.isFinite(t.width)&&(r.width=t.width),typeof t.height=="number"&&Number.isFinite(t.height)&&(r.height=t.height),typeof t.deviceId=="string"&&t.deviceId.length>0){let a=await Je(t.deviceId,e);a!==void 0&&(r.deviceIdHash=a)}let n;try{n=i.label}catch{n=void 0}return{trackSettings:r,capabilitiesPresent:typeof i.getCapabilities=="function",labelClass:je(n),prototypesIntact:$e(e)}}var K=i=>Math.round(i*100)/100;function Ee(i){let e=i,t=typeof e?.requestVideoFrameCallback=="function",r=null,n=null,a=0,s=0,o=0,c=0,l=0,d=0,u=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((f,g)=>{if(r=null,!t)return;let p=g.presentationTime;if(n!==null){let m=p-n.presentationTimeMs;s+=1;let y=m-o;o+=y/s,c+=y*(m-o)}typeof g.captureTime=="number"&&Number.isFinite(g.captureTime)&&(l+=p-g.captureTime,d+=1),a+=1,n={mediaTimeMs:g.mediaTime*1e3,presentationTimeMs:p},u()}))};return u(),{latest:()=>n,stats:()=>({n:a,meanGapMs:s===0?0:K(o),stdGapMs:s<2?0:K(Math.sqrt(c/(s-1))),captureLatencyMs:d===0?null:K(l/d)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function _e(i,e,t){return{...i,rvfc:e,rampPainter:t}}var et=1e3,B="fcv3.hold_upright",tt=200,W=4,rt=600,nt=1e3,Re={sharpness:1,exposure:1,meanLuma:128};function it(i,e){return e.width=i.videoWidth,e.height=i.videoHeight,e.getContext("2d").drawImage(i,0,0),new Promise((t,r)=>e.toBlob(n=>n?t(n):r(new Error("empty-keyframe")),"image/jpeg",.92))}function at(){return X()==="phone"}var ke=class{constructor(e){this.handlers=new Map;this.stateValue="idle";this.attempt=0;this.stream=null;this.detector=null;this.scheduler=null;this.gate=null;this.profiler=null;this.lastGuidanceKey=null;this.positioningStartedAt=0;this.cameraRequestedAt=null;this.cameraReadyAt=null;this.faceAcquiredAt=null;this.captureCompleteAt=null;this.fired=!1;this.carriedDegrade=0;this.carriedMeans=[];this.blockStats=null;this.lastGateSnapshotAt=Number.NEGATIVE_INFINITY;this.uprightGuard=!1;this.trackProvenance=null;this.ramp=null;this.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>r?.delete(t)}emit(e,t){for(let r of[...this.handlers.get(e)??[]])r(t)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}restart(e){this.facing=e,this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:t}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.uprightGuard=(t.isPhone??at)(),this.setState("preflight");let r=$();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let n=t.getUserMedia??(l=>navigator.mediaDevices.getUserMedia(l)),a;this.cameraRequestedAt=this.now();try{let{facingMode:l,...d}=z(Z(),this.facing).video;a=await ie(this.facing,d,{getUserMedia:n,enumerateDevices:lt(t)})}catch(l){if(e!==this.attempt)return;if(l instanceof ne){this.fail("backcamera",{phase:"acquiring",name:R(l)});return}this.fail(ee(l),{phase:"acquiring",name:R(l)});return}if(te(a),re(a),e!==this.attempt){for(let l of a.getTracks())l.stop();return}this.stream=a;let s=a.getVideoTracks?.()[0];if(this.trackProvenance=s===void 0?null:Ce(s).catch(()=>null),this.facing=Q(a)??this.facing,t.video.srcObject=a,await t.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let l={v3AssetBaseUrl:t.v3AssetBaseUrl},d=t.createDetector??(t.createWorker!==void 0&&oe()?async()=>{try{return await le.create(t.createWorker(),l)}catch{return G(l)}}:()=>G(l)),u;try{u=await d()}catch(f){e===this.attempt&&this.fail("models",{phase:"models",name:R(f)},f instanceof ae?f.fallbackReason:ot(f));return}if(e!==this.attempt){u.destroy();return}this.detector=u,this.options.telemetry?.({type:"detector",tier:u.tier,fallbackReason:u.fallbackReason})}let o=ce(),c=t.deviceClass??ue(o);this.profiler=new de(c),this.options.telemetry?.({type:"profile",staticClass:c,activeClass:this.profiler.deviceClass,simd:o.simd}),this.gate=new k(t.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(l=>q=l,()=>{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let t=this.profiler;if(t===null)return;if(this.scheduler!==null){let n=this.scheduler.stats();this.carriedDegrade+=n.degradeCount,n.meanDetectMs>0&&this.carriedMeans.push(n.meanDetectMs),this.scheduler.stop()}let r=new P({cadenceHz:t.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=r,r.start()}async detectTick(e){let{detector:t,gate:r,profiler:n}=this,a=this.options.video;if(e!==this.attempt||t===null||r===null||n===null||this.fired||a.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let s=n.deviceClass,o=this.now(),c=this.options.makeSnapshot?.(a,n.profile.inputWidth)??this.defaultSnapshot(a,n.profile.inputWidth),l=null;try{l=await t.detect(c,a.videoWidth,a.videoHeight)}catch{l=null}if(e!==this.attempt||this.fired)return;n.record(this.now()-o),n.deviceClass!==s&&this.startScheduler(e);let d=l===null?Re:this.options.measureQuality?.(a,l.box)??this.defaultQuality(a,l.box),u=r.tick({timestampMs:this.now(),observation:l,quality:d,frameWidth:a.videoWidth,frameHeight:a.videoHeight});u.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=u.at),this.blockStats?.record(u),!u.ready&&u.at-this.lastGateSnapshotAt>=et&&(this.lastGateSnapshotAt=u.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:u.p,q:u.q,factors:u.factors,attempt:e}),u.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=u.guidanceKey,this.emit("guidance",{key:u.guidanceKey})),u.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=u.at,this.fire(e))}async fire(e){let{options:t}=this,r=this.scheduler;r?.stop(),this.reportGate(!0);let n=r?.stats()??{degradeCount:0,meanDetectMs:0},a=[...this.carriedMeans,...n.meanDetectMs>0?[n.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+n.degradeCount,meanDetectMs:a.length===0?0:a.reduce((M,v)=>M+v,0)/a.length});let s=t.mode??"clip",o=t.rankKeyframes?.()&&q?q.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(s==="photo"){let M=this.watchRotation(e,null),v=await o;if(M(),e!==this.attempt)return;if(v===null){this.fail("generic",{phase:"keyframes"});return}let x=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:v.blob,previewDataUrl:v.previewDataUrl,...x});return}this.setState("recording");let c=this.stream;if(c===null){this.fail("generic",{phase:"recording"});return}let l=t.screenRamp?.(),d=O(l),u=null;o.then(M=>{u=M},()=>{});let f=()=>{e===this.attempt&&u!==null&&this.emit("frozen",{previewDataUrl:u.previewDataUrl})},g=ye(l,U),p=null,m,y=0;try{let M=this.recordTake(e,c,l,g,void 0).then(T=>T,T=>({failed:T})),[v,x]=await Promise.all([M,o]);if(m=x,e!==this.attempt)return;if("failed"in v){if(v.failed.kind==="cliptoolarge")throw v.failed;V(v.failed.requestedMimeType??"")}else p=v,H(v.clip,g)?v.clip.stats===null&&V(v.clip.requestedMimeType??""):f();if(p===null||H(p.clip,g)){y=1,t.telemetry?.({type:"clip_retake",reason:p===null?"error":p.clip.stats===null?"unreadable":"short"});let T=null;try{T=await this.recordTake(e,c,l,g,f)}catch(Ae){if(p===null)throw Ae}if(e!==this.attempt)return;T!==null&&(p===null||be(T.clip,p.clip))&&(p=T),T===null&&f()}}catch(M){if(e!==this.attempt)return;let v=M.kind;this.fail(v==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:R(M)});return}if(p===null){this.fail("recorder",{phase:"recording"});return}let{clip:h,rvfc:b,report:C}=p;if(A(h.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(m===null){this.fail("generic",{phase:"keyframes"});return}let E=await this.provenance(b,d);e===this.attempt&&this.finishCapture({clip:h.blob,clipMimeType:h.mimeType,...h.stats?{clipStats:h.stats}:{},clipRetakes:y,keyframe:m.blob,previewDataUrl:m.previewDataUrl,...C!==void 0&&C.rendered.length>0?{screenRamp:C}:{},...E})}async recordTake(e,t,r,n,a){let s=this.options.createRecorder?.()??new I({now:()=>this.now()}),o=Ee(this.options.video),c=Me(r,{paint:u=>{(u===null||e===this.attempt)&&this.emit("ramp",{colour:u})},now:()=>this.now(),frames:o.latest});this.ramp=c;let l=()=>{o.stop(),c.stop(),this.ramp===c&&(this.ramp=null)},d=this.watchRotation(e,s);try{return{clip:await s.record(t,a,()=>c.started(this.now()),n,o),rvfc:o.stats(),report:c.report()}}finally{d(),l()}}async provenance(e,t){let r=this.trackProvenance;if(r===null)return{};let n,a=new Promise(o=>{n=setTimeout(()=>o(null),nt)}),s=await Promise.race([r,a]);return clearTimeout(n),s===null?{}:{provenance:_e(s,e,t)}}isLandscape(){let e=this.options.video;return this.uprightGuard&&e.videoWidth>e.videoHeight}holdUpright(e){this.gate?.reset(),this.emit("checks",{engine:"v3",progress:0,q:0,factors:{presence:0,single:1,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==B&&(this.lastGuidanceKey=B,this.emit("guidance",{key:B}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,n=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){o();return}r.videoWidth>0&&this.isLandscape()&&(o(),this.abortRecording(e,t))},a=setInterval(n,tt);r.addEventListener?.("resize",n);let s=!1;function o(){s||(s=!0,clearInterval(a),r.removeEventListener?.("resize",n))}return o}abortRecording(e,t){if(e!==this.attempt)return;this.attempt+=1;let r=this.attempt;try{t?.stop()}catch{}this.ramp?.stop(),this.ramp=null,this.fired=!1,this.captureCompleteAt=null,this.gate=new k(this.options.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),this.lastGuidanceKey=null,this.setState("positioning"),this.positioningStartedAt=this.now(),this.holdUpright(r),this.startScheduler(r)}async collectKeyframes(e){let t=this.options.captureKeyframe??(a=>this.defaultKeyframe(a)),r=rt/(W-1),n=null;for(let a=0;a<W;a+=1){if(e!==this.attempt)return n;try{let s=await t(this.options.video);(n===null||s.sharpness>n.sharpness)&&(n=s)}catch{}a<W-1&&await st(r)}return n}finishCapture(e){this.stopTracks(),this.setState("captured");let t=this.captureTiming();this.emit("artifacts",t===void 0?e:{...e,timing:t})}captureTiming(){let e={},t=(r,n,a)=>{n!==null&&a!==null&&(e[r]=Math.max(0,Math.round(a-n)))};return t("cameraReadyMs",this.cameraRequestedAt,this.cameraReadyAt),t("faceAcquireMs",this.cameraReadyAt,this.faceAcquiredAt),t("captureMs",this.faceAcquiredAt,this.captureCompleteAt),Object.keys(e).length>0?e:void 0}async defaultKeyframe(e){let t=document.createElement("canvas"),r=await(this.facing==="user"?Se:it)(e,t),n=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:n,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),n=t/Math.max(1,e.videoWidth),a=Math.max(1,Math.round(e.videoWidth*n)),s=Math.max(1,Math.round(e.videoHeight*n)),o=r.getContext("2d");return o===null?e:(r.width!==a&&(r.width=a),r.height!==s&&(r.height=s),o.drawImage(e,0,0,a,s),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,t){let r=we(e,t,96);return r===null?Re:{sharpness:F(r),exposure:me(r),meanLuma:pe(r)}}centerSharpness(e){let t=se(e),r=we(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:F(r)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.ramp?.stop(),this.ramp=null,this.stopTracks()}reportGate(e){let t=this.blockStats,r=this.profiler;if(t===null||r===null)return;let n=t.summary();e&&(this.blockStats=null),n.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...n})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t,r){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:r});let{phase:n,name:a}=t;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:a===void 0?{phase:n}:{phase:n,name:a}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},q;function st(i){return new Promise(e=>setTimeout(e,i))}function ot(i){return i instanceof Error?i.message:String(i)}function we(i,e,t){try{let r=document.createElement("canvas"),n=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*n)),r.height=Math.max(1,Math.round(e.height*n));let a=r.getContext("2d");return a===null?null:(a.drawImage(i,e.x,e.y,e.width,e.height,0,0,r.width,r.height),a.getImageData(0,0,r.width,r.height))}catch{return null}}function lt(i){if(i.enumerateDevices!==void 0)return i.enumerateDevices;if(i.getUserMedia===void 0&&!(typeof navigator>"u"||typeof navigator.mediaDevices?.enumerateDevices!="function"))return()=>navigator.mediaDevices.enumerateDevices()}export{ut as a,U as b,Pe as c,xe as d,ve as e,Ge as f,Le as g,Fe as h,Ve as i,S as j,Ue as k,H as l,be as m,I as n,Ke as o,ft as p,Se as q,P as r,ze as s,k as t,Ze as u,w as v,et as w,B as x,tt as y,W as z,rt as A,nt as B,ke as C};
@@ -1 +1 @@
1
- import{a as Y,d as ee,e as O,f as te,g as ne}from"./chunk-7QZWBDI5.js";import{C as X,a as j}from"./chunk-ZCOWTM46.js";import{f as Q,l as Z}from"./chunk-CPUECYAJ.js";import{c as $}from"./chunk-TSA6GHUG.js";import{c as J,h as C}from"./chunk-FSSMUAKC.js";var ue=12e4,re=13e4,le=3e3,fe=1200,P=Symbol.for("@sekyro/web.preload.v1");function g(){let e=globalThis;return e[P]??(e[P]=new Map),e[P]}function S(e){let n=(e??J).replace(/\/+$/,"");return n===""?"/":n}function se(e){let n=g(),r=n.get(e);return r===void 0&&(r={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},n.set(e,r)),r}function A(e,n){if(e.status!==n){e.status=n;for(let r of[...e.listeners])r(n)}}var x=e=>C({preferred:["blaze"],v3AssetBaseUrl:e,blazeInitTimeoutMs:ue}),F=x;function Pe(e){F=e??x}function Ae(){for(let e of g().values())e.detector?.destroy();g().clear(),F=x}function pe(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function me(){return navigator.connection?.saveData===!0}function ve(e){let n=window;if(typeof n.requestIdleCallback=="function"){let s=n.requestIdleCallback(e,{timeout:le});return()=>n.cancelIdleCallback?.(s)}let r=setTimeout(e,fe);return()=>clearTimeout(r)}function ge(e,n){let r,s=new Promise(i=>{r=i}),m=!1,d=()=>{},u={promise:s,settle:i=>{m||(m=!0,d(),e.scheduled===u&&(e.scheduled=null),r(i))}};return e.scheduled=u,d=ve(()=>{m||u.settle(I(e,n))}),s}function I(e,n){if((e.status==="loading"||e.status==="ready")&&e.promise!==null)return e.promise;A(e,"loading");let r=new Promise(i=>i(F(n)));e.detectorPromise=r;let s,m=new Promise((i,f)=>{s=setTimeout(()=>{r.then(h=>h.destroy(),()=>{}),f(new Error(`detector preload exceeded ${re} ms`))},re)}),u=Promise.race([r,m]).then(i=>e.detectorPromise!==r?(i.destroy(),e.status):(e.detector=i,A(e,"ready"),"ready"),i=>(e.detectorPromise===r&&(e.detectorPromise=null,e.detector=null,A(e,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",i)),e.status)).finally(()=>clearTimeout(s));return e.promise=u,e.scheduled?.settle(u),u}function we(e={}){if(!pe())return Promise.resolve("idle");let n=S(e.assetBaseUrl),r=se(n);return e.respectSaveData===!0&&me()?Promise.resolve(r.status):(r.status==="loading"||r.status==="ready")&&r.promise!==null?r.promise:e.idle===!0?r.scheduled?.promise??ge(r,n):I(r,n)}function ke(e){return g().get(S(e))?.status??"idle"}function De(e,n){let r=se(S(n));return r.listeners.add(e),()=>{r.listeners.delete(e)}}function _e(e){let n=g().get(S(e));n!==void 0&&(n.scheduled?.settle("idle"),n.detector?.destroy(),n.detector=null,n.detectorPromise=null,n.promise=null,A(n,"idle"))}function he(e){return{get tier(){return e.tier},get fallbackReason(){return e.fallbackReason},detect:(...n)=>e.detect(...n),destroy:()=>{}}}function oe(e){let n=S(e),r=g().get(n);if(!(r===void 0||r.detector===null&&r.detectorPromise===null&&r.scheduled===null))return async()=>{r.scheduled!==null&&I(r,n);let s=r.promise;for(;r.detector===null&&s!==null&&(await s,r.promise!==s);)s=r.promise;return r.detector!==null?he(r.detector):C({v3AssetBaseUrl:n})}}function Ce(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 Se(e){switch(e){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";default:return e}}function ie(e){switch(e){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return e;case"backcamera":return"notfound";default:{let n=e;return"generic"}}}function Le(e,n,r){if(r===void 0)return{kind:ie(e),retryable:n};let s=Z(r.name);return{kind:ie(e),retryable:n,detail:{...s!==void 0?{name:s}:{},phase:r.phase,engineKind:e}}}var ye=new Set(["captured","uploading","checking"]);function Ee(e,n={},r,s=()=>"self",m=()=>{},d){let u=n.now??(()=>performance.now()),i=n.canChooseFacing??ee,f="user",h=te(),p=s(),l=Y(),B=!Q(),H=n.engineOptions,ae=H?.createDetector===void 0&&H?.createWorker===void 0?{createDetector:()=>{let t=oe(e.assetBaseUrl);return t!==void 0?t():C({v3AssetBaseUrl:e.assetBaseUrl})}}:{},U={video:e.video,mode:B?"photo":"clip",rankKeyframes:r,facingMode:void 0,v3AssetBaseUrl:e.assetBaseUrl,screenRamp:()=>p==="self"&&l.count("ramp")>0?m():void 0,...n.engineOptions??{},...ae},o=n.createEngine?.(U)??new X(U),v="idle",L=null,y=0,w=!1,k="full",E=null,b=null,D=0,_=0,K=()=>{e.video.videoWidth>0&&e.video.videoHeight>0&&(D=e.video.videoWidth,_=e.video.videoHeight)},V=ne({enabled:e.keepScreenAwake!==!1}),M=t=>{v=t,V.setActive(t==="starting"||t==="gating"||t==="recording"),l.emit("state",t)},R=()=>l.emit("gate",{progress:y,hint:L,faceDetected:w}),G=()=>{let t=o.animations??"full";t!==k&&(k=t,l.emit("profile",{animations:k}))},de=[o.on("statechange",({state:t})=>{let a=Se(t);a==="starting"&&v!=="starting"&&(L=null,y=0,w=!1,E=null,b=null,D=0,_=0),M(a),G(),a==="recording"&&(K(),E=u(),L="hold",y=1,R())}),o.on("checks",t=>{K(),y=t.progress,w=t.factors.presence>0,R(),G()}),o.on("guidance",({key:t})=>{L=Ce(t),R()}),o.on("frozen",({previewDataUrl:t})=>{b=u(),l.emit("frozen",{previewDataUrl:t})}),o.on("ramp",t=>l.emit("ramp",t)),o.on("artifacts",t=>{if(v!=="captured")return;let a=$(),c=t.clipStats,q=c!==void 0?Math.round(c.durationMs):E!==null&&b!==null?Math.max(0,Math.round(b-E)):void 0,N=c!==void 0&&c.frames>1&&c.durationMs>0?Math.round(c.frames*1e4/c.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||D,height:e.video.videoHeight||_,...q!==void 0?{clipMs:q}:{},...c!==void 0?{clipFrames:c.frames}:{},...N!==void 0?{fps:N}:{},...t.clipRetakes!==void 0?{clipRetakes:t.clipRetakes}:{},...t.clipMimeType!==void 0?{codec:j(t.clipMimeType)}:{},captureChannel:a==="desktop"?"desktop":"mobile",formFactor:a,...B?{degraded:"NO_RECORDER"}:{},engine:"v3",facingMode:o.facingMode,mode:p,...t.timing,...t.screenRamp!==void 0?{screenRamp:t.screenRamp}:{},...t.provenance!==void 0?{provenance:t.provenance}:{}})}),o.on("error",({kind:t,retryable:a,detail:c})=>{t==="backcamera"&&ce()||l.emit("error",Le(t,a,c))})],z=!1;function ce(){return T||z||p!=="assisted"||d===void 0||d.session()!=="choice"?!1:(z=!0,d.onModeChange("self"),p="self",f=O("self"),M("mode_switch"),o.restart(f),!0)}let W=async()=>d!==void 0&&d.session()==="choice"&&await i().catch(()=>!1),T=!1;return{handle:{get state(){return v},get captureMode(){return s()},get facingMode(){return o.facingMode??f},on:(t,a)=>l.on(t,a),start:t=>(p=s(),h.facing(p,e.facing),f=h.facing(p,t?.facing),o.start({facingMode:f})),retry:()=>o.retry(),switchCamera:()=>h.refuseSwitch(s()),canSwitchCaptureMode:W,setCaptureMode:async t=>{if(t===s()||!await W()||T||ye.has(v)||d===void 0)return!1;d.onModeChange(t),p=t;let a=O(t);return f=a,v==="idle"||(M("mode_switch"),o.restart(a)),!0},destroy:()=>{T=!0;for(let t of de)t();V.setActive(!1),o.destroy(),l.clear()}},setFlowState:t=>{v!==t&&M(t)}}}function ze(e){return Ee(e).handle}export{ue as a,re as b,Pe as c,Ae as d,we as e,ke as f,De as g,_e as h,oe as i,Ce as j,Se as k,ie as l,Le as m,Ee as n,ze as o};
1
+ import{a as Y,d as ee,e as O,f as te,g as ne}from"./chunk-7QZWBDI5.js";import{C as X,a as j}from"./chunk-MOOWUPOZ.js";import{f as Q,l as Z}from"./chunk-CPUECYAJ.js";import{c as $}from"./chunk-TSA6GHUG.js";import{c as J,h as C}from"./chunk-FSSMUAKC.js";var ue=12e4,re=13e4,le=3e3,fe=1200,P=Symbol.for("@sekyro/web.preload.v1");function g(){let e=globalThis;return e[P]??(e[P]=new Map),e[P]}function S(e){let n=(e??J).replace(/\/+$/,"");return n===""?"/":n}function se(e){let n=g(),r=n.get(e);return r===void 0&&(r={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},n.set(e,r)),r}function A(e,n){if(e.status!==n){e.status=n;for(let r of[...e.listeners])r(n)}}var x=e=>C({preferred:["blaze"],v3AssetBaseUrl:e,blazeInitTimeoutMs:ue}),F=x;function Pe(e){F=e??x}function Ae(){for(let e of g().values())e.detector?.destroy();g().clear(),F=x}function pe(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function me(){return navigator.connection?.saveData===!0}function ve(e){let n=window;if(typeof n.requestIdleCallback=="function"){let s=n.requestIdleCallback(e,{timeout:le});return()=>n.cancelIdleCallback?.(s)}let r=setTimeout(e,fe);return()=>clearTimeout(r)}function ge(e,n){let r,s=new Promise(i=>{r=i}),m=!1,d=()=>{},u={promise:s,settle:i=>{m||(m=!0,d(),e.scheduled===u&&(e.scheduled=null),r(i))}};return e.scheduled=u,d=ve(()=>{m||u.settle(I(e,n))}),s}function I(e,n){if((e.status==="loading"||e.status==="ready")&&e.promise!==null)return e.promise;A(e,"loading");let r=new Promise(i=>i(F(n)));e.detectorPromise=r;let s,m=new Promise((i,f)=>{s=setTimeout(()=>{r.then(h=>h.destroy(),()=>{}),f(new Error(`detector preload exceeded ${re} ms`))},re)}),u=Promise.race([r,m]).then(i=>e.detectorPromise!==r?(i.destroy(),e.status):(e.detector=i,A(e,"ready"),"ready"),i=>(e.detectorPromise===r&&(e.detectorPromise=null,e.detector=null,A(e,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",i)),e.status)).finally(()=>clearTimeout(s));return e.promise=u,e.scheduled?.settle(u),u}function we(e={}){if(!pe())return Promise.resolve("idle");let n=S(e.assetBaseUrl),r=se(n);return e.respectSaveData===!0&&me()?Promise.resolve(r.status):(r.status==="loading"||r.status==="ready")&&r.promise!==null?r.promise:e.idle===!0?r.scheduled?.promise??ge(r,n):I(r,n)}function ke(e){return g().get(S(e))?.status??"idle"}function De(e,n){let r=se(S(n));return r.listeners.add(e),()=>{r.listeners.delete(e)}}function _e(e){let n=g().get(S(e));n!==void 0&&(n.scheduled?.settle("idle"),n.detector?.destroy(),n.detector=null,n.detectorPromise=null,n.promise=null,A(n,"idle"))}function he(e){return{get tier(){return e.tier},get fallbackReason(){return e.fallbackReason},detect:(...n)=>e.detect(...n),destroy:()=>{}}}function oe(e){let n=S(e),r=g().get(n);if(!(r===void 0||r.detector===null&&r.detectorPromise===null&&r.scheduled===null))return async()=>{r.scheduled!==null&&I(r,n);let s=r.promise;for(;r.detector===null&&s!==null&&(await s,r.promise!==s);)s=r.promise;return r.detector!==null?he(r.detector):C({v3AssetBaseUrl:n})}}function Ce(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 Se(e){switch(e){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";default:return e}}function ie(e){switch(e){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return e;case"backcamera":return"notfound";default:{let n=e;return"generic"}}}function Le(e,n,r){if(r===void 0)return{kind:ie(e),retryable:n};let s=Z(r.name);return{kind:ie(e),retryable:n,detail:{...s!==void 0?{name:s}:{},phase:r.phase,engineKind:e}}}var ye=new Set(["captured","uploading","checking"]);function Ee(e,n={},r,s=()=>"self",m=()=>{},d){let u=n.now??(()=>performance.now()),i=n.canChooseFacing??ee,f="user",h=te(),p=s(),l=Y(),B=!Q(),H=n.engineOptions,ae=H?.createDetector===void 0&&H?.createWorker===void 0?{createDetector:()=>{let t=oe(e.assetBaseUrl);return t!==void 0?t():C({v3AssetBaseUrl:e.assetBaseUrl})}}:{},U={video:e.video,mode:B?"photo":"clip",rankKeyframes:r,facingMode:void 0,v3AssetBaseUrl:e.assetBaseUrl,screenRamp:()=>p==="self"&&l.count("ramp")>0?m():void 0,...n.engineOptions??{},...ae},o=n.createEngine?.(U)??new X(U),v="idle",L=null,y=0,w=!1,k="full",E=null,b=null,D=0,_=0,K=()=>{e.video.videoWidth>0&&e.video.videoHeight>0&&(D=e.video.videoWidth,_=e.video.videoHeight)},V=ne({enabled:e.keepScreenAwake!==!1}),M=t=>{v=t,V.setActive(t==="starting"||t==="gating"||t==="recording"),l.emit("state",t)},R=()=>l.emit("gate",{progress:y,hint:L,faceDetected:w}),G=()=>{let t=o.animations??"full";t!==k&&(k=t,l.emit("profile",{animations:k}))},de=[o.on("statechange",({state:t})=>{let a=Se(t);a==="starting"&&v!=="starting"&&(L=null,y=0,w=!1,E=null,b=null,D=0,_=0),M(a),G(),a==="recording"&&(K(),E=u(),L="hold",y=1,R())}),o.on("checks",t=>{K(),y=t.progress,w=t.factors.presence>0,R(),G()}),o.on("guidance",({key:t})=>{L=Ce(t),R()}),o.on("frozen",({previewDataUrl:t})=>{b=u(),l.emit("frozen",{previewDataUrl:t})}),o.on("ramp",t=>l.emit("ramp",t)),o.on("artifacts",t=>{if(v!=="captured")return;let a=$(),c=t.clipStats,q=c!==void 0?Math.round(c.durationMs):E!==null&&b!==null?Math.max(0,Math.round(b-E)):void 0,N=c!==void 0&&c.frames>1&&c.durationMs>0?Math.round(c.frames*1e4/c.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||D,height:e.video.videoHeight||_,...q!==void 0?{clipMs:q}:{},...c!==void 0?{clipFrames:c.frames}:{},...N!==void 0?{fps:N}:{},...t.clipRetakes!==void 0?{clipRetakes:t.clipRetakes}:{},...t.clipMimeType!==void 0?{codec:j(t.clipMimeType)}:{},captureChannel:a==="desktop"?"desktop":"mobile",formFactor:a,...B?{degraded:"NO_RECORDER"}:{},engine:"v3",facingMode:o.facingMode,mode:p,...t.timing,...t.screenRamp!==void 0?{screenRamp:t.screenRamp}:{},...t.provenance!==void 0?{provenance:t.provenance}:{}})}),o.on("error",({kind:t,retryable:a,detail:c})=>{t==="backcamera"&&ce()||l.emit("error",Le(t,a,c))})],z=!1;function ce(){return T||z||p!=="assisted"||d===void 0||d.session()!=="choice"?!1:(z=!0,d.onModeChange("self"),p="self",f=O("self"),M("mode_switch"),o.restart(f),!0)}let W=async()=>d!==void 0&&d.session()==="choice"&&await i().catch(()=>!1),T=!1;return{handle:{get state(){return v},get captureMode(){return s()},get facingMode(){return o.facingMode??f},on:(t,a)=>l.on(t,a),start:t=>(p=s(),h.facing(p,e.facing),f=h.facing(p,t?.facing),o.start({facingMode:f})),retry:()=>o.retry(),switchCamera:()=>h.refuseSwitch(s()),canSwitchCaptureMode:W,setCaptureMode:async t=>{if(t===s()||!await W()||T||ye.has(v)||d===void 0)return!1;d.onModeChange(t),p=t;let a=O(t);return f=a,v==="idle"||(M("mode_switch"),o.restart(a)),!0},destroy:()=>{T=!0;for(let t of de)t();V.setActive(!1),o.destroy(),l.clear()}},setFlowState:t=>{v!==t&&M(t)}}}function ze(e){return Ee(e).handle}export{ue as a,re as b,Pe as c,Ae as d,we as e,ke as f,De as g,_e as h,oe as i,Ce as j,Se as k,ie as l,Le as m,Ee as n,ze as o};