@sekyro/web 0.1.0-rc.35 → 0.1.0-rc.36

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 (42) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/{capture-session-doc-KAKQJPCO.js → capture-session-doc-LKMMJG4H.js} +1 -1
  3. package/dist/{capture-session-v3-BS2Rl4Kp.d.cts → capture-session-v3-DaRhtwrC.d.cts} +1 -1
  4. package/dist/{capture-session-v3-CYh0Jmyf.d.ts → capture-session-v3-_JtEhXUz.d.ts} +1 -1
  5. package/dist/{chunk-LMAAUMW5.js → chunk-2J6R5JOJ.js} +1 -1
  6. package/dist/{chunk-LRIYZH6A.js → chunk-AIRC3HT7.js} +1 -1
  7. package/dist/{chunk-X7PJC4KD.js → chunk-EF4VD4GD.js} +1 -1
  8. package/dist/{chunk-NUMPZ7OO.js → chunk-H2ZUHMIC.js} +2 -2
  9. package/dist/{chunk-IMFHLLKO.js → chunk-K7ICBHSZ.js} +1 -1
  10. package/dist/{chunk-EDDPTTRH.js → chunk-KCUXJT7L.js} +1 -1
  11. package/dist/{chunk-JQIDW5SX.js → chunk-NMPMXAH3.js} +1 -1
  12. package/dist/{chunk-Y25KN6OM.js → chunk-VZGTOE22.js} +1 -1
  13. package/dist/chunk-W42RLLAC.js +1 -0
  14. package/dist/client/index.cjs +1 -1
  15. package/dist/client/index.d.cts +3 -3
  16. package/dist/client/index.d.ts +3 -3
  17. package/dist/client/index.js +1 -1
  18. package/dist/core/index.cjs +1 -1
  19. package/dist/core/index.d.cts +3 -3
  20. package/dist/core/index.d.ts +3 -3
  21. package/dist/core/index.js +1 -1
  22. package/dist/{create-document-capture-AITCB4ZU.js → create-document-capture-PG6NLCPH.js} +1 -1
  23. package/dist/{create-verification-Db86u8xP.d.ts → create-verification-Bda1l0t0.d.ts} +8 -3
  24. package/dist/{create-verification-BKFbeab5.d.cts → create-verification-C58r4HV-.d.cts} +8 -3
  25. package/dist/{icao-gate-LrDH6YLB.d.cts → icao-gate-67SejsPE.d.cts} +1 -1
  26. package/dist/{icao-gate-CkcYbe6Q.d.ts → icao-gate-CjdvLXEu.d.ts} +1 -1
  27. package/dist/{icao-policy-DdVtGf5g.d.cts → icao-policy-CJsmf9Vh.d.cts} +2 -2
  28. package/dist/{icao-policy-H6l8Q5XX.d.ts → icao-policy-COdRM4m_.d.ts} +2 -2
  29. package/dist/index.cjs +2 -2
  30. package/dist/index.d.cts +7 -7
  31. package/dist/index.d.ts +7 -7
  32. package/dist/index.js +1 -1
  33. package/dist/internal/index.cjs +2 -2
  34. package/dist/internal/index.d.cts +6 -6
  35. package/dist/internal/index.d.ts +6 -6
  36. package/dist/internal/index.js +1 -1
  37. package/dist/{plan-runner-HPXZHAQB.js → plan-runner-BZ7LODPB.js} +1 -1
  38. package/dist/{types-BjzuJVOc.d.cts → types-BOfzAhqF.d.cts} +9 -0
  39. package/dist/{types-BjzuJVOc.d.ts → types-BOfzAhqF.d.ts} +9 -0
  40. package/package.json +1 -1
  41. package/sbom.cdx.json +19 -19
  42. package/dist/chunk-ARQMJKYY.js +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @sekyro/web
2
2
 
3
+ ## 0.1.0-rc.36
4
+
5
+ ### Patch Changes
6
+
7
+ - 8bbc6f8: A level-1 flow (contact or device steps only, Device and network plus Form included) is now named "Contact verification". `HostedSessionView` carries `levelTarget: { min, max }`, the levels the session can reach, and `StepContext.levelName` is `contact` when `levelTarget.max` is 1 or lower, else the session's `purpose`. Older APIs send no `levelTarget`, and `levelName` then follows `purpose` as before.
8
+
3
9
  ## 0.1.0-rc.35
4
10
 
5
11
  ### Patch Changes
@@ -1 +1 @@
1
- import{A as b,B as c,C as d,D as e,E as f,F as g,G as h,H as i,I as j,J as k,z as a}from"./chunk-EDDPTTRH.js";import"./chunk-JULJQOVT.js";import"./chunk-SMKCBUJL.js";import"./chunk-XON3UNG3.js";import"./chunk-XFATG7QI.js";import"./chunk-POIQGEZM.js";import"./chunk-CPUECYAJ.js";import"./chunk-FPXL63KZ.js";import"./chunk-LRIYZH6A.js";import"./chunk-ISMVEF7H.js";export{k as CAPTURE_CANDIDATE_SPACING_MS,j as CAPTURE_EXTRA_CANDIDATES,h as CaptureSessionDoc,c as DOC_BLACK_FRAME_LUMA,d as DOC_BLACK_FRAME_TICKS,e as DOC_CADENCE_HZ,b as DOC_FIRST_FRAME_MS,f as DOC_SHUTTER_DEFAULTS,i as passportBandOf,g as resolveDocShutterTuning,a as warmDocDetector};
1
+ import{A as b,B as c,C as d,D as e,E as f,F as g,G as h,H as i,I as j,J as k,z as a}from"./chunk-KCUXJT7L.js";import"./chunk-JULJQOVT.js";import"./chunk-SMKCBUJL.js";import"./chunk-XON3UNG3.js";import"./chunk-XFATG7QI.js";import"./chunk-POIQGEZM.js";import"./chunk-CPUECYAJ.js";import"./chunk-FPXL63KZ.js";import"./chunk-AIRC3HT7.js";import"./chunk-ISMVEF7H.js";export{k as CAPTURE_CANDIDATE_SPACING_MS,j as CAPTURE_EXTRA_CANDIDATES,h as CaptureSessionDoc,c as DOC_BLACK_FRAME_LUMA,d as DOC_BLACK_FRAME_TICKS,e as DOC_CADENCE_HZ,b as DOC_FIRST_FRAME_MS,f as DOC_SHUTTER_DEFAULTS,i as passportBandOf,g as resolveDocShutterTuning,a as warmDocDetector};
@@ -1,4 +1,4 @@
1
- import { br as ScreenRampReport, bi as CaptureProvenance, bo as ScreenRampChallenge, bp as ScreenRampPaint } from './types-BjzuJVOc.cjs';
1
+ import { br as ScreenRampReport, bi as CaptureProvenance, bo as ScreenRampChallenge, bp as ScreenRampPaint } from './types-BOfzAhqF.cjs';
2
2
  import { F as FaceObservation, b as Detector, W as WorkerLike } from './detect-worker-CHqsPJoM.cjs';
3
3
 
4
4
  /** MP4-first ladder: one container (H.264 MP4) covers iOS/macOS Safari + Chrome 130+.
@@ -1,4 +1,4 @@
1
- import { br as ScreenRampReport, bi as CaptureProvenance, bo as ScreenRampChallenge, bp as ScreenRampPaint } from './types-BjzuJVOc.js';
1
+ import { br as ScreenRampReport, bi as CaptureProvenance, bo as ScreenRampChallenge, bp as ScreenRampPaint } from './types-BOfzAhqF.js';
2
2
  import { F as FaceObservation, b as Detector, W as WorkerLike } from './detect-worker-CHqsPJoM.js';
3
3
 
4
4
  /** MP4-first ladder: one container (H.264 MP4) covers iOS/macOS Safari + Chrome 130+.
@@ -1 +1 @@
1
- import{a as ne,b as ie}from"./chunk-SX7TUC3V.js";import{b as ce,c as ue,d as de}from"./chunk-POIQGEZM.js";import{a as Y,c as j,e as $,g as J,h as A,k as R,m as ee,n as re}from"./chunk-CPUECYAJ.js";import{b as L,c as pe,d as F,e as me}from"./chunk-FPXL63KZ.js";import{a as z,c as X,d as Z,e as Q}from"./chunk-TSA6GHUG.js";import{d as te}from"./chunk-LRIYZH6A.js";import{e as ae,f as se,h as G,j as oe,l as le}from"./chunk-FSSMUAKC.js";var Ie=[...Y.filter(i=>i.startsWith("video/mp4")),"video/webm;codecs=h264","video/webm;codecs=avc1","video/webm;codecs=vp8","video/webm;codecs=vp9","video/webm"],he=new Set;function De(i){let e=/(?:Chrome|Chromium)\/(\d+)\./.exec(i??"");return e?Number(e[1]):null}function fe(i=Oe(),e=globalThis.navigator?.userAgent){if(i===void 0)return"";let t=De(e)===126;for(let r of Ie)if(!(he.has(r)||t&&r.startsWith("video/mp4")))try{if(i(r))return r}catch{}return""}function V(i){i!==""&&he.add(i)}function ge(i){return i.replace(/^video\/x-matroska/i,"video/webm")}function ut(i){let e=/codecs=["']?([^,;"']+)/i.exec(i);return e?e[1].trim():i.split(";")[0].trim()}function Oe(){let i=globalThis.MediaRecorder;return i&&typeof i.isTypeSupported=="function"?e=>i.isTypeSupported(e):void 0}var U=2500,Pe=1e3,xe=1500,ve=25e5,Ge=100,Le=700,Fe=20,Ve=1500,N=null;function Ne(){return N??(N=import("./clip-inspect-DLJXVKV6.js").catch(i=>{throw N=null,i})),N.catch(()=>null)}var S=class extends Error{constructor(e,t){super(t??e),this.kind=e}},Ue=100;function H(i,e){return i.stats===void 0?!1:i.stats===null?!0:i.stats.durationMs<e-Ue}function be(i,e){return i.stats?e.stats?i.stats.durationMs>e.stats.durationMs:!0:!1}var I=class{constructor(e={}){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.pollTimer=null;this.settled=!1;this.now=e.now??(()=>globalThis.performance?.now?.()??Date.now())}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.pollTimer&&clearInterval(this.pollTimer),this.hardStopTimer=null,this.graceTimer=null,this.pollTimer=null}record(e,t,r,n=U,a){let s=fe(),o=Ne();return this.recordRaw(e,t,r,n,a,s).then(c=>He(c,o),c=>{throw c instanceof S&&(c.requestedMimeType=s),c})}recordRaw(e,t,r,n,a,s){return this.recorder&&!this.settled?Promise.reject(new S("generic","record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time")):(this.recorder=null,this.clearTimers(),this.chunks=[],this.bytes=0,this.settled=!1,this.stream=e,new Promise((o,c)=>{let l;try{l=new MediaRecorder(e,s?{mimeType:s,videoBitsPerSecond:ve}:{videoBitsPerSecond:ve})}catch{try{l=new MediaRecorder(e)}catch{c(new S("unsupported"));return}}this.recorder=l;let d=h=>{this.settled||(this.settled=!0,this.clearTimers(),h())},u=()=>d(()=>{let h=ge(l.mimeType||s||j),b=new Blob(this.chunks,{type:h});if(b.size===0){c(new S("generic","empty clip"));return}if(A(b)){c(new S("cliptoolarge"));return}o({blob:b,mimeType:h,requestedMimeType:s})});l.ondataavailable=h=>{h.data&&h.data.size&&(this.chunks.push(h.data),this.bytes+=h.data.size,this.bytes>J&&d(()=>{try{l.state!=="inactive"&&l.stop()}catch{}c(new S("cliptoolarge"))}))},l.onstop=u,l.onerror=()=>d(()=>c(new S("generic")));let f=this.now();if(r!==void 0||a!==void 0){let h=!1;l.onstart=()=>{if(!(h||this.settled)&&(h=!0,f=this.now(),r!==void 0))try{r()}catch{}}}try{l.start(Pe)}catch{d(()=>c(new S("generic")));return}let g=()=>{if(this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=null,this.settled||t?.(),l.state!=="inactive"){try{l.stop()}catch{u()}this.graceTimer=setTimeout(u,xe)}else u()},p=this.now();if(a===void 0){this.hardStopTimer=setTimeout(g,n);return}let m=null,y=!1;this.hardStopTimer=setTimeout(g,n+Le),this.pollTimer=setInterval(()=>{if(this.settled||y)return;let h=null;try{h=a.latest()}catch{h=null}let b=h?.presentationTimeMs;b!==void 0&&Number.isFinite(b)&&b>=f&&m===null&&(m=b);let C=m!==null&&b!==void 0&&b-m>=n,E=m===null&&this.now()-p>=n;if(!(!C&&!E)){if(y=!0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,E){g();return}this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=setTimeout(g,Ge)}},Fe)}))}stop(e){this.clearTimers();let t=this.recorder;if(t&&t.state!=="inactive")try{t.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(n=>n.stop()),this.stream=null}};async function He(i,e){let t,r=new Promise(l=>{t=setTimeout(()=>l(null),Ve)}),n=await Promise.race([e,r]);if(clearTimeout(t),n===null)return i;let a;try{a=await n.blobBytes(i.blob)}catch{return{...i,stats:null}}let s=n.inspectClipBytes(a);if(s?.container!=="webm")return{...i,stats:s};let o=n.withWebmDuration(a,s.durationMs);if(o===null)return{...i,stats:s};let c=n.inspectClipBytes(o);return c===null||c.frames!==s.frames||c.durationMs!==s.durationMs?{...i,stats:s}:{...i,blob:new Blob([o],{type:i.blob.type}),stats:s}}var Ke=["magenta","yellow","green","blue"];var Be={magenta:"rgb(255, 72, 150)",yellow:"rgb(255, 190, 0)",green:"rgb(0, 238, 175)",blue:"rgb(25, 150, 255)",dark:"rgb(0, 0, 0)"};function ft(i){return Be[i]}var We=4,qe=4,D=i=>typeof i=="number"&&Number.isFinite(i);function O(i){if(typeof i!="object"||i===null)return!1;let e=i;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length<1||e.colours.length>8||!e.colours.every(r=>Ke.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==e.colours.length)return!1;let t=-1;for(let r of e.onsetsMs){if(!D(r)||r<0||r<=t)return!1;t=r}return!(!D(e.holdMs)||e.holdMs<=0||!D(e.endMs)||e.endMs<=t||!D(e.clipMs)||e.clipMs<e.endMs||e.clipMs>8e3)}function ye(i,e){return O(i)?Math.max(e,Math.ceil(i.clipMs)):e}function Me(i,e){let t=e.now??(()=>performance.now()),r=O(i)?i:void 0,n=[],a=null,s=null,o=null,c=!1,l=null,d=p=>{l=p;try{e.paint(p)}catch{}},u=p=>{let m=e.frames?.()??null;return m!==null&&o!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-o:p-(s??p)},f=(p,m,y=0)=>{if(c)return;let h=Math.max(0,p-u(t()));a=setTimeout(()=>{if(a=null,!c){if(y<We&&u(t())<p-qe){f(p,m,y+1);return}m()}},h)},g=p=>{if(r===void 0)return;let m=r.endMs;if(p>=r.colours.length){f(m,()=>d(null));return}let y=r.onsetsMs[p],h=p+1<r.onsetsMs.length?r.onsetsMs[p+1]:m;f(y,()=>{let b=u(t());if(b>m){l!==null&&d(null);return}let C=r.colours[p];d(C);let E=n.length===0?0:n[n.length-1].tMs;n.push({tMs:Math.max(E,Math.round(b)),colour:C});let M=y+r.holdMs;if(M<h){f(M,()=>{if(u(t())>m){l!==null&&d(null);return}d("dark"),g(p+1)});return}g(p+1)})};return{started(p){if(r===void 0||c||s!==null)return;s=p;let m=e.frames?.()??null;o=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),g(0)},stop(){c||(c=!0,a!==null&&clearTimeout(a),a=null,l!==null&&d(null))},report(){return r===void 0?void 0:{nonce:r.nonce,rendered:[...n]}}}}function Se(i,e,t=.92){return new Promise((r,n)=>{let a=i.videoWidth,s=i.videoHeight;if(!a||!s){n(new Error("video-not-ready"));return}let o=e.getContext("2d");if(!o){n(new Error("no-2d-context"));return}e.width=a,e.height=s,o.scale(-1,1),o.drawImage(i,-a,0),e.toBlob(c=>c?r(c):n(new Error("empty-keyframe")),"image/jpeg",t)})}var P=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let t=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),t()}))};t();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((t,r)=>t+r,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var ze=Object.freeze({Q_GOOD:.6,RISE_PER_S:.9,FALL_PER_S:.25,CENTER_FALLOFF_IOD_MULTIPLE:1.35,BOX_EYE_OFFSET_FACTOR:.12,IOD_BOX_PROXY_FACTOR:.42,SIZE_IDEAL_MIN:.12,SIZE_IDEAL_MAX:.3,SIZE_HARD_MIN:.08,SIZE_HARD_MAX:.45,ROLL_MAX_DEG:25,MOTION_VELOCITY_IOD_PER_S:.5,MOTION_TAU_S:.4,MOTION_DEADBAND_IOD_PER_S:.1,READY_WINDOW_MS:500,GUIDE_SIZE:.6,GUIDE_CENTERING:.6,GUIDE_POSE:.6,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,GUIDE_MOTION:.5}),_=i=>Math.min(1,Math.max(0,i)),k=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...ze,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:t,quality:r,timestampMs:n}=e,a=this.lastTickAt===null?0:Math.max(0,(n-this.lastTickAt)/1e3);this.lastTickAt=n;let s={presence:0,single:1,centering:0,size:0,pose:0,sharpness:_(r.sharpness),exposure:_(r.exposure),motion:1};if(t!==null){s.presence=1,s.single=(t.extraFaces??0)>0?0:1;let d=this.geometryOf(t,e);s.centering=d.centering,s.size=d.size,s.pose=d.pose,s.motion=this.motionOf(d.center,d.iod,n)}else this.lastCenter=null,this.velocityEma=0;let o=Math.min(s.presence,s.single,s.centering,s.size,s.pose,s.sharpness,s.exposure,s.motion);this.p=_(this.p+(o>=this.t.Q_GOOD?this.t.RISE_PER_S*o:-this.t.FALL_PER_S*(1-o))*a),this.qWindow.push({at:n,q:o}),this.qWindow=this.qWindow.filter(d=>d.at>=n-this.t.READY_WINDOW_MS);let c=this.qWindow.map(d=>d.q);if(c.length>=3){let d=Math.min(...c),u=c.indexOf(d);c=c.filter((f,g)=>g!==u)}let l=this.p>=1&&c.every(d=>d>=this.t.Q_GOOD);return{at:n,q:o,p:this.p,factors:s,guidanceKey:this.guidanceOf(s,r,o),ready:l,accepted:o>=this.t.Q_GOOD}}geometryOf(e,t){let{box:r,eyes:n}=e,a={x:t.frameWidth/2,y:t.frameHeight/2},s=Math.min(t.frameWidth,t.frameHeight),o=n!==void 0?{x:(n.left.x+n.right.x)/2,y:(n.left.y+n.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},c=n!==void 0?Math.hypot(n.right.x-n.left.x,n.right.y-n.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,l=Math.hypot(o.x-a.x,o.y-a.y),d=c<=0?0:1-_(l/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*c)),u=s>0?c/s:0;this.lastSizeDirection=u<this.t.SIZE_IDEAL_MIN?"far":u>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;u<this.t.SIZE_HARD_MIN||u>this.t.SIZE_HARD_MAX?f=0:u<this.t.SIZE_IDEAL_MIN?f=(u-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):u>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-u)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let g=1;if(n!==void 0){let p=Math.abs(Math.atan2(n.right.y-n.left.y,n.right.x-n.left.x))*180/Math.PI;g=1-_(p/this.t.ROLL_MAX_DEG)}return{center:o,iod:c,centering:d,size:f,pose:g}}motionOf(e,t,r){let n=this.lastCenter;if(this.lastCenter={...e,at:r},n===null||t<=0)return 1;let a=(r-n.at)/1e3;if(a<=0)return 1;let s=Math.hypot(e.x-n.x,e.y-n.y)/t/a;s<=this.t.MOTION_DEADBAND_IOD_PER_S&&(s=0);let o=1-Math.exp(-a/this.t.MOTION_TAU_S);return this.velocityEma=o*s+(1-o)*this.velocityEma,1-_(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,r){if(e.presence<=0)return"fcv3.no_face";if(e.single<=0)return"fcv3.one_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(t);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(r<this.t.Q_GOOD){let n=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],a=n[0];for(let s of n)e[s[0]]<e[a[0]]&&(a=s);return a[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(L[0]+L[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Xe=["single","size","centering","pose","exposure","sharpness","motion"];function Ze(i){if(i.accepted)return null;if(i.factors.presence<=0)return"no_face";let e="single";for(let t of Xe)i.factors[t]<i.factors[e]&&(e=t);return e}var w=class{constructor(){this.blocked={};this.acceptedMs=0;this.ticks=0;this.lastAt=null}record(e){let t=this.lastAt===null?0:Math.max(0,e.at-this.lastAt);this.lastAt=e.at,this.ticks+=1;let r=Ze(e);if(r===null){this.acceptedMs+=t;return}let n=this.blocked[r]??{count:0,ms:0};n.count+=1,n.ms+=t,this.blocked[r]=n}summary(){let e={};for(let[t,r]of Object.entries(this.blocked))e[t]={count:r.count,ms:Math.round(r.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var Qe=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ye=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^caméra (avant|arrière)\b/i,/^cámara (frontal|trasera|delantera)\b/i,/^câmera (frontal|traseira)\b/i,/^(front|rück)kamera\b/i,/^الكاميرا (الأمامية|الخلفية)/,/^camera2? ?\d+, facing (front|back|external)/i,/facetime/i,/\b(integrated|built-in|builtin) (web)?cam(era)?\b/i,/\b(hd )?web ?cam\b/i,/\([0-9a-f]{4}:[0-9a-f]{4}\)\s*$/i];function je(i){let e=(i??"").trim().toLowerCase();return e.length===0?"unknown":Qe.some(t=>e.includes(t))?"known_virtual":Ye.some(t=>t.test(e))?"platform":"unknown"}function Te(i){if(typeof i!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(i))}catch{return!1}}function $e(i=globalThis){return Te(i.navigator?.mediaDevices?.getUserMedia)&&Te(i.MediaStreamTrack?.prototype?.getSettings)}async function Je(i,e=globalThis){let t=e.crypto?.subtle?.digest;if(typeof t=="function")try{let r=new Uint8Array(await t.call(e.crypto?.subtle,"SHA-256",new TextEncoder().encode(i)));return Array.from(r.subarray(0,8),n=>n.toString(16).padStart(2,"0")).join("")}catch{return}}async function Ce(i,e=globalThis){let t={};try{t=typeof i.getSettings=="function"?i.getSettings()??{}:{}}catch{t={}}let r={};if((t.facingMode==="user"||t.facingMode==="environment"||t.facingMode==="left"||t.facingMode==="right")&&(r.facingMode=t.facingMode),typeof t.frameRate=="number"&&Number.isFinite(t.frameRate)&&(r.frameRate=t.frameRate),typeof t.width=="number"&&Number.isFinite(t.width)&&(r.width=t.width),typeof t.height=="number"&&Number.isFinite(t.height)&&(r.height=t.height),typeof t.deviceId=="string"&&t.deviceId.length>0){let a=await Je(t.deviceId,e);a!==void 0&&(r.deviceIdHash=a)}let n;try{n=i.label}catch{n=void 0}return{trackSettings:r,capabilitiesPresent:typeof i.getCapabilities=="function",labelClass:je(n),prototypesIntact:$e(e)}}var K=i=>Math.round(i*100)/100;function Ee(i){let e=i,t=typeof e?.requestVideoFrameCallback=="function",r=null,n=null,a=0,s=0,o=0,c=0,l=0,d=0,u=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((f,g)=>{if(r=null,!t)return;let p=g.presentationTime;if(n!==null){let m=p-n.presentationTimeMs;s+=1;let y=m-o;o+=y/s,c+=y*(m-o)}typeof g.captureTime=="number"&&Number.isFinite(g.captureTime)&&(l+=p-g.captureTime,d+=1),a+=1,n={mediaTimeMs:g.mediaTime*1e3,presentationTimeMs:p},u()}))};return u(),{latest:()=>n,stats:()=>({n:a,meanGapMs:s===0?0:K(o),stdGapMs:s<2?0:K(Math.sqrt(c/(s-1))),captureLatencyMs:d===0?null:K(l/d)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function _e(i,e,t){return{...i,rvfc:e,rampPainter:t}}var et=1e3,B="fcv3.hold_upright",tt=200,W=4,rt=600,nt=1e3,Re={sharpness:1,exposure:1,meanLuma:128};function it(i,e){return e.width=i.videoWidth,e.height=i.videoHeight,e.getContext("2d").drawImage(i,0,0),new Promise((t,r)=>e.toBlob(n=>n?t(n):r(new Error("empty-keyframe")),"image/jpeg",.92))}function at(){return X()==="phone"}var ke=class{constructor(e){this.handlers=new Map;this.stateValue="idle";this.attempt=0;this.stream=null;this.detector=null;this.scheduler=null;this.gate=null;this.profiler=null;this.lastGuidanceKey=null;this.positioningStartedAt=0;this.cameraRequestedAt=null;this.cameraReadyAt=null;this.faceAcquiredAt=null;this.captureCompleteAt=null;this.fired=!1;this.carriedDegrade=0;this.carriedMeans=[];this.blockStats=null;this.lastGateSnapshotAt=Number.NEGATIVE_INFINITY;this.uprightGuard=!1;this.trackProvenance=null;this.ramp=null;this.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>r?.delete(t)}emit(e,t){for(let r of[...this.handlers.get(e)??[]])r(t)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}restart(e){this.facing=e,this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:t}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.uprightGuard=(t.isPhone??at)(),this.setState("preflight");let r=$();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let n=t.getUserMedia??(l=>navigator.mediaDevices.getUserMedia(l)),a;this.cameraRequestedAt=this.now();try{let{facingMode:l,...d}=z(Z(),this.facing).video;a=await ie(this.facing,d,{getUserMedia:n,enumerateDevices:lt(t)})}catch(l){if(e!==this.attempt)return;if(l instanceof ne){this.fail("backcamera",{phase:"acquiring",name:R(l)});return}this.fail(ee(l),{phase:"acquiring",name:R(l)});return}if(te(a),re(a),e!==this.attempt){for(let l of a.getTracks())l.stop();return}this.stream=a;let s=a.getVideoTracks?.()[0];if(this.trackProvenance=s===void 0?null:Ce(s).catch(()=>null),this.facing=Q(a)??this.facing,t.video.srcObject=a,await t.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let l={v3AssetBaseUrl:t.v3AssetBaseUrl},d=t.createDetector??(t.createWorker!==void 0&&oe()?async()=>{try{return await le.create(t.createWorker(),l)}catch{return G(l)}}:()=>G(l)),u;try{u=await d()}catch(f){e===this.attempt&&this.fail("models",{phase:"models",name:R(f)},f instanceof ae?f.fallbackReason:ot(f));return}if(e!==this.attempt){u.destroy();return}this.detector=u,this.options.telemetry?.({type:"detector",tier:u.tier,fallbackReason:u.fallbackReason})}let o=ce(),c=t.deviceClass??ue(o);this.profiler=new de(c),this.options.telemetry?.({type:"profile",staticClass:c,activeClass:this.profiler.deviceClass,simd:o.simd}),this.gate=new k(t.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(l=>q=l,()=>{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let t=this.profiler;if(t===null)return;if(this.scheduler!==null){let n=this.scheduler.stats();this.carriedDegrade+=n.degradeCount,n.meanDetectMs>0&&this.carriedMeans.push(n.meanDetectMs),this.scheduler.stop()}let r=new P({cadenceHz:t.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=r,r.start()}async detectTick(e){let{detector:t,gate:r,profiler:n}=this,a=this.options.video;if(e!==this.attempt||t===null||r===null||n===null||this.fired||a.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let s=n.deviceClass,o=this.now(),c=this.options.makeSnapshot?.(a,n.profile.inputWidth)??this.defaultSnapshot(a,n.profile.inputWidth),l=null;try{l=await t.detect(c,a.videoWidth,a.videoHeight)}catch{l=null}if(e!==this.attempt||this.fired)return;n.record(this.now()-o),n.deviceClass!==s&&this.startScheduler(e);let d=l===null?Re:this.options.measureQuality?.(a,l.box)??this.defaultQuality(a,l.box),u=r.tick({timestampMs:this.now(),observation:l,quality:d,frameWidth:a.videoWidth,frameHeight:a.videoHeight});u.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=u.at),this.blockStats?.record(u),!u.ready&&u.at-this.lastGateSnapshotAt>=et&&(this.lastGateSnapshotAt=u.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:u.p,q:u.q,factors:u.factors,attempt:e}),u.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=u.guidanceKey,this.emit("guidance",{key:u.guidanceKey})),u.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=u.at,this.fire(e))}async fire(e){let{options:t}=this,r=this.scheduler;r?.stop(),this.reportGate(!0);let n=r?.stats()??{degradeCount:0,meanDetectMs:0},a=[...this.carriedMeans,...n.meanDetectMs>0?[n.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+n.degradeCount,meanDetectMs:a.length===0?0:a.reduce((M,v)=>M+v,0)/a.length});let s=t.mode??"clip",o=t.rankKeyframes?.()&&q?q.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(s==="photo"){let M=this.watchRotation(e,null),v=await o;if(M(),e!==this.attempt)return;if(v===null){this.fail("generic",{phase:"keyframes"});return}let x=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:v.blob,previewDataUrl:v.previewDataUrl,...x});return}this.setState("recording");let c=this.stream;if(c===null){this.fail("generic",{phase:"recording"});return}let l=t.screenRamp?.(),d=O(l),u=null;o.then(M=>{u=M},()=>{});let f=()=>{e===this.attempt&&u!==null&&this.emit("frozen",{previewDataUrl:u.previewDataUrl})},g=ye(l,U),p=null,m,y=0;try{let M=this.recordTake(e,c,l,g,void 0).then(T=>T,T=>({failed:T})),[v,x]=await Promise.all([M,o]);if(m=x,e!==this.attempt)return;if("failed"in v){if(v.failed.kind==="cliptoolarge")throw v.failed;V(v.failed.requestedMimeType??"")}else p=v,H(v.clip,g)?v.clip.stats===null&&V(v.clip.requestedMimeType??""):f();if(p===null||H(p.clip,g)){y=1,t.telemetry?.({type:"clip_retake",reason:p===null?"error":p.clip.stats===null?"unreadable":"short"});let T=null;try{T=await this.recordTake(e,c,l,g,f)}catch(Ae){if(p===null)throw Ae}if(e!==this.attempt)return;T!==null&&(p===null||be(T.clip,p.clip))&&(p=T),T===null&&f()}}catch(M){if(e!==this.attempt)return;let v=M.kind;this.fail(v==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:R(M)});return}if(p===null){this.fail("recorder",{phase:"recording"});return}let{clip:h,rvfc:b,report:C}=p;if(A(h.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(m===null){this.fail("generic",{phase:"keyframes"});return}let E=await this.provenance(b,d);e===this.attempt&&this.finishCapture({clip:h.blob,clipMimeType:h.mimeType,...h.stats?{clipStats:h.stats}:{},clipRetakes:y,keyframe:m.blob,previewDataUrl:m.previewDataUrl,...C!==void 0&&C.rendered.length>0?{screenRamp:C}:{},...E})}async recordTake(e,t,r,n,a){let s=this.options.createRecorder?.()??new I({now:()=>this.now()}),o=Ee(this.options.video),c=Me(r,{paint:u=>{(u===null||e===this.attempt)&&this.emit("ramp",{colour:u})},now:()=>this.now(),frames:o.latest});this.ramp=c;let l=()=>{o.stop(),c.stop(),this.ramp===c&&(this.ramp=null)},d=this.watchRotation(e,s);try{return{clip:await s.record(t,a,()=>c.started(this.now()),n,o),rvfc:o.stats(),report:c.report()}}finally{d(),l()}}async provenance(e,t){let r=this.trackProvenance;if(r===null)return{};let n,a=new Promise(o=>{n=setTimeout(()=>o(null),nt)}),s=await Promise.race([r,a]);return clearTimeout(n),s===null?{}:{provenance:_e(s,e,t)}}isLandscape(){let e=this.options.video;return this.uprightGuard&&e.videoWidth>e.videoHeight}holdUpright(e){this.gate?.reset(),this.emit("checks",{engine:"v3",progress:0,q:0,factors:{presence:0,single:1,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==B&&(this.lastGuidanceKey=B,this.emit("guidance",{key:B}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,n=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){o();return}r.videoWidth>0&&this.isLandscape()&&(o(),this.abortRecording(e,t))},a=setInterval(n,tt);r.addEventListener?.("resize",n);let s=!1;function o(){s||(s=!0,clearInterval(a),r.removeEventListener?.("resize",n))}return o}abortRecording(e,t){if(e!==this.attempt)return;this.attempt+=1;let r=this.attempt;try{t?.stop()}catch{}this.ramp?.stop(),this.ramp=null,this.fired=!1,this.captureCompleteAt=null,this.gate=new k(this.options.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),this.lastGuidanceKey=null,this.setState("positioning"),this.positioningStartedAt=this.now(),this.holdUpright(r),this.startScheduler(r)}async collectKeyframes(e){let t=this.options.captureKeyframe??(a=>this.defaultKeyframe(a)),r=rt/(W-1),n=null;for(let a=0;a<W;a+=1){if(e!==this.attempt)return n;try{let s=await t(this.options.video);(n===null||s.sharpness>n.sharpness)&&(n=s)}catch{}a<W-1&&await st(r)}return n}finishCapture(e){this.stopTracks(),this.setState("captured");let t=this.captureTiming();this.emit("artifacts",t===void 0?e:{...e,timing:t})}captureTiming(){let e={},t=(r,n,a)=>{n!==null&&a!==null&&(e[r]=Math.max(0,Math.round(a-n)))};return t("cameraReadyMs",this.cameraRequestedAt,this.cameraReadyAt),t("faceAcquireMs",this.cameraReadyAt,this.faceAcquiredAt),t("captureMs",this.faceAcquiredAt,this.captureCompleteAt),Object.keys(e).length>0?e:void 0}async defaultKeyframe(e){let t=document.createElement("canvas"),r=await(this.facing==="user"?Se:it)(e,t),n=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:n,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),n=t/Math.max(1,e.videoWidth),a=Math.max(1,Math.round(e.videoWidth*n)),s=Math.max(1,Math.round(e.videoHeight*n)),o=r.getContext("2d");return o===null?e:(r.width!==a&&(r.width=a),r.height!==s&&(r.height=s),o.drawImage(e,0,0,a,s),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,t){let r=we(e,t,96);return r===null?Re:{sharpness:F(r),exposure:me(r),meanLuma:pe(r)}}centerSharpness(e){let t=se(e),r=we(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:F(r)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.ramp?.stop(),this.ramp=null,this.stopTracks()}reportGate(e){let t=this.blockStats,r=this.profiler;if(t===null||r===null)return;let n=t.summary();e&&(this.blockStats=null),n.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...n})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t,r){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:r});let{phase:n,name:a}=t;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:a===void 0?{phase:n}:{phase:n,name:a}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},q;function st(i){return new Promise(e=>setTimeout(e,i))}function ot(i){return i instanceof Error?i.message:String(i)}function we(i,e,t){try{let r=document.createElement("canvas"),n=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*n)),r.height=Math.max(1,Math.round(e.height*n));let a=r.getContext("2d");return a===null?null:(a.drawImage(i,e.x,e.y,e.width,e.height,0,0,r.width,r.height),a.getImageData(0,0,r.width,r.height))}catch{return null}}function lt(i){if(i.enumerateDevices!==void 0)return i.enumerateDevices;if(i.getUserMedia===void 0&&!(typeof navigator>"u"||typeof navigator.mediaDevices?.enumerateDevices!="function"))return()=>navigator.mediaDevices.enumerateDevices()}export{ut as a,U as b,Pe as c,xe as d,ve as e,Ge as f,Le as g,Fe as h,Ve as i,S as j,Ue as k,H as l,be as m,I as n,Ke as o,ft as p,Se as q,P as r,ze as s,k as t,Ze as u,w as v,et as w,B as x,tt as y,W as z,rt as A,nt as B,ke as C};
1
+ import{a as ne,b as ie}from"./chunk-SX7TUC3V.js";import{b as ce,c as ue,d as de}from"./chunk-POIQGEZM.js";import{a as Y,c as j,e as $,g as J,h as A,k as R,m as ee,n as re}from"./chunk-CPUECYAJ.js";import{b as L,c as pe,d as F,e as me}from"./chunk-FPXL63KZ.js";import{a as z,c as X,d as Z,e as Q}from"./chunk-TSA6GHUG.js";import{d as te}from"./chunk-AIRC3HT7.js";import{e as ae,f as se,h as G,j as oe,l as le}from"./chunk-FSSMUAKC.js";var Ie=[...Y.filter(i=>i.startsWith("video/mp4")),"video/webm;codecs=h264","video/webm;codecs=avc1","video/webm;codecs=vp8","video/webm;codecs=vp9","video/webm"],he=new Set;function De(i){let e=/(?:Chrome|Chromium)\/(\d+)\./.exec(i??"");return e?Number(e[1]):null}function fe(i=Oe(),e=globalThis.navigator?.userAgent){if(i===void 0)return"";let t=De(e)===126;for(let r of Ie)if(!(he.has(r)||t&&r.startsWith("video/mp4")))try{if(i(r))return r}catch{}return""}function V(i){i!==""&&he.add(i)}function ge(i){return i.replace(/^video\/x-matroska/i,"video/webm")}function ut(i){let e=/codecs=["']?([^,;"']+)/i.exec(i);return e?e[1].trim():i.split(";")[0].trim()}function Oe(){let i=globalThis.MediaRecorder;return i&&typeof i.isTypeSupported=="function"?e=>i.isTypeSupported(e):void 0}var U=2500,Pe=1e3,xe=1500,ve=25e5,Ge=100,Le=700,Fe=20,Ve=1500,N=null;function Ne(){return N??(N=import("./clip-inspect-DLJXVKV6.js").catch(i=>{throw N=null,i})),N.catch(()=>null)}var S=class extends Error{constructor(e,t){super(t??e),this.kind=e}},Ue=100;function H(i,e){return i.stats===void 0?!1:i.stats===null?!0:i.stats.durationMs<e-Ue}function be(i,e){return i.stats?e.stats?i.stats.durationMs>e.stats.durationMs:!0:!1}var I=class{constructor(e={}){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.pollTimer=null;this.settled=!1;this.now=e.now??(()=>globalThis.performance?.now?.()??Date.now())}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.pollTimer&&clearInterval(this.pollTimer),this.hardStopTimer=null,this.graceTimer=null,this.pollTimer=null}record(e,t,r,n=U,a){let s=fe(),o=Ne();return this.recordRaw(e,t,r,n,a,s).then(c=>He(c,o),c=>{throw c instanceof S&&(c.requestedMimeType=s),c})}recordRaw(e,t,r,n,a,s){return this.recorder&&!this.settled?Promise.reject(new S("generic","record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time")):(this.recorder=null,this.clearTimers(),this.chunks=[],this.bytes=0,this.settled=!1,this.stream=e,new Promise((o,c)=>{let l;try{l=new MediaRecorder(e,s?{mimeType:s,videoBitsPerSecond:ve}:{videoBitsPerSecond:ve})}catch{try{l=new MediaRecorder(e)}catch{c(new S("unsupported"));return}}this.recorder=l;let d=h=>{this.settled||(this.settled=!0,this.clearTimers(),h())},u=()=>d(()=>{let h=ge(l.mimeType||s||j),b=new Blob(this.chunks,{type:h});if(b.size===0){c(new S("generic","empty clip"));return}if(A(b)){c(new S("cliptoolarge"));return}o({blob:b,mimeType:h,requestedMimeType:s})});l.ondataavailable=h=>{h.data&&h.data.size&&(this.chunks.push(h.data),this.bytes+=h.data.size,this.bytes>J&&d(()=>{try{l.state!=="inactive"&&l.stop()}catch{}c(new S("cliptoolarge"))}))},l.onstop=u,l.onerror=()=>d(()=>c(new S("generic")));let f=this.now();if(r!==void 0||a!==void 0){let h=!1;l.onstart=()=>{if(!(h||this.settled)&&(h=!0,f=this.now(),r!==void 0))try{r()}catch{}}}try{l.start(Pe)}catch{d(()=>c(new S("generic")));return}let g=()=>{if(this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=null,this.settled||t?.(),l.state!=="inactive"){try{l.stop()}catch{u()}this.graceTimer=setTimeout(u,xe)}else u()},p=this.now();if(a===void 0){this.hardStopTimer=setTimeout(g,n);return}let m=null,y=!1;this.hardStopTimer=setTimeout(g,n+Le),this.pollTimer=setInterval(()=>{if(this.settled||y)return;let h=null;try{h=a.latest()}catch{h=null}let b=h?.presentationTimeMs;b!==void 0&&Number.isFinite(b)&&b>=f&&m===null&&(m=b);let C=m!==null&&b!==void 0&&b-m>=n,E=m===null&&this.now()-p>=n;if(!(!C&&!E)){if(y=!0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,E){g();return}this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=setTimeout(g,Ge)}},Fe)}))}stop(e){this.clearTimers();let t=this.recorder;if(t&&t.state!=="inactive")try{t.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(n=>n.stop()),this.stream=null}};async function He(i,e){let t,r=new Promise(l=>{t=setTimeout(()=>l(null),Ve)}),n=await Promise.race([e,r]);if(clearTimeout(t),n===null)return i;let a;try{a=await n.blobBytes(i.blob)}catch{return{...i,stats:null}}let s=n.inspectClipBytes(a);if(s?.container!=="webm")return{...i,stats:s};let o=n.withWebmDuration(a,s.durationMs);if(o===null)return{...i,stats:s};let c=n.inspectClipBytes(o);return c===null||c.frames!==s.frames||c.durationMs!==s.durationMs?{...i,stats:s}:{...i,blob:new Blob([o],{type:i.blob.type}),stats:s}}var Ke=["magenta","yellow","green","blue"];var Be={magenta:"rgb(255, 72, 150)",yellow:"rgb(255, 190, 0)",green:"rgb(0, 238, 175)",blue:"rgb(25, 150, 255)",dark:"rgb(0, 0, 0)"};function ft(i){return Be[i]}var We=4,qe=4,D=i=>typeof i=="number"&&Number.isFinite(i);function O(i){if(typeof i!="object"||i===null)return!1;let e=i;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length<1||e.colours.length>8||!e.colours.every(r=>Ke.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==e.colours.length)return!1;let t=-1;for(let r of e.onsetsMs){if(!D(r)||r<0||r<=t)return!1;t=r}return!(!D(e.holdMs)||e.holdMs<=0||!D(e.endMs)||e.endMs<=t||!D(e.clipMs)||e.clipMs<e.endMs||e.clipMs>8e3)}function ye(i,e){return O(i)?Math.max(e,Math.ceil(i.clipMs)):e}function Me(i,e){let t=e.now??(()=>performance.now()),r=O(i)?i:void 0,n=[],a=null,s=null,o=null,c=!1,l=null,d=p=>{l=p;try{e.paint(p)}catch{}},u=p=>{let m=e.frames?.()??null;return m!==null&&o!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-o:p-(s??p)},f=(p,m,y=0)=>{if(c)return;let h=Math.max(0,p-u(t()));a=setTimeout(()=>{if(a=null,!c){if(y<We&&u(t())<p-qe){f(p,m,y+1);return}m()}},h)},g=p=>{if(r===void 0)return;let m=r.endMs;if(p>=r.colours.length){f(m,()=>d(null));return}let y=r.onsetsMs[p],h=p+1<r.onsetsMs.length?r.onsetsMs[p+1]:m;f(y,()=>{let b=u(t());if(b>m){l!==null&&d(null);return}let C=r.colours[p];d(C);let E=n.length===0?0:n[n.length-1].tMs;n.push({tMs:Math.max(E,Math.round(b)),colour:C});let M=y+r.holdMs;if(M<h){f(M,()=>{if(u(t())>m){l!==null&&d(null);return}d("dark"),g(p+1)});return}g(p+1)})};return{started(p){if(r===void 0||c||s!==null)return;s=p;let m=e.frames?.()??null;o=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),g(0)},stop(){c||(c=!0,a!==null&&clearTimeout(a),a=null,l!==null&&d(null))},report(){return r===void 0?void 0:{nonce:r.nonce,rendered:[...n]}}}}function Se(i,e,t=.92){return new Promise((r,n)=>{let a=i.videoWidth,s=i.videoHeight;if(!a||!s){n(new Error("video-not-ready"));return}let o=e.getContext("2d");if(!o){n(new Error("no-2d-context"));return}e.width=a,e.height=s,o.scale(-1,1),o.drawImage(i,-a,0),e.toBlob(c=>c?r(c):n(new Error("empty-keyframe")),"image/jpeg",t)})}var P=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let t=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),t()}))};t();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((t,r)=>t+r,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var ze=Object.freeze({Q_GOOD:.6,RISE_PER_S:.9,FALL_PER_S:.25,CENTER_FALLOFF_IOD_MULTIPLE:1.35,BOX_EYE_OFFSET_FACTOR:.12,IOD_BOX_PROXY_FACTOR:.42,SIZE_IDEAL_MIN:.12,SIZE_IDEAL_MAX:.3,SIZE_HARD_MIN:.08,SIZE_HARD_MAX:.45,ROLL_MAX_DEG:25,MOTION_VELOCITY_IOD_PER_S:.5,MOTION_TAU_S:.4,MOTION_DEADBAND_IOD_PER_S:.1,READY_WINDOW_MS:500,GUIDE_SIZE:.6,GUIDE_CENTERING:.6,GUIDE_POSE:.6,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,GUIDE_MOTION:.5}),_=i=>Math.min(1,Math.max(0,i)),k=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...ze,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:t,quality:r,timestampMs:n}=e,a=this.lastTickAt===null?0:Math.max(0,(n-this.lastTickAt)/1e3);this.lastTickAt=n;let s={presence:0,single:1,centering:0,size:0,pose:0,sharpness:_(r.sharpness),exposure:_(r.exposure),motion:1};if(t!==null){s.presence=1,s.single=(t.extraFaces??0)>0?0:1;let d=this.geometryOf(t,e);s.centering=d.centering,s.size=d.size,s.pose=d.pose,s.motion=this.motionOf(d.center,d.iod,n)}else this.lastCenter=null,this.velocityEma=0;let o=Math.min(s.presence,s.single,s.centering,s.size,s.pose,s.sharpness,s.exposure,s.motion);this.p=_(this.p+(o>=this.t.Q_GOOD?this.t.RISE_PER_S*o:-this.t.FALL_PER_S*(1-o))*a),this.qWindow.push({at:n,q:o}),this.qWindow=this.qWindow.filter(d=>d.at>=n-this.t.READY_WINDOW_MS);let c=this.qWindow.map(d=>d.q);if(c.length>=3){let d=Math.min(...c),u=c.indexOf(d);c=c.filter((f,g)=>g!==u)}let l=this.p>=1&&c.every(d=>d>=this.t.Q_GOOD);return{at:n,q:o,p:this.p,factors:s,guidanceKey:this.guidanceOf(s,r,o),ready:l,accepted:o>=this.t.Q_GOOD}}geometryOf(e,t){let{box:r,eyes:n}=e,a={x:t.frameWidth/2,y:t.frameHeight/2},s=Math.min(t.frameWidth,t.frameHeight),o=n!==void 0?{x:(n.left.x+n.right.x)/2,y:(n.left.y+n.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},c=n!==void 0?Math.hypot(n.right.x-n.left.x,n.right.y-n.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,l=Math.hypot(o.x-a.x,o.y-a.y),d=c<=0?0:1-_(l/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*c)),u=s>0?c/s:0;this.lastSizeDirection=u<this.t.SIZE_IDEAL_MIN?"far":u>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;u<this.t.SIZE_HARD_MIN||u>this.t.SIZE_HARD_MAX?f=0:u<this.t.SIZE_IDEAL_MIN?f=(u-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):u>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-u)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let g=1;if(n!==void 0){let p=Math.abs(Math.atan2(n.right.y-n.left.y,n.right.x-n.left.x))*180/Math.PI;g=1-_(p/this.t.ROLL_MAX_DEG)}return{center:o,iod:c,centering:d,size:f,pose:g}}motionOf(e,t,r){let n=this.lastCenter;if(this.lastCenter={...e,at:r},n===null||t<=0)return 1;let a=(r-n.at)/1e3;if(a<=0)return 1;let s=Math.hypot(e.x-n.x,e.y-n.y)/t/a;s<=this.t.MOTION_DEADBAND_IOD_PER_S&&(s=0);let o=1-Math.exp(-a/this.t.MOTION_TAU_S);return this.velocityEma=o*s+(1-o)*this.velocityEma,1-_(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,r){if(e.presence<=0)return"fcv3.no_face";if(e.single<=0)return"fcv3.one_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(t);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(r<this.t.Q_GOOD){let n=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],a=n[0];for(let s of n)e[s[0]]<e[a[0]]&&(a=s);return a[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(L[0]+L[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Xe=["single","size","centering","pose","exposure","sharpness","motion"];function Ze(i){if(i.accepted)return null;if(i.factors.presence<=0)return"no_face";let e="single";for(let t of Xe)i.factors[t]<i.factors[e]&&(e=t);return e}var w=class{constructor(){this.blocked={};this.acceptedMs=0;this.ticks=0;this.lastAt=null}record(e){let t=this.lastAt===null?0:Math.max(0,e.at-this.lastAt);this.lastAt=e.at,this.ticks+=1;let r=Ze(e);if(r===null){this.acceptedMs+=t;return}let n=this.blocked[r]??{count:0,ms:0};n.count+=1,n.ms+=t,this.blocked[r]=n}summary(){let e={};for(let[t,r]of Object.entries(this.blocked))e[t]={count:r.count,ms:Math.round(r.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var Qe=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ye=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^caméra (avant|arrière)\b/i,/^cámara (frontal|trasera|delantera)\b/i,/^câmera (frontal|traseira)\b/i,/^(front|rück)kamera\b/i,/^الكاميرا (الأمامية|الخلفية)/,/^camera2? ?\d+, facing (front|back|external)/i,/facetime/i,/\b(integrated|built-in|builtin) (web)?cam(era)?\b/i,/\b(hd )?web ?cam\b/i,/\([0-9a-f]{4}:[0-9a-f]{4}\)\s*$/i];function je(i){let e=(i??"").trim().toLowerCase();return e.length===0?"unknown":Qe.some(t=>e.includes(t))?"known_virtual":Ye.some(t=>t.test(e))?"platform":"unknown"}function Te(i){if(typeof i!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(i))}catch{return!1}}function $e(i=globalThis){return Te(i.navigator?.mediaDevices?.getUserMedia)&&Te(i.MediaStreamTrack?.prototype?.getSettings)}async function Je(i,e=globalThis){let t=e.crypto?.subtle?.digest;if(typeof t=="function")try{let r=new Uint8Array(await t.call(e.crypto?.subtle,"SHA-256",new TextEncoder().encode(i)));return Array.from(r.subarray(0,8),n=>n.toString(16).padStart(2,"0")).join("")}catch{return}}async function Ce(i,e=globalThis){let t={};try{t=typeof i.getSettings=="function"?i.getSettings()??{}:{}}catch{t={}}let r={};if((t.facingMode==="user"||t.facingMode==="environment"||t.facingMode==="left"||t.facingMode==="right")&&(r.facingMode=t.facingMode),typeof t.frameRate=="number"&&Number.isFinite(t.frameRate)&&(r.frameRate=t.frameRate),typeof t.width=="number"&&Number.isFinite(t.width)&&(r.width=t.width),typeof t.height=="number"&&Number.isFinite(t.height)&&(r.height=t.height),typeof t.deviceId=="string"&&t.deviceId.length>0){let a=await Je(t.deviceId,e);a!==void 0&&(r.deviceIdHash=a)}let n;try{n=i.label}catch{n=void 0}return{trackSettings:r,capabilitiesPresent:typeof i.getCapabilities=="function",labelClass:je(n),prototypesIntact:$e(e)}}var K=i=>Math.round(i*100)/100;function Ee(i){let e=i,t=typeof e?.requestVideoFrameCallback=="function",r=null,n=null,a=0,s=0,o=0,c=0,l=0,d=0,u=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((f,g)=>{if(r=null,!t)return;let p=g.presentationTime;if(n!==null){let m=p-n.presentationTimeMs;s+=1;let y=m-o;o+=y/s,c+=y*(m-o)}typeof g.captureTime=="number"&&Number.isFinite(g.captureTime)&&(l+=p-g.captureTime,d+=1),a+=1,n={mediaTimeMs:g.mediaTime*1e3,presentationTimeMs:p},u()}))};return u(),{latest:()=>n,stats:()=>({n:a,meanGapMs:s===0?0:K(o),stdGapMs:s<2?0:K(Math.sqrt(c/(s-1))),captureLatencyMs:d===0?null:K(l/d)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function _e(i,e,t){return{...i,rvfc:e,rampPainter:t}}var et=1e3,B="fcv3.hold_upright",tt=200,W=4,rt=600,nt=1e3,Re={sharpness:1,exposure:1,meanLuma:128};function it(i,e){return e.width=i.videoWidth,e.height=i.videoHeight,e.getContext("2d").drawImage(i,0,0),new Promise((t,r)=>e.toBlob(n=>n?t(n):r(new Error("empty-keyframe")),"image/jpeg",.92))}function at(){return X()==="phone"}var ke=class{constructor(e){this.handlers=new Map;this.stateValue="idle";this.attempt=0;this.stream=null;this.detector=null;this.scheduler=null;this.gate=null;this.profiler=null;this.lastGuidanceKey=null;this.positioningStartedAt=0;this.cameraRequestedAt=null;this.cameraReadyAt=null;this.faceAcquiredAt=null;this.captureCompleteAt=null;this.fired=!1;this.carriedDegrade=0;this.carriedMeans=[];this.blockStats=null;this.lastGateSnapshotAt=Number.NEGATIVE_INFINITY;this.uprightGuard=!1;this.trackProvenance=null;this.ramp=null;this.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>r?.delete(t)}emit(e,t){for(let r of[...this.handlers.get(e)??[]])r(t)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}restart(e){this.facing=e,this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:t}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.uprightGuard=(t.isPhone??at)(),this.setState("preflight");let r=$();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let n=t.getUserMedia??(l=>navigator.mediaDevices.getUserMedia(l)),a;this.cameraRequestedAt=this.now();try{let{facingMode:l,...d}=z(Z(),this.facing).video;a=await ie(this.facing,d,{getUserMedia:n,enumerateDevices:lt(t)})}catch(l){if(e!==this.attempt)return;if(l instanceof ne){this.fail("backcamera",{phase:"acquiring",name:R(l)});return}this.fail(ee(l),{phase:"acquiring",name:R(l)});return}if(te(a),re(a),e!==this.attempt){for(let l of a.getTracks())l.stop();return}this.stream=a;let s=a.getVideoTracks?.()[0];if(this.trackProvenance=s===void 0?null:Ce(s).catch(()=>null),this.facing=Q(a)??this.facing,t.video.srcObject=a,await t.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let l={v3AssetBaseUrl:t.v3AssetBaseUrl},d=t.createDetector??(t.createWorker!==void 0&&oe()?async()=>{try{return await le.create(t.createWorker(),l)}catch{return G(l)}}:()=>G(l)),u;try{u=await d()}catch(f){e===this.attempt&&this.fail("models",{phase:"models",name:R(f)},f instanceof ae?f.fallbackReason:ot(f));return}if(e!==this.attempt){u.destroy();return}this.detector=u,this.options.telemetry?.({type:"detector",tier:u.tier,fallbackReason:u.fallbackReason})}let o=ce(),c=t.deviceClass??ue(o);this.profiler=new de(c),this.options.telemetry?.({type:"profile",staticClass:c,activeClass:this.profiler.deviceClass,simd:o.simd}),this.gate=new k(t.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(l=>q=l,()=>{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let t=this.profiler;if(t===null)return;if(this.scheduler!==null){let n=this.scheduler.stats();this.carriedDegrade+=n.degradeCount,n.meanDetectMs>0&&this.carriedMeans.push(n.meanDetectMs),this.scheduler.stop()}let r=new P({cadenceHz:t.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=r,r.start()}async detectTick(e){let{detector:t,gate:r,profiler:n}=this,a=this.options.video;if(e!==this.attempt||t===null||r===null||n===null||this.fired||a.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let s=n.deviceClass,o=this.now(),c=this.options.makeSnapshot?.(a,n.profile.inputWidth)??this.defaultSnapshot(a,n.profile.inputWidth),l=null;try{l=await t.detect(c,a.videoWidth,a.videoHeight)}catch{l=null}if(e!==this.attempt||this.fired)return;n.record(this.now()-o),n.deviceClass!==s&&this.startScheduler(e);let d=l===null?Re:this.options.measureQuality?.(a,l.box)??this.defaultQuality(a,l.box),u=r.tick({timestampMs:this.now(),observation:l,quality:d,frameWidth:a.videoWidth,frameHeight:a.videoHeight});u.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=u.at),this.blockStats?.record(u),!u.ready&&u.at-this.lastGateSnapshotAt>=et&&(this.lastGateSnapshotAt=u.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:u.p,q:u.q,factors:u.factors,attempt:e}),u.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=u.guidanceKey,this.emit("guidance",{key:u.guidanceKey})),u.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=u.at,this.fire(e))}async fire(e){let{options:t}=this,r=this.scheduler;r?.stop(),this.reportGate(!0);let n=r?.stats()??{degradeCount:0,meanDetectMs:0},a=[...this.carriedMeans,...n.meanDetectMs>0?[n.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+n.degradeCount,meanDetectMs:a.length===0?0:a.reduce((M,v)=>M+v,0)/a.length});let s=t.mode??"clip",o=t.rankKeyframes?.()&&q?q.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(s==="photo"){let M=this.watchRotation(e,null),v=await o;if(M(),e!==this.attempt)return;if(v===null){this.fail("generic",{phase:"keyframes"});return}let x=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:v.blob,previewDataUrl:v.previewDataUrl,...x});return}this.setState("recording");let c=this.stream;if(c===null){this.fail("generic",{phase:"recording"});return}let l=t.screenRamp?.(),d=O(l),u=null;o.then(M=>{u=M},()=>{});let f=()=>{e===this.attempt&&u!==null&&this.emit("frozen",{previewDataUrl:u.previewDataUrl})},g=ye(l,U),p=null,m,y=0;try{let M=this.recordTake(e,c,l,g,void 0).then(T=>T,T=>({failed:T})),[v,x]=await Promise.all([M,o]);if(m=x,e!==this.attempt)return;if("failed"in v){if(v.failed.kind==="cliptoolarge")throw v.failed;V(v.failed.requestedMimeType??"")}else p=v,H(v.clip,g)?v.clip.stats===null&&V(v.clip.requestedMimeType??""):f();if(p===null||H(p.clip,g)){y=1,t.telemetry?.({type:"clip_retake",reason:p===null?"error":p.clip.stats===null?"unreadable":"short"});let T=null;try{T=await this.recordTake(e,c,l,g,f)}catch(Ae){if(p===null)throw Ae}if(e!==this.attempt)return;T!==null&&(p===null||be(T.clip,p.clip))&&(p=T),T===null&&f()}}catch(M){if(e!==this.attempt)return;let v=M.kind;this.fail(v==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:R(M)});return}if(p===null){this.fail("recorder",{phase:"recording"});return}let{clip:h,rvfc:b,report:C}=p;if(A(h.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(m===null){this.fail("generic",{phase:"keyframes"});return}let E=await this.provenance(b,d);e===this.attempt&&this.finishCapture({clip:h.blob,clipMimeType:h.mimeType,...h.stats?{clipStats:h.stats}:{},clipRetakes:y,keyframe:m.blob,previewDataUrl:m.previewDataUrl,...C!==void 0&&C.rendered.length>0?{screenRamp:C}:{},...E})}async recordTake(e,t,r,n,a){let s=this.options.createRecorder?.()??new I({now:()=>this.now()}),o=Ee(this.options.video),c=Me(r,{paint:u=>{(u===null||e===this.attempt)&&this.emit("ramp",{colour:u})},now:()=>this.now(),frames:o.latest});this.ramp=c;let l=()=>{o.stop(),c.stop(),this.ramp===c&&(this.ramp=null)},d=this.watchRotation(e,s);try{return{clip:await s.record(t,a,()=>c.started(this.now()),n,o),rvfc:o.stats(),report:c.report()}}finally{d(),l()}}async provenance(e,t){let r=this.trackProvenance;if(r===null)return{};let n,a=new Promise(o=>{n=setTimeout(()=>o(null),nt)}),s=await Promise.race([r,a]);return clearTimeout(n),s===null?{}:{provenance:_e(s,e,t)}}isLandscape(){let e=this.options.video;return this.uprightGuard&&e.videoWidth>e.videoHeight}holdUpright(e){this.gate?.reset(),this.emit("checks",{engine:"v3",progress:0,q:0,factors:{presence:0,single:1,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==B&&(this.lastGuidanceKey=B,this.emit("guidance",{key:B}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,n=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){o();return}r.videoWidth>0&&this.isLandscape()&&(o(),this.abortRecording(e,t))},a=setInterval(n,tt);r.addEventListener?.("resize",n);let s=!1;function o(){s||(s=!0,clearInterval(a),r.removeEventListener?.("resize",n))}return o}abortRecording(e,t){if(e!==this.attempt)return;this.attempt+=1;let r=this.attempt;try{t?.stop()}catch{}this.ramp?.stop(),this.ramp=null,this.fired=!1,this.captureCompleteAt=null,this.gate=new k(this.options.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),this.lastGuidanceKey=null,this.setState("positioning"),this.positioningStartedAt=this.now(),this.holdUpright(r),this.startScheduler(r)}async collectKeyframes(e){let t=this.options.captureKeyframe??(a=>this.defaultKeyframe(a)),r=rt/(W-1),n=null;for(let a=0;a<W;a+=1){if(e!==this.attempt)return n;try{let s=await t(this.options.video);(n===null||s.sharpness>n.sharpness)&&(n=s)}catch{}a<W-1&&await st(r)}return n}finishCapture(e){this.stopTracks(),this.setState("captured");let t=this.captureTiming();this.emit("artifacts",t===void 0?e:{...e,timing:t})}captureTiming(){let e={},t=(r,n,a)=>{n!==null&&a!==null&&(e[r]=Math.max(0,Math.round(a-n)))};return t("cameraReadyMs",this.cameraRequestedAt,this.cameraReadyAt),t("faceAcquireMs",this.cameraReadyAt,this.faceAcquiredAt),t("captureMs",this.faceAcquiredAt,this.captureCompleteAt),Object.keys(e).length>0?e:void 0}async defaultKeyframe(e){let t=document.createElement("canvas"),r=await(this.facing==="user"?Se:it)(e,t),n=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:n,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),n=t/Math.max(1,e.videoWidth),a=Math.max(1,Math.round(e.videoWidth*n)),s=Math.max(1,Math.round(e.videoHeight*n)),o=r.getContext("2d");return o===null?e:(r.width!==a&&(r.width=a),r.height!==s&&(r.height=s),o.drawImage(e,0,0,a,s),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,t){let r=we(e,t,96);return r===null?Re:{sharpness:F(r),exposure:me(r),meanLuma:pe(r)}}centerSharpness(e){let t=se(e),r=we(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:F(r)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.ramp?.stop(),this.ramp=null,this.stopTracks()}reportGate(e){let t=this.blockStats,r=this.profiler;if(t===null||r===null)return;let n=t.summary();e&&(this.blockStats=null),n.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...n})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t,r){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:r});let{phase:n,name:a}=t;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:a===void 0?{phase:n}:{phase:n,name:a}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},q;function st(i){return new Promise(e=>setTimeout(e,i))}function ot(i){return i instanceof Error?i.message:String(i)}function we(i,e,t){try{let r=document.createElement("canvas"),n=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*n)),r.height=Math.max(1,Math.round(e.height*n));let a=r.getContext("2d");return a===null?null:(a.drawImage(i,e.x,e.y,e.width,e.height,0,0,r.width,r.height),a.getImageData(0,0,r.width,r.height))}catch{return null}}function lt(i){if(i.enumerateDevices!==void 0)return i.enumerateDevices;if(i.getUserMedia===void 0&&!(typeof navigator>"u"||typeof navigator.mediaDevices?.enumerateDevices!="function"))return()=>navigator.mediaDevices.enumerateDevices()}export{ut as a,U as b,Pe as c,xe as d,ve as e,Ge as f,Le as g,Fe as h,Ve as i,S as j,Ue as k,H as l,be as m,I as n,Ke as o,ft as p,Se as q,P as r,ze as s,k as t,Ze as u,w as v,et as w,B as x,tt as y,W as z,rt as A,nt as B,ke as C};
@@ -1 +1 @@
1
- var m="0.1.0-rc.35";var T=/FBAN|FBAV|FB_IAB|FBIOS|MessengerForiOS|Instagram|WhatsApp|musical_ly|BytedanceWebview|TikTok|Snapchat|\bLine\/|LinkedInApp|Pinterest|MicroMessenger|; wv\)/i;function p(t){let e=t??(typeof navigator>"u"?"":String(navigator.userAgent??""));return T.test(e)}var h="sekyro.did",P=1e4,v=()=>globalThis.process?.versions?.node,y;function b(){let t=globalThis.crypto;try{if(typeof t?.randomUUID=="function")return t.randomUUID()}catch{}try{if(typeof t?.getRandomValues=="function"){let e=t.getRandomValues(new Uint8Array(16));return Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}}catch{}}function I(){try{let t=localStorage.getItem(h);if(t)return t;let e=b();return e!==void 0&&localStorage.setItem(h,e),e}catch{return y??(y=b()),y}}async function w(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,r=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),i=await t.digest("SHA-256",new TextEncoder().encode(r));return Array.from(new Uint8Array(i),o=>o.toString(16).padStart(2,"0")).join("").slice(0,32)}function k(){try{let t=Number(navigator.maxTouchPoints);return Number.isFinite(t)&&t>=0?{touch:Math.min(64,Math.trunc(t))}:{}}catch{return{}}}function x(t){let e=new TextEncoder().encode(t),r="";for(let i of e)r+=String.fromCharCode(i);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function A(t){let e,r,i,o,a,l,u=()=>l?.readyState==="live",_=()=>{a!==void 0||!globalThis.crypto?.subtle||v()||u()||(a=Promise.race([import("./print-SEWS3VHQ.js"),new Promise(n=>setTimeout(n,P))]).then(n=>n?.computePrint(u)).then(n=>{n==="busy"?a=void 0:o=n}).catch(()=>{}))};return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(n){n&&(e=n.slice(0,128))},noteCamera(n){r=n},noteCameraTrack(n){l=n},async deviceHeader(){try{i??(i=w().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let f=await i,g=I(),S={v:1,platform:"web",sdk:t.sdk.slice(0,64),caps:["session_proof"],ids:[...g?[{kind:"web_local",value:g.slice(0,128)}]:[],...f?[{kind:"web_fp",value:f}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...k(),...e?{cameraLabel:e}:{},...n.length?{signals:n}:{},...o?{print:{v:2,...o,...r?{camera:r}:{}}}:{},...p()?{inApp:!0}:{}},C=x(JSON.stringify(S));return _(),C}catch{return}},printReady(){return a??Promise.resolve()}}}var s=Symbol.for("sekyro.web.clientContext"),c=globalThis,d=c[s]??(c[s]=A({sdk:`@sekyro/web@${m}`}));function M(t){try{let e=t.getVideoTracks?.()[0];if(e){if(d.noteCameraLabel(e.label),d.noteCameraTrack(e),v())return;import("./camera-trait-V4UAOPIQ.js").then(r=>r.noteCameraTrait(e,d)).catch(()=>{})}}catch{}}export{m as a,p as b,d as c,M as d};
1
+ var m="0.1.0-rc.36";var T=/FBAN|FBAV|FB_IAB|FBIOS|MessengerForiOS|Instagram|WhatsApp|musical_ly|BytedanceWebview|TikTok|Snapchat|\bLine\/|LinkedInApp|Pinterest|MicroMessenger|; wv\)/i;function p(t){let e=t??(typeof navigator>"u"?"":String(navigator.userAgent??""));return T.test(e)}var h="sekyro.did",P=1e4,v=()=>globalThis.process?.versions?.node,y;function b(){let t=globalThis.crypto;try{if(typeof t?.randomUUID=="function")return t.randomUUID()}catch{}try{if(typeof t?.getRandomValues=="function"){let e=t.getRandomValues(new Uint8Array(16));return Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}}catch{}}function I(){try{let t=localStorage.getItem(h);if(t)return t;let e=b();return e!==void 0&&localStorage.setItem(h,e),e}catch{return y??(y=b()),y}}async function w(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,r=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),i=await t.digest("SHA-256",new TextEncoder().encode(r));return Array.from(new Uint8Array(i),o=>o.toString(16).padStart(2,"0")).join("").slice(0,32)}function k(){try{let t=Number(navigator.maxTouchPoints);return Number.isFinite(t)&&t>=0?{touch:Math.min(64,Math.trunc(t))}:{}}catch{return{}}}function x(t){let e=new TextEncoder().encode(t),r="";for(let i of e)r+=String.fromCharCode(i);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function A(t){let e,r,i,o,a,l,u=()=>l?.readyState==="live",_=()=>{a!==void 0||!globalThis.crypto?.subtle||v()||u()||(a=Promise.race([import("./print-SEWS3VHQ.js"),new Promise(n=>setTimeout(n,P))]).then(n=>n?.computePrint(u)).then(n=>{n==="busy"?a=void 0:o=n}).catch(()=>{}))};return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(n){n&&(e=n.slice(0,128))},noteCamera(n){r=n},noteCameraTrack(n){l=n},async deviceHeader(){try{i??(i=w().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let f=await i,g=I(),S={v:1,platform:"web",sdk:t.sdk.slice(0,64),caps:["session_proof"],ids:[...g?[{kind:"web_local",value:g.slice(0,128)}]:[],...f?[{kind:"web_fp",value:f}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...k(),...e?{cameraLabel:e}:{},...n.length?{signals:n}:{},...o?{print:{v:2,...o,...r?{camera:r}:{}}}:{},...p()?{inApp:!0}:{}},C=x(JSON.stringify(S));return _(),C}catch{return}},printReady(){return a??Promise.resolve()}}}var s=Symbol.for("sekyro.web.clientContext"),c=globalThis,d=c[s]??(c[s]=A({sdk:`@sekyro/web@${m}`}));function M(t){try{let e=t.getVideoTracks?.()[0];if(e){if(d.noteCameraLabel(e.label),d.noteCameraTrack(e),v())return;import("./camera-trait-V4UAOPIQ.js").then(r=>r.noteCameraTrait(e,d)).catch(()=>{})}}catch{}}export{m as a,p as b,d as c,M as d};
@@ -1 +1 @@
1
- import{d as re,h as ve,i as Le,j as Te,l as _e}from"./chunk-JULJQOVT.js";import{a as ne,e as Ce,g as xe}from"./chunk-XFATG7QI.js";import{m as j}from"./chunk-JQIDW5SX.js";import{a as we,g as ke}from"./chunk-7QZWBDI5.js";import{k as te}from"./chunk-CPUECYAJ.js";import{d as Re,f as Pe}from"./chunk-ISMVEF7H.js";function Ee(e,t){let n=new Set(e.flatMap(r=>r.sides.filter(i=>i[t]!==null).map(i=>i.side)));return n.size===1?[...n][0]:null}function st(e){let t=Ce.find(r=>r.docType===e),n=t.mrz==="none"?null:t.mrz==="td3"?"single":"verso";return{sides:t.sides,format:xe(e),mrz:t.mrz==="none"?"none":"required",mrzSide:n,barcodeSide:null,portraitSide:t.portraitSide,scripts:null}}function ct(e){let t=[];for(let n of e)for(let r of n.sides){if(!Array.isArray(r.scripts))return null;for(let i of r.scripts)t.includes(i)||t.push(i)}return t}function Oe(e,t){if(t.length===0)return st(e);let n=t.some(s=>s.sides.length>1),r=new Set(t.map(s=>s.format)),i=r.size===1?[...r][0]:"card",u=t.filter(s=>s.sides.some(p=>p.mrz!==null)).length,c=t.find(s=>s.sides.length>1===n)?.sides.find(s=>s.portrait)?.side;return{sides:n?["recto","verso"]:["single"],format:i,mrz:u===t.length?"required":u===0?"none":"optional",mrzSide:Ee(t,"mrz"),barcodeSide:Ee(t,"barcode"),portraitSide:c??(n?"recto":"single"),scripts:ct(t)}}function Ae(e,t){if(e===void 0)return[];let n=e.toUpperCase();return Object.prototype.hasOwnProperty.call(ne,n)?ne[n]?.[t]??[]:[]}async function Be(e,t,n){return await e(t)?n:n==="recto"?"verso":"recto"}function Ie(e,t,n){return e!==t&&t==="verso"&&n.recto!==void 0&&n.verso===void 0?"verso":e}var ut={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 lt(e){let{deviceMemory:t,effectiveType:n,saveData:r,downlinkMbps:i,sourceLongEdge:u}=e,c=r===!0||n==="slow-2g"||n==="2g"||i!=null&&i>0&&i<1,s=t!=null&&t<=2,p=n==="4g"||i!=null&&i>=5,l=t!=null&&t>=6,M;c||s?M="low":p&&l?M="good":M="mid";let f=ut[M],T=u&&u>0?Math.min(f.maxLongEdge,u):f.maxLongEdge;return{tier:M,...f,maxLongEdge:T}}function Fe(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),lt(t)}function dt(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 mt(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 pt(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 We(e,t,n,r,i){if(t<=0||n<=0)return null;let{width:u,height:c}=mt(t,n,r.maxLongEdge),s=document.createElement("canvas");s.width=u,s.height=c;let p=s.getContext("2d");if(!p)return null;p.drawImage(e,0,0,u,c);let l=C=>new Promise((S,P)=>{s.toBlob(d=>d?S(d):P(new Error("canvas toBlob returned null")),"image/jpeg",C)}),M=dt(i,r.qMin,r.qMax),{blob:f,quality:T}=await pt(l,{startQ:M,qMin:r.qMin,budgetBytes:r.payloadTargetBytes}).finally(()=>{s.width=0,s.height=0});if(f.size>5242880)throw new Error("encoded document exceeds the 5242880-byte media cap");return{blob:f,quality:T,width:u,height:c}}async function oe(e){let t=Fe(Math.max(e.width,e.height)),n=await We(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 Ft(e){let t=await createImageBitmap(e);try{return await oe(t)}finally{t.close()}}var zt=250,Ut=.6,Nt=1800,Gt=6e3,qt=2e3,ze=.16;function ie(e,t){return{layout:e,phase:"framing",captured:{},pending:[],lastCaptureAt:t,lastReportAt:t,manualShutter:!1,restPhase:"framing",readSides:[],needFlip:!1,flipped:!1,flipTimeoutSpent:!1,timeoutCapture:!1,lastShotByTimeout:!1}}var Ue=e=>e==="recto"?"verso":"recto",Ne=e=>e.phase==="framing"||e.phase==="locking"||e.phase==="flipCue"||e.phase==="reaskRecto",se=e=>(e.captured.recto!==void 0?1:0)+(e.captured.verso!==void 0?1:0)+e.pending.length;function ae(e,t){return e.lastCaptureAt>=0&&e.lastReportAt>=0?e:{...e,lastCaptureAt:e.lastCaptureAt<0?t:e.lastCaptureAt,lastReportAt:e.lastReportAt<0?t:e.lastReportAt}}function ft(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:u}=e;r&&(u=u??n),u!==void 0&&n-u>=250&&(i=!0),r||(u=void 0);let c=e.flipTimeoutSpent&&!(i&&!e.flipped),s={...e,lastReportAt:n,flipped:i,awaySince:u,flipTimeoutSpent:c,lastArea:t.areaFrac};if(!Ne(e))return s;if(e.needFlip&&!i){if(!t.ready)return{...s,phase:e.restPhase,goodSince:void 0};let p=e.lastShot!==void 0&&e.pending.includes(e.lastShot);if(c||p)return{...s,goodSince:void 0,phase:e.restPhase};let l=e.goodSince??n;return n-l>=1800?{...s,goodSince:l,phase:"capturing",flipTimeoutSpent:!0,timeoutCapture:!0}:{...s,goodSince:l,phase:e.restPhase}}return t.ready?{...s,phase:"capturing",goodSince:e.goodSince??n}:{...s,goodSince:void 0,phase:t.locking?"locking":e.restPhase}}function gt(e,t){if(!Ne(e)||e.manualShutter)return e;let n=t-e.lastReportAt>=2e3,r=t-e.lastCaptureAt>=6e3;return n||r?{...e,manualShutter:!0}:e}function ht(e,t,n){let r=e.layout==="singlePage",i=r?{recto:t}:e.captured,u=r?[]:[...e.pending,t],c={...e,captured:i,pending:u,lastShot:t,lastCaptureAt:n,lastReportAt:-1,manualShutter:!1,goodSince:void 0,notice:void 0,awaySince:void 0,flipped:!1,lastShotByTimeout:e.timeoutCapture,timeoutCapture:!1,captureArea:e.lastArea};return r||se({captured:i,pending:u})>=2?{...c,phase:"reading",restPhase:"framing",current:void 0,needFlip:!1}:{...c,phase:"flipCue",restPhase:"flipCue",current:void 0,needFlip:!0}}function Ge(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:Ue(n),needFlip:!0,flipTimeoutSpent:!0,goodSince:void 0,manualShutter:!0,notice:"same_face",lastCaptureAt:-1,lastReportAt:-1}:e}function bt(e,t,n){if(!e.pending.includes(t))return e;if(e.captured[n]!==void 0)return Ge(e,t,n);let r=e.pending.filter(p=>p!==t),i={...e,pending:r,captured:{...e.captured,[n]:t}};if(se(i)!==1||e.layout==="singlePage")return i;let u=Ue(n),c=u==="recto"&&e.restPhase==="reaskRecto"?"reaskRecto":"flipCue",s=e.phase==="flipCue"||e.phase==="reaskRecto"||e.phase==="framing";return{...i,restPhase:c,current:u,phase:s?c:e.phase}}function yt(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(l=>l!==n),u=e.layout==="twoSided"&&se({captured:r,pending:i})>0,c=e.lastShotByTimeout||n===e.lastShot!==e.flipped,s=u&&!c,p=s?t.side==="recto"?"reaskRecto":"flipCue":"framing";return{...e,captured:r,pending:i,readSides:e.readSides.filter(l=>l!==t.side),lastShot:e.lastShot===n?void 0:e.lastShot,notice:t.issue,goodSince:void 0,manualShutter:!1,phase:p,restPhase:p,current:t.side,needFlip:s,flipped:!1,flipTimeoutSpent:!1,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1}}function qe(e,t){switch(t.type){case"report":return ft(ae(e,t.at),t.report,t.at);case"tick":return gt(ae(e,t.at),t.at);case"captured":return ht(ae(e,t.at),t.id,t.at);case"captureFailed":return{...e,phase:e.restPhase,goodSince:void 0,lastCaptureAt:t.at,manualShutter:!0,timeoutCapture:!1};case"classified":return bt(e,t.id,t.side);case"duplicate":return Ge(e,t.id,t.side);case"readOk":{let n=e.readSides.includes(t.side)?e.readSides:[...e.readSides,t.side],r=["recto","verso"].filter(u=>e.captured[u]!==void 0),i=e.phase==="reading"&&e.pending.length===0&&r.every(u=>n.includes(u));return{...e,readSides:n,flipTimeoutSpent:!1,phase:i?"result":e.phase}}case"readFailed":return yt(e,t);case"clockRestart":return e.lastCaptureAt<0&&e.lastReportAt<0&&e.awaySince===void 0?e:{...e,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1};case"retake":return{...ie(e.layout,-1),lastCaptureAt:-1,lastReportAt:-1};default:return e}}function St(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 Mt(e,t=!1){let{detectMrzBand:n}=await import("./mrz-band-VYHOTDHY.js");return St(n,e,t)}async function ce(e,t=480,n,r=n!=null){let i=n??{x:0,y:0,width:e.width,height:e.height},u=Math.max(1,Math.round(i.height/i.width*t)),c=document.createElement("canvas");c.width=t,c.height=u;try{let s=c.getContext("2d");return s===null?"recto":(s.drawImage(e,i.x,i.y,i.width,i.height,0,0,t,u),await Mt(s.getImageData(0,0,t,u),r))}finally{c.width=0,c.height=0}}async function Xt(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 u=i.getContext("2d");return u===null?(n.close(),null):(u.drawImage(n,0,0,t,r),n.close(),u.getImageData(0,0,t,r))}catch{return null}}var ue=(e,t,n)=>Math.min(n,Math.max(t,Math.round(e))),$=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function He(e,t,n,r){let i=r.decode??(p=>createImageBitmap(p)),u=async()=>e.stillRead(await i(t),r.region??[0,0,1,1],r.detectorLimit),c;try{c=await u()}catch{try{await new Promise(p=>setTimeout(p,r.retryMs??300)),c=await u()}catch{return null}}let s=c.mrzBox;return s===void 0?null:{engine:r.engine,source:"live_mrz",format:n.format,lineCount:ue(n.lineCount,2,3),checkDigitsValid:!0,stillConfirmed:c.valid&&c.digest===n.digest,band:[$(s[0]),$(s[1]),$(Math.min(s[2],1-s[0])),$(Math.min(s[3],1-s[1]))],digest:n.digest,framesToValid:ue(n.framesToValid,1,1e3),msToValid:ue(n.msToValid,0,12e4)}}function Vt(e){let t=null;return e?.then(n=>{t=n}),()=>t}var Dt=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]),wt=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 Xe(e=globalThis){let t=e.WebAssembly?.validate;if(typeof t!="function")return{ok:!1,reason:"simd"};try{if(!t.call(e.WebAssembly,Dt)||!t.call(e.WebAssembly,wt))return{ok:!1,reason:"simd"}}catch{return{ok:!1,reason:"simd"}}return typeof e.Worker!="function"?{ok:!1,reason:"worker"}:typeof e.createImageBitmap!="function"?{ok:!1,reason:"bitmap"}:{ok:!0}}function Ye(e=globalThis){let t=e.navigator?.connection;return t?.saveData===!0||["slow-2g","2g","3g"].includes(t?.effectiveType??"")}var E=class extends Error{constructor(t){super(t),this.name="OcrEngineError",this.code=t}};function Ve(){let e=t=>(t.close(),Promise.reject(new E("unsupported")));return{ready:Promise.resolve("unsupported"),busy:!1,bandRead:e,stillRead:e,layoutRead:e,dispose:()=>{}}}function Qe(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 Ve()}catch{return Ve()}let n=new Map,r=0,i=!1,u=!1,c=!1;t.addEventListener("message",d=>{let g=d.data,D=n.get(g.id);D&&(n.delete(g.id),D.resolve(g))});let s=()=>{for(let d of n.values())d.reject(new E("error"));n.clear(),l()};t.addEventListener("error",s),t.addEventListener("messageerror",s);function p(d,g=[]){if(i)return Promise.reject(new E("disposed"));let D=++r;return new Promise((A,B)=>{n.set(D,{resolve:A,reject:B});try{t.postMessage({...d,id:D},g)}catch{n.delete(D),B(new E("error"))}})}function l(){if(!i){i=!0;try{t.postMessage({id:++r,kind:"dispose"})}catch{}t.terminate();for(let d of n.values())d.reject(new E("disposed"));n.clear()}}let M=(async()=>{let d=await p({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 p({kind:"warmup"});if(g.kind!=="ready")return"error";let D=g.benchMs??g.warmupMs,A=e.deviceMemoryGb===void 0?Pe():e.deviceMemoryGb;return{warmupMs:g.warmupMs,downloadMs:d.downloadMs,cached:d.cached,benchMs:D,tier:Re(D,A)}})().catch(()=>"error"),f,T=new Promise(d=>{f=setTimeout(()=>d("timeout"),e.tuning.loadTimeoutMs)}),C=Promise.race([M,T]).then(d=>(clearTimeout(f),typeof d=="string"?l():c=!0,i&&typeof d!="string"?"error":d));(e.page===void 0?globalThis.addEventListener?globalThis:null:e.page)?.addEventListener("pagehide",l,{once:!0});async function P(d,g,D){if(i)throw g.close(),new E("disposed");if(!c)throw g.close(),new E("not_ready");if(u)throw g.close(),new E("busy");u=!0;let A;try{let B=new Promise((X,z)=>{A=setTimeout(()=>{z(new E("timeout")),l()},e.tuning.readTimeoutMs??1e4)}),O=await Promise.race([p(d,[g]),B]);if(O.kind===D){let{id:X,...z}=O;return z}throw new E(O.kind==="error"?O.code:O.kind==="failed"?O.reason:"error")}finally{clearTimeout(A),u=!1}}return{ready:C,get busy(){return u},bandRead:(d,g=e.tuning.detectorLimit)=>P({kind:"band",bitmap:d,detectorLimit:g},d,"band"),stillRead:(d,g,D=e.tuning.detectorLimit)=>P({kind:"still",bitmap:d,region:g,detectorLimit:D},d,"band"),layoutRead:(d,g)=>P({kind:"layout",bitmap:d,detectorLimit:g},d,"layout"),dispose:l}}var H="sekyro-ocr-1",le=e=>e!==null&&typeof e=="object"?e:{},_=(e,t,n,r)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:r,Ke=(e,t)=>typeof e=="boolean"?e:t,je=e=>{let t=typeof e=="string"?/^sekyro-ocr-(\d{1,4})$/.exec(e):null;return t?Number(t[1]):Number.POSITIVE_INFINITY};function $e(e,t={}){let n=le(e),r=le(n.liveMrz),i=le(n.frontLock),u=je(t.engine??H),c=t.mode==="off",s=d=>d.enabled===!0?d.arm==="live"?"live":"control":null,p=s(r),l=s(i),M=(d,g)=>!c&&g==="live"&&je(d.minEngine??H)<=u,f=Te,T=M(r,p)?{detectorLimit:_(r.detectorLimit,320,1600,f.detectorLimit),bandMaxWidthPx:_(r.bandMaxWidthPx,320,4096,f.bandMaxWidthPx),minBandWidthPx:_(r.minBandWidthPx,0,4096,f.minBandWidthPx),bandTop:_(r.bandTop,0,.95,f.bandTop),minIntervalMs:_(r.minIntervalMs,0,5e3,f.minIntervalMs),stableReads:Math.round(_(r.stableReads,1,10,f.stableReads)),profileReads:Math.round(_(r.profileReads,1,100,f.profileReads)),maxReadMs:_(r.maxReadMs,50,6e4,f.maxReadMs),searchTimeoutMs:_(r.searchTimeoutMs,1e3,12e4,f.searchTimeoutMs),hint:Ke(r.hint,!0),stillConfirm:Ke(r.stillConfirm,!0)}:null,C=Le,S=(d,g,D)=>_(i[d],g,D,C[d]),P=M(i,l)?{minLines:Math.round(S("minLines",1,50)),fillMin:S("fillMin",0,1),fillMax:S("fillMax",0,2),offsetMax:S("offsetMax",0,1),steadyFillDelta:S("steadyFillDelta",0,1),steadyOffsetDelta:S("steadyOffsetDelta",0,1),layoutShiftMax:S("layoutShiftMax",0,1),lineCountDelta:Math.round(S("lineCountDelta",0,50)),lockMs:S("lockMs",0,3e4),steadyMs:S("steadyMs",0,3e4),minFrames:Math.round(S("minFrames",1,100)),minIntervalMs:S("minIntervalMs",0,5e3),maxWidthPx:S("maxWidthPx",160,2048),detectorLimit:S("detectorLimit",320,1600),searchTimeoutMs:S("searchTimeoutMs",1e3,12e4)}:null;return{enabled:T!==null||P!==null,liveMrz:T,textLock:P,liveMrzArm:p,frontLockArm:l,load:{detectorLimit:T?.detectorLimit??P?.detectorLimit??f.detectorLimit,loadTimeoutMs:_(r.loadTimeoutMs,1e3,12e4,2e4),maxDownloadMs:_(r.maxDownloadMs,1e3,12e4,2e4)},reportSampleRate:_(r.reportSampleRate,0,1,1)}}function Je(e,t){return e.enabled?!(t.probe??Xe)().ok||(t.slow??Ye)()?{ok:!1,reason:"unsupported"}:{ok:!0,engine:Qe({baseUrl:t.baseUrl,salt:t.salt,tuning:{detectorLimit:e.load.detectorLimit,maxDownloadMs:e.load.maxDownloadMs,loadTimeoutMs:e.load.loadTimeoutMs},...t.workerUrl!==void 0?{workerUrl:t.workerUrl}:{},...t.createWorker!==void 0?{createWorker:t.createWorker}:{},...t.page!==void 0?{page:t.page}:{},...t.deviceMemoryGb!==void 0?{deviceMemoryGb:t.deviceMemoryGb}:{}})}:{ok:!1,reason:"off"}}function kt(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 I=e=>e===void 0||!Number.isFinite(e)?void 0:Math.min(6e5,Math.max(0,Math.round(e))),de=(e,t,n)=>e===void 0||!Number.isFinite(e)?void 0:Math.min(n,Math.max(t,Math.round(e)));function Ze(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",u={kind:"live_mrz",platform:"web",engine:e.engine??H,arm:e.arm,capture:e.capture,outcome:i,reads:de(t?.reads??0,0,1e4)??0,browser:e.browser??kt()},c=(s,p)=>{p!==void 0&&(u[s]=p)};return c("format",t?.format),c("framesToValid",de(t?.framesToValid,1,1e4)),c("msToValid",I(t?.msToValid)),c("framesToLock",de(t?.framesToLock,1,1e4)),c("msToLock",I(t?.msToLock)),c("msToCapture",I(e.msToCapture)),c("readP50Ms",I(t?.readP50Ms)),c("readP90Ms",I(t?.readP90Ms)),c("deviceClass",t?.deviceClass),n!==null&&(c("warmupMs",I(n.warmupMs)),c("downloadMs",I(n.downloadMs)),c("cached",n.cached),c("tier",n.tier),c("benchMs",I(n.benchMs))),c("stillConfirmed",e.stillConfirmed),c("typeMismatch",e.typeMismatch),u}function me(e,t){return e===void 0?!1:t==="passport"?e!=="TD3":e==="TD3"}var Ct=2;async function xt(e){let t=await import("./capture-session-doc-KAKQJPCO.js");return new t.CaptureSessionDoc(e)}function vt(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 Rt(e,t,n){let r=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let u=0;u<r.length;u+=1){let c=r[u],s=r[(u+1)%r.length];i+=c.x*s.y-s.x*c.y}return t>0&&n>0?Math.abs(i)/2/(t*n):0}function hn(){import("./capture-session-doc-KAKQJPCO.js").then(e=>e.warmDocDetector()).catch(()=>{})}function bn(e){return Pt(e,{}).handle}function Pt(e,t){let n=we(),r=ke({enabled:e.keepScreenAwake!==!1}),i=t.decode??(o=>createImageBitmap(o)),u=t.blurRefuseSharpnessMax??.16,c=t.now??(()=>performance.now()),s=Oe(e.documentType,t.catalogCapture===!0?t.captureSeries??Ae(e.issuer,e.documentType):[]),p=s.sides.length===1||e.side==="single",l=ie(p?"singlePage":"twoSided",c());if(!p&&(e.side==="recto"||e.side==="verso")){let o=e.side==="recto"?"verso":"recto";l={...l,captured:{[o]:"server"},readSides:[o],current:e.side,phase:"flipCue",restPhase:"flipCue"}}let M="idle",f=null,T=null,C=!0,S=0,P=0,d=!1,g=!1,D="",A=null,B,O=null,X=[],z=s.mrz==="none",et=s.barcodeSide==="recto"||s.barcodeSide==="verso"?s.barcodeSide:null,F=z&&!p?t.barcode?.side??et:null,pe=e.barcodeAssetBaseUrl??t.barcode?.assetBaseUrl,fe=null,ge=()=>F===null||pe===void 0||t.barcode?.seen!==void 0?Promise.resolve(null):(fe??(fe=import("./barcode-detect-C5IOXMKI.js").then(o=>o.loadBarcodeDetect(pe)).catch(()=>null)),fe),tt=async(o,a)=>{if(F===null)return null;let m=F==="recto"?"verso":"recto";try{let h=t.barcode?.seen;if(h!==void 0)return await h(o)?F:m;let[v,w]=await Promise.all([ge(),a()]);if(v===null||w===null)return null;let k=Math.min(1600,w.width),y=document.createElement("canvas");y.width=k,y.height=Math.max(1,Math.round(w.height/w.width*k));try{let b=y.getContext("2d");return b===null?null:(b.drawImage(w,0,0,y.width,y.height),await Be(v,b.getImageData(0,0,y.width,y.height),F))}finally{y.width=0,y.height=0}}catch{return null}},x=t.webOcr!==void 0&&!z?$e(t.webOcr.captureDocument,{mode:e.liveMrz?.mode??"auto"}):null,G=null,U=x===null||!x.enabled?"off":null,Y=null,V=null,he=new WeakMap,J="";if(x!==null&&x.enabled&&t.webOcr!==void 0){let o=t.webOcr,a=Je(x,{baseUrl:e.liveMrz?.assetBaseUrl??o.baseUrl,salt:o.salt,...e.liveMrz?.workerUrl!==void 0?{workerUrl:e.liveMrz.workerUrl}:{},...o.createWorker!==void 0?{createWorker:o.createWorker}:{}});if(a.ok){G=a.engine;let m=new _e({textLock:x.textLock,liveMrz:x.liveMrz});Y=m;let h=a.engine;h.ready.then(v=>{U=v,typeof v!="string"&&C&&m.setEngine(h,v.tier)})}else U=a.reason}let N=o=>{let a=JSON.stringify(o);a!==J&&(J=a,n.emit("mrz",o))},be=(o,a)=>{let m=t.webOcr?.reports;if(m===void 0||x===null||o===void 0)return;let h=o.format==="ID-3"||o.side==="single"?"single":o.side==="verso"?"verso":"recto",v=h!=="recto"?x.liveMrzArm??x.frontLockArm:x.frontLockArm;if(v===null||Math.random()>=x.reportSampleRate)return;let w=o.via==="live_mrz"?V:null,k=()=>{let y=w?.value??null;m([Ze({arm:v,capture:h,assist:o.ocr??null,load:v==="control"?"off":U,...o.msToCapture!==void 0?{msToCapture:o.msToCapture}:{},...y!==null&&y.stillConfirmed!==void 0?{stillConfirmed:y.stillConfirmed}:{},...a!==void 0?{typeMismatch:me(a.format,s.format==="ID-3"?"passport":"card")}:{}})])};w!==null&&w.value===null?Promise.race([w.promise,new Promise(y=>setTimeout(y,3e3))]).then(k):k()},W=o=>{!C||o===M||(M=o,r.setActive(o==="starting"||o==="scanning"),n.emit("state",o))},nt=(o,a)=>a===void 0?null:p?"single":o.captured.recto===a?"recto":o.captured.verso===a?"verso":null,rt=o=>({phase:o.phase,captured:p?o.captured.recto!==void 0?["single"]:[]:["recto","verso"].filter(a=>o.captured[a]!==void 0),expected:p?null:o.current??null,notice:o.notice??null,lastShot:nt(o,o.lastShot),manualShutter:o.manualShutter,torchAvailable:f?.torchAvailable()??!1,torch:g}),ye=()=>{let o=f;o!==null&&o.captureNow().catch(()=>L({type:"captureFailed",at:c()}))};function L(o){if(!C)return;let a=l;l=qe(l,o),l.phase==="capturing"&&a.phase!=="capturing"&&Promise.resolve().then(ye),l.phase==="result"&&a.phase!=="result"&&(W("done"),Se());let m=rt(l),h=JSON.stringify(m);h!==D&&(D=h,n.emit("scan",m))}function Se(){O!==null&&clearInterval(O),O=null;for(let o of X.splice(0))o();f?.destroy(),f=null,r.setActive(!1)}let Me=()=>f?.captureReport?.(),Z=!1,De=(o,a)=>{if(!(o===void 0||t.onFaceReport===void 0))try{t.onFaceReport(o,a)}catch{}},Q=o=>{J="",!(f===null||l.phase==="reading"||l.phase==="result")&&(Z=!1,f.rearm(p?"single":l.current??o))},ot=async(o,a,m,h)=>{if(V=null,h!==void 0&&G!==null&&x?.liveMrz?.hint===!0){let b={promise:He(G,o,h,{engine:H,detectorLimit:x.liveMrz.detectorLimit}).catch(()=>null),value:null};b.promise.then(R=>{b.value=R}),V=b}h!==void 0&&me(h.format,s.format==="ID-3"?"passport":"card")&&N({state:"mismatch",format:h.format});let v=Me();De(v,"captured"),Z=!0,be(v,h);let w=m===void 0?A:m===null?null:{quad:vt(m),frameWidth:0,frameHeight:0,inStill:!0},k={decoded:null},y=()=>(k.decoded??(k.decoded=Promise.resolve().then(()=>i(o)).catch(()=>null)),k.decoded);try{await at(o,a,w,y,V)}finally{k.decoded!==null&&(await k.decoded)?.close()}},at=async(o,a,m,h,v)=>{let w=`shot-${S+=1}`;if(L({type:"captured",id:w,at:c()}),e.haptics!==!1)try{globalThis.navigator?.vibrate?.(30)}catch{}if(!d&&u>0){let b=await(t.measureSharpness!==void 0?t.measureSharpness(o,m):h().then(R=>R===null?-1:ve(R,re(m?.quad??null,m?.inStill===!0?R:{width:m?.frameWidth??0,height:m?.frameHeight??0},R)))).catch(()=>-1);if(!C)return;if(Number.isFinite(b)&&b>=0&&b<u){d=!0;let R=p?"recto":l.current??(l.captured.recto===void 0?"recto":"verso");L({type:"readFailed",side:R,id:w,issue:"blurry"}),Q(R);return}}d=!1;let k;if(p)k="single";else{let b=l.current,R=t.classify===void 0?await tt(o,h):null,q=(R===null||F===null?R:Ie(R,F,l.captured))??await(t.classify!==void 0?t.classify(o):h().then(K=>K===null?b??"recto":m?.inStill===!0?ce(K,480,null,!0):ce(K,480,re(m?.quad??null,{width:m?.frameWidth??0,height:m?.frameHeight??0},K)))).catch(()=>b??"recto");if(!C)return;if(l.captured[q]!==void 0&&P<Ct){P+=1,L({type:"duplicate",id:w,side:q}),Q(q==="recto"?"verso":"recto");return}k=l.captured[q]!==void 0&&b!==void 0?b:q,P=0,L({type:"classified",id:w,side:k})}let y=k==="verso"?"verso":"recto";try{let b=t.encode!==void 0?await t.encode(o):await h().then(R=>{if(R===null)throw new Error("the still could not be decoded");return oe(R)});if(!C)return;v!==null&&he.set(b.blob,v),n.emit("captured",{image:b.blob,side:k,documentType:e.documentType,...e.issuer!==void 0?{issuer:e.issuer}:{},width:b.width,height:b.height,previewDataUrl:a}),t.deferRead!==!0&&L({type:"readOk",side:y})}catch(b){L({type:"readFailed",side:y,id:w,issue:"technical"}),n.emit("error",j("generic",!0,{phase:"keyframes",name:te(b)}))}Q(y==="recto"?"verso":"recto")},it=o=>{X.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 h=a.quad===null?0:Rt(a.quad,a.frameWidth,a.frameHeight);A=a.quad===null?null:{quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight},L({type:"report",report:{present:a.quad!==null&&a.plausible||a.guide?.detected===!0,ready:a.ready===!0,locking:a.p>=.5,areaFrac:h},at:c()})}),o.on("error",({kind:a,retryable:m,detail:h})=>n.emit("error",j(a,m,h))),o.on("artifacts",a=>{ot(a.keyframe,a.previewDataUrl,a.docRegion,a.liveMrz)}))},ee=()=>(T??(T=(async()=>{if(C){if(ge(),f===null){let o;try{o=await(t.createEngine??xt)({...t.engineOptions??{},...B!==void 0?{guide:B}:{},video:e.video,format:s.format,side:p?"single":e.side??"recto",autoCapture:!1,...Y!==null?{ocr:Y}:{}})}catch(m){W("error"),n.emit("error",j("models",!0,{phase:"models",name:te(m)}));return}if(!C){o.destroy();return}f=o,it(o);let a=t.tickMs??500;a>0&&(O=setInterval(()=>L({type:"tick",at:c()}),a))}L({type:"clockRestart"}),x!==null&&x.liveMrzArm==="live"&&(U==="unsupported"||U==="off")&&N({state:"fallback",reason:U}),await f.start()}})().finally(()=>{T=null})),T);return{handle:{get state(){return M},on:(o,a)=>n.on(o,a),start:ee,retry:()=>{if(f===null&&l.phase==="result"){L({type:"retake"}),P=0,d=!1,ee();return}if(f!==null&&M!=="error"){L({type:"retake"}),P=0,d=!1,f.rearm(p?"single":void 0);return}ee()},setSide:o=>{p||o==="single"||(l.current!==o&&(l={...l,current:o}),L({type:"clockRestart"}),l.phase!=="reading"&&l.phase!=="result"&&f?.rearm(o))},shutter:ye,focusAt:(o,a)=>{f?.focusAt?.(o,a)},setGuide:o=>{B=o,f?.setGuide?.(o)},setTorch:o=>{g=o,f?.setTorch(o),L({type:"tick",at:c()})},destroy:()=>{if(C&&f!==null&&M!=="done"){let o=Me();!Z&&o!==void 0&&o.ticks>0&&De(o,"abandoned"),be(o,void 0)}C=!1,Se(),Y?.setEngine(null),G?.dispose(),G=null,n.clear()}},plan:s,setFlowState:o=>{(l.phase==="reading"||l.phase==="result")&&W(o==="done"&&l.phase!=="result"?"scanning":o)},settle:(o,a)=>{let m=o==="verso"?"verso":"recto";L(a.ok?{type:"readOk",side:m}:{type:"readFailed",side:m,issue:a.issue}),a.ok||Q(m)},takeDeviceRead:o=>he.get(o.image)?.value??null}}export{Ft as a,zt as b,Ut as c,Nt as d,Gt as e,qt as f,ze as g,ie as h,qe as i,St as j,Mt as k,Xt as l,He as m,Vt as n,H as o,$e as p,Je as q,kt as r,Ze as s,me as t,Ct as u,hn as v,bn as w,Pt as x};
1
+ import{d as re,h as ve,i as Le,j as Te,l as _e}from"./chunk-JULJQOVT.js";import{a as ne,e as Ce,g as xe}from"./chunk-XFATG7QI.js";import{m as j}from"./chunk-NMPMXAH3.js";import{a as we,g as ke}from"./chunk-7QZWBDI5.js";import{k as te}from"./chunk-CPUECYAJ.js";import{d as Re,f as Pe}from"./chunk-ISMVEF7H.js";function Ee(e,t){let n=new Set(e.flatMap(r=>r.sides.filter(i=>i[t]!==null).map(i=>i.side)));return n.size===1?[...n][0]:null}function st(e){let t=Ce.find(r=>r.docType===e),n=t.mrz==="none"?null:t.mrz==="td3"?"single":"verso";return{sides:t.sides,format:xe(e),mrz:t.mrz==="none"?"none":"required",mrzSide:n,barcodeSide:null,portraitSide:t.portraitSide,scripts:null}}function ct(e){let t=[];for(let n of e)for(let r of n.sides){if(!Array.isArray(r.scripts))return null;for(let i of r.scripts)t.includes(i)||t.push(i)}return t}function Oe(e,t){if(t.length===0)return st(e);let n=t.some(s=>s.sides.length>1),r=new Set(t.map(s=>s.format)),i=r.size===1?[...r][0]:"card",u=t.filter(s=>s.sides.some(p=>p.mrz!==null)).length,c=t.find(s=>s.sides.length>1===n)?.sides.find(s=>s.portrait)?.side;return{sides:n?["recto","verso"]:["single"],format:i,mrz:u===t.length?"required":u===0?"none":"optional",mrzSide:Ee(t,"mrz"),barcodeSide:Ee(t,"barcode"),portraitSide:c??(n?"recto":"single"),scripts:ct(t)}}function Ae(e,t){if(e===void 0)return[];let n=e.toUpperCase();return Object.prototype.hasOwnProperty.call(ne,n)?ne[n]?.[t]??[]:[]}async function Be(e,t,n){return await e(t)?n:n==="recto"?"verso":"recto"}function Ie(e,t,n){return e!==t&&t==="verso"&&n.recto!==void 0&&n.verso===void 0?"verso":e}var ut={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 lt(e){let{deviceMemory:t,effectiveType:n,saveData:r,downlinkMbps:i,sourceLongEdge:u}=e,c=r===!0||n==="slow-2g"||n==="2g"||i!=null&&i>0&&i<1,s=t!=null&&t<=2,p=n==="4g"||i!=null&&i>=5,l=t!=null&&t>=6,M;c||s?M="low":p&&l?M="good":M="mid";let f=ut[M],T=u&&u>0?Math.min(f.maxLongEdge,u):f.maxLongEdge;return{tier:M,...f,maxLongEdge:T}}function Fe(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),lt(t)}function dt(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 mt(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 pt(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 We(e,t,n,r,i){if(t<=0||n<=0)return null;let{width:u,height:c}=mt(t,n,r.maxLongEdge),s=document.createElement("canvas");s.width=u,s.height=c;let p=s.getContext("2d");if(!p)return null;p.drawImage(e,0,0,u,c);let l=C=>new Promise((S,P)=>{s.toBlob(d=>d?S(d):P(new Error("canvas toBlob returned null")),"image/jpeg",C)}),M=dt(i,r.qMin,r.qMax),{blob:f,quality:T}=await pt(l,{startQ:M,qMin:r.qMin,budgetBytes:r.payloadTargetBytes}).finally(()=>{s.width=0,s.height=0});if(f.size>5242880)throw new Error("encoded document exceeds the 5242880-byte media cap");return{blob:f,quality:T,width:u,height:c}}async function oe(e){let t=Fe(Math.max(e.width,e.height)),n=await We(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 Ft(e){let t=await createImageBitmap(e);try{return await oe(t)}finally{t.close()}}var zt=250,Ut=.6,Nt=1800,Gt=6e3,qt=2e3,ze=.16;function ie(e,t){return{layout:e,phase:"framing",captured:{},pending:[],lastCaptureAt:t,lastReportAt:t,manualShutter:!1,restPhase:"framing",readSides:[],needFlip:!1,flipped:!1,flipTimeoutSpent:!1,timeoutCapture:!1,lastShotByTimeout:!1}}var Ue=e=>e==="recto"?"verso":"recto",Ne=e=>e.phase==="framing"||e.phase==="locking"||e.phase==="flipCue"||e.phase==="reaskRecto",se=e=>(e.captured.recto!==void 0?1:0)+(e.captured.verso!==void 0?1:0)+e.pending.length;function ae(e,t){return e.lastCaptureAt>=0&&e.lastReportAt>=0?e:{...e,lastCaptureAt:e.lastCaptureAt<0?t:e.lastCaptureAt,lastReportAt:e.lastReportAt<0?t:e.lastReportAt}}function ft(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:u}=e;r&&(u=u??n),u!==void 0&&n-u>=250&&(i=!0),r||(u=void 0);let c=e.flipTimeoutSpent&&!(i&&!e.flipped),s={...e,lastReportAt:n,flipped:i,awaySince:u,flipTimeoutSpent:c,lastArea:t.areaFrac};if(!Ne(e))return s;if(e.needFlip&&!i){if(!t.ready)return{...s,phase:e.restPhase,goodSince:void 0};let p=e.lastShot!==void 0&&e.pending.includes(e.lastShot);if(c||p)return{...s,goodSince:void 0,phase:e.restPhase};let l=e.goodSince??n;return n-l>=1800?{...s,goodSince:l,phase:"capturing",flipTimeoutSpent:!0,timeoutCapture:!0}:{...s,goodSince:l,phase:e.restPhase}}return t.ready?{...s,phase:"capturing",goodSince:e.goodSince??n}:{...s,goodSince:void 0,phase:t.locking?"locking":e.restPhase}}function gt(e,t){if(!Ne(e)||e.manualShutter)return e;let n=t-e.lastReportAt>=2e3,r=t-e.lastCaptureAt>=6e3;return n||r?{...e,manualShutter:!0}:e}function ht(e,t,n){let r=e.layout==="singlePage",i=r?{recto:t}:e.captured,u=r?[]:[...e.pending,t],c={...e,captured:i,pending:u,lastShot:t,lastCaptureAt:n,lastReportAt:-1,manualShutter:!1,goodSince:void 0,notice:void 0,awaySince:void 0,flipped:!1,lastShotByTimeout:e.timeoutCapture,timeoutCapture:!1,captureArea:e.lastArea};return r||se({captured:i,pending:u})>=2?{...c,phase:"reading",restPhase:"framing",current:void 0,needFlip:!1}:{...c,phase:"flipCue",restPhase:"flipCue",current:void 0,needFlip:!0}}function Ge(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:Ue(n),needFlip:!0,flipTimeoutSpent:!0,goodSince:void 0,manualShutter:!0,notice:"same_face",lastCaptureAt:-1,lastReportAt:-1}:e}function bt(e,t,n){if(!e.pending.includes(t))return e;if(e.captured[n]!==void 0)return Ge(e,t,n);let r=e.pending.filter(p=>p!==t),i={...e,pending:r,captured:{...e.captured,[n]:t}};if(se(i)!==1||e.layout==="singlePage")return i;let u=Ue(n),c=u==="recto"&&e.restPhase==="reaskRecto"?"reaskRecto":"flipCue",s=e.phase==="flipCue"||e.phase==="reaskRecto"||e.phase==="framing";return{...i,restPhase:c,current:u,phase:s?c:e.phase}}function yt(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(l=>l!==n),u=e.layout==="twoSided"&&se({captured:r,pending:i})>0,c=e.lastShotByTimeout||n===e.lastShot!==e.flipped,s=u&&!c,p=s?t.side==="recto"?"reaskRecto":"flipCue":"framing";return{...e,captured:r,pending:i,readSides:e.readSides.filter(l=>l!==t.side),lastShot:e.lastShot===n?void 0:e.lastShot,notice:t.issue,goodSince:void 0,manualShutter:!1,phase:p,restPhase:p,current:t.side,needFlip:s,flipped:!1,flipTimeoutSpent:!1,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1}}function qe(e,t){switch(t.type){case"report":return ft(ae(e,t.at),t.report,t.at);case"tick":return gt(ae(e,t.at),t.at);case"captured":return ht(ae(e,t.at),t.id,t.at);case"captureFailed":return{...e,phase:e.restPhase,goodSince:void 0,lastCaptureAt:t.at,manualShutter:!0,timeoutCapture:!1};case"classified":return bt(e,t.id,t.side);case"duplicate":return Ge(e,t.id,t.side);case"readOk":{let n=e.readSides.includes(t.side)?e.readSides:[...e.readSides,t.side],r=["recto","verso"].filter(u=>e.captured[u]!==void 0),i=e.phase==="reading"&&e.pending.length===0&&r.every(u=>n.includes(u));return{...e,readSides:n,flipTimeoutSpent:!1,phase:i?"result":e.phase}}case"readFailed":return yt(e,t);case"clockRestart":return e.lastCaptureAt<0&&e.lastReportAt<0&&e.awaySince===void 0?e:{...e,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1};case"retake":return{...ie(e.layout,-1),lastCaptureAt:-1,lastReportAt:-1};default:return e}}function St(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 Mt(e,t=!1){let{detectMrzBand:n}=await import("./mrz-band-VYHOTDHY.js");return St(n,e,t)}async function ce(e,t=480,n,r=n!=null){let i=n??{x:0,y:0,width:e.width,height:e.height},u=Math.max(1,Math.round(i.height/i.width*t)),c=document.createElement("canvas");c.width=t,c.height=u;try{let s=c.getContext("2d");return s===null?"recto":(s.drawImage(e,i.x,i.y,i.width,i.height,0,0,t,u),await Mt(s.getImageData(0,0,t,u),r))}finally{c.width=0,c.height=0}}async function Xt(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 u=i.getContext("2d");return u===null?(n.close(),null):(u.drawImage(n,0,0,t,r),n.close(),u.getImageData(0,0,t,r))}catch{return null}}var ue=(e,t,n)=>Math.min(n,Math.max(t,Math.round(e))),$=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function He(e,t,n,r){let i=r.decode??(p=>createImageBitmap(p)),u=async()=>e.stillRead(await i(t),r.region??[0,0,1,1],r.detectorLimit),c;try{c=await u()}catch{try{await new Promise(p=>setTimeout(p,r.retryMs??300)),c=await u()}catch{return null}}let s=c.mrzBox;return s===void 0?null:{engine:r.engine,source:"live_mrz",format:n.format,lineCount:ue(n.lineCount,2,3),checkDigitsValid:!0,stillConfirmed:c.valid&&c.digest===n.digest,band:[$(s[0]),$(s[1]),$(Math.min(s[2],1-s[0])),$(Math.min(s[3],1-s[1]))],digest:n.digest,framesToValid:ue(n.framesToValid,1,1e3),msToValid:ue(n.msToValid,0,12e4)}}function Vt(e){let t=null;return e?.then(n=>{t=n}),()=>t}var Dt=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]),wt=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 Xe(e=globalThis){let t=e.WebAssembly?.validate;if(typeof t!="function")return{ok:!1,reason:"simd"};try{if(!t.call(e.WebAssembly,Dt)||!t.call(e.WebAssembly,wt))return{ok:!1,reason:"simd"}}catch{return{ok:!1,reason:"simd"}}return typeof e.Worker!="function"?{ok:!1,reason:"worker"}:typeof e.createImageBitmap!="function"?{ok:!1,reason:"bitmap"}:{ok:!0}}function Ye(e=globalThis){let t=e.navigator?.connection;return t?.saveData===!0||["slow-2g","2g","3g"].includes(t?.effectiveType??"")}var E=class extends Error{constructor(t){super(t),this.name="OcrEngineError",this.code=t}};function Ve(){let e=t=>(t.close(),Promise.reject(new E("unsupported")));return{ready:Promise.resolve("unsupported"),busy:!1,bandRead:e,stillRead:e,layoutRead:e,dispose:()=>{}}}function Qe(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 Ve()}catch{return Ve()}let n=new Map,r=0,i=!1,u=!1,c=!1;t.addEventListener("message",d=>{let g=d.data,D=n.get(g.id);D&&(n.delete(g.id),D.resolve(g))});let s=()=>{for(let d of n.values())d.reject(new E("error"));n.clear(),l()};t.addEventListener("error",s),t.addEventListener("messageerror",s);function p(d,g=[]){if(i)return Promise.reject(new E("disposed"));let D=++r;return new Promise((A,B)=>{n.set(D,{resolve:A,reject:B});try{t.postMessage({...d,id:D},g)}catch{n.delete(D),B(new E("error"))}})}function l(){if(!i){i=!0;try{t.postMessage({id:++r,kind:"dispose"})}catch{}t.terminate();for(let d of n.values())d.reject(new E("disposed"));n.clear()}}let M=(async()=>{let d=await p({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 p({kind:"warmup"});if(g.kind!=="ready")return"error";let D=g.benchMs??g.warmupMs,A=e.deviceMemoryGb===void 0?Pe():e.deviceMemoryGb;return{warmupMs:g.warmupMs,downloadMs:d.downloadMs,cached:d.cached,benchMs:D,tier:Re(D,A)}})().catch(()=>"error"),f,T=new Promise(d=>{f=setTimeout(()=>d("timeout"),e.tuning.loadTimeoutMs)}),C=Promise.race([M,T]).then(d=>(clearTimeout(f),typeof d=="string"?l():c=!0,i&&typeof d!="string"?"error":d));(e.page===void 0?globalThis.addEventListener?globalThis:null:e.page)?.addEventListener("pagehide",l,{once:!0});async function P(d,g,D){if(i)throw g.close(),new E("disposed");if(!c)throw g.close(),new E("not_ready");if(u)throw g.close(),new E("busy");u=!0;let A;try{let B=new Promise((X,z)=>{A=setTimeout(()=>{z(new E("timeout")),l()},e.tuning.readTimeoutMs??1e4)}),O=await Promise.race([p(d,[g]),B]);if(O.kind===D){let{id:X,...z}=O;return z}throw new E(O.kind==="error"?O.code:O.kind==="failed"?O.reason:"error")}finally{clearTimeout(A),u=!1}}return{ready:C,get busy(){return u},bandRead:(d,g=e.tuning.detectorLimit)=>P({kind:"band",bitmap:d,detectorLimit:g},d,"band"),stillRead:(d,g,D=e.tuning.detectorLimit)=>P({kind:"still",bitmap:d,region:g,detectorLimit:D},d,"band"),layoutRead:(d,g)=>P({kind:"layout",bitmap:d,detectorLimit:g},d,"layout"),dispose:l}}var H="sekyro-ocr-1",le=e=>e!==null&&typeof e=="object"?e:{},_=(e,t,n,r)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:r,Ke=(e,t)=>typeof e=="boolean"?e:t,je=e=>{let t=typeof e=="string"?/^sekyro-ocr-(\d{1,4})$/.exec(e):null;return t?Number(t[1]):Number.POSITIVE_INFINITY};function $e(e,t={}){let n=le(e),r=le(n.liveMrz),i=le(n.frontLock),u=je(t.engine??H),c=t.mode==="off",s=d=>d.enabled===!0?d.arm==="live"?"live":"control":null,p=s(r),l=s(i),M=(d,g)=>!c&&g==="live"&&je(d.minEngine??H)<=u,f=Te,T=M(r,p)?{detectorLimit:_(r.detectorLimit,320,1600,f.detectorLimit),bandMaxWidthPx:_(r.bandMaxWidthPx,320,4096,f.bandMaxWidthPx),minBandWidthPx:_(r.minBandWidthPx,0,4096,f.minBandWidthPx),bandTop:_(r.bandTop,0,.95,f.bandTop),minIntervalMs:_(r.minIntervalMs,0,5e3,f.minIntervalMs),stableReads:Math.round(_(r.stableReads,1,10,f.stableReads)),profileReads:Math.round(_(r.profileReads,1,100,f.profileReads)),maxReadMs:_(r.maxReadMs,50,6e4,f.maxReadMs),searchTimeoutMs:_(r.searchTimeoutMs,1e3,12e4,f.searchTimeoutMs),hint:Ke(r.hint,!0),stillConfirm:Ke(r.stillConfirm,!0)}:null,C=Le,S=(d,g,D)=>_(i[d],g,D,C[d]),P=M(i,l)?{minLines:Math.round(S("minLines",1,50)),fillMin:S("fillMin",0,1),fillMax:S("fillMax",0,2),offsetMax:S("offsetMax",0,1),steadyFillDelta:S("steadyFillDelta",0,1),steadyOffsetDelta:S("steadyOffsetDelta",0,1),layoutShiftMax:S("layoutShiftMax",0,1),lineCountDelta:Math.round(S("lineCountDelta",0,50)),lockMs:S("lockMs",0,3e4),steadyMs:S("steadyMs",0,3e4),minFrames:Math.round(S("minFrames",1,100)),minIntervalMs:S("minIntervalMs",0,5e3),maxWidthPx:S("maxWidthPx",160,2048),detectorLimit:S("detectorLimit",320,1600),searchTimeoutMs:S("searchTimeoutMs",1e3,12e4)}:null;return{enabled:T!==null||P!==null,liveMrz:T,textLock:P,liveMrzArm:p,frontLockArm:l,load:{detectorLimit:T?.detectorLimit??P?.detectorLimit??f.detectorLimit,loadTimeoutMs:_(r.loadTimeoutMs,1e3,12e4,2e4),maxDownloadMs:_(r.maxDownloadMs,1e3,12e4,2e4)},reportSampleRate:_(r.reportSampleRate,0,1,1)}}function Je(e,t){return e.enabled?!(t.probe??Xe)().ok||(t.slow??Ye)()?{ok:!1,reason:"unsupported"}:{ok:!0,engine:Qe({baseUrl:t.baseUrl,salt:t.salt,tuning:{detectorLimit:e.load.detectorLimit,maxDownloadMs:e.load.maxDownloadMs,loadTimeoutMs:e.load.loadTimeoutMs},...t.workerUrl!==void 0?{workerUrl:t.workerUrl}:{},...t.createWorker!==void 0?{createWorker:t.createWorker}:{},...t.page!==void 0?{page:t.page}:{},...t.deviceMemoryGb!==void 0?{deviceMemoryGb:t.deviceMemoryGb}:{}})}:{ok:!1,reason:"off"}}function kt(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 I=e=>e===void 0||!Number.isFinite(e)?void 0:Math.min(6e5,Math.max(0,Math.round(e))),de=(e,t,n)=>e===void 0||!Number.isFinite(e)?void 0:Math.min(n,Math.max(t,Math.round(e)));function Ze(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",u={kind:"live_mrz",platform:"web",engine:e.engine??H,arm:e.arm,capture:e.capture,outcome:i,reads:de(t?.reads??0,0,1e4)??0,browser:e.browser??kt()},c=(s,p)=>{p!==void 0&&(u[s]=p)};return c("format",t?.format),c("framesToValid",de(t?.framesToValid,1,1e4)),c("msToValid",I(t?.msToValid)),c("framesToLock",de(t?.framesToLock,1,1e4)),c("msToLock",I(t?.msToLock)),c("msToCapture",I(e.msToCapture)),c("readP50Ms",I(t?.readP50Ms)),c("readP90Ms",I(t?.readP90Ms)),c("deviceClass",t?.deviceClass),n!==null&&(c("warmupMs",I(n.warmupMs)),c("downloadMs",I(n.downloadMs)),c("cached",n.cached),c("tier",n.tier),c("benchMs",I(n.benchMs))),c("stillConfirmed",e.stillConfirmed),c("typeMismatch",e.typeMismatch),u}function me(e,t){return e===void 0?!1:t==="passport"?e!=="TD3":e==="TD3"}var Ct=2;async function xt(e){let t=await import("./capture-session-doc-LKMMJG4H.js");return new t.CaptureSessionDoc(e)}function vt(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 Rt(e,t,n){let r=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let u=0;u<r.length;u+=1){let c=r[u],s=r[(u+1)%r.length];i+=c.x*s.y-s.x*c.y}return t>0&&n>0?Math.abs(i)/2/(t*n):0}function hn(){import("./capture-session-doc-LKMMJG4H.js").then(e=>e.warmDocDetector()).catch(()=>{})}function bn(e){return Pt(e,{}).handle}function Pt(e,t){let n=we(),r=ke({enabled:e.keepScreenAwake!==!1}),i=t.decode??(o=>createImageBitmap(o)),u=t.blurRefuseSharpnessMax??.16,c=t.now??(()=>performance.now()),s=Oe(e.documentType,t.catalogCapture===!0?t.captureSeries??Ae(e.issuer,e.documentType):[]),p=s.sides.length===1||e.side==="single",l=ie(p?"singlePage":"twoSided",c());if(!p&&(e.side==="recto"||e.side==="verso")){let o=e.side==="recto"?"verso":"recto";l={...l,captured:{[o]:"server"},readSides:[o],current:e.side,phase:"flipCue",restPhase:"flipCue"}}let M="idle",f=null,T=null,C=!0,S=0,P=0,d=!1,g=!1,D="",A=null,B,O=null,X=[],z=s.mrz==="none",et=s.barcodeSide==="recto"||s.barcodeSide==="verso"?s.barcodeSide:null,F=z&&!p?t.barcode?.side??et:null,pe=e.barcodeAssetBaseUrl??t.barcode?.assetBaseUrl,fe=null,ge=()=>F===null||pe===void 0||t.barcode?.seen!==void 0?Promise.resolve(null):(fe??(fe=import("./barcode-detect-C5IOXMKI.js").then(o=>o.loadBarcodeDetect(pe)).catch(()=>null)),fe),tt=async(o,a)=>{if(F===null)return null;let m=F==="recto"?"verso":"recto";try{let h=t.barcode?.seen;if(h!==void 0)return await h(o)?F:m;let[v,w]=await Promise.all([ge(),a()]);if(v===null||w===null)return null;let k=Math.min(1600,w.width),y=document.createElement("canvas");y.width=k,y.height=Math.max(1,Math.round(w.height/w.width*k));try{let b=y.getContext("2d");return b===null?null:(b.drawImage(w,0,0,y.width,y.height),await Be(v,b.getImageData(0,0,y.width,y.height),F))}finally{y.width=0,y.height=0}}catch{return null}},x=t.webOcr!==void 0&&!z?$e(t.webOcr.captureDocument,{mode:e.liveMrz?.mode??"auto"}):null,G=null,U=x===null||!x.enabled?"off":null,Y=null,V=null,he=new WeakMap,J="";if(x!==null&&x.enabled&&t.webOcr!==void 0){let o=t.webOcr,a=Je(x,{baseUrl:e.liveMrz?.assetBaseUrl??o.baseUrl,salt:o.salt,...e.liveMrz?.workerUrl!==void 0?{workerUrl:e.liveMrz.workerUrl}:{},...o.createWorker!==void 0?{createWorker:o.createWorker}:{}});if(a.ok){G=a.engine;let m=new _e({textLock:x.textLock,liveMrz:x.liveMrz});Y=m;let h=a.engine;h.ready.then(v=>{U=v,typeof v!="string"&&C&&m.setEngine(h,v.tier)})}else U=a.reason}let N=o=>{let a=JSON.stringify(o);a!==J&&(J=a,n.emit("mrz",o))},be=(o,a)=>{let m=t.webOcr?.reports;if(m===void 0||x===null||o===void 0)return;let h=o.format==="ID-3"||o.side==="single"?"single":o.side==="verso"?"verso":"recto",v=h!=="recto"?x.liveMrzArm??x.frontLockArm:x.frontLockArm;if(v===null||Math.random()>=x.reportSampleRate)return;let w=o.via==="live_mrz"?V:null,k=()=>{let y=w?.value??null;m([Ze({arm:v,capture:h,assist:o.ocr??null,load:v==="control"?"off":U,...o.msToCapture!==void 0?{msToCapture:o.msToCapture}:{},...y!==null&&y.stillConfirmed!==void 0?{stillConfirmed:y.stillConfirmed}:{},...a!==void 0?{typeMismatch:me(a.format,s.format==="ID-3"?"passport":"card")}:{}})])};w!==null&&w.value===null?Promise.race([w.promise,new Promise(y=>setTimeout(y,3e3))]).then(k):k()},W=o=>{!C||o===M||(M=o,r.setActive(o==="starting"||o==="scanning"),n.emit("state",o))},nt=(o,a)=>a===void 0?null:p?"single":o.captured.recto===a?"recto":o.captured.verso===a?"verso":null,rt=o=>({phase:o.phase,captured:p?o.captured.recto!==void 0?["single"]:[]:["recto","verso"].filter(a=>o.captured[a]!==void 0),expected:p?null:o.current??null,notice:o.notice??null,lastShot:nt(o,o.lastShot),manualShutter:o.manualShutter,torchAvailable:f?.torchAvailable()??!1,torch:g}),ye=()=>{let o=f;o!==null&&o.captureNow().catch(()=>L({type:"captureFailed",at:c()}))};function L(o){if(!C)return;let a=l;l=qe(l,o),l.phase==="capturing"&&a.phase!=="capturing"&&Promise.resolve().then(ye),l.phase==="result"&&a.phase!=="result"&&(W("done"),Se());let m=rt(l),h=JSON.stringify(m);h!==D&&(D=h,n.emit("scan",m))}function Se(){O!==null&&clearInterval(O),O=null;for(let o of X.splice(0))o();f?.destroy(),f=null,r.setActive(!1)}let Me=()=>f?.captureReport?.(),Z=!1,De=(o,a)=>{if(!(o===void 0||t.onFaceReport===void 0))try{t.onFaceReport(o,a)}catch{}},Q=o=>{J="",!(f===null||l.phase==="reading"||l.phase==="result")&&(Z=!1,f.rearm(p?"single":l.current??o))},ot=async(o,a,m,h)=>{if(V=null,h!==void 0&&G!==null&&x?.liveMrz?.hint===!0){let b={promise:He(G,o,h,{engine:H,detectorLimit:x.liveMrz.detectorLimit}).catch(()=>null),value:null};b.promise.then(R=>{b.value=R}),V=b}h!==void 0&&me(h.format,s.format==="ID-3"?"passport":"card")&&N({state:"mismatch",format:h.format});let v=Me();De(v,"captured"),Z=!0,be(v,h);let w=m===void 0?A:m===null?null:{quad:vt(m),frameWidth:0,frameHeight:0,inStill:!0},k={decoded:null},y=()=>(k.decoded??(k.decoded=Promise.resolve().then(()=>i(o)).catch(()=>null)),k.decoded);try{await at(o,a,w,y,V)}finally{k.decoded!==null&&(await k.decoded)?.close()}},at=async(o,a,m,h,v)=>{let w=`shot-${S+=1}`;if(L({type:"captured",id:w,at:c()}),e.haptics!==!1)try{globalThis.navigator?.vibrate?.(30)}catch{}if(!d&&u>0){let b=await(t.measureSharpness!==void 0?t.measureSharpness(o,m):h().then(R=>R===null?-1:ve(R,re(m?.quad??null,m?.inStill===!0?R:{width:m?.frameWidth??0,height:m?.frameHeight??0},R)))).catch(()=>-1);if(!C)return;if(Number.isFinite(b)&&b>=0&&b<u){d=!0;let R=p?"recto":l.current??(l.captured.recto===void 0?"recto":"verso");L({type:"readFailed",side:R,id:w,issue:"blurry"}),Q(R);return}}d=!1;let k;if(p)k="single";else{let b=l.current,R=t.classify===void 0?await tt(o,h):null,q=(R===null||F===null?R:Ie(R,F,l.captured))??await(t.classify!==void 0?t.classify(o):h().then(K=>K===null?b??"recto":m?.inStill===!0?ce(K,480,null,!0):ce(K,480,re(m?.quad??null,{width:m?.frameWidth??0,height:m?.frameHeight??0},K)))).catch(()=>b??"recto");if(!C)return;if(l.captured[q]!==void 0&&P<Ct){P+=1,L({type:"duplicate",id:w,side:q}),Q(q==="recto"?"verso":"recto");return}k=l.captured[q]!==void 0&&b!==void 0?b:q,P=0,L({type:"classified",id:w,side:k})}let y=k==="verso"?"verso":"recto";try{let b=t.encode!==void 0?await t.encode(o):await h().then(R=>{if(R===null)throw new Error("the still could not be decoded");return oe(R)});if(!C)return;v!==null&&he.set(b.blob,v),n.emit("captured",{image:b.blob,side:k,documentType:e.documentType,...e.issuer!==void 0?{issuer:e.issuer}:{},width:b.width,height:b.height,previewDataUrl:a}),t.deferRead!==!0&&L({type:"readOk",side:y})}catch(b){L({type:"readFailed",side:y,id:w,issue:"technical"}),n.emit("error",j("generic",!0,{phase:"keyframes",name:te(b)}))}Q(y==="recto"?"verso":"recto")},it=o=>{X.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 h=a.quad===null?0:Rt(a.quad,a.frameWidth,a.frameHeight);A=a.quad===null?null:{quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight},L({type:"report",report:{present:a.quad!==null&&a.plausible||a.guide?.detected===!0,ready:a.ready===!0,locking:a.p>=.5,areaFrac:h},at:c()})}),o.on("error",({kind:a,retryable:m,detail:h})=>n.emit("error",j(a,m,h))),o.on("artifacts",a=>{ot(a.keyframe,a.previewDataUrl,a.docRegion,a.liveMrz)}))},ee=()=>(T??(T=(async()=>{if(C){if(ge(),f===null){let o;try{o=await(t.createEngine??xt)({...t.engineOptions??{},...B!==void 0?{guide:B}:{},video:e.video,format:s.format,side:p?"single":e.side??"recto",autoCapture:!1,...Y!==null?{ocr:Y}:{}})}catch(m){W("error"),n.emit("error",j("models",!0,{phase:"models",name:te(m)}));return}if(!C){o.destroy();return}f=o,it(o);let a=t.tickMs??500;a>0&&(O=setInterval(()=>L({type:"tick",at:c()}),a))}L({type:"clockRestart"}),x!==null&&x.liveMrzArm==="live"&&(U==="unsupported"||U==="off")&&N({state:"fallback",reason:U}),await f.start()}})().finally(()=>{T=null})),T);return{handle:{get state(){return M},on:(o,a)=>n.on(o,a),start:ee,retry:()=>{if(f===null&&l.phase==="result"){L({type:"retake"}),P=0,d=!1,ee();return}if(f!==null&&M!=="error"){L({type:"retake"}),P=0,d=!1,f.rearm(p?"single":void 0);return}ee()},setSide:o=>{p||o==="single"||(l.current!==o&&(l={...l,current:o}),L({type:"clockRestart"}),l.phase!=="reading"&&l.phase!=="result"&&f?.rearm(o))},shutter:ye,focusAt:(o,a)=>{f?.focusAt?.(o,a)},setGuide:o=>{B=o,f?.setGuide?.(o)},setTorch:o=>{g=o,f?.setTorch(o),L({type:"tick",at:c()})},destroy:()=>{if(C&&f!==null&&M!=="done"){let o=Me();!Z&&o!==void 0&&o.ticks>0&&De(o,"abandoned"),be(o,void 0)}C=!1,Se(),Y?.setEngine(null),G?.dispose(),G=null,n.clear()}},plan:s,setFlowState:o=>{(l.phase==="reading"||l.phase==="result")&&W(o==="done"&&l.phase!=="result"?"scanning":o)},settle:(o,a)=>{let m=o==="verso"?"verso":"recto";L(a.ok?{type:"readOk",side:m}:{type:"readFailed",side:m,issue:a.issue}),a.ok||Q(m)},takeDeviceRead:o=>he.get(o.image)?.value??null}}export{Ft as a,zt as b,Ut as c,Nt as d,Gt as e,qt as f,ze as g,ie as h,qe as i,St as j,Mt as k,Xt as l,He as m,Vt as n,H as o,$e as p,Je as q,kt as r,Ze as s,me as t,Ct as u,hn as v,bn as w,Pt as x};
@@ -1,3 +1,3 @@
1
- import{B as ft,C as mt,D as ht,E as yt,a as ot,b as rt,c as it,d as Z,e as J,f as re,g as st,h as K,i as at,j as I,k as j,l as T,m as D,n as U,o as X,p as ut,q as z,r as ie,s as ct,t as dt,u as lt,v as pt}from"./chunk-IMFHLLKO.js";import{n as et}from"./chunk-JQIDW5SX.js";import{a as ze}from"./chunk-7QZWBDI5.js";import{c as G,e as tt,g as nt,h as se}from"./chunk-Y25KN6OM.js";import{c as Je,d as _e}from"./chunk-TSA6GHUG.js";import{b as Xe}from"./chunk-LRIYZH6A.js";function ae(e){return e.idNumberBound??e.nniBound}function ee(e){return e===void 0?void 0:e.idNumberFromDocument??e.nniFromDocument}function gt(e){let t=e.idNumberMasked??e.nniMasked;return typeof t=="string"&&t!==""?t:void 0}var Jt="https://api.sekyro.ai",Xt=5e3,zt=24e4,en=9e4,tn=25*6e4,nn=20*6e4,on=3,rn=3e3,sn=1500,an=10;function St(e){return e instanceof Error&&e.name==="ChallengeError"&&e.code||"challenge_failed"}var _t=new Set(["aborted","embedder_opaque","site_key_rejected"]);function un(e){return new Promise(t=>setTimeout(t,e))}function cn(){let e=globalThis.crypto;if(e!==void 0&&typeof e.randomUUID=="function")return e.randomUUID();let t=new Uint8Array(16);if(e!==void 0&&typeof e.getRandomValues=="function")e.getRandomValues(t);else for(let i=0;i<16;i+=1)t[i]=Math.floor(Math.random()*256);t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let n=[...t].map(i=>i.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function wo(e){return dn(e,{})}function dn(e,t){let n=e.apiOrigin??Jt,i=e.autoRetry??!0,r=e.rearm??"auto",u=t.client??new nt({apiOrigin:n,sessionToken:e.clientToken,fetch:e.fetch,locale:e.locale}),a=new Proxy(u,{get(o,s){if(s==="submitCheck")return Ut;let c=Reflect.get(o,s,o);return typeof c=="function"?c.bind(o):c}}),d=t.sleep??un,h=t.uuid??cn,_=t.getChallengeToken??((o,s)=>import("./challenge-frame-YBTLAQ5G.js").then(c=>c.executeChallenge({frameUrl:o.url,siteKey:o.siteKey,action:"liveness",subject:s.subject,signal:s.signal}))),S=ze(),P=null,g=null,m=!1,M=new AbortController,y=null,ce=null,te=null,ne=()=>te??ct(y),Re=()=>dt(ie(y),ne()),O=o=>{y=o,!I(o)&&(Be(nn)||Lt(o))&&Se(o),S.emit("view",o),P?.onView(o)},A=()=>y!==null?Promise.resolve(y):(ce??(ce=a.getSession().then(o=>(O(o),o)).finally(()=>{ce=null})),ce),E=async()=>{let o=await a.getSession();return O(o),o},de=async(o,s)=>{o.plan!==void 0?O(o):await E()},le=null,Ie=async o=>{let s=await A();if(o||!s.consentRecorded){let c=await a.recordConsent(e.locale);c.plan!==void 0?O(c):y!==null&&O({...y,consentRecorded:!0})}oe()&&Se(s)},F=o=>o?.force===!0?Ie(!0):(le??(le=Ie(!1).finally(()=>{le=null})),le),pe={client:a,ensureConsent:o=>F(o),sleep:d,uuid:h,...t.random!==void 0?{random:t.random}:{},onBusy:o=>{m||S.emit("busy",o)}},Me=!1,Oe=null,fe=o=>{if(o.status==="verified"||o.status==="not_verified"||o.status==="review"){if(Me)return;Me=!0}Oe=JSON.stringify(o),S.emit("result",o)},Ft=o=>{Oe!==JSON.stringify(o)&&fe(o)},Ee=async o=>{let s=y;o&&(s=await E().catch(()=>y));let c=s===null?null:K(s);return c!==null&&!m&&S.emit("method",c),c!==null},ve=null,Te=!1,Ve=!1,Fe=()=>mt(pe,(o,s)=>o.submitCheck("population_registry",{},{idempotencyKey:s})),Ne=o=>ae(o)===!0||ee(T(o,"population_registry"))===!0,Nt=async()=>{try{let o=await A();if(I(o)||K(o)!==null||j(o)?.checkType!=="population_registry")return;if(!Ne(o)&&ee(T(o,"population_registry"))===void 0&&(o=await E()),!Ne(o)){Ve=!0;return}await F(),await de(await Fe(),"population_registry");let s=y===null?void 0:T(y,"population_registry");if(s?.state==="input_required"&&s.reason==="registry_unavailable"&&re(s)>0){if(await d(Xt),m)return;await de(await Fe(),"population_registry")}}catch(o){if(o instanceof G&&(o.code==="check_not_active"||o.code==="step_not_on_path")){await E().catch(()=>{});return}Te=!0;return}y!==null&&I(y)&&fe(X(y,{autoRetry:i}))},He=()=>(ve??(ve=Nt()),ve),v=t.now??Date.now,q=null,Y,me,Ht=0,he=(o,s)=>`${o.url}
1
+ import{B as ft,C as mt,D as ht,E as yt,a as ot,b as rt,c as it,d as Z,e as J,f as re,g as st,h as K,i as at,j as I,k as j,l as T,m as D,n as U,o as X,p as ut,q as z,r as ie,s as ct,t as dt,u as lt,v as pt}from"./chunk-K7ICBHSZ.js";import{n as et}from"./chunk-NMPMXAH3.js";import{a as ze}from"./chunk-7QZWBDI5.js";import{c as G,e as tt,g as nt,h as se}from"./chunk-VZGTOE22.js";import{c as Je,d as _e}from"./chunk-TSA6GHUG.js";import{b as Xe}from"./chunk-AIRC3HT7.js";function ae(e){return e.idNumberBound??e.nniBound}function ee(e){return e===void 0?void 0:e.idNumberFromDocument??e.nniFromDocument}function gt(e){let t=e.idNumberMasked??e.nniMasked;return typeof t=="string"&&t!==""?t:void 0}var Jt="https://api.sekyro.ai",Xt=5e3,zt=24e4,en=9e4,tn=25*6e4,nn=20*6e4,on=3,rn=3e3,sn=1500,an=10;function St(e){return e instanceof Error&&e.name==="ChallengeError"&&e.code||"challenge_failed"}var _t=new Set(["aborted","embedder_opaque","site_key_rejected"]);function un(e){return new Promise(t=>setTimeout(t,e))}function cn(){let e=globalThis.crypto;if(e!==void 0&&typeof e.randomUUID=="function")return e.randomUUID();let t=new Uint8Array(16);if(e!==void 0&&typeof e.getRandomValues=="function")e.getRandomValues(t);else for(let i=0;i<16;i+=1)t[i]=Math.floor(Math.random()*256);t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let n=[...t].map(i=>i.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function xo(e){return dn(e,{})}function dn(e,t){let n=e.apiOrigin??Jt,i=e.autoRetry??!0,r=e.rearm??"auto",u=t.client??new nt({apiOrigin:n,sessionToken:e.clientToken,fetch:e.fetch,locale:e.locale}),a=new Proxy(u,{get(o,s){if(s==="submitCheck")return Ut;let c=Reflect.get(o,s,o);return typeof c=="function"?c.bind(o):c}}),d=t.sleep??un,h=t.uuid??cn,_=t.getChallengeToken??((o,s)=>import("./challenge-frame-YBTLAQ5G.js").then(c=>c.executeChallenge({frameUrl:o.url,siteKey:o.siteKey,action:"liveness",subject:s.subject,signal:s.signal}))),S=ze(),P=null,g=null,m=!1,M=new AbortController,y=null,ce=null,te=null,ne=()=>te??ct(y),Re=()=>dt(ie(y),ne()),O=o=>{y=o,!I(o)&&(Be(nn)||Lt(o))&&Se(o),S.emit("view",o),P?.onView(o)},x=()=>y!==null?Promise.resolve(y):(ce??(ce=a.getSession().then(o=>(O(o),o)).finally(()=>{ce=null})),ce),E=async()=>{let o=await a.getSession();return O(o),o},de=async(o,s)=>{o.plan!==void 0?O(o):await E()},le=null,Ie=async o=>{let s=await x();if(o||!s.consentRecorded){let c=await a.recordConsent(e.locale);c.plan!==void 0?O(c):y!==null&&O({...y,consentRecorded:!0})}oe()&&Se(s)},F=o=>o?.force===!0?Ie(!0):(le??(le=Ie(!1).finally(()=>{le=null})),le),pe={client:a,ensureConsent:o=>F(o),sleep:d,uuid:h,...t.random!==void 0?{random:t.random}:{},onBusy:o=>{m||S.emit("busy",o)}},Me=!1,Oe=null,fe=o=>{if(o.status==="verified"||o.status==="not_verified"||o.status==="review"){if(Me)return;Me=!0}Oe=JSON.stringify(o),S.emit("result",o)},Ft=o=>{Oe!==JSON.stringify(o)&&fe(o)},Ee=async o=>{let s=y;o&&(s=await E().catch(()=>y));let c=s===null?null:K(s);return c!==null&&!m&&S.emit("method",c),c!==null},ve=null,Te=!1,Ve=!1,Fe=()=>mt(pe,(o,s)=>o.submitCheck("population_registry",{},{idempotencyKey:s})),Ne=o=>ae(o)===!0||ee(T(o,"population_registry"))===!0,Nt=async()=>{try{let o=await x();if(I(o)||K(o)!==null||j(o)?.checkType!=="population_registry")return;if(!Ne(o)&&ee(T(o,"population_registry"))===void 0&&(o=await E()),!Ne(o)){Ve=!0;return}await F(),await de(await Fe(),"population_registry");let s=y===null?void 0:T(y,"population_registry");if(s?.state==="input_required"&&s.reason==="registry_unavailable"&&re(s)>0){if(await d(Xt),m)return;await de(await Fe(),"population_registry")}}catch(o){if(o instanceof G&&(o.code==="check_not_active"||o.code==="step_not_on_path")){await E().catch(()=>{});return}Te=!0;return}y!==null&&I(y)&&fe(X(y,{autoRetry:i}))},He=()=>(ve??(ve=Nt()),ve),v=t.now??Date.now,q=null,Y,me,Ht=0,he=(o,s)=>`${o.url}
2
2
  ${o.siteKey}
3
- ${s}`,Le=0,ye,ge=(o,s)=>{Le+=1;let c=v(),f=_(o,{signal:M.signal,subject:s}),p={key:he(o,s),at:c,token:f};return f.then(()=>{p.issuedAt=v(),me=void 0},k=>{let C=St(k);if(p.failed=C,m||C==="aborted")return;me=C;let{detail:w,readyMs:l}=k;W({check:"attestation",kind:"unavailable",engineKind:C,attempt:Ht++,challengeMs:v()-c,readyMs:l,detail:w,inApp:Xe()})}),f.catch(()=>{}),p},De=(o,s)=>o!==null&&o.key===s&&(o.issuedAt===void 0||v()-o.issuedAt<zt),Se=(o,s={})=>{let c=o?.challenge??null;if(o===null||c===null||m)return;let f=D(o.sessionId),p=q;(s.replaceFailed===!0&&p?.failed!==void 0&&!_t.has(p.failed)||!De(p,he(c,f)))&&(q=ge(c,f))},Ue=async(o,s)=>{let c=he(o,s),f=q;q=null;let p=De(f,c)?f:ge(o,s),k=p===f?0:1,C,w=new Promise(l=>{C=setTimeout(()=>l("late"),en)});try{for(;;){let l=await Promise.race([p.token.then(x=>({token:x}),x=>({error:St(x)})),w]);if(l==="late")return!m&&q===null&&(q=p),{error:me??"timeout"};if("token"in l)return ye=Math.max(0,Math.round((p.issuedAt??v())-p.at)),l;if(m||_t.has(l.error)||k>=on||k>0&&await Promise.race([d(rn*k),w])==="late")return l;if(m)return{error:"aborted"};k+=1,p=ge(o,s)}}finally{clearTimeout(C)}},H=null,Lt=o=>J(o).some(s=>(s.checkType==="phone_otp"||s.checkType==="email_otp")&&s.state!=="passed"&&s.state!=="skipped"),Be=o=>H===null||v()-H>=o,oe=()=>Be(tn),Dt=o=>{let s=o.attestation;return typeof s?.turnstileToken=="string"&&s.turnstileToken.length>0},qe=new Map,Ge=async()=>{let o=await A(),s=o.challenge;if(s==null||o.simulation!==void 0)return;let c=await Ue(s,D(o.sessionId));if(!("token"in c))throw new G({status:400,code:"attestation_invalid",message:`browser check: ${c.error}`});return c.token},Ut=async(o,s,c={})=>{let f=s;if("attestation"in f)try{let l=await u.submitCheck(o,s,c);return Dt(f)&&(H=v()),l}catch(l){throw l instanceof G&&l.code==="attestation_invalid"&&(H=null),l}let p=(o==="phone_otp"||o==="email_otp")&&f.action!=="verify",k=c.idempotencyKey,C=k!==void 0?qe.get(k):void 0;C===void 0&&(p||oe())&&(C=await Ge(),k!==void 0&&C!==void 0&&qe.set(k,C));let w=(l,x)=>l!==void 0?{...x,browserCheckToken:l}:x;try{let l=await u.submitCheck(o,s,w(C,c));return C!==void 0&&(H=v()),l}catch(l){if(!(l instanceof G)||l.code!=="attestation_invalid"||(H=null,C!==void 0))throw l;let x=await Ge(),L=k!==void 0?{...c,idempotencyKey:h()}:c,N=await u.submitCheck(o,s,w(x,L));return x!==void 0&&(H=v()),N}},Ke=async(o={})=>{if(Y=void 0,o.always!==!0&&!oe())return{};let s=await A(),c=s.challenge;if(c==null)return{};let f=await Ue(c,D(s.sessionId));if("token"in f)return{channel:"hosted_web",turnstileToken:f.token};if(Y=f.error,s.simulation!==void 0)return{channel:"hosted_web"};throw new ft(f.error)},Bt=()=>Y,qt=()=>({checks:Math.min(50,Le),...ye!==void 0?{challengeMs:Math.min(6e5,ye)}:{}}),W=o=>{if(m)return;let s=a.reportCaptureIssue;if(s===void 0)return;let c=o.formFactor;try{c??(c=Je())}catch{}try{Promise.resolve(s.call(a,{...o,...c!==void 0?{formFactor:c}:{}})).catch(()=>{})}catch{}},R=null,$=null,je=new WeakMap,Ye=Promise.resolve(),Q=0,Gt=async()=>{let o=await A();for(let s=0;s<an&&!m&&!I(o)&&j(o)===void 0&&J(o).some(c=>c.state==="processing")&&(await d(sn),!m);s+=1)o=await E();return o},Kt=async(o,s,c)=>{let{capture:f}=o,p=()=>m,k=()=>o.alive&&o.attempt===c,C=l=>{k()&&f.setFlowState(l)},w=l=>{if(!p()&&(l.status==="unavailable"&&l.reasonCode!==void 0&&!ot(l.reasonCode)&&W({check:"liveness",kind:"unavailable",phase:"upload",engineKind:l.reasonCode,attempt:Math.max(0,o.issues.value)}),fe(l),!!k())){if(l.status==="retry"&&r==="auto"){f.handle.retry();return}f.setFlowState("done")}};if(s.degraded==="NO_RECORDER"){let l=y?.sessionId??(await A().catch(()=>null))?.sessionId??"";w(U(l,"no_recorder"));return}C("uploading");try{if(await He(),p())return;let l=await A(),x;if(!I(l)&&K(l)!==null){await Ee(!1),w(U(l.sessionId,"method_required"));return}if(!I(l)){if(j(l)?.checkType==="population_registry"){w(U(l.sessionId,Ve?"nni_unbound":Te?"network":"registry_unavailable"));return}if(await F(),p())return;x=y??l;let L=await ht({...pe,artifacts:s,getAttestation:Ke,attestationError:Bt,attestationFacts:qt,clipKeys:{get:()=>je.get(s)??null,set:N=>{je.set(s,N)}},getView:()=>y??l,refreshView:E,applySubmit:de,onPhase:C,isCancelled:p,onKeyframePromoted:N=>{g=N}});if(p())return;if(L.kind==="unavailable"){L.reason==="attestation"&&($={bound:o,artifacts:s});let N=U(l.sessionId,L.reason),Ze=L.reason==="attestation"?Y:void 0;w(Ze!==void 0?{...N,attestationError:Ze}:N);return}if(L.kind==="resync"&&await E(),y!==null&&K(y)!==null){await Ee(!1),w(U(l.sessionId,"method_required"));return}l=await Gt()}w(X(l,{autoRetry:i,previous:x}))}catch{if(p())return;w(U(y?.sessionId??"","network"))}},We=(o,s)=>{let c=o.attempt;Q>0&&o.alive&&o.capture.setFlowState("uploading"),Q+=1,Ye=Ye.then(()=>Kt(o,s,c)).finally(()=>{Q-=1,Q===0&&P?.onChainIdle()}).catch(()=>{})},$e=o=>{R?.capture.handle.destroy(),R!==null&&(R.alive=!1);let s=et(o,P?.captureInternals?.(o)??t.capture,()=>y?.capture?.liveness?.keyframe?.rank===!0,Re,()=>y?.capture?.liveness?.screenRamp,{session:()=>ie(y),onModeChange:p=>{te=p}}),c={capture:s,alive:!0,attempt:0,issues:it()};R=c,s.handle.on("error",p=>{W(rt("liveness",p,c.issues.value))}),s.handle.on("state",p=>{if(c.issues.note(p),p==="starting"){c.attempt+=1,$?.bound===c&&($=null),oe()&&Se(y,{replaceFailed:!0});let k=y===null?void 0:j(y)?.checkType;(k==="liveness"||k==="face_match")&&F().catch(()=>{})}}),s.handle.on("captured",p=>{Promise.resolve().then(()=>We(c,p))});let f=s.handle;return{get state(){return f.state},get captureMode(){return f.captureMode},get facingMode(){return f.facingMode},on:(p,k)=>f.on(p,k),start:async p=>{if(y===null&&await A().catch(()=>{}),!!c.alive)return f.start(p)},retry:()=>{let p=$;if(p!==null&&p.bound===c&&c.alive){$=null,We(c,p.artifacts);return}f.retry()},switchCamera:()=>f.switchCamera(),canSwitchCaptureMode:()=>f.canSwitchCaptureMode(),setCaptureMode:p=>f.setCaptureMode(p),destroy:()=>{c.alive=!1,R===c&&(R=null),f.destroy()}}},jt=async()=>{if(m)return null;try{let o=await A();return m?null:K(o)}catch{return null}},Yt=async()=>{if(m)return"self";try{let o=await A();if(m)return"self";let s=ie(o);return s==="choice"?ne()??s:s}catch{return"self"}},Wt=async()=>{if(m)return!1;try{let o=await A();return m||I(o)||_e()?!1:z(o,j(o))==="phone"||z(o,T(o,"liveness"))==="phone"}catch{return!1}},$t=async()=>{if(m)return!1;try{let o=await A();return!m&&o.returning===!0}catch{return!1}},Qt=async o=>{let s=(await A()).plan?.choice,c=s?.options.find(p=>Z[p.service]===o);if(!c)throw new RangeError(`method ${String(o)} is not offered`);let f=await a.choose(s.nodeId,c.id);m||O(f)},Qe=null,Zt=()=>(Qe??(Qe=import("./plan-runner-HPXZHAQB.js").then(o=>{let s=o.createPlanRunner({runtime:pe,currentView:()=>y,cameraMode:Re,captureModeSwitch:{pick:ne,choose:c=>{te=c}},ensureView:A,refreshView:E,ensureConsent:()=>F(),liveness:$e,stopLiveness:()=>{R!==null&&(R.alive=!1,R.capture.handle.destroy(),R=null)},chainBusy:()=>Q>0,destroyed:()=>m,sleep:d,isMobile:_e,now:t.now??Date.now,keptFaceKey:()=>g,setView:O,baseCapture:t.capture,emitStep:c=>{m||S.emit("step",c)},emitResult:Ft,reportCaptureIssue:W,documentInternals:t.document,documentFacts:t.documentFacts,portraitInternals:t.portrait,livePhotoInternals:t.livePhoto,uploadInternals:t.upload,pageCameraInternals:t.pageCamera});return P=s,s})),Qe);return{consent:()=>F(),startRegistry:He,methodChoice:jt,selectMethod:Qt,reportCameraUnavailable:async o=>{await F();let s=a.reportCameraUnavailable;if(s===void 0)throw new TypeError("this client cannot report a missing camera");let c=await s.call(a,o).catch(f=>{if(f instanceof G&&f.code==="check_out_of_order")return a.getSession();throw f});m||O(c)},reportCaptureIssue:W,testerGate:async o=>{let s=a.testerGate;if(s===void 0)throw new TypeError("this client cannot run the tester gate");let c=o.clip,f=tt(o.clipMime??"");if(c===void 0||!pt.includes(f))throw new TypeError("the capture has no clip");await F();let p=await lt(a,"clip",f,c.size,{engine:o.engine,durationMs:o.clipMs});await a.uploadToSpaces(p.uploadUrl,c,f);let{key:k}=await a.completeMedia(p.key),C=await Ke({always:!0}),w=await s.call(a,{clipKey:k,attestation:C,captureChannel:o.captureChannel,capture:{...yt(o),attestationError:Y}}),{bound:l,...x}=w;return m||(x.plan!==void 0?O(x):await E()),{bound:l===!0}},mobileRequired:Wt,captureMode:Yt,chooseCaptureMode:o=>{te=o},get captureChoice(){return ne()},returning:$t,liveness:$e,run:async()=>{if(m)throw new Error("verification destroyed");return(await Zt()).run()},currentStep:()=>P?.current()??null,voiceClips:async()=>{if(m)return null;try{let o=await A();return m?null:o.voice??null}catch{return null}},on:(o,s)=>S.on(o,s),destroy:()=>{m=!0,M.abort(),P?.destroy(),R!==null&&(R.alive=!1,R.capture.handle.destroy(),R=null),S.clear()}}}var kt=["AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AS","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CW","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IR","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","XK","YE","YT","ZA","ZM","ZW"];var ln=["carte_identite","passport","residence_permit","drivers_license"],pn=["carte_identite","passport","residence_permit"];function fn(e,t){let n=e.byIssuer?.[t]??e.default;return ln.filter(i=>n==="*"?pn.includes(i):n.includes(i))}function Ro(e,t=kt){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(i=>fn(e,i).length>0).sort()}function Ct(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}function Io(e){return/^[A-Z]{2}$/.test(e)?String.fromCodePoint(...[...e].map(t=>127462+t.charCodeAt(0)-65)):""}var b={fullNameMin:2,fullName:200,email:254,occupation:120,shortText:120,longText:1e3,addressLine:120,addressLines:4,city:80,postcode:16,number:1e12,dateMin:"1900-01-01",dateMax:"2100-12-31"},mn=new Set(["full_name","birth_date","email","phone","address","country","occupation"]),hn=new Set(["short_text","long_text","single_choice","multiple_choice","yes_no","date","number"]),yn=new Set(["ar","fa","he","ur"]);function bt(e){return yn.has(e.split("-")[0]?.toLowerCase()??"")?"rtl":"ltr"}function wt(e){if(typeof e!="object"||e===null)return null;let t=e;if(typeof t.locale!="string"||!Array.isArray(t.questions)||t.questions.length===0)return null;let n=t.consents??[];if(!Array.isArray(n))return null;for(let r of t.questions)if(!gn(r))return null;for(let r of n)if(!Sn(r))return null;let i={locale:t.locale,questions:t.questions,consents:n};return typeof t.title=="string"&&t.title.trim()!==""&&(i.title=t.title),typeof t.intro=="string"&&t.intro.trim()!==""&&(i.intro=t.intro),typeof t.prefill=="object"&&t.prefill!==null&&!Array.isArray(t.prefill)&&(i.prefill=t.prefill),i}function gn(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id!="string"||typeof t.required!="boolean"?!1:t.kind==="field"?typeof t.field=="string"&&mn.has(t.field):t.kind!=="custom"||typeof t.type!="string"||!hn.has(t.type)||typeof t.label!="string"?!1:t.type==="single_choice"||t.type==="multiple_choice"?Array.isArray(t.choices)&&t.choices.length>=2&&t.choices.every(n=>typeof n=="object"&&n!==null&&typeof n.value=="string"&&typeof n.label=="string"):!0}function Sn(e){if(typeof e!="object"||e===null)return!1;let t=e;if(typeof t.id!="string"||typeof t.required!="boolean"||typeof t.text!="string")return!1;if(t.link===void 0)return!0;let n=t.link;return typeof n=="object"&&n!==null&&typeof n.url=="string"&&/^https:\/\//.test(n.url)&&typeof n.label=="string"}var _n=/^(\d{4})-(\d{2})-(\d{2})$/;function kn(e){if(typeof e!="string")return!1;let t=_n.exec(e);return t===null?!1:new Date(Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3]))).toISOString().slice(0,10)===e&&e>=b.dateMin&&e<=b.dateMax}function Cn(e){return typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<b.number&&Math.round(e*100)/100===e}function At(e){for(let t of e.matchAll(/\d[\d -]{11,}\d/g)){let n=t[0].replace(/[ -]/g,"");if(n.length>=13&&n.length<=19&&bn(n))return!0}return!1}function bn(e){let t=0;for(let n=0;n<e.length;n++){let i=Number(e[e.length-1-n]);n%2===1&&(i*=2,i>9&&(i-=9)),t+=i}return t%10===0}var wn=/^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$/,An=/^\+[1-9]\d{6,14}$/,xt=/^[A-Z]{2}$/,xn=e=>e===void 0||typeof e=="string"&&e.trim()===""||Array.isArray(e)&&e.length===0;function Pn(e=Date.now()){return new Date(e).toISOString().slice(0,10)}function Oo(e,t,n=Pn()){let i=[];for(let r of e.questions){let u=t.answers[r.id];if(xn(u)){r.required&&i.push({id:r.id,code:"required"});continue}let a=r.kind==="field"?Rn(r.field,u,n):Mn(r,u,n);a!==null&&i.push({id:r.id,...a})}for(let r of e.consents)r.required&&t.consents[r.id]!==!0&&i.push({id:r.id,code:"consent_required"});return i}function ue(e,t,n=1){if(typeof e!="string")return{code:"required"};let i=e.trim();return[...i].length>t?{code:"too_long",params:{max:t}}:[...i].length<n?{code:"too_short",params:{min:n}}:At(i)?{code:"card_number"}:null}function Pt(e,t,n={}){return kn(e)?n.period==="past"&&e>=t?{code:"date_not_past"}:n.period==="future"&&e<=t?{code:"date_not_future"}:n.min!==void 0&&e<n.min?{code:"date_too_early",params:{date:n.min}}:n.max!==void 0&&e>n.max?{code:"date_too_late",params:{date:n.max}}:null:{code:"date_invalid"}}function Rn(e,t,n){switch(e){case"full_name":return ue(t,b.fullName,b.fullNameMin);case"occupation":return ue(t,b.occupation);case"birth_date":return Pt(t,n,{period:"past"});case"email":return typeof t=="string"&&t.trim().length<=b.email&&wn.test(t.trim())?null:{code:"email_invalid"};case"phone":return typeof t=="string"&&An.test(t)?null:{code:"phone_invalid"};case"country":return typeof t=="string"&&xt.test(t)?null:{code:"choice_invalid"};case"address":return In(t)?null:{code:"address_invalid"};default:return null}}function In(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e,n=Array.isArray(t.lines)?t.lines.filter(i=>typeof i=="string"&&i.trim()!==""):[];return typeof t.country=="string"&&xt.test(t.country)&&typeof t.city=="string"&&t.city.trim()!==""&&t.city.trim().length<=b.city&&n.length>=1&&n.length<=b.addressLines&&n.every(i=>i.trim().length<=b.addressLine&&!At(i))&&(t.postcode===void 0||typeof t.postcode=="string"&&t.postcode.trim().length<=b.postcode)}function Mn(e,t,n){let i=new Set((e.choices??[]).map(r=>r.value));switch(e.type){case"short_text":return ue(t,b.shortText);case"long_text":return ue(t,b.longText);case"single_choice":return typeof t=="string"&&i.has(t)?null:{code:"choice_invalid"};case"multiple_choice":return Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(r=>i.has(r))?null:{code:"choice_invalid"};case"yes_no":return typeof t=="boolean"?null:{code:"choice_invalid"};case"date":{let r=e.options??{};return Pt(t,n,{...typeof r.min=="string"?{min:r.min}:{},...typeof r.max=="string"?{max:r.max}:{},...r.period==="past"||r.period==="future"?{period:r.period}:{}})}case"number":{if(typeof t!="number"||!Number.isFinite(t)||Math.abs(t)>=b.number)return{code:"number_invalid"};let r=e.options??{};return r.integer===!0&&!Number.isInteger(t)?{code:"number_not_integer"}:Cn(t)?typeof r.min=="number"&&t<r.min?{code:"number_too_small",params:{min:r.min}}:typeof r.max=="number"&&t>r.max?{code:"number_too_large",params:{max:r.max}}:null:{code:"number_decimals"}}default:return null}}var Eo={full_name:b.fullName,occupation:b.occupation,email:b.email,short_text:b.shortText,long_text:b.longText};var Rt=Object.freeze({nni_invalid:"id_number_invalid",nni_not_found:"registry_record_not_found",nni_recheck:"id_number_recheck",document_nni_mismatch:"document_id_number_mismatch",nni_locked:"id_number_locked",nni_unbound:"id_number_unbound",missing_nni:"missing_id_number",registry_needs_nni_source:"registry_needs_id_number_source"}),On=new Map(Object.entries(Rt)),To=new Map(Object.entries(Rt).map(([e,t])=>[t,e]));function It(e){return On.get(e)??e}var qo=["national_number","document_photo","national_eid"],En=new Set(["phone_otp","email_otp","national_eid","document","nfc","population_registry","supplied_identity","summary_confirm","liveness","portrait","face_match","aml_screening","face_dedup","age_estimation","proof_of_address","form"]),vn=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),Ce=["document","population_registry","national_eid"],be=["phone_otp","email_otp"],Et={identity_method:Ce,contact:be},Tn=["population_registry","document"],we="platform_unsupported",Vn=new Set(["prefilled","user_entered","prefilled_or_entered"]),Fn={phone_otp:"contact",email_otp:"contact",eid_auth:"identity",doc_ocr:"identity",nfc_chip:"identity",population_registry:"identity",liveness:"live_photo",portrait_icao:"live_photo",face_match:"live_photo",poa:"documents",form:"form"};function V(e){return e.section??Fn[e.checkType]??null}function Nn(e,t){let n=e.plan?.choice;if(n===void 0||n.locked)return;let i=n.options.find(r=>r.id!==n.selected&&r.available!==!1&&t.includes(r.service));return i===void 0?void 0:{nodeId:n.nodeId,option:i}}function Ae(e){let t=e.plan,n=t?.choice;if(t===void 0||n===void 0||n.locked||t.current===null||t.current===n.nodeId||I(e))return null;let i=Et[n.kind]??[...Ce,...be],r=n.options.flatMap(d=>d.available===!1||!i.includes(d.service)?[]:[d.nationalEid!=null?{id:d.id,service:d.service,nationalEid:d.nationalEid}:{id:d.id,service:d.service}]),u=t.steps.find(d=>d.id===t.current)?.service,a=n.selected??r.find(d=>d.service===u)?.id??null;return r.some(d=>d.id!==a)?{nodeId:n.nodeId,kind:n.kind,current:a,options:r}:null}function vt(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function Hn(e){let t=e.simulation;if(typeof t!="object"||t===null)return;let{otpCode:n,skipCapture:i}=t;if(typeof n!="string"||n===""||typeof i!="boolean")return;let r=ut(e);return r!==void 0?{otpCode:n,skipCapture:i,reason:r}:{otpCode:n,skipCapture:i}}function Ln(e){let t=(e.plan?.sections??[]).map(a=>({id:a.id,state:a.state})),n={sessionId:D(e.sessionId),orgName:e.orgName,sandbox:e.sandbox===!0,returning:e.returning===!0,consentRecorded:e.consentRecorded,expiresAt:e.expiresAt,sections:t.map(a=>a.id),progress:t,purpose:e.purpose??"identity"};e.branding!==void 0&&(n.branding=e.branding),e.cameraUnavailableHandled===!0&&(n.cameraUnavailableHandled=!0);let i=Hn(e);i!==void 0&&(n.simulation=i);let r=e.testerGate;r?.offered===!0&&typeof r.attemptsLeft=="number"&&r.attemptsLeft>0&&(n.testerGate={attemptsLeft:r.attemptsLeft});let u=Ae(e);return u!==null&&(n.switchable=u),n}function Dn(e){let t={attemptsRemaining:re(e),attemptsExhausted:e.attempts.used>=e.attempts.max};return e.reason!==void 0&&(t.reason=e.reason),e.retakeHint!==void 0&&(t.retakeHint=e.retakeHint),t}var Tt={phone_otp:"phone",email_otp:"email"};function Un(e,t){let n=Nn(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return n===void 0?void 0:Tt[n.option.service]}function Bn(e,t,n,i){let r=t.checkType==="email_otp",u=(r?t.emailOtp:t.otp)??{},a=r?t.emailOtp?.emailSource:t.otp?.numberSource,d=a!==void 0&&Vn.has(a)?a:r?"prefilled_or_entered":"user_entered",h=typeof u.sentToMasked=="string"&&u.sentToMasked.length>0,_=u.prefilled===!0,S=Un(e,r?"email_otp":"phone_otp"),P={key:t.checkType,context:n,section:V(t),phase:h?"verify":"send",canSwitch:S!==void 0,...i},g=r?{kind:"email_otp",...P,emailSource:d,needsEmail:d!=="prefilled"&&!_}:{kind:"phone_otp",...P,numberSource:d,needsPhone:d!=="prefilled"&&!_,channels:(t.otp?.channels??[]).filter(m=>m==="whatsapp"||m==="sms")};if(S!==void 0&&(g.switchChannel=S),_&&(g.prefilled=!0),h&&(g.sentToMasked=u.sentToMasked),!r&&t.otp?.channel!==void 0&&(g.channel=t.otp.channel),!r&&Array.isArray(t.phoneCountries)&&(g.phoneCountries=t.phoneCountries.filter(m=>typeof m=="string"&&/^[A-Z]{2}$/.test(m))),!r&&Array.isArray(t.phoneRules)){let m=g.phoneCountries??[];g.phoneRules=t.phoneRules.flatMap(M=>{let y=Kn(M);return y!==void 0&&m.includes(y.code)?[y]:[]})}return!r&&t.phoneInternational===!0&&(g.phoneInternational=!0),u.expiresAt!==void 0&&(g.codeExpiresAt=u.expiresAt),u.resendAvailableAt!==void 0&&(g.resendAvailableAt=u.resendAvailableAt),g}var qn=/^[\d[\]\-|()?:^]{1,64}$/;function Gn(e){try{return typeof e=="string"&&qn.test(e)&&new RegExp(e)!==null}catch{return!1}}var Mt=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function Kn(e){let{code:t,dial:n,trunk:i,lengths:r,formats:u}=e??{};if(typeof t!="string"||typeof n!="string"||!/^\d{1,3}$/.test(n)||i!==void 0&&(typeof i!="string"||!/^\d{1,3}$/.test(i))||!Array.isArray(r)||r.length===0||!r.every(Mt))return;let a={code:t,dial:n,lengths:[...r].sort((d,h)=>d-h)};if(i!==void 0&&(a.trunk=i),u!==void 0){if(!(Array.isArray(u)&&u.length<=8&&u.every(h=>Gn(h?.leading)&&Array.isArray(h.groups)&&h.groups.every(Mt)&&r.includes(h.groups.reduce((_,S)=>_+S,0)))))return;a.formats=u.map(h=>({leading:h.leading,groups:[...h.groups]}))}return a}function jn(e,t,n,i){let r=ae(e)===!0?"bound":ee(t)===!0?"document":"typed",u=r==="typed"&&t.state==="input_required"&&t.reason!==void 0&&It(t.reason)==="id_number_recheck",a=vt(Ae(e)),d=!i.attemptsExhausted&&a.length===1&&a[0]?.service==="document";return{kind:"registry",key:"registry",context:n,section:V(t),state:t.state==="input_required"?"input_required":"pending",source:r,recheck:u,canUseDocument:d,...i}}function Yn(e,t,n,i,r){let u=[...t.acceptedSides??[]],a={kind:"document",key:"document",context:n,section:V(t),side:u.includes("recto")?"verso":"recto",acceptedSides:u,documents:Ct(e),photo:Pe(xe(e.documents),r),...i};return e.detectedCountry!==void 0&&(a.detectedCountry=e.detectedCountry),Qn(e)&&(a.ageStepUp=!0),a}function xe(e,t=!0){let n=e?.source==="upload"||e?.source==="choice"?e.source:"camera",i=e?.sourcePick==="camera"||e?.sourcePick==="upload"?e.sourcePick:null;return{source:n,pick:i,uploadOffered:t&&e?.uploadOffered===!0}}function Pe(e,t){return t?{...e,cameraOnPhone:!0}:e}var Wn=10*1024*1024;function $n(e,t,n,i,r){let u=e.proofOfAddress,a=u?.pdf?.maxBytes,d=u?.phase==="holder_letter"?"holder_letter":"document";return{kind:"proof_of_address",key:"proof_of_address",context:n,section:V(t),phase:d,rule:u?.rule??{country:null,countryFrom:"global",source:"preset_global",kinds:[]},nameMatch:u?.nameMatch??"exact_person",photo:Pe(xe(u),r),maxPages:3,pdf:{maxBytes:typeof a=="number"&&a>0?a:Wn,maxPages:3},licenceAddressAccepted:d==="document"&&u?.licenceAddressAccepted===!0,...i}}function Qn(e){let t=J(e).find(i=>i.checkType==="age_estimation"),n=t?.reason;return t?.state==="failed"&&(n==="age_uncertain"||n==="age_unavailable")}function Zn(e){let t=T(e,"liveness");return t?.state==="passed"||t?.state==="review"}function Ot(e,t,n,i,r,u=!1){let a=t.icao?.report,d=e.portrait,h=r==="capture"?d?.pendingFix??null:null;h!==null&&(r="review");let _=Vt(e);return{kind:"portrait",key:`portrait:${r}`,context:n,section:V(t),phase:r,report:Array.isArray(a)?a:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:se(e),retakeOnly:r==="capture"&&t.state==="input_required"&&_===void 0&&e.capture?.livePhoto?.oneCapture===!0&&Zn(e),photo:Pe(xe(d,r==="capture"),u&&r==="capture"),pendingFix:h,..._!==void 0?{captureMode:_}:{},...d?.reuse?.pending===!0?{reuse:!0}:{},...i}}function Vt(e){let t=e.portrait?.captureMode;return t==="self"||t==="assisted"||t==="choice"?t:void 0}var ke={minLongSidePx:1280,jpegQuality:.95};function Jn(e,t){let n=e.capture?.livePhoto;if(n?.oneCapture!==!0)return null;let i=T(e,"portrait_icao"),r=n.still??ke;return{icao:t==="liveness"&&se(e)!==null&&Vt(e)===void 0&&i!==void 0&&i.state==="pending"&&i.reason===void 0,still:{minLongSidePx:r.minLongSidePx??ke.minLongSidePx,jpegQuality:r.jpegQuality??ke.jpegQuality}}}function Xn(e,t,n,i){let r=t.eid,u=V(t);if(r===void 0||r.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:n,section:u,checkType:"eid_auth",reason:"update_required"};let a=vt(Ae(e)),d=a.length===1&&Tn.includes(a[0]?.service??"")?a[0]:void 0,h=d===void 0?void 0:Z[d.service],_=h!==void 0,S={kind:"eid",key:"eid",context:n,section:u,provider:r.provider,providerName:r.providerName,country:r.country,challenge:"app_code",phase:r.awaiting==="code"?"code":"identifier",identifierBound:r.identifierBound===!0,canUseCamera:_,afterPass:r.afterPass==="continue"?"continue":"end",...i};return _&&(S.cameraMethod=h),r.expiresAt!==void 0&&(S.codeExpiresAt=r.expiresAt),r.resendAvailableAt!==void 0&&(S.resendAvailableAt=r.resendAvailableAt),r.resendsRemaining!==void 0&&(S.resendsRemaining=r.resendsRemaining),r.codeAttemptsRemaining!==void 0&&(S.codeAttemptsRemaining=r.codeAttemptsRemaining),S}function zn(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let n=T(e,"portrait_icao");return n!==void 0&&(n.state==="passed"||n.state==="review")?n:null}var eo={rejected:"rejected",inconclusive:"inconclusive",unavailable:"unavailable",abandoned:"expired",not_opened:"expired",cancelled:"expired",superseded:"expired",policy:"policy"};function to(e){return e.reasonCode===we?"platform_unsupported":e.status==="review_pending"?"review":e.status==="verified"?"verified":e.reasonCode==="device_cooldown"?"cooldown":e.reasonCode==="starter_credit_claimed"?"policy":(e.status==="not_verified"&&e.reason!==void 0?eo[e.reason]:void 0)??"rejected"}function no(e,t){let n=to(e),i=n==="platform_unsupported"?{sessionId:D(e.sessionId),status:"unavailable",reasonCode:we}:X(e,{autoRetry:!1}),r={kind:"result",key:"result",context:t,section:null,display:n,result:i};return e.status==="not_verified"&&e.reason!==void 0&&(r.reason=e.reason),e.reasonCode!==void 0&&(r.reasonCode=e.reasonCode),e.status==="not_verified"&&e.step!==void 0&&(r.step=e.step),e.retryAfter!==void 0&&(r.retryAfter=e.retryAfter),r}function oo(e,t,n){let i=e.identitySummary;if(i==null)return null;let r={kind:"identity_summary",key:"identity_summary",context:t,section:n??"identity",summaryKind:i.kind==="partial"?"partial":i.kind??"full",source:i.source,portraitAvailable:i.portrait?.available===!0,retakeAvailable:i.retakeAvailable===!0};for(let a of ro){let d=i[a];typeof d=="string"&&d!==""&&(r[a]=d)}let u=gt(i);return u!==void 0&&(r.idNumberMasked=u,r.nniMasked=u),r}var ro=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","expiryDate","retakeTarget"];function B(e,t,n,i){return{kind:"unsupported",key:`unsupported:${n}`,context:e,section:t,checkType:n,reason:i}}function io(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function so(e,t){let n=Et[e.kind]??[...Ce,...be],i=io(e),r=e.options.flatMap(a=>{if(a.available===!1||!n.includes(a.service))return[];let d={id:a.id,service:a.service};a.nationalEid!=null&&(d.nationalEid=a.nationalEid);let h=(a.channels??[]).filter(_=>_==="whatsapp"||_==="sms");return a.service==="phone_otp"&&h.length>0&&(d.channels=h),[d]});if(r.length===0){let a=e.options.length>0&&e.options.every(d=>d.service==="nfc");return B(t,i,"choice",a?"platform_unsupported":"update_required")}let u={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:r};if(e.kind==="identity_method"){let a={kind:"method",key:"method",context:t,section:i,options:r.map(h=>Z[h.service]),choice:u},d=r.find(h=>h.nationalEid!==void 0)?.nationalEid;return d!==void 0&&(a.nationalEid=d),a}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:i,options:r.map(a=>Tt[a.service]),selected:null,locked:!1,choice:u}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:i,choice:u}}function ao(e,t,n,i){let r=e.nativeApp,u=typeof r=="object"&&r!==null?r:{},a={sekyroApp:u.sekyroApp===!0};return typeof u.link=="string"&&u.link!==""&&(a.link=u.link),a.sekyroApp&&typeof u.sekyroAppLink=="string"&&u.sekyroAppLink.startsWith("sekyro://")&&(a.sekyroAppLink=u.sekyroAppLink),{kind:"native_app_required",key:`native_app_required:${i}`,context:t,section:n,checkType:i,nativeApp:a}}function Go(e,t={}){let n=Ln(e);if(I(e)||e.reasonCode===we)return no(e,n);let i=e.plan;if(i===void 0||!Array.isArray(i.sections))return B(n,null,"plan","update_required");let r=st(e);if(r!==null)return so(r,n);let u=i.current===null?void 0:i.steps.find(g=>g.id===i.current),a=g=>{let m={kind:"processing",key:"processing",context:n,section:g!==void 0?V(g):i.sections.find(M=>M.state==="current")?.id??null,stalled:!1};return typeof g?.service=="string"&&g.service!==""&&(m.service=g.service),m};if(i.current===null)return a(i.steps.find(g=>g.state==="processing"));if(u===void 0)return B(n,null,"step","update_required");if(!En.has(u.service))return u.interaction==="server"?a(u):B(n,V(u),u.service,"update_required");if(vn.has(u.service)||!at(u))return a(u);let d=u,h=Dn(d),_=d.checkType,S=V(d);if(d.requiresNativeApp===!0)return ao(e,n,S,_);let P=t.isMobile===!1?z(e,d):null;if(P==="phone")return{kind:"mobile_required",key:"mobile_required",context:n,section:S,checkType:_};switch(_){case"phone_otp":case"email_otp":return Bn(e,d,n,h);case"population_registry":return jn(e,d,n,h);case"eid_auth":return Xn(e,d,n,h);case"doc_ocr":return Yn(e,d,n,h,P==="upload_or_phone");case"identity_confirm":return oo(e,n,S)??a(d);case"portrait_icao":return Ot(e,d,n,h,"capture",P==="upload_or_phone");case"liveness":case"face_match":{let g=zn(e,d);if(g!==null)return Ot(e,g,n,h,"match");let m=d.requiresMobile===!0,M=se(e);return{kind:"liveness",key:"biometric",context:n,section:S,mode:_==="face_match"?"selfie":"liveness",requiresMobile:m,instructions:M===null?"standard":"icao",icao:M,livePhoto:Jn(e,_),...h}}case"poa":return $n(e,d,n,h,P==="upload_or_phone");case"form":{let g=wt(d.form);return g===null?B(n,S,_,"update_required"):{kind:"form",key:"form",context:n,section:S,form:g,dir:bt(g.locale),...h}}case"nfc_chip":return B(n,S,_,"platform_unsupported");default:return B(n,S,_,"update_required")}}export{Jt as a,Xt as b,sn as c,an as d,cn as e,wo as f,dn as g,kt as h,ln as i,fn as j,Ro as k,Ct as l,Io as m,b as n,bt as o,kn as p,Cn as q,At as r,Pn as s,Oo as t,qo as u,we as v,V as w,Ae as x,vt as y,zn as z,Go as A};
3
+ ${s}`,Le=0,ye,ge=(o,s)=>{Le+=1;let c=v(),f=_(o,{signal:M.signal,subject:s}),p={key:he(o,s),at:c,token:f};return f.then(()=>{p.issuedAt=v(),me=void 0},k=>{let C=St(k);if(p.failed=C,m||C==="aborted")return;me=C;let{detail:w,readyMs:l}=k;W({check:"attestation",kind:"unavailable",engineKind:C,attempt:Ht++,challengeMs:v()-c,readyMs:l,detail:w,inApp:Xe()})}),f.catch(()=>{}),p},De=(o,s)=>o!==null&&o.key===s&&(o.issuedAt===void 0||v()-o.issuedAt<zt),Se=(o,s={})=>{let c=o?.challenge??null;if(o===null||c===null||m)return;let f=D(o.sessionId),p=q;(s.replaceFailed===!0&&p?.failed!==void 0&&!_t.has(p.failed)||!De(p,he(c,f)))&&(q=ge(c,f))},Ue=async(o,s)=>{let c=he(o,s),f=q;q=null;let p=De(f,c)?f:ge(o,s),k=p===f?0:1,C,w=new Promise(l=>{C=setTimeout(()=>l("late"),en)});try{for(;;){let l=await Promise.race([p.token.then(A=>({token:A}),A=>({error:St(A)})),w]);if(l==="late")return!m&&q===null&&(q=p),{error:me??"timeout"};if("token"in l)return ye=Math.max(0,Math.round((p.issuedAt??v())-p.at)),l;if(m||_t.has(l.error)||k>=on||k>0&&await Promise.race([d(rn*k),w])==="late")return l;if(m)return{error:"aborted"};k+=1,p=ge(o,s)}}finally{clearTimeout(C)}},H=null,Lt=o=>J(o).some(s=>(s.checkType==="phone_otp"||s.checkType==="email_otp")&&s.state!=="passed"&&s.state!=="skipped"),Be=o=>H===null||v()-H>=o,oe=()=>Be(tn),Dt=o=>{let s=o.attestation;return typeof s?.turnstileToken=="string"&&s.turnstileToken.length>0},qe=new Map,Ge=async()=>{let o=await x(),s=o.challenge;if(s==null||o.simulation!==void 0)return;let c=await Ue(s,D(o.sessionId));if(!("token"in c))throw new G({status:400,code:"attestation_invalid",message:`browser check: ${c.error}`});return c.token},Ut=async(o,s,c={})=>{let f=s;if("attestation"in f)try{let l=await u.submitCheck(o,s,c);return Dt(f)&&(H=v()),l}catch(l){throw l instanceof G&&l.code==="attestation_invalid"&&(H=null),l}let p=(o==="phone_otp"||o==="email_otp")&&f.action!=="verify",k=c.idempotencyKey,C=k!==void 0?qe.get(k):void 0;C===void 0&&(p||oe())&&(C=await Ge(),k!==void 0&&C!==void 0&&qe.set(k,C));let w=(l,A)=>l!==void 0?{...A,browserCheckToken:l}:A;try{let l=await u.submitCheck(o,s,w(C,c));return C!==void 0&&(H=v()),l}catch(l){if(!(l instanceof G)||l.code!=="attestation_invalid"||(H=null,C!==void 0))throw l;let A=await Ge(),L=k!==void 0?{...c,idempotencyKey:h()}:c,N=await u.submitCheck(o,s,w(A,L));return A!==void 0&&(H=v()),N}},Ke=async(o={})=>{if(Y=void 0,o.always!==!0&&!oe())return{};let s=await x(),c=s.challenge;if(c==null)return{};let f=await Ue(c,D(s.sessionId));if("token"in f)return{channel:"hosted_web",turnstileToken:f.token};if(Y=f.error,s.simulation!==void 0)return{channel:"hosted_web"};throw new ft(f.error)},Bt=()=>Y,qt=()=>({checks:Math.min(50,Le),...ye!==void 0?{challengeMs:Math.min(6e5,ye)}:{}}),W=o=>{if(m)return;let s=a.reportCaptureIssue;if(s===void 0)return;let c=o.formFactor;try{c??(c=Je())}catch{}try{Promise.resolve(s.call(a,{...o,...c!==void 0?{formFactor:c}:{}})).catch(()=>{})}catch{}},R=null,$=null,je=new WeakMap,Ye=Promise.resolve(),Q=0,Gt=async()=>{let o=await x();for(let s=0;s<an&&!m&&!I(o)&&j(o)===void 0&&J(o).some(c=>c.state==="processing")&&(await d(sn),!m);s+=1)o=await E();return o},Kt=async(o,s,c)=>{let{capture:f}=o,p=()=>m,k=()=>o.alive&&o.attempt===c,C=l=>{k()&&f.setFlowState(l)},w=l=>{if(!p()&&(l.status==="unavailable"&&l.reasonCode!==void 0&&!ot(l.reasonCode)&&W({check:"liveness",kind:"unavailable",phase:"upload",engineKind:l.reasonCode,attempt:Math.max(0,o.issues.value)}),fe(l),!!k())){if(l.status==="retry"&&r==="auto"){f.handle.retry();return}f.setFlowState("done")}};if(s.degraded==="NO_RECORDER"){let l=y?.sessionId??(await x().catch(()=>null))?.sessionId??"";w(U(l,"no_recorder"));return}C("uploading");try{if(await He(),p())return;let l=await x(),A;if(!I(l)&&K(l)!==null){await Ee(!1),w(U(l.sessionId,"method_required"));return}if(!I(l)){if(j(l)?.checkType==="population_registry"){w(U(l.sessionId,Ve?"nni_unbound":Te?"network":"registry_unavailable"));return}if(await F(),p())return;A=y??l;let L=await ht({...pe,artifacts:s,getAttestation:Ke,attestationError:Bt,attestationFacts:qt,clipKeys:{get:()=>je.get(s)??null,set:N=>{je.set(s,N)}},getView:()=>y??l,refreshView:E,applySubmit:de,onPhase:C,isCancelled:p,onKeyframePromoted:N=>{g=N}});if(p())return;if(L.kind==="unavailable"){L.reason==="attestation"&&($={bound:o,artifacts:s});let N=U(l.sessionId,L.reason),Ze=L.reason==="attestation"?Y:void 0;w(Ze!==void 0?{...N,attestationError:Ze}:N);return}if(L.kind==="resync"&&await E(),y!==null&&K(y)!==null){await Ee(!1),w(U(l.sessionId,"method_required"));return}l=await Gt()}w(X(l,{autoRetry:i,previous:A}))}catch{if(p())return;w(U(y?.sessionId??"","network"))}},We=(o,s)=>{let c=o.attempt;Q>0&&o.alive&&o.capture.setFlowState("uploading"),Q+=1,Ye=Ye.then(()=>Kt(o,s,c)).finally(()=>{Q-=1,Q===0&&P?.onChainIdle()}).catch(()=>{})},$e=o=>{R?.capture.handle.destroy(),R!==null&&(R.alive=!1);let s=et(o,P?.captureInternals?.(o)??t.capture,()=>y?.capture?.liveness?.keyframe?.rank===!0,Re,()=>y?.capture?.liveness?.screenRamp,{session:()=>ie(y),onModeChange:p=>{te=p}}),c={capture:s,alive:!0,attempt:0,issues:it()};R=c,s.handle.on("error",p=>{W(rt("liveness",p,c.issues.value))}),s.handle.on("state",p=>{if(c.issues.note(p),p==="starting"){c.attempt+=1,$?.bound===c&&($=null),oe()&&Se(y,{replaceFailed:!0});let k=y===null?void 0:j(y)?.checkType;(k==="liveness"||k==="face_match")&&F().catch(()=>{})}}),s.handle.on("captured",p=>{Promise.resolve().then(()=>We(c,p))});let f=s.handle;return{get state(){return f.state},get captureMode(){return f.captureMode},get facingMode(){return f.facingMode},on:(p,k)=>f.on(p,k),start:async p=>{if(y===null&&await x().catch(()=>{}),!!c.alive)return f.start(p)},retry:()=>{let p=$;if(p!==null&&p.bound===c&&c.alive){$=null,We(c,p.artifacts);return}f.retry()},switchCamera:()=>f.switchCamera(),canSwitchCaptureMode:()=>f.canSwitchCaptureMode(),setCaptureMode:p=>f.setCaptureMode(p),destroy:()=>{c.alive=!1,R===c&&(R=null),f.destroy()}}},jt=async()=>{if(m)return null;try{let o=await x();return m?null:K(o)}catch{return null}},Yt=async()=>{if(m)return"self";try{let o=await x();if(m)return"self";let s=ie(o);return s==="choice"?ne()??s:s}catch{return"self"}},Wt=async()=>{if(m)return!1;try{let o=await x();return m||I(o)||_e()?!1:z(o,j(o))==="phone"||z(o,T(o,"liveness"))==="phone"}catch{return!1}},$t=async()=>{if(m)return!1;try{let o=await x();return!m&&o.returning===!0}catch{return!1}},Qt=async o=>{let s=(await x()).plan?.choice,c=s?.options.find(p=>Z[p.service]===o);if(!c)throw new RangeError(`method ${String(o)} is not offered`);let f=await a.choose(s.nodeId,c.id);m||O(f)},Qe=null,Zt=()=>(Qe??(Qe=import("./plan-runner-BZ7LODPB.js").then(o=>{let s=o.createPlanRunner({runtime:pe,currentView:()=>y,cameraMode:Re,captureModeSwitch:{pick:ne,choose:c=>{te=c}},ensureView:x,refreshView:E,ensureConsent:()=>F(),liveness:$e,stopLiveness:()=>{R!==null&&(R.alive=!1,R.capture.handle.destroy(),R=null)},chainBusy:()=>Q>0,destroyed:()=>m,sleep:d,isMobile:_e,now:t.now??Date.now,keptFaceKey:()=>g,setView:O,baseCapture:t.capture,emitStep:c=>{m||S.emit("step",c)},emitResult:Ft,reportCaptureIssue:W,documentInternals:t.document,documentFacts:t.documentFacts,portraitInternals:t.portrait,livePhotoInternals:t.livePhoto,uploadInternals:t.upload,pageCameraInternals:t.pageCamera});return P=s,s})),Qe);return{consent:()=>F(),startRegistry:He,methodChoice:jt,selectMethod:Qt,reportCameraUnavailable:async o=>{await F();let s=a.reportCameraUnavailable;if(s===void 0)throw new TypeError("this client cannot report a missing camera");let c=await s.call(a,o).catch(f=>{if(f instanceof G&&f.code==="check_out_of_order")return a.getSession();throw f});m||O(c)},reportCaptureIssue:W,testerGate:async o=>{let s=a.testerGate;if(s===void 0)throw new TypeError("this client cannot run the tester gate");let c=o.clip,f=tt(o.clipMime??"");if(c===void 0||!pt.includes(f))throw new TypeError("the capture has no clip");await F();let p=await lt(a,"clip",f,c.size,{engine:o.engine,durationMs:o.clipMs});await a.uploadToSpaces(p.uploadUrl,c,f);let{key:k}=await a.completeMedia(p.key),C=await Ke({always:!0}),w=await s.call(a,{clipKey:k,attestation:C,captureChannel:o.captureChannel,capture:{...yt(o),attestationError:Y}}),{bound:l,...A}=w;return m||(A.plan!==void 0?O(A):await E()),{bound:l===!0}},mobileRequired:Wt,captureMode:Yt,chooseCaptureMode:o=>{te=o},get captureChoice(){return ne()},returning:$t,liveness:$e,run:async()=>{if(m)throw new Error("verification destroyed");return(await Zt()).run()},currentStep:()=>P?.current()??null,voiceClips:async()=>{if(m)return null;try{let o=await x();return m?null:o.voice??null}catch{return null}},on:(o,s)=>S.on(o,s),destroy:()=>{m=!0,M.abort(),P?.destroy(),R!==null&&(R.alive=!1,R.capture.handle.destroy(),R=null),S.clear()}}}var kt=["AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AS","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CW","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IR","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","XK","YE","YT","ZA","ZM","ZW"];var ln=["carte_identite","passport","residence_permit","drivers_license"],pn=["carte_identite","passport","residence_permit"];function fn(e,t){let n=e.byIssuer?.[t]??e.default;return ln.filter(i=>n==="*"?pn.includes(i):n.includes(i))}function Io(e,t=kt){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(i=>fn(e,i).length>0).sort()}function Ct(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}function Mo(e){return/^[A-Z]{2}$/.test(e)?String.fromCodePoint(...[...e].map(t=>127462+t.charCodeAt(0)-65)):""}var b={fullNameMin:2,fullName:200,email:254,occupation:120,shortText:120,longText:1e3,addressLine:120,addressLines:4,city:80,postcode:16,number:1e12,dateMin:"1900-01-01",dateMax:"2100-12-31"},mn=new Set(["full_name","birth_date","email","phone","address","country","occupation"]),hn=new Set(["short_text","long_text","single_choice","multiple_choice","yes_no","date","number"]),yn=new Set(["ar","fa","he","ur"]);function bt(e){return yn.has(e.split("-")[0]?.toLowerCase()??"")?"rtl":"ltr"}function wt(e){if(typeof e!="object"||e===null)return null;let t=e;if(typeof t.locale!="string"||!Array.isArray(t.questions)||t.questions.length===0)return null;let n=t.consents??[];if(!Array.isArray(n))return null;for(let r of t.questions)if(!gn(r))return null;for(let r of n)if(!Sn(r))return null;let i={locale:t.locale,questions:t.questions,consents:n};return typeof t.title=="string"&&t.title.trim()!==""&&(i.title=t.title),typeof t.intro=="string"&&t.intro.trim()!==""&&(i.intro=t.intro),typeof t.prefill=="object"&&t.prefill!==null&&!Array.isArray(t.prefill)&&(i.prefill=t.prefill),i}function gn(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id!="string"||typeof t.required!="boolean"?!1:t.kind==="field"?typeof t.field=="string"&&mn.has(t.field):t.kind!=="custom"||typeof t.type!="string"||!hn.has(t.type)||typeof t.label!="string"?!1:t.type==="single_choice"||t.type==="multiple_choice"?Array.isArray(t.choices)&&t.choices.length>=2&&t.choices.every(n=>typeof n=="object"&&n!==null&&typeof n.value=="string"&&typeof n.label=="string"):!0}function Sn(e){if(typeof e!="object"||e===null)return!1;let t=e;if(typeof t.id!="string"||typeof t.required!="boolean"||typeof t.text!="string")return!1;if(t.link===void 0)return!0;let n=t.link;return typeof n=="object"&&n!==null&&typeof n.url=="string"&&/^https:\/\//.test(n.url)&&typeof n.label=="string"}var _n=/^(\d{4})-(\d{2})-(\d{2})$/;function kn(e){if(typeof e!="string")return!1;let t=_n.exec(e);return t===null?!1:new Date(Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3]))).toISOString().slice(0,10)===e&&e>=b.dateMin&&e<=b.dateMax}function Cn(e){return typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<b.number&&Math.round(e*100)/100===e}function xt(e){for(let t of e.matchAll(/\d[\d -]{11,}\d/g)){let n=t[0].replace(/[ -]/g,"");if(n.length>=13&&n.length<=19&&bn(n))return!0}return!1}function bn(e){let t=0;for(let n=0;n<e.length;n++){let i=Number(e[e.length-1-n]);n%2===1&&(i*=2,i>9&&(i-=9)),t+=i}return t%10===0}var wn=/^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$/,xn=/^\+[1-9]\d{6,14}$/,At=/^[A-Z]{2}$/,An=e=>e===void 0||typeof e=="string"&&e.trim()===""||Array.isArray(e)&&e.length===0;function Pn(e=Date.now()){return new Date(e).toISOString().slice(0,10)}function Eo(e,t,n=Pn()){let i=[];for(let r of e.questions){let u=t.answers[r.id];if(An(u)){r.required&&i.push({id:r.id,code:"required"});continue}let a=r.kind==="field"?Rn(r.field,u,n):Mn(r,u,n);a!==null&&i.push({id:r.id,...a})}for(let r of e.consents)r.required&&t.consents[r.id]!==!0&&i.push({id:r.id,code:"consent_required"});return i}function ue(e,t,n=1){if(typeof e!="string")return{code:"required"};let i=e.trim();return[...i].length>t?{code:"too_long",params:{max:t}}:[...i].length<n?{code:"too_short",params:{min:n}}:xt(i)?{code:"card_number"}:null}function Pt(e,t,n={}){return kn(e)?n.period==="past"&&e>=t?{code:"date_not_past"}:n.period==="future"&&e<=t?{code:"date_not_future"}:n.min!==void 0&&e<n.min?{code:"date_too_early",params:{date:n.min}}:n.max!==void 0&&e>n.max?{code:"date_too_late",params:{date:n.max}}:null:{code:"date_invalid"}}function Rn(e,t,n){switch(e){case"full_name":return ue(t,b.fullName,b.fullNameMin);case"occupation":return ue(t,b.occupation);case"birth_date":return Pt(t,n,{period:"past"});case"email":return typeof t=="string"&&t.trim().length<=b.email&&wn.test(t.trim())?null:{code:"email_invalid"};case"phone":return typeof t=="string"&&xn.test(t)?null:{code:"phone_invalid"};case"country":return typeof t=="string"&&At.test(t)?null:{code:"choice_invalid"};case"address":return In(t)?null:{code:"address_invalid"};default:return null}}function In(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e,n=Array.isArray(t.lines)?t.lines.filter(i=>typeof i=="string"&&i.trim()!==""):[];return typeof t.country=="string"&&At.test(t.country)&&typeof t.city=="string"&&t.city.trim()!==""&&t.city.trim().length<=b.city&&n.length>=1&&n.length<=b.addressLines&&n.every(i=>i.trim().length<=b.addressLine&&!xt(i))&&(t.postcode===void 0||typeof t.postcode=="string"&&t.postcode.trim().length<=b.postcode)}function Mn(e,t,n){let i=new Set((e.choices??[]).map(r=>r.value));switch(e.type){case"short_text":return ue(t,b.shortText);case"long_text":return ue(t,b.longText);case"single_choice":return typeof t=="string"&&i.has(t)?null:{code:"choice_invalid"};case"multiple_choice":return Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(r=>i.has(r))?null:{code:"choice_invalid"};case"yes_no":return typeof t=="boolean"?null:{code:"choice_invalid"};case"date":{let r=e.options??{};return Pt(t,n,{...typeof r.min=="string"?{min:r.min}:{},...typeof r.max=="string"?{max:r.max}:{},...r.period==="past"||r.period==="future"?{period:r.period}:{}})}case"number":{if(typeof t!="number"||!Number.isFinite(t)||Math.abs(t)>=b.number)return{code:"number_invalid"};let r=e.options??{};return r.integer===!0&&!Number.isInteger(t)?{code:"number_not_integer"}:Cn(t)?typeof r.min=="number"&&t<r.min?{code:"number_too_small",params:{min:r.min}}:typeof r.max=="number"&&t>r.max?{code:"number_too_large",params:{max:r.max}}:null:{code:"number_decimals"}}default:return null}}var vo={full_name:b.fullName,occupation:b.occupation,email:b.email,short_text:b.shortText,long_text:b.longText};var Rt=Object.freeze({nni_invalid:"id_number_invalid",nni_not_found:"registry_record_not_found",nni_recheck:"id_number_recheck",document_nni_mismatch:"document_id_number_mismatch",nni_locked:"id_number_locked",nni_unbound:"id_number_unbound",missing_nni:"missing_id_number",registry_needs_nni_source:"registry_needs_id_number_source"}),On=new Map(Object.entries(Rt)),Vo=new Map(Object.entries(Rt).map(([e,t])=>[t,e]));function It(e){return On.get(e)??e}var Go=["national_number","document_photo","national_eid"],En=new Set(["phone_otp","email_otp","national_eid","document","nfc","population_registry","supplied_identity","summary_confirm","liveness","portrait","face_match","aml_screening","face_dedup","age_estimation","proof_of_address","form"]),vn=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),Ce=["document","population_registry","national_eid"],be=["phone_otp","email_otp"],Et={identity_method:Ce,contact:be},Tn=["population_registry","document"],we="platform_unsupported",Vn=new Set(["prefilled","user_entered","prefilled_or_entered"]),Fn={phone_otp:"contact",email_otp:"contact",eid_auth:"identity",doc_ocr:"identity",nfc_chip:"identity",population_registry:"identity",liveness:"live_photo",portrait_icao:"live_photo",face_match:"live_photo",poa:"documents",form:"form"};function V(e){return e.section??Fn[e.checkType]??null}function Nn(e,t){let n=e.plan?.choice;if(n===void 0||n.locked)return;let i=n.options.find(r=>r.id!==n.selected&&r.available!==!1&&t.includes(r.service));return i===void 0?void 0:{nodeId:n.nodeId,option:i}}function xe(e){let t=e.plan,n=t?.choice;if(t===void 0||n===void 0||n.locked||t.current===null||t.current===n.nodeId||I(e))return null;let i=Et[n.kind]??[...Ce,...be],r=n.options.flatMap(d=>d.available===!1||!i.includes(d.service)?[]:[d.nationalEid!=null?{id:d.id,service:d.service,nationalEid:d.nationalEid}:{id:d.id,service:d.service}]),u=t.steps.find(d=>d.id===t.current)?.service,a=n.selected??r.find(d=>d.service===u)?.id??null;return r.some(d=>d.id!==a)?{nodeId:n.nodeId,kind:n.kind,current:a,options:r}:null}function vt(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function Hn(e){let t=e.simulation;if(typeof t!="object"||t===null)return;let{otpCode:n,skipCapture:i}=t;if(typeof n!="string"||n===""||typeof i!="boolean")return;let r=ut(e);return r!==void 0?{otpCode:n,skipCapture:i,reason:r}:{otpCode:n,skipCapture:i}}function Ln(e){let t=e.levelTarget?.max;return typeof t=="number"&&t<=1?"contact":e.purpose??"identity"}function Dn(e){let t=(e.plan?.sections??[]).map(a=>({id:a.id,state:a.state})),n={sessionId:D(e.sessionId),orgName:e.orgName,sandbox:e.sandbox===!0,returning:e.returning===!0,consentRecorded:e.consentRecorded,expiresAt:e.expiresAt,sections:t.map(a=>a.id),progress:t,purpose:e.purpose??"identity",levelName:Ln(e)};e.branding!==void 0&&(n.branding=e.branding),e.cameraUnavailableHandled===!0&&(n.cameraUnavailableHandled=!0);let i=Hn(e);i!==void 0&&(n.simulation=i);let r=e.testerGate;r?.offered===!0&&typeof r.attemptsLeft=="number"&&r.attemptsLeft>0&&(n.testerGate={attemptsLeft:r.attemptsLeft});let u=xe(e);return u!==null&&(n.switchable=u),n}function Un(e){let t={attemptsRemaining:re(e),attemptsExhausted:e.attempts.used>=e.attempts.max};return e.reason!==void 0&&(t.reason=e.reason),e.retakeHint!==void 0&&(t.retakeHint=e.retakeHint),t}var Tt={phone_otp:"phone",email_otp:"email"};function Bn(e,t){let n=Nn(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return n===void 0?void 0:Tt[n.option.service]}function qn(e,t,n,i){let r=t.checkType==="email_otp",u=(r?t.emailOtp:t.otp)??{},a=r?t.emailOtp?.emailSource:t.otp?.numberSource,d=a!==void 0&&Vn.has(a)?a:r?"prefilled_or_entered":"user_entered",h=typeof u.sentToMasked=="string"&&u.sentToMasked.length>0,_=u.prefilled===!0,S=Bn(e,r?"email_otp":"phone_otp"),P={key:t.checkType,context:n,section:V(t),phase:h?"verify":"send",canSwitch:S!==void 0,...i},g=r?{kind:"email_otp",...P,emailSource:d,needsEmail:d!=="prefilled"&&!_}:{kind:"phone_otp",...P,numberSource:d,needsPhone:d!=="prefilled"&&!_,channels:(t.otp?.channels??[]).filter(m=>m==="whatsapp"||m==="sms")};if(S!==void 0&&(g.switchChannel=S),_&&(g.prefilled=!0),h&&(g.sentToMasked=u.sentToMasked),!r&&t.otp?.channel!==void 0&&(g.channel=t.otp.channel),!r&&Array.isArray(t.phoneCountries)&&(g.phoneCountries=t.phoneCountries.filter(m=>typeof m=="string"&&/^[A-Z]{2}$/.test(m))),!r&&Array.isArray(t.phoneRules)){let m=g.phoneCountries??[];g.phoneRules=t.phoneRules.flatMap(M=>{let y=jn(M);return y!==void 0&&m.includes(y.code)?[y]:[]})}return!r&&t.phoneInternational===!0&&(g.phoneInternational=!0),u.expiresAt!==void 0&&(g.codeExpiresAt=u.expiresAt),u.resendAvailableAt!==void 0&&(g.resendAvailableAt=u.resendAvailableAt),g}var Gn=/^[\d[\]\-|()?:^]{1,64}$/;function Kn(e){try{return typeof e=="string"&&Gn.test(e)&&new RegExp(e)!==null}catch{return!1}}var Mt=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function jn(e){let{code:t,dial:n,trunk:i,lengths:r,formats:u}=e??{};if(typeof t!="string"||typeof n!="string"||!/^\d{1,3}$/.test(n)||i!==void 0&&(typeof i!="string"||!/^\d{1,3}$/.test(i))||!Array.isArray(r)||r.length===0||!r.every(Mt))return;let a={code:t,dial:n,lengths:[...r].sort((d,h)=>d-h)};if(i!==void 0&&(a.trunk=i),u!==void 0){if(!(Array.isArray(u)&&u.length<=8&&u.every(h=>Kn(h?.leading)&&Array.isArray(h.groups)&&h.groups.every(Mt)&&r.includes(h.groups.reduce((_,S)=>_+S,0)))))return;a.formats=u.map(h=>({leading:h.leading,groups:[...h.groups]}))}return a}function Yn(e,t,n,i){let r=ae(e)===!0?"bound":ee(t)===!0?"document":"typed",u=r==="typed"&&t.state==="input_required"&&t.reason!==void 0&&It(t.reason)==="id_number_recheck",a=vt(xe(e)),d=!i.attemptsExhausted&&a.length===1&&a[0]?.service==="document";return{kind:"registry",key:"registry",context:n,section:V(t),state:t.state==="input_required"?"input_required":"pending",source:r,recheck:u,canUseDocument:d,...i}}function Wn(e,t,n,i,r){let u=[...t.acceptedSides??[]],a={kind:"document",key:"document",context:n,section:V(t),side:u.includes("recto")?"verso":"recto",acceptedSides:u,documents:Ct(e),photo:Pe(Ae(e.documents),r),...i};return e.detectedCountry!==void 0&&(a.detectedCountry=e.detectedCountry),Zn(e)&&(a.ageStepUp=!0),a}function Ae(e,t=!0){let n=e?.source==="upload"||e?.source==="choice"?e.source:"camera",i=e?.sourcePick==="camera"||e?.sourcePick==="upload"?e.sourcePick:null;return{source:n,pick:i,uploadOffered:t&&e?.uploadOffered===!0}}function Pe(e,t){return t?{...e,cameraOnPhone:!0}:e}var $n=10*1024*1024;function Qn(e,t,n,i,r){let u=e.proofOfAddress,a=u?.pdf?.maxBytes,d=u?.phase==="holder_letter"?"holder_letter":"document";return{kind:"proof_of_address",key:"proof_of_address",context:n,section:V(t),phase:d,rule:u?.rule??{country:null,countryFrom:"global",source:"preset_global",kinds:[]},nameMatch:u?.nameMatch??"exact_person",photo:Pe(Ae(u),r),maxPages:3,pdf:{maxBytes:typeof a=="number"&&a>0?a:$n,maxPages:3},licenceAddressAccepted:d==="document"&&u?.licenceAddressAccepted===!0,...i}}function Zn(e){let t=J(e).find(i=>i.checkType==="age_estimation"),n=t?.reason;return t?.state==="failed"&&(n==="age_uncertain"||n==="age_unavailable")}function Jn(e){let t=T(e,"liveness");return t?.state==="passed"||t?.state==="review"}function Ot(e,t,n,i,r,u=!1){let a=t.icao?.report,d=e.portrait,h=r==="capture"?d?.pendingFix??null:null;h!==null&&(r="review");let _=Vt(e);return{kind:"portrait",key:`portrait:${r}`,context:n,section:V(t),phase:r,report:Array.isArray(a)?a:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:se(e),retakeOnly:r==="capture"&&t.state==="input_required"&&_===void 0&&e.capture?.livePhoto?.oneCapture===!0&&Jn(e),photo:Pe(Ae(d,r==="capture"),u&&r==="capture"),pendingFix:h,..._!==void 0?{captureMode:_}:{},...d?.reuse?.pending===!0?{reuse:!0}:{},...i}}function Vt(e){let t=e.portrait?.captureMode;return t==="self"||t==="assisted"||t==="choice"?t:void 0}var ke={minLongSidePx:1280,jpegQuality:.95};function Xn(e,t){let n=e.capture?.livePhoto;if(n?.oneCapture!==!0)return null;let i=T(e,"portrait_icao"),r=n.still??ke;return{icao:t==="liveness"&&se(e)!==null&&Vt(e)===void 0&&i!==void 0&&i.state==="pending"&&i.reason===void 0,still:{minLongSidePx:r.minLongSidePx??ke.minLongSidePx,jpegQuality:r.jpegQuality??ke.jpegQuality}}}function zn(e,t,n,i){let r=t.eid,u=V(t);if(r===void 0||r.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:n,section:u,checkType:"eid_auth",reason:"update_required"};let a=vt(xe(e)),d=a.length===1&&Tn.includes(a[0]?.service??"")?a[0]:void 0,h=d===void 0?void 0:Z[d.service],_=h!==void 0,S={kind:"eid",key:"eid",context:n,section:u,provider:r.provider,providerName:r.providerName,country:r.country,challenge:"app_code",phase:r.awaiting==="code"?"code":"identifier",identifierBound:r.identifierBound===!0,canUseCamera:_,afterPass:r.afterPass==="continue"?"continue":"end",...i};return _&&(S.cameraMethod=h),r.expiresAt!==void 0&&(S.codeExpiresAt=r.expiresAt),r.resendAvailableAt!==void 0&&(S.resendAvailableAt=r.resendAvailableAt),r.resendsRemaining!==void 0&&(S.resendsRemaining=r.resendsRemaining),r.codeAttemptsRemaining!==void 0&&(S.codeAttemptsRemaining=r.codeAttemptsRemaining),S}function eo(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let n=T(e,"portrait_icao");return n!==void 0&&(n.state==="passed"||n.state==="review")?n:null}var to={rejected:"rejected",inconclusive:"inconclusive",unavailable:"unavailable",abandoned:"expired",not_opened:"expired",cancelled:"expired",superseded:"expired",policy:"policy"};function no(e){return e.reasonCode===we?"platform_unsupported":e.status==="review_pending"?"review":e.status==="verified"?"verified":e.reasonCode==="device_cooldown"?"cooldown":e.reasonCode==="starter_credit_claimed"?"policy":(e.status==="not_verified"&&e.reason!==void 0?to[e.reason]:void 0)??"rejected"}function oo(e,t){let n=no(e),i=n==="platform_unsupported"?{sessionId:D(e.sessionId),status:"unavailable",reasonCode:we}:X(e,{autoRetry:!1}),r={kind:"result",key:"result",context:t,section:null,display:n,result:i};return e.status==="not_verified"&&e.reason!==void 0&&(r.reason=e.reason),e.reasonCode!==void 0&&(r.reasonCode=e.reasonCode),e.status==="not_verified"&&e.step!==void 0&&(r.step=e.step),e.retryAfter!==void 0&&(r.retryAfter=e.retryAfter),r}function ro(e,t,n){let i=e.identitySummary;if(i==null)return null;let r={kind:"identity_summary",key:"identity_summary",context:t,section:n??"identity",summaryKind:i.kind==="partial"?"partial":i.kind??"full",source:i.source,portraitAvailable:i.portrait?.available===!0,retakeAvailable:i.retakeAvailable===!0};for(let a of io){let d=i[a];typeof d=="string"&&d!==""&&(r[a]=d)}let u=gt(i);return u!==void 0&&(r.idNumberMasked=u,r.nniMasked=u),r}var io=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","expiryDate","retakeTarget"];function B(e,t,n,i){return{kind:"unsupported",key:`unsupported:${n}`,context:e,section:t,checkType:n,reason:i}}function so(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function ao(e,t){let n=Et[e.kind]??[...Ce,...be],i=so(e),r=e.options.flatMap(a=>{if(a.available===!1||!n.includes(a.service))return[];let d={id:a.id,service:a.service};a.nationalEid!=null&&(d.nationalEid=a.nationalEid);let h=(a.channels??[]).filter(_=>_==="whatsapp"||_==="sms");return a.service==="phone_otp"&&h.length>0&&(d.channels=h),[d]});if(r.length===0){let a=e.options.length>0&&e.options.every(d=>d.service==="nfc");return B(t,i,"choice",a?"platform_unsupported":"update_required")}let u={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:r};if(e.kind==="identity_method"){let a={kind:"method",key:"method",context:t,section:i,options:r.map(h=>Z[h.service]),choice:u},d=r.find(h=>h.nationalEid!==void 0)?.nationalEid;return d!==void 0&&(a.nationalEid=d),a}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:i,options:r.map(a=>Tt[a.service]),selected:null,locked:!1,choice:u}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:i,choice:u}}function uo(e,t,n,i){let r=e.nativeApp,u=typeof r=="object"&&r!==null?r:{},a={sekyroApp:u.sekyroApp===!0};return typeof u.link=="string"&&u.link!==""&&(a.link=u.link),a.sekyroApp&&typeof u.sekyroAppLink=="string"&&u.sekyroAppLink.startsWith("sekyro://")&&(a.sekyroAppLink=u.sekyroAppLink),{kind:"native_app_required",key:`native_app_required:${i}`,context:t,section:n,checkType:i,nativeApp:a}}function Ko(e,t={}){let n=Dn(e);if(I(e)||e.reasonCode===we)return oo(e,n);let i=e.plan;if(i===void 0||!Array.isArray(i.sections))return B(n,null,"plan","update_required");let r=st(e);if(r!==null)return ao(r,n);let u=i.current===null?void 0:i.steps.find(g=>g.id===i.current),a=g=>{let m={kind:"processing",key:"processing",context:n,section:g!==void 0?V(g):i.sections.find(M=>M.state==="current")?.id??null,stalled:!1};return typeof g?.service=="string"&&g.service!==""&&(m.service=g.service),m};if(i.current===null)return a(i.steps.find(g=>g.state==="processing"));if(u===void 0)return B(n,null,"step","update_required");if(!En.has(u.service))return u.interaction==="server"?a(u):B(n,V(u),u.service,"update_required");if(vn.has(u.service)||!at(u))return a(u);let d=u,h=Un(d),_=d.checkType,S=V(d);if(d.requiresNativeApp===!0)return uo(e,n,S,_);let P=t.isMobile===!1?z(e,d):null;if(P==="phone")return{kind:"mobile_required",key:"mobile_required",context:n,section:S,checkType:_};switch(_){case"phone_otp":case"email_otp":return qn(e,d,n,h);case"population_registry":return Yn(e,d,n,h);case"eid_auth":return zn(e,d,n,h);case"doc_ocr":return Wn(e,d,n,h,P==="upload_or_phone");case"identity_confirm":return ro(e,n,S)??a(d);case"portrait_icao":return Ot(e,d,n,h,"capture",P==="upload_or_phone");case"liveness":case"face_match":{let g=eo(e,d);if(g!==null)return Ot(e,g,n,h,"match");let m=d.requiresMobile===!0,M=se(e);return{kind:"liveness",key:"biometric",context:n,section:S,mode:_==="face_match"?"selfie":"liveness",requiresMobile:m,instructions:M===null?"standard":"icao",icao:M,livePhoto:Xn(e,_),...h}}case"poa":return Qn(e,d,n,h,P==="upload_or_phone");case"form":{let g=wt(d.form);return g===null?B(n,S,_,"update_required"):{kind:"form",key:"form",context:n,section:S,form:g,dir:bt(g.locale),...h}}case"nfc_chip":return B(n,S,_,"platform_unsupported");default:return B(n,S,_,"update_required")}}export{Jt as a,Xt as b,sn as c,an as d,cn as e,xo as f,dn as g,kt as h,ln as i,fn as j,Io as k,Ct as l,Mo as m,b as n,bt as o,kn as p,Cn as q,xt as r,Pn as s,Eo as t,Go as u,we as v,V as w,xe as x,vt as y,eo as z,Ko as A};