@aws-amplify/ui-react-liveness 2.0.7 → 2.0.8
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/dist/esm/components/FaceLivenessDetector/FaceLivenessDetectorCore.mjs +1 -1
- package/dist/esm/components/FaceLivenessDetector/LivenessCheck/LivenessCameraModule.mjs +1 -1
- package/dist/esm/components/FaceLivenessDetector/LivenessCheck/LivenessCheck.mjs +1 -1
- package/dist/esm/components/FaceLivenessDetector/service/types/error.mjs +1 -1
- package/dist/esm/components/FaceLivenessDetector/service/utils/blazefaceFaceDetection.mjs +1 -1
- package/dist/esm/components/FaceLivenessDetector/service/utils/liveness.mjs +1 -1
- package/dist/esm/components/FaceLivenessDetector/service/utils/streamProvider.mjs +1 -1
- package/dist/esm/components/FaceLivenessDetector/shared/DefaultStartScreenComponents.mjs +1 -1
- package/dist/esm/components/FaceLivenessDetector/shared/FaceLivenessErrorModal.mjs +1 -1
- package/dist/esm/components/FaceLivenessDetector/shared/Hint.mjs +1 -1
- package/dist/esm/version.mjs +1 -1
- package/dist/index.js +1 -1
- package/dist/styles.css +48 -25
- package/dist/types/components/FaceLivenessDetector/index.d.ts +1 -1
- package/dist/types/components/FaceLivenessDetector/service/types/error.d.ts +12 -11
- package/dist/types/components/FaceLivenessDetector/service/types/liveness.d.ts +2 -2
- package/dist/types/components/FaceLivenessDetector/service/types/machine.d.ts +2 -2
- package/dist/types/components/FaceLivenessDetector/service/utils/liveness.d.ts +13 -3
- package/dist/types/components/FaceLivenessDetector/service/utils/streamProvider.d.ts +1 -2
- package/dist/types/components/FaceLivenessDetector/shared/FaceLivenessErrorModal.d.ts +2 -2
- package/dist/types/components/FaceLivenessDetector/shared/Hint.d.ts +1 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/types/version.d.ts +1 -1
- package/package.json +6 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as e from"react";import{useInterpret as t,useActor as s}from"@xstate/react";import{livenessMachine as r}from"./service/machine/index.mjs";import"./service/types/liveness.mjs";import"
|
|
1
|
+
import*as e from"react";import{useInterpret as t,useActor as s}from"@xstate/react";import{livenessMachine as r}from"./service/machine/index.mjs";import"./service/types/liveness.mjs";import"tslib";import"@tensorflow/tfjs-core";import"@tensorflow-models/blazeface";import"@tensorflow/tfjs-backend-wasm";import"@tensorflow/tfjs-backend-cpu";import"@aws-amplify/core";import"./service/utils/streamProvider.mjs";import"./service/utils/freshnessColorDisplay.mjs";import{View as o,Flex as i}from"@aws-amplify/ui-react";import{FaceLivenessDetectorProvider as n}from"./providers/FaceLivenessDetectorProvider.mjs";import{StartLiveness as m}from"./StartLiveness/StartLiveness.mjs";import{LivenessCheck as a}from"./LivenessCheck/LivenessCheck.mjs";import{getDisplayText as c}from"./utils/getDisplayText.mjs";const l="liveness-detector";function p(p){const{disableInstructionScreen:f=!1,components:u,config:v,displayText:y}=p,x=e.useRef(null),{hintDisplayText:d,cameraDisplayText:D,instructionDisplayText:j,streamDisplayText:T,errorDisplayText:b}=c(y),h=t(r,{devTools:"development"===process.env.NODE_ENV,context:{componentProps:Object.assign(Object.assign({},p),{config:null!=v?v:{}})}}),[E,w]=s(h),L=E.matches("start")||E.matches("userCancel"),g=e.useCallback((()=>{w({type:"BEGIN"})}),[w]);return e.useLayoutEffect((()=>{f&&L&&g()}),[g,f,L]),e.createElement(o,{className:l,testId:l},e.createElement(n,{componentProps:p,service:h},e.createElement(i,{direction:"column",ref:x},L?e.createElement(m,{beginLivenessCheck:g,components:u,instructionDisplayText:j}):e.createElement(a,{hintDisplayText:d,cameraDisplayText:D,streamDisplayText:T,errorDisplayText:b,components:u}))))}export{p as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import e,{useRef as t,useState as r}from"react";import a from"classnames";import{Loader as s,Flex as o,View as i}from"@aws-amplify/ui-react";import"../service/machine/index.mjs";import{FaceMatchState as c}from"../service/types/liveness.mjs";import"
|
|
1
|
+
import e,{useRef as t,useState as r}from"react";import a from"classnames";import{Loader as s,Flex as o,View as i}from"@aws-amplify/ui-react";import"../service/machine/index.mjs";import{FaceMatchState as c}from"../service/types/liveness.mjs";import"tslib";import"@tensorflow/tfjs-core";import"@tensorflow-models/blazeface";import"@tensorflow/tfjs-backend-wasm";import"@tensorflow/tfjs-backend-cpu";import"@aws-amplify/core";import"../service/utils/streamProvider.mjs";import"../service/utils/freshnessColorDisplay.mjs";import{useLivenessActor as n}from"../hooks/useLivenessActor.mjs";import{useLivenessSelector as m,createLivenessSelector as l}from"../hooks/useLivenessSelector.mjs";import{useMediaStreamInVideo as d}from"../hooks/useMediaStreamInVideo.mjs";import{CancelButton as h}from"../shared/CancelButton.mjs";import{selectErrorState as p,Hint as f}from"../shared/Hint.mjs";import{MatchIndicator as v}from"../shared/MatchIndicator.mjs";import{Overlay as u}from"../shared/Overlay.mjs";import{RecordingIcon as E}from"../shared/RecordingIcon.mjs";import{LivenessClassNames as y}from"../types/classNames.mjs";import{renderErrorModal as C,FaceLivenessErrorModal as j}from"../shared/FaceLivenessErrorModal.mjs";const g=l((e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoMediaStream})),M=l((e=>e.context.faceMatchAssociatedParams.faceMatchPercentage)),N=l((e=>e.context.faceMatchAssociatedParams.faceMatchState)),A=e.createElement(s,{size:"large",className:y.Loader,"data-testid":"centered-loader"}),I=e.memo(v),T=s=>{const{isMobileScreen:l,isRecordingStopped:v,streamDisplayText:T,hintDisplayText:D,errorDisplayText:w,components:x,testId:b}=s,{cancelLivenessCheckText:S,recordingIndicatorText:L}=T,{ErrorView:O=j}=null!=x?x:{},[k,F]=n(),R=m(g),P=m(M),_=m(N),H=m(p),V=[c.TOO_FAR,c.CANT_IDENTIFY,c.FACE_IDENTIFIED,c.MATCHED],{videoRef:z,videoWidth:W,videoHeight:$}=d(R),B=t(null),X=t(null),[Y,q]=r(!1),G=k.matches("cameraCheck"),J=k.matches("recording"),K=k.matches("checkSucceeded"),Q=k.matches({recording:"flashFreshnessColors"}),[U,Z]=r(W),[ee,te]=r($),[re,ae]=r((()=>W&&$?W/$:0));e.useLayoutEffect((()=>{Y&&F({type:"SET_DOM_AND_CAMERA_DETAILS",data:{videoEl:z.current,canvasEl:B.current,freshnessColorEl:X.current,isMobile:l}}),z.current&&(Z(z.current.videoWidth),te(z.current.videoHeight),ae(z.current.videoWidth/z.current.videoHeight))}),[F,z,Y,l]);return G?e.createElement(o,{height:$,width:"100%",position:"relative"},A):e.createElement(o,{className:a(y.CameraModule,l&&`${y.CameraModule}--mobile`),"data-testid":b},!Y&&A,e.createElement(i,{as:"canvas",ref:X,className:y.FreshnessCanvas,hidden:!0}),e.createElement(i,{className:y.VideoAnchor,style:{aspectRatio:`${re}`}},e.createElement("video",{ref:z,muted:!0,autoPlay:!0,playsInline:!0,style:{transform:"scaleX(-1)"},width:U,height:ee,onCanPlay:()=>{q(!0)},"data-testid":"video",className:y.Video}),e.createElement(o,{className:a(y.OvalCanvas,l&&`${y.OvalCanvas}--mobile`,v&&y.FadeOut)},e.createElement(i,{as:"canvas",width:"100%",height:"100%",ref:B})),J&&e.createElement(i,{className:y.RecordingIconContainer},e.createElement(E,null,L)),!K&&e.createElement(i,{className:y.CancelContainer},e.createElement(h,{ariaLabel:S})),e.createElement(u,{anchorOrigin:{horizontal:"center",vertical:J&&!Q?"start":"space-between"},className:y.InstructionOverlay},e.createElement(f,{hintDisplayText:D}),H&&e.createElement(O,{onRetry:()=>{F({type:"CANCEL"})}},C({errorState:H,overrideErrorDisplayText:w})),J&&!Q&&V.includes(_)?e.createElement(I,{percentage:Math.ceil(P)}):null)))};export{T as LivenessCameraModule,M as selectFaceMatchPercentage,N as selectFaceMatchState,g as selectVideoStream};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as e from"react";import{Flex as t,Text as r,Button as s,View as i}from"@aws-amplify/ui-react";import"../service/machine/index.mjs";import"../service/types/liveness.mjs";import{LivenessErrorState as o}from"../service/types/error.mjs";import"tslib";import"@tensorflow/tfjs-core";import"@tensorflow-models/blazeface";import"@tensorflow/tfjs-backend-wasm";import"@tensorflow/tfjs-backend-cpu";import"@aws-amplify/core";import"../service/utils/
|
|
1
|
+
import*as e from"react";import{Flex as t,Text as r,Button as s,View as i}from"@aws-amplify/ui-react";import"../service/machine/index.mjs";import"../service/types/liveness.mjs";import{LivenessErrorState as o}from"../service/types/error.mjs";import"tslib";import"@tensorflow/tfjs-core";import"@tensorflow-models/blazeface";import"@tensorflow/tfjs-backend-wasm";import"@tensorflow/tfjs-backend-cpu";import"@aws-amplify/core";import"../service/utils/streamProvider.mjs";import"../service/utils/freshnessColorDisplay.mjs";import{LivenessCameraModule as a}from"./LivenessCameraModule.mjs";import{useLivenessActor as n}from"../hooks/useLivenessActor.mjs";import{useLivenessSelector as m,createLivenessSelector as c}from"../hooks/useLivenessSelector.mjs";import"@aws-amplify/ui";import{isMobileScreen as p,getLandscapeMediaQuery as l}from"../utils/device.mjs";import{CancelButton as d}from"../shared/CancelButton.mjs";import{defaultErrorDisplayText as f}from"../displayText.mjs";import{LandscapeErrorModal as u}from"../shared/LandscapeErrorModal.mjs";import{selectErrorState as E}from"../shared/Hint.mjs";import"../types/classNames.mjs";const y="liveness-detector-check",g=c((e=>e.context.isRecordingStopped)),h=({hintDisplayText:c,cameraDisplayText:h,streamDisplayText:x,errorDisplayText:R,components:T})=>{const[j,A]=n(),C=m(E),v=m(g),M=j.matches("permissionDenied"),b=p(),L=()=>{A({type:"RETRY_CAMERA_CHECK"})},{cameraMinSpecificationsHeadingText:k,cameraMinSpecificationsMessageText:D,cameraNotFoundHeadingText:w,cameraNotFoundMessageText:_,retryCameraPermissionsText:N}=h,{cancelLivenessCheckText:S}=x;e.useLayoutEffect((()=>{if(b){const e=e=>{e&&A({type:"MOBILE_LANDSCAPE_WARNING"})},t=l();return e(t.matches),t.addEventListener("change",(t=>{e(t.matches)})),()=>{t.removeEventListener("change",(t=>e(t.matches)))}}}),[b,A]);return e.createElement(t,{direction:"column",position:"relative",testId:y,className:y},(()=>{if(C===o.MOBILE_LANDSCAPE_ERROR){const r=Object.assign(Object.assign({},f),R),{landscapeHeaderText:s,portraitMessageText:i,landscapeMessageText:o,tryAgainText:a}=r;return e.createElement(t,{backgroundColor:"background.primary",direction:"column",textAlign:"center",alignItems:"center",justifyContent:"center",position:"absolute",width:"100%"},e.createElement(u,{header:s,portraitMessage:i,landscapeMessage:o,tryAgainText:a,onRetry:()=>{A({type:"CANCEL"})}}))}return M?e.createElement(t,{backgroundColor:"background.primary",direction:"column",textAlign:"center",alignItems:"center",justifyContent:"center",width:"100%",height:480},e.createElement(r,{fontSize:"large",fontWeight:"bold"},C===o.CAMERA_FRAMERATE_ERROR?k:w),e.createElement(r,{maxWidth:300},C===o.CAMERA_FRAMERATE_ERROR?D:_),e.createElement(s,{variation:"primary",type:"button",onClick:L},N),e.createElement(i,{position:"absolute",top:"medium",right:"medium"},e.createElement(d,{ariaLabel:S}))):e.createElement(a,{isMobileScreen:b,isRecordingStopped:v,streamDisplayText:x,hintDisplayText:c,errorDisplayText:R,components:T})})())};export{h as LivenessCheck};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
const R={TIMEOUT:"TIMEOUT",RUNTIME_ERROR:"RUNTIME_ERROR",FRESHNESS_TIMEOUT:"FRESHNESS_TIMEOUT",SERVER_ERROR:"SERVER_ERROR",CAMERA_FRAMERATE_ERROR:"CAMERA_FRAMERATE_ERROR",CAMERA_ACCESS_ERROR:"CAMERA_ACCESS_ERROR",FACE_DISTANCE_ERROR:"FACE_DISTANCE_ERROR",MOBILE_LANDSCAPE_ERROR:"MOBILE_LANDSCAPE_ERROR",MULTIPLE_FACES_ERROR:"MULTIPLE_FACES_ERROR"};export{R as LivenessErrorState};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__awaiter as e}from"tslib";import*as t from"@tensorflow/tfjs-core";import*as o from"@tensorflow-models/blazeface";import*as s from"@tensorflow/tfjs-backend-wasm";import"@tensorflow/tfjs-backend-cpu";import{jitteredExponentialRetry as a}from"@aws-amplify/core";import{isWebAssemblySupported as i}from"./support.mjs";import{FaceDetection as r}from"../types/faceDetection.mjs";import"../types/liveness.mjs";
|
|
1
|
+
import{__awaiter as e}from"tslib";import*as t from"@tensorflow/tfjs-core";import*as o from"@tensorflow-models/blazeface";import*as s from"@tensorflow/tfjs-backend-wasm";import"@tensorflow/tfjs-backend-cpu";import{jitteredExponentialRetry as a}from"@aws-amplify/core";import{isWebAssemblySupported as i}from"./support.mjs";import{FaceDetection as r}from"../types/faceDetection.mjs";import"../types/liveness.mjs";const n="0.0.7",l=`https://cdn.liveness.rekognition.amazonaws.com/face-detection/tensorflow-models/blazeface/${n}/model/model.json`,d=`https://cdn.liveness.rekognition.amazonaws.com/face-detection/tensorflow/tfjs-backend-wasm/${s.version_wasm}/`;class m extends r{constructor(e,t){super(),this.faceModelUrl=null!=t?t:l,this.binaryPath=null!=e?e:d}loadModels(){return e(this,void 0,void 0,(function*(){i()?yield this._loadWebAssemblyBackend():yield this._loadCPUBackend();try{yield t.ready(),this._model=yield a(o.load,[{modelUrl:this.faceModelUrl}])}catch(e){throw new Error("There was an error loading the blazeface model. If you are using a custom blazeface model url ensure that it is a fully qualified url that returns a json file.")}}))}detectFaces(t){return e(this,void 0,void 0,(function*(){const e=yield this._model.estimateFaces(t,!1,!0,!0),o=Date.now();return e.filter((e=>!!e.landmarks)).map((e=>{const{topLeft:t,bottomRight:s,probability:a,landmarks:i}=e,[r,n]=t,[l,d]=s,m=Math.abs(r-l),c=Math.abs(d-n),f=i[0],h=i[1],u=i[2],w=i[3];return{top:n,left:l,width:m,height:c,timestampMs:o,probability:a[0],rightEye:f,leftEye:h,mouth:w,nose:u}}))}))}_loadWebAssemblyBackend(){return e(this,void 0,void 0,(function*(){try{s.setWasmPaths(this.binaryPath),yield a((()=>e(this,void 0,void 0,(function*(){if(!(yield t.setBackend("wasm")))throw new Error("Initialization of backend wasm failed")}))),[]),this.modelBackend="wasm"}catch(e){throw new Error('There was an error loading the TFJS WASM backend. If you are using a custom WASM path ensure that it ends with "/" and that it is not the full URL as @tensorflow/tfjs-backend-wasm will append the wasm binary file name. Read more: https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/src/backend_wasm.ts#L475.')}}))}_loadCPUBackend(){return e(this,void 0,void 0,(function*(){yield t.setBackend("cpu"),this.modelBackend="cpu"}))}}export{n as BLAZEFACE_VERSION,m as BlazeFaceFaceDetection,l as DEFAULT_BLAZEFACE_URL,d as DEFAULT_TFJS_WASM_URL};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__awaiter as t}from"tslib";import{FaceMatchState as e,IlluminationState as o}from"../types/liveness.mjs";import{LivenessErrorState as n}from"../types/error.mjs";import{FACE_DISTANCE_THRESHOLD as i,REDUCED_THRESHOLD_MOBILE as r,REDUCED_THRESHOLD as a}from"./constants.mjs";function h(t,e,o){return t*(o-e)+e}function l(t){const e=t.flippedCenterX-t.width/2,o=t.flippedCenterX+t.width/2,n=t.centerY-t.height/2,i=t.centerY+t.height/2;return{ovalBoundingBox:{left:e,top:n,right:o,bottom:i},minOvalX:e,maxOvalX:o,minOvalY:n,maxOvalY:i}}function c(t,e){const o=Math.max(t.left,e.left),n=Math.max(t.top,e.top),i=Math.min(t.right,e.right),r=Math.min(t.bottom,e.bottom),a=Math.abs(Math.max(0,i-o)*Math.max(0,r-n));if(0===a)return 0;return a/(Math.abs((t.right-t.left)*(t.bottom-t.top))+Math.abs((e.right-e.left)*(e.bottom-e.top))-a)}function s({sessionInformation:t,videoWidth:e}){var o,n;const i=null===(n=null===(o=null==t?void 0:t.Challenge)||void 0===o?void 0:o.FaceMovementAndLightChallenge)||void 0===n?void 0:n.OvalParameters;if(!(i&&i.CenterX&&i.CenterY&&i.Width&&i.Height))throw new Error("Oval parameters not returned from session information.");return{flippedCenterX:e-i.CenterX,centerX:i.CenterX,centerY:i.CenterY,width:i.Width,height:i.Height}}function d({width:t,height:e,widthSeed:o=1,centerXSeed:n=.5,centerYSeed:i=.5}){const r=e;let a=t;const l=.8*o,c=Math.floor(7*t/16),s=Math.floor(9*t/16),d=Math.floor(7*e/16),f=Math.floor(9*e/16),g=h(n,c,s),u=h(i,d,f);t>=e&&(a=3/4*r);const v=l*a,
|
|
1
|
+
import{__awaiter as t}from"tslib";import{FaceMatchState as e,IlluminationState as o}from"../types/liveness.mjs";import{LivenessErrorState as n}from"../types/error.mjs";import{FACE_DISTANCE_THRESHOLD as i,REDUCED_THRESHOLD_MOBILE as r,REDUCED_THRESHOLD as a}from"./constants.mjs";function h(t,e,o){return t*(o-e)+e}function l(t){const e=t.flippedCenterX-t.width/2,o=t.flippedCenterX+t.width/2,n=t.centerY-t.height/2,i=t.centerY+t.height/2;return{ovalBoundingBox:{left:e,top:n,right:o,bottom:i},minOvalX:e,maxOvalX:o,minOvalY:n,maxOvalY:i}}function c(t,e){const o=Math.max(t.left,e.left),n=Math.max(t.top,e.top),i=Math.min(t.right,e.right),r=Math.min(t.bottom,e.bottom),a=Math.abs(Math.max(0,i-o)*Math.max(0,r-n));if(0===a)return 0;return a/(Math.abs((t.right-t.left)*(t.bottom-t.top))+Math.abs((e.right-e.left)*(e.bottom-e.top))-a)}function s({sessionInformation:t,videoWidth:e}){var o,n;const i=null===(n=null===(o=null==t?void 0:t.Challenge)||void 0===o?void 0:o.FaceMovementAndLightChallenge)||void 0===n?void 0:n.OvalParameters;if(!(i&&i.CenterX&&i.CenterY&&i.Width&&i.Height))throw new Error("Oval parameters not returned from session information.");return{flippedCenterX:e-i.CenterX,centerX:i.CenterX,centerY:i.CenterY,width:i.Width,height:i.Height}}function d({width:t,height:e,widthSeed:o=1,centerXSeed:n=.5,centerYSeed:i=.5}){const r=e;let a=t;const l=.8*o,c=Math.floor(7*t/16),s=Math.floor(9*t/16),d=Math.floor(7*e/16),f=Math.floor(9*e/16),g=h(n,c,s),u=h(i,d,f);t>=e&&(a=3/4*r);const v=l*a,p=1.618*v;return{flippedCenterX:Math.floor(a-g),centerX:Math.floor(g),centerY:Math.floor(u),width:Math.floor(v),height:Math.floor(p)}}function f({canvas:t,oval:e,scaleFactor:o,videoEl:n}){const{flippedCenterX:i,centerY:r,width:a,height:h}=e,{width:l,height:c}=t.getBoundingClientRect(),s=t.getContext("2d");if(!s)throw new Error("Cannot find Canvas.");{s.clearRect(0,0,l,c),s.fillStyle="rgba(255, 255, 255, 1.0)",s.fillRect(0,0,l,c);const t={width:n.videoWidth,height:n.videoHeight},e={x:(l-t.width*o)/2,y:(c-t.height*o)/2};s.setTransform(o,0,0,o,e.x,e.y),s.beginPath(),s.ellipse(i,r,a/2,h/2,0,0,2*Math.PI),s.strokeStyle="#AEB3B7",s.lineWidth=3,s.stroke(),s.clip(),s.setTransform(1,0,0,1,0,0),s.clearRect(0,0,l,c)}}function g(t,o,n,i){var r,a;let h;const s=null===(a=null===(r=null==i?void 0:i.Challenge)||void 0===r?void 0:r.FaceMovementAndLightChallenge)||void 0===a?void 0:a.ChallengeConfig;if(!(s&&s.OvalIouThreshold&&s.OvalIouHeightThreshold&&s.OvalIouWidthThreshold&&s.FaceIouHeightThreshold&&s.FaceIouWidthThreshold))throw new Error("Challenge information not returned from session information.");const{OvalIouThreshold:d,OvalIouHeightThreshold:f,OvalIouWidthThreshold:g,FaceIouHeightThreshold:u,FaceIouWidthThreshold:p}=s,m=v(t,o),C=m.left,w=m.right,M=m.top,E=m.bottom,{ovalBoundingBox:O,minOvalX:x,minOvalY:b,maxOvalX:T,maxOvalY:I}=l(o),R=c(m,O),D=d,y=o.width*g,F=o.height*f,A=o.width*p,H=o.height*u,X=100*Math.max(Math.min(1,.75*(R-n)/(D-n)+.25),0);return h=R>D&&Math.abs(x-C)<y&&Math.abs(T-w)<y&&Math.abs(I-E)<F?e.MATCHED:b-M>H||E-I>H||x-C>A&&w-T>A?e.TOO_CLOSE:e.TOO_FAR,{faceMatchState:h,faceMatchPercentage:X}}function u(t){const{leftEye:e,rightEye:o,mouth:n}=t,i=[];i[0]=(e[0]+o[0])/2,i[1]=(e[1]+o[1])/2;return{pupilDistance:Math.sqrt(Math.pow(e[0]-o[0],2)+Math.pow(e[1]-o[1],2)),faceHeight:Math.sqrt(Math.pow(i[0]-n[0],2)+Math.pow(i[1]-n[1],2))}}function v(t,e){const{leftEye:o,rightEye:n,nose:i}=t,{height:r,centerY:a}=e,h=a-r/2,l=[];l[0]=(o[0]+n[0])/2,l[1]=(o[1]+n[1])/2;const{pupilDistance:c,faceHeight:s}=u(t),d=(2*c+1.8*s)/2,f=1.618*d;let g,v;l[1]<=(h+r)/2?(g=(l[0]+i[0])/2,v=(l[1]+i[1])/2):(g=l[0],v=l[1]);const p=g-d/2,m=v-f/2;return{left:p,top:m,right:p+d,bottom:m+f}}function p(t){const e=document.createElement("canvas");e.width=t.videoWidth,e.height=t.videoHeight;const n=e.getContext("2d");if(n){n.drawImage(t,0,0,e.width,e.height);const i=n.getImageData(0,0,e.width,e.height).data,r=8,a=new Array(r).fill(0);for(let t=0;t<i.length;t++){a[Math.round(.2126*i[t++]+.7152*i[t++]+.0722*i[t++])%32]++}let h=-1,l=0;for(let t=0;t<r;t++)a[t]>l&&(l=a[t],h=t);return e.remove(),0===h?o.DARK:h===r?o.BRIGHT:o.NORMAL}throw new Error("Cannot find Video Element.")}function m(t){return t.label.toLowerCase().includes("virtual")}function C({ctx:t,prevColor:e,nextColor:o,fraction:n}){const i=t.canvas.width,r=t.canvas.height;t.fillStyle=o,t.fillRect(0,0,i,r*n),1!==n&&(t.fillStyle=e,t.fillRect(0,r*n,i,r*(1-n)))}function w({overlayCanvas:t,prevColor:e,nextColor:o,videoEl:n,ovalDetails:i,heightFraction:r,scaleFactor:a}){const{x:h,y:l}=n.getBoundingClientRect(),{flippedCenterX:c,centerY:s,width:d,height:f}=i,g=c*a+h,u=s*a+l,v=t.width,p=t.height,m=t.getContext("2d");if(!m)throw new Error("Cannot find Overlay Canvas.");m.canvas.width=window.innerWidth,m.canvas.height=window.innerHeight,m.clearRect(0,0,v,p),C({ctx:m,prevColor:e,nextColor:o,fraction:r}),m.save(),m.beginPath(),m.rect(0,0,v,p),m.clip(),m.clearRect(0,0,v,p),m.globalAlpha=.9,C({ctx:m,prevColor:e,nextColor:o,fraction:r}),m.beginPath(),m.ellipse(g,u,d*a/2,f*a/2,0,0,2*Math.PI),m.strokeStyle="white",m.lineWidth=8,m.stroke(),m.clip(),m.clearRect(0,0,v,p),m.globalAlpha=.75,C({ctx:m,prevColor:e,nextColor:o,fraction:r}),m.restore()}const M=t=>!!t;function E(t){return(t.Challenge.FaceMovementAndLightChallenge.ColorSequences||[]).map((({FreshnessColor:t,DownscrollDuration:e,FlatDisplayDuration:o})=>{const n=t.RGB,i=`rgb(${n[0]},${n[1]},${n[2]})`;return void 0!==i&&void 0!==e&&void 0!==o?{color:i,downscrollDuration:e,flatDisplayDuration:o}:void 0})).filter(M)}function O(t){return t.slice(t.indexOf("(")+1,t.indexOf(")")).split(",").map((t=>parseInt(t)))}function x(o,n){return t(this,void 0,void 0,(function*(){let t;switch((yield o.detectFaces(n)).length){case 0:t=e.CANT_IDENTIFY;break;case 1:t=e.FACE_IDENTIFIED;break;default:t=e.TOO_MANY}return t}))}function b({faceDetector:e,videoEl:o,ovalDetails:h,reduceThreshold:l=!1,isMobile:c=!1}){return t(this,void 0,void 0,(function*(){const t=yield e.detectFaces(o);let s,d,f=!1;switch(t.length){case 0:d=n.FACE_DISTANCE_ERROR;break;case 1:{s=t[0];const e=h.width,{pupilDistance:o,faceHeight:g}=u(s),v=2;e&&(f=(v*o+1.8*g)/2/v/e<(l?c?r:a:i),f||(d=n.FACE_DISTANCE_ERROR));break}default:d=n.MULTIPLE_FACES_ERROR}return{isDistanceBelowThreshold:f,error:d}}))}function T({deviceHeight:t,deviceWidth:e,height:o,width:n,top:i,left:r}){return{Height:o/t,Width:n/e,Top:i/t,Left:r/e}}export{f as drawLivenessOvalInCanvas,p as estimateIllumination,w as fillOverlayCanvasFractional,v as generateBboxFromLandmarks,T as getBoundingBox,E as getColorsSequencesFromSessionInformation,x as getFaceMatchState,g as getFaceMatchStateInLivenessOval,c as getIntersectionOverUnion,l as getOvalBoundingBox,s as getOvalDetailsFromSessionInformation,O as getRGBArrayFromColorString,d as getStaticLivenessOvalDetails,m as isCameraDeviceVirtual,M as isClientFreshnessColorSequence,b as isFaceDistanceBelowThreshold};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__awaiter as e,__asyncGenerator as i,__await as t}from"tslib";import{Credentials as o,getAmplifyUserAgent as n}from"@aws-amplify/core";import{
|
|
1
|
+
import{__awaiter as e,__asyncGenerator as i,__await as t}from"tslib";import{Credentials as o,getAmplifyUserAgent as n}from"@aws-amplify/core";import{RekognitionStreamingClient as r,StartFaceLivenessSessionCommand as s}from"@aws-sdk/client-rekognitionstreaming";import{VideoRecorder as d}from"./videoRecorder.mjs";import{getLivenessUserAgent as a}from"../../utils/platform.mjs";import{CustomWebSocketFetchHandler as l}from"./CustomWebSocketFetchHandler.mjs";const c=process.env.NEXT_PUBLIC_STREAMING_API_URL,h=1e3;function v(e){return void 0!==e.Challenge}function m(e){return void 0!==e.code}class u{constructor({sessionId:e,region:i,stream:t,videoEl:o,credentialProvider:n}){this.sessionId=e,this.region=i,this._stream=t,this.videoEl=o,this.videoRecorder=new d(t),this.credentialProvider=n,this.initPromise=this.init()}getResponseStream(){return e(this,void 0,void 0,(function*(){return yield this.initPromise,this.responseStream}))}startRecordingLivenessVideo(){this.videoRecorder.start(1e3)}sendClientInfo(e){this.videoRecorder.dispatch(new MessageEvent("clientSesssionInfo",{data:{clientInfo:e}}))}stopVideo(){return e(this,void 0,void 0,(function*(){yield this.videoRecorder.stop()}))}dispatchStopVideoEvent(){this.videoRecorder.dispatch(new Event("stopVideo"))}endStreamWithCode(i){return e(this,void 0,void 0,(function*(){"recording"===this.videoRecorder.getState()&&(yield this.stopVideo()),this.videoRecorder.dispatch(new MessageEvent("endStreamWithCode",{data:{code:i}}))}))}init(){var i;return e(this,void 0,void 0,(function*(){const e=null!==(i=this.credentialProvider)&&void 0!==i?i:yield o.get();if(!e)throw new Error("No credentials");const t={credentials:e,region:this.region,customUserAgent:`${n()} ${a()}`,requestHandler:new l({connectionTimeout:1e4})};c&&(t.endpointProvider=()=>({url:new URL(c)})),this._client=new r(t),this.responseStream=yield this.startLivenessVideoConnection()}))}getAsyncGeneratorFromReadableStream(e){const o=this;return this._reader=e.getReader(),function(){return i(this,arguments,(function*(){for(;;){const{done:e,value:i}=yield t(o._reader.read());if(e)return yield t(void 0);if("stopVideo"===i)yield yield t({VideoEvent:{VideoChunk:[],TimestampMillis:Date.now()}});else if(void 0!==i.arrayBuffer){const e=yield t(i.arrayBuffer()),o=new Uint8Array(e);o.length>0&&(yield yield t({VideoEvent:{VideoChunk:o,TimestampMillis:Date.now()}}))}else v(i)?yield yield t({ClientSessionInformationEvent:{Challenge:i.Challenge}}):m(i)&&(yield yield t({VideoEvent:{VideoChunk:[],TimestampMillis:{closeCode:i.code}}}))}}))}}startLivenessVideoConnection(){return e(this,void 0,void 0,(function*(){const e=this.getAsyncGeneratorFromReadableStream(this.videoRecorder.videoStream)();return(yield this._client.send(new s({ChallengeVersions:"FaceMovementAndLightChallenge_1.0.0",SessionId:this.sessionId,LivenessRequestStream:e,VideoWidth:this.videoEl.videoWidth.toString(),VideoHeight:this.videoEl.videoHeight.toString()}))).LivenessResponseStream}))}}export{u as LivenessStreamProvider,h as TIME_SLICE};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"react";import{View as t,Flex as r,ComponentClassNames as a,Text as s}from"@aws-amplify/ui-react";import"@aws-amplify/ui-react/internal";import"@xstate/react";import"../providers/FaceLivenessDetectorProvider.mjs";import"@aws-amplify/ui";import{LivenessClassNames as
|
|
1
|
+
import e from"react";import{View as t,Flex as r,ComponentClassNames as a,Text as s}from"@aws-amplify/ui-react";import"@aws-amplify/ui-react/internal";import"@xstate/react";import"../providers/FaceLivenessDetectorProvider.mjs";import"@aws-amplify/ui";import{LivenessClassNames as o}from"../types/classNames.mjs";import"../service/machine/index.mjs";import"../service/types/liveness.mjs";import"tslib";import"@tensorflow/tfjs-core";import"@tensorflow-models/blazeface";import"@tensorflow/tfjs-backend-wasm";import"@tensorflow/tfjs-backend-cpu";import"@aws-amplify/core";import"../service/utils/streamProvider.mjs";import"../service/utils/freshnessColorDisplay.mjs";import{StartScreenFigure as i}from"./StartScreenFigure.mjs";import{GoodFitIllustration as m}from"./GoodFitIllustration.mjs";import{TooFarIllustration as n}from"./TooFarIllustration.mjs";import{LivenessIconWithPopover as l}from"./LivenessIconWithPopover.mjs";const c=({headingText:r,bodyText:a})=>e.createElement(t,{className:o.StartScreenHeader},e.createElement(t,{className:o.StartScreenHeaderHeading},r),e.createElement(t,{className:o.StartScreenHeaderBody},a)),p=({headingText:s,bodyText:i,infoText:m})=>e.createElement(r,{className:`${a.Alert} ${o.StartScreenWarning}`},e.createElement(t,{flex:"1"},e.createElement(t,{className:a.AlertHeading},s),e.createElement(t,{className:a.AlertBody},i)),e.createElement(l,null,m)),d=({headingText:t,goodFitCaptionText:a,goodFitAltText:l,tooFarCaptionText:c,tooFarAltText:p,steps:d})=>e.createElement(r,{direction:"column"},e.createElement(s,{className:o.StartScreenInstructionsHeading},t),e.createElement(r,{className:o.Figures},e.createElement(i,{variation:"success",caption:a},e.createElement(m,{title:l})),e.createElement(i,{variation:"error",caption:c},e.createElement(n,{title:p}))),e.createElement(r,{as:"ol",className:o.InstructionList},d.map(((t,a)=>e.createElement(r,{as:"li",key:a+1},e.createElement(s,{as:"span","aria-hidden":"true"},a+1,"."),e.createElement(s,{as:"span"},t))))));export{c as DefaultHeader,d as DefaultInstructions,p as DefaultPhotosensitiveWarning};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"react";import{Flex as r,Text as t,Button as s}from"@aws-amplify/ui-react";import{AlertIcon as a}from"@aws-amplify/ui-react/internal";import"../service/machine/index.mjs";import"../service/types/liveness.mjs";import{LivenessErrorState as i}from"../service/types/error.mjs";import"tslib";import"@tensorflow/tfjs-core";import"@tensorflow-models/blazeface";import"@tensorflow/tfjs-backend-wasm";import"@tensorflow/tfjs-backend-cpu";import"@aws-amplify/core";import"../service/utils/
|
|
1
|
+
import e from"react";import{Flex as r,Text as t,Button as s}from"@aws-amplify/ui-react";import{AlertIcon as a}from"@aws-amplify/ui-react/internal";import"../service/machine/index.mjs";import"../service/types/liveness.mjs";import{LivenessErrorState as i}from"../service/types/error.mjs";import"tslib";import"@tensorflow/tfjs-core";import"@tensorflow-models/blazeface";import"@tensorflow/tfjs-backend-wasm";import"@tensorflow/tfjs-backend-cpu";import"@aws-amplify/core";import"../service/utils/streamProvider.mjs";import"../service/utils/freshnessColorDisplay.mjs";import{Toast as o}from"./Toast.mjs";import{Overlay as m}from"./Overlay.mjs";import{defaultErrorDisplayText as l}from"../displayText.mjs";import{LivenessClassNames as c}from"../types/classNames.mjs";const n=({errorState:s,overrideErrorDisplayText:o})=>{const m=Object.assign(Object.assign({},l),o);return s===i.CAMERA_ACCESS_ERROR||s===i.CAMERA_FRAMERATE_ERROR||s===i.MOBILE_LANDSCAPE_ERROR?null:(s=>{const{error:o,displayText:m}=s,{timeoutHeaderText:l,timeoutMessageText:n,faceDistanceHeaderText:p,faceDistanceMessageText:E,multipleFacesHeaderText:R,multipleFacesMessageText:f,clientHeaderText:T,clientMessageText:d,serverHeaderText:u,serverMessageText:y}=m;let x,j;switch(o){case i.TIMEOUT:x=l,j=n;break;case i.FACE_DISTANCE_ERROR:x=p,j=E;break;case i.MULTIPLE_FACES_ERROR:x=R,j=f;break;case i.RUNTIME_ERROR:x=T,j=d;break;case i.SERVER_ERROR:default:x=u,j=y}return e.createElement(e.Fragment,null,e.createElement(r,{className:c.ErrorModal},e.createElement(a,{ariaHidden:!0,variation:"error"}),e.createElement(t,{className:c.ErrorModalHeading},x)),j)})({error:s,displayText:m})},p=t=>{const{children:a,onRetry:i,displayText:n}=t,p=Object.assign(Object.assign({},l),n),{tryAgainText:E}=p;return e.createElement(m,{className:c.OpaqueOverlay},e.createElement(o,null,a,e.createElement(r,{justifyContent:"center"},e.createElement(s,{variation:"primary",type:"button",onClick:i},E))))};export{p as FaceLivenessErrorModal,n as renderErrorModal};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as e from"react";import{Flex as t,Loader as r,View as
|
|
1
|
+
import*as e from"react";import{Flex as t,Loader as r,View as a}from"@aws-amplify/ui-react";import"../service/machine/index.mjs";import{FaceMatchState as o,IlluminationState as n}from"../service/types/liveness.mjs";import"tslib";import"@tensorflow/tfjs-core";import"@tensorflow-models/blazeface";import"@tensorflow/tfjs-backend-wasm";import"@tensorflow/tfjs-backend-cpu";import"@aws-amplify/core";import"../service/utils/streamProvider.mjs";import"../service/utils/freshnessColorDisplay.mjs";import{useLivenessActor as i}from"../hooks/useLivenessActor.mjs";import{createLivenessSelector as s,useLivenessSelector as c}from"../hooks/useLivenessSelector.mjs";import"@aws-amplify/ui";import{Toast as l}from"./Toast.mjs";import{Overlay as m}from"./Overlay.mjs";import{LivenessClassNames as h}from"../types/classNames.mjs";const f=s((e=>e.context.errorState)),T=s((e=>e.context.faceMatchAssociatedParams.faceMatchState)),u=s((e=>e.context.faceMatchAssociatedParams.illuminationState)),p=s((e=>e.context.isFaceFarEnoughBeforeRecording)),O=s((e=>e.context.faceMatchStateBeforeStart)),E=({hintDisplayText:s})=>{const[E]=i(),x=c(f),F=c(T),d=c(u),v=c(O),y=c(p),C=E.matches("checkFaceDetectedBeforeStart"),g=E.matches("checkFaceDistanceBeforeRecording"),A=E.matches("recording"),N=E.matches("notRecording"),j=E.matches("uploading"),S=E.matches("checkSucceeded"),M=E.matches("checkFailed"),D=E.matches({recording:"flashFreshnessColors"}),I={[o.CANT_IDENTIFY]:s.hintCanNotIdentifyText,[o.FACE_IDENTIFIED]:s.hintTooFarText,[o.TOO_MANY]:s.hintTooManyFacesText,[o.TOO_CLOSE]:s.hintTooCloseText,[o.TOO_FAR]:s.hintTooFarText,[o.MATCHED]:s.hintHoldFaceForFreshnessText},_={[n.BRIGHT]:s.hintIlluminationTooBrightText,[n.DARK]:s.hintIlluminationTooDarkText,[n.NORMAL]:s.hintIlluminationNormalText},k=(()=>{if(!(x||M||S)){if(!A){if(C)return v===o.TOO_MANY?e.createElement(l,null,I[v]):e.createElement(l,null,s.hintMoveFaceFrontOfCameraText);if(g&&!1===y)return e.createElement(l,null,s.hintTooCloseText);if(N)return e.createElement(l,null,e.createElement(t,{className:h.HintText},e.createElement(r,null),e.createElement(a,null,s.hintConnectingText)));if(j)return e.createElement(m,{className:h.OpaqueOverlay,anchorOrigin:{horizontal:"center",vertical:"end"}},e.createElement(l,null,e.createElement(t,{className:h.HintText},e.createElement(r,null),e.createElement(a,null,s.hintVerifyingText))));if(d&&d!==n.NORMAL)return e.createElement(l,null,_[d])}return D?e.createElement(l,{size:"large",variation:"primary"},s.hintHoldFaceForFreshnessText):A&&!D?e.createElement(l,{size:"large",variation:F===o.TOO_CLOSE?"error":"primary"},F===o.TOO_CLOSE?I[o.TOO_CLOSE]:I[o.TOO_FAR]):null}})();return k||null};export{E as Hint,f as selectErrorState,T as selectFaceMatchState,O as selectFaceMatchStateBeforeStart,u as selectIlluminationState,p as selectIsFaceFarEnoughBeforeRecording};
|
package/dist/esm/version.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="2.0.
|
|
1
|
+
const o="2.0.8";export{o as VERSION};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("react"),a=require("@aws-amplify/core"),i=require("@xstate/react"),r=require("xstate"),n=require("@tensorflow/tfjs-core"),o=require("@tensorflow-models/blazeface"),s=require("@tensorflow/tfjs-backend-wasm");require("@tensorflow/tfjs-backend-cpu");var c=require("@aws-amplify/predictions"),l=require("@aws-sdk/client-rekognitionstreaming"),d=require("@aws-sdk/util-format-url"),h=require("@smithy/eventstream-serde-browser"),u=require("@smithy/fetch-http-handler"),m=require("@smithy/protocol-http"),f=require("nanoid"),v=require("@aws-amplify/ui-react"),g=require("@aws-amplify/ui-react/internal"),p=require("@aws-amplify/ui"),E=require("classnames");function T(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function C(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(a){if("default"!==a){var i=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,i.get?i:{enumerable:!0,get:function(){return e[a]}})}})),t.default=e,Object.freeze(t)}var S,y,F,x=T(t),R=C(t),M=C(n),A=C(o),w=C(s),_=T(E);class D{triggerModelLoading(){this.modelLoadingPromise=this.loadModels()}}!function(e){e.DARK="dark",e.BRIGHT="bright",e.NORMAL="normal"}(S||(S={})),function(e){e.MATCHED="MATCHED",e.TOO_FAR="TOO FAR",e.TOO_CLOSE="TOO CLOSE",e.CANT_IDENTIFY="CANNOT IDENTIFY",e.FACE_IDENTIFIED="ONE FACE IDENTIFIED",e.TOO_MANY="TOO MANY FACES"}(y||(y={})),function(e){e.TIMEOUT="TIMEOUT",e.RUNTIME_ERROR="RUNTIME_ERROR",e.FRESHNESS_TIMEOUT="FRESHNESS_TIMEOUT",e.SERVER_ERROR="SERVER_ERROR",e.CAMERA_FRAMERATE_ERROR="CAMERA_FRAMERATE_ERROR",e.CAMERA_ACCESS_ERROR="CAMERA_ACCESS_ERROR",e.FACE_DISTANCE_ERROR="FACE_DISTANCE_ERROR",e.MOBILE_LANDSCAPE_ERROR="MOBILE_LANDSCAPE_ERROR",e.MULTIPLE_FACES_ERROR="MULTIPLE_FACES_ERROR"}(F||(F={}));const I=1e3,O=4e3,b=4001,P=4003,k=4005,L=4007;function N(e,t,a){return e*(a-t)+t}function H(e){const t=e.flippedCenterX-e.width/2,a=e.flippedCenterX+e.width/2,i=e.centerY-e.height/2,r=e.centerY+e.height/2;return{ovalBoundingBox:{left:t,top:i,right:a,bottom:r},minOvalX:t,maxOvalX:a,minOvalY:i,maxOvalY:r}}function B(e,t){const a=Math.max(e.left,t.left),i=Math.max(e.top,t.top),r=Math.min(e.right,t.right),n=Math.min(e.bottom,t.bottom),o=Math.abs(Math.max(0,r-a)*Math.max(0,n-i));if(0===o)return 0;return o/(Math.abs((e.right-e.left)*(e.bottom-e.top))+Math.abs((t.right-t.left)*(t.bottom-t.top))-o)}function W({width:e,height:t,widthSeed:a=1,centerXSeed:i=.5,centerYSeed:r=.5}){const n=t;let o=e;const s=.8*a,c=Math.floor(7*e/16),l=Math.floor(9*e/16),d=Math.floor(7*t/16),h=Math.floor(9*t/16),u=N(i,c,l),m=N(r,d,h);e>=t&&(o=3/4*n);const f=s*o,v=1.618*f;return{flippedCenterX:Math.floor(o-u),centerX:Math.floor(u),centerY:Math.floor(m),width:Math.floor(f),height:Math.floor(v)}}function V(e){const{leftEye:t,rightEye:a,mouth:i}=e,r=[];r[0]=(t[0]+a[0])/2,r[1]=(t[1]+a[1])/2;return{pupilDistance:Math.sqrt(Math.pow(t[0]-a[0],2)+Math.pow(t[1]-a[1],2)),faceHeight:Math.sqrt(Math.pow(r[0]-i[0],2)+Math.pow(r[1]-i[1],2))}}function j(e,t){const{leftEye:a,rightEye:i,nose:r}=e,{height:n,centerY:o}=t,s=o-n/2,c=[];c[0]=(a[0]+i[0])/2,c[1]=(a[1]+i[1])/2;const{pupilDistance:l,faceHeight:d}=V(e),h=(2*l+1.8*d)/2,u=1.618*h;let m,f;c[1]<=(s+n)/2?(m=(c[0]+r[0])/2,f=(c[1]+r[1])/2):(m=c[0],f=c[1]);const v=m-h/2,g=f-u/2;return{left:v,top:g,right:v+h,bottom:g+u}}function z(e){const t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;const a=t.getContext("2d");if(a){a.drawImage(e,0,0,t.width,t.height);const i=a.getImageData(0,0,t.width,t.height).data,r=8,n=new Array(r).fill(0);for(let e=0;e<i.length;e++){n[Math.round(.2126*i[e++]+.7152*i[e++]+.0722*i[e++])%32]++}let o=-1,s=0;for(let e=0;e<r;e++)n[e]>s&&(s=n[e],o=e);return t.remove(),0===o?S.DARK:o===r?S.BRIGHT:S.NORMAL}throw new Error("Cannot find Video Element.")}F.RUNTIME_ERROR,F.SERVER_ERROR,F.TIMEOUT,F.FACE_DISTANCE_ERROR,F.MULTIPLE_FACES_ERROR,F.CAMERA_FRAMERATE_ERROR,F.CAMERA_ACCESS_ERROR,F.MOBILE_LANDSCAPE_ERROR,F.FRESHNESS_TIMEOUT;function U({ctx:e,prevColor:t,nextColor:a,fraction:i}){const r=e.canvas.width,n=e.canvas.height;e.fillStyle=a,e.fillRect(0,0,r,n*i),1!==i&&(e.fillStyle=t,e.fillRect(0,n*i,r,n*(1-i)))}const q=e=>!!e;function Y(e){return e.slice(e.indexOf("(")+1,e.indexOf(")")).split(",").map((e=>parseInt(e)))}function $({faceDetector:t,videoEl:a,ovalDetails:i,reduceThreshold:r=!1,isMobile:n=!1}){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield t.detectFaces(a);let o,s,c=!1;switch(e.length){case 0:s=F.FACE_DISTANCE_ERROR;break;case 1:{o=e[0];const t=i.width,{pupilDistance:a,faceHeight:l}=V(o),d=2;t&&(c=(d*a+1.8*l)/2/d/t<(r?n?.37:.4:.32),c||(s=F.FACE_DISTANCE_ERROR));break}default:s=F.MULTIPLE_FACES_ERROR}return{isDistanceBelowThreshold:c,error:s}}))}function G({deviceHeight:e,deviceWidth:t,height:a,width:i,top:r,left:n}){return{Height:a/e,Width:i/t,Top:r/e,Left:n/t}}const X=`https://cdn.liveness.rekognition.amazonaws.com/face-detection/tensorflow/tfjs-backend-wasm/${w.version_wasm}/`;class Z extends D{constructor(e,t){super(),this.faceModelUrl=null!=t?t:"https://cdn.liveness.rekognition.amazonaws.com/face-detection/tensorflow-models/blazeface/0.0.7/model/model.json",this.binaryPath=null!=e?e:X}loadModels(){return e.__awaiter(this,void 0,void 0,(function*(){!function(){try{return!(!window.WebAssembly||!window.WebAssembly.compile&&!window.WebAssembly.compileStreaming)}catch(e){return!1}}()?yield this._loadCPUBackend():yield this._loadWebAssemblyBackend();try{yield M.ready(),this._model=yield a.jitteredExponentialRetry(A.load,[{modelUrl:this.faceModelUrl}])}catch(e){throw new Error("There was an error loading the blazeface model. If you are using a custom blazeface model url ensure that it is a fully qualified url that returns a json file.")}}))}detectFaces(t){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this._model.estimateFaces(t,!1,!0,!0),a=Date.now();return e.filter((e=>!!e.landmarks)).map((e=>{const{topLeft:t,bottomRight:i,probability:r,landmarks:n}=e,[o,s]=t,[c,l]=i,d=Math.abs(o-c),h=Math.abs(l-s),u=n[0],m=n[1],f=n[2],v=n[3];return{top:s,left:c,width:d,height:h,timestampMs:a,probability:r[0],rightEye:u,leftEye:m,mouth:v,nose:f}}))}))}_loadWebAssemblyBackend(){return e.__awaiter(this,void 0,void 0,(function*(){try{w.setWasmPaths(this.binaryPath),yield a.jitteredExponentialRetry((()=>e.__awaiter(this,void 0,void 0,(function*(){if(!(yield M.setBackend("wasm")))throw new Error("Initialization of backend wasm failed")}))),[]),this.modelBackend="wasm"}catch(e){throw new Error('There was an error loading the TFJS WASM backend. If you are using a custom WASM path ensure that it ends with "/" and that it is not the full URL as @tensorflow/tfjs-backend-wasm will append the wasm binary file name. Read more: https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/src/backend_wasm.ts#L475.')}}))}_loadCPUBackend(){return e.__awaiter(this,void 0,void 0,(function*(){yield M.setBackend("cpu"),this.modelBackend="cpu"}))}}class K{constructor(e,t={}){if("undefined"==typeof MediaRecorder)throw Error("MediaRecorder is not supported by this browser");this._stream=e,this._options=t,this._chunks=[],this._recorder=new MediaRecorder(e,{bitsPerSecond:1e6}),this._setupCallbacks()}getState(){return this._recorder.state}start(e){this.clearRecordedData(),this.recordingStartApiTimestamp=Date.now(),this._recorder.start(e)}stop(){return e.__awaiter(this,void 0,void 0,(function*(){return"recording"===this.getState()&&this._recorder.stop(),this._recorderStopped}))}pause(){this._recorder.pause()}clearRecordedData(){this._chunks=[]}dispatch(e){this._recorder.dispatchEvent(e)}getVideoChunkSize(){return this._chunks.length}_setupCallbacks(){this.videoStream=new ReadableStream({start:e=>{this._recorder&&(this._recorder.ondataavailable=t=>{t.data&&t.data.size>0&&(0===this._chunks.length&&(this.firstChunkTimestamp=Date.now()),this._chunks.push(t.data),e.enqueue(t.data))},this._recorder.addEventListener("clientSesssionInfo",(t=>{e.enqueue(t.data.clientInfo)})),this._recorder.addEventListener("stopVideo",(()=>{e.enqueue("stopVideo")})),this._recorder.addEventListener("endStream",(()=>{e.close()})),this._recorder.addEventListener("endStreamWithCode",(t=>{e.enqueue({type:"endStreamWithCode",code:t.data.code})})))}}),this.recorderStarted=new Promise((e=>{this._recorder.onstart=()=>{this.recorderStartTimestamp=Date.now(),e()}})),this._recorderStopped=new Promise((e=>{this._recorder.onstop=()=>{this.recorderEndTimestamp=Date.now(),e()}})),this._recorder.onerror=()=>{"stopped"!==this.getState()&&this.stop()}}}const Q=2e3,J=t=>{return t[Symbol.asyncIterator]?t:(a=t,"function"==typeof ReadableStream&&a instanceof ReadableStream?h.readableStreamtoIterable(t):{[Symbol.asyncIterator]:function(){return e.__asyncGenerator(this,arguments,(function*(){yield yield e.__await(t)}))}});var a};class ee{constructor(e,t=new u.FetchHttpHandler){this.metadata={handlerProtocol:"websocket/h1.1"},this.sockets={},this.utf8decoder=new TextDecoder,this.httpHandler=t,this.configPromise="function"==typeof e?e().then((e=>null!=e?e:{})):Promise.resolve(null!=e?e:{})}destroy(){for(const[e,t]of Object.entries(this.sockets)){for(const e of t)e.close(1e3,"Socket closed through destroy() call");delete this.sockets[e]}}handle(t){return e.__awaiter(this,void 0,void 0,(function*(){if(!(e=>"ws:"===e.protocol||"wss:"===e.protocol)(t))return this.httpHandler.handle(t);const e=d.formatUrl(t),a=new WebSocket(e);this.sockets[e]||(this.sockets[e]=[]),this.sockets[e].push(a),a.binaryType="arraybuffer";const{connectionTimeout:i=Q}=yield this.configPromise;yield this.waitForReady(a,i);const{body:r}=t,n=J(r),o=(e=>"function"==typeof ReadableStream?h.iterableToReadableStream(e):e)(this.connect(a,n));return{response:new m.HttpResponse({statusCode:200,body:o})}}))}removeNotUsableSockets(e){var t;this.sockets[e]=(null!==(t=this.sockets[e])&&void 0!==t?t:[]).filter((e=>![WebSocket.CLOSING,WebSocket.CLOSED].includes(e.readyState)))}waitForReady(e,t){return new Promise(((a,i)=>{const r=setTimeout((()=>{this.removeNotUsableSockets(e.url),i({$metadata:{httpStatusCode:500}})}),t);e.onopen=()=>{clearTimeout(r),a()}}))}connect(t,a){let i,r=!1,n=()=>{},o=()=>{};t.onmessage=e=>{o({done:!1,value:new Uint8Array(e.data)})},t.onerror=e=>{r=!0,t.close(),n(e)},t.onclose=()=>{this.removeNotUsableSockets(t.url),r||(i?n(i):o({done:!0,value:void 0}))};const s={[Symbol.asyncIterator]:()=>({next:()=>new Promise(((e,t)=>{o=e,n=t}))})};return(()=>{e.__awaiter(this,void 0,void 0,(function*(){var r,n,o,s;try{try{for(var c,l=!0,d=e.__asyncValues(a);!(r=(c=yield d.next()).done);){s=c.value,l=!1;try{const e=s,a=this.utf8decoder.decode(e);if(a.includes("closeCode")){const e=a.match(/"closeCode":([0-9]*)/);if(e){const a=e[1];t.close(parseInt(a))}continue}t.send(e)}finally{l=!0}}}catch(e){n={error:e}}finally{try{l||r||!(o=d.return)||(yield o.call(d))}finally{if(n)throw n.error}}}catch(e){i=e}finally{t.close(I)}}))})(),s}}const te=process.env.NEXT_PUBLIC_STREAMING_API_URL;function ae(e){return void 0!==e.Challenge}function ie(e){return void 0!==e.code}class re extends c.AmazonAIInterpretPredictionsProvider{constructor({sessionId:e,region:t,stream:a,videoEl:i,credentialProvider:r}){super(),this.sessionId=e,this.region=t,this._stream=a,this.videoEl=i,this.videoRecorder=new K(a),this.credentialProvider=r,this.initPromise=this.init()}getResponseStream(){return e.__awaiter(this,void 0,void 0,(function*(){return yield this.initPromise,this.responseStream}))}startRecordingLivenessVideo(){this.videoRecorder.start(1e3)}sendClientInfo(e){this.videoRecorder.dispatch(new MessageEvent("clientSesssionInfo",{data:{clientInfo:e}}))}stopVideo(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.videoRecorder.stop()}))}dispatchStopVideoEvent(){this.videoRecorder.dispatch(new Event("stopVideo"))}endStreamWithCode(t){return e.__awaiter(this,void 0,void 0,(function*(){"recording"===this.videoRecorder.getState()&&(yield this.stopVideo()),this.videoRecorder.dispatch(new MessageEvent("endStreamWithCode",{data:{code:t}}))}))}init(){var t;return e.__awaiter(this,void 0,void 0,(function*(){const e=null!==(t=this.credentialProvider)&&void 0!==t?t:yield a.Credentials.get();if(!e)throw new Error("No credentials");const i={credentials:e,region:this.region,customUserAgent:`${a.getAmplifyUserAgent()} ui-react-liveness/2.0.7`,requestHandler:new ee({connectionTimeout:1e4})};te&&(i.endpointProvider=()=>({url:new URL(te)})),this._client=new l.RekognitionStreamingClient(i),this.responseStream=yield this.startLivenessVideoConnection()}))}getAsyncGeneratorFromReadableStream(t){const a=this;return this._reader=t.getReader(),function(){return e.__asyncGenerator(this,arguments,(function*(){for(;;){const{done:t,value:i}=yield e.__await(a._reader.read());if(t)return yield e.__await(void 0);if("stopVideo"===i)yield yield e.__await({VideoEvent:{VideoChunk:[],TimestampMillis:Date.now()}});else if(void 0!==i.arrayBuffer){const t=yield e.__await(i.arrayBuffer()),a=new Uint8Array(t);a.length>0&&(yield yield e.__await({VideoEvent:{VideoChunk:a,TimestampMillis:Date.now()}}))}else ae(i)?yield yield e.__await({ClientSessionInformationEvent:{Challenge:i.Challenge}}):ie(i)&&(yield yield e.__await({VideoEvent:{VideoChunk:[],TimestampMillis:{closeCode:i.code}}}))}}))}}startLivenessVideoConnection(){return e.__awaiter(this,void 0,void 0,(function*(){const e=this.getAsyncGeneratorFromReadableStream(this.videoRecorder.videoStream)();return(yield this._client.send(new l.StartFaceLivenessSessionCommand({ChallengeVersions:"FaceMovementAndLightChallenge_1.0.0",SessionId:this.sessionId,LivenessRequestStream:e,VideoWidth:this.videoEl.videoWidth.toString(),VideoHeight:this.videoEl.videoHeight.toString()}))).LivenessResponseStream}))}}var ne;!function(e){e.SCROLLING="SCROLLING",e.FLAT="FLAT"}(ne||(ne={}));class oe{constructor(e,t){this.context=e,this.freshnessColorsSequence=t,this.isFirstTick=!0}displayColorTick(){return e.__awaiter(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{setTimeout((()=>{this.displayNextColorTick(e,t)}),Math.min(10))}))}))}init(){this.stageIndex=0,this.currColorIndex=0,this.currColorSequence=this.freshnessColorsSequence[0],this.prevColorSequence=this.freshnessColorsSequence[0],this.stage=ne.FLAT,this.timeLastFlatOrScrollChange=Date.now(),this.timeLastFaceMatchChecked=Date.now()}displayNextColorTick(e,t){const{freshnessColorEl:a}=this.context.freshnessColorAssociatedParams,{ovalDetails:i,scaleFactor:r}=this.context.ovalAssociatedParams,{videoEl:n}=this.context.videoAssociatedParams,o=Date.now();this.isFirstTick&&(this.init(),this.isFirstTick=!1,this.sendColorStartTime({tickStartTime:o,currColor:this.currColorSequence.color,prevColor:this.currColorSequence.color,currColorIndex:this.stageIndex}));let s=o-this.timeLastFlatOrScrollChange;if(a.style.display="block",(this.stage===ne.FLAT&&s>=this.currColorSequence.flatDisplayDuration||this.stage===ne.SCROLLING&&s>=this.currColorSequence.downscrollDuration)&&(this.incrementStageIndex(o),s=0),this.currColorIndex<this.freshnessColorsSequence.length){const t=s/(this.stage===ne.SCROLLING?this.currColorSequence.downscrollDuration:this.currColorSequence.flatDisplayDuration);!function({overlayCanvas:e,prevColor:t,nextColor:a,videoEl:i,ovalDetails:r,heightFraction:n,scaleFactor:o}){const{x:s,y:c}=i.getBoundingClientRect(),{flippedCenterX:l,centerY:d,width:h,height:u}=r,m=l*o+s,f=d*o+c,v=e.width,g=e.height,p=e.getContext("2d");if(!p)throw new Error("Cannot find Overlay Canvas.");p.canvas.width=window.innerWidth,p.canvas.height=window.innerHeight,p.clearRect(0,0,v,g),U({ctx:p,prevColor:t,nextColor:a,fraction:n}),p.save(),p.beginPath(),p.rect(0,0,v,g),p.clip(),p.clearRect(0,0,v,g),p.globalAlpha=.9,U({ctx:p,prevColor:t,nextColor:a,fraction:n}),p.beginPath(),p.ellipse(m,f,h*o/2,u*o/2,0,0,2*Math.PI),p.strokeStyle="white",p.lineWidth=8,p.stroke(),p.clip(),p.clearRect(0,0,v,g),p.globalAlpha=.75,U({ctx:p,prevColor:t,nextColor:a,fraction:n}),p.restore()}({overlayCanvas:a,prevColor:this.prevColorSequence.color,nextColor:this.currColorSequence.color,videoEl:n,ovalDetails:i,heightFraction:t,scaleFactor:r}),e(!1)}else a.style.display="none",e(!0)}incrementStageIndex(e){if(this.stageIndex+=1,this.prevColorSequence=this.freshnessColorsSequence[this.currColorIndex],this.stage===ne.FLAT)this.currColorIndex+=1,this.stage=ne.SCROLLING;else if(this.stage===ne.SCROLLING){this.freshnessColorsSequence[this.currColorIndex].flatDisplayDuration>0?this.stage=ne.FLAT:(this.stage=ne.SCROLLING,this.currColorIndex+=1)}this.currColorSequence=this.freshnessColorsSequence[this.currColorIndex],this.timeLastFlatOrScrollChange=Date.now(),this.currColorSequence&&this.sendColorStartTime({tickStartTime:e,currColor:this.currColorSequence.color,prevColor:this.prevColorSequence.color,currColorIndex:this.stageIndex})}sendColorStartTime({tickStartTime:e,currColor:t,prevColor:a,currColorIndex:i}){const{livenessStreamProvider:r,challengeId:n}=this.context;r.sendClientInfo({Challenge:{FaceMovementAndLightChallenge:{ChallengeId:n,ColorDisplayed:{CurrentColor:{RGB:Y(t)},PreviousColor:{RGB:Y(a)},SequenceNumber:i,CurrentColorStartTimestamp:e}}}})}}const se=e=>!!(null==e?void 0:e.DisconnectionEvent),ce=e=>!!(null==e?void 0:e.ValidationException),le=e=>!!(null==e?void 0:e.InternalServerException),de=e=>!!(null==e?void 0:e.ThrottlingException),he=e=>!!(null==e?void 0:e.ServiceQuotaExceededException),ue={width:{min:320,ideal:640},height:{min:240,ideal:480},frameRate:{min:15,ideal:30,max:30},facingMode:"user"};let me;const fe=r.createMachine({id:"livenessMachine",initial:"start",predictableActionArguments:!0,context:{challengeId:f.nanoid(),maxFailedAttempts:0,failedAttempts:0,componentProps:void 0,serverSessionInformation:void 0,videoAssociatedParams:{videoConstraints:ue},ovalAssociatedParams:void 0,faceMatchAssociatedParams:{illuminationState:void 0,faceMatchState:void 0,faceMatchPercentage:25,currentDetectedFace:void 0,startFace:void 0,endFace:void 0,initialFaceMatchTime:void 0},freshnessColorAssociatedParams:{freshnessColorEl:void 0,freshnessColors:[],freshnessColorsComplete:!1,freshnessColorDisplay:void 0},errorState:void 0,livenessStreamProvider:void 0,responseStreamActorRef:void 0,shouldDisconnect:!1,faceMatchStateBeforeStart:void 0,isFaceFarEnoughBeforeRecording:void 0,isRecordingStopped:!1},on:{CANCEL:"userCancel",TIMEOUT:{target:"retryableTimeout",actions:"updateErrorStateForTimeout"},SET_SESSION_INFO:{internal:!0,actions:"updateSessionInfo"},DISCONNECT_EVENT:{internal:!0,actions:"updateShouldDisconnect"},SET_DOM_AND_CAMERA_DETAILS:{actions:"setDOMAndCameraDetails"},SERVER_ERROR:{target:"error",actions:"updateErrorStateForServer"},RUNTIME_ERROR:{target:"error"},MOBILE_LANDSCAPE_WARNING:{target:"mobileLandscapeWarning",actions:"updateErrorStateForServer"}},states:{start:{on:{BEGIN:"cameraCheck"}},cameraCheck:{entry:["resetErrorState","initializeFaceDetector"],invoke:{src:"checkVirtualCameraAndGetStream",onDone:{target:"waitForDOMAndCameraDetails",actions:["updateVideoMediaStream"]},onError:{target:"permissionDenied"}}},waitForDOMAndCameraDetails:{after:{0:{target:"detectFaceBeforeStart",cond:"hasDOMAndCameraDetails"},500:{target:"waitForDOMAndCameraDetails"}}},detectFaceBeforeStart:{invoke:{src:"detectFace",onDone:{target:"checkFaceDetectedBeforeStart",actions:["updateFaceMatchBeforeStartDetails"]}}},checkFaceDetectedBeforeStart:{after:{0:{target:"detectFaceDistanceBeforeRecording",cond:"hasSingleFaceBeforeStart"},100:{target:"detectFaceBeforeStart"}}},detectFaceDistanceBeforeRecording:{invoke:{src:"detectFaceDistance",onDone:{target:"checkFaceDistanceBeforeRecording",actions:["updateFaceDistanceBeforeRecording"]}}},checkFaceDistanceBeforeRecording:{after:{0:{target:"initializeLivenessStream",cond:"hasEnoughFaceDistanceBeforeRecording"},100:{target:"detectFaceDistanceBeforeRecording"}}},initializeLivenessStream:{invoke:{src:"openLivenessStreamConnection",onDone:{target:"notRecording",actions:["updateLivenessStreamProvider","spawnResponseStreamActor"]}}},notRecording:{on:{START_RECORDING:"recording"},initial:"waitForSessionInfo",states:{waitForSessionInfo:{after:{0:{target:"#livenessMachine.recording",cond:"hasServerSessionInfo"},100:{target:"detectFaceDistanceDuringLoading"}}},detectFaceDistanceDuringLoading:{invoke:{src:"detectFaceDistanceWhileLoading",onDone:{target:"checkFaceDistanceDuringLoading",actions:["updateFaceDistanceWhileLoading"]}}},checkFaceDistanceDuringLoading:{always:[{target:"failure",cond:"hasNotEnoughFaceDistanceBeforeRecording"},{target:"waitForSessionInfo"}]},failure:{entry:"sendTimeoutAfterFaceDistanceDelay",type:"final"}}},recording:{entry:["clearErrorState","startRecording"],initial:"ovalDrawing",states:{ovalDrawing:{entry:["sendTimeoutAfterOvalDrawingDelay"],invoke:{src:"detectInitialFaceAndDrawOval",onDone:{target:"checkFaceDetected",actions:["updateOvalAndFaceDetailsPostDraw","sendTimeoutAfterOvalMatchDelay"]},onError:{target:"#livenessMachine.error",actions:"updateErrorStateForRuntime"}}},checkFaceDetected:{after:{0:{target:"checkRecordingStarted",cond:"hasSingleFace"},100:{target:"ovalDrawing"}}},checkRecordingStarted:{after:{0:{target:"ovalMatching",cond:"hasRecordingStarted",actions:["updateRecordingStartTimestampMs"]},100:{target:"checkRecordingStarted"}}},ovalMatching:{entry:["cancelOvalDrawingTimeout"],invoke:{src:"detectFaceAndMatchOval",onDone:{target:"checkMatch",actions:"updateFaceDetailsPostMatch"}}},checkMatch:{after:{0:{target:"flashFreshnessColors",cond:"hasFaceMatchedInOvalWithMinTime",actions:["updateEndFaceMatch","setupFlashFreshnessColors","cancelOvalMatchTimeout","cancelOvalDrawingTimeout"]},.1:{target:"ovalMatching",cond:"hasFaceMatchedInOval",actions:"setFaceMatchTimeAndStartFace"},1:{target:"ovalMatching",cond:"hasNotFaceMatchedInOval"}}},flashFreshnessColors:{invoke:{src:"flashColors",onDone:[{target:"success",cond:"hasFreshnessColorShown"},{target:"flashFreshnessColors",actions:"updateFreshnessDetails"}]}},success:{entry:["stopRecording"],type:"final"}},onDone:"uploading"},uploading:{initial:"pending",states:{pending:{entry:["sendTimeoutAfterWaitingForDisconnect","pauseVideoStream"],invoke:{src:"stopVideo",onDone:"waitForDisconnectEvent",onError:{target:"#livenessMachine.error",actions:"updateErrorStateForRuntime"}}},waitForDisconnectEvent:{after:{0:{target:"getLivenessResult",cond:"getShouldDisconnect"},100:{target:"waitForDisconnectEvent"}}},getLivenessResult:{entry:["cancelWaitForDisconnectTimeout","freezeStream"],invoke:{src:"getLiveness",onError:{target:"#livenessMachine.error",actions:"updateErrorStateForServer"}}}}},retryableTimeout:{entry:"updateFailedAttempts",always:[{target:"timeout",cond:"shouldTimeoutOnFailedAttempts"},{target:"notRecording"}]},permissionDenied:{entry:"callUserPermissionDeniedCallback",on:{RETRY_CAMERA_CHECK:"cameraCheck"}},mobileLandscapeWarning:{entry:"callMobileLandscapeWarningCallback",always:[{target:"error"}]},timeout:{entry:["cleanUpResources","callUserTimeoutCallback","freezeStream"]},error:{entry:["cleanUpResources","callErrorCallback","cancelOvalDrawingTimeout","cancelWaitForDisconnectTimeout","cancelOvalMatchTimeout","freezeStream"]},userCancel:{entry:["cleanUpResources","callUserCancelCallback","resetContext"],always:[{target:"start"}]}}},{actions:{spawnResponseStreamActor:r.assign({responseStreamActorRef:()=>r.spawn(ve)}),updateFailedAttempts:r.assign({failedAttempts:e=>e.failedAttempts+1}),updateVideoMediaStream:r.assign({videoAssociatedParams:(e,t)=>{var a;return Object.assign(Object.assign({},e.videoAssociatedParams),{videoMediaStream:null===(a=t.data)||void 0===a?void 0:a.stream})}}),initializeFaceDetector:r.assign({ovalAssociatedParams:e=>{const{componentProps:t}=e,{faceModelUrl:a,binaryPath:i}=t.config,r=new Z(i,a);return r.triggerModelLoading(),Object.assign(Object.assign({},e.ovalAssociatedParams),{faceDetector:r})}}),updateLivenessStreamProvider:r.assign({livenessStreamProvider:(e,t)=>{var a;return null===(a=t.data)||void 0===a?void 0:a.livenessStreamProvider}}),setDOMAndCameraDetails:r.assign({videoAssociatedParams:(e,t)=>{var a,i,r;return Object.assign(Object.assign({},e.videoAssociatedParams),{videoEl:null===(a=t.data)||void 0===a?void 0:a.videoEl,canvasEl:null===(i=t.data)||void 0===i?void 0:i.canvasEl,isMobile:null===(r=t.data)||void 0===r?void 0:r.isMobile})},freshnessColorAssociatedParams:(e,t)=>{var a;return Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorEl:null===(a=t.data)||void 0===a?void 0:a.freshnessColorEl})}}),updateRecordingStartTimestampMs:r.assign({videoAssociatedParams:e=>{const{challengeId:t,videoAssociatedParams:a,ovalAssociatedParams:i,livenessStreamProvider:r}=e,{recordingStartApiTimestamp:n,recorderStartTimestamp:o}=r.videoRecorder,{videoMediaStream:s}=a,{initialFace:c}=i,l=Math.round(.73*(o-n)+n),{width:d,height:h}=s.getTracks()[0].getSettings(),u=d-c.left-c.width;return e.livenessStreamProvider.sendClientInfo({Challenge:{FaceMovementAndLightChallenge:{ChallengeId:t,VideoStartTimestamp:l,InitialFace:{InitialFaceDetectedTimestamp:c.timestampMs,BoundingBox:G({deviceHeight:h,deviceWidth:d,height:c.height,width:c.width,top:c.top,left:u})}}}}),Object.assign(Object.assign({},e.videoAssociatedParams),{recordingStartTimestampMs:l})}}),startRecording:r.assign({videoAssociatedParams:e=>{if(!e.serverSessionInformation)throw new Error("Session information was not received from response stream");return e.livenessStreamProvider.videoRecorder&&"recording"!==e.livenessStreamProvider.videoRecorder.getState()&&e.livenessStreamProvider.startRecordingLivenessVideo(),Object.assign({},e.videoAssociatedParams)}}),stopRecording:e=>{},updateFaceMatchBeforeStartDetails:r.assign({faceMatchStateBeforeStart:(e,t)=>t.data.faceMatchState}),updateFaceDistanceBeforeRecording:r.assign({isFaceFarEnoughBeforeRecording:(e,t)=>t.data.isFaceFarEnoughBeforeRecording}),updateFaceDistanceWhileLoading:r.assign({isFaceFarEnoughBeforeRecording:(e,t)=>t.data.isFaceFarEnoughBeforeRecording,errorState:(e,t)=>{var a;return null===(a=t.data)||void 0===a?void 0:a.error}}),updateOvalAndFaceDetailsPostDraw:r.assign({ovalAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.ovalAssociatedParams),{initialFace:t.data.initialFace,ovalDetails:t.data.ovalDetails,scaleFactor:t.data.scaleFactor}),faceMatchAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{faceMatchState:t.data.faceMatchState,illuminationState:t.data.illuminationState})}),updateFaceDetailsPostMatch:r.assign({faceMatchAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{faceMatchState:t.data.faceMatchState,faceMatchPercentage:t.data.faceMatchPercentage,illuminationState:t.data.illuminationState,currentDetectedFace:t.data.detectedFace})}),updateEndFaceMatch:r.assign({faceMatchAssociatedParams:e=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{endFace:e.faceMatchAssociatedParams.currentDetectedFace})}),setFaceMatchTimeAndStartFace:r.assign({faceMatchAssociatedParams:e=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{startFace:void 0===e.faceMatchAssociatedParams.startFace?e.faceMatchAssociatedParams.currentDetectedFace:e.faceMatchAssociatedParams.startFace,initialFaceMatchTime:void 0===e.faceMatchAssociatedParams.initialFaceMatchTime?Date.now():e.faceMatchAssociatedParams.initialFaceMatchTime})}),resetErrorState:r.assign({errorState:e=>{}}),updateErrorStateForTimeout:r.assign({errorState:(e,t)=>{var a;return(null===(a=t.data)||void 0===a?void 0:a.errorState)||F.TIMEOUT}}),updateErrorStateForRuntime:r.assign({errorState:(e,t)=>{var a;return(null===(a=t.data)||void 0===a?void 0:a.errorState)||F.RUNTIME_ERROR}}),updateErrorStateForServer:r.assign({errorState:e=>F.SERVER_ERROR}),clearErrorState:r.assign({errorState:e=>{}}),updateSessionInfo:r.assign({serverSessionInformation:(e,t)=>t.data.sessionInfo}),updateShouldDisconnect:r.assign({shouldDisconnect:e=>!0}),updateFreshnessDetails:r.assign({freshnessColorAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorsComplete:t.data.freshnessColorsComplete})}),setupFlashFreshnessColors:r.assign({freshnessColorAssociatedParams:e=>{const{serverSessionInformation:t}=e,a=(t.Challenge.FaceMovementAndLightChallenge.ColorSequences||[]).map((({FreshnessColor:e,DownscrollDuration:t,FlatDisplayDuration:a})=>{const i=e.RGB,r=`rgb(${i[0]},${i[1]},${i[2]})`;return void 0!==r&&void 0!==t&&void 0!==a?{color:r,downscrollDuration:t,flatDisplayDuration:a}:void 0})).filter(q);const i=new oe(e,a);return Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorDisplay:i})}}),sendTimeoutAfterOvalDrawingDelay:r.actions.send({type:"TIMEOUT"},{delay:5e3,id:"ovalDrawingTimeout"}),cancelOvalDrawingTimeout:r.actions.cancel("ovalDrawingTimeout"),sendTimeoutAfterOvalMatchDelay:r.actions.send({type:"TIMEOUT"},{delay:e=>{var t,a,i,r;return(null===(r=null===(i=null===(a=null===(t=e.serverSessionInformation)||void 0===t?void 0:t.Challenge)||void 0===a?void 0:a.FaceMovementAndLightChallenge)||void 0===i?void 0:i.ChallengeConfig)||void 0===r?void 0:r.OvalFitTimeout)||7e3},id:"ovalMatchTimeout"}),cancelOvalMatchTimeout:r.actions.cancel("ovalMatchTimeout"),sendTimeoutAfterWaitingForDisconnect:r.actions.send({type:"TIMEOUT",data:{errorState:F.SERVER_ERROR}},{delay:2e4,id:"waitForDisconnectTimeout"}),cancelWaitForDisconnectTimeout:r.actions.cancel("waitForDisconnectTimeout"),sendTimeoutAfterFaceDistanceDelay:r.actions.send({type:"RUNTIME_ERROR",data:new Error("Avoid moving closer during countdown and ensure only one face is in front of camera.")},{delay:0,id:"faceDistanceTimeout"}),cancelFaceDistanceTimeout:r.actions.cancel("faceDistanceTimeout"),callUserPermissionDeniedCallback:r.assign({errorState:(e,t)=>{var a,i;let r;r=t.data.message.includes("15 fps")?F.CAMERA_FRAMERATE_ERROR:F.CAMERA_ACCESS_ERROR;const n=t.data.message||t.data.Message,o={state:r,error:new Error(n)};return null===(i=(a=e.componentProps).onError)||void 0===i||i.call(a,o),r}}),callMobileLandscapeWarningCallback:r.assign({errorState:e=>F.MOBILE_LANDSCAPE_ERROR}),callUserCancelCallback:t=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,a;null===(a=(e=t.componentProps).onUserCancel)||void 0===a||a.call(e)})),callUserTimeoutCallback:t=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,a;const i=new Error("Client Timeout");i.name=t.errorState;const r={state:t.errorState,error:i};null===(a=(e=t.componentProps).onError)||void 0===a||a.call(e,r)})),callErrorCallback:(t,a)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,i,r;const n={state:t.errorState,error:(null===(e=a.data)||void 0===e?void 0:e.error)||a.data};null===(r=(i=t.componentProps).onError)||void 0===r||r.call(i,n)})),cleanUpResources:t=>e.__awaiter(void 0,void 0,void 0,(function*(){var e;const{freshnessColorEl:a}=t.freshnessColorAssociatedParams;a&&(a.style.display="none");let i=O;t.errorState===F.TIMEOUT?i=b:t.errorState===F.RUNTIME_ERROR?i=k:t.errorState===F.FACE_DISTANCE_ERROR||t.errorState===F.MULTIPLE_FACES_ERROR?i=L:void 0===t.errorState&&(i=P),yield null===(e=t.livenessStreamProvider)||void 0===e?void 0:e.endStreamWithCode(i)})),freezeStream:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const{videoMediaStream:e,videoEl:a}=t.videoAssociatedParams;t.isRecordingStopped=!0,null==a||a.pause(),null==e||e.getTracks().forEach((function(e){e.stop()}))})),pauseVideoStream:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const{videoEl:e}=t.videoAssociatedParams;t.isRecordingStopped=!0,e.pause()})),resetContext:r.assign({challengeId:f.nanoid(),maxFailedAttempts:0,failedAttempts:0,componentProps:e=>e.componentProps,serverSessionInformation:e=>{},videoAssociatedParams:e=>({videoConstraints:ue}),ovalAssociatedParams:e=>{},errorState:e=>{},livenessStreamProvider:e=>{},responseStreamActorRef:e=>{},shouldDisconnect:!1,faceMatchStateBeforeStart:e=>{},isFaceFarEnoughBeforeRecording:e=>{},isRecordingStopped:!1})},guards:{shouldTimeoutOnFailedAttempts:e=>e.failedAttempts>=e.maxFailedAttempts,hasFaceMatchedInOvalWithMinTime:e=>{const{faceMatchState:t,initialFaceMatchTime:a}=e.faceMatchAssociatedParams,i=Date.now()-a;return t===y.MATCHED&&i>=500},hasFaceMatchedInOval:e=>e.faceMatchAssociatedParams.faceMatchState===y.MATCHED,hasNotFaceMatchedInOval:e=>e.faceMatchAssociatedParams.faceMatchState!==y.MATCHED,hasSingleFace:e=>e.faceMatchAssociatedParams.faceMatchState===y.FACE_IDENTIFIED,hasSingleFaceBeforeStart:e=>e.faceMatchStateBeforeStart===y.FACE_IDENTIFIED,hasEnoughFaceDistanceBeforeRecording:e=>e.isFaceFarEnoughBeforeRecording,hasNotEnoughFaceDistanceBeforeRecording:e=>!e.isFaceFarEnoughBeforeRecording,hasLivenessCheckSucceeded:(e,t,a)=>a.state.event.data.isLive,hasFreshnessColorShown:e=>e.freshnessColorAssociatedParams.freshnessColorsComplete,hasServerSessionInfo:e=>void 0!==e.serverSessionInformation,hasDOMAndCameraDetails:e=>void 0!==e.videoAssociatedParams.videoEl&&void 0!==e.videoAssociatedParams.canvasEl&&void 0!==e.freshnessColorAssociatedParams.freshnessColorEl,getShouldDisconnect:e=>!!e.shouldDisconnect,hasRecordingStarted:e=>void 0!==e.livenessStreamProvider.videoRecorder.firstChunkTimestamp},services:{checkVirtualCameraAndGetStream(t){return e.__awaiter(this,void 0,void 0,(function*(){const{videoConstraints:e}=t.videoAssociatedParams,a=yield navigator.mediaDevices.getUserMedia({video:e,audio:!1}),i=(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind)).filter((e=>!function(e){return e.label.toLowerCase().includes("virtual")}(e)));if(!i.length)throw new Error("No real video devices found");const r=a.getTracks().filter((e=>e.getSettings().frameRate>=15));if(r.length<1)throw new Error("No camera found with more than 15 fps");const n=r[0].getSettings().deviceId;let o=a;return i.some((e=>e.deviceId===n))||(o=yield navigator.mediaDevices.getUserMedia({video:Object.assign(Object.assign({},e),{deviceId:{exact:i[0].deviceId}}),audio:!1})),{stream:o}}))},openLivenessStreamConnection(t){return e.__awaiter(this,void 0,void 0,(function*(){const{config:e}=t.componentProps,{credentialProvider:a}=e,i=new re({sessionId:t.componentProps.sessionId,region:t.componentProps.region,stream:t.videoAssociatedParams.videoMediaStream,videoEl:t.videoAssociatedParams.videoEl,credentialProvider:a});return me=i.getResponseStream(),{livenessStreamProvider:i}}))},detectFace(t){return e.__awaiter(this,void 0,void 0,(function*(){const{videoEl:a}=t.videoAssociatedParams,{faceDetector:i}=t.ovalAssociatedParams;try{yield i.modelLoadingPromise}catch(e){console.log({err:e})}const r=yield function(t,a){return e.__awaiter(this,void 0,void 0,(function*(){let e;switch((yield t.detectFaces(a)).length){case 0:e=y.CANT_IDENTIFY;break;case 1:e=y.FACE_IDENTIFIED;break;default:e=y.TOO_MANY}return e}))}(i,a);return{faceMatchState:r}}))},detectFaceDistance(t){return e.__awaiter(this,void 0,void 0,(function*(){const{isFaceFarEnoughBeforeRecording:e}=t,{videoEl:a,videoMediaStream:i,isMobile:r}=t.videoAssociatedParams,{faceDetector:n}=t.ovalAssociatedParams,{width:o,height:s}=i.getTracks()[0].getSettings(),c=W({width:o,height:s}),{isDistanceBelowThreshold:l}=yield $({faceDetector:n,videoEl:a,ovalDetails:c,reduceThreshold:e,isMobile:r});return{isFaceFarEnoughBeforeRecording:l}}))},detectFaceDistanceWhileLoading(t){return e.__awaiter(this,void 0,void 0,(function*(){const{isFaceFarEnoughBeforeRecording:e}=t,{videoEl:a,videoMediaStream:i,isMobile:r}=t.videoAssociatedParams,{faceDetector:n}=t.ovalAssociatedParams,{width:o,height:s}=i.getTracks()[0].getSettings(),c=W({width:o,height:s}),{isDistanceBelowThreshold:l,error:d}=yield $({faceDetector:n,videoEl:a,ovalDetails:c,reduceThreshold:e,isMobile:r});return{isFaceFarEnoughBeforeRecording:l,error:d}}))},detectInitialFaceAndDrawOval(t){return e.__awaiter(this,void 0,void 0,(function*(){const{serverSessionInformation:e,livenessStreamProvider:a}=t,{videoEl:i,canvasEl:r,isMobile:n}=t.videoAssociatedParams,{faceDetector:o}=t.ovalAssociatedParams;try{yield o.modelLoadingPromise,yield a.videoRecorder.recorderStarted}catch(e){console.log({err:e})}const s=yield o.detectFaces(i);let c,l,d;switch(s.length){case 0:l=y.CANT_IDENTIFY,d=z(i);break;case 1:l=y.FACE_IDENTIFIED,c=s[0];break;default:l=y.TOO_MANY}if(!c)return{faceMatchState:l,illuminationState:d};const{width:h,height:u}=i.getBoundingClientRect();n?(r.width=window.innerWidth,r.height=window.innerHeight):(r.width=h,r.height=u);const m=h/i.videoWidth,f=function({sessionInformation:e,videoWidth:t}){var a,i;const r=null===(i=null===(a=null==e?void 0:e.Challenge)||void 0===a?void 0:a.FaceMovementAndLightChallenge)||void 0===i?void 0:i.OvalParameters;if(!(r&&r.CenterX&&r.CenterY&&r.Width&&r.Height))throw new Error("Oval parameters not returned from session information.");return{flippedCenterX:t-r.CenterX,centerX:r.CenterX,centerY:r.CenterY,width:r.Width,height:r.Height}}({sessionInformation:e,videoWidth:i.width}),v=j(c,f);return c.top=v.top,c.left=v.left,c.height=v.bottom-v.top,c.width=v.right-v.left,function({canvas:e,oval:t,scaleFactor:a,videoEl:i}){const{flippedCenterX:r,centerY:n,width:o,height:s}=t,{width:c,height:l}=e.getBoundingClientRect(),d=e.getContext("2d");if(!d)throw new Error("Cannot find Canvas.");{d.clearRect(0,0,c,l),d.fillStyle="rgba(255, 255, 255, 1.0)",d.fillRect(0,0,c,l);const e={width:i.videoWidth,height:i.videoHeight},t={x:(c-e.width*a)/2,y:(l-e.height*a)/2};d.setTransform(a,0,0,a,t.x,t.y),d.beginPath(),d.ellipse(r,n,o/2,s/2,0,0,2*Math.PI),d.strokeStyle="#AEB3B7",d.lineWidth=3,d.stroke(),d.clip(),d.setTransform(1,0,0,1,0,0),d.clearRect(0,0,c,l)}}({canvas:r,oval:f,scaleFactor:m,videoEl:i}),{faceMatchState:l,ovalDetails:f,scaleFactor:m,initialFace:c}}))},detectFaceAndMatchOval(t){return e.__awaiter(this,void 0,void 0,(function*(){const{serverSessionInformation:e}=t,{videoEl:a}=t.videoAssociatedParams,{faceDetector:i,ovalDetails:r,initialFace:n}=t.ovalAssociatedParams,o=yield i.detectFaces(a);let s,c,l,d=0;const h=j(n,r),{ovalBoundingBox:u}=H(r),m=B(h,u);switch(o.length){case 0:s=y.CANT_IDENTIFY,l=z(a);break;case 1:{c=o[0];const{faceMatchState:t,faceMatchPercentage:a}=function(e,t,a,i){var r,n;let o;const s=null===(n=null===(r=null==i?void 0:i.Challenge)||void 0===r?void 0:r.FaceMovementAndLightChallenge)||void 0===n?void 0:n.ChallengeConfig;if(!(s&&s.OvalIouThreshold&&s.OvalIouHeightThreshold&&s.OvalIouWidthThreshold&&s.FaceIouHeightThreshold&&s.FaceIouWidthThreshold))throw new Error("Challenge information not returned from session information.");const{OvalIouThreshold:c,OvalIouHeightThreshold:l,OvalIouWidthThreshold:d,FaceIouHeightThreshold:h,FaceIouWidthThreshold:u}=s,m=j(e,t),f=m.left,v=m.right,g=m.top,p=m.bottom,{ovalBoundingBox:E,minOvalX:T,minOvalY:C,maxOvalX:S,maxOvalY:F}=H(t),x=B(m,E),R=c,M=t.width*d,A=t.height*l,w=t.width*u,_=t.height*h,D=100*Math.max(Math.min(1,.75*(x-a)/(R-a)+.25),0);return o=x>R&&Math.abs(T-f)<M&&Math.abs(S-v)<M&&Math.abs(F-p)<A?y.MATCHED:C-g>_||p-F>_||T-f>w&&v-S>w?y.TOO_CLOSE:y.TOO_FAR,{faceMatchState:o,faceMatchPercentage:D}}(c,r,m,e);s=t,d=a;break}default:s=y.TOO_MANY}return{faceMatchState:s,faceMatchPercentage:d,illuminationState:l,detectedFace:c}}))},flashColors(t){return e.__awaiter(this,void 0,void 0,(function*(){const{freshnessColorsComplete:e,freshnessColorDisplay:a}=t.freshnessColorAssociatedParams;if(e)return;return{freshnessColorsComplete:yield a.displayColorTick()}}))},stopVideo(t){return e.__awaiter(this,void 0,void 0,(function*(){const{challengeId:e,livenessStreamProvider:a}=t,{videoMediaStream:i}=t.videoAssociatedParams,{initialFace:r,ovalDetails:n}=t.ovalAssociatedParams,{startFace:o,endFace:s}=t.faceMatchAssociatedParams,{width:c,height:l}=i.getTracks()[0].getSettings(),d=c-r.left-r.width;yield a.stopVideo();const h={Challenge:{FaceMovementAndLightChallenge:{ChallengeId:e,InitialFace:{InitialFaceDetectedTimestamp:r.timestampMs,BoundingBox:G({deviceHeight:l,deviceWidth:c,height:r.height,width:r.width,top:r.top,left:d})},TargetFace:{FaceDetectedInTargetPositionStartTimestamp:o.timestampMs,FaceDetectedInTargetPositionEndTimestamp:s.timestampMs,BoundingBox:G({deviceHeight:l,deviceWidth:c,height:n.height,width:n.width,top:n.centerY-n.height/2,left:n.centerX-n.width/2})},VideoEndTimestamp:a.videoRecorder.recorderEndTimestamp}}};if(0===a.videoRecorder.getVideoChunkSize())throw new Error("Video chunks not recorded successfully.");a.sendClientInfo(h),yield a.dispatchStopVideoEvent()}))},getLiveness(t){return e.__awaiter(this,void 0,void 0,(function*(){const{onAnalysisComplete:e}=t.componentProps;yield e()}))}}}),ve=t=>e.__awaiter(void 0,void 0,void 0,(function*(){var a,i,r,n,o;try{const d=yield me;try{for(var s,c=!0,l=e.__asyncValues(d);!(a=(s=yield l.next()).done);){n=s.value,c=!1;try{const e=n;(null==(o=e)?void 0:o.ServerSessionInformationEvent)?t({type:"SET_SESSION_INFO",data:{sessionInfo:e.ServerSessionInformationEvent.SessionInformation}}):se(e)?t({type:"DISCONNECT_EVENT"}):ce(e)?t({type:"SERVER_ERROR",data:{error:Object.assign({},e.ValidationException)}}):le(e)?t({type:"SERVER_ERROR",data:{error:Object.assign({},e.InternalServerException)}}):de(e)?t({type:"SERVER_ERROR",data:{error:Object.assign({},e.ThrottlingException)}}):he(e)&&t({type:"SERVER_ERROR",data:{error:Object.assign({},e.ServiceQuotaExceededException)}})}finally{c=!0}}}catch(e){i={error:e}}finally{try{c||a||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}}catch(e){let a=e;(e=>{const{message:t,name:a}=e;return"InvalidSignatureException"===a&&t.includes("valid region")})(e)&&(a=new Error("Invalid region in FaceLivenessDetector or credentials are scoped to the wrong region.")),a instanceof Error&&t({type:"SERVER_ERROR",data:{error:a}})}})),ge=x.default.createContext(null);function pe(t){var{children:a}=t,i=e.__rest(t,["children"]);return x.default.createElement(ge.Provider,{value:i},a)}function Ee(){const e=x.default.useContext(ge);if(null===e)throw new Error("useFaceLivenessDetector must be used within a FaceLivenessDetectorProvider");return e}function Te(){const{service:e}=Ee();return i.useActor(e)}function Ce(e){const{service:t}=Ee();return i.useSelector(t,e)}var Se;!function(e){e.CameraModule="amplify-liveness-camera-module",e.CancelContainer="amplify-liveness-cancel-container",e.CancelButton="amplify-liveness-cancel-button",e.CountdownContainer="amplify-liveness-countdown-container",e.DescriptionBullet="amplify-liveness-description-bullet",e.DescriptionBulletIndex="amplify-liveness-description-bullet__index",e.DescriptionBulletIndexText="amplify-liveness-description-bullet__index__text",e.DescriptionBulletMessage="amplify-liveness-description-bullet__message",e.ErrorModal="amplify-liveness-error-modal",e.ErrorModalHeading="amplify-liveness-error-modal__heading",e.FadeOut="amplify-liveness-fade-out",e.FreshnessCanvas="amplify-liveness-freshness-canvas",e.InstructionList="amplify-liveness-instruction-list",e.InstructionOverlay="amplify-liveness-instruction-overlay",e.Figure="amplify-liveness-figure",e.FigureCaption="amplify-liveness-figure__caption",e.FigureIcon="amplify-liveness-figure__icon",e.FigureImage="amplify-liveness-figure__image",e.Figures="amplify-liveness-figures",e.Hint="amplify-liveness-hint",e.HintText="amplify-liveness-hint__text",e.LandscapeErrorModal="amplify-liveness-landscape-error-modal",e.LandscapeErrorModalButton="amplify-liveness-landscape-error-modal__button",e.LandscapeErrorModalHeader="amplify-liveness-landscape-error-modal__header",e.Loader="amplify-liveness-loader",e.MatchIndicator="amplify-liveness-match-indicator",e.OvalCanvas="amplify-liveness-oval-canvas",e.OpaqueOverlay="amplify-liveness-overlay-opaque",e.Overlay="amplify-liveness-overlay",e.Popover="amplify-liveness-popover",e.PopoverContainer="amplify-liveness-popover__container",e.PopoverAnchor="amplify-liveness-popover__anchor",e.PopoverAnchorSecondary="amplify-liveness-popover__anchor-secondary",e.RecordingIconContainer="amplify-liveness-recording-icon-container",e.RecordingIcon="amplify-liveness-recording-icon",e.StartScreenHeader="amplify-liveness-start-screen-header",e.StartScreenHeaderBody="amplify-liveness-start-screen-header__body",e.StartScreenHeaderHeading="amplify-liveness-start-screen-header__heading",e.StartScreenWarning="amplify-liveness-start-screen-warning",e.StartScreenInstructions="amplify-liveness-start-screen-instructions",e.StartScreenInstructionsHeading="amplify-liveness-start-screen-instructions__heading",e.Toast="amplify-liveness-toast",e.ToastContainer="amplify-liveness-toast__container",e.ToastMessage="amplify-liveness-toast__message",e.Video="amplify-liveness-video",e.VideoAnchor="amplify-liveness-video-anchor"}(Se||(Se={}));const ye=({ariaLabel:e})=>{const[t,a]=Te();return t.done?null:x.default.createElement(v.Button,{autoFocus:!0,variation:"link",onClick:()=>{a({type:"CANCEL"})},size:"large",className:Se.CancelButton,"aria-label":e},x.default.createElement(g.IconClose,{"aria-hidden":"true","data-testid":"close-icon"}))},Fe=t=>{var{variation:a="default",size:i="medium",children:r}=t,n=e.__rest(t,["variation","size","children"]);return R.createElement(v.View,Object.assign({className:`${Se.Toast} ${Se.Toast}--${a} ${Se.Toast}--${i}`,maxWidth:{base:"100%",small:"70%"}},n),R.createElement(v.Flex,{className:Se.ToastContainer},R.createElement(v.Flex,{className:Se.ToastMessage},r)))},xe=t=>{var{children:a,anchorOrigin:i={horizontal:"center",vertical:"center"},className:r}=t,n=e.__rest(t,["children","anchorOrigin","className"]);return R.createElement(v.Flex,Object.assign({className:`${Se.Overlay} ${r}`,alignItems:i.horizontal,justifyContent:i.vertical},n),a)},Re=e=>e.context.errorState,Me=e=>e.context.faceMatchAssociatedParams.faceMatchState,Ae=e=>e.context.faceMatchAssociatedParams.illuminationState,we=e=>e.context.isFaceFarEnoughBeforeRecording,_e=e=>e.context.faceMatchStateBeforeStart,De=({hintDisplayText:e})=>{const[t]=Te(),a=Ce(Re),i=Ce(Me),r=Ce(Ae),n=Ce(_e),o=Ce(we),s=t.matches("checkFaceDetectedBeforeStart"),c=t.matches("checkFaceDistanceBeforeRecording"),l=t.matches("recording"),d=t.matches("notRecording"),h=t.matches("uploading"),u=t.matches("checkSucceeded"),m=t.matches("checkFailed"),f=t.matches({recording:"flashFreshnessColors"}),g={[y.CANT_IDENTIFY]:e.hintCanNotIdentifyText,[y.FACE_IDENTIFIED]:e.hintTooFarText,[y.TOO_MANY]:e.hintTooManyFacesText,[y.TOO_CLOSE]:e.hintTooCloseText,[y.TOO_FAR]:e.hintTooFarText,[y.MATCHED]:e.hintHoldFaceForFreshnessText},p={[S.BRIGHT]:e.hintIlluminationTooBrightText,[S.DARK]:e.hintIlluminationTooDarkText,[S.NORMAL]:e.hintIlluminationNormalText},E=(()=>{if(!(a||m||u)){if(!l){if(s)return n===y.TOO_MANY?R.createElement(Fe,null,g[n]):R.createElement(Fe,null,e.hintMoveFaceFrontOfCameraText);if(c&&!1===o)return R.createElement(Fe,null,e.hintTooCloseText);if(d)return R.createElement(Fe,null,R.createElement(v.Flex,{className:Se.HintText},R.createElement(v.Loader,null),R.createElement(v.View,null,e.hintConnectingText)));if(h)return R.createElement(xe,{className:Se.OpaqueOverlay,anchorOrigin:{horizontal:"center",vertical:"end"}},R.createElement(Fe,null,R.createElement(v.Flex,{className:Se.HintText},R.createElement(v.Loader,null),R.createElement(v.View,null,e.hintVerifyingText))));if(r&&r!==S.NORMAL)return R.createElement(Fe,null,p[r])}return f?R.createElement(Fe,{size:"large",variation:"primary"},e.hintHoldFaceForFreshnessText):l&&!f?R.createElement(Fe,{size:"large",variation:i===y.TOO_CLOSE?"error":"primary"},i===y.TOO_CLOSE?g[y.TOO_CLOSE]:g[y.TOO_FAR]):null}})();return E||null},Ie=({children:e})=>x.default.createElement(v.Flex,{className:Se.RecordingIcon},x.default.createElement(v.Flex,{"data-testid":"rec-icon",justifyContent:"center"},x.default.createElement(v.Icon,{viewBox:{width:20,height:20},width:"20",height:"20"},x.default.createElement("circle",{cx:"10",cy:"10",r:"8",fill:"red"}))),x.default.createElement(v.Text,{as:"span",fontWeight:"bold"},e)),Oe=t=>{var{children:a,caption:i,variation:r="default"}=t,n=e.__rest(t,["children","caption","variation"]);return x.default.createElement(v.Flex,Object.assign({as:"figure",className:`${Se.Figure} ${Se.Figure}--${r}`},n),x.default.createElement(v.View,{className:`${Se.FigureImage} ${Se.FigureImage}--${r}`},"success"===r?x.default.createElement("svg",{className:Se.FigureIcon,"aria-hidden":"true",width:"24",height:"24"},x.default.createElement("g",{fill:"none"},x.default.createElement("path",{fill:"#365E3D",d:"M0 0h24v24H0z"}),x.default.createElement("path",{fill:"#FFF",d:"m9.435 15.62-4.054-4.055L4 12.936l5.435 5.435L21.101 6.704l-1.37-1.371z"}))):null,"error"===r?x.default.createElement("svg",{className:Se.FigureIcon,"aria-hidden":"true",width:"24",height:"24"},x.default.createElement("g",{fill:"none"},x.default.createElement("path",{fill:"#600",d:"M0 0h24v24H0z"}),x.default.createElement("path",{fill:"#FFF",d:"M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}))):null,a),x.default.createElement(v.View,{as:"figcaption",className:`${Se.FigureCaption} ${Se.FigureCaption}--${r}`},i))},be=({title:e,testId:t})=>x.default.createElement("svg",{width:"150",height:"150","data-testid":t},x.default.createElement("title",null,e),x.default.createElement("g",{fill:"none",fillRule:"evenodd",transform:"translate(0 -.001)"},x.default.createElement("path",{fill:"#5B361E",fillRule:"nonzero",d:"M124.655 0c9.173 8.155 9.394 17.812 13.258 32.385l.053.336.108.726.11.796.112.864.114.931.174 1.515.117 1.087.18 1.739.12 1.23.183 1.944.123 1.36.186 2.13.187 2.232.313 3.928.25 3.31.25 3.443.31 4.463.245 3.679.36 5.658.345 5.778.33 5.841.26 4.876.199 3.883.187 3.849.217 4.738.16 3.712.178 4.515.097 2.63v34.977L.519 150 .517 41.97c3-13.353 9.664-29.4 23.841-41.97h100.297Z"}),x.default.createElement("path",{fill:"#FCDDCC",fillRule:"nonzero",stroke:"#000",d:"m50.469 18.849.145.153c9.021 9.393 22.62 16.197 36.089 21.996l2.1.897 1.05.443 2.089.876 8.176 3.385 1.979.825 1.944.82c7.782 3.3 14.617 6.491 19.213 10.006 3.57 2.73 5.793 5.645 5.924 8.999v20.474l-.008.624-.016.669-.04 1.089-.04.777-.047.815-.06.853-.068.887-.08.918-.093.95-.104.978-.057.496-.123 1.016-.066.513-.144 1.049-.076.527-.165 1.077c-.057.36-.116.724-.178 1.086l-.193 1.103-.21 1.116-.11.557-.233 1.13c-.12.564-.247 1.13-.38 1.694l-.275 1.14c-1.037 4.147-2.426 8.3-4.271 11.978-6.17 9.34-12.996 16.035-19.28 20.691l-.8.584-.794.562-.784.539-1.165.77-1.147.724-.755.459c-.249.148-.497.294-.74.434l-.73.416-1.078.588-.702.367-1.033.517-.671.321-.657.303-.643.285-.541.23H68.149a75.81 75.81 0 0 1-.81-.284l-.918-.336a75.953 75.953 0 0 1-.935-.355l-.963-.382a85.513 85.513 0 0 1-1.988-.83l-1.032-.455c-.52-.233-1.05-.475-1.585-.727l-1.087-.517-1.113-.547c-.935-.465-1.893-.959-2.873-1.482l-1.193-.644a141.053 141.053 0 0 1-6.297-3.669l-1.33-.83c-17.11-10.783-22.636-33.458-23.66-49.98l-.071-1.267c-.02-.417-.038-.83-.053-1.235l-.037-1.212a86.317 86.317 0 0 1 .042-5.559l.047-1.002.06-.96.064-.843c1.09-2.51 2.164-4.304 3.296-5.882l.408-.558.415-.545.421-.538 2.026-2.492.481-.597.493-.624.507-.656.518-.69a61.722 61.722 0 0 0 3.769-5.754c4.03-6.917 7.127-14.806 9.544-21.668l.566-1.623.802-2.344 2.077-6.175.416-1.205.395-1.109.373-1.007.267-.682.253-.612c.47-.943.8-1.531 1.06-1.876l-.035.047Z"}),x.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"m94.566 121.353.722.895c-6.828 5.51-14.13 7.462-21.382 6.447-5.417-.758-10.535-3.2-13.987-6.186l-.318-.282.77-.854c3.285 2.964 8.343 5.434 13.694 6.183 6.797.95 13.632-.819 20.089-5.876l.412-.327Z"}),x.default.createElement("ellipse",{cx:"51.331",cy:"80.698",fill:"#000",fillRule:"nonzero",rx:"4.886",ry:"6.707"}),x.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"M42.539 63.719c4.453-2.586 11.355-3.268 17.22-.195l.35.19-.556 1.005c-5.437-3.01-11.946-2.479-16.175-.153l-.262.148-.577-.995Z"}),x.default.createElement("ellipse",{cx:"103.281",cy:"80.698",fill:"#000",fillRule:"nonzero",rx:"4.886",ry:"6.707"}),x.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"M94.492 63.719c4.453-2.586 11.355-3.268 17.22-.195l.35.19-.557 1.005c-5.436-3.01-11.946-2.479-16.174-.153l-.262.148-.577-.995Zm-22.972 32.9c0 4.216 2.006 7.72 5.831 7.48l.232-.018.115 1.144c-4.774.477-7.239-3.571-7.326-8.345l-.003-.26 1.15-.001h.001Z"}),x.default.createElement("path",{fill:"#FFF",fillRule:"nonzero",d:"M75.002.001H0v150h150v-150H75.002Zm0 0c25.627 0 46.402 33.579 46.402 75s-20.775 75-46.402 75c-25.627 0-46.402-33.579-46.402-75s20.775-75 46.402-75Z"}),x.default.createElement("path",{stroke:"#AEB3B7",strokeWidth:"2",d:"M120.921 75.001c0 20.555-5.214 39.117-13.589 52.507-8.386 13.406-19.838 21.493-32.313 21.493-12.476 0-23.928-8.087-32.312-21.493-8.377-13.39-13.59-31.952-13.59-52.507 0-20.555 5.214-39.116 13.589-52.507C51.091 9.09 62.543 1.001 75.018 1.001c12.476 0 23.928 8.088 32.314 21.493 8.375 13.39 13.588 31.952 13.588 52.507h.001Z"}))),Pe=({title:e,testId:t})=>x.default.createElement("svg",{width:"150",height:"150","data-testid":t},x.default.createElement("title",null,e),x.default.createElement("defs",null,x.default.createElement("linearGradient",{id:"a",x1:"50%",x2:"50%",y1:"0%",y2:"100%"},x.default.createElement("stop",{offset:"0%",stopColor:"#C2C2C2"}),x.default.createElement("stop",{offset:"100%",stopColor:"#C2C2C2",stopOpacity:"0"}))),x.default.createElement("g",{fill:"none",fillRule:"evenodd",transform:"translate(2)"},x.default.createElement("path",{fill:"#FFF",fillRule:"nonzero",d:"M3.997 0h136v150h-136z"}),x.default.createElement("path",{fill:"url(#a)",fillRule:"nonzero",d:"M4.333 0h138v150h-138z"}),x.default.createElement("path",{fill:"#5B361E",fillRule:"nonzero",stroke:"#000",strokeWidth:"1.353",d:"m22.515 58.137-1.895 82.434 98.784-2.343c0-8.798.813-16.271.813-31.497 0-15.748-2.345-55.36-3.766-64.125C108.16 11.338 74.737 5.03 56.707 11.04c-28.425 9.475-33.64 35.095-34.192 47.097Z"}),x.default.createElement("path",{fill:"#EF992A",fillRule:"nonzero",d:"M38.104 138.228c8.339-3.98 5.1-1.525 15.916-3.104H90.5c5.448 0 9.541 3.104 28.904 3.104 6.391 0 5.987 8.988-2.473 8.988-24.315 1.08-66.07 1.08-78.281 0-77.975-6.896-10.97-4.014-.546-8.988Z"}),x.default.createElement("path",{fill:"#FCDDCC",fillRule:"nonzero",stroke:"#000",strokeWidth:"1.353",d:"m54.306 134.26 2.645-21.765h30.498l3.05 21.765c-15.778 14.791-30.703 6.163-36.193 0zm-27.59-54.458C25.42 66.68 33.467 67.18 37.653 69.07l2.837 25.314c-10.328-2.228-13.772-12.961-13.772-14.58zm89.512-.81c4.05-15.067-3.984-15.998-8.506-14.58L105.9 91.75c10.328-8.505 9.113-12.758 10.328-12.758z"}),x.default.createElement("path",{fill:"#FCDDCC",fillRule:"nonzero",stroke:"#000",strokeWidth:"1.353",d:"M53.564 109.804c-14.195-8.986-16.116-30.658-15.302-40.37 2.24-5.21 4.37-5.723 7.958-11.909 6.3-10.86 9.028-25.451 10.579-25.009 14.241 16.008 50.215 20.259 50.649 31.708v13.023c0 4.178-.911 14.358-4.558 21.65-8.986 13.674-20.131 18.612-24.58 19.372-2.334.922-10.55.521-24.746-8.465Z"}),x.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"m83.935 98.402.85 1.052c-7.974 6.435-17.2 5.243-23.018.18l-.23-.204.905-1.004c5.273 4.756 13.744 5.998 21.175.227l.318-.251Z"}),x.default.createElement("ellipse",{cx:"56.448",cy:"72.613",fill:"#000",fillRule:"nonzero",rx:"3.128",ry:"4.294"}),x.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"M50.664 61.476c2.917-1.694 7.404-2.147 11.244-.172l.31.165-.655 1.183c-3.348-1.854-7.361-1.545-9.985-.137l-.234.13-.68-1.17Z"}),x.default.createElement("ellipse",{cx:"89.709",cy:"72.613",fill:"#000",fillRule:"nonzero",rx:"3.128",ry:"4.294"}),x.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"M83.926 61.476c2.917-1.694 7.404-2.147 11.244-.172l.31.165-.655 1.183c-3.348-1.854-7.361-1.545-9.985-.137l-.234.13-.68-1.17Z"}),x.default.createElement("path",{stroke:"#000",strokeWidth:"1.353",d:"M69.005 82.806c0 1.858.859 5.487 4.287 5.144"}),x.default.createElement("path",{fill:"#FFF",d:"M73.004 0H0v150h146V0H73.004Zm.496 0C98.629 0 119 33.579 119 75s-20.371 75-45.5 75S28 116.421 28 75 48.371 0 73.5 0Z"}),x.default.createElement("path",{stroke:"#AEB3B7",strokeWidth:"2",d:"M118.4 75c0 20.555-5.156 39.117-13.441 52.507C96.665 140.913 85.338 149 72.999 149c-12.34 0-23.667-8.087-31.961-21.493C32.753 114.117 27.597 95.555 27.597 75c0-20.555 5.156-39.117 13.44-52.507C49.333 9.087 60.66 1 72.999 1c12.34 0 23.667 8.087 31.961 21.493C113.244 35.883 118.4 54.445 118.4 75Z"}))),ke=({children:e})=>{const t=g.useThemeBreakpoint(),[a,i]=R.useState(!1),r=R.useRef(null),n="base"===t;return R.useEffect((()=>{function e(e){a&&r.current&&!r.current.contains(e.target)&&i(!1)}return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}}),[r,a]),R.createElement(v.Flex,{className:Se.Popover,onClick:()=>i(!a),ref:r,testId:"popover-icon"},R.createElement(g.AlertIcon,{ariaHidden:!0,variation:"info"}),a&&R.createElement(R.Fragment,null,R.createElement(v.Flex,{className:Se.PopoverAnchor}),R.createElement(v.Flex,{className:Se.PopoverAnchorSecondary}),R.createElement(v.Flex,{className:Se.PopoverContainer,left:n?-190:-108,"data-testid":"popover-text"},e)))};ke.displayName="LivenessIconWithPopover";const Le=({headingText:e,bodyText:t})=>x.default.createElement(v.View,{className:Se.StartScreenHeader},x.default.createElement(v.View,{className:Se.StartScreenHeaderHeading},e),x.default.createElement(v.View,{className:Se.StartScreenHeaderBody},t)),Ne=({headingText:e,bodyText:t,infoText:a})=>x.default.createElement(v.Flex,{className:`${v.ComponentClassNames.Alert} ${Se.StartScreenWarning}`},x.default.createElement(v.View,{flex:"1"},x.default.createElement(v.View,{className:v.ComponentClassNames.AlertHeading},e),x.default.createElement(v.View,{className:v.ComponentClassNames.AlertBody},t)),x.default.createElement(ke,null,a)),He=({headingText:e,goodFitCaptionText:t,goodFitAltText:a,tooFarCaptionText:i,tooFarAltText:r,steps:n})=>x.default.createElement(v.Flex,{direction:"column"},x.default.createElement(v.Text,{className:Se.StartScreenInstructionsHeading},e),x.default.createElement(v.Flex,{className:Se.Figures},x.default.createElement(Oe,{variation:"success",caption:t},x.default.createElement(be,{title:a})),x.default.createElement(Oe,{variation:"error",caption:i},x.default.createElement(Pe,{title:r}))),x.default.createElement(v.Flex,{as:"ol",className:Se.InstructionList},n.map(((e,t)=>x.default.createElement(v.Flex,{as:"li",key:t+1},x.default.createElement(v.Text,{as:"span","aria-hidden":"true"},t+1,"."),x.default.createElement(v.Text,{as:"span"},e)))))),Be="liveness-detector-start";function We(e){const{beginLivenessCheck:t,components:a,instructionDisplayText:i}=e;return R.createElement(v.Card,{className:Be,"data-testid":Be},R.createElement(v.Flex,{direction:"column"},(null==a?void 0:a.Header)?R.createElement(a.Header,null):R.createElement(Le,{headingText:i.instructionsHeaderHeadingText,bodyText:i.instructionsHeaderBodyText}),(null==a?void 0:a.PhotosensitiveWarning)?R.createElement(a.PhotosensitiveWarning,null):R.createElement(Ne,{headingText:i.photosensitivyWarningHeadingText,bodyText:i.photosensitivyWarningBodyText,infoText:i.photosensitivyWarningInfoText}),(null==a?void 0:a.Instructions)?R.createElement(a.Instructions,null):R.createElement(He,{headingText:i.instructionListHeadingText,goodFitCaptionText:i.goodFitCaptionText,goodFitAltText:i.goodFitAltText,tooFarCaptionText:i.tooFarCaptionText,tooFarAltText:i.tooFarAltText,steps:[i.instructionListStepOneText,i.instructionListStepTwoText,i.instructionListStepThreeText,i.instructionListStepFourText]}),R.createElement(v.Flex,{justifyContent:"center"},R.createElement(v.Button,{variation:"primary",type:"button",onClick:t},i.instructionsBeginCheckText))))}const Ve={timeoutHeaderText:"Time out",timeoutMessageText:"Face didn't fit inside oval in time limit. Try again and completely fill the oval with face in it.",faceDistanceHeaderText:"Forward movement detected",faceDistanceMessageText:"Avoid moving closer when connecting.",multipleFacesHeaderText:"Multiple faces detected",multipleFacesMessageText:"Ensure only one face is present in front of the camera when connecting.",clientHeaderText:"Client error",clientMessageText:"Check failed due to client issue",serverHeaderText:"Server issue",serverMessageText:"Cannot complete check due to server issue",landscapeHeaderText:"Landscape orientation not supported",landscapeMessageText:"Rotate your device to portrait (vertical) orientation.",portraitMessageText:"Ensure your device remains in portrait (vertical) orientation for the check’s duration.",tryAgainText:"Try again"},je=Object.assign({instructionsHeaderHeadingText:"Liveness check",instructionsHeaderBodyText:"You will go through a face verification process to prove that you are a real person.",instructionsBeginCheckText:"Begin check",photosensitivyWarningHeadingText:"Photosensitivity warning",photosensitivyWarningBodyText:"This check displays colored lights. Use caution if you are photosensitive.",photosensitivyWarningInfoText:"A small percentage of individuals may experience epileptic seizures when exposed to colored lights. Use caution if you, or anyone in your family, have an epileptic condition.",instructionListHeadingText:"Follow the instructions to complete the check:",goodFitCaptionText:"Good fit",goodFitAltText:"Ilustration of a person's face, perfectly fitting inside of an oval.",tooFarCaptionText:"Too far",tooFarAltText:"Illustration of a person's face inside of an oval; there is a gap between the perimeter of the face and the boundaries of the oval.",instructionListStepOneText:"When an oval appears, follow the instructions to fit your face in it.",instructionListStepTwoText:"Maximize your screen's brightness.",instructionListStepThreeText:"Make sure your face is not covered with sunglasses or a mask.",instructionListStepFourText:"Move to a well-lit place that is not in direct sunlight.",cameraMinSpecificationsHeadingText:"Camera does not meet minimum specifications",cameraMinSpecificationsMessageText:"Camera must support at least 320*240 resolution and 15 frames per second.",cameraNotFoundHeadingText:"Camera not accessible.",cameraNotFoundMessageText:"Check that camera is connected and camera permissions are enabled in settings before retrying.",retryCameraPermissionsText:"Retry",cancelLivenessCheckText:"Cancel Liveness check",recordingIndicatorText:"Rec",hintMoveFaceFrontOfCameraText:"Move face in front of camera",hintTooManyFacesText:"Ensure only one face is in front of camera",hintFaceDetectedText:"Face detected",hintCanNotIdentifyText:"Move face in front of camera",hintTooCloseText:"Move back",hintTooFarText:"Move closer",hintHoldFacePositionCountdownText:"Hold face position during countdown",hintConnectingText:"Connecting...",hintVerifyingText:"Verifying...",hintIlluminationTooBrightText:"Move to dimmer area",hintIlluminationTooDarkText:"Move to brighter area",hintIlluminationNormalText:"Lighting conditions normal",hintHoldFaceForFreshnessText:"Hold still"},Ve),ze=({errorState:e,overrideErrorDisplayText:t})=>{const a=Object.assign(Object.assign({},Ve),t);return e===F.CAMERA_ACCESS_ERROR||e===F.CAMERA_FRAMERATE_ERROR||e===F.MOBILE_LANDSCAPE_ERROR?null:(e=>{const{error:t,displayText:a}=e,{timeoutHeaderText:i,timeoutMessageText:r,faceDistanceHeaderText:n,faceDistanceMessageText:o,multipleFacesHeaderText:s,multipleFacesMessageText:c,clientHeaderText:l,clientMessageText:d,serverHeaderText:h,serverMessageText:u}=a;let m,f;switch(t){case F.TIMEOUT:m=i,f=r;break;case F.FACE_DISTANCE_ERROR:m=n,f=o;break;case F.MULTIPLE_FACES_ERROR:m=s,f=c;break;case F.RUNTIME_ERROR:m=l,f=d;break;case F.SERVER_ERROR:default:m=h,f=u}return x.default.createElement(x.default.Fragment,null,x.default.createElement(v.Flex,{className:Se.ErrorModal},x.default.createElement(g.AlertIcon,{ariaHidden:!0,variation:"error"}),x.default.createElement(v.Text,{className:Se.ErrorModalHeading},m)),f)})({error:e,displayText:a})},Ue=e=>{const{children:t,onRetry:a,displayText:i}=e,r=Object.assign(Object.assign({},Ve),i),{tryAgainText:n}=r;return x.default.createElement(xe,{className:Se.OpaqueOverlay},x.default.createElement(Fe,null,t,x.default.createElement(v.Flex,{justifyContent:"center"},x.default.createElement(v.Button,{variation:"primary",type:"button",onClick:a},n))))},qe=e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoMediaStream},Ye=e=>e.context.faceMatchAssociatedParams.faceMatchPercentage,$e=e=>e.context.faceMatchAssociatedParams.faceMatchState,Ge=x.default.createElement(v.Loader,{size:"large",className:Se.Loader,"data-testid":"centered-loader"}),Xe=x.default.memo((({percentage:e,initialPercentage:t=25,testId:a})=>{const[i,r]=x.default.useState(t);x.default.useEffect((()=>{r(e<0?0:e>100?100:e)}),[e]);const n={"--percentage":`${i}%`};return x.default.createElement("div",{className:Se.MatchIndicator,"data-testid":a},x.default.createElement("div",{className:`${Se.MatchIndicator}__bar`,style:n}))})),Ze=e=>{const{isMobileScreen:a,isRecordingStopped:i,streamDisplayText:r,hintDisplayText:n,errorDisplayText:o,components:s,testId:c}=e,{cancelLivenessCheckText:l,recordingIndicatorText:d}=r,{ErrorView:h=Ue}=null!=s?s:{},[u,m]=Te(),f=Ce(qe),g=Ce(Ye),E=Ce($e),T=Ce(Re),C=[y.TOO_FAR,y.CANT_IDENTIFY,y.FACE_IDENTIFIED,y.MATCHED],{videoRef:S,videoWidth:F,videoHeight:R}=function(e){const a=ue.height.ideal,i=ue.width.ideal,r=t.useRef(null),[n,o]=t.useState(a),[s,c]=t.useState(i);return t.useEffect((()=>{if(e){p.isObject(r.current)&&(r.current.srcObject=e);const{height:t,width:a}=e.getTracks()[0].getSettings();o(t),c(a)}return()=>{e&&e.getTracks().forEach((t=>{e.removeTrack(t),t.stop()}))}}),[e]),{videoRef:r,videoHeight:n,videoWidth:s}}(f),M=t.useRef(null),A=t.useRef(null),[w,D]=t.useState(!1),I=u.matches("cameraCheck"),O=u.matches("recording"),b=u.matches("checkSucceeded"),P=u.matches({recording:"flashFreshnessColors"}),[k,L]=t.useState(F),[N,H]=t.useState(R),[B,W]=t.useState((()=>F&&R?F/R:0));x.default.useLayoutEffect((()=>{w&&m({type:"SET_DOM_AND_CAMERA_DETAILS",data:{videoEl:S.current,canvasEl:M.current,freshnessColorEl:A.current,isMobile:a}}),S.current&&(L(S.current.videoWidth),H(S.current.videoHeight),W(S.current.videoWidth/S.current.videoHeight))}),[m,S,w,a]);return I?x.default.createElement(v.Flex,{height:R,width:"100%",position:"relative"},Ge):x.default.createElement(v.Flex,{className:_.default(Se.CameraModule,a&&`${Se.CameraModule}--mobile`),"data-testid":c},!w&&Ge,x.default.createElement(v.View,{as:"canvas",ref:A,className:Se.FreshnessCanvas,hidden:!0}),x.default.createElement(v.View,{className:Se.VideoAnchor,style:{aspectRatio:`${B}`}},x.default.createElement("video",{ref:S,muted:!0,autoPlay:!0,playsInline:!0,style:{transform:"scaleX(-1)"},width:k,height:N,onCanPlay:()=>{D(!0)},"data-testid":"video",className:Se.Video}),x.default.createElement(v.Flex,{className:_.default(Se.OvalCanvas,a&&`${Se.OvalCanvas}--mobile`,i&&Se.FadeOut)},x.default.createElement(v.View,{as:"canvas",width:"100%",height:"100%",ref:M})),O&&x.default.createElement(v.View,{className:Se.RecordingIconContainer},x.default.createElement(Ie,null,d)),!b&&x.default.createElement(v.View,{className:Se.CancelContainer},x.default.createElement(ye,{ariaLabel:l})),x.default.createElement(xe,{anchorOrigin:{horizontal:"center",vertical:O&&!P?"start":"space-between"},className:Se.InstructionOverlay},x.default.createElement(De,{hintDisplayText:n}),T&&x.default.createElement(h,{onRetry:()=>{m({type:"CANCEL"})}},ze({errorState:T,overrideErrorDisplayText:o})),O&&!P&&C.includes(E)?x.default.createElement(Xe,{percentage:Math.ceil(g)}):null)))};function Ke(){return/Android|iPhone|iPad/i.test(navigator.userAgent)||/Macintosh/i.test(navigator.userAgent)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>1}function Qe(){return window.matchMedia("(orientation: landscape)")}const Je=e=>{const{onRetry:t,header:a,portraitMessage:i,landscapeMessage:r,tryAgainText:n}=e,[o,s]=R.useState(!0);return R.useLayoutEffect((()=>{const e=Qe();return s(e.matches),e.addEventListener("change",(e=>{s(e.matches)})),()=>{e.removeEventListener("change",(e=>s(e.matches)))}}),[]),R.createElement(v.Flex,{className:Se.LandscapeErrorModal,height:o?"auto":480},R.createElement(v.Text,{className:Se.LandscapeErrorModalHeader},a),R.createElement(v.Text,null,o?r:i),o?null:R.createElement(v.Flex,{className:Se.LandscapeErrorModalButton},R.createElement(v.Button,{variation:"primary",type:"button",onClick:t},n)))},et="liveness-detector-check",tt=e=>e.context.isRecordingStopped,at=({hintDisplayText:e,cameraDisplayText:t,streamDisplayText:a,errorDisplayText:i,components:r})=>{const[n,o]=Te(),s=Ce(Re),c=Ce(tt),l=n.matches("permissionDenied"),d=Ke(),h=()=>{o({type:"RETRY_CAMERA_CHECK"})},{cameraMinSpecificationsHeadingText:u,cameraMinSpecificationsMessageText:m,cameraNotFoundHeadingText:f,cameraNotFoundMessageText:g,retryCameraPermissionsText:p}=t,{cancelLivenessCheckText:E}=a;R.useLayoutEffect((()=>{if(d){const e=e=>{e&&o({type:"MOBILE_LANDSCAPE_WARNING"})},t=Qe();return e(t.matches),t.addEventListener("change",(t=>{e(t.matches)})),()=>{t.removeEventListener("change",(t=>e(t.matches)))}}}),[d,o]);return R.createElement(v.Flex,{direction:"column",position:"relative",testId:et,className:et},(()=>{if(s===F.MOBILE_LANDSCAPE_ERROR){const e=Object.assign(Object.assign({},Ve),i),{landscapeHeaderText:t,portraitMessageText:a,landscapeMessageText:r,tryAgainText:n}=e;return R.createElement(v.Flex,{backgroundColor:"background.primary",direction:"column",textAlign:"center",alignItems:"center",justifyContent:"center",position:"absolute",width:"100%"},R.createElement(Je,{header:t,portraitMessage:a,landscapeMessage:r,tryAgainText:n,onRetry:()=>{o({type:"CANCEL"})}}))}return l?R.createElement(v.Flex,{backgroundColor:"background.primary",direction:"column",textAlign:"center",alignItems:"center",justifyContent:"center",width:"100%",height:480},R.createElement(v.Text,{fontSize:"large",fontWeight:"bold"},s===F.CAMERA_FRAMERATE_ERROR?u:f),R.createElement(v.Text,{maxWidth:300},s===F.CAMERA_FRAMERATE_ERROR?m:g),R.createElement(v.Button,{variation:"primary",type:"button",onClick:h},p),R.createElement(v.View,{position:"absolute",top:"medium",right:"medium"},R.createElement(ye,{ariaLabel:E}))):R.createElement(Ze,{isMobileScreen:d,isRecordingStopped:c,streamDisplayText:a,hintDisplayText:e,errorDisplayText:i,components:r})})())};const it="liveness-detector";function rt(e){const{disableInstructionScreen:t=!1,components:a,config:r,displayText:n}=e,o=R.useRef(null),{hintDisplayText:s,cameraDisplayText:c,instructionDisplayText:l,streamDisplayText:d,errorDisplayText:h}=function(e){const t=Object.assign(Object.assign({},je),e),{instructionsHeaderHeadingText:a,instructionsHeaderBodyText:i,instructionsBeginCheckText:r,photosensitivyWarningHeadingText:n,photosensitivyWarningBodyText:o,photosensitivyWarningInfoText:s,instructionListHeadingText:c,goodFitCaptionText:l,goodFitAltText:d,tooFarCaptionText:h,tooFarAltText:u,instructionListStepOneText:m,instructionListStepTwoText:f,instructionListStepThreeText:v,instructionListStepFourText:g,cameraMinSpecificationsHeadingText:p,cameraMinSpecificationsMessageText:E,cameraNotFoundHeadingText:T,cameraNotFoundMessageText:C,retryCameraPermissionsText:S,cancelLivenessCheckText:y,recordingIndicatorText:F,hintMoveFaceFrontOfCameraText:x,hintTooManyFacesText:R,hintFaceDetectedText:M,hintCanNotIdentifyText:A,hintTooCloseText:w,hintTooFarText:_,hintHoldFacePositionCountdownText:D,hintConnectingText:I,hintVerifyingText:O,hintIlluminationTooBrightText:b,hintIlluminationTooDarkText:P,hintIlluminationNormalText:k,hintHoldFaceForFreshnessText:L,timeoutHeaderText:N,timeoutMessageText:H,faceDistanceHeaderText:B,faceDistanceMessageText:W,multipleFacesHeaderText:V,multipleFacesMessageText:j,clientHeaderText:z,clientMessageText:U,serverHeaderText:q,serverMessageText:Y,landscapeHeaderText:$,landscapeMessageText:G,portraitMessageText:X,tryAgainText:Z}=t;return{hintDisplayText:{hintMoveFaceFrontOfCameraText:x,hintTooManyFacesText:R,hintFaceDetectedText:M,hintCanNotIdentifyText:A,hintTooCloseText:w,hintTooFarText:_,hintHoldFacePositionCountdownText:D,hintConnectingText:I,hintVerifyingText:O,hintIlluminationTooBrightText:b,hintIlluminationTooDarkText:P,hintIlluminationNormalText:k,hintHoldFaceForFreshnessText:L},cameraDisplayText:{cameraMinSpecificationsHeadingText:p,cameraMinSpecificationsMessageText:E,cameraNotFoundHeadingText:T,cameraNotFoundMessageText:C,retryCameraPermissionsText:S},instructionDisplayText:{instructionsHeaderHeadingText:a,instructionsHeaderBodyText:i,instructionsBeginCheckText:r,photosensitivyWarningHeadingText:n,photosensitivyWarningBodyText:o,photosensitivyWarningInfoText:s,instructionListHeadingText:c,goodFitCaptionText:l,goodFitAltText:d,tooFarCaptionText:h,tooFarAltText:u,instructionListStepOneText:m,instructionListStepTwoText:f,instructionListStepThreeText:v,instructionListStepFourText:g},streamDisplayText:{cancelLivenessCheckText:y,recordingIndicatorText:F},errorDisplayText:{timeoutHeaderText:N,timeoutMessageText:H,faceDistanceHeaderText:B,faceDistanceMessageText:W,multipleFacesHeaderText:V,multipleFacesMessageText:j,clientHeaderText:z,clientMessageText:U,serverHeaderText:q,serverMessageText:Y,landscapeHeaderText:$,landscapeMessageText:G,portraitMessageText:X,tryAgainText:Z}}}(n),u=i.useInterpret(fe,{devTools:"development"===process.env.NODE_ENV,context:{componentProps:Object.assign(Object.assign({},e),{config:null!=r?r:{}})}}),[m,f]=i.useActor(u),g=m.matches("start")||m.matches("userCancel"),p=R.useCallback((()=>{f({type:"BEGIN"})}),[f]);return R.useLayoutEffect((()=>{t&&g&&p()}),[p,t,g]),R.createElement(v.View,{className:it,testId:it},R.createElement(pe,{componentProps:e,service:u},R.createElement(v.Flex,{direction:"column",ref:o},g?R.createElement(We,{beginLivenessCheck:p,components:a,instructionDisplayText:l}):R.createElement(at,{hintDisplayText:s,cameraDisplayText:c,streamDisplayText:d,errorDisplayText:h,components:a}))))}const nt=()=>e.__awaiter(void 0,void 0,void 0,(function*(){return yield a.Credentials.get()}));exports.FaceLivenessDetector=function(t){const{config:a}=t,i=e.__rest(t,["config"]);return R.createElement(rt,Object.assign({},i,{config:Object.assign({credentialProvider:nt},a)}))},exports.FaceLivenessDetectorCore=rt;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("react"),a=require("@aws-amplify/core"),i=require("@xstate/react"),r=require("xstate"),n=require("@tensorflow/tfjs-core"),o=require("@tensorflow-models/blazeface"),s=require("@tensorflow/tfjs-backend-wasm");require("@tensorflow/tfjs-backend-cpu");var c=require("@aws-sdk/client-rekognitionstreaming"),l=require("@aws-sdk/util-format-url"),d=require("@smithy/eventstream-serde-browser"),h=require("@smithy/fetch-http-handler"),u=require("@smithy/protocol-http"),m=require("nanoid"),f=require("@aws-amplify/ui-react"),v=require("@aws-amplify/ui-react/internal"),g=require("@aws-amplify/ui"),p=require("classnames");function E(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function T(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(a){if("default"!==a){var i=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,i.get?i:{enumerable:!0,get:function(){return e[a]}})}})),t.default=e,Object.freeze(t)}var C,S,y=E(t),F=T(t),x=T(n),R=T(o),M=T(s),w=E(p);class A{triggerModelLoading(){this.modelLoadingPromise=this.loadModels()}}!function(e){e.DARK="dark",e.BRIGHT="bright",e.NORMAL="normal"}(C||(C={})),function(e){e.MATCHED="MATCHED",e.TOO_FAR="TOO FAR",e.TOO_CLOSE="TOO CLOSE",e.CANT_IDENTIFY="CANNOT IDENTIFY",e.FACE_IDENTIFIED="ONE FACE IDENTIFIED",e.TOO_MANY="TOO MANY FACES"}(S||(S={}));const _={TIMEOUT:"TIMEOUT",RUNTIME_ERROR:"RUNTIME_ERROR",FRESHNESS_TIMEOUT:"FRESHNESS_TIMEOUT",SERVER_ERROR:"SERVER_ERROR",CAMERA_FRAMERATE_ERROR:"CAMERA_FRAMERATE_ERROR",CAMERA_ACCESS_ERROR:"CAMERA_ACCESS_ERROR",FACE_DISTANCE_ERROR:"FACE_DISTANCE_ERROR",MOBILE_LANDSCAPE_ERROR:"MOBILE_LANDSCAPE_ERROR",MULTIPLE_FACES_ERROR:"MULTIPLE_FACES_ERROR"},D=1e3,I=4e3,O=4001,b=4003,P=4005,k=4007;function L(e,t,a){return e*(a-t)+t}function N(e){const t=e.flippedCenterX-e.width/2,a=e.flippedCenterX+e.width/2,i=e.centerY-e.height/2,r=e.centerY+e.height/2;return{ovalBoundingBox:{left:t,top:i,right:a,bottom:r},minOvalX:t,maxOvalX:a,minOvalY:i,maxOvalY:r}}function H(e,t){const a=Math.max(e.left,t.left),i=Math.max(e.top,t.top),r=Math.min(e.right,t.right),n=Math.min(e.bottom,t.bottom),o=Math.abs(Math.max(0,r-a)*Math.max(0,n-i));if(0===o)return 0;return o/(Math.abs((e.right-e.left)*(e.bottom-e.top))+Math.abs((t.right-t.left)*(t.bottom-t.top))-o)}function B({width:e,height:t,widthSeed:a=1,centerXSeed:i=.5,centerYSeed:r=.5}){const n=t;let o=e;const s=.8*a,c=Math.floor(7*e/16),l=Math.floor(9*e/16),d=Math.floor(7*t/16),h=Math.floor(9*t/16),u=L(i,c,l),m=L(r,d,h);e>=t&&(o=3/4*n);const f=s*o,v=1.618*f;return{flippedCenterX:Math.floor(o-u),centerX:Math.floor(u),centerY:Math.floor(m),width:Math.floor(f),height:Math.floor(v)}}function W(e){const{leftEye:t,rightEye:a,mouth:i}=e,r=[];r[0]=(t[0]+a[0])/2,r[1]=(t[1]+a[1])/2;return{pupilDistance:Math.sqrt(Math.pow(t[0]-a[0],2)+Math.pow(t[1]-a[1],2)),faceHeight:Math.sqrt(Math.pow(r[0]-i[0],2)+Math.pow(r[1]-i[1],2))}}function V(e,t){const{leftEye:a,rightEye:i,nose:r}=e,{height:n,centerY:o}=t,s=o-n/2,c=[];c[0]=(a[0]+i[0])/2,c[1]=(a[1]+i[1])/2;const{pupilDistance:l,faceHeight:d}=W(e),h=(2*l+1.8*d)/2,u=1.618*h;let m,f;c[1]<=(s+n)/2?(m=(c[0]+r[0])/2,f=(c[1]+r[1])/2):(m=c[0],f=c[1]);const v=m-h/2,g=f-u/2;return{left:v,top:g,right:v+h,bottom:g+u}}function j(e){const t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;const a=t.getContext("2d");if(a){a.drawImage(e,0,0,t.width,t.height);const i=a.getImageData(0,0,t.width,t.height).data,r=8,n=new Array(r).fill(0);for(let e=0;e<i.length;e++){n[Math.round(.2126*i[e++]+.7152*i[e++]+.0722*i[e++])%32]++}let o=-1,s=0;for(let e=0;e<r;e++)n[e]>s&&(s=n[e],o=e);return t.remove(),0===o?C.DARK:o===r?C.BRIGHT:C.NORMAL}throw new Error("Cannot find Video Element.")}function z({ctx:e,prevColor:t,nextColor:a,fraction:i}){const r=e.canvas.width,n=e.canvas.height;e.fillStyle=a,e.fillRect(0,0,r,n*i),1!==i&&(e.fillStyle=t,e.fillRect(0,n*i,r,n*(1-i)))}const q=e=>!!e;function U(e){return e.slice(e.indexOf("(")+1,e.indexOf(")")).split(",").map((e=>parseInt(e)))}function Y({faceDetector:t,videoEl:a,ovalDetails:i,reduceThreshold:r=!1,isMobile:n=!1}){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield t.detectFaces(a);let o,s,c=!1;switch(e.length){case 0:s=_.FACE_DISTANCE_ERROR;break;case 1:{o=e[0];const t=i.width,{pupilDistance:a,faceHeight:l}=W(o),d=2;t&&(c=(d*a+1.8*l)/2/d/t<(r?n?.37:.4:.32),c||(s=_.FACE_DISTANCE_ERROR));break}default:s=_.MULTIPLE_FACES_ERROR}return{isDistanceBelowThreshold:c,error:s}}))}function $({deviceHeight:e,deviceWidth:t,height:a,width:i,top:r,left:n}){return{Height:a/e,Width:i/t,Top:r/e,Left:n/t}}const G=`https://cdn.liveness.rekognition.amazonaws.com/face-detection/tensorflow/tfjs-backend-wasm/${M.version_wasm}/`;class X extends A{constructor(e,t){super(),this.faceModelUrl=null!=t?t:"https://cdn.liveness.rekognition.amazonaws.com/face-detection/tensorflow-models/blazeface/0.0.7/model/model.json",this.binaryPath=null!=e?e:G}loadModels(){return e.__awaiter(this,void 0,void 0,(function*(){!function(){try{return!(!window.WebAssembly||!window.WebAssembly.compile&&!window.WebAssembly.compileStreaming)}catch(e){return!1}}()?yield this._loadCPUBackend():yield this._loadWebAssemblyBackend();try{yield x.ready(),this._model=yield a.jitteredExponentialRetry(R.load,[{modelUrl:this.faceModelUrl}])}catch(e){throw new Error("There was an error loading the blazeface model. If you are using a custom blazeface model url ensure that it is a fully qualified url that returns a json file.")}}))}detectFaces(t){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this._model.estimateFaces(t,!1,!0,!0),a=Date.now();return e.filter((e=>!!e.landmarks)).map((e=>{const{topLeft:t,bottomRight:i,probability:r,landmarks:n}=e,[o,s]=t,[c,l]=i,d=Math.abs(o-c),h=Math.abs(l-s),u=n[0],m=n[1],f=n[2],v=n[3];return{top:s,left:c,width:d,height:h,timestampMs:a,probability:r[0],rightEye:u,leftEye:m,mouth:v,nose:f}}))}))}_loadWebAssemblyBackend(){return e.__awaiter(this,void 0,void 0,(function*(){try{M.setWasmPaths(this.binaryPath),yield a.jitteredExponentialRetry((()=>e.__awaiter(this,void 0,void 0,(function*(){if(!(yield x.setBackend("wasm")))throw new Error("Initialization of backend wasm failed")}))),[]),this.modelBackend="wasm"}catch(e){throw new Error('There was an error loading the TFJS WASM backend. If you are using a custom WASM path ensure that it ends with "/" and that it is not the full URL as @tensorflow/tfjs-backend-wasm will append the wasm binary file name. Read more: https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/src/backend_wasm.ts#L475.')}}))}_loadCPUBackend(){return e.__awaiter(this,void 0,void 0,(function*(){yield x.setBackend("cpu"),this.modelBackend="cpu"}))}}class Z{constructor(e,t={}){if("undefined"==typeof MediaRecorder)throw Error("MediaRecorder is not supported by this browser");this._stream=e,this._options=t,this._chunks=[],this._recorder=new MediaRecorder(e,{bitsPerSecond:1e6}),this._setupCallbacks()}getState(){return this._recorder.state}start(e){this.clearRecordedData(),this.recordingStartApiTimestamp=Date.now(),this._recorder.start(e)}stop(){return e.__awaiter(this,void 0,void 0,(function*(){return"recording"===this.getState()&&this._recorder.stop(),this._recorderStopped}))}pause(){this._recorder.pause()}clearRecordedData(){this._chunks=[]}dispatch(e){this._recorder.dispatchEvent(e)}getVideoChunkSize(){return this._chunks.length}_setupCallbacks(){this.videoStream=new ReadableStream({start:e=>{this._recorder&&(this._recorder.ondataavailable=t=>{t.data&&t.data.size>0&&(0===this._chunks.length&&(this.firstChunkTimestamp=Date.now()),this._chunks.push(t.data),e.enqueue(t.data))},this._recorder.addEventListener("clientSesssionInfo",(t=>{e.enqueue(t.data.clientInfo)})),this._recorder.addEventListener("stopVideo",(()=>{e.enqueue("stopVideo")})),this._recorder.addEventListener("endStream",(()=>{e.close()})),this._recorder.addEventListener("endStreamWithCode",(t=>{e.enqueue({type:"endStreamWithCode",code:t.data.code})})))}}),this.recorderStarted=new Promise((e=>{this._recorder.onstart=()=>{this.recorderStartTimestamp=Date.now(),e()}})),this._recorderStopped=new Promise((e=>{this._recorder.onstop=()=>{this.recorderEndTimestamp=Date.now(),e()}})),this._recorder.onerror=()=>{"stopped"!==this.getState()&&this.stop()}}}const K=2e3,Q=t=>{return t[Symbol.asyncIterator]?t:(a=t,"function"==typeof ReadableStream&&a instanceof ReadableStream?d.readableStreamtoIterable(t):{[Symbol.asyncIterator]:function(){return e.__asyncGenerator(this,arguments,(function*(){yield yield e.__await(t)}))}});var a};class J{constructor(e,t=new h.FetchHttpHandler){this.metadata={handlerProtocol:"websocket/h1.1"},this.sockets={},this.utf8decoder=new TextDecoder,this.httpHandler=t,this.configPromise="function"==typeof e?e().then((e=>null!=e?e:{})):Promise.resolve(null!=e?e:{})}destroy(){for(const[e,t]of Object.entries(this.sockets)){for(const e of t)e.close(1e3,"Socket closed through destroy() call");delete this.sockets[e]}}handle(t){return e.__awaiter(this,void 0,void 0,(function*(){if(!(e=>"ws:"===e.protocol||"wss:"===e.protocol)(t))return this.httpHandler.handle(t);const e=l.formatUrl(t),a=new WebSocket(e);this.sockets[e]||(this.sockets[e]=[]),this.sockets[e].push(a),a.binaryType="arraybuffer";const{connectionTimeout:i=K}=yield this.configPromise;yield this.waitForReady(a,i);const{body:r}=t,n=Q(r),o=(e=>"function"==typeof ReadableStream?d.iterableToReadableStream(e):e)(this.connect(a,n));return{response:new u.HttpResponse({statusCode:200,body:o})}}))}removeNotUsableSockets(e){var t;this.sockets[e]=(null!==(t=this.sockets[e])&&void 0!==t?t:[]).filter((e=>![WebSocket.CLOSING,WebSocket.CLOSED].includes(e.readyState)))}waitForReady(e,t){return new Promise(((a,i)=>{const r=setTimeout((()=>{this.removeNotUsableSockets(e.url),i({$metadata:{httpStatusCode:500}})}),t);e.onopen=()=>{clearTimeout(r),a()}}))}connect(t,a){let i,r=!1,n=()=>{},o=()=>{};t.onmessage=e=>{o({done:!1,value:new Uint8Array(e.data)})},t.onerror=e=>{r=!0,t.close(),n(e)},t.onclose=()=>{this.removeNotUsableSockets(t.url),r||(i?n(i):o({done:!0,value:void 0}))};const s={[Symbol.asyncIterator]:()=>({next:()=>new Promise(((e,t)=>{o=e,n=t}))})};return(()=>{e.__awaiter(this,void 0,void 0,(function*(){var r,n,o,s;try{try{for(var c,l=!0,d=e.__asyncValues(a);!(r=(c=yield d.next()).done);){s=c.value,l=!1;try{const e=s,a=this.utf8decoder.decode(e);if(a.includes("closeCode")){const e=a.match(/"closeCode":([0-9]*)/);if(e){const a=e[1];t.close(parseInt(a))}continue}t.send(e)}finally{l=!0}}}catch(e){n={error:e}}finally{try{l||r||!(o=d.return)||(yield o.call(d))}finally{if(n)throw n.error}}}catch(e){i=e}finally{t.close(D)}}))})(),s}}const ee=process.env.NEXT_PUBLIC_STREAMING_API_URL;function te(e){return void 0!==e.Challenge}function ae(e){return void 0!==e.code}class ie{constructor({sessionId:e,region:t,stream:a,videoEl:i,credentialProvider:r}){this.sessionId=e,this.region=t,this._stream=a,this.videoEl=i,this.videoRecorder=new Z(a),this.credentialProvider=r,this.initPromise=this.init()}getResponseStream(){return e.__awaiter(this,void 0,void 0,(function*(){return yield this.initPromise,this.responseStream}))}startRecordingLivenessVideo(){this.videoRecorder.start(1e3)}sendClientInfo(e){this.videoRecorder.dispatch(new MessageEvent("clientSesssionInfo",{data:{clientInfo:e}}))}stopVideo(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.videoRecorder.stop()}))}dispatchStopVideoEvent(){this.videoRecorder.dispatch(new Event("stopVideo"))}endStreamWithCode(t){return e.__awaiter(this,void 0,void 0,(function*(){"recording"===this.videoRecorder.getState()&&(yield this.stopVideo()),this.videoRecorder.dispatch(new MessageEvent("endStreamWithCode",{data:{code:t}}))}))}init(){var t;return e.__awaiter(this,void 0,void 0,(function*(){const e=null!==(t=this.credentialProvider)&&void 0!==t?t:yield a.Credentials.get();if(!e)throw new Error("No credentials");const i={credentials:e,region:this.region,customUserAgent:`${a.getAmplifyUserAgent()} ui-react-liveness/2.0.8`,requestHandler:new J({connectionTimeout:1e4})};ee&&(i.endpointProvider=()=>({url:new URL(ee)})),this._client=new c.RekognitionStreamingClient(i),this.responseStream=yield this.startLivenessVideoConnection()}))}getAsyncGeneratorFromReadableStream(t){const a=this;return this._reader=t.getReader(),function(){return e.__asyncGenerator(this,arguments,(function*(){for(;;){const{done:t,value:i}=yield e.__await(a._reader.read());if(t)return yield e.__await(void 0);if("stopVideo"===i)yield yield e.__await({VideoEvent:{VideoChunk:[],TimestampMillis:Date.now()}});else if(void 0!==i.arrayBuffer){const t=yield e.__await(i.arrayBuffer()),a=new Uint8Array(t);a.length>0&&(yield yield e.__await({VideoEvent:{VideoChunk:a,TimestampMillis:Date.now()}}))}else te(i)?yield yield e.__await({ClientSessionInformationEvent:{Challenge:i.Challenge}}):ae(i)&&(yield yield e.__await({VideoEvent:{VideoChunk:[],TimestampMillis:{closeCode:i.code}}}))}}))}}startLivenessVideoConnection(){return e.__awaiter(this,void 0,void 0,(function*(){const e=this.getAsyncGeneratorFromReadableStream(this.videoRecorder.videoStream)();return(yield this._client.send(new c.StartFaceLivenessSessionCommand({ChallengeVersions:"FaceMovementAndLightChallenge_1.0.0",SessionId:this.sessionId,LivenessRequestStream:e,VideoWidth:this.videoEl.videoWidth.toString(),VideoHeight:this.videoEl.videoHeight.toString()}))).LivenessResponseStream}))}}var re;!function(e){e.SCROLLING="SCROLLING",e.FLAT="FLAT"}(re||(re={}));class ne{constructor(e,t){this.context=e,this.freshnessColorsSequence=t,this.isFirstTick=!0}displayColorTick(){return e.__awaiter(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{setTimeout((()=>{this.displayNextColorTick(e,t)}),Math.min(10))}))}))}init(){this.stageIndex=0,this.currColorIndex=0,this.currColorSequence=this.freshnessColorsSequence[0],this.prevColorSequence=this.freshnessColorsSequence[0],this.stage=re.FLAT,this.timeLastFlatOrScrollChange=Date.now(),this.timeLastFaceMatchChecked=Date.now()}displayNextColorTick(e,t){const{freshnessColorEl:a}=this.context.freshnessColorAssociatedParams,{ovalDetails:i,scaleFactor:r}=this.context.ovalAssociatedParams,{videoEl:n}=this.context.videoAssociatedParams,o=Date.now();this.isFirstTick&&(this.init(),this.isFirstTick=!1,this.sendColorStartTime({tickStartTime:o,currColor:this.currColorSequence.color,prevColor:this.currColorSequence.color,currColorIndex:this.stageIndex}));let s=o-this.timeLastFlatOrScrollChange;if(a.style.display="block",(this.stage===re.FLAT&&s>=this.currColorSequence.flatDisplayDuration||this.stage===re.SCROLLING&&s>=this.currColorSequence.downscrollDuration)&&(this.incrementStageIndex(o),s=0),this.currColorIndex<this.freshnessColorsSequence.length){const t=s/(this.stage===re.SCROLLING?this.currColorSequence.downscrollDuration:this.currColorSequence.flatDisplayDuration);!function({overlayCanvas:e,prevColor:t,nextColor:a,videoEl:i,ovalDetails:r,heightFraction:n,scaleFactor:o}){const{x:s,y:c}=i.getBoundingClientRect(),{flippedCenterX:l,centerY:d,width:h,height:u}=r,m=l*o+s,f=d*o+c,v=e.width,g=e.height,p=e.getContext("2d");if(!p)throw new Error("Cannot find Overlay Canvas.");p.canvas.width=window.innerWidth,p.canvas.height=window.innerHeight,p.clearRect(0,0,v,g),z({ctx:p,prevColor:t,nextColor:a,fraction:n}),p.save(),p.beginPath(),p.rect(0,0,v,g),p.clip(),p.clearRect(0,0,v,g),p.globalAlpha=.9,z({ctx:p,prevColor:t,nextColor:a,fraction:n}),p.beginPath(),p.ellipse(m,f,h*o/2,u*o/2,0,0,2*Math.PI),p.strokeStyle="white",p.lineWidth=8,p.stroke(),p.clip(),p.clearRect(0,0,v,g),p.globalAlpha=.75,z({ctx:p,prevColor:t,nextColor:a,fraction:n}),p.restore()}({overlayCanvas:a,prevColor:this.prevColorSequence.color,nextColor:this.currColorSequence.color,videoEl:n,ovalDetails:i,heightFraction:t,scaleFactor:r}),e(!1)}else a.style.display="none",e(!0)}incrementStageIndex(e){if(this.stageIndex+=1,this.prevColorSequence=this.freshnessColorsSequence[this.currColorIndex],this.stage===re.FLAT)this.currColorIndex+=1,this.stage=re.SCROLLING;else if(this.stage===re.SCROLLING){this.freshnessColorsSequence[this.currColorIndex].flatDisplayDuration>0?this.stage=re.FLAT:(this.stage=re.SCROLLING,this.currColorIndex+=1)}this.currColorSequence=this.freshnessColorsSequence[this.currColorIndex],this.timeLastFlatOrScrollChange=Date.now(),this.currColorSequence&&this.sendColorStartTime({tickStartTime:e,currColor:this.currColorSequence.color,prevColor:this.prevColorSequence.color,currColorIndex:this.stageIndex})}sendColorStartTime({tickStartTime:e,currColor:t,prevColor:a,currColorIndex:i}){const{livenessStreamProvider:r,challengeId:n}=this.context;r.sendClientInfo({Challenge:{FaceMovementAndLightChallenge:{ChallengeId:n,ColorDisplayed:{CurrentColor:{RGB:U(t)},PreviousColor:{RGB:U(a)},SequenceNumber:i,CurrentColorStartTimestamp:e}}}})}}const oe=e=>!!(null==e?void 0:e.DisconnectionEvent),se=e=>!!(null==e?void 0:e.ValidationException),ce=e=>!!(null==e?void 0:e.InternalServerException),le=e=>!!(null==e?void 0:e.ThrottlingException),de=e=>!!(null==e?void 0:e.ServiceQuotaExceededException),he={width:{min:320,ideal:640},height:{min:240,ideal:480},frameRate:{min:15,ideal:30,max:30},facingMode:"user"};let ue;const me=r.createMachine({id:"livenessMachine",initial:"start",predictableActionArguments:!0,context:{challengeId:m.nanoid(),maxFailedAttempts:0,failedAttempts:0,componentProps:void 0,serverSessionInformation:void 0,videoAssociatedParams:{videoConstraints:he},ovalAssociatedParams:void 0,faceMatchAssociatedParams:{illuminationState:void 0,faceMatchState:void 0,faceMatchPercentage:25,currentDetectedFace:void 0,startFace:void 0,endFace:void 0,initialFaceMatchTime:void 0},freshnessColorAssociatedParams:{freshnessColorEl:void 0,freshnessColors:[],freshnessColorsComplete:!1,freshnessColorDisplay:void 0},errorState:void 0,livenessStreamProvider:void 0,responseStreamActorRef:void 0,shouldDisconnect:!1,faceMatchStateBeforeStart:void 0,isFaceFarEnoughBeforeRecording:void 0,isRecordingStopped:!1},on:{CANCEL:"userCancel",TIMEOUT:{target:"retryableTimeout",actions:"updateErrorStateForTimeout"},SET_SESSION_INFO:{internal:!0,actions:"updateSessionInfo"},DISCONNECT_EVENT:{internal:!0,actions:"updateShouldDisconnect"},SET_DOM_AND_CAMERA_DETAILS:{actions:"setDOMAndCameraDetails"},SERVER_ERROR:{target:"error",actions:"updateErrorStateForServer"},RUNTIME_ERROR:{target:"error"},MOBILE_LANDSCAPE_WARNING:{target:"mobileLandscapeWarning",actions:"updateErrorStateForServer"}},states:{start:{on:{BEGIN:"cameraCheck"}},cameraCheck:{entry:["resetErrorState","initializeFaceDetector"],invoke:{src:"checkVirtualCameraAndGetStream",onDone:{target:"waitForDOMAndCameraDetails",actions:["updateVideoMediaStream"]},onError:{target:"permissionDenied"}}},waitForDOMAndCameraDetails:{after:{0:{target:"detectFaceBeforeStart",cond:"hasDOMAndCameraDetails"},500:{target:"waitForDOMAndCameraDetails"}}},detectFaceBeforeStart:{invoke:{src:"detectFace",onDone:{target:"checkFaceDetectedBeforeStart",actions:["updateFaceMatchBeforeStartDetails"]}}},checkFaceDetectedBeforeStart:{after:{0:{target:"detectFaceDistanceBeforeRecording",cond:"hasSingleFaceBeforeStart"},100:{target:"detectFaceBeforeStart"}}},detectFaceDistanceBeforeRecording:{invoke:{src:"detectFaceDistance",onDone:{target:"checkFaceDistanceBeforeRecording",actions:["updateFaceDistanceBeforeRecording"]}}},checkFaceDistanceBeforeRecording:{after:{0:{target:"initializeLivenessStream",cond:"hasEnoughFaceDistanceBeforeRecording"},100:{target:"detectFaceDistanceBeforeRecording"}}},initializeLivenessStream:{invoke:{src:"openLivenessStreamConnection",onDone:{target:"notRecording",actions:["updateLivenessStreamProvider","spawnResponseStreamActor"]}}},notRecording:{on:{START_RECORDING:"recording"},initial:"waitForSessionInfo",states:{waitForSessionInfo:{after:{0:{target:"#livenessMachine.recording",cond:"hasServerSessionInfo"},100:{target:"detectFaceDistanceDuringLoading"}}},detectFaceDistanceDuringLoading:{invoke:{src:"detectFaceDistanceWhileLoading",onDone:{target:"checkFaceDistanceDuringLoading",actions:["updateFaceDistanceWhileLoading"]}}},checkFaceDistanceDuringLoading:{always:[{target:"failure",cond:"hasNotEnoughFaceDistanceBeforeRecording"},{target:"waitForSessionInfo"}]},failure:{entry:"sendTimeoutAfterFaceDistanceDelay",type:"final"}}},recording:{entry:["clearErrorState","startRecording"],initial:"ovalDrawing",states:{ovalDrawing:{entry:["sendTimeoutAfterOvalDrawingDelay"],invoke:{src:"detectInitialFaceAndDrawOval",onDone:{target:"checkFaceDetected",actions:["updateOvalAndFaceDetailsPostDraw","sendTimeoutAfterOvalMatchDelay"]},onError:{target:"#livenessMachine.error",actions:"updateErrorStateForRuntime"}}},checkFaceDetected:{after:{0:{target:"checkRecordingStarted",cond:"hasSingleFace"},100:{target:"ovalDrawing"}}},checkRecordingStarted:{after:{0:{target:"ovalMatching",cond:"hasRecordingStarted",actions:["updateRecordingStartTimestampMs"]},100:{target:"checkRecordingStarted"}}},ovalMatching:{entry:["cancelOvalDrawingTimeout"],invoke:{src:"detectFaceAndMatchOval",onDone:{target:"checkMatch",actions:"updateFaceDetailsPostMatch"}}},checkMatch:{after:{0:{target:"flashFreshnessColors",cond:"hasFaceMatchedInOvalWithMinTime",actions:["updateEndFaceMatch","setupFlashFreshnessColors","cancelOvalMatchTimeout","cancelOvalDrawingTimeout"]},.1:{target:"ovalMatching",cond:"hasFaceMatchedInOval",actions:"setFaceMatchTimeAndStartFace"},1:{target:"ovalMatching",cond:"hasNotFaceMatchedInOval"}}},flashFreshnessColors:{invoke:{src:"flashColors",onDone:[{target:"success",cond:"hasFreshnessColorShown"},{target:"flashFreshnessColors",actions:"updateFreshnessDetails"}]}},success:{entry:["stopRecording"],type:"final"}},onDone:"uploading"},uploading:{initial:"pending",states:{pending:{entry:["sendTimeoutAfterWaitingForDisconnect","pauseVideoStream"],invoke:{src:"stopVideo",onDone:"waitForDisconnectEvent",onError:{target:"#livenessMachine.error",actions:"updateErrorStateForRuntime"}}},waitForDisconnectEvent:{after:{0:{target:"getLivenessResult",cond:"getShouldDisconnect"},100:{target:"waitForDisconnectEvent"}}},getLivenessResult:{entry:["cancelWaitForDisconnectTimeout","freezeStream"],invoke:{src:"getLiveness",onError:{target:"#livenessMachine.error",actions:"updateErrorStateForServer"}}}}},retryableTimeout:{entry:"updateFailedAttempts",always:[{target:"timeout",cond:"shouldTimeoutOnFailedAttempts"},{target:"notRecording"}]},permissionDenied:{entry:"callUserPermissionDeniedCallback",on:{RETRY_CAMERA_CHECK:"cameraCheck"}},mobileLandscapeWarning:{entry:"callMobileLandscapeWarningCallback",always:[{target:"error"}]},timeout:{entry:["cleanUpResources","callUserTimeoutCallback","freezeStream"]},error:{entry:["cleanUpResources","callErrorCallback","cancelOvalDrawingTimeout","cancelWaitForDisconnectTimeout","cancelOvalMatchTimeout","freezeStream"]},userCancel:{entry:["cleanUpResources","callUserCancelCallback","resetContext"],always:[{target:"start"}]}}},{actions:{spawnResponseStreamActor:r.assign({responseStreamActorRef:()=>r.spawn(fe)}),updateFailedAttempts:r.assign({failedAttempts:e=>e.failedAttempts+1}),updateVideoMediaStream:r.assign({videoAssociatedParams:(e,t)=>{var a;return Object.assign(Object.assign({},e.videoAssociatedParams),{videoMediaStream:null===(a=t.data)||void 0===a?void 0:a.stream})}}),initializeFaceDetector:r.assign({ovalAssociatedParams:e=>{const{componentProps:t}=e,{faceModelUrl:a,binaryPath:i}=t.config,r=new X(i,a);return r.triggerModelLoading(),Object.assign(Object.assign({},e.ovalAssociatedParams),{faceDetector:r})}}),updateLivenessStreamProvider:r.assign({livenessStreamProvider:(e,t)=>{var a;return null===(a=t.data)||void 0===a?void 0:a.livenessStreamProvider}}),setDOMAndCameraDetails:r.assign({videoAssociatedParams:(e,t)=>{var a,i,r;return Object.assign(Object.assign({},e.videoAssociatedParams),{videoEl:null===(a=t.data)||void 0===a?void 0:a.videoEl,canvasEl:null===(i=t.data)||void 0===i?void 0:i.canvasEl,isMobile:null===(r=t.data)||void 0===r?void 0:r.isMobile})},freshnessColorAssociatedParams:(e,t)=>{var a;return Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorEl:null===(a=t.data)||void 0===a?void 0:a.freshnessColorEl})}}),updateRecordingStartTimestampMs:r.assign({videoAssociatedParams:e=>{const{challengeId:t,videoAssociatedParams:a,ovalAssociatedParams:i,livenessStreamProvider:r}=e,{recordingStartApiTimestamp:n,recorderStartTimestamp:o}=r.videoRecorder,{videoMediaStream:s}=a,{initialFace:c}=i,l=Math.round(.73*(o-n)+n),{width:d,height:h}=s.getTracks()[0].getSettings(),u=d-c.left-c.width;return e.livenessStreamProvider.sendClientInfo({Challenge:{FaceMovementAndLightChallenge:{ChallengeId:t,VideoStartTimestamp:l,InitialFace:{InitialFaceDetectedTimestamp:c.timestampMs,BoundingBox:$({deviceHeight:h,deviceWidth:d,height:c.height,width:c.width,top:c.top,left:u})}}}}),Object.assign(Object.assign({},e.videoAssociatedParams),{recordingStartTimestampMs:l})}}),startRecording:r.assign({videoAssociatedParams:e=>{if(!e.serverSessionInformation)throw new Error("Session information was not received from response stream");return e.livenessStreamProvider.videoRecorder&&"recording"!==e.livenessStreamProvider.videoRecorder.getState()&&e.livenessStreamProvider.startRecordingLivenessVideo(),Object.assign({},e.videoAssociatedParams)}}),stopRecording:e=>{},updateFaceMatchBeforeStartDetails:r.assign({faceMatchStateBeforeStart:(e,t)=>t.data.faceMatchState}),updateFaceDistanceBeforeRecording:r.assign({isFaceFarEnoughBeforeRecording:(e,t)=>t.data.isFaceFarEnoughBeforeRecording}),updateFaceDistanceWhileLoading:r.assign({isFaceFarEnoughBeforeRecording:(e,t)=>t.data.isFaceFarEnoughBeforeRecording,errorState:(e,t)=>{var a;return null===(a=t.data)||void 0===a?void 0:a.error}}),updateOvalAndFaceDetailsPostDraw:r.assign({ovalAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.ovalAssociatedParams),{initialFace:t.data.initialFace,ovalDetails:t.data.ovalDetails,scaleFactor:t.data.scaleFactor}),faceMatchAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{faceMatchState:t.data.faceMatchState,illuminationState:t.data.illuminationState})}),updateFaceDetailsPostMatch:r.assign({faceMatchAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{faceMatchState:t.data.faceMatchState,faceMatchPercentage:t.data.faceMatchPercentage,illuminationState:t.data.illuminationState,currentDetectedFace:t.data.detectedFace})}),updateEndFaceMatch:r.assign({faceMatchAssociatedParams:e=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{endFace:e.faceMatchAssociatedParams.currentDetectedFace})}),setFaceMatchTimeAndStartFace:r.assign({faceMatchAssociatedParams:e=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{startFace:void 0===e.faceMatchAssociatedParams.startFace?e.faceMatchAssociatedParams.currentDetectedFace:e.faceMatchAssociatedParams.startFace,initialFaceMatchTime:void 0===e.faceMatchAssociatedParams.initialFaceMatchTime?Date.now():e.faceMatchAssociatedParams.initialFaceMatchTime})}),resetErrorState:r.assign({errorState:e=>{}}),updateErrorStateForTimeout:r.assign({errorState:(e,t)=>{var a;return(null===(a=t.data)||void 0===a?void 0:a.errorState)||_.TIMEOUT}}),updateErrorStateForRuntime:r.assign({errorState:(e,t)=>{var a;return(null===(a=t.data)||void 0===a?void 0:a.errorState)||_.RUNTIME_ERROR}}),updateErrorStateForServer:r.assign({errorState:e=>_.SERVER_ERROR}),clearErrorState:r.assign({errorState:e=>{}}),updateSessionInfo:r.assign({serverSessionInformation:(e,t)=>t.data.sessionInfo}),updateShouldDisconnect:r.assign({shouldDisconnect:e=>!0}),updateFreshnessDetails:r.assign({freshnessColorAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorsComplete:t.data.freshnessColorsComplete})}),setupFlashFreshnessColors:r.assign({freshnessColorAssociatedParams:e=>{const{serverSessionInformation:t}=e,a=(t.Challenge.FaceMovementAndLightChallenge.ColorSequences||[]).map((({FreshnessColor:e,DownscrollDuration:t,FlatDisplayDuration:a})=>{const i=e.RGB,r=`rgb(${i[0]},${i[1]},${i[2]})`;return void 0!==r&&void 0!==t&&void 0!==a?{color:r,downscrollDuration:t,flatDisplayDuration:a}:void 0})).filter(q);const i=new ne(e,a);return Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorDisplay:i})}}),sendTimeoutAfterOvalDrawingDelay:r.actions.send({type:"TIMEOUT"},{delay:5e3,id:"ovalDrawingTimeout"}),cancelOvalDrawingTimeout:r.actions.cancel("ovalDrawingTimeout"),sendTimeoutAfterOvalMatchDelay:r.actions.send({type:"TIMEOUT"},{delay:e=>{var t,a,i,r;return(null===(r=null===(i=null===(a=null===(t=e.serverSessionInformation)||void 0===t?void 0:t.Challenge)||void 0===a?void 0:a.FaceMovementAndLightChallenge)||void 0===i?void 0:i.ChallengeConfig)||void 0===r?void 0:r.OvalFitTimeout)||7e3},id:"ovalMatchTimeout"}),cancelOvalMatchTimeout:r.actions.cancel("ovalMatchTimeout"),sendTimeoutAfterWaitingForDisconnect:r.actions.send({type:"TIMEOUT",data:{errorState:_.SERVER_ERROR}},{delay:2e4,id:"waitForDisconnectTimeout"}),cancelWaitForDisconnectTimeout:r.actions.cancel("waitForDisconnectTimeout"),sendTimeoutAfterFaceDistanceDelay:r.actions.send({type:"RUNTIME_ERROR",data:new Error("Avoid moving closer during countdown and ensure only one face is in front of camera.")},{delay:0,id:"faceDistanceTimeout"}),cancelFaceDistanceTimeout:r.actions.cancel("faceDistanceTimeout"),callUserPermissionDeniedCallback:r.assign({errorState:(e,t)=>{var a,i;let r;r=t.data.message.includes("15 fps")?_.CAMERA_FRAMERATE_ERROR:_.CAMERA_ACCESS_ERROR;const n=t.data.message||t.data.Message,o={state:r,error:new Error(n)};return null===(i=(a=e.componentProps).onError)||void 0===i||i.call(a,o),r}}),callMobileLandscapeWarningCallback:r.assign({errorState:e=>_.MOBILE_LANDSCAPE_ERROR}),callUserCancelCallback:t=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,a;null===(a=(e=t.componentProps).onUserCancel)||void 0===a||a.call(e)})),callUserTimeoutCallback:t=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,a;const i=new Error("Client Timeout");i.name=t.errorState;const r={state:t.errorState,error:i};null===(a=(e=t.componentProps).onError)||void 0===a||a.call(e,r)})),callErrorCallback:(t,a)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,i,r;const n={state:t.errorState,error:(null===(e=a.data)||void 0===e?void 0:e.error)||a.data};null===(r=(i=t.componentProps).onError)||void 0===r||r.call(i,n)})),cleanUpResources:t=>e.__awaiter(void 0,void 0,void 0,(function*(){var e;const{freshnessColorEl:a}=t.freshnessColorAssociatedParams;a&&(a.style.display="none");let i=I;t.errorState===_.TIMEOUT?i=O:t.errorState===_.RUNTIME_ERROR?i=P:t.errorState===_.FACE_DISTANCE_ERROR||t.errorState===_.MULTIPLE_FACES_ERROR?i=k:void 0===t.errorState&&(i=b),yield null===(e=t.livenessStreamProvider)||void 0===e?void 0:e.endStreamWithCode(i)})),freezeStream:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const{videoMediaStream:e,videoEl:a}=t.videoAssociatedParams;t.isRecordingStopped=!0,null==a||a.pause(),null==e||e.getTracks().forEach((function(e){e.stop()}))})),pauseVideoStream:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const{videoEl:e}=t.videoAssociatedParams;t.isRecordingStopped=!0,e.pause()})),resetContext:r.assign({challengeId:m.nanoid(),maxFailedAttempts:0,failedAttempts:0,componentProps:e=>e.componentProps,serverSessionInformation:e=>{},videoAssociatedParams:e=>({videoConstraints:he}),ovalAssociatedParams:e=>{},errorState:e=>{},livenessStreamProvider:e=>{},responseStreamActorRef:e=>{},shouldDisconnect:!1,faceMatchStateBeforeStart:e=>{},isFaceFarEnoughBeforeRecording:e=>{},isRecordingStopped:!1})},guards:{shouldTimeoutOnFailedAttempts:e=>e.failedAttempts>=e.maxFailedAttempts,hasFaceMatchedInOvalWithMinTime:e=>{const{faceMatchState:t,initialFaceMatchTime:a}=e.faceMatchAssociatedParams,i=Date.now()-a;return t===S.MATCHED&&i>=500},hasFaceMatchedInOval:e=>e.faceMatchAssociatedParams.faceMatchState===S.MATCHED,hasNotFaceMatchedInOval:e=>e.faceMatchAssociatedParams.faceMatchState!==S.MATCHED,hasSingleFace:e=>e.faceMatchAssociatedParams.faceMatchState===S.FACE_IDENTIFIED,hasSingleFaceBeforeStart:e=>e.faceMatchStateBeforeStart===S.FACE_IDENTIFIED,hasEnoughFaceDistanceBeforeRecording:e=>e.isFaceFarEnoughBeforeRecording,hasNotEnoughFaceDistanceBeforeRecording:e=>!e.isFaceFarEnoughBeforeRecording,hasLivenessCheckSucceeded:(e,t,a)=>a.state.event.data.isLive,hasFreshnessColorShown:e=>e.freshnessColorAssociatedParams.freshnessColorsComplete,hasServerSessionInfo:e=>void 0!==e.serverSessionInformation,hasDOMAndCameraDetails:e=>void 0!==e.videoAssociatedParams.videoEl&&void 0!==e.videoAssociatedParams.canvasEl&&void 0!==e.freshnessColorAssociatedParams.freshnessColorEl,getShouldDisconnect:e=>!!e.shouldDisconnect,hasRecordingStarted:e=>void 0!==e.livenessStreamProvider.videoRecorder.firstChunkTimestamp},services:{checkVirtualCameraAndGetStream(t){return e.__awaiter(this,void 0,void 0,(function*(){const{videoConstraints:e}=t.videoAssociatedParams,a=yield navigator.mediaDevices.getUserMedia({video:e,audio:!1}),i=(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind)).filter((e=>!function(e){return e.label.toLowerCase().includes("virtual")}(e)));if(!i.length)throw new Error("No real video devices found");const r=a.getTracks().filter((e=>e.getSettings().frameRate>=15));if(r.length<1)throw new Error("No camera found with more than 15 fps");const n=r[0].getSettings().deviceId;let o=a;return i.some((e=>e.deviceId===n))||(o=yield navigator.mediaDevices.getUserMedia({video:Object.assign(Object.assign({},e),{deviceId:{exact:i[0].deviceId}}),audio:!1})),{stream:o}}))},openLivenessStreamConnection(t){return e.__awaiter(this,void 0,void 0,(function*(){const{config:e}=t.componentProps,{credentialProvider:a}=e,i=new ie({sessionId:t.componentProps.sessionId,region:t.componentProps.region,stream:t.videoAssociatedParams.videoMediaStream,videoEl:t.videoAssociatedParams.videoEl,credentialProvider:a});return ue=i.getResponseStream(),{livenessStreamProvider:i}}))},detectFace(t){return e.__awaiter(this,void 0,void 0,(function*(){const{videoEl:a}=t.videoAssociatedParams,{faceDetector:i}=t.ovalAssociatedParams;try{yield i.modelLoadingPromise}catch(e){console.log({err:e})}const r=yield function(t,a){return e.__awaiter(this,void 0,void 0,(function*(){let e;switch((yield t.detectFaces(a)).length){case 0:e=S.CANT_IDENTIFY;break;case 1:e=S.FACE_IDENTIFIED;break;default:e=S.TOO_MANY}return e}))}(i,a);return{faceMatchState:r}}))},detectFaceDistance(t){return e.__awaiter(this,void 0,void 0,(function*(){const{isFaceFarEnoughBeforeRecording:e}=t,{videoEl:a,videoMediaStream:i,isMobile:r}=t.videoAssociatedParams,{faceDetector:n}=t.ovalAssociatedParams,{width:o,height:s}=i.getTracks()[0].getSettings(),c=B({width:o,height:s}),{isDistanceBelowThreshold:l}=yield Y({faceDetector:n,videoEl:a,ovalDetails:c,reduceThreshold:e,isMobile:r});return{isFaceFarEnoughBeforeRecording:l}}))},detectFaceDistanceWhileLoading(t){return e.__awaiter(this,void 0,void 0,(function*(){const{isFaceFarEnoughBeforeRecording:e}=t,{videoEl:a,videoMediaStream:i,isMobile:r}=t.videoAssociatedParams,{faceDetector:n}=t.ovalAssociatedParams,{width:o,height:s}=i.getTracks()[0].getSettings(),c=B({width:o,height:s}),{isDistanceBelowThreshold:l,error:d}=yield Y({faceDetector:n,videoEl:a,ovalDetails:c,reduceThreshold:e,isMobile:r});return{isFaceFarEnoughBeforeRecording:l,error:d}}))},detectInitialFaceAndDrawOval(t){return e.__awaiter(this,void 0,void 0,(function*(){const{serverSessionInformation:e,livenessStreamProvider:a}=t,{videoEl:i,canvasEl:r,isMobile:n}=t.videoAssociatedParams,{faceDetector:o}=t.ovalAssociatedParams;try{yield o.modelLoadingPromise,yield a.videoRecorder.recorderStarted}catch(e){console.log({err:e})}const s=yield o.detectFaces(i);let c,l,d;switch(s.length){case 0:l=S.CANT_IDENTIFY,d=j(i);break;case 1:l=S.FACE_IDENTIFIED,c=s[0];break;default:l=S.TOO_MANY}if(!c)return{faceMatchState:l,illuminationState:d};const{width:h,height:u}=i.getBoundingClientRect();n?(r.width=window.innerWidth,r.height=window.innerHeight):(r.width=h,r.height=u);const m=h/i.videoWidth,f=function({sessionInformation:e,videoWidth:t}){var a,i;const r=null===(i=null===(a=null==e?void 0:e.Challenge)||void 0===a?void 0:a.FaceMovementAndLightChallenge)||void 0===i?void 0:i.OvalParameters;if(!(r&&r.CenterX&&r.CenterY&&r.Width&&r.Height))throw new Error("Oval parameters not returned from session information.");return{flippedCenterX:t-r.CenterX,centerX:r.CenterX,centerY:r.CenterY,width:r.Width,height:r.Height}}({sessionInformation:e,videoWidth:i.width}),v=V(c,f);return c.top=v.top,c.left=v.left,c.height=v.bottom-v.top,c.width=v.right-v.left,function({canvas:e,oval:t,scaleFactor:a,videoEl:i}){const{flippedCenterX:r,centerY:n,width:o,height:s}=t,{width:c,height:l}=e.getBoundingClientRect(),d=e.getContext("2d");if(!d)throw new Error("Cannot find Canvas.");{d.clearRect(0,0,c,l),d.fillStyle="rgba(255, 255, 255, 1.0)",d.fillRect(0,0,c,l);const e={width:i.videoWidth,height:i.videoHeight},t={x:(c-e.width*a)/2,y:(l-e.height*a)/2};d.setTransform(a,0,0,a,t.x,t.y),d.beginPath(),d.ellipse(r,n,o/2,s/2,0,0,2*Math.PI),d.strokeStyle="#AEB3B7",d.lineWidth=3,d.stroke(),d.clip(),d.setTransform(1,0,0,1,0,0),d.clearRect(0,0,c,l)}}({canvas:r,oval:f,scaleFactor:m,videoEl:i}),{faceMatchState:l,ovalDetails:f,scaleFactor:m,initialFace:c}}))},detectFaceAndMatchOval(t){return e.__awaiter(this,void 0,void 0,(function*(){const{serverSessionInformation:e}=t,{videoEl:a}=t.videoAssociatedParams,{faceDetector:i,ovalDetails:r,initialFace:n}=t.ovalAssociatedParams,o=yield i.detectFaces(a);let s,c,l,d=0;const h=V(n,r),{ovalBoundingBox:u}=N(r),m=H(h,u);switch(o.length){case 0:s=S.CANT_IDENTIFY,l=j(a);break;case 1:{c=o[0];const{faceMatchState:t,faceMatchPercentage:a}=function(e,t,a,i){var r,n;let o;const s=null===(n=null===(r=null==i?void 0:i.Challenge)||void 0===r?void 0:r.FaceMovementAndLightChallenge)||void 0===n?void 0:n.ChallengeConfig;if(!(s&&s.OvalIouThreshold&&s.OvalIouHeightThreshold&&s.OvalIouWidthThreshold&&s.FaceIouHeightThreshold&&s.FaceIouWidthThreshold))throw new Error("Challenge information not returned from session information.");const{OvalIouThreshold:c,OvalIouHeightThreshold:l,OvalIouWidthThreshold:d,FaceIouHeightThreshold:h,FaceIouWidthThreshold:u}=s,m=V(e,t),f=m.left,v=m.right,g=m.top,p=m.bottom,{ovalBoundingBox:E,minOvalX:T,minOvalY:C,maxOvalX:y,maxOvalY:F}=N(t),x=H(m,E),R=c,M=t.width*d,w=t.height*l,A=t.width*u,_=t.height*h,D=100*Math.max(Math.min(1,.75*(x-a)/(R-a)+.25),0);return o=x>R&&Math.abs(T-f)<M&&Math.abs(y-v)<M&&Math.abs(F-p)<w?S.MATCHED:C-g>_||p-F>_||T-f>A&&v-y>A?S.TOO_CLOSE:S.TOO_FAR,{faceMatchState:o,faceMatchPercentage:D}}(c,r,m,e);s=t,d=a;break}default:s=S.TOO_MANY}return{faceMatchState:s,faceMatchPercentage:d,illuminationState:l,detectedFace:c}}))},flashColors(t){return e.__awaiter(this,void 0,void 0,(function*(){const{freshnessColorsComplete:e,freshnessColorDisplay:a}=t.freshnessColorAssociatedParams;if(e)return;return{freshnessColorsComplete:yield a.displayColorTick()}}))},stopVideo(t){return e.__awaiter(this,void 0,void 0,(function*(){const{challengeId:e,livenessStreamProvider:a}=t,{videoMediaStream:i}=t.videoAssociatedParams,{initialFace:r,ovalDetails:n}=t.ovalAssociatedParams,{startFace:o,endFace:s}=t.faceMatchAssociatedParams,{width:c,height:l}=i.getTracks()[0].getSettings(),d=c-r.left-r.width;yield a.stopVideo();const h={Challenge:{FaceMovementAndLightChallenge:{ChallengeId:e,InitialFace:{InitialFaceDetectedTimestamp:r.timestampMs,BoundingBox:$({deviceHeight:l,deviceWidth:c,height:r.height,width:r.width,top:r.top,left:d})},TargetFace:{FaceDetectedInTargetPositionStartTimestamp:o.timestampMs,FaceDetectedInTargetPositionEndTimestamp:s.timestampMs,BoundingBox:$({deviceHeight:l,deviceWidth:c,height:n.height,width:n.width,top:n.centerY-n.height/2,left:n.centerX-n.width/2})},VideoEndTimestamp:a.videoRecorder.recorderEndTimestamp}}};if(0===a.videoRecorder.getVideoChunkSize())throw new Error("Video chunks not recorded successfully.");a.sendClientInfo(h),yield a.dispatchStopVideoEvent()}))},getLiveness(t){return e.__awaiter(this,void 0,void 0,(function*(){const{onAnalysisComplete:e}=t.componentProps;yield e()}))}}}),fe=t=>e.__awaiter(void 0,void 0,void 0,(function*(){var a,i,r,n,o;try{const d=yield ue;try{for(var s,c=!0,l=e.__asyncValues(d);!(a=(s=yield l.next()).done);){n=s.value,c=!1;try{const e=n;(null==(o=e)?void 0:o.ServerSessionInformationEvent)?t({type:"SET_SESSION_INFO",data:{sessionInfo:e.ServerSessionInformationEvent.SessionInformation}}):oe(e)?t({type:"DISCONNECT_EVENT"}):se(e)?t({type:"SERVER_ERROR",data:{error:Object.assign({},e.ValidationException)}}):ce(e)?t({type:"SERVER_ERROR",data:{error:Object.assign({},e.InternalServerException)}}):le(e)?t({type:"SERVER_ERROR",data:{error:Object.assign({},e.ThrottlingException)}}):de(e)&&t({type:"SERVER_ERROR",data:{error:Object.assign({},e.ServiceQuotaExceededException)}})}finally{c=!0}}}catch(e){i={error:e}}finally{try{c||a||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}}catch(e){let a=e;(e=>{const{message:t,name:a}=e;return"InvalidSignatureException"===a&&t.includes("valid region")})(e)&&(a=new Error("Invalid region in FaceLivenessDetector or credentials are scoped to the wrong region.")),a instanceof Error&&t({type:"SERVER_ERROR",data:{error:a}})}})),ve=y.default.createContext(null);function ge(t){var{children:a}=t,i=e.__rest(t,["children"]);return y.default.createElement(ve.Provider,{value:i},a)}function pe(){const e=y.default.useContext(ve);if(null===e)throw new Error("useFaceLivenessDetector must be used within a FaceLivenessDetectorProvider");return e}function Ee(){const{service:e}=pe();return i.useActor(e)}function Te(e){const{service:t}=pe();return i.useSelector(t,e)}var Ce;!function(e){e.CameraModule="amplify-liveness-camera-module",e.CancelContainer="amplify-liveness-cancel-container",e.CancelButton="amplify-liveness-cancel-button",e.CountdownContainer="amplify-liveness-countdown-container",e.DescriptionBullet="amplify-liveness-description-bullet",e.DescriptionBulletIndex="amplify-liveness-description-bullet__index",e.DescriptionBulletIndexText="amplify-liveness-description-bullet__index__text",e.DescriptionBulletMessage="amplify-liveness-description-bullet__message",e.ErrorModal="amplify-liveness-error-modal",e.ErrorModalHeading="amplify-liveness-error-modal__heading",e.FadeOut="amplify-liveness-fade-out",e.FreshnessCanvas="amplify-liveness-freshness-canvas",e.InstructionList="amplify-liveness-instruction-list",e.InstructionOverlay="amplify-liveness-instruction-overlay",e.Figure="amplify-liveness-figure",e.FigureCaption="amplify-liveness-figure__caption",e.FigureIcon="amplify-liveness-figure__icon",e.FigureImage="amplify-liveness-figure__image",e.Figures="amplify-liveness-figures",e.Hint="amplify-liveness-hint",e.HintText="amplify-liveness-hint__text",e.LandscapeErrorModal="amplify-liveness-landscape-error-modal",e.LandscapeErrorModalButton="amplify-liveness-landscape-error-modal__button",e.LandscapeErrorModalHeader="amplify-liveness-landscape-error-modal__header",e.Loader="amplify-liveness-loader",e.MatchIndicator="amplify-liveness-match-indicator",e.OvalCanvas="amplify-liveness-oval-canvas",e.OpaqueOverlay="amplify-liveness-overlay-opaque",e.Overlay="amplify-liveness-overlay",e.Popover="amplify-liveness-popover",e.PopoverContainer="amplify-liveness-popover__container",e.PopoverAnchor="amplify-liveness-popover__anchor",e.PopoverAnchorSecondary="amplify-liveness-popover__anchor-secondary",e.RecordingIconContainer="amplify-liveness-recording-icon-container",e.RecordingIcon="amplify-liveness-recording-icon",e.StartScreenHeader="amplify-liveness-start-screen-header",e.StartScreenHeaderBody="amplify-liveness-start-screen-header__body",e.StartScreenHeaderHeading="amplify-liveness-start-screen-header__heading",e.StartScreenWarning="amplify-liveness-start-screen-warning",e.StartScreenInstructions="amplify-liveness-start-screen-instructions",e.StartScreenInstructionsHeading="amplify-liveness-start-screen-instructions__heading",e.Toast="amplify-liveness-toast",e.ToastContainer="amplify-liveness-toast__container",e.ToastMessage="amplify-liveness-toast__message",e.Video="amplify-liveness-video",e.VideoAnchor="amplify-liveness-video-anchor"}(Ce||(Ce={}));const Se=({ariaLabel:e})=>{const[t,a]=Ee();return t.done?null:y.default.createElement(f.Button,{autoFocus:!0,variation:"link",onClick:()=>{a({type:"CANCEL"})},size:"large",className:Ce.CancelButton,"aria-label":e},y.default.createElement(v.IconClose,{"aria-hidden":"true","data-testid":"close-icon"}))},ye=t=>{var{variation:a="default",size:i="medium",children:r}=t,n=e.__rest(t,["variation","size","children"]);return F.createElement(f.View,Object.assign({className:`${Ce.Toast} ${Ce.Toast}--${a} ${Ce.Toast}--${i}`,maxWidth:{base:"100%",small:"70%"}},n),F.createElement(f.Flex,{className:Ce.ToastContainer},F.createElement(f.Flex,{className:Ce.ToastMessage},r)))},Fe=t=>{var{children:a,anchorOrigin:i={horizontal:"center",vertical:"center"},className:r}=t,n=e.__rest(t,["children","anchorOrigin","className"]);return F.createElement(f.Flex,Object.assign({className:`${Ce.Overlay} ${r}`,alignItems:i.horizontal,justifyContent:i.vertical},n),a)},xe=e=>e.context.errorState,Re=e=>e.context.faceMatchAssociatedParams.faceMatchState,Me=e=>e.context.faceMatchAssociatedParams.illuminationState,we=e=>e.context.isFaceFarEnoughBeforeRecording,Ae=e=>e.context.faceMatchStateBeforeStart,_e=({hintDisplayText:e})=>{const[t]=Ee(),a=Te(xe),i=Te(Re),r=Te(Me),n=Te(Ae),o=Te(we),s=t.matches("checkFaceDetectedBeforeStart"),c=t.matches("checkFaceDistanceBeforeRecording"),l=t.matches("recording"),d=t.matches("notRecording"),h=t.matches("uploading"),u=t.matches("checkSucceeded"),m=t.matches("checkFailed"),v=t.matches({recording:"flashFreshnessColors"}),g={[S.CANT_IDENTIFY]:e.hintCanNotIdentifyText,[S.FACE_IDENTIFIED]:e.hintTooFarText,[S.TOO_MANY]:e.hintTooManyFacesText,[S.TOO_CLOSE]:e.hintTooCloseText,[S.TOO_FAR]:e.hintTooFarText,[S.MATCHED]:e.hintHoldFaceForFreshnessText},p={[C.BRIGHT]:e.hintIlluminationTooBrightText,[C.DARK]:e.hintIlluminationTooDarkText,[C.NORMAL]:e.hintIlluminationNormalText},E=(()=>{if(!(a||m||u)){if(!l){if(s)return n===S.TOO_MANY?F.createElement(ye,null,g[n]):F.createElement(ye,null,e.hintMoveFaceFrontOfCameraText);if(c&&!1===o)return F.createElement(ye,null,e.hintTooCloseText);if(d)return F.createElement(ye,null,F.createElement(f.Flex,{className:Ce.HintText},F.createElement(f.Loader,null),F.createElement(f.View,null,e.hintConnectingText)));if(h)return F.createElement(Fe,{className:Ce.OpaqueOverlay,anchorOrigin:{horizontal:"center",vertical:"end"}},F.createElement(ye,null,F.createElement(f.Flex,{className:Ce.HintText},F.createElement(f.Loader,null),F.createElement(f.View,null,e.hintVerifyingText))));if(r&&r!==C.NORMAL)return F.createElement(ye,null,p[r])}return v?F.createElement(ye,{size:"large",variation:"primary"},e.hintHoldFaceForFreshnessText):l&&!v?F.createElement(ye,{size:"large",variation:i===S.TOO_CLOSE?"error":"primary"},i===S.TOO_CLOSE?g[S.TOO_CLOSE]:g[S.TOO_FAR]):null}})();return E||null},De=({children:e})=>y.default.createElement(f.Flex,{className:Ce.RecordingIcon},y.default.createElement(f.Flex,{"data-testid":"rec-icon",justifyContent:"center"},y.default.createElement(f.Icon,{viewBox:{width:20,height:20},width:"20",height:"20"},y.default.createElement("circle",{cx:"10",cy:"10",r:"8",fill:"red"}))),y.default.createElement(f.Text,{as:"span",fontWeight:"bold"},e)),Ie=t=>{var{children:a,caption:i,variation:r="default"}=t,n=e.__rest(t,["children","caption","variation"]);return y.default.createElement(f.Flex,Object.assign({as:"figure",className:`${Ce.Figure} ${Ce.Figure}--${r}`},n),y.default.createElement(f.View,{className:`${Ce.FigureImage} ${Ce.FigureImage}--${r}`},"success"===r?y.default.createElement("svg",{className:Ce.FigureIcon,"aria-hidden":"true",width:"24",height:"24"},y.default.createElement("g",{fill:"none"},y.default.createElement("path",{fill:"#365E3D",d:"M0 0h24v24H0z"}),y.default.createElement("path",{fill:"#FFF",d:"m9.435 15.62-4.054-4.055L4 12.936l5.435 5.435L21.101 6.704l-1.37-1.371z"}))):null,"error"===r?y.default.createElement("svg",{className:Ce.FigureIcon,"aria-hidden":"true",width:"24",height:"24"},y.default.createElement("g",{fill:"none"},y.default.createElement("path",{fill:"#600",d:"M0 0h24v24H0z"}),y.default.createElement("path",{fill:"#FFF",d:"M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}))):null,a),y.default.createElement(f.View,{as:"figcaption",className:`${Ce.FigureCaption} ${Ce.FigureCaption}--${r}`},i))},Oe=({title:e,testId:t})=>y.default.createElement("svg",{width:"150",height:"150","data-testid":t},y.default.createElement("title",null,e),y.default.createElement("g",{fill:"none",fillRule:"evenodd",transform:"translate(0 -.001)"},y.default.createElement("path",{fill:"#5B361E",fillRule:"nonzero",d:"M124.655 0c9.173 8.155 9.394 17.812 13.258 32.385l.053.336.108.726.11.796.112.864.114.931.174 1.515.117 1.087.18 1.739.12 1.23.183 1.944.123 1.36.186 2.13.187 2.232.313 3.928.25 3.31.25 3.443.31 4.463.245 3.679.36 5.658.345 5.778.33 5.841.26 4.876.199 3.883.187 3.849.217 4.738.16 3.712.178 4.515.097 2.63v34.977L.519 150 .517 41.97c3-13.353 9.664-29.4 23.841-41.97h100.297Z"}),y.default.createElement("path",{fill:"#FCDDCC",fillRule:"nonzero",stroke:"#000",d:"m50.469 18.849.145.153c9.021 9.393 22.62 16.197 36.089 21.996l2.1.897 1.05.443 2.089.876 8.176 3.385 1.979.825 1.944.82c7.782 3.3 14.617 6.491 19.213 10.006 3.57 2.73 5.793 5.645 5.924 8.999v20.474l-.008.624-.016.669-.04 1.089-.04.777-.047.815-.06.853-.068.887-.08.918-.093.95-.104.978-.057.496-.123 1.016-.066.513-.144 1.049-.076.527-.165 1.077c-.057.36-.116.724-.178 1.086l-.193 1.103-.21 1.116-.11.557-.233 1.13c-.12.564-.247 1.13-.38 1.694l-.275 1.14c-1.037 4.147-2.426 8.3-4.271 11.978-6.17 9.34-12.996 16.035-19.28 20.691l-.8.584-.794.562-.784.539-1.165.77-1.147.724-.755.459c-.249.148-.497.294-.74.434l-.73.416-1.078.588-.702.367-1.033.517-.671.321-.657.303-.643.285-.541.23H68.149a75.81 75.81 0 0 1-.81-.284l-.918-.336a75.953 75.953 0 0 1-.935-.355l-.963-.382a85.513 85.513 0 0 1-1.988-.83l-1.032-.455c-.52-.233-1.05-.475-1.585-.727l-1.087-.517-1.113-.547c-.935-.465-1.893-.959-2.873-1.482l-1.193-.644a141.053 141.053 0 0 1-6.297-3.669l-1.33-.83c-17.11-10.783-22.636-33.458-23.66-49.98l-.071-1.267c-.02-.417-.038-.83-.053-1.235l-.037-1.212a86.317 86.317 0 0 1 .042-5.559l.047-1.002.06-.96.064-.843c1.09-2.51 2.164-4.304 3.296-5.882l.408-.558.415-.545.421-.538 2.026-2.492.481-.597.493-.624.507-.656.518-.69a61.722 61.722 0 0 0 3.769-5.754c4.03-6.917 7.127-14.806 9.544-21.668l.566-1.623.802-2.344 2.077-6.175.416-1.205.395-1.109.373-1.007.267-.682.253-.612c.47-.943.8-1.531 1.06-1.876l-.035.047Z"}),y.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"m94.566 121.353.722.895c-6.828 5.51-14.13 7.462-21.382 6.447-5.417-.758-10.535-3.2-13.987-6.186l-.318-.282.77-.854c3.285 2.964 8.343 5.434 13.694 6.183 6.797.95 13.632-.819 20.089-5.876l.412-.327Z"}),y.default.createElement("ellipse",{cx:"51.331",cy:"80.698",fill:"#000",fillRule:"nonzero",rx:"4.886",ry:"6.707"}),y.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"M42.539 63.719c4.453-2.586 11.355-3.268 17.22-.195l.35.19-.556 1.005c-5.437-3.01-11.946-2.479-16.175-.153l-.262.148-.577-.995Z"}),y.default.createElement("ellipse",{cx:"103.281",cy:"80.698",fill:"#000",fillRule:"nonzero",rx:"4.886",ry:"6.707"}),y.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"M94.492 63.719c4.453-2.586 11.355-3.268 17.22-.195l.35.19-.557 1.005c-5.436-3.01-11.946-2.479-16.174-.153l-.262.148-.577-.995Zm-22.972 32.9c0 4.216 2.006 7.72 5.831 7.48l.232-.018.115 1.144c-4.774.477-7.239-3.571-7.326-8.345l-.003-.26 1.15-.001h.001Z"}),y.default.createElement("path",{fill:"#FFF",fillRule:"nonzero",d:"M75.002.001H0v150h150v-150H75.002Zm0 0c25.627 0 46.402 33.579 46.402 75s-20.775 75-46.402 75c-25.627 0-46.402-33.579-46.402-75s20.775-75 46.402-75Z"}),y.default.createElement("path",{stroke:"#AEB3B7",strokeWidth:"2",d:"M120.921 75.001c0 20.555-5.214 39.117-13.589 52.507-8.386 13.406-19.838 21.493-32.313 21.493-12.476 0-23.928-8.087-32.312-21.493-8.377-13.39-13.59-31.952-13.59-52.507 0-20.555 5.214-39.116 13.589-52.507C51.091 9.09 62.543 1.001 75.018 1.001c12.476 0 23.928 8.088 32.314 21.493 8.375 13.39 13.588 31.952 13.588 52.507h.001Z"}))),be=({title:e,testId:t})=>y.default.createElement("svg",{width:"150",height:"150","data-testid":t},y.default.createElement("title",null,e),y.default.createElement("defs",null,y.default.createElement("linearGradient",{id:"a",x1:"50%",x2:"50%",y1:"0%",y2:"100%"},y.default.createElement("stop",{offset:"0%",stopColor:"#C2C2C2"}),y.default.createElement("stop",{offset:"100%",stopColor:"#C2C2C2",stopOpacity:"0"}))),y.default.createElement("g",{fill:"none",fillRule:"evenodd",transform:"translate(2)"},y.default.createElement("path",{fill:"#FFF",fillRule:"nonzero",d:"M3.997 0h136v150h-136z"}),y.default.createElement("path",{fill:"url(#a)",fillRule:"nonzero",d:"M4.333 0h138v150h-138z"}),y.default.createElement("path",{fill:"#5B361E",fillRule:"nonzero",stroke:"#000",strokeWidth:"1.353",d:"m22.515 58.137-1.895 82.434 98.784-2.343c0-8.798.813-16.271.813-31.497 0-15.748-2.345-55.36-3.766-64.125C108.16 11.338 74.737 5.03 56.707 11.04c-28.425 9.475-33.64 35.095-34.192 47.097Z"}),y.default.createElement("path",{fill:"#EF992A",fillRule:"nonzero",d:"M38.104 138.228c8.339-3.98 5.1-1.525 15.916-3.104H90.5c5.448 0 9.541 3.104 28.904 3.104 6.391 0 5.987 8.988-2.473 8.988-24.315 1.08-66.07 1.08-78.281 0-77.975-6.896-10.97-4.014-.546-8.988Z"}),y.default.createElement("path",{fill:"#FCDDCC",fillRule:"nonzero",stroke:"#000",strokeWidth:"1.353",d:"m54.306 134.26 2.645-21.765h30.498l3.05 21.765c-15.778 14.791-30.703 6.163-36.193 0zm-27.59-54.458C25.42 66.68 33.467 67.18 37.653 69.07l2.837 25.314c-10.328-2.228-13.772-12.961-13.772-14.58zm89.512-.81c4.05-15.067-3.984-15.998-8.506-14.58L105.9 91.75c10.328-8.505 9.113-12.758 10.328-12.758z"}),y.default.createElement("path",{fill:"#FCDDCC",fillRule:"nonzero",stroke:"#000",strokeWidth:"1.353",d:"M53.564 109.804c-14.195-8.986-16.116-30.658-15.302-40.37 2.24-5.21 4.37-5.723 7.958-11.909 6.3-10.86 9.028-25.451 10.579-25.009 14.241 16.008 50.215 20.259 50.649 31.708v13.023c0 4.178-.911 14.358-4.558 21.65-8.986 13.674-20.131 18.612-24.58 19.372-2.334.922-10.55.521-24.746-8.465Z"}),y.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"m83.935 98.402.85 1.052c-7.974 6.435-17.2 5.243-23.018.18l-.23-.204.905-1.004c5.273 4.756 13.744 5.998 21.175.227l.318-.251Z"}),y.default.createElement("ellipse",{cx:"56.448",cy:"72.613",fill:"#000",fillRule:"nonzero",rx:"3.128",ry:"4.294"}),y.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"M50.664 61.476c2.917-1.694 7.404-2.147 11.244-.172l.31.165-.655 1.183c-3.348-1.854-7.361-1.545-9.985-.137l-.234.13-.68-1.17Z"}),y.default.createElement("ellipse",{cx:"89.709",cy:"72.613",fill:"#000",fillRule:"nonzero",rx:"3.128",ry:"4.294"}),y.default.createElement("path",{fill:"#000",fillRule:"nonzero",d:"M83.926 61.476c2.917-1.694 7.404-2.147 11.244-.172l.31.165-.655 1.183c-3.348-1.854-7.361-1.545-9.985-.137l-.234.13-.68-1.17Z"}),y.default.createElement("path",{stroke:"#000",strokeWidth:"1.353",d:"M69.005 82.806c0 1.858.859 5.487 4.287 5.144"}),y.default.createElement("path",{fill:"#FFF",d:"M73.004 0H0v150h146V0H73.004Zm.496 0C98.629 0 119 33.579 119 75s-20.371 75-45.5 75S28 116.421 28 75 48.371 0 73.5 0Z"}),y.default.createElement("path",{stroke:"#AEB3B7",strokeWidth:"2",d:"M118.4 75c0 20.555-5.156 39.117-13.441 52.507C96.665 140.913 85.338 149 72.999 149c-12.34 0-23.667-8.087-31.961-21.493C32.753 114.117 27.597 95.555 27.597 75c0-20.555 5.156-39.117 13.44-52.507C49.333 9.087 60.66 1 72.999 1c12.34 0 23.667 8.087 31.961 21.493C113.244 35.883 118.4 54.445 118.4 75Z"}))),Pe=({children:e})=>{const t=v.useThemeBreakpoint(),[a,i]=F.useState(!1),r=F.useRef(null),n="base"===t;return F.useEffect((()=>{function e(e){a&&r.current&&!r.current.contains(e.target)&&i(!1)}return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}}),[r,a]),F.createElement(f.Flex,{className:Ce.Popover,onClick:()=>i(!a),ref:r,testId:"popover-icon"},F.createElement(v.AlertIcon,{ariaHidden:!0,variation:"info"}),a&&F.createElement(F.Fragment,null,F.createElement(f.Flex,{className:Ce.PopoverAnchor}),F.createElement(f.Flex,{className:Ce.PopoverAnchorSecondary}),F.createElement(f.Flex,{className:Ce.PopoverContainer,left:n?-190:-108,"data-testid":"popover-text"},e)))};Pe.displayName="LivenessIconWithPopover";const ke=({headingText:e,bodyText:t})=>y.default.createElement(f.View,{className:Ce.StartScreenHeader},y.default.createElement(f.View,{className:Ce.StartScreenHeaderHeading},e),y.default.createElement(f.View,{className:Ce.StartScreenHeaderBody},t)),Le=({headingText:e,bodyText:t,infoText:a})=>y.default.createElement(f.Flex,{className:`${f.ComponentClassNames.Alert} ${Ce.StartScreenWarning}`},y.default.createElement(f.View,{flex:"1"},y.default.createElement(f.View,{className:f.ComponentClassNames.AlertHeading},e),y.default.createElement(f.View,{className:f.ComponentClassNames.AlertBody},t)),y.default.createElement(Pe,null,a)),Ne=({headingText:e,goodFitCaptionText:t,goodFitAltText:a,tooFarCaptionText:i,tooFarAltText:r,steps:n})=>y.default.createElement(f.Flex,{direction:"column"},y.default.createElement(f.Text,{className:Ce.StartScreenInstructionsHeading},e),y.default.createElement(f.Flex,{className:Ce.Figures},y.default.createElement(Ie,{variation:"success",caption:t},y.default.createElement(Oe,{title:a})),y.default.createElement(Ie,{variation:"error",caption:i},y.default.createElement(be,{title:r}))),y.default.createElement(f.Flex,{as:"ol",className:Ce.InstructionList},n.map(((e,t)=>y.default.createElement(f.Flex,{as:"li",key:t+1},y.default.createElement(f.Text,{as:"span","aria-hidden":"true"},t+1,"."),y.default.createElement(f.Text,{as:"span"},e)))))),He="liveness-detector-start";function Be(e){const{beginLivenessCheck:t,components:a,instructionDisplayText:i}=e;return F.createElement(f.Card,{className:He,"data-testid":He},F.createElement(f.Flex,{direction:"column"},(null==a?void 0:a.Header)?F.createElement(a.Header,null):F.createElement(ke,{headingText:i.instructionsHeaderHeadingText,bodyText:i.instructionsHeaderBodyText}),(null==a?void 0:a.PhotosensitiveWarning)?F.createElement(a.PhotosensitiveWarning,null):F.createElement(Le,{headingText:i.photosensitivyWarningHeadingText,bodyText:i.photosensitivyWarningBodyText,infoText:i.photosensitivyWarningInfoText}),(null==a?void 0:a.Instructions)?F.createElement(a.Instructions,null):F.createElement(Ne,{headingText:i.instructionListHeadingText,goodFitCaptionText:i.goodFitCaptionText,goodFitAltText:i.goodFitAltText,tooFarCaptionText:i.tooFarCaptionText,tooFarAltText:i.tooFarAltText,steps:[i.instructionListStepOneText,i.instructionListStepTwoText,i.instructionListStepThreeText,i.instructionListStepFourText]}),F.createElement(f.Flex,{justifyContent:"center"},F.createElement(f.Button,{variation:"primary",type:"button",onClick:t},i.instructionsBeginCheckText))))}const We={timeoutHeaderText:"Time out",timeoutMessageText:"Face didn't fit inside oval in time limit. Try again and completely fill the oval with face in it.",faceDistanceHeaderText:"Forward movement detected",faceDistanceMessageText:"Avoid moving closer when connecting.",multipleFacesHeaderText:"Multiple faces detected",multipleFacesMessageText:"Ensure only one face is present in front of the camera when connecting.",clientHeaderText:"Client error",clientMessageText:"Check failed due to client issue",serverHeaderText:"Server issue",serverMessageText:"Cannot complete check due to server issue",landscapeHeaderText:"Landscape orientation not supported",landscapeMessageText:"Rotate your device to portrait (vertical) orientation.",portraitMessageText:"Ensure your device remains in portrait (vertical) orientation for the check’s duration.",tryAgainText:"Try again"},Ve=Object.assign({instructionsHeaderHeadingText:"Liveness check",instructionsHeaderBodyText:"You will go through a face verification process to prove that you are a real person.",instructionsBeginCheckText:"Begin check",photosensitivyWarningHeadingText:"Photosensitivity warning",photosensitivyWarningBodyText:"This check displays colored lights. Use caution if you are photosensitive.",photosensitivyWarningInfoText:"A small percentage of individuals may experience epileptic seizures when exposed to colored lights. Use caution if you, or anyone in your family, have an epileptic condition.",instructionListHeadingText:"Follow the instructions to complete the check:",goodFitCaptionText:"Good fit",goodFitAltText:"Ilustration of a person's face, perfectly fitting inside of an oval.",tooFarCaptionText:"Too far",tooFarAltText:"Illustration of a person's face inside of an oval; there is a gap between the perimeter of the face and the boundaries of the oval.",instructionListStepOneText:"When an oval appears, follow the instructions to fit your face in it.",instructionListStepTwoText:"Maximize your screen's brightness.",instructionListStepThreeText:"Make sure your face is not covered with sunglasses or a mask.",instructionListStepFourText:"Move to a well-lit place that is not in direct sunlight.",cameraMinSpecificationsHeadingText:"Camera does not meet minimum specifications",cameraMinSpecificationsMessageText:"Camera must support at least 320*240 resolution and 15 frames per second.",cameraNotFoundHeadingText:"Camera not accessible.",cameraNotFoundMessageText:"Check that camera is connected and camera permissions are enabled in settings before retrying.",retryCameraPermissionsText:"Retry",cancelLivenessCheckText:"Cancel Liveness check",recordingIndicatorText:"Rec",hintMoveFaceFrontOfCameraText:"Move face in front of camera",hintTooManyFacesText:"Ensure only one face is in front of camera",hintFaceDetectedText:"Face detected",hintCanNotIdentifyText:"Move face in front of camera",hintTooCloseText:"Move back",hintTooFarText:"Move closer",hintHoldFacePositionCountdownText:"Hold face position during countdown",hintConnectingText:"Connecting...",hintVerifyingText:"Verifying...",hintIlluminationTooBrightText:"Move to dimmer area",hintIlluminationTooDarkText:"Move to brighter area",hintIlluminationNormalText:"Lighting conditions normal",hintHoldFaceForFreshnessText:"Hold still"},We),je=({errorState:e,overrideErrorDisplayText:t})=>{const a=Object.assign(Object.assign({},We),t);return e===_.CAMERA_ACCESS_ERROR||e===_.CAMERA_FRAMERATE_ERROR||e===_.MOBILE_LANDSCAPE_ERROR?null:(e=>{const{error:t,displayText:a}=e,{timeoutHeaderText:i,timeoutMessageText:r,faceDistanceHeaderText:n,faceDistanceMessageText:o,multipleFacesHeaderText:s,multipleFacesMessageText:c,clientHeaderText:l,clientMessageText:d,serverHeaderText:h,serverMessageText:u}=a;let m,g;switch(t){case _.TIMEOUT:m=i,g=r;break;case _.FACE_DISTANCE_ERROR:m=n,g=o;break;case _.MULTIPLE_FACES_ERROR:m=s,g=c;break;case _.RUNTIME_ERROR:m=l,g=d;break;case _.SERVER_ERROR:default:m=h,g=u}return y.default.createElement(y.default.Fragment,null,y.default.createElement(f.Flex,{className:Ce.ErrorModal},y.default.createElement(v.AlertIcon,{ariaHidden:!0,variation:"error"}),y.default.createElement(f.Text,{className:Ce.ErrorModalHeading},m)),g)})({error:e,displayText:a})},ze=e=>{const{children:t,onRetry:a,displayText:i}=e,r=Object.assign(Object.assign({},We),i),{tryAgainText:n}=r;return y.default.createElement(Fe,{className:Ce.OpaqueOverlay},y.default.createElement(ye,null,t,y.default.createElement(f.Flex,{justifyContent:"center"},y.default.createElement(f.Button,{variation:"primary",type:"button",onClick:a},n))))},qe=e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoMediaStream},Ue=e=>e.context.faceMatchAssociatedParams.faceMatchPercentage,Ye=e=>e.context.faceMatchAssociatedParams.faceMatchState,$e=y.default.createElement(f.Loader,{size:"large",className:Ce.Loader,"data-testid":"centered-loader"}),Ge=y.default.memo((({percentage:e,initialPercentage:t=25,testId:a})=>{const[i,r]=y.default.useState(t);y.default.useEffect((()=>{r(e<0?0:e>100?100:e)}),[e]);const n={"--percentage":`${i}%`};return y.default.createElement("div",{className:Ce.MatchIndicator,"data-testid":a},y.default.createElement("div",{className:`${Ce.MatchIndicator}__bar`,style:n}))})),Xe=e=>{const{isMobileScreen:a,isRecordingStopped:i,streamDisplayText:r,hintDisplayText:n,errorDisplayText:o,components:s,testId:c}=e,{cancelLivenessCheckText:l,recordingIndicatorText:d}=r,{ErrorView:h=ze}=null!=s?s:{},[u,m]=Ee(),v=Te(qe),p=Te(Ue),E=Te(Ye),T=Te(xe),C=[S.TOO_FAR,S.CANT_IDENTIFY,S.FACE_IDENTIFIED,S.MATCHED],{videoRef:F,videoWidth:x,videoHeight:R}=function(e){const a=he.height.ideal,i=he.width.ideal,r=t.useRef(null),[n,o]=t.useState(a),[s,c]=t.useState(i);return t.useEffect((()=>{if(e){g.isObject(r.current)&&(r.current.srcObject=e);const{height:t,width:a}=e.getTracks()[0].getSettings();o(t),c(a)}return()=>{e&&e.getTracks().forEach((t=>{e.removeTrack(t),t.stop()}))}}),[e]),{videoRef:r,videoHeight:n,videoWidth:s}}(v),M=t.useRef(null),A=t.useRef(null),[_,D]=t.useState(!1),I=u.matches("cameraCheck"),O=u.matches("recording"),b=u.matches("checkSucceeded"),P=u.matches({recording:"flashFreshnessColors"}),[k,L]=t.useState(x),[N,H]=t.useState(R),[B,W]=t.useState((()=>x&&R?x/R:0));y.default.useLayoutEffect((()=>{_&&m({type:"SET_DOM_AND_CAMERA_DETAILS",data:{videoEl:F.current,canvasEl:M.current,freshnessColorEl:A.current,isMobile:a}}),F.current&&(L(F.current.videoWidth),H(F.current.videoHeight),W(F.current.videoWidth/F.current.videoHeight))}),[m,F,_,a]);return I?y.default.createElement(f.Flex,{height:R,width:"100%",position:"relative"},$e):y.default.createElement(f.Flex,{className:w.default(Ce.CameraModule,a&&`${Ce.CameraModule}--mobile`),"data-testid":c},!_&&$e,y.default.createElement(f.View,{as:"canvas",ref:A,className:Ce.FreshnessCanvas,hidden:!0}),y.default.createElement(f.View,{className:Ce.VideoAnchor,style:{aspectRatio:`${B}`}},y.default.createElement("video",{ref:F,muted:!0,autoPlay:!0,playsInline:!0,style:{transform:"scaleX(-1)"},width:k,height:N,onCanPlay:()=>{D(!0)},"data-testid":"video",className:Ce.Video}),y.default.createElement(f.Flex,{className:w.default(Ce.OvalCanvas,a&&`${Ce.OvalCanvas}--mobile`,i&&Ce.FadeOut)},y.default.createElement(f.View,{as:"canvas",width:"100%",height:"100%",ref:M})),O&&y.default.createElement(f.View,{className:Ce.RecordingIconContainer},y.default.createElement(De,null,d)),!b&&y.default.createElement(f.View,{className:Ce.CancelContainer},y.default.createElement(Se,{ariaLabel:l})),y.default.createElement(Fe,{anchorOrigin:{horizontal:"center",vertical:O&&!P?"start":"space-between"},className:Ce.InstructionOverlay},y.default.createElement(_e,{hintDisplayText:n}),T&&y.default.createElement(h,{onRetry:()=>{m({type:"CANCEL"})}},je({errorState:T,overrideErrorDisplayText:o})),O&&!P&&C.includes(E)?y.default.createElement(Ge,{percentage:Math.ceil(p)}):null)))};function Ze(){return/Android|iPhone|iPad/i.test(navigator.userAgent)||/Macintosh/i.test(navigator.userAgent)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>1}function Ke(){return window.matchMedia("(orientation: landscape)")}const Qe=e=>{const{onRetry:t,header:a,portraitMessage:i,landscapeMessage:r,tryAgainText:n}=e,[o,s]=F.useState(!0);return F.useLayoutEffect((()=>{const e=Ke();return s(e.matches),e.addEventListener("change",(e=>{s(e.matches)})),()=>{e.removeEventListener("change",(e=>s(e.matches)))}}),[]),F.createElement(f.Flex,{className:Ce.LandscapeErrorModal,height:o?"auto":480},F.createElement(f.Text,{className:Ce.LandscapeErrorModalHeader},a),F.createElement(f.Text,null,o?r:i),o?null:F.createElement(f.Flex,{className:Ce.LandscapeErrorModalButton},F.createElement(f.Button,{variation:"primary",type:"button",onClick:t},n)))},Je="liveness-detector-check",et=e=>e.context.isRecordingStopped,tt=({hintDisplayText:e,cameraDisplayText:t,streamDisplayText:a,errorDisplayText:i,components:r})=>{const[n,o]=Ee(),s=Te(xe),c=Te(et),l=n.matches("permissionDenied"),d=Ze(),h=()=>{o({type:"RETRY_CAMERA_CHECK"})},{cameraMinSpecificationsHeadingText:u,cameraMinSpecificationsMessageText:m,cameraNotFoundHeadingText:v,cameraNotFoundMessageText:g,retryCameraPermissionsText:p}=t,{cancelLivenessCheckText:E}=a;F.useLayoutEffect((()=>{if(d){const e=e=>{e&&o({type:"MOBILE_LANDSCAPE_WARNING"})},t=Ke();return e(t.matches),t.addEventListener("change",(t=>{e(t.matches)})),()=>{t.removeEventListener("change",(t=>e(t.matches)))}}}),[d,o]);return F.createElement(f.Flex,{direction:"column",position:"relative",testId:Je,className:Je},(()=>{if(s===_.MOBILE_LANDSCAPE_ERROR){const e=Object.assign(Object.assign({},We),i),{landscapeHeaderText:t,portraitMessageText:a,landscapeMessageText:r,tryAgainText:n}=e;return F.createElement(f.Flex,{backgroundColor:"background.primary",direction:"column",textAlign:"center",alignItems:"center",justifyContent:"center",position:"absolute",width:"100%"},F.createElement(Qe,{header:t,portraitMessage:a,landscapeMessage:r,tryAgainText:n,onRetry:()=>{o({type:"CANCEL"})}}))}return l?F.createElement(f.Flex,{backgroundColor:"background.primary",direction:"column",textAlign:"center",alignItems:"center",justifyContent:"center",width:"100%",height:480},F.createElement(f.Text,{fontSize:"large",fontWeight:"bold"},s===_.CAMERA_FRAMERATE_ERROR?u:v),F.createElement(f.Text,{maxWidth:300},s===_.CAMERA_FRAMERATE_ERROR?m:g),F.createElement(f.Button,{variation:"primary",type:"button",onClick:h},p),F.createElement(f.View,{position:"absolute",top:"medium",right:"medium"},F.createElement(Se,{ariaLabel:E}))):F.createElement(Xe,{isMobileScreen:d,isRecordingStopped:c,streamDisplayText:a,hintDisplayText:e,errorDisplayText:i,components:r})})())};const at="liveness-detector";function it(e){const{disableInstructionScreen:t=!1,components:a,config:r,displayText:n}=e,o=F.useRef(null),{hintDisplayText:s,cameraDisplayText:c,instructionDisplayText:l,streamDisplayText:d,errorDisplayText:h}=function(e){const t=Object.assign(Object.assign({},Ve),e),{instructionsHeaderHeadingText:a,instructionsHeaderBodyText:i,instructionsBeginCheckText:r,photosensitivyWarningHeadingText:n,photosensitivyWarningBodyText:o,photosensitivyWarningInfoText:s,instructionListHeadingText:c,goodFitCaptionText:l,goodFitAltText:d,tooFarCaptionText:h,tooFarAltText:u,instructionListStepOneText:m,instructionListStepTwoText:f,instructionListStepThreeText:v,instructionListStepFourText:g,cameraMinSpecificationsHeadingText:p,cameraMinSpecificationsMessageText:E,cameraNotFoundHeadingText:T,cameraNotFoundMessageText:C,retryCameraPermissionsText:S,cancelLivenessCheckText:y,recordingIndicatorText:F,hintMoveFaceFrontOfCameraText:x,hintTooManyFacesText:R,hintFaceDetectedText:M,hintCanNotIdentifyText:w,hintTooCloseText:A,hintTooFarText:_,hintHoldFacePositionCountdownText:D,hintConnectingText:I,hintVerifyingText:O,hintIlluminationTooBrightText:b,hintIlluminationTooDarkText:P,hintIlluminationNormalText:k,hintHoldFaceForFreshnessText:L,timeoutHeaderText:N,timeoutMessageText:H,faceDistanceHeaderText:B,faceDistanceMessageText:W,multipleFacesHeaderText:V,multipleFacesMessageText:j,clientHeaderText:z,clientMessageText:q,serverHeaderText:U,serverMessageText:Y,landscapeHeaderText:$,landscapeMessageText:G,portraitMessageText:X,tryAgainText:Z}=t;return{hintDisplayText:{hintMoveFaceFrontOfCameraText:x,hintTooManyFacesText:R,hintFaceDetectedText:M,hintCanNotIdentifyText:w,hintTooCloseText:A,hintTooFarText:_,hintHoldFacePositionCountdownText:D,hintConnectingText:I,hintVerifyingText:O,hintIlluminationTooBrightText:b,hintIlluminationTooDarkText:P,hintIlluminationNormalText:k,hintHoldFaceForFreshnessText:L},cameraDisplayText:{cameraMinSpecificationsHeadingText:p,cameraMinSpecificationsMessageText:E,cameraNotFoundHeadingText:T,cameraNotFoundMessageText:C,retryCameraPermissionsText:S},instructionDisplayText:{instructionsHeaderHeadingText:a,instructionsHeaderBodyText:i,instructionsBeginCheckText:r,photosensitivyWarningHeadingText:n,photosensitivyWarningBodyText:o,photosensitivyWarningInfoText:s,instructionListHeadingText:c,goodFitCaptionText:l,goodFitAltText:d,tooFarCaptionText:h,tooFarAltText:u,instructionListStepOneText:m,instructionListStepTwoText:f,instructionListStepThreeText:v,instructionListStepFourText:g},streamDisplayText:{cancelLivenessCheckText:y,recordingIndicatorText:F},errorDisplayText:{timeoutHeaderText:N,timeoutMessageText:H,faceDistanceHeaderText:B,faceDistanceMessageText:W,multipleFacesHeaderText:V,multipleFacesMessageText:j,clientHeaderText:z,clientMessageText:q,serverHeaderText:U,serverMessageText:Y,landscapeHeaderText:$,landscapeMessageText:G,portraitMessageText:X,tryAgainText:Z}}}(n),u=i.useInterpret(me,{devTools:"development"===process.env.NODE_ENV,context:{componentProps:Object.assign(Object.assign({},e),{config:null!=r?r:{}})}}),[m,v]=i.useActor(u),g=m.matches("start")||m.matches("userCancel"),p=F.useCallback((()=>{v({type:"BEGIN"})}),[v]);return F.useLayoutEffect((()=>{t&&g&&p()}),[p,t,g]),F.createElement(f.View,{className:at,testId:at},F.createElement(ge,{componentProps:e,service:u},F.createElement(f.Flex,{direction:"column",ref:o},g?F.createElement(Be,{beginLivenessCheck:p,components:a,instructionDisplayText:l}):F.createElement(tt,{hintDisplayText:s,cameraDisplayText:c,streamDisplayText:d,errorDisplayText:h,components:a}))))}const rt=()=>e.__awaiter(void 0,void 0,void 0,(function*(){return yield a.Credentials.get()}));exports.FaceLivenessDetector=function(t){const{config:a}=t,i=e.__rest(t,["config"]);return F.createElement(it,Object.assign({},i,{config:Object.assign({credentialProvider:rt},a)}))},exports.FaceLivenessDetectorCore=it;
|
package/dist/styles.css
CHANGED
|
@@ -1000,7 +1000,11 @@
|
|
|
1000
1000
|
--amplify-components-searchfield-button-hover-background-color: var(--amplify-components-button-hover-background-color);
|
|
1001
1001
|
--amplify-components-searchfield-button-hover-border-color: var(--amplify-components-button-hover-border-color);
|
|
1002
1002
|
--amplify-components-searchfield-button-hover-color: var(--amplify-components-button-hover-color);
|
|
1003
|
+
--amplify-components-select-color: var(--amplify-components-fieldcontrol-color);
|
|
1004
|
+
--amplify-components-select-background-color: var(--amplify-colors-background-primary);
|
|
1003
1005
|
--amplify-components-select-padding-inline-end: var(--amplify-space-xxl);
|
|
1006
|
+
--amplify-components-select-disabled-color: var(--amplify-colors-font-disabled);
|
|
1007
|
+
--amplify-components-select-disabled-background-color: var(--amplify-colors-background-disabled);
|
|
1004
1008
|
--amplify-components-select-wrapper-flex: 1;
|
|
1005
1009
|
--amplify-components-select-wrapper-display: block;
|
|
1006
1010
|
--amplify-components-select-wrapper-position: relative;
|
|
@@ -1013,15 +1017,20 @@
|
|
|
1013
1017
|
--amplify-components-select-icon-wrapper-pointer-events: none;
|
|
1014
1018
|
--amplify-components-select-icon-wrapper-small-right: var(--amplify-space-xs);
|
|
1015
1019
|
--amplify-components-select-icon-wrapper-large-right: var(--amplify-space-medium);
|
|
1016
|
-
--amplify-components-select-option-background-color:
|
|
1020
|
+
--amplify-components-select-option-background-color: transparent;
|
|
1017
1021
|
--amplify-components-select-option-color: var(--amplify-colors-font-primary);
|
|
1018
1022
|
--amplify-components-select-option-disabled-color: var(--amplify-colors-font-disabled);
|
|
1023
|
+
--amplify-components-select-option-disabled-background-color: transparent;
|
|
1019
1024
|
--amplify-components-select-white-space: nowrap;
|
|
1020
1025
|
--amplify-components-select-min-width: 6.5rem;
|
|
1021
1026
|
--amplify-components-select-small-min-width: 5.5rem;
|
|
1022
1027
|
--amplify-components-select-small-padding-inline-end: var(--amplify-space-xl);
|
|
1023
1028
|
--amplify-components-select-large-min-width: 7.5rem;
|
|
1024
1029
|
--amplify-components-select-large-padding-inline-end: var(--amplify-space-xxl);
|
|
1030
|
+
--amplify-components-select-expanded-padding-block: var(--amplify-space-xs);
|
|
1031
|
+
--amplify-components-select-expanded-padding-inline: var(--amplify-space-small);
|
|
1032
|
+
--amplify-components-select-expanded-option-padding-block: var(--amplify-space-xs);
|
|
1033
|
+
--amplify-components-select-expanded-option-padding-inline: var(--amplify-space-small);
|
|
1025
1034
|
--amplify-components-selectfield-border-color: var(--amplify-components-fieldcontrol-border-color);
|
|
1026
1035
|
--amplify-components-selectfield-color: var(--amplify-components-fieldcontrol-color);
|
|
1027
1036
|
--amplify-components-selectfield-flex-direction: column;
|
|
@@ -2939,12 +2948,6 @@ strong.amplify-text {
|
|
|
2939
2948
|
border-color: var(--amplify-components-fieldcontrol-error-border-color);
|
|
2940
2949
|
box-shadow: var(--amplify-components-fieldcontrol-error-focus-box-shadow);
|
|
2941
2950
|
}
|
|
2942
|
-
.amplify-input[disabled] {
|
|
2943
|
-
color: var(--amplify-components-fieldcontrol-disabled-color);
|
|
2944
|
-
cursor: var(--amplify-components-fieldcontrol-disabled-cursor);
|
|
2945
|
-
border-color: var(--amplify-components-fieldcontrol-disabled-border-color);
|
|
2946
|
-
background-color: var(--amplify-components-fieldcontrol-disabled-background-color);
|
|
2947
|
-
}
|
|
2948
2951
|
.amplify-input--quiet {
|
|
2949
2952
|
border-block-start: var(--amplify-components-fieldcontrol-quiet-border-block-start);
|
|
2950
2953
|
border-inline-start: var(--amplify-components-fieldcontrol-quiet-border-inline-start);
|
|
@@ -2961,6 +2964,12 @@ strong.amplify-text {
|
|
|
2961
2964
|
.amplify-input--quiet[aria-invalid=true]:focus {
|
|
2962
2965
|
box-shadow: var(--amplify-components-fieldcontrol-quiet-error-focus-box-shadow);
|
|
2963
2966
|
}
|
|
2967
|
+
.amplify-input[disabled] {
|
|
2968
|
+
color: var(--amplify-components-fieldcontrol-disabled-color);
|
|
2969
|
+
cursor: var(--amplify-components-fieldcontrol-disabled-cursor);
|
|
2970
|
+
border-color: var(--amplify-components-fieldcontrol-disabled-border-color);
|
|
2971
|
+
background-color: var(--amplify-components-fieldcontrol-disabled-background-color);
|
|
2972
|
+
}
|
|
2964
2973
|
|
|
2965
2974
|
.amplify-textarea {
|
|
2966
2975
|
box-sizing: border-box;
|
|
@@ -3011,12 +3020,6 @@ strong.amplify-text {
|
|
|
3011
3020
|
border-color: var(--amplify-components-fieldcontrol-error-border-color);
|
|
3012
3021
|
box-shadow: var(--amplify-components-fieldcontrol-error-focus-box-shadow);
|
|
3013
3022
|
}
|
|
3014
|
-
.amplify-textarea[disabled] {
|
|
3015
|
-
color: var(--amplify-components-fieldcontrol-disabled-color);
|
|
3016
|
-
cursor: var(--amplify-components-fieldcontrol-disabled-cursor);
|
|
3017
|
-
border-color: var(--amplify-components-fieldcontrol-disabled-border-color);
|
|
3018
|
-
background-color: var(--amplify-components-fieldcontrol-disabled-background-color);
|
|
3019
|
-
}
|
|
3020
3023
|
.amplify-textarea--quiet {
|
|
3021
3024
|
border-block-start: var(--amplify-components-fieldcontrol-quiet-border-block-start);
|
|
3022
3025
|
border-inline-start: var(--amplify-components-fieldcontrol-quiet-border-inline-start);
|
|
@@ -3033,6 +3036,12 @@ strong.amplify-text {
|
|
|
3033
3036
|
.amplify-textarea--quiet[aria-invalid=true]:focus {
|
|
3034
3037
|
box-shadow: var(--amplify-components-fieldcontrol-quiet-error-focus-box-shadow);
|
|
3035
3038
|
}
|
|
3039
|
+
.amplify-textarea[disabled] {
|
|
3040
|
+
color: var(--amplify-components-fieldcontrol-disabled-color);
|
|
3041
|
+
cursor: var(--amplify-components-fieldcontrol-disabled-cursor);
|
|
3042
|
+
border-color: var(--amplify-components-fieldcontrol-disabled-border-color);
|
|
3043
|
+
background-color: var(--amplify-components-fieldcontrol-disabled-background-color);
|
|
3044
|
+
}
|
|
3036
3045
|
|
|
3037
3046
|
.amplify-image {
|
|
3038
3047
|
height: var(--amplify-components-image-height);
|
|
@@ -5040,6 +5049,8 @@ html[dir=rtl] .amplify-field-group__inner-start {
|
|
|
5040
5049
|
outline-style: var(--amplify-components-fieldcontrol-outline-style);
|
|
5041
5050
|
outline-width: var(--amplify-components-fieldcontrol-outline-width);
|
|
5042
5051
|
outline-offset: var(--amplify-components-fieldcontrol-outline-offset);
|
|
5052
|
+
background-color: var(--amplify-components-select-background-color);
|
|
5053
|
+
color: var(--amplify-components-select-color);
|
|
5043
5054
|
min-width: var(--amplify-components-select-min-width);
|
|
5044
5055
|
padding-inline-end: var(--amplify-components-select-padding-inline-end);
|
|
5045
5056
|
white-space: var(--amplify-components-select-white-space);
|
|
@@ -5069,12 +5080,6 @@ html[dir=rtl] .amplify-field-group__inner-start {
|
|
|
5069
5080
|
border-color: var(--amplify-components-fieldcontrol-error-border-color);
|
|
5070
5081
|
box-shadow: var(--amplify-components-fieldcontrol-error-focus-box-shadow);
|
|
5071
5082
|
}
|
|
5072
|
-
.amplify-select[disabled] {
|
|
5073
|
-
color: var(--amplify-components-fieldcontrol-disabled-color);
|
|
5074
|
-
cursor: var(--amplify-components-fieldcontrol-disabled-cursor);
|
|
5075
|
-
border-color: var(--amplify-components-fieldcontrol-disabled-border-color);
|
|
5076
|
-
background-color: var(--amplify-components-fieldcontrol-disabled-background-color);
|
|
5077
|
-
}
|
|
5078
5083
|
.amplify-select--quiet {
|
|
5079
5084
|
border-block-start: var(--amplify-components-fieldcontrol-quiet-border-block-start);
|
|
5080
5085
|
border-inline-start: var(--amplify-components-fieldcontrol-quiet-border-inline-start);
|
|
@@ -5091,17 +5096,28 @@ html[dir=rtl] .amplify-field-group__inner-start {
|
|
|
5091
5096
|
.amplify-select--quiet[aria-invalid=true]:focus {
|
|
5092
5097
|
box-shadow: var(--amplify-components-fieldcontrol-quiet-error-focus-box-shadow);
|
|
5093
5098
|
}
|
|
5099
|
+
.amplify-select[disabled] {
|
|
5100
|
+
color: var(--amplify-components-fieldcontrol-disabled-color);
|
|
5101
|
+
cursor: var(--amplify-components-fieldcontrol-disabled-cursor);
|
|
5102
|
+
border-color: var(--amplify-components-fieldcontrol-disabled-border-color);
|
|
5103
|
+
background-color: var(--amplify-components-fieldcontrol-disabled-background-color);
|
|
5104
|
+
}
|
|
5094
5105
|
.amplify-select option {
|
|
5095
|
-
color:
|
|
5106
|
+
background-color: var(--amplify-components-select-option-background-color);
|
|
5107
|
+
color: var(--amplify-components-select-option-color);
|
|
5096
5108
|
}
|
|
5097
5109
|
.amplify-select option[disabled=""] {
|
|
5110
|
+
background-color: var(--amplify-components-select-option-disabled-background-color);
|
|
5098
5111
|
color: var(--amplify-components-select-option-disabled-color);
|
|
5112
|
+
cursor: var(--amplify-components-fieldcontrol-disabled-cursor);
|
|
5099
5113
|
}
|
|
5100
|
-
|
|
5101
|
-
|
|
5102
|
-
|
|
5103
|
-
|
|
5104
|
-
|
|
5114
|
+
.amplify-select[disabled] {
|
|
5115
|
+
background-color: var(--amplify-components-select-disabled-background-color);
|
|
5116
|
+
color: var(--amplify-components-select-disabled-color);
|
|
5117
|
+
}
|
|
5118
|
+
.amplify-select[disabled] option {
|
|
5119
|
+
color: inherit;
|
|
5120
|
+
background-color: inherit;
|
|
5105
5121
|
}
|
|
5106
5122
|
.amplify-select--small {
|
|
5107
5123
|
min-width: var(--amplify-components-select-small-min-width);
|
|
@@ -5111,6 +5127,13 @@ html[dir=rtl] .amplify-field-group__inner-start {
|
|
|
5111
5127
|
min-width: var(--amplify-components-select-large-min-width);
|
|
5112
5128
|
padding-inline-end: var(--amplify-components-select-large-padding-inline-end);
|
|
5113
5129
|
}
|
|
5130
|
+
.amplify-select--expanded {
|
|
5131
|
+
overflow: auto;
|
|
5132
|
+
padding: var(--amplify-components-select-expanded-padding-block) var(--amplify-components-select-expanded-padding-inline);
|
|
5133
|
+
}
|
|
5134
|
+
.amplify-select--expanded option {
|
|
5135
|
+
padding: var(--amplify-components-select-expanded-option-padding-block) var(--amplify-components-select-expanded-option-padding-inline);
|
|
5136
|
+
}
|
|
5114
5137
|
|
|
5115
5138
|
.amplify-selectfield {
|
|
5116
5139
|
flex-direction: var(--amplify-components-selectfield-flex-direction);
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export { default as FaceLivenessDetector, FaceLivenessDetectorProps, } from './FaceLivenessDetector';
|
|
2
2
|
export { default as FaceLivenessDetectorCore, FaceLivenessDetectorCoreProps, } from './FaceLivenessDetectorCore';
|
|
3
|
-
export { AwsCredentialProvider, AwsTemporaryCredentials, AwsCredentials, } from './service';
|
|
3
|
+
export { AwsCredentialProvider, AwsTemporaryCredentials, AwsCredentials, ErrorState, } from './service';
|
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The liveness error states
|
|
3
3
|
*/
|
|
4
|
-
export declare
|
|
5
|
-
TIMEOUT
|
|
6
|
-
RUNTIME_ERROR
|
|
7
|
-
FRESHNESS_TIMEOUT
|
|
8
|
-
SERVER_ERROR
|
|
9
|
-
CAMERA_FRAMERATE_ERROR
|
|
10
|
-
CAMERA_ACCESS_ERROR
|
|
11
|
-
FACE_DISTANCE_ERROR
|
|
12
|
-
MOBILE_LANDSCAPE_ERROR
|
|
13
|
-
MULTIPLE_FACES_ERROR
|
|
14
|
-
}
|
|
4
|
+
export declare const LivenessErrorState: {
|
|
5
|
+
readonly TIMEOUT: "TIMEOUT";
|
|
6
|
+
readonly RUNTIME_ERROR: "RUNTIME_ERROR";
|
|
7
|
+
readonly FRESHNESS_TIMEOUT: "FRESHNESS_TIMEOUT";
|
|
8
|
+
readonly SERVER_ERROR: "SERVER_ERROR";
|
|
9
|
+
readonly CAMERA_FRAMERATE_ERROR: "CAMERA_FRAMERATE_ERROR";
|
|
10
|
+
readonly CAMERA_ACCESS_ERROR: "CAMERA_ACCESS_ERROR";
|
|
11
|
+
readonly FACE_DISTANCE_ERROR: "FACE_DISTANCE_ERROR";
|
|
12
|
+
readonly MOBILE_LANDSCAPE_ERROR: "MOBILE_LANDSCAPE_ERROR";
|
|
13
|
+
readonly MULTIPLE_FACES_ERROR: "MULTIPLE_FACES_ERROR";
|
|
14
|
+
};
|
|
15
|
+
export type ErrorState = keyof typeof LivenessErrorState;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AwsCredentialProvider } from './credentials';
|
|
2
|
-
import {
|
|
2
|
+
import { ErrorState } from './error';
|
|
3
3
|
/**
|
|
4
4
|
* The props for the FaceLivenessDetectorCore which allows for full configuration of auth
|
|
5
5
|
*/
|
|
@@ -100,6 +100,6 @@ export declare enum FaceMatchState {
|
|
|
100
100
|
TOO_MANY = "TOO MANY FACES"
|
|
101
101
|
}
|
|
102
102
|
export interface LivenessError {
|
|
103
|
-
state:
|
|
103
|
+
state: ErrorState;
|
|
104
104
|
error: Error;
|
|
105
105
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ActorRef, Interpreter, State } from 'xstate';
|
|
2
2
|
import { ValidationException, InternalServerException, ThrottlingException, ServiceQuotaExceededException, SessionInformation } from '@aws-sdk/client-rekognitionstreaming';
|
|
3
3
|
import { FaceLivenessDetectorCoreProps, FaceMatchState, LivenessOvalDetails, IlluminationState } from './liveness';
|
|
4
|
-
import {
|
|
4
|
+
import { ErrorState } from './error';
|
|
5
5
|
import { VideoRecorder, LivenessStreamProvider, FreshnessColorDisplay } from '../utils';
|
|
6
6
|
import { Face, FaceDetection } from './faceDetection';
|
|
7
7
|
export interface FaceMatchAssociatedParams {
|
|
@@ -45,7 +45,7 @@ export interface HydratedLivenessContext {
|
|
|
45
45
|
ovalAssociatedParams: OvalAssociatedParams;
|
|
46
46
|
faceMatchAssociatedParams: FaceMatchAssociatedParams;
|
|
47
47
|
freshnessColorAssociatedParams: FreshnessColorAssociatedParams;
|
|
48
|
-
errorState:
|
|
48
|
+
errorState: ErrorState;
|
|
49
49
|
livenessStreamProvider: LivenessStreamProvider;
|
|
50
50
|
responseStreamActorRef: ActorRef<any>;
|
|
51
51
|
shouldDisconnect: boolean;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { LivenessOvalDetails, IlluminationState, Face, FaceMatchState, BoundingBox,
|
|
1
|
+
import { LivenessOvalDetails, IlluminationState, Face, FaceMatchState, BoundingBox, ErrorState } from '../types';
|
|
2
2
|
import { FaceDetection } from '../types/faceDetection';
|
|
3
3
|
import { ClientFreshnessColorSequence } from '../types/service';
|
|
4
4
|
import { ColorSequence, SessionInformation } from '@aws-sdk/client-rekognitionstreaming';
|
|
@@ -62,7 +62,17 @@ export declare function estimateIllumination(videoEl: HTMLVideoElement): Illumin
|
|
|
62
62
|
* @param device
|
|
63
63
|
*/
|
|
64
64
|
export declare function isCameraDeviceVirtual(device: MediaDeviceInfo): boolean;
|
|
65
|
-
export declare const LivenessErrorStateStringMap:
|
|
65
|
+
export declare const LivenessErrorStateStringMap: {
|
|
66
|
+
RUNTIME_ERROR: string;
|
|
67
|
+
SERVER_ERROR: string;
|
|
68
|
+
TIMEOUT: string;
|
|
69
|
+
FACE_DISTANCE_ERROR: string;
|
|
70
|
+
MULTIPLE_FACES_ERROR: string;
|
|
71
|
+
CAMERA_FRAMERATE_ERROR: string;
|
|
72
|
+
CAMERA_ACCESS_ERROR: string;
|
|
73
|
+
MOBILE_LANDSCAPE_ERROR: string;
|
|
74
|
+
FRESHNESS_TIMEOUT: string;
|
|
75
|
+
};
|
|
66
76
|
export declare const MOCK_COLOR_SEQUENCES: ColorSequence[];
|
|
67
77
|
interface FillOverlayCanvasFractionalInput {
|
|
68
78
|
overlayCanvas: HTMLCanvasElement;
|
|
@@ -86,7 +96,7 @@ export declare function isFaceDistanceBelowThreshold({ faceDetector, videoEl, ov
|
|
|
86
96
|
isMobile?: boolean;
|
|
87
97
|
}): Promise<{
|
|
88
98
|
isDistanceBelowThreshold: boolean;
|
|
89
|
-
error?:
|
|
99
|
+
error?: ErrorState;
|
|
90
100
|
}>;
|
|
91
101
|
export declare function getBoundingBox({ deviceHeight, deviceWidth, height, width, top, left, }: {
|
|
92
102
|
deviceHeight: number;
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { AmazonAIInterpretPredictionsProvider } from '@aws-amplify/predictions';
|
|
2
1
|
import { ClientSessionInformationEvent, LivenessResponseStream } from '@aws-sdk/client-rekognitionstreaming';
|
|
3
2
|
import { VideoRecorder } from './videoRecorder';
|
|
4
3
|
import { AwsCredentialProvider } from '../types';
|
|
@@ -22,7 +21,7 @@ export interface StreamProviderArgs {
|
|
|
22
21
|
credentialProvider?: AwsCredentialProvider;
|
|
23
22
|
}
|
|
24
23
|
export declare const TIME_SLICE = 1000;
|
|
25
|
-
export declare class LivenessStreamProvider
|
|
24
|
+
export declare class LivenessStreamProvider {
|
|
26
25
|
sessionId: string;
|
|
27
26
|
region: string;
|
|
28
27
|
videoRecorder: VideoRecorder;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
|
-
import {
|
|
2
|
+
import { ErrorState } from '../service';
|
|
3
3
|
import { ErrorDisplayText } from '../displayText';
|
|
4
4
|
export interface CheckScreenComponents {
|
|
5
5
|
ErrorView?: React.ComponentType<FaceLivenessErrorModalProps>;
|
|
@@ -10,7 +10,7 @@ export interface FaceLivenessErrorModalProps {
|
|
|
10
10
|
onRetry: () => void;
|
|
11
11
|
}
|
|
12
12
|
export declare const renderErrorModal: ({ errorState, overrideErrorDisplayText, }: {
|
|
13
|
-
errorState:
|
|
13
|
+
errorState: ErrorState;
|
|
14
14
|
overrideErrorDisplayText?: Partial<{
|
|
15
15
|
timeoutHeaderText: string;
|
|
16
16
|
timeoutMessageText: string;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as React from 'react';
|
|
2
2
|
import { IlluminationState, FaceMatchState } from '../service';
|
|
3
3
|
import { HintDisplayText } from '../displayText';
|
|
4
|
-
export declare const selectErrorState: import("../hooks").LivenessSelectorFn<
|
|
4
|
+
export declare const selectErrorState: import("../hooks").LivenessSelectorFn<"TIMEOUT" | "RUNTIME_ERROR" | "FRESHNESS_TIMEOUT" | "SERVER_ERROR" | "CAMERA_FRAMERATE_ERROR" | "CAMERA_ACCESS_ERROR" | "FACE_DISTANCE_ERROR" | "MOBILE_LANDSCAPE_ERROR" | "MULTIPLE_FACES_ERROR" | undefined>;
|
|
5
5
|
export declare const selectFaceMatchState: import("../hooks").LivenessSelectorFn<FaceMatchState | undefined>;
|
|
6
6
|
export declare const selectIlluminationState: import("../hooks").LivenessSelectorFn<IlluminationState | undefined>;
|
|
7
7
|
export declare const selectIsFaceFarEnoughBeforeRecording: import("../hooks").LivenessSelectorFn<boolean | undefined>;
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { FaceLivenessDetector, FaceLivenessDetectorProps, FaceLivenessDetectorCore, FaceLivenessDetectorCoreProps, AwsCredentialProvider, AwsCredentials, AwsTemporaryCredentials, } from './components';
|
|
1
|
+
export { FaceLivenessDetector, FaceLivenessDetectorProps, FaceLivenessDetectorCore, FaceLivenessDetectorCoreProps, AwsCredentialProvider, AwsCredentials, AwsTemporaryCredentials, ErrorState, } from './components';
|
package/dist/types/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const VERSION = "2.0.
|
|
1
|
+
export declare const VERSION = "2.0.8";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aws-amplify/ui-react-liveness",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.8",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"module": "dist/esm/index.mjs",
|
|
6
6
|
"exports": {
|
|
@@ -48,10 +48,13 @@
|
|
|
48
48
|
"react-dom": ">= 16.14.0"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@aws-amplify/ui": "5.8.
|
|
52
|
-
"@aws-amplify/ui-react": "5.3.
|
|
51
|
+
"@aws-amplify/ui": "5.8.1",
|
|
52
|
+
"@aws-amplify/ui-react": "5.3.1",
|
|
53
53
|
"@aws-sdk/client-rekognitionstreaming": "3.398.0",
|
|
54
|
+
"@aws-sdk/util-format-url": "^3.410.0",
|
|
54
55
|
"@smithy/eventstream-serde-browser": "^2.0.4",
|
|
56
|
+
"@smithy/fetch-http-handler": "^2.1.3",
|
|
57
|
+
"@smithy/protocol-http": "^3.0.3",
|
|
55
58
|
"@tensorflow-models/blazeface": "0.0.7",
|
|
56
59
|
"@tensorflow/tfjs-backend-cpu": "3.11.0",
|
|
57
60
|
"@tensorflow/tfjs-backend-wasm": "3.11.0",
|