@sekyro/web 0.1.0-rc.4 → 0.1.0-rc.40

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 (141) hide show
  1. package/CHANGELOG.md +491 -0
  2. package/LICENSE +25 -16
  3. package/README.md +158 -62
  4. package/THIRD-PARTY-NOTICES.txt +154 -0
  5. package/dist/assets.generated-DpkbvoII.d.cts +249 -0
  6. package/dist/assets.generated-DpkbvoII.d.ts +249 -0
  7. package/dist/background-monitor-A7FKJOAG.js +1 -0
  8. package/dist/barcode-detect-C5IOXMKI.js +1 -0
  9. package/dist/camera-trait-DELAK3YN.js +1 -0
  10. package/dist/capture-constraints-CVqpMNGA.d.cts +48 -0
  11. package/dist/capture-constraints-CVqpMNGA.d.ts +48 -0
  12. package/dist/capture-session-doc-DFLSX6BB.js +1 -0
  13. package/dist/{capture-session-v3-uXJr1Wlm.d.ts → capture-session-v3-C-9FB_vX.d.cts} +232 -13
  14. package/dist/{capture-session-v3-DEInCOUg.d.cts → capture-session-v3-DEpGJ_fI.d.ts} +232 -13
  15. package/dist/challenge-frame-YBTLAQ5G.js +1 -0
  16. package/dist/chunk-22AW4NJD.js +1 -0
  17. package/dist/chunk-33KKMPJ5.js +1 -0
  18. package/dist/chunk-3WQJI7UL.js +1 -0
  19. package/dist/chunk-4NO6MQPH.js +1 -0
  20. package/dist/chunk-53POX7U4.js +1 -0
  21. package/dist/chunk-7QZWBDI5.js +1 -0
  22. package/dist/chunk-BD4KIQQD.js +1 -0
  23. package/dist/chunk-BPAGOPYL.js +1 -0
  24. package/dist/chunk-BRLQIJYF.js +1 -0
  25. package/dist/chunk-CJHMFPL6.js +1 -0
  26. package/dist/chunk-CPUECYAJ.js +1 -0
  27. package/dist/chunk-FPXL63KZ.js +1 -0
  28. package/dist/chunk-FSSMUAKC.js +1 -0
  29. package/dist/chunk-FYU7J2DC.js +1 -0
  30. package/dist/chunk-GFJATPUR.js +1 -0
  31. package/dist/chunk-GI3UFGRQ.js +1 -0
  32. package/dist/chunk-JLVZ35QK.js +2 -0
  33. package/dist/chunk-L3TNFMQK.js +1 -0
  34. package/dist/chunk-M3637QGB.js +1 -0
  35. package/dist/chunk-MQHTFHSN.js +1 -0
  36. package/dist/chunk-POIQGEZM.js +1 -0
  37. package/dist/chunk-QB62OPX5.js +1 -0
  38. package/dist/chunk-QZUFICG3.js +1 -0
  39. package/dist/chunk-RI3E7GBN.js +1 -0
  40. package/dist/chunk-SJ5OJ677.js +1 -0
  41. package/dist/chunk-SMKCBUJL.js +1 -0
  42. package/dist/chunk-SX7TUC3V.js +1 -0
  43. package/dist/chunk-TSA6GHUG.js +1 -0
  44. package/dist/chunk-U5TL63CG.js +1 -0
  45. package/dist/chunk-VSLJZ7GH.js +1 -0
  46. package/dist/chunk-VWGKUQ3C.js +1 -0
  47. package/dist/chunk-W357WDNU.js +1 -0
  48. package/dist/chunk-WNBEOK5Q.js +1 -0
  49. package/dist/chunk-Y5GRT27C.js +3 -0
  50. package/dist/chunk-ZVD6VHM2.js +1 -0
  51. package/dist/client/index.cjs +1 -357
  52. package/dist/client/index.d.cts +6 -37
  53. package/dist/client/index.d.ts +6 -37
  54. package/dist/client/index.js +1 -15
  55. package/dist/clip-inspect-DLJXVKV6.js +1 -0
  56. package/dist/core/index.cjs +1 -1634
  57. package/dist/core/index.d.cts +5 -4
  58. package/dist/core/index.d.ts +5 -4
  59. package/dist/core/index.js +1 -139
  60. package/dist/core/ocr/worker.bundle.js +41 -0
  61. package/dist/core/ocr/worker.cjs +41 -0
  62. package/dist/core/ocr/worker.d.cts +97 -0
  63. package/dist/core/ocr/worker.d.ts +97 -0
  64. package/dist/core/ocr/worker.js +40 -0
  65. package/dist/core/v3/detect-worker.cjs +1 -392
  66. package/dist/core/v3/detect-worker.d.cts +1 -1
  67. package/dist/core/v3/detect-worker.d.ts +1 -1
  68. package/dist/core/v3/detect-worker.js +1 -13
  69. package/dist/create-document-capture-4ZOSBL3Y.js +1 -0
  70. package/dist/create-portrait-capture-5VGYZUOK.js +1 -0
  71. package/dist/create-verification-B8c9xBnz.d.ts +3871 -0
  72. package/dist/create-verification-BadlGBh3.d.cts +3871 -0
  73. package/dist/{detect-worker-CKXHlXx9.d.ts → detect-worker-CHqsPJoM.d.cts} +25 -2
  74. package/dist/{detect-worker-CKXHlXx9.d.cts → detect-worker-CHqsPJoM.d.ts} +25 -2
  75. package/dist/detector-scanic-P2RTEQUV.js +1 -0
  76. package/dist/icao-gate-BqXxEAq6.d.cts +610 -0
  77. package/dist/icao-gate-C7D7Lce7.d.ts +610 -0
  78. package/dist/icao-gate-T3BTOKFJ.js +1 -0
  79. package/dist/icao-policy-Bo7TQyTd.d.ts +80 -0
  80. package/dist/icao-policy-CgSI4oFo.d.cts +80 -0
  81. package/dist/icao-tuning-4ETMF53W.js +1 -0
  82. package/dist/index.cjs +3 -2698
  83. package/dist/index.d.cts +138 -5
  84. package/dist/index.d.ts +138 -5
  85. package/dist/index.js +1 -28
  86. package/dist/internal/index.cjs +3 -4228
  87. package/dist/internal/index.d.cts +306 -371
  88. package/dist/internal/index.d.ts +306 -371
  89. package/dist/internal/index.js +1 -647
  90. package/dist/keyframe-rank-YAJLYJYF.js +1 -0
  91. package/dist/landmarker-KB7LVXAU.js +1 -0
  92. package/dist/mrz-band-VYHOTDHY.js +1 -0
  93. package/dist/plan-runner-3BLEJWHF.js +1 -0
  94. package/dist/popup/index.cjs +1 -76
  95. package/dist/popup/index.d.cts +9 -3
  96. package/dist/popup/index.d.ts +9 -3
  97. package/dist/popup/index.js +1 -11
  98. package/dist/print-DCYX3CZD.js +1 -0
  99. package/dist/scanic-ml-stub-KW7IZHUT.js +1 -0
  100. package/dist/segmenter-USLNBX65.js +1 -0
  101. package/dist/types-BAAj6TOZ.d.cts +2230 -0
  102. package/dist/types-BAAj6TOZ.d.ts +2230 -0
  103. package/dist/upload-file-EGXXM6TQ.js +1 -0
  104. package/package.json +30 -11
  105. package/sbom.cdx.json +349 -0
  106. package/dist/capture-constraints-BujkZcfb.d.cts +0 -21
  107. package/dist/capture-constraints-BujkZcfb.d.ts +0 -21
  108. package/dist/chunk-EWRNPKTR.js +0 -1123
  109. package/dist/chunk-EWRNPKTR.js.map +0 -1
  110. package/dist/chunk-MWNFSNMP.js +0 -52
  111. package/dist/chunk-MWNFSNMP.js.map +0 -1
  112. package/dist/chunk-NILNKLK6.js +0 -50
  113. package/dist/chunk-NILNKLK6.js.map +0 -1
  114. package/dist/chunk-NWF46H7K.js +0 -359
  115. package/dist/chunk-NWF46H7K.js.map +0 -1
  116. package/dist/chunk-TBANUT3X.js +0 -885
  117. package/dist/chunk-TBANUT3X.js.map +0 -1
  118. package/dist/chunk-WY6U7AIK.js +0 -193
  119. package/dist/chunk-WY6U7AIK.js.map +0 -1
  120. package/dist/chunk-YVFF4Q4G.js +0 -327
  121. package/dist/chunk-YVFF4Q4G.js.map +0 -1
  122. package/dist/client/index.cjs.map +0 -1
  123. package/dist/client/index.js.map +0 -1
  124. package/dist/core/index.cjs.map +0 -1
  125. package/dist/core/index.js.map +0 -1
  126. package/dist/core/v3/detect-worker.cjs.map +0 -1
  127. package/dist/core/v3/detect-worker.js.map +0 -1
  128. package/dist/create-verification-Ce1y5kJR.d.ts +0 -371
  129. package/dist/create-verification-Dkb2tXuY.d.cts +0 -371
  130. package/dist/detector-scanic-4C6IEW2K.js +0 -787
  131. package/dist/detector-scanic-4C6IEW2K.js.map +0 -1
  132. package/dist/hosted-client-DWzCRYJK.d.cts +0 -421
  133. package/dist/hosted-client-DWzCRYJK.d.ts +0 -421
  134. package/dist/index.cjs.map +0 -1
  135. package/dist/index.js.map +0 -1
  136. package/dist/internal/index.cjs.map +0 -1
  137. package/dist/internal/index.js.map +0 -1
  138. package/dist/popup/index.cjs.map +0 -1
  139. package/dist/popup/index.js.map +0 -1
  140. package/dist/scanic-ml-stub-S2OZ6HEF.js +0 -10
  141. package/dist/scanic-ml-stub-S2OZ6HEF.js.map +0 -1
@@ -0,0 +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 ie,g as st,h as K,i as at,j as M,k as j,l as V,m as D,n as U,o as X,p as ut,q as z,r as se,s as ct,t as dt,u as lt,v as pt}from"./chunk-M3637QGB.js";import{n as et}from"./chunk-BPAGOPYL.js";import{a as ze}from"./chunk-7QZWBDI5.js";import{c as G,e as tt,g as nt,h as ae}from"./chunk-QZUFICG3.js";import{c as Je,d as ke}from"./chunk-TSA6GHUG.js";import{b as Xe}from"./chunk-22AW4NJD.js";function gt(e){let t=e.now??(()=>Date.now()),n=e.setTimer??((h,p)=>setTimeout(h,p)),i=e.clearTimer??(h=>clearTimeout(h)),r=null,u=!1,s=!1,c=!1,f=0,S=null,_=()=>{S!==null&&i(S),S=null},A=()=>{let h=e.armRamp;h===void 0||u||s||c||t()<f||(u=!0,h().catch(()=>{}).then(p=>{if(u=!1,!c){if(p===void 0){f=t()+2e3;return}if(p.challenge===void 0){s=!0;return}r={challenge:p.challenge,expiresAt:p.expiresAt},_(),S=n(()=>{S=null,!c&&r!==null&&e.waiting()&&A()},Math.max(1e3,p.expiresAt-t()-2e4))}}))};return{arm(){r!==null&&r.expiresAt-t()>2e4||A()},take(){let h=r;return r=null,_(),h!==null&&h.expiresAt-t()>=12e3?h.challenge:void 0},stop(){c=!0,r=null,_()}}}function ue(e){return e.idNumberBound??e.nniBound}function ee(e){return e===void 0?void 0:e.idNumberFromDocument??e.nniFromDocument}function St(e){let t=e.idNumberMasked??e.nniMasked;return typeof t=="string"&&t!==""?t:void 0}var Xt="https://api.sekyro.ai",zt=5e3,en=24e4,tn=9e4,nn=25*6e4,on=20*6e4,rn=3,sn=3e3,an=1500,un=10;function _t(e){return e instanceof Error&&e.name==="ChallengeError"&&e.code||"challenge_failed"}var kt=new Set(["aborted","embedder_opaque","site_key_rejected"]);function cn(e){return new Promise(t=>setTimeout(t,e))}function dn(){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 Po(e){return ln(e,{})}function ln(e,t){let n=e.apiOrigin??Xt,i=e.autoRetry??!0,r=e.rearm??"auto",u=t.client??new nt({apiOrigin:n,sessionToken:e.clientToken,fetch:e.fetch,locale:e.locale}),s=new Proxy(u,{get(o,a){if(a==="submitCheck")return Bt;let d=Reflect.get(o,a,o);return typeof d=="function"?d.bind(o):d}}),c=t.sleep??cn,f=t.uuid??dn,S=t.getChallengeToken??((o,a)=>import("./challenge-frame-YBTLAQ5G.js").then(d=>d.executeChallenge({frameUrl:o.url,siteKey:o.siteKey,action:"liveness",subject:a.subject,signal:a.signal}))),_=ze(),A=null,h=null,p=!1,E=new AbortController,k=null,de=null,te=null,ne=()=>te??ct(k),oe=()=>dt(se(k),ne()),I=o=>{k=o,!M(o)&&(Be(on)||Dt(o))&&_e(o),_.emit("view",o),A?.onView(o)},x=()=>k!==null?Promise.resolve(k):(de??(de=s.getSession().then(o=>(I(o),o)).finally(()=>{de=null})),de),v=async()=>{let o=await s.getSession();return I(o),o},le=async(o,a)=>{o.plan!==void 0?I(o):await v()},pe=null,Me=async o=>{let a=await x();if(o||!a.consentRecorded){let d=await s.recordConsent(e.locale);d.plan!==void 0?I(d):k!==null&&I({...k,consentRecorded:!0})}re()&&_e(a)},N=o=>o?.force===!0?Me(!0):(pe??(pe=Me(!1).finally(()=>{pe=null})),pe),fe={client:s,ensureConsent:o=>N(o),sleep:c,uuid:f,...t.random!==void 0?{random:t.random}:{},onBusy:o=>{p||_.emit("busy",o)}},Oe=!1,Ee=null,me=o=>{if(o.status==="verified"||o.status==="not_verified"||o.status==="review"){if(Oe)return;Oe=!0}Ee=JSON.stringify(o),_.emit("result",o)},Nt=o=>{Ee!==JSON.stringify(o)&&me(o)},Ie=async o=>{let a=k;o&&(a=await v().catch(()=>k));let d=a===null?null:K(a);return d!==null&&!p&&_.emit("method",d),d!==null},ve=null,Te=!1,Ve=!1,Fe=()=>mt(fe,(o,a)=>o.submitCheck("population_registry",{},{idempotencyKey:a})),Ne=o=>ue(o)===!0||ee(V(o,"population_registry"))===!0,Ht=async()=>{try{let o=await x();if(M(o)||K(o)!==null||j(o)?.checkType!=="population_registry")return;if(!Ne(o)&&ee(V(o,"population_registry"))===void 0&&(o=await v()),!Ne(o)){Ve=!0;return}await N(),await le(await Fe(),"population_registry");let a=k===null?void 0:V(k,"population_registry");if(a?.state==="input_required"&&a.reason==="registry_unavailable"&&ie(a)>0){if(await c(zt),p)return;await le(await Fe(),"population_registry")}}catch(o){if(o instanceof G&&(o.code==="check_not_active"||o.code==="step_not_on_path")){await v().catch(()=>{});return}Te=!0;return}k!==null&&M(k)&&me(X(k,{autoRetry:i}))},He=()=>(ve??(ve=Ht()),ve),T=t.now??Date.now,q=null,Y,he,Lt=0,ye=(o,a)=>`${o.url}
2
+ ${o.siteKey}
3
+ ${a}`,Le=0,ge,Se=(o,a)=>{Le+=1;let d=T(),y=S(o,{signal:E.signal,subject:a}),m={key:ye(o,a),at:d,token:y};return y.then(()=>{m.issuedAt=T(),he=void 0},C=>{let g=_t(C);if(m.failed=g,p||g==="aborted")return;he=g;let{detail:b,readyMs:l}=C;W({check:"attestation",kind:"unavailable",engineKind:g,attempt:Lt++,challengeMs:T()-d,readyMs:l,detail:b,inApp:Xe()})}),y.catch(()=>{}),m},De=(o,a)=>o!==null&&o.key===a&&(o.issuedAt===void 0||T()-o.issuedAt<en),_e=(o,a={})=>{let d=o?.challenge??null;if(o===null||d===null||p)return;let y=D(o.sessionId),m=q;(a.replaceFailed===!0&&m?.failed!==void 0&&!kt.has(m.failed)||!De(m,ye(d,y)))&&(q=Se(d,y))},Ue=async(o,a)=>{let d=ye(o,a),y=q;q=null;let m=De(y,d)?y:Se(o,a),C=m===y?0:1,g,b=new Promise(l=>{g=setTimeout(()=>l("late"),tn)});try{for(;;){let l=await Promise.race([m.token.then(P=>({token:P}),P=>({error:_t(P)})),b]);if(l==="late")return!p&&q===null&&(q=m),{error:he??"timeout"};if("token"in l)return ge=Math.max(0,Math.round((m.issuedAt??T())-m.at)),l;if(p||kt.has(l.error)||C>=rn||C>0&&await Promise.race([c(sn*C),b])==="late")return l;if(p)return{error:"aborted"};C+=1,m=Se(o,a)}}finally{clearTimeout(g)}},L=null,Dt=o=>J(o).some(a=>(a.checkType==="phone_otp"||a.checkType==="email_otp")&&a.state!=="passed"&&a.state!=="skipped"),Be=o=>L===null||T()-L>=o,re=()=>Be(nn),Ut=o=>{let a=o.attestation;return typeof a?.turnstileToken=="string"&&a.turnstileToken.length>0},qe=new Map,Ge=async()=>{let o=await x(),a=o.challenge;if(a==null||o.simulation!==void 0)return;let d=await Ue(a,D(o.sessionId));if(!("token"in d))throw new G({status:400,code:"attestation_invalid",message:`browser check: ${d.error}`});return d.token},Bt=async(o,a,d={})=>{let y=a;if("attestation"in y)try{let l=await u.submitCheck(o,a,d);return Ut(y)&&(L=T()),l}catch(l){throw l instanceof G&&l.code==="attestation_invalid"&&(L=null),l}let m=(o==="phone_otp"||o==="email_otp")&&y.action!=="verify",C=d.idempotencyKey,g=C!==void 0?qe.get(C):void 0;g===void 0&&(m||re())&&(g=await Ge(),C!==void 0&&g!==void 0&&qe.set(C,g));let b=(l,P)=>l!==void 0?{...P,browserCheckToken:l}:P;try{let l=await u.submitCheck(o,a,b(g,d));return g!==void 0&&(L=T()),l}catch(l){if(!(l instanceof G)||l.code!=="attestation_invalid"||(L=null,g!==void 0))throw l;let P=await Ge(),O=C!==void 0?{...d,idempotencyKey:f()}:d,H=await u.submitCheck(o,a,b(P,O));return P!==void 0&&(L=T()),H}},Ke=async(o={})=>{if(Y=void 0,o.always!==!0&&!re())return{};let a=await x(),d=a.challenge;if(d==null)return{};let y=await Ue(d,D(a.sessionId));if("token"in y)return{channel:"hosted_web",turnstileToken:y.token};if(Y=y.error,a.simulation!==void 0)return{channel:"hosted_web"};throw new ft(y.error)},qt=()=>Y,Gt=()=>({checks:Math.min(50,Le),...ge!==void 0?{challengeMs:Math.min(6e5,ge)}:{}}),W=o=>{if(p)return;let a=s.reportCaptureIssue;if(a===void 0)return;let d=o.formFactor;try{d??(d=Je())}catch{}try{Promise.resolve(a.call(s,{...o,...d!==void 0?{formFactor:d}:{}})).catch(()=>{})}catch{}},R=null,$=null,je=new WeakMap,Ye=Promise.resolve(),Q=0,Kt=async()=>{let o=await x();for(let a=0;a<un&&!p&&!M(o)&&j(o)===void 0&&J(o).some(d=>d.state==="processing")&&(await c(an),!p);a+=1)o=await v();return o},jt=async(o,a,d)=>{let{capture:y}=o,m=()=>p,C=()=>o.alive&&o.attempt===d,g=l=>{C()&&y.setFlowState(l)},b=l=>{if(!m()&&(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)}),me(l),!!C())){if(l.status==="retry"&&r==="auto"){y.handle.retry();return}y.setFlowState("done")}};if(a.degraded==="NO_RECORDER"){let l=k?.sessionId??(await x().catch(()=>null))?.sessionId??"";b(U(l,"no_recorder"));return}g("uploading");try{if(await He(),m())return;let l=await x(),P;if(!M(l)&&K(l)!==null){await Ie(!1),b(U(l.sessionId,"method_required"));return}if(!M(l)){if(j(l)?.checkType==="population_registry"){b(U(l.sessionId,Ve?"nni_unbound":Te?"network":"registry_unavailable"));return}if(await N(),m())return;P=k??l;let O=await ht({...fe,artifacts:a,getAttestation:Ke,attestationError:qt,attestationFacts:Gt,clipKeys:{get:()=>je.get(a)??null,set:H=>{je.set(a,H)}},getView:()=>k??l,refreshView:v,applySubmit:le,onPhase:g,isCancelled:m,onKeyframePromoted:H=>{h=H}});if(m())return;if(O.kind==="unavailable"){O.reason==="attestation"&&($={bound:o,artifacts:a});let H=U(l.sessionId,O.reason),Ze=O.reason==="attestation"?Y:void 0;b(Ze!==void 0?{...H,attestationError:Ze}:H);return}if(O.kind==="resync"&&await v(),k!==null&&K(k)!==null){await Ie(!1),b(U(l.sessionId,"method_required"));return}l=await Kt()}b(X(l,{autoRetry:i,previous:P}))}catch{if(m())return;b(U(k?.sessionId??"","network"))}},We=(o,a)=>{let d=o.attempt;Q>0&&o.alive&&o.capture.setFlowState("uploading"),Q+=1,Ye=Ye.then(()=>jt(o,a,d)).finally(()=>{Q-=1,Q===0&&A?.onChainIdle()}).catch(()=>{})},$e=o=>{R?.capture.handle.destroy(),R!==null&&(R.alive=!1,R.ramp.stop());let a=gt({armRamp:typeof s.armRamp=="function"?()=>s.armRamp():void 0,waiting:()=>m.alive&&oe()==="self"&&(y.handle.state==="starting"||y.handle.state==="gating")}),d=Promise.resolve(),y=et(o,A?.captureInternals?.(o)??t.capture,()=>k?.capture?.liveness?.keyframe?.rank===!0,oe,()=>a.take()??k?.capture?.liveness?.screenRamp,{session:()=>se(k),onModeChange:g=>{te=g}}),m={capture:y,alive:!0,ramp:a,attempt:0,issues:it()};R=m,y.handle.on("error",g=>{W(rt("liveness",g,m.issues.value))}),y.handle.on("state",g=>{if(m.issues.note(g),g==="starting"){m.attempt+=1,$?.bound===m&&($=null),re()&&_e(k,{replaceFailed:!0});let b=k===null?void 0:j(k)?.checkType;d=b==="liveness"||b==="face_match"?N().catch(()=>{}):Promise.resolve()}(g==="starting"||g==="gating")&&oe()==="self"&&d.then(()=>{m.alive&&a.arm()})}),y.handle.on("captured",g=>{Promise.resolve().then(()=>We(m,g))});let C=y.handle;return{get state(){return C.state},get captureMode(){return C.captureMode},get facingMode(){return C.facingMode},on:(g,b)=>C.on(g,b),start:async g=>{if(k===null&&await x().catch(()=>{}),!!m.alive)return C.start(g)},retry:()=>{let g=$;if(g!==null&&g.bound===m&&m.alive){$=null,We(m,g.artifacts);return}C.retry()},switchCamera:()=>C.switchCamera(),canSwitchCaptureMode:()=>C.canSwitchCaptureMode(),setCaptureMode:g=>C.setCaptureMode(g),destroy:()=>{m.alive=!1,a.stop(),R===m&&(R=null),C.destroy()}}},Yt=async()=>{if(p)return null;try{let o=await x();return p?null:K(o)}catch{return null}},Wt=async()=>{if(p)return"self";try{let o=await x();if(p)return"self";let a=se(o);return a==="choice"?ne()??a:a}catch{return"self"}},$t=async()=>{if(p)return!1;try{let o=await x();return p||M(o)||ke()?!1:z(o,j(o))==="phone"||z(o,V(o,"liveness"))==="phone"}catch{return!1}},Qt=async()=>{if(p)return!1;try{let o=await x();return!p&&o.returning===!0}catch{return!1}},Zt=async o=>{let a=(await x()).plan?.choice,d=a?.options.find(m=>Z[m.service]===o);if(!d)throw new RangeError(`method ${String(o)} is not offered`);let y=await s.choose(a.nodeId,d.id);p||I(y)},Qe=null,Jt=()=>(Qe??(Qe=import("./plan-runner-3BLEJWHF.js").then(o=>{let a=o.createPlanRunner({runtime:fe,currentView:()=>k,cameraMode:oe,captureModeSwitch:{pick:ne,choose:d=>{te=d}},ensureView:x,refreshView:v,ensureConsent:()=>N(),liveness:$e,stopLiveness:()=>{R!==null&&(R.alive=!1,R.ramp.stop(),R.capture.handle.destroy(),R=null)},chainBusy:()=>Q>0,destroyed:()=>p,sleep:c,isMobile:ke,now:t.now??Date.now,keptFaceKey:()=>h,setView:I,baseCapture:t.capture,emitStep:d=>{p||_.emit("step",d)},emitResult:Nt,reportCaptureIssue:W,documentInternals:t.document,documentFacts:t.documentFacts,portraitInternals:t.portrait,livePhotoInternals:t.livePhoto,uploadInternals:t.upload,pageCameraInternals:t.pageCamera});return A=a,a})),Qe);return{consent:()=>N(),startRegistry:He,methodChoice:Yt,selectMethod:Zt,reportCameraUnavailable:async o=>{await N();let a=s.reportCameraUnavailable;if(a===void 0)throw new TypeError("this client cannot report a missing camera");let d=await a.call(s,o).catch(y=>{if(y instanceof G&&y.code==="check_out_of_order")return s.getSession();throw y});p||I(d)},reportCaptureIssue:W,testerGate:async o=>{let a=s.testerGate;if(a===void 0)throw new TypeError("this client cannot run the tester gate");let d=o.clip,y=tt(o.clipMime??"");if(d===void 0||!pt.includes(y))throw new TypeError("the capture has no clip");await N();let m=await lt(s,"clip",y,d.size,{engine:o.engine,durationMs:o.clipMs});await s.uploadToSpaces(m.uploadUrl,d,y);let{key:C}=await s.completeMedia(m.key),g=await Ke({always:!0}),b=await a.call(s,{clipKey:C,attestation:g,captureChannel:o.captureChannel,capture:{...yt(o),attestationError:Y}}),{bound:l,missReason:P,...O}=b;return p||(O.plan!==void 0?I(O):await v()),l===!0||P===void 0?{bound:l===!0}:{bound:!1,missReason:P}},mobileRequired:$t,captureMode:Wt,chooseCaptureMode:o=>{te=o},get captureChoice(){return ne()},returning:Qt,liveness:$e,run:async()=>{if(p)throw new Error("verification destroyed");return(await Jt()).run()},currentStep:()=>A?.current()??null,voiceClips:async()=>{if(p)return null;try{let o=await x();return p?null:o.voice??null}catch{return null}},on:(o,a)=>_.on(o,a),destroy:()=>{p=!0,E.abort(),A?.destroy(),R!==null&&(R.alive=!1,R.capture.handle.destroy(),R=null),_.clear()}}}var Ct=["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 pn=["carte_identite","passport","residence_permit","drivers_license"],fn=["carte_identite","passport","residence_permit"];function mn(e,t){let n=e.byIssuer?.[t]??e.default;return pn.filter(i=>n==="*"?fn.includes(i):n.includes(i))}function Io(e,t=Ct){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(i=>mn(e,i).length>0).sort()}function bt(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}function vo(e){return/^[A-Z]{2}$/.test(e)?String.fromCodePoint(...[...e].map(t=>127462+t.charCodeAt(0)-65)):""}var w={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"},hn=new Set(["full_name","birth_date","email","phone","address","country","occupation"]),yn=new Set(["short_text","long_text","single_choice","multiple_choice","yes_no","date","number"]),gn=new Set(["ar","fa","he","ur"]);function wt(e){return gn.has(e.split("-")[0]?.toLowerCase()??"")?"rtl":"ltr"}function At(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(!Sn(r))return null;for(let r of n)if(!_n(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 Sn(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"&&hn.has(t.field):t.kind!=="custom"||typeof t.type!="string"||!yn.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 _n(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 kn=/^(\d{4})-(\d{2})-(\d{2})$/;function Cn(e){if(typeof e!="string")return!1;let t=kn.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>=w.dateMin&&e<=w.dateMax}function bn(e){return typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<w.number&&Math.round(e*100)/100===e}function Rt(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&&wn(n))return!0}return!1}function wn(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 An=/^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$/,Rn=/^\+[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 Vo(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 s=r.kind==="field"?Mn(r.field,u,n):En(r,u,n);s!==null&&i.push({id:r.id,...s})}for(let r of e.consents)r.required&&t.consents[r.id]!==!0&&i.push({id:r.id,code:"consent_required"});return i}function ce(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}}:Rt(i)?{code:"card_number"}:null}function Pt(e,t,n={}){return Cn(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 Mn(e,t,n){switch(e){case"full_name":return ce(t,w.fullName,w.fullNameMin);case"occupation":return ce(t,w.occupation);case"birth_date":return Pt(t,n,{period:"past"});case"email":return typeof t=="string"&&t.trim().length<=w.email&&An.test(t.trim())?null:{code:"email_invalid"};case"phone":return typeof t=="string"&&Rn.test(t)?null:{code:"phone_invalid"};case"country":return typeof t=="string"&&xt.test(t)?null:{code:"choice_invalid"};case"address":return On(t)?null:{code:"address_invalid"};default:return null}}function On(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<=w.city&&n.length>=1&&n.length<=w.addressLines&&n.every(i=>i.trim().length<=w.addressLine&&!Rt(i))&&(t.postcode===void 0||typeof t.postcode=="string"&&t.postcode.trim().length<=w.postcode)}function En(e,t,n){let i=new Set((e.choices??[]).map(r=>r.value));switch(e.type){case"short_text":return ce(t,w.shortText);case"long_text":return ce(t,w.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)>=w.number)return{code:"number_invalid"};let r=e.options??{};return r.integer===!0&&!Number.isInteger(t)?{code:"number_not_integer"}:bn(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 Fo={full_name:w.fullName,occupation:w.occupation,email:w.email,short_text:w.shortText,long_text:w.longText};var Mt=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"}),In=new Map(Object.entries(Mt)),Ho=new Map(Object.entries(Mt).map(([e,t])=>[t,e]));function Ot(e){return In.get(e)??e}var Yo=["national_number","document_photo","national_eid"],vn=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"]),Tn=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),be=["document","population_registry","national_eid"],we=["phone_otp","email_otp"],vt={identity_method:be,contact:we},Vn=["population_registry","document"],Ae="platform_unsupported",Fn=new Set(["prefilled","user_entered","prefilled_or_entered"]),Nn={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 F(e){return e.section??Nn[e.checkType]??null}function Hn(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 Wo(e,t){let n=e.options.filter(s=>s.id!==e.current);if(t===void 0)return{switchTo:n,methods:[]};let i=s=>s.countries!==void 0&&s.countries.length>0;if(t===null)return{switchTo:n.filter(s=>!i(s)),methods:[]};let r=t.toUpperCase(),u=s=>!i(s)||s.countries.includes(r);return{switchTo:n.filter(u),methods:n.filter(s=>i(s)&&u(s))}}function $o(e,t,n){let i=e.names?.[t.toUpperCase()],r=i?.[n]??i?.en;if(r!==void 0&&r!=="")return r;let u=e.nationalEid?.providerName;return u!==void 0&&u!==""?u:void 0}function Qo(e){return e===void 0?[]:[...new Set(e.options.filter(t=>t.id!==e.current).flatMap(t=>t.countries??[]).map(t=>t.toUpperCase()))]}function Re(e){let t=e.plan,n=t?.choice;if(t===void 0||n===void 0||n.locked||t.current===null||t.current===n.nodeId||M(e))return null;let i=vt[n.kind]??[...be,...we],r=n.options.flatMap(c=>{if(c.available===!1||!i.includes(c.service))return[];let f=c.nationalEid!=null?{id:c.id,service:c.service,nationalEid:c.nationalEid}:{id:c.id,service:c.service},S=c.countries??(c.nationalEid!=null?[c.nationalEid.country]:void 0);return S!==void 0&&S.length>0&&(f.countries=S),c.names!=null&&Object.keys(c.names).length>0&&(f.names=c.names),[f]}),u=t.steps.find(c=>c.id===t.current)?.service,s=n.selected??r.find(c=>c.service===u)?.id??null;return r.some(c=>c.id!==s)?{nodeId:n.nodeId,kind:n.kind,current:s,options:r}:null}function Tt(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function Ln(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 Dn(e){let t=e.levelTarget?.max;return typeof t=="number"&&t<=1?"contact":e.purpose??"identity"}function Un(e){let t=(e.plan?.sections??[]).map(s=>({id:s.id,state:s.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(s=>s.id),progress:t,purpose:e.purpose??"identity",levelName:Dn(e)};e.branding!==void 0&&(n.branding=e.branding),e.cameraUnavailableHandled===!0&&(n.cameraUnavailableHandled=!0);let i=Ln(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=Re(e);return u!==null&&(n.switchable=u),n}function Bn(e){let t={attemptsRemaining:ie(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 Vt={phone_otp:"phone",email_otp:"email"};function qn(e,t){let n=Hn(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return n===void 0?void 0:Vt[n.option.service]}function Gn(e,t,n,i){let r=t.checkType==="email_otp",u=(r?t.emailOtp:t.otp)??{},s=r?t.emailOtp?.emailSource:t.otp?.numberSource,c=s!==void 0&&Fn.has(s)?s:r?"prefilled_or_entered":"user_entered",f=typeof u.sentToMasked=="string"&&u.sentToMasked.length>0,S=u.prefilled===!0,_=qn(e,r?"email_otp":"phone_otp"),A={key:t.checkType,context:n,section:F(t),phase:f?"verify":"send",canSwitch:_!==void 0,...i},h=r?{kind:"email_otp",...A,emailSource:c,needsEmail:c!=="prefilled"&&!S}:{kind:"phone_otp",...A,numberSource:c,needsPhone:c!=="prefilled"&&!S,channels:(t.otp?.channels??[]).filter(p=>p==="whatsapp"||p==="sms")};if(_!==void 0&&(h.switchChannel=_),S&&(h.prefilled=!0),f&&(h.sentToMasked=u.sentToMasked),!r&&t.otp?.channel!==void 0&&(h.channel=t.otp.channel),!r&&Array.isArray(t.phoneCountries)&&(h.phoneCountries=t.phoneCountries.filter(p=>typeof p=="string"&&/^[A-Z]{2}$/.test(p))),!r&&Array.isArray(t.phoneRules)){let p=h.phoneCountries??[];h.phoneRules=t.phoneRules.flatMap(E=>{let k=Yn(E);return k!==void 0&&p.includes(k.code)?[k]:[]})}return!r&&t.phoneInternational===!0&&(h.phoneInternational=!0),u.expiresAt!==void 0&&(h.codeExpiresAt=u.expiresAt),u.resendAvailableAt!==void 0&&(h.resendAvailableAt=u.resendAvailableAt),h}var Kn=/^[\d[\]\-|()?:^]{1,64}$/;function jn(e){try{return typeof e=="string"&&Kn.test(e)&&new RegExp(e)!==null}catch{return!1}}var Et=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function Yn(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(Et))return;let s={code:t,dial:n,lengths:[...r].sort((c,f)=>c-f)};if(i!==void 0&&(s.trunk=i),u!==void 0){if(!(Array.isArray(u)&&u.length<=8&&u.every(f=>jn(f?.leading)&&Array.isArray(f.groups)&&f.groups.every(Et)&&r.includes(f.groups.reduce((S,_)=>S+_,0)))))return;s.formats=u.map(f=>({leading:f.leading,groups:[...f.groups]}))}return s}function Wn(e,t,n,i){let r=ue(e)===!0?"bound":ee(t)===!0?"document":"typed",u=r==="typed"&&t.state==="input_required"&&t.reason!==void 0&&Ot(t.reason)==="id_number_recheck",s=Tt(Re(e)),c=!i.attemptsExhausted&&s.length===1&&s[0]?.service==="document";return{kind:"registry",key:"registry",context:n,section:F(t),state:t.state==="input_required"?"input_required":"pending",source:r,recheck:u,canUseDocument:c,...i}}function $n(e,t,n,i,r){let u=[...t.acceptedSides??[]],s={kind:"document",key:"document",context:n,section:F(t),side:u.includes("recto")?"verso":"recto",acceptedSides:u,documents:bt(e),photo:Pe(xe(e.documents),r),...i};return e.detectedCountry!==void 0&&(s.detectedCountry=e.detectedCountry),Jn(e)&&(s.ageStepUp=!0),s}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 Qn=10*1024*1024;function Zn(e,t,n,i,r){let u=e.proofOfAddress,s=u?.pdf?.maxBytes,c=u?.phase==="holder_letter"?"holder_letter":"document";return{kind:"proof_of_address",key:"proof_of_address",context:n,section:F(t),phase:c,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 s=="number"&&s>0?s:Qn,maxPages:3},licenceAddressAccepted:c==="document"&&u?.licenceAddressAccepted===!0,...i}}function Jn(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 Xn(e){let t=V(e,"liveness");return t?.state==="passed"||t?.state==="review"}function It(e,t,n,i,r,u=!1){let s=t.icao?.report,c=e.portrait,f=r==="capture"?c?.pendingFix??null:null;f!==null&&(r="review");let S=Ft(e);return{kind:"portrait",key:`portrait:${r}`,context:n,section:F(t),phase:r,report:Array.isArray(s)?s:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:ae(e),retakeOnly:r==="capture"&&t.state==="input_required"&&S===void 0&&e.capture?.livePhoto?.oneCapture===!0&&Xn(e),photo:Pe(xe(c,r==="capture"),u&&r==="capture"),pendingFix:f,...S!==void 0?{captureMode:S}:{},...c?.reuse?.pending===!0?{reuse:!0}:{},...i}}function Ft(e){let t=e.portrait?.captureMode;return t==="self"||t==="assisted"||t==="choice"?t:void 0}var Ce={minLongSidePx:1280,jpegQuality:.95};function zn(e,t){let n=e.capture?.livePhoto;if(n?.oneCapture!==!0)return null;let i=V(e,"portrait_icao"),r=n.still??Ce;return{icao:t==="liveness"&&ae(e)!==null&&Ft(e)===void 0&&i!==void 0&&i.state==="pending"&&i.reason===void 0,still:{minLongSidePx:r.minLongSidePx??Ce.minLongSidePx,jpegQuality:r.jpegQuality??Ce.jpegQuality}}}function eo(e,t,n,i){let r=t.eid,u=F(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 s=Tt(Re(e)),c=s.length===1&&Vn.includes(s[0]?.service??"")?s[0]:void 0,f=c===void 0?void 0:Z[c.service],S=f!==void 0,_={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:S,afterPass:r.afterPass==="continue"?"continue":"end",...i};return S&&(_.cameraMethod=f),r.expiresAt!==void 0&&(_.codeExpiresAt=r.expiresAt),r.resendAvailableAt!==void 0&&(_.resendAvailableAt=r.resendAvailableAt),r.resendsRemaining!==void 0&&(_.resendsRemaining=r.resendsRemaining),r.codeAttemptsRemaining!==void 0&&(_.codeAttemptsRemaining=r.codeAttemptsRemaining),_}function to(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let n=V(e,"portrait_icao");return n!==void 0&&(n.state==="passed"||n.state==="review")?n:null}var no={rejected:"rejected",inconclusive:"inconclusive",unavailable:"unavailable",abandoned:"expired",not_opened:"expired",cancelled:"expired",superseded:"expired",policy:"policy"};function oo(e){return e.reasonCode===Ae?"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?no[e.reason]:void 0)??"rejected"}function ro(e,t){let n=oo(e),i=n==="platform_unsupported"?{sessionId:D(e.sessionId),status:"unavailable",reasonCode:Ae}: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 io(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 s of so){let c=i[s];typeof c=="string"&&c!==""&&(r[s]=c)}let u=St(i);return u!==void 0&&(r.idNumberMasked=u,r.nniMasked=u),r}var so=["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 ao(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function uo(e,t){let n=vt[e.kind]??[...be,...we],i=ao(e),r=e.options.flatMap(s=>{if(s.available===!1||!n.includes(s.service))return[];let c={id:s.id,service:s.service};s.nationalEid!=null&&(c.nationalEid=s.nationalEid);let f=(s.channels??[]).filter(S=>S==="whatsapp"||S==="sms");return s.service==="phone_otp"&&f.length>0&&(c.channels=f),[c]});if(r.length===0){let s=e.options.length>0&&e.options.every(c=>c.service==="nfc");return B(t,i,"choice",s?"platform_unsupported":"update_required")}let u={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:r};if(e.kind==="identity_method"){let s={kind:"method",key:"method",context:t,section:i,options:r.map(f=>Z[f.service]),choice:u},c=r.find(f=>f.nationalEid!==void 0)?.nationalEid;return c!==void 0&&(s.nationalEid=c),s}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:i,options:r.map(s=>Vt[s.service]),selected:null,locked:!1,choice:u}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:i,choice:u}}function co(e,t,n,i){let r=e.nativeApp,u=typeof r=="object"&&r!==null?r:{},s={sekyroApp:u.sekyroApp===!0};return typeof u.link=="string"&&u.link!==""&&(s.link=u.link),s.sekyroApp&&typeof u.sekyroAppLink=="string"&&u.sekyroAppLink.startsWith("sekyro://")&&(s.sekyroAppLink=u.sekyroAppLink),{kind:"native_app_required",key:`native_app_required:${i}`,context:t,section:n,checkType:i,nativeApp:s}}function Zo(e,t={}){let n=Un(e);if(M(e)||e.reasonCode===Ae)return ro(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 uo(r,n);let u=i.current===null?void 0:i.steps.find(h=>h.id===i.current),s=h=>{let p={kind:"processing",key:"processing",context:n,section:h!==void 0?F(h):i.sections.find(E=>E.state==="current")?.id??null,stalled:!1};return typeof h?.service=="string"&&h.service!==""&&(p.service=h.service),p};if(i.current===null)return s(i.steps.find(h=>h.state==="processing"));if(u===void 0)return B(n,null,"step","update_required");if(!vn.has(u.service))return u.interaction==="server"?s(u):B(n,F(u),u.service,"update_required");if(Tn.has(u.service)||!at(u))return s(u);let c=u,f=Bn(c),S=c.checkType,_=F(c);if(c.requiresNativeApp===!0)return co(e,n,_,S);let A=t.isMobile===!1?z(e,c):null;if(A==="phone")return{kind:"mobile_required",key:"mobile_required",context:n,section:_,checkType:S};switch(S){case"phone_otp":case"email_otp":return Gn(e,c,n,f);case"population_registry":return Wn(e,c,n,f);case"eid_auth":return eo(e,c,n,f);case"doc_ocr":return $n(e,c,n,f,A==="upload_or_phone");case"identity_confirm":return io(e,n,_)??s(c);case"portrait_icao":return It(e,c,n,f,"capture",A==="upload_or_phone");case"liveness":case"face_match":{let h=to(e,c);if(h!==null)return It(e,h,n,f,"match");let p=c.requiresMobile===!0,E=ae(e);return{kind:"liveness",key:"biometric",context:n,section:_,mode:S==="face_match"?"selfie":"liveness",requiresMobile:p,instructions:E===null?"standard":"icao",icao:E,livePhoto:zn(e,S),...f}}case"poa":return Zn(e,c,n,f,A==="upload_or_phone");case"form":{let h=At(c.form);return h===null?B(n,_,S,"update_required"):{kind:"form",key:"form",context:n,section:_,form:h,dir:wt(h.locale),...f}}case"nfc_chip":return B(n,_,S,"platform_unsupported");default:return B(n,_,S,"update_required")}}export{Xt as a,zt as b,an as c,un as d,dn as e,Po as f,ln as g,Ct as h,pn as i,mn as j,Io as k,bt as l,vo as m,w as n,wt as o,Cn as p,bn as q,Rt as r,Pn as s,Vo as t,Yo as u,Ae as v,F as w,Wo as x,$o as y,Qo as z,Re as A,Tt as B,to as C,Zo as D};
@@ -0,0 +1 @@
1
+ var b=new Set(["challenge_frame_blocked","challenge_script_blocked","site_key_rejected","challenge_failed","timeout","embedder_opaque"]),i=class extends Error{constructor(n,t){super(`Sekyro challenge failed: ${n}${t!==void 0?` (${t})`:""}`),this.name="ChallengeError",this.code=n,t!==void 0&&(this.detail=t)}},_=3e4,E=12e4,p="sekyro.challenge.",v="position:fixed;width:1px;height:1px;inset-block-start:0;inset-inline-start:0;opacity:0;pointer-events:none;border:0",c=null,g=Promise.resolve();function F(){u(),g=Promise.resolve(),m=!1}function d(){return new i("aborted")}function C(){let e=globalThis.crypto;return e!==void 0&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function h(e){return new URL(e,document.baseURI).origin}function u(){let e=c;if(e!==null){c=null,window.removeEventListener("message",e.listener),e.iframe.remove();for(let n of e.waiters.values())n.reject(new i("challenge_frame_blocked"));e.waiters.clear()}}function k(e,n){if(n.source!==e.iframe.contentWindow||n.origin!==e.origin)return;let t=n.data;if(typeof t!="object"||t===null)return;let r=t;if(typeof r.type!="string"||!r.type.startsWith(p)||r.v!==1)return;if(r.type==="sekyro.challenge.ready"){e.readyMs??(e.readyMs=Date.now()-e.insertedAt),e.isReady=!0,e.onReady?.();return}if(typeof r.id!="string")return;let a=e.waiters.get(r.id);if(a!==void 0){if(r.type==="sekyro.challenge.token"&&typeof r.token=="string"&&r.token!=="")e.waiters.delete(r.id),a.resolve(r.token);else if(r.type==="sekyro.challenge.error"){e.waiters.delete(r.id);let o=typeof r.code=="string"&&b.has(r.code)?r.code:"challenge_failed",s=typeof r.detail=="string"||typeof r.detail=="number"?String(r.detail).slice(0,32):void 0;a.reject(new i(o==="challenge_failed"&&s==="200100"?"clock_wrong":o,s))}}}function M(e){if(c!==null&&c.url===e)return c;u();let n=document.createElement("iframe");n.setAttribute("title","Security check"),n.setAttribute("aria-hidden","true"),n.setAttribute("tabindex","-1"),n.setAttribute("referrerpolicy","no-referrer"),n.setAttribute("style",v);let t={url:e,origin:h(e),iframe:n,isReady:!1,insertedAt:Date.now(),onReady:null,waiters:new Map,listener:r=>k(t,r)};return window.addEventListener("message",t.listener),n.src=e,document.body.appendChild(n),c=t,t}function A(e,n,t){return e.isReady?Promise.resolve():new Promise((r,a)=>{let o=()=>{clearTimeout(l),t?.removeEventListener("abort",s),e.onReady=null},s=()=>{o(),a(d())},l=setTimeout(()=>{o(),a(new i("challenge_frame_blocked"))},n);t?.addEventListener("abort",s,{once:!0}),e.onReady=()=>{o(),r()}})}async function y(e){if(e.signal?.aborted)throw d();let n=M(e.frameUrl);try{return await x(n,e)}catch(t){throw t instanceof i&&n.readyMs!==void 0&&(t.readyMs??(t.readyMs=n.readyMs)),t}}async function x(e,n){let t=n.signal;await A(e,n.readyTimeoutMs??_,t);let r=e.iframe.contentWindow;if(r===null)throw new i("challenge_frame_blocked");let a=n.timeoutMs??E,o=C(),s,l;try{return await new Promise((w,f)=>{e.waiters.set(o,{resolve:w,reject:f}),s=setTimeout(()=>f(new i("timeout")),a),t!==void 0&&(l=()=>f(d()),t.addEventListener("abort",l,{once:!0})),r.postMessage({type:"sekyro.challenge.request",v:1,id:o,siteKey:n.siteKey,action:n.action,subject:n.subject},e.origin)})}finally{clearTimeout(s),t!==void 0&&l!==void 0&&t.removeEventListener("abort",l),e.waiters.delete(o)}}var m=!1;function R(e,n){if(m)return;let t;if(n==="challenge_frame_blocked"){let r=e;try{r=h(e)}catch{}t=`Sekyro: the security check frame could not load. Allow \`frame-src ${r}\` in your Content-Security-Policy.`}else if(n==="embedder_opaque")t="Sekyro: the security check needs a page with an origin. Do not run the SDK in a sandboxed or data: document.";else return;m=!0,console.warn(t)}async function S(e){if(globalThis.origin==="null")throw new i("embedder_opaque");if(e.signal?.aborted)throw d();try{return await y(e)}catch(n){if(u(),e.signal?.aborted||n instanceof i&&n.code==="aborted")throw d();if(n instanceof i&&n.code==="timeout")throw n;try{return await y(e)}catch(t){throw u(),e.signal?.aborted?d():t instanceof i?t:new i("challenge_failed")}}}function T(e){let n=()=>S(e).catch(r=>{throw r instanceof i&&R(e.frameUrl,r.code),r}),t=g.then(n,n);return g=t.catch(()=>{}),t}export{i as a,_ as b,E as c,F as d,T as e};
@@ -1,357 +1 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/client/index.ts
21
- var client_exports = {};
22
- __export(client_exports, {
23
- HostedApiError: () => HostedApiError,
24
- HostedClient: () => HostedClient,
25
- KNOWN_CODES: () => KNOWN_CODES,
26
- isKnownCode: () => isKnownCode,
27
- stripMimeParams: () => stripMimeParams
28
- });
29
- module.exports = __toCommonJS(client_exports);
30
-
31
- // src/client/errors.ts
32
- var KNOWN_CODES = [
33
- // auth / addressing (session-token.guard, controllers' own-session guards)
34
- "session_token_invalid",
35
- // 401 — missing/invalid/expired/revoked token
36
- "session_token_required",
37
- // 403 — non-session-token principal on a hosted route (defensive)
38
- "session_token_session_mismatch",
39
- // 403 — route :id differs from the token's bound session
40
- "session_not_found",
41
- // 404 — token's session missing/foreign (findOwned)
42
- // rate limiting (session-token.guard — per-token + per-IP buckets)
43
- "rate_limit_exceeded",
44
- // 429 + Retry-After header (seconds)
45
- // consent gate (Task 0 — submit AND media presign/complete)
46
- "consent_required",
47
- // 409 — record consent before uploading/submitting
48
- // submit flow (sessions.service.submitCheck)
49
- "session_not_active",
50
- // 409 — session is terminal/review; no further submissions
51
- "check_not_found",
52
- // 404 — session has no such checkType
53
- "check_already_finalized",
54
- // 409 — re-submit of a terminal/review check
55
- "check_out_of_order",
56
- // 409 — only the frontier check accepts a submission
57
- "check_type_unsupported",
58
- // 400 — no registered executor for the checkType
59
- "force_outcome_forbidden",
60
- // 403 — forceOutcome on a live session (plan D-C)
61
- "attestation_invalid",
62
- // 400 (Task 1) — Turnstile/attestation failed; reload and retry
63
- "nni_locked",
64
- // 409 (Plan A Task 2) — session is bound to a server-provided NNI; a different client NNI was sent
65
- // media (media.service)
66
- "media_content_type_not_allowed",
67
- // 400 — outside the per-kind MIME allowlist
68
- "media_too_large",
69
- // 413 — over the per-kind byte cap
70
- "media_key_invalid",
71
- // 400 — not a well-formed pending key
72
- "media_key_forbidden",
73
- // 403 — key names another session's pending space
74
- "media_not_found",
75
- // 404 — no uploaded object behind the key
76
- "media_unreadable",
77
- // 422 — magic-byte sniff rejected the object
78
- "media_session_invalid",
79
- // 400 — sessionId unusable as a key segment (never in practice)
80
- // idempotency (idempotency.interceptor — Task 2)
81
- "idempotency_key_collision",
82
- // 409 — same key, different body hash
83
- "idempotency_in_progress",
84
- // 409 — concurrent identical request mid-flight (client auto-retries)
85
- "idempotency_key_required",
86
- // 400 — only on @Idempotent({required:true}) routes (none hosted yet)
87
- // validation + fallback
88
- "validation_error",
89
- // 400 — ValibotPipe rejection (camelToSnake of 'ValidationError')
90
- "internal_error",
91
- // 500 — unhandled server error
92
- // client-synthesized (never sent by the backend)
93
- "unknown_error",
94
- // unparseable (non-JSON) response body — error OR 2xx (defensive)
95
- "upload_failed",
96
- // the bare Spaces PUT answered non-2xx
97
- "network_error",
98
- // fetch rejected: connection drop / DNS / CORS / mid-transfer (status 0)
99
- "timeout"
100
- // AbortSignal.timeout fired — API calls 30 s default, Spaces PUT 15 min (status 0)
101
- ];
102
- function isKnownCode(code) {
103
- return KNOWN_CODES.includes(code);
104
- }
105
- var HostedApiError = class extends Error {
106
- constructor(args) {
107
- super(args.message);
108
- this.name = "HostedApiError";
109
- this.status = args.status;
110
- this.code = args.code;
111
- if (args.retryAfterSeconds !== void 0) this.retryAfterSeconds = args.retryAfterSeconds;
112
- }
113
- };
114
-
115
- // src/client/hosted-client.ts
116
- var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
117
- var SPACES_PUT_TIMEOUT_MS = 9e5;
118
- var UPLOAD_ERROR_SNIPPET_CHARS = 200;
119
- var IN_PROGRESS_RETRY_ATTEMPTS = 5;
120
- var IN_PROGRESS_RETRY_DELAY_MS = 400;
121
- function stripMimeParams(contentType) {
122
- return (contentType.split(";")[0] ?? "").trim();
123
- }
124
- var MEDIA_INPUT_FIELD = {
125
- liveness: "clipKey",
126
- face_match: "imageKey",
127
- doc_ocr: "imageKey"
128
- };
129
- var HostedClient = class {
130
- constructor(opts) {
131
- this.sessionId = null;
132
- this.bootstrap = null;
133
- this.apiOrigin = opts.apiOrigin.replace(/\/+$/, "");
134
- this.sessionToken = opts.sessionToken;
135
- const impl = opts.fetch;
136
- this.fetchImpl = (input, init) => (impl ?? globalThis.fetch).call(globalThis, input, init);
137
- this.requestTimeoutMs = opts.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
138
- this.retryAttempts = opts.inProgressRetry?.attempts ?? IN_PROGRESS_RETRY_ATTEMPTS;
139
- this.retryDelayMs = opts.inProgressRetry?.delayMs ?? IN_PROGRESS_RETRY_DELAY_MS;
140
- }
141
- /** Token-addressed bootstrap — the hosted page's first call. Caches the sessionId. */
142
- async getSession() {
143
- const view = await this.api("GET", "/hosted/session");
144
- this.sessionId = view.sessionId;
145
- return view;
146
- }
147
- /**
148
- * Record consent once (201; an idempotent replay answers 200 with
149
- * `alreadyRecorded: true`). Until recorded, media presign/complete AND check
150
- * submission answer 409 `consent_required`.
151
- */
152
- async recordConsent(locale) {
153
- return this.api("POST", "/hosted/consent", { body: { locale } });
154
- }
155
- /**
156
- * Presign a Spaces PUT for a new pending object. `contentType` is stripped of
157
- * MIME parameters defensively (the allowlist holds bare types; the engine's
158
- * `clipMimeType` carries codec params) — PUT with the SAME bare type, or the
159
- * signed-header check rejects the upload.
160
- */
161
- async presign(kind, contentType, contentLength) {
162
- const id = await this.ensureSessionId();
163
- const body = { kind, contentType: stripMimeParams(contentType), contentLength };
164
- return this.api("POST", `/sessions/${id}/media`, { body });
165
- }
166
- /**
167
- * Bare PUT to the presigned Spaces URL: EXACTLY the signed headers — the
168
- * declared Content-Type and the blob body. NO `x-session-token` (the
169
- * signature IS the credential; an extra header breaks nothing but leaks the
170
- * token to a third-party host) and no JSON envelope.
171
- *
172
- * `contentType` is param-stripped here too (idempotent for bare types): the
173
- * presign strips internally, so a caller composing manually with the engine's
174
- * parameterful `clipMimeType` would otherwise sign `video/webm` but PUT
175
- * `video/webm;codecs=…` — a signed-header mismatch S3 rejects at runtime.
176
- *
177
- * Timeout: 15 min (`AbortSignal.timeout(900_000)`, matching the presign TTL)
178
- * rather than the API calls' 30 s — a 15 MB clip on a slow link legitimately
179
- * exceeds 30 s, but a stalled in-flight socket must still be bounded (the TTL
180
- * alone only bounds when a PUT can START).
181
- *
182
- * Failures are ALWAYS typed: non-2xx throws {@link HostedApiError} with the
183
- * client-synthesized `upload_failed` (message carries a truncated S3 body
184
- * snippet — e.g. SignatureDoesNotMatch); a mid-transfer drop → `network_error`;
185
- * the timeout → `timeout`.
186
- */
187
- async uploadToSpaces(uploadUrl, blob, contentType) {
188
- let res;
189
- try {
190
- res = await this.fetchImpl(uploadUrl, {
191
- method: "PUT",
192
- headers: { "content-type": stripMimeParams(contentType) },
193
- body: blob,
194
- signal: AbortSignal.timeout(SPACES_PUT_TIMEOUT_MS)
195
- });
196
- } catch (err) {
197
- throw asTransportError(err);
198
- }
199
- if (!res.ok) {
200
- const snippet = (await res.text().catch(() => "")).slice(0, UPLOAD_ERROR_SNIPPET_CHARS);
201
- throw new HostedApiError({
202
- status: res.status,
203
- code: "upload_failed",
204
- message: `media upload failed (HTTP ${res.status})${snippet ? `: ${snippet}` : ""}`
205
- });
206
- }
207
- }
208
- /** Finalize an upload: the backend sniffs + promotes; returns the PROMOTED key to submit. */
209
- async completeMedia(key) {
210
- const id = await this.ensureSessionId();
211
- return this.api("POST", `/sessions/${id}/media/complete`, {
212
- body: { key }
213
- });
214
- }
215
- /**
216
- * Submit one check. Sends `{input, forceOutcome?}` (SubmitCheckSchema) and the
217
- * optional `x-idempotency-key` header. Returns the whitelisted SessionView.
218
- */
219
- async submitCheck(checkType, input, opts = {}) {
220
- const id = await this.ensureSessionId();
221
- const body = {
222
- input,
223
- ...opts.forceOutcome !== void 0 ? { forceOutcome: opts.forceOutcome } : {}
224
- };
225
- return this.api("POST", `/sessions/${id}/checks/${checkType}`, {
226
- body,
227
- ...opts.idempotencyKey !== void 0 ? { idempotencyKey: opts.idempotencyKey } : {}
228
- });
229
- }
230
- /**
231
- * Convenience composition: presign → PUT → complete → submit, passing the
232
- * PROMOTED key (from complete's response — never the pending presign key)
233
- * into the check's media input field (`clipKey` for liveness, `imageKey` for
234
- * face_match/doc_ocr). `extraInput` carries the remaining input fields
235
- * (liveness `attestation`, doc_ocr `side`). The media content type is
236
- * param-stripped ONCE and used for both presign and PUT, so the signed
237
- * header always matches.
238
- */
239
- async uploadAndSubmit(checkType, media, extraInput, opts = {}) {
240
- const bareType = stripMimeParams(media.contentType);
241
- const presigned = await this.presign(media.kind, bareType, media.blob.size);
242
- await this.uploadToSpaces(presigned.uploadUrl, media.blob, bareType);
243
- const completed = await this.completeMedia(presigned.key);
244
- const input = {
245
- ...extraInput,
246
- [MEDIA_INPUT_FIELD[checkType]]: completed.key
247
- };
248
- return this.submitCheck(checkType, input, opts);
249
- }
250
- // ── transport ──────────────────────────────────────────────────────────────
251
- /** The token's own sessionId — cached from getSession(), lazily bootstrapped. */
252
- async ensureSessionId() {
253
- if (this.sessionId !== null) return this.sessionId;
254
- this.bootstrap ?? (this.bootstrap = this.getSession().finally(() => {
255
- this.bootstrap = null;
256
- }));
257
- return (await this.bootstrap).sessionId;
258
- }
259
- /**
260
- * One API request: `${apiOrigin}/api/v2${path}`, `x-session-token` always,
261
- * AbortSignal timeout (30 s default), `{success, data}` unwrap on 2xx, flat
262
- * `{code, message}` → {@link HostedApiError} on non-2xx. EVERY failure is
263
- * typed: a rejected fetch → `network_error`, the timeout → `timeout`, an
264
- * unparseable 2xx body → `unknown_error` — the page never sees a raw
265
- * TypeError/DOMException. The ONLY automatic retry is 409
266
- * `idempotency_in_progress` (bounded, short delay).
267
- */
268
- async api(method, path, opts = {}) {
269
- const url = `${this.apiOrigin}/api/v2${path}`;
270
- const headers = { "x-session-token": this.sessionToken };
271
- if (opts.body !== void 0) headers["content-type"] = "application/json";
272
- if (opts.idempotencyKey !== void 0) headers["x-idempotency-key"] = opts.idempotencyKey;
273
- for (let attempt = 0; ; attempt++) {
274
- let res;
275
- try {
276
- res = await this.fetchImpl(url, {
277
- method,
278
- headers,
279
- ...opts.body !== void 0 ? { body: JSON.stringify(opts.body) } : {},
280
- signal: AbortSignal.timeout(this.requestTimeoutMs)
281
- });
282
- } catch (err2) {
283
- throw asTransportError(err2);
284
- }
285
- if (res.ok) {
286
- let raw;
287
- try {
288
- raw = await res.json();
289
- } catch {
290
- throw new HostedApiError({
291
- status: res.status,
292
- code: "unknown_error",
293
- message: `response body was not valid JSON (HTTP ${res.status})`
294
- });
295
- }
296
- return unwrap(raw);
297
- }
298
- const err = await parseErrorResponse(res);
299
- if (err.code === "idempotency_in_progress" && attempt < this.retryAttempts) {
300
- if (this.retryDelayMs > 0) await sleep(this.retryDelayMs);
301
- continue;
302
- }
303
- throw err;
304
- }
305
- }
306
- };
307
- function asTransportError(err) {
308
- const name = typeof err === "object" && err !== null ? err.name : void 0;
309
- if (name === "TimeoutError") {
310
- return new HostedApiError({ status: 0, code: "timeout", message: "request timed out" });
311
- }
312
- const detail = err instanceof Error ? err.message : String(err);
313
- return new HostedApiError({
314
- status: 0,
315
- code: "network_error",
316
- message: `network request failed: ${detail}`
317
- });
318
- }
319
- function unwrap(raw) {
320
- if (raw !== null && typeof raw === "object" && "success" in raw && "data" in raw) {
321
- return raw.data;
322
- }
323
- return raw;
324
- }
325
- async function parseErrorResponse(res) {
326
- let code = "unknown_error";
327
- let message = `request failed (HTTP ${res.status})`;
328
- try {
329
- const body = await res.json();
330
- if (body !== null && typeof body === "object") {
331
- const env = body;
332
- if (typeof env.code === "string" && env.code.length > 0) code = env.code;
333
- if (typeof env.message === "string" && env.message.length > 0) message = env.message;
334
- }
335
- } catch {
336
- }
337
- const retryAfterRaw = res.headers.get("retry-after");
338
- const retryAfter = retryAfterRaw === null ? Number.NaN : Number.parseInt(retryAfterRaw, 10);
339
- return new HostedApiError({
340
- status: res.status,
341
- code,
342
- message,
343
- ...Number.isFinite(retryAfter) && retryAfter >= 0 ? { retryAfterSeconds: retryAfter } : {}
344
- });
345
- }
346
- function sleep(ms) {
347
- return new Promise((resolve) => setTimeout(resolve, ms));
348
- }
349
- // Annotate the CommonJS export names for ESM import in node:
350
- 0 && (module.exports = {
351
- HostedApiError,
352
- HostedClient,
353
- KNOWN_CODES,
354
- isKnownCode,
355
- stripMimeParams
356
- });
357
- //# sourceMappingURL=index.cjs.map
1
+ "use strict";var w=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var re=Object.prototype.hasOwnProperty;var f=(n,e)=>()=>(n&&(e=n(n=0)),e);var P=(n,e)=>{for(var t in e)w(n,t,{get:e[t],enumerable:!0})},ie=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of te(e))!re.call(n,i)&&i!==t&&w(n,i,{get:()=>e[i],enumerable:!(r=ne(e,i))||r.enumerable});return n};var oe=n=>ie(w({},"__esModule",{value:!0}),n);function A(n,e=80){return typeof n=="string"&&n.replace(/[^A-Za-z0-9 ()\-._,]/g,"").trim().slice(0,e)||void 0}function le(n){let e={};for(let[t,r]of Object.entries(n))r!==void 0&&(e[t]=r);return Object.keys(e).length>0?e:void 0}function O(n,e){x=le({renderer:A(n),vendor:A(e)})??x}var Je,x,N=f(()=>{"use strict";Je="zoom torch focusMode focusDistance exposureMode exposureCompensation exposureTime whiteBalanceMode colorTemperature iso facingMode frameRate width height aspectRatio resizeMode deviceId groupId".split(" ")});var H=f(()=>{"use strict"});function S(n,e){return new Promise(t=>{let r=setTimeout(()=>t(void 0),e),i=o=>{clearTimeout(r),t(o)};try{n().then(i,()=>i(void 0))}catch{i(void 0)}})}async function D(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify(n)));return Array.from(new Uint8Array(e).subarray(0,8),t=>t.toString(16).padStart(2,"0")).join("")}var V=f(()=>{"use strict";H()});var K={};P(K,{computePrint:()=>Te,readHints:()=>U});function F(n,e){if(typeof n!="string")return;let t=n.trim();return t.length>0&&t.length<=e?t:void 0}async function U(){let n=navigator.userAgentData;if(typeof n?.getHighEntropyValues!="function")return;let e=await S(()=>n.getHighEntropyValues(["model","platformVersion"]),he);if(e==null)return;let t=F(e.model,ge),r=F(e.platformVersion,be),i={...t!==void 0?{model:t}:{},...r!==void 0?{platformVersion:r}:{}};return Object.keys(i).length>0?i:void 0}async function _e(){let[n,e]=await Promise.all([new L.Thumbmark({stabilize:["private","iframe"],exclude:["permissions","webrtc","speech"],logging:!1,collect_beacon:!1,timeout:me}).get(),U()]),t=n?.components?.hardware?.videocard;t!==null&&typeof t=="object"&&O(t.rendererUnmasked??t.renderer,t.vendorUnmasked??t.vendor);let r=n?.thumbmark;if(typeof r!="string"||r.length<we||r.length>Se)return;let i={};for(let o of pe){let s=n.components?.[o];s==null||s.timeout==="true"||(i[o]=await D(s))}return{hash:r,c:i,...e!==void 0?{hints:e}:{}}}function ve(){return new Promise(n=>{typeof globalThis.requestIdleCallback=="function"?globalThis.requestIdleCallback(()=>n(),{timeout:ye}):n()})}async function Te(n){return n()||(await ve(),n())?"busy":S(_e,fe)}var L,pe,me,fe,he,ye,ge,be,we,Se,B=f(()=>{"use strict";L=require("@thumbmarkjs/thumbmarkjs");N();V();pe=["canvas","webgl","audio","fonts","hardware","screen","system","locales","math","plugins"],me=2e3,fe=4e3,he=1e3,ye=2e3,ge=64,be=32,we=8,Se=128});var qe={};P(qe,{HostedApiError:()=>l,HostedClient:()=>b,KNOWN_CODES:()=>k,SEKYRO_SDK_HEADER:()=>C,icaoPolicyOf:()=>J,isInAppBrowser:()=>g,isKnownCode:()=>$,portraitIcaoGate:()=>Q,stripMimeParams:()=>m});module.exports=oe(qe);var se=600;function E(){if(typeof window>"u"||typeof navigator>"u")return"desktop";let n=navigator.userAgentData,e=n?.mobile||/Android|i(Pad)?OS/.test(String(n?.platform)),t=String(navigator.userAgent??"");if(/iPhone|iPod/i.test(t))return"phone";if(/iPad/i.test(t))return"tablet";if(/Android/i.test(t))return/Mobile/i.test(t)?"phone":"tablet";if(/BlackBerry|IEMobile|Opera Mini/i.test(t))return"phone";if(!e){if(Number(navigator.maxTouchPoints??0)<=1)return"desktop";if(/Macintosh/.test(t))return"tablet";if(/Windows NT|CrOS/.test(t)||!ce())return"desktop"}let r=ae();return r>0&&r<se?"phone":"tablet"}function ae(){try{let n=window.screen,e=Number(n?.width??0),t=Number(n?.height??0);return e>0&&t>0?Math.min(e,t):0}catch{return 0}}function ce(){try{return typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches}catch{return!1}}var de=["magenta","yellow","green","blue"];var h=n=>typeof n=="number"&&Number.isFinite(n);function I(n){if(typeof n!="object"||n===null)return!1;let e=n;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=>de.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==e.colours.length)return!1;let t=-1;for(let r of e.onsetsMs){if(!h(r)||r<0||r<=t)return!1;t=r}return!(!h(e.holdMs)||e.holdMs<=0||!h(e.endMs)||e.endMs<=t||!h(e.clipMs)||e.clipMs<e.endMs||e.clipMs>8e3)}var y="0.1.0-rc.40";var ue=/FBAN|FBAV|FB_IAB|FBIOS|MessengerForiOS|Instagram|WhatsApp|musical_ly|BytedanceWebview|TikTok|Snapchat|\bLine\/|LinkedInApp|Pinterest|MicroMessenger|; wv\)/i;function g(n){let e=n??(typeof navigator>"u"?"":String(navigator.userAgent??""));return ue.test(e)}var G="sekyro.did",ke=1e4,Re=()=>globalThis.process?.versions?.node,W;function q(){let n=globalThis.crypto;try{if(typeof n?.randomUUID=="function")return n.randomUUID()}catch{}try{if(typeof n?.getRandomValues=="function"){let e=n.getRandomValues(new Uint8Array(16));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}}catch{}}function Me(){try{let n=localStorage.getItem(G);if(n)return n;let e=q();return e!==void 0&&localStorage.setItem(G,e),e}catch{return W??(W=q()),W}}async function Ce(){let n=globalThis.crypto?.subtle;if(!n)return"";let e=navigator,t=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]),r=await n.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(r),i=>i.toString(16).padStart(2,"0")).join("").slice(0,32)}function Pe(){try{let n=Number(navigator.maxTouchPoints);return Number.isFinite(n)&&n>=0?{touch:Math.min(64,Math.trunc(n))}:{}}catch{return{}}}function Ee(n){let e=new TextEncoder().encode(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ie(n){let e,t,r,i,o,s,d=()=>s?.readyState==="live",a=()=>{o!==void 0||!globalThis.crypto?.subtle||Re()||d()||(o=Promise.race([Promise.resolve().then(()=>(B(),K)),new Promise(c=>setTimeout(c,ke))]).then(c=>c?.computePrint(d)).then(c=>{c==="busy"?o=void 0:i=c}).catch(()=>{}))};return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(c){c&&(e=c.slice(0,128))},noteCamera(c){t=c},noteCameraTrack(c){s=c},async deviceHeader(){try{r??(r=Ce().catch(()=>""));let c=[];navigator.webdriver&&c.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&c.push("headless");let u=await r,p=Me(),Z={v:1,platform:"web",sdk:n.sdk.slice(0,64),caps:["session_proof"],rampAtArm:!0,ids:[...p?[{kind:"web_local",value:p.slice(0,128)}]:[],...u?[{kind:"web_fp",value:u}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...Pe(),...e?{cameraLabel:e}:{},...c.length?{signals:c}:{},...i?{print:{v:2,...i,...t?{camera:t}:{}}}:{},...g()?{inApp:!0}:{}},ee=Ee(JSON.stringify(Z));return a(),ee}catch{return}},printReady(){return o??Promise.resolve()}}}var _=Symbol.for("sekyro.web.clientContext"),v=globalThis,T=v[_]??(v[_]=Ie({sdk:`@sekyro/web@${y}`}));var k=["session_token_invalid","session_token_required","session_token_session_mismatch","session_not_found","rate_limit_exceeded","consent_required","session_not_active","check_not_found","check_already_finalized","check_out_of_order","check_type_unsupported","force_outcome_forbidden","attestation_invalid","platform_unregistered","app_attest_invalid","too_many_challenges","inference_unavailable","mobile_required","nni_locked","document_nni_mismatch","media_content_type_not_allowed","media_too_large","media_key_invalid","media_key_forbidden","media_not_found","media_unreadable","media_session_invalid","idempotency_key_collision","idempotency_in_progress","idempotency_key_required","validation_error","internal_error","unknown_error","upload_failed","network_error","timeout","nfc_outcome_not_accepted","identity_confirm_required","identity_confirm_locked","choice_not_found","choice_locked","choice_option_unavailable","step_not_on_path","check_not_active","sekyro_app_not_allowed","sekyro_app_unverified","id_number_locked","document_id_number_mismatch","simulated_capture_forbidden","native_app_required"];function $(n){return k.includes(n)}var l=class extends Error{constructor(e){super(e.message),this.name="HostedApiError",this.status=e.status,this.code=e.code,e.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=e.retryAfterSeconds),e.details&&(this.details=e.details)}};function j(n,e,t=Math.random){let r=(n??e)*1e3,i=Math.min(Math.max(r,500),2e4),o=Math.round(i*(1+(t()*2-1)*.25));return Math.min(Math.max(o,500),2e4)}var Y=6e4,R=4,Ae=3e4,xe=9e5,Oe=200,Ne=5,He=400,De=new Set(["server_busy","request_timeout"]),Ve=20,Fe=60,Le=600,Ue=2;function m(n){return(n.split(";")[0]??"").trim()}var Ke={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},C=`@sekyro/web/${y}`,Be=C,b=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.reportedIssues=new Map;this.issueReports=0;this.issuesPausedUntil=0;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let t=e.fetch;this.fetchImpl=(r,i)=>(t??globalThis.fetch).call(globalThis,r,i),this.requestTimeoutMs=e.requestTimeoutMs??Ae,this.retryAttempts=e.inProgressRetry?.attempts??Ne,this.retryDelayMs=e.inProgressRetry?.delayMs??He,this.random=e.random??Math.random,this.clientLocale=e.locale}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){let t=await this.api("POST","/hosted/consent",{body:{locale:e},busyRetry:!0}),r=this.captureHold;return this.captureHold=void 0,r&&this.armCapture(r),t}async reportCameraUnavailable(e){return this.api("POST","/hosted/camera-unavailable",{body:{cause:e}})}async testerGate(e){return this.api("POST","/hosted/tester-gate",{body:{input:e}})}async reportCaptureIssue(e){let t=typeof e.name=="string"?e.name.replace(/[^A-Za-z]/g,"").slice(0,40):"",r=typeof e.engineKind=="string"&&/^[a-z_]{1,32}$/.test(e.engineKind)?e.engineKind:void 0,i=typeof e.attempt=="number"&&Number.isInteger(e.attempt)&&e.attempt>=0&&e.attempt<=1e3?e.attempt:void 0,o=e.check==="attestation"?i??"":"",s=[e.check,o,e.kind,t,e.phase??"",r??""].join("|"),d=this.reportedIssues.get(s);if(d!==void 0)return d;if(Date.now()<this.issuesPausedUntil||this.issueReports>=Ve)return;let a={check:e.check,kind:e.kind,...t!==""?{name:t}:{},...e.phase!==void 0?{phase:e.phase}:{},...r!==void 0?{engineKind:r}:{},...i!==void 0?{attempt:i}:{},...e.formFactor!==void 0?{formFactor:e.formFactor}:{},...typeof e.detail=="string"&&/^\d{1,10}$/.test(e.detail)?{detail:e.detail}:{},...z(e.challengeMs)?{challengeMs:e.challengeMs}:{},...z(e.readyMs)?{readyMs:e.readyMs}:{},...e.inApp===!0?{inApp:!0}:{}};this.issueReports+=1;let c=this.api("POST","/hosted/capture-issue",{body:a,empty:!0}).catch(u=>{if(u instanceof l&&u.status===429){let p=Math.min(Math.max(u.retryAfterSeconds??Fe,0),Le);this.issuesPausedUntil=Math.max(this.issuesPausedUntil,Date.now()+p*1e3);return}(!(u instanceof l)||u.status===0||u.status>=500)&&this.reportedIssues.delete(s)});return this.reportedIssues.set(s,c),c}async choose(e,t){let r=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:t},busyRetry:!0});return this.sessionId=r.sessionId,r}async confirmIdentity(e){return this.api("POST","/hosted/identity/confirm",{body:{decision:e}})}async identityPortrait(){return this.api("GET","/hosted/identity/portrait",{blob:!0})}async presign(e,t,r,i={}){let o=await this.ensureSessionId(),s={kind:e,contentType:m(t),contentLength:r,...i.source==="upload"?{source:"upload"}:{}};return this.api("POST",`/sessions/${o}/media`,{body:s})}armCapture(e=2){let t=Date.now();this.captureNonces.filter(r=>r.expiresAt-Y>t).length>=e||(this.captureHold===void 0?this.fillCaptureNonces(e,e):this.captureHold=Math.max(this.captureHold,e))}async armRamp(){try{let e=await this.ensureSessionId(),t=await this.api("POST",`/sessions/${e}/media/capture-nonces`,{body:{count:2,ramp:!0}}),r=Date.now(),i=I(t.screenRamp)?t.screenRamp:void 0,o=r+Math.max(0,t.expiresIn)*1e3;for(let d of Array.isArray(t.nonces)?t.nonces:[])typeof d!="string"||d.length===0||this.captureNonces.push({nonce:d,expiresAt:o,...i!==void 0?{arm:i.nonce}:{}});this.captureNonces=this.captureNonces.slice(-R),this.captureHold=void 0;let s=typeof t.rampExpiresIn=="number"&&t.rampExpiresIn>0?t.rampExpiresIn:0;return{...i!==void 0?{challenge:i}:{},expiresAt:r+s*1e3}}catch{return}}async presignCapture(e,t,r,i={}){let o=await this.ensureSessionId(),s=await this.takeCaptureNonce(i.arm),d=s===void 0?void 0:{nonce:s,...i.engine!==void 0?{engine:i.engine.slice(0,32)}:{},...i.durationMs!==void 0&&Number.isFinite(i.durationMs)?{captureMs:Math.min(36e5,Math.max(0,Math.round(i.durationMs)))}:{}},a={kind:e,contentType:m(t),contentLength:r,capture:d};return this.api("POST",`/sessions/${o}/media`,{body:a})}async takeCaptureNonce(e){let t=()=>{let r=Date.now();this.captureNonces=this.captureNonces.filter(o=>o.expiresAt-Y>r);let i=this.captureNonces.findIndex(o=>o.arm===e);return this.captureNonces.splice(i<0?0:i,1)[0]?.nonce};for(let r=0;r<2;r++){let i=t();if(i!==void 0)return i;await this.fillCaptureNonces(1)}return t()}fillCaptureNonces(e,t=0){return this.captureFetch??(this.captureFetch=(async()=>{try{let r=await this.ensureSessionId(),i=await this.api("POST",`/sessions/${r}/media/capture-nonces`,{body:{count:Math.min(R,Math.max(1,e))}}),o=Date.now()+Math.max(0,i.expiresIn)*1e3;for(let s of Array.isArray(i.nonces)?i.nonces:[])typeof s=="string"&&s.length>0&&this.captureNonces.push({nonce:s,expiresAt:o});this.captureNonces=this.captureNonces.slice(-R),this.captureHold=void 0}catch(r){r instanceof l&&r.code==="consent_required"&&(this.captureHold=Math.max(this.captureHold??0,t))}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,t,r){let i;try{i=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":m(r)},body:t,signal:AbortSignal.timeout(xe)})}catch(o){throw M(o)}if(!i.ok){let o=(await i.text().catch(()=>"")).slice(0,Oe);throw new l({status:i.status,code:"upload_failed",message:`media upload failed (HTTP ${i.status})${o?`: ${o}`:""}`})}}async completeMedia(e){let t=await this.ensureSessionId();return this.api("POST",`/sessions/${t}/media/complete`,{body:{key:e}})}async submitCheck(e,t,r={}){let i=await this.ensureSessionId(),o={input:t,forceOutcome:r.forceOutcome};return this.api("POST",`/sessions/${i}/checks/${e}`,{body:o,idempotencyKey:r.idempotencyKey,...r.browserCheckToken!==void 0?{browserCheckToken:r.browserCheckToken}:{},busyRetry:r.idempotencyKey!==void 0})}async uploadAndSubmit(e,t,r,i={}){let o=m(t.contentType),s=await this.presign(t.kind,o,t.blob.size);await this.uploadToSpaces(s.uploadUrl,t.blob,o);let d=await this.completeMedia(s.key),a={...r,[Ke[e]]:d.key};return this.submitCheck(e,a,i)}async ensureSessionId(){return this.sessionId!==null?this.sessionId:(this.bootstrap??(this.bootstrap=this.getSession().finally(()=>{this.bootstrap=null})),(await this.bootstrap).sessionId)}async api(e,t,r={}){let i=e==="GET"||r.busyRetry===!0,o=`${this.apiOrigin}/api/v2${t}`,s={"x-session-token":this.sessionToken,"x-sekyro-sdk":Be};r.body!==void 0&&(s["content-type"]="application/json"),r.idempotencyKey!==void 0&&(s["x-idempotency-key"]=r.idempotencyKey),r.browserCheckToken!==void 0&&(s["sekyro-browser-check"]=r.browserCheckToken),this.clientLocale!==void 0&&(s["sekyro-client-locale"]=this.clientLocale);try{let d=T.timezone();d!==void 0&&(s["sekyro-client-timezone"]=d)}catch{}s["sekyro-client-form-factor"]=E();try{let d=await T.deviceHeader();d!==void 0&&(s["sekyro-client-device"]=d)}catch{}for(let d=0;;d++){let a;try{a=await this.fetchImpl(o,{method:e,headers:s,...r.body!==void 0?{body:JSON.stringify(r.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(u){throw M(u)}if(a.ok){if(r.empty===!0)return;if(r.blob===!0)try{return await a.blob()}catch(p){throw M(p)}let u;try{u=await a.json()}catch{throw new l({status:a.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${a.status})`})}return Ge(u)}let c=await We(a);if(c.code==="idempotency_in_progress"&&d<this.retryAttempts){this.retryDelayMs>0&&await X(this.retryDelayMs);continue}if(i&&c.status===503&&De.has(c.code)){i=!1,await X(j(c.retryAfterSeconds,Ue,this.random));continue}throw c}}};function z(n){return typeof n=="number"&&Number.isInteger(n)&&n>=0&&n<=6e5}function M(n){if((typeof n=="object"&&n!==null?n.name:void 0)==="TimeoutError")return new l({status:0,code:"timeout",message:"request timed out"});let t=n instanceof Error?n.message:String(n);return new l({status:0,code:"network_error",message:`network request failed: ${t}`})}function Ge(n){return n!==null&&typeof n=="object"&&"success"in n&&"data"in n?n.data:n}async function We(n){let e="unknown_error",t=`request failed (HTTP ${n.status})`,r=Number.NaN,i;try{let d=await n.json();if(d!==null&&typeof d=="object"){let a=d;typeof a.code=="string"&&a.code.length>0&&(e=a.code),typeof a.message=="string"&&a.message.length>0&&(t=a.message),typeof a.retryAfterSeconds=="number"&&(r=a.retryAfterSeconds),Array.isArray(a.details?.issues)?i=a.details:Array.isArray(a.details?.errors)&&(i={...a.details,issues:[]})}}catch{}let o=n.headers.get("retry-after"),s=o===null?Math.floor(r):Number.parseInt(o,10);return new l({status:n.status,code:e,message:t,...Number.isFinite(s)&&s>=0?{retryAfterSeconds:s}:{},details:i})}function X(n){return new Promise(e=>setTimeout(e,n))}function J(n){let e=n?.portrait,t=e?.icao,r=e?.purpose==="id_document";return t==null?r?{policy:"reject",profile:"id_document"}:null:{policy:t.policy==="alert"?"alert":"reject",profile:r||t.profile==="id_document"?"id_document":"selfie"}}function Q(n){return{...n.baselineEyeOpenness!==void 0?{baselineEyeOpenness:n.baselineEyeOpenness}:{},...n.baselineEyeOpennessLeft!==void 0&&n.baselineEyeOpennessRight!==void 0?{baselineEyeOpennessLeft:n.baselineEyeOpennessLeft,baselineEyeOpennessRight:n.baselineEyeOpennessRight}:{},criteria:n.verdict??{},...n.backgroundCheck!==void 0?{backgroundCheck:n.backgroundCheck}:{}}}0&&(module.exports={HostedApiError,HostedClient,KNOWN_CODES,SEKYRO_SDK_HEADER,icaoPolicyOf,isInAppBrowser,isKnownCode,portraitIcaoGate,stripMimeParams});
@@ -1,39 +1,8 @@
1
- export { A as AttestationInput, i as CheckInputByType, C as CheckReason, a as CheckState, b as CheckType, j as CompleteMediaResult, k as ConsentLocale, l as DocOcrInput, D as DocReason, m as DocSide, n as FaceMatchInput, F as FaceMatchReason, g as HostedClient, o as HostedClientOptions, H as HostedOtpView, c as HostedSessionView, d as HostedStepView, p as LivenessCaptureInput, q as LivenessInput, L as LivenessReason, M as MediaCheckType, r as MediaKind, s as PhoneOtpInput, P as PhoneOtpReason, t as PopulationInput, e as PopulationReason, u as PresignRequest, v as PresignUploadResult, R as RecordConsentResult, S as SessionOutcome, f as SessionStatus, w as SessionStepView, h as SessionView, x as SubmitCheckBody, y as SubmitOptions, U as UploadMedia, z as stripMimeParams } from '../hosted-client-DWzCRYJK.cjs';
1
+ export { H as HostedClient, a as HostedClientOptions, M as MediaCheckType, S as SEKYRO_SDK_HEADER, b as SubmitOptions, U as UploadMedia, s as stripMimeParams } from '../icao-gate-BqXxEAq6.cjs';
2
+ export { H as HostedApiError, a as HostedErrorDetails, b as HostedErrorIssue, K as KNOWN_CODES, c as KnownCode, i as icaoPolicyOf, d as isKnownCode, p as portraitIcaoGate } from '../icao-policy-CgSI4oFo.cjs';
3
+ export { A as AcceptedDocumentType, a as ArmedRamp, b as AttestationInput, C as CaptureContext, c as CaptureMode, d as CaptureNoncesResult, e as CaptureProof, f as CheckInputByType, g as CheckReason, h as CheckState, i as CheckType, j as ClosedBy, k as CompleteMediaResult, l as ConsentLocale, m as ContactChannel, D as DecisionReason, n as DocDeviceRead, o as DocOcrInput, p as DocReason, q as DocSide, E as EidAfterPass, r as EidAuthInput, s as EidReason, t as EmailOtpInput, u as EmailOtpReason, F as FaceMatchInput, v as FaceMatchReason, w as FormAddressValue, x as FormAnswerValue, y as FormChoiceView, z as FormConsentView, B as FormCustomQuestionView, G as FormFieldName, H as FormFieldQuestionView, I as FormInput, J as FormIssueCode, K as FormLocale, L as FormQuestionOptions, M as FormQuestionType, N as FormQuestionView, O as HostedAcceptedDocuments, P as HostedCaptureTuning, Q as HostedChallengeView, R as HostedConsentView, S as HostedDocumentCaptureTuning, T as HostedDocumentScanTuning, U as HostedDocumentsView, V as HostedEidView, W as HostedEmailOtpView, X as HostedFlowRef, Y as HostedFormView, Z as HostedIcaoPolicy, _ as HostedIntegrity, $ as HostedLivePhotoTuning, a0 as HostedNativeAppView, a1 as HostedNativeCaptureTuning, a2 as HostedOcrTuning, a3 as HostedOtpView, a4 as HostedPlanView, a5 as HostedPoaRuleKindView, a6 as HostedPoaRuleView, a7 as HostedPortraitPendingFix, a8 as HostedPortraitView, a9 as HostedProofOfAddressView, aa as HostedSessionView, ab as HostedSimulationView, ac as HostedStepView, ad as HostedTesterGateView, ae as HostedVoiceLocale, af as HostedVoiceView, ag as IcaoCriterion, ah as IcaoReportEntry, ai as IdentityConfirmDecision, aj as IdentityMethod, ak as IdentitySummarySource, al as IdentitySummaryView, am as LivenessCaptureInput, an as LivenessInput, ao as LivenessReason, ap as MatchReason, aq as MediaKind, ar as MethodChoiceView, as as NationalEidOption, at as NfcChipReason, au as NfcStepView, av as OtpChoiceView, aw as PhoneCountryRule, ax as PhoneFormat, ay as PhoneOtpInput, az as PhoneOtpReason, aA as PhotoSource, aB as PhotoSourcePick, aC as PlanAttempts, aD as PlanChoiceKind, aE as PlanChoiceOption, aF as PlanChoiceView, aG as PlanSectionView, aH as PlanStepView, aI as PoaImagesInput, aJ as PoaInput, aK as PoaKind, aL as PoaLicenceInput, aM as PoaNameMatchMode, aN as PoaPdfInput, aO as PoaReason, aP as PoaRuleSource, aQ as PopulationInput, aR as PopulationReason, aS as PortraitFix, aT as PortraitFixReviewInput, aU as PortraitIcaoInput, aV as PortraitIcaoReason, aW as PortraitOutputFormat, aX as PresignRequest, aY as PresignUploadResult, aZ as RecordConsentResult, a_ as ResolvedCaptureMode, a$ as SandboxSimulatedReason, b0 as SandboxSimulation, b1 as SessionDecidingStep, b2 as SessionFailureReason, b3 as SessionReason, b4 as SessionStatus, b5 as SessionStepView, b6 as SessionView, b7 as SimulatedCaptureInput, b8 as StepResult, b9 as StepSection, ba as SubmitCheckBody, bb as TesterGateInput, bc as TesterGateMissReason, bd as TesterGateResponse, be as VerificationAssurance, bf as VerificationLevel } from '../types-BAAj6TOZ.cjs';
2
4
 
3
- /**
4
- * Every error code the hosted page can receive from the session-token surface.
5
- * A closed string-literal union — switch over {@link KnownCode} with a `never`
6
- * default arm for compile-checked exhaustiveness.
7
- */
8
- declare const KNOWN_CODES: readonly ["session_token_invalid", "session_token_required", "session_token_session_mismatch", "session_not_found", "rate_limit_exceeded", "consent_required", "session_not_active", "check_not_found", "check_already_finalized", "check_out_of_order", "check_type_unsupported", "force_outcome_forbidden", "attestation_invalid", "nni_locked", "media_content_type_not_allowed", "media_too_large", "media_key_invalid", "media_key_forbidden", "media_not_found", "media_unreadable", "media_session_invalid", "idempotency_key_collision", "idempotency_in_progress", "idempotency_key_required", "validation_error", "internal_error", "unknown_error", "upload_failed", "network_error", "timeout"];
9
- /** Closed union of {@link KNOWN_CODES} — exhaustively switchable. */
10
- type KnownCode = (typeof KNOWN_CODES)[number];
11
- /** Narrow an arbitrary wire code to the known union (unknown codes stay `string`). */
12
- declare function isKnownCode(code: string): code is KnownCode;
13
- /**
14
- * Typed transport error: EVERY failure surfaces as one of these — non-2xx
15
- * responses, rejected fetches, timeouts, and unparseable bodies alike. The
16
- * hosted page never sees a raw TypeError/DOMException from the client.
17
- *
18
- * - `code` — the public envelope's `code`, or a client-synthesized fallback
19
- * ('unknown_error' / 'upload_failed' / 'network_error' / 'timeout'). Typed
20
- * `string` because the wire may grow codes; narrow with {@link isKnownCode}
21
- * before an exhaustive switch.
22
- * - `status` — the HTTP status, or 0 when no response arrived at all
23
- * ('network_error' / 'timeout').
24
- * - `retryAfterSeconds` — parsed from the `Retry-After` header when present
25
- * (rate-limit 429s always set it).
26
- */
27
- declare class HostedApiError extends Error {
28
- readonly status: number;
29
- readonly code: string;
30
- readonly retryAfterSeconds?: number;
31
- constructor(args: {
32
- status: number;
33
- code: string;
34
- message: string;
35
- retryAfterSeconds?: number;
36
- });
37
- }
5
+ /** The page runs inside an app's WebView (WhatsApp, Instagram, Facebook, TikTok, Snapchat, LINE, LinkedIn, WeChat, an Android WebView…). */
6
+ declare function isInAppBrowser(userAgent?: string): boolean;
38
7
 
39
- export { HostedApiError, KNOWN_CODES, type KnownCode, isKnownCode };
8
+ export { isInAppBrowser };
@@ -1,39 +1,8 @@
1
- export { A as AttestationInput, i as CheckInputByType, C as CheckReason, a as CheckState, b as CheckType, j as CompleteMediaResult, k as ConsentLocale, l as DocOcrInput, D as DocReason, m as DocSide, n as FaceMatchInput, F as FaceMatchReason, g as HostedClient, o as HostedClientOptions, H as HostedOtpView, c as HostedSessionView, d as HostedStepView, p as LivenessCaptureInput, q as LivenessInput, L as LivenessReason, M as MediaCheckType, r as MediaKind, s as PhoneOtpInput, P as PhoneOtpReason, t as PopulationInput, e as PopulationReason, u as PresignRequest, v as PresignUploadResult, R as RecordConsentResult, S as SessionOutcome, f as SessionStatus, w as SessionStepView, h as SessionView, x as SubmitCheckBody, y as SubmitOptions, U as UploadMedia, z as stripMimeParams } from '../hosted-client-DWzCRYJK.js';
1
+ export { H as HostedClient, a as HostedClientOptions, M as MediaCheckType, S as SEKYRO_SDK_HEADER, b as SubmitOptions, U as UploadMedia, s as stripMimeParams } from '../icao-gate-C7D7Lce7.js';
2
+ export { H as HostedApiError, a as HostedErrorDetails, b as HostedErrorIssue, K as KNOWN_CODES, c as KnownCode, i as icaoPolicyOf, d as isKnownCode, p as portraitIcaoGate } from '../icao-policy-Bo7TQyTd.js';
3
+ export { A as AcceptedDocumentType, a as ArmedRamp, b as AttestationInput, C as CaptureContext, c as CaptureMode, d as CaptureNoncesResult, e as CaptureProof, f as CheckInputByType, g as CheckReason, h as CheckState, i as CheckType, j as ClosedBy, k as CompleteMediaResult, l as ConsentLocale, m as ContactChannel, D as DecisionReason, n as DocDeviceRead, o as DocOcrInput, p as DocReason, q as DocSide, E as EidAfterPass, r as EidAuthInput, s as EidReason, t as EmailOtpInput, u as EmailOtpReason, F as FaceMatchInput, v as FaceMatchReason, w as FormAddressValue, x as FormAnswerValue, y as FormChoiceView, z as FormConsentView, B as FormCustomQuestionView, G as FormFieldName, H as FormFieldQuestionView, I as FormInput, J as FormIssueCode, K as FormLocale, L as FormQuestionOptions, M as FormQuestionType, N as FormQuestionView, O as HostedAcceptedDocuments, P as HostedCaptureTuning, Q as HostedChallengeView, R as HostedConsentView, S as HostedDocumentCaptureTuning, T as HostedDocumentScanTuning, U as HostedDocumentsView, V as HostedEidView, W as HostedEmailOtpView, X as HostedFlowRef, Y as HostedFormView, Z as HostedIcaoPolicy, _ as HostedIntegrity, $ as HostedLivePhotoTuning, a0 as HostedNativeAppView, a1 as HostedNativeCaptureTuning, a2 as HostedOcrTuning, a3 as HostedOtpView, a4 as HostedPlanView, a5 as HostedPoaRuleKindView, a6 as HostedPoaRuleView, a7 as HostedPortraitPendingFix, a8 as HostedPortraitView, a9 as HostedProofOfAddressView, aa as HostedSessionView, ab as HostedSimulationView, ac as HostedStepView, ad as HostedTesterGateView, ae as HostedVoiceLocale, af as HostedVoiceView, ag as IcaoCriterion, ah as IcaoReportEntry, ai as IdentityConfirmDecision, aj as IdentityMethod, ak as IdentitySummarySource, al as IdentitySummaryView, am as LivenessCaptureInput, an as LivenessInput, ao as LivenessReason, ap as MatchReason, aq as MediaKind, ar as MethodChoiceView, as as NationalEidOption, at as NfcChipReason, au as NfcStepView, av as OtpChoiceView, aw as PhoneCountryRule, ax as PhoneFormat, ay as PhoneOtpInput, az as PhoneOtpReason, aA as PhotoSource, aB as PhotoSourcePick, aC as PlanAttempts, aD as PlanChoiceKind, aE as PlanChoiceOption, aF as PlanChoiceView, aG as PlanSectionView, aH as PlanStepView, aI as PoaImagesInput, aJ as PoaInput, aK as PoaKind, aL as PoaLicenceInput, aM as PoaNameMatchMode, aN as PoaPdfInput, aO as PoaReason, aP as PoaRuleSource, aQ as PopulationInput, aR as PopulationReason, aS as PortraitFix, aT as PortraitFixReviewInput, aU as PortraitIcaoInput, aV as PortraitIcaoReason, aW as PortraitOutputFormat, aX as PresignRequest, aY as PresignUploadResult, aZ as RecordConsentResult, a_ as ResolvedCaptureMode, a$ as SandboxSimulatedReason, b0 as SandboxSimulation, b1 as SessionDecidingStep, b2 as SessionFailureReason, b3 as SessionReason, b4 as SessionStatus, b5 as SessionStepView, b6 as SessionView, b7 as SimulatedCaptureInput, b8 as StepResult, b9 as StepSection, ba as SubmitCheckBody, bb as TesterGateInput, bc as TesterGateMissReason, bd as TesterGateResponse, be as VerificationAssurance, bf as VerificationLevel } from '../types-BAAj6TOZ.js';
2
4
 
3
- /**
4
- * Every error code the hosted page can receive from the session-token surface.
5
- * A closed string-literal union — switch over {@link KnownCode} with a `never`
6
- * default arm for compile-checked exhaustiveness.
7
- */
8
- declare const KNOWN_CODES: readonly ["session_token_invalid", "session_token_required", "session_token_session_mismatch", "session_not_found", "rate_limit_exceeded", "consent_required", "session_not_active", "check_not_found", "check_already_finalized", "check_out_of_order", "check_type_unsupported", "force_outcome_forbidden", "attestation_invalid", "nni_locked", "media_content_type_not_allowed", "media_too_large", "media_key_invalid", "media_key_forbidden", "media_not_found", "media_unreadable", "media_session_invalid", "idempotency_key_collision", "idempotency_in_progress", "idempotency_key_required", "validation_error", "internal_error", "unknown_error", "upload_failed", "network_error", "timeout"];
9
- /** Closed union of {@link KNOWN_CODES} — exhaustively switchable. */
10
- type KnownCode = (typeof KNOWN_CODES)[number];
11
- /** Narrow an arbitrary wire code to the known union (unknown codes stay `string`). */
12
- declare function isKnownCode(code: string): code is KnownCode;
13
- /**
14
- * Typed transport error: EVERY failure surfaces as one of these — non-2xx
15
- * responses, rejected fetches, timeouts, and unparseable bodies alike. The
16
- * hosted page never sees a raw TypeError/DOMException from the client.
17
- *
18
- * - `code` — the public envelope's `code`, or a client-synthesized fallback
19
- * ('unknown_error' / 'upload_failed' / 'network_error' / 'timeout'). Typed
20
- * `string` because the wire may grow codes; narrow with {@link isKnownCode}
21
- * before an exhaustive switch.
22
- * - `status` — the HTTP status, or 0 when no response arrived at all
23
- * ('network_error' / 'timeout').
24
- * - `retryAfterSeconds` — parsed from the `Retry-After` header when present
25
- * (rate-limit 429s always set it).
26
- */
27
- declare class HostedApiError extends Error {
28
- readonly status: number;
29
- readonly code: string;
30
- readonly retryAfterSeconds?: number;
31
- constructor(args: {
32
- status: number;
33
- code: string;
34
- message: string;
35
- retryAfterSeconds?: number;
36
- });
37
- }
5
+ /** The page runs inside an app's WebView (WhatsApp, Instagram, Facebook, TikTok, Snapchat, LINE, LinkedIn, WeChat, an Android WebView…). */
6
+ declare function isInAppBrowser(userAgent?: string): boolean;
38
7
 
39
- export { HostedApiError, KNOWN_CODES, type KnownCode, isKnownCode };
8
+ export { isInAppBrowser };