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

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 (60) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/{capture-session-doc-6MUKGUJ3.js → capture-session-doc-MGDYUASI.js} +1 -1
  3. package/dist/{capture-session-v3-BdpUe0ht.d.cts → capture-session-v3-Dz-AQW52.d.cts} +1 -1
  4. package/dist/{capture-session-v3-Q4otwuve.d.ts → capture-session-v3-Z2KI_2p9.d.ts} +1 -1
  5. package/dist/chunk-5AR5GTEJ.js +1 -0
  6. package/dist/{chunk-DTQTSZAX.js → chunk-C4XDRRU5.js} +1 -1
  7. package/dist/{chunk-KORZGQLS.js → chunk-COZXZAD5.js} +1 -1
  8. package/dist/chunk-IAKYKPL6.js +1 -0
  9. package/dist/chunk-IOCOIZKE.js +3 -0
  10. package/dist/chunk-MQHTFHSN.js +1 -0
  11. package/dist/chunk-PBWIMNSN.js +1 -0
  12. package/dist/{chunk-7GUHA2NM.js → chunk-QTOMWAS6.js} +1 -1
  13. package/dist/{chunk-LTGRPMMY.js → chunk-TOISWBOX.js} +1 -1
  14. package/dist/chunk-TQQK7464.js +1 -0
  15. package/dist/chunk-U5TL63CG.js +1 -0
  16. package/dist/chunk-VMHFHHPP.js +1 -0
  17. package/dist/{chunk-ISMVEF7H.js → chunk-WNBEOK5Q.js} +1 -1
  18. package/dist/chunk-XDB7L5KS.js +1 -0
  19. package/dist/client/index.cjs +1 -1
  20. package/dist/client/index.d.cts +3 -3
  21. package/dist/client/index.d.ts +3 -3
  22. package/dist/client/index.js +1 -1
  23. package/dist/core/index.cjs +1 -1
  24. package/dist/core/index.d.cts +3 -3
  25. package/dist/core/index.d.ts +3 -3
  26. package/dist/core/index.js +1 -1
  27. package/dist/core/ocr/worker.bundle.js +12 -12
  28. package/dist/core/ocr/worker.cjs +12 -12
  29. package/dist/core/ocr/worker.js +9 -9
  30. package/dist/create-document-capture-KISF6XD3.js +1 -0
  31. package/dist/{create-verification-CCCvsDdp.d.ts → create-verification-2Qm_K28Y.d.ts} +5 -4
  32. package/dist/{create-verification-BJGWTzCS.d.cts → create-verification-BG6A2iyO.d.cts} +5 -4
  33. package/dist/{detector-scanic-LYXXX77M.js → detector-scanic-JC25DD3A.js} +1 -1
  34. package/dist/{icao-gate-C2B9Yyz0.d.cts → icao-gate-Dyb0wGO3.d.cts} +8 -1
  35. package/dist/{icao-gate-toRhhMow.d.ts → icao-gate-QqtNED0V.d.ts} +8 -1
  36. package/dist/{icao-policy-xp26r3lv.d.ts → icao-policy-DsaRylAQ.d.ts} +2 -2
  37. package/dist/{icao-policy-CFoaL76l.d.cts → icao-policy-iIBtqhbf.d.cts} +2 -2
  38. package/dist/index.cjs +2 -2
  39. package/dist/index.d.cts +7 -7
  40. package/dist/index.d.ts +7 -7
  41. package/dist/index.js +1 -1
  42. package/dist/internal/index.cjs +3 -3
  43. package/dist/internal/index.d.cts +6 -6
  44. package/dist/internal/index.d.ts +6 -6
  45. package/dist/internal/index.js +1 -1
  46. package/dist/plan-runner-NWK4LZFI.js +1 -0
  47. package/dist/{types-BUvxjU5V.d.cts → types-Cy_SJtPf.d.cts} +30 -3
  48. package/dist/{types-BUvxjU5V.d.ts → types-Cy_SJtPf.d.ts} +30 -3
  49. package/package.json +1 -1
  50. package/sbom.cdx.json +19 -19
  51. package/dist/chunk-2DBOZDYR.js +0 -1
  52. package/dist/chunk-5QUJHFOH.js +0 -1
  53. package/dist/chunk-AYWS6XTB.js +0 -1
  54. package/dist/chunk-EP6FVAR4.js +0 -3
  55. package/dist/chunk-GVAN773O.js +0 -1
  56. package/dist/chunk-JULJQOVT.js +0 -1
  57. package/dist/chunk-PW2HWXBJ.js +0 -1
  58. package/dist/chunk-QPO6LOYB.js +0 -1
  59. package/dist/create-document-capture-EK7EDLTD.js +0 -1
  60. package/dist/plan-runner-7XZH4SBZ.js +0 -1
@@ -1 +0,0 @@
1
- import{a as se,b as oe}from"./chunk-SX7TUC3V.js";import{b as re,c as ne}from"./chunk-W357WDNU.js";import{b as pe,c as me,d as he}from"./chunk-POIQGEZM.js";import{a as j,c as $,e as J,g as ee,h as I,k,m as te,n as ae}from"./chunk-CPUECYAJ.js";import{b as F,c as fe,d as V,e as ve}from"./chunk-FPXL63KZ.js";import{a as X,c as Z,d as Q,e as Y}from"./chunk-TSA6GHUG.js";import{d as ie}from"./chunk-KORZGQLS.js";import{e as le,f as ce,h as L,j as ue,l as de}from"./chunk-FSSMUAKC.js";var Pe=[...j.filter(i=>i.startsWith("video/mp4")),"video/webm;codecs=h264","video/webm;codecs=avc1","video/webm;codecs=vp8","video/webm;codecs=vp9","video/webm"],ge=new Set;function xe(i){let e=/(?:Chrome|Chromium)\/(\d+)\./.exec(i??"");return e?Number(e[1]):null}function be(i=Ge(),e=globalThis.navigator?.userAgent){if(i===void 0)return"";let t=xe(e)===126;for(let r of Pe)if(!(ge.has(r)||t&&r.startsWith("video/mp4")))try{if(i(r))return r}catch{}return""}function N(i){i!==""&&ge.add(i)}function ye(i){return i.replace(/^video\/x-matroska/i,"video/webm")}function mt(i){let e=/codecs=["']?([^,;"']+)/i.exec(i);return e?e[1].trim():i.split(";")[0].trim()}function Ge(){let i=globalThis.MediaRecorder;return i&&typeof i.isTypeSupported=="function"?e=>i.isTypeSupported(e):void 0}var H=2500,Le=1e3,Fe=1500,Me=25e5,Ve=100,Ne=700,Ue=20,He=1500,U=null;function Ke(){return U??(U=import("./clip-inspect-DLJXVKV6.js").catch(i=>{throw U=null,i})),U.catch(()=>null)}var S=class extends Error{constructor(e,t){super(t??e),this.kind=e}},Be=100;function K(i,e){return i.stats===void 0?!1:i.stats===null?!0:i.stats.durationMs<e-Be}function Se(i,e){return i.stats?e.stats?i.stats.durationMs>e.stats.durationMs:!0:!1}var D=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=H,a){let s=be(),l=Ke();return this.recordRaw(e,t,r,n,a,s).then(c=>We(c,l),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((l,c)=>{let o;try{o=new MediaRecorder(e,s?{mimeType:s,videoBitsPerSecond:Me}:{videoBitsPerSecond:Me})}catch{try{o=new MediaRecorder(e)}catch{c(new S("unsupported"));return}}this.recorder=o;let d=f=>{this.settled||(this.settled=!0,this.clearTimers(),f())},u=()=>d(()=>{let f=ye(o.mimeType||s||$),b=new Blob(this.chunks,{type:f});if(b.size===0){c(new S("generic","empty clip"));return}if(I(b)){c(new S("cliptoolarge"));return}l({blob:b,mimeType:f,requestedMimeType:s})});o.ondataavailable=f=>{f.data&&f.data.size&&(this.chunks.push(f.data),this.bytes+=f.data.size,this.bytes>ee&&d(()=>{try{o.state!=="inactive"&&o.stop()}catch{}c(new S("cliptoolarge"))}))},o.onstop=u,o.onerror=()=>d(()=>c(new S("generic")));let h=this.now();if(r!==void 0||a!==void 0){let f=!1;o.onstart=()=>{if(!(f||this.settled)&&(f=!0,h=this.now(),r!==void 0))try{r()}catch{}}}try{o.start(Le)}catch{d(()=>c(new S("generic")));return}let v=()=>{if(this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=null,this.settled||t?.(),o.state!=="inactive"){try{o.stop()}catch{u()}this.graceTimer=setTimeout(u,Fe)}else u()},p=this.now();if(a===void 0){this.hardStopTimer=setTimeout(v,n);return}let m=null,y=!1;this.hardStopTimer=setTimeout(v,n+Ne),this.pollTimer=setInterval(()=>{if(this.settled||y)return;let f=null;try{f=a.latest()}catch{f=null}let b=f?.presentationTimeMs;b!==void 0&&Number.isFinite(b)&&b>=h&&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){v();return}this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=setTimeout(v,Ve)}},Ue)}))}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 We(i,e){let t,r=new Promise(o=>{t=setTimeout(()=>o(null),He)}),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 l=n.withWebmDuration(a,s.durationMs);if(l===null)return{...i,stats:s};let c=n.inspectClipBytes(l);return c===null||c.frames!==s.frames||c.durationMs!==s.durationMs?{...i,stats:s}:{...i,blob:new Blob([l],{type:i.blob.type}),stats:s}}var qe=["magenta","yellow","green","blue"];var ze={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 bt(i){return ze[i]}var Xe=4,Ze=4,O=i=>typeof i=="number"&&Number.isFinite(i);function P(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=>qe.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==e.colours.length)return!1;let t=-1;for(let r of e.onsetsMs){if(!O(r)||r<0||r<=t)return!1;t=r}return!(!O(e.holdMs)||e.holdMs<=0||!O(e.endMs)||e.endMs<=t||!O(e.clipMs)||e.clipMs<e.endMs||e.clipMs>8e3)}function Te(i,e){return P(i)?Math.max(e,Math.ceil(i.clipMs)):e}function Ce(i,e){let t=e.now??(()=>performance.now()),r=P(i)?i:void 0,n=[],a=null,s=null,l=null,c=!1,o=null,d=p=>{o=p;try{e.paint(p)}catch{}},u=p=>{let m=e.frames?.()??null;return m!==null&&l!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-l:p-(s??p)},h=(p,m,y=0)=>{if(c)return;let f=Math.max(0,p-u(t()));a=setTimeout(()=>{if(a=null,!c){if(y<Xe&&u(t())<p-Ze){h(p,m,y+1);return}m()}},f)},v=p=>{if(r===void 0)return;let m=r.endMs;if(p>=r.colours.length){h(m,()=>d(null));return}let y=r.onsetsMs[p],f=p+1<r.onsetsMs.length?r.onsetsMs[p+1]:m;h(y,()=>{let b=u(t());if(b>m){o!==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 A=y+r.holdMs;if(A<f){h(A,()=>{if(u(t())>m){o!==null&&d(null);return}d("dark"),v(p+1)});return}v(p+1)})};return{started(p){if(r===void 0||c||s!==null)return;s=p;let m=e.frames?.()??null;l=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),v(0)},stop(){c||(c=!0,a!==null&&clearTimeout(a),a=null,o!==null&&d(null))},report(){return r===void 0?void 0:{nonce:r.nonce,rendered:[...n]}}}}function Ee(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 l=e.getContext("2d");if(!l){n(new Error("no-2d-context"));return}e.width=a,e.height=s,l.scale(-1,1),l.drawImage(i,-a,0),e.toBlob(c=>c?r(c):n(new Error("empty-keyframe")),"image/jpeg",t)})}var x=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 Qe=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)),R=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...Qe,...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 l=Math.min(s.presence,s.single,s.centering,s.size,s.pose,s.sharpness,s.exposure,s.motion);this.p=_(this.p+(l>=this.t.Q_GOOD?this.t.RISE_PER_S*l:-this.t.FALL_PER_S*(1-l))*a),this.qWindow.push({at:n,q:l}),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((h,v)=>v!==u)}let o=this.p>=1&&c.every(d=>d>=this.t.Q_GOOD);return{at:n,q:l,p:this.p,factors:s,guidanceKey:this.guidanceOf(s,r,l),ready:o,accepted:l>=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),l=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,o=Math.hypot(l.x-a.x,l.y-a.y),d=c<=0?0:1-_(o/(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 h;u<this.t.SIZE_HARD_MIN||u>this.t.SIZE_HARD_MAX?h=0:u<this.t.SIZE_IDEAL_MIN?h=(u-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):u>this.t.SIZE_IDEAL_MAX?h=(this.t.SIZE_HARD_MAX-u)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):h=1;let v=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;v=1-_(p/this.t.ROLL_MAX_DEG)}return{center:l,iod:c,centering:d,size:h,pose:v}}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 l=1-Math.exp(-a/this.t.MOTION_TAU_S);return this.velocityEma=l*s+(1-l)*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=(F[0]+F[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Ye=["single","size","centering","pose","exposure","sharpness","motion"];function je(i){if(i.accepted)return null;if(i.factors.presence<=0)return"no_face";let e="single";for(let t of Ye)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=je(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 $e=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo","fake_device","fake-capture-device"],Je=[/^(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 et(i){let e=(i??"").trim().toLowerCase();return e.length===0?"unknown":$e.some(t=>e.includes(t))?"known_virtual":Je.some(t=>t.test(e))?"platform":"unknown"}function _e(i){if(typeof i!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(i))}catch{return!1}}function tt(i=globalThis){return _e(i.navigator?.mediaDevices?.getUserMedia)&&_e(i.MediaStreamTrack?.prototype?.getSettings)}async function rt(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 ke(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 rt(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:et(n),prototypesIntact:tt(e)}}var B=i=>Math.round(i*100)/100;function Re(i){let e=i,t=typeof e?.requestVideoFrameCallback=="function",r=null,n=null,a=0,s=0,l=0,c=0,o=0,d=0,u=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((h,v)=>{if(r=null,!t)return;let p=v.presentationTime;if(n!==null){let m=p-n.presentationTimeMs;s+=1;let y=m-l;l+=y/s,c+=y*(m-l)}typeof v.captureTime=="number"&&Number.isFinite(v.captureTime)&&(o+=p-v.captureTime,d+=1),a+=1,n={mediaTimeMs:v.mediaTime*1e3,presentationTimeMs:p},u()}))};return u(),{latest:()=>n,stats:()=>({n:a,meanGapMs:s===0?0:B(l),stdGapMs:s<2?0:B(Math.sqrt(c/(s-1))),captureLatencyMs:d===0?null:B(o/d)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function we(i,e,t){return{...i,rvfc:e,rampPainter:t}}var nt=1e3,W="fcv3.hold_upright",it=200,q=4,at=600,st=1e3,Ae={sharpness:1,exposure:1,meanLuma:128};function ot(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 lt(){return Z()==="phone"}var Ie=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.openEnvironment=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??lt)(),this.setState("preflight");let r=J();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let n=t.getUserMedia??(o=>navigator.mediaDevices.getUserMedia(o)),a;this.cameraRequestedAt=this.now();try{let{facingMode:o,...d}=X(Q(),this.facing).video;a=await oe(this.facing,d,{getUserMedia:n,enumerateDevices:dt(t)})}catch(o){if(e!==this.attempt)return;if(o instanceof se){this.fail("backcamera",{phase:"acquiring",name:k(o)});return}this.fail(te(o),{phase:"acquiring",name:k(o)});return}if(ie(a),ae(a),e!==this.attempt){for(let o of a.getTracks())o.stop();return}this.stream=a;let s=a.getVideoTracks?.()[0];if(this.trackProvenance=s===void 0?null:ke(s).catch(()=>null),this.openEnvironment=s===void 0?null:re(s).catch(()=>({})),this.facing=Y(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 o={v3AssetBaseUrl:t.v3AssetBaseUrl},d=t.createDetector??(t.createWorker!==void 0&&ue()?async()=>{try{return await de.create(t.createWorker(),o)}catch{return L(o)}}:()=>L(o)),u;try{u=await d()}catch(h){e===this.attempt&&this.fail("models",{phase:"models",name:k(h)},h instanceof le?h.fallbackReason:ut(h));return}if(e!==this.attempt){u.destroy();return}this.detector=u,this.options.telemetry?.({type:"detector",tier:u.tier,fallbackReason:u.fallbackReason})}let l=pe(),c=t.deviceClass??me(l);this.profiler=new he(c),this.options.telemetry?.({type:"profile",staticClass:c,activeClass:this.profiler.deviceClass,simd:l.simd}),this.gate=new R(t.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(o=>z=o,()=>{}),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 x({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,l=this.now(),c=this.options.makeSnapshot?.(a,n.profile.inputWidth)??this.defaultSnapshot(a,n.profile.inputWidth),o=null;try{o=await t.detect(c,a.videoWidth,a.videoHeight)}catch{o=null}if(e!==this.attempt||this.fired)return;n.record(this.now()-l),n.deviceClass!==s&&this.startScheduler(e);let d=o===null?Ae:this.options.measureQuality?.(a,o.box)??this.defaultQuality(a,o.box),u=r.tick({timestampMs:this.now(),observation:o,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>=nt&&(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,g)=>M+g,0)/a.length});let s=t.mode??"clip",l=t.rankKeyframes?.()&&z?z.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(s==="photo"){let M=this.watchRotation(e,null),g=await l;if(M(),e!==this.attempt)return;if(g===null){this.fail("generic",{phase:"keyframes"});return}let G=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:g.blob,previewDataUrl:g.previewDataUrl,...G});return}this.setState("recording");let c=this.stream;if(c===null){this.fail("generic",{phase:"recording"});return}let o=t.screenRamp?.(),d=P(o),u=null;l.then(M=>{u=M},()=>{});let h=()=>{e===this.attempt&&u!==null&&this.emit("frozen",{previewDataUrl:u.previewDataUrl})},v=Te(o,H),p=null,m,y=0;try{let M=this.recordTake(e,c,o,v,void 0).then(T=>T,T=>({failed:T})),[g,G]=await Promise.all([M,l]);if(m=G,e!==this.attempt)return;if("failed"in g){if(g.failed.kind==="cliptoolarge")throw g.failed;N(g.failed.requestedMimeType??"")}else p=g,K(g.clip,v)?g.clip.stats===null&&N(g.clip.requestedMimeType??""):h();if(p===null||K(p.clip,v)){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,o,v,h)}catch(Oe){if(p===null)throw Oe}if(e!==this.attempt)return;T!==null&&(p===null||Se(T.clip,p.clip))&&(p=T),T===null&&h()}}catch(M){if(e!==this.attempt)return;let g=M.kind;this.fail(g==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:k(M)});return}if(p===null){this.fail("recorder",{phase:"recording"});return}let{clip:f,rvfc:b,report:C,watched:E}=p;if(I(f.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(m===null){this.fail("generic",{phase:"keyframes"});return}let A=await this.provenance(b,d,E);e===this.attempt&&this.finishCapture({clip:f.blob,clipMimeType:f.mimeType,...f.stats?{clipStats:f.stats}:{},clipRetakes:y,keyframe:m.blob,previewDataUrl:m.previewDataUrl,...C!==void 0&&C.rendered.length>0?{screenRamp:C}:{},...A})}async recordTake(e,t,r,n,a){let s=this.options.createRecorder?.()??new D({now:()=>this.now()}),l=Re(this.options.video),c=Ce(r,{paint:h=>{(h===null||e===this.attempt)&&this.emit("ramp",{colour:h})},now:()=>this.now(),frames:l.latest});this.ramp=c;let o=()=>{l.stop(),c.stop(),this.ramp===c&&(this.ramp=null)},d=this.watchRotation(e,s),u=ne();try{return{clip:await s.record(t,a,()=>c.started(this.now()),n,l),rvfc:l.stats(),report:c.report(),watched:u.stop()}}finally{u.stop(),d(),o()}}async provenance(e,t,r={}){let n=this.trackProvenance;if(n===null)return{};let a,s=new Promise(d=>{a=setTimeout(()=>d(null),st)}),l=await Promise.race([n,s]),c=l===null?null:await Promise.race([this.openEnvironment,s]);if(clearTimeout(a),l===null)return{};let o={...c,...r};return{provenance:{...we(l,e,t),...Object.keys(o).length>0?{env:o}:{}}}}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!==W&&(this.lastGuidanceKey=W,this.emit("guidance",{key:W}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,n=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){l();return}r.videoWidth>0&&this.isLandscape()&&(l(),this.abortRecording(e,t))},a=setInterval(n,it);r.addEventListener?.("resize",n);let s=!1;function l(){s||(s=!0,clearInterval(a),r.removeEventListener?.("resize",n))}return l}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 R(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=at/(q-1),n=null;for(let a=0;a<q;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<q-1&&await ct(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"?Ee:ot)(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)),l=r.getContext("2d");return l===null?e:(r.width!==a&&(r.width=a),r.height!==s&&(r.height=s),l.drawImage(e,0,0,a,s),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,t){let r=De(e,t,96);return r===null?Ae:{sharpness:V(r),exposure:ve(r),meanLuma:fe(r)}}centerSharpness(e){let t=ce(e),r=De(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:V(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()}},z;function ct(i){return new Promise(e=>setTimeout(e,i))}function ut(i){return i instanceof Error?i.message:String(i)}function De(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 dt(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{mt as a,H as b,Le as c,Fe as d,Me as e,Ve as f,Ne as g,Ue as h,He as i,S as j,Be as k,K as l,Se as m,D as n,qe as o,bt as p,Ee as q,x as r,Qe as s,R as t,je as u,w as v,nt as w,W as x,it as y,q as z,at as A,st as B,Ie as C};
@@ -1,3 +0,0 @@
1
- import{B as ft,C as mt,D as ht,E as yt,a as ot,b as rt,c as it,d as Z,e as J,f as re,g as st,h as K,i as at,j as I,k as j,l as T,m as D,n as U,o as X,p as ut,q as z,r as ie,s as ct,t as dt,u as lt,v as pt}from"./chunk-5QUJHFOH.js";import{n as et}from"./chunk-7GUHA2NM.js";import{a as ze}from"./chunk-7QZWBDI5.js";import{c as G,e as tt,g as nt,h as se}from"./chunk-QPO6LOYB.js";import{c as Je,d as _e}from"./chunk-TSA6GHUG.js";import{b as Xe}from"./chunk-KORZGQLS.js";function ae(e){return e.idNumberBound??e.nniBound}function ee(e){return e===void 0?void 0:e.idNumberFromDocument??e.nniFromDocument}function gt(e){let t=e.idNumberMasked??e.nniMasked;return typeof t=="string"&&t!==""?t:void 0}var Jt="https://api.sekyro.ai",Xt=5e3,zt=24e4,en=9e4,tn=25*6e4,nn=20*6e4,on=3,rn=3e3,sn=1500,an=10;function St(e){return e instanceof Error&&e.name==="ChallengeError"&&e.code||"challenge_failed"}var _t=new Set(["aborted","embedder_opaque","site_key_rejected"]);function un(e){return new Promise(t=>setTimeout(t,e))}function cn(){let e=globalThis.crypto;if(e!==void 0&&typeof e.randomUUID=="function")return e.randomUUID();let t=new Uint8Array(16);if(e!==void 0&&typeof e.getRandomValues=="function")e.getRandomValues(t);else for(let i=0;i<16;i+=1)t[i]=Math.floor(Math.random()*256);t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let n=[...t].map(i=>i.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function xo(e){return dn(e,{})}function dn(e,t){let n=e.apiOrigin??Jt,i=e.autoRetry??!0,r=e.rearm??"auto",u=t.client??new nt({apiOrigin:n,sessionToken:e.clientToken,fetch:e.fetch,locale:e.locale}),a=new Proxy(u,{get(o,s){if(s==="submitCheck")return Ut;let c=Reflect.get(o,s,o);return typeof c=="function"?c.bind(o):c}}),d=t.sleep??un,h=t.uuid??cn,_=t.getChallengeToken??((o,s)=>import("./challenge-frame-YBTLAQ5G.js").then(c=>c.executeChallenge({frameUrl:o.url,siteKey:o.siteKey,action:"liveness",subject:s.subject,signal:s.signal}))),S=ze(),P=null,g=null,m=!1,M=new AbortController,y=null,ce=null,te=null,ne=()=>te??ct(y),Re=()=>dt(ie(y),ne()),O=o=>{y=o,!I(o)&&(Be(nn)||Lt(o))&&Se(o),S.emit("view",o),P?.onView(o)},x=()=>y!==null?Promise.resolve(y):(ce??(ce=a.getSession().then(o=>(O(o),o)).finally(()=>{ce=null})),ce),E=async()=>{let o=await a.getSession();return O(o),o},de=async(o,s)=>{o.plan!==void 0?O(o):await E()},le=null,Ie=async o=>{let s=await x();if(o||!s.consentRecorded){let c=await a.recordConsent(e.locale);c.plan!==void 0?O(c):y!==null&&O({...y,consentRecorded:!0})}oe()&&Se(s)},F=o=>o?.force===!0?Ie(!0):(le??(le=Ie(!1).finally(()=>{le=null})),le),pe={client:a,ensureConsent:o=>F(o),sleep:d,uuid:h,...t.random!==void 0?{random:t.random}:{},onBusy:o=>{m||S.emit("busy",o)}},Me=!1,Oe=null,fe=o=>{if(o.status==="verified"||o.status==="not_verified"||o.status==="review"){if(Me)return;Me=!0}Oe=JSON.stringify(o),S.emit("result",o)},Ft=o=>{Oe!==JSON.stringify(o)&&fe(o)},Ee=async o=>{let s=y;o&&(s=await E().catch(()=>y));let c=s===null?null:K(s);return c!==null&&!m&&S.emit("method",c),c!==null},ve=null,Te=!1,Ve=!1,Fe=()=>mt(pe,(o,s)=>o.submitCheck("population_registry",{},{idempotencyKey:s})),Ne=o=>ae(o)===!0||ee(T(o,"population_registry"))===!0,Nt=async()=>{try{let o=await x();if(I(o)||K(o)!==null||j(o)?.checkType!=="population_registry")return;if(!Ne(o)&&ee(T(o,"population_registry"))===void 0&&(o=await E()),!Ne(o)){Ve=!0;return}await F(),await de(await Fe(),"population_registry");let s=y===null?void 0:T(y,"population_registry");if(s?.state==="input_required"&&s.reason==="registry_unavailable"&&re(s)>0){if(await d(Xt),m)return;await de(await Fe(),"population_registry")}}catch(o){if(o instanceof G&&(o.code==="check_not_active"||o.code==="step_not_on_path")){await E().catch(()=>{});return}Te=!0;return}y!==null&&I(y)&&fe(X(y,{autoRetry:i}))},He=()=>(ve??(ve=Nt()),ve),v=t.now??Date.now,q=null,Y,me,Ht=0,he=(o,s)=>`${o.url}
2
- ${o.siteKey}
3
- ${s}`,Le=0,ye,ge=(o,s)=>{Le+=1;let c=v(),f=_(o,{signal:M.signal,subject:s}),p={key:he(o,s),at:c,token:f};return f.then(()=>{p.issuedAt=v(),me=void 0},k=>{let C=St(k);if(p.failed=C,m||C==="aborted")return;me=C;let{detail:w,readyMs:l}=k;W({check:"attestation",kind:"unavailable",engineKind:C,attempt:Ht++,challengeMs:v()-c,readyMs:l,detail:w,inApp:Xe()})}),f.catch(()=>{}),p},De=(o,s)=>o!==null&&o.key===s&&(o.issuedAt===void 0||v()-o.issuedAt<zt),Se=(o,s={})=>{let c=o?.challenge??null;if(o===null||c===null||m)return;let f=D(o.sessionId),p=q;(s.replaceFailed===!0&&p?.failed!==void 0&&!_t.has(p.failed)||!De(p,he(c,f)))&&(q=ge(c,f))},Ue=async(o,s)=>{let c=he(o,s),f=q;q=null;let p=De(f,c)?f:ge(o,s),k=p===f?0:1,C,w=new Promise(l=>{C=setTimeout(()=>l("late"),en)});try{for(;;){let l=await Promise.race([p.token.then(A=>({token:A}),A=>({error:St(A)})),w]);if(l==="late")return!m&&q===null&&(q=p),{error:me??"timeout"};if("token"in l)return ye=Math.max(0,Math.round((p.issuedAt??v())-p.at)),l;if(m||_t.has(l.error)||k>=on||k>0&&await Promise.race([d(rn*k),w])==="late")return l;if(m)return{error:"aborted"};k+=1,p=ge(o,s)}}finally{clearTimeout(C)}},H=null,Lt=o=>J(o).some(s=>(s.checkType==="phone_otp"||s.checkType==="email_otp")&&s.state!=="passed"&&s.state!=="skipped"),Be=o=>H===null||v()-H>=o,oe=()=>Be(tn),Dt=o=>{let s=o.attestation;return typeof s?.turnstileToken=="string"&&s.turnstileToken.length>0},qe=new Map,Ge=async()=>{let o=await x(),s=o.challenge;if(s==null||o.simulation!==void 0)return;let c=await Ue(s,D(o.sessionId));if(!("token"in c))throw new G({status:400,code:"attestation_invalid",message:`browser check: ${c.error}`});return c.token},Ut=async(o,s,c={})=>{let f=s;if("attestation"in f)try{let l=await u.submitCheck(o,s,c);return Dt(f)&&(H=v()),l}catch(l){throw l instanceof G&&l.code==="attestation_invalid"&&(H=null),l}let p=(o==="phone_otp"||o==="email_otp")&&f.action!=="verify",k=c.idempotencyKey,C=k!==void 0?qe.get(k):void 0;C===void 0&&(p||oe())&&(C=await Ge(),k!==void 0&&C!==void 0&&qe.set(k,C));let w=(l,A)=>l!==void 0?{...A,browserCheckToken:l}:A;try{let l=await u.submitCheck(o,s,w(C,c));return C!==void 0&&(H=v()),l}catch(l){if(!(l instanceof G)||l.code!=="attestation_invalid"||(H=null,C!==void 0))throw l;let A=await Ge(),L=k!==void 0?{...c,idempotencyKey:h()}:c,N=await u.submitCheck(o,s,w(A,L));return A!==void 0&&(H=v()),N}},Ke=async(o={})=>{if(Y=void 0,o.always!==!0&&!oe())return{};let s=await x(),c=s.challenge;if(c==null)return{};let f=await Ue(c,D(s.sessionId));if("token"in f)return{channel:"hosted_web",turnstileToken:f.token};if(Y=f.error,s.simulation!==void 0)return{channel:"hosted_web"};throw new ft(f.error)},Bt=()=>Y,qt=()=>({checks:Math.min(50,Le),...ye!==void 0?{challengeMs:Math.min(6e5,ye)}:{}}),W=o=>{if(m)return;let s=a.reportCaptureIssue;if(s===void 0)return;let c=o.formFactor;try{c??(c=Je())}catch{}try{Promise.resolve(s.call(a,{...o,...c!==void 0?{formFactor:c}:{}})).catch(()=>{})}catch{}},R=null,$=null,je=new WeakMap,Ye=Promise.resolve(),Q=0,Gt=async()=>{let o=await x();for(let s=0;s<an&&!m&&!I(o)&&j(o)===void 0&&J(o).some(c=>c.state==="processing")&&(await d(sn),!m);s+=1)o=await E();return o},Kt=async(o,s,c)=>{let{capture:f}=o,p=()=>m,k=()=>o.alive&&o.attempt===c,C=l=>{k()&&f.setFlowState(l)},w=l=>{if(!p()&&(l.status==="unavailable"&&l.reasonCode!==void 0&&!ot(l.reasonCode)&&W({check:"liveness",kind:"unavailable",phase:"upload",engineKind:l.reasonCode,attempt:Math.max(0,o.issues.value)}),fe(l),!!k())){if(l.status==="retry"&&r==="auto"){f.handle.retry();return}f.setFlowState("done")}};if(s.degraded==="NO_RECORDER"){let l=y?.sessionId??(await x().catch(()=>null))?.sessionId??"";w(U(l,"no_recorder"));return}C("uploading");try{if(await He(),p())return;let l=await x(),A;if(!I(l)&&K(l)!==null){await Ee(!1),w(U(l.sessionId,"method_required"));return}if(!I(l)){if(j(l)?.checkType==="population_registry"){w(U(l.sessionId,Ve?"nni_unbound":Te?"network":"registry_unavailable"));return}if(await F(),p())return;A=y??l;let L=await ht({...pe,artifacts:s,getAttestation:Ke,attestationError:Bt,attestationFacts:qt,clipKeys:{get:()=>je.get(s)??null,set:N=>{je.set(s,N)}},getView:()=>y??l,refreshView:E,applySubmit:de,onPhase:C,isCancelled:p,onKeyframePromoted:N=>{g=N}});if(p())return;if(L.kind==="unavailable"){L.reason==="attestation"&&($={bound:o,artifacts:s});let N=U(l.sessionId,L.reason),Ze=L.reason==="attestation"?Y:void 0;w(Ze!==void 0?{...N,attestationError:Ze}:N);return}if(L.kind==="resync"&&await E(),y!==null&&K(y)!==null){await Ee(!1),w(U(l.sessionId,"method_required"));return}l=await Gt()}w(X(l,{autoRetry:i,previous:A}))}catch{if(p())return;w(U(y?.sessionId??"","network"))}},We=(o,s)=>{let c=o.attempt;Q>0&&o.alive&&o.capture.setFlowState("uploading"),Q+=1,Ye=Ye.then(()=>Kt(o,s,c)).finally(()=>{Q-=1,Q===0&&P?.onChainIdle()}).catch(()=>{})},$e=o=>{R?.capture.handle.destroy(),R!==null&&(R.alive=!1);let s=et(o,P?.captureInternals?.(o)??t.capture,()=>y?.capture?.liveness?.keyframe?.rank===!0,Re,()=>y?.capture?.liveness?.screenRamp,{session:()=>ie(y),onModeChange:p=>{te=p}}),c={capture:s,alive:!0,attempt:0,issues:it()};R=c,s.handle.on("error",p=>{W(rt("liveness",p,c.issues.value))}),s.handle.on("state",p=>{if(c.issues.note(p),p==="starting"){c.attempt+=1,$?.bound===c&&($=null),oe()&&Se(y,{replaceFailed:!0});let k=y===null?void 0:j(y)?.checkType;(k==="liveness"||k==="face_match")&&F().catch(()=>{})}}),s.handle.on("captured",p=>{Promise.resolve().then(()=>We(c,p))});let f=s.handle;return{get state(){return f.state},get captureMode(){return f.captureMode},get facingMode(){return f.facingMode},on:(p,k)=>f.on(p,k),start:async p=>{if(y===null&&await x().catch(()=>{}),!!c.alive)return f.start(p)},retry:()=>{let p=$;if(p!==null&&p.bound===c&&c.alive){$=null,We(c,p.artifacts);return}f.retry()},switchCamera:()=>f.switchCamera(),canSwitchCaptureMode:()=>f.canSwitchCaptureMode(),setCaptureMode:p=>f.setCaptureMode(p),destroy:()=>{c.alive=!1,R===c&&(R=null),f.destroy()}}},jt=async()=>{if(m)return null;try{let o=await x();return m?null:K(o)}catch{return null}},Yt=async()=>{if(m)return"self";try{let o=await x();if(m)return"self";let s=ie(o);return s==="choice"?ne()??s:s}catch{return"self"}},Wt=async()=>{if(m)return!1;try{let o=await x();return m||I(o)||_e()?!1:z(o,j(o))==="phone"||z(o,T(o,"liveness"))==="phone"}catch{return!1}},$t=async()=>{if(m)return!1;try{let o=await x();return!m&&o.returning===!0}catch{return!1}},Qt=async o=>{let s=(await x()).plan?.choice,c=s?.options.find(p=>Z[p.service]===o);if(!c)throw new RangeError(`method ${String(o)} is not offered`);let f=await a.choose(s.nodeId,c.id);m||O(f)},Qe=null,Zt=()=>(Qe??(Qe=import("./plan-runner-7XZH4SBZ.js").then(o=>{let s=o.createPlanRunner({runtime:pe,currentView:()=>y,cameraMode:Re,captureModeSwitch:{pick:ne,choose:c=>{te=c}},ensureView:x,refreshView:E,ensureConsent:()=>F(),liveness:$e,stopLiveness:()=>{R!==null&&(R.alive=!1,R.capture.handle.destroy(),R=null)},chainBusy:()=>Q>0,destroyed:()=>m,sleep:d,isMobile:_e,now:t.now??Date.now,keptFaceKey:()=>g,setView:O,baseCapture:t.capture,emitStep:c=>{m||S.emit("step",c)},emitResult:Ft,reportCaptureIssue:W,documentInternals:t.document,documentFacts:t.documentFacts,portraitInternals:t.portrait,livePhotoInternals:t.livePhoto,uploadInternals:t.upload,pageCameraInternals:t.pageCamera});return P=s,s})),Qe);return{consent:()=>F(),startRegistry:He,methodChoice:jt,selectMethod:Qt,reportCameraUnavailable:async o=>{await F();let s=a.reportCameraUnavailable;if(s===void 0)throw new TypeError("this client cannot report a missing camera");let c=await s.call(a,o).catch(f=>{if(f instanceof G&&f.code==="check_out_of_order")return a.getSession();throw f});m||O(c)},reportCaptureIssue:W,testerGate:async o=>{let s=a.testerGate;if(s===void 0)throw new TypeError("this client cannot run the tester gate");let c=o.clip,f=tt(o.clipMime??"");if(c===void 0||!pt.includes(f))throw new TypeError("the capture has no clip");await F();let p=await lt(a,"clip",f,c.size,{engine:o.engine,durationMs:o.clipMs});await a.uploadToSpaces(p.uploadUrl,c,f);let{key:k}=await a.completeMedia(p.key),C=await Ke({always:!0}),w=await s.call(a,{clipKey:k,attestation:C,captureChannel:o.captureChannel,capture:{...yt(o),attestationError:Y}}),{bound:l,...A}=w;return m||(A.plan!==void 0?O(A):await E()),{bound:l===!0}},mobileRequired:Wt,captureMode:Yt,chooseCaptureMode:o=>{te=o},get captureChoice(){return ne()},returning:$t,liveness:$e,run:async()=>{if(m)throw new Error("verification destroyed");return(await Zt()).run()},currentStep:()=>P?.current()??null,voiceClips:async()=>{if(m)return null;try{let o=await x();return m?null:o.voice??null}catch{return null}},on:(o,s)=>S.on(o,s),destroy:()=>{m=!0,M.abort(),P?.destroy(),R!==null&&(R.alive=!1,R.capture.handle.destroy(),R=null),S.clear()}}}var kt=["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 ln=["carte_identite","passport","residence_permit","drivers_license"],pn=["carte_identite","passport","residence_permit"];function fn(e,t){let n=e.byIssuer?.[t]??e.default;return ln.filter(i=>n==="*"?pn.includes(i):n.includes(i))}function Io(e,t=kt){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(i=>fn(e,i).length>0).sort()}function Ct(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}function Mo(e){return/^[A-Z]{2}$/.test(e)?String.fromCodePoint(...[...e].map(t=>127462+t.charCodeAt(0)-65)):""}var b={fullNameMin:2,fullName:200,email:254,occupation:120,shortText:120,longText:1e3,addressLine:120,addressLines:4,city:80,postcode:16,number:1e12,dateMin:"1900-01-01",dateMax:"2100-12-31"},mn=new Set(["full_name","birth_date","email","phone","address","country","occupation"]),hn=new Set(["short_text","long_text","single_choice","multiple_choice","yes_no","date","number"]),yn=new Set(["ar","fa","he","ur"]);function bt(e){return yn.has(e.split("-")[0]?.toLowerCase()??"")?"rtl":"ltr"}function wt(e){if(typeof e!="object"||e===null)return null;let t=e;if(typeof t.locale!="string"||!Array.isArray(t.questions)||t.questions.length===0)return null;let n=t.consents??[];if(!Array.isArray(n))return null;for(let r of t.questions)if(!gn(r))return null;for(let r of n)if(!Sn(r))return null;let i={locale:t.locale,questions:t.questions,consents:n};return typeof t.title=="string"&&t.title.trim()!==""&&(i.title=t.title),typeof t.intro=="string"&&t.intro.trim()!==""&&(i.intro=t.intro),typeof t.prefill=="object"&&t.prefill!==null&&!Array.isArray(t.prefill)&&(i.prefill=t.prefill),i}function gn(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id!="string"||typeof t.required!="boolean"?!1:t.kind==="field"?typeof t.field=="string"&&mn.has(t.field):t.kind!=="custom"||typeof t.type!="string"||!hn.has(t.type)||typeof t.label!="string"?!1:t.type==="single_choice"||t.type==="multiple_choice"?Array.isArray(t.choices)&&t.choices.length>=2&&t.choices.every(n=>typeof n=="object"&&n!==null&&typeof n.value=="string"&&typeof n.label=="string"):!0}function Sn(e){if(typeof e!="object"||e===null)return!1;let t=e;if(typeof t.id!="string"||typeof t.required!="boolean"||typeof t.text!="string")return!1;if(t.link===void 0)return!0;let n=t.link;return typeof n=="object"&&n!==null&&typeof n.url=="string"&&/^https:\/\//.test(n.url)&&typeof n.label=="string"}var _n=/^(\d{4})-(\d{2})-(\d{2})$/;function kn(e){if(typeof e!="string")return!1;let t=_n.exec(e);return t===null?!1:new Date(Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3]))).toISOString().slice(0,10)===e&&e>=b.dateMin&&e<=b.dateMax}function Cn(e){return typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<b.number&&Math.round(e*100)/100===e}function xt(e){for(let t of e.matchAll(/\d[\d -]{11,}\d/g)){let n=t[0].replace(/[ -]/g,"");if(n.length>=13&&n.length<=19&&bn(n))return!0}return!1}function bn(e){let t=0;for(let n=0;n<e.length;n++){let i=Number(e[e.length-1-n]);n%2===1&&(i*=2,i>9&&(i-=9)),t+=i}return t%10===0}var wn=/^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$/,xn=/^\+[1-9]\d{6,14}$/,At=/^[A-Z]{2}$/,An=e=>e===void 0||typeof e=="string"&&e.trim()===""||Array.isArray(e)&&e.length===0;function Pn(e=Date.now()){return new Date(e).toISOString().slice(0,10)}function Eo(e,t,n=Pn()){let i=[];for(let r of e.questions){let u=t.answers[r.id];if(An(u)){r.required&&i.push({id:r.id,code:"required"});continue}let a=r.kind==="field"?Rn(r.field,u,n):Mn(r,u,n);a!==null&&i.push({id:r.id,...a})}for(let r of e.consents)r.required&&t.consents[r.id]!==!0&&i.push({id:r.id,code:"consent_required"});return i}function ue(e,t,n=1){if(typeof e!="string")return{code:"required"};let i=e.trim();return[...i].length>t?{code:"too_long",params:{max:t}}:[...i].length<n?{code:"too_short",params:{min:n}}:xt(i)?{code:"card_number"}:null}function Pt(e,t,n={}){return kn(e)?n.period==="past"&&e>=t?{code:"date_not_past"}:n.period==="future"&&e<=t?{code:"date_not_future"}:n.min!==void 0&&e<n.min?{code:"date_too_early",params:{date:n.min}}:n.max!==void 0&&e>n.max?{code:"date_too_late",params:{date:n.max}}:null:{code:"date_invalid"}}function Rn(e,t,n){switch(e){case"full_name":return ue(t,b.fullName,b.fullNameMin);case"occupation":return ue(t,b.occupation);case"birth_date":return Pt(t,n,{period:"past"});case"email":return typeof t=="string"&&t.trim().length<=b.email&&wn.test(t.trim())?null:{code:"email_invalid"};case"phone":return typeof t=="string"&&xn.test(t)?null:{code:"phone_invalid"};case"country":return typeof t=="string"&&At.test(t)?null:{code:"choice_invalid"};case"address":return In(t)?null:{code:"address_invalid"};default:return null}}function In(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e,n=Array.isArray(t.lines)?t.lines.filter(i=>typeof i=="string"&&i.trim()!==""):[];return typeof t.country=="string"&&At.test(t.country)&&typeof t.city=="string"&&t.city.trim()!==""&&t.city.trim().length<=b.city&&n.length>=1&&n.length<=b.addressLines&&n.every(i=>i.trim().length<=b.addressLine&&!xt(i))&&(t.postcode===void 0||typeof t.postcode=="string"&&t.postcode.trim().length<=b.postcode)}function Mn(e,t,n){let i=new Set((e.choices??[]).map(r=>r.value));switch(e.type){case"short_text":return ue(t,b.shortText);case"long_text":return ue(t,b.longText);case"single_choice":return typeof t=="string"&&i.has(t)?null:{code:"choice_invalid"};case"multiple_choice":return Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(r=>i.has(r))?null:{code:"choice_invalid"};case"yes_no":return typeof t=="boolean"?null:{code:"choice_invalid"};case"date":{let r=e.options??{};return Pt(t,n,{...typeof r.min=="string"?{min:r.min}:{},...typeof r.max=="string"?{max:r.max}:{},...r.period==="past"||r.period==="future"?{period:r.period}:{}})}case"number":{if(typeof t!="number"||!Number.isFinite(t)||Math.abs(t)>=b.number)return{code:"number_invalid"};let r=e.options??{};return r.integer===!0&&!Number.isInteger(t)?{code:"number_not_integer"}:Cn(t)?typeof r.min=="number"&&t<r.min?{code:"number_too_small",params:{min:r.min}}:typeof r.max=="number"&&t>r.max?{code:"number_too_large",params:{max:r.max}}:null:{code:"number_decimals"}}default:return null}}var vo={full_name:b.fullName,occupation:b.occupation,email:b.email,short_text:b.shortText,long_text:b.longText};var Rt=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"}),On=new Map(Object.entries(Rt)),Vo=new Map(Object.entries(Rt).map(([e,t])=>[t,e]));function It(e){return On.get(e)??e}var Go=["national_number","document_photo","national_eid"],En=new Set(["phone_otp","email_otp","national_eid","document","nfc","population_registry","supplied_identity","summary_confirm","liveness","portrait","face_match","aml_screening","face_dedup","age_estimation","proof_of_address","form"]),vn=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),Ce=["document","population_registry","national_eid"],be=["phone_otp","email_otp"],Et={identity_method:Ce,contact:be},Tn=["population_registry","document"],we="platform_unsupported",Vn=new Set(["prefilled","user_entered","prefilled_or_entered"]),Fn={phone_otp:"contact",email_otp:"contact",eid_auth:"identity",doc_ocr:"identity",nfc_chip:"identity",population_registry:"identity",liveness:"live_photo",portrait_icao:"live_photo",face_match:"live_photo",poa:"documents",form:"form"};function V(e){return e.section??Fn[e.checkType]??null}function Nn(e,t){let n=e.plan?.choice;if(n===void 0||n.locked)return;let i=n.options.find(r=>r.id!==n.selected&&r.available!==!1&&t.includes(r.service));return i===void 0?void 0:{nodeId:n.nodeId,option:i}}function xe(e){let t=e.plan,n=t?.choice;if(t===void 0||n===void 0||n.locked||t.current===null||t.current===n.nodeId||I(e))return null;let i=Et[n.kind]??[...Ce,...be],r=n.options.flatMap(d=>d.available===!1||!i.includes(d.service)?[]:[d.nationalEid!=null?{id:d.id,service:d.service,nationalEid:d.nationalEid}:{id:d.id,service:d.service}]),u=t.steps.find(d=>d.id===t.current)?.service,a=n.selected??r.find(d=>d.service===u)?.id??null;return r.some(d=>d.id!==a)?{nodeId:n.nodeId,kind:n.kind,current:a,options:r}:null}function vt(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function Hn(e){let t=e.simulation;if(typeof t!="object"||t===null)return;let{otpCode:n,skipCapture:i}=t;if(typeof n!="string"||n===""||typeof i!="boolean")return;let r=ut(e);return r!==void 0?{otpCode:n,skipCapture:i,reason:r}:{otpCode:n,skipCapture:i}}function Ln(e){let t=e.levelTarget?.max;return typeof t=="number"&&t<=1?"contact":e.purpose??"identity"}function Dn(e){let t=(e.plan?.sections??[]).map(a=>({id:a.id,state:a.state})),n={sessionId:D(e.sessionId),orgName:e.orgName,sandbox:e.sandbox===!0,returning:e.returning===!0,consentRecorded:e.consentRecorded,expiresAt:e.expiresAt,sections:t.map(a=>a.id),progress:t,purpose:e.purpose??"identity",levelName:Ln(e)};e.branding!==void 0&&(n.branding=e.branding),e.cameraUnavailableHandled===!0&&(n.cameraUnavailableHandled=!0);let i=Hn(e);i!==void 0&&(n.simulation=i);let r=e.testerGate;r?.offered===!0&&typeof r.attemptsLeft=="number"&&r.attemptsLeft>0&&(n.testerGate={attemptsLeft:r.attemptsLeft});let u=xe(e);return u!==null&&(n.switchable=u),n}function Un(e){let t={attemptsRemaining:re(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 Tt={phone_otp:"phone",email_otp:"email"};function Bn(e,t){let n=Nn(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return n===void 0?void 0:Tt[n.option.service]}function qn(e,t,n,i){let r=t.checkType==="email_otp",u=(r?t.emailOtp:t.otp)??{},a=r?t.emailOtp?.emailSource:t.otp?.numberSource,d=a!==void 0&&Vn.has(a)?a:r?"prefilled_or_entered":"user_entered",h=typeof u.sentToMasked=="string"&&u.sentToMasked.length>0,_=u.prefilled===!0,S=Bn(e,r?"email_otp":"phone_otp"),P={key:t.checkType,context:n,section:V(t),phase:h?"verify":"send",canSwitch:S!==void 0,...i},g=r?{kind:"email_otp",...P,emailSource:d,needsEmail:d!=="prefilled"&&!_}:{kind:"phone_otp",...P,numberSource:d,needsPhone:d!=="prefilled"&&!_,channels:(t.otp?.channels??[]).filter(m=>m==="whatsapp"||m==="sms")};if(S!==void 0&&(g.switchChannel=S),_&&(g.prefilled=!0),h&&(g.sentToMasked=u.sentToMasked),!r&&t.otp?.channel!==void 0&&(g.channel=t.otp.channel),!r&&Array.isArray(t.phoneCountries)&&(g.phoneCountries=t.phoneCountries.filter(m=>typeof m=="string"&&/^[A-Z]{2}$/.test(m))),!r&&Array.isArray(t.phoneRules)){let m=g.phoneCountries??[];g.phoneRules=t.phoneRules.flatMap(M=>{let y=jn(M);return y!==void 0&&m.includes(y.code)?[y]:[]})}return!r&&t.phoneInternational===!0&&(g.phoneInternational=!0),u.expiresAt!==void 0&&(g.codeExpiresAt=u.expiresAt),u.resendAvailableAt!==void 0&&(g.resendAvailableAt=u.resendAvailableAt),g}var Gn=/^[\d[\]\-|()?:^]{1,64}$/;function Kn(e){try{return typeof e=="string"&&Gn.test(e)&&new RegExp(e)!==null}catch{return!1}}var Mt=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function jn(e){let{code:t,dial:n,trunk:i,lengths:r,formats:u}=e??{};if(typeof t!="string"||typeof n!="string"||!/^\d{1,3}$/.test(n)||i!==void 0&&(typeof i!="string"||!/^\d{1,3}$/.test(i))||!Array.isArray(r)||r.length===0||!r.every(Mt))return;let a={code:t,dial:n,lengths:[...r].sort((d,h)=>d-h)};if(i!==void 0&&(a.trunk=i),u!==void 0){if(!(Array.isArray(u)&&u.length<=8&&u.every(h=>Kn(h?.leading)&&Array.isArray(h.groups)&&h.groups.every(Mt)&&r.includes(h.groups.reduce((_,S)=>_+S,0)))))return;a.formats=u.map(h=>({leading:h.leading,groups:[...h.groups]}))}return a}function Yn(e,t,n,i){let r=ae(e)===!0?"bound":ee(t)===!0?"document":"typed",u=r==="typed"&&t.state==="input_required"&&t.reason!==void 0&&It(t.reason)==="id_number_recheck",a=vt(xe(e)),d=!i.attemptsExhausted&&a.length===1&&a[0]?.service==="document";return{kind:"registry",key:"registry",context:n,section:V(t),state:t.state==="input_required"?"input_required":"pending",source:r,recheck:u,canUseDocument:d,...i}}function Wn(e,t,n,i,r){let u=[...t.acceptedSides??[]],a={kind:"document",key:"document",context:n,section:V(t),side:u.includes("recto")?"verso":"recto",acceptedSides:u,documents:Ct(e),photo:Pe(Ae(e.documents),r),...i};return e.detectedCountry!==void 0&&(a.detectedCountry=e.detectedCountry),Zn(e)&&(a.ageStepUp=!0),a}function Ae(e,t=!0){let n=e?.source==="upload"||e?.source==="choice"?e.source:"camera",i=e?.sourcePick==="camera"||e?.sourcePick==="upload"?e.sourcePick:null;return{source:n,pick:i,uploadOffered:t&&e?.uploadOffered===!0}}function Pe(e,t){return t?{...e,cameraOnPhone:!0}:e}var $n=10*1024*1024;function Qn(e,t,n,i,r){let u=e.proofOfAddress,a=u?.pdf?.maxBytes,d=u?.phase==="holder_letter"?"holder_letter":"document";return{kind:"proof_of_address",key:"proof_of_address",context:n,section:V(t),phase:d,rule:u?.rule??{country:null,countryFrom:"global",source:"preset_global",kinds:[]},nameMatch:u?.nameMatch??"exact_person",photo:Pe(Ae(u),r),maxPages:3,pdf:{maxBytes:typeof a=="number"&&a>0?a:$n,maxPages:3},licenceAddressAccepted:d==="document"&&u?.licenceAddressAccepted===!0,...i}}function Zn(e){let t=J(e).find(i=>i.checkType==="age_estimation"),n=t?.reason;return t?.state==="failed"&&(n==="age_uncertain"||n==="age_unavailable")}function Jn(e){let t=T(e,"liveness");return t?.state==="passed"||t?.state==="review"}function Ot(e,t,n,i,r,u=!1){let a=t.icao?.report,d=e.portrait,h=r==="capture"?d?.pendingFix??null:null;h!==null&&(r="review");let _=Vt(e);return{kind:"portrait",key:`portrait:${r}`,context:n,section:V(t),phase:r,report:Array.isArray(a)?a:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:se(e),retakeOnly:r==="capture"&&t.state==="input_required"&&_===void 0&&e.capture?.livePhoto?.oneCapture===!0&&Jn(e),photo:Pe(Ae(d,r==="capture"),u&&r==="capture"),pendingFix:h,..._!==void 0?{captureMode:_}:{},...d?.reuse?.pending===!0?{reuse:!0}:{},...i}}function Vt(e){let t=e.portrait?.captureMode;return t==="self"||t==="assisted"||t==="choice"?t:void 0}var ke={minLongSidePx:1280,jpegQuality:.95};function Xn(e,t){let n=e.capture?.livePhoto;if(n?.oneCapture!==!0)return null;let i=T(e,"portrait_icao"),r=n.still??ke;return{icao:t==="liveness"&&se(e)!==null&&Vt(e)===void 0&&i!==void 0&&i.state==="pending"&&i.reason===void 0,still:{minLongSidePx:r.minLongSidePx??ke.minLongSidePx,jpegQuality:r.jpegQuality??ke.jpegQuality}}}function zn(e,t,n,i){let r=t.eid,u=V(t);if(r===void 0||r.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:n,section:u,checkType:"eid_auth",reason:"update_required"};let a=vt(xe(e)),d=a.length===1&&Tn.includes(a[0]?.service??"")?a[0]:void 0,h=d===void 0?void 0:Z[d.service],_=h!==void 0,S={kind:"eid",key:"eid",context:n,section:u,provider:r.provider,providerName:r.providerName,country:r.country,challenge:"app_code",phase:r.awaiting==="code"?"code":"identifier",identifierBound:r.identifierBound===!0,canUseCamera:_,afterPass:r.afterPass==="continue"?"continue":"end",...i};return _&&(S.cameraMethod=h),r.expiresAt!==void 0&&(S.codeExpiresAt=r.expiresAt),r.resendAvailableAt!==void 0&&(S.resendAvailableAt=r.resendAvailableAt),r.resendsRemaining!==void 0&&(S.resendsRemaining=r.resendsRemaining),r.codeAttemptsRemaining!==void 0&&(S.codeAttemptsRemaining=r.codeAttemptsRemaining),S}function eo(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let n=T(e,"portrait_icao");return n!==void 0&&(n.state==="passed"||n.state==="review")?n:null}var to={rejected:"rejected",inconclusive:"inconclusive",unavailable:"unavailable",abandoned:"expired",not_opened:"expired",cancelled:"expired",superseded:"expired",policy:"policy"};function no(e){return e.reasonCode===we?"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?to[e.reason]:void 0)??"rejected"}function oo(e,t){let n=no(e),i=n==="platform_unsupported"?{sessionId:D(e.sessionId),status:"unavailable",reasonCode:we}:X(e,{autoRetry:!1}),r={kind:"result",key:"result",context:t,section:null,display:n,result:i};return e.status==="not_verified"&&e.reason!==void 0&&(r.reason=e.reason),e.reasonCode!==void 0&&(r.reasonCode=e.reasonCode),e.status==="not_verified"&&e.step!==void 0&&(r.step=e.step),e.retryAfter!==void 0&&(r.retryAfter=e.retryAfter),r}function ro(e,t,n){let i=e.identitySummary;if(i==null)return null;let r={kind:"identity_summary",key:"identity_summary",context:t,section:n??"identity",summaryKind:i.kind==="partial"?"partial":i.kind??"full",source:i.source,portraitAvailable:i.portrait?.available===!0,retakeAvailable:i.retakeAvailable===!0};for(let a of io){let d=i[a];typeof d=="string"&&d!==""&&(r[a]=d)}let u=gt(i);return u!==void 0&&(r.idNumberMasked=u,r.nniMasked=u),r}var io=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","expiryDate","retakeTarget"];function B(e,t,n,i){return{kind:"unsupported",key:`unsupported:${n}`,context:e,section:t,checkType:n,reason:i}}function so(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function ao(e,t){let n=Et[e.kind]??[...Ce,...be],i=so(e),r=e.options.flatMap(a=>{if(a.available===!1||!n.includes(a.service))return[];let d={id:a.id,service:a.service};a.nationalEid!=null&&(d.nationalEid=a.nationalEid);let h=(a.channels??[]).filter(_=>_==="whatsapp"||_==="sms");return a.service==="phone_otp"&&h.length>0&&(d.channels=h),[d]});if(r.length===0){let a=e.options.length>0&&e.options.every(d=>d.service==="nfc");return B(t,i,"choice",a?"platform_unsupported":"update_required")}let u={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:r};if(e.kind==="identity_method"){let a={kind:"method",key:"method",context:t,section:i,options:r.map(h=>Z[h.service]),choice:u},d=r.find(h=>h.nationalEid!==void 0)?.nationalEid;return d!==void 0&&(a.nationalEid=d),a}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:i,options:r.map(a=>Tt[a.service]),selected:null,locked:!1,choice:u}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:i,choice:u}}function uo(e,t,n,i){let r=e.nativeApp,u=typeof r=="object"&&r!==null?r:{},a={sekyroApp:u.sekyroApp===!0};return typeof u.link=="string"&&u.link!==""&&(a.link=u.link),a.sekyroApp&&typeof u.sekyroAppLink=="string"&&u.sekyroAppLink.startsWith("sekyro://")&&(a.sekyroAppLink=u.sekyroAppLink),{kind:"native_app_required",key:`native_app_required:${i}`,context:t,section:n,checkType:i,nativeApp:a}}function Ko(e,t={}){let n=Dn(e);if(I(e)||e.reasonCode===we)return oo(e,n);let i=e.plan;if(i===void 0||!Array.isArray(i.sections))return B(n,null,"plan","update_required");let r=st(e);if(r!==null)return ao(r,n);let u=i.current===null?void 0:i.steps.find(g=>g.id===i.current),a=g=>{let m={kind:"processing",key:"processing",context:n,section:g!==void 0?V(g):i.sections.find(M=>M.state==="current")?.id??null,stalled:!1};return typeof g?.service=="string"&&g.service!==""&&(m.service=g.service),m};if(i.current===null)return a(i.steps.find(g=>g.state==="processing"));if(u===void 0)return B(n,null,"step","update_required");if(!En.has(u.service))return u.interaction==="server"?a(u):B(n,V(u),u.service,"update_required");if(vn.has(u.service)||!at(u))return a(u);let d=u,h=Un(d),_=d.checkType,S=V(d);if(d.requiresNativeApp===!0)return uo(e,n,S,_);let P=t.isMobile===!1?z(e,d):null;if(P==="phone")return{kind:"mobile_required",key:"mobile_required",context:n,section:S,checkType:_};switch(_){case"phone_otp":case"email_otp":return qn(e,d,n,h);case"population_registry":return Yn(e,d,n,h);case"eid_auth":return zn(e,d,n,h);case"doc_ocr":return Wn(e,d,n,h,P==="upload_or_phone");case"identity_confirm":return ro(e,n,S)??a(d);case"portrait_icao":return Ot(e,d,n,h,"capture",P==="upload_or_phone");case"liveness":case"face_match":{let g=eo(e,d);if(g!==null)return Ot(e,g,n,h,"match");let m=d.requiresMobile===!0,M=se(e);return{kind:"liveness",key:"biometric",context:n,section:S,mode:_==="face_match"?"selfie":"liveness",requiresMobile:m,instructions:M===null?"standard":"icao",icao:M,livePhoto:Xn(e,_),...h}}case"poa":return Qn(e,d,n,h,P==="upload_or_phone");case"form":{let g=wt(d.form);return g===null?B(n,S,_,"update_required"):{kind:"form",key:"form",context:n,section:S,form:g,dir:bt(g.locale),...h}}case"nfc_chip":return B(n,S,_,"platform_unsupported");default:return B(n,S,_,"update_required")}}export{Jt as a,Xt as b,sn as c,an as d,cn as e,xo as f,dn as g,kt as h,ln as i,fn as j,Io as k,Ct as l,Mo as m,b as n,bt as o,kn as p,Cn as q,xt as r,Pn as s,Eo as t,Go as u,we as v,V as w,xe as x,vt as y,eo as z,Ko as A};
@@ -1 +0,0 @@
1
- import{d as qt,h as $t,k as ee}from"./chunk-JULJQOVT.js";import{b as te}from"./chunk-SMKCBUJL.js";import{a as et,b as ie,c as oe,e as mt,f as ne}from"./chunk-LTGRPMMY.js";import{c as Zt,d as Jt}from"./chunk-PW2HWXBJ.js";import{b as Xt,c as jt}from"./chunk-POIQGEZM.js";import{k as Bt,m as Ut,n as Ht,o as Kt,p as Vt,r as ut}from"./chunk-CPUECYAJ.js";import{b as ht,c as dt,d as j,e as Yt}from"./chunk-FPXL63KZ.js";import{d as Wt}from"./chunk-KORZGQLS.js";var it=Object.freeze({sensing:{key:"sensing",reticle:"searching",minDurationMs:900},too_far:{key:"too_far",reticle:"coaching",minDurationMs:1400},too_close:{key:"too_close",reticle:"coaching",minDurationMs:1400},edge_clipped:{key:"edge_clipped",reticle:"coaching",minDurationMs:1400},wrong_shape:{key:"wrong_shape",reticle:"coaching",minDurationMs:1400},tilted:{key:"tilted",reticle:"coaching",minDurationMs:1400},too_dark:{key:"too_dark",reticle:"coaching",minDurationMs:1400},too_bright:{key:"too_bright",reticle:"coaching",minDurationMs:1400},blurry:{key:"blurry",reticle:"coaching",minDurationMs:1400},focus_far:{key:"focus_far",reticle:"coaching",minDurationMs:1600},glare:{key:"glare",reticle:"coaching",minDurationMs:1400},hold_still:{key:"hold_still",reticle:"locking",minDurationMs:900},processing:{key:"processing",reticle:"processing",minDurationMs:800},side_captured:{key:"side_captured",reticle:"flip",minDurationMs:2600},captured:{key:"captured",reticle:"done",minDurationMs:800}});function se(i){return i.framing==="no_document"?"sensing":i.framing==="too_far"?"too_far":i.framing==="too_close"?"too_close":i.framing==="edge_clipped"?"edge_clipped":i.framing==="wrong_shape"?"wrong_shape":i.framing==="tilted"?"tilted":i.lighting==="too_dark"?"too_dark":i.lighting==="too_bright"?"too_bright":i.glare==="glare"?"glare":i.blur==="blurry"?"blurry":"hold_still"}var ot=class{constructor(t=2600,e=.35){this.windowMs=t;this.decayPerSecond=e;this.votes=[];this.current=it.sensing;this.currentSinceMs=null}reset(){this.votes=[],this.current=it.sensing,this.currentSinceMs=null}force(t,e){return this.votes=[],this.current=it[t],this.currentSinceMs=e,this.current}tick(t,e){if(this.currentSinceMs===null&&(this.currentSinceMs=e),this.votes.push({key:t,atMs:e}),this.votes=this.votes.filter(r=>e-r.atMs<=this.windowMs),e-this.currentSinceMs<this.current.minDurationMs)return this.current;let o=new Map;for(let r of this.votes){let c=(e-r.atMs)/1e3,a=this.decayPerSecond**c;o.set(r.key,(o.get(r.key)??0)+a)}let n=this.current.key,s=-1;for(let[r,c]of o)c>s&&(s=c,n=r);return n!==this.current.key&&(this.current=it[n],this.currentSinceMs=e),this.current}};var je=Object.freeze({MAX_AREA_FRAC:.92,TILT_MAX_SIDE_RATIO:1.3,GLARE_MAX_SPECULAR_FRAC:.025});function ae(i){let{data:t,width:e,height:o}=i,n=e*o;if(n===0)return 0;let s=0;for(let r=0;r<n;r++){let c=r*4;.299*(t[c]??0)+.587*(t[c+1]??0)+.114*(t[c+2]??0)>=252&&s++}return s/n}function Ye(i){let t=(a,l)=>Math.hypot(l.x-a.x,l.y-a.y),e=t(i.topLeft,i.topRight),o=t(i.bottomLeft,i.bottomRight),n=t(i.topLeft,i.bottomLeft),s=t(i.topRight,i.bottomRight),r=Math.max(e,o)/Math.max(1e-6,Math.min(e,o)),c=Math.max(n,s)/Math.max(1e-6,Math.min(n,s));return Math.max(r,c)}function ce(i){let t={...ie,...i.thresholds},e=je,{quad:o,frameWidth:n,frameHeight:s,measures:r}=i,c=i.format==="ID-3",a="ok";if(o===null)a="no_document";else if(c){let m=mt(o),h=n>0?m.width/n:0,f=m.height>0?m.width/m.height:0;h<t.ID3_BAND_MIN_WIDTH_FRAC?a="too_far":re(o,n,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":(f<t.ID3_BAND_ASPECT_MIN||f>t.ID3_BAND_ASPECT_MAX)&&(a="wrong_shape")}else{let m=oe(o,n,s),h=mt(o),f=Math.max(h.width,h.height)/Math.max(1e-6,Math.min(h.width,h.height));m<t.MIN_AREA_FRAC?a="too_far":m>e.MAX_AREA_FRAC?a="too_close":re(o,n,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":Jt(i.format,f)?Ye(o)>e.TILT_MAX_SIDE_RATIO&&(a="tilted"):a="wrong_shape"}let l=r.exposure>=t.GUIDE_EXPOSURE?"ok":r.meanLuma<(ht[0]+ht[1])/2?"too_dark":"too_bright",u=r.sharpness>=t.GUIDE_SHARPNESS?"ok":"blurry",d=r.specularFraction>=e.GLARE_MAX_SPECULAR_FRAC?"glare":"ok";return{framing:a,lighting:l,blur:u,glare:d,acceptable:a==="ok"&&l==="ok"&&u==="ok"&&d==="ok"}}function re(i,t,e,o){return[i.topLeft,i.topRight,i.bottomRight,i.bottomLeft].some(s=>s.x<=o||s.y<=o||s.x>=t-o||s.y>=e-o)}var ue=Object.freeze({width:1920,height:1080}),Ze=Object.freeze({width:3840,height:2160}),le=4096,Je=2560,he=640,nt=.15,Y=Object.freeze({side:.2,above:.9,below:.3});function E(i){let t=[i.topLeft.x,i.topRight.x,i.bottomRight.x,i.bottomLeft.x],e=[i.topLeft.y,i.topRight.y,i.bottomRight.y,i.bottomLeft.y],o=Math.min(...t),n=Math.min(...e);return{x:o,y:n,width:Math.max(...t)-o,height:Math.max(...e)-n}}function de(i,t){let e=Math.max(0,Math.floor(i.x)),o=Math.max(0,Math.floor(i.y)),n=Math.min(t.width,Math.ceil(i.x+i.width)),s=Math.min(t.height,Math.ceil(i.y+i.height));return n-e<16||s-o<16?null:{x:e,y:o,width:n-e,height:s-o}}function qe(i,t,e){if(i===null||t.width<=0||t.height<=0)return null;let o=E(i);if(o.width<=0||o.height<=0)return null;let n=e==="ID-3"?{x:o.x-o.width*Y.side,y:o.y-o.width*Y.above,width:o.width*(1+2*Y.side),height:o.height+o.width*(Y.above+Y.below)}:{x:o.x-o.width*nt,y:o.y-o.height*nt,width:o.width*(1+2*nt),height:o.height*(1+2*nt)};return de(n,t)}function pt(i,t,e){let o=Math.max(i,t);return o>0?Math.min(1,e/o):1}function gt(i,t,e,o,n=Je){let s=t.width>0?e.width/t.width:1,r=t.height>0?e.height/t.height:1,c=i===null?null:{topLeft:{x:i.topLeft.x*s,y:i.topLeft.y*r},topRight:{x:i.topRight.x*s,y:i.topRight.y*r},bottomRight:{x:i.bottomRight.x*s,y:i.bottomRight.y*r},bottomLeft:{x:i.bottomLeft.x*s,y:i.bottomLeft.y*r}},a=qe(c,e,o)??{x:0,y:0,width:e.width,height:e.height},l=pt(a.width,a.height,n),u=Math.max(1,Math.round(a.width*l)),d=Math.max(1,Math.round(a.height*l)),m=null;if(c!==null){let h=E(c);m=de({x:(h.x-a.x)*l,y:(h.y-a.y)*l,width:h.width*l,height:h.height*l},{width:u,height:d})}return{crop:a,width:u,height:d,docRegion:m}}var $e=960,ft=[{width:1920,height:1080},{width:2560,height:1440}];function ti(i){let t=Number.isFinite(i)&&i>0?Math.min(1,i):.85;return ft.find(e=>e.height*t>=$e)??ft[ft.length-1]}function me(i,t,e,o=Ze,n){let s=n===void 0?null:ti(n.fill);if(e==="LOW"&&s===null)return null;let r=e==="LOW"||s!==null&&Math.max(s.width,s.height)>Math.max(o.width,o.height)?s:o,c=i?.width?.max,a=i?.height?.max;if(typeof c!="number"||typeof a!="number"||c<=0||a<=0)return null;let l=Math.max(c,a),u=Math.min(c,a),d=Math.min(l,Math.max(r.width,r.height)),m=Math.min(u,Math.min(r.width,r.height));return d<=Math.max(t.width,t.height)?null:{width:{ideal:d},height:{ideal:m}}}function fe(i){let t={},e=i?.imageWidth,o=i?.imageHeight;if(typeof e?.max=="number"&&e.max>0){let n=typeof o?.max=="number"&&o.max>0?e.max/o.max:1.3333333333333333,s=n>=1?le:le*n,r=Math.min(e.max,Math.floor(s)),c=typeof e.step=="number"&&e.step>0?e.step:1,a=typeof e.min=="number"?e.min:0;r=Math.max(a,a+Math.floor((r-a)/c)*c),t.imageWidth=r}return i?.fillLightMode?.includes("off")===!0&&(t.fillLightMode="off"),t}function pe(i,t){if(i.width<=0||i.height<=0||t.width<=0||t.height<=0)return!1;let e=i.width>i.height,o=t.width>t.height;return e!==o&&i.width!==i.height&&t.width!==t.height?!1:Math.max(i.width,i.height)>=1.2*Math.max(t.width,t.height)}function ge(i,t,e,o){if(e===null)return!1;let n=E(i),s=E(e);if(t.width<=0||o.width<=0)return!1;let r=n.width/t.width,c=s.width/o.width;return c>0&&r>=.6*c&&r<=1.25*c}var be=3500,ei=.92;function Me(){let i=globalThis.ImageCapture;return typeof i=="function"?i:null}function ii(i){return/AppleWebKit\//.test(i)&&!/(Chrome|Chromium|Edg|OPR)\//.test(i)}function ke(i,t=typeof navigator>"u"?"":navigator.userAgent){return Me()!==null&&!ii(t)&&i!=null&&i.kind==="video"&&i.readyState==="live"}function ye(i,t){return new Promise((e,o)=>{let n=setTimeout(()=>o(new Error("takePhoto timed out")),t);i.then(s=>{clearTimeout(n),e(s)},s=>{clearTimeout(n),o(s)})})}function bt(i,t){let e=document.createElement("canvas");return e.width=i,e.height=t,e}function oi(i,t){return new Promise((e,o)=>{i.toBlob(n=>n?e(n):o(new Error("toBlob failed")),"image/jpeg",t)})}async function xe(i,t,e,o,n){let s=bt(e,o),r=bt(1,1);try{let c=s.getContext("2d");if(c===null)throw new Error("2d context unavailable");c.imageSmoothingQuality="high",c.drawImage(i,t.x,t.y,t.width,t.height,0,0,e,o);let a=await oi(s,ei),l=n===null?null:qt({topLeft:{x:n.x,y:n.y},topRight:{x:n.x+n.width,y:n.y},bottomRight:{x:n.x+n.width,y:n.y+n.height},bottomLeft:{x:n.x,y:n.y+n.height}},{width:e,height:o},{width:e,height:o}),u=$t(s,l),d=pt(e,o,he);return r.width=Math.max(1,Math.round(e*d)),r.height=Math.max(1,Math.round(o*d)),r.getContext("2d")?.drawImage(s,0,0,r.width,r.height),{blob:a,previewDataUrl:r.toDataURL("image/jpeg",.85),sharpness:u}}finally{s.width=0,s.height=0,r.width=0,r.height=0}}function ni(i,t){let e=Math.min(1,t/i.width),o=bt(Math.max(1,Math.round(i.width*e)),Math.max(1,Math.round(i.height*e)));try{let n=o.getContext("2d",{willReadFrequently:!0});return n===null?null:(n.imageSmoothingQuality="high",n.drawImage(i,0,0,o.width,o.height),n.getImageData(0,0,o.width,o.height))}finally{o.width=0,o.height=0}}async function De(i,t,e,o){let n={width:Math.max(1,i.videoWidth),height:Math.max(1,i.videoHeight)},s=gt(t,e,n,o);return{...await xe(i,s.crop,s.width,s.height,s.docRegion),docRegion:s.docRegion,source:"video",width:s.width,height:s.height}}async function we(i,t,e,o,n){let s=Me();if(s===null)return null;let r=null;try{let c=new s(n.track),a=await ye(c.getPhotoCapabilities?.()??Promise.resolve({}),be).catch(()=>({})),l=await ye(c.takePhoto(fe(a)),be);r=await createImageBitmap(l);let u={width:i.videoWidth,height:i.videoHeight};if(!pe(r,u))return null;let d=ni(r,n.detectWidth),m=null;d!==null&&t!==null&&(m=await n.detect(d).catch(()=>null));let h=d??{width:r.width,height:r.height};m!==null&&!ge(m,h,t,e)&&(m=null);let f=gt(m,h,r,o);return{...await xe(r,f.crop,f.width,f.height,f.docRegion),docRegion:f.docRegion,source:"photo",width:f.width,height:f.height}}catch{return null}finally{r?.close()}}var st=Object.freeze({width:3840,height:2160,lensSelection:!0,continuousFocus:!0,refocusBeforePhotoMs:350,zoomMax:2,zoomNoFocusInfo:1.5,zoomMinSourcePx:2160,fillDistanceM:Object.freeze({id1:.11,id3:.15}),focusMarginFrac:.2,stillSharpnessMin:.16,stillRefusalsMax:2,focusFarFillFrac:.45,noDocFarHintMs:1500,zoomFallbackMs:8e3}),S=(i,t,e)=>typeof i=="number"&&Number.isFinite(i)&&i>=t&&i<=e?i:void 0;function Ri(i){let t=st,e=i!==null&&typeof i=="object"?i:{},o=e.fillDistanceM!==null&&typeof e.fillDistanceM=="object"?e.fillDistanceM:{},n=(s,r)=>typeof s=="boolean"?s:r;return{width:S(e.width,640,7680)??t.width,height:S(e.height,480,4320)??t.height,lensSelection:n(e.lensSelection,t.lensSelection),continuousFocus:n(e.continuousFocus,t.continuousFocus),refocusBeforePhotoMs:S(e.refocusBeforePhotoMs,0,2e3)??t.refocusBeforePhotoMs,zoomMax:S(e.zoomMax,1,5)??t.zoomMax,zoomNoFocusInfo:S(e.zoomNoFocusInfo,1,5)??t.zoomNoFocusInfo,zoomMinSourcePx:S(e.zoomMinSourcePx,0,8e3)??t.zoomMinSourcePx,fillDistanceM:{id1:S(o.id1,.03,1)??t.fillDistanceM.id1,id3:S(o.id3,.03,1)??t.fillDistanceM.id3},focusMarginFrac:S(e.focusMarginFrac,0,2)??t.focusMarginFrac,stillSharpnessMin:S(e.stillSharpnessMin,0,10)??t.stillSharpnessMin,stillRefusalsMax:S(e.stillRefusalsMax,0,10)??t.stillRefusalsMax,focusFarFillFrac:S(e.focusFarFillFrac,0,1)??t.focusFarFillFrac,noDocFarHintMs:S(e.noDocFarHintMs,0,6e4)??t.noDocFarHintMs,zoomFallbackMs:S(e.zoomFallbackMs,0,12e4)??t.zoomFallbackMs}}var yt="sekyro.doc.camera";function si(){try{let i=globalThis.localStorage?.getItem(yt);return typeof i=="string"&&i!==""?i:null}catch{return null}}function ve(i){try{i===null?globalThis.localStorage?.removeItem(yt):globalThis.localStorage?.setItem(yt,i)}catch{}}var rt=(i,t)=>Array.isArray(i?.focusMode)&&i.focusMode.includes(t);function kt(i,t,e){if(!rt(i,"single-shot"))return null;let o=n=>Math.min(1,Math.max(0,Number.isFinite(n)?n:.5));return{focusMode:"single-shot",pointsOfInterest:[{x:o(t),y:o(e)}]}}function Ci(i,t,e,o){if(!Number.isFinite(i)||!Number.isFinite(t)||e.width<=0||e.height<=0||o.width<=0||o.height<=0)return null;let n=Math.max(e.width/o.width,e.height/o.height),s=o.width*n,r=o.height*n,c=(i-e.left+(s-e.width)/2)/s,a=(t-e.top+(r-e.height)/2)/r;return{x:Math.min(1,Math.max(0,c)),y:Math.min(1,Math.max(0,a))}}function _e(i,t,e,o=st){let n=i?.zoom?.min,s=i?.zoom?.max;if(typeof s!="number"||s<=1)return 1;let r=e==="ID-3"?o.fillDistanceM.id3:o.fillDistanceM.id1,c=i?.focusDistance?.min,a;if(typeof c=="number"&&c>0&&c<1){if(a=c*(1+o.focusMarginFrac)/r,a<=1.05)return 1}else{if(Math.min(t.width,t.height)<o.zoomMinSourcePx)return 1;a=o.zoomNoFocusInfo}let l=Math.min(a,o.zoomMax,s);typeof n=="number"&&(l=Math.max(l,n));let u=i?.zoom?.step;return typeof u=="number"&&u>0&&(l=Math.round(l/u)*u),l>1.01?Number(l.toFixed(2)):1}function Mt(i){try{return i.getVideoTracks?.()[0]}catch{return}}function Se(i){if(i!==null)for(let t of i.getTracks())t.stop()}function ri(i){try{let t=Mt(i)?.getCapabilities?.();return!Array.isArray(t?.focusMode)||t.focusMode.includes("continuous")}catch{return!0}}async function Te(i){let t=s=>({audio:!1,video:{...s,width:{ideal:i.base.width},height:{ideal:i.base.height}}}),e=s=>i.getUserMedia(t({deviceId:{exact:s}})),o=()=>i.getUserMedia(t({facingMode:{ideal:"environment"}}));if(i.lensSelection){let s=si();if(s!==null)try{return{stream:await e(s),lens:"stored"}}catch{ve(null)}}let n=await o();if(!i.lensSelection||i.enumerateDevices===void 0)return{stream:n,lens:"default"};try{let s=ut(await i.enumerateDevices()).slice(0,3);if(s.length===0)return{stream:n,lens:"default"};let r=null;for(let c of s){let a=n!==null?Mt(n)?.getSettings?.().deviceId:void 0;if(n===null||a!==c){Se(n),n=null;try{n=await e(c)}catch{continue}}if(r??(r=c),ri(n))return ve(c),{stream:n,lens:"selected"}}if(n!==null&&r!==null&&Mt(n)?.getSettings?.().deviceId===r)return{stream:n,lens:"selected"};if(Se(n),n=null,r!==null)try{return{stream:await e(r),lens:"selected"}}catch{}return{stream:await o(),lens:"default"}}catch{return{stream:n??await o(),lens:"default"}}}var Z=Object.freeze({brightness:0,glare:0,cardGlare:0,sharpness:0,fill:0,shape:0,content:0,offsetX:0,offsetY:0,edgeConfidence:0,box:null}),L=i=>Math.min(1,Math.max(0,i));function Fe(i,t,e,o=.06){let n=Math.max(i.width/e,i.height),s=n*e,r=(i.width-s)/2,c=(i.height-n)/2,a=L((t.x-t.width*o-r)/s),l=L((t.y-t.height*o-c)/n),u=L((t.x+t.width*(1+o)-r)/s),d=L((t.y+t.height*(1+o)-c)/n);return{x:a,y:l,width:u-a,height:d-l}}function Ce(i,t,e={}){let o=e.edgePeakFrac??0,{width:n,height:s,data:r}=i;if(n<=0||s<=0)return Z;let c=L(t.x),a=L(t.y),l={x:c,y:a,width:Math.max(0,L(t.x+t.width)-c),height:Math.max(0,L(t.y+t.height)-a)};if(l.width<=0||l.height<=0)return Z;let u=l.x*n,d=l.y*s,m=(l.x+l.width)*n,h=(l.y+l.height)*s,f=(m-u)*.15,g=(h-d)*.15,y=(p,b,R)=>Math.min(R,Math.max(b,p)),x=y(Math.floor(u-f),0,n-1),w=y(Math.floor(d-g),0,s-1),O=y(Math.ceil(m+f),x+1,n),v=y(Math.ceil(h+g),w+1,s),D=Math.max(1,Math.ceil(Math.max(O-x,v-w)/320)),M=Math.floor((O-x+D-1)/D),_=Math.floor((v-w+D-1)/D);if(M<3||_<3)return Z;let k=new Int32Array(M*_);for(let p=0;p<_;p++){let b=w+p*D;for(let R=0;R<M;R++){let F=(b*n+x+R*D)*4;k[p*M+R]=(r[F]??0)*77+(r[F+1]??0)*150+(r[F+2]??0)*29>>8}}let C=(p,b)=>(p-b-.5)/D,T=C(u,x),A=C(m,x),B=C(d,w),U=C(h,w),Dt=(m-u)/D,wt=(h-d)/D,vt=y(Math.ceil(T),0,M-1),Ge=y(Math.floor(A),vt,M-1),St=y(Math.ceil(B),0,_-1),ze=y(Math.floor(U),St,_-1),_t=0,Tt=0,W=0,Rt=0,Ft=0,H=0;for(let p=St;p<=ze;p++)for(let b=vt;b<=Ge;b++){let R=k[p*M+b];if(_t+=R,R>=248&&Tt++,W++,b>=1&&b<M-1&&p>=1&&p<_-1){let F=k[p*M+b-1]+k[p*M+b+1]+k[(p-1)*M+b]+k[(p+1)*M+b]-4*R;Rt+=F,Ft+=F*F,H++}}let Ne=W>0?_t/W:0,Ct=W>0?Tt/W:0,At=H>0?Rt/H:0,Qe=H>0?Math.max(0,Ft/H-At*At):0,K=new Float64Array(M),V=new Float64Array(_);for(let p=0;p<_;p++)for(let b=1;b<M-1;b++)K[b]=K[b]+Math.abs(k[p*M+b+1]-k[p*M+b-1]);for(let p=1;p<_-1;p++)for(let b=0;b<M;b++)V[p]=V[p]+Math.abs(k[(p+1)*M+b]-k[(p-1)*M+b]);let I=at(K,!0,T,o),P=at(K,!1,A,o),G=at(V,!0,B,o),z=at(V,!1,U,o),Et=(P.position-I.position)/Dt,Lt=(z.position-G.position)/wt,Be=Lt>0?Et/Lt:0,Ue=((I.position+P.position)/2-(T+A)/2)/Dt,We=((G.position+z.position)/2-(B+U)/2)/wt,Ot=Re(K),It=Re(V),He=Ot<=0||It<=0?0:Math.min(Math.min(I.value,P.value)/Ot,Math.min(G.value,z.value)/It),$=(p,b)=>b+(p+.5)*D,Pt=Ct,Gt=0;{let p=(P.position-I.position)*.06,b=(z.position-G.position)*.06,R=y(Math.ceil(I.position+p),0,M-1),F=y(Math.floor(P.position-p),0,M-1),Ke=y(Math.ceil(G.position+b),0,_-1),zt=y(Math.floor(z.position-b),0,_-1),Nt=0,tt=0,Qt=0;for(let N=Ke;N<=zt;N++)for(let Q=R;Q<=F;Q++){tt++;let X=k[N*M+Q];X>=248&&Nt++;let Ve=Q+2<=F?k[N*M+Q+2]:X,Xe=N+2<=zt?k[(N+2)*M+Q]:X;(Math.abs(Ve-X)>=24||Math.abs(Xe-X)>=24)&&Qt++}tt>=16&&(Pt=Nt/tt,Gt=Qt/tt)}return{brightness:Ne,glare:Ct,cardGlare:Pt,sharpness:Qe,fill:Et,shape:Be,content:Gt,offsetX:Ue,offsetY:We,edgeConfidence:He,box:{left:$(I.position,x),right:$(P.position,x),top:$(G.position,w),bottom:$(z.position,w)}}}function at(i,t,e,o){let n=i.length,s=Math.max(1,Math.floor(n*.45)),r=t?1:Math.max(1,n-1-s),c=t?Math.min(n-2,s):n-2,a=r;for(let h=r;h<=c;h++)i[h]>i[a]&&(a=h);if(o>0&&o<1){let h=i[a]*o,f=a,g=Math.abs(a-e);for(let y=r;y<=c;y++){let x=i[y];if(x<h||x<(i[y-1]??0)||x<(i[y+1]??0))continue;let w=Math.abs(y-e);w<g&&(f=y,g=w)}a=f}let l=a>0?i[a-1]:0,u=i[a],d=a<n-1?i[a+1]:0,m=l+u+d;return{position:m>0?a+(d-l)/m:a,value:u}}function Re(i){if(i.length<3)return 0;let t=0;for(let e=1;e<i.length-1;e++)t+=i[e];return t/(i.length-2)}function Ae(i){let t=i.box;return t===null||t.right-t.left<4||t.bottom-t.top<4?null:{topLeft:{x:t.left,y:t.top},topRight:{x:t.right,y:t.top},bottomRight:{x:t.right,y:t.bottom},bottomLeft:{x:t.left,y:t.bottom}}}var J=Object.freeze({fillMin:.82,fillMax:1.06,offsetMax:.06,glareMax:.025,sharpnessMin:180,edgeConfidenceMin:1.6,darkBrightness:70,lockMs:450,steadyMs:900,steadyFillMin:.45,steadyFillMax:1.3,steadyFillDelta:.06,steadyOffsetDelta:.04,steadyRefMs:100,edgePeakFrac:.4,shapeTolerance:.2,contentMin:.1});function Oi(i){let t=i!==null&&typeof i=="object"?i:{},e={...J};for(let o of Object.keys(J)){let n=t[o];typeof n=="number"&&Number.isFinite(n)&&n>=0&&n<=1e6&&(e[o]=n)}return e}var ct=class{constructor(t=J){this.t=t;this.goodSince=null;this.steadySince=null;this.last=null}reset(){this.goodSince=null,this.steadySince=null,this.last=null}tick(t,e){let o=this.t,n=o.shapeTolerance<=0||Math.abs(t.shape-1)<=o.shapeTolerance,s=t.edgeConfidence>=o.edgeConfidenceMin&&n&&t.content>=o.contentMin,r=t.fill>=o.fillMin&&t.fill<=o.fillMax,c=Math.abs(t.offsetX)<=o.offsetMax&&Math.abs(t.offsetY)<=o.offsetMax,a=t.cardGlare<=o.glareMax,l=t.sharpness>=o.sharpnessMin,u=this.last;this.last={fill:t.fill,offsetX:t.offsetX,offsetY:t.offsetY,at:e};let d=u!==null&&o.steadyRefMs>0?Math.min(3,Math.max(1,(e-u.at)/o.steadyRefMs)):1,m=s&&a&&l&&t.fill>=o.steadyFillMin&&t.fill<=o.steadyFillMax&&u!==null&&Math.abs(t.fill-u.fill)<=o.steadyFillDelta*d&&Math.abs(t.offsetX-u.offsetX)<=o.steadyOffsetDelta*d&&Math.abs(t.offsetY-u.offsetY)<=o.steadyOffsetDelta*d,h=s&&r&&c&&a&&l,f;if(s?a?t.fill<o.fillMin?f="too_small":t.fill>o.fillMax?f="too_big":l?c?f="locking":f="off_center":f="blurry":f="glare":f="no_card",h){if(m&&(this.steadySince??(this.steadySince=e)),this.goodSince??(this.goodSince=e),e-this.goodSince>=o.lockMs)return{detected:s,ready:!0,via:"good",blocker:"locking"};let g=this.steadySince!==null&&e-this.steadySince>=o.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:"locking"}}if(this.goodSince=null,m){this.steadySince??(this.steadySince=e);let g=e-this.steadySince>=o.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:g?"locking":"steadying"}}return this.steadySince=null,{detected:s,ready:!1,via:null,blocker:f}}};var q=null;async function ai(i){return q===null&&(q=(await import("./detector-scanic-LYXXX77M.js")).detectQuad),q(i)}async function ci(i){let t=te(i);return t===null?null:{topLeft:{x:t.x,y:t.y},topRight:{x:t.x+t.width,y:t.y},bottomRight:{x:t.x+t.width,y:t.y+t.height},bottomLeft:{x:t.x,y:t.y+t.height}}}function Ji(){q===null&&import("./detector-scanic-LYXXX77M.js").then(i=>{q=i.detectQuad}).catch(()=>{})}var Ee=4e3,li=2,Le=3,ui=Object.freeze({LOW:3,MID:5,HIGH:6}),xt=Object.freeze({manualShutterMs:6e3,detectedNoLockMs:1950});function qi(i){let t=i!==null&&typeof i=="object"?i:{},e=(o,n,s)=>typeof o=="number"&&Number.isFinite(o)&&o>=n&&o<=s?o:void 0;return{manualShutterMs:e(t.manualShutterMs,1e3,6e4)??xt.manualShutterMs,detectedNoLockMs:e(t.steadyMs,300,3e4)!==void 0?t.steadyMs+(e(t.lockMs,0,1e4)??450):xt.detectedNoLockMs}}var Oe=class i{constructor(t){this.torchOn=!1;this.stillRefusals=0;this.zoom=1;this.positioningSince=null;this.detectedSince=null;this.lastSeenAt=null;this.lastGuideQuad=null;this.lastOcrReady=null;this.shutterOffered=!1;this.stats=i.freshStats();this.handlers=new Map;this.stream=null;this.timer=null;this.state="idle";this.lastGuidance=null;this.attempt=0;this.capturing=!1;this.feedback=new ot;this.lastFeedbackKey=null;this.lastQuad=null;this.lastDetect=null;this.frameWatch=null;this.reopened=!1;this.lit=!1;this.blackTicks=0;this.offEnded=null;this.opts=t,this.gate=new ne(t.format??"ID-1",t.thresholds);let e=t.deviceClass??jt(Xt());this.deviceClass=e,this.camera=t.camera??st,this.shutterTuning=t.shutter??xt,this.guideTuning=t.guideLock??J,this.guideLock=new ct(this.guideTuning),this.cadenceMs=1e3/ui[e]}on(t,e){let o=this.handlers.get(t);return o||(o=new Set,this.handlers.set(t,o)),o.add(e),()=>o?.delete(e)}emit(t,e){for(let o of[...this.handlers.get(t)??[]])o(e)}async start(){let t=this.state==="error"?this.resumePlayback():null,e=++this.attempt;if(this.clearFrameWatch(),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.lit=!1,this.blackTicks=0,t!==null&&await t&&e===this.attempt){this.setState("positioning"),this.scheduleTick(e),this.watchFrames(e);return}if(e===this.attempt){this.releaseStream(),Kt(),this.setState("preflight");try{let o=this.opts.getUserMedia??(r=>navigator.mediaDevices.getUserMedia(r));this.setState("acquiring");let n=this.opts.enumerateDevices??(this.opts.getUserMedia===void 0&&typeof navigator<"u"&&navigator.mediaDevices?.enumerateDevices?()=>navigator.mediaDevices.enumerateDevices():void 0),s=await Te({getUserMedia:o,...n!==void 0?{enumerateDevices:n}:{},lensSelection:this.camera.lensSelection,base:ue});if(e!==this.attempt){for(let r of s.stream.getTracks())r.stop();return}if(this.stream=s.stream,Wt(this.stream),Ht(this.stream),this.watchEnded(e),this.opts.upgradeResolution!==!1&&await this.upgradeResolution(),e!==this.attempt||(await this.applyFocusAndZoom(),e!==this.attempt)||(this.opts.video.srcObject=this.stream,await this.opts.video.play().catch(()=>{}),e!==this.attempt))return;this.setState("positioning"),this.scheduleTick(e),this.watchFrames(e)}catch(o){if(e!==this.attempt)return;let n=Ut(o),s=Bt(o);this.setState("error"),this.emit("error",{kind:n,retryable:!0,detail:s===void 0?{phase:"acquiring"}:{phase:"acquiring",name:s}})}}}resumePlayback(){let t=this.opts.video,e=this.videoTrack();if(this.stream===null||e===null||e.readyState!=="live"||t.srcObject!==this.stream)return null;try{return Promise.resolve(t.play()).then(()=>this.framesNow(),()=>!1)}catch{return null}}framesNow(){let t=this.opts.video;return this.opts.hasFrames!==void 0?this.opts.hasFrames(t):!t.paused&&t.readyState>=2&&t.videoWidth>0}watchFrames(t){let e=this.opts.firstFrameMs??Ee;e<=0||(this.clearFrameWatch(),this.frameWatch=setTimeout(()=>{if(this.frameWatch=null,!(t!==this.attempt||this.state!=="positioning")){if(this.framesNow()&&this.blackTicks<Le){this.reopened=!1;return}this.cameraDead(t)}},e))}clearFrameWatch(){this.frameWatch!==null&&clearTimeout(this.frameWatch),this.frameWatch=null}watchEnded(t){this.offEnded?.(),this.offEnded=null;let e=this.videoTrack();if(e===null||typeof e.addEventListener!="function")return;let o=()=>{t===this.attempt&&(this.state==="positioning"||this.state==="acquiring")&&this.cameraDead(t)};e.addEventListener("ended",o),this.offEnded=()=>e.removeEventListener?.("ended",o)}cameraDead(t){if(t!==this.attempt)return;let e=this.videoTrack(),o=e!==null&&e.readyState==="live"&&!e.muted&&this.opts.video.paused&&!this.framesNow();if(!o&&!this.reopened){this.reopened=!0,this.start();return}this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.clearFrameWatch(),o||this.releaseStream(),this.reopened=!1,this.setState("error"),this.emit("error",{kind:"generic",retryable:!0,detail:{phase:"acquiring"}})}releaseStream(){if(this.offEnded?.(),this.offEnded=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject!==null&&this.opts.video.srcObject!==void 0&&(this.opts.video.srcObject=null)}rearm(t){t!==void 0&&(this.opts.side=t),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.stillRefusals=0,this.state==="captured"&&(this.setState("positioning"),this.scheduleTick(this.attempt))}async captureNow(){if(this.state!=="positioning"||this.capturing)return;let t=this.opts.video,e=this.lastDetect?.width??Math.max(1,t.videoWidth),o=this.lastDetect?.height??Math.max(1,t.videoHeight),n=this.lastQuad??this.lastGuideQuad??{topLeft:{x:0,y:0},topRight:{x:e,y:0},bottomRight:{x:e,y:o},bottomLeft:{x:0,y:o}},s=(this.opts.now??(()=>performance.now()))(),r=this.feedback.force("processing",s);this.lastFeedbackKey=r.key,this.emit("feedback",r),await this.fire(this.attempt,this.lastOcrReady!==null?this.lastOcrReady.quad:n,{width:e,height:o,tickSharpness:this.lastDetect?.tickSharpness??0},this.lastOcrReady?.via??"manual")}captureReport(){let t=this.stats;return{...this.opts.side!==void 0?{side:this.opts.side}:{},format:this.opts.format??"ID-1",deviceClass:this.deviceClass,video:{width:this.opts.video.videoWidth||0,height:this.opts.video.videoHeight||0},zoom:this.zoom,...t.zoomFallbackAtMs!==void 0?{zoomFallbackAtMs:t.zoomFallbackAtMs}:{},...t.msToCapture!==void 0?{msToCapture:t.msToCapture}:{},...t.via!==void 0?{via:t.via}:{},...t.shutterAtMs!==void 0?{shutterAtMs:t.shutterAtMs}:{},...t.shutterReason!==void 0?{shutterReason:t.shutterReason}:{},ticks:t.ticks,quadFraming:{...t.quadFraming},qualityBlockers:{...t.qualityBlockers},guideBlockers:{...t.guideBlockers},stillRefusals:t.stillRefusals,...this.ocrReport()}}ocrReport(){let t=this.opts.ocr;if(t===void 0)return{};let e=(this.opts.format??"ID-1")==="ID-3"||this.opts.side==="single"?"single":this.opts.side==="verso"?"verso":"recto",o=t.report(e,this.stats.via,(this.opts.now??(()=>performance.now()))());return o===null?{}:{ocr:o}}static freshStats(){return{ticks:0,quadFraming:{},qualityBlockers:{},guideBlockers:{},stillRefusals:0}}setGuide(t){t===void 0?delete this.opts.guide:this.opts.guide=t,this.guideLock.reset()}guideRegion(t){let e=t.width/Math.max(1,t.height),o=this.opts.guide;if(o!==void 0&&o.viewAspect>0){let c={width:o.viewAspect,height:1},a={x:o.rect.x*o.viewAspect,y:o.rect.y,width:o.rect.width*o.viewAspect,height:o.rect.height};return Fe(c,a,e,0)}let n=Zt(this.opts.format??"ID-1").center,s=.86,r=s*e/n;return r>.84&&(r=.84,s=r*n/e),{x:(1-s)/2,y:(1-r)/2,width:s,height:r}}resetSide(){this.positioningSince=null,this.detectedSince=null,this.lastSeenAt=null,this.guideLock.reset(),this.lastGuideQuad=null,this.lastOcrReady=null,this.opts.ocr?.reset(),this.stats=i.freshStats(),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}withdrawShutter(){this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}zoomFallback(t){let e=this.videoTrack();if(e===null||this.zoom<=1)return;let o=this.focusCaps(),n=typeof o?.zoom?.min=="number"?Math.max(o.zoom.min,1):1;this.zoom=n,this.stats.zoomFallbackAtMs=Math.round(t-(this.positioningSince??t)),this.guideLock.reset(),this.gate.reset(),e.applyConstraints({advanced:[{zoom:n}]}).catch(()=>{})}offerShutter(t,e){this.shutterOffered||(this.shutterOffered=!0,this.stats.shutterAtMs=Math.round(e-(this.positioningSince??e)),this.stats.shutterReason=t,this.emit("shutter",{available:!0,reason:t}))}torchAvailable(){try{return this.stream?.getVideoTracks?.()[0]?.getCapabilities?.()?.torch===!0}catch{return!1}}async setTorch(t){this.torchOn=t;try{await this.stream?.getVideoTracks?.()[0]?.applyConstraints({advanced:[{torch:t}]})}catch{}}destroy(){if(this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.clearFrameWatch(),this.offEnded?.(),this.offEnded=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject=null}async upgradeResolution(){try{let t=this.stream?.getVideoTracks?.()[0];if(t===void 0)return;let e=t.getSettings?.()??{},o=me(t.getCapabilities?.(),{width:e.width??0,height:e.height??0},this.deviceClass,{width:this.camera.width,height:this.camera.height},this.opts.ocr?.liveMrzOn===!0?{fill:this.guideRegion({width:1080,height:1920}).width}:void 0);o!==null&&await t.applyConstraints(o)}catch{}}focusCaps(){try{return this.videoTrack()?.getCapabilities?.()??null}catch{return null}}async applyFocusAndZoom(){let t=this.videoTrack();if(t===null)return;let e=this.focusCaps();this.camera.continuousFocus&&rt(e,"continuous")&&await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{});let o={width:0,height:0};try{let s=t.getSettings?.()??{};o={width:s.width??0,height:s.height??0}}catch{}let n=_e(e,o,this.opts.format??"ID-1",this.camera);if(n>1)try{await t.applyConstraints({advanced:[{zoom:n}]}),this.zoom=n}catch{this.zoom=1}}async focusAt(t,e){let o=this.videoTrack(),n=kt(this.focusCaps(),t,e);if(!(o===null||n===null))try{await o.applyConstraints({advanced:[n]}),(this.opts.setTimer??setTimeout)(()=>{this.restoreContinuous()},1500)}catch{}}async restoreContinuous(){let t=this.videoTrack();t===null||!this.camera.continuousFocus||!rt(this.focusCaps(),"continuous")||await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})}async refocusOn(t,e){let o=this.camera.refocusBeforePhotoMs,n=this.videoTrack();if(o<=0||n===null||e.width<=0||e.height<=0)return;let s=E(t),r=kt(this.focusCaps(),(s.x+s.width/2)/e.width,(s.y+s.height/2)/e.height);if(r!==null)try{await n.applyConstraints({advanced:[r]});let c=this.opts.setTimer??setTimeout;await new Promise(a=>{c(()=>a(),o)})}catch{}}videoTrack(){try{return this.stream?.getVideoTracks?.()[0]??null}catch{return null}}async takeStill(t,e,o){if(this.opts.captureStill!==void 0)return this.opts.captureStill(this.opts.video,t,e);let n=this.opts.format??"ID-1",s=this.videoTrack();if(o&&this.opts.photoCapture!==!1&&this.deviceClass!=="LOW"&&!this.torchOn&&s!==null&&ke(s)){await this.refocusOn(t,e);let r=await we(this.opts.video,t,e,n,{track:s,detect:this.detector(),detectWidth:et});if(this.restoreContinuous(),r!==null)return r}return De(this.opts.video,t,e,n)}detector(){return this.opts.detect??((this.opts.format??"ID-1")==="ID-3"?ci:ai)}setState(t){this.state=t,this.emit("statechange",{state:t})}scheduleTick(t){let e=this.opts.setTimer??setTimeout;this.timer=e(()=>{this.tick(t)},this.cadenceMs)}async tick(t){if(t!==this.attempt||this.state!=="positioning"||this.capturing)return;let e=this.opts.now??(()=>performance.now()),o=this.opts.grabDetectFrame??Pe,n=this.detector(),s=o(this.opts.video,et);if(s===null){this.scheduleTick(t);return}if(!this.lit){if(dt(s)>li)this.lit=!0,this.blackTicks=0;else if(++this.blackTicks>=Le&&this.frameWatch===null&&(this.opts.firstFrameMs??Ee)>0){this.cameraDead(t);return}}let r=null;try{r=await n(s)}catch{r=null}if(t!==this.attempt)return;let c=r!==null?lt(s,r):s,a=e(),l={sharpness:j(c),exposure:Yt(c),meanLuma:dt(c),specularFraction:ae(c)},u=ce({format:this.opts.format??"ID-1",quad:r,frameWidth:s.width,frameHeight:s.height,measures:l,...this.opts.thresholds!==void 0?{thresholds:this.opts.thresholds}:{}}),d=this.gate.tick({timestampMs:a,quad:r,quality:l,frameWidth:s.width,frameHeight:s.height}),h=(this.opts.format??"ID-1")!=="ID-3"?Ce(s,this.guideRegion(s),{edgePeakFrac:this.guideTuning.edgePeakFrac}):Z,f=this.guideLock.tick(h,a);this.lastGuideQuad=f.detected?Ae(h):null;let g=this.capturing?null:this.ocrTick(s,r,h,f.detected,u,a);this.positioningSince??(this.positioningSince=a);let y=this.stats;if(y.ticks+=1,y.quadFraming[u.framing]=(y.quadFraming[u.framing]??0)+1,u.framing==="ok"&&!d.ready){let T=u.lighting!=="ok"?u.lighting:u.glare!=="ok"?"glare":u.blur!=="ok"?"blurry":"steadying";y.qualityBlockers[T]=(y.qualityBlockers[T]??0)+1}y.guideBlockers[f.blocker]=(y.guideBlockers[f.blocker]??0)+1,r!==null||f.detected?(this.detectedSince??(this.detectedSince=a),this.lastSeenAt=a):this.detectedSince=null,this.lastSeenAt!==null&&a-this.lastSeenAt<=bi?a-this.positioningSince>=this.shutterTuning.manualShutterMs?this.offerShutter("timeout",a):g?.suspendQuality!==!0&&this.detectedSince!==null&&a-this.detectedSince>=this.shutterTuning.detectedNoLockMs&&this.offerShutter("detected_no_lock",a):this.withdrawShutter();let O=a-(this.lastSeenAt??this.positioningSince);this.zoom>1&&this.camera.zoomFallbackMs>0&&O>=this.camera.zoomFallbackMs&&this.zoomFallback(a),this.emit("checks",{engine:"docv1",p:d.p,plausible:d.plausible,stableTicks:d.stableTicks,quad:d.quad,frameWidth:s.width,frameHeight:s.height,analysis:u,ready:g?.suspendQuality!==!0&&(d.ready&&r!==null||f.ready&&this.lastGuideQuad!==null)||this.lastOcrReady!==null,guide:{detected:f.detected,blocker:f.blocker,fill:h.fill,shape:h.shape,content:h.content,offsetX:h.offsetX,offsetY:h.offsetY},...g!==null&&g.mode!=="off"?{ocr:{mode:g.mode,...g.mrz?{mrz:g.mrz}:{},...g.lock?{lock:g.lock}:{}}}:g?.mrz?{ocr:{mode:g.mode,mrz:g.mrz}}:{}}),this.lastQuad=d.plausible?r:null,this.lastDetect={width:s.width,height:s.height,tickSharpness:l.sharpness};let v=se(u);u.framing!=="ok"&&f.detected&&(v=gi(f.blocker,h.brightness<this.guideTuning.darkBrightness)),v==="blurry"&&r!==null&&di(r,s,this.opts.format??"ID-1")>=this.camera.focusFarFillFrac&&(v="focus_far"),v==="sensing"&&this.zoom>1&&this.camera.noDocFarHintMs>0&&O>=this.camera.noDocFarHintMs&&(v="focus_far");let D=this.feedback.tick(v,a);if(D.key!==this.lastFeedbackKey&&(this.lastFeedbackKey=D.key,this.emit("feedback",D)),d.guidanceKey!==this.lastGuidance&&(this.lastGuidance=d.guidanceKey,this.emit("guidance",{key:d.guidanceKey})),this.capturing)return;let M=g?.suspendQuality!==!0,_=M&&d.ready&&r!==null,k=M&&f.ready&&this.lastGuideQuad!==null,C=this.lastOcrReady;if(C!==null&&this.opts.autoCapture!==!1){let T=this.feedback.force("processing",a);this.lastFeedbackKey=T.key,this.emit("feedback",T);let A=j(lt(s,C.quad));await this.fire(t,C.quad,{width:s.width,height:s.height,tickSharpness:A},C.via);return}if((_||k)&&this.opts.autoCapture!==!1){let T=this.feedback.force("processing",a);this.lastFeedbackKey=T.key,this.emit("feedback",T);let A=k?this.lastGuideQuad:r,B=k?f.via==="steady"?"guide_steady":"guide_good":"quad",U=k?j(lt(s,A)):l.sharpness;await this.fire(t,A,{width:s.width,height:s.height,tickSharpness:U},B);return}this.scheduleTick(t)}async fire(t,e,o,n){this.capturing=!0;let s=this.opts.grabDetectFrame??Pe,r=this.opts.setTimer??setTimeout,c={width:o.width,height:o.height};try{let a={still:await this.takeStill(e,c,!0),sharpness:o.tickSharpness};if(t!==this.attempt)return;let l=a.still.source==="photo"?0:mi;for(let m=0;m<l;m++){if(await new Promise(g=>{r(()=>g(),fi)}),t!==this.attempt)return;let h=s(this.opts.video,et);if(h===null)continue;let f=j(lt(h,e));if(f>a.sharpness*pi){let g=await this.takeStill(e,c,!1);if(t!==this.attempt)return;a={still:g,sharpness:f}}}if(t!==this.attempt)return;let u=a.still.sharpness;if(this.opts.autoCapture!==!1&&n!=="manual"&&typeof u=="number"&&u>=0&&u<this.camera.stillSharpnessMin&&this.stillRefusals<this.camera.stillRefusalsMax){this.stillRefusals+=1,this.stats.stillRefusals+=1,this.guideLock.reset(),this.lastOcrReady=null,(n==="text_lock"||n==="live_mrz")&&this.opts.ocr?.rearmFace();let m=(this.opts.now??(()=>performance.now()))(),h=this.feedback.force("focus_far",m);this.lastFeedbackKey=h.key,this.emit("feedback",h),this.capturing=!1,this.gate.reset(),this.scheduleTick(t);return}this.stillRefusals=0;let d=(this.opts.now??(()=>performance.now()))();this.stats.via=n,this.stats.msToCapture=Math.round(d-(this.positioningSince??d)),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1})),this.setState("captured"),this.emit("artifacts",{keyframe:a.still.blob,previewDataUrl:a.still.previewDataUrl,...this.opts.side!==void 0?{side:this.opts.side}:{},...a.still.docRegion!==void 0?{docRegion:a.still.docRegion}:{},...(()=>{let m=n==="live_mrz"?this.opts.ocr?.liveCapture():null;return m?{liveMrz:m}:{}})()})}catch{if(t!==this.attempt)return;this.capturing=!1,this.gate.reset(),this.guideLock.reset(),this.lastOcrReady=null,(n==="text_lock"||n==="live_mrz")&&this.opts.ocr?.rearmFace(),this.scheduleTick(t)}}ocrTick(t,e,o,n,s,r){let c=this.opts.ocr,a=this.opts.video;if(c===void 0||!c.hasEngine)return this.lastOcrReady=null,null;let l=a.videoWidth,u=a.videoHeight;if(l<=0||u<=0||t.width<=0||t.height<=0)return null;let m=(this.opts.format??"ID-1")==="ID-3",h=this.guideRegion(t),f={x:h.x*l,y:h.y*u,w:h.width*l,h:h.height*u},g=l/t.width,y=u/t.height,x;m&&e!==null?x=hi(E(e),g,y,l,u):x=ee(f,c.bandTop,u);let w=m?s.glare==="ok":o.cardGlare<=this.guideTuning.glareMax,O=m?s.blur==="ok":o.sharpness>=this.guideTuning.sharpnessMin,v=c.tick({atMs:r,video:a,mrzFace:m||this.opts.side==="verso"||this.opts.side==="single",present:m||e!==null||n,card:f,band:x,portrait:u>l,glareOk:w,sharpOk:O});if(v.ready&&v.via!==void 0){let D=m?e??Ie(h,t):this.lastGuideQuad??Ie(h,t);this.lastOcrReady={quad:D,via:v.via}}else this.lastOcrReady=null;return v}};function hi(i,t,e,o,n){let s=Math.min(o,i.width*1.06*t),r=Math.min(n,Math.max(i.height*1.6*e,s/5)),c=(i.y+i.height/2)*e,a=Math.max(0,Math.min(o-s,(i.x-i.width*.03)*t)),l=Math.max(0,Math.min(n-r,c-r/2));return{x:a,y:l,w:s,h:r}}function Ie(i,t){let e=i.x*t.width,o=i.y*t.height,n=(i.x+i.width)*t.width,s=(i.y+i.height)*t.height;return{topLeft:{x:e,y:o},topRight:{x:n,y:o},bottomRight:{x:n,y:s},bottomLeft:{x:e,y:s}}}function di(i,t,e){let o=E(i);return t.width<=0||t.height<=0?0:e==="ID-3"?o.width/t.width:o.width*o.height/(t.width*t.height)}var mi=2,fi=260,pi=1.08;function Pe(i,t){let e=i.videoWidth,o=i.videoHeight;if(e===0||o===0)return null;let n=Math.min(1,t/e),s=Math.round(e*n),r=Math.round(o*n),c=document.createElement("canvas");c.width=s,c.height=r;let a=c.getContext("2d",{willReadFrequently:!0});return a===null?null:(e/Math.max(1,s)>4&&(a.imageSmoothingQuality="high"),a.drawImage(i,0,0,s,r),a.getImageData(0,0,s,r))}function lt(i,t){let e=[t.topLeft.x,t.topRight.x,t.bottomRight.x,t.bottomLeft.x],o=[t.topLeft.y,t.topRight.y,t.bottomRight.y,t.bottomLeft.y],n=Math.max(0,Math.floor(Math.min(...e))),s=Math.max(0,Math.floor(Math.min(...o))),r=Math.min(i.width,Math.ceil(Math.max(...e))),c=Math.min(i.height,Math.ceil(Math.max(...o))),a=Math.max(1,r-n),l=Math.max(1,c-s),u=new Uint8ClampedArray(a*l*4);for(let d=0;d<l;d++){let m=((s+d)*i.width+n)*4;u.set(i.data.subarray(m,m+a*4),d*a*4)}return{data:u,width:a,height:l,colorSpace:i.colorSpace}}function gi(i,t){return i==="glare"?"glare":i==="too_small"?"too_far":i==="too_big"?"too_close":t?"too_dark":i==="blurry"?"blurry":i==="off_center"?"edge_clipped":i==="no_card"?"sensing":"hold_still"}var bi=1200;export{it as a,se as b,ot as c,je as d,ae as e,Ye as f,ce as g,st as h,Ri as i,yt as j,si as k,ve as l,rt as m,kt as n,Ci as o,_e as p,ri as q,Te as r,Z as s,Fe as t,Ce as u,Ae as v,J as w,Oi as x,ct as y,Ji as z,Ee as A,li as B,Le as C,ui as D,xt as E,qi as F,Oe as G,hi as H,mi as I,fi as J};
@@ -1 +0,0 @@
1
- import{a as z,b as S,e as R}from"./chunk-ISMVEF7H.js";var V=1e3,_=[[1,0],[0,1],[1,1],[1,-1]];function L(i){let{width:t,height:e,data:r}=i;if(t<16||e<16)return-1;let s=new Uint8Array(t*e);for(let a=0,o=0;a<s.length;a+=1,o+=4)s[a]=Math.round(.299*(r[o]??0)+.587*(r[o+1]??0)+.114*(r[o+2]??0));let l=-1;for(let[a,o]of _){let n=new Uint32Array(256),c=new Float64Array(256),b=0;for(let h=1;h<e-1;h+=1){let u=h*t,I=(h+o)*t,A=(h-o)*t;for(let M=1;M<t-1;M+=1){let y=s[I+M+a]??0,T=s[A+M-a]??0,k=Math.abs(y-T);n[k]=(n[k]??0)+1,c[k]=(c[k]??0)+Math.abs(y+T-2*(s[u+M]??0)),b+=1}}let v=Math.max(1,Math.floor(b/20)),d=0,m=0,f=0;for(let h=255;h>=0&&d<v;h-=1){let u=n[h]??0;d+=u,m+=u*h,f+=c[h]??0}if(m===0)return 0;let p=f/m;l=l<0?p:Math.min(l,p)}return l}var E=.06;function W(i,t,e,r=E){if(i===null||t.width<=0||t.height<=0)return null;let s=[i.topLeft,i.topRight,i.bottomRight,i.bottomLeft],l=e.width/t.width,a=e.height/t.height,o=Math.min(...s.map(u=>u.x))*l,n=Math.max(...s.map(u=>u.x))*l,c=Math.min(...s.map(u=>u.y))*a,b=Math.max(...s.map(u=>u.y))*a,v=(n-o)*r,d=(b-c)*r,m=Math.max(0,Math.floor(o-v)),f=Math.max(0,Math.floor(c-d)),p=Math.min(e.width,Math.ceil(n+v)),h=Math.min(e.height,Math.ceil(b+d));return p-m<16||h-f<16?null:{x:m,y:f,width:p-m,height:h-f}}function F(i,t){let e=new Uint8ClampedArray(t.width*t.height*4);for(let r=0;r<t.height;r+=1)for(let s=0;s<t.width*4;s+=1)e[r*t.width*4+s]=i.data[((t.y+r)*i.width+t.x)*4+s]??0;return{data:e,width:t.width,height:t.height}}function D(i,t=1e3){let e=t/Math.max(i.width,i.height);if(e>=1)return i;let r=Math.max(1,Math.round(i.width*e)),s=Math.max(1,Math.round(i.height*e)),l=new Uint8ClampedArray(r*s*4);for(let a=0;a<s;a+=1){let o=Math.floor(a/e),n=Math.min(i.height,Math.max(o+1,Math.floor((a+1)/e)));for(let c=0;c<r;c+=1){let b=Math.floor(c/e),v=Math.min(i.width,Math.max(b+1,Math.floor((c+1)/e)));for(let d=0;d<3;d+=1){let m=0;for(let f=o;f<n;f+=1)for(let p=b;p<v;p+=1)m+=i.data[(f*i.width+p)*4+d]??0;l[(a*r+c)*4+d]=m/((n-o)*(v-b))}l[(a*r+c)*4+3]=255}}return{data:l,width:r,height:s}}function B(i,t){return L(D(t===null?i:F(i,t)))}function Q(i,t){let e=t??{x:0,y:0,width:i.width,height:i.height},r=Math.min(1,1e3/Math.max(e.width,e.height)),s=Math.max(1,Math.round(e.width*r)),l=Math.max(1,Math.round(e.height*r)),a=document.createElement("canvas");a.width=s,a.height=l;try{let o=a.getContext("2d",{willReadFrequently:!0});return o===null?-1:(o.imageSmoothingQuality="high",o.drawImage(i,e.x,e.y,e.width,e.height,0,0,s,l),L(o.getImageData(0,0,s,l)))}catch{return-1}finally{a.width=0,a.height=0}}var g=class{constructor(t=2){this.stableReads=t;this.last=null;this.run=0}offer(t){return t===null?(this.reset(),!1):(this.run=t===this.last?this.run+1:1,this.last=t,this.run>=this.stableReads)}reset(){this.last=null,this.run=0}};var N=Object.freeze({...z,minIntervalMs:150,maxWidthPx:480,detectorLimit:960,searchTimeoutMs:12e3}),O=Object.freeze({detectorLimit:960,bandMaxWidthPx:1280,minBandWidthPx:900,bandTop:.55,minIntervalMs:150,stableReads:2,profileReads:5,maxReadMs:1200,searchTimeoutMs:12e3}),P=()=>typeof document>"u"||document.visibilityState!=="hidden",C=(i,t,e)=>createImageBitmap(i,Math.round(t.x),Math.round(t.y),Math.max(1,Math.round(t.w)),Math.max(1,Math.round(t.h)),{resizeWidth:Math.max(1,Math.round(Math.min(t.w,e))),resizeQuality:"high"}),x=(i,t)=>{if(i.length===0)return 0;let e=[...i].sort((r,s)=>r-s);return e[Math.min(e.length-1,Math.floor(e.length*t))]};function G(i){return i<=250?"fast":i<=600?"mid":"slow"}function Z(i,t,e){let r=i.y+i.h*t,s=Math.min(e,i.y+i.h*1.05);return{x:i.x,y:r,w:i.w,h:Math.max(1,s-r)}}var w=class{constructor(t){this.o=t;this.engine=null;this.tier=null;this.gen=0;this.ticksSinceRead=Number.POSITIVE_INFINITY;this.hiddenSince=null;this.inFlight=!1;this.lastReadAt=Number.NEGATIVE_INFINITY;this.firstSeen=null;this.reads=0;this.times=[];this.mrzState={state:"searching"};this.lockState={state:"searching"};this.fallback=null;this.lockOff=!1;this.lockError=!1;this.fired=null;this.valid=null;this.faceMode="off";this.disabled=!1;this.crop=t.crop??C,this.visible=t.visible??P,this.mrzGate=new g(t.liveMrz?.stableReads??2),this.lockGate=new S(t.textLock??N)}setEngine(t,e){this.engine=t,e!==void 0&&(this.tier=e)}liveCadence(t){let e=this.tier===null?null:R[this.tier];return{stride:e?.stride??1,bandWidthPx:Math.min(t.bandMaxWidthPx,e?.bandWidthPx??t.bandMaxWidthPx)}}get bandTop(){return this.o.liveMrz?.bandTop??O.bandTop}get liveMrzOn(){return this.o.liveMrz!==null}get hasEngine(){return this.engine!==null&&!this.disabled}reset(){this.gen++,this.inFlight=!1,this.lastReadAt=Number.NEGATIVE_INFINITY,this.ticksSinceRead=Number.POSITIVE_INFINITY,this.hiddenSince=null,this.firstSeen=null,this.reads=0,this.times=[],this.mrzGate.reset(),this.lockGate.reset(),this.mrzState={state:"searching"},this.lockState={state:"searching"},this.fallback=null,this.lockOff=!1,this.lockError=!1,this.fired=null,this.valid=null,this.faceMode="off"}rearmFace(){this.gen++,this.inFlight=!1,this.lastReadAt=Number.NEGATIVE_INFINITY,this.ticksSinceRead=Number.POSITIVE_INFINITY,this.mrzGate.reset(),this.lockGate.reset(),this.fired=null,this.valid=null,this.fallback===null&&(this.mrzState={state:"searching"}),this.lockOff||(this.lockState={state:"searching"})}liveCapture(){return this.fired?.via==="live_mrz"?this.valid:null}modeFor(t){return this.engine===null||this.disabled?"off":t.mrzFace&&this.o.liveMrz!==null&&this.fallback===null?"live_mrz":this.o.textLock!==null&&!this.lockOff?"text_lock":"off"}tick(t){let e=this.modeFor(t);return e!=="off"&&(this.faceMode=e),this.fired!==null?{ready:!0,via:this.fired.via,suspendQuality:this.fired.via==="live_mrz",mode:e,...this.states()}:e!=="off"&&!this.visible()?(this.hiddenSince??(this.hiddenSince=t.atMs),this.mrzGate.reset(),{ready:!1,suspendQuality:e==="live_mrz"&&this.fallback===null,mode:e,...this.states()}):(this.hiddenSince!==null&&(this.firstSeen!==null&&(this.firstSeen+=t.atMs-this.hiddenSince),this.hiddenSince=null),e==="live_mrz"?this.liveTick(t,this.o.liveMrz):e==="text_lock"?this.lockTick(t,this.o.textLock):{ready:!1,suspendQuality:!1,mode:e,...this.states()})}states(){return{...this.faceMode==="live_mrz"||this.fallback!==null?{mrz:this.fallback!==null?{state:"fallback",reason:this.fallback}:this.mrzState}:{},...this.faceMode==="text_lock"?{lock:this.lockState}:{}}}canRead(t,e){let r=this.engine;return r!==null&&!this.inFlight&&!r.busy&&t-this.lastReadAt>=e}fall(t){this.fallback=t,this.mrzGate.reset()}liveTick(t,e){let r=()=>this.fallback!==null?{ready:!1,suspendQuality:!1,mode:"live_mrz",mrz:{state:"fallback",reason:this.fallback}}:{ready:!1,suspendQuality:!0,mode:"live_mrz",mrz:this.mrzState};if(!t.present||t.band===null)return this.mrzGate.reset(),this.mrzState={state:"searching"},r();if(this.firstSeen??(this.firstSeen=t.atMs),t.atMs-this.firstSeen>e.searchTimeoutMs)return this.fall("timeout"),r();if(t.band.w<e.minBandWidthPx)return t.card!==null&&t.card.w<e.minBandWidthPx?(this.fall("unsupported"),r()):(this.mrzState={state:"reading",coach:t.portrait?"turnSideways":"moveCloser"},{ready:!1,suspendQuality:!1,mode:"live_mrz",mrz:this.mrzState});let s=this.liveCadence(e);if(this.ticksSinceRead++,this.ticksSinceRead<s.stride||!this.canRead(t.atMs,e.minIntervalMs))return r();this.inFlight=!0,this.lastReadAt=t.atMs,this.ticksSinceRead=0;let l=this.gen,a=this.engine,o=t.glareOk?t.sharpOk?void 0:"holdStill":"glare";return this.crop(t.video,t.band,s.bandWidthPx).then(n=>a.bandRead(n,e.detectorLimit)).then(n=>{if(l===this.gen){if(this.reads++,this.times.push(n.ms),this.times.length>8&&this.times.shift(),this.reads>=e.profileReads&&x(this.times,.5)>e.maxReadMs)return this.fall("slow");if(this.mrzGate.offer(n.valid?n.digest??null:null)&&n.format&&n.digest){this.valid={format:n.format,...n.documentCode!==void 0?{documentCode:n.documentCode}:{},digest:n.digest,lineCount:n.lineCount,framesToValid:this.reads,msToValid:Math.round(t.atMs-(this.firstSeen??t.atMs))},this.mrzState={state:"valid",format:n.format},this.fired={via:"live_mrz",at:t.atMs};return}this.mrzState={state:"reading",...o?{coach:o}:{},...n.format?{format:n.format}:{}}}}).catch(()=>{l===this.gen&&this.fall("error")}).finally(()=>{l===this.gen&&(this.inFlight=!1)}),r()}lockTick(t,e){let r=()=>({ready:!1,suspendQuality:!1,mode:"text_lock",lock:this.lockState,...this.fallback!==null?{mrz:{state:"fallback",reason:this.fallback}}:{}});if(!t.present||t.card===null)return this.lockGate.reset(),this.lockState={state:"searching"},r();if(this.firstSeen??(this.firstSeen=t.atMs),t.atMs-this.firstSeen>e.searchTimeoutMs)return this.lockOff=!0,r();if(!this.canRead(t.atMs,e.minIntervalMs))return r();this.inFlight=!0,this.lastReadAt=t.atMs;let s=this.gen,l=this.engine,a={glareOk:t.glareOk,sharpOk:t.sharpOk};return this.crop(t.video,t.card,e.maxWidthPx).then(o=>l.layoutRead(o,e.detectorLimit)).then(o=>{if(s!==this.gen)return;this.reads++,this.times.push(o.ms),this.times.length>8&&this.times.shift();let n=this.lockGate.offer(o,t.atMs,a);this.lockState=n.state==="locked"?{state:"locked"}:{state:n.state,...n.hint?{hint:n.hint}:{}},n.state==="locked"&&(this.fired={via:"text_lock",at:t.atMs})}).catch(()=>{s===this.gen&&(this.lockOff=!0,this.lockError=!0)}).finally(()=>{s===this.gen&&(this.inFlight=!1)}),r()}disable(){this.disabled=!0,this.reset()}report(t,e,r){let s=this.faceMode;if(s==="off")return null;let l=x(this.times,.5),a={capture:t,mode:s,reads:this.reads,...this.times.length>0?{readP50Ms:Math.round(l),readP90Ms:Math.round(x(this.times,.9)),deviceClass:G(l)}:{}};return s==="live_mrz"?this.fired?.via==="live_mrz"&&this.valid!==null&&e==="live_mrz"?{...a,outcome:"valid",format:this.valid.format,framesToValid:this.valid.framesToValid,msToValid:this.valid.msToValid}:this.fallback!==null?{...a,outcome:this.fallback}:{...a,outcome:r-(this.firstSeen??r)>=(this.o.liveMrz?.searchTimeoutMs??1/0)?"timeout":"off"}:this.fired?.via==="text_lock"?{...a,outcome:"locked",framesToLock:Math.max(1,this.reads),msToLock:Math.round(this.fired.at-(this.firstSeen??this.fired.at))}:{...a,outcome:this.lockError?"error":this.lockOff?"timeout":"off"}}};export{V as a,L as b,E as c,W as d,F as e,D as f,B as g,Q as h,N as i,O as j,Z as k,w as l};