@tsocial/tvweb-sdk.platform 5.36.0 → 5.37.0
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/build/esm/{chunk-44240957.js → chunk-147a2e31.js} +1 -1
- package/build/esm/{chunk-5544ce07.js → chunk-2932b8ef.js} +1 -1
- package/build/esm/{chunk-390ea2aa.js → chunk-2bfdf00f.js} +1 -1
- package/build/esm/{chunk-58f60271.js → chunk-2e802851.js} +2 -2
- package/build/esm/{chunk-7c980e08.js → chunk-2f57cc44.js} +1 -1
- package/build/esm/{chunk-ce4fbdae.js → chunk-337b9ebf.js} +1 -1
- package/build/esm/{chunk-e1ce62d6.js → chunk-38f2d65b.js} +1 -1
- package/build/esm/{chunk-41c1d4f2.js → chunk-39db42b0.js} +1 -1
- package/build/esm/chunk-5993adde.js +1 -0
- package/build/esm/{chunk-e468b8ce.js → chunk-5d5d5df1.js} +1 -1
- package/build/esm/chunk-68e90ba2.js +1121 -0
- package/build/esm/{chunk-3fc64163.js → chunk-77790073.js} +1 -1
- package/build/esm/{chunk-c298ad04.js → chunk-7d0d639a.js} +1 -1
- package/build/esm/{chunk-fdbce3d2.js → chunk-9038aebd.js} +1 -1
- package/build/esm/{chunk-a37a1269.js → chunk-a4a97e90.js} +1 -1
- package/build/esm/{chunk-4da2a90d.js → chunk-bcf5eed2.js} +1 -1
- package/build/esm/{chunk-dad8ede3.js → chunk-c04f48e4.js} +1 -1
- package/build/esm/{chunk-eea8c6e6.js → chunk-ccb7bcab.js} +1 -1
- package/build/esm/{chunk-afb105f2.js → chunk-d02bd3cc.js} +55 -55
- package/build/esm/{chunk-b39a7ba9.js → chunk-e5b81ec5.js} +1 -1
- package/build/esm/{chunk-1bd57581.js → chunk-e7ee9d9f.js} +1 -1
- package/build/esm/{chunk-989d36e3.js → chunk-fbc39ae4.js} +1 -1
- package/build/esm/tvweb-sdk.platform.esm.min.js +1 -1
- package/build/tvweb-sdk.platform.cjs.min.js +668 -668
- package/build/tvweb-sdk.platform.standalone.js +1504 -15963
- package/build/tvweb-sdk.platform.standalone.min.js +668 -668
- package/package.json +5 -6
- package/build/esm/chunk-9390d088.js +0 -1121
- package/build/esm/chunk-c136757f.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e,b as t,u as s,aH as a,s as n,c as i,ab as r,d as l,e as c,f as o,k as u,aK as _,aL as m,J as g,O as d,Y as f,Q as h,F as b,av as v,t as p,aB as w,j as k}from"./chunk-9390d088.js";import{t as y}from"./chunk-c298ad04.js";import{t as F}from"./chunk-fdbce3d2.js";import{n as T,u as L,o as R,q as B,r as C,v as S,s as x,x as I}from"./chunk-a37a1269.js";import{m as M}from"./chunk-4da2a90d.js";import{u as D}from"./chunk-dad8ede3.js";let E=a.faceTracker(),j=new _,{FaceDirection:P,Errors:A,Messages:V,TrackLivenessEvents:W}=n,N={enable:!1,framesIntervalTime:180,framesBatchLength:0},U={[n.FaceDirection.UP]:{delayTime:0},[n.FaceDirection.LEFT]:{delayTime:0},[n.FaceDirection.RIGHT]:{delayTime:0},[n.FaceDirection.FRONTAL]:{delayTime:2e3}},O=()=>{},z=()=>{},K=()=>{};function q({apiCheck:_,bgCameraMask:k,bgCameraMaskRed:Z,surroundStyle:G,cropAreaDimension:H,customInstructions:J,customIcon:Q,customDirectionIcon:X,customStepTimeConstraints:Y=U,onLivenessDetectionDone:$,onError:ee,frontalMinSize:et,waitingTimeToGetBetterFrames:es=500,captureFrameSettings:ea=N,setRemainingTime:en=O,onProcessing:ei=K,customErrors:er,customMessages:el,apiCredentials:ec={},onFramesCaptured:eo=z,initFirstGestureTimeout:eu=2e3,outputEncryptionSettings:e_,cameraScale:em=1,passiveModeAuto:eg=!1,sendCustomEvent:ed,serviceSettings:ef,currentOrientation:eh,onReset:eb}={}){let[ev,ep]=e.useState(!1),[ew,ek]=e.useState(!1),[ey,eF]=e.useState(!1),[eT,eL]=e.useState(!1),eR=e.useRef(null),{lang:eB,assetRoot:eC,customUrls:eS,exifKey:ex}=i.useSDKSettings(),eI=r.useSDKLocale(),{apiClient:eM}=l.useApiClient({apiCredentials:ec}),[,eD]=e.useReducer(e=>e+1,0),eE=e.useRef(null),[ej,eP]=e.useState(!1),eA=e.useRef({}),{sendEvent:eV}=c.useSDKTracking(),[eW,eN]=e.useState(3),[eU,eO]=e.useState(!1),ez=e.useRef(!1),eK=e.useCallback(e=>{eO(e),ez.current=e},[]),eq=e.useRef(null),eZ=e.useRef([]),eG=e.useRef(null),eH=e.useRef(),eJ=e.useRef(null);null===eJ.current&&(eJ.current=a.initFaceVerificationData({assetRoot:eC,customInstructions:J,customIcon:Q,customDirectionIcon:X,customStepTimeConstraints:Y,Locale:eI,lang:eB}));let[eQ,eX]=e.useState(),eY=e.useCallback(e=>{eX(e)},[]),e$=e.useMemo(()=>y(eY,500),[eY]),e0=e.useRef([]),e1=e.useRef(),e4=D(),{flowIntervalTimeMs:e2,limitTimeLivenessCheck:e3,terminateIfNoFace:e5,closeEyeDetectorSettings:e7,exifDataSettings:e6,recordVideo:e8,autoCaptureSettings:e9,manualCaptureSettings:te,blurCheckSettings:tt,webIsRequiredFrontalFace:ts,waitBeforeStartFlowMs:ta,resetFlowOnOrientationChange:tn,captureFrameSettings:ti}=function({clientSettings:a,captureFrameSettingsProp:n}){return e.useMemo(()=>{let e,i=M({},T,a),r={enable:t(i,"data.settings.sdk_settings.passive_liveness_settings.auto_capture.enable"),showCaptureButton:t(i,"data.settings.sdk_settings.passive_liveness_settings.auto_capture.show_capture_button"),showCountdown:t(i,"data.settings.sdk_settings.passive_liveness_settings.auto_capture.show_countdown"),waitForBestImageTimeMsWeb:t(i,"data.settings.sdk_settings.passive_liveness_settings.auto_capture.wait_for_best_image_time_ms_web")},l={showCountdown:t(i,"data.settings.sdk_settings.passive_liveness_settings.manual_capture.show_countdown"),waitForBestImageTimeMsWeb:t(i,"data.settings.sdk_settings.passive_liveness_settings.manual_capture.wait_for_best_image_time_ms_web")},c={enable:t(i,"data.settings.sdk_settings.passive_liveness_settings.blur_check.enable"),webBlurryThreshold:t(i,"data.settings.sdk_settings.passive_liveness_settings.blur_check.web_blurry_threshold")},o={enable:t(i,"data.settings.sdk_settings.passive_liveness_settings.close_eye_detector.enable"),webThreshold:t(i,"data.settings.sdk_settings.passive_liveness_settings.close_eye_detector.web_threshold"),webTimeout:t(i,"data.settings.sdk_settings.passive_liveness_settings.close_eye_detector.web_timeout"),forceCheck:t(i,"data.settings.sdk_settings.passive_liveness_settings.close_eye_detector.force_check")},u=t(i,"data.settings.sdk_settings.passive_liveness_settings.web_is_required_frontal_face"),_=s.getWebSetting(i,"data.settings.sdk_settings.active_liveness_settings.limit_time_liveness_check.max_retry_count"),m={enable:t(i,"data.settings.sdk_settings.active_liveness_settings.limit_time_liveness_check.enable"),limitTimeSecond:t(i,"data.settings.sdk_settings.active_liveness_settings.limit_time_liveness_check.limit_time_second"),remainTimeShow:t(i,"data.settings.sdk_settings.active_liveness_settings.limit_time_liveness_check.remain_time_show"),format:t(i,"data.settings.sdk_settings.active_liveness_settings.limit_time_liveness_check.format"),enableMaxRetries:_>0,totalMaxRetries:_,interruptible:!s.getWebSetting(i,"data.settings.sdk_settings.active_liveness_settings.limit_time_liveness_check.non_stoppable")},g={enable:t(i,"data.settings.sdk_settings.active_liveness_settings.terminate_if_no_face.enable"),maxInvalidFrame:t(i,"data.settings.sdk_settings.active_liveness_settings.terminate_if_no_face.max_invalid_frame"),maxTimeMs:t(i,"data.settings.sdk_settings.active_liveness_settings.terminate_if_no_face.max_time_ms")},d={enable:t(i,"data.settings.sdk_settings.active_liveness_settings.exif_data_settings.enable")},f={enable:t(i,"data.settings.sdk_settings.active_liveness_settings.record_video.enable")},h=t(i,"data.settings.sdk_settings.active_liveness_settings.wait_before_start_flow_ms"),b=t(i,"data.settings.sdk_settings.active_liveness_settings.reset_flow_on_orientation_change"),v=t(i,"data.settings.sdk_settings.active_liveness_settings.flow_interval_time_ms"),p=t(a,"data.settings.sdk_settings.active_liveness_settings.save_encoded_frames");return{autoCaptureSettings:r,manualCaptureSettings:l,blurCheckSettings:c,closeEyeDetectorSettings:o,webIsRequiredFrontalFace:u,limitTimeLivenessCheck:m,terminateIfNoFace:g,exifDataSettings:d,recordVideo:f,waitBeforeStartFlowMs:h,resetFlowOnOrientationChange:b,flowIntervalTimeMs:v,captureFrameSettings:e=p?{enable:p.enable,enableLogging:p.enable_logging,framesBatchLength:p.frames_batch_len,framesIntervalTime:p.frames_interval_ms}:n}},[a,n])}({clientSettings:e4,captureFrameSettingsProp:ea}),tr=e9?.enable?e9?.waitForBestImageTimeMsWeb:te?.waitForBestImageTimeMsWeb,tl=e8?.enable,tc=e.useMemo(()=>o.getEnabledServices(ef,e4),[e4,ef]),to=e.useRef(""),tu=e.useCallback(e=>{if(e?.event){if(e.event===W?.show_alert){let t=e.log?.alert;if(t===to.current)return;to.current=t}eV(e),ed&&ed(e)}},[ed,eV]),t_=e.useMemo(()=>y(e=>{tu(e)},2e3),[tu]),tm=e.useRef(0),tg=e.useRef(),td=e.useRef();e.useEffect(()=>{tu({tag:"selfie",event:W?.start_camera,log:{}})},[tu]),e.useEffect(()=>(j.start(),()=>{j.stop()}),[]),e.useEffect(()=>{let e=!1;return async function t(){!ej&&(e1.current=performance.now(),eA.current=await m(eS),await g.initTensorFlow({preferredBackends:["wasm","webgl","cpu"]}),e||(eP(!0),tu({tag:"selfie",event:W?.show_warmup,log:{}}),tu({tag:"selfie",event:W?.finish_load_model,log:{status:"success",time_in_ms:performance.now()-e1.current}}),e1.current=null))}(),()=>{e=!0}},[ej,eS,tu]);let tf=e.useRef(!1),th=e.useCallback(()=>{eJ.current.curStepIndex=eJ.current.steps.length,tf.current=!0,eF(!1),td.current?.discardRecording(),clearInterval(eq.current)},[]),tb=e.useCallback(()=>{eJ.current=a.initFaceVerificationData({assetRoot:eC,customInstructions:J,customIcon:Q,customDirectionIcon:X,Locale:eI,lang:eB}),tm.current=0,tg.current=null,e0.current=[],eL(!1),eX(null),x(),td.current?.start(),tf.current=!1,eK(!1),eN(3),eG.current=null,eZ.current=[],eH.current=null,"function"==typeof eb&&eb(),eD()},[eI,eC,X,Q,J,eK,eB,eb]),tv=e.useCallback(()=>{th(),setTimeout(()=>{tb()},e2)},[e2,tb,th]),tp=e.useMemo(()=>({...A,...er}),[er]),tw=e.useMemo(()=>({...V,...el}),[el]),tk=e.useCallback(()=>{let e={};Object.keys(tp.liveness_terminated_time_out?.msg).forEach(t=>{let s=F(tp.liveness_terminated_time_out?.msg[t]);e[t]=s({x:e3.limitTimeSecond})}),eX({...tp.liveness_terminated_time_out,msg:e,duration:.95*e2}),tu({tag:"selfie",event:W?.show_alert,log:{alert:"liveness_terminated_time_out,"}}),j.stop(),en(""),th()},[tp.liveness_terminated_time_out,e2,e3.limitTimeSecond,th,tu,en]),ty=e.useCallback(({remainTime:e})=>{if(e>0&&e<=e3.remainTimeShow){let t=F(tw.REMAIN_TIME[eB]),s=e;switch(e3.format){case"mm:ss":s=e.toString().padStart(5,"00:00");break;case"ss":s=e.toString().padStart(2,"0")}en(t({x:s}))}},[eB,e3.format,e3.remainTimeShow,tw.REMAIN_TIME,en]),tF=e.useCallback(({attemptCount:e,fromBackground:t})=>{e3.enableMaxRetries&&e>=e3.totalMaxRetries&&ee(n.Errors.max_retry_reached),t&&th(),j.start(),tb()},[e3.enableMaxRetries,e3.totalMaxRetries,ee,tb,th]),{stopTimer:tT}=L({totalTime:e3.limitTimeSecond,totalDelayBetweenReset:e2/1e3,interruptible:e3.interruptible,shouldStart:ew&&e3.enable&&ej,onTimesUp:tk,onTick:ty,onReset:tF}),tL=e.useCallback(({clientWidth:e,clientHeight:t,videoAreaWidth:s,videoAreaHeight:a,lostX:n,lostY:i})=>{let r,l;u.isMobile?l=r=s:r=l=a-200;let c=Math.floor((s-r)/2)+n;eE.current={x:c,y:5+i,width:r,height:l,image:k,surroundStyle:G},"object"==typeof H?eE.current={...eE.current,...H}:"function"==typeof H&&(eE.current={...eE.current,...H({clientWidth:e,clientHeight:t,videoAreaWidth:s,videoAreaHeight:a,lostX:n,lostY:i,isMobile:u.isMobile,width:r,height:l})}),eD(),ek(!0)},[k,G,H]),tR=e.useCallback(()=>{eN(3),clearInterval(eq.current),eK(!0);let e=async e=>{if(e-1==0){let e;j.stop(),tT(),clearInterval(eq.current),ei(),await td.current?.stopVideoRecording(),ep(!0),d.addExifData("user_action",{start_selfie:Date.now()-1e3*j.duration("from_1st_frame"),end_selfie:Date.now()});let t=(e=e9.enable?[eG.current]:eZ.current).map(e=>f.resizeBlobImg(e.blob,400,400)),s=(await Promise.all(t)).map((t,s)=>{let a=d.parseLivenessImg({...e[s],gesture:"frontal"});return d.writeCurrentExif({imageData:{blob:t},enableExifData:e6.enable,additionalData:a})}),a=await Promise.all(s),n={};if(e_&&e_.key){let{key:e}=e_,t=a.map(t=>h.encrypt({blob:t,key:e}));n={frontalFacesEncrypted:await Promise.all(t)}}let i=[...e0.current];if(e_&&e_.key){let e=await Promise.all(i.map(e=>e?.base64));if(i=i.map((t,s)=>({...t,base64:e[s]})),ti.enable&&ti.framesBatchLength>0&&i.length%ti.framesBatchLength>0){let e=i.slice(-1*(i.length%ti.framesBatchLength));eo(e),_&&tc.enableUploadFrames&&R(e_,e,eM,i.length===ti.framesBatchLength)}}else ti.enable&&ti.framesBatchLength>0&&i.length%ti.framesBatchLength>0&&(eo(i.slice(-1*(i.length%ti.framesBatchLength)).map(({base64:e,label:t,index:s})=>({base64:e,label:t,index:s}))),_&&tc.enableUploadFrames&&R(e_,i.slice(-1*(i.length%ti.framesBatchLength)),eM));if(_&&tc.enableUploadImages){let t=e=>({label:"portrait",metadata:JSON.stringify({gesture_score:e,gesture:P.FRONTAL})}),s=e.map((e,s)=>eM.uploadImage({file:a[s],...t(e.leftRightScore)}));e_&&e_.key&&(s=e.map((e,s)=>{let a=new Blob([n.frontalFacesEncrypted[s].hex]);return eM.uploadImage({file:a,...t(e.leftRightScore)},{"X-TV-Key":e_.key})}));try{let t=await Promise.all(s),a=null;tc.enableVerifyFaceLiveness&&(a=eM.verifyFaceLiveness({images:t.map(e=>({id:e.data.image_id})),videos:[{frames:i}]}));let n=null;tc.enableVerifySanityPortrait&&(n=eM.requestVerifyPortrait({image:{id:t?.[t.length-1]?.data?.image_id}}));let[r,l]=await Promise.all([a,n]);$({apiCheckPassed:r?.data.is_live??!1,verifyFaceLivenessResult:r?.data??null,verifyFacePortraitResult:l?.data??null,frontalFaces:t.map((t,s)=>({id:t?.data?.image_id,blob:e?.[s]?.blob}))})}catch(e){ee({error:e})}}else $({frontalFaces:a,...n,capturedFrames:i,video:B()}),C()}};eq.current=setInterval(()=>{eN(t=>(e(t),t-1))},tr/3)},[eK,tr,tT,ei,e9.enable,e_,ti.enable,ti.framesBatchLength,_,tc.enableUploadImages,tc.enableUploadFrames,tc.enableVerifyFaceLiveness,tc.enableVerifySanityPortrait,e6.enable,eo,eM,$,ee]),tB=e.useRef({});e.useEffect(()=>{tB.current.isFirstValidFrameFoundRef=eT},[eT]),e.useEffect(()=>{let e,t=eR.current;async function s({faceDirection:e,canvas:t,leftRightScore:s,blurScore:a,isEyeClosed:n}){if(!0===ez.current&&(ts&&e===P.FRONTAL||!ts)){let e=await b.takePicture({canvas:t});e9?.enable&&Date.now()-eH.current<e9?.waitForBestImageTimeMsWeb?(eG.current||(eG.current={blob:e,blurScore:a,isEyeClosed:n,captureTime:Date.now()}),tt?.enable&&(eG.current=I({incomingFrame:{blob:e,blurScore:a,isEyeClosed:n,captureTime:Date.now()},currentBestFrame:eG.current}))):eZ.current.length<1&&eZ.current.push({blob:e,leftRightScore:s,captureTime:Date.now(),blurScore:a})}}async function i(r,l){let c,o;if(l?.width===0||l?.height===0)return;let{isFirstValidFrameFoundRef:u}=tB.current,{cropX:m,cropY:g,cropWidth:d,cropHeight:f}=r;l.getContext("2d").drawImage(t,m,g,d,f,-((400*em-400)/2)/em,-((400*em-400)/2)/em,400,400);let{blazefaceModel:h,closeEyesModel:b}=eA.current,[y,F]=await Promise.all([v.calculateBlurScore(l),p.getModelPredictions({model:h,sCanvas:l})]),{error:T,fullFace:L,faceRatio:B,faceNotFrontalMinThreshold:C}=await a.validatePredictions({predictions:F,width:p.SIZE,height:p.SIZE});c=T,eE.current.image=k;let S=null,x=null,I=null,{curStepIndex:M,steps:D}=eJ.current;if(L){I=L.landmarks;let e=await a.calculateFaceDirection({landmarks:I,getPerfectFrontal:!0});e&&(S=e.gesture,x=e.leftRightScore);let t=e7?.webTimeout+Y[n.FaceDirection.FRONTAL].delayTime/1e3;if(e7?.enable&&(-1===j.duration("limit_close_eye")||j.duration("limit_close_eye")<t)){e7?.forceCheck||-1!==j.duration("limit_close_eye")||j.start("limit_close_eye");let{isEyeClose:e}=await b.predict(l,I,e7?.webThreshold);e&&!c&&(c=A.close_eye)}}let V=c?.code==="no_face"||c?.code==="partial_face",N=M<D.length;if(!function({noFace:e,isFirstValidFrameFoundRef:t}){if(!e5.enable||!t)return;let{max_time_ms:s}=e5;tg.current&&e||(tg.current={time:Date.now(),frame:0}),e&&tg.current.frame++;let{time:a}=tg.current;e&&Date.now()-a>=s&&(eX({...tp.liveness_terminated_no_face,duration:e2}),tu({tag:"selfie",event:W?.show_alert,log:{alert:"liveness_terminated_no_face"}}),tv())}({noFace:V&&N,isFirstValidFrameFoundRef:u}),c?.code&&t_({tag:"selfie",event:W?.show_alert,log:{alert:c.code}}),!c||"face_too_small"===c.code&&S!==P.FRONTAL&&B>=C){if(!function(e,t,s,a){if(e0.current.length&&Date.now()-e0.current[e0.current.length-1].time<ti.framesIntervalTime)return;if(ti.enable&&!0){let{topLeft:a,bottomRight:n}=e,i=[...a,...n],{score:r,time:l}=E(e,0===e0.current.length),c={label:"portrait",base64:t.toDataURL("image/jpeg",.8).split(",")[1],landmarks:s,original_landmarks:s,score:r,time:l,index:e0.current.length,bbox:i,original_bbox:i};if(e_&&e_.key){if(c.base64=w.encryptFrameBase64(c.base64,e_.key),e0.current.push(c),ti.framesBatchLength>0&&e0.current.length%ti.framesBatchLength==0&&eo){let e=e0.current.slice(-ti.framesBatchLength);Promise.all(e.map(e=>e?.base64)).then(t=>{eo(e.map(({label:e,index:s},a)=>({base64:t[a],label:e,index:s}))),_&&tc.enableUploadFrames&&R(e_,e.map(({label:e,index:s},a)=>({base64:t[a],label:e,index:s})),eM,e0.current.length===ti.framesBatchLength)})}}else e0.current.push(c),ti.framesBatchLength>0&&e0.current.length%ti.framesBatchLength==0&&eo&&(eo(e0.current.slice(-ti.framesBatchLength).map(({base64:e,label:t,index:s})=>({base64:e,label:t,index:s}))),_&&tc.enableUploadFrames&&R(e_,e0.current.slice(-ti.framesBatchLength),eM,e0.current.length===ti.framesBatchLength));return};}(F[0],l,I),S!==P.FRONTAL&&ts)o=tp.not_frontal_face,eE.current.image=Z;else if(!c){u||(eL(!0),j.start("from_1st_frame"));let e=e9?.enable&&!ez.current&&0===eZ.current.length;tt?.enable?null!==y&&y>tt?.webBlurryThreshold?(o=null,e&&(eH.current=Date.now(),tR())):ez.current||(o=tp.liveness_blurry):e&&(eH.current=Date.now(),tR());let{isEyeClose:t}=await b.predict(l,I,e7?.webThreshold);await s({faceDirection:S,canvas:l,leftRightScore:x,blurScore:y,...null!==t?{isEyeClosed:t}:{}})}}else M<D.length&&(o=tp[c.code],eE.current.image=Z);e$(o),-1!==e&&(e=requestAnimationFrame(()=>i(r,l)))}async function r(){let e=b.analyzeVideoAndWindowSizes(t,eE.current),s=document.createElement("canvas");s.width=400,s.height=400;let a=s.getContext("2d");a.translate(400,0),a.scale(-1*em,+em);let{mediaRecorder:n}=tl&&t?await S({outputImagesSize:400,videoEl:t,resultAnalyzeVideoAndWindowSizes:e}):{};td.current=n,td.current&&td.current.start(),i(e,s)}return ew&&ej&&setTimeout(()=>{r()},ta??eu),()=>{cancelAnimationFrame(e),e=-1}},[eh,ta,ts,tt?.enable,tt?.webBlurryThreshold,e9?.enable,e9?.waitForBestImageTimeMsWeb,eu,ew,eB,eM,_,k,Z,$,ee,et,es,ti,ei,e3.enable,en,e$,Y,e2,tv,e5,tp,ej,tu,eo,e_,em,tR,eg,e7?.enable,e7?.webThreshold,e7?.webTimeout,e7?.forceCheck,e6.enable,ex,t_,ti.framesBatchLength,tl,tc.enableUploadFrames]),e.useEffect(()=>{eQ&&(eQ?.code!==tp?.liveness_terminated_time_out&&eQ?.code!==tp?.liveness_terminated_no_face&&e9?.enable&&ez.current||(clearInterval(eq.current),eK(!1),eG.current=null,eZ.current=[],eH.current=null))},[e9?.enable,eQ,eK,tp]);let{curStepIndex:tC,steps:tS}=eJ.current,tx=eT&&!eQ&&!eg&&(!e9?.enable||e9?.showCaptureButton),tI=eU&&!tf.current&&(e9?.enable?e9?.showCountdown:te?.showCountdown);return{resetFlowOnOrientationChange:tn,countdownToTakePicture:eW,cropArea:eE,curStepIndex:tC,faceDetectionError:eQ,resetFlow:tv,handleTriggerPassiveMode:tR,handleVideoPlayed:tL,refVideo:eR,refIsReseting:tf,showCountdown:eU,steps:tS,videoPlayed:ew,activeCapturing:ey,isFirstValidFrameFound:eT,warmupDone:ej,showLoading:ev,showCaptureButton:tx,shouldShowCountdown:tI}}function Z({className:e="",fillColor:t=null}){return k.jsxs("svg",{className:e,width:"38px",height:"32px",viewBox:"0 0 24 21","data-testid":"camera-icon",children:[k.jsx("title",{children:"FA45C15C-1E21-4D7B-9585-07FB9F999CB8"}),k.jsx("desc",{children:"Created with sketchtool."}),k.jsx("g",{id:"Web-demo",stroke:"none",strokeWidth:"1",fill:"none",fillRule:"evenodd",children:k.jsx("g",{id:"step1",transform:"translate(-950.000000, -380.000000)",fill:t??"currentColor",fillRule:"nonzero",children:k.jsx("g",{id:"Group",transform:"translate(950.000000, 380.000000)",children:k.jsx("g",{id:"Group-2",children:k.jsx("g",{id:"camera",children:k.jsx("path",{d:"M21,3 L17,3 L15,0 L9,0 L7,3 L3,3 C1.34314575,3 0,4.34314575 0,6 L0,18 C0,19.6568542 1.34314575,21 3,21 L21,21 C22.6568542,21 24,19.6568542 24,18 L24,6 C24,4.34314575 22.6568542,3 21,3 Z M12,17 C9.23857625,17 7,14.7614237 7,12 C7,9.23857625 9.23857625,7 12,7 C14.7614237,7 17,9.23857625 17,12 C17,14.7614237 14.7614237,17 12,17 L12,17 Z",id:"Shape"})})})})})})]})}export{Z as C,q as u};
|
|
1
|
+
import{r as e,b as t,u as s,aH as a,s as n,c as i,ab as r,d as l,e as c,f as o,k as u,aK as _,aL as m,I as g,O as d,Y as f,Q as h,G as b,av as v,t as p,aB as w,j as k}from"./chunk-68e90ba2.js";import{t as y}from"./chunk-7d0d639a.js";import{t as F}from"./chunk-9038aebd.js";import{n as T,u as L,o as R,q as B,r as C,v as S,s as x,x as I}from"./chunk-a4a97e90.js";import{m as M}from"./chunk-bcf5eed2.js";import{u as D}from"./chunk-c04f48e4.js";let E=a.faceTracker(),j=new _,{FaceDirection:P,Errors:A,Messages:V,TrackLivenessEvents:W}=n,N={enable:!1,framesIntervalTime:180,framesBatchLength:0},U={[n.FaceDirection.UP]:{delayTime:0},[n.FaceDirection.LEFT]:{delayTime:0},[n.FaceDirection.RIGHT]:{delayTime:0},[n.FaceDirection.FRONTAL]:{delayTime:2e3}},O=()=>{},z=()=>{},K=()=>{};function q({apiCheck:_,bgCameraMask:k,bgCameraMaskRed:G,surroundStyle:Z,cropAreaDimension:H,customInstructions:J,customIcon:Q,customDirectionIcon:X,customStepTimeConstraints:Y=U,onLivenessDetectionDone:$,onError:ee,frontalMinSize:et,waitingTimeToGetBetterFrames:es=500,captureFrameSettings:ea=N,setRemainingTime:en=O,onProcessing:ei=K,customErrors:er,customMessages:el,apiCredentials:ec={},onFramesCaptured:eo=z,initFirstGestureTimeout:eu=2e3,outputEncryptionSettings:e_,cameraScale:em=1,passiveModeAuto:eg=!1,sendCustomEvent:ed,serviceSettings:ef,currentOrientation:eh,onReset:eb}={}){let[ev,ep]=e.useState(!1),[ew,ek]=e.useState(!1),[ey,eF]=e.useState(!1),[eT,eL]=e.useState(!1),eR=e.useRef(null),{lang:eB,assetRoot:eC,customUrls:eS,exifKey:ex}=i.useSDKSettings(),eI=r.useSDKLocale(),{apiClient:eM}=l.useApiClient({apiCredentials:ec}),[,eD]=e.useReducer(e=>e+1,0),eE=e.useRef(null),[ej,eP]=e.useState(!1),eA=e.useRef({}),{sendEvent:eV}=c.useSDKTracking(),[eW,eN]=e.useState(3),[eU,eO]=e.useState(!1),ez=e.useRef(!1),eK=e.useCallback(e=>{eO(e),ez.current=e},[]),eq=e.useRef(null),eG=e.useRef([]),eZ=e.useRef(null),eH=e.useRef(),eJ=e.useRef(null);null===eJ.current&&(eJ.current=a.initFaceVerificationData({assetRoot:eC,customInstructions:J,customIcon:Q,customDirectionIcon:X,customStepTimeConstraints:Y,Locale:eI,lang:eB}));let[eQ,eX]=e.useState(),eY=e.useCallback(e=>{eX(e)},[]),e$=e.useMemo(()=>y(eY,500),[eY]),e0=e.useRef([]),e1=e.useRef(),e4=D(),{flowIntervalTimeMs:e2,limitTimeLivenessCheck:e3,terminateIfNoFace:e5,closeEyeDetectorSettings:e7,exifDataSettings:e6,recordVideo:e8,autoCaptureSettings:e9,manualCaptureSettings:te,blurCheckSettings:tt,webIsRequiredFrontalFace:ts,waitBeforeStartFlowMs:ta,resetFlowOnOrientationChange:tn,captureFrameSettings:ti}=function({clientSettings:a,captureFrameSettingsProp:n}){return e.useMemo(()=>{let e,i=M({},T,a),r={enable:t(i,"data.settings.sdk_settings.passive_liveness_settings.auto_capture.enable"),showCaptureButton:t(i,"data.settings.sdk_settings.passive_liveness_settings.auto_capture.show_capture_button"),showCountdown:t(i,"data.settings.sdk_settings.passive_liveness_settings.auto_capture.show_countdown"),waitForBestImageTimeMsWeb:t(i,"data.settings.sdk_settings.passive_liveness_settings.auto_capture.wait_for_best_image_time_ms_web")},l={showCountdown:t(i,"data.settings.sdk_settings.passive_liveness_settings.manual_capture.show_countdown"),waitForBestImageTimeMsWeb:t(i,"data.settings.sdk_settings.passive_liveness_settings.manual_capture.wait_for_best_image_time_ms_web")},c={enable:t(i,"data.settings.sdk_settings.passive_liveness_settings.blur_check.enable"),webBlurryThreshold:t(i,"data.settings.sdk_settings.passive_liveness_settings.blur_check.web_blurry_threshold")},o={enable:t(i,"data.settings.sdk_settings.passive_liveness_settings.close_eye_detector.enable"),webThreshold:t(i,"data.settings.sdk_settings.passive_liveness_settings.close_eye_detector.web_threshold"),webTimeout:t(i,"data.settings.sdk_settings.passive_liveness_settings.close_eye_detector.web_timeout"),forceCheck:t(i,"data.settings.sdk_settings.passive_liveness_settings.close_eye_detector.force_check")},u=t(i,"data.settings.sdk_settings.passive_liveness_settings.web_is_required_frontal_face"),_=s.getWebSetting(i,"data.settings.sdk_settings.active_liveness_settings.limit_time_liveness_check.max_retry_count"),m={enable:t(i,"data.settings.sdk_settings.active_liveness_settings.limit_time_liveness_check.enable"),limitTimeSecond:t(i,"data.settings.sdk_settings.active_liveness_settings.limit_time_liveness_check.limit_time_second"),remainTimeShow:t(i,"data.settings.sdk_settings.active_liveness_settings.limit_time_liveness_check.remain_time_show"),format:t(i,"data.settings.sdk_settings.active_liveness_settings.limit_time_liveness_check.format"),enableMaxRetries:_>0,totalMaxRetries:_,interruptible:!s.getWebSetting(i,"data.settings.sdk_settings.active_liveness_settings.limit_time_liveness_check.non_stoppable")},g={enable:t(i,"data.settings.sdk_settings.active_liveness_settings.terminate_if_no_face.enable"),maxInvalidFrame:t(i,"data.settings.sdk_settings.active_liveness_settings.terminate_if_no_face.max_invalid_frame"),maxTimeMs:t(i,"data.settings.sdk_settings.active_liveness_settings.terminate_if_no_face.max_time_ms")},d={enable:t(i,"data.settings.sdk_settings.active_liveness_settings.exif_data_settings.enable")},f={enable:t(i,"data.settings.sdk_settings.active_liveness_settings.record_video.enable")},h=t(i,"data.settings.sdk_settings.active_liveness_settings.wait_before_start_flow_ms"),b=t(i,"data.settings.sdk_settings.active_liveness_settings.reset_flow_on_orientation_change"),v=t(i,"data.settings.sdk_settings.active_liveness_settings.flow_interval_time_ms"),p=t(a,"data.settings.sdk_settings.active_liveness_settings.save_encoded_frames");return{autoCaptureSettings:r,manualCaptureSettings:l,blurCheckSettings:c,closeEyeDetectorSettings:o,webIsRequiredFrontalFace:u,limitTimeLivenessCheck:m,terminateIfNoFace:g,exifDataSettings:d,recordVideo:f,waitBeforeStartFlowMs:h,resetFlowOnOrientationChange:b,flowIntervalTimeMs:v,captureFrameSettings:e=p?{enable:p.enable,enableLogging:p.enable_logging,framesBatchLength:p.frames_batch_len,framesIntervalTime:p.frames_interval_ms}:n}},[a,n])}({clientSettings:e4,captureFrameSettingsProp:ea}),tr=e9?.enable?e9?.waitForBestImageTimeMsWeb:te?.waitForBestImageTimeMsWeb,tl=e8?.enable,tc=e.useMemo(()=>o.getEnabledServices(ef,e4),[e4,ef]),to=e.useRef(""),tu=e.useCallback(e=>{if(e?.event){if(e.event===W?.show_alert){let t=e.log?.alert;if(t===to.current)return;to.current=t}eV(e),ed&&ed(e)}},[ed,eV]),t_=e.useMemo(()=>y(e=>{tu(e)},2e3),[tu]),tm=e.useRef(0),tg=e.useRef(),td=e.useRef();e.useEffect(()=>{tu({tag:"selfie",event:W?.start_camera,log:{}})},[tu]),e.useEffect(()=>(j.start(),()=>{j.stop()}),[]),e.useEffect(()=>{let e=!1;return async function t(){!ej&&(e1.current=performance.now(),eA.current=await m(eS),await g.initTensorFlow({preferredBackends:["wasm","webgl","cpu"]}),e||(eP(!0),tu({tag:"selfie",event:W?.show_warmup,log:{}}),tu({tag:"selfie",event:W?.finish_load_model,log:{status:"success",time_in_ms:performance.now()-e1.current}}),e1.current=null))}(),()=>{e=!0}},[ej,eS,tu]);let tf=e.useRef(!1),th=e.useCallback(()=>{eJ.current.curStepIndex=eJ.current.steps.length,tf.current=!0,eF(!1),td.current?.discardRecording(),clearInterval(eq.current)},[]),tb=e.useCallback(()=>{eJ.current=a.initFaceVerificationData({assetRoot:eC,customInstructions:J,customIcon:Q,customDirectionIcon:X,Locale:eI,lang:eB}),tm.current=0,tg.current=null,e0.current=[],eL(!1),eX(null),x(),td.current?.start(),tf.current=!1,eK(!1),eN(3),eZ.current=null,eG.current=[],eH.current=null,"function"==typeof eb&&eb(),eD()},[eI,eC,X,Q,J,eK,eB,eb]),tv=e.useCallback(()=>{th(),setTimeout(()=>{tb()},e2)},[e2,tb,th]),tp=e.useMemo(()=>({...A,...er}),[er]),tw=e.useMemo(()=>({...V,...el}),[el]),tk=e.useCallback(()=>{let e={};Object.keys(tp.liveness_terminated_time_out?.msg).forEach(t=>{let s=F(tp.liveness_terminated_time_out?.msg[t]);e[t]=s({x:e3.limitTimeSecond})}),eX({...tp.liveness_terminated_time_out,msg:e,duration:.95*e2}),tu({tag:"selfie",event:W?.show_alert,log:{alert:"liveness_terminated_time_out,"}}),j.stop(),en(""),th()},[tp.liveness_terminated_time_out,e2,e3.limitTimeSecond,th,tu,en]),ty=e.useCallback(({remainTime:e})=>{if(e>0&&e<=e3.remainTimeShow){let t=F(tw.REMAIN_TIME[eB]),s=e;switch(e3.format){case"mm:ss":s=e.toString().padStart(5,"00:00");break;case"ss":s=e.toString().padStart(2,"0")}en(t({x:s}))}},[eB,e3.format,e3.remainTimeShow,tw.REMAIN_TIME,en]),tF=e.useCallback(({attemptCount:e,fromBackground:t})=>{e3.enableMaxRetries&&e>=e3.totalMaxRetries&&ee(n.Errors.max_retry_reached),t&&th(),j.start(),tb()},[e3.enableMaxRetries,e3.totalMaxRetries,ee,tb,th]),{stopTimer:tT}=L({totalTime:e3.limitTimeSecond,totalDelayBetweenReset:e2/1e3,interruptible:e3.interruptible,shouldStart:ew&&e3.enable&&ej,onTimesUp:tk,onTick:ty,onReset:tF}),tL=e.useCallback(({clientWidth:e,clientHeight:t,videoAreaWidth:s,videoAreaHeight:a,lostX:n,lostY:i})=>{let r,l;u.isMobile?l=r=s:r=l=a-200;let c=Math.floor((s-r)/2)+n;eE.current={x:c,y:5+i,width:r,height:l,image:k,surroundStyle:Z},"object"==typeof H?eE.current={...eE.current,...H}:"function"==typeof H&&(eE.current={...eE.current,...H({clientWidth:e,clientHeight:t,videoAreaWidth:s,videoAreaHeight:a,lostX:n,lostY:i,isMobile:u.isMobile,width:r,height:l})}),eD(),ek(!0)},[k,Z,H]),tR=e.useCallback(()=>{eN(3),clearInterval(eq.current),eK(!0);let e=async e=>{if(e-1==0){let e;j.stop(),tT(),clearInterval(eq.current),ei(),await td.current?.stopVideoRecording(),ep(!0),d.addExifData("user_action",{start_selfie:Date.now()-1e3*j.duration("from_1st_frame"),end_selfie:Date.now()});let t=(e=e9.enable?[eZ.current]:eG.current).map(e=>f.resizeBlobImg(e.blob,400,400)),s=(await Promise.all(t)).map((t,s)=>{let a=d.parseLivenessImg({...e[s],gesture:"frontal"});return d.writeCurrentExif({imageData:{blob:t},enableExifData:e6.enable,additionalData:a})}),a=await Promise.all(s),n={};if(e_&&e_.key){let{key:e}=e_,t=a.map(t=>h.encrypt({blob:t,key:e}));n={frontalFacesEncrypted:await Promise.all(t)}}let i=[...e0.current];if(e_&&e_.key){let e=await Promise.all(i.map(e=>e?.base64));if(i=i.map((t,s)=>({...t,base64:e[s]})),ti.enable&&ti.framesBatchLength>0&&i.length%ti.framesBatchLength>0){let e=i.slice(-1*(i.length%ti.framesBatchLength));eo(e),_&&tc.enableUploadFrames&&R(e_,e,eM,i.length===ti.framesBatchLength)}}else ti.enable&&ti.framesBatchLength>0&&i.length%ti.framesBatchLength>0&&(eo(i.slice(-1*(i.length%ti.framesBatchLength)).map(({base64:e,label:t,index:s})=>({base64:e,label:t,index:s}))),_&&tc.enableUploadFrames&&R(e_,i.slice(-1*(i.length%ti.framesBatchLength)),eM));if(_&&tc.enableUploadImages){let t=e=>({label:"portrait",metadata:JSON.stringify({gesture_score:e,gesture:P.FRONTAL})}),s=e.map((e,s)=>eM.uploadImage({file:a[s],...t(e.leftRightScore)}));e_&&e_.key&&(s=e.map((e,s)=>{let a=new Blob([n.frontalFacesEncrypted[s].hex]);return eM.uploadImage({file:a,...t(e.leftRightScore)},{"X-TV-Key":e_.key})}));try{let t=await Promise.all(s),a=null;tc.enableVerifyFaceLiveness&&(a=eM.verifyFaceLiveness({images:t.map(e=>({id:e.data.image_id})),videos:[{frames:i}]}));let n=null;tc.enableVerifySanityPortrait&&(n=eM.requestVerifyPortrait({image:{id:t?.[t.length-1]?.data?.image_id}}));let[r,l]=await Promise.all([a,n]);$({apiCheckPassed:r?.data.is_live??!1,verifyFaceLivenessResult:r?.data??null,verifyFacePortraitResult:l?.data??null,frontalFaces:t.map((t,s)=>({id:t?.data?.image_id,blob:e?.[s]?.blob}))})}catch(e){ee({error:e})}}else $({frontalFaces:a,...n,capturedFrames:i,video:B()}),C()}};eq.current=setInterval(()=>{eN(t=>(e(t),t-1))},tr/3)},[eK,tr,tT,ei,e9.enable,e_,ti.enable,ti.framesBatchLength,_,tc.enableUploadImages,tc.enableUploadFrames,tc.enableVerifyFaceLiveness,tc.enableVerifySanityPortrait,e6.enable,eo,eM,$,ee]),tB=e.useRef({});e.useEffect(()=>{tB.current.isFirstValidFrameFoundRef=eT},[eT]),e.useEffect(()=>{let e,t=eR.current;async function s({faceDirection:e,canvas:t,leftRightScore:s,blurScore:a,isEyeClosed:n}){if(!0===ez.current&&(ts&&e===P.FRONTAL||!ts)){let e=await b.takePicture({canvas:t});e9?.enable&&Date.now()-eH.current<e9?.waitForBestImageTimeMsWeb?(eZ.current||(eZ.current={blob:e,blurScore:a,isEyeClosed:n,captureTime:Date.now()}),tt?.enable&&(eZ.current=I({incomingFrame:{blob:e,blurScore:a,isEyeClosed:n,captureTime:Date.now()},currentBestFrame:eZ.current}))):eG.current.length<1&&eG.current.push({blob:e,leftRightScore:s,captureTime:Date.now(),blurScore:a})}}async function i(r,l){let c,o;if(l?.width===0||l?.height===0)return;let{isFirstValidFrameFoundRef:u}=tB.current,{cropX:m,cropY:g,cropWidth:d,cropHeight:f}=r;l.getContext("2d").drawImage(t,m,g,d,f,-((400*em-400)/2)/em,-((400*em-400)/2)/em,400,400);let{blazefaceModel:h,closeEyesModel:b}=eA.current,[y,F]=await Promise.all([v.calculateBlurScore(l),p.getModelPredictions({model:h,sCanvas:l})]),{error:T,fullFace:L,faceRatio:B,faceNotFrontalMinThreshold:C}=await a.validatePredictions({predictions:F,width:p.SIZE,height:p.SIZE});c=T,eE.current.image=k;let S=null,x=null,I=null,{curStepIndex:M,steps:D}=eJ.current;if(L){I=L.landmarks;let e=await a.calculateFaceDirection({landmarks:I,getPerfectFrontal:!0});e&&(S=e.gesture,x=e.leftRightScore);let t=e7?.webTimeout+Y[n.FaceDirection.FRONTAL].delayTime/1e3;if(e7?.enable&&(-1===j.duration("limit_close_eye")||j.duration("limit_close_eye")<t)){e7?.forceCheck||-1!==j.duration("limit_close_eye")||j.start("limit_close_eye");let{isEyeClose:e}=await b.predict(l,I,e7?.webThreshold);e&&!c&&(c=A.close_eye)}}let V=c?.code==="no_face"||c?.code==="partial_face",N=M<D.length;if(!function({noFace:e,isFirstValidFrameFoundRef:t}){if(!e5.enable||!t)return;let{max_time_ms:s}=e5;tg.current&&e||(tg.current={time:Date.now(),frame:0}),e&&tg.current.frame++;let{time:a}=tg.current;e&&Date.now()-a>=s&&(eX({...tp.liveness_terminated_no_face,duration:e2}),tu({tag:"selfie",event:W?.show_alert,log:{alert:"liveness_terminated_no_face"}}),tv())}({noFace:V&&N,isFirstValidFrameFoundRef:u}),c?.code&&t_({tag:"selfie",event:W?.show_alert,log:{alert:c.code}}),!c||"face_too_small"===c.code&&S!==P.FRONTAL&&B>=C){if(!function(e,t,s,a){if(e0.current.length&&Date.now()-e0.current[e0.current.length-1].time<ti.framesIntervalTime)return;if(ti.enable&&!0){let{topLeft:a,bottomRight:n}=e,i=[...a,...n],{score:r,time:l}=E(e,0===e0.current.length),c={label:"portrait",base64:t.toDataURL("image/jpeg",.8).split(",")[1],landmarks:s,original_landmarks:s,score:r,time:l,index:e0.current.length,bbox:i,original_bbox:i};if(e_&&e_.key){if(c.base64=w.encryptFrameBase64(c.base64,e_.key),e0.current.push(c),ti.framesBatchLength>0&&e0.current.length%ti.framesBatchLength==0&&eo){let e=e0.current.slice(-ti.framesBatchLength);Promise.all(e.map(e=>e?.base64)).then(t=>{eo(e.map(({label:e,index:s},a)=>({base64:t[a],label:e,index:s}))),_&&tc.enableUploadFrames&&R(e_,e.map(({label:e,index:s},a)=>({base64:t[a],label:e,index:s})),eM,e0.current.length===ti.framesBatchLength)})}}else e0.current.push(c),ti.framesBatchLength>0&&e0.current.length%ti.framesBatchLength==0&&eo&&(eo(e0.current.slice(-ti.framesBatchLength).map(({base64:e,label:t,index:s})=>({base64:e,label:t,index:s}))),_&&tc.enableUploadFrames&&R(e_,e0.current.slice(-ti.framesBatchLength),eM,e0.current.length===ti.framesBatchLength));return};}(F[0],l,I),S!==P.FRONTAL&&ts)o=tp.not_frontal_face,eE.current.image=G;else if(!c){u||(eL(!0),j.start("from_1st_frame"));let e=e9?.enable&&!ez.current&&0===eG.current.length;tt?.enable?null!==y&&y>tt?.webBlurryThreshold?(o=null,e&&(eH.current=Date.now(),tR())):ez.current||(o=tp.liveness_blurry):e&&(eH.current=Date.now(),tR());let{isEyeClose:t}=await b.predict(l,I,e7?.webThreshold);await s({faceDirection:S,canvas:l,leftRightScore:x,blurScore:y,...null!==t?{isEyeClosed:t}:{}})}}else M<D.length&&(o=tp[c.code],eE.current.image=G);e$(o),-1!==e&&(e=requestAnimationFrame(()=>i(r,l)))}async function r(){let e=b.analyzeVideoAndWindowSizes(t,eE.current),s=document.createElement("canvas");s.width=400,s.height=400;let a=s.getContext("2d");a.translate(400,0),a.scale(-1*em,+em);let{mediaRecorder:n}=tl&&t?await S({outputImagesSize:400,videoEl:t,resultAnalyzeVideoAndWindowSizes:e}):{};td.current=n,td.current&&td.current.start(),i(e,s)}return ew&&ej&&setTimeout(()=>{r()},ta??eu),()=>{cancelAnimationFrame(e),e=-1}},[eh,ta,ts,tt?.enable,tt?.webBlurryThreshold,e9?.enable,e9?.waitForBestImageTimeMsWeb,eu,ew,eB,eM,_,k,G,$,ee,et,es,ti,ei,e3.enable,en,e$,Y,e2,tv,e5,tp,ej,tu,eo,e_,em,tR,eg,e7?.enable,e7?.webThreshold,e7?.webTimeout,e7?.forceCheck,e6.enable,ex,t_,ti.framesBatchLength,tl,tc.enableUploadFrames]),e.useEffect(()=>{eQ&&(eQ?.code!==tp?.liveness_terminated_time_out&&eQ?.code!==tp?.liveness_terminated_no_face&&e9?.enable&&ez.current||(clearInterval(eq.current),eK(!1),eZ.current=null,eG.current=[],eH.current=null))},[e9?.enable,eQ,eK,tp]);let{curStepIndex:tC,steps:tS}=eJ.current,tx=eT&&!eQ&&!eg&&(!e9?.enable||e9?.showCaptureButton),tI=eU&&!tf.current&&(e9?.enable?e9?.showCountdown:te?.showCountdown);return{resetFlowOnOrientationChange:tn,countdownToTakePicture:eW,cropArea:eE,curStepIndex:tC,faceDetectionError:eQ,resetFlow:tv,handleTriggerPassiveMode:tR,handleVideoPlayed:tL,refVideo:eR,refIsReseting:tf,showCountdown:eU,steps:tS,videoPlayed:ew,activeCapturing:ey,isFirstValidFrameFound:eT,warmupDone:ej,showLoading:ev,showCaptureButton:tx,shouldShowCountdown:tI}}function G({className:e="",fillColor:t=null}){return k.jsxs("svg",{className:e,width:"38px",height:"32px",viewBox:"0 0 24 21","data-testid":"camera-icon",children:[k.jsx("title",{children:"FA45C15C-1E21-4D7B-9585-07FB9F999CB8"}),k.jsx("desc",{children:"Created with sketchtool."}),k.jsx("g",{id:"Web-demo",stroke:"none",strokeWidth:"1",fill:"none",fillRule:"evenodd",children:k.jsx("g",{id:"step1",transform:"translate(-950.000000, -380.000000)",fill:t??"currentColor",fillRule:"nonzero",children:k.jsx("g",{id:"Group",transform:"translate(950.000000, 380.000000)",children:k.jsx("g",{id:"Group-2",children:k.jsx("g",{id:"camera",children:k.jsx("path",{d:"M21,3 L17,3 L15,0 L9,0 L7,3 L3,3 C1.34314575,3 0,4.34314575 0,6 L0,18 C0,19.6568542 1.34314575,21 3,21 L21,21 C22.6568542,21 24,19.6568542 24,18 L24,6 C24,4.34314575 22.6568542,3 21,3 Z M12,17 C9.23857625,17 7,14.7614237 7,12 C7,9.23857625 9.23857625,7 12,7 C14.7614237,7 17,9.23857625 17,12 C17,14.7614237 14.7614237,17 12,17 L12,17 Z",id:"Shape"})})})})})})]})}export{G as C,q as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as e,C as r,T as s,r as n,m as a,c as t,s as o,j as i,a4 as c,b as l,P as u,k as p}from"./chunk-
|
|
1
|
+
import{A as e,C as r,T as s,r as n,m as a,c as t,s as o,j as i,a4 as c,b as l,P as u,k as p}from"./chunk-68e90ba2.js";import{p as m,g as d,S as f,a as h,O as g,C as C,E as j,b as y,B as D,c as F,L as S}from"./chunk-a4a97e90.js";import{u as x,C as b}from"./chunk-147a2e31.js";import{M as T,O as k,W as I,C as E}from"./chunk-5d5d5df1.js";import{D as R}from"./chunk-fbc39ae4.js";import{u as L}from"./chunk-bcf5eed2.js";import"./chunk-7d0d639a.js";import"./chunk-9038aebd.js";import"./chunk-c04f48e4.js";let v=p.isMobile?{width:{ideal:640}}:null;function P(u){let{apiCheck:p,onLivenessDetectionDone:R,captureFrameSettings:P,onFramesCaptured:A,frontCamera:M,flipVideoHorizontal:O,customDirectionIcon:H,customStepTimeConstraints:V,onProcessing:w,customErrors:U,apiCredentials:$,outputEncryptionSettings:_,cameraScale:B,defaultCameraId:K,passiveModeAuto:N,offsetFaceY:z,styledComponent:G,serviceSettings:Y,onReset:W,isLoading:q}=u,J=e(),{onErrorCallback:Q,onCloseCallback:X}=L(),Z=r.useAsset("bg_camera_mask.png"),ee=r.useAsset("bg_camera_mask_red.png"),er=s("IDCapturing.loadingIcon.src","ic_loading.gif"),[es,en]=n.useState({}),{yFaceDetectionError:ea,yFaceVerificationStepsWrapper:et}=es,[eo,ei]=n.useState(""),[ec,el]=n.useState(),eu=n.useMemo(()=>({backgroundColor:a("Selfie.backgroundColor")({theme:J})}),[J]),ep=n.useCallback(({lostY:e,height:r,clientHeight:s})=>{let n=e+25,a=n+30;en({yFaceDetectionError:n,yFaceVerificationStepsWrapper:a+r+20});let t=Math.floor(e),o=Math.floor(s-e),i=Math.floor(a);return 0!==z&&(i+z<t||i+z+r>o)?Q({code:`offsetFaceY must be in [-${i-t}, ${o-r-i}]`}):i+=z,{y:i}},[z,Q]),{shouldResetFlowOnOrientationChange:em,countdownToTakePicture:ed,cropArea:ef,curStepIndex:eh,faceDetectionError:eg,resetFlow:eC,handleTriggerPassiveMode:ej,handleVideoPlayed:ey,refVideo:eD,showCountdown:eF,steps:eS,refIsReseting:ex,videoPlayed:eb,warmupDone:eT,showCaptureButton:ek,shouldShowCountdown:eI,showLoading:eE}=x({currentOrientation:ec,apiCheck:p,bgCameraMask:Z,bgCameraMaskRed:ee,surroundStyle:eu,onLivenessDetectionDone:R,onError:Q,cropAreaDimension:ep,customDirectionIcon:H,captureFrameSettings:P,onFramesCaptured:A,setRemainingTime:ei,customStepTimeConstraints:V,onProcessing:w,customErrors:U,apiCredentials:$,outputEncryptionSettings:_,cameraScale:B,passiveModeAuto:N,serviceSettings:Y,onReset:W});n.useEffect(()=>{"string"==typeof eS[0]?.directionIcon&&Promise.all(eS.map(e=>m(e.directionIcon)))},[eS]);let{CloseCameraButton:eR}=G,eL=d(u,J),ev=ex.current?0:eh/eS.length*100,{lang:eP}=t.useSDKSettings(),eA=n.useRef(0),eM=n.useRef({}),eO=n.useRef(o.ErrorDuration.SHORT),eH=n.useMemo(()=>{let{msg:e,duration:r=o.ErrorDuration.SHORT}=eg||{},s=e?.[eP];return Date.now()-eA.current>=eO.current&&(eA.current=Date.now(),eO.current=r,eM.current=s),eM.current},[eg,eh]),eV=n.useCallback(e=>{el(e),em?eC():e===T.LANDSCAPE?eD.current?.pause():eD.current?.play()},[eD,eC,em]);return i.jsx(k,{onOrientationChange:eV,children:i.jsxs(c,{frontCamera:M,onVideoPlayed:ey,onClose:X,flipHorizontal:O??M,ref:eD,videoSettings:v,onError:Q,scale:B,defaultCameraId:K,closeButton:eR||null,children:[!eT&&i.jsx(I,{}),eb?i.jsxs(i.Fragment,{children:["string"==typeof eH?i.jsx(f,{top:ea-15,className:"face-detection-error",children:eH}):null,ef.current?i.jsxs(E,{x:`${ef.current.x}px`,y:`${ef.current.y}px`,width:`${ef.current.width}px`,height:`${ef.current.height}px`,surroundStyle:ef.current.surroundStyle,children:[i.jsx(h,{}),i.jsx(g,{...eL,progress:ev,showErrorRing:!!eg&&a("Selfie.progressCircle.showErrorRing")({theme:J})}),eI?i.jsx(C,{children:ed}):null,eg&&i.jsx(j,{})]}):null,eo&&i.jsx(y,{top:et-30,children:eo}),ek?i.jsx(D,{children:i.jsx(F,{onClick:ej,disabled:eF,children:l(J,"Selfie.captureIcon.src")?i.jsx("img",{src:l(J,"Selfie.captureIcon.src"),alt:""}):i.jsx(b,{fillColor:"rgba(193, 197, 204, 1)"})})}):null]}):null,(eE||q)&&i.jsx(S,{children:i.jsx("img",{src:er,alt:""})})]})})}P.propTypes={apiCheck:u.bool,mode:u.string,onLivenessDetectionDone:u.func,onClose:u.func,onError:u.func,onReset:u.func,captureFrameSettings:u.shape({}),onFramesCaptured:u.func,frontCamera:u.bool,isLoading:u.bool,flipVideoHorizontal:u.bool,customDirectionIcon:u.shape({}),customStepTimeConstraints:u.shape({}),onProcessing:u.func,customErrors:u.shape({}),apiCredentials:u.shape({accessKey:u.string,secretKey:u.string,apiUrl:u.string}),outputEncryptionSettings:u.shape({}),cameraScale:u.number,defaultCameraId:u.string,passiveModeAuto:u.bool,offsetFaceY:u.number,styledComponent:u.shape({CloseCameraButton:u.node}),serviceSettings:u.shape({})},P.defaultProps={apiCheck:!1,mode:null,onLivenessDetectionDone:null,onClose:null,onError:()=>{},onReset:()=>{},captureFrameSettings:{enable:!1,framesIntervalTime:180,framesBatchLength:0},onFramesCaptured:()=>{},frontCamera:!0,isLoading:!1,flipVideoHorizontal:null,customDirectionIcon:{[o.FaceDirection.LEFT]:i.jsx(R,{type:o.FaceDirection.LEFT}),[o.FaceDirection.RIGHT]:i.jsx(R,{type:o.FaceDirection.RIGHT}),[o.FaceDirection.UP]:i.jsx(R,{type:o.FaceDirection.UP}),[o.FaceDirection.FRONTAL]:i.jsx(R,{type:o.FaceDirection.FRONTAL})},customStepTimeConstraints:{[o.FaceDirection.UP]:{delayTime:0},[o.FaceDirection.LEFT]:{delayTime:0},[o.FaceDirection.RIGHT]:{delayTime:0},[o.FaceDirection.FRONTAL]:{delayTime:2e3}},onProcessing:()=>{},customErrors:null,apiCredentials:{accessKey:"",secretKey:"",apiUrl:""},outputEncryptionSettings:null,cameraScale:1,defaultCameraId:void 0,passiveModeAuto:!1,offsetFaceY:0,styledComponent:{CloseCameraButton:null},serviceSettings:{enableUploadFrames:!0,enableUploadImages:!0,enableVerifySanityPortrait:!0,enableVerifySanityIDCard:!0,enableVerifyFaceLiveness:!0,enableDetectIDCardTampering:!0,enableReadIDCardInfo:!0}};export{P as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as e,C as r,T as s,r as t,m as n,aI as a,b as o,c as i,s as c,j as l,a4 as u,az as m,a7 as p,W as d,P as h,k as g,aJ as f}from"./chunk-
|
|
1
|
+
import{A as e,C as r,T as s,r as t,m as n,aI as a,b as o,c as i,s as c,j as l,a4 as u,az as m,a7 as p,W as d,P as h,k as g,aJ as f}from"./chunk-68e90ba2.js";import{M as j,O as x,W as y,C as C}from"./chunk-5d5d5df1.js";import{u as F}from"./chunk-39db42b0.js";import{D as D}from"./chunk-fbc39ae4.js";import{p as S,d as b,e as v,A as T,f as k,I as I,h as E,F as _,i as V,j as L,T as R,L as w,k as A,l as P,S as H}from"./chunk-a4a97e90.js";import{u as N}from"./chunk-bcf5eed2.js";import"./chunk-5993adde.js";import"./chunk-7d0d639a.js";import"./chunk-9038aebd.js";import"./chunk-c04f48e4.js";let M=g.isMobile?{width:{ideal:640}}:null,$=({stepNumber:e,type:r,theme:s})=>{let t=f(`instruction_${r}.svg`),n=o(s,`Selfie.Active.imageHolder.${r}`);return null===n?l.jsx(l.Fragment,{}):"string"==typeof n&&""!==n?l.jsx("img",{src:n,alt:""}):"v1"===o(s,"themeVersion")?l.jsx("span",{children:e}):l.jsx("img",{src:t,alt:""})};function O(h){var f,D;let{apiCheck:O,onLivenessDetectionDone:U,captureFrameSettings:B,onFramesCaptured:K,frontCamera:z,flipVideoHorizontal:W,customDirectionIcon:G,customStepTimeConstraints:Y,onProcessing:J,customErrors:q,apiCredentials:Q,outputEncryptionSettings:X,cameraScale:Z,defaultCameraId:ee,offsetFaceY:er,isLoading:es,serviceSettings:et,onReset:en}=h,ea=e(),{onErrorCallback:eo,onCloseCallback:ei}=N(),ec=r.useAsset("bg_camera_mask.png"),el=r.useAsset("bg_camera_mask_red.png"),eu=s("IDCapturing.loadingIcon.src","ic_loading.gif"),[em,ep]=t.useState({}),{yFaceVerificationStepsWrapper:ed,yFaceDetectionError:eh,yCountdown:eg}=em,[ef,ej]=t.useState(""),[ex,ey]=t.useState(),eC=t.useMemo(()=>({backgroundColor:n("Selfie.backgroundColor")({theme:ea})}),[ea]);a(o(ea,"themeVersion"),"up_arrow.gif"),a(o(ea,"themeVersion"),"left_arrow.gif"),a(o(ea,"themeVersion"),"right_arrow.gif"),a(o(ea,"themeVersion"),"frontal_arrow.svg"),a(o(ea,"themeVersion"),"instruction_up.svg"),a(o(ea,"themeVersion"),"instruction_left.svg"),a(o(ea,"themeVersion"),"instruction_right.svg"),a(o(ea,"themeVersion"),"instruction_frontal.svg");let eF=t.useCallback(({lostY:e,height:r,clientHeight:s})=>{let t=g.isMobile?e:e+80,n=t+r+20,a=n+110;ep({yFaceDetectionError:a+30,yCountdown:a,yFaceVerificationStepsWrapper:n});let o=Math.floor(e),i=Math.floor(s-e),c=Math.floor(t);return 0!==er&&(c+er<o||c+er+r>i)?eo({code:`offsetFaceY must be in [-${c-o}, ${i-r-c}]`}):c+=er,{y:c}},[er,eo]),{shouldResetFlowOnOrientationChange:eD,cropArea:eS,curStepIndex:eb,directionIcon:ev,directionIconAnimation:eT,faceDetectionError:ek,resetFlow:eI,handleVideoPlayed:eE,instructions:e_,refVideo:eV,refIsReseting:eL,steps:eR,videoPlayed:ew,activeCapturing:eA,warmupDone:eP,showLoading:eH}=F({currentOrientation:ex,apiCheck:O,bgCameraMask:ec,bgCameraMaskRed:el,surroundStyle:eC,onLivenessDetectionDone:U,onError:eo,cropAreaDimension:eF,customDirectionIcon:G,captureFrameSettings:B,onFramesCaptured:K,setRemainingTime:ej,customStepTimeConstraints:Y,onProcessing:J,customErrors:q,apiCredentials:Q,outputEncryptionSettings:X,cameraScale:Z,serviceSettings:et,onReset:en});t.useEffect(()=>{"string"==typeof eR[0]?.directionIcon&&Promise.all(eR.map(e=>S(e.directionIcon)))},[eR]);let eN=b(h,ea),eM=eL.current?0:eb/eR.length*100,{lang:e$}=i.useSDKSettings(),eO=t.useRef(0),eU=t.useRef({}),eB=t.useRef(c.ErrorDuration.SHORT),eK=t.useMemo(()=>{let{msg:e,duration:r=c.ErrorDuration.SHORT}=ek||{},s=e?.[e$];return Date.now()-eO.current>=eB.current&&(eO.current=Date.now(),eB.current=r,eU.current=s),eU.current},[ek,eb]),ez=t.useCallback(e=>{ey(e),eD?eI():e===j.LANDSCAPE?eV.current?.pause():eV.current?.play()},[eV,eI,eD]);return l.jsx(x,{onOrientationChange:ez,children:l.jsxs(u,{frontCamera:z,onVideoPlayed:eE,onClose:ei,flipHorizontal:W??z,ref:eV,videoSettings:M,onError:eo,scale:Z,defaultCameraId:ee,closeButton:l.jsx(m,{}),children:[!eP&&l.jsx(y,{}),ew?l.jsxs(l.Fragment,{children:[eS.current?l.jsxs(C,{x:`${eS.current.x}px`,y:`${eS.current.y}px`,width:`${eS.current.width}px`,height:`${eS.current.height}px`,surroundStyle:eS.current.surroundStyle,children:[l.jsx(v,{padding:T}),l.jsx(k,{...eN,progress:eM,showErrorRing:!!ek}),l.jsx(I,{children:(f=ev,D=eT,f?"string"==typeof f?l.jsx("img",{className:D,src:f,alt:"",style:{maxWidth:"98px",maxHeight:"98px",marginBottom:"25px"}}):f:null)}),eA&&l.jsx(E,{})]}):null,e_?l.jsxs(l.Fragment,{children:[l.jsx(_,{top:ed+5,className:"instructions",children:e_}),l.jsx(V,{top:ed+40,children:eR.map((e,r)=>{let{name:s,image:{objUrl:t}}=e;return l.jsx(L,{active:eb>=r,className:"step-item",children:t?l.jsx("img",{className:"image_preview",src:t,alt:""}):l.jsx($,{stepNumber:r+1,type:s,theme:ea})},s)})})]}):null]}):null,l.jsx(R,{y:"20px",children:l.jsx(p,{id:"flash_liveness.title"})}),(eH||es)&&l.jsx(w,{children:l.jsx("img",{src:eu,alt:""})}),ef&&l.jsxs(A,{top:eg,children:[l.jsx(d,{color:n("Selfie.countdown.color")({theme:ea})}),l.jsx(P,{children:ef})]}),"string"==typeof eK?l.jsx(H,{top:eh,className:"face-detection-error",children:eK}):null]})})}O.propTypes={apiCheck:h.bool,onLivenessDetectionDone:h.func,onClose:h.func,onError:h.func,onReset:h.func,captureFrameSettings:h.shape({}),onFramesCaptured:h.func,flipVideoHorizontal:h.bool,frontCamera:h.bool,isLoading:h.bool,customDirectionIcon:h.shape({}),customStepTimeConstraints:h.shape({}),onProcessing:h.func,customErrors:h.shape({}),apiCredentials:h.shape({accessKey:h.string,secretKey:h.string,apiUrl:h.string}),outputEncryptionSettings:h.shape({}),cameraScale:h.number,defaultCameraId:h.string,offsetFaceY:h.number,styledComponent:h.shape({CloseCameraButton:h.node}),serviceSettings:h.shape({})},O.defaultProps={apiCheck:!1,onLivenessDetectionDone:null,onClose:null,onError:()=>{},onReset:()=>{},captureFrameSettings:{enable:!1,framesIntervalTime:180,framesBatchLength:0},onFramesCaptured:()=>{},flipVideoHorizontal:null,frontCamera:!0,isLoading:!1,customDirectionIcon:{[c.FaceDirection.LEFT]:l.jsx(D,{type:c.FaceDirection.LEFT}),[c.FaceDirection.RIGHT]:l.jsx(D,{type:c.FaceDirection.RIGHT}),[c.FaceDirection.UP]:l.jsx(D,{type:c.FaceDirection.UP}),[c.FaceDirection.FRONTAL]:l.jsx(D,{type:c.FaceDirection.FRONTAL})},customStepTimeConstraints:{[c.FaceDirection.UP]:{delayTime:0},[c.FaceDirection.LEFT]:{delayTime:0},[c.FaceDirection.RIGHT]:{delayTime:0},[c.FaceDirection.FRONTAL]:{delayTime:2e3}},onProcessing:()=>{},customErrors:null,apiCredentials:{accessKey:"",secretKey:"",apiUrl:""},outputEncryptionSettings:null,cameraScale:1,defaultCameraId:void 0,offsetFaceY:0,styledComponent:{CloseCameraButton:null},serviceSettings:{enableUploadFrames:!0,enableUploadImages:!0,enableVerifySanityPortrait:!0,enableVerifySanityIDCard:!0,enableVerifyFaceLiveness:!0,enableDetectIDCardTampering:!0,enableReadIDCardInfo:!0}};export{O as default};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
let e,t;import{r as r,i as a,j as o,e as i,
|
|
1
|
+
let e,t;import{r as r,i as a,j as o,e as i,G as n,aE as l,I as s,au as c,aF as u,aG as h,s as d,c as f,J as m,t as g,aH as _,v as p,av as b,k as y,K as w,P as E,d as C}from"./chunk-68e90ba2.js";import{W as v}from"./chunk-5d5d5df1.js";let A=({onVideoPlayed:e})=>{let[t,a]=r.useState(!1),[o,i]=r.useState({});return{onVideoPlayed:r.useCallback(t=>{i((e=>{let{videoAreaWidth:t,videoAreaHeight:r,lostX:a,lostY:o}=e;return{width:t,height:r,x:Math.max(a,0),y:Math.max(o,0)}})(t)),a(!0),"function"==typeof e&&e(t)},[e]),cropArea:o,isPlaying:t}},F={LOADING:"loading",FAR_FACE:"far_face",CLOSE_FACE:"close_face",START_FLASHING:"start_flashing",STOP_DECTECTING:"stop_detecting"},R={FAR_FACE:"far",CLOSE_FACE:"close",FLASHING:"flashing"},S={timeout:"timeout",no_face:"no_face"},x=({prediction:e,canvas:t,index:r,quality:a=.8})=>{let o=t.toDataURL("image/jpeg",a);return e?{label:"portrait",base64:o.split(",")[1],landmarks:e.landmarks,index:r}:{label:"portrait",base64:o.split(",")[1],index:r}},k=a.div`
|
|
2
2
|
position: fixed;
|
|
3
3
|
top: 0;
|
|
4
4
|
left: 0;
|
|
@@ -7,4 +7,4 @@ let e,t;import{r as r,i as a,j as o,e as i,F as n,aE as l,J as s,au as c,aF as u
|
|
|
7
7
|
z-index: 1001;
|
|
8
8
|
|
|
9
9
|
background-color: ${e=>e.$overlay?"white":"transparent"};
|
|
10
|
-
`,T=({children:e=null,overlay:t=!1,loadingComponent:r=o.jsx(v,{})})=>o.jsxs(k,{$overlay:t,children:[t&&r,o.jsx("div",{style:{visibility:t?"hidden":"visible"},children:e})]}),L=(e,t,r)=>{let{smallScale:a,largeScale:o,ovalPadding:i}=e,n=t.width/t.height,l=a*r.height,s=o*r.height,c=i.top+i.bottom,u=i.left+i.right,h=s-c;if(parseFloat((h*n).toFixed(2))+u>r.width){let e=Number(((r.width-u)/t.width).toFixed(2));return{smallScale:Number((a/o*e).toFixed(2)),largeScale:e}}let d=Number(((l-c)/t.height).toFixed(2));return{smallScale:d,largeScale:Number((h/t.height).toFixed(2))}},M=({offset:e,ovalPadding:t,largeScale:r,ovalHeight:a,maskHeight:o})=>{let i=a/2+t.bottom;return(i+e)*r>o/2?o/2/r-i:e},P=e=>{r.useEffect(()=>()=>{e&&e.srcObject?.getTracks().forEach(e=>{e.stop()})},[e])},O=()=>{let[e,t]=r.useState(null),[a,o]=r.useState(!1),i=r.useRef(null);return r.useEffect(()=>{if(!i.current)return()=>{};let e=i.current,r=()=>{t(e.getBoundingClientRect()),o(!1)},a=()=>{o(!0)};return e.addEventListener("transitionstart",a),e.addEventListener("transitionend",r),()=>{e.removeEventListener("transitionstart",a),e.removeEventListener("transitionend",r)}},[]),[i,e??i.current?.getBoundingClientRect(),a,o]},B=()=>{let e=r.useRef(),{sendEvent:t}=i.useSDKTracking();return r.useCallback((r,a,o={})=>{let i=performance.now(),n={};"object"==typeof o&&(n={...o},e.current&&(n.interval_vs_previous_in_ms=Math.round(i-e.current))),"function"==typeof o&&(n=o({lastTimeLog:e.current})),e.current=i,t({tag:r,event:a,log:n})},[t])},D=(e,t)=>{let a=r.useRef(e);r.useEffect(()=>{a.current=e},[e]),r.useEffect(()=>{t&&"function"==typeof a.current&&a.current()},[t])},N=({compareFn:e,duration:t,minFrames:a=null})=>{let o=r.useRef(null),i=r.useRef(!1),n=r.useRef(0),l=r.useRef(()=>{}),{compareAndStoreResult:s,getBestResult:c,reset:u}=r.useMemo(()=>{var r,a;let o,i,n;return r=e,a=t,o=null,i=null,n=()=>null!==i&&performance.now()-i>a,{checkIsTimeUp:n,compareAndStoreResult:e=>{null===o&&(o=e,i=performance.now()),n()||r(o,e)&&(o=e)},getBestResult:()=>o,reset:()=>{o=null,i=null}}},[e,t]),h=r.useCallback(()=>{u(),n.current=0,i.current=!1,o.current&&(clearTimeout(o.current),o.current=null)},[u]),d=r.useCallback(()=>null!==o.current,[]),f=r.useCallback(e=>{if(s(e),n.current+=1,!i.current||"number"!=typeof a||n.current<a)return;let t=c();l.current(t),h()},[s,c,a,h]),m=r.useCallback(({initialFrame:e,onDone:r})=>{l.current=r,f(e),o.current=setTimeout(()=>{if(i.current=!0,"number"==typeof a&&n.current<a)return;let e=c();l.current(e),h()},t)},[f,t,c,a,h]);return r.useEffect(()=>()=>{clearTimeout(o.current)},[]),r.useMemo(()=>({captureFrame:f,getBestResult:c,isAutoCapturing:d,startCapturing:m,stopCapturing:h}),[f,c,d,m,h])},I=e=>{let t=document.createElement("canvas");return t.setAttribute("width",e.videoWidth.toString()),t.setAttribute("height",e.videoHeight.toString()),t.getContext("2d").drawImage(e,0,0,e.videoWidth,e.videoHeight),t},j=()=>{let[e,t]=r.useState(Date.now());return{sessionId:e,updateSessionId:r.useCallback(()=>{t(Date.now())},[])}},z=(e,t)=>{if(0===Object.keys(e).length)return{topLeft:[0,0],bottomRight:[0,0],probability:0,landmarks:[]};let r=e.topLeft??[0,0],a=e.bottomRight??[0,0],o=e.probability??0,i=e.landmarks??[];return{topLeft:[r[0]*t,r[1]*t],bottomRight:[a[0]*t,a[1]*t],probability:o,landmarks:i.map(e=>[e[0]*t,e[1]*t])}},W=200,q=({size:e,scale:t=1,video:r,baseSize:a=W})=>{let{width:o,height:i}=e,{videoWidth:n=Number.MAX_SAFE_INTEGER,videoHeight:l=Number.MAX_SAFE_INTEGER}=r??{},s=Math.min(o,i)/a,c=Math.round(o/s*t),u=Math.round(i/s*t);return c>n||u>l?{width:o,height:i}:{width:c,height:u}},G=({width:e,height:t,cameraScale:r})=>{let a=document.createElement("canvas");a.width=e,a.height=t;let o=a.getContext("2d");return o?(o.translate(e,0),o.scale(-1*r,+r)):console.error("Failed to get 2D context from canvas in createLivenessCanvas"),a},H=({maskBoundingBox:e,faceRatio:t,validFaceRatio:r,video:a,shouldCropCenterSquare:o=!0,cropArea:i,frame:l,facePrediction:s,detectionToWholeFaceRatio:c=.8})=>{let u=e.width*t/r,h=u/e.width,d=e.height*h,f={x:e.x-(u-e.width)/2,y:e.y-(d-e.height)/2,width:u,height:d};f.x+f.width>i.x+i.width&&(f.width=i.width,f.x=i.x),f.y+f.height>i.y+i.height&&(f.height=i.height,f.y=i.y);let m=null;if(o){let e=Math.min(f.width,f.height),t=(s.bottomRight[1]-s.topLeft[1])/c,r=s.bottomRight[1]-t+(t-e)/2+i.y;r+e>f.y+f.height&&(r=f.y+f.height-e);let o={x:f.x+f.width/2-e/2,y:r,width:e,height:e};m=n.analyzeVideoAndWindowSizes(a,o)}else m=n.analyzeVideoAndWindowSizes(a,f);let g=q({size:{width:m.cropWidth,height:m.cropHeight},baseSize:400,video:a}),_=G({width:g.width,height:g.height,cameraScale:1}),p=_.width,b=_.height;return _.getContext("2d").drawImage(l,m.cropX,m.cropY,m.cropWidth,m.cropHeight,0,0,p,b),_},V=l(async function e({tfScriptUrls:t,closeEyesModelUrl:r,blazefaceModelUrl:a,qualifyModelUrl:o,opencvUrl:i}={}){let n=new u(r),l=new h(o),d=new c;await s.loadTensorFlow(t),await s.initTensorFlow({preferredBackends:["wasm","cpu"]});let f=[s.loadBlazefaceModel({modelUrl:a}),n.load(),l.init({opencvUrl:i}),c.init({opencvUrl:i})],[{blazefaceModel:m}]=await Promise.all(f);return{closeEyesModel:n,blazefaceModel:m,notQualifiedModel:l,brightnessDetector:d}}),U=({width:e,height:t,cameraScale:a=1,debug:o=!1})=>{let[i,n]=r.useState(null);return r.useEffect(()=>{let r=G({width:e,height:t,cameraScale:a});return o&&(document.body.appendChild(r),r.style.position="fixed",r.style.top="0",r.style.left="0",r.style.zIndex="9999"),n(r),()=>{o&&document.body.removeChild(r)}},[a,o,t,e]),i},K=y.isMobile?200:400;function J({cameraScale:e=1,isVideoPlaying:t,step:a,cropArea:o,videoRef:i,onFarFaceDetected:l,onFarFullFaceDetected:s,onCloseFaceDetected:c,onCloseFullFaceDetected:u,onFlashingFramesCaptured:h,frameInterval:y=0,useFaceDetectorWhenFlashing:w,onFaceError:E,onError:C,maskBoundingRect:v,shouldPauseFaceDetection:A,shouldContinueOnError:R,debug:S=!1,faceDetectionSettings:x}){let{faceSettings:k,maskSettings:T,closeEyesSettings:L,captureFrameSettings:M,blurCheckFarSettings:P,blurCheckCloseSettings:O,brightnessDetectionFarSettings:B,brightnessDetectionCloseSettings:D,notQualifiedFarSettings:N,notQualifiedCloseSettings:I,frontalFaceCheckSettings:j}=x,{chinToMaskBottomPadding:W}=T,{frameScale:G}=M,{enable:H,timeout:J,forceCheck:X}=L,{enable:$,upDownBoundMin:Y,upDownBoundMax:Q}=j,{minFarFaceRatio:Z,maxFarFaceRatio:ee,closeFaceRatio:et}=k,er=(e=>{let[t,a]=r.useState(e);return r.useEffect(()=>{(async()=>{try{let t=Math.max(16.666666666666668,33.333333333333336,e);a(t)}catch(e){console.error(e),a(20)}})()},[e]),t})(y),ea=(({videoRef:e,cropArea:t})=>r.useMemo(()=>e.current&&0!==Object.keys(t).length?n.analyzeVideoAndWindowSizes(e.current,t):{},[e,t]))({videoRef:i,cropArea:o}),eo=q({size:{width:ea.cropWidth,height:ea.cropHeight},scale:G,video:i.current}),ei=(({cropArea:e,maskBoundingRect:t,baseSize:r})=>{let{width:a,height:o,x:i,y:n}=e,l=Math.min(a,o)/r,s=t?.left??0,c=t?.top??0,u=t?.right??a;return{left:Math.max((s-i)/l,0),right:Math.min((u-i)/l,a/l),top:Math.max((c-n)/l,0),bottom:Math.min(((t?.bottom??o)-n)/l,o/l)}})({cropArea:o,maskBoundingRect:v,baseSize:Math.min(eo.width,eo.height)}),en=U({width:eo.width,height:eo.height,cameraScale:e}),el=Math.min(o.width,o.height)/Math.min(eo.width,eo.height),es=U({width:K,height:K*(eo.height/eo.width),cameraScale:e,debug:S}),ec=(({width:e,height:t,debug:a})=>{let o=r.useRef(null),i=r.useMemo(()=>{let r=document.createElement("canvas");return r.width=e,r.height=t,r.style.position="fixed",r.style.bottom="0",r.style.left="0",r.style.zIndex="99999",o.current=r,a&&document.body.appendChild(r),r},[t,e,a]);return r.useEffect(()=>()=>{a&&document.body.removeChild(o.current)},[a]),i})({width:160,height:150,debug:S}),{customUrls:eu}=f.useSDKSettings(),[eh,ed]=((e,t)=>{let[a,o]=r.useState({}),i=Object.keys(a).length>0;return r.useEffect(()=>{let r=!1;return(async()=>{try{let t=await V(e);if(r)return;o(t)}catch(e){t({...d.Errors.unable_to_load_model,details:e}),console.error(e)}})(),()=>{r=!0}},[i,e,t]),[a,i]})(eu,C),ef=r.useRef(null),{markTime:em,checkIfEllapsed:eg}=(({timeout:e})=>{let t=r.useRef(null),a=r.useCallback(()=>{t.current=performance.now()},[]),o=r.useCallback(()=>null===t.current?(a(),!1):performance.now()-t.current>e,[a,e]);return{markTime:a,checkIfEllapsed:o}})({timeout:1e3*J}),e_=ed&&t,{closeEyesModel:ep,blazefaceModel:eb,notQualifiedModel:ey,brightnessDetector:ew}=eh,eE=r.useCallback(async(e,t)=>{try{if(t?.width===0||t?.height===0||null===i.current||A||a===F.STOP_DECTECTING)return;let{cropX:n,cropY:f,cropWidth:y,cropHeight:C}=e,v=t.width,x=t.height;t.getContext("2d").drawImage(i.current,n,f,y,C,0,0,v,x);let k=m.drawToSquareCanvas(t),T=K/v;if(S&&es.getContext("2d").drawImage(i.current,n,f,y,C,0,0,v*T,x*T),!w&&a===F.START_FLASHING){"function"==typeof h&&await h({prediction:null,originalRatio:el,canvas:t});return}let L=await g.getModelPredictions({model:eb,sCanvas:k}),M=[[ei.left,ei.top],[ei.right,ei.bottom]],{error:j,fullFace:q,faceRatio:G}=await _.validatePredictions({predictions:L,cropAreaCoordinates:M});if(S){var r,o;let e,t={left:ei.left*T,top:ei.top*T,right:ei.right*T,bottom:ei.bottom*T};r=es,o={x:t.left,y:t.top,width:t.right-t.left,height:t.bottom-t.top},e=r.getContext("2d"),e?(e.strokeStyle="red",e.lineWidth=1,e.beginPath(),e.rect(o.x,o.y,o.width,o.height),e.stroke(),e.closePath()):console.warn("drawBoundingBox: 2D context is not available.");let a=L.map(e=>z(e,T));((e,t,r=!1)=>{let a=e.getContext("2d");if(!a)return;let o=e.width;a.strokeStyle="blue",a.fillStyle="blue",a.lineWidth=1,t.forEach(e=>{e.landmarks.forEach(e=>{a.beginPath(),a.arc(r?o-e[0]:e[0],e[1],2,0,2*Math.PI),a.fill(),a.closePath()}),a.beginPath();let t={x:r?o-e.bottomRight[0]:e.bottomRight[0],y:e.topLeft[1],width:e.bottomRight[0]-e.topLeft[0],height:e.bottomRight[1]-e.topLeft[1]};a.rect(t.x,t.y,t.width,t.height),a.stroke(),a.closePath()})})(es,a,!0)}let V=d.FaceDirection.FRONTAL;if(q&&$){let e=await _.calculateFaceDirection({landmarks:q.landmarks,upDownBound:{lower:Y,upper:Q}});V=e?.gesture??""}(q||j?.code===d.Errors.partial_face.code)&&a===F.FAR_FACE&&"function"==typeof l&&await l({prediction:L[0],originalRatio:el,canvas:t}),(q||j?.code===d.Errors.partial_face.code)&&a===F.CLOSE_FACE&&"function"==typeof c&&await c({prediction:L[0],originalRatio:el,canvas:t});let U=j?.code;try{if(U===d.Errors.no_face.code)throw Error("no_face");if(U===d.Errors.multiple_faces.code){let e=_.calculateFaceArea(L[0]),t=_.calculateFaceArea(L[1]);if(e<=2*t)throw Error("multiple_faces")}if(V!==d.FaceDirection.FRONTAL)throw Error("face_not_frontal");if(U===d.Errors.partial_face.code){let e=_.cropFaceInsideBox([L[0].topLeft,L[0].bottomRight],M);if(p.rectEdgeRatio(e,M)>.95)throw Error("face_too_large")}if(a===F.FAR_FACE){if(G>ee)throw Error("face_too_large");if(G<Z)throw Error("face_too_small")}if(a===F.CLOSE_FACE&&G<et)throw Error("face_too_small");if(Array.isArray(L)&&L.length>0&&ei.bottom-L[0].bottomRight[1]>W)throw Error("face_too_high");if(U===d.Errors.face_out_of_box.code&&(a===F.FAR_FACE&&G>=Z&&G<=ee||a===F.CLOSE_FACE&&G>=et))throw Error("")}catch(e){U=e.message}let J=null;if(H)if(U)em();else{let e=await ep.predict(t,q.landmarks),r=!X&&eg();J=e.isEyeClose,e.isEyeClose&&!r&&(U="eye_close")}let er=null,ea=a===F.FAR_FACE?B:D;if((ea.enableTooBrightCheck||ea.enableTooDarkCheck)&&Array.isArray(L)&&L.length>0){let e=[[Math.max(L[0].topLeft[1],0),Math.min(L[0].bottomRight[0],t.width),Math.min(L[0].bottomRight[1],t.height),Math.max(L[0].topLeft[0],0)]],{score:r,message:a}=ew.score(t,e,ea.tooDarkThreshold,ea.tooBrightThreshold);er=r,""===U&&ea.enableTooBrightCheck&&"face_too_bright"===a&&(U="face_too_bright"),""===U&&ea.enableTooDarkCheck&&"face_too_dark"===a&&(U="face_too_dark")}let eo=0,en={enable:a===F.FAR_FACE?P.enable:O.enable,threshold:a===F.FAR_FACE?P.threshold:O.threshold};en.enable&&(eo=await b.calculateBlurScore(t),""!==U||b.hasBetterBlurScore(eo,en.threshold)||(U="blurry_face"));let eu=0,eh=0,ed="model_not_run",ef={enable:a===F.FAR_FACE?N.enable:I.enable,threshold:a===F.FAR_FACE?N.threshold:I.threshold};if(ef.enable&&q&&q.landmarks){let[e,r,a,o]=await ey.predict(t,q.landmarks,ef.threshold);eu=r,eh=o,ed=a,""!==U||e||(U="face_not_qualified")}if((S&&m.drawDebugCanvas(ec,{error:U,ovalFaceRatio:G?.toFixed(3)??"null",ovalError:j?.code??"null",step:a===F.FAR_FACE?"far":"close",blurScore:eo.toFixed(3),qualifyScore:eu.toFixed(3),brightnessScore:er?.toFixed(3)??"null"}),U)&&("function"==typeof E&&await E({error:U,currentStep:a}),!R))return;let e_=q,eE=G;if(!e_&&R&&(e_=Array.isArray(L)&&L.length>0?L[0]:{},eE=a===F.FAR_FACE?ee:et),a===F.FAR_FACE&&e_&&Z<=eE&&eE<=ee&&"function"==typeof s)return void await s({prediction:e_,originalRatio:el,canvas:t,frame:{faceRatio:eE,isEyeClosed:J,blurScore:eo,qualifyScore:eu,realQualifyScore:eh,qualifyModelMessage:ed,brightnessScore:er,faceError:U}});if(e_&&a===F.CLOSE_FACE&&eE>=et&&"function"==typeof u)return void await u({prediction:e_,originalRatio:el,canvas:t,frame:{faceRatio:eE,isEyeClosed:J,blurScore:eo,qualifyScore:eu,realQualifyScore:eh,qualifyModelMessage:ed,brightnessScore:er,faceError:U}});w&&e_&&a===F.START_FLASHING&&eE>=et&&"function"==typeof h&&await h({prediction:e_,originalRatio:el,canvas:t,faceError:U})}catch(e){console.error(e),C({error:e})}},[i,A,a,S,w,eb,ei.left,ei.top,ei.right,ei.bottom,$,H,B,D,P.enable,P.threshold,O.enable,O.threshold,N.enable,N.threshold,I.enable,I.threshold,R,Z,ee,et,es,h,el,Y,Q,l,c,W,ep,X,eg,em,ew,ey,ec,E,s,u,C]);return r.useEffect(()=>{let e=null,t=!1;return e_&&function r(){e=requestAnimationFrame(async e=>{t||null===i.current||((null===ef.current&&(ef.current=e),e-ef.current<er)?r():(ef.current=e,await eE(ea,en),r()))})}(),()=>{t=!0,cancelAnimationFrame(e)}},[en,ea,eE,e_,i,er]),{warmupDone:ed}}let X=e=>{let{shouldStart:t,totalTime:a,totalDelay:o,onError:i,onTimeout:n,onDelayEnd:l,maxRetriesSettings:s,interruptible:c=!0}=e,u=r.useRef(new w({totalTime:a,interruptible:c,totalDelayBetweenReset:o})),[h,f]=r.useState(a);return r.useEffect(()=>u.current.on("tick",({remainTime:e})=>{f(e)}),[n]),r.useEffect(()=>u.current.on("delaystart",({attemptCount:e})=>{s.enable&&e>=s.total?i(d.Errors.max_retry_reached):n()}),[s.enable,s.total,i,n]),r.useEffect(()=>u.current.on("delayend",()=>{l()}),[l]),r.useEffect(()=>u.current.on("reset",({attemptCount:e,fromBackground:t})=>{s.enable&&e>=s.total&&i(d.Errors.max_retry_reached),t&&(n(),l())}),[n,l,s.enable,s.total,i]),r.useEffect(()=>t?u.current.start():()=>{},[t]),{remaining:h}},$=e=>{switch(e){case"partial_face":return"flash_liveness.error.partial_face";case"no_face":case"face_out_of_box":return"flash_liveness.error.no_face";case"face_too_small":return"flash_liveness.error.face_too_small";case"face_too_large":return"flash_liveness.error.face_too_large";case"eye_close":return"flash_liveness.error.close_eye";case"face_not_frontal":return"flash_liveness.error.face_not_frontal";case"multiple_faces":return"flash_liveness.error.multiple_faces";case"face_too_high":return"flash_liveness.error.face_too_high";case"blurry_face":return"flash_liveness.error.face_too_blurry";case"face_not_qualified":return"flash_liveness.error.face_not_qualified";case"face_too_bright":return"flash_liveness.error.face_too_bright";case"face_too_dark":return"flash_liveness.error.face_too_dark";default:return""}},Y=e=>Array.isArray(e)?e.map(({base64:e,label:t,index:r,metadata:a})=>({base64:e,label:t,index:r,metadata:a})):e,Q=r.createContext({enable:!1,key:""}),Z=({children:e,settings:t})=>{let a=r.useMemo(()=>{let e=t?.key??"";return{enable:!!e,key:e}},[t?.key]);return o.jsx(Q.Provider,{value:a,children:e})};Z.propTypes={children:E.node.isRequired,settings:E.shape({key:E.string})},Z.defaultProps={settings:{key:""}};let ee=()=>r.useContext(Q),et=r.createContext({}),er=({apiCredentials:e,children:t})=>{let{apiClient:r}=C.useApiClient({apiCredentials:e});return o.jsx(et.Provider,{value:r,children:t})};er.propTypes={apiCredentials:E.shape({accessKey:E.string.isRequired,secretKey:E.string.isRequired,apiUrl:E.string.isRequired}),children:E.node.isRequired},er.defaultProps={apiCredentials:{}};let ea=()=>r.useContext(et);let eo=(e=[],t=async()=>(await Promise.all(e)).map(e=>({id:e?.data?.file_id??-1})),{uploadFrameBatch:(t,r,a)=>{let o=new Blob([JSON.stringify(t)]);e.push(r.uploadFile({file:o,metadata:JSON.stringify({type:"selfie"}),label:"video"},a))},getAllUploadedBatches:t,resetUploadBatches:()=>{e.length=0}});export{er as A,R as F,Z as O,S as R,F as S,T as W,O as a,N as b,j as c,A as d,I as e,x as f,J as g,P as h,D as i,X as j,H as k,M as l,$ as m,L as n,ee as o,ea as p,eo as q,Y as r,z as s,B as u};
|
|
10
|
+
`,T=({children:e=null,overlay:t=!1,loadingComponent:r=o.jsx(v,{})})=>o.jsxs(k,{$overlay:t,children:[t&&r,o.jsx("div",{style:{visibility:t?"hidden":"visible"},children:e})]}),L=(e,t,r)=>{let{smallScale:a,largeScale:o,ovalPadding:i}=e,n=t.width/t.height,l=a*r.height,s=o*r.height,c=i.top+i.bottom,u=i.left+i.right,h=s-c;if(parseFloat((h*n).toFixed(2))+u>r.width){let e=Number(((r.width-u)/t.width).toFixed(2));return{smallScale:Number((a/o*e).toFixed(2)),largeScale:e}}let d=Number(((l-c)/t.height).toFixed(2));return{smallScale:d,largeScale:Number((h/t.height).toFixed(2))}},M=({offset:e,ovalPadding:t,largeScale:r,ovalHeight:a,maskHeight:o})=>{let i=a/2+t.bottom;return(i+e)*r>o/2?o/2/r-i:e},P=e=>{r.useEffect(()=>()=>{e&&e.srcObject?.getTracks().forEach(e=>{e.stop()})},[e])},O=()=>{let[e,t]=r.useState(null),[a,o]=r.useState(!1),i=r.useRef(null);return r.useEffect(()=>{if(!i.current)return()=>{};let e=i.current,r=()=>{t(e.getBoundingClientRect()),o(!1)},a=()=>{o(!0)};return e.addEventListener("transitionstart",a),e.addEventListener("transitionend",r),()=>{e.removeEventListener("transitionstart",a),e.removeEventListener("transitionend",r)}},[]),[i,e??i.current?.getBoundingClientRect(),a,o]},B=()=>{let e=r.useRef(),{sendEvent:t}=i.useSDKTracking();return r.useCallback((r,a,o={})=>{let i=performance.now(),n={};"object"==typeof o&&(n={...o},e.current&&(n.interval_vs_previous_in_ms=Math.round(i-e.current))),"function"==typeof o&&(n=o({lastTimeLog:e.current})),e.current=i,t({tag:r,event:a,log:n})},[t])},D=(e,t)=>{let a=r.useRef(e);r.useEffect(()=>{a.current=e},[e]),r.useEffect(()=>{t&&"function"==typeof a.current&&a.current()},[t])},I=({compareFn:e,duration:t,minFrames:a=null})=>{let o=r.useRef(null),i=r.useRef(!1),n=r.useRef(0),l=r.useRef(()=>{}),{compareAndStoreResult:s,getBestResult:c,reset:u}=r.useMemo(()=>{var r,a;let o,i,n;return r=e,a=t,o=null,i=null,n=()=>null!==i&&performance.now()-i>a,{checkIsTimeUp:n,compareAndStoreResult:e=>{null===o&&(o=e,i=performance.now()),n()||r(o,e)&&(o=e)},getBestResult:()=>o,reset:()=>{o=null,i=null}}},[e,t]),h=r.useCallback(()=>{u(),n.current=0,i.current=!1,o.current&&(clearTimeout(o.current),o.current=null)},[u]),d=r.useCallback(()=>null!==o.current,[]),f=r.useCallback(e=>{if(s(e),n.current+=1,!i.current||"number"!=typeof a||n.current<a)return;let t=c();l.current(t),h()},[s,c,a,h]),m=r.useCallback(({initialFrame:e,onDone:r})=>{l.current=r,f(e),o.current=setTimeout(()=>{if(i.current=!0,"number"==typeof a&&n.current<a)return;let e=c();l.current(e),h()},t)},[f,t,c,a,h]);return r.useEffect(()=>()=>{clearTimeout(o.current)},[]),r.useMemo(()=>({captureFrame:f,getBestResult:c,isAutoCapturing:d,startCapturing:m,stopCapturing:h}),[f,c,d,m,h])},N=e=>{let t=document.createElement("canvas");return t.setAttribute("width",e.videoWidth.toString()),t.setAttribute("height",e.videoHeight.toString()),t.getContext("2d").drawImage(e,0,0,e.videoWidth,e.videoHeight),t},j=()=>{let[e,t]=r.useState(Date.now());return{sessionId:e,updateSessionId:r.useCallback(()=>{t(Date.now())},[])}},z=(e,t)=>{if(0===Object.keys(e).length)return{topLeft:[0,0],bottomRight:[0,0],probability:0,landmarks:[]};let r=e.topLeft??[0,0],a=e.bottomRight??[0,0],o=e.probability??0,i=e.landmarks??[];return{topLeft:[r[0]*t,r[1]*t],bottomRight:[a[0]*t,a[1]*t],probability:o,landmarks:i.map(e=>[e[0]*t,e[1]*t])}},W=200,q=({size:e,scale:t=1,video:r,baseSize:a=W})=>{let{width:o,height:i}=e,{videoWidth:n=Number.MAX_SAFE_INTEGER,videoHeight:l=Number.MAX_SAFE_INTEGER}=r??{},s=Math.min(o,i)/a,c=Math.round(o/s*t),u=Math.round(i/s*t);return c>n||u>l?{width:o,height:i}:{width:c,height:u}},G=({width:e,height:t,cameraScale:r})=>{let a=document.createElement("canvas");a.width=e,a.height=t;let o=a.getContext("2d");return o?(o.translate(e,0),o.scale(-1*r,+r)):console.error("Failed to get 2D context from canvas in createLivenessCanvas"),a},H=({maskBoundingBox:e,faceRatio:t,validFaceRatio:r,video:a,shouldCropCenterSquare:o=!0,cropArea:i,frame:l,facePrediction:s,detectionToWholeFaceRatio:c=.8})=>{let u=e.width*t/r,h=u/e.width,d=e.height*h,f={x:e.x-(u-e.width)/2,y:e.y-(d-e.height)/2,width:u,height:d};f.x+f.width>i.x+i.width&&(f.width=i.width,f.x=i.x),f.y+f.height>i.y+i.height&&(f.height=i.height,f.y=i.y);let m=null;if(o){let e=Math.min(f.width,f.height),t=(s.bottomRight[1]-s.topLeft[1])/c,r=s.bottomRight[1]-t+(t-e)/2+i.y;r+e>f.y+f.height&&(r=f.y+f.height-e);let o={x:f.x+f.width/2-e/2,y:r,width:e,height:e};m=n.analyzeVideoAndWindowSizes(a,o)}else m=n.analyzeVideoAndWindowSizes(a,f);let g=q({size:{width:m.cropWidth,height:m.cropHeight},baseSize:400,video:a}),_=G({width:g.width,height:g.height,cameraScale:1}),p=_.width,b=_.height;return _.getContext("2d").drawImage(l,m.cropX,m.cropY,m.cropWidth,m.cropHeight,0,0,p,b),_},V=l(async function e({tfScriptUrls:t,closeEyesModelUrl:r,blazefaceModelUrl:a,qualifyModelUrl:o,opencvUrl:i}={}){let n=new u(r),l=new h(o),d=new c;await s.loadTensorFlow(t),await s.initTensorFlow({preferredBackends:["wasm","cpu"]});let f=[s.loadBlazefaceModel({modelUrl:a}),n.load(),l.init({opencvUrl:i}),c.init({opencvUrl:i})],[{blazefaceModel:m}]=await Promise.all(f);return{closeEyesModel:n,blazefaceModel:m,notQualifiedModel:l,brightnessDetector:d}}),U=({width:e,height:t,cameraScale:a=1,debug:o=!1})=>{let[i,n]=r.useState(null);return r.useEffect(()=>{let r=G({width:e,height:t,cameraScale:a});return o&&(document.body.appendChild(r),r.style.position="fixed",r.style.top="0",r.style.left="0",r.style.zIndex="9999"),n(r),()=>{o&&document.body.removeChild(r)}},[a,o,t,e]),i},K=y.isMobile?200:400;function J({cameraScale:e=1,isVideoPlaying:t,step:a,cropArea:o,videoRef:i,onFarFaceDetected:l,onFarFullFaceDetected:s,onCloseFaceDetected:c,onCloseFullFaceDetected:u,onFlashingFramesCaptured:h,frameInterval:y=0,useFaceDetectorWhenFlashing:w,onFaceError:E,onError:C,maskBoundingRect:v,shouldPauseFaceDetection:A,shouldContinueOnError:R,debug:S=!1,faceDetectionSettings:x}){let{faceSettings:k,maskSettings:T,closeEyesSettings:L,captureFrameSettings:M,blurCheckFarSettings:P,blurCheckCloseSettings:O,brightnessDetectionFarSettings:B,brightnessDetectionCloseSettings:D,notQualifiedFarSettings:I,notQualifiedCloseSettings:N,frontalFaceCheckSettings:j}=x,{chinToMaskBottomPadding:W}=T,{frameScale:G}=M,{enable:H,timeout:J,forceCheck:X}=L,{enable:$,upDownBoundMin:Y,upDownBoundMax:Q}=j,{minFarFaceRatio:Z,maxFarFaceRatio:ee,closeFaceRatio:et}=k,er=(e=>{let[t,a]=r.useState(e);return r.useEffect(()=>{(async()=>{try{let t=Math.max(16.666666666666668,33.333333333333336,e);a(t)}catch(e){console.error(e),a(20)}})()},[e]),t})(y),ea=(({videoRef:e,cropArea:t})=>r.useMemo(()=>e.current&&0!==Object.keys(t).length?n.analyzeVideoAndWindowSizes(e.current,t):{},[e,t]))({videoRef:i,cropArea:o}),eo=q({size:{width:ea.cropWidth,height:ea.cropHeight},scale:G,video:i.current}),ei=(({cropArea:e,maskBoundingRect:t,baseSize:r})=>{let{width:a,height:o,x:i,y:n}=e,l=Math.min(a,o)/r,s=t?.left??0,c=t?.top??0,u=t?.right??a;return{left:Math.max((s-i)/l,0),right:Math.min((u-i)/l,a/l),top:Math.max((c-n)/l,0),bottom:Math.min(((t?.bottom??o)-n)/l,o/l)}})({cropArea:o,maskBoundingRect:v,baseSize:Math.min(eo.width,eo.height)}),en=U({width:eo.width,height:eo.height,cameraScale:e}),el=Math.min(o.width,o.height)/Math.min(eo.width,eo.height),es=U({width:K,height:K*(eo.height/eo.width),cameraScale:e,debug:S}),ec=(({width:e,height:t,debug:a})=>{let o=r.useRef(null),i=r.useMemo(()=>{let r=document.createElement("canvas");return r.width=e,r.height=t,r.style.position="fixed",r.style.bottom="0",r.style.left="0",r.style.zIndex="99999",o.current=r,a&&document.body.appendChild(r),r},[t,e,a]);return r.useEffect(()=>()=>{a&&document.body.removeChild(o.current)},[a]),i})({width:160,height:150,debug:S}),{customUrls:eu}=f.useSDKSettings(),[eh,ed]=((e,t)=>{let[a,o]=r.useState({}),i=Object.keys(a).length>0;return r.useEffect(()=>{let r=!1;return(async()=>{try{let t=await V(e);if(r)return;o(t)}catch(e){t({...d.Errors.unable_to_load_model,details:e}),console.error(e)}})(),()=>{r=!0}},[i,e,t]),[a,i]})(eu,C),ef=r.useRef(null),{markTime:em,checkIfEllapsed:eg}=(({timeout:e})=>{let t=r.useRef(null),a=r.useCallback(()=>{t.current=performance.now()},[]),o=r.useCallback(()=>null===t.current?(a(),!1):performance.now()-t.current>e,[a,e]);return{markTime:a,checkIfEllapsed:o}})({timeout:1e3*J}),e_=ed&&t,{closeEyesModel:ep,blazefaceModel:eb,notQualifiedModel:ey,brightnessDetector:ew}=eh,eE=r.useCallback(async(e,t)=>{try{if(t?.width===0||t?.height===0||null===i.current||A||a===F.STOP_DECTECTING)return;let{cropX:n,cropY:f,cropWidth:y,cropHeight:C}=e,v=t.width,x=t.height;t.getContext("2d").drawImage(i.current,n,f,y,C,0,0,v,x);let k=m.drawToSquareCanvas(t),T=K/v;if(S&&es.getContext("2d").drawImage(i.current,n,f,y,C,0,0,v*T,x*T),!w&&a===F.START_FLASHING){"function"==typeof h&&await h({prediction:null,originalRatio:el,canvas:t});return}let L=await g.getModelPredictions({model:eb,sCanvas:k}),M=[[ei.left,ei.top],[ei.right,ei.bottom]],{error:j,fullFace:q,faceRatio:G}=await _.validatePredictions({predictions:L,cropAreaCoordinates:M});if(S){var r,o;let e,t={left:ei.left*T,top:ei.top*T,right:ei.right*T,bottom:ei.bottom*T};r=es,o={x:t.left,y:t.top,width:t.right-t.left,height:t.bottom-t.top},e=r.getContext("2d"),e?(e.strokeStyle="red",e.lineWidth=1,e.beginPath(),e.rect(o.x,o.y,o.width,o.height),e.stroke(),e.closePath()):console.warn("drawBoundingBox: 2D context is not available.");let a=L.map(e=>z(e,T));((e,t,r=!1)=>{let a=e.getContext("2d");if(!a)return;let o=e.width;a.strokeStyle="blue",a.fillStyle="blue",a.lineWidth=1,t.forEach(e=>{e.landmarks.forEach(e=>{a.beginPath(),a.arc(r?o-e[0]:e[0],e[1],2,0,2*Math.PI),a.fill(),a.closePath()}),a.beginPath();let t={x:r?o-e.bottomRight[0]:e.bottomRight[0],y:e.topLeft[1],width:e.bottomRight[0]-e.topLeft[0],height:e.bottomRight[1]-e.topLeft[1]};a.rect(t.x,t.y,t.width,t.height),a.stroke(),a.closePath()})})(es,a,!0)}let V=d.FaceDirection.FRONTAL;if(q&&$){let e=await _.calculateFaceDirection({landmarks:q.landmarks,upDownBound:{lower:Y,upper:Q}});V=e?.gesture??""}(q||j?.code===d.Errors.partial_face.code)&&a===F.FAR_FACE&&"function"==typeof l&&await l({prediction:L[0],originalRatio:el,canvas:t}),(q||j?.code===d.Errors.partial_face.code)&&a===F.CLOSE_FACE&&"function"==typeof c&&await c({prediction:L[0],originalRatio:el,canvas:t});let U=j?.code;try{if(U===d.Errors.no_face.code)throw Error("no_face");if(U===d.Errors.multiple_faces.code){let e=_.calculateFaceArea(L[0]),t=_.calculateFaceArea(L[1]);if(e<=2*t)throw Error("multiple_faces")}if(V!==d.FaceDirection.FRONTAL)throw Error("face_not_frontal");if(U===d.Errors.partial_face.code){let e=_.cropFaceInsideBox([L[0].topLeft,L[0].bottomRight],M);if(p.rectEdgeRatio(e,M)>.95)throw Error("face_too_large")}if(a===F.FAR_FACE){if(G>ee)throw Error("face_too_large");if(G<Z)throw Error("face_too_small")}if(a===F.CLOSE_FACE&&G<et)throw Error("face_too_small");if(Array.isArray(L)&&L.length>0&&ei.bottom-L[0].bottomRight[1]>W)throw Error("face_too_high");if(U===d.Errors.face_out_of_box.code&&(a===F.FAR_FACE&&G>=Z&&G<=ee||a===F.CLOSE_FACE&&G>=et))throw Error("")}catch(e){U=e.message}let J=null;if(H)if(U)em();else{let e=await ep.predict(t,q.landmarks),r=!X&&eg();J=e.isEyeClose,e.isEyeClose&&!r&&(U="eye_close")}let er=null,ea=a===F.FAR_FACE?B:D;if((ea.enableTooBrightCheck||ea.enableTooDarkCheck)&&Array.isArray(L)&&L.length>0){let e=[[Math.max(L[0].topLeft[1],0),Math.min(L[0].bottomRight[0],t.width),Math.min(L[0].bottomRight[1],t.height),Math.max(L[0].topLeft[0],0)]],{score:r,message:a}=ew.score(t,e,ea.tooDarkThreshold,ea.tooBrightThreshold);er=r,""===U&&ea.enableTooBrightCheck&&"face_too_bright"===a&&(U="face_too_bright"),""===U&&ea.enableTooDarkCheck&&"face_too_dark"===a&&(U="face_too_dark")}let eo=0,en={enable:a===F.FAR_FACE?P.enable:O.enable,threshold:a===F.FAR_FACE?P.threshold:O.threshold};en.enable&&(eo=await b.calculateBlurScore(t),""!==U||b.hasBetterBlurScore(eo,en.threshold)||(U="blurry_face"));let eu=0,eh=0,ed="model_not_run",ef={enable:a===F.FAR_FACE?I.enable:N.enable,threshold:a===F.FAR_FACE?I.threshold:N.threshold};if(ef.enable&&q&&q.landmarks){let[e,r,a,o]=await ey.predict(t,q.landmarks,ef.threshold);eu=r,eh=o,ed=a,""!==U||e||(U="face_not_qualified")}if((S&&m.drawDebugCanvas(ec,{error:U,ovalFaceRatio:G?.toFixed(3)??"null",ovalError:j?.code??"null",step:a===F.FAR_FACE?"far":"close",blurScore:eo.toFixed(3),qualifyScore:eu.toFixed(3),brightnessScore:er?.toFixed(3)??"null"}),U)&&("function"==typeof E&&await E({error:U,currentStep:a}),!R))return;let e_=q,eE=G;if(!e_&&R&&(e_=Array.isArray(L)&&L.length>0?L[0]:{},eE=a===F.FAR_FACE?ee:et),a===F.FAR_FACE&&e_&&Z<=eE&&eE<=ee&&"function"==typeof s)return void await s({prediction:e_,originalRatio:el,canvas:t,frame:{faceRatio:eE,isEyeClosed:J,blurScore:eo,qualifyScore:eu,realQualifyScore:eh,qualifyModelMessage:ed,brightnessScore:er,faceError:U}});if(e_&&a===F.CLOSE_FACE&&eE>=et&&"function"==typeof u)return void await u({prediction:e_,originalRatio:el,canvas:t,frame:{faceRatio:eE,isEyeClosed:J,blurScore:eo,qualifyScore:eu,realQualifyScore:eh,qualifyModelMessage:ed,brightnessScore:er,faceError:U}});w&&e_&&a===F.START_FLASHING&&eE>=et&&"function"==typeof h&&await h({prediction:e_,originalRatio:el,canvas:t,faceError:U})}catch(e){console.error(e),C({error:e})}},[i,A,a,S,w,eb,ei.left,ei.top,ei.right,ei.bottom,$,H,B,D,P.enable,P.threshold,O.enable,O.threshold,I.enable,I.threshold,N.enable,N.threshold,R,Z,ee,et,es,h,el,Y,Q,l,c,W,ep,X,eg,em,ew,ey,ec,E,s,u,C]);return r.useEffect(()=>{let e=null,t=!1;return e_&&function r(){e=requestAnimationFrame(async e=>{t||null===i.current||((null===ef.current&&(ef.current=e),e-ef.current<er)?r():(ef.current=e,await eE(ea,en),r()))})}(),()=>{t=!0,cancelAnimationFrame(e)}},[en,ea,eE,e_,i,er]),{warmupDone:ed}}let X=e=>{let{shouldStart:t,totalTime:a,totalDelay:o,onError:i,onTimeout:n,onDelayEnd:l,maxRetriesSettings:s,interruptible:c=!0}=e,u=r.useRef(new w({totalTime:a,interruptible:c,totalDelayBetweenReset:o})),[h,f]=r.useState(a);return r.useEffect(()=>u.current.on("tick",({remainTime:e})=>{f(e)}),[n]),r.useEffect(()=>u.current.on("delaystart",({attemptCount:e})=>{s.enable&&e>=s.total?i(d.Errors.max_retry_reached):n()}),[s.enable,s.total,i,n]),r.useEffect(()=>u.current.on("delayend",()=>{l()}),[l]),r.useEffect(()=>u.current.on("reset",({attemptCount:e,fromBackground:t})=>{s.enable&&e>=s.total&&i(d.Errors.max_retry_reached),t&&(n(),l())}),[n,l,s.enable,s.total,i]),r.useEffect(()=>t?u.current.start():()=>{},[t]),{remaining:h}},$=e=>{switch(e){case"partial_face":return"flash_liveness.error.partial_face";case"no_face":case"face_out_of_box":return"flash_liveness.error.no_face";case"face_too_small":return"flash_liveness.error.face_too_small";case"face_too_large":return"flash_liveness.error.face_too_large";case"eye_close":return"flash_liveness.error.close_eye";case"face_not_frontal":return"flash_liveness.error.face_not_frontal";case"multiple_faces":return"flash_liveness.error.multiple_faces";case"face_too_high":return"flash_liveness.error.face_too_high";case"blurry_face":return"flash_liveness.error.face_too_blurry";case"face_not_qualified":return"flash_liveness.error.face_not_qualified";case"face_too_bright":return"flash_liveness.error.face_too_bright";case"face_too_dark":return"flash_liveness.error.face_too_dark";default:return""}},Y=e=>Array.isArray(e)?e.map(({base64:e,label:t,index:r,metadata:a})=>({base64:e,label:t,index:r,metadata:a})):e,Q=r.createContext({enable:!1,key:""}),Z=({children:e,settings:t})=>{let a=r.useMemo(()=>{let e=t?.key??"";return{enable:!!e,key:e}},[t?.key]);return o.jsx(Q.Provider,{value:a,children:e})};Z.propTypes={children:E.node.isRequired,settings:E.shape({key:E.string})},Z.defaultProps={settings:{key:""}};let ee=()=>r.useContext(Q),et=r.createContext({}),er=({apiCredentials:e,children:t})=>{let{apiClient:r}=C.useApiClient({apiCredentials:e});return o.jsx(et.Provider,{value:r,children:t})};er.propTypes={apiCredentials:E.shape({accessKey:E.string.isRequired,secretKey:E.string.isRequired,apiUrl:E.string.isRequired}),children:E.node.isRequired},er.defaultProps={apiCredentials:{}};let ea=()=>r.useContext(et);let eo=(e=[],t=async()=>(await Promise.all(e)).map(e=>({id:e?.data?.file_id??-1})),{uploadFrameBatch:(t,r,a)=>{let o=new Blob([JSON.stringify(t)]);e.push(r.uploadFile({file:o,metadata:JSON.stringify({type:"selfie"}),label:"video"},a))},getAllUploadedBatches:t,resetUploadBatches:()=>{e.length=0}});export{er as A,R as F,Z as O,S as R,F as S,T as W,O as a,I as b,j as c,A as d,N as e,x as f,J as g,P as h,D as i,X as j,H as k,M as l,$ as m,L as n,ee as o,ea as p,eo as q,Y as r,z as s,B as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{s as e,r as t,d as r,f as a,c as i,p as n,u as l,g as s,l as d,j as o,a as u,P as c}from"./chunk-
|
|
1
|
+
import{s as e,r as t,d as r,f as a,c as i,p as n,u as l,g as s,l as d,j as o,a as u,P as c}from"./chunk-68e90ba2.js";import{g as p,S as g,R as f}from"./chunk-d02bd3cc.js";import{W as m}from"./chunk-bcf5eed2.js";import"./chunk-5d5d5df1.js";let{IDCardSide:y,Errors:I}=e;async function b({image:e,cardType:t,cardSide:r,apiClient:a,outputEncryptionSettings:i}){let n={label:`id_card.${t}.${r}`};if(i&&i.key){let t=new File([e.encrypted.hex],`${Date.now()}.jpg`,{type:"image/jpeg"});return a.uploadImage({file:t,...n},{"X-TV-Key":i.key})}let l=new File([e.blob],`${Date.now()}.jpg`,{type:"image/jpeg"});return a.uploadImage({file:l,...n})}let S={data:{image_id:null}};async function _({image:e,apiClient:t,rawString:r,results:a,outputEncryptionSettings:i}){if(!e||!e.blob||!r)return Promise.resolve(S);let n={raw:r};a&&a.length>1&&(n=a.reduce((e,t,r)=>(e[0===r?"raw":`raw${r+1}`]=t,e),{}));let l={label:"qr_code",metadata:JSON.stringify(n)};if(i&&i.key){let r=new Blob([e.encrypted.hex]);return t.uploadImage({file:r,...l},{"X-TV-Key":i.key})}return t.uploadImage({file:e.blob,...l})}let C={data:{file_id:null}};async function h({video:e,apiClient:t,outputEncryptionSettings:r}){if(!e||!e.blob)return Promise.resolve(C);let a={label:"video"};if(r&&r.key){let i=new Blob([e.encrypted.hex]);return t.uploadFile({file:i,...a},{"X-TV-Key":r.key})}return t.uploadFile({file:e.blob,...a})}async function v({imageId:e,cardType:t,apiClient:r}){return r.requestVerifyIDCard({card_type:t,image1:{id:e}})}async function D({apiClient:e,cardType:t,frontCardId:r,isCapturingFrontSide:a,backCardId:i,recordedVideos:n=[],qrImageId:l,previousCapturingVideoId:s,previousFullVideoId:d,latestCapturingVideoId:o,latestFullVideoId:u}){let c=n.filter(e=>null!==e.id),p=n.filter(e=>null===e.id&&e.frames.length>0),g=await Promise.all(p.map(t=>e.fileService.request({frames:t.frames}))),f={card_type:t,image:{id:r},image2:a?void 0:{id:i},videos:[...[s,d,o,u].filter(e=>null!=e).map(e=>({id:e})),...c.map(e=>({id:e.id})),...g.map(e=>({id:e.data.file_id}))]};return l&&(f.qr1_images=[{id:l}]),e.detectIDTampering(f)}async function w({cardType:e,apiClient:t,cardImageId:r,qrImageId:a}){let i={card_type:e,image1:{id:r}};return a&&(i.qr1_images=[{id:a}]),t.readIDCard(i)}async function k({image:e,frontCardId:t,qrImageId:r,onError:a,recordedVideos:i,apiClient:n,cardType:l,cardSide:s,qrScannedResult:d,outputEncryptionSettings:o,enabledServices:u,fullVideo:c,capturingVideo:p,previousCapturingVideoId:g,previousFullVideoId:f}){let m=[b({image:e,cardType:l,cardSide:s,apiClient:n,outputEncryptionSettings:o})];m.push(_({image:d?.image,apiClient:n,rawString:d?.result,results:d?.results,outputEncryptionSettings:o})),m.push(h({video:c,apiClient:n,outputEncryptionSettings:o}),h({video:p,apiClient:n,outputEncryptionSettings:o}));let[S,C,k,E]=await Promise.all(m);if(S.errors)return void a({...I.upload_error,details:S.errors});let V=S.data.image_id,j=C?.data?.image_id||r,R={data:null};if(u?.enableVerifySanityIDCard){let e=await v({imageId:V,cardType:l,apiClient:n});if(e.errors)return void a({...I.sanity_check_error,details:e.errors});R.data=e.data}let B={data:null};if(u?.enableReadIDCardInfo){let e=await w({cardType:l,apiClient:n,cardImageId:V,qrImageId:j});if(e.errors)return void a({...I.read_id_card_error,details:e.errors});B.data=e.data}let F=k?.data?.file_id||null,T=E?.data?.file_id||null,K={data:null};if(u?.enableDetectIDCardTampering){let e,r;if(s===y.BACK&&!t)return void a(I.missing_front_id_card);let d=s===y.FRONT;d?e=V:(e=t,r=V);let o=await D({apiClient:n,cardType:l,frontCardId:e,isCapturingFrontSide:d,backCardId:r,recordedVideos:i,qrImageId:j,previousCapturingVideoId:g,previousFullVideoId:f,latestCapturingVideoId:T,latestFullVideoId:F});if(o.errors)return void a({...I.detect_id_tampering_error,details:o.errors});K.data=o.data}return{sanityResult:R.data,tamperingInfo:K.data,cardInfo:B.data,cardImageId:V,qrImageId:j,mp4VideoIds:{full:F,capturing:T}}}let{Errors:E}=e,V=({readIDCardUIOnlyComponent:c,...f})=>{let{onError:y,onStepDone:I,apiCredentials:b,logCredentials:S,outputEncryptionSettings:_,serviceSettings:C,flowId:h,clientSettings:v,...D}=f,[w,V]=t.useState(v),[j,R]=t.useState(!1),{apiClient:B}=r.useApiClient({apiCredentials:b,logCredentials:S}),F=t.useRef(""),T=t.useRef(""),K=t.useRef(null),U=t.useRef(null),q=a.getEnabledServices(C,w),{billingSettings:O,enableBilling:P}=i.useSDKSettings(),x=n.buildBillingInput(f),A=l.getWebSetting(w,"data.settings.sdk_settings.billing_settings.billing_config"),{submitBilling:W}=s({enable:P,onError:y,billingSettings:O??{json:A??{}},billingUrl:l.getWebSetting(w,"data.settings.sdk_settings.billing_settings.url")}),$=t.useCallback(t=>{if(e.ErrorsWithoutBilling.includes(t.code))return void y(t);let r={error:t,sdkStatus:e.BillingStatus.fail};W({service:p(D.steps),input:x,output:r}),y&&y(t)},[W,D.steps,x,y]),G=t.useCallback((t,r)=>{if(r){let r={sdkStatus:e.BillingStatus.success,result:n.buildBillingOutput(t)},a={service:p(D.steps),input:x,output:r};if(Array.isArray(D.steps)&&1===D.steps.length&&D.steps[0].scannerType===g.QR_CODE){let{qrScannedResult:r={}}=t,i=r.result;if(i){let e=i.split("|")[0];a.id_num=d.SHA256(e),a.full_hash=d.SHA256(i)}else a.output={...a.output,sdkStatus:e.BillingStatus.cancel}}W(a)}I&&I(t)},[I,D.steps,x,W]);t.useEffect(()=>{async function e(){try{let e=await B.clientSettings({flow_id:h});V(e)}catch(e){console.error("Error fetching client settings:",e)}finally{R(!0)}}q.enableGetClientSettings&&e()},[B,q.enableGetClientSettings,h]);let N=t.useCallback(async(t,{shouldBilling:r})=>{let{cardType:a,cardSide:i,recordedVideos:n,qrScannedResult:l,image:s,fullVideo:d,capturingVideo:o}=t;try{if(!q.enableUploadImages||!s.blob)return void G(t,r);let u=null;(u=await k({image:s,cardSide:i,frontCardId:F.current,qrImageId:T.current,onError:$,apiClient:B,cardType:a,recordedVideos:n,qrScannedResult:l,outputEncryptionSettings:_,enabledServices:q,fullVideo:d,capturingVideo:o,previousCapturingVideoId:U.current,previousFullVideoId:K.current}))&&(i===e.IDCardSide.FRONT&&(F.current=u.cardImageId),U.current=u?.mp4VideoIds?.capturing,K.current=u?.mp4VideoIds?.full,T.current=u.qrImageId,G({...t,apiResult:u},r))}catch(e){$({...E.api_call_error,details:e})}},[B,q,$,G,_]);return q.enableGetClientSettings&&!j?null:o.jsx(u.LicenseProvider,{clientSettings:w,onError:y,children:o.jsx(m,{isWrappedBy:"id_with_api_call",children:o.jsx(c,{logCredentials:S,onError:y,onStepDone:N,outputEncryptionSettings:_,...D,clientSettings:w})})})};V.propTypes={onError:c.func,onStepDone:c.func,apiCredentials:c.shape({accessKey:c.string,secretKey:c.string,apiUrl:c.string}),logCredentials:c.shape({}),outputEncryptionSettings:c.shape({}),readIDCardUIOnlyComponent:c.func,serviceSettings:c.shape({}),flowId:c.string,clientSettings:c.shape({})},V.defaultProps={onError:()=>{},onStepDone:()=>{},apiCredentials:{accessKey:"",secretKey:"",apiUrl:""},logCredentials:{enable:!1},outputEncryptionSettings:{key:""},readIDCardUIOnlyComponent:f,serviceSettings:{enableUploadFrames:!0,enableUploadImages:!0,enableVerifySanityPortrait:!0,enableVerifySanityIDCard:!0,enableVerifyFaceLiveness:!0,enableDetectIDCardTampering:!0,enableReadIDCardInfo:!0},flowId:"",clientSettings:null};export{V as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e,s as t,P as s,j as a,b as n,u as i,k as r,A as l,m as o,ap as _,aq as g,M as c,O as d,ar as f,as as h,at as u,au as m,av as b,aw as p,ax as v,ay as y,az as S,F as k,R as C,d as F,f as x,Q as E,aA as w,aB as M,Y as R}from"./chunk-9390d088.js";import{d as L}from"./chunk-c136757f.js";import{t as W}from"./chunk-c298ad04.js";import{C as I,O as A}from"./chunk-e468b8ce.js";import{u as D,S as T,a as B,F as q,b as O,c as P,d as j,n as Q,l as V,e as N,s as U,f as H,R as $,g as G,h as J,i as z,j as K,W as X,k as Y,m as Z,o as ee,p as et,q as es,r as ea,A as en,O as ei}from"./chunk-58f60271.js";import{m as er,u as el,b as eo}from"./chunk-4da2a90d.js";import{u as e_}from"./chunk-dad8ede3.js";let eg=e.createContext(t.Mode.FLASH_ADVANCED),ec=({flashMode:e,children:s})=>{let n=e===t.Mode.FLASH||e.startsWith("flash_")?e:t.Mode.FLASH;return a.jsx(eg.Provider,{value:n,children:s})};ec.defaultProps={flashMode:t.Mode.FLASH_ADVANCED},ec.propTypes={flashMode(e,t,s){if(!/(^flash_|^flash$)/.test(e[t]))return Error(`Invalid prop \`${t}\` of value \`${e[t]}\` supplied to \`${s}\`. \`${t}\` is either 'flash' or begins with 'flash_'. Falling back to 'flash'.`)},children:s.node.isRequired};let ed=()=>{let t=e.useContext(eg);if(void 0===t)throw Error("useFlashMode must be used within a FlashModeProvider");return t},ef=0,eh=1,eu={data:{settings:{flashing_modes:{flash:{frames_per_color:8,frames_per_color_web:8,colors:"r r rrr",colors_web:"r r rrr"}},sdk_settings:{flash_liveness_settings:{frontal_face_check:{enable:!0,up_down_bound_min:.35,up_down_bound_max:.7},capture_frame_settings:{enable:!1,frames_batch_length:10,frames_interval_time:0,frame_quality:.8,frame_scale:1,auto_capture_min_frames:0,auto_capture_min_frames_far:0,auto_capture_min_frames_close:0},not_qualified_settings:{enable_far:!1,enable_close:!1,threshold_far:.11,threshold_close:.11},close_eyes_settings:{enable:!1,timeout:5,force_check:!1},face_settings:{close_face_ratio:.82,max_far_face_ratio:.9,min_far_face_ratio:.8,mobile:{close_face_ratio:.95,max_far_face_ratio:.9,min_far_face_ratio:.85}},flash_settings:{colors_length:10,flash_color:"rgb(255, 0, 0)",secondary_flash_color:"rgba(0,0,0,0.6)",delay_between_colors:120,flash_intensity:1,frames_per_color:4,use_face_detector_when_flashing:!1,flash_frame_interval:0},liveness_settings:{enable_far_step:!0},timeout_settings:{enable:!0,total:30,countdown:10,max_retry_count:0,non_stoppable:!1},exif_data_settings:{enable:!0},mask_settings:{chin_to_mask_bottom_padding:20,large_scale:.85,mobile:{chin_to_mask_bottom_padding:20,large_scale:.9,oval_padding:{bottom:20,left:20,right:20,top:0},oval_vertical_offset:60,small_scale:.65},oval_padding:{bottom:20,left:30,right:30,top:0},oval_vertical_offset:0,small_scale:.6},image_settings:{valid_face_ratio:.6,image_quality:1,crop_center_far:!0,crop_center_close:!1,detection_to_whole_face_ratio:.8},blur_far_settings:{enable:!0,blurry_threshold:.4,wait_for_best_image_time_ms:1e3},blur_close_settings:{enable:!0,blurry_threshold:.4,wait_for_best_image_time_ms:1e3},brightness_detection_far_settings:{enable_too_bright_check:!1,enable_too_dark_check:!1,too_bright_threshold:.83,too_dark_threshold:.195},brightness_detection_close_settings:{enable_too_bright_check:!1,enable_too_dark_check:!1,too_bright_threshold:.83,too_dark_threshold:.195},output_image_settings:{image_ordering:["close","far"]},auto_gen_frame_ids:{enable:!1,max_items:50}}}}}},em=()=>{let s=e_(),a=ed();return e.useMemo(()=>{let e=er({},eu,s),l=n(e,`data.settings.flashing_modes.${t.Mode.FLASH}`),o=n(e,`data.settings.flashing_modes.${a}`,l),_={enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.capture_frame_settings.enable"),framesIntervalTime:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.capture_frame_settings.frames_interval_time"),framesBatchLength:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.capture_frame_settings.frames_batch_length"),frameScale:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.capture_frame_settings.frame_scale"),frameQuality:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.capture_frame_settings.frame_quality"),autoCaptureMinFramesFar:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.capture_frame_settings.auto_capture_min_frames_far"),autoCaptureMinFramesClose:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.capture_frame_settings.auto_capture_min_frames_close")},g={enableFarStep:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.liveness_settings.enable_far_step")},c={flashColor:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.flash_settings.flash_color"),secondaryFlashColor:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.flash_settings.secondary_flash_color"),colors:i.getWebSetting(o,"colors"),delayBetweenColors:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.flash_settings.delay_between_colors"),framesPerColor:i.getWebSetting(o,"frames_per_color"),flashIntensity:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.flash_settings.flash_intensity"),useFaceDetectorWhenFlashing:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.flash_settings.use_face_detector_when_flashing"),flashFrameInterval:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.flash_settings.flash_frame_interval")},d={smallScale:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.mask_settings.mobile.small_scale":"data.settings.sdk_settings.flash_liveness_settings.mask_settings.small_scale"),largeScale:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.mask_settings.mobile.large_scale":"data.settings.sdk_settings.flash_liveness_settings.mask_settings.large_scale"),ovalPadding:{left:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.mask_settings.mobile.oval_padding.left":"data.settings.sdk_settings.flash_liveness_settings.mask_settings.oval_padding.left"),right:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.mask_settings.mobile.oval_padding.right":"data.settings.sdk_settings.flash_liveness_settings.mask_settings.oval_padding.right"),top:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.mask_settings.mobile.oval_padding.top":"data.settings.sdk_settings.flash_liveness_settings.mask_settings.oval_padding.top"),bottom:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.mask_settings.mobile.oval_padding.bottom":"data.settings.sdk_settings.flash_liveness_settings.mask_settings.oval_padding.bottom")},ovalVerticalOffset:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.mask_settings.mobile.oval_vertical_offset":"data.settings.sdk_settings.flash_liveness_settings.mask_settings.oval_vertical_offset"),chinToMaskBottomPadding:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.mask_settings.mobile.chin_to_mask_bottom_padding":"data.settings.sdk_settings.flash_liveness_settings.mask_settings.chin_to_mask_bottom_padding")},f={minFarFaceRatio:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.face_settings.mobile.min_far_face_ratio":"data.settings.sdk_settings.flash_liveness_settings.face_settings.min_far_face_ratio"),maxFarFaceRatio:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.face_settings.mobile.max_far_face_ratio":"data.settings.sdk_settings.flash_liveness_settings.face_settings.max_far_face_ratio"),closeFaceRatio:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.face_settings.mobile.close_face_ratio":"data.settings.sdk_settings.flash_liveness_settings.face_settings.close_face_ratio")},h={enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.close_eyes_settings.enable"),timeout:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.close_eyes_settings.timeout"),forceCheck:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.close_eyes_settings.force_check")},u={enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.exif_data_settings.enable")},m={imageQuality:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.image_settings.image_quality"),validFaceRatio:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.image_settings.valid_face_ratio"),enableCropCenterFar:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.image_settings.crop_center_far"),enableCropCenterClose:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.image_settings.crop_center_close"),detectionToWholeFaceRatio:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.image_settings.detection_to_whole_face_ratio")},b=i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.timeout_settings.max_retry_count"),p={enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.timeout_settings.enable"),total:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.timeout_settings.total"),countdown:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.timeout_settings.countdown"),enableMaxRetryCount:b>0,maxRetryCount:b,interruptible:!i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.timeout_settings.non_stoppable")},v={enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.blur_far_settings.enable"),threshold:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.blur_far_settings.blurry_threshold"),duration:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.blur_far_settings.wait_for_best_image_time_ms")},y={enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.blur_close_settings.enable"),threshold:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.blur_close_settings.blurry_threshold"),duration:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.blur_close_settings.wait_for_best_image_time_ms")},S={enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.not_qualified_settings.enable_far"),threshold:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.not_qualified_settings.threshold_far")},k={enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.not_qualified_settings.enable_close"),threshold:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.not_qualified_settings.threshold_close")},C={enableTooBrightCheck:n(e,"data.settings.sdk_settings.flash_liveness_settings.brightness_detection_far_settings.enable_too_bright_check"),enableTooDarkCheck:n(e,"data.settings.sdk_settings.flash_liveness_settings.brightness_detection_far_settings.enable_too_dark_check"),tooBrightThreshold:n(e,"data.settings.sdk_settings.flash_liveness_settings.brightness_detection_far_settings.too_bright_threshold"),tooDarkThreshold:n(e,"data.settings.sdk_settings.flash_liveness_settings.brightness_detection_far_settings.too_dark_threshold")},F={enableTooBrightCheck:n(e,"data.settings.sdk_settings.flash_liveness_settings.brightness_detection_close_settings.enable_too_bright_check"),enableTooDarkCheck:n(e,"data.settings.sdk_settings.flash_liveness_settings.brightness_detection_close_settings.enable_too_dark_check"),tooBrightThreshold:n(e,"data.settings.sdk_settings.flash_liveness_settings.brightness_detection_close_settings.too_bright_threshold"),tooDarkThreshold:n(e,"data.settings.sdk_settings.flash_liveness_settings.brightness_detection_close_settings.too_dark_threshold")},x={imageOrdering:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.output_image_settings.image_ordering"),farImageOrder:eh,closeImageOrder:ef};Array.isArray(x.imageOrdering)&&2===x.imageOrdering.length&&"far"===x.imageOrdering[0]&&"close"===x.imageOrdering[1]&&(x.farImageOrder=0,x.closeImageOrder=1);let E={enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.auto_gen_frame_ids.enable")&&p.enable,maxItems:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.auto_gen_frame_ids.max_items")};return{captureFrameSettings:_,livenessSettings:g,flashSettings:c,maskSettings:d,faceSettings:f,closeEyesSettings:h,exifSettings:u,imageSettings:m,timeoutSettings:p,blurCheckFarSettings:v,blurCheckCloseSettings:y,notQualifiedFarSettings:S,notQualifiedCloseSettings:k,brightnessDetectionFarSettings:C,brightnessDetectionCloseSettings:F,outputImageSettings:x,autoGenFrameIds:E,frontalFaceCheckSettings:{enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.frontal_face_check.enable"),upDownBoundMin:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.frontal_face_check.up_down_bound_min"),upDownBoundMax:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.frontal_face_check.up_down_bound_max")}}},[s,a])},eb=r.isMobile?{width:{ideal:640},whiteBalanceMode:"none"}:{width:{ideal:9999},whiteBalanceMode:"none"},ep=(e,t)=>""===t.faceError&&(!!e.isEyeClosed&&!t.isEyeClosed||(!!e.isEyeClosed||!t.isEyeClosed)&&(!!m.hasBetterBrightnessScore(t.brightnessScore,e.brightnessScore)||!!m.hasSameBrightnessScore(t.brightnessScore,e.brightnessScore)&&b.hasBetterBlurScore(t.blurScore,e.blurScore)));function ev(s){let{onReset:n,onFlashDone:i,frontCamera:r,styledComponent:m,onFramesCaptured:b,customComponent:F,extraConfig:x,onImageCaptured:E}=s,{onCloseCallback:w,onErrorCallback:M}=el(),R=em(),A=F?.FlashLivenessBody??p,ee=F?.FlashLivenessOverlay??v,et=F?.FlashLivenessError??y,es=F?.FlashLivenessCloseIcon??S,{maskSettings:ea,flashSettings:en,faceSettings:ei,livenessSettings:er,captureFrameSettings:e_,imageSettings:eg,timeoutSettings:ec,blurCheckFarSettings:ef,blurCheckCloseSettings:eh,exifSettings:eu,autoGenFrameIds:ev}=R;if(ea.smallScale>ea.largeScale)throw Error("smallScale must be smaller than largeScale");let ey=e.useRef(),eS=D(),ek=eo(),{framesPerColor:eC,delayBetweenColors:eF,useFaceDetectorWhenFlashing:ex,flashIntensity:eE,flashColor:ew,colors:eM,flashFrameInterval:eR,secondaryFlashColor:eL}=en,[eW,eI]=e.useState(""),eA=e.useMemo(()=>W(eI,1e3),[]),[eD,eT]=e.useState(!1),[eB,eq]=e.useState(T.LOADING),eO=l(),eP={width:o("FlashLiveness.mask.width")({theme:eO}),height:o("FlashLiveness.mask.height")({theme:eO}),strokeColor:(eB===T.FAR_FACE||eB===T.CLOSE_FACE)&&eW&&!eD?o("FlashLiveness.mask.strokeColorError")({theme:eO}):o("FlashLiveness.mask.strokeColor")({theme:eO}),strokeWidth:2*o("FlashLiveness.mask.strokeWidth")({theme:eO}),path:o("FlashLiveness.mask.path")({theme:eO}),backgroundColor:o("FlashLiveness.maskFill")({theme:eO})},ej=e.useRef(null),[eQ,eV,eN,eU]=B(),[eH,e$]=e.useState(0),[eG,eJ]=e.useState(!1),ez=e.useRef({frames:[],total:{[q.FAR_FACE]:0,[q.CLOSE_FACE]:0}}),eK=e.useRef(!1),eX=e.useRef(!1),eY=e.useRef(!1),eZ=O({compareFn:ep,duration:ef.duration,minFrames:e_.autoCaptureMinFramesFar}),e0=O({compareFn:ep,duration:eh.duration,minFrames:e_.autoCaptureMinFramesClose}),e1=ed(),[e2,e3]=e.useState(!1),{sessionId:e5,updateSessionId:e8}=P(),e9=e.useRef(_.createSingleUUID()),{onVideoPlayed:e6,cropArea:e4,isPlaying:e7}=j({}),{smallScale:te,largeScale:tt}=Q(ea,{width:eP.width,height:eP.height},{width:e4.width,height:e4.height}),ts=e.useRef(null),ta=e.useRef(null),tn=1e3*ec.total/e_.framesIntervalTime+eM.length*eC,{uuids:ti,getNextUUID:tr,reset:tl}=g({total:Math.min(ev.maxItems,Math.ceil(tn/e_.framesBatchLength))}),to=e.useCallback(e=>{let t=e[e.length-1];try{let e=JSON.parse(t.metadata);ev.enable&&(e.global_batch_id=tr()),e.global_session_id=e9.current,t.metadata=JSON.stringify(e)}catch(e){console.error("Unable to process last frame metadata",e)}},[ev.enable,tr]),{playVoice:t_}=c.useVoicePlayer(),tg=e.useMemo(()=>L(({reason:e})=>{if(eY.current=!1,ez.current.frames=[],ez.current.total[q.FAR_FACE]=0,ez.current.total[q.CLOSE_FACE]=0,eK.current=!1,eX.current=!1,ts.current=null,ta.current=null,er.enableFarStep?(e$(te),eq(T.FAR_FACE),t_("move_face_into_frame")):t_("move_face_closer"),e8(),ev.enable){let e=tl();d.addExifData("frame_batch_ids",e)}n({reason:e})},200,{leading:!0}),[er.enableFarStep,e8,ev.enable,n,te,t_,tl]),tc=V({offset:ea.ovalVerticalOffset,ovalPadding:ea.ovalPadding,largeScale:tt,maskHeight:e4.height,ovalHeight:eP.height}),{flashingColors:td,currentColor:tf,colorIndex:th,startFlashing:tu,goToNextColor:tm,colorInfoRef:tb,checkIsLastColor:tp}=(({colors:s="",onFlashDone:a,onErrorCallback:n,framesPerColor:i,flashColor:r,secondaryFlashColor:l})=>{let[o,_]=e.useState(null),g=e.useRef({colorIndex:null,frameIndex:null,colorStringIndex:null}),c=e.useMemo(()=>s.split("").reduce((e,t)=>e+t.repeat(i),""),[s,i]),d=" "===c[o]?l:r,f=e.useCallback(()=>g.current.colorStringIndex===c.length-1,[c.length]),h=e.useCallback(()=>{if(g.current.colorIndex+=Math.floor((g.current.frameIndex+1)/i),g.current.frameIndex=(g.current.frameIndex+1)%i,g.current.colorStringIndex+=1,!(g.current.colorStringIndex>c.length)){if(g.current.colorStringIndex<c.length)return void _(e=>e+1);_(null),g.current={colorIndex:null,frameIndex:null,colorStringIndex:null},"function"==typeof a&&a()}},[c.length,i,a]),u=e.useCallback(()=>{_(0),g.current={colorIndex:0,frameIndex:0,colorStringIndex:0}},[]);return e.useEffect(()=>{0===c.length&&"function"==typeof n&&n(t.Errors.flashing_color_error)},[c.length,n]),{flashingColors:c,colorIndex:o,currentColor:d,goToNextColor:h,startFlashing:u,colorInfoRef:g,checkIsLastColor:f}})({colors:eM,onFlashDone:e.useCallback(async()=>{eq(T.STOP_DECTECTING),eS("selfie_flash","user_activity.finish_flash"),eS("selfie_flash","user_activity",({lastTimeLog:e})=>({flash_liveness_in_ms:e-ey.current}));let{frames:e}=ez.current;if(e_.enable&&e_.framesBatchLength>0){let t=e.length%e_.framesBatchLength;if(0!==t){let s=e.slice(-1*t);to(s),"function"==typeof b&&b(s)}}try{"function"==typeof i&&await i({frames:ez.current.frames})}catch(e){M({error:e})}},[eS,e_.enable,e_.framesBatchLength,to,b,i,M]),onErrorCallback:M,framesPerColor:eC,flashColor:ew,secondaryFlashColor:eL}),tv=e.useCallback(()=>{!er.enableFarStep||(0===ez.current.total[q.FAR_FACE]&&(eY.current=!0),e_.enable&&(ez.current.total[q.FAR_FACE]+=1))},[e_.enable,er.enableFarStep]),ty=e.useMemo(()=>({x:Math.max(eV?.left,0),y:Math.max(eV?.top,0),width:Math.min(eV?.right-eV?.left,e4.width),height:Math.min(eV?.bottom-eV?.top,e4.height)}),[e4.height,e4.width,eV?.bottom,eV?.left,eV?.right,eV?.top]),tS=e.useCallback(({frame:e,prediction:t,originalRatio:s})=>{if(eK.current)return;let a=e=>{let t=Y({maskBoundingBox:ty,faceRatio:e.faceRatio,validFaceRatio:eg.validFaceRatio,video:ej.current,shouldCropCenterSquare:eg.enableCropCenterFar,cropArea:e4,frame:e.snapshot,facePrediction:e.facePrediction,detectionToWholeFaceRatio:eg.detectionToWholeFaceRatio}),s={blob:k.takePicture({canvas:t,quality:eg.imageQuality}),gesture:"frontal",captureTime:e.captureTime,selfieLabel:q.FAR_FACE,qualifyScore:e.qualifyScore,blurScore:e.blurScore,brightnessScore:e.brightnessScore,realQualifyScore:e.realQualifyScore,qualifyModelMessage:e.qualifyModelMessage};eK.current=!0,d.addExifData("flash_liveness.number_of_frames.far_frames",ez.current.total[q.FAR_FACE]),d.addExifData("model_score.face_blurry_score",s.blurScore),d.addExifData("model_score.face_brightness_score",s.brightnessScore),d.addExifData("model_score.face_qualify_score",s.qualifyScore),d.addExifData("debug_log.face_real_qualify_score",s.realQualifyScore),d.addExifData("debug_log.face_qualify_model_message",s.qualifyModelMessage),d.addExifData("selfie_label",s.selfieLabel),d.addExifData("capture_time",s.captureTime),d.addExifData("type",s.gesture),E(s),eI(""),e$(tt),eU(!0),eq(T.CLOSE_FACE),t_("move_face_closer")},n={qualifyScore:e.qualifyScore,blurScore:e.blurScore,isEyeClosed:e.isEyeClosed,faceRatio:e.faceRatio,snapshot:N(ej.current),captureTime:Date.now(),facePrediction:U(t,s),brightnessScore:e.brightnessScore,faceError:e.faceError,realQualifyScore:e.realQualifyScore,qualifyModelMessage:e.qualifyModelMessage};if(!ef.enable)return void a(n);if(!eZ.isAutoCapturing()){eT(!0),eZ.startCapturing({onDone:e=>{eT(!1),a(e)},initialFrame:n});return}eZ.captureFrame(n)},[ef.enable,eZ,ty,eg.validFaceRatio,eg.enableCropCenterFar,eg.detectionToWholeFaceRatio,eg.imageQuality,e4,E,tt,eU,t_]),tk=e.useCallback(({frame:e,prediction:t,originalRatio:s})=>{if(eX.current)return;let a=e=>{let t=Y({maskBoundingBox:ty,faceRatio:e.faceRatio,validFaceRatio:eg.validFaceRatio,video:ej.current,shouldCropCenterSquare:eg.enableCropCenterClose,cropArea:e4,frame:e.snapshot,facePrediction:e.facePrediction,detectionToWholeFaceRatio:eg.detectionToWholeFaceRatio}),s={blob:k.takePicture({canvas:t,quality:eg.imageQuality}),gesture:"frontal",captureTime:e.captureTime,selfieLabel:q.CLOSE_FACE,qualifyScore:e.qualifyScore,blurScore:e.blurScore,brightnessScore:e.brightnessScore,realQualifyScore:e.realQualifyScore,qualifyModelMessage:e.qualifyModelMessage};eX.current=!0,d.addExifData("flash_liveness.number_of_frames.close_frames",ez.current.total[q.CLOSE_FACE]),d.addExifData("model_score.face_blurry_score",s.blurScore),d.addExifData("model_score.face_brightness_score",s.brightnessScore),d.addExifData("model_score.face_qualify_score",s.qualifyScore),d.addExifData("debug_log.face_real_qualify_score",s.realQualifyScore),d.addExifData("debug_log.face_qualify_model_message",s.qualifyModelMessage),d.addExifData("selfie_label",s.selfieLabel),d.addExifData("capture_time",s.captureTime),d.addExifData("type",s.gesture),E(s),eI(""),eJ(!1),eq(T.START_FLASHING),tu()},n={qualifyScore:e.qualifyScore,blurScore:e.blurScore,isEyeClosed:e.isEyeClosed,faceRatio:e.faceRatio,snapshot:N(ej.current),captureTime:Date.now(),facePrediction:U(t,s),brightnessScore:e.brightnessScore,faceError:e.faceError,realQualifyScore:e.realQualifyScore,qualifyModelMessage:e.qualifyModelMessage};if(!eh.enable)return void a(n);if(!e0.isAutoCapturing()){t_("please_hold_still"),eT(!0),e0.startCapturing({onDone:e=>{eT(!1),a(e)},initialFrame:n});return}e0.captureFrame(n)},[eh.enable,e0,ty,eg.validFaceRatio,eg.enableCropCenterClose,eg.detectionToWholeFaceRatio,eg.imageQuality,e4,E,tu,t_]),tC=e.useMemo(()=>{if("number"==typeof th&&th%eC==0){let e=td[th-1];return e===td[th]?eR:Math.max(eF,eR)}return eR},[th,eF,eR,td,eC]),tF=null!==th&&eB===T.START_FLASHING,tx=e.useRef(!1),tE=e.useCallback(({prediction:e,canvas:t})=>{if(!tF||tx.current||null===tb.current.colorIndex||null===tb.current.frameIndex)return;if(!e_.enable)return void tm();let s=performance.now();if(null!==ta.current&&s-ta.current<tC)return;ta.current=s;let{frames:a}=ez.current,n=H({prediction:e,canvas:t,index:a.length,quality:e_.frameQuality}),i={color:tf,type:q.FLASHING,time:Math.round(performance.now()),colorIndex:tb.current.colorIndex,frameIndex:tb.current.frameIndex,colorStringIndex:tb.current.colorStringIndex,pattern:eM,session_id:e5},r=tp();if(r&&eu.enable&&(d.addExifData("flash_liveness.flash_liveness_in_ms",Math.round(performance.now()-ey.current)),i.exif=d.getCurrentExif()),n.metadata=JSON.stringify(i),a.push(n),e_.framesBatchLength>0&&a.length%e_.framesBatchLength==0){let e=a.slice(-1*e_.framesBatchLength);to(e),"function"==typeof b&&b(e)}r&&(tx.current=!0),tm()},[tF,e_.enable,e_.frameQuality,e_.framesBatchLength,tC,tf,tb,eM,e5,tp,eu.enable,tm,to,b]),tw=e.useCallback(({error:e})=>{eA(e),("no_face"===e||"multiple_faces"===e)&&"no_face"===e&&eY.current&&!eD&&tg({reason:$.no_face})},[eD,tg,eA]),{warmupDone:tM}=G({onError:M,isVideoPlaying:e7,step:eB,cropArea:e4,videoRef:ej,onFarFaceDetected:tv,onFarFullFaceDetected:tS,onCloseFaceDetected:e.useCallback(({prediction:e,canvas:t})=>{let{frames:s}=ez.current;if(er.enableFarStep||0!==s.length||(eY.current=!0),!e_.enable)return;let a=performance.now();if(null!==ta.current&&a-ta.current<e_.framesIntervalTime)return;ta.current=a;let n=H({prediction:e,canvas:t,index:s.length,quality:e_.frameQuality});if(n.metadata=JSON.stringify({color:"",type:q.CLOSE_FACE,time:Math.round(performance.now()),colorIndex:tb.current.colorIndex,pattern:eM,session_id:e5}),ez.current.total[q.CLOSE_FACE]+=1,s.push(n),e_.framesBatchLength>0&&s.length%e_.framesBatchLength==0){let e=s.slice(-1*e_.framesBatchLength);to(e),"function"==typeof b&&b(e)}},[er.enableFarStep,e_.enable,e_.framesIntervalTime,e_.frameQuality,e_.framesBatchLength,tb,eM,e5,to,b]),onCloseFullFaceDetected:tk,onFlashingFramesCaptured:tE,useFaceDetectorWhenFlashing:ex,onFaceError:tw,maskBoundingRect:eV,shouldPauseFaceDetection:eN||e2,faceDetectionSettings:R,shouldContinueOnError:eD,debug:ek});J(ej.current);z(()=>{!async function(){let{resourceReport:e,measureReport:t}=await C.reportAll();Object.values(e).forEach(e=>{eS("selfie_flash","sdk.download_model",e)}),Object.values(t).forEach(e=>{eS("selfie_flash","sdk.init_model",e)})}()},tM),z(()=>{er.enableFarStep?(t_("move_face_into_frame"),eq(T.FAR_FACE),e$(te)):(t_("move_face_closer"),eq(T.CLOSE_FACE),e$(tt)),eJ(!0),d.addExifData("selfie_type",e1),d.addExifData("flash_liveness",{flash_settings:{delay_between_colors:en.delayBetweenColors,flash_color:en.flashColor,secondary_flash_color:en.secondaryFlashColor},face_settings:{close_face_ratio:ei.closeFaceRatio,max_far_face_ratio:ei.maxFarFaceRatio,min_far_face_ratio:ei.minFarFaceRatio},mask_settings:{oval_vertical_offset:ea.ovalVerticalOffset,small_scale:ea.smallScale,large_scale:ea.largeScale},image_settings:{valid_face_ratio:eg.validFaceRatio}}),d.addExifData("global_session_id",e9.current),d.addExifData("pattern",eM),ev.enable&&d.addExifData("frame_batch_ids",ti),ey.current||(ey.current=performance.now())},tM&&e7),z(()=>eS("selfie_flash","user_activity.start"),!0),z(()=>eS("selfie_flash","user_activity.start_far"),eB===T.FAR_FACE),z(()=>eS("selfie_flash","user_activity.start_close"),eB===T.CLOSE_FACE),z(()=>eS("selfie_flash","user_activity.start_flash"),eB===T.START_FLASHING);let tR=null===th?0:Math.min(Math.round((th+1)/(eM.length*eC)*100),100),{Loading:tL}=m,tW=e.useCallback(()=>{eT(!1),eZ.stopCapturing(),e0.stopCapturing(),e3(!0)},[e0,eZ]),tI=e.useCallback(()=>{e3(!1),tg({reason:$.timeout})},[tg]),{remaining:tA}=K({shouldStart:eG&&ec.enable,onTimeout:tW,onDelayEnd:tI,onError:M,totalTime:ec.total,totalDelay:3,maxRetriesSettings:{enable:ec.enableMaxRetryCount,total:ec.maxRetryCount},interruptible:ec.interruptible}),tD=Z(eW),tT=e4.y+e4.height/2+tc;return a.jsxs(a.Fragment,{children:[a.jsx(f,{frontCamera:r,onVideoPlayed:e6,onClose:w,flipHorizontal:r,ref:ej,onError:M,videoSettings:eb,closeButton:a.jsx(es,{}),children:a.jsxs(X,{overlay:!tM||!e7,loadingComponent:tL,children:[""!==eW&&a.jsx(h,{}),a.jsx(I,{x:`${Math.round(e4.x)}px`,y:`${Math.round(e4.y)}px`,width:`${e4.width}px`,height:`${e4.height}px`,surroundStyle:{background:o("FlashLiveness.maskFill")({theme:eO})},children:a.jsx(u,{ref:eQ,scale:eH,debug:ek,width:e4.width,height:e4.height,padding:ea.ovalPadding,verticalOffset:tc,mask:eP})}),!eD&&""!==tD&&"start_flashing"!==eB&&a.jsx(et,{errorY:tT,errorMessage:tD})]})}),a.jsx(A,{step:eB,currentProgress:tR,errorCode:eW,timeoutProps:{remaining:tA,warningThreshold:ec.countdown,total:ec.total,shouldStart:eG&&ec.enable},isFlashingColor:tf===ew,isAutoCapturing:eD,extraConfig:x}),a.jsx(ee,{step:eB,currentColor:tf,flashIntensity:eE,flashColor:ew,secondaryFlashColor:eL})]})}let ey=s=>{let{apiCheck:n,onLivenessDetectionDone:i,frontalMinSize:r,serviceSettings:l,apiCredentials:o,..._}=s,g=_.customComponent?.FlashLivenessLoading??w,[c,f]=e.useState(!1),h=ee(),u=ed(),m=e_(),b=x.getEnabledServices(l,m),{verifyFlashLiveness:p,uploadImage:v}=function({outputEncryptionSettings:t,selfieType:s,enabledServices:a,apiCredentials:n}){let{apiClient:i}=F.useApiClient({apiCredentials:n}),r=e.useCallback(async e=>{if(!t.enable)return i.uploadImage({label:"portrait",file:e.blob,metadata:JSON.stringify({label:e.selfieLabel})});let s=new Blob([e.encrypted.hex]);return i.uploadImage({file:s,label:"portrait",metadata:JSON.stringify({label:e.selfieLabel})},{"X-TV-Key":t.key})},[i,t.enable,t.key]);return{verifyFlashLiveness:e.useCallback(async({videos:e,uploadedImages:t,metadata:n})=>{try{let r=null;a.enableVerifyFaceLiveness&&(r=i.verifyFaceLiveness({images:t.map(e=>({id:e?.data?.image_id,label:"portrait"})),videos:e,metadata:n,selfie_type:s}));let l=null;a.enableVerifySanityPortrait&&(l=i.requestVerifyPortrait({image:{id:t[t.length-1]?.data?.image_id},selfie_type:s}));let[o,_]=await Promise.all([r,l]);return{uploadedImages:t,faceLivenessResult:o,portraitResult:_}}catch(e){return console.error(e),{}}},[i,a.enableVerifyFaceLiveness,a.enableVerifySanityPortrait,s]),uploadImage:r}}({outputEncryptionSettings:h,selfieType:u,enabledServices:b,apiCredentials:o}),{captureFrameSettings:y,flashSettings:S,exifSettings:k,outputImageSettings:C}=em(),{framesIntervalTime:L}=y,{onFramesCaptured:W,onReset:I}=s,{onErrorCallback:A}=el(),D=et(),T=e.useRef([]),B=e.useRef([]),O=async e=>{let t=e;if(h.enable&&(t=await M.encryptFrames(t,h.key)),"function"==typeof W&&W(t),n&&b.enableUploadFrames){let e={};h.enable&&(e["X-TV-Key"]=h.key),es.uploadFrameBatch(ea(t),D,e)}},P=e.useCallback(async e=>{let t,s=new Promise(e=>{t=e});B.current.push(s);let a={...e,blob:await e.blob},i=await d.writeCurrentExif({imageData:a,enableExifData:k.enable});a.blob=i,h.enable&&(a.encrypted=await E.encrypt({blob:a.blob,key:h.key}));let r=e.selfieLabel===q.FAR_FACE?C.farImageOrder:C.closeImageOrder;T.current.push({image:a,uploadPromise:n&&b.enableUploadImages?v(a):null,order:r}),t()},[n,b.enableUploadImages,k.enable,h.enable,h.key,C.closeImageOrder,C.farImageOrder,v]),j=async e=>{f(!0),await Promise.all(B.current);let s={flash_color:S.flashColor,colors:S.colors,frames_per_color:S.framesPerColor,frame_interval:L,delay_between_colors:S.delayBetweenColors,use_face_detector_when_flashing:S.useFaceDetectorWhenFlashing};T.current=T.current.filter(e=>!!e),T.current.sort((e,t)=>e.order-t.order);let a=T.current.map(e=>e.image).filter(e=>"frontal"===e.gesture),l=a.map(e=>e.blob),o=a.map(e=>e.encrypted),_=l[l.length-1],g=_&&"number"==typeof r?await R.scaleImage(_,{minsize:r}):null,c=e.frames;if(h.enable&&(c=await M.encryptFrames(c,h.key)),!n||!b.enableUploadImages){await i({capturedFrames:c,frontalFaces:l,frontalFacesEncrypted:o,frontalScaledImage:g,steps:[],metadata:s}),f(!1);return}try{let e=null;e=y.enable?await es.getAllUploadedBatches():[{frames:ea(c)}];let t=await Promise.all(T.current.map(e=>e.uploadPromise)),{faceLivenessResult:a,portraitResult:n}=await p({videos:e,uploadedImages:t,metadata:s});if(es.resetUploadBatches(),f(!1),a?.errors)throw a.errors;if(n?.errors)throw n.errors;await i({capturedFrames:c,steps:[],frontalFaces:l.map((e,s)=>({blob:e,id:t?.[s]?.data?.image_id})),frontalFacesEncrypted:o,frontalScaledImage:g,apiCheckPassed:a?.data.is_live??!1,verifyFaceLivenessResult:a?.data??null,verifyPortraitResult:n?.data??null,uploadFramesResult:e})}catch(e){console.error(e),f(!1),A({...t.Errors.api_call_error,details:e})}};return a.jsxs(a.Fragment,{children:[a.jsx(ev,{..._,apiCheck:n,onFlashDone:j,onFramesCaptured:O,onReset:()=>{T.current=[],B.current=[],es.resetUploadBatches(),"function"==typeof I&&I()},onImageCaptured:P}),a.jsx(g,{loading:c})]})},eS=e=>{let{apiCredentials:t,outputEncryptionSettings:s,mode:n}=e;return a.jsx(A,{version:"v2",unmountOnHidden:!0,children:a.jsx(en,{apiCredentials:t,children:a.jsx(ec,{flashMode:n,children:a.jsx(ei,{settings:s,children:a.jsx(ey,{...e})})})})})};eS.propTypes={apiCheck:s.bool,apiCredentials:s.shape({accessKey:s.string,secretKey:s.string,apiUrl:s.string}),onReset:s.func,onLivenessDetectionDone:s.func,onClose:s.func,onError:s.func,onFramesCaptured:s.func,frontCamera:s.bool,styledComponent:s.shape({CloseCameraButton:s.node}),outputEncryptionSettings:s.shape({key:s.string}),frontalMinSize:s.number,serviceSettings:s.shape({enableGetClientSettings:s.bool,enableUploadFrames:s.bool,enableUploadImages:s.bool,enableVerifySanityPortrait:s.bool,enableVerifyFaceLiveness:s.bool}),mode:s.string,flowId:s.string,customTexts:s.shape({}),customComponents:s.shape({FlashLivenessBody:s.elementType,FlashLivenessOverlay:s.elementType}),extraConfig:s.shape({})},eS.defaultProps={apiCheck:!1,apiCredentials:{},onReset:()=>{},onLivenessDetectionDone:()=>{},onClose:()=>{},onError:()=>{},onFramesCaptured:()=>{},frontCamera:!0,styledComponent:{CloseCameraButton:null},outputEncryptionSettings:{key:""},frontalMinSize:null,serviceSettings:{enableGetClientSettings:!0,enableUploadFrames:!0,enableUploadImages:!0,enableVerifySanityPortrait:!0,enableVerifyFaceLiveness:!0},mode:t.Mode.FLASH_ADVANCED,flowId:"",customTexts:{},customComponents:{FlashLivenessBody:null,FlashLivenessOverlay:null},extraConfig:null};export{eS as default};
|
|
1
|
+
import{r as e,s as t,P as s,j as a,b as n,u as i,k as r,A as l,m as o,ap as _,aq as g,M as c,O as d,ar as f,as as h,at as u,au as m,av as b,aw as p,ax as v,ay as y,az as S,G as k,R as C,d as F,f as x,Q as E,aA as w,aB as M,Y as R}from"./chunk-68e90ba2.js";import{d as L}from"./chunk-5993adde.js";import{t as W}from"./chunk-7d0d639a.js";import{C as I,O as A}from"./chunk-5d5d5df1.js";import{u as D,S as T,a as B,F as q,b as O,c as P,d as j,n as Q,l as V,e as N,s as U,f as H,R as $,g as G,h as J,i as z,j as K,W as X,k as Y,m as Z,o as ee,p as et,q as es,r as ea,A as en,O as ei}from"./chunk-2e802851.js";import{m as er,u as el,b as eo}from"./chunk-bcf5eed2.js";import{u as e_}from"./chunk-c04f48e4.js";let eg=e.createContext(t.Mode.FLASH_ADVANCED),ec=({flashMode:e,children:s})=>{let n=e===t.Mode.FLASH||e.startsWith("flash_")?e:t.Mode.FLASH;return a.jsx(eg.Provider,{value:n,children:s})};ec.defaultProps={flashMode:t.Mode.FLASH_ADVANCED},ec.propTypes={flashMode(e,t,s){if(!/(^flash_|^flash$)/.test(e[t]))return Error(`Invalid prop \`${t}\` of value \`${e[t]}\` supplied to \`${s}\`. \`${t}\` is either 'flash' or begins with 'flash_'. Falling back to 'flash'.`)},children:s.node.isRequired};let ed=()=>{let t=e.useContext(eg);if(void 0===t)throw Error("useFlashMode must be used within a FlashModeProvider");return t},ef=0,eh=1,eu={data:{settings:{flashing_modes:{flash:{frames_per_color:8,frames_per_color_web:8,colors:"r r rrr",colors_web:"r r rrr"}},sdk_settings:{flash_liveness_settings:{frontal_face_check:{enable:!0,up_down_bound_min:.35,up_down_bound_max:.7},capture_frame_settings:{enable:!1,frames_batch_length:10,frames_interval_time:0,frame_quality:.8,frame_scale:1,auto_capture_min_frames:0,auto_capture_min_frames_far:0,auto_capture_min_frames_close:0},not_qualified_settings:{enable_far:!1,enable_close:!1,threshold_far:.11,threshold_close:.11},close_eyes_settings:{enable:!1,timeout:5,force_check:!1},face_settings:{close_face_ratio:.82,max_far_face_ratio:.9,min_far_face_ratio:.8,mobile:{close_face_ratio:.95,max_far_face_ratio:.9,min_far_face_ratio:.85}},flash_settings:{colors_length:10,flash_color:"rgb(255, 0, 0)",secondary_flash_color:"rgba(0,0,0,0.6)",delay_between_colors:120,flash_intensity:1,frames_per_color:4,use_face_detector_when_flashing:!1,flash_frame_interval:0},liveness_settings:{enable_far_step:!0},timeout_settings:{enable:!0,total:30,countdown:10,max_retry_count:0,non_stoppable:!1},exif_data_settings:{enable:!0},mask_settings:{chin_to_mask_bottom_padding:20,large_scale:.85,mobile:{chin_to_mask_bottom_padding:20,large_scale:.9,oval_padding:{bottom:20,left:20,right:20,top:0},oval_vertical_offset:60,small_scale:.65},oval_padding:{bottom:20,left:30,right:30,top:0},oval_vertical_offset:0,small_scale:.6},image_settings:{valid_face_ratio:.6,image_quality:1,crop_center_far:!0,crop_center_close:!1,detection_to_whole_face_ratio:.8},blur_far_settings:{enable:!0,blurry_threshold:.4,wait_for_best_image_time_ms:1e3},blur_close_settings:{enable:!0,blurry_threshold:.4,wait_for_best_image_time_ms:1e3},brightness_detection_far_settings:{enable_too_bright_check:!1,enable_too_dark_check:!1,too_bright_threshold:.83,too_dark_threshold:.195},brightness_detection_close_settings:{enable_too_bright_check:!1,enable_too_dark_check:!1,too_bright_threshold:.83,too_dark_threshold:.195},output_image_settings:{image_ordering:["close","far"]},auto_gen_frame_ids:{enable:!1,max_items:50}}}}}},em=()=>{let s=e_(),a=ed();return e.useMemo(()=>{let e=er({},eu,s),l=n(e,`data.settings.flashing_modes.${t.Mode.FLASH}`),o=n(e,`data.settings.flashing_modes.${a}`,l),_={enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.capture_frame_settings.enable"),framesIntervalTime:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.capture_frame_settings.frames_interval_time"),framesBatchLength:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.capture_frame_settings.frames_batch_length"),frameScale:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.capture_frame_settings.frame_scale"),frameQuality:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.capture_frame_settings.frame_quality"),autoCaptureMinFramesFar:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.capture_frame_settings.auto_capture_min_frames_far"),autoCaptureMinFramesClose:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.capture_frame_settings.auto_capture_min_frames_close")},g={enableFarStep:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.liveness_settings.enable_far_step")},c={flashColor:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.flash_settings.flash_color"),secondaryFlashColor:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.flash_settings.secondary_flash_color"),colors:i.getWebSetting(o,"colors"),delayBetweenColors:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.flash_settings.delay_between_colors"),framesPerColor:i.getWebSetting(o,"frames_per_color"),flashIntensity:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.flash_settings.flash_intensity"),useFaceDetectorWhenFlashing:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.flash_settings.use_face_detector_when_flashing"),flashFrameInterval:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.flash_settings.flash_frame_interval")},d={smallScale:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.mask_settings.mobile.small_scale":"data.settings.sdk_settings.flash_liveness_settings.mask_settings.small_scale"),largeScale:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.mask_settings.mobile.large_scale":"data.settings.sdk_settings.flash_liveness_settings.mask_settings.large_scale"),ovalPadding:{left:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.mask_settings.mobile.oval_padding.left":"data.settings.sdk_settings.flash_liveness_settings.mask_settings.oval_padding.left"),right:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.mask_settings.mobile.oval_padding.right":"data.settings.sdk_settings.flash_liveness_settings.mask_settings.oval_padding.right"),top:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.mask_settings.mobile.oval_padding.top":"data.settings.sdk_settings.flash_liveness_settings.mask_settings.oval_padding.top"),bottom:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.mask_settings.mobile.oval_padding.bottom":"data.settings.sdk_settings.flash_liveness_settings.mask_settings.oval_padding.bottom")},ovalVerticalOffset:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.mask_settings.mobile.oval_vertical_offset":"data.settings.sdk_settings.flash_liveness_settings.mask_settings.oval_vertical_offset"),chinToMaskBottomPadding:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.mask_settings.mobile.chin_to_mask_bottom_padding":"data.settings.sdk_settings.flash_liveness_settings.mask_settings.chin_to_mask_bottom_padding")},f={minFarFaceRatio:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.face_settings.mobile.min_far_face_ratio":"data.settings.sdk_settings.flash_liveness_settings.face_settings.min_far_face_ratio"),maxFarFaceRatio:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.face_settings.mobile.max_far_face_ratio":"data.settings.sdk_settings.flash_liveness_settings.face_settings.max_far_face_ratio"),closeFaceRatio:i.getWebSetting(e,r.isMobile?"data.settings.sdk_settings.flash_liveness_settings.face_settings.mobile.close_face_ratio":"data.settings.sdk_settings.flash_liveness_settings.face_settings.close_face_ratio")},h={enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.close_eyes_settings.enable"),timeout:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.close_eyes_settings.timeout"),forceCheck:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.close_eyes_settings.force_check")},u={enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.exif_data_settings.enable")},m={imageQuality:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.image_settings.image_quality"),validFaceRatio:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.image_settings.valid_face_ratio"),enableCropCenterFar:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.image_settings.crop_center_far"),enableCropCenterClose:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.image_settings.crop_center_close"),detectionToWholeFaceRatio:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.image_settings.detection_to_whole_face_ratio")},b=i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.timeout_settings.max_retry_count"),p={enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.timeout_settings.enable"),total:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.timeout_settings.total"),countdown:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.timeout_settings.countdown"),enableMaxRetryCount:b>0,maxRetryCount:b,interruptible:!i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.timeout_settings.non_stoppable")},v={enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.blur_far_settings.enable"),threshold:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.blur_far_settings.blurry_threshold"),duration:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.blur_far_settings.wait_for_best_image_time_ms")},y={enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.blur_close_settings.enable"),threshold:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.blur_close_settings.blurry_threshold"),duration:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.blur_close_settings.wait_for_best_image_time_ms")},S={enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.not_qualified_settings.enable_far"),threshold:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.not_qualified_settings.threshold_far")},k={enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.not_qualified_settings.enable_close"),threshold:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.not_qualified_settings.threshold_close")},C={enableTooBrightCheck:n(e,"data.settings.sdk_settings.flash_liveness_settings.brightness_detection_far_settings.enable_too_bright_check"),enableTooDarkCheck:n(e,"data.settings.sdk_settings.flash_liveness_settings.brightness_detection_far_settings.enable_too_dark_check"),tooBrightThreshold:n(e,"data.settings.sdk_settings.flash_liveness_settings.brightness_detection_far_settings.too_bright_threshold"),tooDarkThreshold:n(e,"data.settings.sdk_settings.flash_liveness_settings.brightness_detection_far_settings.too_dark_threshold")},F={enableTooBrightCheck:n(e,"data.settings.sdk_settings.flash_liveness_settings.brightness_detection_close_settings.enable_too_bright_check"),enableTooDarkCheck:n(e,"data.settings.sdk_settings.flash_liveness_settings.brightness_detection_close_settings.enable_too_dark_check"),tooBrightThreshold:n(e,"data.settings.sdk_settings.flash_liveness_settings.brightness_detection_close_settings.too_bright_threshold"),tooDarkThreshold:n(e,"data.settings.sdk_settings.flash_liveness_settings.brightness_detection_close_settings.too_dark_threshold")},x={imageOrdering:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.output_image_settings.image_ordering"),farImageOrder:eh,closeImageOrder:ef};Array.isArray(x.imageOrdering)&&2===x.imageOrdering.length&&"far"===x.imageOrdering[0]&&"close"===x.imageOrdering[1]&&(x.farImageOrder=0,x.closeImageOrder=1);let E={enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.auto_gen_frame_ids.enable")&&p.enable,maxItems:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.auto_gen_frame_ids.max_items")};return{captureFrameSettings:_,livenessSettings:g,flashSettings:c,maskSettings:d,faceSettings:f,closeEyesSettings:h,exifSettings:u,imageSettings:m,timeoutSettings:p,blurCheckFarSettings:v,blurCheckCloseSettings:y,notQualifiedFarSettings:S,notQualifiedCloseSettings:k,brightnessDetectionFarSettings:C,brightnessDetectionCloseSettings:F,outputImageSettings:x,autoGenFrameIds:E,frontalFaceCheckSettings:{enable:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.frontal_face_check.enable"),upDownBoundMin:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.frontal_face_check.up_down_bound_min"),upDownBoundMax:i.getWebSetting(e,"data.settings.sdk_settings.flash_liveness_settings.frontal_face_check.up_down_bound_max")}}},[s,a])},eb=r.isMobile?{width:{ideal:640},whiteBalanceMode:"none"}:{width:{ideal:9999},whiteBalanceMode:"none"},ep=(e,t)=>""===t.faceError&&(!!e.isEyeClosed&&!t.isEyeClosed||(!!e.isEyeClosed||!t.isEyeClosed)&&(!!m.hasBetterBrightnessScore(t.brightnessScore,e.brightnessScore)||!!m.hasSameBrightnessScore(t.brightnessScore,e.brightnessScore)&&b.hasBetterBlurScore(t.blurScore,e.blurScore)));function ev(s){let{onReset:n,onFlashDone:i,frontCamera:r,styledComponent:m,onFramesCaptured:b,customComponent:F,extraConfig:x,onImageCaptured:E}=s,{onCloseCallback:w,onErrorCallback:M}=el(),R=em(),A=F?.FlashLivenessBody??p,ee=F?.FlashLivenessOverlay??v,et=F?.FlashLivenessError??y,es=F?.FlashLivenessCloseIcon??S,{maskSettings:ea,flashSettings:en,faceSettings:ei,livenessSettings:er,captureFrameSettings:e_,imageSettings:eg,timeoutSettings:ec,blurCheckFarSettings:ef,blurCheckCloseSettings:eh,exifSettings:eu,autoGenFrameIds:ev}=R;if(ea.smallScale>ea.largeScale)throw Error("smallScale must be smaller than largeScale");let ey=e.useRef(),eS=D(),ek=eo(),{framesPerColor:eC,delayBetweenColors:eF,useFaceDetectorWhenFlashing:ex,flashIntensity:eE,flashColor:ew,colors:eM,flashFrameInterval:eR,secondaryFlashColor:eL}=en,[eW,eI]=e.useState(""),eA=e.useMemo(()=>W(eI,1e3),[]),[eD,eT]=e.useState(!1),[eB,eq]=e.useState(T.LOADING),eO=l(),eP={width:o("FlashLiveness.mask.width")({theme:eO}),height:o("FlashLiveness.mask.height")({theme:eO}),strokeColor:(eB===T.FAR_FACE||eB===T.CLOSE_FACE)&&eW&&!eD?o("FlashLiveness.mask.strokeColorError")({theme:eO}):o("FlashLiveness.mask.strokeColor")({theme:eO}),strokeWidth:2*o("FlashLiveness.mask.strokeWidth")({theme:eO}),path:o("FlashLiveness.mask.path")({theme:eO}),backgroundColor:o("FlashLiveness.maskFill")({theme:eO})},ej=e.useRef(null),[eQ,eV,eN,eU]=B(),[eH,e$]=e.useState(0),[eG,eJ]=e.useState(!1),ez=e.useRef({frames:[],total:{[q.FAR_FACE]:0,[q.CLOSE_FACE]:0}}),eK=e.useRef(!1),eX=e.useRef(!1),eY=e.useRef(!1),eZ=O({compareFn:ep,duration:ef.duration,minFrames:e_.autoCaptureMinFramesFar}),e0=O({compareFn:ep,duration:eh.duration,minFrames:e_.autoCaptureMinFramesClose}),e1=ed(),[e2,e3]=e.useState(!1),{sessionId:e5,updateSessionId:e8}=P(),e9=e.useRef(_.createSingleUUID()),{onVideoPlayed:e6,cropArea:e4,isPlaying:e7}=j({}),{smallScale:te,largeScale:tt}=Q(ea,{width:eP.width,height:eP.height},{width:e4.width,height:e4.height}),ts=e.useRef(null),ta=e.useRef(null),tn=1e3*ec.total/e_.framesIntervalTime+eM.length*eC,{uuids:ti,getNextUUID:tr,reset:tl}=g({total:Math.min(ev.maxItems,Math.ceil(tn/e_.framesBatchLength))}),to=e.useCallback(e=>{let t=e[e.length-1];try{let e=JSON.parse(t.metadata);ev.enable&&(e.global_batch_id=tr()),e.global_session_id=e9.current,t.metadata=JSON.stringify(e)}catch(e){console.error("Unable to process last frame metadata",e)}},[ev.enable,tr]),{playVoice:t_}=c.useVoicePlayer(),tg=e.useMemo(()=>L(({reason:e})=>{if(eY.current=!1,ez.current.frames=[],ez.current.total[q.FAR_FACE]=0,ez.current.total[q.CLOSE_FACE]=0,eK.current=!1,eX.current=!1,ts.current=null,ta.current=null,er.enableFarStep?(e$(te),eq(T.FAR_FACE),t_("move_face_into_frame")):t_("move_face_closer"),e8(),ev.enable){let e=tl();d.addExifData("frame_batch_ids",e)}n({reason:e})},200,{leading:!0}),[er.enableFarStep,e8,ev.enable,n,te,t_,tl]),tc=V({offset:ea.ovalVerticalOffset,ovalPadding:ea.ovalPadding,largeScale:tt,maskHeight:e4.height,ovalHeight:eP.height}),{flashingColors:td,currentColor:tf,colorIndex:th,startFlashing:tu,goToNextColor:tm,colorInfoRef:tb,checkIsLastColor:tp}=(({colors:s="",onFlashDone:a,onErrorCallback:n,framesPerColor:i,flashColor:r,secondaryFlashColor:l})=>{let[o,_]=e.useState(null),g=e.useRef({colorIndex:null,frameIndex:null,colorStringIndex:null}),c=e.useMemo(()=>s.split("").reduce((e,t)=>e+t.repeat(i),""),[s,i]),d=" "===c[o]?l:r,f=e.useCallback(()=>g.current.colorStringIndex===c.length-1,[c.length]),h=e.useCallback(()=>{if(g.current.colorIndex+=Math.floor((g.current.frameIndex+1)/i),g.current.frameIndex=(g.current.frameIndex+1)%i,g.current.colorStringIndex+=1,!(g.current.colorStringIndex>c.length)){if(g.current.colorStringIndex<c.length)return void _(e=>e+1);_(null),g.current={colorIndex:null,frameIndex:null,colorStringIndex:null},"function"==typeof a&&a()}},[c.length,i,a]),u=e.useCallback(()=>{_(0),g.current={colorIndex:0,frameIndex:0,colorStringIndex:0}},[]);return e.useEffect(()=>{0===c.length&&"function"==typeof n&&n(t.Errors.flashing_color_error)},[c.length,n]),{flashingColors:c,colorIndex:o,currentColor:d,goToNextColor:h,startFlashing:u,colorInfoRef:g,checkIsLastColor:f}})({colors:eM,onFlashDone:e.useCallback(async()=>{eq(T.STOP_DECTECTING),eS("selfie_flash","user_activity.finish_flash"),eS("selfie_flash","user_activity",({lastTimeLog:e})=>({flash_liveness_in_ms:e-ey.current}));let{frames:e}=ez.current;if(e_.enable&&e_.framesBatchLength>0){let t=e.length%e_.framesBatchLength;if(0!==t){let s=e.slice(-1*t);to(s),"function"==typeof b&&b(s)}}try{"function"==typeof i&&await i({frames:ez.current.frames})}catch(e){M({error:e})}},[eS,e_.enable,e_.framesBatchLength,to,b,i,M]),onErrorCallback:M,framesPerColor:eC,flashColor:ew,secondaryFlashColor:eL}),tv=e.useCallback(()=>{!er.enableFarStep||(0===ez.current.total[q.FAR_FACE]&&(eY.current=!0),e_.enable&&(ez.current.total[q.FAR_FACE]+=1))},[e_.enable,er.enableFarStep]),ty=e.useMemo(()=>({x:Math.max(eV?.left,0),y:Math.max(eV?.top,0),width:Math.min(eV?.right-eV?.left,e4.width),height:Math.min(eV?.bottom-eV?.top,e4.height)}),[e4.height,e4.width,eV?.bottom,eV?.left,eV?.right,eV?.top]),tS=e.useCallback(({frame:e,prediction:t,originalRatio:s})=>{if(eK.current)return;let a=e=>{let t=Y({maskBoundingBox:ty,faceRatio:e.faceRatio,validFaceRatio:eg.validFaceRatio,video:ej.current,shouldCropCenterSquare:eg.enableCropCenterFar,cropArea:e4,frame:e.snapshot,facePrediction:e.facePrediction,detectionToWholeFaceRatio:eg.detectionToWholeFaceRatio}),s={blob:k.takePicture({canvas:t,quality:eg.imageQuality}),gesture:"frontal",captureTime:e.captureTime,selfieLabel:q.FAR_FACE,qualifyScore:e.qualifyScore,blurScore:e.blurScore,brightnessScore:e.brightnessScore,realQualifyScore:e.realQualifyScore,qualifyModelMessage:e.qualifyModelMessage};eK.current=!0,d.addExifData("flash_liveness.number_of_frames.far_frames",ez.current.total[q.FAR_FACE]),d.addExifData("model_score.face_blurry_score",s.blurScore),d.addExifData("model_score.face_brightness_score",s.brightnessScore),d.addExifData("model_score.face_qualify_score",s.qualifyScore),d.addExifData("debug_log.face_real_qualify_score",s.realQualifyScore),d.addExifData("debug_log.face_qualify_model_message",s.qualifyModelMessage),d.addExifData("selfie_label",s.selfieLabel),d.addExifData("capture_time",s.captureTime),d.addExifData("type",s.gesture),E(s),eI(""),e$(tt),eU(!0),eq(T.CLOSE_FACE),t_("move_face_closer")},n={qualifyScore:e.qualifyScore,blurScore:e.blurScore,isEyeClosed:e.isEyeClosed,faceRatio:e.faceRatio,snapshot:N(ej.current),captureTime:Date.now(),facePrediction:U(t,s),brightnessScore:e.brightnessScore,faceError:e.faceError,realQualifyScore:e.realQualifyScore,qualifyModelMessage:e.qualifyModelMessage};if(!ef.enable)return void a(n);if(!eZ.isAutoCapturing()){eT(!0),eZ.startCapturing({onDone:e=>{eT(!1),a(e)},initialFrame:n});return}eZ.captureFrame(n)},[ef.enable,eZ,ty,eg.validFaceRatio,eg.enableCropCenterFar,eg.detectionToWholeFaceRatio,eg.imageQuality,e4,E,tt,eU,t_]),tk=e.useCallback(({frame:e,prediction:t,originalRatio:s})=>{if(eX.current)return;let a=e=>{let t=Y({maskBoundingBox:ty,faceRatio:e.faceRatio,validFaceRatio:eg.validFaceRatio,video:ej.current,shouldCropCenterSquare:eg.enableCropCenterClose,cropArea:e4,frame:e.snapshot,facePrediction:e.facePrediction,detectionToWholeFaceRatio:eg.detectionToWholeFaceRatio}),s={blob:k.takePicture({canvas:t,quality:eg.imageQuality}),gesture:"frontal",captureTime:e.captureTime,selfieLabel:q.CLOSE_FACE,qualifyScore:e.qualifyScore,blurScore:e.blurScore,brightnessScore:e.brightnessScore,realQualifyScore:e.realQualifyScore,qualifyModelMessage:e.qualifyModelMessage};eX.current=!0,d.addExifData("flash_liveness.number_of_frames.close_frames",ez.current.total[q.CLOSE_FACE]),d.addExifData("model_score.face_blurry_score",s.blurScore),d.addExifData("model_score.face_brightness_score",s.brightnessScore),d.addExifData("model_score.face_qualify_score",s.qualifyScore),d.addExifData("debug_log.face_real_qualify_score",s.realQualifyScore),d.addExifData("debug_log.face_qualify_model_message",s.qualifyModelMessage),d.addExifData("selfie_label",s.selfieLabel),d.addExifData("capture_time",s.captureTime),d.addExifData("type",s.gesture),E(s),eI(""),eJ(!1),eq(T.START_FLASHING),tu()},n={qualifyScore:e.qualifyScore,blurScore:e.blurScore,isEyeClosed:e.isEyeClosed,faceRatio:e.faceRatio,snapshot:N(ej.current),captureTime:Date.now(),facePrediction:U(t,s),brightnessScore:e.brightnessScore,faceError:e.faceError,realQualifyScore:e.realQualifyScore,qualifyModelMessage:e.qualifyModelMessage};if(!eh.enable)return void a(n);if(!e0.isAutoCapturing()){t_("please_hold_still"),eT(!0),e0.startCapturing({onDone:e=>{eT(!1),a(e)},initialFrame:n});return}e0.captureFrame(n)},[eh.enable,e0,ty,eg.validFaceRatio,eg.enableCropCenterClose,eg.detectionToWholeFaceRatio,eg.imageQuality,e4,E,tu,t_]),tC=e.useMemo(()=>{if("number"==typeof th&&th%eC==0){let e=td[th-1];return e===td[th]?eR:Math.max(eF,eR)}return eR},[th,eF,eR,td,eC]),tF=null!==th&&eB===T.START_FLASHING,tx=e.useRef(!1),tE=e.useCallback(({prediction:e,canvas:t})=>{if(!tF||tx.current||null===tb.current.colorIndex||null===tb.current.frameIndex)return;if(!e_.enable)return void tm();let s=performance.now();if(null!==ta.current&&s-ta.current<tC)return;ta.current=s;let{frames:a}=ez.current,n=H({prediction:e,canvas:t,index:a.length,quality:e_.frameQuality}),i={color:tf,type:q.FLASHING,time:Math.round(performance.now()),colorIndex:tb.current.colorIndex,frameIndex:tb.current.frameIndex,colorStringIndex:tb.current.colorStringIndex,pattern:eM,session_id:e5},r=tp();if(r&&eu.enable&&(d.addExifData("flash_liveness.flash_liveness_in_ms",Math.round(performance.now()-ey.current)),i.exif=d.getCurrentExif()),n.metadata=JSON.stringify(i),a.push(n),e_.framesBatchLength>0&&a.length%e_.framesBatchLength==0){let e=a.slice(-1*e_.framesBatchLength);to(e),"function"==typeof b&&b(e)}r&&(tx.current=!0),tm()},[tF,e_.enable,e_.frameQuality,e_.framesBatchLength,tC,tf,tb,eM,e5,tp,eu.enable,tm,to,b]),tw=e.useCallback(({error:e})=>{eA(e),("no_face"===e||"multiple_faces"===e)&&"no_face"===e&&eY.current&&!eD&&tg({reason:$.no_face})},[eD,tg,eA]),{warmupDone:tM}=G({onError:M,isVideoPlaying:e7,step:eB,cropArea:e4,videoRef:ej,onFarFaceDetected:tv,onFarFullFaceDetected:tS,onCloseFaceDetected:e.useCallback(({prediction:e,canvas:t})=>{let{frames:s}=ez.current;if(er.enableFarStep||0!==s.length||(eY.current=!0),!e_.enable)return;let a=performance.now();if(null!==ta.current&&a-ta.current<e_.framesIntervalTime)return;ta.current=a;let n=H({prediction:e,canvas:t,index:s.length,quality:e_.frameQuality});if(n.metadata=JSON.stringify({color:"",type:q.CLOSE_FACE,time:Math.round(performance.now()),colorIndex:tb.current.colorIndex,pattern:eM,session_id:e5}),ez.current.total[q.CLOSE_FACE]+=1,s.push(n),e_.framesBatchLength>0&&s.length%e_.framesBatchLength==0){let e=s.slice(-1*e_.framesBatchLength);to(e),"function"==typeof b&&b(e)}},[er.enableFarStep,e_.enable,e_.framesIntervalTime,e_.frameQuality,e_.framesBatchLength,tb,eM,e5,to,b]),onCloseFullFaceDetected:tk,onFlashingFramesCaptured:tE,useFaceDetectorWhenFlashing:ex,onFaceError:tw,maskBoundingRect:eV,shouldPauseFaceDetection:eN||e2,faceDetectionSettings:R,shouldContinueOnError:eD,debug:ek});J(ej.current);z(()=>{!async function(){let{resourceReport:e,measureReport:t}=await C.reportAll();Object.values(e).forEach(e=>{eS("selfie_flash","sdk.download_model",e)}),Object.values(t).forEach(e=>{eS("selfie_flash","sdk.init_model",e)})}()},tM),z(()=>{er.enableFarStep?(t_("move_face_into_frame"),eq(T.FAR_FACE),e$(te)):(t_("move_face_closer"),eq(T.CLOSE_FACE),e$(tt)),eJ(!0),d.addExifData("selfie_type",e1),d.addExifData("flash_liveness",{flash_settings:{delay_between_colors:en.delayBetweenColors,flash_color:en.flashColor,secondary_flash_color:en.secondaryFlashColor},face_settings:{close_face_ratio:ei.closeFaceRatio,max_far_face_ratio:ei.maxFarFaceRatio,min_far_face_ratio:ei.minFarFaceRatio},mask_settings:{oval_vertical_offset:ea.ovalVerticalOffset,small_scale:ea.smallScale,large_scale:ea.largeScale},image_settings:{valid_face_ratio:eg.validFaceRatio}}),d.addExifData("global_session_id",e9.current),d.addExifData("pattern",eM),ev.enable&&d.addExifData("frame_batch_ids",ti),ey.current||(ey.current=performance.now())},tM&&e7),z(()=>eS("selfie_flash","user_activity.start"),!0),z(()=>eS("selfie_flash","user_activity.start_far"),eB===T.FAR_FACE),z(()=>eS("selfie_flash","user_activity.start_close"),eB===T.CLOSE_FACE),z(()=>eS("selfie_flash","user_activity.start_flash"),eB===T.START_FLASHING);let tR=null===th?0:Math.min(Math.round((th+1)/(eM.length*eC)*100),100),{Loading:tL}=m,tW=e.useCallback(()=>{eT(!1),eZ.stopCapturing(),e0.stopCapturing(),e3(!0)},[e0,eZ]),tI=e.useCallback(()=>{e3(!1),tg({reason:$.timeout})},[tg]),{remaining:tA}=K({shouldStart:eG&&ec.enable,onTimeout:tW,onDelayEnd:tI,onError:M,totalTime:ec.total,totalDelay:3,maxRetriesSettings:{enable:ec.enableMaxRetryCount,total:ec.maxRetryCount},interruptible:ec.interruptible}),tD=Z(eW),tT=e4.y+e4.height/2+tc;return a.jsxs(a.Fragment,{children:[a.jsx(f,{frontCamera:r,onVideoPlayed:e6,onClose:w,flipHorizontal:r,ref:ej,onError:M,videoSettings:eb,closeButton:a.jsx(es,{}),children:a.jsxs(X,{overlay:!tM||!e7,loadingComponent:tL,children:[""!==eW&&a.jsx(h,{}),a.jsx(I,{x:`${Math.round(e4.x)}px`,y:`${Math.round(e4.y)}px`,width:`${e4.width}px`,height:`${e4.height}px`,surroundStyle:{background:o("FlashLiveness.maskFill")({theme:eO})},children:a.jsx(u,{ref:eQ,scale:eH,debug:ek,width:e4.width,height:e4.height,padding:ea.ovalPadding,verticalOffset:tc,mask:eP})}),!eD&&""!==tD&&"start_flashing"!==eB&&a.jsx(et,{errorY:tT,errorMessage:tD})]})}),a.jsx(A,{step:eB,currentProgress:tR,errorCode:eW,timeoutProps:{remaining:tA,warningThreshold:ec.countdown,total:ec.total,shouldStart:eG&&ec.enable},isFlashingColor:tf===ew,isAutoCapturing:eD,extraConfig:x}),a.jsx(ee,{step:eB,currentColor:tf,flashIntensity:eE,flashColor:ew,secondaryFlashColor:eL})]})}let ey=s=>{let{apiCheck:n,onLivenessDetectionDone:i,frontalMinSize:r,serviceSettings:l,apiCredentials:o,..._}=s,g=_.customComponent?.FlashLivenessLoading??w,[c,f]=e.useState(!1),h=ee(),u=ed(),m=e_(),b=x.getEnabledServices(l,m),{verifyFlashLiveness:p,uploadImage:v}=function({outputEncryptionSettings:t,selfieType:s,enabledServices:a,apiCredentials:n}){let{apiClient:i}=F.useApiClient({apiCredentials:n}),r=e.useCallback(async e=>{if(!t.enable)return i.uploadImage({label:"portrait",file:e.blob,metadata:JSON.stringify({label:e.selfieLabel})});let s=new Blob([e.encrypted.hex]);return i.uploadImage({file:s,label:"portrait",metadata:JSON.stringify({label:e.selfieLabel})},{"X-TV-Key":t.key})},[i,t.enable,t.key]);return{verifyFlashLiveness:e.useCallback(async({videos:e,uploadedImages:t,metadata:n})=>{try{let r=null;a.enableVerifyFaceLiveness&&(r=i.verifyFaceLiveness({images:t.map(e=>({id:e?.data?.image_id,label:"portrait"})),videos:e,metadata:n,selfie_type:s}));let l=null;a.enableVerifySanityPortrait&&(l=i.requestVerifyPortrait({image:{id:t[t.length-1]?.data?.image_id},selfie_type:s}));let[o,_]=await Promise.all([r,l]);return{uploadedImages:t,faceLivenessResult:o,portraitResult:_}}catch(e){return console.error(e),{}}},[i,a.enableVerifyFaceLiveness,a.enableVerifySanityPortrait,s]),uploadImage:r}}({outputEncryptionSettings:h,selfieType:u,enabledServices:b,apiCredentials:o}),{captureFrameSettings:y,flashSettings:S,exifSettings:k,outputImageSettings:C}=em(),{framesIntervalTime:L}=y,{onFramesCaptured:W,onReset:I}=s,{onErrorCallback:A}=el(),D=et(),T=e.useRef([]),B=e.useRef([]),O=async e=>{let t=e;if(h.enable&&(t=await M.encryptFrames(t,h.key)),"function"==typeof W&&W(t),n&&b.enableUploadFrames){let e={};h.enable&&(e["X-TV-Key"]=h.key),es.uploadFrameBatch(ea(t),D,e)}},P=e.useCallback(async e=>{let t,s=new Promise(e=>{t=e});B.current.push(s);let a={...e,blob:await e.blob},i=await d.writeCurrentExif({imageData:a,enableExifData:k.enable});a.blob=i,h.enable&&(a.encrypted=await E.encrypt({blob:a.blob,key:h.key}));let r=e.selfieLabel===q.FAR_FACE?C.farImageOrder:C.closeImageOrder;T.current.push({image:a,uploadPromise:n&&b.enableUploadImages?v(a):null,order:r}),t()},[n,b.enableUploadImages,k.enable,h.enable,h.key,C.closeImageOrder,C.farImageOrder,v]),j=async e=>{f(!0),await Promise.all(B.current);let s={flash_color:S.flashColor,colors:S.colors,frames_per_color:S.framesPerColor,frame_interval:L,delay_between_colors:S.delayBetweenColors,use_face_detector_when_flashing:S.useFaceDetectorWhenFlashing};T.current=T.current.filter(e=>!!e),T.current.sort((e,t)=>e.order-t.order);let a=T.current.map(e=>e.image).filter(e=>"frontal"===e.gesture),l=a.map(e=>e.blob),o=a.map(e=>e.encrypted),_=l[l.length-1],g=_&&"number"==typeof r?await R.scaleImage(_,{minsize:r}):null,c=e.frames;if(h.enable&&(c=await M.encryptFrames(c,h.key)),!n||!b.enableUploadImages){await i({capturedFrames:c,frontalFaces:l,frontalFacesEncrypted:o,frontalScaledImage:g,steps:[],metadata:s}),f(!1);return}try{let e=null;e=y.enable?await es.getAllUploadedBatches():[{frames:ea(c)}];let t=await Promise.all(T.current.map(e=>e.uploadPromise)),{faceLivenessResult:a,portraitResult:n}=await p({videos:e,uploadedImages:t,metadata:s});if(es.resetUploadBatches(),f(!1),a?.errors)throw a.errors;if(n?.errors)throw n.errors;await i({capturedFrames:c,steps:[],frontalFaces:l.map((e,s)=>({blob:e,id:t?.[s]?.data?.image_id})),frontalFacesEncrypted:o,frontalScaledImage:g,apiCheckPassed:a?.data.is_live??!1,verifyFaceLivenessResult:a?.data??null,verifyPortraitResult:n?.data??null,uploadFramesResult:e})}catch(e){console.error(e),f(!1),A({...t.Errors.api_call_error,details:e})}};return a.jsxs(a.Fragment,{children:[a.jsx(ev,{..._,apiCheck:n,onFlashDone:j,onFramesCaptured:O,onReset:()=>{T.current=[],B.current=[],es.resetUploadBatches(),"function"==typeof I&&I()},onImageCaptured:P}),a.jsx(g,{loading:c})]})},eS=e=>{let{apiCredentials:t,outputEncryptionSettings:s,mode:n}=e;return a.jsx(A,{version:"v2",unmountOnHidden:!0,children:a.jsx(en,{apiCredentials:t,children:a.jsx(ec,{flashMode:n,children:a.jsx(ei,{settings:s,children:a.jsx(ey,{...e})})})})})};eS.propTypes={apiCheck:s.bool,apiCredentials:s.shape({accessKey:s.string,secretKey:s.string,apiUrl:s.string}),onReset:s.func,onLivenessDetectionDone:s.func,onClose:s.func,onError:s.func,onFramesCaptured:s.func,frontCamera:s.bool,styledComponent:s.shape({CloseCameraButton:s.node}),outputEncryptionSettings:s.shape({key:s.string}),frontalMinSize:s.number,serviceSettings:s.shape({enableGetClientSettings:s.bool,enableUploadFrames:s.bool,enableUploadImages:s.bool,enableVerifySanityPortrait:s.bool,enableVerifyFaceLiveness:s.bool}),mode:s.string,flowId:s.string,customTexts:s.shape({}),customComponents:s.shape({FlashLivenessBody:s.elementType,FlashLivenessOverlay:s.elementType}),extraConfig:s.shape({})},eS.defaultProps={apiCheck:!1,apiCredentials:{},onReset:()=>{},onLivenessDetectionDone:()=>{},onClose:()=>{},onError:()=>{},onFramesCaptured:()=>{},frontCamera:!0,styledComponent:{CloseCameraButton:null},outputEncryptionSettings:{key:""},frontalMinSize:null,serviceSettings:{enableGetClientSettings:!0,enableUploadFrames:!0,enableUploadImages:!0,enableVerifySanityPortrait:!0,enableVerifyFaceLiveness:!0},mode:t.Mode.FLASH_ADVANCED,flowId:"",customTexts:{},customComponents:{FlashLivenessBody:null,FlashLivenessOverlay:null},extraConfig:null};export{eS as default};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{P as e,c as a,r as t,j as r,o as s,e as n,b as i,h as c,s as l,i as d}from"./chunk-9390d088.js";import{P as o,O as u}from"./chunk-e468b8ce.js";import{u as f,a as p,S as m,R as g,U as y}from"./chunk-afb105f2.js";import{d as _,m as C}from"./chunk-4da2a90d.js";import{L as h}from"./chunk-dad8ede3.js";import{t as R}from"./chunk-fdbce3d2.js";let v=e=>{let{clientSettings:i,onError:c,onStepDone:l,logCredentials:d,uiOnlyComponent:o,detectIdCard:u,outputEncryptionSettings:g,steps:y,customTheme:C}=e,{settings:h}=f({clientSettings:i}),{themeVersion:R}=a.useSDKSettings(),v=t.useCallback(async e=>await l({...e,restartSession:I?.handleRestartSession}),[l,I?.handleRestartSession]),I=p({settings:h,onError:c,detectIdCard:u,outputEncryptionSettings:g,steps:y,onStepDone:v});return r.jsx(s,{theme:{...C,themeVersion:R,defaultThemes:_},children:r.jsx(n.SDKTrackingProvider,{value:{tracking:{...d}},children:r.jsx(o,{...e,onStepDone:v,settings:h,scannerTypeCons:m,...I})})})};v.propTypes={clientSettings:e.shape({}),onError:e.func,onStepDone:e.func,logCredentials:e.shape({}),readIDCardUIOnlyComponent:e.func,uiOnlyComponent:e.func,steps:e.arrayOf(e.shape({})),detectIdCard:e.func,outputEncryptionSettings:e.shape({}),customTheme:e.shape({})},v.defaultProps={clientSettings:void 0,onError:()=>{},onStepDone:()=>{},logCredentials:{enable:!0},readIDCardUIOnlyComponent:g,uiOnlyComponent:y,steps:void 0,detectIdCard:void 0,outputEncryptionSettings:null,customTheme:{}};let I={id_card_sanity:3,portrait_sanity:3,face_liveness_with_card_tampering_ocr:3,compare_faces:3},F={card_sanity:!0,card_tampering:!0,card_ocr:!0,face_sanity:!0,face_liveness:!0,compare_faces:!0,search_face:!0,index_face:!0},T="ID_CARD",A="FACE_LIVENESS",k="IDLE",S={},b={REACH_RETRY_LIMIT:{en:"You have reached the retry limit. Please try again later.",vi:"Bạn đ\xe3 vượt qu\xe1 số lần thử. Vui l\xf2ng thử lại sau."},FAIL_STEP:{en:"Please try again at step: <%= step %>.",vi:"Vui l\xf2ng thử lại ở bước: <%= step %>."},FAIL_FRONT_CARD_SANITY:{en:"The front side of your ID card failed sanity check.",vi:"H\xecnh ảnh Mặt trước của GTTT kh\xf4ng đạt chất lượng y\xeau cầu."},FAIL_FRONT_CARD_TAMPERING:{en:"The front side of your ID card failed tampering check.",vi:"H\xecnh ảnh Mặt trước của GTTT kh\xf4ng hợp lệ."},FAIL_FRONT_CARD_OCR:{en:"Cannot read information on the front side of your ID card.",vi:"Kh\xf4ng đọc được th\xf4ng tin từ h\xecnh ảnh Mặt trước của GTTT."},FAIL_BACK_CARD_SANITY:{en:"The back side of your ID card failed sanity check.",vi:"H\xecnh ảnh Mặt sau của GTTT kh\xf4ng đạt chất lượng y\xeau cầu."},FAIL_BACK_CARD_TAMPERING:{en:"The back side of your ID card failed tampering check.",vi:"H\xecnh ảnh Mặt sau của GTTT kh\xf4ng hợp lệ."},FAIL_BACK_CARD_OCR:{en:"Cannot read information on the back side of your ID card.",vi:"Kh\xf4ng đọc được th\xf4ng tin từ h\xecnh ảnh Mặt sau của GTTT."},FAIL_FACE_SANITY:{en:"Selfie step failed sanity check.",vi:"H\xecnh ảnh khu\xf4n mặt kh\xf4ng đạt chất lượng y\xeau cầu."},FAIL_FACE_LIVENESS:{en:"Selfie step failed liveness check.",vi:"H\xecnh ảnh khu\xf4n mặt kh\xf4ng hợp lệ."},FAIL_COMPARE_FACE:{en:"Failed compare faces between ID photo and selfie.",vi:"H\xecnh ảnh khu\xf4n mặt tr\xean GTTT kh\xf4ng giống h\xecnh chụp ch\xe2n dung"},RETRY_BUTTON:{en:"Retry",vi:"Thử lại"},STOP_BUTTON:{en:"Stop",vi:"Dừng"},FRONT_CARD:{en:"Front Card",vi:"Mặt trước"},BACK_CARD:{en:"Back Card",vi:"Mặt sau"},ID_CARD:{en:"ID Card",vi:"Thẻ ID"},FACE_LIVENESS:{en:"Face Liveness",vi:"Nhận diện khu\xf4n mặt"}};function L(e){var a;if("object"!=typeof(a=e)||"function"!=typeof a.then)return"pending";let t={};return Promise.race([e,t]).then(e=>e===t?"pending":"fulfilled",()=>"rejected")}let w=(e,a)=>{if(!i(a,"face_liveness"))return!1;let t=i(e,"verifyFaceLivenessResult.is_live",!1),r=i(e,"verifyFaceLivenessResult.status","");return!t||"success"!==r},E=(e,a)=>{if(!i(a,"card_sanity"))return!1;let t=i(e,"apiResult.sanityResult.status",""),r=i(e,"apiResult.sanityResult.card_sanity.verdict","");return"success"!==t||"good"!==r},D=e=>!!i(e,"errors")||"success"!==i(e,"data.status","")||"good"!==i(e,"data.card_tampering.verdict",""),O=e=>!!i(e,"errors")||"success"!==i(e,"data.status",""),N=e=>{let a=i(e,"compare_faces",[]);return a[0]?.result!=="matched"||1!==a.filter(e=>e?.result==="matched").length||e.errors},P=async(e,a,t)=>{if(i(a,"card_tampering")){let a=i(e.current,"frontCard.apiResult.detectIDTamperingBackground");if("fulfilled"===await L(a)){let{result:a,message:t}=await i(e.current,"frontCard.apiResult.detectIDTamperingBackground"),r=D(a),s={frontCard:{apiResult:{tamperingInfo:{...a?.data,message:r?i(t,"error"):i(t,"success")}}}};if(C(e.current,s),r)return!0}if(t){let a=i(e.current,"backCard.apiResult.detectIDTamperingBackground");if("fulfilled"===await L(a)){let{result:a,message:t}=await i(e.current,"backCard.apiResult.detectIDTamperingBackground"),r=D(a),s={backCard:{apiResult:{tamperingInfo:{...a?.data,message:r?i(t,"error"):i(t,"success")}}}};if(C(e.current,s),r)return!0}}}if(i(a,"card_ocr")){let a=i(e.current,"frontCard.apiResult.readIDCardBackground");if("fulfilled"===await L(a)){let{result:a,message:t}=await i(e.current,"frontCard.apiResult.readIDCardBackground"),r=O(a),s={frontCard:{apiResult:{cardInfo:{...a?.data,message:r?i(t,"error"):i(t,"success")}}}};if(C(e.current,s),r)return!0}if(t){let a=i(e.current,"backCard.apiResult.readIDCardBackground");if("fulfilled"===await L(a)){let{result:a,message:t}=await i(e.current,"backCard.apiResult.readIDCardBackground"),r=O(a),s={backCard:{apiResult:{cardInfo:{...a?.data,message:r?i(t,"error"):i(t,"success")}}}};if(C(e.current,s),r)return!0}}}return!1},x=async(e,a,t)=>{let r=!1;if(i(a,"card_tampering")){let{result:a,message:s}=await i(e.current,"frontCard.apiResult.detectIDTamperingBackground"),n=D(a);r=r||n;let c={frontCard:{apiResult:{tamperingInfo:{...a?.data,message:n?i(s,"error"):i(s,"success")}}}};if(C(e.current,c),t){let{result:a}=await i(e.current,"backCard.apiResult.detectIDTamperingBackground"),t=D(a);r=r||t;let n={backCard:{apiResult:{tamperingInfo:{...a?.data,message:t?i(s,"error"):i(s,"success")}}}};C(e.current,n)}}if(i(a,"card_ocr")){let{result:a,message:s}=await i(e.current,"frontCard.apiResult.readIDCardBackground"),n=O(a);r=r||n;let c={frontCard:{apiResult:{cardInfo:{...a?.data,message:n?i(s,"error"):i(s,"success")}}}};if(C(e.current,c),t){let{result:a}=await i(e.current,"backCard.apiResult.readIDCardBackground"),t=O(a);r=r||t;let n={backCard:{apiResult:{cardInfo:{...a?.data,message:t?i(s,"error"):i(s,"success")}}}};C(e.current,n)}}return r},j=(e,a)=>{for(let t in e)a.includes(t)?delete e[t]:"object"==typeof e[t]&&j(e[t],a);return e},B=e=>j(e.current,["message","step","restartSession","detectIDTamperingBackground","readIDCardBackground"]),K=(e,a,t)=>{let r=[];if(i(e,"frontCard.apiResult.sanityResult")&&"good"!==i(e,"frontCard.apiResult.sanityResult.card_sanity.verdict","")){let a=i(e,"frontCard.apiResult.sanityResult.message",null);a?.[t]?r.push(a[t]):r.push(b.FAIL_FRONT_CARD_SANITY[t])}if(i(e,"frontCard.apiResult.tamperingInfo")&&"good"!==i(e,"frontCard.apiResult.tamperingInfo.card_tampering.verdict","")){let a=i(e,"frontCard.apiResult.tamperingInfo.message",null);a?.[t]?r.push(a[t]):r.push(b.FAIL_FRONT_CARD_TAMPERING[t])}if(i(e,"frontCard.apiResult.cardInfo")&&"success"!==i(e,"frontCard.apiResult.cardInfo.status","")){let a=i(e,"frontCard.apiResult.cardInfo.message",null);a?.[t]?r.push(a[t]):r.push(b.FAIL_FRONT_CARD_OCR[t])}if(i(e,"backCard.apiResult.sanityResult")&&"good"!==i(e,"backCard.apiResult.sanityResult.card_sanity.verdict","")){let a=i(e,"backCard.apiResult.sanityResult.message",null);a?.[t]?r.push(a[t]):r.push(b.FAIL_BACK_CARD_SANITY[t])}if(i(e,"backCard.apiResult.tamperingInfo")&&"good"!==i(e,"backCard.apiResult.tamperingInfo.card_tampering.verdict","")){let a=i(e,"backCard.apiResult.tamperingInfo.message",null);a?.[t]?r.push(a[t]):r.push(b.FAIL_BACK_CARD_TAMPERING[t])}if(i(e,"backCard.apiResult.cardInfo")&&"success"!==i(e,"backCard.apiResult.cardInfo.status","")){let a=i(e,"backCard.apiResult.cardInfo.message",null);a?.[t]?r.push(a[t]):r.push(b.FAIL_BACK_CARD_OCR[t])}if(i(e,"faceLiveness.verifyFacePortraitResult")&&"good"!==i(e,"faceLiveness.verifyFacePortraitResult.portrait_sanity.verdict","")){let a=i(e,"faceLiveness.verifyFacePortraitResult.message",null);a?.[t]?r.push(a[t]):r.push(b.FAIL_FACE_SANITY[t])}if(i(e,"faceLiveness.verifyFaceLivenessResult")&&!i(e,"faceLiveness.verifyFaceLivenessResult.is_live",!1)){let a=i(e,"faceLiveness.verifyFaceLivenessResult.message",null);a?.[t]?r.push(a[t]):r.push(b.FAIL_FACE_LIVENESS[t])}if(i(e,"compareFaces",null)&&N(i(e,"compareFaces"))){let a=i(e,"compareFaces.message",null);a?.[t]?r.push(a[t]):r.push(b.FAIL_COMPARE_FACE[t])}return{retryAt:a,results:r}},M=e=>{let a=i(e,"frontCard.apiResult.cardInfo.card_information",[]).find(e=>"id"===e.field);return i(a,"value","")},{Errors:Y,IDCardSide:G,FaceDirection:U,Mode:V}=l,q=[],H=()=>{q=[]},J=()=>new Promise(e=>{let a=setInterval(()=>{q.every(e=>e.id)&&(e(),clearInterval(a))},200)});async function W({hasBackCardStep:e,stepResult:a,frontCardId:t,qrImageId:r,sdkAdapter:s,onError:n,refEkycResult:l,handleFailCardTamperingOCRBackground:d,services:o}){let u,f,p,m;if(!(s instanceof c))return a;let{cardSide:g,cardType:y,recordedVideos:_,qrScannedResult:C,image:h}=a;if(g===G.BACK&&!t)return n(Y.missing_front_id_card),!1;let{uploadImage:R,uploadFiles:v,requestVerifyIDCard:I,detectIDTampering:F,readIDCard:T}=s,A=[R({file:h?.blob,label:`id_card.${y}.${g}`})];C&&C.image&&C.result&&A.push(R({file:C?.image?.blob,label:"qr_code",rawString:C?.result}));let[k,S]=await Promise.all(A);if(k.errors)return n({...Y.upload_error,details:k.reason}),!1;let b=k?.data?.image_id,L=S?.data?.image_data||r;g===G.FRONT?u=b:(u=t,f=b);let w={qrImageId:L,frontCardId:u,backCardId:f};if(i(o,"card_sanity")){let{result:e,message:t}=await I({card_type:y,image1:{id:g===G.FRONT?u:f}});if("good"!==i(e,"data.card_sanity.verdict","")||e.errors)return{...a,apiResult:{...w,sanityResult:{...e?.data,message:i(t,"error")}}};w.sanityResult={...e?.data,message:i(t,"success")}}if(g===G.BACK&&"function"==typeof d&&await P(l,o,e))return d(),{...a,apiResult:w};if(i(o,"card_tampering")){let e={card_type:y,image:{id:u},...g===G.FRONT?{image2:void 0,level:"1"}:{image2:{id:f},level:"concurrent"}};if(L&&(e.qr1_images=[{id:L}]),_&&Array.isArray(_)&&_.length>0){let a=_.filter(e=>null!==e.id),t=_.filter(e=>null===e.id&&e.frames.length>0),r=await Promise.all(t.map(e=>v({frames:e.frames})));e.videos=[...a.map(e=>({id:e.id})),...r.map(e=>({id:e.data.file_id}))]}p=F(e)}if(i(o,"card_ocr")){let e={card_type:y,image1:g===G.FRONT?{id:u}:{id:f}};L&&(e.qr1_images={id:L}),m=T(e)}return{...a,apiResult:{...w,detectIDTamperingBackground:p,readIDCardBackground:m}}}async function z({stepResult:e,sdkAdapter:a,services:t}){let{uploadImage:r,uploadFiles:s,verifyFaceLiveness:n,requestVerifyPortrait:c}=a,l=i(e,"frontalFaces",[]).map(e=>r({file:e,label:"portrait",metadata:JSON.stringify({gesture:U.FRONTAL},{"Content-Type":"multipart/form-data"})})),d=i(e,"steps",[]).map(e=>r({file:e?.image?.blob,label:"portrait",metadata:JSON.stringify({gesture:e?.name})},{"Content-Type":"multipart/form-data"})),o=await Promise.all([...l,...d]),u=o.slice(0,l.length),f=o.slice(-d.length);await J();let{video:p}=e;p&&await s({file:p,label:"video"},{"Content-Type":"multipart/form-data"});let m={...e,frontalFaces:u.map((a,t)=>({id:a?.data?.image_id,blob:e?.frontalFaces?.[t]})),steps:f.map((a,t)=>({image:{id:a?.data?.image_id,blob:e?.steps?.[t]?.image?.blob},name:e?.steps?.[t]?.name})),capturedFrames:e?.capturedFrames};if(i(t,"face_sanity")){let{result:e,message:a}=await c({image:{id:u?.[u.length-1]?.data?.image_id}});if("good"!==i(e,"data.portrait_sanity.verdict","")||i(e,"errors"))return{...m,verifyFacePortraitResult:{...i(e,"data",i(e,"error",{})),message:i(a,"error")}};m.verifyFacePortraitResult={...e?.data,message:i(a,"success")}}if(i(t,"face_liveness")){let{result:a,message:t}=await n({images:u.map(e=>({id:e?.data?.image_id})),gesture_images:f.map((a,t)=>({gesture:e?.steps?.[t]?.name,images:[{id:a?.data?.image_id}]})),videos:q}),r=i(a,"data.is_live");m.verifyFaceLivenessResult={...i(a,"data",i(a,"error",{})),message:r?i(t,"success"):i(t,"error")}}return m}async function $({stepResult:e,sdkAdapter:a,services:t}){let{uploadImage:r,uploadFiles:s,verifyFaceLiveness:n,requestVerifyPortrait:c}=a,l=i(e,"frontalFaces",[]).map(e=>r({file:e,label:"portrait",metadata:JSON.stringify({gesture:U.FRONTAL},{"Content-Type":"multipart/form-data"})})),d=await Promise.all(l);await J();let{video:o}=e;o&&Array.isArray(o)&&o.length>0&&await s({file:o[0],label:"video"},{"Content-Type":"multipart/form-data"});let u={...e,images:d.map((a,t)=>({id:a?.data?.image_id,blob:e?.frontalFaces?.[t]})),frontalFaces:d.map((a,t)=>({id:a?.data?.image_id,blob:e?.frontalFaces?.[t]})),capturedFrames:e?.capturedFrames};if(i(t,"face_sanity")){let{result:e,message:a}=await c({image:{id:d?.[d.length-1]?.data?.image_id}});if("good"!==i(e,"data.portrait_sanity.verdict","")||i(e,"errors"))return{...u,verifyFacePortraitResult:{...i(e,"data",i(e,"error",{})),message:i(a,"error")}};u.verifyFacePortraitResult={...e?.data,message:i(a,"success")}}if(i(t,"face_liveness")){let{result:e,message:a}=await n({images:d.map(e=>({id:e?.data?.image_id})),videos:q}),t=i(e,"data.is_live");u.verifyFaceLivenessResult={...i(e,"data",i(e,"error",{})),message:t?i(a,"success"):i(a,"error")}}return u}async function Q({stepResult:e,sdkAdapter:a,services:t}){let{uploadImage:r,uploadFiles:s,verifyFaceLiveness:n,requestVerifyPortrait:c}=a,l=i(e,"frontalFaces",[]).map(e=>r({file:e,label:"portrait",metadata:JSON.stringify({gesture:U.FRONTAL},{"Content-Type":"multipart/form-data"})})),d=await Promise.all(l);await J();let{video:o}=e;o&&Array.isArray(o)&&o.length>0&&await s({file:o[0],label:"video"},{"Content-Type":"multipart/form-data"});let u={...e,frontalFaces:d.map((a,t)=>({id:a?.data?.image_id,blob:e?.frontalFaces?.[t]})),capturedFrames:e?.capturedFrames};if(i(t,"face_sanity")){let{result:e,message:a}=await c({image:{id:d?.[d.length-1]?.data?.image_id}});if("good"!==i(e,"data.portrait_sanity.verdict","")||i(e,"errors"))return{...u,verifyFacePortraitResult:{...i(e,"data",i(e,"error",{})),message:i(a,"error")}};u.verifyFacePortraitResult={...e?.data,message:i(a,"success")}}if(i(t,"face_liveness")){let{result:e,message:a}=await n({images:d.map(e=>({id:e?.data?.image_id})),videos:q}),t=i(e,"data.is_live");u.verifyFaceLivenessResult={...i(e,"data",i(e,"error",{})),message:t?i(a,"success"):i(a,"error")}}return u}async function X({mode:e,stepResult:a,sdkAdapter:t,services:r}){return e===V.ACTIVE?z({stepResult:a,sdkAdapter:t,services:r}):e===V.PASSIVE?$({stepResult:a,sdkAdapter:t,services:r}):e.includes("flash")?Q({stepResult:a,sdkAdapter:t,services:r}):void 0}async function Z(e){let{livenessMode:a,sdkAdapter:t,onError:r,services:s,hasBackCardStep:n,hasIDFlow:l,...d}=e;if(!(t instanceof c))return d;let{compareFaces:o,searchFaces:u,indexFaces:f}=t,p=i(e,"frontCard.apiResult.frontCardId",null),m=null,g=i(e,"faceLiveness.frontalFaces",[]);m=g[g.length-1]?.id;let y=p&&m,_={...d};if(i(s,"compare_faces")&&l&&y){let{result:e,message:a}=await o({image1:{id:p},image2:{id:m}});if(N(i(e,"data")))return{..._,step:T,compareFaces:{...i(e,"data",i(e,"error",{})),message:i(a,"error")}};_={..._,compareFaces:{...e?.data,message:i(a,"success")}}}if(i(s,"search_face")){let{result:e,message:a}=await u({image:{id:m}}),t=i(e,"data.faces",null);if(Array.isArray(t)&&t.length)return{..._,searchFaces:{...i(e,"data",i(e,"error",{})),message:i(a,"error")}};_={..._,searchFaces:{...e?.data,message:i(a,"success")}}}if(i(s,"index_face")){let a=M(e),{result:t}=await f({image:{id:m,...a?{metadata:JSON.stringify({id:M(e)})}:{}}});_={..._,indexFaces:t?.data}}return _}let ee=d.div`
|
|
1
|
+
import{P as e,c as a,r as t,j as r,o as s,e as n,b as i,h as c,s as l,i as d}from"./chunk-68e90ba2.js";import{P as o,O as u}from"./chunk-5d5d5df1.js";import{u as f,a as p,S as m,R as g,U as y}from"./chunk-d02bd3cc.js";import{d as _,m as C}from"./chunk-bcf5eed2.js";import{L as h}from"./chunk-c04f48e4.js";import{t as R}from"./chunk-9038aebd.js";let v=e=>{let{clientSettings:i,onError:c,onStepDone:l,logCredentials:d,uiOnlyComponent:o,detectIdCard:u,outputEncryptionSettings:g,steps:y,customTheme:C}=e,{settings:h}=f({clientSettings:i}),{themeVersion:R}=a.useSDKSettings(),v=t.useCallback(async e=>await l({...e,restartSession:I?.handleRestartSession}),[l,I?.handleRestartSession]),I=p({settings:h,onError:c,detectIdCard:u,outputEncryptionSettings:g,steps:y,onStepDone:v});return r.jsx(s,{theme:{...C,themeVersion:R,defaultThemes:_},children:r.jsx(n.SDKTrackingProvider,{value:{tracking:{...d}},children:r.jsx(o,{...e,onStepDone:v,settings:h,scannerTypeCons:m,...I})})})};v.propTypes={clientSettings:e.shape({}),onError:e.func,onStepDone:e.func,logCredentials:e.shape({}),readIDCardUIOnlyComponent:e.func,uiOnlyComponent:e.func,steps:e.arrayOf(e.shape({})),detectIdCard:e.func,outputEncryptionSettings:e.shape({}),customTheme:e.shape({})},v.defaultProps={clientSettings:void 0,onError:()=>{},onStepDone:()=>{},logCredentials:{enable:!0},readIDCardUIOnlyComponent:g,uiOnlyComponent:y,steps:void 0,detectIdCard:void 0,outputEncryptionSettings:null,customTheme:{}};let I={id_card_sanity:3,portrait_sanity:3,face_liveness_with_card_tampering_ocr:3,compare_faces:3},F={card_sanity:!0,card_tampering:!0,card_ocr:!0,face_sanity:!0,face_liveness:!0,compare_faces:!0,search_face:!0,index_face:!0},T="ID_CARD",A="FACE_LIVENESS",k="IDLE",S={},b={REACH_RETRY_LIMIT:{en:"You have reached the retry limit. Please try again later.",vi:"Bạn đ\xe3 vượt qu\xe1 số lần thử. Vui l\xf2ng thử lại sau."},FAIL_STEP:{en:"Please try again at step: <%= step %>.",vi:"Vui l\xf2ng thử lại ở bước: <%= step %>."},FAIL_FRONT_CARD_SANITY:{en:"The front side of your ID card failed sanity check.",vi:"H\xecnh ảnh Mặt trước của GTTT kh\xf4ng đạt chất lượng y\xeau cầu."},FAIL_FRONT_CARD_TAMPERING:{en:"The front side of your ID card failed tampering check.",vi:"H\xecnh ảnh Mặt trước của GTTT kh\xf4ng hợp lệ."},FAIL_FRONT_CARD_OCR:{en:"Cannot read information on the front side of your ID card.",vi:"Kh\xf4ng đọc được th\xf4ng tin từ h\xecnh ảnh Mặt trước của GTTT."},FAIL_BACK_CARD_SANITY:{en:"The back side of your ID card failed sanity check.",vi:"H\xecnh ảnh Mặt sau của GTTT kh\xf4ng đạt chất lượng y\xeau cầu."},FAIL_BACK_CARD_TAMPERING:{en:"The back side of your ID card failed tampering check.",vi:"H\xecnh ảnh Mặt sau của GTTT kh\xf4ng hợp lệ."},FAIL_BACK_CARD_OCR:{en:"Cannot read information on the back side of your ID card.",vi:"Kh\xf4ng đọc được th\xf4ng tin từ h\xecnh ảnh Mặt sau của GTTT."},FAIL_FACE_SANITY:{en:"Selfie step failed sanity check.",vi:"H\xecnh ảnh khu\xf4n mặt kh\xf4ng đạt chất lượng y\xeau cầu."},FAIL_FACE_LIVENESS:{en:"Selfie step failed liveness check.",vi:"H\xecnh ảnh khu\xf4n mặt kh\xf4ng hợp lệ."},FAIL_COMPARE_FACE:{en:"Failed compare faces between ID photo and selfie.",vi:"H\xecnh ảnh khu\xf4n mặt tr\xean GTTT kh\xf4ng giống h\xecnh chụp ch\xe2n dung"},RETRY_BUTTON:{en:"Retry",vi:"Thử lại"},STOP_BUTTON:{en:"Stop",vi:"Dừng"},FRONT_CARD:{en:"Front Card",vi:"Mặt trước"},BACK_CARD:{en:"Back Card",vi:"Mặt sau"},ID_CARD:{en:"ID Card",vi:"Thẻ ID"},FACE_LIVENESS:{en:"Face Liveness",vi:"Nhận diện khu\xf4n mặt"}};function L(e){var a;if("object"!=typeof(a=e)||"function"!=typeof a.then)return"pending";let t={};return Promise.race([e,t]).then(e=>e===t?"pending":"fulfilled",()=>"rejected")}let w=(e,a)=>{if(!i(a,"face_liveness"))return!1;let t=i(e,"verifyFaceLivenessResult.is_live",!1),r=i(e,"verifyFaceLivenessResult.status","");return!t||"success"!==r},E=(e,a)=>{if(!i(a,"card_sanity"))return!1;let t=i(e,"apiResult.sanityResult.status",""),r=i(e,"apiResult.sanityResult.card_sanity.verdict","");return"success"!==t||"good"!==r},D=e=>!!i(e,"errors")||"success"!==i(e,"data.status","")||"good"!==i(e,"data.card_tampering.verdict",""),O=e=>!!i(e,"errors")||"success"!==i(e,"data.status",""),N=e=>{let a=i(e,"compare_faces",[]);return a[0]?.result!=="matched"||1!==a.filter(e=>e?.result==="matched").length||e.errors},P=async(e,a,t)=>{if(i(a,"card_tampering")){let a=i(e.current,"frontCard.apiResult.detectIDTamperingBackground");if("fulfilled"===await L(a)){let{result:a,message:t}=await i(e.current,"frontCard.apiResult.detectIDTamperingBackground"),r=D(a),s={frontCard:{apiResult:{tamperingInfo:{...a?.data,message:r?i(t,"error"):i(t,"success")}}}};if(C(e.current,s),r)return!0}if(t){let a=i(e.current,"backCard.apiResult.detectIDTamperingBackground");if("fulfilled"===await L(a)){let{result:a,message:t}=await i(e.current,"backCard.apiResult.detectIDTamperingBackground"),r=D(a),s={backCard:{apiResult:{tamperingInfo:{...a?.data,message:r?i(t,"error"):i(t,"success")}}}};if(C(e.current,s),r)return!0}}}if(i(a,"card_ocr")){let a=i(e.current,"frontCard.apiResult.readIDCardBackground");if("fulfilled"===await L(a)){let{result:a,message:t}=await i(e.current,"frontCard.apiResult.readIDCardBackground"),r=O(a),s={frontCard:{apiResult:{cardInfo:{...a?.data,message:r?i(t,"error"):i(t,"success")}}}};if(C(e.current,s),r)return!0}if(t){let a=i(e.current,"backCard.apiResult.readIDCardBackground");if("fulfilled"===await L(a)){let{result:a,message:t}=await i(e.current,"backCard.apiResult.readIDCardBackground"),r=O(a),s={backCard:{apiResult:{cardInfo:{...a?.data,message:r?i(t,"error"):i(t,"success")}}}};if(C(e.current,s),r)return!0}}}return!1},x=async(e,a,t)=>{let r=!1;if(i(a,"card_tampering")){let{result:a,message:s}=await i(e.current,"frontCard.apiResult.detectIDTamperingBackground"),n=D(a);r=r||n;let c={frontCard:{apiResult:{tamperingInfo:{...a?.data,message:n?i(s,"error"):i(s,"success")}}}};if(C(e.current,c),t){let{result:a}=await i(e.current,"backCard.apiResult.detectIDTamperingBackground"),t=D(a);r=r||t;let n={backCard:{apiResult:{tamperingInfo:{...a?.data,message:t?i(s,"error"):i(s,"success")}}}};C(e.current,n)}}if(i(a,"card_ocr")){let{result:a,message:s}=await i(e.current,"frontCard.apiResult.readIDCardBackground"),n=O(a);r=r||n;let c={frontCard:{apiResult:{cardInfo:{...a?.data,message:n?i(s,"error"):i(s,"success")}}}};if(C(e.current,c),t){let{result:a}=await i(e.current,"backCard.apiResult.readIDCardBackground"),t=O(a);r=r||t;let n={backCard:{apiResult:{cardInfo:{...a?.data,message:t?i(s,"error"):i(s,"success")}}}};C(e.current,n)}}return r},j=(e,a)=>{for(let t in e)a.includes(t)?delete e[t]:"object"==typeof e[t]&&j(e[t],a);return e},B=e=>j(e.current,["message","step","restartSession","detectIDTamperingBackground","readIDCardBackground"]),K=(e,a,t)=>{let r=[];if(i(e,"frontCard.apiResult.sanityResult")&&"good"!==i(e,"frontCard.apiResult.sanityResult.card_sanity.verdict","")){let a=i(e,"frontCard.apiResult.sanityResult.message",null);a?.[t]?r.push(a[t]):r.push(b.FAIL_FRONT_CARD_SANITY[t])}if(i(e,"frontCard.apiResult.tamperingInfo")&&"good"!==i(e,"frontCard.apiResult.tamperingInfo.card_tampering.verdict","")){let a=i(e,"frontCard.apiResult.tamperingInfo.message",null);a?.[t]?r.push(a[t]):r.push(b.FAIL_FRONT_CARD_TAMPERING[t])}if(i(e,"frontCard.apiResult.cardInfo")&&"success"!==i(e,"frontCard.apiResult.cardInfo.status","")){let a=i(e,"frontCard.apiResult.cardInfo.message",null);a?.[t]?r.push(a[t]):r.push(b.FAIL_FRONT_CARD_OCR[t])}if(i(e,"backCard.apiResult.sanityResult")&&"good"!==i(e,"backCard.apiResult.sanityResult.card_sanity.verdict","")){let a=i(e,"backCard.apiResult.sanityResult.message",null);a?.[t]?r.push(a[t]):r.push(b.FAIL_BACK_CARD_SANITY[t])}if(i(e,"backCard.apiResult.tamperingInfo")&&"good"!==i(e,"backCard.apiResult.tamperingInfo.card_tampering.verdict","")){let a=i(e,"backCard.apiResult.tamperingInfo.message",null);a?.[t]?r.push(a[t]):r.push(b.FAIL_BACK_CARD_TAMPERING[t])}if(i(e,"backCard.apiResult.cardInfo")&&"success"!==i(e,"backCard.apiResult.cardInfo.status","")){let a=i(e,"backCard.apiResult.cardInfo.message",null);a?.[t]?r.push(a[t]):r.push(b.FAIL_BACK_CARD_OCR[t])}if(i(e,"faceLiveness.verifyFacePortraitResult")&&"good"!==i(e,"faceLiveness.verifyFacePortraitResult.portrait_sanity.verdict","")){let a=i(e,"faceLiveness.verifyFacePortraitResult.message",null);a?.[t]?r.push(a[t]):r.push(b.FAIL_FACE_SANITY[t])}if(i(e,"faceLiveness.verifyFaceLivenessResult")&&!i(e,"faceLiveness.verifyFaceLivenessResult.is_live",!1)){let a=i(e,"faceLiveness.verifyFaceLivenessResult.message",null);a?.[t]?r.push(a[t]):r.push(b.FAIL_FACE_LIVENESS[t])}if(i(e,"compareFaces",null)&&N(i(e,"compareFaces"))){let a=i(e,"compareFaces.message",null);a?.[t]?r.push(a[t]):r.push(b.FAIL_COMPARE_FACE[t])}return{retryAt:a,results:r}},M=e=>{let a=i(e,"frontCard.apiResult.cardInfo.card_information",[]).find(e=>"id"===e.field);return i(a,"value","")},{Errors:Y,IDCardSide:G,FaceDirection:U,Mode:V}=l,q=[],H=()=>{q=[]},J=()=>new Promise(e=>{let a=setInterval(()=>{q.every(e=>e.id)&&(e(),clearInterval(a))},200)});async function W({hasBackCardStep:e,stepResult:a,frontCardId:t,qrImageId:r,sdkAdapter:s,onError:n,refEkycResult:l,handleFailCardTamperingOCRBackground:d,services:o}){let u,f,p,m;if(!(s instanceof c))return a;let{cardSide:g,cardType:y,recordedVideos:_,qrScannedResult:C,image:h}=a;if(g===G.BACK&&!t)return n(Y.missing_front_id_card),!1;let{uploadImage:R,uploadFiles:v,requestVerifyIDCard:I,detectIDTampering:F,readIDCard:T}=s,A=[R({file:h?.blob,label:`id_card.${y}.${g}`})];C&&C.image&&C.result&&A.push(R({file:C?.image?.blob,label:"qr_code",rawString:C?.result}));let[k,S]=await Promise.all(A);if(k.errors)return n({...Y.upload_error,details:k.reason}),!1;let b=k?.data?.image_id,L=S?.data?.image_data||r;g===G.FRONT?u=b:(u=t,f=b);let w={qrImageId:L,frontCardId:u,backCardId:f};if(i(o,"card_sanity")){let{result:e,message:t}=await I({card_type:y,image1:{id:g===G.FRONT?u:f}});if("good"!==i(e,"data.card_sanity.verdict","")||e.errors)return{...a,apiResult:{...w,sanityResult:{...e?.data,message:i(t,"error")}}};w.sanityResult={...e?.data,message:i(t,"success")}}if(g===G.BACK&&"function"==typeof d&&await P(l,o,e))return d(),{...a,apiResult:w};if(i(o,"card_tampering")){let e={card_type:y,image:{id:u},...g===G.FRONT?{image2:void 0,level:"1"}:{image2:{id:f},level:"concurrent"}};if(L&&(e.qr1_images=[{id:L}]),_&&Array.isArray(_)&&_.length>0){let a=_.filter(e=>null!==e.id),t=_.filter(e=>null===e.id&&e.frames.length>0),r=await Promise.all(t.map(e=>v({frames:e.frames})));e.videos=[...a.map(e=>({id:e.id})),...r.map(e=>({id:e.data.file_id}))]}p=F(e)}if(i(o,"card_ocr")){let e={card_type:y,image1:g===G.FRONT?{id:u}:{id:f}};L&&(e.qr1_images={id:L}),m=T(e)}return{...a,apiResult:{...w,detectIDTamperingBackground:p,readIDCardBackground:m}}}async function z({stepResult:e,sdkAdapter:a,services:t}){let{uploadImage:r,uploadFiles:s,verifyFaceLiveness:n,requestVerifyPortrait:c}=a,l=i(e,"frontalFaces",[]).map(e=>r({file:e,label:"portrait",metadata:JSON.stringify({gesture:U.FRONTAL},{"Content-Type":"multipart/form-data"})})),d=i(e,"steps",[]).map(e=>r({file:e?.image?.blob,label:"portrait",metadata:JSON.stringify({gesture:e?.name})},{"Content-Type":"multipart/form-data"})),o=await Promise.all([...l,...d]),u=o.slice(0,l.length),f=o.slice(-d.length);await J();let{video:p}=e;p&&await s({file:p,label:"video"},{"Content-Type":"multipart/form-data"});let m={...e,frontalFaces:u.map((a,t)=>({id:a?.data?.image_id,blob:e?.frontalFaces?.[t]})),steps:f.map((a,t)=>({image:{id:a?.data?.image_id,blob:e?.steps?.[t]?.image?.blob},name:e?.steps?.[t]?.name})),capturedFrames:e?.capturedFrames};if(i(t,"face_sanity")){let{result:e,message:a}=await c({image:{id:u?.[u.length-1]?.data?.image_id}});if("good"!==i(e,"data.portrait_sanity.verdict","")||i(e,"errors"))return{...m,verifyFacePortraitResult:{...i(e,"data",i(e,"error",{})),message:i(a,"error")}};m.verifyFacePortraitResult={...e?.data,message:i(a,"success")}}if(i(t,"face_liveness")){let{result:a,message:t}=await n({images:u.map(e=>({id:e?.data?.image_id})),gesture_images:f.map((a,t)=>({gesture:e?.steps?.[t]?.name,images:[{id:a?.data?.image_id}]})),videos:q}),r=i(a,"data.is_live");m.verifyFaceLivenessResult={...i(a,"data",i(a,"error",{})),message:r?i(t,"success"):i(t,"error")}}return m}async function $({stepResult:e,sdkAdapter:a,services:t}){let{uploadImage:r,uploadFiles:s,verifyFaceLiveness:n,requestVerifyPortrait:c}=a,l=i(e,"frontalFaces",[]).map(e=>r({file:e,label:"portrait",metadata:JSON.stringify({gesture:U.FRONTAL},{"Content-Type":"multipart/form-data"})})),d=await Promise.all(l);await J();let{video:o}=e;o&&Array.isArray(o)&&o.length>0&&await s({file:o[0],label:"video"},{"Content-Type":"multipart/form-data"});let u={...e,images:d.map((a,t)=>({id:a?.data?.image_id,blob:e?.frontalFaces?.[t]})),frontalFaces:d.map((a,t)=>({id:a?.data?.image_id,blob:e?.frontalFaces?.[t]})),capturedFrames:e?.capturedFrames};if(i(t,"face_sanity")){let{result:e,message:a}=await c({image:{id:d?.[d.length-1]?.data?.image_id}});if("good"!==i(e,"data.portrait_sanity.verdict","")||i(e,"errors"))return{...u,verifyFacePortraitResult:{...i(e,"data",i(e,"error",{})),message:i(a,"error")}};u.verifyFacePortraitResult={...e?.data,message:i(a,"success")}}if(i(t,"face_liveness")){let{result:e,message:a}=await n({images:d.map(e=>({id:e?.data?.image_id})),videos:q}),t=i(e,"data.is_live");u.verifyFaceLivenessResult={...i(e,"data",i(e,"error",{})),message:t?i(a,"success"):i(a,"error")}}return u}async function Q({stepResult:e,sdkAdapter:a,services:t}){let{uploadImage:r,uploadFiles:s,verifyFaceLiveness:n,requestVerifyPortrait:c}=a,l=i(e,"frontalFaces",[]).map(e=>r({file:e,label:"portrait",metadata:JSON.stringify({gesture:U.FRONTAL},{"Content-Type":"multipart/form-data"})})),d=await Promise.all(l);await J();let{video:o}=e;o&&Array.isArray(o)&&o.length>0&&await s({file:o[0],label:"video"},{"Content-Type":"multipart/form-data"});let u={...e,frontalFaces:d.map((a,t)=>({id:a?.data?.image_id,blob:e?.frontalFaces?.[t]})),capturedFrames:e?.capturedFrames};if(i(t,"face_sanity")){let{result:e,message:a}=await c({image:{id:d?.[d.length-1]?.data?.image_id}});if("good"!==i(e,"data.portrait_sanity.verdict","")||i(e,"errors"))return{...u,verifyFacePortraitResult:{...i(e,"data",i(e,"error",{})),message:i(a,"error")}};u.verifyFacePortraitResult={...e?.data,message:i(a,"success")}}if(i(t,"face_liveness")){let{result:e,message:a}=await n({images:d.map(e=>({id:e?.data?.image_id})),videos:q}),t=i(e,"data.is_live");u.verifyFaceLivenessResult={...i(e,"data",i(e,"error",{})),message:t?i(a,"success"):i(a,"error")}}return u}async function X({mode:e,stepResult:a,sdkAdapter:t,services:r}){return e===V.ACTIVE?z({stepResult:a,sdkAdapter:t,services:r}):e===V.PASSIVE?$({stepResult:a,sdkAdapter:t,services:r}):e.includes("flash")?Q({stepResult:a,sdkAdapter:t,services:r}):void 0}async function Z(e){let{livenessMode:a,sdkAdapter:t,onError:r,services:s,hasBackCardStep:n,hasIDFlow:l,...d}=e;if(!(t instanceof c))return d;let{compareFaces:o,searchFaces:u,indexFaces:f}=t,p=i(e,"frontCard.apiResult.frontCardId",null),m=null,g=i(e,"faceLiveness.frontalFaces",[]);m=g[g.length-1]?.id;let y=p&&m,_={...d};if(i(s,"compare_faces")&&l&&y){let{result:e,message:a}=await o({image1:{id:p},image2:{id:m}});if(N(i(e,"data")))return{..._,step:T,compareFaces:{...i(e,"data",i(e,"error",{})),message:i(a,"error")}};_={..._,compareFaces:{...e?.data,message:i(a,"success")}}}if(i(s,"search_face")){let{result:e,message:a}=await u({image:{id:m}}),t=i(e,"data.faces",null);if(Array.isArray(t)&&t.length)return{..._,searchFaces:{...i(e,"data",i(e,"error",{})),message:i(a,"error")}};_={..._,searchFaces:{...e?.data,message:i(a,"success")}}}if(i(s,"index_face")){let a=M(e),{result:t}=await f({image:{id:m,...a?{metadata:JSON.stringify({id:M(e)})}:{}}});_={..._,indexFaces:t?.data}}return _}let ee=d.div`
|
|
2
2
|
display: flex;
|
|
3
3
|
justify-content: space-between;
|
|
4
4
|
align-items: center;
|