@aws-amplify/ui-react-liveness 1.0.1 → 1.0.2

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.
@@ -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"./service/types/error.mjs";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/liveness.mjs";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 m}from"./providers/FaceLivenessDetectorProvider.mjs";import{StartLiveness as n}from"./StartLiveness/StartLiveness.mjs";import{LivenessCheck as a}from"./LivenessCheck/LivenessCheck.mjs";import{getVideoConstraints as c}from"./StartLiveness/helpers.mjs";import{getDisplayText as p}from"./utils/getDisplayText.mjs";const l="liveness-detector";function f(f){const{disableInstructionScreen:v=!1,components:u,config:y,displayText:d}=f,j=e.useRef(null),{hintDisplayText:x,cameraDisplayText:D,instructionDisplayText:T,streamDisplayText:h,errorDisplayText:E}=p(d),b=t(r,{devTools:"development"===process.env.NODE_ENV,context:{componentProps:Object.assign(Object.assign({},f),{config:null!=y?y:{}})}}),[L,w]=s(b),C=L.matches("start")||L.matches("userCancel"),g=e.useCallback((()=>{const e=c();w({type:"BEGIN",data:{videoConstraints:e}})}),[w]);return e.useLayoutEffect((()=>{v&&C&&g()}),[g,v,C]),e.createElement(o,{className:l,testId:l},e.createElement(m,{componentProps:f,service:b},e.createElement(i,{direction:"column",ref:j},C?e.createElement(n,{beginLivenessCheck:g,components:u,instructionDisplayText:T}):e.createElement(a,{hintDisplayText:x,cameraDisplayText:D,streamDisplayText:h,errorDisplayText:E,components:u}))))}export{f as default};
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"./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/liveness.mjs";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 m}from"./providers/FaceLivenessDetectorProvider.mjs";import{StartLiveness as n}from"./StartLiveness/StartLiveness.mjs";import{LivenessCheck as a}from"./LivenessCheck/LivenessCheck.mjs";import{getVideoConstraints as c}from"./StartLiveness/helpers.mjs";import{getDisplayText as p}from"./utils/getDisplayText.mjs";const l="liveness-detector";function f(f){const{disableInstructionScreen:v=!1,components:u,config:y,displayText:d}=f,j=e.useRef(null),{hintDisplayText:x,cameraDisplayText:D,instructionDisplayText:T,streamDisplayText:h,errorDisplayText:b}=p(d),E=t(r,{devTools:"development"===process.env.NODE_ENV,context:{componentProps:Object.assign(Object.assign({},f),{config:null!=y?y:{}})}}),[L,w]=s(E),C=L.matches("start")||L.matches("userCancel"),g=e.useCallback((()=>{const e=c();w({type:"BEGIN",data:{videoConstraints:e}})}),[w]);return e.useLayoutEffect((()=>{v&&C&&g()}),[g,v,C]),e.createElement(o,{className:l,testId:l},e.createElement(m,{componentProps:f,service:E},e.createElement(i,{direction:"column",ref:j},C?e.createElement(n,{beginLivenessCheck:g,components:u,instructionDisplayText:T}):e.createElement(a,{hintDisplayText:x,cameraDisplayText:D,streamDisplayText:h,errorDisplayText:b,components:u}))))}export{f as default};
@@ -1 +1 @@
1
- import e,{useRef as t,useState as r}from"react";import a from"react-countdown-circle-timer";import o from"classnames";import{Loader as s,useTheme as i,Flex as n,View as c,Text as m}from"@aws-amplify/ui-react";import"../service/machine/index.mjs";import{FaceMatchState as l}from"../service/types/liveness.mjs";import"../service/types/error.mjs";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/liveness.mjs";import"../service/utils/streamProvider.mjs";import"../service/utils/freshnessColorDisplay.mjs";import{useLivenessActor as d}from"../hooks/useLivenessActor.mjs";import{useLivenessSelector as h,createLivenessSelector as p}from"../hooks/useLivenessSelector.mjs";import{useMediaStreamInVideo as v}from"../hooks/useMediaStreamInVideo.mjs";import{CancelButton as u}from"../shared/CancelButton.mjs";import{selectErrorState as f,Hint as E}from"../shared/Hint.mjs";import{MatchIndicator as C}from"../shared/MatchIndicator.mjs";import{Overlay as y}from"../shared/Overlay.mjs";import{RecordingIcon as g}from"../shared/RecordingIcon.mjs";import{LivenessClassNames as j}from"../types/classNames.mjs";import{renderErrorModal as T,FaceLivenessErrorModal as w}from"../shared/FaceLivenessErrorModal.mjs";const N=p((e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoConstraints})),x=p((e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoMediaStream})),A=p((e=>e.context.faceMatchAssociatedParams.faceMatchPercentage)),I=p((e=>e.context.faceMatchAssociatedParams.faceMatchState)),M=e.createElement(s,{size:"large",className:j.Loader,"data-testid":"centered-loader"}),D=s=>{const{isMobileScreen:p,isRecordingStopped:D,streamDisplayText:b,hintDisplayText:k,errorDisplayText:R,components:S,testId:O}=s,{cancelLivenessCheckText:L,recordingIndicatorText:P}=b,{ErrorView:F=w}=null!=S?S:{},{tokens:_}=i(),[z,H]=d(),W=h(x),V=h(N),$=h(A),B=h(I),G=h(f),X=[l.TOO_FAR,l.CANT_IDENTIFY,l.FACE_IDENTIFIED,l.MATCHED],{videoRef:Y,videoWidth:q,videoHeight:J}=v(W,V),K=t(null),Q=t(null),[U,Z]=r(!1),[ee,te]=r(!1),re=z.matches("cameraCheck"),ae=z.matches("notRecording"),oe=z.matches("recording"),se=z.matches("checkSucceeded"),ie=z.matches({recording:"flashFreshnessColors"}),[ne,ce]=r(q),[me,le]=r(J),[de,he]=r((()=>q&&J?q/J:0));e.useLayoutEffect((()=>{ee&&H({type:"SET_DOM_AND_CAMERA_DETAILS",data:{videoEl:Y.current,canvasEl:K.current,freshnessColorEl:Q.current,isMobile:p}}),Y.current&&(ce(Y.current.videoWidth),le(Y.current.videoHeight),he(Y.current.videoWidth/Y.current.videoHeight))}),[H,Y,ee,p]);return re?e.createElement(n,{height:J,width:"100%",position:"relative"},M):e.createElement(n,{className:o(j.CameraModule,p&&`${j.CameraModule}--mobile`),"data-testid":O},!ee&&M,e.createElement(c,{as:"canvas",ref:Q,className:j.FreshnessCanvas,hidden:!0}),e.createElement(c,{className:j.VideoAnchor,style:{aspectRatio:`${de}`}},e.createElement("video",{ref:Y,muted:!0,autoPlay:!0,playsInline:!0,style:{transform:"scaleX(-1)"},width:ne,height:me,onCanPlay:()=>{te(!0),Z(!0)},"data-testid":"video",className:j.Video}),e.createElement(n,{className:o(j.OvalCanvas,p&&`${j.OvalCanvas}--mobile`,D&&j.FadeOut)},e.createElement(c,{as:"canvas",width:"100%",height:"100%",ref:K})),oe&&e.createElement(c,{className:j.RecordingIconContainer},e.createElement(g,null,P)),!se&&e.createElement(c,{className:j.CancelContainer},e.createElement(u,{ariaLabel:L})),U&&e.createElement(y,{anchorOrigin:{horizontal:"center",vertical:oe&&!ie?"start":"space-between"},className:j.InstructionOverlay},e.createElement(E,{hintDisplayText:k}),G&&e.createElement(F,{onRetry:()=>{H({type:"CANCEL"})}},T({errorState:G,overrideErrorDisplayText:R})),oe&&!ie&&X.includes(B)?e.createElement(C,{percentage:$}):null,ae&&e.createElement(c,{className:j.CountdownContainer,testId:"liveness-camera-countdown-timer"},e.createElement(a.CountdownCircleTimer,{isPlaying:ae,size:85,strokeWidth:8,duration:3,rotation:"counterclockwise",colors:"#40aabf",trailColor:`${_.colors.background.primary}`,onComplete:()=>{H({type:"START_RECORDING"})}},(({remainingTime:t})=>e.createElement(m,{fontSize:"xxxl",fontWeight:"bold"},t)))))))};export{D as LivenessCameraModule,A as selectFaceMatchPercentage,I as selectFaceMatchState,N as selectVideoConstraints,x as selectVideoStream};
1
+ import e,{useRef as t,useState as r}from"react";import a from"react-countdown-circle-timer";import o from"classnames";import{Loader as s,useTheme as i,Flex as n,View as c,Text as m}from"@aws-amplify/ui-react";import"../service/machine/index.mjs";import{FaceMatchState as l}from"../service/types/liveness.mjs";import"../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/liveness.mjs";import"../service/utils/streamProvider.mjs";import"../service/utils/freshnessColorDisplay.mjs";import{useLivenessActor as d}from"../hooks/useLivenessActor.mjs";import{useLivenessSelector as p,createLivenessSelector as h}from"../hooks/useLivenessSelector.mjs";import{useMediaStreamInVideo as v}from"../hooks/useMediaStreamInVideo.mjs";import{CancelButton as u}from"../shared/CancelButton.mjs";import{selectErrorState as f,Hint as E}from"../shared/Hint.mjs";import{MatchIndicator as C}from"../shared/MatchIndicator.mjs";import{Overlay as y}from"../shared/Overlay.mjs";import{RecordingIcon as g}from"../shared/RecordingIcon.mjs";import{LivenessClassNames as j}from"../types/classNames.mjs";import{renderErrorModal as T,FaceLivenessErrorModal as w}from"../shared/FaceLivenessErrorModal.mjs";const N=h((e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoConstraints})),x=h((e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoMediaStream})),A=h((e=>e.context.faceMatchAssociatedParams.faceMatchPercentage)),I=h((e=>e.context.faceMatchAssociatedParams.faceMatchState)),M=e.createElement(s,{size:"large",className:j.Loader,"data-testid":"centered-loader"}),D=s=>{const{isMobileScreen:h,isRecordingStopped:D,streamDisplayText:b,hintDisplayText:k,errorDisplayText:R,components:S,testId:O}=s,{cancelLivenessCheckText:L,recordingIndicatorText:P}=b,{ErrorView:F=w}=null!=S?S:{},{tokens:_}=i(),[z,H]=d(),W=p(x),V=p(N),$=p(A),B=p(I),G=p(f),X=[l.TOO_FAR,l.CANT_IDENTIFY,l.FACE_IDENTIFIED,l.MATCHED],{videoRef:Y,videoWidth:q,videoHeight:J}=v(W,V),K=t(null),Q=t(null),[U,Z]=r(!1),[ee,te]=r(!1),re=z.matches("cameraCheck"),ae=z.matches("notRecording"),oe=z.matches("recording"),se=z.matches("checkSucceeded"),ie=z.matches({recording:"flashFreshnessColors"}),[ne,ce]=r(q),[me,le]=r(J),[de,pe]=r((()=>q&&J?q/J:0));e.useLayoutEffect((()=>{ee&&H({type:"SET_DOM_AND_CAMERA_DETAILS",data:{videoEl:Y.current,canvasEl:K.current,freshnessColorEl:Q.current,isMobile:h}}),Y.current&&(ce(Y.current.videoWidth),le(Y.current.videoHeight),pe(Y.current.videoWidth/Y.current.videoHeight))}),[H,Y,ee,h]);return re?e.createElement(n,{height:J,width:"100%",position:"relative"},M):e.createElement(n,{className:o(j.CameraModule,h&&`${j.CameraModule}--mobile`),"data-testid":O},!ee&&M,e.createElement(c,{as:"canvas",ref:Q,className:j.FreshnessCanvas,hidden:!0}),e.createElement(c,{className:j.VideoAnchor,style:{aspectRatio:`${de}`}},e.createElement("video",{ref:Y,muted:!0,autoPlay:!0,playsInline:!0,style:{transform:"scaleX(-1)"},width:ne,height:me,onCanPlay:()=>{te(!0),Z(!0)},"data-testid":"video",className:j.Video}),e.createElement(n,{className:o(j.OvalCanvas,h&&`${j.OvalCanvas}--mobile`,D&&j.FadeOut)},e.createElement(c,{as:"canvas",width:"100%",height:"100%",ref:K})),oe&&e.createElement(c,{className:j.RecordingIconContainer},e.createElement(g,null,P)),!se&&e.createElement(c,{className:j.CancelContainer},e.createElement(u,{ariaLabel:L})),U&&e.createElement(y,{anchorOrigin:{horizontal:"center",vertical:oe&&!ie?"start":"space-between"},className:j.InstructionOverlay},e.createElement(E,{hintDisplayText:k}),G&&e.createElement(F,{onRetry:()=>{H({type:"CANCEL"})}},T({errorState:G,overrideErrorDisplayText:R})),oe&&!ie&&X.includes(B)?e.createElement(C,{percentage:$}):null,ae&&e.createElement(c,{className:j.CountdownContainer,testId:"liveness-camera-countdown-timer"},e.createElement(a.CountdownCircleTimer,{isPlaying:ae,size:85,strokeWidth:8,duration:3,rotation:"counterclockwise",colors:"#40aabf",trailColor:`${_.colors.background.primary}`,onComplete:()=>{H({type:"START_RECORDING"})}},(({remainingTime:t})=>e.createElement(m,{fontSize:"xxxl",fontWeight:"bold"},t)))))))};export{D as LivenessCameraModule,A as selectFaceMatchPercentage,I as selectFaceMatchState,N as selectVideoConstraints,x 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"@tensorflow/tfjs-core";import"@tensorflow-models/blazeface";import"@tensorflow/tfjs-backend-wasm";import"@tensorflow/tfjs-backend-cpu";import"@aws-amplify/core";import"../service/utils/liveness.mjs";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 u}from"../displayText.mjs";import{LandscapeErrorModal as f}from"../shared/LandscapeErrorModal.mjs";const E="liveness-detector-check",g=c((e=>e.context.errorState)),y=c((e=>e.context.isRecordingStopped)),x=({hintDisplayText:c,cameraDisplayText:x,streamDisplayText:h,errorDisplayText:R,components:T})=>{const[A,j]=n(),v=m(g),C=m(y),M=A.matches("permissionDenied"),b=p(),L=()=>{j({type:"RETRY_CAMERA_CHECK"})},{cameraMinSpecificationsHeadingText:k,cameraMinSpecificationsMessageText:D,cameraNotFoundHeadingText:w,cameraNotFoundMessageText:S,retryCameraPermissionsText:_}=x,{cancelLivenessCheckText:N}=h;e.useLayoutEffect((()=>{if(b){const e=e=>{e&&j({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,j]);return e.createElement(t,{direction:"column",position:"relative",testId:E,className:E},(()=>{if(v===o.MOBILE_LANDSCAPE_ERROR){const r=Object.assign(Object.assign({},u),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(f,{header:s,portraitMessage:i,landscapeMessage:o,tryAgainText:a,onRetry:()=>{j({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"},v===o.CAMERA_FRAMERATE_ERROR?k:w),e.createElement(r,{maxWidth:300},v===o.CAMERA_FRAMERATE_ERROR?D:S),e.createElement(s,{variation:"primary",type:"button",onClick:L},_),e.createElement(i,{position:"absolute",top:"medium",right:"medium"},e.createElement(d,{ariaLabel:N}))):e.createElement(a,{isMobileScreen:b,isRecordingStopped:C,streamDisplayText:h,hintDisplayText:c,errorDisplayText:R,components:T})})())};export{x as LivenessCheck,g as selectErrorState,y as selectIsRecordingStopped};
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/liveness.mjs";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 u}from"../displayText.mjs";import{LandscapeErrorModal as f}from"../shared/LandscapeErrorModal.mjs";const E="liveness-detector-check",g=c((e=>e.context.errorState)),y=c((e=>e.context.isRecordingStopped)),x=({hintDisplayText:c,cameraDisplayText:x,streamDisplayText:h,errorDisplayText:R,components:T})=>{const[A,j]=n(),v=m(g),C=m(y),M=A.matches("permissionDenied"),b=p(),L=()=>{j({type:"RETRY_CAMERA_CHECK"})},{cameraMinSpecificationsHeadingText:k,cameraMinSpecificationsMessageText:D,cameraNotFoundHeadingText:w,cameraNotFoundMessageText:S,retryCameraPermissionsText:_}=x,{cancelLivenessCheckText:N}=h;e.useLayoutEffect((()=>{if(b){const e=e=>{e&&j({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,j]);return e.createElement(t,{direction:"column",position:"relative",testId:E,className:E},(()=>{if(v===o.MOBILE_LANDSCAPE_ERROR){const r=Object.assign(Object.assign({},u),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(f,{header:s,portraitMessage:i,landscapeMessage:o,tryAgainText:a,onRetry:()=>{j({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"},v===o.CAMERA_FRAMERATE_ERROR?k:w),e.createElement(r,{maxWidth:300},v===o.CAMERA_FRAMERATE_ERROR?D:S),e.createElement(s,{variation:"primary",type:"button",onClick:L},_),e.createElement(i,{position:"absolute",top:"medium",right:"medium"},e.createElement(d,{ariaLabel:N}))):e.createElement(a,{isMobileScreen:b,isRecordingStopped:C,streamDisplayText:h,hintDisplayText:c,errorDisplayText:R,components:T})})())};export{x as LivenessCheck,g as selectErrorState,y as selectIsRecordingStopped};
@@ -1 +1 @@
1
- import{__rest as e}from"../../../node_modules/tslib/tslib.es6.mjs";import t from"react";const r=t.createContext(null);function n(n){var{children:o}=n,i=e(n,["children"]);return t.createElement(r.Provider,{value:i},o)}function o(){const e=t.useContext(r);if(null===e)throw new Error("useFaceLivenessDetector must be used within a FaceLivenessDetectorProvider");return e}export{n as FaceLivenessDetectorProvider,o as useFaceLivenessDetector};
1
+ import{__rest as e}from"tslib";import r from"react";const t=r.createContext(null);function n(n){var{children:o}=n,i=e(n,["children"]);return r.createElement(t.Provider,{value:i},o)}function o(){const e=r.useContext(t);if(null===e)throw new Error("useFaceLivenessDetector must be used within a FaceLivenessDetectorProvider");return e}export{n as FaceLivenessDetectorProvider,o as useFaceLivenessDetector};
@@ -1 +1 @@
1
- import{__awaiter as e,__asyncValues as t}from"../../../../node_modules/tslib/tslib.es6.mjs";import{createMachine as a,assign as o,spawn as i,actions as r}from"xstate";import{getBoundingBox as s,getColorsSequencesFromSessionInformation as n,LivenessErrorStateStringMap as c,isCameraDeviceVirtual as d,getFaceMatchState as l,isFaceDistanceBelowThreshold as v,estimateIllumination as m,getOvalDetailsFromSessionInformation as h,generateBboxFromLandmarks as g,drawLivenessOvalInCanvas as f,getOvalBoundingBox as u,getIntersectionOverUnion as S,getFaceMatchStateInLivenessOval as p,getStaticLivenessOvalDetails as F}from"../utils/liveness.mjs";import{FaceMatchState as D}from"../types/liveness.mjs";import{LivenessErrorState as E}from"../types/error.mjs";import{BlazeFaceFaceDetection as A}from"../utils/blazefaceFaceDetection.mjs";import{LivenessStreamProvider as M}from"../utils/streamProvider.mjs";import{FreshnessColorDisplay as R}from"../utils/freshnessColorDisplay.mjs";import{nanoid as C}from"nanoid";import{isServerSesssionInformationEvent as P,isDisconnectionEvent as T,isValidationExceptionEvent as O,isInternalServerExceptionEvent as I,isThrottlingExceptionEvent as w,isServiceQuotaExceededExceptionEvent as y,isInvalidSignatureRegionException as b}from"../utils/eventUtils.mjs";const k=500;let B;const j=a({id:"livenessMachine",initial:"start",predictableActionArguments:!0,context:{challengeId:C(),maxFailedAttempts:0,failedAttempts:0,componentProps:void 0,serverSessionInformation:void 0,videoAssociatedParams:void 0,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"},MOBILE_LANDSCAPE_WARNING:{target:"mobileLandscapeWarning",actions:"updateErrorStateForServer"}},states:{start:{on:{BEGIN:"cameraCheck"}},cameraCheck:{entry:["resetErrorState","setVideoConstraints","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:"waitForSessionInfo",actions:["updateLivenessStreamProvider","spawnResponseStreamActor"]}}},waitForSessionInfo:{after:{0:{target:"notRecording",cond:"hasServerSessionInfo"},100:{target:"waitForSessionInfo"}}},notRecording:{on:{START_RECORDING:"recording"},initial:"detectFaceDistanceDuringCountdown",states:{detectFaceDistanceDuringCountdown:{invoke:{src:"detectFaceDistance",onDone:{target:"checkFaceDistanceDuringCountdown",actions:["updateFaceDistanceBeforeRecording"]}}},checkFaceDistanceDuringCountdown:{after:{0:{target:"failure",cond:"hasNotEnoughFaceDistanceBeforeRecording"},200:{target:"detectFaceDistanceDuringCountdown"}}},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:o({responseStreamActorRef:()=>i(_)}),updateFailedAttempts:o({failedAttempts:e=>e.failedAttempts+1}),setVideoConstraints:o({videoAssociatedParams:(e,t)=>{var a,o;return Object.assign(Object.assign({},e.videoAssociatedParams),{videoConstraints:(null===(a=t.data)||void 0===a?void 0:a.videoConstraints)||(null===(o=e.videoAssociatedParams)||void 0===o?void 0:o.videoConstraints)})}}),updateVideoMediaStream:o({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:o({ovalAssociatedParams:e=>{const{componentProps:t}=e,{faceModelUrl:a,binaryPath:o}=t.config,i=new A(o,a);return i.triggerModelLoading(),Object.assign(Object.assign({},e.ovalAssociatedParams),{faceDetector:i})}}),updateLivenessStreamProvider:o({livenessStreamProvider:(e,t)=>{var a;return null===(a=t.data)||void 0===a?void 0:a.livenessStreamProvider}}),setDOMAndCameraDetails:o({videoAssociatedParams:(e,t)=>{var a,o,i;return Object.assign(Object.assign({},e.videoAssociatedParams),{videoEl:null===(a=t.data)||void 0===a?void 0:a.videoEl,canvasEl:null===(o=t.data)||void 0===o?void 0:o.canvasEl,isMobile:null===(i=t.data)||void 0===i?void 0:i.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:o({videoAssociatedParams:e=>{const{challengeId:t,videoAssociatedParams:a,ovalAssociatedParams:o,livenessStreamProvider:i}=e,{recordingStartApiTimestamp:r,recorderStartTimestamp:n}=i.videoRecorder,{videoMediaStream:c}=a,{initialFace:d}=o,l=Math.round(.73*(n-r)+r),{width:v,height:m}=c.getTracks()[0].getSettings(),h=v-d.left-d.width;return e.livenessStreamProvider.sendClientInfo({Challenge:{FaceMovementAndLightChallenge:{ChallengeId:t,VideoStartTimestamp:l,InitialFace:{InitialFaceDetectedTimestamp:d.timestampMs,BoundingBox:s({deviceHeight:m,deviceWidth:v,height:d.height,width:d.width,top:d.top,left:h})}}}}),Object.assign(Object.assign({},e.videoAssociatedParams),{recordingStartTimestampMs:l})}}),startRecording:o({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:o({faceMatchStateBeforeStart:(e,t)=>t.data.faceMatchState}),updateFaceDistanceBeforeRecording:o({isFaceFarEnoughBeforeRecording:(e,t)=>t.data.isFaceFarEnoughBeforeRecording}),updateOvalAndFaceDetailsPostDraw:o({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:o({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:o({faceMatchAssociatedParams:e=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{endFace:e.faceMatchAssociatedParams.currentDetectedFace})}),setFaceMatchTimeAndStartFace:o({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:o({errorState:e=>{}}),updateErrorStateForTimeout:o({errorState:(e,t)=>{var a;return(null===(a=t.data)||void 0===a?void 0:a.errorState)||E.TIMEOUT}}),updateErrorStateForRuntime:o({errorState:e=>E.RUNTIME_ERROR}),updateErrorStateForServer:o({errorState:e=>E.SERVER_ERROR}),clearErrorState:o({errorState:e=>{}}),updateSessionInfo:o({serverSessionInformation:(e,t)=>t.data.sessionInfo}),updateShouldDisconnect:o({shouldDisconnect:e=>!0}),updateFreshnessDetails:o({freshnessColorAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorsComplete:t.data.freshnessColorsComplete})}),setupFlashFreshnessColors:o({freshnessColorAssociatedParams:e=>{const{serverSessionInformation:t}=e,a=n(t),o=new R(e,a);return Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorDisplay:o})}}),sendTimeoutAfterOvalDrawingDelay:r.send({type:"TIMEOUT"},{delay:5e3,id:"ovalDrawingTimeout"}),cancelOvalDrawingTimeout:r.cancel("ovalDrawingTimeout"),sendTimeoutAfterOvalMatchDelay:r.send({type:"TIMEOUT"},{delay:7e3,id:"ovalMatchTimeout"}),cancelOvalMatchTimeout:r.cancel("ovalMatchTimeout"),sendTimeoutAfterWaitingForDisconnect:r.send({type:"TIMEOUT",data:{errorState:E.SERVER_ERROR}},{delay:2e4,id:"waitForDisconnectTimeout"}),cancelWaitForDisconnectTimeout:r.cancel("waitForDisconnectTimeout"),sendTimeoutAfterFaceDistanceDelay:r.send({type:"TIMEOUT",data:{errorState:E.FACE_DISTANCE_ERROR}},{delay:0,id:"faceDistanceTimeout"}),cancelFaceDistanceTimeout:r.cancel("faceDistanceTimeout"),callUserPermissionDeniedCallback:o({errorState:(e,t)=>{var a,o;let i;i=t.data.message.includes("15 fps")?E.CAMERA_FRAMERATE_ERROR:E.CAMERA_ACCESS_ERROR;const r=t.data.message||t.data.Message,s=new Error(r);return s.name=i,null===(o=(a=e.componentProps).onError)||void 0===o||o.call(a,s),i}}),callMobileLandscapeWarningCallback:o({errorState:e=>E.MOBILE_LANDSCAPE_ERROR}),callUserCancelCallback:t=>e(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(void 0,void 0,void 0,(function*(){var e,a;const o=new Error(c[t.errorState]);o.name=t.errorState,null===(a=(e=t.componentProps).onError)||void 0===a||a.call(e,o)})),callErrorCallback:(t,a)=>e(void 0,void 0,void 0,(function*(){var e,o,i,r,s,n;const c=(null===(o=null===(e=a.data)||void 0===e?void 0:e.error)||void 0===o?void 0:o.message)||(null===(r=null===(i=a.data)||void 0===i?void 0:i.error)||void 0===r?void 0:r.Message),d=new Error(c);d.name=t.errorState,null===(n=(s=t.componentProps).onError)||void 0===n||n.call(s,d)})),cleanUpResources:t=>e(void 0,void 0,void 0,(function*(){var e;const{freshnessColorEl:a}=t.freshnessColorAssociatedParams;a&&(a.style.display="none"),yield null===(e=t.livenessStreamProvider)||void 0===e?void 0:e.endStream()})),freezeStream:t=>e(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(void 0,void 0,void 0,(function*(){const{videoEl:e}=t.videoAssociatedParams;t.isRecordingStopped=!0,e.pause()})),resetContext:o({challengeId:C(),maxFailedAttempts:0,failedAttempts:0,componentProps:e=>e.componentProps,serverSessionInformation:e=>{},videoAssociatedParams:e=>{},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,o=Date.now()-a;return t===D.MATCHED&&o>=500},hasFaceMatchedInOval:e=>e.faceMatchAssociatedParams.faceMatchState===D.MATCHED,hasNotFaceMatchedInOval:e=>e.faceMatchAssociatedParams.faceMatchState!==D.MATCHED,hasSingleFace:e=>e.faceMatchAssociatedParams.faceMatchState===D.FACE_IDENTIFIED,hasSingleFaceBeforeStart:e=>e.faceMatchStateBeforeStart===D.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(this,void 0,void 0,(function*(){const{videoConstraints:e}=t.videoAssociatedParams,a=yield navigator.mediaDevices.getUserMedia({video:e,audio:!1}),o=(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind)).filter((e=>!d(e)));if(!o.length)throw new Error("No real video devices found");const i=a.getTracks().filter((e=>e.getSettings().frameRate>=15));if(i.length<1)throw new Error("No camera found with more than 15 fps");const r=i[0].getSettings().deviceId;let s=a;return o.some((e=>e.deviceId===r))||(s=yield navigator.mediaDevices.getUserMedia({video:Object.assign(Object.assign({},e),{deviceId:{exact:o[0].deviceId}}),audio:!1})),{stream:s}}))},openLivenessStreamConnection(t){return e(this,void 0,void 0,(function*(){const e=new M(t.componentProps.sessionId,t.componentProps.region,t.videoAssociatedParams.videoMediaStream,t.videoAssociatedParams.videoEl);return B=e.getResponseStream(),{livenessStreamProvider:e}}))},detectFace(t){return e(this,void 0,void 0,(function*(){const{videoEl:e}=t.videoAssociatedParams,{faceDetector:a}=t.ovalAssociatedParams;try{yield a.modelLoadingPromise}catch(e){console.log({err:e})}return{faceMatchState:yield l(a,e)}}))},detectFaceDistance(t){return e(this,void 0,void 0,(function*(){const{isFaceFarEnoughBeforeRecording:e}=t,{videoEl:a,videoMediaStream:o,isMobile:i}=t.videoAssociatedParams,{faceDetector:r}=t.ovalAssociatedParams,{width:s,height:n}=o.getTracks()[0].getSettings(),c=F({width:s,height:n});return{isFaceFarEnoughBeforeRecording:yield v({faceDetector:r,videoEl:a,ovalDetails:c,reduceThreshold:e,isMobile:i})}}))},detectInitialFaceAndDrawOval(t){return e(this,void 0,void 0,(function*(){const{serverSessionInformation:e,livenessStreamProvider:a}=t,{videoEl:o,canvasEl:i,isMobile:r}=t.videoAssociatedParams,{faceDetector:s}=t.ovalAssociatedParams;try{yield s.modelLoadingPromise,yield a.videoRecorder.recorderStarted}catch(e){console.log({err:e})}const n=yield s.detectFaces(o);let c,d,l;switch(n.length){case 0:d=D.CANT_IDENTIFY,l=m(o);break;case 1:d=D.FACE_IDENTIFIED,c=n[0];break;default:d=D.TOO_MANY}if(!c)return{faceMatchState:d,illuminationState:l};const{width:v,height:u}=o.getBoundingClientRect();r?(i.width=window.innerWidth,i.height=window.innerHeight):(i.width=v,i.height=u);const S=v/o.videoWidth,p=h({sessionInformation:e,videoWidth:o.width}),F=g(c,p);return c.top=F.top,c.left=F.left,c.height=F.bottom-F.top,c.width=F.right-F.left,f({canvas:i,oval:p,scaleFactor:S,videoEl:o}),{faceMatchState:d,ovalDetails:p,scaleFactor:S,initialFace:c}}))},detectFaceAndMatchOval(t){return e(this,void 0,void 0,(function*(){const{serverSessionInformation:e}=t,{videoEl:a}=t.videoAssociatedParams,{faceDetector:o,ovalDetails:i,initialFace:r}=t.ovalAssociatedParams,s=yield o.detectFaces(a);let n,c,d,l=0;const v=g(r,i),{ovalBoundingBox:h}=u(i),f=S(v,h);switch(s.length){case 0:n=D.CANT_IDENTIFY,d=m(a);break;case 1:{c=s[0];const{faceMatchState:t,faceMatchPercentage:a}=p(c,i,f,e);n=t,l=a;break}default:n=D.TOO_MANY}return{faceMatchState:n,faceMatchPercentage:l,illuminationState:d,detectedFace:c}}))},flashColors(t){return e(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(this,void 0,void 0,(function*(){const{challengeId:e,livenessStreamProvider:a}=t,{videoMediaStream:o}=t.videoAssociatedParams,{initialFace:i,ovalDetails:r}=t.ovalAssociatedParams,{startFace:n,endFace:c}=t.faceMatchAssociatedParams,{width:d,height:l}=o.getTracks()[0].getSettings(),v=d-i.left-i.width;yield a.stopVideo();const m={Challenge:{FaceMovementAndLightChallenge:{ChallengeId:e,InitialFace:{InitialFaceDetectedTimestamp:i.timestampMs,BoundingBox:s({deviceHeight:l,deviceWidth:d,height:i.height,width:i.width,top:i.top,left:v})},TargetFace:{FaceDetectedInTargetPositionStartTimestamp:n.timestampMs,FaceDetectedInTargetPositionEndTimestamp:c.timestampMs,BoundingBox:s({deviceHeight:l,deviceWidth:d,height:r.height,width:r.width,top:r.centerY-r.height/2,left:r.centerX-r.width/2})},VideoEndTimestamp:a.videoRecorder.recorderEndTimestamp}}};a.sendClientInfo(m),yield a.dispatchStopVideoEvent()}))},getLiveness(t){return e(this,void 0,void 0,(function*(){const{livenessStreamProvider:e}=t,{onAnalysisComplete:a}=t.componentProps;e.endStream(),yield a()}))}}}),_=a=>e(void 0,void 0,void 0,(function*(){var e,o,i,r;try{const d=yield B;try{for(var s,n=!0,c=t(d);!(e=(s=yield c.next()).done);){r=s.value,n=!1;try{const e=r;P(e)?a({type:"SET_SESSION_INFO",data:{sessionInfo:e.ServerSessionInformationEvent.SessionInformation}}):T(e)?a({type:"DISCONNECT_EVENT"}):O(e)?a({type:"SERVER_ERROR",data:{error:Object.assign({},e.ValidationException)}}):I(e)?a({type:"SERVER_ERROR",data:{error:Object.assign({},e.InternalServerException)}}):w(e)?a({type:"SERVER_ERROR",data:{error:Object.assign({},e.ThrottlingException)}}):y(e)&&a({type:"SERVER_ERROR",data:{error:Object.assign({},e.ServiceQuotaExceededException)}})}finally{n=!0}}}catch(e){o={error:e}}finally{try{n||e||!(i=c.return)||(yield i.call(c))}finally{if(o)throw o.error}}}catch(e){let t=e;b(e)&&(t=new Error("Invalid region in FaceLivenessDetector or credentials are scoped to the wrong region.")),t instanceof Error&&a({type:"SERVER_ERROR",data:{error:t}})}}));export{k as MIN_FACE_MATCH_TIME,j as livenessMachine};
1
+ import{__awaiter as e,__asyncValues as t}from"tslib";import{createMachine as a,assign as o,spawn as i,actions as r}from"xstate";import{getBoundingBox as s,getColorsSequencesFromSessionInformation as n,LivenessErrorStateStringMap as c,isCameraDeviceVirtual as d,getFaceMatchState as l,isFaceDistanceBelowThreshold as v,estimateIllumination as m,getOvalDetailsFromSessionInformation as h,generateBboxFromLandmarks as g,drawLivenessOvalInCanvas as f,getOvalBoundingBox as u,getIntersectionOverUnion as S,getFaceMatchStateInLivenessOval as p,getStaticLivenessOvalDetails as F}from"../utils/liveness.mjs";import{FaceMatchState as D}from"../types/liveness.mjs";import{LivenessErrorState as E}from"../types/error.mjs";import{BlazeFaceFaceDetection as A}from"../utils/blazefaceFaceDetection.mjs";import{LivenessStreamProvider as M}from"../utils/streamProvider.mjs";import{FreshnessColorDisplay as R}from"../utils/freshnessColorDisplay.mjs";import{nanoid as C}from"nanoid";import{isServerSesssionInformationEvent as P,isDisconnectionEvent as T,isValidationExceptionEvent as O,isInternalServerExceptionEvent as I,isThrottlingExceptionEvent as w,isServiceQuotaExceededExceptionEvent as y,isInvalidSignatureRegionException as b}from"../utils/eventUtils.mjs";const k=500;let B;const j=a({id:"livenessMachine",initial:"start",predictableActionArguments:!0,context:{challengeId:C(),maxFailedAttempts:0,failedAttempts:0,componentProps:void 0,serverSessionInformation:void 0,videoAssociatedParams:void 0,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"},MOBILE_LANDSCAPE_WARNING:{target:"mobileLandscapeWarning",actions:"updateErrorStateForServer"}},states:{start:{on:{BEGIN:"cameraCheck"}},cameraCheck:{entry:["resetErrorState","setVideoConstraints","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:"waitForSessionInfo",actions:["updateLivenessStreamProvider","spawnResponseStreamActor"]}}},waitForSessionInfo:{after:{0:{target:"notRecording",cond:"hasServerSessionInfo"},100:{target:"waitForSessionInfo"}}},notRecording:{on:{START_RECORDING:"recording"},initial:"detectFaceDistanceDuringCountdown",states:{detectFaceDistanceDuringCountdown:{invoke:{src:"detectFaceDistance",onDone:{target:"checkFaceDistanceDuringCountdown",actions:["updateFaceDistanceBeforeRecording"]}}},checkFaceDistanceDuringCountdown:{after:{0:{target:"failure",cond:"hasNotEnoughFaceDistanceBeforeRecording"},200:{target:"detectFaceDistanceDuringCountdown"}}},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:o({responseStreamActorRef:()=>i(_)}),updateFailedAttempts:o({failedAttempts:e=>e.failedAttempts+1}),setVideoConstraints:o({videoAssociatedParams:(e,t)=>{var a,o;return Object.assign(Object.assign({},e.videoAssociatedParams),{videoConstraints:(null===(a=t.data)||void 0===a?void 0:a.videoConstraints)||(null===(o=e.videoAssociatedParams)||void 0===o?void 0:o.videoConstraints)})}}),updateVideoMediaStream:o({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:o({ovalAssociatedParams:e=>{const{componentProps:t}=e,{faceModelUrl:a,binaryPath:o}=t.config,i=new A(o,a);return i.triggerModelLoading(),Object.assign(Object.assign({},e.ovalAssociatedParams),{faceDetector:i})}}),updateLivenessStreamProvider:o({livenessStreamProvider:(e,t)=>{var a;return null===(a=t.data)||void 0===a?void 0:a.livenessStreamProvider}}),setDOMAndCameraDetails:o({videoAssociatedParams:(e,t)=>{var a,o,i;return Object.assign(Object.assign({},e.videoAssociatedParams),{videoEl:null===(a=t.data)||void 0===a?void 0:a.videoEl,canvasEl:null===(o=t.data)||void 0===o?void 0:o.canvasEl,isMobile:null===(i=t.data)||void 0===i?void 0:i.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:o({videoAssociatedParams:e=>{const{challengeId:t,videoAssociatedParams:a,ovalAssociatedParams:o,livenessStreamProvider:i}=e,{recordingStartApiTimestamp:r,recorderStartTimestamp:n}=i.videoRecorder,{videoMediaStream:c}=a,{initialFace:d}=o,l=Math.round(.73*(n-r)+r),{width:v,height:m}=c.getTracks()[0].getSettings(),h=v-d.left-d.width;return e.livenessStreamProvider.sendClientInfo({Challenge:{FaceMovementAndLightChallenge:{ChallengeId:t,VideoStartTimestamp:l,InitialFace:{InitialFaceDetectedTimestamp:d.timestampMs,BoundingBox:s({deviceHeight:m,deviceWidth:v,height:d.height,width:d.width,top:d.top,left:h})}}}}),Object.assign(Object.assign({},e.videoAssociatedParams),{recordingStartTimestampMs:l})}}),startRecording:o({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:o({faceMatchStateBeforeStart:(e,t)=>t.data.faceMatchState}),updateFaceDistanceBeforeRecording:o({isFaceFarEnoughBeforeRecording:(e,t)=>t.data.isFaceFarEnoughBeforeRecording}),updateOvalAndFaceDetailsPostDraw:o({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:o({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:o({faceMatchAssociatedParams:e=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{endFace:e.faceMatchAssociatedParams.currentDetectedFace})}),setFaceMatchTimeAndStartFace:o({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:o({errorState:e=>{}}),updateErrorStateForTimeout:o({errorState:(e,t)=>{var a;return(null===(a=t.data)||void 0===a?void 0:a.errorState)||E.TIMEOUT}}),updateErrorStateForRuntime:o({errorState:e=>E.RUNTIME_ERROR}),updateErrorStateForServer:o({errorState:e=>E.SERVER_ERROR}),clearErrorState:o({errorState:e=>{}}),updateSessionInfo:o({serverSessionInformation:(e,t)=>t.data.sessionInfo}),updateShouldDisconnect:o({shouldDisconnect:e=>!0}),updateFreshnessDetails:o({freshnessColorAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorsComplete:t.data.freshnessColorsComplete})}),setupFlashFreshnessColors:o({freshnessColorAssociatedParams:e=>{const{serverSessionInformation:t}=e,a=n(t),o=new R(e,a);return Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorDisplay:o})}}),sendTimeoutAfterOvalDrawingDelay:r.send({type:"TIMEOUT"},{delay:5e3,id:"ovalDrawingTimeout"}),cancelOvalDrawingTimeout:r.cancel("ovalDrawingTimeout"),sendTimeoutAfterOvalMatchDelay:r.send({type:"TIMEOUT"},{delay:7e3,id:"ovalMatchTimeout"}),cancelOvalMatchTimeout:r.cancel("ovalMatchTimeout"),sendTimeoutAfterWaitingForDisconnect:r.send({type:"TIMEOUT",data:{errorState:E.SERVER_ERROR}},{delay:2e4,id:"waitForDisconnectTimeout"}),cancelWaitForDisconnectTimeout:r.cancel("waitForDisconnectTimeout"),sendTimeoutAfterFaceDistanceDelay:r.send({type:"TIMEOUT",data:{errorState:E.FACE_DISTANCE_ERROR}},{delay:0,id:"faceDistanceTimeout"}),cancelFaceDistanceTimeout:r.cancel("faceDistanceTimeout"),callUserPermissionDeniedCallback:o({errorState:(e,t)=>{var a,o;let i;i=t.data.message.includes("15 fps")?E.CAMERA_FRAMERATE_ERROR:E.CAMERA_ACCESS_ERROR;const r=t.data.message||t.data.Message,s=new Error(r);return s.name=i,null===(o=(a=e.componentProps).onError)||void 0===o||o.call(a,s),i}}),callMobileLandscapeWarningCallback:o({errorState:e=>E.MOBILE_LANDSCAPE_ERROR}),callUserCancelCallback:t=>e(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(void 0,void 0,void 0,(function*(){var e,a;const o=new Error(c[t.errorState]);o.name=t.errorState,null===(a=(e=t.componentProps).onError)||void 0===a||a.call(e,o)})),callErrorCallback:(t,a)=>e(void 0,void 0,void 0,(function*(){var e,o,i,r,s,n;const c=(null===(o=null===(e=a.data)||void 0===e?void 0:e.error)||void 0===o?void 0:o.message)||(null===(r=null===(i=a.data)||void 0===i?void 0:i.error)||void 0===r?void 0:r.Message),d=new Error(c);d.name=t.errorState,null===(n=(s=t.componentProps).onError)||void 0===n||n.call(s,d)})),cleanUpResources:t=>e(void 0,void 0,void 0,(function*(){var e;const{freshnessColorEl:a}=t.freshnessColorAssociatedParams;a&&(a.style.display="none"),yield null===(e=t.livenessStreamProvider)||void 0===e?void 0:e.endStream()})),freezeStream:t=>e(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(void 0,void 0,void 0,(function*(){const{videoEl:e}=t.videoAssociatedParams;t.isRecordingStopped=!0,e.pause()})),resetContext:o({challengeId:C(),maxFailedAttempts:0,failedAttempts:0,componentProps:e=>e.componentProps,serverSessionInformation:e=>{},videoAssociatedParams:e=>{},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,o=Date.now()-a;return t===D.MATCHED&&o>=500},hasFaceMatchedInOval:e=>e.faceMatchAssociatedParams.faceMatchState===D.MATCHED,hasNotFaceMatchedInOval:e=>e.faceMatchAssociatedParams.faceMatchState!==D.MATCHED,hasSingleFace:e=>e.faceMatchAssociatedParams.faceMatchState===D.FACE_IDENTIFIED,hasSingleFaceBeforeStart:e=>e.faceMatchStateBeforeStart===D.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(this,void 0,void 0,(function*(){const{videoConstraints:e}=t.videoAssociatedParams,a=yield navigator.mediaDevices.getUserMedia({video:e,audio:!1}),o=(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind)).filter((e=>!d(e)));if(!o.length)throw new Error("No real video devices found");const i=a.getTracks().filter((e=>e.getSettings().frameRate>=15));if(i.length<1)throw new Error("No camera found with more than 15 fps");const r=i[0].getSettings().deviceId;let s=a;return o.some((e=>e.deviceId===r))||(s=yield navigator.mediaDevices.getUserMedia({video:Object.assign(Object.assign({},e),{deviceId:{exact:o[0].deviceId}}),audio:!1})),{stream:s}}))},openLivenessStreamConnection(t){return e(this,void 0,void 0,(function*(){const e=new M(t.componentProps.sessionId,t.componentProps.region,t.videoAssociatedParams.videoMediaStream,t.videoAssociatedParams.videoEl);return B=e.getResponseStream(),{livenessStreamProvider:e}}))},detectFace(t){return e(this,void 0,void 0,(function*(){const{videoEl:e}=t.videoAssociatedParams,{faceDetector:a}=t.ovalAssociatedParams;try{yield a.modelLoadingPromise}catch(e){console.log({err:e})}return{faceMatchState:yield l(a,e)}}))},detectFaceDistance(t){return e(this,void 0,void 0,(function*(){const{isFaceFarEnoughBeforeRecording:e}=t,{videoEl:a,videoMediaStream:o,isMobile:i}=t.videoAssociatedParams,{faceDetector:r}=t.ovalAssociatedParams,{width:s,height:n}=o.getTracks()[0].getSettings(),c=F({width:s,height:n});return{isFaceFarEnoughBeforeRecording:yield v({faceDetector:r,videoEl:a,ovalDetails:c,reduceThreshold:e,isMobile:i})}}))},detectInitialFaceAndDrawOval(t){return e(this,void 0,void 0,(function*(){const{serverSessionInformation:e,livenessStreamProvider:a}=t,{videoEl:o,canvasEl:i,isMobile:r}=t.videoAssociatedParams,{faceDetector:s}=t.ovalAssociatedParams;try{yield s.modelLoadingPromise,yield a.videoRecorder.recorderStarted}catch(e){console.log({err:e})}const n=yield s.detectFaces(o);let c,d,l;switch(n.length){case 0:d=D.CANT_IDENTIFY,l=m(o);break;case 1:d=D.FACE_IDENTIFIED,c=n[0];break;default:d=D.TOO_MANY}if(!c)return{faceMatchState:d,illuminationState:l};const{width:v,height:u}=o.getBoundingClientRect();r?(i.width=window.innerWidth,i.height=window.innerHeight):(i.width=v,i.height=u);const S=v/o.videoWidth,p=h({sessionInformation:e,videoWidth:o.width}),F=g(c,p);return c.top=F.top,c.left=F.left,c.height=F.bottom-F.top,c.width=F.right-F.left,f({canvas:i,oval:p,scaleFactor:S,videoEl:o}),{faceMatchState:d,ovalDetails:p,scaleFactor:S,initialFace:c}}))},detectFaceAndMatchOval(t){return e(this,void 0,void 0,(function*(){const{serverSessionInformation:e}=t,{videoEl:a}=t.videoAssociatedParams,{faceDetector:o,ovalDetails:i,initialFace:r}=t.ovalAssociatedParams,s=yield o.detectFaces(a);let n,c,d,l=0;const v=g(r,i),{ovalBoundingBox:h}=u(i),f=S(v,h);switch(s.length){case 0:n=D.CANT_IDENTIFY,d=m(a);break;case 1:{c=s[0];const{faceMatchState:t,faceMatchPercentage:a}=p(c,i,f,e);n=t,l=a;break}default:n=D.TOO_MANY}return{faceMatchState:n,faceMatchPercentage:l,illuminationState:d,detectedFace:c}}))},flashColors(t){return e(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(this,void 0,void 0,(function*(){const{challengeId:e,livenessStreamProvider:a}=t,{videoMediaStream:o}=t.videoAssociatedParams,{initialFace:i,ovalDetails:r}=t.ovalAssociatedParams,{startFace:n,endFace:c}=t.faceMatchAssociatedParams,{width:d,height:l}=o.getTracks()[0].getSettings(),v=d-i.left-i.width;yield a.stopVideo();const m={Challenge:{FaceMovementAndLightChallenge:{ChallengeId:e,InitialFace:{InitialFaceDetectedTimestamp:i.timestampMs,BoundingBox:s({deviceHeight:l,deviceWidth:d,height:i.height,width:i.width,top:i.top,left:v})},TargetFace:{FaceDetectedInTargetPositionStartTimestamp:n.timestampMs,FaceDetectedInTargetPositionEndTimestamp:c.timestampMs,BoundingBox:s({deviceHeight:l,deviceWidth:d,height:r.height,width:r.width,top:r.centerY-r.height/2,left:r.centerX-r.width/2})},VideoEndTimestamp:a.videoRecorder.recorderEndTimestamp}}};a.sendClientInfo(m),yield a.dispatchStopVideoEvent()}))},getLiveness(t){return e(this,void 0,void 0,(function*(){const{livenessStreamProvider:e}=t,{onAnalysisComplete:a}=t.componentProps;e.endStream(),yield a()}))}}}),_=a=>e(void 0,void 0,void 0,(function*(){var e,o,i,r;try{const d=yield B;try{for(var s,n=!0,c=t(d);!(e=(s=yield c.next()).done);){r=s.value,n=!1;try{const e=r;P(e)?a({type:"SET_SESSION_INFO",data:{sessionInfo:e.ServerSessionInformationEvent.SessionInformation}}):T(e)?a({type:"DISCONNECT_EVENT"}):O(e)?a({type:"SERVER_ERROR",data:{error:Object.assign({},e.ValidationException)}}):I(e)?a({type:"SERVER_ERROR",data:{error:Object.assign({},e.InternalServerException)}}):w(e)?a({type:"SERVER_ERROR",data:{error:Object.assign({},e.ThrottlingException)}}):y(e)&&a({type:"SERVER_ERROR",data:{error:Object.assign({},e.ServiceQuotaExceededException)}})}finally{n=!0}}}catch(e){o={error:e}}finally{try{n||e||!(i=c.return)||(yield i.call(c))}finally{if(o)throw o.error}}}catch(e){let t=e;b(e)&&(t=new Error("Invalid region in FaceLivenessDetector or credentials are scoped to the wrong region.")),t instanceof Error&&a({type:"SERVER_ERROR",data:{error:t}})}}));export{k as MIN_FACE_MATCH_TIME,j as livenessMachine};
@@ -1 +1 @@
1
- import{__awaiter as t}from"../../../../node_modules/tslib/tslib.es6.mjs";import*as e from"@tensorflow/tfjs-core";import*as s from"@tensorflow-models/blazeface";import*as o from"@tensorflow/tfjs-backend-wasm";import"@tensorflow/tfjs-backend-cpu";import{jitteredExponentialRetry as a}from"@aws-amplify/core";import{isWebAssemblySupported as r}from"./support.mjs";import{FaceDetection as i}from"../types/faceDetection.mjs";import"../types/liveness.mjs";import"../types/error.mjs";class n extends i{constructor(t,e){super(),this.faceModelUrl=e,this.binaryPath=null!=t?t:`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${o.version_wasm}/dist/`}loadModels(){return t(this,void 0,void 0,(function*(){r()?yield this._loadWebAssemblyBackend():yield this._loadCPUBackend();try{yield e.ready(),this._model=yield a(s.load,[{modelUrl:this.faceModelUrl}])}catch(t){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(e){return t(this,void 0,void 0,(function*(){const t=yield this._model.estimateFaces(e,!1,!0,!0),s=Date.now();return t.filter((t=>!!t.landmarks)).map((t=>{const{topLeft:e,bottomRight:o,probability:a,landmarks:r}=t,[i,n]=e,[l,d]=o,m=Math.abs(i-l),c=Math.abs(d-n),f=r[0],h=r[1],u=r[2],p=r[3];return{top:n,left:l,width:m,height:c,timestampMs:s,probability:a[0],rightEye:f,leftEye:h,mouth:p,nose:u}}))}))}_loadWebAssemblyBackend(){return t(this,void 0,void 0,(function*(){try{o.setWasmPaths(this.binaryPath),yield a((()=>t(this,void 0,void 0,(function*(){if(!(yield e.setBackend("wasm")))throw new Error("Initialization of backend wasm failed")}))),[]),this.modelBackend="wasm"}catch(t){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 t(this,void 0,void 0,(function*(){yield e.setBackend("cpu"),this.modelBackend="cpu"}))}}export{n as BlazeFaceFaceDetection};
1
+ import{__awaiter as t}from"tslib";import*as e 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 r}from"./support.mjs";import{FaceDetection as i}from"../types/faceDetection.mjs";import"../types/liveness.mjs";import"../types/error.mjs";class n extends i{constructor(t,e){super(),this.faceModelUrl=e,this.binaryPath=null!=t?t:`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${s.version_wasm}/dist/`}loadModels(){return t(this,void 0,void 0,(function*(){r()?yield this._loadWebAssemblyBackend():yield this._loadCPUBackend();try{yield e.ready(),this._model=yield a(o.load,[{modelUrl:this.faceModelUrl}])}catch(t){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(e){return t(this,void 0,void 0,(function*(){const t=yield this._model.estimateFaces(e,!1,!0,!0),o=Date.now();return t.filter((t=>!!t.landmarks)).map((t=>{const{topLeft:e,bottomRight:s,probability:a,landmarks:r}=t,[i,n]=e,[l,d]=s,m=Math.abs(i-l),c=Math.abs(d-n),f=r[0],h=r[1],u=r[2],p=r[3];return{top:n,left:l,width:m,height:c,timestampMs:o,probability:a[0],rightEye:f,leftEye:h,mouth:p,nose:u}}))}))}_loadWebAssemblyBackend(){return t(this,void 0,void 0,(function*(){try{s.setWasmPaths(this.binaryPath),yield a((()=>t(this,void 0,void 0,(function*(){if(!(yield e.setBackend("wasm")))throw new Error("Initialization of backend wasm failed")}))),[]),this.modelBackend="wasm"}catch(t){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 t(this,void 0,void 0,(function*(){yield e.setBackend("cpu"),this.modelBackend="cpu"}))}}export{n as BlazeFaceFaceDetection};
@@ -1 +1 @@
1
- import{__awaiter as e}from"../../../../node_modules/tslib/tslib.es6.mjs";import{fillOverlayCanvasFractional as r,getRGBArrayFromColorString as o}from"./liveness.mjs";var t;!function(e){e.SCROLLING="SCROLLING",e.FLAT="FLAT"}(t||(t={}));class s{constructor(e,r){this.context=e,this.freshnessColorsSequence=r,this.isFirstTick=!0}displayColorTick(){return e(this,void 0,void 0,(function*(){return new Promise(((e,r)=>{setTimeout((()=>{this.displayNextColorTick(e,r)}),Math.min(10))}))}))}init(){this.stageIndex=0,this.currColorIndex=0,this.currColorSequence=this.freshnessColorsSequence[0],this.prevColorSequence=this.freshnessColorsSequence[0],this.stage=t.FLAT,this.timeLastFlatOrScrollChange=Date.now(),this.timeLastFaceMatchChecked=Date.now()}displayNextColorTick(e,o){const{freshnessColorEl:s}=this.context.freshnessColorAssociatedParams,{ovalDetails:i,scaleFactor:l}=this.context.ovalAssociatedParams,{videoEl:n}=this.context.videoAssociatedParams,c=Date.now();this.isFirstTick&&(this.init(),this.isFirstTick=!1,this.sendColorStartTime({tickStartTime:c,currColor:this.currColorSequence.color,prevColor:this.currColorSequence.color,currColorIndex:this.stageIndex}));let a=c-this.timeLastFlatOrScrollChange;if(s.style.display="block",(this.stage===t.FLAT&&a>=this.currColorSequence.flatDisplayDuration||this.stage===t.SCROLLING&&a>=this.currColorSequence.downscrollDuration)&&(this.incrementStageIndex(c),a=0),this.currColorIndex<this.freshnessColorsSequence.length){const o=a/(this.stage===t.SCROLLING?this.currColorSequence.downscrollDuration:this.currColorSequence.flatDisplayDuration);r({overlayCanvas:s,prevColor:this.prevColorSequence.color,nextColor:this.currColorSequence.color,videoEl:n,ovalDetails:i,heightFraction:o,scaleFactor:l}),e(!1)}else s.style.display="none",e(!0)}incrementStageIndex(e){if(this.stageIndex+=1,this.prevColorSequence=this.freshnessColorsSequence[this.currColorIndex],this.stage===t.FLAT)this.currColorIndex+=1,this.stage=t.SCROLLING;else if(this.stage===t.SCROLLING){this.freshnessColorsSequence[this.currColorIndex].flatDisplayDuration>0?this.stage=t.FLAT:(this.stage=t.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:r,prevColor:t,currColorIndex:s}){const{livenessStreamProvider:i,challengeId:l}=this.context;i.sendClientInfo({Challenge:{FaceMovementAndLightChallenge:{ChallengeId:l,ColorDisplayed:{CurrentColor:{RGB:o(r)},PreviousColor:{RGB:o(t)},SequenceNumber:s,CurrentColorStartTimestamp:e}}}})}}export{s as FreshnessColorDisplay};
1
+ import{__awaiter as e}from"tslib";import{fillOverlayCanvasFractional as r,getRGBArrayFromColorString as o}from"./liveness.mjs";var t;!function(e){e.SCROLLING="SCROLLING",e.FLAT="FLAT"}(t||(t={}));class s{constructor(e,r){this.context=e,this.freshnessColorsSequence=r,this.isFirstTick=!0}displayColorTick(){return e(this,void 0,void 0,(function*(){return new Promise(((e,r)=>{setTimeout((()=>{this.displayNextColorTick(e,r)}),Math.min(10))}))}))}init(){this.stageIndex=0,this.currColorIndex=0,this.currColorSequence=this.freshnessColorsSequence[0],this.prevColorSequence=this.freshnessColorsSequence[0],this.stage=t.FLAT,this.timeLastFlatOrScrollChange=Date.now(),this.timeLastFaceMatchChecked=Date.now()}displayNextColorTick(e,o){const{freshnessColorEl:s}=this.context.freshnessColorAssociatedParams,{ovalDetails:i,scaleFactor:l}=this.context.ovalAssociatedParams,{videoEl:n}=this.context.videoAssociatedParams,c=Date.now();this.isFirstTick&&(this.init(),this.isFirstTick=!1,this.sendColorStartTime({tickStartTime:c,currColor:this.currColorSequence.color,prevColor:this.currColorSequence.color,currColorIndex:this.stageIndex}));let a=c-this.timeLastFlatOrScrollChange;if(s.style.display="block",(this.stage===t.FLAT&&a>=this.currColorSequence.flatDisplayDuration||this.stage===t.SCROLLING&&a>=this.currColorSequence.downscrollDuration)&&(this.incrementStageIndex(c),a=0),this.currColorIndex<this.freshnessColorsSequence.length){const o=a/(this.stage===t.SCROLLING?this.currColorSequence.downscrollDuration:this.currColorSequence.flatDisplayDuration);r({overlayCanvas:s,prevColor:this.prevColorSequence.color,nextColor:this.currColorSequence.color,videoEl:n,ovalDetails:i,heightFraction:o,scaleFactor:l}),e(!1)}else s.style.display="none",e(!0)}incrementStageIndex(e){if(this.stageIndex+=1,this.prevColorSequence=this.freshnessColorsSequence[this.currColorIndex],this.stage===t.FLAT)this.currColorIndex+=1,this.stage=t.SCROLLING;else if(this.stage===t.SCROLLING){this.freshnessColorsSequence[this.currColorIndex].flatDisplayDuration>0?this.stage=t.FLAT:(this.stage=t.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:r,prevColor:t,currColorIndex:s}){const{livenessStreamProvider:i,challengeId:l}=this.context;i.sendClientInfo({Challenge:{FaceMovementAndLightChallenge:{ChallengeId:l,ColorDisplayed:{CurrentColor:{RGB:o(r)},PreviousColor:{RGB:o(t)},SequenceNumber:s,CurrentColorStartTimestamp:e}}}})}}export{s as FreshnessColorDisplay};
@@ -1 +1 @@
1
- import{__awaiter as t}from"../../../../node_modules/tslib/tslib.es6.mjs";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,R=1.618*v;return{flippedCenterX:Math.floor(a-g),centerX:Math.floor(g),centerY:Math.floor(u),width:Math.floor(v),height:Math.floor(R)}}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:R}=s,E=v(t,o),C=E.left,m=E.right,p=E.top,M=E.bottom,{ovalBoundingBox:w,minOvalX:O,minOvalY:A,maxOvalX:T,maxOvalY:I}=l(o),x=c(E,w),b=d,_=o.width*g,S=o.height*f,F=o.width*R,D=o.height*u,y=100*Math.max(Math.min(1,.75*(x-n)/(b-n)+.25),0);return h=x>b&&Math.abs(O-C)<_&&Math.abs(T-m)<_&&Math.abs(I-M)<S?e.MATCHED:A-p>D||M-I>D||O-C>F&&m-T>F?e.TOO_CLOSE:e.TOO_FAR,{faceMatchState:h,faceMatchPercentage:y}}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 R=g-d/2,E=v-f/2;return{left:R,top:E,right:R+d,bottom:E+f}}function R(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 E(t){return t.label.toLowerCase().includes("virtual")}const C={[n.RUNTIME_ERROR]:"RUNTIME_ERROR",[n.SERVER_ERROR]:"SERVER_ERROR",[n.TIMEOUT]:"TIMEOUT",[n.FACE_DISTANCE_ERROR]:"FACE_DISTANCE_ERROR",[n.CAMERA_FRAMERATE_ERROR]:"CAMERA_FRAMERATE_ERROR",[n.CAMERA_ACCESS_ERROR]:"CAMERA_ACCESS_ERROR",[n.MOBILE_LANDSCAPE_ERROR]:"MOBILE_LANDSCAPE_ERROR",[n.FRESHNESS_TIMEOUT]:"FRESHNESS_TIMEOUT"};function m({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 p({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,R=t.height,E=t.getContext("2d");if(!E)throw new Error("Cannot find Overlay Canvas.");E.canvas.width=window.innerWidth,E.canvas.height=window.innerHeight,E.clearRect(0,0,v,R),m({ctx:E,prevColor:e,nextColor:o,fraction:r}),E.save(),E.beginPath(),E.rect(0,0,v,R),E.clip(),E.clearRect(0,0,v,R),E.globalAlpha=.9,m({ctx:E,prevColor:e,nextColor:o,fraction:r}),E.beginPath(),E.ellipse(g,u,d*a/2,f*a/2,0,0,2*Math.PI),E.strokeStyle="white",E.lineWidth=8,E.stroke(),E.clip(),E.clearRect(0,0,v,R),E.globalAlpha=.75,m({ctx:E,prevColor:e,nextColor:o,fraction:r}),E.restore()}const M=t=>!!t;function w(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 A(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 T({faceDetector:e,videoEl:o,ovalDetails:n,reduceThreshold:h=!1,isMobile:l=!1}){return t(this,void 0,void 0,(function*(){const t=yield e.detectFaces(o);let c,s=!1;switch(t.length){case 0:break;case 1:{c=t[0];const e=n.width,{pupilDistance:o,faceHeight:d}=u(c),f=2;e&&(s=(f*o+1.8*d)/2/f/e<(h?l?r:a:i));break}}return s}))}function I({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{C as LivenessErrorStateStringMap,f as drawLivenessOvalInCanvas,R as estimateIllumination,p as fillOverlayCanvasFractional,v as generateBboxFromLandmarks,I as getBoundingBox,w as getColorsSequencesFromSessionInformation,A as getFaceMatchState,g as getFaceMatchStateInLivenessOval,c as getIntersectionOverUnion,l as getOvalBoundingBox,s as getOvalDetailsFromSessionInformation,O as getRGBArrayFromColorString,d as getStaticLivenessOvalDetails,E as isCameraDeviceVirtual,M as isClientFreshnessColorSequence,T as isFaceDistanceBelowThreshold};
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,R=1.618*v;return{flippedCenterX:Math.floor(a-g),centerX:Math.floor(g),centerY:Math.floor(u),width:Math.floor(v),height:Math.floor(R)}}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:R}=s,E=v(t,o),C=E.left,p=E.right,m=E.top,M=E.bottom,{ovalBoundingBox:w,minOvalX:O,minOvalY:A,maxOvalX:T,maxOvalY:I}=l(o),x=c(E,w),b=d,S=o.width*g,_=o.height*f,F=o.width*R,D=o.height*u,y=100*Math.max(Math.min(1,.75*(x-n)/(b-n)+.25),0);return h=x>b&&Math.abs(O-C)<S&&Math.abs(T-p)<S&&Math.abs(I-M)<_?e.MATCHED:A-m>D||M-I>D||O-C>F&&p-T>F?e.TOO_CLOSE:e.TOO_FAR,{faceMatchState:h,faceMatchPercentage:y}}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 R=g-d/2,E=v-f/2;return{left:R,top:E,right:R+d,bottom:E+f}}function R(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 E(t){return t.label.toLowerCase().includes("virtual")}const C={[n.RUNTIME_ERROR]:"RUNTIME_ERROR",[n.SERVER_ERROR]:"SERVER_ERROR",[n.TIMEOUT]:"TIMEOUT",[n.FACE_DISTANCE_ERROR]:"FACE_DISTANCE_ERROR",[n.CAMERA_FRAMERATE_ERROR]:"CAMERA_FRAMERATE_ERROR",[n.CAMERA_ACCESS_ERROR]:"CAMERA_ACCESS_ERROR",[n.MOBILE_LANDSCAPE_ERROR]:"MOBILE_LANDSCAPE_ERROR",[n.FRESHNESS_TIMEOUT]:"FRESHNESS_TIMEOUT"};function p({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 m({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,R=t.height,E=t.getContext("2d");if(!E)throw new Error("Cannot find Overlay Canvas.");E.canvas.width=window.innerWidth,E.canvas.height=window.innerHeight,E.clearRect(0,0,v,R),p({ctx:E,prevColor:e,nextColor:o,fraction:r}),E.save(),E.beginPath(),E.rect(0,0,v,R),E.clip(),E.clearRect(0,0,v,R),E.globalAlpha=.9,p({ctx:E,prevColor:e,nextColor:o,fraction:r}),E.beginPath(),E.ellipse(g,u,d*a/2,f*a/2,0,0,2*Math.PI),E.strokeStyle="white",E.lineWidth=8,E.stroke(),E.clip(),E.clearRect(0,0,v,R),E.globalAlpha=.75,p({ctx:E,prevColor:e,nextColor:o,fraction:r}),E.restore()}const M=t=>!!t;function w(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 A(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 T({faceDetector:e,videoEl:o,ovalDetails:n,reduceThreshold:h=!1,isMobile:l=!1}){return t(this,void 0,void 0,(function*(){const t=yield e.detectFaces(o);let c,s=!1;switch(t.length){case 0:break;case 1:{c=t[0];const e=n.width,{pupilDistance:o,faceHeight:d}=u(c),f=2;e&&(s=(f*o+1.8*d)/2/f/e<(h?l?r:a:i));break}}return s}))}function I({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{C as LivenessErrorStateStringMap,f as drawLivenessOvalInCanvas,R as estimateIllumination,m as fillOverlayCanvasFractional,v as generateBboxFromLandmarks,I as getBoundingBox,w as getColorsSequencesFromSessionInformation,A as getFaceMatchState,g as getFaceMatchStateInLivenessOval,c as getIntersectionOverUnion,l as getOvalBoundingBox,s as getOvalDetailsFromSessionInformation,O as getRGBArrayFromColorString,d as getStaticLivenessOvalDetails,E as isCameraDeviceVirtual,M as isClientFreshnessColorSequence,T as isFaceDistanceBelowThreshold};
@@ -1 +1 @@
1
- import{__awaiter as e,__asyncGenerator as i,__await as t}from"../../../../node_modules/tslib/tslib.es6.mjs";import{Credentials as o,getAmplifyUserAgent as n}from"@aws-amplify/core";import{AmazonAIInterpretPredictionsProvider as s}from"@aws-amplify/predictions";import{RekognitionStreamingClient as r,StartFaceLivenessSessionCommand as d}from"@aws-sdk/client-rekognitionstreaming";import{WebSocketFetchHandler as a}from"@aws-sdk/middleware-websocket";import{VideoRecorder as l}from"./videoRecorder.mjs";const h=process.env.NEXT_PUBLIC_STREAMING_API_URL,c=1e3;function v(e){return void 0!==e.Challenge}class m extends s{constructor(e,i,t,o){super(),this.sessionId=e,this.region=i,this._stream=t,this.videoEl=o,this.videoRecorder=new l(t),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"))}endStream(){return e(this,void 0,void 0,(function*(){if("recording"===this.videoRecorder.getState()&&(yield this.stopVideo(),this.dispatchStopVideoEvent()),this._reader)return yield this._reader.cancel(),this._reader.closed}))}init(){return e(this,void 0,void 0,(function*(){const e=yield o.get();if(!e)throw new Error("No credentials");const i={credentials:e,region:this.region,customUserAgent:n(),requestHandler:new a({connectionTimeout:1e4})};h&&(i.endpointProvider=()=>({url:new URL(h)})),this._client=new r(i),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}}))}}))}}startLivenessVideoConnection(){return e(this,void 0,void 0,(function*(){const e=this.getAsyncGeneratorFromReadableStream(this.videoRecorder.videoStream)();return(yield this._client.send(new d({ChallengeVersions:"FaceMovementAndLightChallenge_1.0.0",SessionId:this.sessionId,LivenessRequestStream:e,VideoWidth:this.videoEl.videoWidth.toString(),VideoHeight:this.videoEl.videoHeight.toString()}))).LivenessResponseStream}))}}export{m as LivenessStreamProvider,c as TIME_SLICE};
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{AmazonAIInterpretPredictionsProvider as s}from"@aws-amplify/predictions";import{RekognitionStreamingClient as r,StartFaceLivenessSessionCommand as d}from"@aws-sdk/client-rekognitionstreaming";import{WebSocketFetchHandler as a}from"@aws-sdk/middleware-websocket";import{VideoRecorder as l}from"./videoRecorder.mjs";const h=process.env.NEXT_PUBLIC_STREAMING_API_URL,c=1e3;function v(e){return void 0!==e.Challenge}class m extends s{constructor(e,i,t,o){super(),this.sessionId=e,this.region=i,this._stream=t,this.videoEl=o,this.videoRecorder=new l(t),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"))}endStream(){return e(this,void 0,void 0,(function*(){if("recording"===this.videoRecorder.getState()&&(yield this.stopVideo(),this.dispatchStopVideoEvent()),this._reader)return yield this._reader.cancel(),this._reader.closed}))}init(){return e(this,void 0,void 0,(function*(){const e=yield o.get();if(!e)throw new Error("No credentials");const i={credentials:e,region:this.region,customUserAgent:n(),requestHandler:new a({connectionTimeout:1e4})};h&&(i.endpointProvider=()=>({url:new URL(h)})),this._client=new r(i),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}}))}}))}}startLivenessVideoConnection(){return e(this,void 0,void 0,(function*(){const e=this.getAsyncGeneratorFromReadableStream(this.videoRecorder.videoStream)();return(yield this._client.send(new d({ChallengeVersions:"FaceMovementAndLightChallenge_1.0.0",SessionId:this.sessionId,LivenessRequestStream:e,VideoWidth:this.videoEl.videoWidth.toString(),VideoHeight:this.videoEl.videoHeight.toString()}))).LivenessResponseStream}))}}export{m as LivenessStreamProvider,c as TIME_SLICE};
@@ -1 +1 @@
1
- import{__awaiter as e}from"../../../../node_modules/tslib/tslib.es6.mjs";class t{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(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)}_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.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()}}}export{t as VideoRecorder};
1
+ import{__awaiter as e}from"tslib";class t{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(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)}_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.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()}}}export{t as VideoRecorder};
@@ -1 +1 @@
1
- import e from"react";import{View as t,Flex as r,ComponentClassNames as o,Text as a}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 i}from"../types/classNames.mjs";import"../service/machine/index.mjs";import"../service/types/liveness.mjs";import"../service/types/error.mjs";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/liveness.mjs";import"../service/utils/streamProvider.mjs";import"../service/utils/freshnessColorDisplay.mjs";import{StartScreenFigure as s}from"./StartScreenFigure.mjs";import{GoodFitIllustration as m}from"./GoodFitIllustration.mjs";import{TooFarIllustration as l}from"./TooFarIllustration.mjs";import{LivenessIconWithPopover as n}from"./LivenessIconWithPopover.mjs";const c=({headingText:r,bodyText:o})=>e.createElement(t,{flex:"1"},e.createElement(t,{color:"font.primary",fontWeight:"bold"},r),e.createElement(t,{color:"font.primary"},o)),p=({headingText:a,bodyText:i,infoText:s})=>e.createElement(r,{className:o.Alert,color:"orange.80",backgroundColor:"orange.20",alignItems:"center"},e.createElement(t,{flex:"1"},e.createElement(t,{className:o.AlertHeading},a),e.createElement(t,{className:o.AlertBody},i)),e.createElement(n,null,s)),f=({headingText:t,goodFitCaptionText:o,goodFitAltText:n,tooFarCaptionText:c,tooFarAltText:p,steps:f})=>e.createElement(r,{direction:"column"},e.createElement(a,{color:"font.primary",fontWeight:"bold"},t),e.createElement(r,{className:i.Figures},e.createElement(s,{variation:"success",caption:o},e.createElement(m,{title:n})),e.createElement(s,{variation:"error",caption:c},e.createElement(l,{title:p}))),e.createElement(r,{as:"ol",className:i.InstructionList},f.map(((t,o)=>e.createElement(r,{as:"li",key:o+1},e.createElement(a,{as:"span","aria-hidden":"true"},o+1,"."),e.createElement(a,{as:"span"},t))))));export{c as DefaultHeader,f as DefaultInstructions,p as DefaultPhotosensitiveWarning};
1
+ import e from"react";import{View as t,Flex as r,ComponentClassNames as o,Text as a}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 i}from"../types/classNames.mjs";import"../service/machine/index.mjs";import"../service/types/liveness.mjs";import"../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/liveness.mjs";import"../service/utils/streamProvider.mjs";import"../service/utils/freshnessColorDisplay.mjs";import{StartScreenFigure as s}from"./StartScreenFigure.mjs";import{GoodFitIllustration as m}from"./GoodFitIllustration.mjs";import{TooFarIllustration as l}from"./TooFarIllustration.mjs";import{LivenessIconWithPopover as n}from"./LivenessIconWithPopover.mjs";const c=({headingText:r,bodyText:o})=>e.createElement(t,{flex:"1"},e.createElement(t,{color:"font.primary",fontWeight:"bold"},r),e.createElement(t,{color:"font.primary"},o)),p=({headingText:a,bodyText:i,infoText:s})=>e.createElement(r,{className:o.Alert,color:"orange.80",backgroundColor:"orange.20",alignItems:"center"},e.createElement(t,{flex:"1"},e.createElement(t,{className:o.AlertHeading},a),e.createElement(t,{className:o.AlertBody},i)),e.createElement(n,null,s)),f=({headingText:t,goodFitCaptionText:o,goodFitAltText:n,tooFarCaptionText:c,tooFarAltText:p,steps:f})=>e.createElement(r,{direction:"column"},e.createElement(a,{color:"font.primary",fontWeight:"bold"},t),e.createElement(r,{className:i.Figures},e.createElement(s,{variation:"success",caption:o},e.createElement(m,{title:n})),e.createElement(s,{variation:"error",caption:c},e.createElement(l,{title:p}))),e.createElement(r,{as:"ol",className:i.InstructionList},f.map(((t,o)=>e.createElement(r,{as:"li",key:o+1},e.createElement(a,{as:"span","aria-hidden":"true"},o+1,"."),e.createElement(a,{as:"span"},t))))));export{c as DefaultHeader,f 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 o}from"../service/types/error.mjs";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/liveness.mjs";import"../service/utils/streamProvider.mjs";import"../service/utils/freshnessColorDisplay.mjs";import{Toast as i}from"./Toast.mjs";import{Overlay as n}from"./Overlay.mjs";import{defaultErrorDisplayText as m}from"../displayText.mjs";const c=({errorState:s,overrideErrorDisplayText:i})=>{const n=Object.assign(Object.assign({},m),i);return s===o.CAMERA_ACCESS_ERROR||s===o.CAMERA_FRAMERATE_ERROR||s===o.MOBILE_LANDSCAPE_ERROR?null:(s=>{const{error:i,displayText:n}=s,{timeoutHeaderText:m,timeoutMessageText:c,faceDistanceHeaderText:l,faceDistanceMessageText:p,clientHeaderText:E,clientMessageText:f,serverHeaderText:R,serverMessageText:d}=n;let T,u;switch(i){case o.TIMEOUT:T=m,u=c;break;case o.FACE_DISTANCE_ERROR:T=l,u=p;break;case o.RUNTIME_ERROR:T=E,u=f;break;case o.SERVER_ERROR:default:T=R,u=d}return e.createElement(e.Fragment,null,e.createElement(r,{gap:"xs",alignItems:"center",justifyContent:"center",color:"font.error"},e.createElement(a,{ariaHidden:!0,variation:"error"}),e.createElement(t,{fontWeight:"bold"},T)),u)})({error:s,displayText:n})},l=t=>{const{children:a,onRetry:o,displayText:c}=t,l=Object.assign(Object.assign({},m),c),{tryAgainText:p}=l;return e.createElement(n,{backgroundColor:"overlay.40"},e.createElement(i,null,a,e.createElement(r,{justifyContent:"center"},e.createElement(s,{variation:"primary",type:"button",onClick:o},p))))};export{l as FaceLivenessErrorModal,c as renderErrorModal};
1
+ import e from"react";import{Flex as t,Text as r,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/liveness.mjs";import"../service/utils/streamProvider.mjs";import"../service/utils/freshnessColorDisplay.mjs";import{Toast as o}from"./Toast.mjs";import{Overlay as n}from"./Overlay.mjs";import{defaultErrorDisplayText as m}from"../displayText.mjs";const c=({errorState:s,overrideErrorDisplayText:o})=>{const n=Object.assign(Object.assign({},m),o);return s===i.CAMERA_ACCESS_ERROR||s===i.CAMERA_FRAMERATE_ERROR||s===i.MOBILE_LANDSCAPE_ERROR?null:(s=>{const{error:o,displayText:n}=s,{timeoutHeaderText:m,timeoutMessageText:c,faceDistanceHeaderText:l,faceDistanceMessageText:p,clientHeaderText:E,clientMessageText:f,serverHeaderText:R,serverMessageText:d}=n;let T,u;switch(o){case i.TIMEOUT:T=m,u=c;break;case i.FACE_DISTANCE_ERROR:T=l,u=p;break;case i.RUNTIME_ERROR:T=E,u=f;break;case i.SERVER_ERROR:default:T=R,u=d}return e.createElement(e.Fragment,null,e.createElement(t,{gap:"xs",alignItems:"center",justifyContent:"center",color:"font.error"},e.createElement(a,{ariaHidden:!0,variation:"error"}),e.createElement(r,{fontWeight:"bold"},T)),u)})({error:s,displayText:n})},l=r=>{const{children:a,onRetry:i,displayText:c}=r,l=Object.assign(Object.assign({},m),c),{tryAgainText:p}=l;return e.createElement(n,{backgroundColor:"overlay.40"},e.createElement(o,null,a,e.createElement(t,{justifyContent:"center"},e.createElement(s,{variation:"primary",type:"button",onClick:i},p))))};export{l as FaceLivenessErrorModal,c as renderErrorModal};
@@ -1 +1 @@
1
- import*as e from"react";import{Flex as t,Loader as r,View as o}from"@aws-amplify/ui-react";import"../service/machine/index.mjs";import{FaceMatchState as n,IlluminationState as a}from"../service/types/liveness.mjs";import"../service/types/error.mjs";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/liveness.mjs";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";const h=s((e=>e.context.errorState)),f=s((e=>e.context.faceMatchAssociatedParams.faceMatchState)),u=s((e=>e.context.faceMatchAssociatedParams.illuminationState)),T=s((e=>e.context.isFaceFarEnoughBeforeRecording)),p=s((e=>e.context.faceMatchStateBeforeStart)),E=({hintDisplayText:s})=>{const[E]=i(),x=c(h),O=c(f),d=c(u),F=c(p),g=c(T),v=E.matches("checkFaceDetectedBeforeStart"),C=E.matches("checkFaceDistanceBeforeRecording"),y=E.matches("recording"),j=E.matches("notRecording"),A=E.matches("waitForSessionInfo"),I=E.matches("uploading"),S=E.matches("checkSucceeded"),M=E.matches("checkFailed"),k=E.matches({recording:"flashFreshnessColors"}),w={[n.CANT_IDENTIFY]:s.hintCanNotIdentifyText,[n.FACE_IDENTIFIED]:s.hintTooFarText,[n.TOO_MANY]:s.hintTooManyFacesText,[n.TOO_CLOSE]:s.hintTooCloseText,[n.TOO_FAR]:s.hintTooFarText,[n.MATCHED]:s.hintHoldFaceForFreshnessText},D={[a.BRIGHT]:s.hintIlluminationTooBrightText,[a.DARK]:s.hintIlluminationTooDarkText,[a.NORMAL]:s.hintIlluminationNormalText},_=(()=>{if(!(x||M||S)){if(!y){if(v)return F===n.TOO_MANY?e.createElement(l,null,w[F]):e.createElement(l,null,s.hintMoveFaceFrontOfCameraText);if(C&&!1===g)return e.createElement(l,null,s.hintTooCloseText);if(j)return e.createElement(l,null,s.hintHoldFacePositionCountdownText);if(A)return e.createElement(l,null,e.createElement(t,{alignItems:"center",gap:"xs"},e.createElement(r,null),e.createElement(o,null,s.hintConnectingText)));if(I)return e.createElement(m,{backgroundColor:"overlay.40",anchorOrigin:{horizontal:"center",vertical:"end"}},e.createElement(l,null,e.createElement(t,{alignItems:"center",gap:"xs"},e.createElement(r,null),e.createElement(o,null,s.hintVerifyingText))));if(d&&d!==a.NORMAL)return e.createElement(l,null,D[d])}return k?e.createElement(l,{size:"large",variation:"primary"},s.hintHoldFaceForFreshnessText):y&&!k?e.createElement(l,{size:"large",variation:O===n.TOO_CLOSE?"error":"primary"},O===n.TOO_CLOSE?w[n.TOO_CLOSE]:w[n.TOO_FAR]):null}})();return _||null};export{E as Hint,h as selectErrorState,f as selectFaceMatchState,p as selectFaceMatchStateBeforeStart,u as selectIlluminationState,T as selectIsFaceFarEnoughBeforeRecording};
1
+ import*as e from"react";import{Flex as t,Loader as r,View as o}from"@aws-amplify/ui-react";import"../service/machine/index.mjs";import{FaceMatchState as n,IlluminationState as i}from"../service/types/liveness.mjs";import"../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/liveness.mjs";import"../service/utils/streamProvider.mjs";import"../service/utils/freshnessColorDisplay.mjs";import{useLivenessActor as a}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";const h=s((e=>e.context.errorState)),f=s((e=>e.context.faceMatchAssociatedParams.faceMatchState)),u=s((e=>e.context.faceMatchAssociatedParams.illuminationState)),T=s((e=>e.context.isFaceFarEnoughBeforeRecording)),p=s((e=>e.context.faceMatchStateBeforeStart)),E=({hintDisplayText:s})=>{const[E]=a(),x=c(h),O=c(f),d=c(u),F=c(p),g=c(T),v=E.matches("checkFaceDetectedBeforeStart"),C=E.matches("checkFaceDistanceBeforeRecording"),y=E.matches("recording"),j=E.matches("notRecording"),A=E.matches("waitForSessionInfo"),I=E.matches("uploading"),S=E.matches("checkSucceeded"),M=E.matches("checkFailed"),k=E.matches({recording:"flashFreshnessColors"}),w={[n.CANT_IDENTIFY]:s.hintCanNotIdentifyText,[n.FACE_IDENTIFIED]:s.hintTooFarText,[n.TOO_MANY]:s.hintTooManyFacesText,[n.TOO_CLOSE]:s.hintTooCloseText,[n.TOO_FAR]:s.hintTooFarText,[n.MATCHED]:s.hintHoldFaceForFreshnessText},D={[i.BRIGHT]:s.hintIlluminationTooBrightText,[i.DARK]:s.hintIlluminationTooDarkText,[i.NORMAL]:s.hintIlluminationNormalText},_=(()=>{if(!(x||M||S)){if(!y){if(v)return F===n.TOO_MANY?e.createElement(l,null,w[F]):e.createElement(l,null,s.hintMoveFaceFrontOfCameraText);if(C&&!1===g)return e.createElement(l,null,s.hintTooCloseText);if(j)return e.createElement(l,null,s.hintHoldFacePositionCountdownText);if(A)return e.createElement(l,null,e.createElement(t,{alignItems:"center",gap:"xs"},e.createElement(r,null),e.createElement(o,null,s.hintConnectingText)));if(I)return e.createElement(m,{backgroundColor:"overlay.40",anchorOrigin:{horizontal:"center",vertical:"end"}},e.createElement(l,null,e.createElement(t,{alignItems:"center",gap:"xs"},e.createElement(r,null),e.createElement(o,null,s.hintVerifyingText))));if(d&&d!==i.NORMAL)return e.createElement(l,null,D[d])}return k?e.createElement(l,{size:"large",variation:"primary"},s.hintHoldFaceForFreshnessText):y&&!k?e.createElement(l,{size:"large",variation:O===n.TOO_CLOSE?"error":"primary"},O===n.TOO_CLOSE?w[n.TOO_CLOSE]:w[n.TOO_FAR]):null}})();return _||null};export{E as Hint,h as selectErrorState,f as selectFaceMatchState,p as selectFaceMatchStateBeforeStart,u as selectIlluminationState,T as selectIsFaceFarEnoughBeforeRecording};
@@ -1 +1 @@
1
- import{__rest as t}from"../../../node_modules/tslib/tslib.es6.mjs";import*as i from"react";import{Flex as e}from"@aws-amplify/ui-react";const r=r=>{var{children:o,anchorOrigin:n={horizontal:"center",vertical:"center"}}=r,a=t(r,["children","anchorOrigin"]);return i.createElement(e,Object.assign({direction:"column",position:"absolute",left:"0",top:"0",alignItems:n.horizontal,justifyContent:n.vertical,width:"100%",height:"100%",padding:"xl"},a),o)};export{r as Overlay};
1
+ import{__rest as t}from"tslib";import*as i from"react";import{Flex as r}from"@aws-amplify/ui-react";const e=e=>{var{children:n,anchorOrigin:o={horizontal:"center",vertical:"center"}}=e,a=t(e,["children","anchorOrigin"]);return i.createElement(r,Object.assign({direction:"column",position:"absolute",left:"0",top:"0",alignItems:o.horizontal,justifyContent:o.vertical,width:"100%",height:"100%",padding:"xl"},a),n)};export{e as Overlay};
@@ -1 +1 @@
1
- import{__rest as e}from"../../../node_modules/tslib/tslib.es6.mjs";import t from"react";import{Flex as a,View as r}from"@aws-amplify/ui-react";import{LivenessClassNames as i}from"../types/classNames.mjs";const l=l=>{var{children:n,caption:m,variation:s="default"}=l,c=e(l,["children","caption","variation"]);return t.createElement(a,Object.assign({as:"figure",className:`${i.Figure} ${i.Figure}--${s}`},c),t.createElement(r,{className:`${i.FigureImage} ${i.FigureImage}--${s}`},"success"===s?t.createElement("svg",{className:i.FigureIcon,"aria-hidden":"true",width:"24",height:"24"},t.createElement("g",{fill:"none"},t.createElement("path",{fill:"#365E3D",d:"M0 0h24v24H0z"}),t.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"===s?t.createElement("svg",{className:i.FigureIcon,"aria-hidden":"true",width:"24",height:"24"},t.createElement("g",{fill:"none"},t.createElement("path",{fill:"#600",d:"M0 0h24v24H0z"}),t.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,n),t.createElement(r,{as:"figcaption",className:`${i.FigureCaption} ${i.FigureCaption}--${s}`},m))};export{l as StartScreenFigure};
1
+ import{__rest as e}from"tslib";import t from"react";import{Flex as a,View as r}from"@aws-amplify/ui-react";import{LivenessClassNames as i}from"../types/classNames.mjs";const l=l=>{var{children:n,caption:c,variation:m="default"}=l,s=e(l,["children","caption","variation"]);return t.createElement(a,Object.assign({as:"figure",className:`${i.Figure} ${i.Figure}--${m}`},s),t.createElement(r,{className:`${i.FigureImage} ${i.FigureImage}--${m}`},"success"===m?t.createElement("svg",{className:i.FigureIcon,"aria-hidden":"true",width:"24",height:"24"},t.createElement("g",{fill:"none"},t.createElement("path",{fill:"#365E3D",d:"M0 0h24v24H0z"}),t.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"===m?t.createElement("svg",{className:i.FigureIcon,"aria-hidden":"true",width:"24",height:"24"},t.createElement("g",{fill:"none"},t.createElement("path",{fill:"#600",d:"M0 0h24v24H0z"}),t.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,n),t.createElement(r,{as:"figcaption",className:`${i.FigureCaption} ${i.FigureCaption}--${m}`},c))};export{l as StartScreenFigure};
@@ -1 +1 @@
1
- import{__rest as e}from"../../../node_modules/tslib/tslib.es6.mjs";import*as a from"react";import{View as t,Flex as s}from"@aws-amplify/ui-react";import{LivenessClassNames as m}from"../types/classNames.mjs";const i=i=>{var{variation:r="default",size:o="medium",children:l}=i,n=e(i,["variation","size","children"]);return a.createElement(t,Object.assign({padding:"small",borderRadius:"medium",className:`${m.Toast} ${m.Toast}--${r} ${m.Toast}--${o}`,maxWidth:{base:"100%",small:"70%"}},n),a.createElement(s,{gap:"xs",direction:"column",alignItems:"center"},a.createElement(s,{className:`${m.Toast}__message`,textAlign:"center",direction:"column"},l)))};export{i as Toast};
1
+ import{__rest as e}from"tslib";import*as a from"react";import{View as t,Flex as s}from"@aws-amplify/ui-react";import{LivenessClassNames as i}from"../types/classNames.mjs";const m=m=>{var{variation:r="default",size:o="medium",children:l}=m,n=e(m,["variation","size","children"]);return a.createElement(t,Object.assign({padding:"small",borderRadius:"medium",className:`${i.Toast} ${i.Toast}--${r} ${i.Toast}--${o}`,maxWidth:{base:"100%",small:"70%"}},n),a.createElement(s,{gap:"xs",direction:"column",alignItems:"center"},a.createElement(s,{className:`${i.Toast}__message`,textAlign:"center",direction:"column"},l)))};export{m as Toast};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("@xstate/react"),a=require("xstate"),i=require("@tensorflow/tfjs-core"),n=require("@tensorflow-models/blazeface"),r=require("@tensorflow/tfjs-backend-wasm");require("@tensorflow/tfjs-backend-cpu");var o=require("@aws-amplify/core"),s=require("@aws-amplify/predictions"),c=require("@aws-sdk/client-rekognitionstreaming"),l=require("@aws-sdk/middleware-websocket"),d=require("nanoid"),h=require("@aws-amplify/ui-react"),u=require("@aws-amplify/ui-react/internal"),m=require("@aws-amplify/ui"),f=require("react-countdown-circle-timer"),g=require("classnames");function v(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function p(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 E,T,C,x=v(e),S=p(e),y=p(i),F=p(n),R=p(r),M=v(f),A=v(g);function D(e,t){var a={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(a[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(a[i[n]]=e[i[n]])}return a}function w(e,t,a,i){return new(a||(a=Promise))((function(n,r){function o(e){try{c(i.next(e))}catch(e){r(e)}}function s(e){try{c(i.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof a?t:new a((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))}function I(e){var t="function"==typeof Symbol&&Symbol.iterator,a=t&&e[t],i=0;if(a)return a.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function O(e){return this instanceof O?(this.v=e,this):new O(e)}function b(e,t,a){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,n=a.apply(e,t||[]),r=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(e){n[e]&&(i[e]=function(t){return new Promise((function(a,i){r.push([e,t,a,i])>1||s(e,t)}))})}function s(e,t){try{(a=n[e](t)).value instanceof O?Promise.resolve(a.value.v).then(c,l):d(r[0][2],a)}catch(e){d(r[0][3],e)}var a}function c(e){s("next",e)}function l(e){s("throw",e)}function d(e,t){e(t),r.shift(),r.length&&s(r[0][0],r[0][1])}}function _(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,a=e[Symbol.asyncIterator];return a?a.call(e):(e=I(e),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(a){t[a]=e[a]&&function(t){return new Promise((function(i,n){(function(e,t,a,i){Promise.resolve(i).then((function(t){e({value:t,done:a})}),t)})(i,n,(t=e[a](t)).done,t.value)}))}}}class P{triggerModelLoading(){this.modelLoadingPromise=this.loadModels()}}!function(e){e.DARK="dark",e.BRIGHT="bright",e.NORMAL="normal"}(E||(E={})),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"}(T||(T={})),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"}(C||(C={}));function k(e,t,a){return e*(a-t)+t}function L(e){const t=e.flippedCenterX-e.width/2,a=e.flippedCenterX+e.width/2,i=e.centerY-e.height/2,n=e.centerY+e.height/2;return{ovalBoundingBox:{left:t,top:i,right:a,bottom:n},minOvalX:t,maxOvalX:a,minOvalY:i,maxOvalY:n}}function N(e,t){const a=Math.max(e.left,t.left),i=Math.max(e.top,t.top),n=Math.min(e.right,t.right),r=Math.min(e.bottom,t.bottom),o=Math.abs(Math.max(0,n-a)*Math.max(0,r-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(e){const{leftEye:t,rightEye:a,mouth:i}=e,n=[];n[0]=(t[0]+a[0])/2,n[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(n[0]-i[0],2)+Math.pow(n[1]-i[1],2))}}function H(e,t){const{leftEye:a,rightEye:i,nose:n}=e,{height:r,centerY:o}=t,s=o-r/2,c=[];c[0]=(a[0]+i[0])/2,c[1]=(a[1]+i[1])/2;const{pupilDistance:l,faceHeight:d}=B(e),h=(2*l+1.8*d)/2,u=1.618*h;let m,f;c[1]<=(s+r)/2?(m=(c[0]+n[0])/2,f=(c[1]+n[1])/2):(m=c[0],f=c[1]);const g=m-h/2,v=f-u/2;return{left:g,top:v,right:g+h,bottom:v+u}}function W(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,n=8,r=new Array(n).fill(0);for(let e=0;e<i.length;e++){r[Math.round(.2126*i[e++]+.7152*i[e++]+.0722*i[e++])%32]++}let o=-1,s=0;for(let e=0;e<n;e++)r[e]>s&&(s=r[e],o=e);return t.remove(),0===o?E.DARK:o===n?E.BRIGHT:E.NORMAL}throw new Error("Cannot find Video Element.")}const V={[C.RUNTIME_ERROR]:"RUNTIME_ERROR",[C.SERVER_ERROR]:"SERVER_ERROR",[C.TIMEOUT]:"TIMEOUT",[C.FACE_DISTANCE_ERROR]:"FACE_DISTANCE_ERROR",[C.CAMERA_FRAMERATE_ERROR]:"CAMERA_FRAMERATE_ERROR",[C.CAMERA_ACCESS_ERROR]:"CAMERA_ACCESS_ERROR",[C.MOBILE_LANDSCAPE_ERROR]:"MOBILE_LANDSCAPE_ERROR",[C.FRESHNESS_TIMEOUT]:"FRESHNESS_TIMEOUT"};function j({ctx:e,prevColor:t,nextColor:a,fraction:i}){const n=e.canvas.width,r=e.canvas.height;e.fillStyle=a,e.fillRect(0,0,n,r*i),1!==i&&(e.fillStyle=t,e.fillRect(0,r*i,n,r*(1-i)))}const z=e=>!!e;function q(e){return e.slice(e.indexOf("(")+1,e.indexOf(")")).split(",").map((e=>parseInt(e)))}function U({deviceHeight:e,deviceWidth:t,height:a,width:i,top:n,left:r}){return{Height:a/e,Width:i/t,Top:n/e,Left:r/t}}class Y extends P{constructor(e,t){super(),this.faceModelUrl=t,this.binaryPath=null!=e?e:`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${R.version_wasm}/dist/`}loadModels(){return w(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 y.ready(),this._model=yield o.jitteredExponentialRetry(F.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(e){return w(this,void 0,void 0,(function*(){const t=yield this._model.estimateFaces(e,!1,!0,!0),a=Date.now();return t.filter((e=>!!e.landmarks)).map((e=>{const{topLeft:t,bottomRight:i,probability:n,landmarks:r}=e,[o,s]=t,[c,l]=i,d=Math.abs(o-c),h=Math.abs(l-s),u=r[0],m=r[1],f=r[2],g=r[3];return{top:s,left:c,width:d,height:h,timestampMs:a,probability:n[0],rightEye:u,leftEye:m,mouth:g,nose:f}}))}))}_loadWebAssemblyBackend(){return w(this,void 0,void 0,(function*(){try{R.setWasmPaths(this.binaryPath),yield o.jitteredExponentialRetry((()=>w(this,void 0,void 0,(function*(){if(!(yield y.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 w(this,void 0,void 0,(function*(){yield y.setBackend("cpu"),this.modelBackend="cpu"}))}}class ${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 w(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)}_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.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 G=process.env.NEXT_PUBLIC_STREAMING_API_URL;function X(e){return void 0!==e.Challenge}class Z extends s.AmazonAIInterpretPredictionsProvider{constructor(e,t,a,i){super(),this.sessionId=e,this.region=t,this._stream=a,this.videoEl=i,this.videoRecorder=new $(a),this.initPromise=this.init()}getResponseStream(){return w(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 w(this,void 0,void 0,(function*(){yield this.videoRecorder.stop()}))}dispatchStopVideoEvent(){this.videoRecorder.dispatch(new Event("stopVideo"))}endStream(){return w(this,void 0,void 0,(function*(){if("recording"===this.videoRecorder.getState()&&(yield this.stopVideo(),this.dispatchStopVideoEvent()),this._reader)return yield this._reader.cancel(),this._reader.closed}))}init(){return w(this,void 0,void 0,(function*(){const e=yield o.Credentials.get();if(!e)throw new Error("No credentials");const t={credentials:e,region:this.region,customUserAgent:o.getAmplifyUserAgent(),requestHandler:new l.WebSocketFetchHandler({connectionTimeout:1e4})};G&&(t.endpointProvider=()=>({url:new URL(G)})),this._client=new c.RekognitionStreamingClient(t),this.responseStream=yield this.startLivenessVideoConnection()}))}getAsyncGeneratorFromReadableStream(e){const t=this;return this._reader=e.getReader(),function(){return b(this,arguments,(function*(){for(;;){const{done:e,value:a}=yield O(t._reader.read());if(e)return yield O(void 0);if("stopVideo"===a)yield yield O({VideoEvent:{VideoChunk:[],TimestampMillis:Date.now()}});else if(void 0!==a.arrayBuffer){const e=yield O(a.arrayBuffer()),t=new Uint8Array(e);t.length>0&&(yield yield O({VideoEvent:{VideoChunk:t,TimestampMillis:Date.now()}}))}else X(a)&&(yield yield O({ClientSessionInformationEvent:{Challenge:a.Challenge}}))}}))}}startLivenessVideoConnection(){return w(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 K;!function(e){e.SCROLLING="SCROLLING",e.FLAT="FLAT"}(K||(K={}));class Q{constructor(e,t){this.context=e,this.freshnessColorsSequence=t,this.isFirstTick=!0}displayColorTick(){return w(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=K.FLAT,this.timeLastFlatOrScrollChange=Date.now(),this.timeLastFaceMatchChecked=Date.now()}displayNextColorTick(e,t){const{freshnessColorEl:a}=this.context.freshnessColorAssociatedParams,{ovalDetails:i,scaleFactor:n}=this.context.ovalAssociatedParams,{videoEl:r}=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===K.FLAT&&s>=this.currColorSequence.flatDisplayDuration||this.stage===K.SCROLLING&&s>=this.currColorSequence.downscrollDuration)&&(this.incrementStageIndex(o),s=0),this.currColorIndex<this.freshnessColorsSequence.length){const t=s/(this.stage===K.SCROLLING?this.currColorSequence.downscrollDuration:this.currColorSequence.flatDisplayDuration);!function({overlayCanvas:e,prevColor:t,nextColor:a,videoEl:i,ovalDetails:n,heightFraction:r,scaleFactor:o}){const{x:s,y:c}=i.getBoundingClientRect(),{flippedCenterX:l,centerY:d,width:h,height:u}=n,m=l*o+s,f=d*o+c,g=e.width,v=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,g,v),j({ctx:p,prevColor:t,nextColor:a,fraction:r}),p.save(),p.beginPath(),p.rect(0,0,g,v),p.clip(),p.clearRect(0,0,g,v),p.globalAlpha=.9,j({ctx:p,prevColor:t,nextColor:a,fraction:r}),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,g,v),p.globalAlpha=.75,j({ctx:p,prevColor:t,nextColor:a,fraction:r}),p.restore()}({overlayCanvas:a,prevColor:this.prevColorSequence.color,nextColor:this.currColorSequence.color,videoEl:r,ovalDetails:i,heightFraction:t,scaleFactor:n}),e(!1)}else a.style.display="none",e(!0)}incrementStageIndex(e){if(this.stageIndex+=1,this.prevColorSequence=this.freshnessColorsSequence[this.currColorIndex],this.stage===K.FLAT)this.currColorIndex+=1,this.stage=K.SCROLLING;else if(this.stage===K.SCROLLING){this.freshnessColorsSequence[this.currColorIndex].flatDisplayDuration>0?this.stage=K.FLAT:(this.stage=K.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:n,challengeId:r}=this.context;n.sendClientInfo({Challenge:{FaceMovementAndLightChallenge:{ChallengeId:r,ColorDisplayed:{CurrentColor:{RGB:q(t)},PreviousColor:{RGB:q(a)},SequenceNumber:i,CurrentColorStartTimestamp:e}}}})}}const J=e=>!!(null==e?void 0:e.DisconnectionEvent),ee=e=>!!(null==e?void 0:e.ValidationException),te=e=>!!(null==e?void 0:e.InternalServerException),ae=e=>!!(null==e?void 0:e.ThrottlingException),ie=e=>!!(null==e?void 0:e.ServiceQuotaExceededException);let ne;const re=a.createMachine({id:"livenessMachine",initial:"start",predictableActionArguments:!0,context:{challengeId:d.nanoid(),maxFailedAttempts:0,failedAttempts:0,componentProps:void 0,serverSessionInformation:void 0,videoAssociatedParams:void 0,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"},MOBILE_LANDSCAPE_WARNING:{target:"mobileLandscapeWarning",actions:"updateErrorStateForServer"}},states:{start:{on:{BEGIN:"cameraCheck"}},cameraCheck:{entry:["resetErrorState","setVideoConstraints","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:"waitForSessionInfo",actions:["updateLivenessStreamProvider","spawnResponseStreamActor"]}}},waitForSessionInfo:{after:{0:{target:"notRecording",cond:"hasServerSessionInfo"},100:{target:"waitForSessionInfo"}}},notRecording:{on:{START_RECORDING:"recording"},initial:"detectFaceDistanceDuringCountdown",states:{detectFaceDistanceDuringCountdown:{invoke:{src:"detectFaceDistance",onDone:{target:"checkFaceDistanceDuringCountdown",actions:["updateFaceDistanceBeforeRecording"]}}},checkFaceDistanceDuringCountdown:{after:{0:{target:"failure",cond:"hasNotEnoughFaceDistanceBeforeRecording"},200:{target:"detectFaceDistanceDuringCountdown"}}},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:a.assign({responseStreamActorRef:()=>a.spawn(oe)}),updateFailedAttempts:a.assign({failedAttempts:e=>e.failedAttempts+1}),setVideoConstraints:a.assign({videoAssociatedParams:(e,t)=>{var a,i;return Object.assign(Object.assign({},e.videoAssociatedParams),{videoConstraints:(null===(a=t.data)||void 0===a?void 0:a.videoConstraints)||(null===(i=e.videoAssociatedParams)||void 0===i?void 0:i.videoConstraints)})}}),updateVideoMediaStream:a.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:a.assign({ovalAssociatedParams:e=>{const{componentProps:t}=e,{faceModelUrl:a,binaryPath:i}=t.config,n=new Y(i,a);return n.triggerModelLoading(),Object.assign(Object.assign({},e.ovalAssociatedParams),{faceDetector:n})}}),updateLivenessStreamProvider:a.assign({livenessStreamProvider:(e,t)=>{var a;return null===(a=t.data)||void 0===a?void 0:a.livenessStreamProvider}}),setDOMAndCameraDetails:a.assign({videoAssociatedParams:(e,t)=>{var a,i,n;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===(n=t.data)||void 0===n?void 0:n.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:a.assign({videoAssociatedParams:e=>{const{challengeId:t,videoAssociatedParams:a,ovalAssociatedParams:i,livenessStreamProvider:n}=e,{recordingStartApiTimestamp:r,recorderStartTimestamp:o}=n.videoRecorder,{videoMediaStream:s}=a,{initialFace:c}=i,l=Math.round(.73*(o-r)+r),{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:U({deviceHeight:h,deviceWidth:d,height:c.height,width:c.width,top:c.top,left:u})}}}}),Object.assign(Object.assign({},e.videoAssociatedParams),{recordingStartTimestampMs:l})}}),startRecording:a.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:a.assign({faceMatchStateBeforeStart:(e,t)=>t.data.faceMatchState}),updateFaceDistanceBeforeRecording:a.assign({isFaceFarEnoughBeforeRecording:(e,t)=>t.data.isFaceFarEnoughBeforeRecording}),updateOvalAndFaceDetailsPostDraw:a.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:a.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:a.assign({faceMatchAssociatedParams:e=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{endFace:e.faceMatchAssociatedParams.currentDetectedFace})}),setFaceMatchTimeAndStartFace:a.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:a.assign({errorState:e=>{}}),updateErrorStateForTimeout:a.assign({errorState:(e,t)=>{var a;return(null===(a=t.data)||void 0===a?void 0:a.errorState)||C.TIMEOUT}}),updateErrorStateForRuntime:a.assign({errorState:e=>C.RUNTIME_ERROR}),updateErrorStateForServer:a.assign({errorState:e=>C.SERVER_ERROR}),clearErrorState:a.assign({errorState:e=>{}}),updateSessionInfo:a.assign({serverSessionInformation:(e,t)=>t.data.sessionInfo}),updateShouldDisconnect:a.assign({shouldDisconnect:e=>!0}),updateFreshnessDetails:a.assign({freshnessColorAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorsComplete:t.data.freshnessColorsComplete})}),setupFlashFreshnessColors:a.assign({freshnessColorAssociatedParams:e=>{const{serverSessionInformation:t}=e,a=(t.Challenge.FaceMovementAndLightChallenge.ColorSequences||[]).map((({FreshnessColor:e,DownscrollDuration:t,FlatDisplayDuration:a})=>{const i=e.RGB,n=`rgb(${i[0]},${i[1]},${i[2]})`;return void 0!==n&&void 0!==t&&void 0!==a?{color:n,downscrollDuration:t,flatDisplayDuration:a}:void 0})).filter(z);const i=new Q(e,a);return Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorDisplay:i})}}),sendTimeoutAfterOvalDrawingDelay:a.actions.send({type:"TIMEOUT"},{delay:5e3,id:"ovalDrawingTimeout"}),cancelOvalDrawingTimeout:a.actions.cancel("ovalDrawingTimeout"),sendTimeoutAfterOvalMatchDelay:a.actions.send({type:"TIMEOUT"},{delay:7e3,id:"ovalMatchTimeout"}),cancelOvalMatchTimeout:a.actions.cancel("ovalMatchTimeout"),sendTimeoutAfterWaitingForDisconnect:a.actions.send({type:"TIMEOUT",data:{errorState:C.SERVER_ERROR}},{delay:2e4,id:"waitForDisconnectTimeout"}),cancelWaitForDisconnectTimeout:a.actions.cancel("waitForDisconnectTimeout"),sendTimeoutAfterFaceDistanceDelay:a.actions.send({type:"TIMEOUT",data:{errorState:C.FACE_DISTANCE_ERROR}},{delay:0,id:"faceDistanceTimeout"}),cancelFaceDistanceTimeout:a.actions.cancel("faceDistanceTimeout"),callUserPermissionDeniedCallback:a.assign({errorState:(e,t)=>{var a,i;let n;n=t.data.message.includes("15 fps")?C.CAMERA_FRAMERATE_ERROR:C.CAMERA_ACCESS_ERROR;const r=t.data.message||t.data.Message,o=new Error(r);return o.name=n,null===(i=(a=e.componentProps).onError)||void 0===i||i.call(a,o),n}}),callMobileLandscapeWarningCallback:a.assign({errorState:e=>C.MOBILE_LANDSCAPE_ERROR}),callUserCancelCallback:e=>w(void 0,void 0,void 0,(function*(){var t,a;null===(a=(t=e.componentProps).onUserCancel)||void 0===a||a.call(t)})),callUserTimeoutCallback:e=>w(void 0,void 0,void 0,(function*(){var t,a;const i=new Error(V[e.errorState]);i.name=e.errorState,null===(a=(t=e.componentProps).onError)||void 0===a||a.call(t,i)})),callErrorCallback:(e,t)=>w(void 0,void 0,void 0,(function*(){var a,i,n,r,o,s;const c=(null===(i=null===(a=t.data)||void 0===a?void 0:a.error)||void 0===i?void 0:i.message)||(null===(r=null===(n=t.data)||void 0===n?void 0:n.error)||void 0===r?void 0:r.Message),l=new Error(c);l.name=e.errorState,null===(s=(o=e.componentProps).onError)||void 0===s||s.call(o,l)})),cleanUpResources:e=>w(void 0,void 0,void 0,(function*(){var t;const{freshnessColorEl:a}=e.freshnessColorAssociatedParams;a&&(a.style.display="none"),yield null===(t=e.livenessStreamProvider)||void 0===t?void 0:t.endStream()})),freezeStream:e=>w(void 0,void 0,void 0,(function*(){const{videoMediaStream:t,videoEl:a}=e.videoAssociatedParams;e.isRecordingStopped=!0,null==a||a.pause(),null==t||t.getTracks().forEach((function(e){e.stop()}))})),pauseVideoStream:e=>w(void 0,void 0,void 0,(function*(){const{videoEl:t}=e.videoAssociatedParams;e.isRecordingStopped=!0,t.pause()})),resetContext:a.assign({challengeId:d.nanoid(),maxFailedAttempts:0,failedAttempts:0,componentProps:e=>e.componentProps,serverSessionInformation:e=>{},videoAssociatedParams:e=>{},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===T.MATCHED&&i>=500},hasFaceMatchedInOval:e=>e.faceMatchAssociatedParams.faceMatchState===T.MATCHED,hasNotFaceMatchedInOval:e=>e.faceMatchAssociatedParams.faceMatchState!==T.MATCHED,hasSingleFace:e=>e.faceMatchAssociatedParams.faceMatchState===T.FACE_IDENTIFIED,hasSingleFaceBeforeStart:e=>e.faceMatchStateBeforeStart===T.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(e){return w(this,void 0,void 0,(function*(){const{videoConstraints:t}=e.videoAssociatedParams,a=yield navigator.mediaDevices.getUserMedia({video:t,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 n=a.getTracks().filter((e=>e.getSettings().frameRate>=15));if(n.length<1)throw new Error("No camera found with more than 15 fps");const r=n[0].getSettings().deviceId;let o=a;return i.some((e=>e.deviceId===r))||(o=yield navigator.mediaDevices.getUserMedia({video:Object.assign(Object.assign({},t),{deviceId:{exact:i[0].deviceId}}),audio:!1})),{stream:o}}))},openLivenessStreamConnection(e){return w(this,void 0,void 0,(function*(){const t=new Z(e.componentProps.sessionId,e.componentProps.region,e.videoAssociatedParams.videoMediaStream,e.videoAssociatedParams.videoEl);return ne=t.getResponseStream(),{livenessStreamProvider:t}}))},detectFace(e){return w(this,void 0,void 0,(function*(){const{videoEl:t}=e.videoAssociatedParams,{faceDetector:a}=e.ovalAssociatedParams;try{yield a.modelLoadingPromise}catch(e){console.log({err:e})}const i=yield function(e,t){return w(this,void 0,void 0,(function*(){let a;switch((yield e.detectFaces(t)).length){case 0:a=T.CANT_IDENTIFY;break;case 1:a=T.FACE_IDENTIFIED;break;default:a=T.TOO_MANY}return a}))}(a,t);return{faceMatchState:i}}))},detectFaceDistance(e){return w(this,void 0,void 0,(function*(){const{isFaceFarEnoughBeforeRecording:t}=e,{videoEl:a,videoMediaStream:i,isMobile:n}=e.videoAssociatedParams,{faceDetector:r}=e.ovalAssociatedParams,{width:o,height:s}=i.getTracks()[0].getSettings(),c=function({width:e,height:t,widthSeed:a=1,centerXSeed:i=.5,centerYSeed:n=.5}){const r=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=k(i,c,l),m=k(n,d,h);e>=t&&(o=3/4*r);const f=s*o,g=1.618*f;return{flippedCenterX:Math.floor(o-u),centerX:Math.floor(u),centerY:Math.floor(m),width:Math.floor(f),height:Math.floor(g)}}({width:o,height:s}),l=yield function({faceDetector:e,videoEl:t,ovalDetails:a,reduceThreshold:i=!1,isMobile:n=!1}){return w(this,void 0,void 0,(function*(){const r=yield e.detectFaces(t);let o,s=!1;switch(r.length){case 0:break;case 1:{o=r[0];const e=a.width,{pupilDistance:t,faceHeight:c}=B(o),l=2;e&&(s=(l*t+1.8*c)/2/l/e<(i?n?.37:.4:.32));break}}return s}))}({faceDetector:r,videoEl:a,ovalDetails:c,reduceThreshold:t,isMobile:n});return{isFaceFarEnoughBeforeRecording:l}}))},detectInitialFaceAndDrawOval(e){return w(this,void 0,void 0,(function*(){const{serverSessionInformation:t,livenessStreamProvider:a}=e,{videoEl:i,canvasEl:n,isMobile:r}=e.videoAssociatedParams,{faceDetector:o}=e.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=T.CANT_IDENTIFY,d=W(i);break;case 1:l=T.FACE_IDENTIFIED,c=s[0];break;default:l=T.TOO_MANY}if(!c)return{faceMatchState:l,illuminationState:d};const{width:h,height:u}=i.getBoundingClientRect();r?(n.width=window.innerWidth,n.height=window.innerHeight):(n.width=h,n.height=u);const m=h/i.videoWidth,f=function({sessionInformation:e,videoWidth:t}){var a,i;const n=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(!(n&&n.CenterX&&n.CenterY&&n.Width&&n.Height))throw new Error("Oval parameters not returned from session information.");return{flippedCenterX:t-n.CenterX,centerX:n.CenterX,centerY:n.CenterY,width:n.Width,height:n.Height}}({sessionInformation:t,videoWidth:i.width}),g=H(c,f);return c.top=g.top,c.left=g.left,c.height=g.bottom-g.top,c.width=g.right-g.left,function({canvas:e,oval:t,scaleFactor:a,videoEl:i}){const{flippedCenterX:n,centerY:r,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(n,r,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:n,oval:f,scaleFactor:m,videoEl:i}),{faceMatchState:l,ovalDetails:f,scaleFactor:m,initialFace:c}}))},detectFaceAndMatchOval(e){return w(this,void 0,void 0,(function*(){const{serverSessionInformation:t}=e,{videoEl:a}=e.videoAssociatedParams,{faceDetector:i,ovalDetails:n,initialFace:r}=e.ovalAssociatedParams,o=yield i.detectFaces(a);let s,c,l,d=0;const h=H(r,n),{ovalBoundingBox:u}=L(n),m=N(h,u);switch(o.length){case 0:s=T.CANT_IDENTIFY,l=W(a);break;case 1:{c=o[0];const{faceMatchState:e,faceMatchPercentage:a}=function(e,t,a,i){var n,r;let o;const s=null===(r=null===(n=null==i?void 0:i.Challenge)||void 0===n?void 0:n.FaceMovementAndLightChallenge)||void 0===r?void 0:r.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=H(e,t),f=m.left,g=m.right,v=m.top,p=m.bottom,{ovalBoundingBox:E,minOvalX:C,minOvalY:x,maxOvalX:S,maxOvalY:y}=L(t),F=N(m,E),R=c,M=t.width*d,A=t.height*l,D=t.width*u,w=t.height*h,I=100*Math.max(Math.min(1,.75*(F-a)/(R-a)+.25),0);return o=F>R&&Math.abs(C-f)<M&&Math.abs(S-g)<M&&Math.abs(y-p)<A?T.MATCHED:x-v>w||p-y>w||C-f>D&&g-S>D?T.TOO_CLOSE:T.TOO_FAR,{faceMatchState:o,faceMatchPercentage:I}}(c,n,m,t);s=e,d=a;break}default:s=T.TOO_MANY}return{faceMatchState:s,faceMatchPercentage:d,illuminationState:l,detectedFace:c}}))},flashColors(e){return w(this,void 0,void 0,(function*(){const{freshnessColorsComplete:t,freshnessColorDisplay:a}=e.freshnessColorAssociatedParams;if(t)return;return{freshnessColorsComplete:yield a.displayColorTick()}}))},stopVideo(e){return w(this,void 0,void 0,(function*(){const{challengeId:t,livenessStreamProvider:a}=e,{videoMediaStream:i}=e.videoAssociatedParams,{initialFace:n,ovalDetails:r}=e.ovalAssociatedParams,{startFace:o,endFace:s}=e.faceMatchAssociatedParams,{width:c,height:l}=i.getTracks()[0].getSettings(),d=c-n.left-n.width;yield a.stopVideo();const h={Challenge:{FaceMovementAndLightChallenge:{ChallengeId:t,InitialFace:{InitialFaceDetectedTimestamp:n.timestampMs,BoundingBox:U({deviceHeight:l,deviceWidth:c,height:n.height,width:n.width,top:n.top,left:d})},TargetFace:{FaceDetectedInTargetPositionStartTimestamp:o.timestampMs,FaceDetectedInTargetPositionEndTimestamp:s.timestampMs,BoundingBox:U({deviceHeight:l,deviceWidth:c,height:r.height,width:r.width,top:r.centerY-r.height/2,left:r.centerX-r.width/2})},VideoEndTimestamp:a.videoRecorder.recorderEndTimestamp}}};a.sendClientInfo(h),yield a.dispatchStopVideoEvent()}))},getLiveness(e){return w(this,void 0,void 0,(function*(){const{livenessStreamProvider:t}=e,{onAnalysisComplete:a}=e.componentProps;t.endStream(),yield a()}))}}}),oe=e=>w(void 0,void 0,void 0,(function*(){var t,a,i,n,r;try{const l=yield ne;try{for(var o,s=!0,c=_(l);!(t=(o=yield c.next()).done);){n=o.value,s=!1;try{const t=n;(null==(r=t)?void 0:r.ServerSessionInformationEvent)?e({type:"SET_SESSION_INFO",data:{sessionInfo:t.ServerSessionInformationEvent.SessionInformation}}):J(t)?e({type:"DISCONNECT_EVENT"}):ee(t)?e({type:"SERVER_ERROR",data:{error:Object.assign({},t.ValidationException)}}):te(t)?e({type:"SERVER_ERROR",data:{error:Object.assign({},t.InternalServerException)}}):ae(t)?e({type:"SERVER_ERROR",data:{error:Object.assign({},t.ThrottlingException)}}):ie(t)&&e({type:"SERVER_ERROR",data:{error:Object.assign({},t.ServiceQuotaExceededException)}})}finally{s=!0}}}catch(e){a={error:e}}finally{try{s||t||!(i=c.return)||(yield i.call(c))}finally{if(a)throw a.error}}}catch(t){let a=t;(e=>{const{message:t,name:a}=e;return"InvalidSignatureException"===a&&t.includes("valid region")})(t)&&(a=new Error("Invalid region in FaceLivenessDetector or credentials are scoped to the wrong region.")),a instanceof Error&&e({type:"SERVER_ERROR",data:{error:a}})}})),se=x.default.createContext(null);function ce(e){var{children:t}=e,a=D(e,["children"]);return x.default.createElement(se.Provider,{value:a},t)}function le(){const e=x.default.useContext(se);if(null===e)throw new Error("useFaceLivenessDetector must be used within a FaceLivenessDetectorProvider");return e}function de(){const{service:e}=le();return t.useActor(e)}function he(e){const{service:a}=le();return t.useSelector(a,e)}var ue;!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.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.Loader="amplify-liveness-loader",e.MatchIndicator="amplify-liveness-match-indicator",e.OvalCanvas="amplify-liveness-oval-canvas",e.RecordingIconContainer="amplify-liveness-recording-icon-container",e.RecordingIcon="amplify-liveness-recording-icon",e.Toast="amplify-liveness-toast",e.Video="amplify-liveness-video",e.VideoAnchor="amplify-liveness-video-anchor"}(ue||(ue={}));const me=({ariaLabel:e})=>{const[t,a]=de();return t.done?null:x.default.createElement(h.Button,{autoFocus:!0,variation:"link",onClick:()=>{a({type:"CANCEL"})},size:"large",className:ue.CancelButton,"aria-label":e},x.default.createElement(u.IconClose,{"aria-hidden":"true","data-testid":"close-icon"}))},fe=e=>{var{variation:t="default",size:a="medium",children:i}=e,n=D(e,["variation","size","children"]);return S.createElement(h.View,Object.assign({padding:"small",borderRadius:"medium",className:`${ue.Toast} ${ue.Toast}--${t} ${ue.Toast}--${a}`,maxWidth:{base:"100%",small:"70%"}},n),S.createElement(h.Flex,{gap:"xs",direction:"column",alignItems:"center"},S.createElement(h.Flex,{className:`${ue.Toast}__message`,textAlign:"center",direction:"column"},i)))},ge=e=>{var{children:t,anchorOrigin:a={horizontal:"center",vertical:"center"}}=e,i=D(e,["children","anchorOrigin"]);return S.createElement(h.Flex,Object.assign({direction:"column",position:"absolute",left:"0",top:"0",alignItems:a.horizontal,justifyContent:a.vertical,width:"100%",height:"100%",padding:"xl"},i),t)},ve=e=>e.context.errorState,pe=e=>e.context.faceMatchAssociatedParams.faceMatchState,Ee=e=>e.context.faceMatchAssociatedParams.illuminationState,Te=e=>e.context.isFaceFarEnoughBeforeRecording,Ce=e=>e.context.faceMatchStateBeforeStart,xe=({hintDisplayText:e})=>{const[t]=de(),a=he(ve),i=he(pe),n=he(Ee),r=he(Ce),o=he(Te),s=t.matches("checkFaceDetectedBeforeStart"),c=t.matches("checkFaceDistanceBeforeRecording"),l=t.matches("recording"),d=t.matches("notRecording"),u=t.matches("waitForSessionInfo"),m=t.matches("uploading"),f=t.matches("checkSucceeded"),g=t.matches("checkFailed"),v=t.matches({recording:"flashFreshnessColors"}),p={[T.CANT_IDENTIFY]:e.hintCanNotIdentifyText,[T.FACE_IDENTIFIED]:e.hintTooFarText,[T.TOO_MANY]:e.hintTooManyFacesText,[T.TOO_CLOSE]:e.hintTooCloseText,[T.TOO_FAR]:e.hintTooFarText,[T.MATCHED]:e.hintHoldFaceForFreshnessText},C={[E.BRIGHT]:e.hintIlluminationTooBrightText,[E.DARK]:e.hintIlluminationTooDarkText,[E.NORMAL]:e.hintIlluminationNormalText},x=(()=>{if(!(a||g||f)){if(!l){if(s)return r===T.TOO_MANY?S.createElement(fe,null,p[r]):S.createElement(fe,null,e.hintMoveFaceFrontOfCameraText);if(c&&!1===o)return S.createElement(fe,null,e.hintTooCloseText);if(d)return S.createElement(fe,null,e.hintHoldFacePositionCountdownText);if(u)return S.createElement(fe,null,S.createElement(h.Flex,{alignItems:"center",gap:"xs"},S.createElement(h.Loader,null),S.createElement(h.View,null,e.hintConnectingText)));if(m)return S.createElement(ge,{backgroundColor:"overlay.40",anchorOrigin:{horizontal:"center",vertical:"end"}},S.createElement(fe,null,S.createElement(h.Flex,{alignItems:"center",gap:"xs"},S.createElement(h.Loader,null),S.createElement(h.View,null,e.hintVerifyingText))));if(n&&n!==E.NORMAL)return S.createElement(fe,null,C[n])}return v?S.createElement(fe,{size:"large",variation:"primary"},e.hintHoldFaceForFreshnessText):l&&!v?S.createElement(fe,{size:"large",variation:i===T.TOO_CLOSE?"error":"primary"},i===T.TOO_CLOSE?p[T.TOO_CLOSE]:p[T.TOO_FAR]):null}})();return x||null},Se=({percentage:e,initialPercentage:t=25,testId:a})=>{const[i,n]=x.default.useState(t);x.default.useEffect((()=>{n(e<0?0:e>100?100:e)}),[e]);const r={"--percentage":`${i}%`};return x.default.createElement("div",{className:ue.MatchIndicator,"data-testid":a},x.default.createElement("div",{className:`${ue.MatchIndicator}__bar`,style:r}),x.default.createElement("div",{className:`${ue.MatchIndicator}__pin`,style:r}))},ye=({children:e})=>x.default.createElement(h.Flex,{className:ue.RecordingIcon},x.default.createElement(h.Flex,{"data-testid":"rec-icon",justifyContent:"center"},x.default.createElement(h.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(h.Text,{as:"span",fontWeight:"bold"},e)),Fe=e=>{var{children:t,caption:a,variation:i="default"}=e,n=D(e,["children","caption","variation"]);return x.default.createElement(h.Flex,Object.assign({as:"figure",className:`${ue.Figure} ${ue.Figure}--${i}`},n),x.default.createElement(h.View,{className:`${ue.FigureImage} ${ue.FigureImage}--${i}`},"success"===i?x.default.createElement("svg",{className:ue.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"===i?x.default.createElement("svg",{className:ue.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,t),x.default.createElement(h.View,{as:"figcaption",className:`${ue.FigureCaption} ${ue.FigureCaption}--${i}`},a))},Re=({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"}))),Me=({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"}))),Ae=({children:e})=>{const{tokens:t}=h.useTheme(),a=u.useThemeBreakpoint(),[i,n]=S.useState(!1),r=S.useRef(null),o="base"===a;return S.useEffect((()=>{function e(e){i&&r.current&&!r.current.contains(e.target)&&n(!1)}return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}}),[r,i]),S.createElement(h.Flex,{position:"relative",onClick:()=>n(!i),ref:r,style:{cursor:"pointer"},testId:"popover-icon"},S.createElement(u.AlertIcon,{ariaHidden:!0,variation:"info"}),i&&S.createElement(S.Fragment,null,S.createElement(h.Flex,{position:"absolute",top:26,left:3,style:{zIndex:3,borderStyle:"solid",borderWidth:"0 9px 9px 9px",borderColor:`transparent transparent ${t.colors.background.primary} transparent`}}),S.createElement(h.Flex,{position:"absolute",top:24,left:2,style:{zIndex:2,borderStyle:"solid",borderWidth:"0 10px 10px 10px",borderColor:`transparent transparent ${t.colors.border.secondary} transparent`}}),S.createElement(h.Flex,{position:"absolute",backgroundColor:`${t.colors.background.primary}`,color:`${t.colors.font.primary}`,direction:"row",fontSize:t.fontSizes.xs,padding:t.space.small,top:33,minWidth:240,left:o?-190:-108,border:`1px solid ${t.colors.border.secondary}`,borderRadius:2,"data-testid":"popover-text"},e)))};Ae.displayName="LivenessIconWithPopover";const De=({headingText:e,bodyText:t})=>x.default.createElement(h.View,{flex:"1"},x.default.createElement(h.View,{color:"font.primary",fontWeight:"bold"},e),x.default.createElement(h.View,{color:"font.primary"},t)),we=({headingText:e,bodyText:t,infoText:a})=>x.default.createElement(h.Flex,{className:h.ComponentClassNames.Alert,color:"orange.80",backgroundColor:"orange.20",alignItems:"center"},x.default.createElement(h.View,{flex:"1"},x.default.createElement(h.View,{className:h.ComponentClassNames.AlertHeading},e),x.default.createElement(h.View,{className:h.ComponentClassNames.AlertBody},t)),x.default.createElement(Ae,null,a)),Ie=({headingText:e,goodFitCaptionText:t,goodFitAltText:a,tooFarCaptionText:i,tooFarAltText:n,steps:r})=>x.default.createElement(h.Flex,{direction:"column"},x.default.createElement(h.Text,{color:"font.primary",fontWeight:"bold"},e),x.default.createElement(h.Flex,{className:ue.Figures},x.default.createElement(Fe,{variation:"success",caption:t},x.default.createElement(Re,{title:a})),x.default.createElement(Fe,{variation:"error",caption:i},x.default.createElement(Me,{title:n}))),x.default.createElement(h.Flex,{as:"ol",className:ue.InstructionList},r.map(((e,t)=>x.default.createElement(h.Flex,{as:"li",key:t+1},x.default.createElement(h.Text,{as:"span","aria-hidden":"true"},t+1,"."),x.default.createElement(h.Text,{as:"span"},e)))))),Oe="liveness-detector-start";function be(e){const{beginLivenessCheck:t,components:a,instructionDisplayText:i}=e;return S.createElement(h.Card,{className:Oe,"data-testid":Oe},S.createElement(h.Flex,{direction:"column"},(null==a?void 0:a.Header)?S.createElement(a.Header,null):S.createElement(De,{headingText:i.instructionsHeaderHeadingText,bodyText:i.instructionsHeaderBodyText}),(null==a?void 0:a.PhotosensitiveWarning)?S.createElement(a.PhotosensitiveWarning,null):S.createElement(we,{headingText:i.photosensitivyWarningHeadingText,bodyText:i.photosensitivyWarningBodyText,infoText:i.photosensitivyWarningInfoText}),(null==a?void 0:a.Instructions)?S.createElement(a.Instructions,null):S.createElement(Ie,{headingText:i.instructionListHeadingText,goodFitCaptionText:i.goodFitCaptionText,goodFitAltText:i.goodFitAltText,tooFarCaptionText:i.tooFarCaptionText,tooFarAltText:i.tooFarAltText,steps:[i.instructionListStepOneText,i.instructionListStepTwoText,i.instructionListStepThreeText,i.instructionListStepFourText]}),S.createElement(h.Flex,{justifyContent:"center"},S.createElement(h.Button,{variation:"primary",type:"button",onClick:t},i.instructionsBeginCheckText))))}const _e={timeoutHeaderText:"Time out",timeoutMessageText:"Face didn't fill oval within time limit. Try again and completely fill oval with face within 7 seconds.",faceDistanceHeaderText:"Check failed during countdown",faceDistanceMessageText:"Avoid moving closer during countdown and ensure only one face is in front of camera.",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"},Pe=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, fill the oval with your face within 7 seconds.",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"},_e),ke=({errorState:e,overrideErrorDisplayText:t})=>{const a=Object.assign(Object.assign({},_e),t);return e===C.CAMERA_ACCESS_ERROR||e===C.CAMERA_FRAMERATE_ERROR||e===C.MOBILE_LANDSCAPE_ERROR?null:(e=>{const{error:t,displayText:a}=e,{timeoutHeaderText:i,timeoutMessageText:n,faceDistanceHeaderText:r,faceDistanceMessageText:o,clientHeaderText:s,clientMessageText:c,serverHeaderText:l,serverMessageText:d}=a;let m,f;switch(t){case C.TIMEOUT:m=i,f=n;break;case C.FACE_DISTANCE_ERROR:m=r,f=o;break;case C.RUNTIME_ERROR:m=s,f=c;break;case C.SERVER_ERROR:default:m=l,f=d}return x.default.createElement(x.default.Fragment,null,x.default.createElement(h.Flex,{gap:"xs",alignItems:"center",justifyContent:"center",color:"font.error"},x.default.createElement(u.AlertIcon,{ariaHidden:!0,variation:"error"}),x.default.createElement(h.Text,{fontWeight:"bold"},m)),f)})({error:e,displayText:a})},Le=e=>{const{children:t,onRetry:a,displayText:i}=e,n=Object.assign(Object.assign({},_e),i),{tryAgainText:r}=n;return x.default.createElement(ge,{backgroundColor:"overlay.40"},x.default.createElement(fe,null,t,x.default.createElement(h.Flex,{justifyContent:"center"},x.default.createElement(h.Button,{variation:"primary",type:"button",onClick:a},r))))},Ne=e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoConstraints},Be=e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoMediaStream},He=e=>e.context.faceMatchAssociatedParams.faceMatchPercentage,We=e=>e.context.faceMatchAssociatedParams.faceMatchState,Ve=x.default.createElement(h.Loader,{size:"large",className:ue.Loader,"data-testid":"centered-loader"}),je=t=>{const{isMobileScreen:a,isRecordingStopped:i,streamDisplayText:n,hintDisplayText:r,errorDisplayText:o,components:s,testId:c}=t,{cancelLivenessCheckText:l,recordingIndicatorText:d}=n,{ErrorView:u=Le}=null!=s?s:{},{tokens:f}=h.useTheme(),[g,v]=de(),p=he(Be),E=he(Ne),C=he(He),S=he(We),y=he(ve),F=[T.TOO_FAR,T.CANT_IDENTIFY,T.FACE_IDENTIFIED,T.MATCHED],{videoRef:R,videoWidth:D,videoHeight:w}=function(t,a){const i=a.height.ideal,n=a.width.ideal,r=e.useRef(null),[o,s]=e.useState(i),[c,l]=e.useState(n);return e.useEffect((()=>{if(t){m.isObject(r.current)&&(r.current.srcObject=t);const{height:e,width:a}=t.getTracks()[0].getSettings();s(e),l(a)}return()=>{t&&t.getTracks().forEach((e=>{t.removeTrack(e),e.stop()}))}}),[t]),{videoRef:r,videoHeight:o,videoWidth:c}}(p,E),I=e.useRef(null),O=e.useRef(null),[b,_]=e.useState(!1),[P,k]=e.useState(!1),L=g.matches("cameraCheck"),N=g.matches("notRecording"),B=g.matches("recording"),H=g.matches("checkSucceeded"),W=g.matches({recording:"flashFreshnessColors"}),[V,j]=e.useState(D),[z,q]=e.useState(w),[U,Y]=e.useState((()=>D&&w?D/w:0));x.default.useLayoutEffect((()=>{P&&v({type:"SET_DOM_AND_CAMERA_DETAILS",data:{videoEl:R.current,canvasEl:I.current,freshnessColorEl:O.current,isMobile:a}}),R.current&&(j(R.current.videoWidth),q(R.current.videoHeight),Y(R.current.videoWidth/R.current.videoHeight))}),[v,R,P,a]);return L?x.default.createElement(h.Flex,{height:w,width:"100%",position:"relative"},Ve):x.default.createElement(h.Flex,{className:A.default(ue.CameraModule,a&&`${ue.CameraModule}--mobile`),"data-testid":c},!P&&Ve,x.default.createElement(h.View,{as:"canvas",ref:O,className:ue.FreshnessCanvas,hidden:!0}),x.default.createElement(h.View,{className:ue.VideoAnchor,style:{aspectRatio:`${U}`}},x.default.createElement("video",{ref:R,muted:!0,autoPlay:!0,playsInline:!0,style:{transform:"scaleX(-1)"},width:V,height:z,onCanPlay:()=>{k(!0),_(!0)},"data-testid":"video",className:ue.Video}),x.default.createElement(h.Flex,{className:A.default(ue.OvalCanvas,a&&`${ue.OvalCanvas}--mobile`,i&&ue.FadeOut)},x.default.createElement(h.View,{as:"canvas",width:"100%",height:"100%",ref:I})),B&&x.default.createElement(h.View,{className:ue.RecordingIconContainer},x.default.createElement(ye,null,d)),!H&&x.default.createElement(h.View,{className:ue.CancelContainer},x.default.createElement(me,{ariaLabel:l})),b&&x.default.createElement(ge,{anchorOrigin:{horizontal:"center",vertical:B&&!W?"start":"space-between"},className:ue.InstructionOverlay},x.default.createElement(xe,{hintDisplayText:r}),y&&x.default.createElement(u,{onRetry:()=>{v({type:"CANCEL"})}},ke({errorState:y,overrideErrorDisplayText:o})),B&&!W&&F.includes(S)?x.default.createElement(Se,{percentage:C}):null,N&&x.default.createElement(h.View,{className:ue.CountdownContainer,testId:"liveness-camera-countdown-timer"},x.default.createElement(M.default.CountdownCircleTimer,{isPlaying:N,size:85,strokeWidth:8,duration:3,rotation:"counterclockwise",colors:"#40aabf",trailColor:`${f.colors.background.primary}`,onComplete:()=>{v({type:"START_RECORDING"})}},(({remainingTime:e})=>x.default.createElement(h.Text,{fontSize:"xxxl",fontWeight:"bold"},e)))))))};function ze(){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 Ue=e=>{const{onRetry:t,header:a,portraitMessage:i,landscapeMessage:n,tryAgainText:r}=e,[o,s]=S.useState(!0);return S.useLayoutEffect((()=>{const e=qe();return s(e.matches),e.addEventListener("change",(e=>{s(e.matches)})),()=>{e.removeEventListener("change",(e=>s(e.matches)))}}),[]),S.createElement(h.Flex,{backgroundColor:"background.primary",direction:"column",textAlign:"center",alignItems:"center",justifyContent:"center",width:"100%",height:o?"auto":480},S.createElement(h.Text,{fontSize:"large",fontWeight:"bold"},a),S.createElement(h.Text,null,o?n:i),o?null:S.createElement(h.Flex,{justifyContent:"center"},S.createElement(h.Button,{variation:"primary",type:"button",onClick:t},r)))},Ye="liveness-detector-check",$e=e=>e.context.errorState,Ge=e=>e.context.isRecordingStopped,Xe=({hintDisplayText:e,cameraDisplayText:t,streamDisplayText:a,errorDisplayText:i,components:n})=>{const[r,o]=de(),s=he($e),c=he(Ge),l=r.matches("permissionDenied"),d=ze(),u=()=>{o({type:"RETRY_CAMERA_CHECK"})},{cameraMinSpecificationsHeadingText:m,cameraMinSpecificationsMessageText:f,cameraNotFoundHeadingText:g,cameraNotFoundMessageText:v,retryCameraPermissionsText:p}=t,{cancelLivenessCheckText:E}=a;S.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 S.createElement(h.Flex,{direction:"column",position:"relative",testId:Ye,className:Ye},(()=>{if(s===C.MOBILE_LANDSCAPE_ERROR){const e=Object.assign(Object.assign({},_e),i),{landscapeHeaderText:t,portraitMessageText:a,landscapeMessageText:n,tryAgainText:r}=e;return S.createElement(h.Flex,{backgroundColor:"background.primary",direction:"column",textAlign:"center",alignItems:"center",justifyContent:"center",position:"absolute",width:"100%"},S.createElement(Ue,{header:t,portraitMessage:a,landscapeMessage:n,tryAgainText:r,onRetry:()=>{o({type:"CANCEL"})}}))}return l?S.createElement(h.Flex,{backgroundColor:"background.primary",direction:"column",textAlign:"center",alignItems:"center",justifyContent:"center",width:"100%",height:480},S.createElement(h.Text,{fontSize:"large",fontWeight:"bold"},s===C.CAMERA_FRAMERATE_ERROR?m:g),S.createElement(h.Text,{maxWidth:300},s===C.CAMERA_FRAMERATE_ERROR?f:v),S.createElement(h.Button,{variation:"primary",type:"button",onClick:u},p),S.createElement(h.View,{position:"absolute",top:"medium",right:"medium"},S.createElement(me,{ariaLabel:E}))):S.createElement(je,{isMobileScreen:d,isRecordingStopped:c,streamDisplayText:a,hintDisplayText:e,errorDisplayText:i,components:n})})())};const Ze="liveness-detector";exports.FaceLivenessDetector=function(e){const{disableInstructionScreen:a=!1,components:i,config:n,displayText:r}=e,o=S.useRef(null),{hintDisplayText:s,cameraDisplayText:c,instructionDisplayText:l,streamDisplayText:d,errorDisplayText:u}=function(e){const t=Object.assign(Object.assign({},Pe),e),{instructionsHeaderHeadingText:a,instructionsHeaderBodyText:i,instructionsBeginCheckText:n,photosensitivyWarningHeadingText:r,photosensitivyWarningBodyText:o,photosensitivyWarningInfoText:s,instructionListHeadingText:c,goodFitCaptionText:l,goodFitAltText:d,tooFarCaptionText:h,tooFarAltText:u,instructionListStepOneText:m,instructionListStepTwoText:f,instructionListStepThreeText:g,instructionListStepFourText:v,cameraMinSpecificationsHeadingText:p,cameraMinSpecificationsMessageText:E,cameraNotFoundHeadingText:T,cameraNotFoundMessageText:C,retryCameraPermissionsText:x,cancelLivenessCheckText:S,recordingIndicatorText:y,hintMoveFaceFrontOfCameraText:F,hintTooManyFacesText:R,hintFaceDetectedText:M,hintCanNotIdentifyText:A,hintTooCloseText:D,hintTooFarText:w,hintHoldFacePositionCountdownText:I,hintConnectingText:O,hintVerifyingText:b,hintIlluminationTooBrightText:_,hintIlluminationTooDarkText:P,hintIlluminationNormalText:k,hintHoldFaceForFreshnessText:L,timeoutHeaderText:N,timeoutMessageText:B,faceDistanceHeaderText:H,faceDistanceMessageText:W,clientHeaderText:V,clientMessageText:j,serverHeaderText:z,serverMessageText:q,landscapeHeaderText:U,landscapeMessageText:Y,portraitMessageText:$,tryAgainText:G}=t;return{hintDisplayText:{hintMoveFaceFrontOfCameraText:F,hintTooManyFacesText:R,hintFaceDetectedText:M,hintCanNotIdentifyText:A,hintTooCloseText:D,hintTooFarText:w,hintHoldFacePositionCountdownText:I,hintConnectingText:O,hintVerifyingText:b,hintIlluminationTooBrightText:_,hintIlluminationTooDarkText:P,hintIlluminationNormalText:k,hintHoldFaceForFreshnessText:L},cameraDisplayText:{cameraMinSpecificationsHeadingText:p,cameraMinSpecificationsMessageText:E,cameraNotFoundHeadingText:T,cameraNotFoundMessageText:C,retryCameraPermissionsText:x},instructionDisplayText:{instructionsHeaderHeadingText:a,instructionsHeaderBodyText:i,instructionsBeginCheckText:n,photosensitivyWarningHeadingText:r,photosensitivyWarningBodyText:o,photosensitivyWarningInfoText:s,instructionListHeadingText:c,goodFitCaptionText:l,goodFitAltText:d,tooFarCaptionText:h,tooFarAltText:u,instructionListStepOneText:m,instructionListStepTwoText:f,instructionListStepThreeText:g,instructionListStepFourText:v},streamDisplayText:{cancelLivenessCheckText:S,recordingIndicatorText:y},errorDisplayText:{timeoutHeaderText:N,timeoutMessageText:B,faceDistanceHeaderText:H,faceDistanceMessageText:W,clientHeaderText:V,clientMessageText:j,serverHeaderText:z,serverMessageText:q,landscapeHeaderText:U,landscapeMessageText:Y,portraitMessageText:$,tryAgainText:G}}}(r),m=t.useInterpret(re,{devTools:"development"===process.env.NODE_ENV,context:{componentProps:Object.assign(Object.assign({},e),{config:null!=n?n:{}})}}),[f,g]=t.useActor(m),v=f.matches("start")||f.matches("userCancel"),p=S.useCallback((()=>{g({type:"BEGIN",data:{videoConstraints:{width:{min:320,ideal:640},height:{min:240,ideal:480},frameRate:{min:15,ideal:30,max:30},facingMode:"user"}}})}),[g]);return S.useLayoutEffect((()=>{a&&v&&p()}),[p,a,v]),S.createElement(h.View,{className:Ze,testId:Ze},S.createElement(ce,{componentProps:e,service:m},S.createElement(h.Flex,{direction:"column",ref:o},v?S.createElement(be,{beginLivenessCheck:p,components:i,instructionDisplayText:l}):S.createElement(Xe,{hintDisplayText:s,cameraDisplayText:c,streamDisplayText:d,errorDisplayText:u,components:i}))))};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("@xstate/react"),a=require("tslib"),i=require("xstate"),n=require("@tensorflow/tfjs-core"),r=require("@tensorflow-models/blazeface"),o=require("@tensorflow/tfjs-backend-wasm");require("@tensorflow/tfjs-backend-cpu");var s=require("@aws-amplify/core"),c=require("@aws-amplify/predictions"),l=require("@aws-sdk/client-rekognitionstreaming"),d=require("@aws-sdk/middleware-websocket"),h=require("nanoid"),u=require("@aws-amplify/ui-react"),m=require("@aws-amplify/ui-react/internal"),f=require("@aws-amplify/ui"),g=require("react-countdown-circle-timer"),v=require("classnames");function p(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function E(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 T,C,x,S=p(e),F=E(e),R=E(n),y=E(r),M=E(o),A=p(g),w=p(v);class D{triggerModelLoading(){this.modelLoadingPromise=this.loadModels()}}!function(e){e.DARK="dark",e.BRIGHT="bright",e.NORMAL="normal"}(T||(T={})),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"}(C||(C={})),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"}(x||(x={}));function _(e,t,a){return e*(a-t)+t}function I(e){const t=e.flippedCenterX-e.width/2,a=e.flippedCenterX+e.width/2,i=e.centerY-e.height/2,n=e.centerY+e.height/2;return{ovalBoundingBox:{left:t,top:i,right:a,bottom:n},minOvalX:t,maxOvalX:a,minOvalY:i,maxOvalY:n}}function O(e,t){const a=Math.max(e.left,t.left),i=Math.max(e.top,t.top),n=Math.min(e.right,t.right),r=Math.min(e.bottom,t.bottom),o=Math.abs(Math.max(0,n-a)*Math.max(0,r-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(e){const{leftEye:t,rightEye:a,mouth:i}=e,n=[];n[0]=(t[0]+a[0])/2,n[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(n[0]-i[0],2)+Math.pow(n[1]-i[1],2))}}function k(e,t){const{leftEye:a,rightEye:i,nose:n}=e,{height:r,centerY:o}=t,s=o-r/2,c=[];c[0]=(a[0]+i[0])/2,c[1]=(a[1]+i[1])/2;const{pupilDistance:l,faceHeight:d}=b(e),h=(2*l+1.8*d)/2,u=1.618*h;let m,f;c[1]<=(s+r)/2?(m=(c[0]+n[0])/2,f=(c[1]+n[1])/2):(m=c[0],f=c[1]);const g=m-h/2,v=f-u/2;return{left:g,top:v,right:g+h,bottom:v+u}}function P(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,n=8,r=new Array(n).fill(0);for(let e=0;e<i.length;e++){r[Math.round(.2126*i[e++]+.7152*i[e++]+.0722*i[e++])%32]++}let o=-1,s=0;for(let e=0;e<n;e++)r[e]>s&&(s=r[e],o=e);return t.remove(),0===o?T.DARK:o===n?T.BRIGHT:T.NORMAL}throw new Error("Cannot find Video Element.")}const L={[x.RUNTIME_ERROR]:"RUNTIME_ERROR",[x.SERVER_ERROR]:"SERVER_ERROR",[x.TIMEOUT]:"TIMEOUT",[x.FACE_DISTANCE_ERROR]:"FACE_DISTANCE_ERROR",[x.CAMERA_FRAMERATE_ERROR]:"CAMERA_FRAMERATE_ERROR",[x.CAMERA_ACCESS_ERROR]:"CAMERA_ACCESS_ERROR",[x.MOBILE_LANDSCAPE_ERROR]:"MOBILE_LANDSCAPE_ERROR",[x.FRESHNESS_TIMEOUT]:"FRESHNESS_TIMEOUT"};function N({ctx:e,prevColor:t,nextColor:a,fraction:i}){const n=e.canvas.width,r=e.canvas.height;e.fillStyle=a,e.fillRect(0,0,n,r*i),1!==i&&(e.fillStyle=t,e.fillRect(0,r*i,n,r*(1-i)))}const B=e=>!!e;function H(e){return e.slice(e.indexOf("(")+1,e.indexOf(")")).split(",").map((e=>parseInt(e)))}function V({deviceHeight:e,deviceWidth:t,height:a,width:i,top:n,left:r}){return{Height:a/e,Width:i/t,Top:n/e,Left:r/t}}class W extends D{constructor(e,t){super(),this.faceModelUrl=t,this.binaryPath=null!=e?e:`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${M.version_wasm}/dist/`}loadModels(){return a.__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 R.ready(),this._model=yield s.jitteredExponentialRetry(y.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(e){return a.__awaiter(this,void 0,void 0,(function*(){const t=yield this._model.estimateFaces(e,!1,!0,!0),a=Date.now();return t.filter((e=>!!e.landmarks)).map((e=>{const{topLeft:t,bottomRight:i,probability:n,landmarks:r}=e,[o,s]=t,[c,l]=i,d=Math.abs(o-c),h=Math.abs(l-s),u=r[0],m=r[1],f=r[2],g=r[3];return{top:s,left:c,width:d,height:h,timestampMs:a,probability:n[0],rightEye:u,leftEye:m,mouth:g,nose:f}}))}))}_loadWebAssemblyBackend(){return a.__awaiter(this,void 0,void 0,(function*(){try{M.setWasmPaths(this.binaryPath),yield s.jitteredExponentialRetry((()=>a.__awaiter(this,void 0,void 0,(function*(){if(!(yield R.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 a.__awaiter(this,void 0,void 0,(function*(){yield R.setBackend("cpu"),this.modelBackend="cpu"}))}}class j{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 a.__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)}_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.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 z=process.env.NEXT_PUBLIC_STREAMING_API_URL;function q(e){return void 0!==e.Challenge}class U extends c.AmazonAIInterpretPredictionsProvider{constructor(e,t,a,i){super(),this.sessionId=e,this.region=t,this._stream=a,this.videoEl=i,this.videoRecorder=new j(a),this.initPromise=this.init()}getResponseStream(){return a.__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 a.__awaiter(this,void 0,void 0,(function*(){yield this.videoRecorder.stop()}))}dispatchStopVideoEvent(){this.videoRecorder.dispatch(new Event("stopVideo"))}endStream(){return a.__awaiter(this,void 0,void 0,(function*(){if("recording"===this.videoRecorder.getState()&&(yield this.stopVideo(),this.dispatchStopVideoEvent()),this._reader)return yield this._reader.cancel(),this._reader.closed}))}init(){return a.__awaiter(this,void 0,void 0,(function*(){const e=yield s.Credentials.get();if(!e)throw new Error("No credentials");const t={credentials:e,region:this.region,customUserAgent:s.getAmplifyUserAgent(),requestHandler:new d.WebSocketFetchHandler({connectionTimeout:1e4})};z&&(t.endpointProvider=()=>({url:new URL(z)})),this._client=new l.RekognitionStreamingClient(t),this.responseStream=yield this.startLivenessVideoConnection()}))}getAsyncGeneratorFromReadableStream(e){const t=this;return this._reader=e.getReader(),function(){return a.__asyncGenerator(this,arguments,(function*(){for(;;){const{done:e,value:i}=yield a.__await(t._reader.read());if(e)return yield a.__await(void 0);if("stopVideo"===i)yield yield a.__await({VideoEvent:{VideoChunk:[],TimestampMillis:Date.now()}});else if(void 0!==i.arrayBuffer){const e=yield a.__await(i.arrayBuffer()),t=new Uint8Array(e);t.length>0&&(yield yield a.__await({VideoEvent:{VideoChunk:t,TimestampMillis:Date.now()}}))}else q(i)&&(yield yield a.__await({ClientSessionInformationEvent:{Challenge:i.Challenge}}))}}))}}startLivenessVideoConnection(){return a.__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 Y;!function(e){e.SCROLLING="SCROLLING",e.FLAT="FLAT"}(Y||(Y={}));class ${constructor(e,t){this.context=e,this.freshnessColorsSequence=t,this.isFirstTick=!0}displayColorTick(){return a.__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=Y.FLAT,this.timeLastFlatOrScrollChange=Date.now(),this.timeLastFaceMatchChecked=Date.now()}displayNextColorTick(e,t){const{freshnessColorEl:a}=this.context.freshnessColorAssociatedParams,{ovalDetails:i,scaleFactor:n}=this.context.ovalAssociatedParams,{videoEl:r}=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===Y.FLAT&&s>=this.currColorSequence.flatDisplayDuration||this.stage===Y.SCROLLING&&s>=this.currColorSequence.downscrollDuration)&&(this.incrementStageIndex(o),s=0),this.currColorIndex<this.freshnessColorsSequence.length){const t=s/(this.stage===Y.SCROLLING?this.currColorSequence.downscrollDuration:this.currColorSequence.flatDisplayDuration);!function({overlayCanvas:e,prevColor:t,nextColor:a,videoEl:i,ovalDetails:n,heightFraction:r,scaleFactor:o}){const{x:s,y:c}=i.getBoundingClientRect(),{flippedCenterX:l,centerY:d,width:h,height:u}=n,m=l*o+s,f=d*o+c,g=e.width,v=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,g,v),N({ctx:p,prevColor:t,nextColor:a,fraction:r}),p.save(),p.beginPath(),p.rect(0,0,g,v),p.clip(),p.clearRect(0,0,g,v),p.globalAlpha=.9,N({ctx:p,prevColor:t,nextColor:a,fraction:r}),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,g,v),p.globalAlpha=.75,N({ctx:p,prevColor:t,nextColor:a,fraction:r}),p.restore()}({overlayCanvas:a,prevColor:this.prevColorSequence.color,nextColor:this.currColorSequence.color,videoEl:r,ovalDetails:i,heightFraction:t,scaleFactor:n}),e(!1)}else a.style.display="none",e(!0)}incrementStageIndex(e){if(this.stageIndex+=1,this.prevColorSequence=this.freshnessColorsSequence[this.currColorIndex],this.stage===Y.FLAT)this.currColorIndex+=1,this.stage=Y.SCROLLING;else if(this.stage===Y.SCROLLING){this.freshnessColorsSequence[this.currColorIndex].flatDisplayDuration>0?this.stage=Y.FLAT:(this.stage=Y.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:n,challengeId:r}=this.context;n.sendClientInfo({Challenge:{FaceMovementAndLightChallenge:{ChallengeId:r,ColorDisplayed:{CurrentColor:{RGB:H(t)},PreviousColor:{RGB:H(a)},SequenceNumber:i,CurrentColorStartTimestamp:e}}}})}}const G=e=>!!(null==e?void 0:e.DisconnectionEvent),X=e=>!!(null==e?void 0:e.ValidationException),Z=e=>!!(null==e?void 0:e.InternalServerException),K=e=>!!(null==e?void 0:e.ThrottlingException),Q=e=>!!(null==e?void 0:e.ServiceQuotaExceededException);let J;const ee=i.createMachine({id:"livenessMachine",initial:"start",predictableActionArguments:!0,context:{challengeId:h.nanoid(),maxFailedAttempts:0,failedAttempts:0,componentProps:void 0,serverSessionInformation:void 0,videoAssociatedParams:void 0,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"},MOBILE_LANDSCAPE_WARNING:{target:"mobileLandscapeWarning",actions:"updateErrorStateForServer"}},states:{start:{on:{BEGIN:"cameraCheck"}},cameraCheck:{entry:["resetErrorState","setVideoConstraints","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:"waitForSessionInfo",actions:["updateLivenessStreamProvider","spawnResponseStreamActor"]}}},waitForSessionInfo:{after:{0:{target:"notRecording",cond:"hasServerSessionInfo"},100:{target:"waitForSessionInfo"}}},notRecording:{on:{START_RECORDING:"recording"},initial:"detectFaceDistanceDuringCountdown",states:{detectFaceDistanceDuringCountdown:{invoke:{src:"detectFaceDistance",onDone:{target:"checkFaceDistanceDuringCountdown",actions:["updateFaceDistanceBeforeRecording"]}}},checkFaceDistanceDuringCountdown:{after:{0:{target:"failure",cond:"hasNotEnoughFaceDistanceBeforeRecording"},200:{target:"detectFaceDistanceDuringCountdown"}}},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:i.assign({responseStreamActorRef:()=>i.spawn(te)}),updateFailedAttempts:i.assign({failedAttempts:e=>e.failedAttempts+1}),setVideoConstraints:i.assign({videoAssociatedParams:(e,t)=>{var a,i;return Object.assign(Object.assign({},e.videoAssociatedParams),{videoConstraints:(null===(a=t.data)||void 0===a?void 0:a.videoConstraints)||(null===(i=e.videoAssociatedParams)||void 0===i?void 0:i.videoConstraints)})}}),updateVideoMediaStream:i.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:i.assign({ovalAssociatedParams:e=>{const{componentProps:t}=e,{faceModelUrl:a,binaryPath:i}=t.config,n=new W(i,a);return n.triggerModelLoading(),Object.assign(Object.assign({},e.ovalAssociatedParams),{faceDetector:n})}}),updateLivenessStreamProvider:i.assign({livenessStreamProvider:(e,t)=>{var a;return null===(a=t.data)||void 0===a?void 0:a.livenessStreamProvider}}),setDOMAndCameraDetails:i.assign({videoAssociatedParams:(e,t)=>{var a,i,n;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===(n=t.data)||void 0===n?void 0:n.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:i.assign({videoAssociatedParams:e=>{const{challengeId:t,videoAssociatedParams:a,ovalAssociatedParams:i,livenessStreamProvider:n}=e,{recordingStartApiTimestamp:r,recorderStartTimestamp:o}=n.videoRecorder,{videoMediaStream:s}=a,{initialFace:c}=i,l=Math.round(.73*(o-r)+r),{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:V({deviceHeight:h,deviceWidth:d,height:c.height,width:c.width,top:c.top,left:u})}}}}),Object.assign(Object.assign({},e.videoAssociatedParams),{recordingStartTimestampMs:l})}}),startRecording:i.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:i.assign({faceMatchStateBeforeStart:(e,t)=>t.data.faceMatchState}),updateFaceDistanceBeforeRecording:i.assign({isFaceFarEnoughBeforeRecording:(e,t)=>t.data.isFaceFarEnoughBeforeRecording}),updateOvalAndFaceDetailsPostDraw:i.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:i.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:i.assign({faceMatchAssociatedParams:e=>Object.assign(Object.assign({},e.faceMatchAssociatedParams),{endFace:e.faceMatchAssociatedParams.currentDetectedFace})}),setFaceMatchTimeAndStartFace:i.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:i.assign({errorState:e=>{}}),updateErrorStateForTimeout:i.assign({errorState:(e,t)=>{var a;return(null===(a=t.data)||void 0===a?void 0:a.errorState)||x.TIMEOUT}}),updateErrorStateForRuntime:i.assign({errorState:e=>x.RUNTIME_ERROR}),updateErrorStateForServer:i.assign({errorState:e=>x.SERVER_ERROR}),clearErrorState:i.assign({errorState:e=>{}}),updateSessionInfo:i.assign({serverSessionInformation:(e,t)=>t.data.sessionInfo}),updateShouldDisconnect:i.assign({shouldDisconnect:e=>!0}),updateFreshnessDetails:i.assign({freshnessColorAssociatedParams:(e,t)=>Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorsComplete:t.data.freshnessColorsComplete})}),setupFlashFreshnessColors:i.assign({freshnessColorAssociatedParams:e=>{const{serverSessionInformation:t}=e,a=(t.Challenge.FaceMovementAndLightChallenge.ColorSequences||[]).map((({FreshnessColor:e,DownscrollDuration:t,FlatDisplayDuration:a})=>{const i=e.RGB,n=`rgb(${i[0]},${i[1]},${i[2]})`;return void 0!==n&&void 0!==t&&void 0!==a?{color:n,downscrollDuration:t,flatDisplayDuration:a}:void 0})).filter(B);const i=new $(e,a);return Object.assign(Object.assign({},e.freshnessColorAssociatedParams),{freshnessColorDisplay:i})}}),sendTimeoutAfterOvalDrawingDelay:i.actions.send({type:"TIMEOUT"},{delay:5e3,id:"ovalDrawingTimeout"}),cancelOvalDrawingTimeout:i.actions.cancel("ovalDrawingTimeout"),sendTimeoutAfterOvalMatchDelay:i.actions.send({type:"TIMEOUT"},{delay:7e3,id:"ovalMatchTimeout"}),cancelOvalMatchTimeout:i.actions.cancel("ovalMatchTimeout"),sendTimeoutAfterWaitingForDisconnect:i.actions.send({type:"TIMEOUT",data:{errorState:x.SERVER_ERROR}},{delay:2e4,id:"waitForDisconnectTimeout"}),cancelWaitForDisconnectTimeout:i.actions.cancel("waitForDisconnectTimeout"),sendTimeoutAfterFaceDistanceDelay:i.actions.send({type:"TIMEOUT",data:{errorState:x.FACE_DISTANCE_ERROR}},{delay:0,id:"faceDistanceTimeout"}),cancelFaceDistanceTimeout:i.actions.cancel("faceDistanceTimeout"),callUserPermissionDeniedCallback:i.assign({errorState:(e,t)=>{var a,i;let n;n=t.data.message.includes("15 fps")?x.CAMERA_FRAMERATE_ERROR:x.CAMERA_ACCESS_ERROR;const r=t.data.message||t.data.Message,o=new Error(r);return o.name=n,null===(i=(a=e.componentProps).onError)||void 0===i||i.call(a,o),n}}),callMobileLandscapeWarningCallback:i.assign({errorState:e=>x.MOBILE_LANDSCAPE_ERROR}),callUserCancelCallback:e=>a.__awaiter(void 0,void 0,void 0,(function*(){var t,a;null===(a=(t=e.componentProps).onUserCancel)||void 0===a||a.call(t)})),callUserTimeoutCallback:e=>a.__awaiter(void 0,void 0,void 0,(function*(){var t,a;const i=new Error(L[e.errorState]);i.name=e.errorState,null===(a=(t=e.componentProps).onError)||void 0===a||a.call(t,i)})),callErrorCallback:(e,t)=>a.__awaiter(void 0,void 0,void 0,(function*(){var a,i,n,r,o,s;const c=(null===(i=null===(a=t.data)||void 0===a?void 0:a.error)||void 0===i?void 0:i.message)||(null===(r=null===(n=t.data)||void 0===n?void 0:n.error)||void 0===r?void 0:r.Message),l=new Error(c);l.name=e.errorState,null===(s=(o=e.componentProps).onError)||void 0===s||s.call(o,l)})),cleanUpResources:e=>a.__awaiter(void 0,void 0,void 0,(function*(){var t;const{freshnessColorEl:a}=e.freshnessColorAssociatedParams;a&&(a.style.display="none"),yield null===(t=e.livenessStreamProvider)||void 0===t?void 0:t.endStream()})),freezeStream:e=>a.__awaiter(void 0,void 0,void 0,(function*(){const{videoMediaStream:t,videoEl:a}=e.videoAssociatedParams;e.isRecordingStopped=!0,null==a||a.pause(),null==t||t.getTracks().forEach((function(e){e.stop()}))})),pauseVideoStream:e=>a.__awaiter(void 0,void 0,void 0,(function*(){const{videoEl:t}=e.videoAssociatedParams;e.isRecordingStopped=!0,t.pause()})),resetContext:i.assign({challengeId:h.nanoid(),maxFailedAttempts:0,failedAttempts:0,componentProps:e=>e.componentProps,serverSessionInformation:e=>{},videoAssociatedParams:e=>{},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===C.MATCHED&&i>=500},hasFaceMatchedInOval:e=>e.faceMatchAssociatedParams.faceMatchState===C.MATCHED,hasNotFaceMatchedInOval:e=>e.faceMatchAssociatedParams.faceMatchState!==C.MATCHED,hasSingleFace:e=>e.faceMatchAssociatedParams.faceMatchState===C.FACE_IDENTIFIED,hasSingleFaceBeforeStart:e=>e.faceMatchStateBeforeStart===C.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(e){return a.__awaiter(this,void 0,void 0,(function*(){const{videoConstraints:t}=e.videoAssociatedParams,a=yield navigator.mediaDevices.getUserMedia({video:t,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 n=a.getTracks().filter((e=>e.getSettings().frameRate>=15));if(n.length<1)throw new Error("No camera found with more than 15 fps");const r=n[0].getSettings().deviceId;let o=a;return i.some((e=>e.deviceId===r))||(o=yield navigator.mediaDevices.getUserMedia({video:Object.assign(Object.assign({},t),{deviceId:{exact:i[0].deviceId}}),audio:!1})),{stream:o}}))},openLivenessStreamConnection(e){return a.__awaiter(this,void 0,void 0,(function*(){const t=new U(e.componentProps.sessionId,e.componentProps.region,e.videoAssociatedParams.videoMediaStream,e.videoAssociatedParams.videoEl);return J=t.getResponseStream(),{livenessStreamProvider:t}}))},detectFace(e){return a.__awaiter(this,void 0,void 0,(function*(){const{videoEl:t}=e.videoAssociatedParams,{faceDetector:i}=e.ovalAssociatedParams;try{yield i.modelLoadingPromise}catch(e){console.log({err:e})}const n=yield function(e,t){return a.__awaiter(this,void 0,void 0,(function*(){let a;switch((yield e.detectFaces(t)).length){case 0:a=C.CANT_IDENTIFY;break;case 1:a=C.FACE_IDENTIFIED;break;default:a=C.TOO_MANY}return a}))}(i,t);return{faceMatchState:n}}))},detectFaceDistance(e){return a.__awaiter(this,void 0,void 0,(function*(){const{isFaceFarEnoughBeforeRecording:t}=e,{videoEl:i,videoMediaStream:n,isMobile:r}=e.videoAssociatedParams,{faceDetector:o}=e.ovalAssociatedParams,{width:s,height:c}=n.getTracks()[0].getSettings(),l=function({width:e,height:t,widthSeed:a=1,centerXSeed:i=.5,centerYSeed:n=.5}){const r=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=_(i,c,l),m=_(n,d,h);e>=t&&(o=3/4*r);const f=s*o,g=1.618*f;return{flippedCenterX:Math.floor(o-u),centerX:Math.floor(u),centerY:Math.floor(m),width:Math.floor(f),height:Math.floor(g)}}({width:s,height:c}),d=yield function({faceDetector:e,videoEl:t,ovalDetails:i,reduceThreshold:n=!1,isMobile:r=!1}){return a.__awaiter(this,void 0,void 0,(function*(){const a=yield e.detectFaces(t);let o,s=!1;switch(a.length){case 0:break;case 1:{o=a[0];const e=i.width,{pupilDistance:t,faceHeight:c}=b(o),l=2;e&&(s=(l*t+1.8*c)/2/l/e<(n?r?.37:.4:.32));break}}return s}))}({faceDetector:o,videoEl:i,ovalDetails:l,reduceThreshold:t,isMobile:r});return{isFaceFarEnoughBeforeRecording:d}}))},detectInitialFaceAndDrawOval(e){return a.__awaiter(this,void 0,void 0,(function*(){const{serverSessionInformation:t,livenessStreamProvider:a}=e,{videoEl:i,canvasEl:n,isMobile:r}=e.videoAssociatedParams,{faceDetector:o}=e.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=C.CANT_IDENTIFY,d=P(i);break;case 1:l=C.FACE_IDENTIFIED,c=s[0];break;default:l=C.TOO_MANY}if(!c)return{faceMatchState:l,illuminationState:d};const{width:h,height:u}=i.getBoundingClientRect();r?(n.width=window.innerWidth,n.height=window.innerHeight):(n.width=h,n.height=u);const m=h/i.videoWidth,f=function({sessionInformation:e,videoWidth:t}){var a,i;const n=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(!(n&&n.CenterX&&n.CenterY&&n.Width&&n.Height))throw new Error("Oval parameters not returned from session information.");return{flippedCenterX:t-n.CenterX,centerX:n.CenterX,centerY:n.CenterY,width:n.Width,height:n.Height}}({sessionInformation:t,videoWidth:i.width}),g=k(c,f);return c.top=g.top,c.left=g.left,c.height=g.bottom-g.top,c.width=g.right-g.left,function({canvas:e,oval:t,scaleFactor:a,videoEl:i}){const{flippedCenterX:n,centerY:r,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(n,r,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:n,oval:f,scaleFactor:m,videoEl:i}),{faceMatchState:l,ovalDetails:f,scaleFactor:m,initialFace:c}}))},detectFaceAndMatchOval(e){return a.__awaiter(this,void 0,void 0,(function*(){const{serverSessionInformation:t}=e,{videoEl:a}=e.videoAssociatedParams,{faceDetector:i,ovalDetails:n,initialFace:r}=e.ovalAssociatedParams,o=yield i.detectFaces(a);let s,c,l,d=0;const h=k(r,n),{ovalBoundingBox:u}=I(n),m=O(h,u);switch(o.length){case 0:s=C.CANT_IDENTIFY,l=P(a);break;case 1:{c=o[0];const{faceMatchState:e,faceMatchPercentage:a}=function(e,t,a,i){var n,r;let o;const s=null===(r=null===(n=null==i?void 0:i.Challenge)||void 0===n?void 0:n.FaceMovementAndLightChallenge)||void 0===r?void 0:r.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=k(e,t),f=m.left,g=m.right,v=m.top,p=m.bottom,{ovalBoundingBox:E,minOvalX:T,minOvalY:x,maxOvalX:S,maxOvalY:F}=I(t),R=O(m,E),y=c,M=t.width*d,A=t.height*l,w=t.width*u,D=t.height*h,_=100*Math.max(Math.min(1,.75*(R-a)/(y-a)+.25),0);return o=R>y&&Math.abs(T-f)<M&&Math.abs(S-g)<M&&Math.abs(F-p)<A?C.MATCHED:x-v>D||p-F>D||T-f>w&&g-S>w?C.TOO_CLOSE:C.TOO_FAR,{faceMatchState:o,faceMatchPercentage:_}}(c,n,m,t);s=e,d=a;break}default:s=C.TOO_MANY}return{faceMatchState:s,faceMatchPercentage:d,illuminationState:l,detectedFace:c}}))},flashColors(e){return a.__awaiter(this,void 0,void 0,(function*(){const{freshnessColorsComplete:t,freshnessColorDisplay:a}=e.freshnessColorAssociatedParams;if(t)return;return{freshnessColorsComplete:yield a.displayColorTick()}}))},stopVideo(e){return a.__awaiter(this,void 0,void 0,(function*(){const{challengeId:t,livenessStreamProvider:a}=e,{videoMediaStream:i}=e.videoAssociatedParams,{initialFace:n,ovalDetails:r}=e.ovalAssociatedParams,{startFace:o,endFace:s}=e.faceMatchAssociatedParams,{width:c,height:l}=i.getTracks()[0].getSettings(),d=c-n.left-n.width;yield a.stopVideo();const h={Challenge:{FaceMovementAndLightChallenge:{ChallengeId:t,InitialFace:{InitialFaceDetectedTimestamp:n.timestampMs,BoundingBox:V({deviceHeight:l,deviceWidth:c,height:n.height,width:n.width,top:n.top,left:d})},TargetFace:{FaceDetectedInTargetPositionStartTimestamp:o.timestampMs,FaceDetectedInTargetPositionEndTimestamp:s.timestampMs,BoundingBox:V({deviceHeight:l,deviceWidth:c,height:r.height,width:r.width,top:r.centerY-r.height/2,left:r.centerX-r.width/2})},VideoEndTimestamp:a.videoRecorder.recorderEndTimestamp}}};a.sendClientInfo(h),yield a.dispatchStopVideoEvent()}))},getLiveness(e){return a.__awaiter(this,void 0,void 0,(function*(){const{livenessStreamProvider:t}=e,{onAnalysisComplete:a}=e.componentProps;t.endStream(),yield a()}))}}}),te=e=>a.__awaiter(void 0,void 0,void 0,(function*(){var t,i,n,r,o;try{const d=yield J;try{for(var s,c=!0,l=a.__asyncValues(d);!(t=(s=yield l.next()).done);){r=s.value,c=!1;try{const t=r;(null==(o=t)?void 0:o.ServerSessionInformationEvent)?e({type:"SET_SESSION_INFO",data:{sessionInfo:t.ServerSessionInformationEvent.SessionInformation}}):G(t)?e({type:"DISCONNECT_EVENT"}):X(t)?e({type:"SERVER_ERROR",data:{error:Object.assign({},t.ValidationException)}}):Z(t)?e({type:"SERVER_ERROR",data:{error:Object.assign({},t.InternalServerException)}}):K(t)?e({type:"SERVER_ERROR",data:{error:Object.assign({},t.ThrottlingException)}}):Q(t)&&e({type:"SERVER_ERROR",data:{error:Object.assign({},t.ServiceQuotaExceededException)}})}finally{c=!0}}}catch(e){i={error:e}}finally{try{c||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}catch(t){let a=t;(e=>{const{message:t,name:a}=e;return"InvalidSignatureException"===a&&t.includes("valid region")})(t)&&(a=new Error("Invalid region in FaceLivenessDetector or credentials are scoped to the wrong region.")),a instanceof Error&&e({type:"SERVER_ERROR",data:{error:a}})}})),ae=S.default.createContext(null);function ie(e){var{children:t}=e,i=a.__rest(e,["children"]);return S.default.createElement(ae.Provider,{value:i},t)}function ne(){const e=S.default.useContext(ae);if(null===e)throw new Error("useFaceLivenessDetector must be used within a FaceLivenessDetectorProvider");return e}function re(){const{service:e}=ne();return t.useActor(e)}function oe(e){const{service:a}=ne();return t.useSelector(a,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.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.Loader="amplify-liveness-loader",e.MatchIndicator="amplify-liveness-match-indicator",e.OvalCanvas="amplify-liveness-oval-canvas",e.RecordingIconContainer="amplify-liveness-recording-icon-container",e.RecordingIcon="amplify-liveness-recording-icon",e.Toast="amplify-liveness-toast",e.Video="amplify-liveness-video",e.VideoAnchor="amplify-liveness-video-anchor"}(se||(se={}));const ce=({ariaLabel:e})=>{const[t,a]=re();return t.done?null:S.default.createElement(u.Button,{autoFocus:!0,variation:"link",onClick:()=>{a({type:"CANCEL"})},size:"large",className:se.CancelButton,"aria-label":e},S.default.createElement(m.IconClose,{"aria-hidden":"true","data-testid":"close-icon"}))},le=e=>{var{variation:t="default",size:i="medium",children:n}=e,r=a.__rest(e,["variation","size","children"]);return F.createElement(u.View,Object.assign({padding:"small",borderRadius:"medium",className:`${se.Toast} ${se.Toast}--${t} ${se.Toast}--${i}`,maxWidth:{base:"100%",small:"70%"}},r),F.createElement(u.Flex,{gap:"xs",direction:"column",alignItems:"center"},F.createElement(u.Flex,{className:`${se.Toast}__message`,textAlign:"center",direction:"column"},n)))},de=e=>{var{children:t,anchorOrigin:i={horizontal:"center",vertical:"center"}}=e,n=a.__rest(e,["children","anchorOrigin"]);return F.createElement(u.Flex,Object.assign({direction:"column",position:"absolute",left:"0",top:"0",alignItems:i.horizontal,justifyContent:i.vertical,width:"100%",height:"100%",padding:"xl"},n),t)},he=e=>e.context.errorState,ue=e=>e.context.faceMatchAssociatedParams.faceMatchState,me=e=>e.context.faceMatchAssociatedParams.illuminationState,fe=e=>e.context.isFaceFarEnoughBeforeRecording,ge=e=>e.context.faceMatchStateBeforeStart,ve=({hintDisplayText:e})=>{const[t]=re(),a=oe(he),i=oe(ue),n=oe(me),r=oe(ge),o=oe(fe),s=t.matches("checkFaceDetectedBeforeStart"),c=t.matches("checkFaceDistanceBeforeRecording"),l=t.matches("recording"),d=t.matches("notRecording"),h=t.matches("waitForSessionInfo"),m=t.matches("uploading"),f=t.matches("checkSucceeded"),g=t.matches("checkFailed"),v=t.matches({recording:"flashFreshnessColors"}),p={[C.CANT_IDENTIFY]:e.hintCanNotIdentifyText,[C.FACE_IDENTIFIED]:e.hintTooFarText,[C.TOO_MANY]:e.hintTooManyFacesText,[C.TOO_CLOSE]:e.hintTooCloseText,[C.TOO_FAR]:e.hintTooFarText,[C.MATCHED]:e.hintHoldFaceForFreshnessText},E={[T.BRIGHT]:e.hintIlluminationTooBrightText,[T.DARK]:e.hintIlluminationTooDarkText,[T.NORMAL]:e.hintIlluminationNormalText},x=(()=>{if(!(a||g||f)){if(!l){if(s)return r===C.TOO_MANY?F.createElement(le,null,p[r]):F.createElement(le,null,e.hintMoveFaceFrontOfCameraText);if(c&&!1===o)return F.createElement(le,null,e.hintTooCloseText);if(d)return F.createElement(le,null,e.hintHoldFacePositionCountdownText);if(h)return F.createElement(le,null,F.createElement(u.Flex,{alignItems:"center",gap:"xs"},F.createElement(u.Loader,null),F.createElement(u.View,null,e.hintConnectingText)));if(m)return F.createElement(de,{backgroundColor:"overlay.40",anchorOrigin:{horizontal:"center",vertical:"end"}},F.createElement(le,null,F.createElement(u.Flex,{alignItems:"center",gap:"xs"},F.createElement(u.Loader,null),F.createElement(u.View,null,e.hintVerifyingText))));if(n&&n!==T.NORMAL)return F.createElement(le,null,E[n])}return v?F.createElement(le,{size:"large",variation:"primary"},e.hintHoldFaceForFreshnessText):l&&!v?F.createElement(le,{size:"large",variation:i===C.TOO_CLOSE?"error":"primary"},i===C.TOO_CLOSE?p[C.TOO_CLOSE]:p[C.TOO_FAR]):null}})();return x||null},pe=({percentage:e,initialPercentage:t=25,testId:a})=>{const[i,n]=S.default.useState(t);S.default.useEffect((()=>{n(e<0?0:e>100?100:e)}),[e]);const r={"--percentage":`${i}%`};return S.default.createElement("div",{className:se.MatchIndicator,"data-testid":a},S.default.createElement("div",{className:`${se.MatchIndicator}__bar`,style:r}),S.default.createElement("div",{className:`${se.MatchIndicator}__pin`,style:r}))},Ee=({children:e})=>S.default.createElement(u.Flex,{className:se.RecordingIcon},S.default.createElement(u.Flex,{"data-testid":"rec-icon",justifyContent:"center"},S.default.createElement(u.Icon,{viewBox:{width:20,height:20},width:"20",height:"20"},S.default.createElement("circle",{cx:"10",cy:"10",r:"8",fill:"red"}))),S.default.createElement(u.Text,{as:"span",fontWeight:"bold"},e)),Te=e=>{var{children:t,caption:i,variation:n="default"}=e,r=a.__rest(e,["children","caption","variation"]);return S.default.createElement(u.Flex,Object.assign({as:"figure",className:`${se.Figure} ${se.Figure}--${n}`},r),S.default.createElement(u.View,{className:`${se.FigureImage} ${se.FigureImage}--${n}`},"success"===n?S.default.createElement("svg",{className:se.FigureIcon,"aria-hidden":"true",width:"24",height:"24"},S.default.createElement("g",{fill:"none"},S.default.createElement("path",{fill:"#365E3D",d:"M0 0h24v24H0z"}),S.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"===n?S.default.createElement("svg",{className:se.FigureIcon,"aria-hidden":"true",width:"24",height:"24"},S.default.createElement("g",{fill:"none"},S.default.createElement("path",{fill:"#600",d:"M0 0h24v24H0z"}),S.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,t),S.default.createElement(u.View,{as:"figcaption",className:`${se.FigureCaption} ${se.FigureCaption}--${n}`},i))},Ce=({title:e,testId:t})=>S.default.createElement("svg",{width:"150",height:"150","data-testid":t},S.default.createElement("title",null,e),S.default.createElement("g",{fill:"none",fillRule:"evenodd",transform:"translate(0 -.001)"},S.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"}),S.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"}),S.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"}),S.default.createElement("ellipse",{cx:"51.331",cy:"80.698",fill:"#000",fillRule:"nonzero",rx:"4.886",ry:"6.707"}),S.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"}),S.default.createElement("ellipse",{cx:"103.281",cy:"80.698",fill:"#000",fillRule:"nonzero",rx:"4.886",ry:"6.707"}),S.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"}),S.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"}),S.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"}))),xe=({title:e,testId:t})=>S.default.createElement("svg",{width:"150",height:"150","data-testid":t},S.default.createElement("title",null,e),S.default.createElement("defs",null,S.default.createElement("linearGradient",{id:"a",x1:"50%",x2:"50%",y1:"0%",y2:"100%"},S.default.createElement("stop",{offset:"0%",stopColor:"#C2C2C2"}),S.default.createElement("stop",{offset:"100%",stopColor:"#C2C2C2",stopOpacity:"0"}))),S.default.createElement("g",{fill:"none",fillRule:"evenodd",transform:"translate(2)"},S.default.createElement("path",{fill:"#FFF",fillRule:"nonzero",d:"M3.997 0h136v150h-136z"}),S.default.createElement("path",{fill:"url(#a)",fillRule:"nonzero",d:"M4.333 0h138v150h-138z"}),S.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"}),S.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"}),S.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"}),S.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"}),S.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"}),S.default.createElement("ellipse",{cx:"56.448",cy:"72.613",fill:"#000",fillRule:"nonzero",rx:"3.128",ry:"4.294"}),S.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"}),S.default.createElement("ellipse",{cx:"89.709",cy:"72.613",fill:"#000",fillRule:"nonzero",rx:"3.128",ry:"4.294"}),S.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"}),S.default.createElement("path",{stroke:"#000",strokeWidth:"1.353",d:"M69.005 82.806c0 1.858.859 5.487 4.287 5.144"}),S.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"}),S.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"}))),Se=({children:e})=>{const{tokens:t}=u.useTheme(),a=m.useThemeBreakpoint(),[i,n]=F.useState(!1),r=F.useRef(null),o="base"===a;return F.useEffect((()=>{function e(e){i&&r.current&&!r.current.contains(e.target)&&n(!1)}return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}}),[r,i]),F.createElement(u.Flex,{position:"relative",onClick:()=>n(!i),ref:r,style:{cursor:"pointer"},testId:"popover-icon"},F.createElement(m.AlertIcon,{ariaHidden:!0,variation:"info"}),i&&F.createElement(F.Fragment,null,F.createElement(u.Flex,{position:"absolute",top:26,left:3,style:{zIndex:3,borderStyle:"solid",borderWidth:"0 9px 9px 9px",borderColor:`transparent transparent ${t.colors.background.primary} transparent`}}),F.createElement(u.Flex,{position:"absolute",top:24,left:2,style:{zIndex:2,borderStyle:"solid",borderWidth:"0 10px 10px 10px",borderColor:`transparent transparent ${t.colors.border.secondary} transparent`}}),F.createElement(u.Flex,{position:"absolute",backgroundColor:`${t.colors.background.primary}`,color:`${t.colors.font.primary}`,direction:"row",fontSize:t.fontSizes.xs,padding:t.space.small,top:33,minWidth:240,left:o?-190:-108,border:`1px solid ${t.colors.border.secondary}`,borderRadius:2,"data-testid":"popover-text"},e)))};Se.displayName="LivenessIconWithPopover";const Fe=({headingText:e,bodyText:t})=>S.default.createElement(u.View,{flex:"1"},S.default.createElement(u.View,{color:"font.primary",fontWeight:"bold"},e),S.default.createElement(u.View,{color:"font.primary"},t)),Re=({headingText:e,bodyText:t,infoText:a})=>S.default.createElement(u.Flex,{className:u.ComponentClassNames.Alert,color:"orange.80",backgroundColor:"orange.20",alignItems:"center"},S.default.createElement(u.View,{flex:"1"},S.default.createElement(u.View,{className:u.ComponentClassNames.AlertHeading},e),S.default.createElement(u.View,{className:u.ComponentClassNames.AlertBody},t)),S.default.createElement(Se,null,a)),ye=({headingText:e,goodFitCaptionText:t,goodFitAltText:a,tooFarCaptionText:i,tooFarAltText:n,steps:r})=>S.default.createElement(u.Flex,{direction:"column"},S.default.createElement(u.Text,{color:"font.primary",fontWeight:"bold"},e),S.default.createElement(u.Flex,{className:se.Figures},S.default.createElement(Te,{variation:"success",caption:t},S.default.createElement(Ce,{title:a})),S.default.createElement(Te,{variation:"error",caption:i},S.default.createElement(xe,{title:n}))),S.default.createElement(u.Flex,{as:"ol",className:se.InstructionList},r.map(((e,t)=>S.default.createElement(u.Flex,{as:"li",key:t+1},S.default.createElement(u.Text,{as:"span","aria-hidden":"true"},t+1,"."),S.default.createElement(u.Text,{as:"span"},e)))))),Me="liveness-detector-start";function Ae(e){const{beginLivenessCheck:t,components:a,instructionDisplayText:i}=e;return F.createElement(u.Card,{className:Me,"data-testid":Me},F.createElement(u.Flex,{direction:"column"},(null==a?void 0:a.Header)?F.createElement(a.Header,null):F.createElement(Fe,{headingText:i.instructionsHeaderHeadingText,bodyText:i.instructionsHeaderBodyText}),(null==a?void 0:a.PhotosensitiveWarning)?F.createElement(a.PhotosensitiveWarning,null):F.createElement(Re,{headingText:i.photosensitivyWarningHeadingText,bodyText:i.photosensitivyWarningBodyText,infoText:i.photosensitivyWarningInfoText}),(null==a?void 0:a.Instructions)?F.createElement(a.Instructions,null):F.createElement(ye,{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(u.Flex,{justifyContent:"center"},F.createElement(u.Button,{variation:"primary",type:"button",onClick:t},i.instructionsBeginCheckText))))}const we={timeoutHeaderText:"Time out",timeoutMessageText:"Face didn't fill oval within time limit. Try again and completely fill oval with face within 7 seconds.",faceDistanceHeaderText:"Check failed during countdown",faceDistanceMessageText:"Avoid moving closer during countdown and ensure only one face is in front of camera.",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"},De=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, fill the oval with your face within 7 seconds.",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),_e=({errorState:e,overrideErrorDisplayText:t})=>{const a=Object.assign(Object.assign({},we),t);return e===x.CAMERA_ACCESS_ERROR||e===x.CAMERA_FRAMERATE_ERROR||e===x.MOBILE_LANDSCAPE_ERROR?null:(e=>{const{error:t,displayText:a}=e,{timeoutHeaderText:i,timeoutMessageText:n,faceDistanceHeaderText:r,faceDistanceMessageText:o,clientHeaderText:s,clientMessageText:c,serverHeaderText:l,serverMessageText:d}=a;let h,f;switch(t){case x.TIMEOUT:h=i,f=n;break;case x.FACE_DISTANCE_ERROR:h=r,f=o;break;case x.RUNTIME_ERROR:h=s,f=c;break;case x.SERVER_ERROR:default:h=l,f=d}return S.default.createElement(S.default.Fragment,null,S.default.createElement(u.Flex,{gap:"xs",alignItems:"center",justifyContent:"center",color:"font.error"},S.default.createElement(m.AlertIcon,{ariaHidden:!0,variation:"error"}),S.default.createElement(u.Text,{fontWeight:"bold"},h)),f)})({error:e,displayText:a})},Ie=e=>{const{children:t,onRetry:a,displayText:i}=e,n=Object.assign(Object.assign({},we),i),{tryAgainText:r}=n;return S.default.createElement(de,{backgroundColor:"overlay.40"},S.default.createElement(le,null,t,S.default.createElement(u.Flex,{justifyContent:"center"},S.default.createElement(u.Button,{variation:"primary",type:"button",onClick:a},r))))},Oe=e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoConstraints},be=e=>{var t;return null===(t=e.context.videoAssociatedParams)||void 0===t?void 0:t.videoMediaStream},ke=e=>e.context.faceMatchAssociatedParams.faceMatchPercentage,Pe=e=>e.context.faceMatchAssociatedParams.faceMatchState,Le=S.default.createElement(u.Loader,{size:"large",className:se.Loader,"data-testid":"centered-loader"}),Ne=t=>{const{isMobileScreen:a,isRecordingStopped:i,streamDisplayText:n,hintDisplayText:r,errorDisplayText:o,components:s,testId:c}=t,{cancelLivenessCheckText:l,recordingIndicatorText:d}=n,{ErrorView:h=Ie}=null!=s?s:{},{tokens:m}=u.useTheme(),[g,v]=re(),p=oe(be),E=oe(Oe),T=oe(ke),x=oe(Pe),F=oe(he),R=[C.TOO_FAR,C.CANT_IDENTIFY,C.FACE_IDENTIFIED,C.MATCHED],{videoRef:y,videoWidth:M,videoHeight:D}=function(t,a){const i=a.height.ideal,n=a.width.ideal,r=e.useRef(null),[o,s]=e.useState(i),[c,l]=e.useState(n);return e.useEffect((()=>{if(t){f.isObject(r.current)&&(r.current.srcObject=t);const{height:e,width:a}=t.getTracks()[0].getSettings();s(e),l(a)}return()=>{t&&t.getTracks().forEach((e=>{t.removeTrack(e),e.stop()}))}}),[t]),{videoRef:r,videoHeight:o,videoWidth:c}}(p,E),_=e.useRef(null),I=e.useRef(null),[O,b]=e.useState(!1),[k,P]=e.useState(!1),L=g.matches("cameraCheck"),N=g.matches("notRecording"),B=g.matches("recording"),H=g.matches("checkSucceeded"),V=g.matches({recording:"flashFreshnessColors"}),[W,j]=e.useState(M),[z,q]=e.useState(D),[U,Y]=e.useState((()=>M&&D?M/D:0));S.default.useLayoutEffect((()=>{k&&v({type:"SET_DOM_AND_CAMERA_DETAILS",data:{videoEl:y.current,canvasEl:_.current,freshnessColorEl:I.current,isMobile:a}}),y.current&&(j(y.current.videoWidth),q(y.current.videoHeight),Y(y.current.videoWidth/y.current.videoHeight))}),[v,y,k,a]);return L?S.default.createElement(u.Flex,{height:D,width:"100%",position:"relative"},Le):S.default.createElement(u.Flex,{className:w.default(se.CameraModule,a&&`${se.CameraModule}--mobile`),"data-testid":c},!k&&Le,S.default.createElement(u.View,{as:"canvas",ref:I,className:se.FreshnessCanvas,hidden:!0}),S.default.createElement(u.View,{className:se.VideoAnchor,style:{aspectRatio:`${U}`}},S.default.createElement("video",{ref:y,muted:!0,autoPlay:!0,playsInline:!0,style:{transform:"scaleX(-1)"},width:W,height:z,onCanPlay:()=>{P(!0),b(!0)},"data-testid":"video",className:se.Video}),S.default.createElement(u.Flex,{className:w.default(se.OvalCanvas,a&&`${se.OvalCanvas}--mobile`,i&&se.FadeOut)},S.default.createElement(u.View,{as:"canvas",width:"100%",height:"100%",ref:_})),B&&S.default.createElement(u.View,{className:se.RecordingIconContainer},S.default.createElement(Ee,null,d)),!H&&S.default.createElement(u.View,{className:se.CancelContainer},S.default.createElement(ce,{ariaLabel:l})),O&&S.default.createElement(de,{anchorOrigin:{horizontal:"center",vertical:B&&!V?"start":"space-between"},className:se.InstructionOverlay},S.default.createElement(ve,{hintDisplayText:r}),F&&S.default.createElement(h,{onRetry:()=>{v({type:"CANCEL"})}},_e({errorState:F,overrideErrorDisplayText:o})),B&&!V&&R.includes(x)?S.default.createElement(pe,{percentage:T}):null,N&&S.default.createElement(u.View,{className:se.CountdownContainer,testId:"liveness-camera-countdown-timer"},S.default.createElement(A.default.CountdownCircleTimer,{isPlaying:N,size:85,strokeWidth:8,duration:3,rotation:"counterclockwise",colors:"#40aabf",trailColor:`${m.colors.background.primary}`,onComplete:()=>{v({type:"START_RECORDING"})}},(({remainingTime:e})=>S.default.createElement(u.Text,{fontSize:"xxxl",fontWeight:"bold"},e)))))))};function Be(){return/Android|iPhone|iPad/i.test(navigator.userAgent)||/Macintosh/i.test(navigator.userAgent)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>1}function He(){return window.matchMedia("(orientation: landscape)")}const Ve=e=>{const{onRetry:t,header:a,portraitMessage:i,landscapeMessage:n,tryAgainText:r}=e,[o,s]=F.useState(!0);return F.useLayoutEffect((()=>{const e=He();return s(e.matches),e.addEventListener("change",(e=>{s(e.matches)})),()=>{e.removeEventListener("change",(e=>s(e.matches)))}}),[]),F.createElement(u.Flex,{backgroundColor:"background.primary",direction:"column",textAlign:"center",alignItems:"center",justifyContent:"center",width:"100%",height:o?"auto":480},F.createElement(u.Text,{fontSize:"large",fontWeight:"bold"},a),F.createElement(u.Text,null,o?n:i),o?null:F.createElement(u.Flex,{justifyContent:"center"},F.createElement(u.Button,{variation:"primary",type:"button",onClick:t},r)))},We="liveness-detector-check",je=e=>e.context.errorState,ze=e=>e.context.isRecordingStopped,qe=({hintDisplayText:e,cameraDisplayText:t,streamDisplayText:a,errorDisplayText:i,components:n})=>{const[r,o]=re(),s=oe(je),c=oe(ze),l=r.matches("permissionDenied"),d=Be(),h=()=>{o({type:"RETRY_CAMERA_CHECK"})},{cameraMinSpecificationsHeadingText:m,cameraMinSpecificationsMessageText:f,cameraNotFoundHeadingText:g,cameraNotFoundMessageText:v,retryCameraPermissionsText:p}=t,{cancelLivenessCheckText:E}=a;F.useLayoutEffect((()=>{if(d){const e=e=>{e&&o({type:"MOBILE_LANDSCAPE_WARNING"})},t=He();return e(t.matches),t.addEventListener("change",(t=>{e(t.matches)})),()=>{t.removeEventListener("change",(t=>e(t.matches)))}}}),[d,o]);return F.createElement(u.Flex,{direction:"column",position:"relative",testId:We,className:We},(()=>{if(s===x.MOBILE_LANDSCAPE_ERROR){const e=Object.assign(Object.assign({},we),i),{landscapeHeaderText:t,portraitMessageText:a,landscapeMessageText:n,tryAgainText:r}=e;return F.createElement(u.Flex,{backgroundColor:"background.primary",direction:"column",textAlign:"center",alignItems:"center",justifyContent:"center",position:"absolute",width:"100%"},F.createElement(Ve,{header:t,portraitMessage:a,landscapeMessage:n,tryAgainText:r,onRetry:()=>{o({type:"CANCEL"})}}))}return l?F.createElement(u.Flex,{backgroundColor:"background.primary",direction:"column",textAlign:"center",alignItems:"center",justifyContent:"center",width:"100%",height:480},F.createElement(u.Text,{fontSize:"large",fontWeight:"bold"},s===x.CAMERA_FRAMERATE_ERROR?m:g),F.createElement(u.Text,{maxWidth:300},s===x.CAMERA_FRAMERATE_ERROR?f:v),F.createElement(u.Button,{variation:"primary",type:"button",onClick:h},p),F.createElement(u.View,{position:"absolute",top:"medium",right:"medium"},F.createElement(ce,{ariaLabel:E}))):F.createElement(Ne,{isMobileScreen:d,isRecordingStopped:c,streamDisplayText:a,hintDisplayText:e,errorDisplayText:i,components:n})})())};const Ue="liveness-detector";exports.FaceLivenessDetector=function(e){const{disableInstructionScreen:a=!1,components:i,config:n,displayText:r}=e,o=F.useRef(null),{hintDisplayText:s,cameraDisplayText:c,instructionDisplayText:l,streamDisplayText:d,errorDisplayText:h}=function(e){const t=Object.assign(Object.assign({},De),e),{instructionsHeaderHeadingText:a,instructionsHeaderBodyText:i,instructionsBeginCheckText:n,photosensitivyWarningHeadingText:r,photosensitivyWarningBodyText:o,photosensitivyWarningInfoText:s,instructionListHeadingText:c,goodFitCaptionText:l,goodFitAltText:d,tooFarCaptionText:h,tooFarAltText:u,instructionListStepOneText:m,instructionListStepTwoText:f,instructionListStepThreeText:g,instructionListStepFourText:v,cameraMinSpecificationsHeadingText:p,cameraMinSpecificationsMessageText:E,cameraNotFoundHeadingText:T,cameraNotFoundMessageText:C,retryCameraPermissionsText:x,cancelLivenessCheckText:S,recordingIndicatorText:F,hintMoveFaceFrontOfCameraText:R,hintTooManyFacesText:y,hintFaceDetectedText:M,hintCanNotIdentifyText:A,hintTooCloseText:w,hintTooFarText:D,hintHoldFacePositionCountdownText:_,hintConnectingText:I,hintVerifyingText:O,hintIlluminationTooBrightText:b,hintIlluminationTooDarkText:k,hintIlluminationNormalText:P,hintHoldFaceForFreshnessText:L,timeoutHeaderText:N,timeoutMessageText:B,faceDistanceHeaderText:H,faceDistanceMessageText:V,clientHeaderText:W,clientMessageText:j,serverHeaderText:z,serverMessageText:q,landscapeHeaderText:U,landscapeMessageText:Y,portraitMessageText:$,tryAgainText:G}=t;return{hintDisplayText:{hintMoveFaceFrontOfCameraText:R,hintTooManyFacesText:y,hintFaceDetectedText:M,hintCanNotIdentifyText:A,hintTooCloseText:w,hintTooFarText:D,hintHoldFacePositionCountdownText:_,hintConnectingText:I,hintVerifyingText:O,hintIlluminationTooBrightText:b,hintIlluminationTooDarkText:k,hintIlluminationNormalText:P,hintHoldFaceForFreshnessText:L},cameraDisplayText:{cameraMinSpecificationsHeadingText:p,cameraMinSpecificationsMessageText:E,cameraNotFoundHeadingText:T,cameraNotFoundMessageText:C,retryCameraPermissionsText:x},instructionDisplayText:{instructionsHeaderHeadingText:a,instructionsHeaderBodyText:i,instructionsBeginCheckText:n,photosensitivyWarningHeadingText:r,photosensitivyWarningBodyText:o,photosensitivyWarningInfoText:s,instructionListHeadingText:c,goodFitCaptionText:l,goodFitAltText:d,tooFarCaptionText:h,tooFarAltText:u,instructionListStepOneText:m,instructionListStepTwoText:f,instructionListStepThreeText:g,instructionListStepFourText:v},streamDisplayText:{cancelLivenessCheckText:S,recordingIndicatorText:F},errorDisplayText:{timeoutHeaderText:N,timeoutMessageText:B,faceDistanceHeaderText:H,faceDistanceMessageText:V,clientHeaderText:W,clientMessageText:j,serverHeaderText:z,serverMessageText:q,landscapeHeaderText:U,landscapeMessageText:Y,portraitMessageText:$,tryAgainText:G}}}(r),m=t.useInterpret(ee,{devTools:"development"===process.env.NODE_ENV,context:{componentProps:Object.assign(Object.assign({},e),{config:null!=n?n:{}})}}),[f,g]=t.useActor(m),v=f.matches("start")||f.matches("userCancel"),p=F.useCallback((()=>{g({type:"BEGIN",data:{videoConstraints:{width:{min:320,ideal:640},height:{min:240,ideal:480},frameRate:{min:15,ideal:30,max:30},facingMode:"user"}}})}),[g]);return F.useLayoutEffect((()=>{a&&v&&p()}),[p,a,v]),F.createElement(u.View,{className:Ue,testId:Ue},F.createElement(ie,{componentProps:e,service:m},F.createElement(u.Flex,{direction:"column",ref:o},v?F.createElement(Ae,{beginLivenessCheck:p,components:i,instructionDisplayText:l}):F.createElement(qe,{hintDisplayText:s,cameraDisplayText:c,streamDisplayText:d,errorDisplayText:h,components:i}))))};
@@ -1 +1 @@
1
- export declare const VERSION = "1.0.1";
1
+ export declare const VERSION = "1.0.2";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@aws-amplify/ui-react-liveness",
3
3
  "private": false,
4
- "version": "1.0.1",
4
+ "version": "1.0.2",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/esm/index.mjs",
7
7
  "exports": {
@@ -61,6 +61,7 @@
61
61
  "classnames": "2.3.1",
62
62
  "nanoid": "3.1.31",
63
63
  "react-countdown-circle-timer": "^2.5.4",
64
+ "tslib": "2.4.1",
64
65
  "xstate": "^4.33.6"
65
66
  },
66
67
  "devDependencies": {