@sekyro/web 0.1.0-rc.16 → 0.1.0-rc.18
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.
- package/CHANGELOG.md +12 -0
- package/dist/{capture-session-doc-BIW3YORT.js → capture-session-doc-IE5VPYWC.js} +1 -1
- package/dist/{capture-session-v3-B4wPuppJ.d.ts → capture-session-v3-Dxus1Se9.d.ts} +1 -1
- package/dist/{capture-session-v3-BRu4ET1H.d.cts → capture-session-v3-DyUA2uCL.d.cts} +1 -1
- package/dist/{chunk-ZBRKR5KC.js → chunk-D42NBRSV.js} +1 -1
- package/dist/{chunk-UFUBBIAS.js → chunk-DNB3R4PI.js} +1 -1
- package/dist/chunk-G2HL2ZWH.js +1 -0
- package/dist/chunk-JDTZK3A7.js +1 -0
- package/dist/{chunk-PGEOLOGD.js → chunk-KBKCYDZQ.js} +1 -1
- package/dist/{chunk-TPYWFLT4.js → chunk-OG4QAJ3M.js} +1 -1
- package/dist/chunk-SVNAHPQU.js +1 -0
- package/dist/{chunk-LIMHSSC4.js → chunk-VCUOPQFA.js} +1 -1
- package/dist/{chunk-73B7S6RA.js → chunk-ZMO2ZQAS.js} +1 -1
- package/dist/client/index.cjs +1 -1
- package/dist/client/index.d.cts +4 -4
- package/dist/client/index.d.ts +4 -4
- package/dist/client/index.js +1 -1
- package/dist/core/index.cjs +1 -1
- package/dist/core/index.d.cts +3 -3
- package/dist/core/index.d.ts +3 -3
- package/dist/core/index.js +1 -1
- package/dist/{create-document-capture-E733IQ2S.js → create-document-capture-35HFVNC3.js} +1 -1
- package/dist/{create-verification-CMFtWutL.d.ts → create-verification-C_fx3n4A.d.ts} +27 -5
- package/dist/{create-verification-ayrPuW_P.d.cts → create-verification-DiH7QRdv.d.cts} +27 -5
- package/dist/{icao-gate-aS101PTk.d.ts → icao-gate-5FzqyitT.d.ts} +1 -1
- package/dist/{icao-gate-D9D3t6z2.d.cts → icao-gate-C-lfjEpH.d.cts} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +1 -1
- package/dist/internal/index.cjs +1 -1
- package/dist/internal/index.d.cts +6 -6
- package/dist/internal/index.d.ts +6 -6
- package/dist/internal/index.js +1 -1
- package/dist/{plan-runner-LWPBOZX6.js → plan-runner-YXTOSPDP.js} +1 -1
- package/dist/{types---PS7_W4.d.cts → types-CKgMWVnP.d.cts} +34 -2
- package/dist/{types---PS7_W4.d.ts → types-CKgMWVnP.d.ts} +34 -2
- package/package.json +1 -1
- package/sbom.cdx.json +7 -7
- package/dist/chunk-4QJIIN6X.js +0 -1
- package/dist/chunk-CGRFUBVV.js +0 -1
- package/dist/chunk-SIPWSFTI.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as V,c as F,d as N,e as H}from"./chunk-FUHDOEBP.js";import{b as $,c as J,d as ee}from"./chunk-POIQGEZM.js";import{b as U,c as K,d as B,e as W,g as z,h as R,k as X}from"./chunk-2BFYVMUU.js";import{b as D,c as te,d as O,e as re}from"./chunk-FPXL63KZ.js";import{c as q}from"./chunk-UFUBBIAS.js";import{c as Z,d as Q,f as w,h as Y,j}from"./chunk-OKWG3PVH.js";var ve=2500,ge=1e3,be=1500,ie=25e5,b=class extends Error{constructor(e,t){super(t??e),this.kind=e}},k=class{constructor(){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.settled=!1}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.hardStopTimer=null,this.graceTimer=null}record(e,t,r){if(this.recorder&&!this.settled)return Promise.reject(new b("generic","record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time"));this.recorder=null,this.clearTimers(),this.chunks=[],this.bytes=0,this.settled=!1,this.stream=e;let i=U();return new Promise((n,a)=>{let s;try{s=new MediaRecorder(e,i?{mimeType:i,videoBitsPerSecond:ie}:{videoBitsPerSecond:ie})}catch{try{s=new MediaRecorder(e)}catch{a(new b("unsupported"));return}}this.recorder=s;let d=c=>{this.settled||(this.settled=!0,this.clearTimers(),c())},u=()=>d(()=>{let c=s.mimeType||i||K,l=new Blob(this.chunks,{type:c});if(l.size===0){a(new b("generic","empty clip"));return}if(R(l)){a(new b("cliptoolarge"));return}n({blob:l,mimeType:c})});if(s.ondataavailable=c=>{c.data&&c.data.size&&(this.chunks.push(c.data),this.bytes+=c.data.size,this.bytes>z&&d(()=>{try{s.state!=="inactive"&&s.stop()}catch{}a(new b("cliptoolarge"))}))},s.onstop=u,s.onerror=()=>d(()=>a(new b("generic"))),r!==void 0){let c=!1;s.onstart=()=>{if(!(c||this.settled)){c=!0;try{r()}catch{}}}}try{s.start(ge)}catch{d(()=>a(new b("generic")));return}this.hardStopTimer=setTimeout(()=>{if(this.settled||t?.(),s.state!=="inactive"){try{s.stop()}catch{u()}this.graceTimer=setTimeout(u,be)}else u()},ve)})}stop(e){this.clearTimers();let t=this.recorder;if(t&&t.state!=="inactive")try{t.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(i=>i.stop()),this.stream=null}};var Ke=400,Be=2e3,ye=["rose","peach","sand","mint","sky","lilac"],Se={rose:"rgb(255, 185, 205)",peach:"rgb(245, 193, 159)",sand:"rgb(195, 210, 158)",mint:"rgb(139, 219, 203)",sky:"rgb(140, 214, 249)",lilac:"rgb(208, 197, 249)"};function We(o){return Se[o]}var Ee=4,Me=4;function _e(o){if(typeof o!="object"||o===null)return!1;let e=o;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length!==3||!e.colours.every(r=>ye.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==3)return!1;let t=-1;for(let r of e.onsetsMs){if(typeof r!="number"||!Number.isFinite(r)||r<=t||r>=2e3)return!1;t=r}return!0}function ne(o,e){let t=e.now??(()=>performance.now()),r=_e(o)?o:void 0,i=[],n=null,a=null,s=null,d=!1,u=null,c=p=>{u=p;try{e.paint(p)}catch{}},l=p=>{let m=e.frames?.()??null;return m!==null&&s!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-s:p-(a??p)},f=(p,m,v=0)=>{if(d)return;let E=Math.max(0,p-l(t()));n=setTimeout(()=>{if(n=null,!d){if(v<Ee&&l(t())<p-Me){f(p,m,v+1);return}m()}},E)},h=p=>{if(r!==void 0){if(p>=3){f(2e3,()=>c(null));return}f(r.onsetsMs[p],()=>{let m=l(t());if(m>2e3){u!==null&&c(null);return}let v=r.colours[p];c(v);let E=i.length===0?0:i[i.length-1].tMs;i.push({tMs:Math.max(E,Math.round(m)),colour:v}),h(p+1)})}};return{started(p){if(r===void 0||d||a!==null)return;a=p;let m=e.frames?.()??null;s=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),h(0)},stop(){d||(d=!0,n!==null&&clearTimeout(n),n=null,u!==null&&c(null))},report(){return r===void 0?void 0:{nonce:r.nonce,rendered:[...i]}}}}function ae(o,e,t=.92){return new Promise((r,i)=>{let n=o.videoWidth,a=o.videoHeight;if(!n||!a){i(new Error("video-not-ready"));return}let s=e.getContext("2d");if(!s){i(new Error("no-2d-context"));return}e.width=n,e.height=a,s.scale(-1,1),s.drawImage(o,-n,0),e.toBlob(d=>d?r(d):i(new Error("empty-keyframe")),"image/jpeg",t)})}var A=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let t=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),t()}))};t();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((t,r)=>t+r,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var Ce=Object.freeze({Q_GOOD:.6,RISE_PER_S:.9,FALL_PER_S:.25,CENTER_FALLOFF_IOD_MULTIPLE:1.35,BOX_EYE_OFFSET_FACTOR:.12,IOD_BOX_PROXY_FACTOR:.42,SIZE_IDEAL_MIN:.12,SIZE_IDEAL_MAX:.3,SIZE_HARD_MIN:.08,SIZE_HARD_MAX:.45,ROLL_MAX_DEG:25,MOTION_VELOCITY_IOD_PER_S:.5,MOTION_TAU_S:.4,MOTION_DEADBAND_IOD_PER_S:.1,READY_WINDOW_MS:500,GUIDE_SIZE:.6,GUIDE_CENTERING:.6,GUIDE_POSE:.6,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,GUIDE_MOTION:.5}),S=o=>Math.min(1,Math.max(0,o)),M=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...Ce,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:t,quality:r,timestampMs:i}=e,n=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let a={presence:0,centering:0,size:0,pose:0,sharpness:S(r.sharpness),exposure:S(r.exposure),motion:1};if(t!==null){a.presence=1;let c=this.geometryOf(t,e);a.centering=c.centering,a.size=c.size,a.pose=c.pose,a.motion=this.motionOf(c.center,c.iod,i)}else this.lastCenter=null,this.velocityEma=0;let s=Math.min(a.presence,a.centering,a.size,a.pose,a.sharpness,a.exposure,a.motion);this.p=S(this.p+(s>=this.t.Q_GOOD?this.t.RISE_PER_S*s:-this.t.FALL_PER_S*(1-s))*n),this.qWindow.push({at:i,q:s}),this.qWindow=this.qWindow.filter(c=>c.at>=i-this.t.READY_WINDOW_MS);let d=this.qWindow.map(c=>c.q);if(d.length>=3){let c=Math.min(...d),l=d.indexOf(c);d=d.filter((f,h)=>h!==l)}let u=this.p>=1&&d.every(c=>c>=this.t.Q_GOOD);return{at:i,q:s,p:this.p,factors:a,guidanceKey:this.guidanceOf(a,r,s),ready:u,accepted:s>=this.t.Q_GOOD}}geometryOf(e,t){let{box:r,eyes:i}=e,n={x:t.frameWidth/2,y:t.frameHeight/2},a=Math.min(t.frameWidth,t.frameHeight),s=i!==void 0?{x:(i.left.x+i.right.x)/2,y:(i.left.y+i.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},d=i!==void 0?Math.hypot(i.right.x-i.left.x,i.right.y-i.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,u=Math.hypot(s.x-n.x,s.y-n.y),c=d<=0?0:1-S(u/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*d)),l=a>0?d/a:0;this.lastSizeDirection=l<this.t.SIZE_IDEAL_MIN?"far":l>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;l<this.t.SIZE_HARD_MIN||l>this.t.SIZE_HARD_MAX?f=0:l<this.t.SIZE_IDEAL_MIN?f=(l-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):l>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-l)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let h=1;if(i!==void 0){let p=Math.abs(Math.atan2(i.right.y-i.left.y,i.right.x-i.left.x))*180/Math.PI;h=1-S(p/this.t.ROLL_MAX_DEG)}return{center:s,iod:d,centering:c,size:f,pose:h}}motionOf(e,t,r){let i=this.lastCenter;if(this.lastCenter={...e,at:r},i===null||t<=0)return 1;let n=(r-i.at)/1e3;if(n<=0)return 1;let a=Math.hypot(e.x-i.x,e.y-i.y)/t/n;a<=this.t.MOTION_DEADBAND_IOD_PER_S&&(a=0);let s=1-Math.exp(-n/this.t.MOTION_TAU_S);return this.velocityEma=s*a+(1-s)*this.velocityEma,1-S(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,r){if(e.presence<=0)return"fcv3.no_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(t);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(r<this.t.Q_GOOD){let i=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],n=i[0];for(let a of i)e[a[0]]<e[n[0]]&&(n=a);return n[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(D[0]+D[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Te=["size","centering","pose","exposure","sharpness","motion"];function Re(o){if(o.accepted)return null;if(o.factors.presence<=0)return"no_face";let e="size";for(let t of Te)o.factors[t]<o.factors[e]&&(e=t);return e}var _=class{constructor(){this.blocked={};this.acceptedMs=0;this.ticks=0;this.lastAt=null}record(e){let t=this.lastAt===null?0:Math.max(0,e.at-this.lastAt);this.lastAt=e.at,this.ticks+=1;let r=Re(e);if(r===null){this.acceptedMs+=t;return}let i=this.blocked[r]??{count:0,ms:0};i.count+=1,i.ms+=t,this.blocked[r]=i}summary(){let e={};for(let[t,r]of Object.entries(this.blocked))e[t]={count:r.count,ms:Math.round(r.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var ke=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ae=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^camera2? ?\d+, facing (front|back|external)/i,/facetime/i,/\b(integrated|built-in|builtin) (web)?cam(era)?\b/i,/\b(hd )?web ?cam\b/i,/\([0-9a-f]{4}:[0-9a-f]{4}\)\s*$/i];function Ie(o){let e=(o??"").trim().toLowerCase();return e.length===0?"unknown":ke.some(t=>e.includes(t))?"known_virtual":Ae.some(t=>t.test(e))?"platform":"unknown"}function se(o){if(typeof o!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(o))}catch{return!1}}function we(o=globalThis){return se(o.navigator?.mediaDevices?.getUserMedia)&&se(o.MediaStreamTrack?.prototype?.getSettings)}async function De(o,e=globalThis){let t=e.crypto?.subtle?.digest;if(typeof t=="function")try{let r=new Uint8Array(await t.call(e.crypto?.subtle,"SHA-256",new TextEncoder().encode(o)));return Array.from(r.subarray(0,8),i=>i.toString(16).padStart(2,"0")).join("")}catch{return}}async function oe(o,e=globalThis){let t={};try{t=typeof o.getSettings=="function"?o.getSettings()??{}:{}}catch{t={}}let r={};if((t.facingMode==="user"||t.facingMode==="environment"||t.facingMode==="left"||t.facingMode==="right")&&(r.facingMode=t.facingMode),typeof t.frameRate=="number"&&Number.isFinite(t.frameRate)&&(r.frameRate=t.frameRate),typeof t.width=="number"&&Number.isFinite(t.width)&&(r.width=t.width),typeof t.height=="number"&&Number.isFinite(t.height)&&(r.height=t.height),typeof t.deviceId=="string"&&t.deviceId.length>0){let n=await De(t.deviceId,e);n!==void 0&&(r.deviceIdHash=n)}let i;try{i=o.label}catch{i=void 0}return{trackSettings:r,capabilitiesPresent:typeof o.getCapabilities=="function",labelClass:Ie(i),prototypesIntact:we(e)}}var x=o=>Math.round(o*100)/100;function ce(o){let e=o,t=typeof e?.requestVideoFrameCallback=="function",r=null,i=null,n=0,a=0,s=0,d=0,u=0,c=0,l=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((f,h)=>{if(r=null,!t)return;let p=h.presentationTime;if(i!==null){let m=p-i.presentationTimeMs;a+=1;let v=m-s;s+=v/a,d+=v*(m-s)}typeof h.captureTime=="number"&&Number.isFinite(h.captureTime)&&(u+=p-h.captureTime,c+=1),n+=1,i={mediaTimeMs:h.mediaTime*1e3,presentationTimeMs:p},l()}))};return l(),{latest:()=>i,stats:()=>({n,meanGapMs:a===0?0:x(s),stdGapMs:a<2?0:x(Math.sqrt(d/(a-1))),captureLatencyMs:c===0?null:x(u/c)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function le(o,e,t){return{...o,rvfc:e,rampPainter:t}}var Oe=1e3,P="fcv3.hold_upright",xe=200,G=4,Pe=600,Ge=1e3,ue={sharpness:1,exposure:1,meanLuma:128};function Le(o,e){return e.width=o.videoWidth,e.height=o.videoHeight,e.getContext("2d").drawImage(o,0,0),new Promise((t,r)=>e.toBlob(i=>i?t(i):r(new Error("empty-keyframe")),"image/jpeg",.92))}function Ve(){return F()==="phone"}var de=class{constructor(e){this.handlers=new Map;this.stateValue="idle";this.attempt=0;this.stream=null;this.detector=null;this.scheduler=null;this.gate=null;this.profiler=null;this.lastGuidanceKey=null;this.positioningStartedAt=0;this.cameraRequestedAt=null;this.cameraReadyAt=null;this.faceAcquiredAt=null;this.captureCompleteAt=null;this.fired=!1;this.carriedDegrade=0;this.carriedMeans=[];this.blockStats=null;this.lastGateSnapshotAt=Number.NEGATIVE_INFINITY;this.uprightGuard=!1;this.trackProvenance=null;this.ramp=null;this.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>r?.delete(t)}emit(e,t){for(let r of[...this.handlers.get(e)??[]])r(t)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:t}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.uprightGuard=(t.isPhone??Ve)(),this.setState("preflight");let r=W();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported");return}this.setState("acquiring");let i=t.getUserMedia??(u=>navigator.mediaDevices.getUserMedia(u)),n;this.cameraRequestedAt=this.now();try{n=await i(V(N(),this.facing))}catch(u){if(e!==this.attempt)return;this.fail(B(u));return}if(q(n),X(n),e!==this.attempt){for(let u of n.getTracks())u.stop();return}this.stream=n;let a=n.getVideoTracks?.()[0];if(this.trackProvenance=a===void 0?null:oe(a).catch(()=>null),this.facing=H(n)??this.facing,t.video.srcObject=n,await t.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let u={v3AssetBaseUrl:t.v3AssetBaseUrl},c=t.createDetector??(t.createWorker!==void 0&&Y()?async()=>{try{return await j.create(t.createWorker(),u)}catch{return w(u)}}:()=>w(u)),l;try{l=await c()}catch(f){e===this.attempt&&this.fail("models",f instanceof Z?f.fallbackReason:Ne(f));return}if(e!==this.attempt){l.destroy();return}this.detector=l,this.options.telemetry?.({type:"detector",tier:l.tier,fallbackReason:l.fallbackReason})}let s=$(),d=t.deviceClass??J(s);this.profiler=new ee(d),this.options.telemetry?.({type:"profile",staticClass:d,activeClass:this.profiler.deviceClass,simd:s.simd}),this.gate=new M(t.thresholds??{}),this.blockStats=new _,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(u=>L=u,()=>{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let t=this.profiler;if(t===null)return;if(this.scheduler!==null){let i=this.scheduler.stats();this.carriedDegrade+=i.degradeCount,i.meanDetectMs>0&&this.carriedMeans.push(i.meanDetectMs),this.scheduler.stop()}let r=new A({cadenceHz:t.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=r,r.start()}async detectTick(e){let{detector:t,gate:r,profiler:i}=this,n=this.options.video;if(e!==this.attempt||t===null||r===null||i===null||this.fired||n.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let a=i.deviceClass,s=this.now(),d=this.options.makeSnapshot?.(n,i.profile.inputWidth)??this.defaultSnapshot(n,i.profile.inputWidth),u=null;try{u=await t.detect(d,n.videoWidth,n.videoHeight)}catch{u=null}if(e!==this.attempt||this.fired)return;i.record(this.now()-s),i.deviceClass!==a&&this.startScheduler(e);let c=u===null?ue:this.options.measureQuality?.(n,u.box)??this.defaultQuality(n,u.box),l=r.tick({timestampMs:this.now(),observation:u,quality:c,frameWidth:n.videoWidth,frameHeight:n.videoHeight});l.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=l.at),this.blockStats?.record(l),!l.ready&&l.at-this.lastGateSnapshotAt>=Oe&&(this.lastGateSnapshotAt=l.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:l.p,q:l.q,factors:l.factors,attempt:e}),l.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=l.guidanceKey,this.emit("guidance",{key:l.guidanceKey})),l.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=l.at,this.fire(e))}async fire(e){let{options:t}=this,r=this.scheduler;r?.stop(),this.reportGate(!0);let i=r?.stats()??{degradeCount:0,meanDetectMs:0},n=[...this.carriedMeans,...i.meanDetectMs>0?[i.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+i.degradeCount,meanDetectMs:n.length===0?0:n.reduce((g,y)=>g+y,0)/n.length});let a=t.mode??"clip",s=t.rankKeyframes?.()&&L?L.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(a==="photo"){let g=this.watchRotation(e,null),y=await s;if(g(),e!==this.attempt)return;if(y===null){this.fail("generic");return}let fe=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:y.blob,previewDataUrl:y.previewDataUrl,...fe});return}this.setState("recording");let d=t.createRecorder?.()??new k,u=this.stream;if(u===null){this.fail("generic");return}let c=ce(t.video),l=t.screenRamp?.(),f=l!==void 0,h=ne(l,{paint:g=>{(g===null||e===this.attempt)&&this.emit("ramp",{colour:g})},now:()=>this.now(),frames:c.latest});this.ramp=h;let p=()=>{c.stop(),h.stop(),this.ramp===h&&(this.ramp=null)},m=this.watchRotation(e,d),v=null;s.then(g=>{v=g},()=>{});let E=()=>{e===this.attempt&&v!==null&&this.emit("frozen",{previewDataUrl:v.previewDataUrl})},C,T;try{[C,T]=await Promise.all([d.record(u,E,()=>h.started(this.now())),s])}catch(g){if(m(),p(),e!==this.attempt)return;let y=g.kind;this.fail(y==="cliptoolarge"?"cliptoolarge":"recorder");return}m();let he=c.stats();if(p(),e!==this.attempt)return;if(R(C.blob)){this.fail("cliptoolarge");return}if(T===null){this.fail("generic");return}let I=h.report(),me=await this.provenance(he,f);e===this.attempt&&this.finishCapture({clip:C.blob,clipMimeType:C.mimeType,keyframe:T.blob,previewDataUrl:T.previewDataUrl,...I!==void 0&&I.rendered.length>0?{screenRamp:I}:{},...me})}async provenance(e,t){let r=this.trackProvenance;if(r===null)return{};let i,n=new Promise(s=>{i=setTimeout(()=>s(null),Ge)}),a=await Promise.race([r,n]);return clearTimeout(i),a===null?{}:{provenance:le(a,e,t)}}isLandscape(){let e=this.options.video;return this.uprightGuard&&e.videoWidth>e.videoHeight}holdUpright(e){this.gate?.reset(),this.emit("checks",{engine:"v3",progress:0,q:0,factors:{presence:0,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==P&&(this.lastGuidanceKey=P,this.emit("guidance",{key:P}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,i=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){s();return}r.videoWidth>0&&this.isLandscape()&&(s(),this.abortRecording(e,t))},n=setInterval(i,xe);r.addEventListener?.("resize",i);let a=!1;function s(){a||(a=!0,clearInterval(n),r.removeEventListener?.("resize",i))}return s}abortRecording(e,t){if(e!==this.attempt)return;this.attempt+=1;let r=this.attempt;try{t?.stop()}catch{}this.ramp?.stop(),this.ramp=null,this.fired=!1,this.captureCompleteAt=null,this.gate=new M(this.options.thresholds??{}),this.blockStats=new _,this.lastGateSnapshotAt=this.now(),this.lastGuidanceKey=null,this.setState("positioning"),this.positioningStartedAt=this.now(),this.holdUpright(r),this.startScheduler(r)}async collectKeyframes(e){let t=this.options.captureKeyframe??(n=>this.defaultKeyframe(n)),r=Pe/(G-1),i=null;for(let n=0;n<G;n+=1){if(e!==this.attempt)return i;try{let a=await t(this.options.video);(i===null||a.sharpness>i.sharpness)&&(i=a)}catch{}n<G-1&&await Fe(r)}return i}finishCapture(e){this.stopTracks(),this.setState("captured");let t=this.captureTiming();this.emit("artifacts",t===void 0?e:{...e,timing:t})}captureTiming(){let e={},t=(r,i,n)=>{i!==null&&n!==null&&(e[r]=Math.max(0,Math.round(n-i)))};return t("cameraReadyMs",this.cameraRequestedAt,this.cameraReadyAt),t("faceAcquireMs",this.cameraReadyAt,this.faceAcquiredAt),t("captureMs",this.faceAcquiredAt,this.captureCompleteAt),Object.keys(e).length>0?e:void 0}async defaultKeyframe(e){let t=document.createElement("canvas"),r=await(this.facing==="user"?ae:Le)(e,t),i=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:i,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),i=t/Math.max(1,e.videoWidth),n=Math.max(1,Math.round(e.videoWidth*i)),a=Math.max(1,Math.round(e.videoHeight*i)),s=r.getContext("2d");return s===null?e:(r.width!==n&&(r.width=n),r.height!==a&&(r.height=a),s.drawImage(e,0,0,n,a),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,t){let r=pe(e,t,96);return r===null?ue:{sharpness:O(r),exposure:re(r),meanLuma:te(r)}}centerSharpness(e){let t=Q(e),r=pe(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:O(r)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.ramp?.stop(),this.ramp=null,this.stopTracks()}reportGate(e){let t=this.blockStats,r=this.profiler;if(t===null||r===null)return;let i=t.summary();e&&(this.blockStats=null),i.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...i})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:t}),this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported"})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},L;function Fe(o){return new Promise(e=>setTimeout(e,o))}function Ne(o){return o instanceof Error?o.message:String(o)}function pe(o,e,t){try{let r=document.createElement("canvas"),i=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*i)),r.height=Math.max(1,Math.round(e.height*i));let n=r.getContext("2d");return n===null?null:(n.drawImage(o,e.x,e.y,e.width,e.height,0,0,r.width,r.height),n.getImageData(0,0,r.width,r.height))}catch{return null}}export{ve as a,ge as b,be as c,ie as d,b as e,k as f,Ke as g,Be as h,ye as i,We as j,ae as k,A as l,Ce as m,M as n,Re as o,_ as p,Oe as q,P as r,xe as s,G as t,Pe as u,Ge as v,de as w};
|
|
1
|
+
import{a as V,c as F,d as N,e as H}from"./chunk-FUHDOEBP.js";import{b as $,c as J,d as ee}from"./chunk-POIQGEZM.js";import{b as U,c as K,d as B,e as W,g as z,h as R,k as X}from"./chunk-2BFYVMUU.js";import{b as D,c as te,d as O,e as re}from"./chunk-FPXL63KZ.js";import{c as q}from"./chunk-DNB3R4PI.js";import{c as Z,d as Q,f as w,h as Y,j}from"./chunk-OKWG3PVH.js";var ve=2500,ge=1e3,be=1500,ie=25e5,b=class extends Error{constructor(e,t){super(t??e),this.kind=e}},k=class{constructor(){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.settled=!1}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.hardStopTimer=null,this.graceTimer=null}record(e,t,r){if(this.recorder&&!this.settled)return Promise.reject(new b("generic","record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time"));this.recorder=null,this.clearTimers(),this.chunks=[],this.bytes=0,this.settled=!1,this.stream=e;let i=U();return new Promise((n,a)=>{let s;try{s=new MediaRecorder(e,i?{mimeType:i,videoBitsPerSecond:ie}:{videoBitsPerSecond:ie})}catch{try{s=new MediaRecorder(e)}catch{a(new b("unsupported"));return}}this.recorder=s;let d=c=>{this.settled||(this.settled=!0,this.clearTimers(),c())},u=()=>d(()=>{let c=s.mimeType||i||K,l=new Blob(this.chunks,{type:c});if(l.size===0){a(new b("generic","empty clip"));return}if(R(l)){a(new b("cliptoolarge"));return}n({blob:l,mimeType:c})});if(s.ondataavailable=c=>{c.data&&c.data.size&&(this.chunks.push(c.data),this.bytes+=c.data.size,this.bytes>z&&d(()=>{try{s.state!=="inactive"&&s.stop()}catch{}a(new b("cliptoolarge"))}))},s.onstop=u,s.onerror=()=>d(()=>a(new b("generic"))),r!==void 0){let c=!1;s.onstart=()=>{if(!(c||this.settled)){c=!0;try{r()}catch{}}}}try{s.start(ge)}catch{d(()=>a(new b("generic")));return}this.hardStopTimer=setTimeout(()=>{if(this.settled||t?.(),s.state!=="inactive"){try{s.stop()}catch{u()}this.graceTimer=setTimeout(u,be)}else u()},ve)})}stop(e){this.clearTimers();let t=this.recorder;if(t&&t.state!=="inactive")try{t.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(i=>i.stop()),this.stream=null}};var Ke=400,Be=2e3,ye=["rose","peach","sand","mint","sky","lilac"],Se={rose:"rgb(255, 185, 205)",peach:"rgb(245, 193, 159)",sand:"rgb(195, 210, 158)",mint:"rgb(139, 219, 203)",sky:"rgb(140, 214, 249)",lilac:"rgb(208, 197, 249)"};function We(o){return Se[o]}var Ee=4,Me=4;function _e(o){if(typeof o!="object"||o===null)return!1;let e=o;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length!==3||!e.colours.every(r=>ye.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==3)return!1;let t=-1;for(let r of e.onsetsMs){if(typeof r!="number"||!Number.isFinite(r)||r<=t||r>=2e3)return!1;t=r}return!0}function ne(o,e){let t=e.now??(()=>performance.now()),r=_e(o)?o:void 0,i=[],n=null,a=null,s=null,d=!1,u=null,c=p=>{u=p;try{e.paint(p)}catch{}},l=p=>{let m=e.frames?.()??null;return m!==null&&s!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-s:p-(a??p)},f=(p,m,v=0)=>{if(d)return;let E=Math.max(0,p-l(t()));n=setTimeout(()=>{if(n=null,!d){if(v<Ee&&l(t())<p-Me){f(p,m,v+1);return}m()}},E)},h=p=>{if(r!==void 0){if(p>=3){f(2e3,()=>c(null));return}f(r.onsetsMs[p],()=>{let m=l(t());if(m>2e3){u!==null&&c(null);return}let v=r.colours[p];c(v);let E=i.length===0?0:i[i.length-1].tMs;i.push({tMs:Math.max(E,Math.round(m)),colour:v}),h(p+1)})}};return{started(p){if(r===void 0||d||a!==null)return;a=p;let m=e.frames?.()??null;s=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),h(0)},stop(){d||(d=!0,n!==null&&clearTimeout(n),n=null,u!==null&&c(null))},report(){return r===void 0?void 0:{nonce:r.nonce,rendered:[...i]}}}}function ae(o,e,t=.92){return new Promise((r,i)=>{let n=o.videoWidth,a=o.videoHeight;if(!n||!a){i(new Error("video-not-ready"));return}let s=e.getContext("2d");if(!s){i(new Error("no-2d-context"));return}e.width=n,e.height=a,s.scale(-1,1),s.drawImage(o,-n,0),e.toBlob(d=>d?r(d):i(new Error("empty-keyframe")),"image/jpeg",t)})}var A=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let t=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),t()}))};t();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((t,r)=>t+r,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var Ce=Object.freeze({Q_GOOD:.6,RISE_PER_S:.9,FALL_PER_S:.25,CENTER_FALLOFF_IOD_MULTIPLE:1.35,BOX_EYE_OFFSET_FACTOR:.12,IOD_BOX_PROXY_FACTOR:.42,SIZE_IDEAL_MIN:.12,SIZE_IDEAL_MAX:.3,SIZE_HARD_MIN:.08,SIZE_HARD_MAX:.45,ROLL_MAX_DEG:25,MOTION_VELOCITY_IOD_PER_S:.5,MOTION_TAU_S:.4,MOTION_DEADBAND_IOD_PER_S:.1,READY_WINDOW_MS:500,GUIDE_SIZE:.6,GUIDE_CENTERING:.6,GUIDE_POSE:.6,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,GUIDE_MOTION:.5}),S=o=>Math.min(1,Math.max(0,o)),M=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...Ce,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:t,quality:r,timestampMs:i}=e,n=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let a={presence:0,centering:0,size:0,pose:0,sharpness:S(r.sharpness),exposure:S(r.exposure),motion:1};if(t!==null){a.presence=1;let c=this.geometryOf(t,e);a.centering=c.centering,a.size=c.size,a.pose=c.pose,a.motion=this.motionOf(c.center,c.iod,i)}else this.lastCenter=null,this.velocityEma=0;let s=Math.min(a.presence,a.centering,a.size,a.pose,a.sharpness,a.exposure,a.motion);this.p=S(this.p+(s>=this.t.Q_GOOD?this.t.RISE_PER_S*s:-this.t.FALL_PER_S*(1-s))*n),this.qWindow.push({at:i,q:s}),this.qWindow=this.qWindow.filter(c=>c.at>=i-this.t.READY_WINDOW_MS);let d=this.qWindow.map(c=>c.q);if(d.length>=3){let c=Math.min(...d),l=d.indexOf(c);d=d.filter((f,h)=>h!==l)}let u=this.p>=1&&d.every(c=>c>=this.t.Q_GOOD);return{at:i,q:s,p:this.p,factors:a,guidanceKey:this.guidanceOf(a,r,s),ready:u,accepted:s>=this.t.Q_GOOD}}geometryOf(e,t){let{box:r,eyes:i}=e,n={x:t.frameWidth/2,y:t.frameHeight/2},a=Math.min(t.frameWidth,t.frameHeight),s=i!==void 0?{x:(i.left.x+i.right.x)/2,y:(i.left.y+i.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},d=i!==void 0?Math.hypot(i.right.x-i.left.x,i.right.y-i.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,u=Math.hypot(s.x-n.x,s.y-n.y),c=d<=0?0:1-S(u/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*d)),l=a>0?d/a:0;this.lastSizeDirection=l<this.t.SIZE_IDEAL_MIN?"far":l>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;l<this.t.SIZE_HARD_MIN||l>this.t.SIZE_HARD_MAX?f=0:l<this.t.SIZE_IDEAL_MIN?f=(l-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):l>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-l)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let h=1;if(i!==void 0){let p=Math.abs(Math.atan2(i.right.y-i.left.y,i.right.x-i.left.x))*180/Math.PI;h=1-S(p/this.t.ROLL_MAX_DEG)}return{center:s,iod:d,centering:c,size:f,pose:h}}motionOf(e,t,r){let i=this.lastCenter;if(this.lastCenter={...e,at:r},i===null||t<=0)return 1;let n=(r-i.at)/1e3;if(n<=0)return 1;let a=Math.hypot(e.x-i.x,e.y-i.y)/t/n;a<=this.t.MOTION_DEADBAND_IOD_PER_S&&(a=0);let s=1-Math.exp(-n/this.t.MOTION_TAU_S);return this.velocityEma=s*a+(1-s)*this.velocityEma,1-S(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,r){if(e.presence<=0)return"fcv3.no_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(t);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(r<this.t.Q_GOOD){let i=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],n=i[0];for(let a of i)e[a[0]]<e[n[0]]&&(n=a);return n[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(D[0]+D[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Te=["size","centering","pose","exposure","sharpness","motion"];function Re(o){if(o.accepted)return null;if(o.factors.presence<=0)return"no_face";let e="size";for(let t of Te)o.factors[t]<o.factors[e]&&(e=t);return e}var _=class{constructor(){this.blocked={};this.acceptedMs=0;this.ticks=0;this.lastAt=null}record(e){let t=this.lastAt===null?0:Math.max(0,e.at-this.lastAt);this.lastAt=e.at,this.ticks+=1;let r=Re(e);if(r===null){this.acceptedMs+=t;return}let i=this.blocked[r]??{count:0,ms:0};i.count+=1,i.ms+=t,this.blocked[r]=i}summary(){let e={};for(let[t,r]of Object.entries(this.blocked))e[t]={count:r.count,ms:Math.round(r.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var ke=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ae=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^camera2? ?\d+, facing (front|back|external)/i,/facetime/i,/\b(integrated|built-in|builtin) (web)?cam(era)?\b/i,/\b(hd )?web ?cam\b/i,/\([0-9a-f]{4}:[0-9a-f]{4}\)\s*$/i];function Ie(o){let e=(o??"").trim().toLowerCase();return e.length===0?"unknown":ke.some(t=>e.includes(t))?"known_virtual":Ae.some(t=>t.test(e))?"platform":"unknown"}function se(o){if(typeof o!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(o))}catch{return!1}}function we(o=globalThis){return se(o.navigator?.mediaDevices?.getUserMedia)&&se(o.MediaStreamTrack?.prototype?.getSettings)}async function De(o,e=globalThis){let t=e.crypto?.subtle?.digest;if(typeof t=="function")try{let r=new Uint8Array(await t.call(e.crypto?.subtle,"SHA-256",new TextEncoder().encode(o)));return Array.from(r.subarray(0,8),i=>i.toString(16).padStart(2,"0")).join("")}catch{return}}async function oe(o,e=globalThis){let t={};try{t=typeof o.getSettings=="function"?o.getSettings()??{}:{}}catch{t={}}let r={};if((t.facingMode==="user"||t.facingMode==="environment"||t.facingMode==="left"||t.facingMode==="right")&&(r.facingMode=t.facingMode),typeof t.frameRate=="number"&&Number.isFinite(t.frameRate)&&(r.frameRate=t.frameRate),typeof t.width=="number"&&Number.isFinite(t.width)&&(r.width=t.width),typeof t.height=="number"&&Number.isFinite(t.height)&&(r.height=t.height),typeof t.deviceId=="string"&&t.deviceId.length>0){let n=await De(t.deviceId,e);n!==void 0&&(r.deviceIdHash=n)}let i;try{i=o.label}catch{i=void 0}return{trackSettings:r,capabilitiesPresent:typeof o.getCapabilities=="function",labelClass:Ie(i),prototypesIntact:we(e)}}var x=o=>Math.round(o*100)/100;function ce(o){let e=o,t=typeof e?.requestVideoFrameCallback=="function",r=null,i=null,n=0,a=0,s=0,d=0,u=0,c=0,l=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((f,h)=>{if(r=null,!t)return;let p=h.presentationTime;if(i!==null){let m=p-i.presentationTimeMs;a+=1;let v=m-s;s+=v/a,d+=v*(m-s)}typeof h.captureTime=="number"&&Number.isFinite(h.captureTime)&&(u+=p-h.captureTime,c+=1),n+=1,i={mediaTimeMs:h.mediaTime*1e3,presentationTimeMs:p},l()}))};return l(),{latest:()=>i,stats:()=>({n,meanGapMs:a===0?0:x(s),stdGapMs:a<2?0:x(Math.sqrt(d/(a-1))),captureLatencyMs:c===0?null:x(u/c)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function le(o,e,t){return{...o,rvfc:e,rampPainter:t}}var Oe=1e3,P="fcv3.hold_upright",xe=200,G=4,Pe=600,Ge=1e3,ue={sharpness:1,exposure:1,meanLuma:128};function Le(o,e){return e.width=o.videoWidth,e.height=o.videoHeight,e.getContext("2d").drawImage(o,0,0),new Promise((t,r)=>e.toBlob(i=>i?t(i):r(new Error("empty-keyframe")),"image/jpeg",.92))}function Ve(){return F()==="phone"}var de=class{constructor(e){this.handlers=new Map;this.stateValue="idle";this.attempt=0;this.stream=null;this.detector=null;this.scheduler=null;this.gate=null;this.profiler=null;this.lastGuidanceKey=null;this.positioningStartedAt=0;this.cameraRequestedAt=null;this.cameraReadyAt=null;this.faceAcquiredAt=null;this.captureCompleteAt=null;this.fired=!1;this.carriedDegrade=0;this.carriedMeans=[];this.blockStats=null;this.lastGateSnapshotAt=Number.NEGATIVE_INFINITY;this.uprightGuard=!1;this.trackProvenance=null;this.ramp=null;this.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>r?.delete(t)}emit(e,t){for(let r of[...this.handlers.get(e)??[]])r(t)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:t}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.uprightGuard=(t.isPhone??Ve)(),this.setState("preflight");let r=W();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported");return}this.setState("acquiring");let i=t.getUserMedia??(u=>navigator.mediaDevices.getUserMedia(u)),n;this.cameraRequestedAt=this.now();try{n=await i(V(N(),this.facing))}catch(u){if(e!==this.attempt)return;this.fail(B(u));return}if(q(n),X(n),e!==this.attempt){for(let u of n.getTracks())u.stop();return}this.stream=n;let a=n.getVideoTracks?.()[0];if(this.trackProvenance=a===void 0?null:oe(a).catch(()=>null),this.facing=H(n)??this.facing,t.video.srcObject=n,await t.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let u={v3AssetBaseUrl:t.v3AssetBaseUrl},c=t.createDetector??(t.createWorker!==void 0&&Y()?async()=>{try{return await j.create(t.createWorker(),u)}catch{return w(u)}}:()=>w(u)),l;try{l=await c()}catch(f){e===this.attempt&&this.fail("models",f instanceof Z?f.fallbackReason:Ne(f));return}if(e!==this.attempt){l.destroy();return}this.detector=l,this.options.telemetry?.({type:"detector",tier:l.tier,fallbackReason:l.fallbackReason})}let s=$(),d=t.deviceClass??J(s);this.profiler=new ee(d),this.options.telemetry?.({type:"profile",staticClass:d,activeClass:this.profiler.deviceClass,simd:s.simd}),this.gate=new M(t.thresholds??{}),this.blockStats=new _,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(u=>L=u,()=>{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let t=this.profiler;if(t===null)return;if(this.scheduler!==null){let i=this.scheduler.stats();this.carriedDegrade+=i.degradeCount,i.meanDetectMs>0&&this.carriedMeans.push(i.meanDetectMs),this.scheduler.stop()}let r=new A({cadenceHz:t.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=r,r.start()}async detectTick(e){let{detector:t,gate:r,profiler:i}=this,n=this.options.video;if(e!==this.attempt||t===null||r===null||i===null||this.fired||n.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let a=i.deviceClass,s=this.now(),d=this.options.makeSnapshot?.(n,i.profile.inputWidth)??this.defaultSnapshot(n,i.profile.inputWidth),u=null;try{u=await t.detect(d,n.videoWidth,n.videoHeight)}catch{u=null}if(e!==this.attempt||this.fired)return;i.record(this.now()-s),i.deviceClass!==a&&this.startScheduler(e);let c=u===null?ue:this.options.measureQuality?.(n,u.box)??this.defaultQuality(n,u.box),l=r.tick({timestampMs:this.now(),observation:u,quality:c,frameWidth:n.videoWidth,frameHeight:n.videoHeight});l.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=l.at),this.blockStats?.record(l),!l.ready&&l.at-this.lastGateSnapshotAt>=Oe&&(this.lastGateSnapshotAt=l.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:l.p,q:l.q,factors:l.factors,attempt:e}),l.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=l.guidanceKey,this.emit("guidance",{key:l.guidanceKey})),l.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=l.at,this.fire(e))}async fire(e){let{options:t}=this,r=this.scheduler;r?.stop(),this.reportGate(!0);let i=r?.stats()??{degradeCount:0,meanDetectMs:0},n=[...this.carriedMeans,...i.meanDetectMs>0?[i.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+i.degradeCount,meanDetectMs:n.length===0?0:n.reduce((g,y)=>g+y,0)/n.length});let a=t.mode??"clip",s=t.rankKeyframes?.()&&L?L.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(a==="photo"){let g=this.watchRotation(e,null),y=await s;if(g(),e!==this.attempt)return;if(y===null){this.fail("generic");return}let fe=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:y.blob,previewDataUrl:y.previewDataUrl,...fe});return}this.setState("recording");let d=t.createRecorder?.()??new k,u=this.stream;if(u===null){this.fail("generic");return}let c=ce(t.video),l=t.screenRamp?.(),f=l!==void 0,h=ne(l,{paint:g=>{(g===null||e===this.attempt)&&this.emit("ramp",{colour:g})},now:()=>this.now(),frames:c.latest});this.ramp=h;let p=()=>{c.stop(),h.stop(),this.ramp===h&&(this.ramp=null)},m=this.watchRotation(e,d),v=null;s.then(g=>{v=g},()=>{});let E=()=>{e===this.attempt&&v!==null&&this.emit("frozen",{previewDataUrl:v.previewDataUrl})},C,T;try{[C,T]=await Promise.all([d.record(u,E,()=>h.started(this.now())),s])}catch(g){if(m(),p(),e!==this.attempt)return;let y=g.kind;this.fail(y==="cliptoolarge"?"cliptoolarge":"recorder");return}m();let he=c.stats();if(p(),e!==this.attempt)return;if(R(C.blob)){this.fail("cliptoolarge");return}if(T===null){this.fail("generic");return}let I=h.report(),me=await this.provenance(he,f);e===this.attempt&&this.finishCapture({clip:C.blob,clipMimeType:C.mimeType,keyframe:T.blob,previewDataUrl:T.previewDataUrl,...I!==void 0&&I.rendered.length>0?{screenRamp:I}:{},...me})}async provenance(e,t){let r=this.trackProvenance;if(r===null)return{};let i,n=new Promise(s=>{i=setTimeout(()=>s(null),Ge)}),a=await Promise.race([r,n]);return clearTimeout(i),a===null?{}:{provenance:le(a,e,t)}}isLandscape(){let e=this.options.video;return this.uprightGuard&&e.videoWidth>e.videoHeight}holdUpright(e){this.gate?.reset(),this.emit("checks",{engine:"v3",progress:0,q:0,factors:{presence:0,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==P&&(this.lastGuidanceKey=P,this.emit("guidance",{key:P}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,i=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){s();return}r.videoWidth>0&&this.isLandscape()&&(s(),this.abortRecording(e,t))},n=setInterval(i,xe);r.addEventListener?.("resize",i);let a=!1;function s(){a||(a=!0,clearInterval(n),r.removeEventListener?.("resize",i))}return s}abortRecording(e,t){if(e!==this.attempt)return;this.attempt+=1;let r=this.attempt;try{t?.stop()}catch{}this.ramp?.stop(),this.ramp=null,this.fired=!1,this.captureCompleteAt=null,this.gate=new M(this.options.thresholds??{}),this.blockStats=new _,this.lastGateSnapshotAt=this.now(),this.lastGuidanceKey=null,this.setState("positioning"),this.positioningStartedAt=this.now(),this.holdUpright(r),this.startScheduler(r)}async collectKeyframes(e){let t=this.options.captureKeyframe??(n=>this.defaultKeyframe(n)),r=Pe/(G-1),i=null;for(let n=0;n<G;n+=1){if(e!==this.attempt)return i;try{let a=await t(this.options.video);(i===null||a.sharpness>i.sharpness)&&(i=a)}catch{}n<G-1&&await Fe(r)}return i}finishCapture(e){this.stopTracks(),this.setState("captured");let t=this.captureTiming();this.emit("artifacts",t===void 0?e:{...e,timing:t})}captureTiming(){let e={},t=(r,i,n)=>{i!==null&&n!==null&&(e[r]=Math.max(0,Math.round(n-i)))};return t("cameraReadyMs",this.cameraRequestedAt,this.cameraReadyAt),t("faceAcquireMs",this.cameraReadyAt,this.faceAcquiredAt),t("captureMs",this.faceAcquiredAt,this.captureCompleteAt),Object.keys(e).length>0?e:void 0}async defaultKeyframe(e){let t=document.createElement("canvas"),r=await(this.facing==="user"?ae:Le)(e,t),i=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:i,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),i=t/Math.max(1,e.videoWidth),n=Math.max(1,Math.round(e.videoWidth*i)),a=Math.max(1,Math.round(e.videoHeight*i)),s=r.getContext("2d");return s===null?e:(r.width!==n&&(r.width=n),r.height!==a&&(r.height=a),s.drawImage(e,0,0,n,a),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,t){let r=pe(e,t,96);return r===null?ue:{sharpness:O(r),exposure:re(r),meanLuma:te(r)}}centerSharpness(e){let t=Q(e),r=pe(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:O(r)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.ramp?.stop(),this.ramp=null,this.stopTracks()}reportGate(e){let t=this.blockStats,r=this.profiler;if(t===null||r===null)return;let i=t.summary();e&&(this.blockStats=null),i.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...i})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:t}),this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported"})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},L;function Fe(o){return new Promise(e=>setTimeout(e,o))}function Ne(o){return o instanceof Error?o.message:String(o)}function pe(o,e,t){try{let r=document.createElement("canvas"),i=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*i)),r.height=Math.max(1,Math.round(e.height*i));let n=r.getContext("2d");return n===null?null:(n.drawImage(o,e.x,e.y,e.width,e.height,0,0,r.width,r.height),n.getImageData(0,0,r.width,r.height))}catch{return null}}export{ve as a,ge as b,be as c,ie as d,b as e,k as f,Ke as g,Be as h,ye as i,We as j,ae as k,A as l,Ce as m,M as n,Re as o,_ as p,Oe as q,P as r,xe as s,G as t,Pe as u,Ge as v,de as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as X,b as Pe,d as V,e as L,f as U,g as be,h as E,i as B,j as P,k as F,l as x,m as z,n as w,o as D,w as xe,x as Re}from"./chunk-JDTZK3A7.js";import{m as _e}from"./chunk-VCUOPQFA.js";import{a as Ce}from"./chunk-GT2ZLGF7.js";import{d as Q}from"./chunk-FUHDOEBP.js";import{c as j,f as ke,g as G}from"./chunk-ZMO2ZQAS.js";function K(e){return e.idNumberBound??e.nniBound}function H(e){return e===void 0?void 0:e.idNumberFromDocument??e.nniFromDocument}function ve(e){let t=e.idNumberMasked??e.nniMasked;return typeof t=="string"&&t!==""?t:void 0}var $e="https://api.sekyro.ai",Je=5e3,Qe=1500,je=10;function Xe(e){return new Promise(t=>setTimeout(t,e))}function ze(){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 o=0;o<16;o+=1)t[o]=Math.floor(Math.random()*256);t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let i=[...t].map(o=>o.toString(16).padStart(2,"0")).join("");return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}function Lt(e){return et(e,{})}function et(e,t){let i=e.apiOrigin??$e,o=e.autoRetry??!0,r=e.rearm??"auto",s=t.client??new ke({apiOrigin:i,sessionToken:e.clientToken,fetch:e.fetch}),u=t.sleep??Xe,a=t.uuid??ze,l=t.getTurnstileToken??((n,c)=>import("./turnstile-FATNZ4AG.js").then(p=>p.executeTurnstile(n,c))),S=Ce(),h=null,m=null,d=!1,b=new AbortController,f=null,q=null,R=n=>{f=n,S.emit("view",n),h?.onView(n)},_=()=>f!==null?Promise.resolve(f):(q??(q=s.getSession().then(n=>(R(n),n)).finally(()=>{q=null})),q),v=async()=>{let n=await s.getSession();return R(n),n},Y=async(n,c)=>{n.plan!==void 0?R(n):await v()},Z=null,oe=async n=>{let c=await _();if(!n&&c.consentRecorded)return;let p=await s.recordConsent(e.locale);p.plan!==void 0?R(p):f!==null&&R({...f,consentRecorded:!0})},O=n=>n?.force===!0?oe(!0):(Z??(Z=oe(!1).finally(()=>{Z=null})),Z),W={client:s,ensureConsent:n=>O(n),sleep:u,uuid:a,onBusy:n=>{d||S.emit("busy",n)}},re=!1,se=null,$=n=>{if(n.status==="approved"||n.status==="rejected"||n.status==="review"){if(re)return;re=!0}se=JSON.stringify(n),S.emit("result",n)},De=n=>{se!==JSON.stringify(n)&&$(n)},ae=async n=>{let c=f;n&&(c=await v().catch(()=>f));let p=c===null?null:E(c);return p!==null&&!d&&S.emit("method",p),p!==null},ce=null,ue=!1,de=!1,le=()=>xe(W,(n,c)=>n.submitCheck("population_registry",{},{idempotencyKey:c})),pe=n=>K(n)===!0||H(x(n,"population_registry"))===!0,He=async()=>{try{let n=await _();if(P(n)||E(n)!==null||F(n)?.checkType!=="population_registry")return;if(!pe(n)&&H(x(n,"population_registry"))===void 0&&(n=await v()),!pe(n)){de=!0;return}await O(),await Y(await le(),"population_registry");let c=f===null?void 0:x(f,"population_registry");if(c?.state==="input_required"&&c.reason==="registry_unavailable"&&U(c)>0){if(await u(Je),d)return;await Y(await le(),"population_registry")}}catch(n){if(n instanceof j&&(n.code==="check_not_active"||n.code==="step_not_on_path")){await v().catch(()=>{});return}ue=!0;return}f!==null&&P(f)&&$(D(f,{autoRetry:o}))},fe=()=>(ce??(ce=He()),ce),Ne=async()=>{let c=(await _()).turnstileSiteKey;return c===null?{sandbox:!0}:{channel:"hosted_web",siteKey:c,turnstileToken:await l(c,{signal:b.signal})}},k=null,me=Promise.resolve(),T=0,Le=async()=>{let n=await _();for(let c=0;c<je&&!d&&!P(n)&&F(n)===void 0&&L(n).some(p=>p.state==="processing")&&(await u(Qe),!d);c+=1)n=await v();return n},Ue=async(n,c,p)=>{let{capture:g}=n,C=()=>d,N=()=>n.alive&&n.attempt===p,ye=y=>{N()&&g.setFlowState(y)},I=y=>{if(!C()&&($(y),!!N())){if(y.status==="retry"&&r==="auto"){g.handle.retry();return}g.setFlowState("done")}};if(c.degraded==="NO_RECORDER"){let y=f?.sessionId??(await _().catch(()=>null))?.sessionId??"";I(w(y,"no_recorder"));return}ye("uploading");try{if(await fe(),C())return;let y=await _(),ge;if(!P(y)&&E(y)!==null){await ae(!1),I(w(y.sessionId,"method_required"));return}if(!P(y)){if(F(y)?.checkType==="population_registry"){I(w(y.sessionId,de?"nni_unbound":ue?"network":"registry_unavailable"));return}if(await O(),C())return;ge=f??y;let J=await Re({...W,artifacts:c,getAttestation:Ne,getView:()=>f??y,refreshView:v,applySubmit:Y,onPhase:ye,isCancelled:C,onKeyframePromoted:We=>{m=We}});if(C())return;if(J.kind==="unavailable"){I(w(y.sessionId,J.reason));return}if(J.kind==="resync"&&await v(),f!==null&&E(f)!==null){await ae(!1),I(w(y.sessionId,"method_required"));return}y=await Le()}I(D(y,{autoRetry:o,previous:ge}))}catch{if(C())return;I(w(f?.sessionId??"","network"))}},Be=(n,c)=>{let p=n.attempt;T>0&&n.alive&&n.capture.setFlowState("uploading"),T+=1,me=me.then(()=>Ue(n,c,p)).finally(()=>{T-=1,T===0&&h?.onChainIdle()}).catch(()=>{})},he=n=>{k?.capture.handle.destroy(),k!==null&&(k.alive=!1);let c=_e(n,h?.captureInternals?.(n)??t.capture,()=>f?.capture?.liveness?.keyframe?.rank===!0,()=>X(f),()=>f?.capture?.liveness?.screenRamp),p={capture:c,alive:!0,attempt:0};k=p,c.handle.on("state",C=>{C==="starting"&&(p.attempt+=1)}),c.handle.on("captured",C=>{Promise.resolve().then(()=>Be(p,C))});let g=c.handle;return{get state(){return g.state},get captureMode(){return g.captureMode},get facingMode(){return g.facingMode},on:(C,N)=>g.on(C,N),start:async C=>{if(f===null&&await _().catch(()=>{}),!!p.alive)return g.start(C)},retry:()=>g.retry(),switchCamera:()=>g.switchCamera(),destroy:()=>{p.alive=!1,k===p&&(k=null),g.destroy()}}},Fe=async()=>{if(d)return null;try{let n=await _();return d?null:E(n)}catch{return null}},Ge=async()=>{if(d)return"self";try{let n=await _();return d?"self":X(n)}catch{return"self"}},Ke=async()=>{if(d)return!1;try{let n=await _();if(d||P(n))return!1;let c=x(n,"liveness");return B(c)&&c?.requiresMobile===!0&&!Q()}catch{return!1}},qe=async()=>{if(d)return!1;try{let n=await _();return!d&&n.returning===!0}catch{return!1}},Ye=async n=>{let c=(await _()).plan?.choice,p=c?.options.find(C=>V[C.service]===n);if(!p)throw new RangeError(`method ${String(n)} is not offered`);let g=await s.choose(c.nodeId,p.id);d||R(g)},Se=null,Ze=()=>(Se??(Se=import("./plan-runner-YXTOSPDP.js").then(n=>{let c=n.createPlanRunner({runtime:W,currentView:()=>f,ensureView:_,refreshView:v,ensureConsent:()=>O(),liveness:he,chainBusy:()=>T>0,destroyed:()=>d,sleep:u,isMobile:Q,now:t.now??Date.now,keptFaceKey:()=>m,setView:R,baseCapture:t.capture,emitStep:p=>{d||S.emit("step",p)},emitResult:De,documentInternals:t.document,portraitInternals:t.portrait,livePhotoInternals:t.livePhoto});return h=c,c})),Se);return{consent:()=>O(),startRegistry:fe,methodChoice:Fe,selectMethod:Ye,reportCameraUnavailable:async n=>{await O();let c=s.reportCameraUnavailable;if(c===void 0)throw new TypeError("this client cannot report a missing camera");let p=await c.call(s,n).catch(g=>{if(g instanceof j&&g.code==="check_out_of_order")return s.getSession();throw g});d||R(p)},mobileRequired:Ke,captureMode:Ge,returning:qe,liveness:he,run:async()=>{if(d)throw new Error("verification destroyed");return(await Ze()).run()},currentStep:()=>h?.current()??null,voiceClips:async()=>{if(d)return null;try{let n=await _();return d?null:n.voice??null}catch{return null}},on:(n,c)=>S.on(n,c),destroy:()=>{d=!0,b.abort(),h?.destroy(),k!==null&&(k.alive=!1,k.capture.handle.destroy(),k=null),S.clear()}}}var Ae=["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 tt=["carte_identite","passport","residence_permit"];function nt(e,t){let i=e.byIssuer?.[t]??e.default;return tt.filter(o=>i==="*"||i.includes(o))}function Gt(e,t=Ae){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(o=>nt(e,o).length>0).sort()}function Ie(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}function Kt(e){return/^[A-Z]{2}$/.test(e)?String.fromCodePoint(...[...e].map(t=>127462+t.charCodeAt(0)-65)):""}var Qt=["national_number","document_photo","national_eid"],it=new Set(["phone_otp","email_otp","national_eid","document","nfc","population_registry","supplied_identity","summary_confirm","liveness","face_match","aml_screening","face_dedup","age_estimation"]),ot=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),te=["document","population_registry","national_eid"],ne=["phone_otp","email_otp"],Ee={identity_method:te,contact:ne},rt=["population_registry","document"],Me="platform_unsupported",st=new Set(["prefilled","user_entered","prefilled_or_entered"]),at={phone_otp:"contact",email_otp:"contact",eid_auth:"identity",doc_ocr:"identity",nfc_chip:"identity",population_registry:"identity",liveness:"live_photo",portrait_icao:"live_photo",face_match:"live_photo"};function A(e){return e.section??at[e.checkType]??null}function ct(e,t){let i=e.plan?.choice;if(i===void 0||i.locked)return;let o=i.options.find(r=>r.id!==i.selected&&r.available!==!1&&t.includes(r.service));return o===void 0?void 0:{nodeId:i.nodeId,option:o}}function ie(e){let t=e.plan,i=t?.choice;if(t===void 0||i===void 0||i.locked||t.current===null||t.current===i.nodeId||P(e))return null;let o=Ee[i.kind]??[...te,...ne],r=i.options.flatMap(a=>a.available===!1||!o.includes(a.service)?[]:[a.nationalEid!=null?{id:a.id,service:a.service,nationalEid:a.nationalEid}:{id:a.id,service:a.service}]),s=t.steps.find(a=>a.id===t.current)?.service,u=i.selected??r.find(a=>a.service===s)?.id??null;return r.some(a=>a.id!==u)?{nodeId:i.nodeId,kind:i.kind,current:u,options:r}:null}function Te(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function ut(e){let t=(e.plan?.sections??[]).map(r=>({id:r.id,state:r.state})),i={sessionId:z(e.sessionId),orgName:e.orgName,returning:e.returning===!0,consentRecorded:e.consentRecorded,expiresAt:e.expiresAt,sections:t.map(r=>r.id),progress:t,purpose:e.purpose??"identity"};e.branding!==void 0&&(i.branding=e.branding),e.cameraUnavailableHandled===!0&&(i.cameraUnavailableHandled=!0);let o=ie(e);return o!==null&&(i.switchable=o),i}function dt(e){let t={attemptsRemaining:U(e),attemptsExhausted:e.attemptsExhausted===!0};return e.reason!==void 0&&(t.reason=e.reason),e.retakeHint!==void 0&&(t.retakeHint=e.retakeHint),t}var Ve={phone_otp:"phone",email_otp:"email"};function lt(e,t){let i=ct(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return i===void 0?void 0:Ve[i.option.service]}function pt(e,t,i,o){let r=t.checkType==="email_otp",s=(r?t.emailOtp:t.otp)??{},u=r?t.emailOtp?.emailSource:t.otp?.numberSource,a=u!==void 0&&st.has(u)?u:r?"prefilled_or_entered":"user_entered",l=typeof s.sentToMasked=="string"&&s.sentToMasked.length>0,S=lt(e,r?"email_otp":"phone_otp"),h={key:t.checkType,context:i,section:A(t),phase:l?"verify":"send",canSwitch:S!==void 0,...o},m=r?{kind:"email_otp",...h,emailSource:a,needsEmail:a!=="prefilled"}:{kind:"phone_otp",...h,numberSource:a,needsPhone:a!=="prefilled",channels:(t.otp?.channels??[]).filter(d=>d==="whatsapp"||d==="sms")};if(S!==void 0&&(m.switchChannel=S),l&&(m.sentToMasked=s.sentToMasked),!r&&t.otp?.channel!==void 0&&(m.channel=t.otp.channel),!r&&Array.isArray(t.phoneCountries)&&(m.phoneCountries=t.phoneCountries.filter(d=>typeof d=="string"&&/^[A-Z]{2}$/.test(d))),!r&&Array.isArray(t.phoneRules)){let d=m.phoneCountries??[];m.phoneRules=t.phoneRules.flatMap(b=>{let f=ht(b);return f!==void 0&&d.includes(f.code)?[f]:[]})}return!r&&t.phoneInternational===!0&&(m.phoneInternational=!0),s.expiresAt!==void 0&&(m.codeExpiresAt=s.expiresAt),s.resendAvailableAt!==void 0&&(m.resendAvailableAt=s.resendAvailableAt),m}var ft=/^[\d[\]\-|()?:^]{1,64}$/;function mt(e){try{return typeof e=="string"&&ft.test(e)&&new RegExp(e)!==null}catch{return!1}}var we=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function ht(e){let{code:t,dial:i,trunk:o,lengths:r,formats:s}=e??{};if(typeof t!="string"||typeof i!="string"||!/^\d{1,3}$/.test(i)||o!==void 0&&(typeof o!="string"||!/^\d{1,3}$/.test(o))||!Array.isArray(r)||r.length===0||!r.every(we))return;let u={code:t,dial:i,lengths:[...r].sort((a,l)=>a-l)};if(o!==void 0&&(u.trunk=o),s!==void 0){if(!(Array.isArray(s)&&s.length<=8&&s.every(l=>mt(l?.leading)&&Array.isArray(l.groups)&&l.groups.every(we)&&r.includes(l.groups.reduce((S,h)=>S+h,0)))))return;u.formats=s.map(l=>({leading:l.leading,groups:[...l.groups]}))}return u}function St(e,t,i,o){let r=K(e)===!0?"bound":H(t)===!0?"document":"typed",s=r==="typed"&&t.state==="input_required"&&t.reason!==void 0&&Pe(t.reason)==="id_number_recheck",u=Te(ie(e)),a=!o.attemptsExhausted&&u.length===1&&u[0]?.service==="document";return{kind:"registry",key:"registry",context:i,section:A(t),state:t.state==="input_required"?"input_required":"pending",source:r,recheck:s,canUseDocument:a,...o}}function yt(e,t,i,o){let r=[...t.acceptedSides??[]];return{kind:"document",key:"document",context:i,section:A(t),side:r.includes("recto")?"verso":"recto",acceptedSides:r,documents:Ie(e),...o}}function gt(e){let t=x(e,"liveness");return t?.state==="passed"||t?.state==="review"}function Oe(e,t,i,o,r){let s=t.icao?.report;return{kind:"portrait",key:`portrait:${r}`,context:i,section:A(t),phase:r,report:Array.isArray(s)?s:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:G(e),retakeOnly:r==="capture"&&t.state==="input_required"&&e.capture?.livePhoto?.oneCapture===!0&>(e),...o}}var ee={minLongSidePx:1280,jpegQuality:.95};function Ct(e,t){let i=e.capture?.livePhoto;if(i?.oneCapture!==!0)return null;let o=x(e,"portrait_icao"),r=i.still??ee;return{icao:t==="liveness"&&G(e)!==null&&o!==void 0&&o.state==="pending"&&o.reason===void 0,still:{minLongSidePx:r.minLongSidePx??ee.minLongSidePx,jpegQuality:r.jpegQuality??ee.jpegQuality}}}function _t(e,t,i,o){let r=t.eid,s=A(t);if(r===void 0||r.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:i,section:s,checkType:"eid_auth",reason:"update_required"};let u=Te(ie(e)),a=u.length===1&&rt.includes(u[0]?.service??"")?u[0]:void 0,l=a===void 0?void 0:V[a.service],S=l!==void 0,h={kind:"eid",key:"eid",context:i,section:s,provider:r.provider,providerName:r.providerName,country:r.country,challenge:"app_code",phase:r.awaiting==="code"?"code":"identifier",identifierBound:r.identifierBound===!0,canUseCamera:S,afterPass:r.afterPass==="continue"?"continue":"end",...o};return S&&(h.cameraMethod=l),r.expiresAt!==void 0&&(h.codeExpiresAt=r.expiresAt),r.resendAvailableAt!==void 0&&(h.resendAvailableAt=r.resendAvailableAt),r.resendsRemaining!==void 0&&(h.resendsRemaining=r.resendsRemaining),r.codeAttemptsRemaining!==void 0&&(h.codeAttemptsRemaining=r.codeAttemptsRemaining),h}function kt(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let i=x(e,"portrait_icao");return i!==void 0&&(i.state==="passed"||i.state==="review")?i:null}function Pt(e){return L(e).filter(t=>t.state==="failed").pop()?.attemptsExhausted===!0}function bt(e,t){let i=e.failureReason,o;i===Me?o="platform_unsupported":e.status==="expired"?o="expired":e.status==="review_pending"?o="review":e.status==="completed"&&e.outcome==="approved"?o="approved":e.status==="completed"&&e.outcome==="review"?o="review":i==="device_cooldown"?o="cooldown":i!==void 0?o="policy_stop":Pt(e)?o="attempts_exhausted":o="rejected";let r=o==="platform_unsupported"?{sessionId:z(e.sessionId),status:"unavailable"}:D(e,{autoRetry:!1}),s={kind:"result",key:"result",context:t,section:null,display:o,result:r};return i!==void 0&&(s.failureReason=i),e.retryAfter!==void 0&&(s.retryAfter=e.retryAfter),s}function xt(e,t,i){let o=e.identitySummary;if(o==null)return null;let r={kind:"identity_summary",key:"identity_summary",context:t,section:i??"identity",summaryKind:o.kind==="partial"?"partial":o.kind??"full",source:o.source,portraitAvailable:o.portrait?.available===!0,retakeAvailable:o.retakeAvailable===!0};for(let u of Rt){let a=o[u];typeof a=="string"&&a!==""&&(r[u]=a)}let s=ve(o);return s!==void 0&&(r.idNumberMasked=s,r.nniMasked=s),r}var Rt=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","expiryDate","retakeTarget"];function M(e,t,i,o){return{kind:"unsupported",key:`unsupported:${i}`,context:e,section:t,checkType:i,reason:o}}function vt(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function At(e,t){let i=Ee[e.kind]??[...te,...ne],o=vt(e),r=e.options.flatMap(u=>{if(u.available===!1||!i.includes(u.service))return[];let a={id:u.id,service:u.service};return u.nationalEid!=null&&(a.nationalEid=u.nationalEid),[a]});if(r.length===0){let u=e.options.length>0&&e.options.every(a=>a.service==="nfc");return M(t,o,"choice",u?"platform_unsupported":"update_required")}let s={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:r};if(e.kind==="identity_method"){let u={kind:"method",key:"method",context:t,section:o,options:r.map(l=>V[l.service]),choice:s},a=r.find(l=>l.nationalEid!==void 0)?.nationalEid;return a!==void 0&&(u.nationalEid=a),u}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:o,options:r.map(u=>Ve[u.service]),selected:null,locked:!1,choice:s}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:o,choice:s}}function jt(e,t={}){let i=ut(e);if(P(e)||e.failureReason===Me)return bt(e,i);let o=e.plan;if(o===void 0||!Array.isArray(o.sections))return M(i,null,"plan","update_required");let r=be(e);if(r!==null)return At(r,i);let s=o.current===null?void 0:o.steps.find(m=>m.id===o.current),u=m=>{let d={kind:"processing",key:"processing",context:i,section:m!==void 0?A(m):o.sections.find(b=>b.state==="current")?.id??null,stalled:!1};return typeof m?.service=="string"&&m.service!==""&&(d.service=m.service),d};if(o.current===null)return u(o.steps.find(m=>m.state==="processing"));if(s===void 0)return M(i,null,"step","update_required");if(!it.has(s.service))return s.interaction==="server"?u(s):M(i,A(s),s.service,"update_required");if(ot.has(s.service)||!B(s))return u(s);let a=s,l=dt(a),S=a.checkType,h=A(a);switch(S){case"phone_otp":case"email_otp":return pt(e,a,i,l);case"population_registry":return St(e,a,i,l);case"eid_auth":return _t(e,a,i,l);case"doc_ocr":return yt(e,a,i,l);case"identity_confirm":return xt(e,i,h)??u(a);case"portrait_icao":return Oe(e,a,i,l,"capture");case"liveness":case"face_match":{let m=kt(e,a);if(m!==null)return Oe(e,m,i,l,"match");let d=a.requiresMobile===!0,b=G(e);return d&&t.isMobile===!1?{kind:"mobile_required",key:"mobile_required",context:i,section:h,checkType:S}:{kind:"liveness",key:"biometric",context:i,section:h,mode:S==="face_match"?"selfie":"liveness",requiresMobile:d,instructions:b===null?"standard":"icao",icao:b,livePhoto:Ct(e,S),...l}}case"nfc_chip":return M(i,h,S,"platform_unsupported");default:return M(i,h,S,"update_required")}}export{$e as a,Je as b,Qe as c,je as d,ze as e,Lt as f,et as g,Ae as h,tt as i,nt as j,Gt as k,Ie as l,Kt as m,Qt as n,Me as o,A as p,ie as q,Te as r,kt as s,jt as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as Q,d as Z,e as j}from"./chunk-GT2ZLGF7.js";import{w as $}from"./chunk-
|
|
1
|
+
import{a as Q,d as Z,e as j}from"./chunk-GT2ZLGF7.js";import{w as $}from"./chunk-OG4QAJ3M.js";import{c as q}from"./chunk-FUHDOEBP.js";import{f as G}from"./chunk-2BFYVMUU.js";import{a as N,f as v}from"./chunk-OKWG3PVH.js";var ne=12e4,J=13e4,re=3e3,se=1200,P=Symbol.for("@sekyro/web.preload.v1");function f(){let e=globalThis;return e[P]??(e[P]=new Map),e[P]}function g(e){let n=(e??N).replace(/\/+$/,"");return n===""?"/":n}function X(e){let n=f(),r=n.get(e);return r===void 0&&(r={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},n.set(e,r)),r}function A(e,n){if(e.status!==n){e.status=n;for(let r of[...e.listeners])r(n)}}var x=e=>v({preferred:["blaze"],v3AssetBaseUrl:e,blazeInitTimeoutMs:ne}),I=x;function ge(e){I=e??x}function he(){for(let e of f().values())e.detector?.destroy();f().clear(),I=x}function oe(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function ie(){return navigator.connection?.saveData===!0}function ae(e){let n=window;if(typeof n.requestIdleCallback=="function"){let s=n.requestIdleCallback(e,{timeout:re});return()=>n.cancelIdleCallback?.(s)}let r=setTimeout(e,se);return()=>clearTimeout(r)}function ce(e,n){let r,s=new Promise(o=>{r=o}),u=!1,l=()=>{},d={promise:s,settle:o=>{u||(u=!0,l(),e.scheduled===d&&(e.scheduled=null),r(o))}};return e.scheduled=d,l=ae(()=>{u||d.settle(R(e,n))}),s}function R(e,n){if((e.status==="loading"||e.status==="ready")&&e.promise!==null)return e.promise;A(e,"loading");let r=new Promise(o=>o(I(n)));e.detectorPromise=r;let s,u=new Promise((o,h)=>{s=setTimeout(()=>{r.then(S=>S.destroy(),()=>{}),h(new Error(`detector preload exceeded ${J} ms`))},J)}),d=Promise.race([r,u]).then(o=>e.detectorPromise!==r?(o.destroy(),e.status):(e.detector=o,A(e,"ready"),"ready"),o=>(e.detectorPromise===r&&(e.detectorPromise=null,e.detector=null,A(e,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",o)),e.status)).finally(()=>clearTimeout(s));return e.promise=d,e.scheduled?.settle(d),d}function Se(e={}){if(!oe())return Promise.resolve("idle");let n=g(e.assetBaseUrl),r=X(n);return e.respectSaveData===!0&&ie()?Promise.resolve(r.status):(r.status==="loading"||r.status==="ready")&&r.promise!==null?r.promise:e.idle===!0?r.scheduled?.promise??ce(r,n):R(r,n)}function Ce(e){return f().get(g(e))?.status??"idle"}function Le(e,n){let r=X(g(n));return r.listeners.add(e),()=>{r.listeners.delete(e)}}function ye(e){let n=f().get(g(e));n!==void 0&&(n.scheduled?.settle("idle"),n.detector?.destroy(),n.detector=null,n.detectorPromise=null,n.promise=null,A(n,"idle"))}function de(e){return{get tier(){return e.tier},get fallbackReason(){return e.fallbackReason},detect:(...n)=>e.detect(...n),destroy:()=>{}}}function Y(e){let n=g(e),r=f().get(n);if(!(r===void 0||r.detector===null&&r.detectorPromise===null&&r.scheduled===null))return async()=>{r.scheduled!==null&&R(r,n);let s=r.promise;for(;r.detector===null&&s!==null&&(await s,r.promise!==s);)s=r.promise;return r.detector!==null?de(r.detector):v({v3AssetBaseUrl:n})}}function ue(e){switch(e){case"fcv3.no_face":case"fcv3.center_face":case"fcv3.straighten":return"center";case"fcv3.come_closer":return"closer";case"fcv3.move_back":return"farther";case"fcv3.more_light":case"fcv3.too_bright":return"light";case"fcv3.hold_still":case"fcv3.steady_camera":return"still";case"fcv3.hold_upright":return"upright";default:return null}}function le(e){switch(e){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";default:return e}}function fe(e){switch(e){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return e;default:{let n=e;return"generic"}}}function pe(e,n={},r,s=()=>"self",u=()=>{}){let l=n.now??(()=>performance.now()),d=n.canChooseFacing??Z,o="user",h=!1,S=t=>(t==="environment"&&!h&&(h=!0,console.warn('[@sekyro/web] facing "environment" ignored: this capture is a self capture (the person films themselves), which uses the front camera only. The back camera is for assisted capture, set in the flow.')),"user"),k=!1,p=s(),c=Q(),H=!G(),U=n.engineOptions,ee=U?.createDetector===void 0&&U?.createWorker===void 0?{createDetector:()=>{let t=Y(e.assetBaseUrl);return t!==void 0?t():v({v3AssetBaseUrl:e.assetBaseUrl})}}:{},B={video:e.video,mode:H?"photo":"clip",rankKeyframes:r,facingMode:void 0,v3AssetBaseUrl:e.assetBaseUrl,screenRamp:()=>p==="self"&&c.count("ramp")>0?u():void 0,...n.engineOptions??{},...ee},i=n.createEngine?.(B)??new $(B),C="idle",L=null,y=0,D=!1,M="full",E=null,b=null,_=0,F=0,K=()=>{e.video.videoWidth>0&&e.video.videoHeight>0&&(_=e.video.videoWidth,F=e.video.videoHeight)},V=j({enabled:e.keepScreenAwake!==!1}),W=t=>{C=t,V.setActive(t==="starting"||t==="gating"||t==="recording"),c.emit("state",t)},O=()=>c.emit("gate",{progress:y,hint:L,faceDetected:D}),z=()=>{let t=i.animations??"full";t!==M&&(M=t,c.emit("profile",{animations:M}))},te=[i.on("statechange",({state:t})=>{let a=le(t);a==="starting"&&C!=="starting"&&(L=null,y=0,D=!1,E=null,b=null,_=0,F=0),W(a),z(),a==="recording"&&(K(),E=l(),L="hold",y=1,O())}),i.on("checks",t=>{K(),y=t.progress,D=t.factors.presence>0,O(),z()}),i.on("guidance",({key:t})=>{L=ue(t),O()}),i.on("frozen",({previewDataUrl:t})=>{b=l(),c.emit("frozen",{previewDataUrl:t})}),i.on("ramp",t=>c.emit("ramp",t)),i.on("artifacts",t=>{let a=q(),m=E!==null&&b!==null?Math.max(0,Math.round(b-E)):void 0;c.emit("captured",{keyframe:t.keyframe,...t.clip!==void 0?{clip:t.clip}:{},...t.clipMimeType!==void 0?{clipMime:t.clipMimeType}:{},width:e.video.videoWidth||_,height:e.video.videoHeight||F,...m!==void 0?{clipMs:m}:{},captureChannel:a==="desktop"?"desktop":"mobile",formFactor:a,...H?{degraded:"NO_RECORDER"}:{},engine:"v3",facingMode:i.facingMode,mode:p,...t.timing,...t.screenRamp!==void 0?{screenRamp:t.screenRamp}:{},...t.provenance!==void 0?{provenance:t.provenance}:{}})}),i.on("error",({kind:t,retryable:a})=>{c.emit("error",{kind:fe(t),retryable:a})})];return{handle:{get state(){return C},get captureMode(){return s()},get facingMode(){return i.facingMode??o},on:(t,a)=>c.on(t,a),start:t=>{if(p=s(),p==="self")return S(e.facing),S(t?.facing),k=!0,o="user",i.start({facingMode:"user"});let a=!k;k=!0;let m=t?.facing??(a?e.facing:void 0),T=w=>(o=w,i.start({facingMode:w}));return m!==void 0?T(m):a?d().then(w=>T(w?"environment":"user"),()=>T("user")):i.start({})},retry:()=>i.retry(),switchCamera:()=>s()!=="assisted"?!1:(p="assisted",o=o==="user"?"environment":"user",i.switchCamera(),!0),destroy:()=>{for(let t of te)t();V.setActive(!1),i.destroy(),c.clear()}},setFlowState:t=>{C!==t&&W(t)}}}function Fe(e){return pe(e).handle}export{ne as a,J as b,ge as c,he as d,Se as e,Ce as f,Le as g,ye as h,Y as i,ue as j,le as k,fe as l,pe as m,Fe as n};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as m,b as p}from"./chunk-
|
|
1
|
+
import{a as m,b as p}from"./chunk-DNB3R4PI.js";var g=["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"];function A(s){return g.includes(s)}var d=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)}};var b=6e4,f=4,T=3e4,w=9e5,k=200,S=5,P=400;function l(s){return(s.split(";")[0]??"").trim()}var C={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},I=`@sekyro/web/${m}`,E=I,h=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let n=e.fetch;this.fetchImpl=(t,i)=>(n??globalThis.fetch).call(globalThis,t,i),this.requestTimeoutMs=e.requestTimeoutMs??T,this.retryAttempts=e.inProgressRetry?.attempts??S,this.retryDelayMs=e.inProgressRetry?.delayMs??P}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e}})}async reportCameraUnavailable(e){return this.api("POST","/hosted/camera-unavailable",{body:{cause:e}})}async choose(e,n){let t=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:n}});return this.sessionId=t.sessionId,t}async confirmIdentity(e){return this.api("POST","/hosted/identity/confirm",{body:{decision:e}})}async identityPortrait(){return this.api("GET","/hosted/identity/portrait",{blob:!0})}async presign(e,n,t){let i=await this.ensureSessionId(),o={kind:e,contentType:l(n),contentLength:t};return this.api("POST",`/sessions/${i}/media`,{body:o})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,n,t,i={}){let o=await this.ensureSessionId(),r=await this.takeCaptureNonce(),c=r===void 0?void 0:{nonce:r,...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:l(n),contentLength:t,capture:c};return this.api("POST",`/sessions/${o}/media`,{body:a})}async takeCaptureNonce(){let e=()=>{let n=Date.now();return this.captureNonces=this.captureNonces.filter(t=>t.expiresAt-b>n),this.captureNonces.shift()?.nonce};for(let n=0;n<2;n++){let t=e();if(t!==void 0)return t;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let n=await this.ensureSessionId(),t=await this.api("POST",`/sessions/${n}/media/capture-nonces`,{body:{count:Math.min(f,Math.max(1,e))}}),i=Date.now()+Math.max(0,t.expiresIn)*1e3;for(let o of Array.isArray(t.nonces)?t.nonces:[])typeof o=="string"&&o.length>0&&this.captureNonces.push({nonce:o,expiresAt:i});this.captureNonces=this.captureNonces.slice(-f)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,n,t){let i;try{i=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":l(t)},body:n,signal:AbortSignal.timeout(w)})}catch(o){throw y(o)}if(!i.ok){let o=(await i.text().catch(()=>"")).slice(0,k);throw new d({status:i.status,code:"upload_failed",message:`media upload failed (HTTP ${i.status})${o?`: ${o}`:""}`})}}async completeMedia(e){let n=await this.ensureSessionId();return this.api("POST",`/sessions/${n}/media/complete`,{body:{key:e}})}async submitCheck(e,n,t={}){let i=await this.ensureSessionId(),o={input:n,forceOutcome:t.forceOutcome};return this.api("POST",`/sessions/${i}/checks/${e}`,{body:o,idempotencyKey:t.idempotencyKey})}async uploadAndSubmit(e,n,t,i={}){let o=l(n.contentType),r=await this.presign(n.kind,o,n.blob.size);await this.uploadToSpaces(r.uploadUrl,n.blob,o);let c=await this.completeMedia(r.key),a={...t,[C[e]]:c.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,n,t={}){let i=`${this.apiOrigin}/api/v2${n}`,o={"x-session-token":this.sessionToken,"x-sekyro-sdk":E};t.body!==void 0&&(o["content-type"]="application/json"),t.idempotencyKey!==void 0&&(o["x-idempotency-key"]=t.idempotencyKey);try{let r=p.timezone();r!==void 0&&(o["sekyro-client-timezone"]=r)}catch{}try{let r=await p.deviceHeader();r!==void 0&&(o["sekyro-client-device"]=r)}catch{}for(let r=0;;r++){let c;try{c=await this.fetchImpl(i,{method:e,headers:o,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(u){throw y(u)}if(c.ok){if(t.blob===!0)try{return await c.blob()}catch(_){throw y(_)}let u;try{u=await c.json()}catch{throw new d({status:c.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${c.status})`})}return M(u)}let a=await v(c);if(a.code==="idempotency_in_progress"&&r<this.retryAttempts){this.retryDelayMs>0&&await O(this.retryDelayMs);continue}throw a}}};function y(s){if((typeof s=="object"&&s!==null?s.name:void 0)==="TimeoutError")return new d({status:0,code:"timeout",message:"request timed out"});let n=s instanceof Error?s.message:String(s);return new d({status:0,code:"network_error",message:`network request failed: ${n}`})}function M(s){return s!==null&&typeof s=="object"&&"success"in s&&"data"in s?s.data:s}async function v(s){let e="unknown_error",n=`request failed (HTTP ${s.status})`,t=Number.NaN,i;try{let c=await s.json();if(c!==null&&typeof c=="object"){let a=c;typeof a.code=="string"&&a.code.length>0&&(e=a.code),typeof a.message=="string"&&a.message.length>0&&(n=a.message),typeof a.retryAfterSeconds=="number"&&(t=a.retryAfterSeconds),Array.isArray(a.details?.issues)&&(i=a.details)}}catch{}let o=s.headers.get("retry-after"),r=o===null?Math.floor(t):Number.parseInt(o,10);return new d({status:s.status,code:e,message:n,...Number.isFinite(r)&&r>=0?{retryAfterSeconds:r}:{},details:i})}function O(s){return new Promise(e=>setTimeout(e,s))}function U(s){let e=s?.portrait,n=e?.icao,t=e?.purpose==="id_document";return n==null?t?{policy:"reject",profile:"id_document"}:null:{policy:n.policy==="alert"&&!t?"alert":"reject",profile:t||n.profile==="id_document"?"id_document":"selfie"}}function K(s){return{...s.baselineEyeOpenness!==void 0?{baselineEyeOpenness:s.baselineEyeOpenness}:{},criteria:s.verdict??{},...s.backgroundCheck!==void 0?{backgroundCheck:s.backgroundCheck}:{}}}export{g as a,A as b,d as c,l as d,I as e,h as f,U as g,K as h};
|
package/dist/client/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var m=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var H=Object.prototype.hasOwnProperty;var M=(t,e)=>{for(var o in e)m(t,o,{get:e[o],enumerable:!0})},A=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of O(e))!H.call(t,i)&&i!==o&&m(t,i,{get:()=>e[i],enumerable:!(n=v(e,i))||n.enumerable});return t};var N=t=>A(m({},"__esModule",{value:!0}),t);var J={};M(J,{HostedApiError:()=>d,HostedClient:()=>y,KNOWN_CODES:()=>g,SEKYRO_SDK_HEADER:()=>S,icaoPolicyOf:()=>I,isKnownCode:()=>P,portraitIcaoGate:()=>E,stripMimeParams:()=>u});module.exports=N(J);var p="0.1.0-rc.16";var w="sekyro.did",C;function T(){let t=globalThis.crypto;try{if(typeof t?.randomUUID=="function")return t.randomUUID()}catch{}try{if(typeof t?.getRandomValues=="function"){let e=t.getRandomValues(new Uint8Array(16));return Array.from(e,o=>o.toString(16).padStart(2,"0")).join("")}}catch{}}function D(){try{let t=localStorage.getItem(w);if(t)return t;let e=T();return e!==void 0&&localStorage.setItem(w,e),e}catch{return C??(C=T()),C}}async function x(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,o=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]),n=await t.digest("SHA-256",new TextEncoder().encode(o));return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("").slice(0,32)}function V(t){let e=new TextEncoder().encode(t),o="";for(let n of e)o+=String.fromCharCode(n);return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function K(t){let e,o;return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(n){n&&(e=n.slice(0,128))},async deviceHeader(){try{o??(o=x().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let i=await o,s=D(),r={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...s?[{kind:"web_local",value:s.slice(0,128)}]:[],...i?[{kind:"web_fp",value:i}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...e?{cameraLabel:e}:{},...n.length?{signals:n}:{}};return V(JSON.stringify(r))}catch{return}}}}var f=Symbol.for("sekyro.web.clientContext"),h=globalThis,_=h[f]??(h[f]=K({sdk:`@sekyro/web@${p}`}));var g=["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"];function P(t){return g.includes(t)}var d=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)}};var U=6e4,k=4,L=3e4,$=9e5,q=200,F=5,B=400;function u(t){return(t.split(";")[0]??"").trim()}var j={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},S=`@sekyro/web/${p}`,G=S,y=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let o=e.fetch;this.fetchImpl=(n,i)=>(o??globalThis.fetch).call(globalThis,n,i),this.requestTimeoutMs=e.requestTimeoutMs??L,this.retryAttempts=e.inProgressRetry?.attempts??F,this.retryDelayMs=e.inProgressRetry?.delayMs??B}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e}})}async reportCameraUnavailable(e){return this.api("POST","/hosted/camera-unavailable",{body:{cause:e}})}async choose(e,o){let n=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:o}});return this.sessionId=n.sessionId,n}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,o,n){let i=await this.ensureSessionId(),s={kind:e,contentType:u(o),contentLength:n};return this.api("POST",`/sessions/${i}/media`,{body:s})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,o,n,i={}){let s=await this.ensureSessionId(),r=await this.takeCaptureNonce(),c=r===void 0?void 0:{nonce:r,...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:u(o),contentLength:n,capture:c};return this.api("POST",`/sessions/${s}/media`,{body:a})}async takeCaptureNonce(){let e=()=>{let o=Date.now();return this.captureNonces=this.captureNonces.filter(n=>n.expiresAt-U>o),this.captureNonces.shift()?.nonce};for(let o=0;o<2;o++){let n=e();if(n!==void 0)return n;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let o=await this.ensureSessionId(),n=await this.api("POST",`/sessions/${o}/media/capture-nonces`,{body:{count:Math.min(k,Math.max(1,e))}}),i=Date.now()+Math.max(0,n.expiresIn)*1e3;for(let s of Array.isArray(n.nonces)?n.nonces:[])typeof s=="string"&&s.length>0&&this.captureNonces.push({nonce:s,expiresAt:i});this.captureNonces=this.captureNonces.slice(-k)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,o,n){let i;try{i=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":u(n)},body:o,signal:AbortSignal.timeout($)})}catch(s){throw b(s)}if(!i.ok){let s=(await i.text().catch(()=>"")).slice(0,q);throw new d({status:i.status,code:"upload_failed",message:`media upload failed (HTTP ${i.status})${s?`: ${s}`:""}`})}}async completeMedia(e){let o=await this.ensureSessionId();return this.api("POST",`/sessions/${o}/media/complete`,{body:{key:e}})}async submitCheck(e,o,n={}){let i=await this.ensureSessionId(),s={input:o,forceOutcome:n.forceOutcome};return this.api("POST",`/sessions/${i}/checks/${e}`,{body:s,idempotencyKey:n.idempotencyKey})}async uploadAndSubmit(e,o,n,i={}){let s=u(o.contentType),r=await this.presign(o.kind,s,o.blob.size);await this.uploadToSpaces(r.uploadUrl,o.blob,s);let c=await this.completeMedia(r.key),a={...n,[j[e]]:c.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,o,n={}){let i=`${this.apiOrigin}/api/v2${o}`,s={"x-session-token":this.sessionToken,"x-sekyro-sdk":G};n.body!==void 0&&(s["content-type"]="application/json"),n.idempotencyKey!==void 0&&(s["x-idempotency-key"]=n.idempotencyKey);try{let r=_.timezone();r!==void 0&&(s["sekyro-client-timezone"]=r)}catch{}try{let r=await _.deviceHeader();r!==void 0&&(s["sekyro-client-device"]=r)}catch{}for(let r=0;;r++){let c;try{c=await this.fetchImpl(i,{method:e,headers:s,...n.body!==void 0?{body:JSON.stringify(n.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(l){throw b(l)}if(c.ok){if(n.blob===!0)try{return await c.blob()}catch(R){throw b(R)}let l;try{l=await c.json()}catch{throw new d({status:c.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${c.status})`})}return Y(l)}let a=await z(c);if(a.code==="idempotency_in_progress"&&r<this.retryAttempts){this.retryDelayMs>0&&await W(this.retryDelayMs);continue}throw a}}};function b(t){if((typeof t=="object"&&t!==null?t.name:void 0)==="TimeoutError")return new d({status:0,code:"timeout",message:"request timed out"});let o=t instanceof Error?t.message:String(t);return new d({status:0,code:"network_error",message:`network request failed: ${o}`})}function Y(t){return t!==null&&typeof t=="object"&&"success"in t&&"data"in t?t.data:t}async function z(t){let e="unknown_error",o=`request failed (HTTP ${t.status})`,n=Number.NaN,i;try{let c=await t.json();if(c!==null&&typeof c=="object"){let a=c;typeof a.code=="string"&&a.code.length>0&&(e=a.code),typeof a.message=="string"&&a.message.length>0&&(o=a.message),typeof a.retryAfterSeconds=="number"&&(n=a.retryAfterSeconds),Array.isArray(a.details?.issues)&&(i=a.details)}}catch{}let s=t.headers.get("retry-after"),r=s===null?Math.floor(n):Number.parseInt(s,10);return new d({status:t.status,code:e,message:o,...Number.isFinite(r)&&r>=0?{retryAfterSeconds:r}:{},details:i})}function W(t){return new Promise(e=>setTimeout(e,t))}function I(t){let e=t?.portrait,o=e?.icao,n=e?.purpose==="id_document";return o==null?n?{policy:"reject",profile:"id_document"}:null:{policy:o.policy==="alert"&&!n?"alert":"reject",profile:n||o.profile==="id_document"?"id_document":"selfie"}}function E(t){return{...t.baselineEyeOpenness!==void 0?{baselineEyeOpenness:t.baselineEyeOpenness}:{},criteria:t.verdict??{},...t.backgroundCheck!==void 0?{backgroundCheck:t.backgroundCheck}:{}}}0&&(module.exports={HostedApiError,HostedClient,KNOWN_CODES,SEKYRO_SDK_HEADER,icaoPolicyOf,isKnownCode,portraitIcaoGate,stripMimeParams});
|
|
1
|
+
"use strict";var m=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var H=Object.prototype.hasOwnProperty;var M=(t,e)=>{for(var o in e)m(t,o,{get:e[o],enumerable:!0})},A=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of O(e))!H.call(t,i)&&i!==o&&m(t,i,{get:()=>e[i],enumerable:!(n=v(e,i))||n.enumerable});return t};var N=t=>A(m({},"__esModule",{value:!0}),t);var J={};M(J,{HostedApiError:()=>d,HostedClient:()=>y,KNOWN_CODES:()=>g,SEKYRO_SDK_HEADER:()=>S,icaoPolicyOf:()=>I,isKnownCode:()=>P,portraitIcaoGate:()=>E,stripMimeParams:()=>u});module.exports=N(J);var p="0.1.0-rc.18";var w="sekyro.did",C;function T(){let t=globalThis.crypto;try{if(typeof t?.randomUUID=="function")return t.randomUUID()}catch{}try{if(typeof t?.getRandomValues=="function"){let e=t.getRandomValues(new Uint8Array(16));return Array.from(e,o=>o.toString(16).padStart(2,"0")).join("")}}catch{}}function D(){try{let t=localStorage.getItem(w);if(t)return t;let e=T();return e!==void 0&&localStorage.setItem(w,e),e}catch{return C??(C=T()),C}}async function x(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,o=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]),n=await t.digest("SHA-256",new TextEncoder().encode(o));return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("").slice(0,32)}function V(t){let e=new TextEncoder().encode(t),o="";for(let n of e)o+=String.fromCharCode(n);return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function K(t){let e,o;return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(n){n&&(e=n.slice(0,128))},async deviceHeader(){try{o??(o=x().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let i=await o,s=D(),r={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...s?[{kind:"web_local",value:s.slice(0,128)}]:[],...i?[{kind:"web_fp",value:i}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...e?{cameraLabel:e}:{},...n.length?{signals:n}:{}};return V(JSON.stringify(r))}catch{return}}}}var f=Symbol.for("sekyro.web.clientContext"),h=globalThis,_=h[f]??(h[f]=K({sdk:`@sekyro/web@${p}`}));var g=["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"];function P(t){return g.includes(t)}var d=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)}};var U=6e4,k=4,L=3e4,F=9e5,$=200,q=5,B=400;function u(t){return(t.split(";")[0]??"").trim()}var j={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},S=`@sekyro/web/${p}`,G=S,y=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let o=e.fetch;this.fetchImpl=(n,i)=>(o??globalThis.fetch).call(globalThis,n,i),this.requestTimeoutMs=e.requestTimeoutMs??L,this.retryAttempts=e.inProgressRetry?.attempts??q,this.retryDelayMs=e.inProgressRetry?.delayMs??B}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e}})}async reportCameraUnavailable(e){return this.api("POST","/hosted/camera-unavailable",{body:{cause:e}})}async choose(e,o){let n=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:o}});return this.sessionId=n.sessionId,n}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,o,n){let i=await this.ensureSessionId(),s={kind:e,contentType:u(o),contentLength:n};return this.api("POST",`/sessions/${i}/media`,{body:s})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,o,n,i={}){let s=await this.ensureSessionId(),r=await this.takeCaptureNonce(),c=r===void 0?void 0:{nonce:r,...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:u(o),contentLength:n,capture:c};return this.api("POST",`/sessions/${s}/media`,{body:a})}async takeCaptureNonce(){let e=()=>{let o=Date.now();return this.captureNonces=this.captureNonces.filter(n=>n.expiresAt-U>o),this.captureNonces.shift()?.nonce};for(let o=0;o<2;o++){let n=e();if(n!==void 0)return n;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let o=await this.ensureSessionId(),n=await this.api("POST",`/sessions/${o}/media/capture-nonces`,{body:{count:Math.min(k,Math.max(1,e))}}),i=Date.now()+Math.max(0,n.expiresIn)*1e3;for(let s of Array.isArray(n.nonces)?n.nonces:[])typeof s=="string"&&s.length>0&&this.captureNonces.push({nonce:s,expiresAt:i});this.captureNonces=this.captureNonces.slice(-k)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,o,n){let i;try{i=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":u(n)},body:o,signal:AbortSignal.timeout(F)})}catch(s){throw b(s)}if(!i.ok){let s=(await i.text().catch(()=>"")).slice(0,$);throw new d({status:i.status,code:"upload_failed",message:`media upload failed (HTTP ${i.status})${s?`: ${s}`:""}`})}}async completeMedia(e){let o=await this.ensureSessionId();return this.api("POST",`/sessions/${o}/media/complete`,{body:{key:e}})}async submitCheck(e,o,n={}){let i=await this.ensureSessionId(),s={input:o,forceOutcome:n.forceOutcome};return this.api("POST",`/sessions/${i}/checks/${e}`,{body:s,idempotencyKey:n.idempotencyKey})}async uploadAndSubmit(e,o,n,i={}){let s=u(o.contentType),r=await this.presign(o.kind,s,o.blob.size);await this.uploadToSpaces(r.uploadUrl,o.blob,s);let c=await this.completeMedia(r.key),a={...n,[j[e]]:c.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,o,n={}){let i=`${this.apiOrigin}/api/v2${o}`,s={"x-session-token":this.sessionToken,"x-sekyro-sdk":G};n.body!==void 0&&(s["content-type"]="application/json"),n.idempotencyKey!==void 0&&(s["x-idempotency-key"]=n.idempotencyKey);try{let r=_.timezone();r!==void 0&&(s["sekyro-client-timezone"]=r)}catch{}try{let r=await _.deviceHeader();r!==void 0&&(s["sekyro-client-device"]=r)}catch{}for(let r=0;;r++){let c;try{c=await this.fetchImpl(i,{method:e,headers:s,...n.body!==void 0?{body:JSON.stringify(n.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(l){throw b(l)}if(c.ok){if(n.blob===!0)try{return await c.blob()}catch(R){throw b(R)}let l;try{l=await c.json()}catch{throw new d({status:c.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${c.status})`})}return Y(l)}let a=await z(c);if(a.code==="idempotency_in_progress"&&r<this.retryAttempts){this.retryDelayMs>0&&await W(this.retryDelayMs);continue}throw a}}};function b(t){if((typeof t=="object"&&t!==null?t.name:void 0)==="TimeoutError")return new d({status:0,code:"timeout",message:"request timed out"});let o=t instanceof Error?t.message:String(t);return new d({status:0,code:"network_error",message:`network request failed: ${o}`})}function Y(t){return t!==null&&typeof t=="object"&&"success"in t&&"data"in t?t.data:t}async function z(t){let e="unknown_error",o=`request failed (HTTP ${t.status})`,n=Number.NaN,i;try{let c=await t.json();if(c!==null&&typeof c=="object"){let a=c;typeof a.code=="string"&&a.code.length>0&&(e=a.code),typeof a.message=="string"&&a.message.length>0&&(o=a.message),typeof a.retryAfterSeconds=="number"&&(n=a.retryAfterSeconds),Array.isArray(a.details?.issues)&&(i=a.details)}}catch{}let s=t.headers.get("retry-after"),r=s===null?Math.floor(n):Number.parseInt(s,10);return new d({status:t.status,code:e,message:o,...Number.isFinite(r)&&r>=0?{retryAfterSeconds:r}:{},details:i})}function W(t){return new Promise(e=>setTimeout(e,t))}function I(t){let e=t?.portrait,o=e?.icao,n=e?.purpose==="id_document";return o==null?n?{policy:"reject",profile:"id_document"}:null:{policy:o.policy==="alert"&&!n?"alert":"reject",profile:n||o.profile==="id_document"?"id_document":"selfie"}}function E(t){return{...t.baselineEyeOpenness!==void 0?{baselineEyeOpenness:t.baselineEyeOpenness}:{},criteria:t.verdict??{},...t.backgroundCheck!==void 0?{backgroundCheck:t.backgroundCheck}:{}}}0&&(module.exports={HostedApiError,HostedClient,KNOWN_CODES,SEKYRO_SDK_HEADER,icaoPolicyOf,isKnownCode,portraitIcaoGate,stripMimeParams});
|
package/dist/client/index.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { c as IcaoGateSummary } from '../icao-gate-
|
|
2
|
-
export { N as HostedClient, O as HostedClientOptions, Q as MediaCheckType, S as SEKYRO_SDK_HEADER, T as SubmitOptions, U as UploadMedia, V as stripMimeParams } from '../icao-gate-
|
|
3
|
-
import { H as HostedSessionView, G as HostedIcaoPolicy,
|
|
4
|
-
export { A as AcceptedDocumentType,
|
|
1
|
+
import { c as IcaoGateSummary } from '../icao-gate-C-lfjEpH.cjs';
|
|
2
|
+
export { N as HostedClient, O as HostedClientOptions, Q as MediaCheckType, S as SEKYRO_SDK_HEADER, T as SubmitOptions, U as UploadMedia, V as stripMimeParams } from '../icao-gate-C-lfjEpH.cjs';
|
|
3
|
+
import { H as HostedSessionView, G as HostedIcaoPolicy, aj as PortraitIcaoInput } from '../types-CKgMWVnP.cjs';
|
|
4
|
+
export { A as AcceptedDocumentType, az as AttestationInput, c as CaptureContext, i as CaptureMode, aA as CaptureNoncesResult, aB as CaptureProof, f as CheckInputByType, k as CheckReason, l as CheckState, e as CheckType, d as CompleteMediaResult, C as ConsentLocale, m as ContactChannel, D as DecisionReason, aC as DocDeviceRead, aD as DocOcrInput, n as DocReason, aE as DocSide, E as EidAfterPass, o as EidAuthInput, p as EidReason, aF as EmailOtpInput, q as EmailOtpReason, aG as FaceMatchInput, F as FaceMatchReason, r as HostedAcceptedDocuments, u as HostedCaptureTuning, a as HostedConsentView, v as HostedDocumentCaptureTuning, w as HostedDocumentScanTuning, x as HostedEidView, y as HostedEmailOtpView, z as HostedFlowRef, J as HostedIntegrity, K as HostedLivePhotoTuning, N as HostedNativeCaptureTuning, O as HostedOcrTuning, Q as HostedOtpView, T as HostedPlanView, U as HostedPortraitView, V as HostedStepView, W as HostedVoiceLocale, X as HostedVoiceView, g as IcaoCriterion, Z as IcaoReportEntry, I as IdentityConfirmDecision, _ as IdentityMethod, $ as IdentitySummarySource, a0 as IdentitySummaryView, aH as LivenessCaptureInput, aI as LivenessInput, a1 as LivenessReason, a2 as MatchReason, M as MediaKind, a3 as MethodChoiceView, a4 as NationalEidOption, a5 as NfcChipReason, a6 as NfcStepView, a7 as OtpChoiceView, a8 as PhoneCountryRule, a9 as PhoneFormat, aJ as PhoneOtpInput, aa as PhoneOtpReason, ab as PlanAttempts, ac as PlanChoiceKind, ad as PlanChoiceOption, ae as PlanChoiceView, af as PlanSectionView, ag as PlanStepView, ah as PolicyFailureReason, aK as PopulationInput, ai as PopulationReason, ak as PortraitIcaoReason, aL as PresignRequest, P as PresignUploadResult, aM as RecordConsentResult, ap as SessionFailureReason, aq as SessionOutcome, ar as SessionStatus, aN as SessionStepView, aO as SessionView, as as StepSection, aP as SubmitCheckBody, at as VerificationAssurance, au as VerificationLevel } from '../types-CKgMWVnP.cjs';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Every error code the hosted page can receive from the session-token surface.
|
package/dist/client/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { c as IcaoGateSummary } from '../icao-gate-
|
|
2
|
-
export { N as HostedClient, O as HostedClientOptions, Q as MediaCheckType, S as SEKYRO_SDK_HEADER, T as SubmitOptions, U as UploadMedia, V as stripMimeParams } from '../icao-gate-
|
|
3
|
-
import { H as HostedSessionView, G as HostedIcaoPolicy,
|
|
4
|
-
export { A as AcceptedDocumentType,
|
|
1
|
+
import { c as IcaoGateSummary } from '../icao-gate-5FzqyitT.js';
|
|
2
|
+
export { N as HostedClient, O as HostedClientOptions, Q as MediaCheckType, S as SEKYRO_SDK_HEADER, T as SubmitOptions, U as UploadMedia, V as stripMimeParams } from '../icao-gate-5FzqyitT.js';
|
|
3
|
+
import { H as HostedSessionView, G as HostedIcaoPolicy, aj as PortraitIcaoInput } from '../types-CKgMWVnP.js';
|
|
4
|
+
export { A as AcceptedDocumentType, az as AttestationInput, c as CaptureContext, i as CaptureMode, aA as CaptureNoncesResult, aB as CaptureProof, f as CheckInputByType, k as CheckReason, l as CheckState, e as CheckType, d as CompleteMediaResult, C as ConsentLocale, m as ContactChannel, D as DecisionReason, aC as DocDeviceRead, aD as DocOcrInput, n as DocReason, aE as DocSide, E as EidAfterPass, o as EidAuthInput, p as EidReason, aF as EmailOtpInput, q as EmailOtpReason, aG as FaceMatchInput, F as FaceMatchReason, r as HostedAcceptedDocuments, u as HostedCaptureTuning, a as HostedConsentView, v as HostedDocumentCaptureTuning, w as HostedDocumentScanTuning, x as HostedEidView, y as HostedEmailOtpView, z as HostedFlowRef, J as HostedIntegrity, K as HostedLivePhotoTuning, N as HostedNativeCaptureTuning, O as HostedOcrTuning, Q as HostedOtpView, T as HostedPlanView, U as HostedPortraitView, V as HostedStepView, W as HostedVoiceLocale, X as HostedVoiceView, g as IcaoCriterion, Z as IcaoReportEntry, I as IdentityConfirmDecision, _ as IdentityMethod, $ as IdentitySummarySource, a0 as IdentitySummaryView, aH as LivenessCaptureInput, aI as LivenessInput, a1 as LivenessReason, a2 as MatchReason, M as MediaKind, a3 as MethodChoiceView, a4 as NationalEidOption, a5 as NfcChipReason, a6 as NfcStepView, a7 as OtpChoiceView, a8 as PhoneCountryRule, a9 as PhoneFormat, aJ as PhoneOtpInput, aa as PhoneOtpReason, ab as PlanAttempts, ac as PlanChoiceKind, ad as PlanChoiceOption, ae as PlanChoiceView, af as PlanSectionView, ag as PlanStepView, ah as PolicyFailureReason, aK as PopulationInput, ai as PopulationReason, ak as PortraitIcaoReason, aL as PresignRequest, P as PresignUploadResult, aM as RecordConsentResult, ap as SessionFailureReason, aq as SessionOutcome, ar as SessionStatus, aN as SessionStepView, aO as SessionView, as as StepSection, aP as SubmitCheckBody, at as VerificationAssurance, au as VerificationLevel } from '../types-CKgMWVnP.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Every error code the hosted page can receive from the session-token surface.
|
package/dist/client/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,b as t,c as o,d as i,e as n,f as s,g as a,h as p}from"../chunk-
|
|
1
|
+
import{a as e,b as t,c as o,d as i,e as n,f as s,g as a,h as p}from"../chunk-ZMO2ZQAS.js";import"../chunk-DNB3R4PI.js";export{o as HostedApiError,s as HostedClient,e as KNOWN_CODES,n as SEKYRO_SDK_HEADER,a as icaoPolicyOf,t as isKnownCode,p as portraitIcaoGate,i as stripMimeParams};
|