@sekyro/web 0.1.0-rc.18 → 0.1.0-rc.19
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 +14 -0
- package/README.md +1 -2
- package/dist/{capture-session-doc-IE5VPYWC.js → capture-session-doc-VXWWQEP4.js} +1 -1
- package/dist/{capture-session-v3-Dxus1Se9.d.ts → capture-session-v3-CFSVWYzi.d.ts} +13 -2
- package/dist/{capture-session-v3-DyUA2uCL.d.cts → capture-session-v3-Cs4yV3HJ.d.cts} +13 -2
- package/dist/chunk-4GJXUVZK.js +1 -0
- package/dist/chunk-5Y3UST3W.js +1 -0
- package/dist/{chunk-JDTZK3A7.js → chunk-64V55KD7.js} +1 -1
- package/dist/chunk-6K4D3U6Q.js +1 -0
- package/dist/chunk-CQ7SKLMC.js +1 -0
- package/dist/{chunk-DNB3R4PI.js → chunk-JUEOHNVW.js} +1 -1
- package/dist/chunk-L45YTRJJ.js +1 -0
- package/dist/chunk-PLH6ZR6J.js +1 -0
- package/dist/chunk-RNJA5GDF.js +1 -0
- package/dist/chunk-ZO6IHP2I.js +1 -0
- package/dist/chunk-ZPXL26BF.js +1 -0
- 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-FVSQPUF6.js +1 -0
- package/dist/create-portrait-capture-INDCF65X.js +1 -0
- package/dist/{create-verification-DiH7QRdv.d.cts → create-verification-1BrMZqPJ.d.cts} +67 -15
- package/dist/{create-verification-C_fx3n4A.d.ts → create-verification-CuoYJ3kj.d.ts} +67 -15
- package/dist/{icao-gate-5FzqyitT.d.ts → icao-gate-BSbyqLUh.d.ts} +25 -9
- package/dist/{icao-gate-C-lfjEpH.d.cts → icao-gate-D-wePfoV.d.cts} +25 -9
- 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-WEUIMCYU.js +1 -0
- package/dist/{types-CKgMWVnP.d.cts → types-DPl0hsmI.d.cts} +29 -5
- package/dist/{types-CKgMWVnP.d.ts → types-DPl0hsmI.d.ts} +29 -5
- package/package.json +1 -1
- package/sbom.cdx.json +7 -7
- package/dist/chunk-2BFYVMUU.js +0 -1
- package/dist/chunk-D42NBRSV.js +0 -1
- package/dist/chunk-G2HL2ZWH.js +0 -1
- package/dist/chunk-G6MU3B5V.js +0 -1
- package/dist/chunk-KBKCYDZQ.js +0 -1
- package/dist/chunk-OG4QAJ3M.js +0 -1
- package/dist/chunk-SVNAHPQU.js +0 -1
- package/dist/chunk-VCUOPQFA.js +0 -1
- package/dist/chunk-ZMO2ZQAS.js +0 -1
- package/dist/create-document-capture-35HFVNC3.js +0 -1
- package/dist/create-portrait-capture-53XBURNT.js +0 -1
- package/dist/plan-runner-YXTOSPDP.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as Jt}from"./chunk-SMKCBUJL.js";import{a as et,b as $t,c as te,e as dt,f as ee}from"./chunk-MXWLCDFX.js";import{d as Yt,h as Zt,k as qt}from"./chunk-G6LKLN4U.js";import{b as Xt,c as jt}from"./chunk-TDLIXFDT.js";import{b as Ht,c as Kt}from"./chunk-POIQGEZM.js";import{k as Nt,m as Qt,n as Ut,o as Wt}from"./chunk-CQ7SKLMC.js";import{b as ut,c as ht,d as j,e as Vt}from"./chunk-FPXL63KZ.js";import{c as Bt}from"./chunk-JUEOHNVW.js";var it=Object.freeze({sensing:{key:"sensing",reticle:"searching",minDurationMs:900},too_far:{key:"too_far",reticle:"coaching",minDurationMs:1400},too_close:{key:"too_close",reticle:"coaching",minDurationMs:1400},edge_clipped:{key:"edge_clipped",reticle:"coaching",minDurationMs:1400},wrong_shape:{key:"wrong_shape",reticle:"coaching",minDurationMs:1400},tilted:{key:"tilted",reticle:"coaching",minDurationMs:1400},too_dark:{key:"too_dark",reticle:"coaching",minDurationMs:1400},too_bright:{key:"too_bright",reticle:"coaching",minDurationMs:1400},blurry:{key:"blurry",reticle:"coaching",minDurationMs:1400},focus_far:{key:"focus_far",reticle:"coaching",minDurationMs:1600},glare:{key:"glare",reticle:"coaching",minDurationMs:1400},hold_still:{key:"hold_still",reticle:"locking",minDurationMs:900},processing:{key:"processing",reticle:"processing",minDurationMs:800},side_captured:{key:"side_captured",reticle:"flip",minDurationMs:2600},captured:{key:"captured",reticle:"done",minDurationMs:800}});function ie(i){return i.framing==="no_document"?"sensing":i.framing==="too_far"?"too_far":i.framing==="too_close"?"too_close":i.framing==="edge_clipped"?"edge_clipped":i.framing==="wrong_shape"?"wrong_shape":i.framing==="tilted"?"tilted":i.lighting==="too_dark"?"too_dark":i.lighting==="too_bright"?"too_bright":i.glare==="glare"?"glare":i.blur==="blurry"?"blurry":"hold_still"}var nt=class{constructor(t=2600,e=.35){this.windowMs=t;this.decayPerSecond=e;this.votes=[];this.current=it.sensing;this.currentSinceMs=null}reset(){this.votes=[],this.current=it.sensing,this.currentSinceMs=null}force(t,e){return this.votes=[],this.current=it[t],this.currentSinceMs=e,this.current}tick(t,e){if(this.currentSinceMs===null&&(this.currentSinceMs=e),this.votes.push({key:t,atMs:e}),this.votes=this.votes.filter(r=>e-r.atMs<=this.windowMs),e-this.currentSinceMs<this.current.minDurationMs)return this.current;let n=new Map;for(let r of this.votes){let c=(e-r.atMs)/1e3,a=this.decayPerSecond**c;n.set(r.key,(n.get(r.key)??0)+a)}let o=this.current.key,s=-1;for(let[r,c]of n)c>s&&(s=c,o=r);return o!==this.current.key&&(this.current=it[o],this.currentSinceMs=e),this.current}};var Ke=Object.freeze({MAX_AREA_FRAC:.92,TILT_MAX_SIDE_RATIO:1.3,GLARE_MAX_SPECULAR_FRAC:.025});function oe(i){let{data:t,width:e,height:n}=i,o=e*n;if(o===0)return 0;let s=0;for(let r=0;r<o;r++){let c=r*4;.299*(t[c]??0)+.587*(t[c+1]??0)+.114*(t[c+2]??0)>=252&&s++}return s/o}function Ve(i){let t=(a,l)=>Math.hypot(l.x-a.x,l.y-a.y),e=t(i.topLeft,i.topRight),n=t(i.bottomLeft,i.bottomRight),o=t(i.topLeft,i.bottomLeft),s=t(i.topRight,i.bottomRight),r=Math.max(e,n)/Math.max(1e-6,Math.min(e,n)),c=Math.max(o,s)/Math.max(1e-6,Math.min(o,s));return Math.max(r,c)}function se(i){let t={...$t,...i.thresholds},e=Ke,{quad:n,frameWidth:o,frameHeight:s,measures:r}=i,c=i.format==="ID-3",a="ok";if(n===null)a="no_document";else if(c){let m=dt(n),h=o>0?m.width/o:0,f=m.height>0?m.width/m.height:0;h<t.ID3_BAND_MIN_WIDTH_FRAC?a="too_far":ne(n,o,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":(f<t.ID3_BAND_ASPECT_MIN||f>t.ID3_BAND_ASPECT_MAX)&&(a="wrong_shape")}else{let m=te(n,o,s),h=dt(n),f=Math.max(h.width,h.height)/Math.max(1e-6,Math.min(h.width,h.height));m<t.MIN_AREA_FRAC?a="too_far":m>e.MAX_AREA_FRAC?a="too_close":ne(n,o,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":jt(i.format,f)?Ve(n)>e.TILT_MAX_SIDE_RATIO&&(a="tilted"):a="wrong_shape"}let l=r.exposure>=t.GUIDE_EXPOSURE?"ok":r.meanLuma<(ut[0]+ut[1])/2?"too_dark":"too_bright",u=r.sharpness>=t.GUIDE_SHARPNESS?"ok":"blurry",d=r.specularFraction>=e.GLARE_MAX_SPECULAR_FRAC?"glare":"ok";return{framing:a,lighting:l,blur:u,glare:d,acceptable:a==="ok"&&l==="ok"&&u==="ok"&&d==="ok"}}function ne(i,t,e,n){return[i.topLeft,i.topRight,i.bottomRight,i.bottomLeft].some(s=>s.x<=n||s.y<=n||s.x>=t-n||s.y>=e-n)}var ae=Object.freeze({width:1920,height:1080}),Xe=Object.freeze({width:3840,height:2160}),re=4096,je=2560,ce=640,ot=.15,Y=Object.freeze({side:.2,above:.9,below:.3});function E(i){let t=[i.topLeft.x,i.topRight.x,i.bottomRight.x,i.bottomLeft.x],e=[i.topLeft.y,i.topRight.y,i.bottomRight.y,i.bottomLeft.y],n=Math.min(...t),o=Math.min(...e);return{x:n,y:o,width:Math.max(...t)-n,height:Math.max(...e)-o}}function le(i,t){let e=Math.max(0,Math.floor(i.x)),n=Math.max(0,Math.floor(i.y)),o=Math.min(t.width,Math.ceil(i.x+i.width)),s=Math.min(t.height,Math.ceil(i.y+i.height));return o-e<16||s-n<16?null:{x:e,y:n,width:o-e,height:s-n}}function Ye(i,t,e){if(i===null||t.width<=0||t.height<=0)return null;let n=E(i);if(n.width<=0||n.height<=0)return null;let o=e==="ID-3"?{x:n.x-n.width*Y.side,y:n.y-n.width*Y.above,width:n.width*(1+2*Y.side),height:n.height+n.width*(Y.above+Y.below)}:{x:n.x-n.width*ot,y:n.y-n.height*ot,width:n.width*(1+2*ot),height:n.height*(1+2*ot)};return le(o,t)}function mt(i,t,e){let n=Math.max(i,t);return n>0?Math.min(1,e/n):1}function ft(i,t,e,n,o=je){let s=t.width>0?e.width/t.width:1,r=t.height>0?e.height/t.height:1,c=i===null?null:{topLeft:{x:i.topLeft.x*s,y:i.topLeft.y*r},topRight:{x:i.topRight.x*s,y:i.topRight.y*r},bottomRight:{x:i.bottomRight.x*s,y:i.bottomRight.y*r},bottomLeft:{x:i.bottomLeft.x*s,y:i.bottomLeft.y*r}},a=Ye(c,e,n)??{x:0,y:0,width:e.width,height:e.height},l=mt(a.width,a.height,o),u=Math.max(1,Math.round(a.width*l)),d=Math.max(1,Math.round(a.height*l)),m=null;if(c!==null){let h=E(c);m=le({x:(h.x-a.x)*l,y:(h.y-a.y)*l,width:h.width*l,height:h.height*l},{width:u,height:d})}return{crop:a,width:u,height:d,docRegion:m}}function ue(i,t,e,n=Xe){if(e==="LOW")return null;let o=i?.width?.max,s=i?.height?.max;if(typeof o!="number"||typeof s!="number"||o<=0||s<=0)return null;let r=Math.max(o,s),c=Math.min(o,s),a=Math.min(r,Math.max(n.width,n.height)),l=Math.min(c,Math.min(n.width,n.height));return a<=Math.max(t.width,t.height)?null:{width:{ideal:a},height:{ideal:l}}}function he(i){let t={},e=i?.imageWidth,n=i?.imageHeight;if(typeof e?.max=="number"&&e.max>0){let o=typeof n?.max=="number"&&n.max>0?e.max/n.max:1.3333333333333333,s=o>=1?re:re*o,r=Math.min(e.max,Math.floor(s)),c=typeof e.step=="number"&&e.step>0?e.step:1,a=typeof e.min=="number"?e.min:0;r=Math.max(a,a+Math.floor((r-a)/c)*c),t.imageWidth=r}return i?.fillLightMode?.includes("off")===!0&&(t.fillLightMode="off"),t}function de(i,t){if(i.width<=0||i.height<=0||t.width<=0||t.height<=0)return!1;let e=i.width>i.height,n=t.width>t.height;return e!==n&&i.width!==i.height&&t.width!==t.height?!1:Math.max(i.width,i.height)>=1.2*Math.max(t.width,t.height)}function me(i,t,e,n){if(e===null)return!1;let o=E(i),s=E(e);if(t.width<=0||n.width<=0)return!1;let r=o.width/t.width,c=s.width/n.width;return c>0&&r>=.6*c&&r<=1.25*c}var fe=3500,Ze=.92;function ge(){let i=globalThis.ImageCapture;return typeof i=="function"?i:null}function Je(i){return/AppleWebKit\//.test(i)&&!/(Chrome|Chromium|Edg|OPR)\//.test(i)}function be(i,t=typeof navigator>"u"?"":navigator.userAgent){return ge()!==null&&!Je(t)&&i!=null&&i.kind==="video"&&i.readyState==="live"}function pe(i,t){return new Promise((e,n)=>{let o=setTimeout(()=>n(new Error("takePhoto timed out")),t);i.then(s=>{clearTimeout(o),e(s)},s=>{clearTimeout(o),n(s)})})}function pt(i,t){let e=document.createElement("canvas");return e.width=i,e.height=t,e}function qe(i,t){return new Promise((e,n)=>{i.toBlob(o=>o?e(o):n(new Error("toBlob failed")),"image/jpeg",t)})}async function ye(i,t,e,n,o){let s=pt(e,n),r=pt(1,1);try{let c=s.getContext("2d");if(c===null)throw new Error("2d context unavailable");c.imageSmoothingQuality="high",c.drawImage(i,t.x,t.y,t.width,t.height,0,0,e,n);let a=await qe(s,Ze),l=o===null?null:Yt({topLeft:{x:o.x,y:o.y},topRight:{x:o.x+o.width,y:o.y},bottomRight:{x:o.x+o.width,y:o.y+o.height},bottomLeft:{x:o.x,y:o.y+o.height}},{width:e,height:n},{width:e,height:n}),u=Zt(s,l),d=mt(e,n,ce);return r.width=Math.max(1,Math.round(e*d)),r.height=Math.max(1,Math.round(n*d)),r.getContext("2d")?.drawImage(s,0,0,r.width,r.height),{blob:a,previewDataUrl:r.toDataURL("image/jpeg",.85),sharpness:u}}finally{s.width=0,s.height=0,r.width=0,r.height=0}}function $e(i,t){let e=Math.min(1,t/i.width),n=pt(Math.max(1,Math.round(i.width*e)),Math.max(1,Math.round(i.height*e)));try{let o=n.getContext("2d",{willReadFrequently:!0});return o===null?null:(o.imageSmoothingQuality="high",o.drawImage(i,0,0,n.width,n.height),o.getImageData(0,0,n.width,n.height))}finally{n.width=0,n.height=0}}async function Me(i,t,e,n){let o={width:Math.max(1,i.videoWidth),height:Math.max(1,i.videoHeight)},s=ft(t,e,o,n);return{...await ye(i,s.crop,s.width,s.height,s.docRegion),docRegion:s.docRegion,source:"video",width:s.width,height:s.height}}async function ke(i,t,e,n,o){let s=ge();if(s===null)return null;let r=null;try{let c=new s(o.track),a=await pe(c.getPhotoCapabilities?.()??Promise.resolve({}),fe).catch(()=>({})),l=await pe(c.takePhoto(he(a)),fe);r=await createImageBitmap(l);let u={width:i.videoWidth,height:i.videoHeight};if(!de(r,u))return null;let d=$e(r,o.detectWidth),m=null;d!==null&&t!==null&&(m=await o.detect(d).catch(()=>null));let h=d??{width:r.width,height:r.height};m!==null&&!me(m,h,t,e)&&(m=null);let f=ft(m,h,r,n);return{...await ye(r,f.crop,f.width,f.height,f.docRegion),docRegion:f.docRegion,source:"photo",width:f.width,height:f.height}}catch{return null}finally{r?.close()}}var st=Object.freeze({width:3840,height:2160,lensSelection:!0,continuousFocus:!0,refocusBeforePhotoMs:350,zoomMax:2,zoomNoFocusInfo:1.5,zoomMinSourcePx:2160,fillDistanceM:Object.freeze({id1:.11,id3:.15}),focusMarginFrac:.2,stillSharpnessMin:.16,stillRefusalsMax:2,focusFarFillFrac:.45,noDocFarHintMs:1500,zoomFallbackMs:8e3}),S=(i,t,e)=>typeof i=="number"&&Number.isFinite(i)&&i>=t&&i<=e?i:void 0;function Ti(i){let t=st,e=i!==null&&typeof i=="object"?i:{},n=e.fillDistanceM!==null&&typeof e.fillDistanceM=="object"?e.fillDistanceM:{},o=(s,r)=>typeof s=="boolean"?s:r;return{width:S(e.width,640,7680)??t.width,height:S(e.height,480,4320)??t.height,lensSelection:o(e.lensSelection,t.lensSelection),continuousFocus:o(e.continuousFocus,t.continuousFocus),refocusBeforePhotoMs:S(e.refocusBeforePhotoMs,0,2e3)??t.refocusBeforePhotoMs,zoomMax:S(e.zoomMax,1,5)??t.zoomMax,zoomNoFocusInfo:S(e.zoomNoFocusInfo,1,5)??t.zoomNoFocusInfo,zoomMinSourcePx:S(e.zoomMinSourcePx,0,8e3)??t.zoomMinSourcePx,fillDistanceM:{id1:S(n.id1,.03,1)??t.fillDistanceM.id1,id3:S(n.id3,.03,1)??t.fillDistanceM.id3},focusMarginFrac:S(e.focusMarginFrac,0,2)??t.focusMarginFrac,stillSharpnessMin:S(e.stillSharpnessMin,0,10)??t.stillSharpnessMin,stillRefusalsMax:S(e.stillRefusalsMax,0,10)??t.stillRefusalsMax,focusFarFillFrac:S(e.focusFarFillFrac,0,1)??t.focusFarFillFrac,noDocFarHintMs:S(e.noDocFarHintMs,0,6e4)??t.noDocFarHintMs,zoomFallbackMs:S(e.zoomFallbackMs,0,12e4)??t.zoomFallbackMs}}function ti(i){let t=i.toLowerCase();return t===""?"unknown":/front|facing front|user|selfie|face ?time/.test(t)?"front":/ultra|0\.5x|wide angle/.test(t)?"ultra":/tele|zoom|periscope|[2-9]x/.test(t)?"tele":/depth|tof|infrared|\bir\b|truedepth|lidar|macro|monochrome|mono\b/.test(t)?"depth":/dual|triple/.test(t)?"virtual":/back|rear|environment|facing back|arrière|خلفية/.test(t)?"main":"unknown"}function ei(i){let t=/camera2?\s*(\d+)/i.exec(i);return t?Number(t[1]):Number.POSITIVE_INFINITY}function ii(i){let t={main:0,virtual:1,ultra:9,tele:9,depth:9,front:9,unknown:9};return i.filter(e=>(e.kind===void 0||e.kind==="videoinput")&&e.deviceId!=="").map((e,n)=>({id:e.deviceId,kind:ti(e.label),index:ei(e.label),i:n})).filter(e=>t[e.kind]<9).sort((e,n)=>t[e.kind]-t[n.kind]||e.index-n.index||e.i-n.i).map(e=>e.id)}var gt="sekyro.doc.camera";function ni(){try{let i=globalThis.localStorage?.getItem(gt);return typeof i=="string"&&i!==""?i:null}catch{return null}}function xe(i){try{i===null?globalThis.localStorage?.removeItem(gt):globalThis.localStorage?.setItem(gt,i)}catch{}}var rt=(i,t)=>Array.isArray(i?.focusMode)&&i.focusMode.includes(t);function yt(i,t,e){if(!rt(i,"single-shot"))return null;let n=o=>Math.min(1,Math.max(0,Number.isFinite(o)?o:.5));return{focusMode:"single-shot",pointsOfInterest:[{x:n(t),y:n(e)}]}}function _i(i,t,e,n){if(!Number.isFinite(i)||!Number.isFinite(t)||e.width<=0||e.height<=0||n.width<=0||n.height<=0)return null;let o=Math.max(e.width/n.width,e.height/n.height),s=n.width*o,r=n.height*o,c=(i-e.left+(s-e.width)/2)/s,a=(t-e.top+(r-e.height)/2)/r;return{x:Math.min(1,Math.max(0,c)),y:Math.min(1,Math.max(0,a))}}function we(i,t,e,n=st){let o=i?.zoom?.min,s=i?.zoom?.max;if(typeof s!="number"||s<=1)return 1;let r=e==="ID-3"?n.fillDistanceM.id3:n.fillDistanceM.id1,c=i?.focusDistance?.min,a;if(typeof c=="number"&&c>0&&c<1){if(a=c*(1+n.focusMarginFrac)/r,a<=1.05)return 1}else{if(Math.min(t.width,t.height)<n.zoomMinSourcePx)return 1;a=n.zoomNoFocusInfo}let l=Math.min(a,n.zoomMax,s);typeof o=="number"&&(l=Math.max(l,o));let u=i?.zoom?.step;return typeof u=="number"&&u>0&&(l=Math.round(l/u)*u),l>1.01?Number(l.toFixed(2)):1}function bt(i){try{return i.getVideoTracks?.()[0]}catch{return}}function De(i){if(i!==null)for(let t of i.getTracks())t.stop()}function oi(i){try{let t=bt(i)?.getCapabilities?.();return!Array.isArray(t?.focusMode)||t.focusMode.includes("continuous")}catch{return!0}}var si=3;async function ve(i){let t=s=>({audio:!1,video:{...s,width:{ideal:i.base.width},height:{ideal:i.base.height}}}),e=s=>i.getUserMedia(t({deviceId:{exact:s}})),n=()=>i.getUserMedia(t({facingMode:{ideal:"environment"}}));if(i.lensSelection){let s=ni();if(s!==null)try{return{stream:await e(s),lens:"stored"}}catch{xe(null)}}let o=await n();if(!i.lensSelection||i.enumerateDevices===void 0)return{stream:o,lens:"default"};try{let s=ii(await i.enumerateDevices()).slice(0,si);if(s.length===0)return{stream:o,lens:"default"};let r=null;for(let c of s){let a=o!==null?bt(o)?.getSettings?.().deviceId:void 0;if(o===null||a!==c){De(o),o=null;try{o=await e(c)}catch{continue}}if(r??(r=c),oi(o))return xe(c),{stream:o,lens:"selected"}}if(o!==null&&r!==null&&bt(o)?.getSettings?.().deviceId===r)return{stream:o,lens:"selected"};if(De(o),o=null,r!==null)try{return{stream:await e(r),lens:"selected"}}catch{}return{stream:await n(),lens:"default"}}catch{return{stream:o??await n(),lens:"default"}}}var Z=Object.freeze({brightness:0,glare:0,cardGlare:0,sharpness:0,fill:0,shape:0,content:0,offsetX:0,offsetY:0,edgeConfidence:0,box:null}),L=i=>Math.min(1,Math.max(0,i));function Te(i,t,e,n=.06){let o=Math.max(i.width/e,i.height),s=o*e,r=(i.width-s)/2,c=(i.height-o)/2,a=L((t.x-t.width*n-r)/s),l=L((t.y-t.height*n-c)/o),u=L((t.x+t.width*(1+n)-r)/s),d=L((t.y+t.height*(1+n)-c)/o);return{x:a,y:l,width:u-a,height:d-l}}function _e(i,t,e={}){let n=e.edgePeakFrac??0,{width:o,height:s,data:r}=i;if(o<=0||s<=0)return Z;let c=L(t.x),a=L(t.y),l={x:c,y:a,width:Math.max(0,L(t.x+t.width)-c),height:Math.max(0,L(t.y+t.height)-a)};if(l.width<=0||l.height<=0)return Z;let u=l.x*o,d=l.y*s,m=(l.x+l.width)*o,h=(l.y+l.height)*s,f=(m-u)*.15,g=(h-d)*.15,y=(p,b,R)=>Math.min(R,Math.max(b,p)),x=y(Math.floor(u-f),0,o-1),w=y(Math.floor(d-g),0,s-1),I=y(Math.ceil(m+f),x+1,o),v=y(Math.ceil(h+g),w+1,s),D=Math.max(1,Math.ceil(Math.max(I-x,v-w)/320)),M=Math.floor((I-x+D-1)/D),T=Math.floor((v-w+D-1)/D);if(M<3||T<3)return Z;let k=new Int32Array(M*T);for(let p=0;p<T;p++){let b=w+p*D;for(let R=0;R<M;R++){let F=(b*o+x+R*D)*4;k[p*M+R]=(r[F]??0)*77+(r[F+1]??0)*150+(r[F+2]??0)*29>>8}}let C=(p,b)=>(p-b-.5)/D,_=C(u,x),A=C(m,x),B=C(d,w),U=C(h,w),kt=(m-u)/D,xt=(h-d)/D,Dt=y(Math.ceil(_),0,M-1),Ie=y(Math.floor(A),Dt,M-1),wt=y(Math.ceil(B),0,T-1),Oe=y(Math.floor(U),wt,T-1),vt=0,St=0,W=0,Tt=0,_t=0,H=0;for(let p=wt;p<=Oe;p++)for(let b=Dt;b<=Ie;b++){let R=k[p*M+b];if(vt+=R,R>=248&&St++,W++,b>=1&&b<M-1&&p>=1&&p<T-1){let F=k[p*M+b-1]+k[p*M+b+1]+k[(p-1)*M+b]+k[(p+1)*M+b]-4*R;Tt+=F,_t+=F*F,H++}}let Pe=W>0?vt/W:0,Rt=W>0?St/W:0,Ft=H>0?Tt/H:0,Ge=H>0?Math.max(0,_t/H-Ft*Ft):0,K=new Float64Array(M),V=new Float64Array(T);for(let p=0;p<T;p++)for(let b=1;b<M-1;b++)K[b]=K[b]+Math.abs(k[p*M+b+1]-k[p*M+b-1]);for(let p=1;p<T-1;p++)for(let b=0;b<M;b++)V[p]=V[p]+Math.abs(k[(p+1)*M+b]-k[(p-1)*M+b]);let O=at(K,!0,_,n),P=at(K,!1,A,n),G=at(V,!0,B,n),z=at(V,!1,U,n),Ct=(P.position-O.position)/kt,At=(z.position-G.position)/xt,ze=At>0?Ct/At:0,Ne=((O.position+P.position)/2-(_+A)/2)/kt,Qe=((G.position+z.position)/2-(B+U)/2)/xt,Et=Se(K),Lt=Se(V),Be=Et<=0||Lt<=0?0:Math.min(Math.min(O.value,P.value)/Et,Math.min(G.value,z.value)/Lt),$=(p,b)=>b+(p+.5)*D,It=Rt,Ot=0;{let p=(P.position-O.position)*.06,b=(z.position-G.position)*.06,R=y(Math.ceil(O.position+p),0,M-1),F=y(Math.floor(P.position-p),0,M-1),Ue=y(Math.ceil(G.position+b),0,T-1),Pt=y(Math.floor(z.position-b),0,T-1),Gt=0,tt=0,zt=0;for(let N=Ue;N<=Pt;N++)for(let Q=R;Q<=F;Q++){tt++;let X=k[N*M+Q];X>=248&&Gt++;let We=Q+2<=F?k[N*M+Q+2]:X,He=N+2<=Pt?k[(N+2)*M+Q]:X;(Math.abs(We-X)>=24||Math.abs(He-X)>=24)&&zt++}tt>=16&&(It=Gt/tt,Ot=zt/tt)}return{brightness:Pe,glare:Rt,cardGlare:It,sharpness:Ge,fill:Ct,shape:ze,content:Ot,offsetX:Ne,offsetY:Qe,edgeConfidence:Be,box:{left:$(O.position,x),right:$(P.position,x),top:$(G.position,w),bottom:$(z.position,w)}}}function at(i,t,e,n){let o=i.length,s=Math.max(1,Math.floor(o*.45)),r=t?1:Math.max(1,o-1-s),c=t?Math.min(o-2,s):o-2,a=r;for(let h=r;h<=c;h++)i[h]>i[a]&&(a=h);if(n>0&&n<1){let h=i[a]*n,f=a,g=Math.abs(a-e);for(let y=r;y<=c;y++){let x=i[y];if(x<h||x<(i[y-1]??0)||x<(i[y+1]??0))continue;let w=Math.abs(y-e);w<g&&(f=y,g=w)}a=f}let l=a>0?i[a-1]:0,u=i[a],d=a<o-1?i[a+1]:0,m=l+u+d;return{position:m>0?a+(d-l)/m:a,value:u}}function Se(i){if(i.length<3)return 0;let t=0;for(let e=1;e<i.length-1;e++)t+=i[e];return t/(i.length-2)}function Re(i){let t=i.box;return t===null||t.right-t.left<4||t.bottom-t.top<4?null:{topLeft:{x:t.left,y:t.top},topRight:{x:t.right,y:t.top},bottomRight:{x:t.right,y:t.bottom},bottomLeft:{x:t.left,y:t.bottom}}}var J=Object.freeze({fillMin:.82,fillMax:1.06,offsetMax:.06,glareMax:.025,sharpnessMin:180,edgeConfidenceMin:1.6,darkBrightness:70,lockMs:450,steadyMs:900,steadyFillMin:.45,steadyFillMax:1.3,steadyFillDelta:.06,steadyOffsetDelta:.04,steadyRefMs:100,edgePeakFrac:.4,shapeTolerance:.2,contentMin:.1});function Fi(i){let t=i!==null&&typeof i=="object"?i:{},e={...J};for(let n of Object.keys(J)){let o=t[n];typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1e6&&(e[n]=o)}return e}var ct=class{constructor(t=J){this.t=t;this.goodSince=null;this.steadySince=null;this.last=null}reset(){this.goodSince=null,this.steadySince=null,this.last=null}tick(t,e){let n=this.t,o=n.shapeTolerance<=0||Math.abs(t.shape-1)<=n.shapeTolerance,s=t.edgeConfidence>=n.edgeConfidenceMin&&o&&t.content>=n.contentMin,r=t.fill>=n.fillMin&&t.fill<=n.fillMax,c=Math.abs(t.offsetX)<=n.offsetMax&&Math.abs(t.offsetY)<=n.offsetMax,a=t.cardGlare<=n.glareMax,l=t.sharpness>=n.sharpnessMin,u=this.last;this.last={fill:t.fill,offsetX:t.offsetX,offsetY:t.offsetY,at:e};let d=u!==null&&n.steadyRefMs>0?Math.min(3,Math.max(1,(e-u.at)/n.steadyRefMs)):1,m=s&&a&&l&&t.fill>=n.steadyFillMin&&t.fill<=n.steadyFillMax&&u!==null&&Math.abs(t.fill-u.fill)<=n.steadyFillDelta*d&&Math.abs(t.offsetX-u.offsetX)<=n.steadyOffsetDelta*d&&Math.abs(t.offsetY-u.offsetY)<=n.steadyOffsetDelta*d,h=s&&r&&c&&a&&l,f;if(s?a?t.fill<n.fillMin?f="too_small":t.fill>n.fillMax?f="too_big":l?c?f="locking":f="off_center":f="blurry":f="glare":f="no_card",h){if(m&&(this.steadySince??(this.steadySince=e)),this.goodSince??(this.goodSince=e),e-this.goodSince>=n.lockMs)return{detected:s,ready:!0,via:"good",blocker:"locking"};let g=this.steadySince!==null&&e-this.steadySince>=n.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:"locking"}}if(this.goodSince=null,m){this.steadySince??(this.steadySince=e);let g=e-this.steadySince>=n.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:g?"locking":"steadying"}}return this.steadySince=null,{detected:s,ready:!1,via:null,blocker:f}}};var q=null;async function ri(i){return q===null&&(q=(await import("./detector-scanic-YCDNLCGV.js")).detectQuad),q(i)}async function ai(i){let t=Jt(i);return t===null?null:{topLeft:{x:t.x,y:t.y},topRight:{x:t.x+t.width,y:t.y},bottomRight:{x:t.x+t.width,y:t.y+t.height},bottomLeft:{x:t.x,y:t.y+t.height}}}function Vi(){q===null&&import("./detector-scanic-YCDNLCGV.js").then(i=>{q=i.detectQuad}).catch(()=>{})}var Fe=4e3,ci=2,Ce=3,li=Object.freeze({LOW:3,MID:5,HIGH:6}),Mt=Object.freeze({manualShutterMs:6e3,detectedNoLockMs:1950});function Xi(i){let t=i!==null&&typeof i=="object"?i:{},e=(n,o,s)=>typeof n=="number"&&Number.isFinite(n)&&n>=o&&n<=s?n:void 0;return{manualShutterMs:e(t.manualShutterMs,1e3,6e4)??Mt.manualShutterMs,detectedNoLockMs:e(t.steadyMs,300,3e4)!==void 0?t.steadyMs+(e(t.lockMs,0,1e4)??450):Mt.detectedNoLockMs}}var Ae=class i{constructor(t){this.torchOn=!1;this.stillRefusals=0;this.zoom=1;this.positioningSince=null;this.detectedSince=null;this.lastSeenAt=null;this.lastGuideQuad=null;this.lastOcrReady=null;this.shutterOffered=!1;this.stats=i.freshStats();this.handlers=new Map;this.stream=null;this.timer=null;this.state="idle";this.lastGuidance=null;this.attempt=0;this.capturing=!1;this.feedback=new nt;this.lastFeedbackKey=null;this.lastQuad=null;this.lastDetect=null;this.frameWatch=null;this.reopened=!1;this.lit=!1;this.blackTicks=0;this.offEnded=null;this.opts=t,this.gate=new ee(t.format??"ID-1",t.thresholds);let e=t.deviceClass??Kt(Ht());this.deviceClass=e,this.camera=t.camera??st,this.shutterTuning=t.shutter??Mt,this.guideTuning=t.guideLock??J,this.guideLock=new ct(this.guideTuning),this.cadenceMs=1e3/li[e]}on(t,e){let n=this.handlers.get(t);return n||(n=new Set,this.handlers.set(t,n)),n.add(e),()=>n?.delete(e)}emit(t,e){for(let n of[...this.handlers.get(t)??[]])n(e)}async start(){let t=this.state==="error"?this.resumePlayback():null,e=++this.attempt;if(this.clearFrameWatch(),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.lit=!1,this.blackTicks=0,t!==null&&await t&&e===this.attempt){this.setState("positioning"),this.scheduleTick(e),this.watchFrames(e);return}if(e===this.attempt){this.releaseStream(),Wt(),this.setState("preflight");try{let n=this.opts.getUserMedia??(r=>navigator.mediaDevices.getUserMedia(r));this.setState("acquiring");let o=this.opts.enumerateDevices??(this.opts.getUserMedia===void 0&&typeof navigator<"u"&&navigator.mediaDevices?.enumerateDevices?()=>navigator.mediaDevices.enumerateDevices():void 0),s=await ve({getUserMedia:n,...o!==void 0?{enumerateDevices:o}:{},lensSelection:this.camera.lensSelection,base:ae});if(e!==this.attempt){for(let r of s.stream.getTracks())r.stop();return}if(this.stream=s.stream,Bt(this.stream),Ut(this.stream),this.watchEnded(e),this.opts.upgradeResolution!==!1&&await this.upgradeResolution(),e!==this.attempt||(await this.applyFocusAndZoom(),e!==this.attempt)||(this.opts.video.srcObject=this.stream,await this.opts.video.play().catch(()=>{}),e!==this.attempt))return;this.setState("positioning"),this.scheduleTick(e),this.watchFrames(e)}catch(n){if(e!==this.attempt)return;let o=Qt(n),s=Nt(n);this.setState("error"),this.emit("error",{kind:o,retryable:!0,detail:s===void 0?{phase:"acquiring"}:{phase:"acquiring",name:s}})}}}resumePlayback(){let t=this.opts.video,e=this.videoTrack();if(this.stream===null||e===null||e.readyState!=="live"||t.srcObject!==this.stream)return null;try{return Promise.resolve(t.play()).then(()=>this.framesNow(),()=>!1)}catch{return null}}framesNow(){let t=this.opts.video;return this.opts.hasFrames!==void 0?this.opts.hasFrames(t):!t.paused&&t.readyState>=2&&t.videoWidth>0}watchFrames(t){let e=this.opts.firstFrameMs??Fe;e<=0||(this.clearFrameWatch(),this.frameWatch=setTimeout(()=>{if(this.frameWatch=null,!(t!==this.attempt||this.state!=="positioning")){if(this.framesNow()&&this.blackTicks<Ce){this.reopened=!1;return}this.cameraDead(t)}},e))}clearFrameWatch(){this.frameWatch!==null&&clearTimeout(this.frameWatch),this.frameWatch=null}watchEnded(t){this.offEnded?.(),this.offEnded=null;let e=this.videoTrack();if(e===null||typeof e.addEventListener!="function")return;let n=()=>{t===this.attempt&&(this.state==="positioning"||this.state==="acquiring")&&this.cameraDead(t)};e.addEventListener("ended",n),this.offEnded=()=>e.removeEventListener?.("ended",n)}cameraDead(t){if(t!==this.attempt)return;let e=this.videoTrack(),n=e!==null&&e.readyState==="live"&&!e.muted&&this.opts.video.paused&&!this.framesNow();if(!n&&!this.reopened){this.reopened=!0,this.start();return}this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.clearFrameWatch(),n||this.releaseStream(),this.reopened=!1,this.setState("error"),this.emit("error",{kind:"generic",retryable:!0,detail:{phase:"acquiring"}})}releaseStream(){if(this.offEnded?.(),this.offEnded=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject!==null&&this.opts.video.srcObject!==void 0&&(this.opts.video.srcObject=null)}rearm(t){t!==void 0&&(this.opts.side=t),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.stillRefusals=0,this.state==="captured"&&(this.setState("positioning"),this.scheduleTick(this.attempt))}async captureNow(){if(this.state!=="positioning"||this.capturing)return;let t=this.opts.video,e=this.lastDetect?.width??Math.max(1,t.videoWidth),n=this.lastDetect?.height??Math.max(1,t.videoHeight),o=this.lastQuad??this.lastGuideQuad??{topLeft:{x:0,y:0},topRight:{x:e,y:0},bottomRight:{x:e,y:n},bottomLeft:{x:0,y:n}},s=(this.opts.now??(()=>performance.now()))(),r=this.feedback.force("processing",s);this.lastFeedbackKey=r.key,this.emit("feedback",r),await this.fire(this.attempt,this.lastOcrReady!==null?this.lastOcrReady.quad:o,{width:e,height:n,tickSharpness:this.lastDetect?.tickSharpness??0},this.lastOcrReady?.via??"manual")}captureReport(){let t=this.stats;return{...this.opts.side!==void 0?{side:this.opts.side}:{},format:this.opts.format??"ID-1",deviceClass:this.deviceClass,video:{width:this.opts.video.videoWidth||0,height:this.opts.video.videoHeight||0},zoom:this.zoom,...t.zoomFallbackAtMs!==void 0?{zoomFallbackAtMs:t.zoomFallbackAtMs}:{},...t.msToCapture!==void 0?{msToCapture:t.msToCapture}:{},...t.via!==void 0?{via:t.via}:{},...t.shutterAtMs!==void 0?{shutterAtMs:t.shutterAtMs}:{},...t.shutterReason!==void 0?{shutterReason:t.shutterReason}:{},ticks:t.ticks,quadFraming:{...t.quadFraming},qualityBlockers:{...t.qualityBlockers},guideBlockers:{...t.guideBlockers},stillRefusals:t.stillRefusals,...this.ocrReport()}}ocrReport(){let t=this.opts.ocr;if(t===void 0)return{};let e=(this.opts.format??"ID-1")==="ID-3"||this.opts.side==="single"?"single":this.opts.side==="verso"?"verso":"recto",n=t.report(e,this.stats.via,(this.opts.now??(()=>performance.now()))());return n===null?{}:{ocr:n}}static freshStats(){return{ticks:0,quadFraming:{},qualityBlockers:{},guideBlockers:{},stillRefusals:0}}setGuide(t){t===void 0?delete this.opts.guide:this.opts.guide=t,this.guideLock.reset()}guideRegion(t){let e=t.width/Math.max(1,t.height),n=this.opts.guide;if(n!==void 0&&n.viewAspect>0){let c={width:n.viewAspect,height:1},a={x:n.rect.x*n.viewAspect,y:n.rect.y,width:n.rect.width*n.viewAspect,height:n.rect.height};return Te(c,a,e,0)}let o=Xt(this.opts.format??"ID-1").center,s=.86,r=s*e/o;return r>.84&&(r=.84,s=r*o/e),{x:(1-s)/2,y:(1-r)/2,width:s,height:r}}resetSide(){this.positioningSince=null,this.detectedSince=null,this.lastSeenAt=null,this.guideLock.reset(),this.lastGuideQuad=null,this.lastOcrReady=null,this.opts.ocr?.reset(),this.stats=i.freshStats(),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}withdrawShutter(){this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}zoomFallback(t){let e=this.videoTrack();if(e===null||this.zoom<=1)return;let n=this.focusCaps(),o=typeof n?.zoom?.min=="number"?Math.max(n.zoom.min,1):1;this.zoom=o,this.stats.zoomFallbackAtMs=Math.round(t-(this.positioningSince??t)),this.guideLock.reset(),this.gate.reset(),e.applyConstraints({advanced:[{zoom:o}]}).catch(()=>{})}offerShutter(t,e){this.shutterOffered||(this.shutterOffered=!0,this.stats.shutterAtMs=Math.round(e-(this.positioningSince??e)),this.stats.shutterReason=t,this.emit("shutter",{available:!0,reason:t}))}torchAvailable(){try{return this.stream?.getVideoTracks?.()[0]?.getCapabilities?.()?.torch===!0}catch{return!1}}async setTorch(t){this.torchOn=t;try{await this.stream?.getVideoTracks?.()[0]?.applyConstraints({advanced:[{torch:t}]})}catch{}}destroy(){if(this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.clearFrameWatch(),this.offEnded?.(),this.offEnded=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject=null}async upgradeResolution(){try{let t=this.stream?.getVideoTracks?.()[0];if(t===void 0)return;let e=t.getSettings?.()??{},n=ue(t.getCapabilities?.(),{width:e.width??0,height:e.height??0},this.deviceClass,{width:this.camera.width,height:this.camera.height});n!==null&&await t.applyConstraints(n)}catch{}}focusCaps(){try{return this.videoTrack()?.getCapabilities?.()??null}catch{return null}}async applyFocusAndZoom(){let t=this.videoTrack();if(t===null)return;let e=this.focusCaps();this.camera.continuousFocus&&rt(e,"continuous")&&await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{});let n={width:0,height:0};try{let s=t.getSettings?.()??{};n={width:s.width??0,height:s.height??0}}catch{}let o=we(e,n,this.opts.format??"ID-1",this.camera);if(o>1)try{await t.applyConstraints({advanced:[{zoom:o}]}),this.zoom=o}catch{this.zoom=1}}async focusAt(t,e){let n=this.videoTrack(),o=yt(this.focusCaps(),t,e);if(!(n===null||o===null))try{await n.applyConstraints({advanced:[o]}),(this.opts.setTimer??setTimeout)(()=>{this.restoreContinuous()},1500)}catch{}}async restoreContinuous(){let t=this.videoTrack();t===null||!this.camera.continuousFocus||!rt(this.focusCaps(),"continuous")||await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})}async refocusOn(t,e){let n=this.camera.refocusBeforePhotoMs,o=this.videoTrack();if(n<=0||o===null||e.width<=0||e.height<=0)return;let s=E(t),r=yt(this.focusCaps(),(s.x+s.width/2)/e.width,(s.y+s.height/2)/e.height);if(r!==null)try{await o.applyConstraints({advanced:[r]});let c=this.opts.setTimer??setTimeout;await new Promise(a=>{c(()=>a(),n)})}catch{}}videoTrack(){try{return this.stream?.getVideoTracks?.()[0]??null}catch{return null}}async takeStill(t,e,n){if(this.opts.captureStill!==void 0)return this.opts.captureStill(this.opts.video,t,e);let o=this.opts.format??"ID-1",s=this.videoTrack();if(n&&this.opts.photoCapture!==!1&&this.deviceClass!=="LOW"&&!this.torchOn&&s!==null&&be(s)){await this.refocusOn(t,e);let r=await ke(this.opts.video,t,e,o,{track:s,detect:this.detector(),detectWidth:et});if(this.restoreContinuous(),r!==null)return r}return Me(this.opts.video,t,e,o)}detector(){return this.opts.detect??((this.opts.format??"ID-1")==="ID-3"?ai:ri)}setState(t){this.state=t,this.emit("statechange",{state:t})}scheduleTick(t){let e=this.opts.setTimer??setTimeout;this.timer=e(()=>{this.tick(t)},this.cadenceMs)}async tick(t){if(t!==this.attempt||this.state!=="positioning"||this.capturing)return;let e=this.opts.now??(()=>performance.now()),n=this.opts.grabDetectFrame??Le,o=this.detector(),s=n(this.opts.video,et);if(s===null){this.scheduleTick(t);return}if(!this.lit){if(ht(s)>ci)this.lit=!0,this.blackTicks=0;else if(++this.blackTicks>=Ce&&this.frameWatch===null&&(this.opts.firstFrameMs??Fe)>0){this.cameraDead(t);return}}let r=null;try{r=await o(s)}catch{r=null}if(t!==this.attempt)return;let c=r!==null?lt(s,r):s,a=e(),l={sharpness:j(c),exposure:Vt(c),meanLuma:ht(c),specularFraction:oe(c)},u=se({format:this.opts.format??"ID-1",quad:r,frameWidth:s.width,frameHeight:s.height,measures:l,...this.opts.thresholds!==void 0?{thresholds:this.opts.thresholds}:{}}),d=this.gate.tick({timestampMs:a,quad:r,quality:l,frameWidth:s.width,frameHeight:s.height}),h=(this.opts.format??"ID-1")!=="ID-3"?_e(s,this.guideRegion(s),{edgePeakFrac:this.guideTuning.edgePeakFrac}):Z,f=this.guideLock.tick(h,a);this.lastGuideQuad=f.detected?Re(h):null;let g=this.capturing?null:this.ocrTick(s,r,h,f.detected,u,a);this.positioningSince??(this.positioningSince=a);let y=this.stats;if(y.ticks+=1,y.quadFraming[u.framing]=(y.quadFraming[u.framing]??0)+1,u.framing==="ok"&&!d.ready){let _=u.lighting!=="ok"?u.lighting:u.glare!=="ok"?"glare":u.blur!=="ok"?"blurry":"steadying";y.qualityBlockers[_]=(y.qualityBlockers[_]??0)+1}y.guideBlockers[f.blocker]=(y.guideBlockers[f.blocker]??0)+1,r!==null||f.detected?(this.detectedSince??(this.detectedSince=a),this.lastSeenAt=a):this.detectedSince=null,this.lastSeenAt!==null&&a-this.lastSeenAt<=gi?a-this.positioningSince>=this.shutterTuning.manualShutterMs?this.offerShutter("timeout",a):g?.suspendQuality!==!0&&this.detectedSince!==null&&a-this.detectedSince>=this.shutterTuning.detectedNoLockMs&&this.offerShutter("detected_no_lock",a):this.withdrawShutter();let I=a-(this.lastSeenAt??this.positioningSince);this.zoom>1&&this.camera.zoomFallbackMs>0&&I>=this.camera.zoomFallbackMs&&this.zoomFallback(a),this.emit("checks",{engine:"docv1",p:d.p,plausible:d.plausible,stableTicks:d.stableTicks,quad:d.quad,frameWidth:s.width,frameHeight:s.height,analysis:u,ready:g?.suspendQuality!==!0&&(d.ready&&r!==null||f.ready&&this.lastGuideQuad!==null)||this.lastOcrReady!==null,guide:{detected:f.detected,blocker:f.blocker,fill:h.fill,shape:h.shape,content:h.content,offsetX:h.offsetX,offsetY:h.offsetY},...g!==null&&g.mode!=="off"?{ocr:{mode:g.mode,...g.mrz?{mrz:g.mrz}:{},...g.lock?{lock:g.lock}:{}}}:g?.mrz?{ocr:{mode:g.mode,mrz:g.mrz}}:{}}),this.lastQuad=d.plausible?r:null,this.lastDetect={width:s.width,height:s.height,tickSharpness:l.sharpness};let v=ie(u);u.framing!=="ok"&&f.detected&&(v=pi(f.blocker,h.brightness<this.guideTuning.darkBrightness)),v==="blurry"&&r!==null&&hi(r,s,this.opts.format??"ID-1")>=this.camera.focusFarFillFrac&&(v="focus_far"),v==="sensing"&&this.zoom>1&&this.camera.noDocFarHintMs>0&&I>=this.camera.noDocFarHintMs&&(v="focus_far");let D=this.feedback.tick(v,a);if(D.key!==this.lastFeedbackKey&&(this.lastFeedbackKey=D.key,this.emit("feedback",D)),d.guidanceKey!==this.lastGuidance&&(this.lastGuidance=d.guidanceKey,this.emit("guidance",{key:d.guidanceKey})),this.capturing)return;let M=g?.suspendQuality!==!0,T=M&&d.ready&&r!==null,k=M&&f.ready&&this.lastGuideQuad!==null,C=this.lastOcrReady;if(C!==null&&this.opts.autoCapture!==!1){let _=this.feedback.force("processing",a);this.lastFeedbackKey=_.key,this.emit("feedback",_);let A=j(lt(s,C.quad));await this.fire(t,C.quad,{width:s.width,height:s.height,tickSharpness:A},C.via);return}if((T||k)&&this.opts.autoCapture!==!1){let _=this.feedback.force("processing",a);this.lastFeedbackKey=_.key,this.emit("feedback",_);let A=k?this.lastGuideQuad:r,B=k?f.via==="steady"?"guide_steady":"guide_good":"quad",U=k?j(lt(s,A)):l.sharpness;await this.fire(t,A,{width:s.width,height:s.height,tickSharpness:U},B);return}this.scheduleTick(t)}async fire(t,e,n,o){this.capturing=!0;let s=this.opts.grabDetectFrame??Le,r=this.opts.setTimer??setTimeout,c={width:n.width,height:n.height};try{let a={still:await this.takeStill(e,c,!0),sharpness:n.tickSharpness};if(t!==this.attempt)return;let l=a.still.source==="photo"?0:di;for(let m=0;m<l;m++){if(await new Promise(g=>{r(()=>g(),mi)}),t!==this.attempt)return;let h=s(this.opts.video,et);if(h===null)continue;let f=j(lt(h,e));if(f>a.sharpness*fi){let g=await this.takeStill(e,c,!1);if(t!==this.attempt)return;a={still:g,sharpness:f}}}if(t!==this.attempt)return;let u=a.still.sharpness;if(this.opts.autoCapture!==!1&&o!=="manual"&&typeof u=="number"&&u>=0&&u<this.camera.stillSharpnessMin&&this.stillRefusals<this.camera.stillRefusalsMax){this.stillRefusals+=1,this.stats.stillRefusals+=1,this.guideLock.reset(),this.lastOcrReady=null,(o==="text_lock"||o==="live_mrz")&&this.opts.ocr?.rearmFace();let m=(this.opts.now??(()=>performance.now()))(),h=this.feedback.force("focus_far",m);this.lastFeedbackKey=h.key,this.emit("feedback",h),this.capturing=!1,this.gate.reset(),this.scheduleTick(t);return}this.stillRefusals=0;let d=(this.opts.now??(()=>performance.now()))();this.stats.via=o,this.stats.msToCapture=Math.round(d-(this.positioningSince??d)),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1})),this.setState("captured"),this.emit("artifacts",{keyframe:a.still.blob,previewDataUrl:a.still.previewDataUrl,...this.opts.side!==void 0?{side:this.opts.side}:{},...a.still.docRegion!==void 0?{docRegion:a.still.docRegion}:{},...(()=>{let m=o==="live_mrz"?this.opts.ocr?.liveCapture():null;return m?{liveMrz:m}:{}})()})}catch{if(t!==this.attempt)return;this.capturing=!1,this.gate.reset(),this.guideLock.reset(),this.lastOcrReady=null,(o==="text_lock"||o==="live_mrz")&&this.opts.ocr?.rearmFace(),this.scheduleTick(t)}}ocrTick(t,e,n,o,s,r){let c=this.opts.ocr,a=this.opts.video;if(c===void 0||!c.hasEngine)return this.lastOcrReady=null,null;let l=a.videoWidth,u=a.videoHeight;if(l<=0||u<=0||t.width<=0||t.height<=0)return null;let m=(this.opts.format??"ID-1")==="ID-3",h=this.guideRegion(t),f={x:h.x*l,y:h.y*u,w:h.width*l,h:h.height*u},g=l/t.width,y=u/t.height,x;m&&e!==null?x=ui(E(e),g,y,l,u):x=qt(f,c.bandTop,u);let w=m?s.glare==="ok":n.cardGlare<=this.guideTuning.glareMax,I=m?s.blur==="ok":n.sharpness>=this.guideTuning.sharpnessMin,v=c.tick({atMs:r,video:a,mrzFace:m||this.opts.side==="verso"||this.opts.side==="single",present:m||e!==null||o,card:f,band:x,portrait:u>l,glareOk:w,sharpOk:I});if(v.ready&&v.via!==void 0){let D=m?e??Ee(h,t):this.lastGuideQuad??Ee(h,t);this.lastOcrReady={quad:D,via:v.via}}else this.lastOcrReady=null;return v}};function ui(i,t,e,n,o){let s=Math.min(n,i.width*1.06*t),r=Math.min(o,Math.max(i.height*1.6*e,s/5)),c=(i.y+i.height/2)*e,a=Math.max(0,Math.min(n-s,(i.x-i.width*.03)*t)),l=Math.max(0,Math.min(o-r,c-r/2));return{x:a,y:l,w:s,h:r}}function Ee(i,t){let e=i.x*t.width,n=i.y*t.height,o=(i.x+i.width)*t.width,s=(i.y+i.height)*t.height;return{topLeft:{x:e,y:n},topRight:{x:o,y:n},bottomRight:{x:o,y:s},bottomLeft:{x:e,y:s}}}function hi(i,t,e){let n=E(i);return t.width<=0||t.height<=0?0:e==="ID-3"?n.width/t.width:n.width*n.height/(t.width*t.height)}var di=2,mi=260,fi=1.08;function Le(i,t){let e=i.videoWidth,n=i.videoHeight;if(e===0||n===0)return null;let o=Math.min(1,t/e),s=Math.round(e*o),r=Math.round(n*o),c=document.createElement("canvas");c.width=s,c.height=r;let a=c.getContext("2d",{willReadFrequently:!0});return a===null?null:(e/Math.max(1,s)>4&&(a.imageSmoothingQuality="high"),a.drawImage(i,0,0,s,r),a.getImageData(0,0,s,r))}function lt(i,t){let e=[t.topLeft.x,t.topRight.x,t.bottomRight.x,t.bottomLeft.x],n=[t.topLeft.y,t.topRight.y,t.bottomRight.y,t.bottomLeft.y],o=Math.max(0,Math.floor(Math.min(...e))),s=Math.max(0,Math.floor(Math.min(...n))),r=Math.min(i.width,Math.ceil(Math.max(...e))),c=Math.min(i.height,Math.ceil(Math.max(...n))),a=Math.max(1,r-o),l=Math.max(1,c-s),u=new Uint8ClampedArray(a*l*4);for(let d=0;d<l;d++){let m=((s+d)*i.width+o)*4;u.set(i.data.subarray(m,m+a*4),d*a*4)}return{data:u,width:a,height:l,colorSpace:i.colorSpace}}function pi(i,t){return i==="glare"?"glare":i==="too_small"?"too_far":i==="too_big"?"too_close":t?"too_dark":i==="blurry"?"blurry":i==="off_center"?"edge_clipped":i==="no_card"?"sensing":"hold_still"}var gi=1200;export{it as a,ie as b,nt as c,Ke as d,oe as e,Ve as f,se as g,st as h,Ti as i,ti as j,ii as k,gt as l,ni as m,xe as n,rt as o,yt as p,_i as q,we as r,oi as s,si as t,ve as u,Z as v,Te as w,_e as x,Re as y,J as z,Fi as A,ct as B,Vi as C,Fe as D,ci as E,Ce as F,li as G,Mt as H,Xi as I,Ae as J,ui as K,di as L,mi as M};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as F,c as N,d as H,e as U}from"./chunk-FUHDOEBP.js";import{b as J,c as ee,d as te}from"./chunk-POIQGEZM.js";import{b as K,c as B,e as W,g as z,h as R,k,m as q,n as Z}from"./chunk-CQ7SKLMC.js";import{b as O,c as re,d as x,e as ie}from"./chunk-FPXL63KZ.js";import{c as X}from"./chunk-JUEOHNVW.js";import{c as Q,d as Y,f as w,h as j,j as $}from"./chunk-OKWG3PVH.js";var ge=2500,be=1e3,ye=1500,ne=25e5,b=class extends Error{constructor(e,t){super(t??e),this.kind=e}},A=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=K();return new Promise((n,a)=>{let s;try{s=new MediaRecorder(e,i?{mimeType:i,videoBitsPerSecond:ne}:{videoBitsPerSecond:ne})}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||B,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(be)}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,ye)}else u()},ge)})}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 Be=400,We=2e3,Se=["rose","peach","sand","mint","sky","lilac"],Ee={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 ze(o){return Ee[o]}var Me=4,_e=4;function Ce(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=>Se.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 ae(o,e){let t=e.now??(()=>performance.now()),r=Ce(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<Me&&l(t())<p-_e){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 se(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 I=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 Te=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={...Te,...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=(O[0]+O[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Re=["size","centering","pose","exposure","sharpness","motion"];function ke(o){if(o.accepted)return null;if(o.factors.presence<=0)return"no_face";let e="size";for(let t of Re)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=ke(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 Ae=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ie=[/^(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 De(o){let e=(o??"").trim().toLowerCase();return e.length===0?"unknown":Ae.some(t=>e.includes(t))?"known_virtual":Ie.some(t=>t.test(e))?"platform":"unknown"}function oe(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 oe(o.navigator?.mediaDevices?.getUserMedia)&&oe(o.MediaStreamTrack?.prototype?.getSettings)}async function Oe(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 ce(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 Oe(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:De(i),prototypesIntact:we(e)}}var P=o=>Math.round(o*100)/100;function le(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:P(s),stdGapMs:a<2?0:P(Math.sqrt(d/(a-1))),captureLatencyMs:c===0?null:P(u/c)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function ue(o,e,t){return{...o,rvfc:e,rampPainter:t}}var xe=1e3,G="fcv3.hold_upright",Pe=200,L=4,Ge=600,Le=1e3,de={sharpness:1,exposure:1,meanLuma:128};function Ve(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 Fe(){return N()==="phone"}var pe=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??Fe)(),this.setState("preflight");let r=W();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let i=t.getUserMedia??(u=>navigator.mediaDevices.getUserMedia(u)),n;this.cameraRequestedAt=this.now();try{n=await i(F(H(),this.facing))}catch(u){if(e!==this.attempt)return;this.fail(q(u),{phase:"acquiring",name:k(u)});return}if(X(n),Z(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:ce(a).catch(()=>null),this.facing=U(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&&j()?async()=>{try{return await $.create(t.createWorker(),u)}catch{return w(u)}}:()=>w(u)),l;try{l=await c()}catch(f){e===this.attempt&&this.fail("models",{phase:"models",name:k(f)},f instanceof Q?f.fallbackReason:He(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=J(),d=t.deviceClass??ee(s);this.profiler=new te(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=>V=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 I({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?de: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>=xe&&(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?.()&&V?V.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",{phase:"keyframes"});return}let ve=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,...ve});return}this.setState("recording");let d=t.createRecorder?.()??new A,u=this.stream;if(u===null){this.fail("generic",{phase:"recording"});return}let c=le(t.video),l=t.screenRamp?.(),f=l!==void 0,h=ae(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",{phase:"recording",name:k(g)});return}m();let me=c.stats();if(p(),e!==this.attempt)return;if(R(C.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(T===null){this.fail("generic",{phase:"keyframes"});return}let D=h.report(),fe=await this.provenance(me,f);e===this.attempt&&this.finishCapture({clip:C.blob,clipMimeType:C.mimeType,keyframe:T.blob,previewDataUrl:T.previewDataUrl,...D!==void 0&&D.rendered.length>0?{screenRamp:D}:{},...fe})}async provenance(e,t){let r=this.trackProvenance;if(r===null)return{};let i,n=new Promise(s=>{i=setTimeout(()=>s(null),Le)}),a=await Promise.race([r,n]);return clearTimeout(i),a===null?{}:{provenance:ue(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!==G&&(this.lastGuidanceKey=G,this.emit("guidance",{key:G}))}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,Pe);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=Ge/(L-1),i=null;for(let n=0;n<L;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<L-1&&await Ne(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"?se:Ve)(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=he(e,t,96);return r===null?de:{sharpness:x(r),exposure:ie(r),meanLuma:re(r)}}centerSharpness(e){let t=Y(e),r=he(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:x(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,r){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:r});let{phase:i,name:n}=t;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:n===void 0?{phase:i}:{phase:i,name:n}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},V;function Ne(o){return new Promise(e=>setTimeout(e,o))}function He(o){return o instanceof Error?o.message:String(o)}function he(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{ge as a,be as b,ye as c,ne as d,b as e,A as f,Be as g,We as h,Se as i,ze as j,se as k,I as l,Te as m,M as n,ke as o,_ as p,xe as q,G as r,Pe as s,L as t,Ge as u,Le as v,pe as w};
|
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.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});
|
|
1
|
+
"use strict";var f=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var N=(n,e)=>{for(var o in e)f(n,o,{get:e[o],enumerable:!0})},D=(n,e,o,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of M(e))!A.call(n,i)&&i!==o&&f(n,i,{get:()=>e[i],enumerable:!(t=H(e,i))||t.enumerable});return n};var x=n=>D(f({},"__esModule",{value:!0}),n);var Q={};N(Q,{HostedApiError:()=>d,HostedClient:()=>m,KNOWN_CODES:()=>b,SEKYRO_SDK_HEADER:()=>w,icaoPolicyOf:()=>E,isKnownCode:()=>k,portraitIcaoGate:()=>v,stripMimeParams:()=>u});module.exports=x(Q);var y="0.1.0-rc.19";var C="sekyro.did",T;function P(){let n=globalThis.crypto;try{if(typeof n?.randomUUID=="function")return n.randomUUID()}catch{}try{if(typeof n?.getRandomValues=="function"){let e=n.getRandomValues(new Uint8Array(16));return Array.from(e,o=>o.toString(16).padStart(2,"0")).join("")}}catch{}}function V(){try{let n=localStorage.getItem(C);if(n)return n;let e=P();return e!==void 0&&localStorage.setItem(C,e),e}catch{return T??(T=P()),T}}async function K(){let n=globalThis.crypto?.subtle;if(!n)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]),t=await n.digest("SHA-256",new TextEncoder().encode(o));return Array.from(new Uint8Array(t),i=>i.toString(16).padStart(2,"0")).join("").slice(0,32)}function U(n){let e=new TextEncoder().encode(n),o="";for(let t of e)o+=String.fromCharCode(t);return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function L(n){let e,o;return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(t){t&&(e=t.slice(0,128))},async deviceHeader(){try{o??(o=K().catch(()=>""));let t=[];navigator.webdriver&&t.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&t.push("headless");let i=await o,s=V(),a={v:1,platform:"web",sdk:n.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}:{},...t.length?{signals:t}:{}};return U(JSON.stringify(a))}catch{return}}}}var h=Symbol.for("sekyro.web.clientContext"),_=globalThis,g=_[h]??(_[h]=L({sdk:`@sekyro/web@${y}`}));var b=["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 k(n){return b.includes(n)}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 F=6e4,I=4,$=3e4,q=9e5,B=200,Y=5,j=400,G=new Set(["server_busy","request_timeout"]),z=3e3;function u(n){return(n.split(";")[0]??"").trim()}var W={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},w=`@sekyro/web/${y}`,J=w,m=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.reportedIssues=new Set;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let o=e.fetch;this.fetchImpl=(t,i)=>(o??globalThis.fetch).call(globalThis,t,i),this.requestTimeoutMs=e.requestTimeoutMs??$,this.retryAttempts=e.inProgressRetry?.attempts??Y,this.retryDelayMs=e.inProgressRetry?.delayMs??j}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},busyRetry:!0})}async reportCameraUnavailable(e){return this.api("POST","/hosted/camera-unavailable",{body:{cause:e}})}async reportCaptureIssue(e){let o=typeof e.name=="string"?e.name.replace(/[^A-Za-z]/g,"").slice(0,40):"",t=typeof e.engineKind=="string"&&/^[a-z_]{1,32}$/.test(e.engineKind)?e.engineKind:void 0,i=typeof e.attempt=="number"&&Number.isInteger(e.attempt)&&e.attempt>=0&&e.attempt<=1e3?e.attempt:void 0,s=[e.check,i??"",e.kind,o,e.phase??""].join("|");if(this.reportedIssues.has(s))return;this.reportedIssues.add(s);let a={check:e.check,kind:e.kind,...o!==""?{name:o}:{},...e.phase!==void 0?{phase:e.phase}:{},...t!==void 0?{engineKind:t}:{},...i!==void 0?{attempt:i}:{},...e.formFactor!==void 0?{formFactor:e.formFactor}:{}};try{await this.api("POST","/hosted/capture-issue",{body:a,empty:!0})}catch{}}async choose(e,o){let t=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:o},busyRetry:!0});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,o,t){let i=await this.ensureSessionId(),s={kind:e,contentType:u(o),contentLength:t};return this.api("POST",`/sessions/${i}/media`,{body:s})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,o,t,i={}){let s=await this.ensureSessionId(),a=await this.takeCaptureNonce(),c=a===void 0?void 0:{nonce:a,...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)))}:{}},r={kind:e,contentType:u(o),contentLength:t,capture:c};return this.api("POST",`/sessions/${s}/media`,{body:r})}async takeCaptureNonce(){let e=()=>{let o=Date.now();return this.captureNonces=this.captureNonces.filter(t=>t.expiresAt-F>o),this.captureNonces.shift()?.nonce};for(let o=0;o<2;o++){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 o=await this.ensureSessionId(),t=await this.api("POST",`/sessions/${o}/media/capture-nonces`,{body:{count:Math.min(I,Math.max(1,e))}}),i=Date.now()+Math.max(0,t.expiresIn)*1e3;for(let s of Array.isArray(t.nonces)?t.nonces:[])typeof s=="string"&&s.length>0&&this.captureNonces.push({nonce:s,expiresAt:i});this.captureNonces=this.captureNonces.slice(-I)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,o,t){let i;try{i=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":u(t)},body:o,signal:AbortSignal.timeout(q)})}catch(s){throw S(s)}if(!i.ok){let s=(await i.text().catch(()=>"")).slice(0,B);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,t={}){let i=await this.ensureSessionId(),s={input:o,forceOutcome:t.forceOutcome};return this.api("POST",`/sessions/${i}/checks/${e}`,{body:s,idempotencyKey:t.idempotencyKey,busyRetry:t.idempotencyKey!==void 0})}async uploadAndSubmit(e,o,t,i={}){let s=u(o.contentType),a=await this.presign(o.kind,s,o.blob.size);await this.uploadToSpaces(a.uploadUrl,o.blob,s);let c=await this.completeMedia(a.key),r={...t,[W[e]]:c.key};return this.submitCheck(e,r,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,t={}){let i=e==="GET"||t.busyRetry===!0,s=`${this.apiOrigin}/api/v2${o}`,a={"x-session-token":this.sessionToken,"x-sekyro-sdk":J};t.body!==void 0&&(a["content-type"]="application/json"),t.idempotencyKey!==void 0&&(a["x-idempotency-key"]=t.idempotencyKey);try{let c=g.timezone();c!==void 0&&(a["sekyro-client-timezone"]=c)}catch{}try{let c=await g.deviceHeader();c!==void 0&&(a["sekyro-client-device"]=c)}catch{}for(let c=0;;c++){let r;try{r=await this.fetchImpl(s,{method:e,headers:a,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(l){throw S(l)}if(r.ok){if(t.empty===!0)return;if(t.blob===!0)try{return await r.blob()}catch(O){throw S(O)}let l;try{l=await r.json()}catch{throw new d({status:r.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${r.status})`})}return Z(l)}let p=await X(r);if(p.code==="idempotency_in_progress"&&c<this.retryAttempts){this.retryDelayMs>0&&await R(this.retryDelayMs);continue}if(i&&p.status===503&&G.has(p.code)){i=!1,await R(Math.min((p.retryAfterSeconds??2)*1e3,z));continue}throw p}}};function S(n){if((typeof n=="object"&&n!==null?n.name:void 0)==="TimeoutError")return new d({status:0,code:"timeout",message:"request timed out"});let o=n instanceof Error?n.message:String(n);return new d({status:0,code:"network_error",message:`network request failed: ${o}`})}function Z(n){return n!==null&&typeof n=="object"&&"success"in n&&"data"in n?n.data:n}async function X(n){let e="unknown_error",o=`request failed (HTTP ${n.status})`,t=Number.NaN,i;try{let c=await n.json();if(c!==null&&typeof c=="object"){let r=c;typeof r.code=="string"&&r.code.length>0&&(e=r.code),typeof r.message=="string"&&r.message.length>0&&(o=r.message),typeof r.retryAfterSeconds=="number"&&(t=r.retryAfterSeconds),Array.isArray(r.details?.issues)&&(i=r.details)}}catch{}let s=n.headers.get("retry-after"),a=s===null?Math.floor(t):Number.parseInt(s,10);return new d({status:n.status,code:e,message:o,...Number.isFinite(a)&&a>=0?{retryAfterSeconds:a}:{},details:i})}function R(n){return new Promise(e=>setTimeout(e,n))}function E(n){let e=n?.portrait,o=e?.icao,t=e?.purpose==="id_document";return o==null?t?{policy:"reject",profile:"id_document"}:null:{policy:o.policy==="alert"&&!t?"alert":"reject",profile:t||o.profile==="id_document"?"id_document":"selfie"}}function v(n){return{...n.baselineEyeOpenness!==void 0?{baselineEyeOpenness:n.baselineEyeOpenness}:{},criteria:n.verdict??{},...n.backgroundCheck!==void 0?{backgroundCheck:n.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,
|
|
4
|
-
export { A as AcceptedDocumentType,
|
|
1
|
+
import { c as IcaoGateSummary } from '../icao-gate-D-wePfoV.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-D-wePfoV.cjs';
|
|
3
|
+
import { H as HostedSessionView, J as HostedIcaoPolicy, ak as PortraitIcaoInput } from '../types-DPl0hsmI.cjs';
|
|
4
|
+
export { A as AcceptedDocumentType, aB as AttestationInput, d as CaptureContext, j as CaptureMode, aC as CaptureNoncesResult, aD as CaptureProof, g as CheckInputByType, l as CheckReason, m as CheckState, f as CheckType, e as CompleteMediaResult, C as ConsentLocale, n as ContactChannel, D as DecisionReason, aE as DocDeviceRead, aF as DocOcrInput, o as DocReason, aG as DocSide, E as EidAfterPass, p as EidAuthInput, q as EidReason, aH as EmailOtpInput, r as EmailOtpReason, aI as FaceMatchInput, F as FaceMatchReason, s as HostedAcceptedDocuments, v as HostedCaptureTuning, a as HostedConsentView, w as HostedDocumentCaptureTuning, x as HostedDocumentScanTuning, y as HostedEidView, z as HostedEmailOtpView, G as HostedFlowRef, K as HostedIntegrity, L as HostedLivePhotoTuning, O as HostedNativeCaptureTuning, Q as HostedOcrTuning, T as HostedOtpView, U as HostedPlanView, V as HostedPortraitView, W as HostedStepView, X as HostedVoiceLocale, Y as HostedVoiceView, h as IcaoCriterion, _ as IcaoReportEntry, I as IdentityConfirmDecision, $ as IdentityMethod, a0 as IdentitySummarySource, a1 as IdentitySummaryView, aJ as LivenessCaptureInput, aK as LivenessInput, a2 as LivenessReason, a3 as MatchReason, M as MediaKind, a4 as MethodChoiceView, a5 as NationalEidOption, a6 as NfcChipReason, a7 as NfcStepView, a8 as OtpChoiceView, a9 as PhoneCountryRule, aa as PhoneFormat, aL as PhoneOtpInput, ab as PhoneOtpReason, ac as PlanAttempts, ad as PlanChoiceKind, ae as PlanChoiceOption, af as PlanChoiceView, ag as PlanSectionView, ah as PlanStepView, ai as PolicyFailureReason, aM as PopulationInput, aj as PopulationReason, al as PortraitIcaoReason, aN as PresignRequest, P as PresignUploadResult, aO as RecordConsentResult, am as ResolvedCaptureMode, ar as SessionFailureReason, as as SessionOutcome, at as SessionStatus, aP as SessionStepView, aQ as SessionView, au as StepSection, aR as SubmitCheckBody, av as VerificationAssurance, aw as VerificationLevel } from '../types-DPl0hsmI.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,
|
|
4
|
-
export { A as AcceptedDocumentType,
|
|
1
|
+
import { c as IcaoGateSummary } from '../icao-gate-BSbyqLUh.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-BSbyqLUh.js';
|
|
3
|
+
import { H as HostedSessionView, J as HostedIcaoPolicy, ak as PortraitIcaoInput } from '../types-DPl0hsmI.js';
|
|
4
|
+
export { A as AcceptedDocumentType, aB as AttestationInput, d as CaptureContext, j as CaptureMode, aC as CaptureNoncesResult, aD as CaptureProof, g as CheckInputByType, l as CheckReason, m as CheckState, f as CheckType, e as CompleteMediaResult, C as ConsentLocale, n as ContactChannel, D as DecisionReason, aE as DocDeviceRead, aF as DocOcrInput, o as DocReason, aG as DocSide, E as EidAfterPass, p as EidAuthInput, q as EidReason, aH as EmailOtpInput, r as EmailOtpReason, aI as FaceMatchInput, F as FaceMatchReason, s as HostedAcceptedDocuments, v as HostedCaptureTuning, a as HostedConsentView, w as HostedDocumentCaptureTuning, x as HostedDocumentScanTuning, y as HostedEidView, z as HostedEmailOtpView, G as HostedFlowRef, K as HostedIntegrity, L as HostedLivePhotoTuning, O as HostedNativeCaptureTuning, Q as HostedOcrTuning, T as HostedOtpView, U as HostedPlanView, V as HostedPortraitView, W as HostedStepView, X as HostedVoiceLocale, Y as HostedVoiceView, h as IcaoCriterion, _ as IcaoReportEntry, I as IdentityConfirmDecision, $ as IdentityMethod, a0 as IdentitySummarySource, a1 as IdentitySummaryView, aJ as LivenessCaptureInput, aK as LivenessInput, a2 as LivenessReason, a3 as MatchReason, M as MediaKind, a4 as MethodChoiceView, a5 as NationalEidOption, a6 as NfcChipReason, a7 as NfcStepView, a8 as OtpChoiceView, a9 as PhoneCountryRule, aa as PhoneFormat, aL as PhoneOtpInput, ab as PhoneOtpReason, ac as PlanAttempts, ad as PlanChoiceKind, ae as PlanChoiceOption, af as PlanChoiceView, ag as PlanSectionView, ah as PlanStepView, ai as PolicyFailureReason, aM as PopulationInput, aj as PopulationReason, al as PortraitIcaoReason, aN as PresignRequest, P as PresignUploadResult, aO as RecordConsentResult, am as ResolvedCaptureMode, ar as SessionFailureReason, as as SessionOutcome, at as SessionStatus, aP as SessionStepView, aQ as SessionView, au as StepSection, aR as SubmitCheckBody, av as VerificationAssurance, aw as VerificationLevel } from '../types-DPl0hsmI.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-5Y3UST3W.js";import"../chunk-JUEOHNVW.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};
|
package/dist/core/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var lt=Object.create;var V=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var mt=Object.getPrototypeOf,pt=Object.prototype.hasOwnProperty;var ft=(r,e)=>()=>(r&&(e=r(r=0)),e);var Se=(r,e)=>{for(var t in e)V(r,t,{get:e[t],enumerable:!0})},Ee=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of dt(e))!pt.call(r,i)&&i!==t&&V(r,i,{get:()=>e[i],enumerable:!(n=ut(e,i))||n.enumerable});return r};var ht=(r,e,t)=>(t=r!=null?lt(mt(r)):{},Ee(e||!r||!r.__esModule?V(t,"default",{value:r,enumerable:!0}):t,r)),yt=r=>Ee(V({},"__esModule",{value:!0}),r);var et={};Se(et,{RANK_CANDIDATES:()=>jt,RANK_TOLERANCE:()=>Z,RANK_WINDOW_MS:()=>$t,ROLL_ZERO_DEG:()=>er,SHARPNESS_REPORT_MAX:()=>$e,YAW_REPORT_MAX:()=>je,YAW_ZERO_IOD:()=>Jt,collectRankedKeyframes:()=>Je,default:()=>rr,featuresOf:()=>Ze,frontalOf:()=>Ye,rankKeyframes:()=>Qe});function Ye(r){let e=r.eyes;if(e===void 0)return{frontal:1,yaw:null,roll:null};let t=e.right.x-e.left.x,n=e.right.y-e.left.y,i=t*t+n*n;if(i===0)return{frontal:1,yaw:null,roll:null};let a=Math.abs(Math.atan2(n,Math.abs(t))*180/Math.PI),s=qe(1-a/30),o=null,l=r.nose;if(l!==void 0){let d=(e.left.x+e.right.x)/2,c=(e.left.y+e.right.y)/2;o=Math.abs(((l.x-d)*t+(l.y-c)*n)/i),s*=qe(1-o/.5)}return{frontal:s,yaw:o,roll:a}}function Ze(r,e){return r===null?{face:!1,frontal:0,yaw:null,roll:null,eyes:null,score:0,sharpness:e}:{face:!0,...Ye(r),eyes:null,score:r.score,sharpness:e}}function Qe(r){let e=r.map((i,a)=>a),t=(i,a)=>{let s=Number.NEGATIVE_INFINITY;for(let o of e)s=Math.max(s,i(r[o]));e=e.filter(o=>i(r[o])>=s-a)};t(i=>i.frontal,Z.frontal),t(i=>i.eyes??1,Z.eyes),t(i=>i.score,Z.score);let n=-1;for(let i of e)(n===-1||r[i].sharpness>r[n].sharpness)&&(n=i);return n}function tr(r){return{face:r.face,frontal:O(r.frontal),...r.yaw!==null?{yaw:Math.min(O(r.yaw),je)}:{},...r.roll!==null?{roll:O(r.roll)}:{},...r.eyes!==null?{eyes:O(r.eyes)}:{},score:O(r.score),sharpness:Math.min(O(r.sharpness),$e)}}async function Je(r,e){let{options:t}=r,n=t.video,i=t.now??(()=>performance.now()),a=t.captureKeyframe??(m=>r.defaultKeyframe(m)),s=600/3,o=[],l=[],d=0;for(let m=0;m<4;m+=1){if(e!==r.attempt)return null;let f=r.detector,p=Promise.resolve(null),h,y=0;try{if(f!==null){let T=r.profiler?.profile.inputWidth??160,I=t.makeSnapshot?.(n,T)??r.defaultSnapshot(n,T);h=a(n).then(g=>(y=i(),g));let $=i();p=f.detect(I,n.videoWidth,n.videoHeight).then(g=>(d+=i()-$,g),()=>null)}else h=a(n).then(T=>(y=i(),T));let[v,k]=await Promise.all([h,p]);o.push(v),l.push(Ze(k,v.sharpness))}catch{h?.catch(()=>{})}let S=y>0?Math.max(0,i()-y):0;m<3&&await new Promise(v=>setTimeout(v,Math.max(0,s-S)))}if(e!==r.attempt)return null;let c=Qe(l);if(c===-1)return null;let u=0;l.forEach((m,f)=>{m.sharpness>l[u].sharpness&&(u=f)});try{t.telemetry?.({type:"keyframe",tier:r.detector?.tier??null,chosen:c,sharpest:u,detectMs:Math.round(d),candidates:l.map(tr)})}catch{}return o[c]??null}var jt,$t,Jt,er,Z,qe,O,je,$e,rr,tt=ft(()=>{"use strict";jt=4,$t=600,Jt=.5,er=30,Z={frontal:.1,eyes:.1,score:.05},qe=r=>r<0?0:r>1?1:r;O=r=>Number.isFinite(r)?Math.round(r*1e3)/1e3:0,je=99,$e=999999;rr=Je});var or={};Se(or,{CENTERED_FACTOR:()=>_t,CIRCLE_RADIUS_FACTOR:()=>kt,CLIP_MS:()=>ke,CaptureSessionV3:()=>ve,ClipError:()=>b,ClipRecorder:()=>P,DEFAULT_CLIP_MIME:()=>W,DEFAULT_TIER_ORDER:()=>De,DEFAULT_V3_ASSET_BASE_URL:()=>we,DEVICE_PROFILES:()=>Ae,DetectScheduler:()=>G,DetectorLadderError:()=>C,DeviceProfiler:()=>N,EXPOSURE_BAND:()=>L,FaceGateV3:()=>w,GATE_SNAPSHOT_MS:()=>it,GateBlockStats:()=>D,HOLD_UPRIGHT_KEY:()=>Q,IN_CIRCLE_FACTOR:()=>Tt,KEYFRAME_CANDIDATES:()=>j,KEYFRAME_WINDOW_MS:()=>st,MAX_CLIP_BYTES:()=>H,MIME_CANDIDATES:()=>Me,PHONE_MAX_SHORT_SIDE:()=>Ce,PROVENANCE_WAIT_MS:()=>ot,SHARP_REF:()=>Mr,STOP_GRACE_MS:()=>_e,TIMESLICE_MS:()=>Te,UPRIGHT_WATCH_MS:()=>at,V3_GATE_DEFAULTS:()=>Ie,VIDEO_BPS:()=>ie,blockReasonOf:()=>Xe,buildCaptureConstraints:()=>ae,buildLivenessV2FormData:()=>bt,cameraPreflight:()=>re,captureMirroredKeyframe:()=>ne,classifyDevice:()=>me,createDetector:()=>x,detectFormFactor:()=>K,detectIsMobile:()=>se,errorCopy:()=>vt,exposure:()=>le,extForMime:()=>J,intrinsicSize:()=>_,isClipTooLarge:()=>A,isMediaRecorderSupported:()=>gt,mapGetUserMediaError:()=>te,meanLuma:()=>X,pickMimeType:()=>ee,probeDevice:()=>de,sharpness:()=>q,toStreamPixels:()=>F,trackFacingMode:()=>oe,uiCopy:()=>St});module.exports=yt(or);var Me=["video/mp4;codecs=avc1.42E01E,mp4a.40.2","video/mp4;codecs=avc1.42E01E","video/mp4","video/webm;codecs=vp9,opus","video/webm;codecs=vp9","video/webm;codecs=vp8,opus","video/webm;codecs=vp8","video/webm"];function ee(){let r=globalThis.MediaRecorder;return!r||typeof r.isTypeSupported!="function"?"":Me.find(e=>r.isTypeSupported(e))??""}var W="video/webm";function te(r){if(r instanceof TypeError)return"insecure";switch(r?.name??""){case"NotAllowedError":case"PermissionDeniedError":return"permission";case"NotFoundError":case"DevicesNotFoundError":return"notfound";case"NotReadableError":case"TrackStartError":return"inuse";case"OverconstrainedError":case"ConstraintNotSatisfiedError":return"overconstrained";default:return"generic"}}function re(){let r=globalThis;if(typeof r.window<"u"&&r.window.isSecureContext===!1)return"INSECURE_CONTEXT";let e=r.navigator?.mediaDevices;return!e||typeof e.getUserMedia!="function"?"UNSUPPORTED":"OK"}function gt(){let r=globalThis.MediaRecorder;return typeof r<"u"&&typeof r.isTypeSupported=="function"}var H=8*1024*1024;function A(r){return r.size>H}function J(r){let e=(r||"").toLowerCase();return e.startsWith("image/jpeg")?"jpg":e.startsWith("video/mp4")?"mp4":(e.startsWith("video/webm"),"webm")}function bt(r){let{token:e,clip:t,keyframe:n}=r,i=r.ts??Date.now(),a=t.type||W,s=n.type||"image/jpeg",o=new FormData;return o.append("token",e),o.append("clip",new File([t],`liveness-${i}.${J(a)}`,{type:a})),o.append("keyframe",new File([n],`keyframe-${i}.${J(s)}`,{type:s})),o}function ne(r,e,t=.92){return new Promise((n,i)=>{let a=r.videoWidth,s=r.videoHeight;if(!a||!s){i(new Error("video-not-ready"));return}let o=e.getContext("2d");if(!o){i(new Error("no-2d-context"));return}e.width=a,e.height=s,o.scale(-1,1),o.drawImage(r,-a,0),e.toBlob(l=>l?n(l):i(new Error("empty-keyframe")),"image/jpeg",t)})}var vt={permission:{key:"fcv2.err.permission",fr:"Autorisez la cam\xE9ra dans les r\xE9glages du navigateur (ic\xF4ne cam\xE9ra dans la barre d\u2019adresse), puis r\xE9essayez."},notfound:{key:"fcv2.err.notfound",fr:"Aucune cam\xE9ra d\xE9tect\xE9e. Branchez ou activez une cam\xE9ra, puis r\xE9essayez."},inuse:{key:"fcv2.err.inuse",fr:"La cam\xE9ra est utilis\xE9e par une autre application. Fermez-la puis r\xE9essayez."},overconstrained:{key:"fcv2.err.overconstrained",fr:"La cam\xE9ra ne prend pas en charge les r\xE9glages demand\xE9s. Nouvel essai en cours\u2026"},insecure:{key:"fcv2.err.insecure",fr:"La cam\xE9ra n\xE9cessite une connexion s\xE9curis\xE9e (HTTPS). Ouvrez la page en HTTPS."},unsupported:{key:"fcv2.err.unsupported",fr:"Votre navigateur ne prend pas en charge l\u2019enregistrement vid\xE9o. Utilisez un navigateur r\xE9cent."},generic:{key:"fcv2.err.generic",fr:"Cam\xE9ra indisponible. R\xE9essayez ou contactez le support."}},St={recording:{key:"fcv2.recording",fr:"Enregistrement en cours\u2026"},uploading:{key:"fcv2.uploading",fr:"Envoi en cours\u2026"},clipTooLarge:{key:"fcv2.err.cliptoolarge",fr:"La vid\xE9o est trop volumineuse. R\xE9essayez dans un endroit mieux \xE9clair\xE9."},retry:{key:"fcv2.retry",fr:"R\xE9essayer"},listen:{key:"fcv2.listen",fr:"\xC9couter"}};var ke=2500,Te=1e3,_e=1500,ie=25e5,b=class extends Error{constructor(e,t){super(t??e),this.kind=e}},P=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,n){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=ee();return new Promise((a,s)=>{let o;try{o=new MediaRecorder(e,i?{mimeType:i,videoBitsPerSecond:ie}:{videoBitsPerSecond:ie})}catch{try{o=new MediaRecorder(e)}catch{s(new b("unsupported"));return}}this.recorder=o;let l=c=>{this.settled||(this.settled=!0,this.clearTimers(),c())},d=()=>l(()=>{let c=o.mimeType||i||W,u=new Blob(this.chunks,{type:c});if(u.size===0){s(new b("generic","empty clip"));return}if(A(u)){s(new b("cliptoolarge"));return}a({blob:u,mimeType:c})});if(o.ondataavailable=c=>{c.data&&c.data.size&&(this.chunks.push(c.data),this.bytes+=c.data.size,this.bytes>H&&l(()=>{try{o.state!=="inactive"&&o.stop()}catch{}s(new b("cliptoolarge"))}))},o.onstop=d,o.onerror=()=>l(()=>s(new b("generic"))),n!==void 0){let c=!1;o.onstart=()=>{if(!(c||this.settled)){c=!0;try{n()}catch{}}}}try{o.start(Te)}catch{l(()=>s(new b("generic")));return}this.hardStopTimer=setTimeout(()=>{if(this.settled||t?.(),o.state!=="inactive"){try{o.stop()}catch{d()}this.graceTimer=setTimeout(d,_e)}else d()},ke)})}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}};function ae(r,e){return{video:{width:{ideal:1280,max:1280},height:{ideal:720,max:720},facingMode:e,frameRate:{ideal:24,max:30}},audio:!1}}var Ce=600;function K(){if(typeof window>"u"||typeof navigator>"u")return"desktop";let r=String(navigator.userAgent??"");if(/iPhone|iPod/i.test(r))return"phone";if(/iPad/i.test(r))return"tablet";if(/Android/i.test(r))return/Mobile/i.test(r)?"phone":"tablet";if(/BlackBerry|IEMobile|Opera Mini/i.test(r))return"phone";if(Number(navigator.maxTouchPoints??0)<=1)return"desktop";if(/Macintosh/.test(r))return"tablet";if(!Mt())return"desktop";let t=Et();return t>0&&t<Ce?"phone":"tablet"}function se(){return K()!=="desktop"}function Et(){try{let r=window.screen,e=Number(r?.width??0),t=Number(r?.height??0);return e>0&&t>0?Math.min(e,t):0}catch{return 0}}function oe(r){try{let t=r?.getVideoTracks?.()[0]?.getSettings?.().facingMode;return t==="user"||t==="environment"?t:null}catch{return null}}function Mt(){try{return typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches}catch{return!1}}var kt=.45,Tt=.9,_t=.4;var xe=1e4,U=class r{constructor(e,t){this.tier="blaze";this.inner=e,t!==void 0&&(this.fallbackReason=t)}static async create(e,t){let n=await import("@mediapipe/tasks-vision"),i=await n.FilesetResolver.forVisionTasks(e),a=await n.FaceDetector.createFromOptions(i,{baseOptions:{modelAssetPath:`${e}/blaze_face_short_range.tflite`,delegate:"CPU"},runningMode:"IMAGE"});return new r(a,t)}async detect(e,t,n){let i;try{i=this.inner.detect(e).detections}catch{return null}let a=Ct(i);if(a?.boundingBox===void 0)return null;let s=_(e),o=xt(a.keypoints,s),l=a.keypoints?.[2],d={box:{x:a.boundingBox.originX,y:a.boundingBox.originY,width:a.boundingBox.width,height:a.boundingBox.height},...o!==void 0?{eyes:o}:{},...l!==void 0?{nose:{x:l.x*s.width,y:l.y*s.height}}:{},score:a.categories[0]?.score??0};return F(d,e,t,n)}destroy(){try{this.inner.close()}catch{}}};function Ct(r){let e,t=-1;for(let n of r){let i=n.categories[0]?.score??0;i>t&&(e=n,t=i)}return e}function xt(r,e){let t=r?.[0],n=r?.[1];if(t===void 0||n===void 0)return;let i=o=>({x:o.x*e.width,y:o.y*e.height}),[a,s]=[i(t),i(n)];return a.x<=s.x?{left:a,right:s}:{left:s,right:a}}function Rt(){if(typeof OffscreenCanvas=="function")return new OffscreenCanvas(2,2);let r=document.createElement("canvas");return r.width=2,r.height=2,r}async function Re(){let r=globalThis.FaceDetector;if(typeof r!="function")return{ok:!1,reason:"unsupported"};try{let e=new r({fastMode:!0,maxDetectedFaces:1});return await e.detect(Rt()),{ok:!0,instance:e}}catch(e){return{ok:!1,reason:`smoke_failed:${e instanceof Error?e.message:String(e)}`}}}var B=class{constructor(e,t){this.tier="native";this.inner=e,t!==void 0&&(this.fallbackReason=t)}async detect(e,t,n){let i;try{i=await this.inner.detect(e)}catch{return null}let a=i[0];if(a===void 0)return null;let s=wt(a.landmarks),o={box:{x:a.boundingBox.x,y:a.boundingBox.y,width:a.boundingBox.width,height:a.boundingBox.height},...s!==void 0?{eyes:s}:{},score:1};return F(o,e,t,n)}destroy(){}};function wt(r){if(r===void 0)return;let e=r.filter(i=>i.type==="eye").map(i=>i.locations[0]).filter(i=>i!==void 0),[t,n]=e;if(!(t===void 0||n===void 0))return t.x<=n.x?{left:t,right:n}:{left:n,right:t}}var we="/models-v3",De=["native","blaze"],C=class extends Error{constructor(e){super(`no detector tier available (${e})`),this.name="DetectorLadderError",this.fallbackReason=e}};function _(r){let e=r;if(typeof e.videoWidth=="number"&&e.videoWidth>0)return{width:e.videoWidth,height:e.videoHeight??0};if(typeof e.naturalWidth=="number"&&e.naturalWidth>0)return{width:e.naturalWidth,height:e.naturalHeight??0};let t=typeof e.width=="number"?e.width:0,n=typeof e.height=="number"?e.height:0;return{width:t,height:n}}function F(r,e,t,n){let i=_(e),a=i.width>0?t/i.width:1,s=i.height>0?n/i.height:1,o=l=>({x:l.x*a,y:l.y*s});return{box:{x:r.box.x*a,y:r.box.y*s,width:r.box.width*a,height:r.box.height*s},...r.eyes!==void 0?{eyes:{left:o(r.eyes.left),right:o(r.eyes.right)}}:{},...r.nose!==void 0?{nose:o(r.nose)}:{},score:r.score}}function Dt(r){return r instanceof Error?r.message:String(r)}async function x(r){let e=r.preferred??De,t=[];for(let n of e){if(n==="native"){let i=await Re();if(i.ok)return new B(i.instance,ce(t));t.push(`native:${i.reason}`);continue}try{return await Ot(U.create(r.v3AssetBaseUrl??we,ce(t)),r.blazeInitTimeoutMs??xe)}catch(i){t.push(i instanceof z?"blaze:blaze_init_timeout":`blaze:${Dt(i)}`)}}throw new C(ce(t)??"no_tier_available")}function ce(r){return r.length>0?r.join("; "):void 0}var z=class extends Error{};function Ot(r,e){return new Promise((t,n)=>{let i=setTimeout(()=>{n(new z(`init exceeded ${e}ms`)),r.then(a=>a.destroy(),()=>{})},e);r.then(a=>{clearTimeout(i),t(a)},a=>{clearTimeout(i),n(a)})})}var Mr=180,L=[100,190],It=64;function Oe(r,e){return .299*(r[e]??0)+.587*(r[e+1]??0)+.114*(r[e+2]??0)}function X(r){let{data:e,width:t,height:n}=r,i=t*n;if(i===0)return 0;let a=0;for(let s=0;s<i;s+=1)a+=Oe(e,s*4);return a/i}function q(r){let{data:e,width:t,height:n}=r;if(t<3||n<3)return 0;let i=new Float32Array(t*n);for(let c=0;c<i.length;c+=1)i[c]=Oe(e,c*4);let a=0,s=0,o=0;for(let c=1;c<n-1;c+=1)for(let u=1;u<t-1;u+=1){let m=c*t+u,f=(i[m-t]??0)+(i[m-1]??0)+(i[m+1]??0)+(i[m+t]??0)-4*(i[m]??0);a+=f,s+=f*f,o+=1}if(o===0)return 0;let l=a/o,d=s/o-l*l;return Math.min(1,Math.max(0,d)/180)}function le(r){let e=X(r),[t,n]=L,i=e<t?t-e:e>n?e-n:0;return Math.max(0,1-i/It)}var Ie=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}),R=r=>Math.min(1,Math.max(0,r)),w=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...Ie,...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:n,timestampMs:i}=e,a=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let s={presence:0,centering:0,size:0,pose:0,sharpness:R(n.sharpness),exposure:R(n.exposure),motion:1};if(t!==null){s.presence=1;let c=this.geometryOf(t,e);s.centering=c.centering,s.size=c.size,s.pose=c.pose,s.motion=this.motionOf(c.center,c.iod,i)}else this.lastCenter=null,this.velocityEma=0;let o=Math.min(s.presence,s.centering,s.size,s.pose,s.sharpness,s.exposure,s.motion);this.p=R(this.p+(o>=this.t.Q_GOOD?this.t.RISE_PER_S*o:-this.t.FALL_PER_S*(1-o))*a),this.qWindow.push({at:i,q:o}),this.qWindow=this.qWindow.filter(c=>c.at>=i-this.t.READY_WINDOW_MS);let l=this.qWindow.map(c=>c.q);if(l.length>=3){let c=Math.min(...l),u=l.indexOf(c);l=l.filter((m,f)=>f!==u)}let d=this.p>=1&&l.every(c=>c>=this.t.Q_GOOD);return{at:i,q:o,p:this.p,factors:s,guidanceKey:this.guidanceOf(s,n,o),ready:d,accepted:o>=this.t.Q_GOOD}}geometryOf(e,t){let{box:n,eyes:i}=e,a={x:t.frameWidth/2,y:t.frameHeight/2},s=Math.min(t.frameWidth,t.frameHeight),o=i!==void 0?{x:(i.left.x+i.right.x)/2,y:(i.left.y+i.right.y)/2}:{x:n.x+n.width/2,y:n.y+n.height/2-this.t.BOX_EYE_OFFSET_FACTOR*n.height},l=i!==void 0?Math.hypot(i.right.x-i.left.x,i.right.y-i.left.y):this.t.IOD_BOX_PROXY_FACTOR*n.width,d=Math.hypot(o.x-a.x,o.y-a.y),c=l<=0?0:1-R(d/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*l)),u=s>0?l/s:0;this.lastSizeDirection=u<this.t.SIZE_IDEAL_MIN?"far":u>this.t.SIZE_IDEAL_MAX?"close":"ideal";let m;u<this.t.SIZE_HARD_MIN||u>this.t.SIZE_HARD_MAX?m=0:u<this.t.SIZE_IDEAL_MIN?m=(u-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):u>this.t.SIZE_IDEAL_MAX?m=(this.t.SIZE_HARD_MAX-u)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):m=1;let f=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;f=1-R(p/this.t.ROLL_MAX_DEG)}return{center:o,iod:l,centering:c,size:m,pose:f}}motionOf(e,t,n){let i=this.lastCenter;if(this.lastCenter={...e,at:n},i===null||t<=0)return 1;let a=(n-i.at)/1e3;if(a<=0)return 1;let s=Math.hypot(e.x-i.x,e.y-i.y)/t/a;s<=this.t.MOTION_DEADBAND_IOD_PER_S&&(s=0);let o=1-Math.exp(-a/this.t.MOTION_TAU_S);return this.velocityEma=o*s+(1-o)*this.velocityEma,1-R(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,n){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(n<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"]],a=i[0];for(let s of i)e[s[0]]<e[a[0]]&&(a=s);return a[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(L[0]+L[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Ae=Object.freeze({LOW:Object.freeze({cadenceHz:5,inputWidth:128,animations:"reduced"}),MID:Object.freeze({cadenceHz:8,inputWidth:160,animations:"full"}),HIGH:Object.freeze({cadenceHz:10,inputWidth:192,animations:"full"})}),At=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);function de(){let r=typeof navigator>"u"?void 0:navigator,e=!1;try{e=typeof WebAssembly<"u"&&WebAssembly.validate(At)}catch{e=!1}return{cores:r?.hardwareConcurrency??2,memGB:r?.deviceMemory??null,simd:e}}function me(r){let e=r.memGB??4;return r.cores<4||e<3?"LOW":r.cores>=8&&e>=6?"HIGH":"MID"}var ue=["LOW","MID","HIGH"],N=class{constructor(e){this.samples=[];this.adjusted=!1;this.current=e}get deviceClass(){return this.current}get profile(){return Ae[this.current]}record(e){if(this.adjusted||this.samples.length>=10)return this.current;if(this.samples.push(e),this.samples.length<10)return this.current;this.adjusted=!0;let t=this.samples.reduce((n,i)=>n+i,0)/this.samples.length;if(t>70)this.current="LOW";else if(t<25){let n=ue.indexOf(this.current);this.current=ue[Math.min(ue.length-1,n+1)]??this.current}return this.current}};var G=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,n)=>t+n,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 Pe="0.1.0-rc.18";var Fe="sekyro.did",Le;function Ne(){let r=globalThis.crypto;try{if(typeof r?.randomUUID=="function")return r.randomUUID()}catch{}try{if(typeof r?.getRandomValues=="function"){let e=r.getRandomValues(new Uint8Array(16));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}}catch{}}function Pt(){try{let r=localStorage.getItem(Fe);if(r)return r;let e=Ne();return e!==void 0&&localStorage.setItem(Fe,e),e}catch{return Le??(Le=Ne()),Le}}async function Ft(){let r=globalThis.crypto?.subtle;if(!r)return"";let e=navigator,t=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),n=await r.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("").slice(0,32)}function Lt(r){let e=new TextEncoder().encode(r),t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Nt(r){let e,t;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{t??(t=Ft().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let i=await t,a=Pt(),s={v:1,platform:"web",sdk:r.sdk.slice(0,64),ids:[...a?[{kind:"web_local",value:a.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 Lt(JSON.stringify(s))}catch{return}}}}var pe=Symbol.for("sekyro.web.clientContext"),fe=globalThis,Gt=fe[pe]??(fe[pe]=Nt({sdk:`@sekyro/web@${Pe}`}));function Ge(r){try{let e=r.getVideoTracks?.()[0];e&&Gt.noteCameraLabel(e.label)}catch{}}var he=Symbol.for("sekyro.web.cameraStreams"),ye=globalThis,Vt=ye[he]??(ye[he]=new Set);function Ve(r){try{Vt.add(r)}catch{}}var Wt=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ht=[/^(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 Kt(r){let e=(r??"").trim().toLowerCase();return e.length===0?"unknown":Wt.some(t=>e.includes(t))?"known_virtual":Ht.some(t=>t.test(e))?"platform":"unknown"}function We(r){if(typeof r!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(r))}catch{return!1}}function Ut(r=globalThis){return We(r.navigator?.mediaDevices?.getUserMedia)&&We(r.MediaStreamTrack?.prototype?.getSettings)}async function Bt(r,e=globalThis){let t=e.crypto?.subtle?.digest;if(typeof t=="function")try{let n=new Uint8Array(await t.call(e.crypto?.subtle,"SHA-256",new TextEncoder().encode(r)));return Array.from(n.subarray(0,8),i=>i.toString(16).padStart(2,"0")).join("")}catch{return}}async function He(r,e=globalThis){let t={};try{t=typeof r.getSettings=="function"?r.getSettings()??{}:{}}catch{t={}}let n={};if((t.facingMode==="user"||t.facingMode==="environment"||t.facingMode==="left"||t.facingMode==="right")&&(n.facingMode=t.facingMode),typeof t.frameRate=="number"&&Number.isFinite(t.frameRate)&&(n.frameRate=t.frameRate),typeof t.width=="number"&&Number.isFinite(t.width)&&(n.width=t.width),typeof t.height=="number"&&Number.isFinite(t.height)&&(n.height=t.height),typeof t.deviceId=="string"&&t.deviceId.length>0){let a=await Bt(t.deviceId,e);a!==void 0&&(n.deviceIdHash=a)}let i;try{i=r.label}catch{i=void 0}return{trackSettings:n,capabilitiesPresent:typeof r.getCapabilities=="function",labelClass:Kt(i),prototypesIntact:Ut(e)}}var ge=r=>Math.round(r*100)/100;function Ke(r){let e=r,t=typeof e?.requestVideoFrameCallback=="function",n=null,i=null,a=0,s=0,o=0,l=0,d=0,c=0,u=()=>{!t||e?.requestVideoFrameCallback===void 0||(n=e.requestVideoFrameCallback((m,f)=>{if(n=null,!t)return;let p=f.presentationTime;if(i!==null){let h=p-i.presentationTimeMs;s+=1;let y=h-o;o+=y/s,l+=y*(h-o)}typeof f.captureTime=="number"&&Number.isFinite(f.captureTime)&&(d+=p-f.captureTime,c+=1),a+=1,i={mediaTimeMs:f.mediaTime*1e3,presentationTimeMs:p},u()}))};return u(),{latest:()=>i,stats:()=>({n:a,meanGapMs:s===0?0:ge(o),stdGapMs:s<2?0:ge(Math.sqrt(l/(s-1))),captureLatencyMs:c===0?null:ge(d/c)}),stop:()=>{t&&(t=!1,n!==null&&e?.cancelVideoFrameCallback?.(n),n=null)}}}function Ue(r,e,t){return{...r,rvfc:e,rampPainter:t}}var zt=["rose","peach","sand","mint","sky","lilac"];var Xt=4,qt=4;function Yt(r){if(typeof r!="object"||r===null)return!1;let e=r;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length!==3||!e.colours.every(n=>zt.includes(n))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==3)return!1;let t=-1;for(let n of e.onsetsMs){if(typeof n!="number"||!Number.isFinite(n)||n<=t||n>=2e3)return!1;t=n}return!0}function Be(r,e){let t=e.now??(()=>performance.now()),n=Yt(r)?r:void 0,i=[],a=null,s=null,o=null,l=!1,d=null,c=p=>{d=p;try{e.paint(p)}catch{}},u=p=>{let h=e.frames?.()??null;return h!==null&&o!==null?h.mediaTimeMs+(p-h.presentationTimeMs)-o:p-(s??p)},m=(p,h,y=0)=>{if(l)return;let S=Math.max(0,p-u(t()));a=setTimeout(()=>{if(a=null,!l){if(y<Xt&&u(t())<p-qt){m(p,h,y+1);return}h()}},S)},f=p=>{if(n!==void 0){if(p>=3){m(2e3,()=>c(null));return}m(n.onsetsMs[p],()=>{let h=u(t());if(h>2e3){d!==null&&c(null);return}let y=n.colours[p];c(y);let S=i.length===0?0:i[i.length-1].tMs;i.push({tMs:Math.max(S,Math.round(h)),colour:y}),f(p+1)})}};return{started(p){if(n===void 0||l||s!==null)return;s=p;let h=e.frames?.()??null;o=h===null?null:h.mediaTimeMs+(p-h.presentationTimeMs),f(0)},stop(){l||(l=!0,a!==null&&clearTimeout(a),a=null,d!==null&&c(null))},report(){return n===void 0?void 0:{nonce:n.nonce,rendered:[...i]}}}}var M=1;function ze(){return typeof OffscreenCanvas=="function"&&typeof createImageBitmap=="function"&&typeof Worker=="function"}function Zt(r,e={}){let t=e.createDetector??x,n=null;r.onmessage=i=>{let a=i.data;if(a.v!==M){a.bitmap?.close?.();return}if(a.type==="init"){t(a.options).then(s=>{n=s;let o={v:M,type:"ready",tier:s.tier,...s.fallbackReason!==void 0?{fallbackReason:s.fallbackReason}:{}};r.postMessage(o)});return}if(a.type==="detect"){let s=o=>{let l={v:M,type:"result",id:a.id,observation:o};r.postMessage(l),a.bitmap.close?.()};if(n===null){s(null);return}n.detect(a.bitmap,a.streamWidth,a.streamHeight).then(s,()=>s(null))}}}typeof self<"u"&&typeof self.importScripts=="function"&&Zt(self);var Y=class r{constructor(e,t){this.pending=new Map;this.nextId=1;this.worker=e,this.tier=t.tier,t.fallbackReason!==void 0&&(this.fallbackReason=t.fallbackReason),e.addEventListener("message",n=>{let i=n.data;if(i.v!==M||i.type!=="result")return;let a=this.pending.get(i.id);this.pending.delete(i.id),a?.(i.observation)})}static create(e,t,n=1e4){return new Promise((i,a)=>{let s=setTimeout(()=>{e.removeEventListener("message",o),e.terminate(),a(new Error(`worker detector not ready within ${n}ms`))},n),o=d=>{let c=d.data;c.v!==M||c.type!=="ready"||(clearTimeout(s),e.removeEventListener("message",o),i(new r(e,c)))};e.addEventListener("message",o);let l={v:M,type:"init",options:t};e.postMessage(l)})}async detect(e,t,n){let i;try{typeof ImageBitmap<"u"&&e instanceof ImageBitmap?i=e:typeof createImageBitmap=="function"?i=await createImageBitmap(e):i=e}catch{return null}let a=this.nextId;return this.nextId+=1,new Promise(s=>{this.pending.set(a,s);let o={v:M,type:"detect",id:a,bitmap:i,streamWidth:t,streamHeight:n};this.worker.postMessage(o,[i])})}destroy(){for(let e of this.pending.values())e(null);this.pending.clear(),this.worker.terminate()}};var Qt=["size","centering","pose","exposure","sharpness","motion"];function Xe(r){if(r.accepted)return null;if(r.factors.presence<=0)return"no_face";let e="size";for(let t of Qt)r.factors[t]<r.factors[e]&&(e=t);return e}var D=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 n=Xe(e);if(n===null){this.acceptedMs+=t;return}let i=this.blocked[n]??{count:0,ms:0};i.count+=1,i.ms+=t,this.blocked[n]=i}summary(){let e={};for(let[t,n]of Object.entries(this.blocked))e[t]={count:n.count,ms:Math.round(n.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var it=1e3,Q="fcv3.hold_upright",at=200,j=4,st=600,ot=1e3,rt={sharpness:1,exposure:1,meanLuma:128};function nr(r,e){return e.width=r.videoWidth,e.height=r.videoHeight,e.getContext("2d").drawImage(r,0,0),new Promise((t,n)=>e.toBlob(i=>i?t(i):n(new Error("empty-keyframe")),"image/jpeg",.92))}function ir(){return K()==="phone"}var ve=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 n=this.handlers.get(e);return n||(n=new Set,this.handlers.set(e,n)),n.add(t),()=>n?.delete(t)}emit(e,t){for(let n of[...this.handlers.get(e)??[]])n(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??ir)(),this.setState("preflight");let n=re();if(n!=="OK"){this.fail(n==="INSECURE_CONTEXT"?"insecure":"unsupported");return}this.setState("acquiring");let i=t.getUserMedia??(d=>navigator.mediaDevices.getUserMedia(d)),a;this.cameraRequestedAt=this.now();try{a=await i(ae(se(),this.facing))}catch(d){if(e!==this.attempt)return;this.fail(te(d));return}if(Ge(a),Ve(a),e!==this.attempt){for(let d of a.getTracks())d.stop();return}this.stream=a;let s=a.getVideoTracks?.()[0];if(this.trackProvenance=s===void 0?null:He(s).catch(()=>null),this.facing=oe(a)??this.facing,t.video.srcObject=a,await t.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let d={v3AssetBaseUrl:t.v3AssetBaseUrl},c=t.createDetector??(t.createWorker!==void 0&&ze()?async()=>{try{return await Y.create(t.createWorker(),d)}catch{return x(d)}}:()=>x(d)),u;try{u=await c()}catch(m){e===this.attempt&&this.fail("models",m instanceof C?m.fallbackReason:sr(m));return}if(e!==this.attempt){u.destroy();return}this.detector=u,this.options.telemetry?.({type:"detector",tier:u.tier,fallbackReason:u.fallbackReason})}let o=de(),l=t.deviceClass??me(o);this.profiler=new N(l),this.options.telemetry?.({type:"profile",staticClass:l,activeClass:this.profiler.deviceClass,simd:o.simd}),this.gate=new w(t.thresholds??{}),this.blockStats=new D,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&Promise.resolve().then(()=>(tt(),et)).then(d=>be=d,()=>{}),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 n=new G({cadenceHz:t.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=n,n.start()}async detectTick(e){let{detector:t,gate:n,profiler:i}=this,a=this.options.video;if(e!==this.attempt||t===null||n===null||i===null||this.fired||a.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let s=i.deviceClass,o=this.now(),l=this.options.makeSnapshot?.(a,i.profile.inputWidth)??this.defaultSnapshot(a,i.profile.inputWidth),d=null;try{d=await t.detect(l,a.videoWidth,a.videoHeight)}catch{d=null}if(e!==this.attempt||this.fired)return;i.record(this.now()-o),i.deviceClass!==s&&this.startScheduler(e);let c=d===null?rt:this.options.measureQuality?.(a,d.box)??this.defaultQuality(a,d.box),u=n.tick({timestampMs:this.now(),observation:d,quality:c,frameWidth:a.videoWidth,frameHeight:a.videoHeight});u.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=u.at),this.blockStats?.record(u),!u.ready&&u.at-this.lastGateSnapshotAt>=it&&(this.lastGateSnapshotAt=u.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:u.p,q:u.q,factors:u.factors,attempt:e}),u.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=u.guidanceKey,this.emit("guidance",{key:u.guidanceKey})),u.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=u.at,this.fire(e))}async fire(e){let{options:t}=this,n=this.scheduler;n?.stop(),this.reportGate(!0);let i=n?.stats()??{degradeCount:0,meanDetectMs:0},a=[...this.carriedMeans,...i.meanDetectMs>0?[i.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+i.degradeCount,meanDetectMs:a.length===0?0:a.reduce((g,E)=>g+E,0)/a.length});let s=t.mode??"clip",o=t.rankKeyframes?.()&&be?be.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(s==="photo"){let g=this.watchRotation(e,null),E=await o;if(g(),e!==this.attempt)return;if(E===null){this.fail("generic");return}let ct=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:E.blob,previewDataUrl:E.previewDataUrl,...ct});return}this.setState("recording");let l=t.createRecorder?.()??new P,d=this.stream;if(d===null){this.fail("generic");return}let c=Ke(t.video),u=t.screenRamp?.(),m=u!==void 0,f=Be(u,{paint:g=>{(g===null||e===this.attempt)&&this.emit("ramp",{colour:g})},now:()=>this.now(),frames:c.latest});this.ramp=f;let p=()=>{c.stop(),f.stop(),this.ramp===f&&(this.ramp=null)},h=this.watchRotation(e,l),y=null;o.then(g=>{y=g},()=>{});let S=()=>{e===this.attempt&&y!==null&&this.emit("frozen",{previewDataUrl:y.previewDataUrl})},v,k;try{[v,k]=await Promise.all([l.record(d,S,()=>f.started(this.now())),o])}catch(g){if(h(),p(),e!==this.attempt)return;let E=g.kind;this.fail(E==="cliptoolarge"?"cliptoolarge":"recorder");return}h();let T=c.stats();if(p(),e!==this.attempt)return;if(A(v.blob)){this.fail("cliptoolarge");return}if(k===null){this.fail("generic");return}let I=f.report(),$=await this.provenance(T,m);e===this.attempt&&this.finishCapture({clip:v.blob,clipMimeType:v.mimeType,keyframe:k.blob,previewDataUrl:k.previewDataUrl,...I!==void 0&&I.rendered.length>0?{screenRamp:I}:{},...$})}async provenance(e,t){let n=this.trackProvenance;if(n===null)return{};let i,a=new Promise(o=>{i=setTimeout(()=>o(null),ot)}),s=await Promise.race([n,a]);return clearTimeout(i),s===null?{}:{provenance:Ue(s,e,t)}}isLandscape(){let e=this.options.video;return this.uprightGuard&&e.videoWidth>e.videoHeight}holdUpright(e){this.gate?.reset(),this.emit("checks",{engine:"v3",progress:0,q:0,factors:{presence:0,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==Q&&(this.lastGuidanceKey=Q,this.emit("guidance",{key:Q}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let n=this.options.video,i=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){o();return}n.videoWidth>0&&this.isLandscape()&&(o(),this.abortRecording(e,t))},a=setInterval(i,at);n.addEventListener?.("resize",i);let s=!1;function o(){s||(s=!0,clearInterval(a),n.removeEventListener?.("resize",i))}return o}abortRecording(e,t){if(e!==this.attempt)return;this.attempt+=1;let n=this.attempt;try{t?.stop()}catch{}this.ramp?.stop(),this.ramp=null,this.fired=!1,this.captureCompleteAt=null,this.gate=new w(this.options.thresholds??{}),this.blockStats=new D,this.lastGateSnapshotAt=this.now(),this.lastGuidanceKey=null,this.setState("positioning"),this.positioningStartedAt=this.now(),this.holdUpright(n),this.startScheduler(n)}async collectKeyframes(e){let t=this.options.captureKeyframe??(a=>this.defaultKeyframe(a)),n=st/(j-1),i=null;for(let a=0;a<j;a+=1){if(e!==this.attempt)return i;try{let s=await t(this.options.video);(i===null||s.sharpness>i.sharpness)&&(i=s)}catch{}a<j-1&&await ar(n)}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=(n,i,a)=>{i!==null&&a!==null&&(e[n]=Math.max(0,Math.round(a-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"),n=await(this.facing==="user"?ne:nr)(e,t),i=t.toDataURL("image/jpeg",.92);return{blob:n,previewDataUrl:i,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let n=this.snapshotCanvas??document.createElement("canvas"),i=t/Math.max(1,e.videoWidth),a=Math.max(1,Math.round(e.videoWidth*i)),s=Math.max(1,Math.round(e.videoHeight*i)),o=n.getContext("2d");return o===null?e:(n.width!==a&&(n.width=a),n.height!==s&&(n.height=s),o.drawImage(e,0,0,a,s),this.snapshotCanvas=n,n)}catch{return e}}defaultQuality(e,t){let n=nt(e,t,96);return n===null?rt:{sharpness:q(n),exposure:le(n),meanLuma:X(n)}}centerSharpness(e){let t=_(e),n=nt(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return n===null?0:q(n)}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,n=this.profiler;if(t===null||n===null)return;let i=t.summary();e&&(this.blockStats=null),i.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:n.deviceClass,cadenceHz:n.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()}},be;function ar(r){return new Promise(e=>setTimeout(e,r))}function sr(r){return r instanceof Error?r.message:String(r)}function nt(r,e,t){try{let n=document.createElement("canvas"),i=t/Math.max(1,e.width);n.width=Math.max(1,Math.round(e.width*i)),n.height=Math.max(1,Math.round(e.height*i));let a=n.getContext("2d");return a===null?null:(a.drawImage(r,e.x,e.y,e.width,e.height,0,0,n.width,n.height),a.getImageData(0,0,n.width,n.height))}catch{return null}}0&&(module.exports={CENTERED_FACTOR,CIRCLE_RADIUS_FACTOR,CLIP_MS,CaptureSessionV3,ClipError,ClipRecorder,DEFAULT_CLIP_MIME,DEFAULT_TIER_ORDER,DEFAULT_V3_ASSET_BASE_URL,DEVICE_PROFILES,DetectScheduler,DetectorLadderError,DeviceProfiler,EXPOSURE_BAND,FaceGateV3,GATE_SNAPSHOT_MS,GateBlockStats,HOLD_UPRIGHT_KEY,IN_CIRCLE_FACTOR,KEYFRAME_CANDIDATES,KEYFRAME_WINDOW_MS,MAX_CLIP_BYTES,MIME_CANDIDATES,PHONE_MAX_SHORT_SIDE,PROVENANCE_WAIT_MS,SHARP_REF,STOP_GRACE_MS,TIMESLICE_MS,UPRIGHT_WATCH_MS,V3_GATE_DEFAULTS,VIDEO_BPS,blockReasonOf,buildCaptureConstraints,buildLivenessV2FormData,cameraPreflight,captureMirroredKeyframe,classifyDevice,createDetector,detectFormFactor,detectIsMobile,errorCopy,exposure,extForMime,intrinsicSize,isClipTooLarge,isMediaRecorderSupported,mapGetUserMediaError,meanLuma,pickMimeType,probeDevice,sharpness,toStreamPixels,trackFacingMode,uiCopy});
|
|
1
|
+
"use strict";var dt=Object.create;var K=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var pt=Object.getOwnPropertyNames;var ft=Object.getPrototypeOf,ht=Object.prototype.hasOwnProperty;var gt=(r,e)=>()=>(r&&(e=r(r=0)),e);var Se=(r,e)=>{for(var t in e)K(r,t,{get:e[t],enumerable:!0})},ke=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of pt(e))!ht.call(r,i)&&i!==t&&K(r,i,{get:()=>e[i],enumerable:!(n=mt(e,i))||n.enumerable});return r};var yt=(r,e,t)=>(t=r!=null?dt(ft(r)):{},ke(e||!r||!r.__esModule?K(t,"default",{value:r,enumerable:!0}):t,r)),bt=r=>ke(K({},"__esModule",{value:!0}),r);var rt={};Se(rt,{RANK_CANDIDATES:()=>tr,RANK_TOLERANCE:()=>Q,RANK_WINDOW_MS:()=>rr,ROLL_ZERO_DEG:()=>ir,SHARPNESS_REPORT_MAX:()=>et,YAW_REPORT_MAX:()=>Je,YAW_ZERO_IOD:()=>nr,collectRankedKeyframes:()=>tt,default:()=>sr,featuresOf:()=>je,frontalOf:()=>Qe,rankKeyframes:()=>$e});function Qe(r){let e=r.eyes;if(e===void 0)return{frontal:1,yaw:null,roll:null};let t=e.right.x-e.left.x,n=e.right.y-e.left.y,i=t*t+n*n;if(i===0)return{frontal:1,yaw:null,roll:null};let a=Math.abs(Math.atan2(n,Math.abs(t))*180/Math.PI),s=Ze(1-a/30),o=null,u=r.nose;if(u!==void 0){let d=(e.left.x+e.right.x)/2,c=(e.left.y+e.right.y)/2;o=Math.abs(((u.x-d)*t+(u.y-c)*n)/i),s*=Ze(1-o/.5)}return{frontal:s,yaw:o,roll:a}}function je(r,e){return r===null?{face:!1,frontal:0,yaw:null,roll:null,eyes:null,score:0,sharpness:e}:{face:!0,...Qe(r),eyes:null,score:r.score,sharpness:e}}function $e(r){let e=r.map((i,a)=>a),t=(i,a)=>{let s=Number.NEGATIVE_INFINITY;for(let o of e)s=Math.max(s,i(r[o]));e=e.filter(o=>i(r[o])>=s-a)};t(i=>i.frontal,Q.frontal),t(i=>i.eyes??1,Q.eyes),t(i=>i.score,Q.score);let n=-1;for(let i of e)(n===-1||r[i].sharpness>r[n].sharpness)&&(n=i);return n}function ar(r){return{face:r.face,frontal:O(r.frontal),...r.yaw!==null?{yaw:Math.min(O(r.yaw),Je)}:{},...r.roll!==null?{roll:O(r.roll)}:{},...r.eyes!==null?{eyes:O(r.eyes)}:{},score:O(r.score),sharpness:Math.min(O(r.sharpness),et)}}async function tt(r,e){let{options:t}=r,n=t.video,i=t.now??(()=>performance.now()),a=t.captureKeyframe??(m=>r.defaultKeyframe(m)),s=600/3,o=[],u=[],d=0;for(let m=0;m<4;m+=1){if(e!==r.attempt)return null;let f=r.detector,p=Promise.resolve(null),h,g=0;try{if(f!==null){let _=r.profiler?.profile.inputWidth??160,I=t.makeSnapshot?.(n,_)??r.defaultSnapshot(n,_);h=a(n).then(y=>(g=i(),y));let J=i();p=f.detect(I,n.videoWidth,n.videoHeight).then(y=>(d+=i()-J,y),()=>null)}else h=a(n).then(_=>(g=i(),_));let[v,M]=await Promise.all([h,p]);o.push(v),u.push(je(M,v.sharpness))}catch{h?.catch(()=>{})}let E=g>0?Math.max(0,i()-g):0;m<3&&await new Promise(v=>setTimeout(v,Math.max(0,s-E)))}if(e!==r.attempt)return null;let c=$e(u);if(c===-1)return null;let l=0;u.forEach((m,f)=>{m.sharpness>u[l].sharpness&&(l=f)});try{t.telemetry?.({type:"keyframe",tier:r.detector?.tier??null,chosen:c,sharpest:l,detectMs:Math.round(d),candidates:u.map(ar)})}catch{}return o[c]??null}var tr,rr,nr,ir,Q,Ze,O,Je,et,sr,nt=gt(()=>{"use strict";tr=4,rr=600,nr=.5,ir=30,Q={frontal:.1,eyes:.1,score:.05},Ze=r=>r<0?0:r>1?1:r;O=r=>Number.isFinite(r)?Math.round(r*1e3)/1e3:0,Je=99,et=999999;sr=tt});var dr={};Se(dr,{CENTERED_FACTOR:()=>xt,CIRCLE_RADIUS_FACTOR:()=>Ct,CLIP_MS:()=>_e,CaptureSessionV3:()=>Ee,ClipError:()=>b,ClipRecorder:()=>P,DEFAULT_CLIP_MIME:()=>W,DEFAULT_TIER_ORDER:()=>Oe,DEFAULT_V3_ASSET_BASE_URL:()=>De,DEVICE_PROFILES:()=>Pe,DetectScheduler:()=>G,DetectorLadderError:()=>T,DeviceProfiler:()=>N,EXPOSURE_BAND:()=>L,FaceGateV3:()=>w,GATE_SNAPSHOT_MS:()=>st,GateBlockStats:()=>D,HOLD_UPRIGHT_KEY:()=>j,IN_CIRCLE_FACTOR:()=>Tt,KEYFRAME_CANDIDATES:()=>$,KEYFRAME_WINDOW_MS:()=>ct,MAX_CLIP_BYTES:()=>H,MIME_CANDIDATES:()=>Me,PHONE_MAX_SHORT_SIDE:()=>xe,PROVENANCE_WAIT_MS:()=>ut,SHARP_REF:()=>Tr,STOP_GRACE_MS:()=>Te,TIMESLICE_MS:()=>Ce,UPRIGHT_WATCH_MS:()=>ot,V3_GATE_DEFAULTS:()=>Ae,VIDEO_BPS:()=>ae,blockReasonOf:()=>Ye,buildCaptureConstraints:()=>se,buildLivenessV2FormData:()=>Et,cameraPreflight:()=>ne,captureMirroredKeyframe:()=>ie,classifyDevice:()=>pe,createDetector:()=>x,detectFormFactor:()=>U,detectIsMobile:()=>oe,errorCopy:()=>St,exposure:()=>le,extForMime:()=>ee,intrinsicSize:()=>C,isClipTooLarge:()=>A,isMediaRecorderSupported:()=>vt,mapGetUserMediaError:()=>re,meanLuma:()=>q,pickMimeType:()=>te,probeDevice:()=>me,sharpness:()=>Y,toStreamPixels:()=>F,trackFacingMode:()=>ce,uiCopy:()=>kt});module.exports=bt(dr);var Me=["video/mp4;codecs=avc1.42E01E,mp4a.40.2","video/mp4;codecs=avc1.42E01E","video/mp4","video/webm;codecs=vp9,opus","video/webm;codecs=vp9","video/webm;codecs=vp8,opus","video/webm;codecs=vp8","video/webm"];function te(){let r=globalThis.MediaRecorder;return!r||typeof r.isTypeSupported!="function"?"":Me.find(e=>r.isTypeSupported(e))??""}var W="video/webm";function re(r){if(r instanceof TypeError)return"insecure";switch(r?.name??""){case"NotAllowedError":case"PermissionDeniedError":return"permission";case"NotFoundError":case"DevicesNotFoundError":return"notfound";case"NotReadableError":case"TrackStartError":return"inuse";case"OverconstrainedError":case"ConstraintNotSatisfiedError":return"overconstrained";default:return"generic"}}function ne(){let r=globalThis;if(typeof r.window<"u"&&r.window.isSecureContext===!1)return"INSECURE_CONTEXT";let e=r.navigator?.mediaDevices;return!e||typeof e.getUserMedia!="function"?"UNSUPPORTED":"OK"}function vt(){let r=globalThis.MediaRecorder;return typeof r<"u"&&typeof r.isTypeSupported=="function"}var H=8*1024*1024;function A(r){return r.size>H}function ee(r){let e=(r||"").toLowerCase();return e.startsWith("image/jpeg")?"jpg":e.startsWith("video/mp4")?"mp4":(e.startsWith("video/webm"),"webm")}function Et(r){let{token:e,clip:t,keyframe:n}=r,i=r.ts??Date.now(),a=t.type||W,s=n.type||"image/jpeg",o=new FormData;return o.append("token",e),o.append("clip",new File([t],`liveness-${i}.${ee(a)}`,{type:a})),o.append("keyframe",new File([n],`keyframe-${i}.${ee(s)}`,{type:s})),o}function ie(r,e,t=.92){return new Promise((n,i)=>{let a=r.videoWidth,s=r.videoHeight;if(!a||!s){i(new Error("video-not-ready"));return}let o=e.getContext("2d");if(!o){i(new Error("no-2d-context"));return}e.width=a,e.height=s,o.scale(-1,1),o.drawImage(r,-a,0),e.toBlob(u=>u?n(u):i(new Error("empty-keyframe")),"image/jpeg",t)})}var St={permission:{key:"fcv2.err.permission",fr:"Autorisez la cam\xE9ra dans les r\xE9glages du navigateur (ic\xF4ne cam\xE9ra dans la barre d\u2019adresse), puis r\xE9essayez."},notfound:{key:"fcv2.err.notfound",fr:"Aucune cam\xE9ra d\xE9tect\xE9e. Branchez ou activez une cam\xE9ra, puis r\xE9essayez."},inuse:{key:"fcv2.err.inuse",fr:"La cam\xE9ra est utilis\xE9e par une autre application. Fermez-la puis r\xE9essayez."},overconstrained:{key:"fcv2.err.overconstrained",fr:"La cam\xE9ra ne prend pas en charge les r\xE9glages demand\xE9s. Nouvel essai en cours\u2026"},insecure:{key:"fcv2.err.insecure",fr:"La cam\xE9ra n\xE9cessite une connexion s\xE9curis\xE9e (HTTPS). Ouvrez la page en HTTPS."},unsupported:{key:"fcv2.err.unsupported",fr:"Votre navigateur ne prend pas en charge l\u2019enregistrement vid\xE9o. Utilisez un navigateur r\xE9cent."},generic:{key:"fcv2.err.generic",fr:"Cam\xE9ra indisponible. R\xE9essayez ou contactez le support."}},kt={recording:{key:"fcv2.recording",fr:"Enregistrement en cours\u2026"},uploading:{key:"fcv2.uploading",fr:"Envoi en cours\u2026"},clipTooLarge:{key:"fcv2.err.cliptoolarge",fr:"La vid\xE9o est trop volumineuse. R\xE9essayez dans un endroit mieux \xE9clair\xE9."},retry:{key:"fcv2.retry",fr:"R\xE9essayer"},listen:{key:"fcv2.listen",fr:"\xC9couter"}};var _e=2500,Ce=1e3,Te=1500,ae=25e5,b=class extends Error{constructor(e,t){super(t??e),this.kind=e}},P=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,n){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=te();return new Promise((a,s)=>{let o;try{o=new MediaRecorder(e,i?{mimeType:i,videoBitsPerSecond:ae}:{videoBitsPerSecond:ae})}catch{try{o=new MediaRecorder(e)}catch{s(new b("unsupported"));return}}this.recorder=o;let u=c=>{this.settled||(this.settled=!0,this.clearTimers(),c())},d=()=>u(()=>{let c=o.mimeType||i||W,l=new Blob(this.chunks,{type:c});if(l.size===0){s(new b("generic","empty clip"));return}if(A(l)){s(new b("cliptoolarge"));return}a({blob:l,mimeType:c})});if(o.ondataavailable=c=>{c.data&&c.data.size&&(this.chunks.push(c.data),this.bytes+=c.data.size,this.bytes>H&&u(()=>{try{o.state!=="inactive"&&o.stop()}catch{}s(new b("cliptoolarge"))}))},o.onstop=d,o.onerror=()=>u(()=>s(new b("generic"))),n!==void 0){let c=!1;o.onstart=()=>{if(!(c||this.settled)){c=!0;try{n()}catch{}}}}try{o.start(Ce)}catch{u(()=>s(new b("generic")));return}this.hardStopTimer=setTimeout(()=>{if(this.settled||t?.(),o.state!=="inactive"){try{o.stop()}catch{d()}this.graceTimer=setTimeout(d,Te)}else d()},_e)})}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}};function se(r,e){return{video:{width:{ideal:1280,max:1280},height:{ideal:720,max:720},facingMode:e,frameRate:{ideal:24,max:30}},audio:!1}}var xe=600;function U(){if(typeof window>"u"||typeof navigator>"u")return"desktop";let r=String(navigator.userAgent??"");if(/iPhone|iPod/i.test(r))return"phone";if(/iPad/i.test(r))return"tablet";if(/Android/i.test(r))return/Mobile/i.test(r)?"phone":"tablet";if(/BlackBerry|IEMobile|Opera Mini/i.test(r))return"phone";if(Number(navigator.maxTouchPoints??0)<=1)return"desktop";if(/Macintosh/.test(r))return"tablet";if(!_t())return"desktop";let t=Mt();return t>0&&t<xe?"phone":"tablet"}function oe(){return U()!=="desktop"}function Mt(){try{let r=window.screen,e=Number(r?.width??0),t=Number(r?.height??0);return e>0&&t>0?Math.min(e,t):0}catch{return 0}}function ce(r){try{let t=r?.getVideoTracks?.()[0]?.getSettings?.().facingMode;return t==="user"||t==="environment"?t:null}catch{return null}}function _t(){try{return typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches}catch{return!1}}var Ct=.45,Tt=.9,xt=.4;var Re=1e4,B=class r{constructor(e,t){this.tier="blaze";this.inner=e,t!==void 0&&(this.fallbackReason=t)}static async create(e,t){let n=await import("@mediapipe/tasks-vision"),i=await n.FilesetResolver.forVisionTasks(e),a=await n.FaceDetector.createFromOptions(i,{baseOptions:{modelAssetPath:`${e}/blaze_face_short_range.tflite`,delegate:"CPU"},runningMode:"IMAGE"});return new r(a,t)}async detect(e,t,n){let i;try{i=this.inner.detect(e).detections}catch{return null}let a=Rt(i);if(a?.boundingBox===void 0)return null;let s=C(e),o=wt(a.keypoints,s),u=a.keypoints?.[2],d={box:{x:a.boundingBox.originX,y:a.boundingBox.originY,width:a.boundingBox.width,height:a.boundingBox.height},...o!==void 0?{eyes:o}:{},...u!==void 0?{nose:{x:u.x*s.width,y:u.y*s.height}}:{},score:a.categories[0]?.score??0};return F(d,e,t,n)}destroy(){try{this.inner.close()}catch{}}};function Rt(r){let e,t=-1;for(let n of r){let i=n.categories[0]?.score??0;i>t&&(e=n,t=i)}return e}function wt(r,e){let t=r?.[0],n=r?.[1];if(t===void 0||n===void 0)return;let i=o=>({x:o.x*e.width,y:o.y*e.height}),[a,s]=[i(t),i(n)];return a.x<=s.x?{left:a,right:s}:{left:s,right:a}}function Dt(){if(typeof OffscreenCanvas=="function")return new OffscreenCanvas(2,2);let r=document.createElement("canvas");return r.width=2,r.height=2,r}async function we(){let r=globalThis.FaceDetector;if(typeof r!="function")return{ok:!1,reason:"unsupported"};try{let e=new r({fastMode:!0,maxDetectedFaces:1});return await e.detect(Dt()),{ok:!0,instance:e}}catch(e){return{ok:!1,reason:`smoke_failed:${e instanceof Error?e.message:String(e)}`}}}var z=class{constructor(e,t){this.tier="native";this.inner=e,t!==void 0&&(this.fallbackReason=t)}async detect(e,t,n){let i;try{i=await this.inner.detect(e)}catch{return null}let a=i[0];if(a===void 0)return null;let s=Ot(a.landmarks),o={box:{x:a.boundingBox.x,y:a.boundingBox.y,width:a.boundingBox.width,height:a.boundingBox.height},...s!==void 0?{eyes:s}:{},score:1};return F(o,e,t,n)}destroy(){}};function Ot(r){if(r===void 0)return;let e=r.filter(i=>i.type==="eye").map(i=>i.locations[0]).filter(i=>i!==void 0),[t,n]=e;if(!(t===void 0||n===void 0))return t.x<=n.x?{left:t,right:n}:{left:n,right:t}}var De="/models-v3",Oe=["native","blaze"],T=class extends Error{constructor(e){super(`no detector tier available (${e})`),this.name="DetectorLadderError",this.fallbackReason=e}};function C(r){let e=r;if(typeof e.videoWidth=="number"&&e.videoWidth>0)return{width:e.videoWidth,height:e.videoHeight??0};if(typeof e.naturalWidth=="number"&&e.naturalWidth>0)return{width:e.naturalWidth,height:e.naturalHeight??0};let t=typeof e.width=="number"?e.width:0,n=typeof e.height=="number"?e.height:0;return{width:t,height:n}}function F(r,e,t,n){let i=C(e),a=i.width>0?t/i.width:1,s=i.height>0?n/i.height:1,o=u=>({x:u.x*a,y:u.y*s});return{box:{x:r.box.x*a,y:r.box.y*s,width:r.box.width*a,height:r.box.height*s},...r.eyes!==void 0?{eyes:{left:o(r.eyes.left),right:o(r.eyes.right)}}:{},...r.nose!==void 0?{nose:o(r.nose)}:{},score:r.score}}function It(r){return r instanceof Error?r.message:String(r)}async function x(r){let e=r.preferred??Oe,t=[];for(let n of e){if(n==="native"){let i=await we();if(i.ok)return new z(i.instance,ue(t));t.push(`native:${i.reason}`);continue}try{return await At(B.create(r.v3AssetBaseUrl??De,ue(t)),r.blazeInitTimeoutMs??Re)}catch(i){t.push(i instanceof X?"blaze:blaze_init_timeout":`blaze:${It(i)}`)}}throw new T(ue(t)??"no_tier_available")}function ue(r){return r.length>0?r.join("; "):void 0}var X=class extends Error{};function At(r,e){return new Promise((t,n)=>{let i=setTimeout(()=>{n(new X(`init exceeded ${e}ms`)),r.then(a=>a.destroy(),()=>{})},e);r.then(a=>{clearTimeout(i),t(a)},a=>{clearTimeout(i),n(a)})})}var Tr=180,L=[100,190],Pt=64;function Ie(r,e){return .299*(r[e]??0)+.587*(r[e+1]??0)+.114*(r[e+2]??0)}function q(r){let{data:e,width:t,height:n}=r,i=t*n;if(i===0)return 0;let a=0;for(let s=0;s<i;s+=1)a+=Ie(e,s*4);return a/i}function Y(r){let{data:e,width:t,height:n}=r;if(t<3||n<3)return 0;let i=new Float32Array(t*n);for(let c=0;c<i.length;c+=1)i[c]=Ie(e,c*4);let a=0,s=0,o=0;for(let c=1;c<n-1;c+=1)for(let l=1;l<t-1;l+=1){let m=c*t+l,f=(i[m-t]??0)+(i[m-1]??0)+(i[m+1]??0)+(i[m+t]??0)-4*(i[m]??0);a+=f,s+=f*f,o+=1}if(o===0)return 0;let u=a/o,d=s/o-u*u;return Math.min(1,Math.max(0,d)/180)}function le(r){let e=q(r),[t,n]=L,i=e<t?t-e:e>n?e-n:0;return Math.max(0,1-i/Pt)}var Ae=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}),R=r=>Math.min(1,Math.max(0,r)),w=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...Ae,...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:n,timestampMs:i}=e,a=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let s={presence:0,centering:0,size:0,pose:0,sharpness:R(n.sharpness),exposure:R(n.exposure),motion:1};if(t!==null){s.presence=1;let c=this.geometryOf(t,e);s.centering=c.centering,s.size=c.size,s.pose=c.pose,s.motion=this.motionOf(c.center,c.iod,i)}else this.lastCenter=null,this.velocityEma=0;let o=Math.min(s.presence,s.centering,s.size,s.pose,s.sharpness,s.exposure,s.motion);this.p=R(this.p+(o>=this.t.Q_GOOD?this.t.RISE_PER_S*o:-this.t.FALL_PER_S*(1-o))*a),this.qWindow.push({at:i,q:o}),this.qWindow=this.qWindow.filter(c=>c.at>=i-this.t.READY_WINDOW_MS);let u=this.qWindow.map(c=>c.q);if(u.length>=3){let c=Math.min(...u),l=u.indexOf(c);u=u.filter((m,f)=>f!==l)}let d=this.p>=1&&u.every(c=>c>=this.t.Q_GOOD);return{at:i,q:o,p:this.p,factors:s,guidanceKey:this.guidanceOf(s,n,o),ready:d,accepted:o>=this.t.Q_GOOD}}geometryOf(e,t){let{box:n,eyes:i}=e,a={x:t.frameWidth/2,y:t.frameHeight/2},s=Math.min(t.frameWidth,t.frameHeight),o=i!==void 0?{x:(i.left.x+i.right.x)/2,y:(i.left.y+i.right.y)/2}:{x:n.x+n.width/2,y:n.y+n.height/2-this.t.BOX_EYE_OFFSET_FACTOR*n.height},u=i!==void 0?Math.hypot(i.right.x-i.left.x,i.right.y-i.left.y):this.t.IOD_BOX_PROXY_FACTOR*n.width,d=Math.hypot(o.x-a.x,o.y-a.y),c=u<=0?0:1-R(d/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*u)),l=s>0?u/s:0;this.lastSizeDirection=l<this.t.SIZE_IDEAL_MIN?"far":l>this.t.SIZE_IDEAL_MAX?"close":"ideal";let m;l<this.t.SIZE_HARD_MIN||l>this.t.SIZE_HARD_MAX?m=0:l<this.t.SIZE_IDEAL_MIN?m=(l-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):l>this.t.SIZE_IDEAL_MAX?m=(this.t.SIZE_HARD_MAX-l)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):m=1;let f=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;f=1-R(p/this.t.ROLL_MAX_DEG)}return{center:o,iod:u,centering:c,size:m,pose:f}}motionOf(e,t,n){let i=this.lastCenter;if(this.lastCenter={...e,at:n},i===null||t<=0)return 1;let a=(n-i.at)/1e3;if(a<=0)return 1;let s=Math.hypot(e.x-i.x,e.y-i.y)/t/a;s<=this.t.MOTION_DEADBAND_IOD_PER_S&&(s=0);let o=1-Math.exp(-a/this.t.MOTION_TAU_S);return this.velocityEma=o*s+(1-o)*this.velocityEma,1-R(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,n){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(n<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"]],a=i[0];for(let s of i)e[s[0]]<e[a[0]]&&(a=s);return a[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(L[0]+L[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Pe=Object.freeze({LOW:Object.freeze({cadenceHz:5,inputWidth:128,animations:"reduced"}),MID:Object.freeze({cadenceHz:8,inputWidth:160,animations:"full"}),HIGH:Object.freeze({cadenceHz:10,inputWidth:192,animations:"full"})}),Ft=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);function me(){let r=typeof navigator>"u"?void 0:navigator,e=!1;try{e=typeof WebAssembly<"u"&&WebAssembly.validate(Ft)}catch{e=!1}return{cores:r?.hardwareConcurrency??2,memGB:r?.deviceMemory??null,simd:e}}function pe(r){let e=r.memGB??4;return r.cores<4||e<3?"LOW":r.cores>=8&&e>=6?"HIGH":"MID"}var de=["LOW","MID","HIGH"],N=class{constructor(e){this.samples=[];this.adjusted=!1;this.current=e}get deviceClass(){return this.current}get profile(){return Pe[this.current]}record(e){if(this.adjusted||this.samples.length>=10)return this.current;if(this.samples.push(e),this.samples.length<10)return this.current;this.adjusted=!0;let t=this.samples.reduce((n,i)=>n+i,0)/this.samples.length;if(t>70)this.current="LOW";else if(t<25){let n=de.indexOf(this.current);this.current=de[Math.min(de.length-1,n+1)]??this.current}return this.current}};var G=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,n)=>t+n,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 Fe="0.1.0-rc.19";var Le="sekyro.did",Ne;function Ge(){let r=globalThis.crypto;try{if(typeof r?.randomUUID=="function")return r.randomUUID()}catch{}try{if(typeof r?.getRandomValues=="function"){let e=r.getRandomValues(new Uint8Array(16));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}}catch{}}function Lt(){try{let r=localStorage.getItem(Le);if(r)return r;let e=Ge();return e!==void 0&&localStorage.setItem(Le,e),e}catch{return Ne??(Ne=Ge()),Ne}}async function Nt(){let r=globalThis.crypto?.subtle;if(!r)return"";let e=navigator,t=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),n=await r.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("").slice(0,32)}function Gt(r){let e=new TextEncoder().encode(r),t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Vt(r){let e,t;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{t??(t=Nt().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let i=await t,a=Lt(),s={v:1,platform:"web",sdk:r.sdk.slice(0,64),ids:[...a?[{kind:"web_local",value:a.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 Gt(JSON.stringify(s))}catch{return}}}}var fe=Symbol.for("sekyro.web.clientContext"),he=globalThis,Kt=he[fe]??(he[fe]=Vt({sdk:`@sekyro/web@${Fe}`}));function Ve(r){try{let e=r.getVideoTracks?.()[0];e&&Kt.noteCameraLabel(e.label)}catch{}}var ge=Symbol.for("sekyro.web.cameraStreams"),ye=globalThis,Wt=ye[ge]??(ye[ge]=new Set);function Ke(r){try{Wt.add(r)}catch{}}var Ht=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ut=[/^(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 Bt(r){let e=(r??"").trim().toLowerCase();return e.length===0?"unknown":Ht.some(t=>e.includes(t))?"known_virtual":Ut.some(t=>t.test(e))?"platform":"unknown"}function We(r){if(typeof r!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(r))}catch{return!1}}function zt(r=globalThis){return We(r.navigator?.mediaDevices?.getUserMedia)&&We(r.MediaStreamTrack?.prototype?.getSettings)}async function Xt(r,e=globalThis){let t=e.crypto?.subtle?.digest;if(typeof t=="function")try{let n=new Uint8Array(await t.call(e.crypto?.subtle,"SHA-256",new TextEncoder().encode(r)));return Array.from(n.subarray(0,8),i=>i.toString(16).padStart(2,"0")).join("")}catch{return}}async function He(r,e=globalThis){let t={};try{t=typeof r.getSettings=="function"?r.getSettings()??{}:{}}catch{t={}}let n={};if((t.facingMode==="user"||t.facingMode==="environment"||t.facingMode==="left"||t.facingMode==="right")&&(n.facingMode=t.facingMode),typeof t.frameRate=="number"&&Number.isFinite(t.frameRate)&&(n.frameRate=t.frameRate),typeof t.width=="number"&&Number.isFinite(t.width)&&(n.width=t.width),typeof t.height=="number"&&Number.isFinite(t.height)&&(n.height=t.height),typeof t.deviceId=="string"&&t.deviceId.length>0){let a=await Xt(t.deviceId,e);a!==void 0&&(n.deviceIdHash=a)}let i;try{i=r.label}catch{i=void 0}return{trackSettings:n,capabilitiesPresent:typeof r.getCapabilities=="function",labelClass:Bt(i),prototypesIntact:zt(e)}}var be=r=>Math.round(r*100)/100;function Ue(r){let e=r,t=typeof e?.requestVideoFrameCallback=="function",n=null,i=null,a=0,s=0,o=0,u=0,d=0,c=0,l=()=>{!t||e?.requestVideoFrameCallback===void 0||(n=e.requestVideoFrameCallback((m,f)=>{if(n=null,!t)return;let p=f.presentationTime;if(i!==null){let h=p-i.presentationTimeMs;s+=1;let g=h-o;o+=g/s,u+=g*(h-o)}typeof f.captureTime=="number"&&Number.isFinite(f.captureTime)&&(d+=p-f.captureTime,c+=1),a+=1,i={mediaTimeMs:f.mediaTime*1e3,presentationTimeMs:p},l()}))};return l(),{latest:()=>i,stats:()=>({n:a,meanGapMs:s===0?0:be(o),stdGapMs:s<2?0:be(Math.sqrt(u/(s-1))),captureLatencyMs:c===0?null:be(d/c)}),stop:()=>{t&&(t=!1,n!==null&&e?.cancelVideoFrameCallback?.(n),n=null)}}}function Be(r,e,t){return{...r,rvfc:e,rampPainter:t}}var qt=["rose","peach","sand","mint","sky","lilac"];var Yt=4,Zt=4;function Qt(r){if(typeof r!="object"||r===null)return!1;let e=r;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length!==3||!e.colours.every(n=>qt.includes(n))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==3)return!1;let t=-1;for(let n of e.onsetsMs){if(typeof n!="number"||!Number.isFinite(n)||n<=t||n>=2e3)return!1;t=n}return!0}function ze(r,e){let t=e.now??(()=>performance.now()),n=Qt(r)?r:void 0,i=[],a=null,s=null,o=null,u=!1,d=null,c=p=>{d=p;try{e.paint(p)}catch{}},l=p=>{let h=e.frames?.()??null;return h!==null&&o!==null?h.mediaTimeMs+(p-h.presentationTimeMs)-o:p-(s??p)},m=(p,h,g=0)=>{if(u)return;let E=Math.max(0,p-l(t()));a=setTimeout(()=>{if(a=null,!u){if(g<Yt&&l(t())<p-Zt){m(p,h,g+1);return}h()}},E)},f=p=>{if(n!==void 0){if(p>=3){m(2e3,()=>c(null));return}m(n.onsetsMs[p],()=>{let h=l(t());if(h>2e3){d!==null&&c(null);return}let g=n.colours[p];c(g);let E=i.length===0?0:i[i.length-1].tMs;i.push({tMs:Math.max(E,Math.round(h)),colour:g}),f(p+1)})}};return{started(p){if(n===void 0||u||s!==null)return;s=p;let h=e.frames?.()??null;o=h===null?null:h.mediaTimeMs+(p-h.presentationTimeMs),f(0)},stop(){u||(u=!0,a!==null&&clearTimeout(a),a=null,d!==null&&c(null))},report(){return n===void 0?void 0:{nonce:n.nonce,rendered:[...i]}}}}var jt=40;function V(r){if(r===null||typeof r!="object"&&typeof r!="function")return;let e;try{e=r.name}catch{return}return $t(e)}function $t(r){if(typeof r!="string")return;let e=r.replace(/[^A-Za-z]/g,"").slice(0,jt);return e===""?void 0:e}function Xe(r){let e=re(r);if(e!=="generic")return e;switch(V(r)){case"AbortError":return"inuse";case"SecurityError":return"permission";default:return e}}var k=1;function qe(){return typeof OffscreenCanvas=="function"&&typeof createImageBitmap=="function"&&typeof Worker=="function"}function Jt(r,e={}){let t=e.createDetector??x,n=null;r.onmessage=i=>{let a=i.data;if(a.v!==k){a.bitmap?.close?.();return}if(a.type==="init"){t(a.options).then(s=>{n=s;let o={v:k,type:"ready",tier:s.tier,...s.fallbackReason!==void 0?{fallbackReason:s.fallbackReason}:{}};r.postMessage(o)});return}if(a.type==="detect"){let s=o=>{let u={v:k,type:"result",id:a.id,observation:o};r.postMessage(u),a.bitmap.close?.()};if(n===null){s(null);return}n.detect(a.bitmap,a.streamWidth,a.streamHeight).then(s,()=>s(null))}}}typeof self<"u"&&typeof self.importScripts=="function"&&Jt(self);var Z=class r{constructor(e,t){this.pending=new Map;this.nextId=1;this.worker=e,this.tier=t.tier,t.fallbackReason!==void 0&&(this.fallbackReason=t.fallbackReason),e.addEventListener("message",n=>{let i=n.data;if(i.v!==k||i.type!=="result")return;let a=this.pending.get(i.id);this.pending.delete(i.id),a?.(i.observation)})}static create(e,t,n=1e4){return new Promise((i,a)=>{let s=setTimeout(()=>{e.removeEventListener("message",o),e.terminate(),a(new Error(`worker detector not ready within ${n}ms`))},n),o=d=>{let c=d.data;c.v!==k||c.type!=="ready"||(clearTimeout(s),e.removeEventListener("message",o),i(new r(e,c)))};e.addEventListener("message",o);let u={v:k,type:"init",options:t};e.postMessage(u)})}async detect(e,t,n){let i;try{typeof ImageBitmap<"u"&&e instanceof ImageBitmap?i=e:typeof createImageBitmap=="function"?i=await createImageBitmap(e):i=e}catch{return null}let a=this.nextId;return this.nextId+=1,new Promise(s=>{this.pending.set(a,s);let o={v:k,type:"detect",id:a,bitmap:i,streamWidth:t,streamHeight:n};this.worker.postMessage(o,[i])})}destroy(){for(let e of this.pending.values())e(null);this.pending.clear(),this.worker.terminate()}};var er=["size","centering","pose","exposure","sharpness","motion"];function Ye(r){if(r.accepted)return null;if(r.factors.presence<=0)return"no_face";let e="size";for(let t of er)r.factors[t]<r.factors[e]&&(e=t);return e}var D=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 n=Ye(e);if(n===null){this.acceptedMs+=t;return}let i=this.blocked[n]??{count:0,ms:0};i.count+=1,i.ms+=t,this.blocked[n]=i}summary(){let e={};for(let[t,n]of Object.entries(this.blocked))e[t]={count:n.count,ms:Math.round(n.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var st=1e3,j="fcv3.hold_upright",ot=200,$=4,ct=600,ut=1e3,it={sharpness:1,exposure:1,meanLuma:128};function or(r,e){return e.width=r.videoWidth,e.height=r.videoHeight,e.getContext("2d").drawImage(r,0,0),new Promise((t,n)=>e.toBlob(i=>i?t(i):n(new Error("empty-keyframe")),"image/jpeg",.92))}function cr(){return U()==="phone"}var Ee=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 n=this.handlers.get(e);return n||(n=new Set,this.handlers.set(e,n)),n.add(t),()=>n?.delete(t)}emit(e,t){for(let n of[...this.handlers.get(e)??[]])n(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??cr)(),this.setState("preflight");let n=ne();if(n!=="OK"){this.fail(n==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let i=t.getUserMedia??(d=>navigator.mediaDevices.getUserMedia(d)),a;this.cameraRequestedAt=this.now();try{a=await i(se(oe(),this.facing))}catch(d){if(e!==this.attempt)return;this.fail(Xe(d),{phase:"acquiring",name:V(d)});return}if(Ve(a),Ke(a),e!==this.attempt){for(let d of a.getTracks())d.stop();return}this.stream=a;let s=a.getVideoTracks?.()[0];if(this.trackProvenance=s===void 0?null:He(s).catch(()=>null),this.facing=ce(a)??this.facing,t.video.srcObject=a,await t.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let d={v3AssetBaseUrl:t.v3AssetBaseUrl},c=t.createDetector??(t.createWorker!==void 0&&qe()?async()=>{try{return await Z.create(t.createWorker(),d)}catch{return x(d)}}:()=>x(d)),l;try{l=await c()}catch(m){e===this.attempt&&this.fail("models",{phase:"models",name:V(m)},m instanceof T?m.fallbackReason:lr(m));return}if(e!==this.attempt){l.destroy();return}this.detector=l,this.options.telemetry?.({type:"detector",tier:l.tier,fallbackReason:l.fallbackReason})}let o=me(),u=t.deviceClass??pe(o);this.profiler=new N(u),this.options.telemetry?.({type:"profile",staticClass:u,activeClass:this.profiler.deviceClass,simd:o.simd}),this.gate=new w(t.thresholds??{}),this.blockStats=new D,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&Promise.resolve().then(()=>(nt(),rt)).then(d=>ve=d,()=>{}),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 n=new G({cadenceHz:t.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=n,n.start()}async detectTick(e){let{detector:t,gate:n,profiler:i}=this,a=this.options.video;if(e!==this.attempt||t===null||n===null||i===null||this.fired||a.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let s=i.deviceClass,o=this.now(),u=this.options.makeSnapshot?.(a,i.profile.inputWidth)??this.defaultSnapshot(a,i.profile.inputWidth),d=null;try{d=await t.detect(u,a.videoWidth,a.videoHeight)}catch{d=null}if(e!==this.attempt||this.fired)return;i.record(this.now()-o),i.deviceClass!==s&&this.startScheduler(e);let c=d===null?it:this.options.measureQuality?.(a,d.box)??this.defaultQuality(a,d.box),l=n.tick({timestampMs:this.now(),observation:d,quality:c,frameWidth:a.videoWidth,frameHeight:a.videoHeight});l.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=l.at),this.blockStats?.record(l),!l.ready&&l.at-this.lastGateSnapshotAt>=st&&(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,n=this.scheduler;n?.stop(),this.reportGate(!0);let i=n?.stats()??{degradeCount:0,meanDetectMs:0},a=[...this.carriedMeans,...i.meanDetectMs>0?[i.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+i.degradeCount,meanDetectMs:a.length===0?0:a.reduce((y,S)=>y+S,0)/a.length});let s=t.mode??"clip",o=t.rankKeyframes?.()&&ve?ve.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(s==="photo"){let y=this.watchRotation(e,null),S=await o;if(y(),e!==this.attempt)return;if(S===null){this.fail("generic",{phase:"keyframes"});return}let lt=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:S.blob,previewDataUrl:S.previewDataUrl,...lt});return}this.setState("recording");let u=t.createRecorder?.()??new P,d=this.stream;if(d===null){this.fail("generic",{phase:"recording"});return}let c=Ue(t.video),l=t.screenRamp?.(),m=l!==void 0,f=ze(l,{paint:y=>{(y===null||e===this.attempt)&&this.emit("ramp",{colour:y})},now:()=>this.now(),frames:c.latest});this.ramp=f;let p=()=>{c.stop(),f.stop(),this.ramp===f&&(this.ramp=null)},h=this.watchRotation(e,u),g=null;o.then(y=>{g=y},()=>{});let E=()=>{e===this.attempt&&g!==null&&this.emit("frozen",{previewDataUrl:g.previewDataUrl})},v,M;try{[v,M]=await Promise.all([u.record(d,E,()=>f.started(this.now())),o])}catch(y){if(h(),p(),e!==this.attempt)return;let S=y.kind;this.fail(S==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:V(y)});return}h();let _=c.stats();if(p(),e!==this.attempt)return;if(A(v.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(M===null){this.fail("generic",{phase:"keyframes"});return}let I=f.report(),J=await this.provenance(_,m);e===this.attempt&&this.finishCapture({clip:v.blob,clipMimeType:v.mimeType,keyframe:M.blob,previewDataUrl:M.previewDataUrl,...I!==void 0&&I.rendered.length>0?{screenRamp:I}:{},...J})}async provenance(e,t){let n=this.trackProvenance;if(n===null)return{};let i,a=new Promise(o=>{i=setTimeout(()=>o(null),ut)}),s=await Promise.race([n,a]);return clearTimeout(i),s===null?{}:{provenance:Be(s,e,t)}}isLandscape(){let e=this.options.video;return this.uprightGuard&&e.videoWidth>e.videoHeight}holdUpright(e){this.gate?.reset(),this.emit("checks",{engine:"v3",progress:0,q:0,factors:{presence:0,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==j&&(this.lastGuidanceKey=j,this.emit("guidance",{key:j}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let n=this.options.video,i=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){o();return}n.videoWidth>0&&this.isLandscape()&&(o(),this.abortRecording(e,t))},a=setInterval(i,ot);n.addEventListener?.("resize",i);let s=!1;function o(){s||(s=!0,clearInterval(a),n.removeEventListener?.("resize",i))}return o}abortRecording(e,t){if(e!==this.attempt)return;this.attempt+=1;let n=this.attempt;try{t?.stop()}catch{}this.ramp?.stop(),this.ramp=null,this.fired=!1,this.captureCompleteAt=null,this.gate=new w(this.options.thresholds??{}),this.blockStats=new D,this.lastGateSnapshotAt=this.now(),this.lastGuidanceKey=null,this.setState("positioning"),this.positioningStartedAt=this.now(),this.holdUpright(n),this.startScheduler(n)}async collectKeyframes(e){let t=this.options.captureKeyframe??(a=>this.defaultKeyframe(a)),n=ct/($-1),i=null;for(let a=0;a<$;a+=1){if(e!==this.attempt)return i;try{let s=await t(this.options.video);(i===null||s.sharpness>i.sharpness)&&(i=s)}catch{}a<$-1&&await ur(n)}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=(n,i,a)=>{i!==null&&a!==null&&(e[n]=Math.max(0,Math.round(a-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"),n=await(this.facing==="user"?ie:or)(e,t),i=t.toDataURL("image/jpeg",.92);return{blob:n,previewDataUrl:i,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let n=this.snapshotCanvas??document.createElement("canvas"),i=t/Math.max(1,e.videoWidth),a=Math.max(1,Math.round(e.videoWidth*i)),s=Math.max(1,Math.round(e.videoHeight*i)),o=n.getContext("2d");return o===null?e:(n.width!==a&&(n.width=a),n.height!==s&&(n.height=s),o.drawImage(e,0,0,a,s),this.snapshotCanvas=n,n)}catch{return e}}defaultQuality(e,t){let n=at(e,t,96);return n===null?it:{sharpness:Y(n),exposure:le(n),meanLuma:q(n)}}centerSharpness(e){let t=C(e),n=at(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return n===null?0:Y(n)}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,n=this.profiler;if(t===null||n===null)return;let i=t.summary();e&&(this.blockStats=null),i.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:n.deviceClass,cadenceHz:n.profile.cadenceHz,...i})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t,n){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:n});let{phase:i,name:a}=t;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:a===void 0?{phase:i}:{phase:i,name:a}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},ve;function ur(r){return new Promise(e=>setTimeout(e,r))}function lr(r){return r instanceof Error?r.message:String(r)}function at(r,e,t){try{let n=document.createElement("canvas"),i=t/Math.max(1,e.width);n.width=Math.max(1,Math.round(e.width*i)),n.height=Math.max(1,Math.round(e.height*i));let a=n.getContext("2d");return a===null?null:(a.drawImage(r,e.x,e.y,e.width,e.height,0,0,n.width,n.height),a.getImageData(0,0,n.width,n.height))}catch{return null}}0&&(module.exports={CENTERED_FACTOR,CIRCLE_RADIUS_FACTOR,CLIP_MS,CaptureSessionV3,ClipError,ClipRecorder,DEFAULT_CLIP_MIME,DEFAULT_TIER_ORDER,DEFAULT_V3_ASSET_BASE_URL,DEVICE_PROFILES,DetectScheduler,DetectorLadderError,DeviceProfiler,EXPOSURE_BAND,FaceGateV3,GATE_SNAPSHOT_MS,GateBlockStats,HOLD_UPRIGHT_KEY,IN_CIRCLE_FACTOR,KEYFRAME_CANDIDATES,KEYFRAME_WINDOW_MS,MAX_CLIP_BYTES,MIME_CANDIDATES,PHONE_MAX_SHORT_SIDE,PROVENANCE_WAIT_MS,SHARP_REF,STOP_GRACE_MS,TIMESLICE_MS,UPRIGHT_WATCH_MS,V3_GATE_DEFAULTS,VIDEO_BPS,blockReasonOf,buildCaptureConstraints,buildLivenessV2FormData,cameraPreflight,captureMirroredKeyframe,classifyDevice,createDetector,detectFormFactor,detectIsMobile,errorCopy,exposure,extForMime,intrinsicSize,isClipTooLarge,isMediaRecorderSupported,mapGetUserMediaError,meanLuma,pickMimeType,probeDevice,sharpness,toStreamPixels,trackFacingMode,uiCopy});
|
package/dist/core/index.d.cts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { C as CameraErrorKind } from '../capture-session-v3-
|
|
2
|
-
export { a as CLIP_MS, b as CaptureArtifacts, c as CaptureErrorKind, d as CaptureSessionEvents, e as CaptureSessionV3, f as CaptureSessionV3Events, g as CaptureSessionV3Options, h as CaptureSessionV3StartOptions, i as CaptureState, j as CaptureTiming, k as ClipError, l as ClipErrorKind, m as ClipRecorder, n as ClipResult, D as DEFAULT_CLIP_MIME, o as DEVICE_PROFILES, p as DeviceClass, q as DeviceProbe, r as DeviceProfile, s as DeviceProfiler, E as EscalationClipArtifact, t as EscalationHook, F as FaceGateV3, G as GATE_SNAPSHOT_MS, u as GateBlockEntry, v as GateBlockReason, w as GateBlockStats, x as GateBlockSummary, y as GateChecks, H as HOLD_UPRIGHT_KEY, K as KEYFRAME_CANDIDATES, z as KEYFRAME_WINDOW_MS, M as MAX_CLIP_BYTES, A as MIME_CANDIDATES, P as PROVENANCE_WAIT_MS, S as STOP_GRACE_MS, T as TIMESLICE_MS, U as UPRIGHT_WATCH_MS, V as V3ChecksPayload, B as V3GateFactor, I as V3GateQuality, J as V3GateThresholds, L as V3GateTick, N as V3GateTickInput, O as V3TelemetryEvent, Q as V3_GATE_DEFAULTS, R as VIDEO_BPS, W as blockReasonOf, X as buildLivenessV2FormData, Y as cameraPreflight, Z as classifyDevice, _ as extForMime, $ as isClipTooLarge, a0 as isMediaRecorderSupported, a1 as mapGetUserMediaError, a2 as pickMimeType, a3 as probeDevice } from '../capture-session-v3-
|
|
1
|
+
import { C as CameraErrorKind } from '../capture-session-v3-Cs4yV3HJ.cjs';
|
|
2
|
+
export { a as CLIP_MS, b as CaptureArtifacts, c as CaptureErrorKind, d as CaptureSessionEvents, e as CaptureSessionV3, f as CaptureSessionV3Events, g as CaptureSessionV3Options, h as CaptureSessionV3StartOptions, i as CaptureState, j as CaptureTiming, k as ClipError, l as ClipErrorKind, m as ClipRecorder, n as ClipResult, D as DEFAULT_CLIP_MIME, o as DEVICE_PROFILES, p as DeviceClass, q as DeviceProbe, r as DeviceProfile, s as DeviceProfiler, E as EscalationClipArtifact, t as EscalationHook, F as FaceGateV3, G as GATE_SNAPSHOT_MS, u as GateBlockEntry, v as GateBlockReason, w as GateBlockStats, x as GateBlockSummary, y as GateChecks, H as HOLD_UPRIGHT_KEY, K as KEYFRAME_CANDIDATES, z as KEYFRAME_WINDOW_MS, M as MAX_CLIP_BYTES, A as MIME_CANDIDATES, P as PROVENANCE_WAIT_MS, S as STOP_GRACE_MS, T as TIMESLICE_MS, U as UPRIGHT_WATCH_MS, V as V3ChecksPayload, B as V3GateFactor, I as V3GateQuality, J as V3GateThresholds, L as V3GateTick, N as V3GateTickInput, O as V3TelemetryEvent, Q as V3_GATE_DEFAULTS, R as VIDEO_BPS, W as blockReasonOf, X as buildLivenessV2FormData, Y as cameraPreflight, Z as classifyDevice, _ as extForMime, $ as isClipTooLarge, a0 as isMediaRecorderSupported, a1 as mapGetUserMediaError, a2 as pickMimeType, a3 as probeDevice } from '../capture-session-v3-Cs4yV3HJ.cjs';
|
|
3
3
|
export { C as CENTERED_FACTOR, a as CIRCLE_RADIUS_FACTOR, F as FormFactor, I as IN_CIRCLE_FACTOR, P as PHONE_MAX_SHORT_SIDE, b as buildCaptureConstraints, d as detectFormFactor, c as detectIsMobile, t as trackFacingMode } from '../capture-constraints-B5omafmk.cjs';
|
|
4
4
|
export { C as CreateDetectorOptions, D as DEFAULT_TIER_ORDER, a as DEFAULT_V3_ASSET_BASE_URL, b as Detector, c as DetectorLadderError, F as FaceObservation, d as createDetector, i as intrinsicSize, t as toStreamPixels } from '../detect-worker-DclNxkZT.cjs';
|
|
5
|
-
import '../types-
|
|
5
|
+
import '../types-DPl0hsmI.cjs';
|
|
6
6
|
|
|
7
7
|
declare function captureMirroredKeyframe(video: HTMLVideoElement, canvas: HTMLCanvasElement, quality?: number): Promise<Blob>;
|
|
8
8
|
|
package/dist/core/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { C as CameraErrorKind } from '../capture-session-v3-
|
|
2
|
-
export { a as CLIP_MS, b as CaptureArtifacts, c as CaptureErrorKind, d as CaptureSessionEvents, e as CaptureSessionV3, f as CaptureSessionV3Events, g as CaptureSessionV3Options, h as CaptureSessionV3StartOptions, i as CaptureState, j as CaptureTiming, k as ClipError, l as ClipErrorKind, m as ClipRecorder, n as ClipResult, D as DEFAULT_CLIP_MIME, o as DEVICE_PROFILES, p as DeviceClass, q as DeviceProbe, r as DeviceProfile, s as DeviceProfiler, E as EscalationClipArtifact, t as EscalationHook, F as FaceGateV3, G as GATE_SNAPSHOT_MS, u as GateBlockEntry, v as GateBlockReason, w as GateBlockStats, x as GateBlockSummary, y as GateChecks, H as HOLD_UPRIGHT_KEY, K as KEYFRAME_CANDIDATES, z as KEYFRAME_WINDOW_MS, M as MAX_CLIP_BYTES, A as MIME_CANDIDATES, P as PROVENANCE_WAIT_MS, S as STOP_GRACE_MS, T as TIMESLICE_MS, U as UPRIGHT_WATCH_MS, V as V3ChecksPayload, B as V3GateFactor, I as V3GateQuality, J as V3GateThresholds, L as V3GateTick, N as V3GateTickInput, O as V3TelemetryEvent, Q as V3_GATE_DEFAULTS, R as VIDEO_BPS, W as blockReasonOf, X as buildLivenessV2FormData, Y as cameraPreflight, Z as classifyDevice, _ as extForMime, $ as isClipTooLarge, a0 as isMediaRecorderSupported, a1 as mapGetUserMediaError, a2 as pickMimeType, a3 as probeDevice } from '../capture-session-v3-
|
|
1
|
+
import { C as CameraErrorKind } from '../capture-session-v3-CFSVWYzi.js';
|
|
2
|
+
export { a as CLIP_MS, b as CaptureArtifacts, c as CaptureErrorKind, d as CaptureSessionEvents, e as CaptureSessionV3, f as CaptureSessionV3Events, g as CaptureSessionV3Options, h as CaptureSessionV3StartOptions, i as CaptureState, j as CaptureTiming, k as ClipError, l as ClipErrorKind, m as ClipRecorder, n as ClipResult, D as DEFAULT_CLIP_MIME, o as DEVICE_PROFILES, p as DeviceClass, q as DeviceProbe, r as DeviceProfile, s as DeviceProfiler, E as EscalationClipArtifact, t as EscalationHook, F as FaceGateV3, G as GATE_SNAPSHOT_MS, u as GateBlockEntry, v as GateBlockReason, w as GateBlockStats, x as GateBlockSummary, y as GateChecks, H as HOLD_UPRIGHT_KEY, K as KEYFRAME_CANDIDATES, z as KEYFRAME_WINDOW_MS, M as MAX_CLIP_BYTES, A as MIME_CANDIDATES, P as PROVENANCE_WAIT_MS, S as STOP_GRACE_MS, T as TIMESLICE_MS, U as UPRIGHT_WATCH_MS, V as V3ChecksPayload, B as V3GateFactor, I as V3GateQuality, J as V3GateThresholds, L as V3GateTick, N as V3GateTickInput, O as V3TelemetryEvent, Q as V3_GATE_DEFAULTS, R as VIDEO_BPS, W as blockReasonOf, X as buildLivenessV2FormData, Y as cameraPreflight, Z as classifyDevice, _ as extForMime, $ as isClipTooLarge, a0 as isMediaRecorderSupported, a1 as mapGetUserMediaError, a2 as pickMimeType, a3 as probeDevice } from '../capture-session-v3-CFSVWYzi.js';
|
|
3
3
|
export { C as CENTERED_FACTOR, a as CIRCLE_RADIUS_FACTOR, F as FormFactor, I as IN_CIRCLE_FACTOR, P as PHONE_MAX_SHORT_SIDE, b as buildCaptureConstraints, d as detectFormFactor, c as detectIsMobile, t as trackFacingMode } from '../capture-constraints-B5omafmk.js';
|
|
4
4
|
export { C as CreateDetectorOptions, D as DEFAULT_TIER_ORDER, a as DEFAULT_V3_ASSET_BASE_URL, b as Detector, c as DetectorLadderError, F as FaceObservation, d as createDetector, i as intrinsicSize, t as toStreamPixels } from '../detect-worker-DclNxkZT.js';
|
|
5
|
-
import '../types-
|
|
5
|
+
import '../types-DPl0hsmI.js';
|
|
6
6
|
|
|
7
7
|
declare function captureMirroredKeyframe(video: HTMLVideoElement, canvas: HTMLCanvasElement, quality?: number): Promise<Blob>;
|
|
8
8
|
|
package/dist/core/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as x,b as k,c as z,d as C,e as L,f as T,k as E,l as N,m as w,n as D,o as G,p as I,q as J,r as M,s as Q,t as W,u as X,v as Y,w as Z}from"../chunk-
|
|
1
|
+
import{a as x,b as k,c as z,d as C,e as L,f as T,k as E,l as N,m as w,n as D,o as G,p as I,q as J,r as M,s as Q,t as W,u as X,v as Y,w as Z}from"../chunk-ZPXL26BF.js";import{a as e,b as r,c as o,d as n,e as a,f as s,g as t,h as i}from"../chunk-FUHDOEBP.js";import{a as P,b as S,c as B,d as F}from"../chunk-POIQGEZM.js";import{a as c,b as p,c as u,d as f,e as m,f as d,g as l,h as v,i as y,j as g}from"../chunk-CQ7SKLMC.js";import{a as O,b as U,c as V,d as j,e as q}from"../chunk-FPXL63KZ.js";import"../chunk-JUEOHNVW.js";import{a as R,b as h,c as b,d as A,e as H,f as K}from"../chunk-OKWG3PVH.js";var _={permission:{key:"fcv2.err.permission",fr:"Autorisez la cam\xE9ra dans les r\xE9glages du navigateur (ic\xF4ne cam\xE9ra dans la barre d\u2019adresse), puis r\xE9essayez."},notfound:{key:"fcv2.err.notfound",fr:"Aucune cam\xE9ra d\xE9tect\xE9e. Branchez ou activez une cam\xE9ra, puis r\xE9essayez."},inuse:{key:"fcv2.err.inuse",fr:"La cam\xE9ra est utilis\xE9e par une autre application. Fermez-la puis r\xE9essayez."},overconstrained:{key:"fcv2.err.overconstrained",fr:"La cam\xE9ra ne prend pas en charge les r\xE9glages demand\xE9s. Nouvel essai en cours\u2026"},insecure:{key:"fcv2.err.insecure",fr:"La cam\xE9ra n\xE9cessite une connexion s\xE9curis\xE9e (HTTPS). Ouvrez la page en HTTPS."},unsupported:{key:"fcv2.err.unsupported",fr:"Votre navigateur ne prend pas en charge l\u2019enregistrement vid\xE9o. Utilisez un navigateur r\xE9cent."},generic:{key:"fcv2.err.generic",fr:"Cam\xE9ra indisponible. R\xE9essayez ou contactez le support."}},$={recording:{key:"fcv2.recording",fr:"Enregistrement en cours\u2026"},uploading:{key:"fcv2.uploading",fr:"Envoi en cours\u2026"},clipTooLarge:{key:"fcv2.err.cliptoolarge",fr:"La vid\xE9o est trop volumineuse. R\xE9essayez dans un endroit mieux \xE9clair\xE9."},retry:{key:"fcv2.retry",fr:"R\xE9essayer"},listen:{key:"fcv2.listen",fr:"\xC9couter"}};export{i as CENTERED_FACTOR,s as CIRCLE_RADIUS_FACTOR,x as CLIP_MS,Z as CaptureSessionV3,L as ClipError,T as ClipRecorder,u as DEFAULT_CLIP_MIME,h as DEFAULT_TIER_ORDER,R as DEFAULT_V3_ASSET_BASE_URL,P as DEVICE_PROFILES,N as DetectScheduler,b as DetectorLadderError,F as DeviceProfiler,U as EXPOSURE_BAND,D as FaceGateV3,J as GATE_SNAPSHOT_MS,I as GateBlockStats,M as HOLD_UPRIGHT_KEY,t as IN_CIRCLE_FACTOR,W as KEYFRAME_CANDIDATES,X as KEYFRAME_WINDOW_MS,l as MAX_CLIP_BYTES,c as MIME_CANDIDATES,r as PHONE_MAX_SHORT_SIDE,Y as PROVENANCE_WAIT_MS,O as SHARP_REF,z as STOP_GRACE_MS,k as TIMESLICE_MS,Q as UPRIGHT_WATCH_MS,w as V3_GATE_DEFAULTS,C as VIDEO_BPS,G as blockReasonOf,e as buildCaptureConstraints,g as buildLivenessV2FormData,m as cameraPreflight,E as captureMirroredKeyframe,B as classifyDevice,K as createDetector,o as detectFormFactor,n as detectIsMobile,_ as errorCopy,q as exposure,y as extForMime,A as intrinsicSize,v as isClipTooLarge,d as isMediaRecorderSupported,f as mapGetUserMediaError,V as meanLuma,p as pickMimeType,S as probeDevice,j as sharpness,H as toStreamPixels,a as trackFacingMode,$ as uiCopy};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{u as a,v as b,w as c,x as d}from"./chunk-RNJA5GDF.js";import"./chunk-G6LKLN4U.js";import"./chunk-TDLIXFDT.js";import"./chunk-6K4D3U6Q.js";import"./chunk-GT2ZLGF7.js";import"./chunk-ZPXL26BF.js";import"./chunk-FUHDOEBP.js";import"./chunk-POIQGEZM.js";import"./chunk-CQ7SKLMC.js";import"./chunk-FPXL63KZ.js";import"./chunk-JUEOHNVW.js";import"./chunk-OKWG3PVH.js";import"./chunk-DK5YPBDQ.js";export{a as SAME_FACE_MAX_DROPS,c as createDocumentCapture,d as createDocumentCaptureInternal,b as warmDocumentCapture};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{j as a,k as b,l as c,m as d,n as e,o as f}from"./chunk-4GJXUVZK.js";import"./chunk-CJHMFPL6.js";import"./chunk-RI3E7GBN.js";import"./chunk-7ZCZY3ZP.js";import"./chunk-BPE5NSQ2.js";import"./chunk-GI3UFGRQ.js";import"./chunk-GT2ZLGF7.js";import"./chunk-FUHDOEBP.js";import"./chunk-CQ7SKLMC.js";export{a as ANALYSIS_LONG_EDGE,b as PORTRAIT_JPEG_QUALITY,e as createPortraitCaptureInternal,c as defaultGrabber,d as observe,f as warmPortraitCapture};
|