@sekyro/web 0.1.0-rc.2 → 0.1.0-rc.21

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 (133) hide show
  1. package/CHANGELOG.md +313 -0
  2. package/LICENSE +25 -16
  3. package/README.md +111 -60
  4. package/THIRD-PARTY-NOTICES.txt +154 -0
  5. package/dist/background-monitor-A7FKJOAG.js +1 -0
  6. package/dist/camera-trait-45MJTW4K.js +1 -0
  7. package/dist/capture-constraints-B5omafmk.d.cts +44 -0
  8. package/dist/capture-constraints-B5omafmk.d.ts +44 -0
  9. package/dist/capture-session-doc-XBZGXWOP.js +1 -0
  10. package/dist/{capture-session-v3-CAoWM8iT.d.cts → capture-session-v3-26FgzBIl.d.cts} +185 -15
  11. package/dist/{capture-session-v3-BJ8ciaWl.d.ts → capture-session-v3-ZO0QOeQH.d.ts} +185 -15
  12. package/dist/chunk-234OZEDB.js +1 -0
  13. package/dist/chunk-33KKMPJ5.js +1 -0
  14. package/dist/chunk-53POX7U4.js +1 -0
  15. package/dist/chunk-7Q4YPMAF.js +1 -0
  16. package/dist/chunk-A3FUGHAH.js +2 -0
  17. package/dist/chunk-B2X33ZW2.js +1 -0
  18. package/dist/chunk-CJHMFPL6.js +1 -0
  19. package/dist/chunk-CQ7SKLMC.js +1 -0
  20. package/dist/chunk-DFTCAWMP.js +1 -0
  21. package/dist/chunk-DK5YPBDQ.js +1 -0
  22. package/dist/chunk-FPXL63KZ.js +1 -0
  23. package/dist/chunk-FUHDOEBP.js +1 -0
  24. package/dist/chunk-G6LKLN4U.js +1 -0
  25. package/dist/chunk-GI3UFGRQ.js +1 -0
  26. package/dist/chunk-GT2ZLGF7.js +1 -0
  27. package/dist/chunk-H3HVCWLF.js +1 -0
  28. package/dist/chunk-MXWLCDFX.js +1 -0
  29. package/dist/chunk-O5WKNZ2C.js +1 -0
  30. package/dist/chunk-OKWG3PVH.js +1 -0
  31. package/dist/chunk-P3H3D33O.js +1 -0
  32. package/dist/chunk-P6UP4UQY.js +1 -0
  33. package/dist/chunk-POIQGEZM.js +1 -0
  34. package/dist/chunk-QYYJLXKA.js +1 -0
  35. package/dist/chunk-RI3E7GBN.js +1 -0
  36. package/dist/chunk-SMKCBUJL.js +1 -0
  37. package/dist/chunk-SNACCYTL.js +1 -0
  38. package/dist/chunk-TDLIXFDT.js +1 -0
  39. package/dist/chunk-TQB3URP2.js +1 -0
  40. package/dist/chunk-VIAT4DEA.js +1 -0
  41. package/dist/chunk-ZADZTM3M.js +1 -0
  42. package/dist/chunk-ZNIZACXD.js +1 -0
  43. package/dist/client/index.cjs +1 -357
  44. package/dist/client/index.d.cts +6 -37
  45. package/dist/client/index.d.ts +6 -37
  46. package/dist/client/index.js +1 -15
  47. package/dist/core/index.cjs +1 -1605
  48. package/dist/core/index.d.cts +5 -4
  49. package/dist/core/index.d.ts +5 -4
  50. package/dist/core/index.js +1 -139
  51. package/dist/core/ocr/worker.bundle.js +42 -0
  52. package/dist/core/ocr/worker.cjs +42 -0
  53. package/dist/core/ocr/worker.d.cts +84 -0
  54. package/dist/core/ocr/worker.d.ts +84 -0
  55. package/dist/core/ocr/worker.js +41 -0
  56. package/dist/core/v3/detect-worker.cjs +1 -392
  57. package/dist/core/v3/detect-worker.d.cts +1 -1
  58. package/dist/core/v3/detect-worker.d.ts +1 -1
  59. package/dist/core/v3/detect-worker.js +1 -13
  60. package/dist/create-document-capture-23R2F47A.js +1 -0
  61. package/dist/create-portrait-capture-AGFHECK7.js +1 -0
  62. package/dist/create-verification-CXhXxknV.d.cts +3313 -0
  63. package/dist/create-verification-KlHIU4Fy.d.ts +3313 -0
  64. package/dist/{detect-worker-CKXHlXx9.d.cts → detect-worker-DclNxkZT.d.cts} +6 -0
  65. package/dist/{detect-worker-CKXHlXx9.d.ts → detect-worker-DclNxkZT.d.ts} +6 -0
  66. package/dist/detector-scanic-YCDNLCGV.js +1 -0
  67. package/dist/icao-gate-DI8VePWd.d.ts +566 -0
  68. package/dist/icao-gate-DvzOzHq6.d.cts +566 -0
  69. package/dist/icao-gate-T3BTOKFJ.js +1 -0
  70. package/dist/icao-policy-DztbA50-.d.ts +71 -0
  71. package/dist/icao-policy-MRB8NMAu.d.cts +71 -0
  72. package/dist/icao-tuning-4ETMF53W.js +1 -0
  73. package/dist/index.cjs +1 -2636
  74. package/dist/index.d.cts +110 -5
  75. package/dist/index.d.ts +110 -5
  76. package/dist/index.js +1 -28
  77. package/dist/internal/index.cjs +1 -4166
  78. package/dist/internal/index.d.cts +369 -324
  79. package/dist/internal/index.d.ts +369 -324
  80. package/dist/internal/index.js +1 -647
  81. package/dist/keyframe-rank-YAJLYJYF.js +1 -0
  82. package/dist/landmarker-KB7LVXAU.js +1 -0
  83. package/dist/mrz-band-VYHOTDHY.js +1 -0
  84. package/dist/plan-runner-NUWONT7F.js +1 -0
  85. package/dist/popup/index.cjs +1 -76
  86. package/dist/popup/index.d.cts +8 -2
  87. package/dist/popup/index.d.ts +8 -2
  88. package/dist/popup/index.js +1 -11
  89. package/dist/print-AYSCRSZB.js +1 -0
  90. package/dist/scanic-ml-stub-KW7IZHUT.js +1 -0
  91. package/dist/segmenter-USLNBX65.js +1 -0
  92. package/dist/turnstile-FATNZ4AG.js +1 -0
  93. package/dist/types-C_XP92JQ.d.cts +1732 -0
  94. package/dist/types-C_XP92JQ.d.ts +1732 -0
  95. package/dist/upload-file-UYXOHCRG.js +1 -0
  96. package/package.json +27 -11
  97. package/sbom.cdx.json +234 -0
  98. package/dist/capture-constraints-BujkZcfb.d.cts +0 -21
  99. package/dist/capture-constraints-BujkZcfb.d.ts +0 -21
  100. package/dist/chunk-BPYVZUJA.js +0 -852
  101. package/dist/chunk-BPYVZUJA.js.map +0 -1
  102. package/dist/chunk-LOTAJDRE.js +0 -1094
  103. package/dist/chunk-LOTAJDRE.js.map +0 -1
  104. package/dist/chunk-MWNFSNMP.js +0 -52
  105. package/dist/chunk-MWNFSNMP.js.map +0 -1
  106. package/dist/chunk-NILNKLK6.js +0 -50
  107. package/dist/chunk-NILNKLK6.js.map +0 -1
  108. package/dist/chunk-NWF46H7K.js +0 -359
  109. package/dist/chunk-NWF46H7K.js.map +0 -1
  110. package/dist/chunk-WY6U7AIK.js +0 -193
  111. package/dist/chunk-WY6U7AIK.js.map +0 -1
  112. package/dist/chunk-YVFF4Q4G.js +0 -327
  113. package/dist/chunk-YVFF4Q4G.js.map +0 -1
  114. package/dist/client/index.cjs.map +0 -1
  115. package/dist/client/index.js.map +0 -1
  116. package/dist/core/index.cjs.map +0 -1
  117. package/dist/core/index.js.map +0 -1
  118. package/dist/core/v3/detect-worker.cjs.map +0 -1
  119. package/dist/core/v3/detect-worker.js.map +0 -1
  120. package/dist/create-verification-CjLnJ0w6.d.ts +0 -348
  121. package/dist/create-verification-EnZ13uY4.d.cts +0 -348
  122. package/dist/detector-scanic-4C6IEW2K.js +0 -787
  123. package/dist/detector-scanic-4C6IEW2K.js.map +0 -1
  124. package/dist/hosted-client-BpvBqu9f.d.cts +0 -408
  125. package/dist/hosted-client-BpvBqu9f.d.ts +0 -408
  126. package/dist/index.cjs.map +0 -1
  127. package/dist/index.js.map +0 -1
  128. package/dist/internal/index.cjs.map +0 -1
  129. package/dist/internal/index.js.map +0 -1
  130. package/dist/popup/index.cjs.map +0 -1
  131. package/dist/popup/index.js.map +0 -1
  132. package/dist/scanic-ml-stub-S2OZ6HEF.js +0 -10
  133. package/dist/scanic-ml-stub-S2OZ6HEF.js.map +0 -1
@@ -0,0 +1 @@
1
+ import{a as T,b as R}from"./chunk-DK5YPBDQ.js";var N=1e3,_=[[1,0],[0,1],[1,1],[1,-1]];function w(i){let{width:t,height:e,data:r}=i;if(t<16||e<16)return-1;let s=new Uint8Array(t*e);for(let n=0,a=0;n<s.length;n+=1,a+=4)s[n]=Math.round(.299*(r[a]??0)+.587*(r[a+1]??0)+.114*(r[a+2]??0));let o=-1;for(let[n,a]of _){let l=new Uint32Array(256),c=new Float64Array(256),p=0;for(let h=1;h<e-1;h+=1){let u=h*t,S=(h+a)*t,A=(h-a)*t;for(let g=1;g<t-1;g+=1){let y=s[S+g+n]??0,z=s[A+g-n]??0,v=Math.abs(y-z);l[v]=(l[v]??0)+1,c[v]=(c[v]??0)+Math.abs(y+z-2*(s[u+g]??0)),p+=1}}let M=Math.max(1,Math.floor(p/20)),m=0,d=0,f=0;for(let h=255;h>=0&&m<M;h-=1){let u=l[h]??0;m+=u,d+=u*h,f+=c[h]??0}if(d===0)return 0;let b=f/d;o=o<0?b:Math.min(o,b)}return o}var I=.06;function P(i,t,e,r=I){if(i===null||t.width<=0||t.height<=0)return null;let s=[i.topLeft,i.topRight,i.bottomRight,i.bottomLeft],o=e.width/t.width,n=e.height/t.height,a=Math.min(...s.map(u=>u.x))*o,l=Math.max(...s.map(u=>u.x))*o,c=Math.min(...s.map(u=>u.y))*n,p=Math.max(...s.map(u=>u.y))*n,M=(l-a)*r,m=(p-c)*r,d=Math.max(0,Math.floor(a-M)),f=Math.max(0,Math.floor(c-m)),b=Math.min(e.width,Math.ceil(l+M)),h=Math.min(e.height,Math.ceil(p+m));return b-d<16||h-f<16?null:{x:d,y:f,width:b-d,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 E(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)),o=new Uint8ClampedArray(r*s*4);for(let n=0;n<s;n+=1){let a=Math.floor(n/e),l=Math.min(i.height,Math.max(a+1,Math.floor((n+1)/e)));for(let c=0;c<r;c+=1){let p=Math.floor(c/e),M=Math.min(i.width,Math.max(p+1,Math.floor((c+1)/e)));for(let m=0;m<3;m+=1){let d=0;for(let f=a;f<l;f+=1)for(let b=p;b<M;b+=1)d+=i.data[(f*i.width+b)*4+m]??0;o[(n*r+c)*4+m]=d/((l-a)*(M-p))}o[(n*r+c)*4+3]=255}}return{data:o,width:r,height:s}}function V(i,t){return w(E(t===null?i:F(i,t)))}function B(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)),o=Math.max(1,Math.round(e.height*r)),n=document.createElement("canvas");n.width=s,n.height=o;try{let a=n.getContext("2d",{willReadFrequently:!0});return a===null?-1:(a.imageSmoothingQuality="high",a.drawImage(i,e.x,e.y,e.width,e.height,0,0,s,o),w(a.getImageData(0,0,s,o)))}catch{return-1}finally{n.width=0,n.height=0}}var k=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 D=Object.freeze({...T,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}),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 Y(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 L=class{constructor(t){this.o=t;this.engine=null;this.gen=0;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.mrzGate=new k(t.liveMrz?.stableReads??2),this.lockGate=new R(t.textLock??D)}setEngine(t){this.engine=t}get bandTop(){return this.o.liveMrz?.bandTop??O.bandTop}get hasEngine(){return this.engine!==null&&!this.disabled}reset(){this.gen++,this.inFlight=!1,this.lastReadAt=Number.NEGATIVE_INFINITY,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.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==="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});if(!this.canRead(t.atMs,e.minIntervalMs))return r();this.inFlight=!0,this.lastReadAt=t.atMs;let s=this.gen,o=this.engine,n=t.glareOk?t.sharpOk?void 0:"holdStill":"glare";return this.crop(t.video,t.band,e.bandMaxWidthPx).then(a=>o.bandRead(a,e.detectorLimit)).then(a=>{if(s===this.gen){if(this.reads++,this.times.push(a.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(a.valid?a.digest??null:null)&&a.format&&a.digest){this.valid={format:a.format,...a.documentCode!==void 0?{documentCode:a.documentCode}:{},digest:a.digest,lineCount:a.lineCount,framesToValid:this.reads,msToValid:Math.round(t.atMs-(this.firstSeen??t.atMs))},this.mrzState={state:"valid",format:a.format},this.fired={via:"live_mrz",at:t.atMs};return}this.mrzState={state:"reading",...n?{coach:n}:{},...a.format?{format:a.format}:{}}}}).catch(()=>{s===this.gen&&this.fall("error")}).finally(()=>{s===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,o=this.engine,n={glareOk:t.glareOk,sharpOk:t.sharpOk};return this.crop(t.video,t.card,e.maxWidthPx).then(a=>o.layoutRead(a,e.detectorLimit)).then(a=>{if(s!==this.gen)return;this.reads++,this.times.push(a.ms),this.times.length>8&&this.times.shift();let l=this.lockGate.offer(a,t.atMs,n);this.lockState=l.state==="locked"?{state:"locked"}:{state:l.state,...l.hint?{hint:l.hint}:{}},l.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 o=x(this.times,.5),n={capture:t,mode:s,reads:this.reads,...this.times.length>0?{readP50Ms:Math.round(o),readP90Ms:Math.round(x(this.times,.9)),deviceClass:G(o)}:{}};return s==="live_mrz"?this.fired?.via==="live_mrz"&&this.valid!==null&&e==="live_mrz"?{...n,outcome:"valid",format:this.valid.format,framesToValid:this.valid.framesToValid,msToValid:this.valid.msToValid}:this.fallback!==null?{...n,outcome:this.fallback}:{...n,outcome:r-(this.firstSeen??r)>=(this.o.liveMrz?.searchTimeoutMs??1/0)?"timeout":"off"}:this.fired?.via==="text_lock"?{...n,outcome:"locked",framesToLock:Math.max(1,this.reads),msToLock:Math.round(this.fired.at-(this.firstSeen??this.fired.at))}:{...n,outcome:this.lockError?"error":this.lockOff?"timeout":"off"}}};export{N as a,w as b,I as c,P as d,F as e,E as f,V as g,B as h,D as i,O as j,Y as k,L as l};
@@ -0,0 +1 @@
1
+ var K={enabled:!0,hz:3,segmenterTimeoutMs:8e3,segmenterBudgetMs:120,maskThreshold:.5,maxColorStd:28,maxEdgeDensity:.08,edgeLuma:24,maxGradient:.18,minPixels:300,timeoutMs:4e3},V=12e3,b=(n,o,t)=>Math.min(t,Math.max(o,Math.round(n)));function W(n,o,t){let{x:r,y:m,width:a,height:u}=n;if(t)return[{x:r-1.5*a,y:m-.8*u,width:4*a,height:2.8*u}];let d=m-.4*u,p=1.4*u;return[{x:r-.9*a,y:d,width:.75*a,height:p},{x:r+1.15*a,y:d,width:.75*a,height:p}].map(h=>{let M=Math.max(0,h.x),l=Math.min(o.width,h.x+h.width);return{x:M,y:h.y,width:Math.max(0,l-M),height:h.height}})}function Z(n,o,t,r=K){let m=t!==null&&t.width>0&&t.height>0,a=W(o,n,m),u=a.reduce((e,s)=>e+Math.max(0,s.width)*Math.max(0,s.height),0);if(u<=0)return null;let d=Math.max(1,Math.floor(Math.sqrt(u/V))),p=m?t.data instanceof Float32Array?1:1/255:1,h=(e,s)=>{if(!m)return!1;let w=b(e/n.width*t.width-.5,0,t.width-1),C=b(s/n.height*t.height-.5,0,t.height-1);return t.data[C*t.width+w]*p>=r.maskThreshold},M=e=>.299*n.data[e]+.587*n.data[e+1]+.114*n.data[e+2],l=0,B=[0,0,0],S=[0,0,0],k=0,T=0,D=0,_=0,P=0,A=0,E=0,L=0,F=0,G=0,O=Math.min(...a.map(e=>e.x)),j=Math.max(...a.map(e=>e.x+e.width)),H=Math.min(...a.map(e=>e.y)),I=Math.max(...a.map(e=>e.y+e.height)),J=(O+j)/2,Q=(H+I)/2;for(let e of a){let s=b(e.x,0,n.width),w=b(e.x+e.width,0,n.width),C=b(e.y,0,n.height),q=b(e.y+e.height,0,n.height);for(let c=C;c<q;c+=d)for(let g=s;g<w;g+=d){if(h(g,c))continue;let Y=(c*n.width+g)*4;for(let i=0;i<3;i+=1){let x=n.data[Y+i];B[i]=B[i]+x,S[i]=S[i]+x*x}l+=1;let y=M(Y);g<J?(D+=y,_+=1):(P+=y,A+=1),c<Q?(E+=y,L+=1):(F+=y,G+=1);for(let[i,x]of[[g+d,c],[g,c+d]])i>=w||x>=q||h(i,x)||(k+=1,Math.abs(M((x*n.width+i)*4)-y)>r.edgeLuma&&(T+=1))}}if(l<r.minPixels)return null;let U=0;for(let e=0;e<3;e+=1){let s=B[e]/l;U+=Math.max(0,S[e]/l-s*s)}let N=Math.sqrt(U/3),z=k===0?0:T/k,f=(e,s)=>s===0?null:e/s,R=(e,s)=>e===null||s===null?0:Math.abs(e-s)/255,X=Math.max(R(f(D,_),f(P,A)),R(f(E,L),f(F,G)));return{method:m?"segmenter":"strip",uniform:N<=r.maxColorStd&&z<=r.maxEdgeDensity&&X<=r.maxGradient,colorStd:Math.round(N*10)/10,edgeDensity:Math.round(z*1e3)/1e3,gradient:Math.round(X*1e3)/1e3,pixels:l}}function $(n){let o=n!==null&&typeof n=="object"?n:{},t=K,r=(m,a,u,d)=>typeof m=="number"&&Number.isFinite(m)&&m>=u&&m<=d?m:a;return{enabled:typeof o.enabled=="boolean"?o.enabled:t.enabled,hz:r(o.hz,t.hz,.5,15),segmenterTimeoutMs:r(o.segmenterTimeoutMs,t.segmenterTimeoutMs,0,6e4),segmenterBudgetMs:r(o.segmenterBudgetMs,t.segmenterBudgetMs,1,2e3),maskThreshold:r(o.maskThreshold,t.maskThreshold,0,1),maxColorStd:r(o.maxColorStd,t.maxColorStd,0,255),maxEdgeDensity:r(o.maxEdgeDensity,t.maxEdgeDensity,0,1),edgeLuma:r(o.edgeLuma,t.edgeLuma,0,255),maxGradient:r(o.maxGradient,t.maxGradient,0,1),minPixels:r(o.minPixels,t.minPixels,1,1e6),timeoutMs:r(o.timeoutMs,t.timeoutMs,0,6e4)}}export{K as a,Z as b,$ as c};
@@ -0,0 +1 @@
1
+ function y(){let e=new Map;return{on(i,n){let t=e.get(i);t===void 0&&(t=new Set,e.set(i,t));let r=n;return t.add(r),()=>{t?.delete(r)}},emit(i,n){let t=e.get(i);if(t!==void 0)for(let r of[...t])r(n)},count(i){return e.get(i)?.size??0},clear(){e.clear()}}}async function f(){try{return typeof navigator>"u"||typeof navigator.permissions?.query!="function"?null:await navigator.permissions.query({name:"camera"})}catch{return null}}function u(e){return e==="granted"||e==="prompt"||e==="denied"?e:"unknown"}async function g(){let e=await f();return e===null?"unknown":u(e.state)}function h(e){let i=!1,n=null,t=()=>{!i&&n!==null&&e(u(n.state))};return f().then(r=>{i||(n=r,e(r===null?"unknown":u(r.state)),r?.addEventListener?.("change",t))}),()=>{i=!0,n?.removeEventListener?.("change",t)}}async function b(){if(typeof navigator>"u")return!1;let e=String(navigator.userAgent??"");if(/Android|iPhone|iPad|iPod/i.test(e)||/Macintosh/.test(e)&&(navigator.maxTouchPoints??0)>1)return!0;try{return(await navigator.mediaDevices?.enumerateDevices?.()??[]).filter(n=>n.kind==="videoinput").length>=2}catch{return!1}}function v(){if(typeof navigator>"u"||!("wakeLock"in navigator))return null;let e=navigator.wakeLock;return typeof e?.request=="function"?e:null}function m(){return typeof document>"u"||document.visibilityState==="visible"}function p(e){try{e.release().catch(()=>{})}catch{}}function S(e={}){if(e.enabled===!1)return{setActive:()=>{}};let i=!1,n=null,t=!1,r=!1,l=()=>{if(!i||t||n!==null&&!n.released)return;let o=v();if(o===null||!m())return;let a;try{a=o.request("screen")}catch{return}t=!0,a.then(s=>{if(t=!1,!i){p(s);return}n=s,s.addEventListener?.("release",()=>{n===s&&(n=null)})},()=>{t=!1})},c=()=>{m()&&l()},d=o=>{typeof document>"u"||o===r||(r=o,o?document.addEventListener("visibilitychange",c):document.removeEventListener("visibilitychange",c))};return{setActive:o=>{if(i=o,o){if(v()===null)return;d(!0),l();return}if(d(!1),n!==null){let a=n;n=null,p(a)}}}}export{y as a,g as b,h as c,b as d,S as e};
@@ -0,0 +1 @@
1
+ import{c as v,d as V,e as A}from"./chunk-B2X33ZW2.js";var j=new Set(["nni_unbound","id_number_unbound","method_required","mobile_required","portrait_required"]);function we(e){return j.has(e)}function be(e,n,t){let i=n.detail;return{check:e,kind:n.kind,...i?.name!==void 0?{name:i.name}:{},...i?.phase!==void 0?{phase:i.phase}:{},...i?.engineKind!==void 0?{engineKind:i.engineKind}:{},attempt:Math.max(0,Math.min(1e3,t))}}function ke(){let e=-1,n="";return{note(t){t==="starting"&&n!=="starting"&&(e+=1),n=t},newHandle(){n=""},noteError(){e<0&&(e=0)},get value(){return e}}}var H=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",sandbox_nni_not_seeded:"sandbox_id_number_not_seeded",missing_nni:"missing_id_number",registry_needs_nni_source:"registry_needs_id_number_source"}),I=new Map(Object.entries(H)),$=new Map(Object.entries(H).map(([e,n])=>[n,e]));function ve(e){return I.get(e)??e}function z(e){let n=I.get(e)??$.get(e);return n===void 0?[e]:[e,n]}function T(e){let n=[];for(let t of e)for(let i of z(t))n.includes(i)||n.push(i);return n}var W=new Set(T(["no_face","media_unreadable","clip_too_short","no_face_source","side_missing","unreadable","registry_unavailable","otp_mismatch","otp_expired","otp_send_failed","document_type_not_accepted","age_unverifiable","nationality_unreadable","liveness_inconclusive","match_inconclusive","document_authenticity","probe_not_from_liveness","capture_back_camera","capture_not_upright","chip_read_failed","chip_access_denied","chip_parse_failed","icao_pose","icao_eyes","icao_mouth","icao_occlusion","icao_lighting","icao_background","icao_resolution","portrait_not_from_liveness","nni_recheck","device_integrity_failed","eid_identifier_invalid","eid_code_invalid","eid_code_expired","eid_unavailable","eid_resend_too_soon"])),X={document:"document_photo",nfc:"document_chip",population_registry:"national_number",national_eid:"national_eid"};function p(e){return e.plan?.steps??[]}function O(e){return Math.max(0,e.attempts.max-e.attempts.used)}function G(e){let n=e.plan?.choice;return n!==void 0&&e.plan?.current===n.nodeId?n:null}function Me(e){let n=G(e);if(n?.kind!=="identity_method")return null;let t=n.options.map(o=>X[o.service]).filter(o=>o!==void 0),i=n.options.find(o=>o.nationalEid)?.nationalEid;return i?{available:!0,selected:null,options:t,nationalEid:i}:{available:!0,selected:null,options:t}}var J=new Set(["liveness","face_match"]);function x(e){return e!==void 0&&(e.state==="pending"||e.state==="input_required")}function L(e){return e.status!=="created"&&e.status!=="in_progress"}function E(e){let n=e.plan?.current,t=n==null?void 0:p(e).find(i=>i.id===n);return x(t)?t:void 0}function y(e,n){return p(e).find(t=>t.checkType===n)}function g(e){let n=p(e),t=n.findIndex(i=>i.checkType==="liveness");return n.find((i,o)=>o>t&&i.checkType==="face_match")}function N(e,n){let t=y(n,"liveness")?.state,i=g(n)?.state;return(g(e)?.state??"pending")==="pending"&&(t==="passed"||t==="review")&&i!==void 0&&i!=="pending"&&i!=="skipped"}function M(e,n){let t=new Map(p(e).map(i=>[i.id,i.state]));return p(n).filter(i=>i.checkType==="face_match"&&(t.get(i.id)??"pending")==="pending"&&i.state!=="pending"&&i.state!=="skipped").map(i=>i.id)}var Q=/^[0-9a-f]{24}$/i;function b(e){return Q.test(e)?`ses_${e}`:e}function w(e,n){let t=b(e);return n===void 0?{sessionId:t,status:"unavailable"}:{sessionId:t,status:"unavailable",reason:n}}function _(e,n,t){let i=b(e);return t===void 0?{sessionId:i,status:n}:{sessionId:i,status:n,reason:t}}function Pe(e,n){let{sessionId:t}=e;switch(e.status){case"completed":case"failed":case"review_pending":return ee(e,ne(e));case"expired":return w(t);case"created":case"in_progress":break;default:{let i=e.status;throw new Error(`mapSessionResult: unhandled status ${i}`)}}return ie(e,n)}var Z=new Set([0,1,2,3]);function ee(e,n){return Z.has(e.level)&&(n.level=e.level),typeof e.assurance=="string"&&e.assurance.length>0&&(n.assurance=e.assurance),n}function ne(e){let n=b(e.sessionId);switch(e.status){case"completed":return e.outcome==="approved"?{sessionId:n,status:"approved"}:e.outcome==="review"?_(n,"review",h(e,"review")):_(n,"rejected",h(e,"failed"));case"failed":{let t=_(n,"rejected",e.failureReason??h(e,"failed"));return e.failureReason==="device_cooldown"&&e.retryAfter!==void 0&&(t.retryAfter=e.retryAfter),t}default:return _(n,"review",h(e,"review"))}}function te(e,n){if(n===void 0)return!1;let t=p(n).find(i=>i.id===e.id);return t!==void 0&&t.attempts.used===e.attempts.used}function ie(e,n){let t=b(e.sessionId),i=p(e).find(s=>J.has(s.checkType)&&s.state==="input_required"&&s.reason!==void 0);if(i?.reason==="mobile_required")return w(t,"mobile_required");if(i?.reason!==void 0){let s=n.autoRetry&&O(i)>0&&(W.has(i.reason)||te(i,n.previous)),d={sessionId:t,status:s?"retry":"rejected",reason:i.reason,attemptsRemaining:O(i)};return i.retakeHint!==void 0&&(d.retakeHint=i.retakeHint),d}let o=E(e);return o===void 0&&p(e).some(s=>s.state==="review")?_(t,"review",h(e,"review")):o?.checkType==="portrait_icao"?w(t,"portrait_required"):w(t)}function h(e,n){let t=p(e).filter(i=>i.state===n&&i.reason!==void 0);return t[n==="failed"?t.length-1:0]?.reason}function K(e,n,t,i,o){return e.presignCapture!==void 0?e.presignCapture(n,t,i,o):e.presign(n,t,i)}function q(e){return{engine:e?.engine,durationMs:e?.clipMs}}var oe=["video/webm","video/mp4"],F="image/jpeg",se=2,re=1e3,ae=1e4,de=3,ue=10,ce=3,le=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),pe=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order","identity_confirm_required","check_not_active","step_not_on_path"]),S=class extends Error{constructor(){super("verification destroyed"),this.name="FlowCancelledError"}};function fe(e){let n=g(e);return y(e,"portrait_icao")?.state!=="pending"&&(n!==void 0?x(n):e.capture?.livePhoto?.oneCapture===!0)}var R=class extends Error{constructor(n){super(n),this.name="AttestationError"}};async function D(e,n,t={}){let i=e.uuid(),o=!1,s=!1,d=0,u=0;for(;;)try{return await n(e.client,i)}catch(r){if(r instanceof R){if(s)throw r;s=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(!(r instanceof v))throw r;if(r.code==="consent_required"&&!o){o=!0,await e.ensureConsent({force:!0}),i=e.uuid();continue}if(r.code==="attestation_invalid"&&!s){s=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(r.code==="inference_unavailable"&&u<de){u+=1;let a=V(r.retryAfterSeconds,ue,e.random??Math.random);e.onBusy?.({attempt:u,retryAfterSeconds:a/1e3}),await e.sleep(a),t.onAttestationInvalid?.(),i=e.uuid();continue}if(le.has(r.code)&&d<se){d+=1;let a=r.retryAfterSeconds!==void 0?r.retryAfterSeconds*1e3:void 0;await e.sleep(a!==void 0?Math.min(a,ae):re);continue}throw r}}var me=new Set(["passed","review","processing","skipped"]);async function Oe(e){let{artifacts:n}=e,t=n.clip,i=A(n.clipMime??"");if(n.degraded==="NO_RECORDER"||t===void 0||!oe.includes(i))return{kind:"unavailable",reason:"no_recorder"};e.client.armCapture?.(2);let o=_e(e,n.keyframe),s=he(e,t,i,o),d=ge(e,o),u=!1,r=new Set,a=!0,m=0;for(;;){if(e.isCancelled())return{kind:"cancelled"};let l=e.getView();if(L(l))return{kind:"settled"};let k=E(l),P=k?.checkType,C=P==="liveness"&&!u?"liveness":P==="face_match"&&!r.has(k?.id)&&r.size<2&&a?"face_match":null;if(C===null)return{kind:"settled"};if(C==="liveness"&&n.captureChannel==="desktop"&&y(l,"liveness")?.requiresMobile===!0)return{kind:"unavailable",reason:"mobile_required"};try{if(C==="liveness"){u=!0;let c=await s();if(e.isCancelled())return{kind:"cancelled"};N(l,c)&&r.add(g(c)?.id);for(let B of M(l,c))r.add(B);await e.applySubmit(c,"liveness");let f=y(e.getView(),"liveness")?.state;a=f===void 0||me.has(f)}else{r.add(k?.id);let c=await d();if(e.isCancelled())return{kind:"cancelled"};for(let f of M(l,c))r.add(f);await e.applySubmit(c,"face_match")}}catch(c){if(e.isCancelled()||c instanceof S)return{kind:"cancelled"};let f=Re(c);if(f.kind!=="resync"||m>=ce)return f;m+=1,await e.refreshView()}}}function _e(e,n){let t=null,i=null,o=()=>t!==null?Promise.resolve(t):(i??(i=(async()=>{let s=await K(e.client,"image",F,n.size,q(e.artifacts));return await e.client.uploadToSpaces(s.uploadUrl,n,F),t=(await e.client.completeMedia(s.key)).key,e.onKeyframePromoted?.(t),t})().finally(()=>{i=null})),i);return{ensure:o,attempt:()=>o().catch(()=>null),current:()=>t}}function he(e,n,t,i){let o=null,s,d=null;return()=>D(e,async(u,r)=>{if(o===null||s===void 0){if(e.isCancelled())throw new S;s===void 0&&!fe(e.getView())&&(s=null),e.onPhase("uploading");let[a,m]=await Promise.all([o!==null?Promise.resolve(o):(async()=>{let l=await K(u,"clip",t,n.size,q(e.artifacts));return await u.uploadToSpaces(l.uploadUrl,n,t),(await u.completeMedia(l.key)).key})(),s!==void 0?Promise.resolve(s===null?null:s.imageKey):i.attempt()]);o=a,s===void 0&&(s=m===null?null:{imageKey:m})}if(d===null)try{d=await e.getAttestation()}catch(a){throw new R(a instanceof Error?a.message:String(a))}return e.onPhase("checking"),u.submitCheck("liveness",{clipKey:o,attestation:d,captureChannel:e.artifacts.captureChannel,capture:ye(e.artifacts),...s!==null?{faceMatch:s}:{}},{idempotencyKey:r})},{onAttestationInvalid:()=>{d=null}})}function ge(e,n){return()=>D(e,async(t,i)=>{if(n.current()===null){if(e.isCancelled())throw new S;e.onPhase("uploading")}let o=await n.ensure();return e.onPhase("checking"),t.submitCheck("face_match",{imageKey:o},{idempotencyKey:i})})}function ye(e){let n={width:e.width,height:e.height};for(let t of Se)e[t]!==void 0&&(n[t]=e[t]);return n}var Se=["engine","facingMode","mode","formFactor","clipMs","cameraReadyMs","faceAcquireMs","captureMs","screenRamp","provenance"];function Re(e){if(e instanceof R)return{kind:"unavailable",reason:"attestation"};if(e instanceof v){if(e.code==="attestation_invalid")return{kind:"unavailable",reason:"attestation"};if(e.code==="inference_unavailable")return{kind:"unavailable",reason:"inference_unavailable"};if(e.code==="mobile_required")return{kind:"unavailable",reason:"mobile_required"};if(pe.has(e.code))return{kind:"resync"}}return{kind:"unavailable",reason:"network"}}var U=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="InvalidInputError",this.field=n,this.kind=t}},Y=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="OtpInputError",this.field=n,this.kind=t}};function Fe(e){let n=e?.capture,t=n?.mode;return t==="assisted"||t==="self"||t==="choice"?t:n?.cameraSwitch===!0?"assisted":"self"}function Ke(e,n){return e==="choice"?n??"self":e}export{we as a,be as b,ke as c,Fe as d,Ke as e,ve as f,W as g,X as h,p as i,O as j,G as k,Me as l,x as m,L as n,E as o,y as p,b as q,w as r,Pe as s,K as t,oe as u,se as v,re as w,de as x,ue as y,R as z,D as A,Oe as B,U as C,Y as D};
@@ -0,0 +1 @@
1
+ import{c as x}from"./chunk-TDLIXFDT.js";import{b}from"./chunk-FPXL63KZ.js";var T=480,y=Object.freeze({MIN_AREA_FRAC:.15,EDGE_CLIP_MARGIN_PX:4,STABLE_TICKS:3,IOU_STABLE_MIN:.85,RISE_PER_S:.9,FALL_PER_S:.25,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,ID3_BAND_MIN_WIDTH_FRAC:.55,ID3_BAND_ASPECT_MIN:4,ID3_BAND_ASPECT_MAX:40}),p=e=>Math.min(1,Math.max(0,e));function E(e,o,t){let n=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let s=0;s<4;s++){let r=n[s],c=n[(s+1)%4];i+=r.x*c.y-c.x*r.y}let a=o*t;return a>0?Math.abs(i/2)/a:0}function I(e,o){let t=D(e),n=D(o),i=Math.max(t.x1,n.x1),a=Math.max(t.y1,n.y1),s=Math.min(t.x2,n.x2),r=Math.min(t.y2,n.y2),c=Math.max(0,s-i)*Math.max(0,r-a),u=(t.x2-t.x1)*(t.y2-t.y1),_=(n.x2-n.x1)*(n.y2-n.y1),m=u+_-c;return m>0?c/m:0}function R(e){let o=D(e);return{width:o.x2-o.x1,height:o.y2-o.y1}}function D(e){let o=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft];return{x1:Math.min(...o.map(t=>t.x)),y1:Math.min(...o.map(t=>t.y)),x2:Math.max(...o.map(t=>t.x)),y2:Math.max(...o.map(t=>t.y))}}function M(e){let o=Math.hypot(e.topRight.x-e.topLeft.x,e.topRight.y-e.topLeft.y),t=Math.hypot(e.bottomRight.x-e.bottomLeft.x,e.bottomRight.y-e.bottomLeft.y),n=Math.hypot(e.bottomLeft.x-e.topLeft.x,e.bottomLeft.y-e.topLeft.y),i=Math.hypot(e.bottomRight.x-e.topRight.x,e.bottomRight.y-e.topRight.y),a=(o+t)/2,s=(n+i)/2;return a<=0||s<=0?0:Math.max(a,s)/Math.min(a,s)}var d=class{constructor(o,t={}){this.p=0;this.lastTickAt=null;this.lastQuad=null;this.streak=0;this.format=o,this.t={...y,...t}}reset(){this.p=0,this.lastTickAt=null,this.lastQuad=null,this.streak=0}tick(o){let{quad:t,quality:n,timestampMs:i}=o,a=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let s=null;if(t===null)s="dcv1.no_doc";else if(this.format==="ID-3"){let h=R(t),f=h.height>0?h.width/h.height:0;h.width<this.t.ID3_BAND_MIN_WIDTH_FRAC*o.frameWidth?s="dcv1.come_closer":this.edgeClipped(t,o.frameWidth,o.frameHeight)?s="dcv1.fit_document":(f<this.t.ID3_BAND_ASPECT_MIN||f>this.t.ID3_BAND_ASPECT_MAX)&&(s="dcv1.wrong_shape")}else E(t,o.frameWidth,o.frameHeight)<this.t.MIN_AREA_FRAC?s="dcv1.come_closer":this.edgeClipped(t,o.frameWidth,o.frameHeight)?s="dcv1.fit_document":x(this.format,M(t))||(s="dcv1.wrong_shape");let r=s===null,c=p(n.exposure)>=this.t.GUIDE_EXPOSURE,u=p(n.sharpness)>=this.t.GUIDE_SHARPNESS,_=c&&u;if(r&&_&&t!==null){let h=this.lastQuad===null||I(t,this.lastQuad)>=this.t.IOU_STABLE_MIN;this.streak=h?this.streak+1:1}else this.streak=0;this.lastQuad=t;let m=r&&_;this.p=p(this.p+(m?this.t.RISE_PER_S:-this.t.FALL_PER_S)*a);let A=m&&this.streak>=this.t.STABLE_TICKS,l;if(s!==null)l=s;else if(c)u?l="dcv1.hold_still":l="dcv1.steady";else{let h=(b[0]+b[1])/2;l=n.meanLuma<h?"dcv1.more_light":"dcv1.too_bright"}return{at:i,quad:t,plausible:r,p:this.p,guidanceKey:l,ready:A,stableTicks:this.streak}}edgeClipped(o,t,n){let i=this.t.EDGE_CLIP_MARGIN_PX;return[o.topLeft,o.topRight,o.bottomRight,o.bottomLeft].some(s=>s.x<=i||s.y<=i||s.x>=t-i||s.y>=n-i)}};export{T as a,y as b,E as c,I as d,R as e,d as f};
@@ -0,0 +1 @@
1
+ var f="https://challenges.cloudflare.com/turnstile/v0/api.js",g=3e4;function p(){return window.turnstile}var o=null;function w(){o=null}function E(){return o??(o=new Promise((s,t)=>{let r=p();if(r){s(r);return}let e=document.createElement("script");e.src=f,e.async=!0,e.onload=()=>{let n=p();n?s(n):(o=null,t(new Error("Turnstile script loaded but exposed no API")))},e.onerror=()=>{o=null,e.remove(),t(new Error("Turnstile script failed to load"))},document.head.appendChild(e)})),o}function d(){return new Error("Turnstile challenge aborted")}async function x(s,t={}){let r=t.timeoutMs??3e4,e=t.signal;if(e?.aborted)throw d();let n=await E();if(e?.aborted)throw d();let a=document.createElement("div");document.body.appendChild(a);let i,c,u;try{return await new Promise((m,l)=>{if(c=setTimeout(()=>l(new Error(`Turnstile challenge timed out (${r} ms)`)),r),e!==void 0&&(u=()=>l(d()),e.addEventListener("abort",u,{once:!0})),i=n.render(a,{sitekey:s,execution:"execute",appearance:"execute",callback:m,"error-callback":T=>{l(new Error(`Turnstile challenge failed${T?` (${T})`:""}`))}}),i===void 0){l(new Error("Turnstile render returned no widget id"));return}n.execute(i)})}finally{if(clearTimeout(c),e!==void 0&&u!==void 0&&e.removeEventListener("abort",u),i!==void 0)try{n.remove(i)}catch{}a.remove()}}export{f as a,g as b,w as c,E as d,x as e};
@@ -0,0 +1 @@
1
+ var v=1e4,u=class t{constructor(e,i){this.tier="blaze";this.inner=e,i!==void 0&&(this.fallbackReason=i)}static async create(e,i){let o=await import("@mediapipe/tasks-vision"),n=await o.FilesetResolver.forVisionTasks(e),r=await o.FaceDetector.createFromOptions(n,{baseOptions:{modelAssetPath:`${e}/blaze_face_short_range.tflite`,delegate:"CPU"},runningMode:"IMAGE"});return new t(r,i)}async detect(e,i,o){let n;try{n=this.inner.detect(e).detections}catch{return null}let r=O(n);if(r?.boundingBox===void 0)return null;let a=g(e),s=w(r.keypoints,a),c=r.keypoints?.[2],b={box:{x:r.boundingBox.originX,y:r.boundingBox.originY,width:r.boundingBox.width,height:r.boundingBox.height},...s!==void 0?{eyes:s}:{},...c!==void 0?{nose:{x:c.x*a.width,y:c.y*a.height}}:{},score:r.categories[0]?.score??0};return l(b,e,i,o)}destroy(){try{this.inner.close()}catch{}}};function O(t){let e,i=-1;for(let o of t){let n=o.categories[0]?.score??0;n>i&&(e=o,i=n)}return e}function w(t,e){let i=t?.[0],o=t?.[1];if(i===void 0||o===void 0)return;let n=s=>({x:s.x*e.width,y:s.y*e.height}),[r,a]=[n(i),n(o)];return r.x<=a.x?{left:r,right:a}:{left:a,right:r}}function R(){if(typeof OffscreenCanvas=="function")return new OffscreenCanvas(2,2);let t=document.createElement("canvas");return t.width=2,t.height=2,t}async function x(){let t=globalThis.FaceDetector;if(typeof t!="function")return{ok:!1,reason:"unsupported"};try{let e=new t({fastMode:!0,maxDetectedFaces:1});return await e.detect(R()),{ok:!0,instance:e}}catch(e){return{ok:!1,reason:`smoke_failed:${e instanceof Error?e.message:String(e)}`}}}var m=class{constructor(e,i){this.tier="native";this.inner=e,i!==void 0&&(this.fallbackReason=i)}async detect(e,i,o){let n;try{n=await this.inner.detect(e)}catch{return null}let r=n[0];if(r===void 0)return null;let a=T(r.landmarks),s={box:{x:r.boundingBox.x,y:r.boundingBox.y,width:r.boundingBox.width,height:r.boundingBox.height},...a!==void 0?{eyes:a}:{},score:1};return l(s,e,i,o)}destroy(){}};function T(t){if(t===void 0)return;let e=t.filter(n=>n.type==="eye").map(n=>n.locations[0]).filter(n=>n!==void 0),[i,o]=e;if(!(i===void 0||o===void 0))return i.x<=o.x?{left:i,right:o}:{left:o,right:i}}var F="/models-v3",I=["native","blaze"],y=class extends Error{constructor(e){super(`no detector tier available (${e})`),this.name="DetectorLadderError",this.fallbackReason=e}};function g(t){let e=t;if(typeof e.videoWidth=="number"&&e.videoWidth>0)return{width:e.videoWidth,height:e.videoHeight??0};if(typeof e.naturalWidth=="number"&&e.naturalWidth>0)return{width:e.naturalWidth,height:e.naturalHeight??0};let i=typeof e.width=="number"?e.width:0,o=typeof e.height=="number"?e.height:0;return{width:i,height:o}}function l(t,e,i,o){let n=g(e),r=n.width>0?i/n.width:1,a=n.height>0?o/n.height:1,s=c=>({x:c.x*r,y:c.y*a});return{box:{x:t.box.x*r,y:t.box.y*a,width:t.box.width*r,height:t.box.height*a},...t.eyes!==void 0?{eyes:{left:s(t.eyes.left),right:s(t.eyes.right)}}:{},...t.nose!==void 0?{nose:s(t.nose)}:{},score:t.score}}function E(t){return t instanceof Error?t.message:String(t)}async function k(t){let e=t.preferred??I,i=[];for(let o of e){if(o==="native"){let n=await x();if(n.ok)return new m(n.instance,h(i));i.push(`native:${n.reason}`);continue}try{return await S(u.create(t.v3AssetBaseUrl??F,h(i)),t.blazeInitTimeoutMs??v)}catch(n){i.push(n instanceof f?"blaze:blaze_init_timeout":`blaze:${E(n)}`)}}throw new y(h(i)??"no_tier_available")}function h(t){return t.length>0?t.join("; "):void 0}var f=class extends Error{};function S(t,e){return new Promise((i,o)=>{let n=setTimeout(()=>{o(new f(`init exceeded ${e}ms`)),t.then(r=>r.destroy(),()=>{})},e);t.then(r=>{clearTimeout(n),i(r)},r=>{clearTimeout(n),o(r)})})}var d=1;function A(){return typeof OffscreenCanvas=="function"&&typeof createImageBitmap=="function"&&typeof Worker=="function"}function M(t,e={}){let i=e.createDetector??k,o=null;t.onmessage=n=>{let r=n.data;if(r.v!==d){r.bitmap?.close?.();return}if(r.type==="init"){i(r.options).then(a=>{o=a;let s={v:d,type:"ready",tier:a.tier,...a.fallbackReason!==void 0?{fallbackReason:a.fallbackReason}:{}};t.postMessage(s)});return}if(r.type==="detect"){let a=s=>{let c={v:d,type:"result",id:r.id,observation:s};t.postMessage(c),r.bitmap.close?.()};if(o===null){a(null);return}o.detect(r.bitmap,r.streamWidth,r.streamHeight).then(a,()=>a(null))}}}typeof self<"u"&&typeof self.importScripts=="function"&&M(self);var D=class t{constructor(e,i){this.pending=new Map;this.nextId=1;this.worker=e,this.tier=i.tier,i.fallbackReason!==void 0&&(this.fallbackReason=i.fallbackReason),e.addEventListener("message",o=>{let n=o.data;if(n.v!==d||n.type!=="result")return;let r=this.pending.get(n.id);this.pending.delete(n.id),r?.(n.observation)})}static create(e,i,o=1e4){return new Promise((n,r)=>{let a=setTimeout(()=>{e.removeEventListener("message",s),e.terminate(),r(new Error(`worker detector not ready within ${o}ms`))},o),s=b=>{let p=b.data;p.v!==d||p.type!=="ready"||(clearTimeout(a),e.removeEventListener("message",s),n(new t(e,p)))};e.addEventListener("message",s);let c={v:d,type:"init",options:i};e.postMessage(c)})}async detect(e,i,o){let n;try{typeof ImageBitmap<"u"&&e instanceof ImageBitmap?n=e:typeof createImageBitmap=="function"?n=await createImageBitmap(e):n=e}catch{return null}let r=this.nextId;return this.nextId+=1,new Promise(a=>{this.pending.set(r,a);let s={v:d,type:"detect",id:r,bitmap:n,streamWidth:i,streamHeight:o};this.worker.postMessage(s,[n])})}destroy(){for(let e of this.pending.values())e(null);this.pending.clear(),this.worker.terminate()}};export{F as a,I as b,y as c,g as d,l as e,k as f,d as g,A as h,M as i,D as j};
@@ -0,0 +1 @@
1
+ import{a as Z,d as j,e as J}from"./chunk-GT2ZLGF7.js";import{w as Q}from"./chunk-7Q4YPMAF.js";import{c as q}from"./chunk-FUHDOEBP.js";import{f as G,l as N}from"./chunk-CQ7SKLMC.js";import{a as $,f as v}from"./chunk-OKWG3PVH.js";var se=12e4,X=13e4,oe=3e3,ie=1200,P=Symbol.for("@sekyro/web.preload.v1");function p(){let e=globalThis;return e[P]??(e[P]=new Map),e[P]}function g(e){let t=(e??$).replace(/\/+$/,"");return t===""?"/":t}function Y(e){let t=p(),r=t.get(e);return r===void 0&&(r={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},t.set(e,r)),r}function A(e,t){if(e.status!==t){e.status=t;for(let r of[...e.listeners])r(t)}}var T=e=>v({preferred:["blaze"],v3AssetBaseUrl:e,blazeInitTimeoutMs:se}),x=T;function Se(e){x=e??T}function Ce(){for(let e of p().values())e.detector?.destroy();p().clear(),x=T}function ae(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function ce(){return navigator.connection?.saveData===!0}function de(e){let t=window;if(typeof t.requestIdleCallback=="function"){let s=t.requestIdleCallback(e,{timeout:oe});return()=>t.cancelIdleCallback?.(s)}let r=setTimeout(e,ie);return()=>clearTimeout(r)}function ue(e,t){let r,s=new Promise(o=>{r=o}),u=!1,f=()=>{},d={promise:s,settle:o=>{u||(u=!0,f(),e.scheduled===d&&(e.scheduled=null),r(o))}};return e.scheduled=d,f=de(()=>{u||d.settle(I(e,t))}),s}function I(e,t){if((e.status==="loading"||e.status==="ready")&&e.promise!==null)return e.promise;A(e,"loading");let r=new Promise(o=>o(x(t)));e.detectorPromise=r;let s,u=new Promise((o,h)=>{s=setTimeout(()=>{r.then(S=>S.destroy(),()=>{}),h(new Error(`detector preload exceeded ${X} ms`))},X)}),d=Promise.race([r,u]).then(o=>e.detectorPromise!==r?(o.destroy(),e.status):(e.detector=o,A(e,"ready"),"ready"),o=>(e.detectorPromise===r&&(e.detectorPromise=null,e.detector=null,A(e,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",o)),e.status)).finally(()=>clearTimeout(s));return e.promise=d,e.scheduled?.settle(d),d}function Le(e={}){if(!ae())return Promise.resolve("idle");let t=g(e.assetBaseUrl),r=Y(t);return e.respectSaveData===!0&&ce()?Promise.resolve(r.status):(r.status==="loading"||r.status==="ready")&&r.promise!==null?r.promise:e.idle===!0?r.scheduled?.promise??ue(r,t):I(r,t)}function Ee(e){return p().get(g(e))?.status??"idle"}function ye(e,t){let r=Y(g(t));return r.listeners.add(e),()=>{r.listeners.delete(e)}}function be(e){let t=p().get(g(e));t!==void 0&&(t.scheduled?.settle("idle"),t.detector?.destroy(),t.detector=null,t.detectorPromise=null,t.promise=null,A(t,"idle"))}function le(e){return{get tier(){return e.tier},get fallbackReason(){return e.fallbackReason},detect:(...t)=>e.detect(...t),destroy:()=>{}}}function ee(e){let t=g(e),r=p().get(t);if(!(r===void 0||r.detector===null&&r.detectorPromise===null&&r.scheduled===null))return async()=>{r.scheduled!==null&&I(r,t);let s=r.promise;for(;r.detector===null&&s!==null&&(await s,r.promise!==s);)s=r.promise;return r.detector!==null?le(r.detector):v({v3AssetBaseUrl:t})}}function fe(e){switch(e){case"fcv3.no_face":case"fcv3.center_face":case"fcv3.straighten":return"center";case"fcv3.come_closer":return"closer";case"fcv3.move_back":return"farther";case"fcv3.more_light":case"fcv3.too_bright":return"light";case"fcv3.hold_still":case"fcv3.steady_camera":return"still";case"fcv3.hold_upright":return"upright";default:return null}}function pe(e){switch(e){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";default:return e}}function te(e){switch(e){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return e;default:{let t=e;return"generic"}}}function me(e,t,r){if(r===void 0)return{kind:te(e),retryable:t};let s=N(r.name);return{kind:te(e),retryable:t,detail:{...s!==void 0?{name:s}:{},phase:r.phase,engineKind:e}}}function ve(e,t={},r,s=()=>"self",u=()=>{}){let f=t.now??(()=>performance.now()),d=t.canChooseFacing??j,o="user",h=!1,S=n=>(n==="environment"&&!h&&(h=!0,console.warn('[@sekyro/web] facing "environment" ignored: this capture is a self capture (the person films themselves), which uses the front camera only. The back camera is for assisted capture, set in the flow.')),"user"),D=!1,m=s(),c=Z(),H=!G(),U=t.engineOptions,re=U?.createDetector===void 0&&U?.createWorker===void 0?{createDetector:()=>{let n=ee(e.assetBaseUrl);return n!==void 0?n():v({v3AssetBaseUrl:e.assetBaseUrl})}}:{},B={video:e.video,mode:H?"photo":"clip",rankKeyframes:r,facingMode:void 0,v3AssetBaseUrl:e.assetBaseUrl,screenRamp:()=>m==="self"&&c.count("ramp")>0?u():void 0,...t.engineOptions??{},...re},i=t.createEngine?.(B)??new Q(B),C="idle",L=null,E=0,k=!1,M="full",y=null,b=null,_=0,F=0,K=()=>{e.video.videoWidth>0&&e.video.videoHeight>0&&(_=e.video.videoWidth,F=e.video.videoHeight)},V=J({enabled:e.keepScreenAwake!==!1}),z=n=>{C=n,V.setActive(n==="starting"||n==="gating"||n==="recording"),c.emit("state",n)},O=()=>c.emit("gate",{progress:E,hint:L,faceDetected:k}),W=()=>{let n=i.animations??"full";n!==M&&(M=n,c.emit("profile",{animations:M}))},ne=[i.on("statechange",({state:n})=>{let a=pe(n);a==="starting"&&C!=="starting"&&(L=null,E=0,k=!1,y=null,b=null,_=0,F=0),z(a),W(),a==="recording"&&(K(),y=f(),L="hold",E=1,O())}),i.on("checks",n=>{K(),E=n.progress,k=n.factors.presence>0,O(),W()}),i.on("guidance",({key:n})=>{L=fe(n),O()}),i.on("frozen",({previewDataUrl:n})=>{b=f(),c.emit("frozen",{previewDataUrl:n})}),i.on("ramp",n=>c.emit("ramp",n)),i.on("artifacts",n=>{let a=q(),l=y!==null&&b!==null?Math.max(0,Math.round(b-y)):void 0;c.emit("captured",{keyframe:n.keyframe,...n.clip!==void 0?{clip:n.clip}:{},...n.clipMimeType!==void 0?{clipMime:n.clipMimeType}:{},width:e.video.videoWidth||_,height:e.video.videoHeight||F,...l!==void 0?{clipMs:l}:{},captureChannel:a==="desktop"?"desktop":"mobile",formFactor:a,...H?{degraded:"NO_RECORDER"}:{},engine:"v3",facingMode:i.facingMode,mode:m,...n.timing,...n.screenRamp!==void 0?{screenRamp:n.screenRamp}:{},...n.provenance!==void 0?{provenance:n.provenance}:{}})}),i.on("error",({kind:n,retryable:a,detail:l})=>{c.emit("error",me(n,a,l))})];return{handle:{get state(){return C},get captureMode(){return s()},get facingMode(){return i.facingMode??o},on:(n,a)=>c.on(n,a),start:n=>{if(m=s(),m==="self")return S(e.facing),S(n?.facing),D=!0,o="user",i.start({facingMode:"user"});let a=!D;D=!0;let l=n?.facing??(a?e.facing:void 0),R=w=>(o=w,i.start({facingMode:w}));return l!==void 0?R(l):a?d().then(w=>R(w?"environment":"user"),()=>R("user")):i.start({})},retry:()=>i.retry(),switchCamera:()=>s()!=="assisted"?!1:(m="assisted",o=o==="user"?"environment":"user",i.switchCamera(),!0),destroy:()=>{for(let n of ne)n();V.setActive(!1),i.destroy(),c.clear()}},setFlowState:n=>{C!==n&&z(n)}}}function Te(e){return ve(e).handle}export{se as a,X as b,Se as c,Ce as d,Le as e,Ee as f,ye as g,be as h,ee as i,fe as j,pe as k,te as l,me as m,ve as n,Te as o};
@@ -0,0 +1 @@
1
+ import{b as Jt}from"./chunk-SMKCBUJL.js";import{a as et,b as $t,c as te,e as dt,f as ee}from"./chunk-MXWLCDFX.js";import{d as Yt,h as Zt,k as qt}from"./chunk-G6LKLN4U.js";import{b as Xt,c as jt}from"./chunk-TDLIXFDT.js";import{b as Ht,c as Kt}from"./chunk-POIQGEZM.js";import{k as Nt,m as Qt,n as Ut,o as Wt}from"./chunk-CQ7SKLMC.js";import{b as ut,c as ht,d as j,e as Vt}from"./chunk-FPXL63KZ.js";import{d as Bt}from"./chunk-VIAT4DEA.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 ie(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 nt=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 n=new Map;for(let r of this.votes){let c=(e-r.atMs)/1e3,a=this.decayPerSecond**c;n.set(r.key,(n.get(r.key)??0)+a)}let o=this.current.key,s=-1;for(let[r,c]of n)c>s&&(s=c,o=r);return o!==this.current.key&&(this.current=it[o],this.currentSinceMs=e),this.current}};var Ke=Object.freeze({MAX_AREA_FRAC:.92,TILT_MAX_SIDE_RATIO:1.3,GLARE_MAX_SPECULAR_FRAC:.025});function oe(i){let{data:t,width:e,height:n}=i,o=e*n;if(o===0)return 0;let s=0;for(let r=0;r<o;r++){let c=r*4;.299*(t[c]??0)+.587*(t[c+1]??0)+.114*(t[c+2]??0)>=252&&s++}return s/o}function Ve(i){let t=(a,l)=>Math.hypot(l.x-a.x,l.y-a.y),e=t(i.topLeft,i.topRight),n=t(i.bottomLeft,i.bottomRight),o=t(i.topLeft,i.bottomLeft),s=t(i.topRight,i.bottomRight),r=Math.max(e,n)/Math.max(1e-6,Math.min(e,n)),c=Math.max(o,s)/Math.max(1e-6,Math.min(o,s));return Math.max(r,c)}function se(i){let t={...$t,...i.thresholds},e=Ke,{quad:n,frameWidth:o,frameHeight:s,measures:r}=i,c=i.format==="ID-3",a="ok";if(n===null)a="no_document";else if(c){let m=dt(n),h=o>0?m.width/o:0,f=m.height>0?m.width/m.height:0;h<t.ID3_BAND_MIN_WIDTH_FRAC?a="too_far":ne(n,o,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=te(n,o,s),h=dt(n),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":ne(n,o,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":jt(i.format,f)?Ve(n)>e.TILT_MAX_SIDE_RATIO&&(a="tilted"):a="wrong_shape"}let l=r.exposure>=t.GUIDE_EXPOSURE?"ok":r.meanLuma<(ut[0]+ut[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 ne(i,t,e,n){return[i.topLeft,i.topRight,i.bottomRight,i.bottomLeft].some(s=>s.x<=n||s.y<=n||s.x>=t-n||s.y>=e-n)}var ae=Object.freeze({width:1920,height:1080}),Xe=Object.freeze({width:3840,height:2160}),re=4096,je=2560,ce=640,ot=.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],n=Math.min(...t),o=Math.min(...e);return{x:n,y:o,width:Math.max(...t)-n,height:Math.max(...e)-o}}function le(i,t){let e=Math.max(0,Math.floor(i.x)),n=Math.max(0,Math.floor(i.y)),o=Math.min(t.width,Math.ceil(i.x+i.width)),s=Math.min(t.height,Math.ceil(i.y+i.height));return o-e<16||s-n<16?null:{x:e,y:n,width:o-e,height:s-n}}function Ye(i,t,e){if(i===null||t.width<=0||t.height<=0)return null;let n=E(i);if(n.width<=0||n.height<=0)return null;let o=e==="ID-3"?{x:n.x-n.width*Y.side,y:n.y-n.width*Y.above,width:n.width*(1+2*Y.side),height:n.height+n.width*(Y.above+Y.below)}:{x:n.x-n.width*ot,y:n.y-n.height*ot,width:n.width*(1+2*ot),height:n.height*(1+2*ot)};return le(o,t)}function mt(i,t,e){let n=Math.max(i,t);return n>0?Math.min(1,e/n):1}function ft(i,t,e,n,o=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=Ye(c,e,n)??{x:0,y:0,width:e.width,height:e.height},l=mt(a.width,a.height,o),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=le({x:(h.x-a.x)*l,y:(h.y-a.y)*l,width:h.width*l,height:h.height*l},{width:u,height:d})}return{crop:a,width:u,height:d,docRegion:m}}function ue(i,t,e,n=Xe){if(e==="LOW")return null;let o=i?.width?.max,s=i?.height?.max;if(typeof o!="number"||typeof s!="number"||o<=0||s<=0)return null;let r=Math.max(o,s),c=Math.min(o,s),a=Math.min(r,Math.max(n.width,n.height)),l=Math.min(c,Math.min(n.width,n.height));return a<=Math.max(t.width,t.height)?null:{width:{ideal:a},height:{ideal:l}}}function he(i){let t={},e=i?.imageWidth,n=i?.imageHeight;if(typeof e?.max=="number"&&e.max>0){let o=typeof n?.max=="number"&&n.max>0?e.max/n.max:1.3333333333333333,s=o>=1?re:re*o,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 de(i,t){if(i.width<=0||i.height<=0||t.width<=0||t.height<=0)return!1;let e=i.width>i.height,n=t.width>t.height;return e!==n&&i.width!==i.height&&t.width!==t.height?!1:Math.max(i.width,i.height)>=1.2*Math.max(t.width,t.height)}function me(i,t,e,n){if(e===null)return!1;let o=E(i),s=E(e);if(t.width<=0||n.width<=0)return!1;let r=o.width/t.width,c=s.width/n.width;return c>0&&r>=.6*c&&r<=1.25*c}var fe=3500,Ze=.92;function ge(){let i=globalThis.ImageCapture;return typeof i=="function"?i:null}function Je(i){return/AppleWebKit\//.test(i)&&!/(Chrome|Chromium|Edg|OPR)\//.test(i)}function be(i,t=typeof navigator>"u"?"":navigator.userAgent){return ge()!==null&&!Je(t)&&i!=null&&i.kind==="video"&&i.readyState==="live"}function pe(i,t){return new Promise((e,n)=>{let o=setTimeout(()=>n(new Error("takePhoto timed out")),t);i.then(s=>{clearTimeout(o),e(s)},s=>{clearTimeout(o),n(s)})})}function pt(i,t){let e=document.createElement("canvas");return e.width=i,e.height=t,e}function qe(i,t){return new Promise((e,n)=>{i.toBlob(o=>o?e(o):n(new Error("toBlob failed")),"image/jpeg",t)})}async function ye(i,t,e,n,o){let s=pt(e,n),r=pt(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,n);let a=await qe(s,Ze),l=o===null?null:Yt({topLeft:{x:o.x,y:o.y},topRight:{x:o.x+o.width,y:o.y},bottomRight:{x:o.x+o.width,y:o.y+o.height},bottomLeft:{x:o.x,y:o.y+o.height}},{width:e,height:n},{width:e,height:n}),u=Zt(s,l),d=mt(e,n,ce);return r.width=Math.max(1,Math.round(e*d)),r.height=Math.max(1,Math.round(n*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 $e(i,t){let e=Math.min(1,t/i.width),n=pt(Math.max(1,Math.round(i.width*e)),Math.max(1,Math.round(i.height*e)));try{let o=n.getContext("2d",{willReadFrequently:!0});return o===null?null:(o.imageSmoothingQuality="high",o.drawImage(i,0,0,n.width,n.height),o.getImageData(0,0,n.width,n.height))}finally{n.width=0,n.height=0}}async function Me(i,t,e,n){let o={width:Math.max(1,i.videoWidth),height:Math.max(1,i.videoHeight)},s=ft(t,e,o,n);return{...await ye(i,s.crop,s.width,s.height,s.docRegion),docRegion:s.docRegion,source:"video",width:s.width,height:s.height}}async function ke(i,t,e,n,o){let s=ge();if(s===null)return null;let r=null;try{let c=new s(o.track),a=await pe(c.getPhotoCapabilities?.()??Promise.resolve({}),fe).catch(()=>({})),l=await pe(c.takePhoto(he(a)),fe);r=await createImageBitmap(l);let u={width:i.videoWidth,height:i.videoHeight};if(!de(r,u))return null;let d=$e(r,o.detectWidth),m=null;d!==null&&t!==null&&(m=await o.detect(d).catch(()=>null));let h=d??{width:r.width,height:r.height};m!==null&&!me(m,h,t,e)&&(m=null);let f=ft(m,h,r,n);return{...await ye(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 Ti(i){let t=st,e=i!==null&&typeof i=="object"?i:{},n=e.fillDistanceM!==null&&typeof e.fillDistanceM=="object"?e.fillDistanceM:{},o=(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:o(e.lensSelection,t.lensSelection),continuousFocus:o(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(n.id1,.03,1)??t.fillDistanceM.id1,id3:S(n.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}}function ti(i){let t=i.toLowerCase();return t===""?"unknown":/front|facing front|user|selfie|face ?time/.test(t)?"front":/ultra|0\.5x|wide angle/.test(t)?"ultra":/tele|zoom|periscope|[2-9]x/.test(t)?"tele":/depth|tof|infrared|\bir\b|truedepth|lidar|macro|monochrome|mono\b/.test(t)?"depth":/dual|triple/.test(t)?"virtual":/back|rear|environment|facing back|arrière|خلفية/.test(t)?"main":"unknown"}function ei(i){let t=/camera2?\s*(\d+)/i.exec(i);return t?Number(t[1]):Number.POSITIVE_INFINITY}function ii(i){let t={main:0,virtual:1,ultra:9,tele:9,depth:9,front:9,unknown:9};return i.filter(e=>(e.kind===void 0||e.kind==="videoinput")&&e.deviceId!=="").map((e,n)=>({id:e.deviceId,kind:ti(e.label),index:ei(e.label),i:n})).filter(e=>t[e.kind]<9).sort((e,n)=>t[e.kind]-t[n.kind]||e.index-n.index||e.i-n.i).map(e=>e.id)}var gt="sekyro.doc.camera";function ni(){try{let i=globalThis.localStorage?.getItem(gt);return typeof i=="string"&&i!==""?i:null}catch{return null}}function xe(i){try{i===null?globalThis.localStorage?.removeItem(gt):globalThis.localStorage?.setItem(gt,i)}catch{}}var rt=(i,t)=>Array.isArray(i?.focusMode)&&i.focusMode.includes(t);function yt(i,t,e){if(!rt(i,"single-shot"))return null;let n=o=>Math.min(1,Math.max(0,Number.isFinite(o)?o:.5));return{focusMode:"single-shot",pointsOfInterest:[{x:n(t),y:n(e)}]}}function _i(i,t,e,n){if(!Number.isFinite(i)||!Number.isFinite(t)||e.width<=0||e.height<=0||n.width<=0||n.height<=0)return null;let o=Math.max(e.width/n.width,e.height/n.height),s=n.width*o,r=n.height*o,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 we(i,t,e,n=st){let o=i?.zoom?.min,s=i?.zoom?.max;if(typeof s!="number"||s<=1)return 1;let r=e==="ID-3"?n.fillDistanceM.id3:n.fillDistanceM.id1,c=i?.focusDistance?.min,a;if(typeof c=="number"&&c>0&&c<1){if(a=c*(1+n.focusMarginFrac)/r,a<=1.05)return 1}else{if(Math.min(t.width,t.height)<n.zoomMinSourcePx)return 1;a=n.zoomNoFocusInfo}let l=Math.min(a,n.zoomMax,s);typeof o=="number"&&(l=Math.max(l,o));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 bt(i){try{return i.getVideoTracks?.()[0]}catch{return}}function De(i){if(i!==null)for(let t of i.getTracks())t.stop()}function oi(i){try{let t=bt(i)?.getCapabilities?.();return!Array.isArray(t?.focusMode)||t.focusMode.includes("continuous")}catch{return!0}}var si=3;async function ve(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}})),n=()=>i.getUserMedia(t({facingMode:{ideal:"environment"}}));if(i.lensSelection){let s=ni();if(s!==null)try{return{stream:await e(s),lens:"stored"}}catch{xe(null)}}let o=await n();if(!i.lensSelection||i.enumerateDevices===void 0)return{stream:o,lens:"default"};try{let s=ii(await i.enumerateDevices()).slice(0,si);if(s.length===0)return{stream:o,lens:"default"};let r=null;for(let c of s){let a=o!==null?bt(o)?.getSettings?.().deviceId:void 0;if(o===null||a!==c){De(o),o=null;try{o=await e(c)}catch{continue}}if(r??(r=c),oi(o))return xe(c),{stream:o,lens:"selected"}}if(o!==null&&r!==null&&bt(o)?.getSettings?.().deviceId===r)return{stream:o,lens:"selected"};if(De(o),o=null,r!==null)try{return{stream:await e(r),lens:"selected"}}catch{}return{stream:await n(),lens:"default"}}catch{return{stream:o??await n(),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 Te(i,t,e,n=.06){let o=Math.max(i.width/e,i.height),s=o*e,r=(i.width-s)/2,c=(i.height-o)/2,a=L((t.x-t.width*n-r)/s),l=L((t.y-t.height*n-c)/o),u=L((t.x+t.width*(1+n)-r)/s),d=L((t.y+t.height*(1+n)-c)/o);return{x:a,y:l,width:u-a,height:d-l}}function _e(i,t,e={}){let n=e.edgePeakFrac??0,{width:o,height:s,data:r}=i;if(o<=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*o,d=l.y*s,m=(l.x+l.width)*o,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,o-1),w=y(Math.floor(d-g),0,s-1),I=y(Math.ceil(m+f),x+1,o),v=y(Math.ceil(h+g),w+1,s),D=Math.max(1,Math.ceil(Math.max(I-x,v-w)/320)),M=Math.floor((I-x+D-1)/D),T=Math.floor((v-w+D-1)/D);if(M<3||T<3)return Z;let k=new Int32Array(M*T);for(let p=0;p<T;p++){let b=w+p*D;for(let R=0;R<M;R++){let F=(b*o+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,_=C(u,x),A=C(m,x),B=C(d,w),U=C(h,w),kt=(m-u)/D,xt=(h-d)/D,Dt=y(Math.ceil(_),0,M-1),Ie=y(Math.floor(A),Dt,M-1),wt=y(Math.ceil(B),0,T-1),Oe=y(Math.floor(U),wt,T-1),vt=0,St=0,W=0,Tt=0,_t=0,H=0;for(let p=wt;p<=Oe;p++)for(let b=Dt;b<=Ie;b++){let R=k[p*M+b];if(vt+=R,R>=248&&St++,W++,b>=1&&b<M-1&&p>=1&&p<T-1){let F=k[p*M+b-1]+k[p*M+b+1]+k[(p-1)*M+b]+k[(p+1)*M+b]-4*R;Tt+=F,_t+=F*F,H++}}let Pe=W>0?vt/W:0,Rt=W>0?St/W:0,Ft=H>0?Tt/H:0,Ge=H>0?Math.max(0,_t/H-Ft*Ft):0,K=new Float64Array(M),V=new Float64Array(T);for(let p=0;p<T;p++)for(let b=1;b<M-1;b++)K[b]=K[b]+Math.abs(k[p*M+b+1]-k[p*M+b-1]);for(let p=1;p<T-1;p++)for(let b=0;b<M;b++)V[p]=V[p]+Math.abs(k[(p+1)*M+b]-k[(p-1)*M+b]);let O=at(K,!0,_,n),P=at(K,!1,A,n),G=at(V,!0,B,n),z=at(V,!1,U,n),Ct=(P.position-O.position)/kt,At=(z.position-G.position)/xt,ze=At>0?Ct/At:0,Ne=((O.position+P.position)/2-(_+A)/2)/kt,Qe=((G.position+z.position)/2-(B+U)/2)/xt,Et=Se(K),Lt=Se(V),Be=Et<=0||Lt<=0?0:Math.min(Math.min(O.value,P.value)/Et,Math.min(G.value,z.value)/Lt),$=(p,b)=>b+(p+.5)*D,It=Rt,Ot=0;{let p=(P.position-O.position)*.06,b=(z.position-G.position)*.06,R=y(Math.ceil(O.position+p),0,M-1),F=y(Math.floor(P.position-p),0,M-1),Ue=y(Math.ceil(G.position+b),0,T-1),Pt=y(Math.floor(z.position-b),0,T-1),Gt=0,tt=0,zt=0;for(let N=Ue;N<=Pt;N++)for(let Q=R;Q<=F;Q++){tt++;let X=k[N*M+Q];X>=248&&Gt++;let We=Q+2<=F?k[N*M+Q+2]:X,He=N+2<=Pt?k[(N+2)*M+Q]:X;(Math.abs(We-X)>=24||Math.abs(He-X)>=24)&&zt++}tt>=16&&(It=Gt/tt,Ot=zt/tt)}return{brightness:Pe,glare:Rt,cardGlare:It,sharpness:Ge,fill:Ct,shape:ze,content:Ot,offsetX:Ne,offsetY:Qe,edgeConfidence:Be,box:{left:$(O.position,x),right:$(P.position,x),top:$(G.position,w),bottom:$(z.position,w)}}}function at(i,t,e,n){let o=i.length,s=Math.max(1,Math.floor(o*.45)),r=t?1:Math.max(1,o-1-s),c=t?Math.min(o-2,s):o-2,a=r;for(let h=r;h<=c;h++)i[h]>i[a]&&(a=h);if(n>0&&n<1){let h=i[a]*n,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<o-1?i[a+1]:0,m=l+u+d;return{position:m>0?a+(d-l)/m:a,value:u}}function Se(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 Re(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 Fi(i){let t=i!==null&&typeof i=="object"?i:{},e={...J};for(let n of Object.keys(J)){let o=t[n];typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1e6&&(e[n]=o)}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 n=this.t,o=n.shapeTolerance<=0||Math.abs(t.shape-1)<=n.shapeTolerance,s=t.edgeConfidence>=n.edgeConfidenceMin&&o&&t.content>=n.contentMin,r=t.fill>=n.fillMin&&t.fill<=n.fillMax,c=Math.abs(t.offsetX)<=n.offsetMax&&Math.abs(t.offsetY)<=n.offsetMax,a=t.cardGlare<=n.glareMax,l=t.sharpness>=n.sharpnessMin,u=this.last;this.last={fill:t.fill,offsetX:t.offsetX,offsetY:t.offsetY,at:e};let d=u!==null&&n.steadyRefMs>0?Math.min(3,Math.max(1,(e-u.at)/n.steadyRefMs)):1,m=s&&a&&l&&t.fill>=n.steadyFillMin&&t.fill<=n.steadyFillMax&&u!==null&&Math.abs(t.fill-u.fill)<=n.steadyFillDelta*d&&Math.abs(t.offsetX-u.offsetX)<=n.steadyOffsetDelta*d&&Math.abs(t.offsetY-u.offsetY)<=n.steadyOffsetDelta*d,h=s&&r&&c&&a&&l,f;if(s?a?t.fill<n.fillMin?f="too_small":t.fill>n.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>=n.lockMs)return{detected:s,ready:!0,via:"good",blocker:"locking"};let g=this.steadySince!==null&&e-this.steadySince>=n.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>=n.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 ri(i){return q===null&&(q=(await import("./detector-scanic-YCDNLCGV.js")).detectQuad),q(i)}async function ai(i){let t=Jt(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 Vi(){q===null&&import("./detector-scanic-YCDNLCGV.js").then(i=>{q=i.detectQuad}).catch(()=>{})}var Fe=4e3,ci=2,Ce=3,li=Object.freeze({LOW:3,MID:5,HIGH:6}),Mt=Object.freeze({manualShutterMs:6e3,detectedNoLockMs:1950});function Xi(i){let t=i!==null&&typeof i=="object"?i:{},e=(n,o,s)=>typeof n=="number"&&Number.isFinite(n)&&n>=o&&n<=s?n:void 0;return{manualShutterMs:e(t.manualShutterMs,1e3,6e4)??Mt.manualShutterMs,detectedNoLockMs:e(t.steadyMs,300,3e4)!==void 0?t.steadyMs+(e(t.lockMs,0,1e4)??450):Mt.detectedNoLockMs}}var Ae=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 nt;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 ee(t.format??"ID-1",t.thresholds);let e=t.deviceClass??Kt(Ht());this.deviceClass=e,this.camera=t.camera??st,this.shutterTuning=t.shutter??Mt,this.guideTuning=t.guideLock??J,this.guideLock=new ct(this.guideTuning),this.cadenceMs=1e3/li[e]}on(t,e){let n=this.handlers.get(t);return n||(n=new Set,this.handlers.set(t,n)),n.add(e),()=>n?.delete(e)}emit(t,e){for(let n of[...this.handlers.get(t)??[]])n(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(),Wt(),this.setState("preflight");try{let n=this.opts.getUserMedia??(r=>navigator.mediaDevices.getUserMedia(r));this.setState("acquiring");let o=this.opts.enumerateDevices??(this.opts.getUserMedia===void 0&&typeof navigator<"u"&&navigator.mediaDevices?.enumerateDevices?()=>navigator.mediaDevices.enumerateDevices():void 0),s=await ve({getUserMedia:n,...o!==void 0?{enumerateDevices:o}:{},lensSelection:this.camera.lensSelection,base:ae});if(e!==this.attempt){for(let r of s.stream.getTracks())r.stop();return}if(this.stream=s.stream,Bt(this.stream),Ut(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(n){if(e!==this.attempt)return;let o=Qt(n),s=Nt(n);this.setState("error"),this.emit("error",{kind:o,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??Fe;e<=0||(this.clearFrameWatch(),this.frameWatch=setTimeout(()=>{if(this.frameWatch=null,!(t!==this.attempt||this.state!=="positioning")){if(this.framesNow()&&this.blackTicks<Ce){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 n=()=>{t===this.attempt&&(this.state==="positioning"||this.state==="acquiring")&&this.cameraDead(t)};e.addEventListener("ended",n),this.offEnded=()=>e.removeEventListener?.("ended",n)}cameraDead(t){if(t!==this.attempt)return;let e=this.videoTrack(),n=e!==null&&e.readyState==="live"&&!e.muted&&this.opts.video.paused&&!this.framesNow();if(!n&&!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(),n||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),n=this.lastDetect?.height??Math.max(1,t.videoHeight),o=this.lastQuad??this.lastGuideQuad??{topLeft:{x:0,y:0},topRight:{x:e,y:0},bottomRight:{x:e,y:n},bottomLeft:{x:0,y:n}},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:o,{width:e,height:n,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",n=t.report(e,this.stats.via,(this.opts.now??(()=>performance.now()))());return n===null?{}:{ocr:n}}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),n=this.opts.guide;if(n!==void 0&&n.viewAspect>0){let c={width:n.viewAspect,height:1},a={x:n.rect.x*n.viewAspect,y:n.rect.y,width:n.rect.width*n.viewAspect,height:n.rect.height};return Te(c,a,e,0)}let o=Xt(this.opts.format??"ID-1").center,s=.86,r=s*e/o;return r>.84&&(r=.84,s=r*o/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 n=this.focusCaps(),o=typeof n?.zoom?.min=="number"?Math.max(n.zoom.min,1):1;this.zoom=o,this.stats.zoomFallbackAtMs=Math.round(t-(this.positioningSince??t)),this.guideLock.reset(),this.gate.reset(),e.applyConstraints({advanced:[{zoom:o}]}).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?.()??{},n=ue(t.getCapabilities?.(),{width:e.width??0,height:e.height??0},this.deviceClass,{width:this.camera.width,height:this.camera.height});n!==null&&await t.applyConstraints(n)}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 n={width:0,height:0};try{let s=t.getSettings?.()??{};n={width:s.width??0,height:s.height??0}}catch{}let o=we(e,n,this.opts.format??"ID-1",this.camera);if(o>1)try{await t.applyConstraints({advanced:[{zoom:o}]}),this.zoom=o}catch{this.zoom=1}}async focusAt(t,e){let n=this.videoTrack(),o=yt(this.focusCaps(),t,e);if(!(n===null||o===null))try{await n.applyConstraints({advanced:[o]}),(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 n=this.camera.refocusBeforePhotoMs,o=this.videoTrack();if(n<=0||o===null||e.width<=0||e.height<=0)return;let s=E(t),r=yt(this.focusCaps(),(s.x+s.width/2)/e.width,(s.y+s.height/2)/e.height);if(r!==null)try{await o.applyConstraints({advanced:[r]});let c=this.opts.setTimer??setTimeout;await new Promise(a=>{c(()=>a(),n)})}catch{}}videoTrack(){try{return this.stream?.getVideoTracks?.()[0]??null}catch{return null}}async takeStill(t,e,n){if(this.opts.captureStill!==void 0)return this.opts.captureStill(this.opts.video,t,e);let o=this.opts.format??"ID-1",s=this.videoTrack();if(n&&this.opts.photoCapture!==!1&&this.deviceClass!=="LOW"&&!this.torchOn&&s!==null&&be(s)){await this.refocusOn(t,e);let r=await ke(this.opts.video,t,e,o,{track:s,detect:this.detector(),detectWidth:et});if(this.restoreContinuous(),r!==null)return r}return Me(this.opts.video,t,e,o)}detector(){return this.opts.detect??((this.opts.format??"ID-1")==="ID-3"?ai:ri)}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()),n=this.opts.grabDetectFrame??Le,o=this.detector(),s=n(this.opts.video,et);if(s===null){this.scheduleTick(t);return}if(!this.lit){if(ht(s)>ci)this.lit=!0,this.blackTicks=0;else if(++this.blackTicks>=Ce&&this.frameWatch===null&&(this.opts.firstFrameMs??Fe)>0){this.cameraDead(t);return}}let r=null;try{r=await o(s)}catch{r=null}if(t!==this.attempt)return;let c=r!==null?lt(s,r):s,a=e(),l={sharpness:j(c),exposure:Vt(c),meanLuma:ht(c),specularFraction:oe(c)},u=se({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"?_e(s,this.guideRegion(s),{edgePeakFrac:this.guideTuning.edgePeakFrac}):Z,f=this.guideLock.tick(h,a);this.lastGuideQuad=f.detected?Re(h):null;let g=this.capturing?null:this.ocrTick(s,r,h,f.detected,u,a);this.positioningSince??(this.positioningSince=a);let y=this.stats;if(y.ticks+=1,y.quadFraming[u.framing]=(y.quadFraming[u.framing]??0)+1,u.framing==="ok"&&!d.ready){let _=u.lighting!=="ok"?u.lighting:u.glare!=="ok"?"glare":u.blur!=="ok"?"blurry":"steadying";y.qualityBlockers[_]=(y.qualityBlockers[_]??0)+1}y.guideBlockers[f.blocker]=(y.guideBlockers[f.blocker]??0)+1,r!==null||f.detected?(this.detectedSince??(this.detectedSince=a),this.lastSeenAt=a):this.detectedSince=null,this.lastSeenAt!==null&&a-this.lastSeenAt<=gi?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 I=a-(this.lastSeenAt??this.positioningSince);this.zoom>1&&this.camera.zoomFallbackMs>0&&I>=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=ie(u);u.framing!=="ok"&&f.detected&&(v=pi(f.blocker,h.brightness<this.guideTuning.darkBrightness)),v==="blurry"&&r!==null&&hi(r,s,this.opts.format??"ID-1")>=this.camera.focusFarFillFrac&&(v="focus_far"),v==="sensing"&&this.zoom>1&&this.camera.noDocFarHintMs>0&&I>=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,T=M&&d.ready&&r!==null,k=M&&f.ready&&this.lastGuideQuad!==null,C=this.lastOcrReady;if(C!==null&&this.opts.autoCapture!==!1){let _=this.feedback.force("processing",a);this.lastFeedbackKey=_.key,this.emit("feedback",_);let A=j(lt(s,C.quad));await this.fire(t,C.quad,{width:s.width,height:s.height,tickSharpness:A},C.via);return}if((T||k)&&this.opts.autoCapture!==!1){let _=this.feedback.force("processing",a);this.lastFeedbackKey=_.key,this.emit("feedback",_);let A=k?this.lastGuideQuad:r,B=k?f.via==="steady"?"guide_steady":"guide_good":"quad",U=k?j(lt(s,A)):l.sharpness;await this.fire(t,A,{width:s.width,height:s.height,tickSharpness:U},B);return}this.scheduleTick(t)}async fire(t,e,n,o){this.capturing=!0;let s=this.opts.grabDetectFrame??Le,r=this.opts.setTimer??setTimeout,c={width:n.width,height:n.height};try{let a={still:await this.takeStill(e,c,!0),sharpness:n.tickSharpness};if(t!==this.attempt)return;let l=a.still.source==="photo"?0:di;for(let m=0;m<l;m++){if(await new Promise(g=>{r(()=>g(),mi)}),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*fi){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&&o!=="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,(o==="text_lock"||o==="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=o,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=o==="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,(o==="text_lock"||o==="live_mrz")&&this.opts.ocr?.rearmFace(),this.scheduleTick(t)}}ocrTick(t,e,n,o,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=ui(E(e),g,y,l,u):x=qt(f,c.bandTop,u);let w=m?s.glare==="ok":n.cardGlare<=this.guideTuning.glareMax,I=m?s.blur==="ok":n.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||o,card:f,band:x,portrait:u>l,glareOk:w,sharpOk:I});if(v.ready&&v.via!==void 0){let D=m?e??Ee(h,t):this.lastGuideQuad??Ee(h,t);this.lastOcrReady={quad:D,via:v.via}}else this.lastOcrReady=null;return v}};function ui(i,t,e,n,o){let s=Math.min(n,i.width*1.06*t),r=Math.min(o,Math.max(i.height*1.6*e,s/5)),c=(i.y+i.height/2)*e,a=Math.max(0,Math.min(n-s,(i.x-i.width*.03)*t)),l=Math.max(0,Math.min(o-r,c-r/2));return{x:a,y:l,w:s,h:r}}function Ee(i,t){let e=i.x*t.width,n=i.y*t.height,o=(i.x+i.width)*t.width,s=(i.y+i.height)*t.height;return{topLeft:{x:e,y:n},topRight:{x:o,y:n},bottomRight:{x:o,y:s},bottomLeft:{x:e,y:s}}}function hi(i,t,e){let n=E(i);return t.width<=0||t.height<=0?0:e==="ID-3"?n.width/t.width:n.width*n.height/(t.width*t.height)}var di=2,mi=260,fi=1.08;function Le(i,t){let e=i.videoWidth,n=i.videoHeight;if(e===0||n===0)return null;let o=Math.min(1,t/e),s=Math.round(e*o),r=Math.round(n*o),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],n=[t.topLeft.y,t.topRight.y,t.bottomRight.y,t.bottomLeft.y],o=Math.max(0,Math.floor(Math.min(...e))),s=Math.max(0,Math.floor(Math.min(...n))),r=Math.min(i.width,Math.ceil(Math.max(...e))),c=Math.min(i.height,Math.ceil(Math.max(...n))),a=Math.max(1,r-o),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+o)*4;u.set(i.data.subarray(m,m+a*4),d*a*4)}return{data:u,width:a,height:l,colorSpace:i.colorSpace}}function pi(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 gi=1200;export{it as a,ie as b,nt as c,Ke as d,oe as e,Ve as f,se as g,st as h,Ti as i,ti as j,ii as k,gt as l,ni as m,xe as n,rt as o,yt as p,_i as q,we as r,oi as s,si as t,ve as u,Z as v,Te as w,_e as x,Re as y,J as z,Fi as A,ct as B,Vi as C,Fe as D,ci as E,Ce as F,li as G,Mt as H,Xi as I,Ae as J,ui as K,di as L,mi as M};
@@ -0,0 +1 @@
1
+ var a=Object.freeze({LOW:Object.freeze({cadenceHz:5,inputWidth:128,animations:"reduced"}),MID:Object.freeze({cadenceHz:8,inputWidth:160,animations:"full"}),HIGH:Object.freeze({cadenceHz:10,inputWidth:192,animations:"full"})}),u=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);function o(){let t=typeof navigator>"u"?void 0:navigator,e=!1;try{e=typeof WebAssembly<"u"&&WebAssembly.validate(u)}catch{e=!1}return{cores:t?.hardwareConcurrency??2,memGB:t?.deviceMemory??null,simd:e}}function l(t){let e=t.memGB??4;return t.cores<4||e<3?"LOW":t.cores>=8&&e>=6?"HIGH":"MID"}var n=["LOW","MID","HIGH"],i=class{constructor(e){this.samples=[];this.adjusted=!1;this.current=e}get deviceClass(){return this.current}get profile(){return a[this.current]}record(e){if(this.adjusted||this.samples.length>=10)return this.current;if(this.samples.push(e),this.samples.length<10)return this.current;this.adjusted=!0;let s=this.samples.reduce((r,c)=>r+c,0)/this.samples.length;if(s>70)this.current="LOW";else if(s<25){let r=n.indexOf(this.current);this.current=n[Math.min(n.length-1,r+1)]??this.current}return this.current}};export{a,o as b,l as c,i as d};
@@ -0,0 +1 @@
1
+ import{d as J,h as he,i as ye,j as Se,l as Me}from"./chunk-G6LKLN4U.js";import{f as be}from"./chunk-TDLIXFDT.js";import{m as V}from"./chunk-P3H3D33O.js";import{a as fe,e as ge}from"./chunk-GT2ZLGF7.js";import{k as $}from"./chunk-CQ7SKLMC.js";var qe={low:{maxLongEdge:1920,payloadTargetBytes:7e5,qMin:.7,qMax:.92},mid:{maxLongEdge:2240,payloadTargetBytes:12e5,qMin:.7,qMax:.92},good:{maxLongEdge:2560,payloadTargetBytes:16e5,qMin:.7,qMax:.92}};function He(e){let{deviceMemory:t,effectiveType:n,saveData:r,downlinkMbps:i,sourceLongEdge:l}=e,s=r===!0||n==="slow-2g"||n==="2g"||i!=null&&i>0&&i<1,u=t!=null&&t<=2,c=n==="4g"||i!=null&&i>=5,f=t!=null&&t>=6,p;s||u?p="low":c&&f?p="good":p="mid";let b=qe[p],S=l&&l>0?Math.min(b.maxLongEdge,l):b.maxLongEdge;return{tier:p,...b,maxLongEdge:S}}function ke(e){let t={};try{let n=navigator;typeof n.deviceMemory=="number"&&(t.deviceMemory=n.deviceMemory);let r=n.connection;r&&(t.effectiveType=r.effectiveType,t.saveData=r.saveData,t.downlinkMbps=r.downlink)}catch{}return typeof e=="number"&&e>0&&(t.sourceLongEdge=e),He(t)}function Xe(e,t,n){let r=Math.min(1,Math.max(0,(e-.28)/.21999999999999997)),i=(t+n)/2;return Math.max(t,n-r*(n-i))}function Ve(e,t,n){let r=Math.max(e,t),i=r>0?Math.min(1,n/r):1;return{width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(t*i))}}async function Ye(e,t){let n=t.startQ,r=await e(n);for(let i=0;i<4&&!(r.size<=t.budgetBytes||n<=t.qMin);i++)n=Math.max(t.qMin,n-.08),r=await e(n);return{blob:r,quality:n}}async function De(e,t,n,r,i){if(t<=0||n<=0)return null;let{width:l,height:s}=Ve(t,n,r.maxLongEdge),u=document.createElement("canvas");u.width=l,u.height=s;let c=u.getContext("2d");if(!c)return null;c.drawImage(e,0,0,l,s);let f=I=>new Promise((h,w)=>{u.toBlob(d=>d?h(d):w(new Error("canvas toBlob returned null")),"image/jpeg",I)}),p=Xe(i,r.qMin,r.qMax),{blob:b,quality:S}=await Ye(f,{startQ:p,qMin:r.qMin,budgetBytes:r.payloadTargetBytes}).finally(()=>{u.width=0,u.height=0});if(b.size>5242880)throw new Error("encoded document exceeds the 5242880-byte media cap");return{blob:b,quality:S,width:l,height:s}}async function Z(e){let t=ke(Math.max(e.width,e.height)),n=await De(e,e.width,e.height,t,.5);if(n===null)throw new Error("canvas encode unavailable");return{blob:n.blob,width:n.width,height:n.height}}async function mt(e){let t=await createImageBitmap(e);try{return await Z(t)}finally{t.close()}}var ft=250,gt=.6,bt=1800,ht=6e3,yt=2e3,we=.16;function te(e,t){return{layout:e,phase:"framing",captured:{},pending:[],lastCaptureAt:t,lastReportAt:t,manualShutter:!1,restPhase:"framing",readSides:[],needFlip:!1,flipped:!1,flipTimeoutSpent:!1,timeoutCapture:!1,lastShotByTimeout:!1}}var Ce=e=>e==="recto"?"verso":"recto",Re=e=>e.phase==="framing"||e.phase==="locking"||e.phase==="flipCue"||e.phase==="reaskRecto",ne=e=>(e.captured.recto!==void 0?1:0)+(e.captured.verso!==void 0?1:0)+e.pending.length;function ee(e,t){return e.lastCaptureAt>=0&&e.lastReportAt>=0?e:{...e,lastCaptureAt:e.lastCaptureAt<0?t:e.lastCaptureAt,lastReportAt:e.lastReportAt<0?t:e.lastReportAt}}function Qe(e,t,n){if(e.phase==="result")return{...e,lastReportAt:n};let r=!t.present||e.captureArea!==void 0&&t.areaFrac<.6*e.captureArea,{flipped:i,awaySince:l}=e;r&&(l=l??n),l!==void 0&&n-l>=250&&(i=!0),r||(l=void 0);let s=e.flipTimeoutSpent&&!(i&&!e.flipped),u={...e,lastReportAt:n,flipped:i,awaySince:l,flipTimeoutSpent:s,lastArea:t.areaFrac};if(!Re(e))return u;if(e.needFlip&&!i){if(!t.ready)return{...u,phase:e.restPhase,goodSince:void 0};let c=e.lastShot!==void 0&&e.pending.includes(e.lastShot);if(s||c)return{...u,goodSince:void 0,phase:e.restPhase};let f=e.goodSince??n;return n-f>=1800?{...u,goodSince:f,phase:"capturing",flipTimeoutSpent:!0,timeoutCapture:!0}:{...u,goodSince:f,phase:e.restPhase}}return t.ready?{...u,phase:"capturing",goodSince:e.goodSince??n}:{...u,goodSince:void 0,phase:t.locking?"locking":e.restPhase}}function Ke(e,t){if(!Re(e)||e.manualShutter)return e;let n=t-e.lastReportAt>=2e3,r=t-e.lastCaptureAt>=6e3;return n||r?{...e,manualShutter:!0}:e}function je(e,t,n){let r=e.layout==="singlePage",i=r?{recto:t}:e.captured,l=r?[]:[...e.pending,t],s={...e,captured:i,pending:l,lastShot:t,lastCaptureAt:n,lastReportAt:-1,manualShutter:!1,goodSince:void 0,notice:void 0,awaySince:void 0,flipped:!1,lastShotByTimeout:e.timeoutCapture,timeoutCapture:!1,captureArea:e.lastArea};return r||ne({captured:i,pending:l})>=2?{...s,phase:"reading",restPhase:"framing",current:void 0,needFlip:!1}:{...s,phase:"flipCue",restPhase:"flipCue",current:void 0,needFlip:!0}}function xe(e,t,n){return e.pending.includes(t)?{...e,pending:e.pending.filter(r=>r!==t),lastShot:e.lastShot===t?void 0:e.lastShot,phase:e.phase==="capturing"?e.phase:"flipCue",restPhase:"flipCue",current:Ce(n),needFlip:!0,flipTimeoutSpent:!0,goodSince:void 0,manualShutter:!0,notice:"same_face",lastCaptureAt:-1,lastReportAt:-1}:e}function $e(e,t,n){if(!e.pending.includes(t))return e;if(e.captured[n]!==void 0)return xe(e,t,n);let r=e.pending.filter(c=>c!==t),i={...e,pending:r,captured:{...e.captured,[n]:t}};if(ne(i)!==1||e.layout==="singlePage")return i;let l=Ce(n),s=l==="recto"&&e.restPhase==="reaskRecto"?"reaskRecto":"flipCue",u=e.phase==="flipCue"||e.phase==="reaskRecto"||e.phase==="framing";return{...i,restPhase:s,current:l,phase:u?s:e.phase}}function Je(e,t){let n=t.id??e.captured[t.side],r={...e.captured};(t.id===void 0||r[t.side]===t.id)&&delete r[t.side];let i=e.pending.filter(f=>f!==n),l=e.layout==="twoSided"&&ne({captured:r,pending:i})>0,s=e.lastShotByTimeout||n===e.lastShot!==e.flipped,u=l&&!s,c=u?t.side==="recto"?"reaskRecto":"flipCue":"framing";return{...e,captured:r,pending:i,readSides:e.readSides.filter(f=>f!==t.side),lastShot:e.lastShot===n?void 0:e.lastShot,notice:t.issue,goodSince:void 0,manualShutter:!1,phase:c,restPhase:c,current:t.side,needFlip:u,flipped:!1,flipTimeoutSpent:!1,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1}}function ve(e,t){switch(t.type){case"report":return Qe(ee(e,t.at),t.report,t.at);case"tick":return Ke(ee(e,t.at),t.at);case"captured":return je(ee(e,t.at),t.id,t.at);case"captureFailed":return{...e,phase:e.restPhase,goodSince:void 0,lastCaptureAt:t.at,manualShutter:!0,timeoutCapture:!1};case"classified":return $e(e,t.id,t.side);case"duplicate":return xe(e,t.id,t.side);case"readOk":{let n=e.readSides.includes(t.side)?e.readSides:[...e.readSides,t.side],r=["recto","verso"].filter(l=>e.captured[l]!==void 0),i=e.phase==="reading"&&e.pending.length===0&&r.every(l=>n.includes(l));return{...e,readSides:n,flipTimeoutSpent:!1,phase:i?"result":e.phase}}case"readFailed":return Je(e,t);case"clockRestart":return e.lastCaptureAt<0&&e.lastReportAt<0&&e.awaySince===void 0?e:{...e,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1};case"retake":return{...te(e.layout,-1),lastCaptureAt:-1,lastReportAt:-1};default:return e}}function Ze(e,t,n=!1){let r=e(t);return r===null?"recto":!n||r.y+r.height/2>=t.height/2?"verso":"recto"}async function et(e,t=!1){let{detectMrzBand:n}=await import("./mrz-band-VYHOTDHY.js");return Ze(n,e,t)}async function re(e,t=480,n,r=n!=null){let i=n??{x:0,y:0,width:e.width,height:e.height},l=Math.max(1,Math.round(i.height/i.width*t)),s=document.createElement("canvas");s.width=t,s.height=l;try{let u=s.getContext("2d");return u===null?"recto":(u.drawImage(e,i.x,i.y,i.width,i.height,0,0,t,l),await et(u.getImageData(0,0,t,l),r))}finally{s.width=0,s.height=0}}async function Mt(e,t=480){try{let n=await createImageBitmap(e),r=Math.max(1,Math.round(n.height/n.width*t)),i=document.createElement("canvas");i.width=t,i.height=r;let l=i.getContext("2d");return l===null?(n.close(),null):(l.drawImage(n,0,0,t,r),n.close(),l.getImageData(0,0,t,r))}catch{return null}}var oe=(e,t,n)=>Math.min(n,Math.max(t,Math.round(e))),Y=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function Le(e,t,n,r){let i=r.decode??(c=>createImageBitmap(c)),l=async()=>e.stillRead(await i(t),r.region??[0,0,1,1],r.detectorLimit),s;try{s=await l()}catch{try{await new Promise(c=>setTimeout(c,r.retryMs??300)),s=await l()}catch{return null}}let u=s.mrzBox;return u===void 0?null:{engine:r.engine,source:"live_mrz",format:n.format,lineCount:oe(n.lineCount,2,3),checkDigitsValid:!0,stillConfirmed:s.valid&&s.digest===n.digest,band:[Y(u[0]),Y(u[1]),Y(Math.min(u[2],1-u[0])),Y(Math.min(u[3],1-u[1]))],digest:n.digest,framesToValid:oe(n.framesToValid,1,1e3),msToValid:oe(n.msToValid,0,12e4)}}function Dt(e){let t=null;return e?.then(n=>{t=n}),()=>t}var tt=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]),nt=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,7,1,5,0,6,64,11,11]);function _e(e,t=globalThis){let n=t.WebAssembly?.validate;if(typeof n!="function")return{ok:!1,reason:"simd"};try{if(!n.call(t.WebAssembly,tt)||!n.call(t.WebAssembly,nt))return{ok:!1,reason:"simd"}}catch{return{ok:!1,reason:"simd"}}if(typeof t.Worker!="function")return{ok:!1,reason:"worker"};if(typeof t.createImageBitmap!="function")return{ok:!1,reason:"bitmap"};let r=t.navigator?.deviceMemory;return typeof r=="number"&&r<e.minDeviceMemoryGb?{ok:!1,reason:"memory"}:{ok:!0}}function Te(e=globalThis){let t=e.navigator?.connection;return t?.saveData===!0||["slow-2g","2g","3g"].includes(t?.effectiveType??"")}var T=class extends Error{constructor(t){super(t),this.name="OcrEngineError",this.code=t}};function Ee(){let e=t=>(t.close(),Promise.reject(new T("unsupported")));return{ready:Promise.resolve("unsupported"),busy:!1,bandRead:e,stillRead:e,layoutRead:e,dispose:()=>{}}}function Oe(e){let t;try{if(e.createWorker)t=e.createWorker();else if(e.workerUrl!==void 0)t=new Worker(e.workerUrl,{type:"module",name:"sekyro-ocr"});else return Ee()}catch{return Ee()}let n=new Map,r=0,i=!1,l=!1,s=!1;t.addEventListener("message",d=>{let g=d.data,C=n.get(g.id);C&&(n.delete(g.id),C.resolve(g))});let u=()=>{for(let d of n.values())d.reject(new T("error"));n.clear(),f()};t.addEventListener("error",u),t.addEventListener("messageerror",u);function c(d,g=[]){if(i)return Promise.reject(new T("disposed"));let C=++r;return new Promise((B,O)=>{n.set(C,{resolve:B,reject:O});try{t.postMessage({...d,id:C},g)}catch{n.delete(C),O(new T("error"))}})}function f(){if(!i){i=!0;try{t.postMessage({id:++r,kind:"dispose"})}catch{}t.terminate();for(let d of n.values())d.reject(new T("disposed"));n.clear()}}let p=(async()=>{let d=await c({kind:"init",baseUrl:e.baseUrl,salt:e.salt,detectorLimit:e.tuning.detectorLimit,maxDownloadMs:e.tuning.maxDownloadMs});if(d.kind==="failed")return d.reason;if(d.kind!=="ready")return"error";let g=await c({kind:"warmup"});return g.kind!=="ready"?"error":{warmupMs:g.warmupMs,downloadMs:d.downloadMs,cached:d.cached}})().catch(()=>"error"),b,S=new Promise(d=>{b=setTimeout(()=>d("timeout"),e.tuning.loadTimeoutMs)}),I=Promise.race([p,S]).then(d=>(clearTimeout(b),typeof d=="string"?f():s=!0,i&&typeof d!="string"?"error":d));(e.page===void 0?globalThis.addEventListener?globalThis:null:e.page)?.addEventListener("pagehide",f,{once:!0});async function w(d,g,C){if(i)throw g.close(),new T("disposed");if(!s)throw g.close(),new T("not_ready");if(l)throw g.close(),new T("busy");l=!0;let B;try{let O=new Promise((k,A)=>{B=setTimeout(()=>{A(new T("timeout")),f()},e.tuning.readTimeoutMs??1e4)}),P=await Promise.race([c(d,[g]),O]);if(P.kind===C){let{id:k,...A}=P;return A}throw new T(P.kind==="error"?P.code:P.kind==="failed"?P.reason:"error")}finally{clearTimeout(B),l=!1}}return{ready:I,get busy(){return l},bandRead:(d,g=e.tuning.detectorLimit)=>w({kind:"band",bitmap:d,detectorLimit:g},d,"band"),stillRead:(d,g,C=e.tuning.detectorLimit)=>w({kind:"still",bitmap:d,region:g,detectorLimit:C},d,"band"),layoutRead:(d,g)=>w({kind:"layout",bitmap:d,detectorLimit:g},d,"layout"),dispose:f}}var U="sekyro-ocr-1",ae=e=>e!==null&&typeof e=="object"?e:{},v=(e,t,n,r)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:r,Pe=(e,t)=>typeof e=="boolean"?e:t,Ae=e=>{let t=typeof e=="string"?/^sekyro-ocr-(\d{1,4})$/.exec(e):null;return t?Number(t[1]):Number.POSITIVE_INFINITY};function Be(e,t={}){let n=ae(e),r=ae(n.liveMrz),i=ae(n.frontLock),l=Ae(t.engine??U),s=t.mode==="off",u=d=>d.enabled===!0?d.arm==="live"?"live":"control":null,c=u(r),f=u(i),p=(d,g)=>!s&&g==="live"&&Ae(d.minEngine??U)<=l,b=Se,S=p(r,c)?{detectorLimit:v(r.detectorLimit,320,1600,b.detectorLimit),bandMaxWidthPx:v(r.bandMaxWidthPx,320,4096,b.bandMaxWidthPx),minBandWidthPx:v(r.minBandWidthPx,0,4096,b.minBandWidthPx),bandTop:v(r.bandTop,0,.95,b.bandTop),minIntervalMs:v(r.minIntervalMs,0,5e3,b.minIntervalMs),stableReads:Math.round(v(r.stableReads,1,10,b.stableReads)),profileReads:Math.round(v(r.profileReads,1,100,b.profileReads)),maxReadMs:v(r.maxReadMs,50,6e4,b.maxReadMs),searchTimeoutMs:v(r.searchTimeoutMs,1e3,12e4,b.searchTimeoutMs),hint:Pe(r.hint,!0),stillConfirm:Pe(r.stillConfirm,!0)}:null,I=ye,h=(d,g,C)=>v(i[d],g,C,I[d]),w=p(i,f)?{minLines:Math.round(h("minLines",1,50)),fillMin:h("fillMin",0,1),fillMax:h("fillMax",0,2),offsetMax:h("offsetMax",0,1),steadyFillDelta:h("steadyFillDelta",0,1),steadyOffsetDelta:h("steadyOffsetDelta",0,1),layoutShiftMax:h("layoutShiftMax",0,1),lineCountDelta:Math.round(h("lineCountDelta",0,50)),lockMs:h("lockMs",0,3e4),steadyMs:h("steadyMs",0,3e4),minFrames:Math.round(h("minFrames",1,100)),minIntervalMs:h("minIntervalMs",0,5e3),maxWidthPx:h("maxWidthPx",160,2048),detectorLimit:h("detectorLimit",320,1600),searchTimeoutMs:h("searchTimeoutMs",1e3,12e4)}:null;return{enabled:S!==null||w!==null,liveMrz:S,textLock:w,liveMrzArm:c,frontLockArm:f,load:{detectorLimit:S?.detectorLimit??w?.detectorLimit??b.detectorLimit,loadTimeoutMs:v(r.loadTimeoutMs,1e3,12e4,2e4),maxDownloadMs:v(r.maxDownloadMs,1e3,12e4,2e4),minDeviceMemoryGb:v(r.minDeviceMemoryGb,0,64,2)},reportSampleRate:v(r.reportSampleRate,0,1,1)}}function Ie(e,t){return e.enabled?!(t.probe??_e)({minDeviceMemoryGb:e.load.minDeviceMemoryGb}).ok||(t.slow??Te)()?{ok:!1,reason:"unsupported"}:{ok:!0,engine:Oe({baseUrl:t.baseUrl,salt:t.salt,tuning:{detectorLimit:e.load.detectorLimit,maxDownloadMs:e.load.maxDownloadMs,loadTimeoutMs:e.load.loadTimeoutMs},...t.workerUrl!==void 0?{workerUrl:t.workerUrl}:{},...t.createWorker!==void 0?{createWorker:t.createWorker}:{},...t.page!==void 0?{page:t.page}:{}})}:{ok:!1,reason:"off"}}function rt(e=typeof navigator<"u"?navigator.userAgent:""){return/SamsungBrowser\//.test(e)?"samsung":/Firefox\/|FxiOS\//.test(e)?"firefox":/Chrome\/|CriOS\/|Chromium\//.test(e)&&!/Edg\/|OPR\//.test(e)?"chrome":/Safari\//.test(e)&&/Version\/|Mobile\//.test(e)&&!/Chrome\/|CriOS\//.test(e)?"safari":"other"}var F=e=>e===void 0||!Number.isFinite(e)?void 0:Math.min(6e5,Math.max(0,Math.round(e))),ie=(e,t,n)=>e===void 0||!Number.isFinite(e)?void 0:Math.min(n,Math.max(t,Math.round(e)));function We(e){let t=e.assist??null,n=e.load!==null&&e.load!==void 0&&typeof e.load=="object"?e.load:null,r=typeof e.load=="string"?e.load:null,i=t!==null?t.outcome:r==="unsupported"||r==="download"||r==="integrity"?r:r==="error"||r==="timeout"?"error":"off",l={kind:"live_mrz",platform:"web",engine:e.engine??U,arm:e.arm,capture:e.capture,outcome:i,reads:ie(t?.reads??0,0,1e4)??0,browser:e.browser??rt()},s=(u,c)=>{c!==void 0&&(l[u]=c)};return s("format",t?.format),s("framesToValid",ie(t?.framesToValid,1,1e4)),s("msToValid",F(t?.msToValid)),s("framesToLock",ie(t?.framesToLock,1,1e4)),s("msToLock",F(t?.msToLock)),s("msToCapture",F(e.msToCapture)),s("readP50Ms",F(t?.readP50Ms)),s("readP90Ms",F(t?.readP90Ms)),s("deviceClass",t?.deviceClass),n!==null&&(s("warmupMs",F(n.warmupMs)),s("downloadMs",F(n.downloadMs)),s("cached",n.cached)),s("stillConfirmed",e.stillConfirmed),s("typeMismatch",e.typeMismatch),l}function se(e,t){return e===void 0?!1:t==="passport"?e!=="TD3":e==="TD3"}var ot=2;async function at(e){let t=await import("./capture-session-doc-XBZGXWOP.js");return new t.CaptureSessionDoc(e)}function it(e){return{topLeft:{x:e.x,y:e.y},topRight:{x:e.x+e.width,y:e.y},bottomRight:{x:e.x+e.width,y:e.y+e.height},bottomLeft:{x:e.x,y:e.y+e.height}}}function st(e,t,n){let r=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let l=0;l<r.length;l+=1){let s=r[l],u=r[(l+1)%r.length];i+=s.x*u.y-u.x*s.y}return t>0&&n>0?Math.abs(i)/2/(t*n):0}function Gt(){import("./capture-session-doc-XBZGXWOP.js").then(e=>e.warmDocDetector()).catch(()=>{})}function qt(e){return ut(e,{}).handle}function ut(e,t){let n=fe(),r=ge({enabled:e.keepScreenAwake!==!1}),i=t.decode??(o=>createImageBitmap(o)),l=t.blurRefuseSharpnessMax??.16,s=t.now??(()=>performance.now()),u=e.documentType==="passport"||e.side==="single",c=te(u?"singlePage":"twoSided",s());if(!u&&(e.side==="recto"||e.side==="verso")){let o=e.side==="recto"?"verso":"recto";c={...c,captured:{[o]:"server"},readSides:[o],current:e.side,phase:"flipCue",restPhase:"flipCue"}}let f="idle",p=null,b=null,S=!0,I=0,h=0,w=!1,d=!1,g="",C=null,B,O=null,P=[],k=t.webOcr!==void 0?Be(t.webOcr.captureDocument,{mode:e.liveMrz?.mode??"auto"}):null,A=null,z=k===null||!k.enabled?"off":null,G=null,q=null,ue=new WeakMap,Q="";if(k!==null&&k.enabled&&t.webOcr!==void 0){let o=t.webOcr,a=Ie(k,{baseUrl:e.liveMrz?.assetBaseUrl??o.baseUrl,salt:o.salt,...e.liveMrz?.workerUrl!==void 0?{workerUrl:e.liveMrz.workerUrl}:{},...o.createWorker!==void 0?{createWorker:o.createWorker}:{}});if(a.ok){A=a.engine;let m=new Me({textLock:k.textLock,liveMrz:k.liveMrz});G=m;let y=a.engine;y.ready.then(L=>{z=L,typeof L!="string"&&S&&m.setEngine(y)})}else z=a.reason}let N=o=>{let a=JSON.stringify(o);a!==Q&&(Q=a,n.emit("mrz",o))},le=(o,a)=>{let m=t.webOcr?.reports;if(m===void 0||k===null||o===void 0)return;let y=o.format==="ID-3"||o.side==="single"?"single":o.side==="verso"?"verso":"recto",L=y!=="recto"?k.liveMrzArm??k.frontLockArm:k.frontLockArm;if(L===null||Math.random()>=k.reportSampleRate)return;let _=o.via==="live_mrz"?q:null,x=()=>{let E=_?.value??null;m([We({arm:L,capture:y,assist:o.ocr??null,load:L==="control"?"off":z,...o.msToCapture!==void 0?{msToCapture:o.msToCapture}:{},...E!==null&&E.stillConfirmed!==void 0?{stillConfirmed:E.stillConfirmed}:{},...a!==void 0?{typeMismatch:se(a.format,e.documentType==="passport"?"passport":"card")}:{}})])};_!==null&&_.value===null?Promise.race([_.promise,new Promise(E=>setTimeout(E,3e3))]).then(x):x()},W=o=>{!S||o===f||(f=o,r.setActive(o==="starting"||o==="scanning"),n.emit("state",o))},Fe=(o,a)=>a===void 0?null:u?"single":o.captured.recto===a?"recto":o.captured.verso===a?"verso":null,ze=o=>({phase:o.phase,captured:u?o.captured.recto!==void 0?["single"]:[]:["recto","verso"].filter(a=>o.captured[a]!==void 0),expected:u?null:o.current??null,notice:o.notice??null,lastShot:Fe(o,o.lastShot),manualShutter:o.manualShutter,torchAvailable:p?.torchAvailable()??!1,torch:d}),ce=()=>{let o=p;o!==null&&o.captureNow().catch(()=>R({type:"captureFailed",at:s()}))};function R(o){if(!S)return;let a=c;c=ve(c,o),c.phase==="capturing"&&a.phase!=="capturing"&&Promise.resolve().then(ce),c.phase==="result"&&a.phase!=="result"&&(W("done"),de());let m=ze(c),y=JSON.stringify(m);y!==g&&(g=y,n.emit("scan",m))}function de(){O!==null&&clearInterval(O),O=null;for(let o of P.splice(0))o();p?.destroy(),p=null,r.setActive(!1)}let me=()=>p?.captureReport?.(),K=!1,pe=(o,a)=>{if(!(o===void 0||t.onFaceReport===void 0))try{t.onFaceReport(o,a)}catch{}},H=o=>{Q="",!(p===null||c.phase==="reading"||c.phase==="result")&&(K=!1,p.rearm(u?"single":c.current??o))},Ne=async(o,a,m,y)=>{if(q=null,y!==void 0&&A!==null&&k?.liveMrz?.hint===!0){let M={promise:Le(A,o,y,{engine:U,detectorLimit:k.liveMrz.detectorLimit}).catch(()=>null),value:null};M.promise.then(D=>{M.value=D}),q=M}y!==void 0&&se(y.format,e.documentType==="passport"?"passport":"card")&&N({state:"mismatch",format:y.format});let L=me();pe(L,"captured"),K=!0,le(L,y);let _=m===void 0?C:m===null?null:{quad:it(m),frameWidth:0,frameHeight:0,inStill:!0},x={decoded:null},E=()=>(x.decoded??(x.decoded=Promise.resolve().then(()=>i(o)).catch(()=>null)),x.decoded);try{await Ue(o,a,_,E,q)}finally{x.decoded!==null&&(await x.decoded)?.close()}},Ue=async(o,a,m,y,L)=>{let _=`shot-${I+=1}`;if(R({type:"captured",id:_,at:s()}),e.haptics!==!1)try{globalThis.navigator?.vibrate?.(30)}catch{}if(!w&&l>0){let M=await(t.measureSharpness!==void 0?t.measureSharpness(o,m):y().then(D=>D===null?-1:he(D,J(m?.quad??null,m?.inStill===!0?D:{width:m?.frameWidth??0,height:m?.frameHeight??0},D)))).catch(()=>-1);if(!S)return;if(Number.isFinite(M)&&M>=0&&M<l){w=!0;let D=u?"recto":c.current??(c.captured.recto===void 0?"recto":"verso");R({type:"readFailed",side:D,id:_,issue:"blurry"}),H(D);return}}w=!1;let x;if(u)x="single";else{let M=c.current,D=await(t.classify!==void 0?t.classify(o):y().then(X=>X===null?M??"recto":m?.inStill===!0?re(X,480,null,!0):re(X,480,J(m?.quad??null,{width:m?.frameWidth??0,height:m?.frameHeight??0},X)))).catch(()=>M??"recto");if(!S)return;if(c.captured[D]!==void 0&&h<ot){h+=1,R({type:"duplicate",id:_,side:D}),H(D==="recto"?"verso":"recto");return}x=c.captured[D]!==void 0&&M!==void 0?M:D,h=0,R({type:"classified",id:_,side:x})}let E=x==="verso"?"verso":"recto";try{let M=t.encode!==void 0?await t.encode(o):await y().then(D=>{if(D===null)throw new Error("the still could not be decoded");return Z(D)});if(!S)return;L!==null&&ue.set(M.blob,L),n.emit("captured",{image:M.blob,side:x,documentType:e.documentType,...e.issuer!==void 0?{issuer:e.issuer}:{},width:M.width,height:M.height,previewDataUrl:a}),t.deferRead!==!0&&R({type:"readOk",side:E})}catch(M){R({type:"readFailed",side:E,id:_,issue:"technical"}),n.emit("error",V("generic",!0,{phase:"keyframes",name:$(M)}))}H(E==="recto"?"verso":"recto")},Ge=o=>{P.push(o.on("statechange",({state:a})=>{a==="preflight"||a==="acquiring"?W("starting"):a==="positioning"?W("scanning"):a==="captured"?W("captured"):a==="error"&&W("error")}),o.on("feedback",({key:a,reticle:m})=>n.emit("feedback",{key:a,reticle:m})),o.on("checks",a=>{n.emit("gate",{progress:a.p,quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight,...a.guide!==void 0?{guide:{detected:a.guide.detected,fill:a.guide.fill,offsetX:a.guide.offsetX??0,offsetY:a.guide.offsetY??0}}:{}});let m=a.ocr?.mrz;m!==void 0&&(m.state==="fallback"?N({state:"fallback",reason:m.reason}):m.state==="valid"?N({state:"valid",format:m.format}):m.state==="reading"?N({state:"reading",...m.format?{format:m.format}:{},...m.coach?{coach:m.coach}:{}}):N({state:"searching"}));let y=a.quad===null?0:st(a.quad,a.frameWidth,a.frameHeight);C=a.quad===null?null:{quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight},R({type:"report",report:{present:a.quad!==null&&a.plausible||a.guide?.detected===!0,ready:a.ready===!0,locking:a.p>=.5,areaFrac:y},at:s()})}),o.on("error",({kind:a,retryable:m,detail:y})=>n.emit("error",V(a,m,y))),o.on("artifacts",a=>{Ne(a.keyframe,a.previewDataUrl,a.docRegion,a.liveMrz)}))},j=()=>(b??(b=(async()=>{if(S){if(p===null){let o;try{o=await(t.createEngine??at)({...t.engineOptions??{},...B!==void 0?{guide:B}:{},video:e.video,format:be(e.documentType),side:u?"single":e.side??"recto",autoCapture:!1,...G!==null?{ocr:G}:{}})}catch(m){W("error"),n.emit("error",V("models",!0,{phase:"models",name:$(m)}));return}if(!S){o.destroy();return}p=o,Ge(o);let a=t.tickMs??500;a>0&&(O=setInterval(()=>R({type:"tick",at:s()}),a))}R({type:"clockRestart"}),k!==null&&k.liveMrzArm==="live"&&(z==="unsupported"||z==="off")&&N({state:"fallback",reason:z}),await p.start()}})().finally(()=>{b=null})),b);return{handle:{get state(){return f},on:(o,a)=>n.on(o,a),start:j,retry:()=>{if(p===null&&c.phase==="result"){R({type:"retake"}),h=0,w=!1,j();return}if(p!==null&&f!=="error"){R({type:"retake"}),h=0,w=!1,p.rearm(u?"single":void 0);return}j()},setSide:o=>{u||o==="single"||(c.current!==o&&(c={...c,current:o}),R({type:"clockRestart"}),c.phase!=="reading"&&c.phase!=="result"&&p?.rearm(o))},shutter:ce,focusAt:(o,a)=>{p?.focusAt?.(o,a)},setGuide:o=>{B=o,p?.setGuide?.(o)},setTorch:o=>{d=o,p?.setTorch(o),R({type:"tick",at:s()})},destroy:()=>{if(S&&p!==null&&f!=="done"){let o=me();!K&&o!==void 0&&o.ticks>0&&pe(o,"abandoned"),le(o,void 0)}S=!1,de(),G?.setEngine(null),A?.dispose(),A=null,n.clear()}},setFlowState:o=>{(c.phase==="reading"||c.phase==="result")&&W(o==="done"&&c.phase!=="result"?"scanning":o)},settle:(o,a)=>{let m=o==="verso"?"verso":"recto";R(a.ok?{type:"readOk",side:m}:{type:"readFailed",side:m,issue:a.issue}),a.ok||H(m)},takeDeviceRead:o=>ue.get(o.image)?.value??null}}export{mt as a,ft as b,gt as c,bt as d,ht as e,yt as f,we as g,te as h,ve as i,Ze as j,et as k,Mt as l,Le as m,Dt as n,U as o,Be as p,Ie as q,rt as r,We as s,se as t,ot as u,Gt as v,qt as w,ut as x};
@@ -0,0 +1 @@
1
+ import{b as M}from"./chunk-GI3UFGRQ.js";var A=2;function L(u){let l=u.tuning,s=u.now??(()=>performance.now()),t=null,o=!1,g=!1,d=Number.NEGATIVE_INFINITY,a=null,h=0,i=null,n=null,f=0,p=!1,T=()=>{if(p||!l.enabled)return;p=!0;let r=(u.createSegmenter??(e=>import("./segmenter-USLNBX65.js").then(m=>m.createSelfieSegmenter(e))))(u.assetBaseUrl);n=setTimeout(()=>{t===null&&(o=!0)},l.segmenterTimeoutMs),r.then(e=>{n!==null&&clearTimeout(n),g||o?e.close():t=e},()=>{n!==null&&clearTimeout(n),o=!0})};return{measure(r,e,m,S){if(!l.enabled||r.pixels===null)return null;T();let c=s();if(c-d<1e3/l.hz)return a;d=c;let k=r.width/Math.max(1,m),y=r.height/Math.max(1,S),w={x:e.x*k,y:e.y*y,width:e.width*k,height:e.height*y},B=null;if(t!==null&&!o){let x=Math.max(c,h+1);h=x;let U=s();B=t.segment(r.source,x);let b=s()-U;f+=1,f>A&&(i=i===null?b:i*.7+b*.3),i!==null&&i>l.segmenterBudgetMs&&(o=!0,t.close(),t=null)}return a=M(r.pixels,w,B,l),a},close(){g=!0,n!==null&&clearTimeout(n),t?.close(),t=null}}}export{L as a};
@@ -0,0 +1 @@
1
+ var p=Object.freeze({EDGE_LUMA_DELTA:40,MIN_ROW_DENSITY:.08,MIN_COLUMN_COVERAGE:.6,MIN_WIDTH_FRAC:.55,MIN_HEIGHT_FRAC:.02,MAX_HEIGHT_FRAC:.16,ROW_MERGE_GAP:18}),I=12;function F(H,D={}){let r={...p,...D},{data:s,width:n,height:t}=H;if(n<32||t<32)return null;let c=new Array(t).fill(!1),R=new Float32Array(t),u=new Int32Array(t).fill(n),a=new Int32Array(t).fill(-1),w=n/I,d=new Array(I);for(let e=0;e<t;e++){let M=0;d.fill(!1);let E=e*n*4,G=.299*(s[E]??0)+.587*(s[E+1]??0)+.114*(s[E+2]??0);for(let o=1;o<n;o++){let T=E+o*4,y=.299*(s[T]??0)+.587*(s[T+1]??0)+.114*(s[T+2]??0);Math.abs(y-G)>=r.EDGE_LUMA_DELTA&&(M+=1,d[Math.min(I-1,Math.floor(o/w))]=!0,o<u[e]&&(u[e]=o),o>a[e]&&(a[e]=o)),G=y}R[e]=M/n;let O=d.filter(Boolean).length/I;c[e]=R[e]>=r.MIN_ROW_DENSITY&&O>=r.MIN_COLUMN_COVERAGE&&a[e]-u[e]>=r.MIN_WIDTH_FRAC*n}let _=null,l=-1,f=-1,i=0,N=e=>{if(l<0)return;let M=e-l+1;M>=r.MIN_HEIGHT_FRAC*t&&M<=r.MAX_HEIGHT_FRAC*t&&i>=4&&(_===null||i>_.rows)&&(_={top:l,bottom:e,rows:i}),l=-1,i=0};for(let e=0;e<t;e++)c[e]&&(l<0?l=e:e-f>r.ROW_MERGE_GAP&&(N(f),l=e),f=e,i+=1);if(N(f),_===null)return null;let b=_,m=n,A=-1,C=0,h=0;for(let e=b.top;e<=b.bottom;e++)c[e]&&(u[e]<m&&(m=u[e]),a[e]>A&&(A=a[e]),C+=R[e],h+=1);return A-m<r.MIN_WIDTH_FRAC*n?null:{x:m,y:b.top,width:A-m,height:b.bottom-b.top+1,density:h>0?C/h:0}}export{p as a,F as b};
@@ -0,0 +1 @@
1
+ var v=["session.completed","session.failed","session.review_pending","session.expired","session.cancelled"],u=new Set([0,1,2,3]),a="sekyro-verify",E="width=480,height=720,noopener=false",f=new Set(v);function y(e){if(e===null||typeof e!="object")return!1;let n=e;return n.source==="sekyro"&&n.version===1&&typeof n.sessionId=="string"&&typeof n.event=="string"&&f.has(n.event)}function S(e){let n=new URL(e.hostedUrl).origin,t=window.open(e.hostedUrl,a,E);if(!t)return{error:"popup_blocked"};let r=o=>{if(o.source!==t||o.origin!==n||!y(o.data))return;let{source:p,version:d,event:c,sessionId:l,level:s}=o.data,i={source:p,version:d,event:c,sessionId:l};u.has(s)&&(i.level=s),e.onEvent(i)};return window.addEventListener("message",r),{close(){window.removeEventListener("message",r),t.close()}}}function k(e,n){return n.mode==="redirect"?(window.location.assign(e),{close(){}}):S({hostedUrl:e,onEvent:n.onEvent??(()=>{})})}export{v as a,S as b,k as c};
@@ -0,0 +1 @@
1
+ var o={"ID-1":{center:1.586,tolerance:.15},"ID-2":{center:1.419,tolerance:.12},"ID-3":{center:1.42,tolerance:.2}},c={"ID-1":["ID-1"],"ID-2":["ID-2"],"ID-3":["ID-3"],card:["ID-1","ID-2"]};function i(e){return o[e==="card"?"ID-1":e]}function d(e,r){return c[e].some(t=>Math.abs(r-o[t].center)<=o[t].tolerance)}var a=[{docType:"carte_identite",format:"ID-1",sides:["recto","verso"],mrz:"td1",portraitSide:"recto",aspectRatio:1.586,identifierSource:"mrz"},{docType:"passport",format:"ID-3",sides:["single"],mrz:"td3",portraitSide:"single",aspectRatio:1.42,identifierSource:"mrz"}],n=[...a,{docType:"residence_permit",format:"ID-1",sides:["recto","verso"],mrz:"td1",portraitSide:"recto",aspectRatio:1.586,identifierSource:"mrz"}];function s(e){let r=n.find(t=>t.docType===e);return r===void 0||r.format==="ID-1"?"card":r.format}export{o as a,i as b,d as c,a as d,n as e,s as f};
@@ -0,0 +1 @@
1
+ var u=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],l=[/^(front|back|rear)( [a-z ]+)? camera$/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 c(n){let e=(n??"").trim().toLowerCase();return e.length===0?"unknown":u.some(t=>e.includes(t))?"known_virtual":l.some(t=>t.test(e))?"platform":"unknown"}var d=1e3;function m(n,e){return new Promise(t=>{let a=setTimeout(()=>t(void 0),e),r=s=>{clearTimeout(a),t(s)};try{n().then(r,()=>r(void 0))}catch{r(void 0)}})}async function f(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify(n)));return Array.from(new Uint8Array(e).subarray(0,8),t=>t.toString(16).padStart(2,"0")).join("")}var i=n=>Array.isArray(n)?[...n].sort():null,o=n=>{let e=n;return e==null?null:[e.min??null,e.max??null]};function p(n){try{return n.getSettings?.().facingMode==="environment"}catch{return!1}}async function g(n){try{if(n.readyState==="ended"||p(n))return;let e={};try{e=n.getCapabilities?.()??{}}catch{}let t=await m(()=>navigator.mediaDevices.enumerateDevices(),d);return await f([o(e.width),o(e.height),o(e.frameRate),i(e.facingMode),i(e.focusMode),i(e.exposureMode),c(n.label),t?.filter(a=>a.kind==="videoinput").length??null])}catch{return}}async function v(n,e){let t=await g(n);t&&e.noteCamera(t)}export{m as a,f as b,g as c,v as d};
@@ -0,0 +1 @@
1
+ var m="0.1.0-rc.21";var T=/FBAN|FBAV|FB_IAB|FBIOS|MessengerForiOS|Instagram|WhatsApp|musical_ly|BytedanceWebview|TikTok|Snapchat|\bLine\/|LinkedInApp|Pinterest|MicroMessenger|; wv\)/i;function p(t){let e=t??(typeof navigator>"u"?"":String(navigator.userAgent??""));return T.test(e)}var y="sekyro.did",I=1e4,v=()=>globalThis.process?.versions?.node,h;function b(){let t=globalThis.crypto;try{if(typeof t?.randomUUID=="function")return t.randomUUID()}catch{}try{if(typeof t?.getRandomValues=="function"){let e=t.getRandomValues(new Uint8Array(16));return Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}}catch{}}function w(){try{let t=localStorage.getItem(y);if(t)return t;let e=b();return e!==void 0&&localStorage.setItem(y,e),e}catch{return h??(h=b()),h}}async function P(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,r=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),i=await t.digest("SHA-256",new TextEncoder().encode(r));return Array.from(new Uint8Array(i),o=>o.toString(16).padStart(2,"0")).join("").slice(0,32)}function k(t){let e=new TextEncoder().encode(t),r="";for(let i of e)r+=String.fromCharCode(i);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function x(t){let e,r,i,o,a,l,u=()=>l?.readyState==="live",_=()=>{a!==void 0||!globalThis.crypto?.subtle||v()||u()||(a=Promise.race([import("./print-AYSCRSZB.js"),new Promise(n=>setTimeout(n,I))]).then(n=>n?.computePrint(u)).then(n=>{n==="busy"?a=void 0:o=n}).catch(()=>{}))};return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(n){n&&(e=n.slice(0,128))},noteCamera(n){r=n},noteCameraTrack(n){l=n},async deviceHeader(){try{i??(i=P().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let g=await i,f=w(),S={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...f?[{kind:"web_local",value:f.slice(0,128)}]:[],...g?[{kind:"web_fp",value:g}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...e?{cameraLabel:e}:{},...n.length?{signals:n}:{},...o?{print:{v:2,...o,...r?{camera:r}:{}}}:{},...p()?{inApp:!0}:{}},C=k(JSON.stringify(S));return _(),C}catch{return}},printReady(){return a??Promise.resolve()}}}var s=Symbol.for("sekyro.web.clientContext"),c=globalThis,d=c[s]??(c[s]=x({sdk:`@sekyro/web@${m}`}));function N(t){try{let e=t.getVideoTracks?.()[0];if(e){if(d.noteCameraLabel(e.label),d.noteCameraTrack(e),v())return;import("./camera-trait-45MJTW4K.js").then(r=>r.noteCameraTrait(e,d)).catch(()=>{})}}catch{}}export{m as a,p as b,d as c,N as d};
@@ -0,0 +1 @@
1
+ import{A as Ee,B as Te,a as Re,b as Ie,c as Ae,d as ee,e as we,f as Oe,h as H,i as D,j as G,k as Me,l as E,m as K,n as b,o as q,p as x,q as te,r as O,s as N}from"./chunk-H3HVCWLF.js";import{n as xe}from"./chunk-P3H3D33O.js";import{a as be}from"./chunk-GT2ZLGF7.js";import{c as Pe,d as X}from"./chunk-FUHDOEBP.js";import{c as z,g as ve,h as Y}from"./chunk-B2X33ZW2.js";function Z(e){return e.idNumberBound??e.nniBound}function L(e){return e===void 0?void 0:e.idNumberFromDocument??e.nniFromDocument}function Ve(e){let t=e.idNumberMasked??e.nniMasked;return typeof t=="string"&&t!==""?t:void 0}var it="https://api.sekyro.ai",rt=5e3,st=1500,at=10;function ut(e){return new Promise(t=>setTimeout(t,e))}function ct(){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 Qt(e){return dt(e,{})}function dt(e,t){let n=e.apiOrigin??it,i=e.autoRetry??!0,r=e.rearm??"auto",s=t.client??new ve({apiOrigin:n,sessionToken:e.clientToken,fetch:e.fetch}),c=t.sleep??ut,a=t.uuid??ct,l=t.getTurnstileToken??((o,u)=>import("./turnstile-FATNZ4AG.js").then(p=>p.executeTurnstile(o,u))),f=be(),m=null,g=null,d=!1,k=new AbortController,h=null,A=null,U=null,se=()=>we(ee(h),U),v=o=>{h=o,f.emit("view",o),m?.onView(o)},_=()=>h!==null?Promise.resolve(h):(A??(A=s.getSession().then(o=>(v(o),o)).finally(()=>{A=null})),A),R=async()=>{let o=await s.getSession();return v(o),o},W=async(o,u)=>{o.plan!==void 0?v(o):await R()},$=null,ae=async o=>{let u=await _();if(!o&&u.consentRecorded)return;let p=await s.recordConsent(e.locale);p.plan!==void 0?v(p):h!==null&&v({...h,consentRecorded:!0})},M=o=>o?.force===!0?ae(!0):($??($=ae(!1).finally(()=>{$=null})),$),j={client:s,ensureConsent:o=>M(o),sleep:c,uuid:a,...t.random!==void 0?{random:t.random}:{},onBusy:o=>{d||f.emit("busy",o)}},ue=!1,ce=null,J=o=>{if(o.status==="approved"||o.status==="rejected"||o.status==="review"){if(ue)return;ue=!0}ce=JSON.stringify(o),f.emit("result",o)},Ye=o=>{ce!==JSON.stringify(o)&&J(o)},de=async o=>{let u=h;o&&(u=await R().catch(()=>h));let p=u===null?null:E(u);return p!==null&&!d&&f.emit("method",p),p!==null},le=null,pe=!1,fe=!1,me=()=>Ee(j,(o,u)=>o.submitCheck("population_registry",{},{idempotencyKey:u})),he=o=>Z(o)===!0||L(x(o,"population_registry"))===!0,Ze=async()=>{try{let o=await _();if(b(o)||E(o)!==null||q(o)?.checkType!=="population_registry")return;if(!he(o)&&L(x(o,"population_registry"))===void 0&&(o=await R()),!he(o)){fe=!0;return}await M(),await W(await me(),"population_registry");let u=h===null?void 0:x(h,"population_registry");if(u?.state==="input_required"&&u.reason==="registry_unavailable"&&G(u)>0){if(await c(rt),d)return;await W(await me(),"population_registry")}}catch(o){if(o instanceof z&&(o.code==="check_not_active"||o.code==="step_not_on_path")){await R().catch(()=>{});return}pe=!0;return}h!==null&&b(h)&&J(N(h,{autoRetry:i}))},Se=()=>(le??(le=Ze()),le),We=async()=>{let u=(await _()).turnstileSiteKey;return u===null?{sandbox:!0}:{channel:"hosted_web",siteKey:u,turnstileToken:await l(u,{signal:k.signal})}},F=o=>{if(d)return;let u=s.reportCaptureIssue;if(u===void 0)return;let p=o.formFactor;try{p??(p=Pe())}catch{}try{Promise.resolve(u.call(s,{...o,...p!==void 0?{formFactor:p}:{}})).catch(()=>{})}catch{}},P=null,ye=Promise.resolve(),V=0,$e=async()=>{let o=await _();for(let u=0;u<at&&!d&&!b(o)&&q(o)===void 0&&D(o).some(p=>p.state==="processing")&&(await c(st),!d);u+=1)o=await R();return o},je=async(o,u,p)=>{let{capture:C}=o,y=()=>d,B=()=>o.alive&&o.attempt===p,ke=S=>{B()&&C.setFlowState(S)},w=S=>{if(!y()&&(S.status==="unavailable"&&S.reason!==void 0&&!Re(S.reason)&&F({check:"liveness",kind:"unavailable",phase:"upload",engineKind:S.reason,attempt:Math.max(0,o.issues.value)}),J(S),!!B())){if(S.status==="retry"&&r==="auto"){C.handle.retry();return}C.setFlowState("done")}};if(u.degraded==="NO_RECORDER"){let S=h?.sessionId??(await _().catch(()=>null))?.sessionId??"";w(O(S,"no_recorder"));return}ke("uploading");try{if(await Se(),y())return;let S=await _(),_e;if(!b(S)&&E(S)!==null){await de(!1),w(O(S.sessionId,"method_required"));return}if(!b(S)){if(q(S)?.checkType==="population_registry"){w(O(S.sessionId,fe?"nni_unbound":pe?"network":"registry_unavailable"));return}if(await M(),y())return;_e=h??S;let Q=await Te({...j,artifacts:u,getAttestation:We,getView:()=>h??S,refreshView:R,applySubmit:W,onPhase:ke,isCancelled:y,onKeyframePromoted:ot=>{g=ot}});if(y())return;if(Q.kind==="unavailable"){w(O(S.sessionId,Q.reason));return}if(Q.kind==="resync"&&await R(),h!==null&&E(h)!==null){await de(!1),w(O(S.sessionId,"method_required"));return}S=await $e()}w(N(S,{autoRetry:i,previous:_e}))}catch{if(y())return;w(O(h?.sessionId??"","network"))}},Je=(o,u)=>{let p=o.attempt;V>0&&o.alive&&o.capture.setFlowState("uploading"),V+=1,ye=ye.then(()=>je(o,u,p)).finally(()=>{V-=1,V===0&&m?.onChainIdle()}).catch(()=>{})},ge=o=>{P?.capture.handle.destroy(),P!==null&&(P.alive=!1);let u=xe(o,m?.captureInternals?.(o)??t.capture,()=>h?.capture?.liveness?.keyframe?.rank===!0,se,()=>h?.capture?.liveness?.screenRamp),p={capture:u,alive:!0,attempt:0,issues:Ae()};P=p,u.handle.on("error",y=>{F(Ie("liveness",y,p.issues.value))}),u.handle.on("state",y=>{p.issues.note(y),y==="starting"&&(p.attempt+=1)}),u.handle.on("captured",y=>{Promise.resolve().then(()=>Je(p,y))});let C=u.handle;return{get state(){return C.state},get captureMode(){return C.captureMode},get facingMode(){return C.facingMode},on:(y,B)=>C.on(y,B),start:async y=>{if(h===null&&await _().catch(()=>{}),!!p.alive)return C.start(y)},retry:()=>C.retry(),switchCamera:()=>C.switchCamera(),destroy:()=>{p.alive=!1,P===p&&(P=null),C.destroy()}}},Qe=async()=>{if(d)return null;try{let o=await _();return d?null:E(o)}catch{return null}},Xe=async()=>{if(d)return"self";try{let o=await _();if(d)return"self";let u=ee(o);return u==="choice"?U??u:u}catch{return"self"}},ze=async()=>{if(d)return!1;try{let o=await _();if(d||b(o))return!1;let u=x(o,"liveness");return K(u)&&u?.requiresMobile===!0&&!X()}catch{return!1}},et=async()=>{if(d)return!1;try{let o=await _();return!d&&o.returning===!0}catch{return!1}},tt=async o=>{let u=(await _()).plan?.choice,p=u?.options.find(y=>H[y.service]===o);if(!p)throw new RangeError(`method ${String(o)} is not offered`);let C=await s.choose(u.nodeId,p.id);d||v(C)},Ce=null,nt=()=>(Ce??(Ce=import("./plan-runner-NUWONT7F.js").then(o=>{let u=o.createPlanRunner({runtime:j,currentView:()=>h,cameraMode:se,ensureView:_,refreshView:R,ensureConsent:()=>M(),liveness:ge,stopLiveness:()=>{P!==null&&(P.alive=!1,P.capture.handle.destroy(),P=null)},chainBusy:()=>V>0,destroyed:()=>d,sleep:c,isMobile:X,now:t.now??Date.now,keptFaceKey:()=>g,setView:v,baseCapture:t.capture,emitStep:p=>{d||f.emit("step",p)},emitResult:Ye,reportCaptureIssue:F,documentInternals:t.document,portraitInternals:t.portrait,livePhotoInternals:t.livePhoto,uploadInternals:t.upload});return m=u,u})),Ce);return{consent:()=>M(),startRegistry:Se,methodChoice:Qe,selectMethod:tt,reportCameraUnavailable:async o=>{await M();let u=s.reportCameraUnavailable;if(u===void 0)throw new TypeError("this client cannot report a missing camera");let p=await u.call(s,o).catch(C=>{if(C instanceof z&&C.code==="check_out_of_order")return s.getSession();throw C});d||v(p)},reportCaptureIssue:F,mobileRequired:ze,captureMode:Xe,chooseCaptureMode:o=>{U=o},get captureChoice(){return U},returning:et,liveness:ge,run:async()=>{if(d)throw new Error("verification destroyed");return(await nt()).run()},currentStep:()=>m?.current()??null,voiceClips:async()=>{if(d)return null;try{let o=await _();return d?null:o.voice??null}catch{return null}},on:(o,u)=>f.on(o,u),destroy:()=>{d=!0,k.abort(),m?.destroy(),P!==null&&(P.alive=!1,P.capture.handle.destroy(),P=null),f.clear()}}}var He=["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 lt=["carte_identite","passport","residence_permit"];function pt(e,t){let n=e.byIssuer?.[t]??e.default;return lt.filter(i=>n==="*"||n.includes(i))}function tn(e,t=He){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(i=>pt(e,i).length>0).sort()}function De(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}function nn(e){return/^[A-Z]{2}$/.test(e)?String.fromCodePoint(...[...e].map(t=>127462+t.charCodeAt(0)-65)):""}var dn=["national_number","document_photo","national_eid"],ft=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"]),mt=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),oe=["document","population_registry","national_eid"],ie=["phone_otp","email_otp"],Ue={identity_method:oe,contact:ie},ht=["population_registry","document"],Fe="platform_unsupported",St=new Set(["prefilled","user_entered","prefilled_or_entered"]),yt={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"};function I(e){return e.section??yt[e.checkType]??null}function gt(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 re(e){let t=e.plan,n=t?.choice;if(t===void 0||n===void 0||n.locked||t.current===null||t.current===n.nodeId||b(e))return null;let i=Ue[n.kind]??[...oe,...ie],r=n.options.flatMap(a=>a.available===!1||!i.includes(a.service)?[]:[a.nationalEid!=null?{id:a.id,service:a.service,nationalEid:a.nationalEid}:{id:a.id,service:a.service}]),s=t.steps.find(a=>a.id===t.current)?.service,c=n.selected??r.find(a=>a.service===s)?.id??null;return r.some(a=>a.id!==c)?{nodeId:n.nodeId,kind:n.kind,current:c,options:r}:null}function Be(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function Ct(e){let t=e.simulation;if(typeof t!="object"||t===null)return;let{otpCode:n,skipCapture:i}=t;return typeof n=="string"&&n!==""&&typeof i=="boolean"?{otpCode:n,skipCapture:i}:void 0}function kt(e){let t=(e.plan?.sections??[]).map(s=>({id:s.id,state:s.state})),n={sessionId:te(e.sessionId),orgName:e.orgName,returning:e.returning===!0,consentRecorded:e.consentRecorded,expiresAt:e.expiresAt,sections:t.map(s=>s.id),progress:t,purpose:e.purpose??"identity"};e.branding!==void 0&&(n.branding=e.branding),e.cameraUnavailableHandled===!0&&(n.cameraUnavailableHandled=!0);let i=Ct(e);i!==void 0&&(n.simulation=i);let r=re(e);return r!==null&&(n.switchable=r),n}function _t(e){let t={attemptsRemaining:G(e),attemptsExhausted:e.attemptsExhausted===!0};return e.reason!==void 0&&(t.reason=e.reason),e.retakeHint!==void 0&&(t.retakeHint=e.retakeHint),t}var Ge={phone_otp:"phone",email_otp:"email"};function Pt(e,t){let n=gt(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return n===void 0?void 0:Ge[n.option.service]}function bt(e,t,n,i){let r=t.checkType==="email_otp",s=(r?t.emailOtp:t.otp)??{},c=r?t.emailOtp?.emailSource:t.otp?.numberSource,a=c!==void 0&&St.has(c)?c:r?"prefilled_or_entered":"user_entered",l=typeof s.sentToMasked=="string"&&s.sentToMasked.length>0,f=s.prefilled===!0,m=Pt(e,r?"email_otp":"phone_otp"),g={key:t.checkType,context:n,section:I(t),phase:l?"verify":"send",canSwitch:m!==void 0,...i},d=r?{kind:"email_otp",...g,emailSource:a,needsEmail:a!=="prefilled"&&!f}:{kind:"phone_otp",...g,numberSource:a,needsPhone:a!=="prefilled"&&!f,channels:(t.otp?.channels??[]).filter(k=>k==="whatsapp"||k==="sms")};if(m!==void 0&&(d.switchChannel=m),f&&(d.prefilled=!0),l&&(d.sentToMasked=s.sentToMasked),!r&&t.otp?.channel!==void 0&&(d.channel=t.otp.channel),!r&&Array.isArray(t.phoneCountries)&&(d.phoneCountries=t.phoneCountries.filter(k=>typeof k=="string"&&/^[A-Z]{2}$/.test(k))),!r&&Array.isArray(t.phoneRules)){let k=d.phoneCountries??[];d.phoneRules=t.phoneRules.flatMap(h=>{let A=Rt(h);return A!==void 0&&k.includes(A.code)?[A]:[]})}return!r&&t.phoneInternational===!0&&(d.phoneInternational=!0),s.expiresAt!==void 0&&(d.codeExpiresAt=s.expiresAt),s.resendAvailableAt!==void 0&&(d.resendAvailableAt=s.resendAvailableAt),d}var xt=/^[\d[\]\-|()?:^]{1,64}$/;function vt(e){try{return typeof e=="string"&&xt.test(e)&&new RegExp(e)!==null}catch{return!1}}var Ne=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function Rt(e){let{code:t,dial:n,trunk:i,lengths:r,formats:s}=e??{};if(typeof t!="string"||typeof n!="string"||!/^\d{1,3}$/.test(n)||i!==void 0&&(typeof i!="string"||!/^\d{1,3}$/.test(i))||!Array.isArray(r)||r.length===0||!r.every(Ne))return;let c={code:t,dial:n,lengths:[...r].sort((a,l)=>a-l)};if(i!==void 0&&(c.trunk=i),s!==void 0){if(!(Array.isArray(s)&&s.length<=8&&s.every(l=>vt(l?.leading)&&Array.isArray(l.groups)&&l.groups.every(Ne)&&r.includes(l.groups.reduce((f,m)=>f+m,0)))))return;c.formats=s.map(l=>({leading:l.leading,groups:[...l.groups]}))}return c}function It(e,t,n,i){let r=Z(e)===!0?"bound":L(t)===!0?"document":"typed",s=r==="typed"&&t.state==="input_required"&&t.reason!==void 0&&Oe(t.reason)==="id_number_recheck",c=Be(re(e)),a=!i.attemptsExhausted&&c.length===1&&c[0]?.service==="document";return{kind:"registry",key:"registry",context:n,section:I(t),state:t.state==="input_required"?"input_required":"pending",source:r,recheck:s,canUseDocument:a,...i}}function At(e,t,n,i){let r=[...t.acceptedSides??[]],s={kind:"document",key:"document",context:n,section:I(t),side:r.includes("recto")?"verso":"recto",acceptedSides:r,documents:De(e),photo:Ke(e.documents),...i};return e.detectedCountry!==void 0&&(s.detectedCountry=e.detectedCountry),wt(e)&&(s.ageStepUp=!0),s}function Ke(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 wt(e){let t=D(e).find(i=>i.checkType==="age_estimation"),n=t?.reason;return t?.state==="failed"&&(n==="age_uncertain"||n==="age_unavailable")}function Ot(e){let t=x(e,"liveness");return t?.state==="passed"||t?.state==="review"}function Le(e,t,n,i,r){let s=t.icao?.report,c=e.portrait,a=r==="capture"?c?.pendingFix??null:null;a!==null&&(r="review");let l=qe(e);return{kind:"portrait",key:`portrait:${r}`,context:n,section:I(t),phase:r,report:Array.isArray(s)?s:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:Y(e),retakeOnly:r==="capture"&&t.state==="input_required"&&l===void 0&&e.capture?.livePhoto?.oneCapture===!0&&Ot(e),photo:Ke(c,r==="capture"),pendingFix:a,...l!==void 0?{captureMode:l}:{},...c?.reuse?.pending===!0?{reuse:!0}:{},...i}}function qe(e){let t=e.portrait?.captureMode;return t==="self"||t==="assisted"||t==="choice"?t:void 0}var ne={minLongSidePx:1280,jpegQuality:.95};function Mt(e,t){let n=e.capture?.livePhoto;if(n?.oneCapture!==!0)return null;let i=x(e,"portrait_icao"),r=n.still??ne;return{icao:t==="liveness"&&Y(e)!==null&&qe(e)===void 0&&i!==void 0&&i.state==="pending"&&i.reason===void 0,still:{minLongSidePx:r.minLongSidePx??ne.minLongSidePx,jpegQuality:r.jpegQuality??ne.jpegQuality}}}function Et(e,t,n,i){let r=t.eid,s=I(t);if(r===void 0||r.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:n,section:s,checkType:"eid_auth",reason:"update_required"};let c=Be(re(e)),a=c.length===1&&ht.includes(c[0]?.service??"")?c[0]:void 0,l=a===void 0?void 0:H[a.service],f=l!==void 0,m={kind:"eid",key:"eid",context:n,section:s,provider:r.provider,providerName:r.providerName,country:r.country,challenge:"app_code",phase:r.awaiting==="code"?"code":"identifier",identifierBound:r.identifierBound===!0,canUseCamera:f,afterPass:r.afterPass==="continue"?"continue":"end",...i};return f&&(m.cameraMethod=l),r.expiresAt!==void 0&&(m.codeExpiresAt=r.expiresAt),r.resendAvailableAt!==void 0&&(m.resendAvailableAt=r.resendAvailableAt),r.resendsRemaining!==void 0&&(m.resendsRemaining=r.resendsRemaining),r.codeAttemptsRemaining!==void 0&&(m.codeAttemptsRemaining=r.codeAttemptsRemaining),m}function Tt(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let n=x(e,"portrait_icao");return n!==void 0&&(n.state==="passed"||n.state==="review")?n:null}function Vt(e){return D(e).filter(t=>t.state==="failed").pop()?.attemptsExhausted===!0}function Ht(e,t){let n=e.failureReason,i;n===Fe?i="platform_unsupported":e.status==="expired"?i="expired":e.status==="review_pending"?i="review":e.status==="completed"&&e.outcome==="approved"?i="approved":e.status==="completed"&&e.outcome==="review"?i="review":n==="device_cooldown"?i="cooldown":n!==void 0?i="policy_stop":Vt(e)?i="attempts_exhausted":i="rejected";let r=i==="platform_unsupported"?{sessionId:te(e.sessionId),status:"unavailable"}:N(e,{autoRetry:!1}),s={kind:"result",key:"result",context:t,section:null,display:i,result:r};return n!==void 0&&(s.failureReason=n),e.retryAfter!==void 0&&(s.retryAfter=e.retryAfter),s}function Dt(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 c of Nt){let a=i[c];typeof a=="string"&&a!==""&&(r[c]=a)}let s=Ve(i);return s!==void 0&&(r.idNumberMasked=s,r.nniMasked=s),r}var Nt=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","expiryDate","retakeTarget"];function T(e,t,n,i){return{kind:"unsupported",key:`unsupported:${n}`,context:e,section:t,checkType:n,reason:i}}function Lt(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function Ut(e,t){let n=Ue[e.kind]??[...oe,...ie],i=Lt(e),r=e.options.flatMap(c=>{if(c.available===!1||!n.includes(c.service))return[];let a={id:c.id,service:c.service};c.nationalEid!=null&&(a.nationalEid=c.nationalEid);let l=(c.channels??[]).filter(f=>f==="whatsapp"||f==="sms");return c.service==="phone_otp"&&l.length>0&&(a.channels=l),[a]});if(r.length===0){let c=e.options.length>0&&e.options.every(a=>a.service==="nfc");return T(t,i,"choice",c?"platform_unsupported":"update_required")}let s={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:r};if(e.kind==="identity_method"){let c={kind:"method",key:"method",context:t,section:i,options:r.map(l=>H[l.service]),choice:s},a=r.find(l=>l.nationalEid!==void 0)?.nationalEid;return a!==void 0&&(c.nationalEid=a),c}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:i,options:r.map(c=>Ge[c.service]),selected:null,locked:!1,choice:s}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:i,choice:s}}function ln(e,t={}){let n=kt(e);if(b(e)||e.failureReason===Fe)return Ht(e,n);let i=e.plan;if(i===void 0||!Array.isArray(i.sections))return T(n,null,"plan","update_required");let r=Me(e);if(r!==null)return Ut(r,n);let s=i.current===null?void 0:i.steps.find(g=>g.id===i.current),c=g=>{let d={kind:"processing",key:"processing",context:n,section:g!==void 0?I(g):i.sections.find(k=>k.state==="current")?.id??null,stalled:!1};return typeof g?.service=="string"&&g.service!==""&&(d.service=g.service),d};if(i.current===null)return c(i.steps.find(g=>g.state==="processing"));if(s===void 0)return T(n,null,"step","update_required");if(!ft.has(s.service))return s.interaction==="server"?c(s):T(n,I(s),s.service,"update_required");if(mt.has(s.service)||!K(s))return c(s);let a=s,l=_t(a),f=a.checkType,m=I(a);switch(f){case"phone_otp":case"email_otp":return bt(e,a,n,l);case"population_registry":return It(e,a,n,l);case"eid_auth":return Et(e,a,n,l);case"doc_ocr":return At(e,a,n,l);case"identity_confirm":return Dt(e,n,m)??c(a);case"portrait_icao":return Le(e,a,n,l,"capture");case"liveness":case"face_match":{let g=Tt(e,a);if(g!==null)return Le(e,g,n,l,"match");let d=a.requiresMobile===!0,k=Y(e);return d&&t.isMobile===!1?{kind:"mobile_required",key:"mobile_required",context:n,section:m,checkType:f}:{kind:"liveness",key:"biometric",context:n,section:m,mode:f==="face_match"?"selfie":"liveness",requiresMobile:d,instructions:k===null?"standard":"icao",icao:k,livePhoto:Mt(e,f),...l}}case"nfc_chip":return T(n,m,f,"platform_unsupported");default:return T(n,m,f,"update_required")}}export{it as a,rt as b,st as c,at as d,ct as e,Qt as f,dt as g,He as h,lt as i,pt as j,tn as k,De as l,nn as m,dn as n,Fe as o,I as p,re as q,Be as r,Tt as s,ln as t};
@@ -0,0 +1 @@
1
+ import{a as G,e as ae,g as oe,m as ie}from"./chunk-53POX7U4.js";import{b as ce}from"./chunk-33KKMPJ5.js";import{a as se,d as ue}from"./chunk-CJHMFPL6.js";import{a as le}from"./chunk-RI3E7GBN.js";import{a as te,d as ne,e as re}from"./chunk-GT2ZLGF7.js";import{e as $}from"./chunk-FUHDOEBP.js";import{k as N,m as Z,n as ee}from"./chunk-CQ7SKLMC.js";var be=250,we=180,ve=96;function de(n){let{data:e,width:t,height:r}=n,a=new Uint8Array(t*r);for(let o=0,c=0;o<a.length;o+=1,c+=4)a[o]=Math.round(.299*(e[c]??0)+.587*(e[c+1]??0)+.114*(e[c+2]??0));return{data:a,width:t,height:r}}function V(n,e){return{x0:Math.max(0,Math.floor(n.x)),y0:Math.max(0,Math.floor(n.y)),x1:Math.min(e.width,Math.ceil(n.x+n.width)),y1:Math.min(e.height,Math.ceil(n.y+n.height))}}function T(n,e,t){let r=V(e,n),a=t===void 0?null:V(t,n),o=0,c=0,u=0,m=0;for(let s=r.y0;s<r.y1;s+=1)for(let x=r.x0;x<r.x1;x+=1){if(a!==null&&x>=a.x0&&x<a.x1&&s>=a.y0&&s<a.y1)continue;let M=n.data[s*n.width+x];o+=1,c+=M,u+=M*M,M>=be&&(m+=1)}if(o===0)return{mean:0,sd:0,clipped:0,count:0};let d=c/o;return{mean:d,sd:Math.sqrt(Math.max(0,u/o-d*d)),clipped:m/o,count:o}}function me(n){let{box:e}=n,r=(n.leftEye.y+n.rightEye.y)/2-.1*e.height,a=e.y+.85*e.height;return{x:e.x+.15*e.width,y:r,width:.7*e.width,height:Math.max(1,a-r)}}function Ce(n,e){let t=me(e),r=T(n,t);if(r.count===0)return null;let a=Math.min(Math.max(e.nose.x,t.x+1),t.x+t.width-1),o=T(n,{x:t.x,y:t.y,width:a-t.x,height:t.height}),c=T(n,{x:a,y:t.y,width:t.x+t.width-a,height:t.height}),u=c.mean>0?o.mean/c.mean:o.mean>0?Number.POSITIVE_INFINITY:1;return{faceLuma:r.mean,halfRatio:u,clipped:r.clipped}}function Pe(n,e){let t=0,r=0;for(let a of[e.leftEyeBox,e.rightEyeBox]){let o=a.width*.15,c=a.height*.5,u=T(n,{x:a.x-o,y:a.y-c,width:a.width+2*o,height:a.height+2*c});t+=u.count,r+=u.clipped*u.count}return t===0?null:r/t}function ke(n,e){let t=ae(e),{box:r}=e,a={x:r.x-.2*r.width,y:t.y,width:1.4*r.width,height:r.y+r.height-t.y},o=0,c=0,u=0;for(let d of[t.x,t.x+.8*t.width]){let s=T(n,{x:d,y:t.y+.04*t.height,width:.2*t.width,height:.25*t.height},a);o+=s.count,c+=s.mean*s.count,u+=(s.sd*s.sd+s.mean*s.mean)*s.count}if(o===0)return null;let m=c/o;return{luma:m,sd:Math.sqrt(Math.max(0,u/o-m*m)),count:o}}function Me(n,e){let t=V(me(e),n),r=Math.max(1,Math.floor(Math.max(t.x1-t.x0,t.y1-t.y0)/ve)),a=(d,s)=>n.data[s*n.width+d],o=0,c=0,u=0;for(let d=t.y0+r;d<t.y1-r;d+=r)for(let s=t.x0+r;s<t.x1-r;s+=r){let x=a(s,d-r)+a(s-r,d)+a(s+r,d)+a(s,d+r)-4*a(s,d);o+=1,c+=x,u+=x*x}if(o===0)return null;let m=c/o;return Math.min(1,Math.max(0,u/o-m*m)/we)}function he(n,e){return{lighting:Ce(n,e),eyeSpecular:Pe(n,e),background:ke(n,e),sharpness:Me(n,e)}}var Se="/models-v3",Le=640,Fe=.92;function K(n){return{width:n.videoWidth||0,height:n.videoHeight||0}}function W(n,e){if(typeof document<"u"){let t=document.createElement("canvas");return t.width=n,t.height=e,t}return typeof OffscreenCanvas=="function"?new OffscreenCanvas(n,e):null}function Te(){let n=null;return(e,t)=>{let{width:r,height:a}=K(e);if(r===0||a===0)return null;let o=t===null?1:Math.min(1,t/Math.max(r,a)),c=Math.round(r*o),u=Math.round(a*o),m;t===null?m=W(c,u):((n===null||n.width!==c||n.height!==u)&&(n=W(c,u)),m=n);let d=m?.getContext("2d",{willReadFrequently:!0});if(m==null||d==null)return null;d.drawImage(e,0,0,c,u);let s=null;try{s=d.getImageData(0,0,c,u)}catch{s=null}return{source:m,width:c,height:u,pixels:s}}}async function Ee(n,e,t,r){let a=Math.round(t*e.width/e.height),o=W(a,t),c=o?.getContext("2d");if(o==null||c==null)throw new Error("canvas unavailable");return c.fillStyle="#fff",c.fillRect(0,0,a,t),c.drawImage(n.source,e.x,e.y,e.width,e.height,0,0,a,t),"convertToBlob"in o?o.convertToBlob({type:"image/jpeg",quality:r}):new Promise((u,m)=>{o.toBlob(d=>d===null?m(new Error("encode failed")):u(d),"image/jpeg",r)})}var Y=class extends Error{};function Ie(n,e,t){return new Promise((r,a)=>{let o=setTimeout(()=>{a(new Y(`init exceeded ${e}ms`)),n.then(t,()=>{})},e);n.then(c=>{clearTimeout(o),r(c)},c=>{clearTimeout(o),a(c)})})}function Re(n){let e=Z(n),t=e==="overconstrained"?"generic":e,r=N(n);return{kind:t,retryable:t!=="insecure"&&t!=="unsupported",detail:{...r!==void 0?{name:r}:{},phase:"acquiring",engineKind:e}}}function Ge(n,e,t,r){let a=n.length===1?n[0]:void 0,o=a===void 0?null:G(a.landmarks,t,r),c=null;if(a!==void 0&&e.pixels!==null){let u=G(a.landmarks,e.width,e.height),m=de(e.pixels);u!==null&&(c=he(m,u))}return{frameWidth:t,frameHeight:r,faces:n.length,geometry:o,matrix:a?.matrix??null,blendshapes:a?.blendshapes??null,stats:c}}function Je(n,e={},t=()=>"self"){let r=ce(n.tuning,n.tuningVersion),a=te(),o=e.now??(()=>performance.now()),c=e.setTimer??((i,l)=>setTimeout(i,l)),u=e.clearTimer??(i=>clearTimeout(i)),m=e.grabFrame??Te(),d=e.encodeRegion??Ee,s=e.getUserMedia??(i=>navigator.mediaDevices.getUserMedia(i)),x=e.createLandmarker??ue,M=n.assetBaseUrl??Se,j=re({enabled:n.keepScreenAwake!==!1}),S=ie(r,{policy:n.policy??"reject"}),w=n.video,z=le({tuning:r.backgroundCheck,assetBaseUrl:M,...e.createSegmenter!==void 0?{createSegmenter:e.createSegmenter}:{},now:o}),h="idle",C=null,b=null,E=null,B=!1,g=!1,p=0,J=0,O=[],v="user",A=!1,fe=e.canChooseFacing??ne,L=i=>{h===i||g||(h=i,j.setActive(i==="starting"||i==="gating"),a.emit("state",i))},U=()=>{E!==null&&u(E),E=null},I=()=>{U();for(let i of C?.getTracks()??[])i.stop();C=null;try{w.srcObject=null}catch{}},H=i=>{I(),L("error"),a.emit("error",i)},Q=()=>{let i=Math.max(o(),J+1);return J=i,i},ge=async i=>{let l=m(w,null),{width:P,height:k}=l??K(w);if(l===null||b===null){S.reset();return}let f=b.detect(l.source,Q()),y=(f.length===1?f:O.length===1?O:[])[0],F=y===void 0?null:G(y.landmarks,P,k);if(F===null){S.reset();return}let R=oe(F,P,k,{margin:r.cropMargin,minWidth:r.resolution.minWidth,minHeight:r.resolution.minHeight}),q=Math.max(r.resolution.minHeight,R.height),xe=await d(l,R,q,Fe);if(g||i!==p)return;let X={image:xe,width:Math.round(q*R.width/R.height),height:q,gate:S.summary()};r.tuningVersion!==null&&(X.tuningVersion=r.tuningVersion),U(),L("captured"),a.emit("captured",X)},_=async i=>{if(!(g||i!==p||h!=="gating"||b===null)){if(!B){B=!0;try{let l=m(w,Le);if(l!==null){let{width:P,height:k}=K(w),f=b.detect(l.source,Q());O=f;let y=Ge(f,l,P||l.width,k||l.height);y.geometry!==null&&r.background.required&&(y.backgroundCheck=z.measure(l,y.geometry.box,P||l.width,k||l.height));let F=S.push(y,o());if(g||i!==p||(a.emit("gate",F),F.ready&&(await ge(i),h!=="gating")))return}}catch{}finally{B=!1}}!g&&i===p&&h==="gating"&&(E=c(()=>{_(i)},1e3/r.cadenceHz))}},pe=()=>Ie(x(M),2e4,i=>i.close()),ye=async i=>{if(t()!=="assisted")return"user";let l=i??(A?void 0:n.facing);if(l!==void 0)return l;if(A)return v;try{return await fe()?"environment":"user"}catch{return"user"}},D=async i=>{if(g||h==="starting"||h==="gating")return;p+=1;let l=p;S.reset(),L("starting");let P=await ye(i?.facing);if(g||l!==p)return;if(C!==null&&P!==v&&I(),v=P,A=!0,C===null&&e.getUserMedia===void 0&&(typeof navigator>"u"||typeof navigator.mediaDevices?.getUserMedia!="function")){let f=typeof window<"u"&&window.isSecureContext===!1?"insecure":"unsupported";H({kind:f,retryable:!1,detail:{phase:"preflight",engineKind:f}});return}let k=b!==null?Promise.resolve(b):pe();k.catch(()=>{});try{if(C===null){let f=await s({video:{facingMode:v,width:{ideal:r.camera.width},height:{ideal:r.camera.height}},audio:!1});if(g||l!==p){for(let y of f.getTracks())y.stop();return}C=f,ee(f),v=$(f)??v,w.srcObject=C,w.muted=!0,w.playsInline=!0,await w.play().catch(()=>{})}}catch(f){!g&&l===p&&H(Re(f));return}try{b=await k}catch(f){if(!g&&l===p){let y=N(f);H({kind:"generic",retryable:!0,detail:{...y!==void 0?{name:y}:{},phase:"models",engineKind:"models"}})}return}g||l!==p||(L("gating"),_(l))};return{handle:{get state(){return h},get captureMode(){return t()},get facingMode(){return v},on:(i,l)=>a.on(i,l),start:D,retry:()=>{if(!g){if(C!==null&&b!==null&&h!=="error"){p+=1;let i=p;U(),S.reset(),L("gating"),_(i);return}h="idle",D()}},switchCamera:()=>{if(g||t()!=="assisted"||h!=="idle"&&h!=="starting"&&h!=="gating"&&h!=="error")return!1;let i=v==="user"?"environment":"user";return p+=1,I(),v=i,h="idle",D({facing:i}),!0},destroy:()=>{g||(p+=1,I(),j.setActive(!1),g=!0,b?.close(),b=null,z.close(),a.clear())}},gateScores:()=>S.scores(),setFlowState:i=>{(h==="captured"||h==="uploading"||h==="checking"||h==="done"&&i==="done")&&L(i)}}}function Qe(){import("@mediapipe/tasks-vision").catch(()=>{})}export{be as a,we as b,de as c,T as d,Ce as e,Pe as f,ke as g,Me as h,he as i,Le as j,Fe as k,Te as l,Ge as m,Je as n,Qe as o};