@idmission/websdk-core 0.1.0-rc.1

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.
Files changed (416) hide show
  1. package/README.md +66 -0
  2. package/dist/attestation/attestationState.d.ts +24 -0
  3. package/dist/attestation/attestationState.d.ts.map +1 -0
  4. package/dist/attestation/attestationState.js +57 -0
  5. package/dist/attestation/clientAttestation.d.ts +40 -0
  6. package/dist/attestation/clientAttestation.d.ts.map +1 -0
  7. package/dist/attestation/clientAttestation.js +19 -0
  8. package/dist/attestation/collectClientAttestation.d.ts +10 -0
  9. package/dist/attestation/collectClientAttestation.d.ts.map +1 -0
  10. package/dist/attestation/collectClientAttestation.js +18 -0
  11. package/dist/attestation/index.d.ts +5 -0
  12. package/dist/attestation/index.d.ts.map +1 -0
  13. package/dist/attestation/index.js +4 -0
  14. package/dist/attestation/nativeAttestationBridge.d.ts +3 -0
  15. package/dist/attestation/nativeAttestationBridge.d.ts.map +1 -0
  16. package/dist/attestation/nativeAttestationBridge.js +38 -0
  17. package/dist/barcode/AAMVAParser.d.ts +77 -0
  18. package/dist/barcode/AAMVAParser.d.ts.map +1 -0
  19. package/dist/barcode/AAMVAParser.js +422 -0
  20. package/dist/barcode/NativeBarcodeDecoder.d.ts +157 -0
  21. package/dist/barcode/NativeBarcodeDecoder.d.ts.map +1 -0
  22. package/dist/barcode/NativeBarcodeDecoder.js +832 -0
  23. package/dist/barcode/Parse.d.ts +6 -0
  24. package/dist/barcode/Parse.d.ts.map +1 -0
  25. package/dist/barcode/Parse.js +148 -0
  26. package/dist/barcode/decodeSummary.d.ts +45 -0
  27. package/dist/barcode/decodeSummary.d.ts.map +1 -0
  28. package/dist/barcode/decodeSummary.js +23 -0
  29. package/dist/barcode/index.d.ts +5 -0
  30. package/dist/barcode/index.d.ts.map +1 -0
  31. package/dist/barcode/index.js +4 -0
  32. package/dist/camera/Camera.d.ts +37 -0
  33. package/dist/camera/Camera.d.ts.map +1 -0
  34. package/dist/camera/Camera.js +453 -0
  35. package/dist/camera/acquireCamera.d.ts +29 -0
  36. package/dist/camera/acquireCamera.d.ts.map +1 -0
  37. package/dist/camera/acquireCamera.js +224 -0
  38. package/dist/camera/cameraSignals.d.ts +23 -0
  39. package/dist/camera/cameraSignals.d.ts.map +1 -0
  40. package/dist/camera/cameraSignals.js +32 -0
  41. package/dist/camera/getUserMediaIntegrity.d.ts +72 -0
  42. package/dist/camera/getUserMediaIntegrity.d.ts.map +1 -0
  43. package/dist/camera/getUserMediaIntegrity.js +256 -0
  44. package/dist/camera/index.d.ts +6 -0
  45. package/dist/camera/index.d.ts.map +1 -0
  46. package/dist/camera/index.js +5 -0
  47. package/dist/camera/isVirtualCamera.d.ts +10 -0
  48. package/dist/camera/isVirtualCamera.d.ts.map +1 -0
  49. package/dist/camera/isVirtualCamera.js +11 -0
  50. package/dist/client/IdmissionClient.d.ts +151 -0
  51. package/dist/client/IdmissionClient.d.ts.map +1 -0
  52. package/dist/client/IdmissionClient.js +638 -0
  53. package/dist/client/additionalDocument.d.ts +14 -0
  54. package/dist/client/additionalDocument.d.ts.map +1 -0
  55. package/dist/client/additionalDocument.js +24 -0
  56. package/dist/client/artifacts.d.ts +146 -0
  57. package/dist/client/artifacts.d.ts.map +1 -0
  58. package/dist/client/artifacts.js +1 -0
  59. package/dist/client/blobToB64.d.ts +2 -0
  60. package/dist/client/blobToB64.d.ts.map +1 -0
  61. package/dist/client/blobToB64.js +17 -0
  62. package/dist/client/endpoints.d.ts +7 -0
  63. package/dist/client/endpoints.d.ts.map +1 -0
  64. package/dist/client/endpoints.js +59 -0
  65. package/dist/client/errors.d.ts +20 -0
  66. package/dist/client/errors.d.ts.map +1 -0
  67. package/dist/client/errors.js +45 -0
  68. package/dist/client/index.d.ts +23 -0
  69. package/dist/client/index.d.ts.map +1 -0
  70. package/dist/client/index.js +38 -0
  71. package/dist/client/payload.d.ts +36 -0
  72. package/dist/client/payload.d.ts.map +1 -0
  73. package/dist/client/payload.js +397 -0
  74. package/dist/client/sessionMachine.d.ts +26 -0
  75. package/dist/client/sessionMachine.d.ts.map +1 -0
  76. package/dist/client/sessionMachine.js +23 -0
  77. package/dist/client/submissionMetadata.d.ts +31 -0
  78. package/dist/client/submissionMetadata.d.ts.map +1 -0
  79. package/dist/client/submissionMetadata.js +90 -0
  80. package/dist/client/timings.d.ts +49 -0
  81. package/dist/client/timings.d.ts.map +1 -0
  82. package/dist/client/timings.js +32 -0
  83. package/dist/client/types.d.ts +305 -0
  84. package/dist/client/types.d.ts.map +1 -0
  85. package/dist/client/types.js +18 -0
  86. package/dist/client/upload.d.ts +60 -0
  87. package/dist/client/upload.d.ts.map +1 -0
  88. package/dist/client/upload.js +313 -0
  89. package/dist/client/uploadedDocument.d.ts +7 -0
  90. package/dist/client/uploadedDocument.d.ts.map +1 -0
  91. package/dist/client/uploadedDocument.js +4 -0
  92. package/dist/client/urls.d.ts +30 -0
  93. package/dist/client/urls.d.ts.map +1 -0
  94. package/dist/client/urls.js +73 -0
  95. package/dist/client/validateSession.d.ts +7 -0
  96. package/dist/client/validateSession.d.ts.map +1 -0
  97. package/dist/client/validateSession.js +63 -0
  98. package/dist/config/cdn.d.ts +2 -0
  99. package/dist/config/cdn.d.ts.map +1 -0
  100. package/dist/config/cdn.js +1 -0
  101. package/dist/diagnostics/buffer.d.ts +8 -0
  102. package/dist/diagnostics/buffer.d.ts.map +1 -0
  103. package/dist/diagnostics/buffer.js +25 -0
  104. package/dist/diagnostics/envCapability.d.ts +3 -0
  105. package/dist/diagnostics/envCapability.d.ts.map +1 -0
  106. package/dist/diagnostics/envCapability.js +40 -0
  107. package/dist/diagnostics/floodControl.d.ts +6 -0
  108. package/dist/diagnostics/floodControl.d.ts.map +1 -0
  109. package/dist/diagnostics/floodControl.js +29 -0
  110. package/dist/diagnostics/index.d.ts +8 -0
  111. package/dist/diagnostics/index.d.ts.map +1 -0
  112. package/dist/diagnostics/index.js +17 -0
  113. package/dist/diagnostics/install.d.ts +20 -0
  114. package/dist/diagnostics/install.d.ts.map +1 -0
  115. package/dist/diagnostics/install.js +159 -0
  116. package/dist/diagnostics/redaction.d.ts +7 -0
  117. package/dist/diagnostics/redaction.d.ts.map +1 -0
  118. package/dist/diagnostics/redaction.js +73 -0
  119. package/dist/diagnostics/transport.d.ts +15 -0
  120. package/dist/diagnostics/transport.d.ts.map +1 -0
  121. package/dist/diagnostics/transport.js +35 -0
  122. package/dist/diagnostics/types.d.ts +59 -0
  123. package/dist/diagnostics/types.d.ts.map +1 -0
  124. package/dist/diagnostics/types.js +1 -0
  125. package/dist/documentCapture/controller.d.ts +35 -0
  126. package/dist/documentCapture/controller.d.ts.map +1 -0
  127. package/dist/documentCapture/controller.js +254 -0
  128. package/dist/documentCapture/index.d.ts +4 -0
  129. package/dist/documentCapture/index.d.ts.map +1 -0
  130. package/dist/documentCapture/index.js +8 -0
  131. package/dist/documentCapture/reducer.d.ts +31 -0
  132. package/dist/documentCapture/reducer.d.ts.map +1 -0
  133. package/dist/documentCapture/reducer.js +87 -0
  134. package/dist/documentCapture/state.d.ts +49 -0
  135. package/dist/documentCapture/state.d.ts.map +1 -0
  136. package/dist/documentCapture/state.js +36 -0
  137. package/dist/idCapture/controller.d.ts +228 -0
  138. package/dist/idCapture/controller.d.ts.map +1 -0
  139. package/dist/idCapture/controller.js +1453 -0
  140. package/dist/idCapture/errors.d.ts +36 -0
  141. package/dist/idCapture/errors.d.ts.map +1 -0
  142. package/dist/idCapture/errors.js +18 -0
  143. package/dist/idCapture/guidance.d.ts +80 -0
  144. package/dist/idCapture/guidance.d.ts.map +1 -0
  145. package/dist/idCapture/guidance.js +143 -0
  146. package/dist/idCapture/index.d.ts +22 -0
  147. package/dist/idCapture/index.d.ts.map +1 -0
  148. package/dist/idCapture/index.js +46 -0
  149. package/dist/idCapture/phase.d.ts +10 -0
  150. package/dist/idCapture/phase.d.ts.map +1 -0
  151. package/dist/idCapture/phase.js +28 -0
  152. package/dist/idCapture/pipeline.d.ts +176 -0
  153. package/dist/idCapture/pipeline.d.ts.map +1 -0
  154. package/dist/idCapture/pipeline.js +1028 -0
  155. package/dist/idCapture/reducer.d.ts +3 -0
  156. package/dist/idCapture/reducer.d.ts.map +1 -0
  157. package/dist/idCapture/reducer.js +661 -0
  158. package/dist/idCapture/requirements.d.ts +10 -0
  159. package/dist/idCapture/requirements.d.ts.map +1 -0
  160. package/dist/idCapture/requirements.js +43 -0
  161. package/dist/idCapture/stabilizer.d.ts +2 -0
  162. package/dist/idCapture/stabilizer.d.ts.map +1 -0
  163. package/dist/idCapture/stabilizer.js +4 -0
  164. package/dist/idCapture/state.d.ts +426 -0
  165. package/dist/idCapture/state.d.ts.map +1 -0
  166. package/dist/idCapture/state.js +91 -0
  167. package/dist/idCapture/submit.d.ts +33 -0
  168. package/dist/idCapture/submit.d.ts.map +1 -0
  169. package/dist/idCapture/submit.js +105 -0
  170. package/dist/idCapture/types.d.ts +20 -0
  171. package/dist/idCapture/types.d.ts.map +1 -0
  172. package/dist/idCapture/types.js +12 -0
  173. package/dist/index.d.ts +6 -0
  174. package/dist/index.d.ts.map +1 -0
  175. package/dist/index.js +5 -0
  176. package/dist/liveness/challengeGeometry.d.ts +66 -0
  177. package/dist/liveness/challengeGeometry.d.ts.map +1 -0
  178. package/dist/liveness/challengeGeometry.js +226 -0
  179. package/dist/liveness/challengeSequence.d.ts +49 -0
  180. package/dist/liveness/challengeSequence.d.ts.map +1 -0
  181. package/dist/liveness/challengeSequence.js +71 -0
  182. package/dist/liveness/index.d.ts +4 -0
  183. package/dist/liveness/index.d.ts.map +1 -0
  184. package/dist/liveness/index.js +3 -0
  185. package/dist/liveness/livenessResult.d.ts +11 -0
  186. package/dist/liveness/livenessResult.d.ts.map +1 -0
  187. package/dist/liveness/livenessResult.js +16 -0
  188. package/dist/models/BarcodeReadability.d.ts +36 -0
  189. package/dist/models/BarcodeReadability.d.ts.map +1 -0
  190. package/dist/models/BarcodeReadability.js +71 -0
  191. package/dist/models/CapabilityProbing.d.ts +25 -0
  192. package/dist/models/CapabilityProbing.d.ts.map +1 -0
  193. package/dist/models/CapabilityProbing.js +172 -0
  194. package/dist/models/DocumentDetection.d.ts +96 -0
  195. package/dist/models/DocumentDetection.d.ts.map +1 -0
  196. package/dist/models/DocumentDetection.js +257 -0
  197. package/dist/models/FaceDetection.d.ts +21 -0
  198. package/dist/models/FaceDetection.d.ts.map +1 -0
  199. package/dist/models/FaceDetection.js +4 -0
  200. package/dist/models/Focus.d.ts +36 -0
  201. package/dist/models/Focus.d.ts.map +1 -0
  202. package/dist/models/Focus.js +69 -0
  203. package/dist/models/FrameLoop.d.ts +13 -0
  204. package/dist/models/FrameLoop.d.ts.map +1 -0
  205. package/dist/models/FrameLoop.js +56 -0
  206. package/dist/models/VisionRuntime.d.ts +18 -0
  207. package/dist/models/VisionRuntime.d.ts.map +1 -0
  208. package/dist/models/VisionRuntime.js +158 -0
  209. package/dist/models/defaults/BarcodeReadability.d.ts +3 -0
  210. package/dist/models/defaults/BarcodeReadability.d.ts.map +1 -0
  211. package/dist/models/defaults/BarcodeReadability.js +3 -0
  212. package/dist/models/defaults/BarcodeReadabilityLiteRT.d.ts +3 -0
  213. package/dist/models/defaults/BarcodeReadabilityLiteRT.d.ts.map +1 -0
  214. package/dist/models/defaults/BarcodeReadabilityLiteRT.js +3 -0
  215. package/dist/models/defaults/DocumentDetector.d.ts +3 -0
  216. package/dist/models/defaults/DocumentDetector.d.ts.map +1 -0
  217. package/dist/models/defaults/DocumentDetector.js +3 -0
  218. package/dist/models/defaults/DocumentDetectorLiteRT.d.ts +3 -0
  219. package/dist/models/defaults/DocumentDetectorLiteRT.d.ts.map +1 -0
  220. package/dist/models/defaults/DocumentDetectorLiteRT.js +3 -0
  221. package/dist/models/defaults/FaceDetector.d.ts +3 -0
  222. package/dist/models/defaults/FaceDetector.d.ts.map +1 -0
  223. package/dist/models/defaults/FaceDetector.js +3 -0
  224. package/dist/models/defaults/FaceLandmarker.d.ts +3 -0
  225. package/dist/models/defaults/FaceLandmarker.d.ts.map +1 -0
  226. package/dist/models/defaults/FaceLandmarker.js +8 -0
  227. package/dist/models/defaults/FaceLandmarkerLiteRT.d.ts +3 -0
  228. package/dist/models/defaults/FaceLandmarkerLiteRT.d.ts.map +1 -0
  229. package/dist/models/defaults/FaceLandmarkerLiteRT.js +3 -0
  230. package/dist/models/defaults/Focus.d.ts +3 -0
  231. package/dist/models/defaults/Focus.d.ts.map +1 -0
  232. package/dist/models/defaults/Focus.js +3 -0
  233. package/dist/models/defaults/FocusLiteRT.d.ts +3 -0
  234. package/dist/models/defaults/FocusLiteRT.d.ts.map +1 -0
  235. package/dist/models/defaults/FocusLiteRT.js +3 -0
  236. package/dist/models/defaults/index.d.ts +31 -0
  237. package/dist/models/defaults/index.d.ts.map +1 -0
  238. package/dist/models/defaults/index.js +38 -0
  239. package/dist/models/helpers.d.ts +25 -0
  240. package/dist/models/helpers.d.ts.map +1 -0
  241. package/dist/models/helpers.js +98 -0
  242. package/dist/models/index.d.ts +15 -0
  243. package/dist/models/index.d.ts.map +1 -0
  244. package/dist/models/index.js +14 -0
  245. package/dist/models/modelLifecycle.d.ts +26 -0
  246. package/dist/models/modelLifecycle.d.ts.map +1 -0
  247. package/dist/models/modelLifecycle.js +137 -0
  248. package/dist/models/occlusion.d.ts +20 -0
  249. package/dist/models/occlusion.d.ts.map +1 -0
  250. package/dist/models/occlusion.js +109 -0
  251. package/dist/models/passportBooklet.d.ts +34 -0
  252. package/dist/models/passportBooklet.d.ts.map +1 -0
  253. package/dist/models/passportBooklet.js +152 -0
  254. package/dist/models/preloadModels.d.ts +42 -0
  255. package/dist/models/preloadModels.d.ts.map +1 -0
  256. package/dist/models/preloadModels.js +204 -0
  257. package/dist/models/providers/litert/BarcodeReadability.d.ts +11 -0
  258. package/dist/models/providers/litert/BarcodeReadability.d.ts.map +1 -0
  259. package/dist/models/providers/litert/BarcodeReadability.js +135 -0
  260. package/dist/models/providers/litert/CapabilityProbe.d.ts +3 -0
  261. package/dist/models/providers/litert/CapabilityProbe.d.ts.map +1 -0
  262. package/dist/models/providers/litert/CapabilityProbe.js +44 -0
  263. package/dist/models/providers/litert/DocumentDetection.d.ts +18 -0
  264. package/dist/models/providers/litert/DocumentDetection.d.ts.map +1 -0
  265. package/dist/models/providers/litert/DocumentDetection.js +194 -0
  266. package/dist/models/providers/litert/FaceDetection.d.ts +11 -0
  267. package/dist/models/providers/litert/FaceDetection.d.ts.map +1 -0
  268. package/dist/models/providers/litert/FaceDetection.js +204 -0
  269. package/dist/models/providers/litert/FaceLandmarker.d.ts +11 -0
  270. package/dist/models/providers/litert/FaceLandmarker.d.ts.map +1 -0
  271. package/dist/models/providers/litert/FaceLandmarker.js +199 -0
  272. package/dist/models/providers/litert/Focus.d.ts +11 -0
  273. package/dist/models/providers/litert/Focus.d.ts.map +1 -0
  274. package/dist/models/providers/litert/Focus.js +141 -0
  275. package/dist/models/providers/litert/barcodeReadabilityPrePost.d.ts +6 -0
  276. package/dist/models/providers/litert/barcodeReadabilityPrePost.d.ts.map +1 -0
  277. package/dist/models/providers/litert/barcodeReadabilityPrePost.js +68 -0
  278. package/dist/models/providers/litert/blazeFacePrePost.d.ts +30 -0
  279. package/dist/models/providers/litert/blazeFacePrePost.d.ts.map +1 -0
  280. package/dist/models/providers/litert/blazeFacePrePost.js +206 -0
  281. package/dist/models/providers/litert/docDetectPrePost.d.ts +25 -0
  282. package/dist/models/providers/litert/docDetectPrePost.d.ts.map +1 -0
  283. package/dist/models/providers/litert/docDetectPrePost.js +197 -0
  284. package/dist/models/providers/litert/faceMeshPrePost.d.ts +23 -0
  285. package/dist/models/providers/litert/faceMeshPrePost.d.ts.map +1 -0
  286. package/dist/models/providers/litert/faceMeshPrePost.js +86 -0
  287. package/dist/models/providers/litert/focusPrePost.d.ts +6 -0
  288. package/dist/models/providers/litert/focusPrePost.d.ts.map +1 -0
  289. package/dist/models/providers/litert/focusPrePost.js +67 -0
  290. package/dist/models/providers/litert/runtime.d.ts +14 -0
  291. package/dist/models/providers/litert/runtime.d.ts.map +1 -0
  292. package/dist/models/providers/litert/runtime.js +83 -0
  293. package/dist/models/providers/mediapipe/BarcodeReadability.d.ts +11 -0
  294. package/dist/models/providers/mediapipe/BarcodeReadability.d.ts.map +1 -0
  295. package/dist/models/providers/mediapipe/BarcodeReadability.js +68 -0
  296. package/dist/models/providers/mediapipe/CapabilityProbe.d.ts +2 -0
  297. package/dist/models/providers/mediapipe/CapabilityProbe.d.ts.map +1 -0
  298. package/dist/models/providers/mediapipe/CapabilityProbe.js +14 -0
  299. package/dist/models/providers/mediapipe/DocumentDetection.d.ts +12 -0
  300. package/dist/models/providers/mediapipe/DocumentDetection.d.ts.map +1 -0
  301. package/dist/models/providers/mediapipe/DocumentDetection.js +90 -0
  302. package/dist/models/providers/mediapipe/FaceDetection.d.ts +11 -0
  303. package/dist/models/providers/mediapipe/FaceDetection.d.ts.map +1 -0
  304. package/dist/models/providers/mediapipe/FaceDetection.js +93 -0
  305. package/dist/models/providers/mediapipe/FaceLandmarker.d.ts +46 -0
  306. package/dist/models/providers/mediapipe/FaceLandmarker.d.ts.map +1 -0
  307. package/dist/models/providers/mediapipe/FaceLandmarker.js +166 -0
  308. package/dist/models/providers/mediapipe/Focus.d.ts +11 -0
  309. package/dist/models/providers/mediapipe/Focus.d.ts.map +1 -0
  310. package/dist/models/providers/mediapipe/Focus.js +51 -0
  311. package/dist/models/runtimeSelection.d.ts +5 -0
  312. package/dist/models/runtimeSelection.d.ts.map +1 -0
  313. package/dist/models/runtimeSelection.js +21 -0
  314. package/dist/selfieCapture/challengeRunner.d.ts +38 -0
  315. package/dist/selfieCapture/challengeRunner.d.ts.map +1 -0
  316. package/dist/selfieCapture/challengeRunner.js +181 -0
  317. package/dist/selfieCapture/controller.d.ts +166 -0
  318. package/dist/selfieCapture/controller.d.ts.map +1 -0
  319. package/dist/selfieCapture/controller.js +1253 -0
  320. package/dist/selfieCapture/faceTracking.d.ts +67 -0
  321. package/dist/selfieCapture/faceTracking.d.ts.map +1 -0
  322. package/dist/selfieCapture/faceTracking.js +158 -0
  323. package/dist/selfieCapture/guidance.d.ts +24 -0
  324. package/dist/selfieCapture/guidance.d.ts.map +1 -0
  325. package/dist/selfieCapture/guidance.js +41 -0
  326. package/dist/selfieCapture/index.d.ts +18 -0
  327. package/dist/selfieCapture/index.d.ts.map +1 -0
  328. package/dist/selfieCapture/index.js +11 -0
  329. package/dist/selfieCapture/lighting.d.ts +36 -0
  330. package/dist/selfieCapture/lighting.d.ts.map +1 -0
  331. package/dist/selfieCapture/lighting.js +95 -0
  332. package/dist/selfieCapture/livenessMachine.d.ts +66 -0
  333. package/dist/selfieCapture/livenessMachine.d.ts.map +1 -0
  334. package/dist/selfieCapture/livenessMachine.js +137 -0
  335. package/dist/selfieCapture/pipeline.d.ts +42 -0
  336. package/dist/selfieCapture/pipeline.d.ts.map +1 -0
  337. package/dist/selfieCapture/pipeline.js +282 -0
  338. package/dist/selfieCapture/reducer.d.ts +35 -0
  339. package/dist/selfieCapture/reducer.d.ts.map +1 -0
  340. package/dist/selfieCapture/reducer.js +143 -0
  341. package/dist/selfieCapture/state.d.ts +40 -0
  342. package/dist/selfieCapture/state.d.ts.map +1 -0
  343. package/dist/selfieCapture/state.js +36 -0
  344. package/dist/selfieCapture/testing/challengeFixtures.d.ts +43 -0
  345. package/dist/selfieCapture/testing/challengeFixtures.d.ts.map +1 -0
  346. package/dist/selfieCapture/testing/challengeFixtures.js +43 -0
  347. package/dist/signature/frameDecode.d.ts +48 -0
  348. package/dist/signature/frameDecode.d.ts.map +1 -0
  349. package/dist/signature/frameDecode.js +491 -0
  350. package/dist/signature/index.d.ts +5 -0
  351. package/dist/signature/index.d.ts.map +1 -0
  352. package/dist/signature/index.js +4 -0
  353. package/dist/signature/metadata.d.ts +63 -0
  354. package/dist/signature/metadata.d.ts.map +1 -0
  355. package/dist/signature/metadata.js +1 -0
  356. package/dist/signature/quality.d.ts +169 -0
  357. package/dist/signature/quality.d.ts.map +1 -0
  358. package/dist/signature/quality.js +186 -0
  359. package/dist/signature/signatureValidity.d.ts +149 -0
  360. package/dist/signature/signatureValidity.d.ts.map +1 -0
  361. package/dist/signature/signatureValidity.js +305 -0
  362. package/dist/signatureCapture/controller.d.ts +67 -0
  363. package/dist/signatureCapture/controller.d.ts.map +1 -0
  364. package/dist/signatureCapture/controller.js +534 -0
  365. package/dist/signatureCapture/guidance.d.ts +9 -0
  366. package/dist/signatureCapture/guidance.d.ts.map +1 -0
  367. package/dist/signatureCapture/guidance.js +7 -0
  368. package/dist/signatureCapture/index.d.ts +6 -0
  369. package/dist/signatureCapture/index.d.ts.map +1 -0
  370. package/dist/signatureCapture/index.js +5 -0
  371. package/dist/signatureCapture/pipeline.d.ts +111 -0
  372. package/dist/signatureCapture/pipeline.d.ts.map +1 -0
  373. package/dist/signatureCapture/pipeline.js +680 -0
  374. package/dist/signatureCapture/reducer.d.ts +42 -0
  375. package/dist/signatureCapture/reducer.d.ts.map +1 -0
  376. package/dist/signatureCapture/reducer.js +159 -0
  377. package/dist/signatureCapture/state.d.ts +92 -0
  378. package/dist/signatureCapture/state.d.ts.map +1 -0
  379. package/dist/signatureCapture/state.js +24 -0
  380. package/dist/utils/canvas.d.ts +4 -0
  381. package/dist/utils/canvas.d.ts.map +1 -0
  382. package/dist/utils/canvas.js +21 -0
  383. package/dist/utils/cropping.d.ts +8 -0
  384. package/dist/utils/cropping.d.ts.map +1 -0
  385. package/dist/utils/cropping.js +85 -0
  386. package/dist/utils/dataUrlToBase64.d.ts +7 -0
  387. package/dist/utils/dataUrlToBase64.d.ts.map +1 -0
  388. package/dist/utils/dataUrlToBase64.js +67 -0
  389. package/dist/utils/getFrameDimensions.d.ts +3 -0
  390. package/dist/utils/getFrameDimensions.d.ts.map +1 -0
  391. package/dist/utils/getFrameDimensions.js +12 -0
  392. package/dist/utils/isMobile.d.ts +3 -0
  393. package/dist/utils/isMobile.d.ts.map +1 -0
  394. package/dist/utils/isMobile.js +36 -0
  395. package/dist/utils/logger.d.ts +19 -0
  396. package/dist/utils/logger.d.ts.map +1 -0
  397. package/dist/utils/logger.js +25 -0
  398. package/dist/utils/platform.d.ts +4 -0
  399. package/dist/utils/platform.d.ts.map +1 -0
  400. package/dist/utils/platform.js +11 -0
  401. package/dist/utils/stabilizer.d.ts +26 -0
  402. package/dist/utils/stabilizer.d.ts.map +1 -0
  403. package/dist/utils/stabilizer.js +65 -0
  404. package/dist/version.d.ts +2 -0
  405. package/dist/version.d.ts.map +1 -0
  406. package/dist/version.js +1 -0
  407. package/dist/videoIdCapture/controller.d.ts +108 -0
  408. package/dist/videoIdCapture/controller.d.ts.map +1 -0
  409. package/dist/videoIdCapture/controller.js +833 -0
  410. package/dist/videoIdCapture/index.d.ts +5 -0
  411. package/dist/videoIdCapture/index.d.ts.map +1 -0
  412. package/dist/videoIdCapture/index.js +2 -0
  413. package/dist/videoIdCapture/state.d.ts +88 -0
  414. package/dist/videoIdCapture/state.d.ts.map +1 -0
  415. package/dist/videoIdCapture/state.js +67 -0
  416. package/package.json +111 -0
@@ -0,0 +1,1253 @@
1
+ // Vanilla-store selfie capture controller (iteration 4 plan 3). Mirrors
2
+ // idCapture/controller.ts's anatomy: io seam with receiver-strict binds
3
+ // (:251-273), colon-namespaced timer map (:404-428), cached-snapshot
4
+ // publish (:462-478), StrictMode-safe attach/detach (:1320-1515). Composes
5
+ // the pure selfieCapture modules, including (task 4) the liveness machine +
6
+ // challenge runner ported from sdk2's FaceLivenessCapture.tsx. One
7
+ // deliberate improvement over the idCapture controller: subscribe
8
+ // listeners are individually try/caught (a throwing listener must not break
9
+ // the frame loop or its siblings).
10
+ import { createStore } from 'zustand/vanilla';
11
+ import { acquireCamera, } from '../camera/acquireCamera';
12
+ import { CaptureAttachError } from '../idCapture/errors';
13
+ import { waitForVideoReady } from '../models/helpers';
14
+ import { createFrameLoop } from '../models/FrameLoop';
15
+ import { createRunningAvg, detectBrightnessAndContrast } from './lighting';
16
+ import { cropToShoulders } from '../utils/cropping';
17
+ import { createInitialSelfieCaptureState, } from './state';
18
+ import { reduceSelfieCapture } from './reducer';
19
+ import { isSatisfiedSelfieCode } from './guidance';
20
+ import { createSelfiePipeline, DEFAULT_SELFIE_DETECTOR, } from './pipeline';
21
+ import { createInitialLivenessMachineState, hasExceededLivenessFailureLimit, reduceLivenessMachine, LIVENESS_RESET_DELAY_MS, } from './livenessMachine';
22
+ import { createChallengeRunner, DEFAULT_CHALLENGE_COUNT, DEFAULT_RESPONSE_WINDOW_MS, } from './challengeRunner';
23
+ import { setLastChallengeResult, } from '../liveness/challengeSequence';
24
+ import { dataUrlToBase64Sync } from '../utils/dataUrlToBase64';
25
+ import { error, warn } from '../utils/logger';
26
+ // sdk2 SelfieGuidanceModelsProvider.tsx onPredictionMade's useThrottledCallback
27
+ // second argument (SelfieCapture.tsx:225 -- "locks to 60fps maximum").
28
+ export const DEFAULT_PREDICTION_THROTTLE_MS = 16;
29
+ // sdk2 SelfieCapture.tsx:254 (`setTimeout(doCapture, 100)` armed once
30
+ // prediction.faceReady flips true).
31
+ export const AUTO_CAPTURE_FIRE_DELAY_MS = 100;
32
+ // sdk2 SelfieCaptureWizard.tsx:115 (`initialCaptureDelayMs = 1000` prop
33
+ // default).
34
+ export const DEFAULT_INITIAL_CAPTURE_DELAY_MS = 1000;
35
+ // sdk2 FaceLivenessCapture challenge safety-tick cadence: the controller arms a
36
+ // coarse repeating tick so the challenge runner's event-evaluated deadlines
37
+ // (response window / settle fallback) fire even if camera frames stall.
38
+ export const CHALLENGE_TICK_MS = 250;
39
+ // sdk2 FaceLivenessCapture default `timeoutDurationMs` (the overall kick-out).
40
+ export const KICKOUT_TIMEOUT_MS = 15000;
41
+ // sdk2 useTimeout.ts:38 hardcoded `shouldWaitLonger` grace window: when the
42
+ // kickout fires while a liveness check is IN_PROGRESS, wait this long before
43
+ // denying (a slow backend must not boot a user mid-check).
44
+ export const KICKOUT_WAIT_LONGER_MS = 120000;
45
+ // Maps a CaptureAttachError onto the selfie flow's error shape. Mirrors
46
+ // idCapture/controller.ts's requestCamera pattern of storing the error's
47
+ // OWN code (err.captureError, not the wrapper) rather than collapsing every
48
+ // camera failure into 'CAPTURE_FAILED' -- adapted to selfie's error shape,
49
+ // which (unlike idCapture's bare CaptureError) also carries a `message`.
50
+ // Only the codes state.ts's SelfieCaptureFlowError additively widened for pass
51
+ // through verbatim; anything else falls back to the generic CAPTURE_FAILED
52
+ // bucket rather than growing the union further.
53
+ const PASSTHROUGH_CODES = [
54
+ 'CAMERA_UNAVAILABLE',
55
+ 'CAMERA_PERMISSION_DENIED',
56
+ // Passed through so a view can honour sdk2's tamper callbacks. It stays
57
+ // `recoverable: false` (acquireCamera's own verdict), so the error screen
58
+ // still offers an exit rather than a retry.
59
+ 'CAMERA_TAMPERING_SUSPECTED',
60
+ ];
61
+ function toSelfieCaptureError(err) {
62
+ const code = err.captureError.code;
63
+ return {
64
+ code: (PASSTHROUGH_CODES.indexOf(code) === -1
65
+ ? 'CAPTURE_FAILED'
66
+ : code),
67
+ message: err.message,
68
+ recoverable: err.captureError.recoverable,
69
+ };
70
+ }
71
+ export function createSelfieCaptureController(config = {}) {
72
+ // Receiver-strict io seam: setTimeout/clearTimeout are branded globals
73
+ // that throw Illegal invocation when invoked as methods of `io` unless
74
+ // pre-bound (idCapture controller.ts:251-273).
75
+ const io = {
76
+ now: config.io?.now ?? (() => new Date()),
77
+ setTimeout: config.io?.setTimeout ?? setTimeout.bind(globalThis),
78
+ clearTimeout: config.io?.clearTimeout ?? clearTimeout.bind(globalThis),
79
+ acquireCamera: config.io?.acquireCamera ?? acquireCamera,
80
+ createPipeline: config.io?.createPipeline ?? createSelfiePipeline,
81
+ createCanvas: config.io?.createCanvas ?? (() => document.createElement('canvas')),
82
+ createFrameLoop: config.io?.createFrameLoop ?? createFrameLoop,
83
+ };
84
+ // Challenge enable gate, sdk2 FaceLivenessCapture :684-698: the feature
85
+ // requires the face-landmarker detector (468-point mesh / named keypoints);
86
+ // a misconfig warns and proceeds without challenges — it must never block
87
+ // the user.
88
+ const detectorKind = config.detector ?? DEFAULT_SELFIE_DETECTOR;
89
+ if (config.liveness?.challenge?.enabled === true &&
90
+ detectorKind !== 'face-landmarker') {
91
+ warn("[selfieCapture] liveness.challenge.enabled requires detector='face-landmarker'; " +
92
+ `got '${detectorKind}'. Skipping challenge-response.`);
93
+ }
94
+ const challengeEnabled = config.liveness?.challenge?.enabled === true &&
95
+ detectorKind === 'face-landmarker';
96
+ const internal = createStore(() => ({
97
+ ...createInitialSelfieCaptureState({ thresholds: config.thresholds }),
98
+ camera: { ready: false, isRearFacing: false, accessRequested: false },
99
+ capturedAttempt: null,
100
+ capturedImageUrl: null,
101
+ liveness: config.liveness ? createInitialLivenessMachineState() : null,
102
+ challenge: null,
103
+ livenessTimedOut: false,
104
+ }));
105
+ function dispatch(event) {
106
+ internal.setState((s) => ({ ...s, ...reduceSelfieCapture(s, event) }));
107
+ }
108
+ // --- timers (idCapture pattern, colon-namespaced) ---
109
+ const timers = new Map();
110
+ function clearAllTimers() {
111
+ for (const handle of timers.values())
112
+ io.clearTimeout(handle);
113
+ timers.clear();
114
+ }
115
+ // Re-added by Task 3 (frame loop's 'capture:initialDelay'/'capture:fire'
116
+ // are the first callers) -- idCapture controller.ts:421-438, verbatim.
117
+ function armTimer(name, ms, fn) {
118
+ clearTimer(name);
119
+ timers.set(name, io.setTimeout(() => {
120
+ timers.delete(name);
121
+ fn();
122
+ }, ms));
123
+ }
124
+ function clearTimer(name) {
125
+ const handle = timers.get(name);
126
+ if (handle !== undefined) {
127
+ io.clearTimeout(handle);
128
+ timers.delete(name);
129
+ }
130
+ }
131
+ const listeners = new Set();
132
+ let snapshot = null;
133
+ // Liveness phase mapping (task 5's full public shape). Mirrors idCapture's
134
+ // derivePhase (idCapture/phase.ts): error always wins, computed here rather
135
+ // than stored via raw `phase: 'error'` setState writes -- requestCamera()'s
136
+ // and doAttach()'s catch blocks below only set `error` now (Task-2 review
137
+ // finding); this derivation is what turns that into the public 'error'
138
+ // phase, exactly like the reducer's own error-setting transitions
139
+ // (modelsProgressed/captureFailed, left as-is) already pair `error` with a
140
+ // literal `phase: 'error'` write of their own.
141
+ //
142
+ // Below the error check, when liveness is configured and the flow has left
143
+ // initializing/loading, the machine's requestState is the source of truth
144
+ // for phase (sdk2 FaceLivenessCapture's requestState ladder, ported
145
+ // verbatim onto the plain flow's phase union):
146
+ // CAPTURING | GUIDANCE_SATISFIED | CAPTURE_STARTED -> 'capturing'
147
+ // CHALLENGE -> 'challenge'
148
+ // CAPTURED -> 'processing'
149
+ // IN_PROGRESS -> 'checking'
150
+ // PASSED -> 'completed'
151
+ // FAILED -> 'failed'
152
+ // ERROR -> 'error'
153
+ // (FAILED maps to 'failed' unconditionally while the machine sits in that
154
+ // state; runLivenessEffects' reset-after-verdict timer is what moves the
155
+ // machine back to CAPTURING -- via a fresh capture attempt -- once the
156
+ // failure-limit check has run, so there is no separate "not yet exceeded"
157
+ // branch to encode here.)
158
+ function derivedPhase(s) {
159
+ if (s.error)
160
+ return 'error';
161
+ const machine = s.liveness;
162
+ if (!machine || s.phase === 'initializing' || s.phase === 'loading') {
163
+ return s.phase;
164
+ }
165
+ switch (machine.requestState) {
166
+ case 'CAPTURING':
167
+ case 'GUIDANCE_SATISFIED':
168
+ case 'CAPTURE_STARTED':
169
+ return 'capturing';
170
+ case 'CHALLENGE':
171
+ return 'challenge';
172
+ case 'CAPTURED':
173
+ return 'processing';
174
+ case 'IN_PROGRESS':
175
+ return 'checking';
176
+ case 'PASSED':
177
+ return 'completed';
178
+ case 'FAILED':
179
+ return 'failed';
180
+ case 'ERROR':
181
+ return 'error';
182
+ }
183
+ }
184
+ function toPublicState(s) {
185
+ return {
186
+ ...s,
187
+ phase: derivedPhase(s),
188
+ // Held guidance event (idCapture parity: controller.ts:461-465). The
189
+ // held CODE drives every consuming surface; `satisfied` is derived from
190
+ // it, never from a raw per-frame candidate.
191
+ guidance: {
192
+ code: s.guidance.displayed,
193
+ satisfied: isSatisfiedSelfieCode(s.guidance.displayed),
194
+ },
195
+ };
196
+ }
197
+ function publish() {
198
+ snapshot = toPublicState(internal.getState());
199
+ for (const cb of [...listeners]) {
200
+ try {
201
+ cb(snapshot);
202
+ }
203
+ catch {
204
+ // Deliberate divergence: a throwing listener must not break the
205
+ // frame loop or its sibling listeners.
206
+ }
207
+ }
208
+ }
209
+ internal.subscribe((next, prev) => {
210
+ if (attached)
211
+ runEffects(prev, next);
212
+ publish();
213
+ });
214
+ // sdk2 kickoutResetKey (:829-843): the overall kick-out countdown restarts
215
+ // whenever the key changes — constant -1 outside CHALLENGE, the challenge
216
+ // stepIndex inside — so a user completing instructions keeps earning a
217
+ // fresh window (and entering/leaving the challenge phase also restarts it),
218
+ // while non-challenge flows keep their single overall timeout.
219
+ function livenessKickoutKey(s) {
220
+ return s.liveness?.requestState === 'CHALLENGE'
221
+ ? (s.challenge?.stepIndex ?? 0)
222
+ : -1;
223
+ }
224
+ function runEffects(prev, next) {
225
+ if (config.liveness &&
226
+ livenessKickoutKey(next) !== livenessKickoutKey(prev)) {
227
+ armKickout();
228
+ }
229
+ }
230
+ // --- lifecycle ---
231
+ let active = false;
232
+ let attached = false;
233
+ let attaching = false;
234
+ // The attachGeneration the in-flight doAttach belongs to (see doAttach).
235
+ let attachingGeneration = -1;
236
+ let videoEl = null;
237
+ let cameraHandle = null;
238
+ let pipeline = null;
239
+ let pipelineLoaded = false;
240
+ // Edge-detects the model aggregate's transition into 'error' so the cause is
241
+ // logged once rather than on every progress tick.
242
+ let lastReportedLoadState = null;
243
+ // Attach-generation counter (mirrors idCapture/controller.ts's
244
+ // recaptureGeneration pattern): a plain `active` boolean can't distinguish
245
+ // "still the same session" from "detached, then reattached" -- attach()
246
+ // flips `active` back to true, so a slow in-flight runLivenessCheck from
247
+ // the OLD session could otherwise resolve after detach()+attach()+start()
248
+ // and dispatch its verdict (even onSuccess, with the previous attempt's
249
+ // image) into the NEW machine. Incremented on every detach(); captured by
250
+ // runLivenessCheck before its await and compared after.
251
+ let attachGeneration = 0;
252
+ // --- frame loop + capture (Task 3) ---
253
+ // Mirrors SelfieGuidanceModelsProvider's tick (:179-271) + SelfieCapture's
254
+ // dual-path prediction handler (:197-256) + SelfieCaptureWizard's clock/crop
255
+ // chain (:151-209), fused into one controller-owned loop instead of split
256
+ // across a React provider + consumer.
257
+ let frameLoop = null;
258
+ let trackingOnly = false;
259
+ let throttleMs = config.throttleMs;
260
+ let initialDelayOver = false;
261
+ let busy = false;
262
+ let operationStartedAt = null;
263
+ let captureStartedAt = null;
264
+ let lastHandledAt = 0;
265
+ const mirrorCanvas = io.createCanvas();
266
+ const captureCanvas = io.createCanvas();
267
+ const rawCanvas = io.createCanvas();
268
+ const cropCanvas = io.createCanvas();
269
+ const resizeCanvas = io.createCanvas();
270
+ const lighting = createRunningAvg(5);
271
+ // Live path (task 4's challenge feed): fed the raw per-frame face on EVERY
272
+ // tick, independent of the gated reducer path below -- sdk2 wires
273
+ // onPrediction(prediction) but the liveness runner only reads
274
+ // prediction.face, so passing faces[0] ?? null is observably equivalent
275
+ // (SelfieCapture.tsx:204, FaceLivenessCapture.tsx:709-717). Face present ->
276
+ // 'face' event (mesh + keypoints for the gesture detectors); face lost ->
277
+ // 'faceLost' (the runner banks its pausable response-window clock).
278
+ const onLivePrediction = (face, atMs) => {
279
+ if (internal.getState().liveness?.requestState !== 'CHALLENGE')
280
+ return;
281
+ const runner = challengeRunner;
282
+ if (!runner)
283
+ return;
284
+ handleRunnerSnapshot(face
285
+ ? runner.step({
286
+ type: 'face',
287
+ frame: { mesh: face.meshLandmarks, keypoints: face.keypoints },
288
+ atMs,
289
+ })
290
+ : runner.step({ type: 'faceLost', atMs }));
291
+ };
292
+ // Liveness mode narrows the forwarding gate to the machine states where
293
+ // capture may proceed (sdk2 shouldCapture, FaceLivenessCapture.tsx:996-1003):
294
+ // CAPTURING always; GUIDANCE_SATISFIED only on the challenge path (after a
295
+ // passed challenge the flow re-enters capture from GUIDANCE_SATISFIED on a
296
+ // remounted SelfieCapture in sdk2; here the same gate re-opens forwarding).
297
+ function shouldForwardToReducer() {
298
+ const s = internal.getState();
299
+ if (trackingOnly)
300
+ return true;
301
+ if (s.phase !== 'capturing' || !initialDelayOver || busy)
302
+ return false;
303
+ const machine = s.liveness;
304
+ if (!machine)
305
+ return true;
306
+ return (machine.requestState === 'CAPTURING' ||
307
+ (challengeEnabled && machine.requestState === 'GUIDANCE_SATISFIED'));
308
+ }
309
+ // Overlay tracking (sdk2's ungated `debugPrediction` channel,
310
+ // SelfieCapture.tsx:205-208): the states where the capture path has stopped
311
+ // consuming frames but the camera feed -- and the landmark mesh drawn over
312
+ // it -- is still on screen. Frames here refresh `prediction` only, via the
313
+ // reducer's `liveFrameAnalyzed`.
314
+ //
315
+ // Deliberately EXCLUDES the capture-path states (CAPTURING /
316
+ // GUIDANCE_SATISFIED / CAPTURE_STARTED). Those are either already forwarding
317
+ // through `shouldForwardToReducer`, or inside the busy latch's ~100ms
318
+ // auto-fire window, where `captureCanvas` is frozen on the latching frame:
319
+ // advancing the prediction there would hand doCapture a crop box from a
320
+ // LATER frame than the image it crops. PASSED is excluded too -- the success
321
+ // screen has replaced the feed by then (the loop is stopped outright there).
322
+ function shouldTrackForOverlay() {
323
+ // Signature-stage tracking already forwards every frame on its own path.
324
+ if (trackingOnly)
325
+ return false;
326
+ const s = internal.getState();
327
+ // The error screen covers the feed.
328
+ if (s.error)
329
+ return false;
330
+ const machine = s.liveness;
331
+ if (!machine)
332
+ return s.phase === 'processing';
333
+ switch (machine.requestState) {
334
+ case 'CHALLENGE':
335
+ case 'CAPTURED':
336
+ case 'IN_PROGRESS':
337
+ case 'FAILED':
338
+ case 'ERROR':
339
+ return true;
340
+ default:
341
+ return false;
342
+ }
343
+ }
344
+ function copyCanvas(dest, src) {
345
+ dest.width = src.width;
346
+ dest.height = src.height;
347
+ dest.getContext('2d')?.drawImage(src, 0, 0);
348
+ }
349
+ async function tick() {
350
+ const el = videoEl;
351
+ if (!el || !cameraHandle || !internal.getState().models.ready || !pipeline)
352
+ return;
353
+ const atMs = io.now().getTime();
354
+ if (atMs - lastHandledAt < DEFAULT_PREDICTION_THROTTLE_MS)
355
+ return;
356
+ const vw = el.videoWidth;
357
+ const vh = el.videoHeight;
358
+ // A shared video can briefly retain readyState=4 while its track swap
359
+ // resets the intrinsic dimensions. Model preprocessors draw this mirror
360
+ // canvas and browsers reject zero-sized canvas sources with InvalidStateError.
361
+ if (vw === 0 || vh === 0)
362
+ return;
363
+ lastHandledAt = atMs;
364
+ mirrorCanvas.width = vw;
365
+ mirrorCanvas.height = vh;
366
+ const ctx = mirrorCanvas.getContext('2d');
367
+ if (ctx && el.readyState === 4) {
368
+ ctx.translate(vw, 0);
369
+ ctx.scale(-1, 1);
370
+ ctx.drawImage(el, 0, 0, vw, vh);
371
+ }
372
+ const result = await pipeline.predict(mirrorCanvas);
373
+ const faces = result?.faces ?? [];
374
+ // Lighting sample runs unconditionally: state.thresholds (what
375
+ // trackFaceStep actually gates on) is ALWAYS populated -- either the
376
+ // caller's config.thresholds or state.ts's DEFAULT_MIN_CAPTURE_* trio --
377
+ // per createInitialSelfieCaptureState. Gating this sample on
378
+ // config.thresholds being explicitly set (the prior behavior) silently
379
+ // disabled the #257 visibility gates for every default-config caller,
380
+ // since sdk2's SelfieGuidanceModelsProvider defaults thresholds ON.
381
+ const primaryFace = faces[0];
382
+ const primaryFaceBounds = primaryFace
383
+ ? {
384
+ x: primaryFace.box.xMin,
385
+ y: primaryFace.box.yMin,
386
+ width: primaryFace.box.width,
387
+ height: primaryFace.box.height,
388
+ }
389
+ : undefined;
390
+ const lightingSample = detectBrightnessAndContrast(mirrorCanvas, lighting.add, primaryFaceBounds);
391
+ // Live path: every tick, gate-independent (Task 4's challenge feed).
392
+ onLivePrediction(faces[0] ?? null, atMs);
393
+ const frame = {
394
+ faces,
395
+ videoWidth: vw,
396
+ videoHeight: vh,
397
+ frameCapturedAt: atMs,
398
+ lighting: lightingSample,
399
+ };
400
+ if (!shouldForwardToReducer()) {
401
+ // Keep the mesh tracking the face for as long as the feed is shown --
402
+ // prediction only, no capture machinery, no stored-frame overwrite.
403
+ if (shouldTrackForOverlay())
404
+ dispatch({ type: 'liveFrameAnalyzed', frame });
405
+ return;
406
+ }
407
+ // A signature-stage observer only needs the live prediction. It must not
408
+ // replace the stored capture frame or enter the auto-capture machinery.
409
+ if (!trackingOnly)
410
+ copyCanvas(captureCanvas, mirrorCanvas);
411
+ dispatch({
412
+ type: trackingOnly ? 'trackingFrameAnalyzed' : 'frameAnalyzed',
413
+ frame,
414
+ });
415
+ if (trackingOnly)
416
+ return;
417
+ const post = internal.getState();
418
+ if (post.prediction?.face && post.prediction.faceReady) {
419
+ // Guidance -> machine (sdk2 :937-948): only CAPTURING may advance, and
420
+ // the prior challenge result is cleared before this attempt's
421
+ // challenge-or-skip decision (guidanceSatisfied is the sole gateway
422
+ // into CHALLENGE, so this covers both starting and skipping a run).
423
+ if (post.liveness?.requestState === 'CAPTURING') {
424
+ setLastChallengeResult(null);
425
+ dispatchLiveness({
426
+ type: 'guidanceSatisfied',
427
+ payload: { enterChallenge: challengeEnabled },
428
+ });
429
+ }
430
+ // Busy-latch auto-capture. Re-read the machine: the dispatch above may
431
+ // have just entered CHALLENGE, which pauses capture (in sdk2 the
432
+ // straggler doCapture fires anyway and the machine guards drop it; the
433
+ // fused loop can simply not arm) -- only the capture-path states
434
+ // (matching the selfieCaptureStarted guard) arm the fire timer.
435
+ const machine = internal.getState().liveness;
436
+ if (!machine ||
437
+ machine.requestState === 'CAPTURING' ||
438
+ machine.requestState === 'GUIDANCE_SATISFIED') {
439
+ // wizard onFaceDetected (:185-189): latch once, never overwrite.
440
+ captureStartedAt ||= io.now();
441
+ if (!busy) {
442
+ busy = true;
443
+ armTimer('capture:fire', AUTO_CAPTURE_FIRE_DELAY_MS, () => doCapture());
444
+ dispatchLiveness({ type: 'selfieCaptureStarted' });
445
+ }
446
+ }
447
+ }
448
+ }
449
+ // doCapture (contract item 5): shared by both the auto-fire timer and
450
+ // captureNow() -- sdk2 stamps autoCapture: 'Y' even on the manual button
451
+ // and never adds captureMode on this path (wizard :173-183, verbatim).
452
+ function doCapture() {
453
+ // Clear the armed auto-fire timer FIRST, unconditionally: doCapture is
454
+ // reachable both from that timer and from captureNow() racing ahead of
455
+ // it, and this is the single choke point where both paths converge. If
456
+ // captureNow() wins the race, this clears the still-pending
457
+ // 'capture:fire' so it can never fire a second, stale doCapture() whose
458
+ // raw internal.setState({ capturedAttempt, capturedImageUrl }) would
459
+ // otherwise bypass the reducer's phase guard and clobber the committed
460
+ // capture with data from a frame that's no longer current.
461
+ clearTimer('capture:fire');
462
+ if (trackingOnly || internal.getState().phase !== 'capturing')
463
+ return;
464
+ // Straggler guard (liveness mode): while the machine is off the capture
465
+ // path (CHALLENGE, or a verdict/in-flight state) a manual captureNow()
466
+ // or a stale fire must not commit a flow capture the machine would drop
467
+ // -- mirrors the machine's own selfieCaptureStarted/livenessReady guards.
468
+ const machineAtCapture = internal.getState().liveness;
469
+ if (machineAtCapture &&
470
+ machineAtCapture.requestState !== 'CAPTURING' &&
471
+ machineAtCapture.requestState !== 'GUIDANCE_SATISFIED' &&
472
+ machineAtCapture.requestState !== 'CAPTURE_STARTED') {
473
+ busy = false;
474
+ return;
475
+ }
476
+ const ctx = captureCanvas.getContext('2d');
477
+ if (!ctx) {
478
+ // Unlikely in a real browser (a canvas's 2d context is effectively
479
+ // always obtainable), but if it ever happens, don't strand busy=true
480
+ // -- that would permanently block the tick loop from re-arming
481
+ // capture:fire on a future faceReady frame.
482
+ busy = false;
483
+ return;
484
+ }
485
+ const imageData = ctx.getImageData(0, 0, captureCanvas.width, captureCanvas.height);
486
+ const prediction = internal.getState().prediction;
487
+ const dataUrl = cropToShoulders(rawCanvas, cropCanvas, resizeCanvas, imageData, prediction?.face ?? undefined, 0.92, 600);
488
+ const now = io.now();
489
+ const attempt = {
490
+ autoCapture: 'Y',
491
+ captureTime: now.getTime() - (captureStartedAt ?? now).getTime(),
492
+ operationTime: now.getTime() - (operationStartedAt ?? now).getTime(),
493
+ };
494
+ internal.setState({ capturedAttempt: attempt, capturedImageUrl: dataUrl });
495
+ // sdk2 doCapture (SelfieCapture.tsx:238-249) fires captureStarted before
496
+ // handing the frame over: idempotent no-op for the auto path (the arming
497
+ // latch already dispatched it), needed for the manual captureNow() path.
498
+ dispatchLiveness({ type: 'selfieCaptureStarted' });
499
+ dispatch({ type: 'selfieCaptured', dataUrl, capturedAt: now });
500
+ // Machine handoff after the flow-reducer commit (contract point 3): the
501
+ // CAPTURE_STARTED guard on livenessReady makes any straggler drop free.
502
+ dispatchLiveness({
503
+ type: 'livenessReady',
504
+ payload: { frame: imageData, face: prediction?.face ?? undefined },
505
+ });
506
+ // The loop keeps running: `shouldForwardToReducer` is already closed (the
507
+ // flow left 'capturing'), so nothing re-enters the capture path, but
508
+ // `shouldTrackForOverlay` now owns the ticks and keeps the landmark mesh
509
+ // locked to the face through the whole liveness call -- which is what
510
+ // sdk2 did, and what stopping the loop here regressed. The terminal
511
+ // outcomes (PASSED, denial, kick-out) stop it; so does detach().
512
+ busy = false;
513
+ }
514
+ // Shared frame-loop construction: enterCapturing() (fresh loop on
515
+ // start()/retry()) and setThrottleMs() (recreate a running loop with the
516
+ // new throttle) both need the identical { throttleMs, now, setTimeout }
517
+ // literal wired to `tick`.
518
+ function spawnLoop() {
519
+ return io.createFrameLoop(tick, {
520
+ throttleMs,
521
+ now: () => io.now().getTime(),
522
+ setTimeout: io.setTimeout,
523
+ });
524
+ }
525
+ // Shared by start() and retry() (contract item 8): loop create/start +
526
+ // 'capture:initialDelay' timer + clock stamps. Does NOT dispatch --
527
+ // callers dispatch their own event ('captureStarted'/'retryRequested')
528
+ // first, since the reducer already re-enters 'capturing' for both.
529
+ function enterCapturing() {
530
+ trackingOnly = false;
531
+ operationStartedAt = io.now();
532
+ captureStartedAt = null;
533
+ initialDelayOver = false;
534
+ busy = false;
535
+ lastHandledAt = 0;
536
+ clearTimer('capture:fire');
537
+ frameLoop?.stop();
538
+ frameLoop = spawnLoop();
539
+ frameLoop.start();
540
+ armTimer('capture:initialDelay', config.initialCaptureDelayMs ?? DEFAULT_INITIAL_CAPTURE_DELAY_MS, () => {
541
+ initialDelayOver = true;
542
+ });
543
+ }
544
+ // --- liveness integration (Task 4) ---
545
+ // Ports sdk2 FaceLivenessCapture's effect web onto the machine: every
546
+ // machine transition flows through dispatchLiveness, and ALL
547
+ // transition-reactive side effects (timers, runner lifecycle, callbacks,
548
+ // the check itself) live in runLivenessEffects' prev/next comparisons —
549
+ // mirroring how sdk2's useEffects key on state.requestState. The only
550
+ // arms outside the effects function are the ones sdk2 also drives outside
551
+ // that keying: the overall kick-out on start() (useTimeout mount,
552
+ // :836-843), its 120s grace in the kick-out handler (useTimeout.ts:38),
553
+ // the kickoutResetKey re-arm in runEffects, and the challenge tick's
554
+ // self-re-arm while the machine stays in CHALLENGE.
555
+ let challengeRunner = null;
556
+ let challengeResultConsumed = false;
557
+ let livenessCheckInFlight = false;
558
+ // Bumped by BOTH detach() and retry(): each starts a fresh liveness machine,
559
+ // so a check still in flight from the previous one must not report into it.
560
+ // Distinct from attachGeneration, which tracks the camera/pipeline session
561
+ // and must NOT move on a retry (no re-acquisition happens there).
562
+ let livenessGeneration = 0;
563
+ function dispatchLiveness(action) {
564
+ const prev = internal.getState().liveness;
565
+ if (!prev)
566
+ return;
567
+ const next = reduceLivenessMachine(prev, action);
568
+ if (next === prev)
569
+ return; // guard branches return by identity
570
+ internal.setState({ liveness: next });
571
+ runLivenessEffects(prev, next);
572
+ }
573
+ function runLivenessEffects(prev, next) {
574
+ const liveness = config.liveness;
575
+ if (!liveness)
576
+ return;
577
+ const stateChanged = next.requestState !== prev.requestState;
578
+ // Challenge phase lifecycle (contract points 4/5; sdk2 :700-717).
579
+ if (stateChanged && next.requestState === 'CHALLENGE') {
580
+ challengeResultConsumed = false;
581
+ challengeRunner = createChallengeRunner({
582
+ challengeCount: liveness.challenge?.challengeCount ?? DEFAULT_CHALLENGE_COUNT,
583
+ responseWindowMs: liveness.challenge?.responseWindowMs ?? DEFAULT_RESPONSE_WINDOW_MS,
584
+ rng: liveness.rng,
585
+ });
586
+ internal.setState({ challenge: challengeRunner.snapshot() });
587
+ armTimer('challenge:tick', CHALLENGE_TICK_MS, onChallengeTick);
588
+ }
589
+ if (stateChanged && prev.requestState === 'CHALLENGE') {
590
+ challengeRunner = null;
591
+ clearTimer('challenge:tick');
592
+ // sdk2 remounts SelfieCapture on CHALLENGE -> GUIDANCE_SATISFIED
593
+ // (:954-968) so its busy latch clears and auto-capture can re-arm;
594
+ // the fused loop only needs the latch reset.
595
+ if (next.requestState === 'GUIDANCE_SATISFIED')
596
+ busy = false;
597
+ }
598
+ // Failure-limit kickout (sdk2 :812-823): fires once per count change.
599
+ if (next.timesLivenessCheckFailed !== prev.timesLivenessCheckFailed &&
600
+ hasExceededLivenessFailureLimit(next)) {
601
+ // Terminal: the lockout screen replaces the feed, so the overlay
602
+ // tracking the FAILED state would otherwise keep running has nothing
603
+ // left to draw on.
604
+ frameLoop?.stop();
605
+ liveness.onFailure?.();
606
+ liveness.onDenied?.();
607
+ }
608
+ // Reset-after-verdict (sdk2 :797-803) — skipped when the failure limit
609
+ // is exceeded: that outcome is terminal (public phase 'failed').
610
+ if (stateChanged &&
611
+ (next.requestState === 'FAILED' || next.requestState === 'ERROR') &&
612
+ !hasExceededLivenessFailureLimit(next)) {
613
+ armTimer('liveness:reset', LIVENESS_RESET_DELAY_MS, () => {
614
+ dispatchLiveness({ type: 'resetLivenessCheck' });
615
+ // Re-enter the capture loop: fresh tracking via the flow reducer
616
+ // (no-op by identity when the flow never left 'capturing', e.g.
617
+ // after a challenge timeout where nothing was captured).
618
+ dispatch({ type: 'retryRequested' });
619
+ enterCapturing();
620
+ });
621
+ }
622
+ // resetLivenessCheck re-entry: drop the finished challenge snapshot so
623
+ // `challenge` is null outside a run (the next CHALLENGE entry republishes).
624
+ if (stateChanged && next.requestState === 'CAPTURING') {
625
+ if (internal.getState().challenge)
626
+ internal.setState({ challenge: null });
627
+ }
628
+ // Frame captured -> run the check (sdk2 checkLivenessIfPossible :722-764).
629
+ if (stateChanged && next.requestState === 'CAPTURED')
630
+ void runLivenessCheck();
631
+ if (stateChanged && next.requestState === 'PASSED') {
632
+ clearTimer('liveness:kickout');
633
+ clearTimer('liveness:kickoutGrace');
634
+ // Terminal: the success screen owns the phase from here.
635
+ frameLoop?.stop();
636
+ // sdk2 callSuccessIfAvailable (:805-810): PASSED always carries the
637
+ // imageUrl (livenessChecked stamped it).
638
+ if (next.imageUrl)
639
+ liveness.onSuccess?.(next.imageUrl);
640
+ }
641
+ }
642
+ // Overall kick-out (sdk2 useTimeout wiring :825-843): armed on start(),
643
+ // re-armed by runEffects' kickoutResetKey comparison.
644
+ function armKickout() {
645
+ const liveness = config.liveness;
646
+ if (!liveness)
647
+ return;
648
+ armTimer('liveness:kickout', liveness.timeoutDurationMs ?? KICKOUT_TIMEOUT_MS, onKickout);
649
+ }
650
+ // Shared terminal handling (sdk2 useTimeout's second effect): PASSED or a
651
+ // model error averts the timeout entirely; otherwise the hook fires.
652
+ // callOnTimeoutHooks (FaceLivenessCapture.tsx:825-827) calls ONLY
653
+ // onTimeout -- onDenied is exclusively the failure-limit hook above; a
654
+ // kickout is never itself a denial (byte-faithful to sdk2, confirmed
655
+ // against FaceLivenessWizard/FaceValidation: onDenied is never invoked on
656
+ // the timeout path).
657
+ function fireKickoutHooks() {
658
+ const s = internal.getState();
659
+ const machine = s.liveness;
660
+ if (!machine || machine.requestState === 'PASSED' || s.models.error)
661
+ return;
662
+ // Terminal: the kick-out puts up the lockout screen (same reasoning as
663
+ // the denial branch in runLivenessEffects).
664
+ frameLoop?.stop();
665
+ // Publish BEFORE the hook so a listener that re-reads state from inside
666
+ // onTimeout already sees the terminal outcome.
667
+ internal.setState({ livenessTimedOut: true });
668
+ config.liveness?.onTimeout?.();
669
+ }
670
+ function onKickout() {
671
+ const s = internal.getState();
672
+ const machine = s.liveness;
673
+ if (!machine || machine.requestState === 'PASSED' || s.models.error)
674
+ return;
675
+ if (machine.requestState === 'IN_PROGRESS') {
676
+ // A check is in flight: a slow backend must not boot the user
677
+ // mid-check — wait the hardcoded grace (sdk2 useTimeout.ts:38) before
678
+ // applying the same terminal handling.
679
+ //
680
+ // Observable divergence from sdk2: sdk2's useTimeout re-runs its
681
+ // effect reactively (shouldWaitLonger is a dep), so it fires onTimeout
682
+ // the instant IN_PROGRESS ends un-averted mid-grace -- e.g. the check
683
+ // resolves FAILED partway through the window. This port only checks
684
+ // machine state when the fixed 120s grace itself expires, so it always
685
+ // waits out the full window; a PASSED landing anywhere inside it still
686
+ // averts (runLivenessEffects' PASSED branch clears this timer). More
687
+ // lenient, at-most-once.
688
+ armTimer('liveness:kickoutGrace', KICKOUT_WAIT_LONGER_MS, fireKickoutHooks);
689
+ return;
690
+ }
691
+ fireKickoutHooks();
692
+ }
693
+ // Coarse safety tick (CHALLENGE only): drives the runner's event-evaluated
694
+ // deadlines (response window / settle fallback) even if camera frames
695
+ // stall; re-arms itself only while the machine stays in CHALLENGE.
696
+ function onChallengeTick() {
697
+ const runner = challengeRunner;
698
+ if (!runner)
699
+ return;
700
+ handleRunnerSnapshot(runner.step({ type: 'tick', atMs: io.now().getTime() }));
701
+ if (challengeRunner &&
702
+ internal.getState().liveness?.requestState === 'CHALLENGE') {
703
+ armTimer('challenge:tick', CHALLENGE_TICK_MS, onChallengeTick);
704
+ }
705
+ }
706
+ function challengeSnapshotChanged(a, b) {
707
+ return (!a ||
708
+ a.promptKind !== b.promptKind ||
709
+ a.promptCount !== b.promptCount ||
710
+ a.stepIndex !== b.stepIndex ||
711
+ a.stepCount !== b.stepCount ||
712
+ a.awaitingReturn !== b.awaitingReturn ||
713
+ a.settling !== b.settling ||
714
+ a.finalized !== b.finalized ||
715
+ a.result !== b.result);
716
+ }
717
+ // Single sink for runner snapshots (contract point 5): publishes changes,
718
+ // and consumes a finalized result exactly once — callback first, then the
719
+ // machine verdict (challengeFailed in observe mode records-and-proceeds).
720
+ // The dispatch moves the machine out of CHALLENGE, so the effects' exit
721
+ // branch drops the runner and clears the tick.
722
+ function handleRunnerSnapshot(snap) {
723
+ if (challengeSnapshotChanged(internal.getState().challenge, snap)) {
724
+ internal.setState({ challenge: snap });
725
+ }
726
+ if (snap.finalized && !challengeResultConsumed) {
727
+ challengeResultConsumed = true;
728
+ const result = snap.result;
729
+ config.liveness?.onChallengeComplete?.(result);
730
+ dispatchLiveness(result.passed
731
+ ? { type: 'challengePassed' }
732
+ : {
733
+ type: 'challengeFailed',
734
+ payload: {
735
+ observe: config.liveness?.challenge?.mode === 'observe',
736
+ },
737
+ });
738
+ }
739
+ }
740
+ // sdk2 checkLivenessIfPossible (:722-764), non-softFail semantics: ONE
741
+ // livenessChecked dispatch per response (verdict failures resolve ok:true
742
+ // and the MACHINE judges them; only transport/API errors land in the
743
+ // ok:false / thrown arms). Single-flight guarded; every failure path is a
744
+ // livenessCheckFailed dispatch, never a silent drop.
745
+ async function runLivenessCheck() {
746
+ const liveness = config.liveness;
747
+ if (!liveness || livenessCheckInFlight)
748
+ return;
749
+ const machine = internal.getState().liveness;
750
+ if (!machine?.frame)
751
+ return;
752
+ // Captured before the await so a detach()+attach() OR a retry() -- both
753
+ // of which build a new machine -- is detectable on resume. `active` alone
754
+ // is not enough, since attach() flips it back to true for the NEW session
755
+ // and retry() never clears it at all.
756
+ const generation = livenessGeneration;
757
+ livenessCheckInFlight = true;
758
+ try {
759
+ dispatchLiveness({ type: 'livenessChecking' });
760
+ const { frame, face } = machine;
761
+ const imageUrl = cropToShoulders(rawCanvas, cropCanvas, resizeCanvas, frame, face, 0.92, 600);
762
+ const result = await liveness.checkLiveness(dataUrlToBase64Sync(imageUrl));
763
+ // Stale generation: a detach()+attach() or a retry() happened during the
764
+ // await, so a NEW machine may already be running. Bail without
765
+ // dispatching -- the reducer's livenessChecked case is unguarded
766
+ // (sdk2-faithfully), so a stale dispatch here would land a verdict
767
+ // (even onSuccess, with THIS attempt's image) into the new machine.
768
+ if (generation !== livenessGeneration)
769
+ return;
770
+ if (result.ok) {
771
+ // The submission's `metadata.selfie[].livenessScore` — sdk2 carries
772
+ // the live check's `realScore` there (SelfieCapture.tsx's
773
+ // captureAttempt is stamped with it once the check returns), and the
774
+ // backend receives it on every enrollment.
775
+ //
776
+ // Stamped HERE rather than in doCapture because that is the only
777
+ // point where both halves exist: doCapture builds the attempt before
778
+ // any check has run, and the verdict arrives without a reference to
779
+ // the attempt it belongs to. The generation guard above already
780
+ // established that this response belongs to the CURRENT attempt.
781
+ //
782
+ // Missing this was a silent data loss the both-builds payload diff
783
+ // caught: the field simply was not in 3.0's body.
784
+ const capturedAttempt = internal.getState().capturedAttempt;
785
+ const realScore = result.response.resultData?.realScore;
786
+ if (capturedAttempt && typeof realScore === 'number') {
787
+ internal.setState({
788
+ capturedAttempt: { ...capturedAttempt, livenessScore: realScore },
789
+ });
790
+ }
791
+ liveness.onLivenessChecked?.(result.response);
792
+ dispatchLiveness({
793
+ type: 'livenessChecked',
794
+ payload: { frame, face, imageUrl, response: result.response },
795
+ });
796
+ }
797
+ else {
798
+ dispatchLiveness({
799
+ type: 'livenessCheckFailed',
800
+ payload: { error: result.error },
801
+ });
802
+ }
803
+ }
804
+ catch (e) {
805
+ if (generation === livenessGeneration) {
806
+ dispatchLiveness({
807
+ type: 'livenessCheckFailed',
808
+ payload: { error: e instanceof Error ? e : new Error(String(e)) },
809
+ });
810
+ }
811
+ }
812
+ finally {
813
+ // Stale generation: also skip the guard-reset. The NEW machine's own
814
+ // in-flight check (if any) owns `livenessCheckInFlight` now, and this
815
+ // stale finally clearing it to false would let a second concurrent
816
+ // check start against it (detach() and retry() each reset the flag
817
+ // once, synchronously, when they ended the previous attempt).
818
+ if (generation === livenessGeneration)
819
+ livenessCheckInFlight = false;
820
+ }
821
+ }
822
+ async function acquireCameraStep(el) {
823
+ // Captured before the await: a detach() (or a detach+re-attach, which a
824
+ // retry performs) while getUserMedia is in flight bumps this, and the
825
+ // resolved camera then belongs to a session that no longer exists.
826
+ //
827
+ // Landing it anyway is actively destructive, not merely wasteful:
828
+ // acquireCamera() calls releaseGlobalCameraAccess() early, and that
829
+ // release nulls `video.srcObject` on the element the CURRENT session just
830
+ // wired up. The result is the exact contradiction this bug presented as --
831
+ // `camera.ready === true` (written by the stale acquisition below)
832
+ // alongside a mounted <video> with no stream at all, so the model
833
+ // lifecycle's readyState wait never completes.
834
+ //
835
+ // A fake camera resolves in ~0ms, so this window only opens with a real
836
+ // one, where getUserMedia takes hundreds of milliseconds.
837
+ const generation = attachGeneration;
838
+ try {
839
+ // Front camera by default for selfies (see the config.camera JSDoc);
840
+ // an explicit config.camera.preferFrontFacingCamera wins via spread.
841
+ const acquired = await io.acquireCamera(el, {
842
+ preferFrontFacingCamera: true,
843
+ ...config.camera,
844
+ });
845
+ if (!active || generation !== attachGeneration) {
846
+ // Superseded: hand the stream back rather than leaking it, and leave
847
+ // the live session's state untouched.
848
+ acquired.release();
849
+ return;
850
+ }
851
+ cameraHandle = acquired;
852
+ internal.setState((s) => ({
853
+ camera: {
854
+ ready: true,
855
+ isRearFacing: acquired.isRearFacing,
856
+ accessRequested: true,
857
+ },
858
+ // On recovery from a prior error, clear it and restore phase to
859
+ // 'loading' (the pre-capture state; models/reducer drive forward).
860
+ // `s.error` alone is the complete check: every phase:'error' write
861
+ // (the reducer's own modelsProgressed/captureFailed transitions) also
862
+ // sets `error`, and the two catch blocks above no longer write a raw
863
+ // phase at all -- so error non-null is the single source of truth.
864
+ ...(s.error ? { error: null, phase: 'loading' } : {}),
865
+ }));
866
+ }
867
+ catch (e) {
868
+ throw e instanceof CaptureAttachError
869
+ ? e
870
+ : new CaptureAttachError({
871
+ code: 'CAMERA_UNAVAILABLE',
872
+ recoverable: true,
873
+ cause: e,
874
+ });
875
+ }
876
+ finally {
877
+ // sdk2 cameraStore finally-latch: settled (granted OR denied).
878
+ const cam = internal.getState().camera;
879
+ if (!cam.accessRequested) {
880
+ internal.setState({ camera: { ...cam, accessRequested: true } });
881
+ }
882
+ }
883
+ }
884
+ async function loadPipelineStep(el) {
885
+ // Captured before the await below, same reason as acquireCameraStep's.
886
+ const generation = attachGeneration;
887
+ if (!pipeline) {
888
+ pipeline = io.createPipeline({
889
+ detector: config.detector,
890
+ runtime: config.runtime,
891
+ modelAssetPath: config.modelAssetPath,
892
+ modelLoadTimeoutMs: config.modelLoadTimeoutMs,
893
+ videoReady: () => waitForVideoReady({ current: el }),
894
+ onStateChange: (aggregate) => {
895
+ // Same reason as the ID pipeline's onLifecycleChange: the reducer
896
+ // keeps only `error.message`, and the host callback reduces it
897
+ // further, so nothing ever printed WHY the selfie models failed.
898
+ // Logged on the transition into 'error' (this fires per progress
899
+ // tick) at error level, which the LiteRT console filter never
900
+ // touches.
901
+ if (aggregate.loadState === 'error' &&
902
+ lastReportedLoadState !== 'error') {
903
+ error('[SelfieCapture] models failed to load:', aggregate.error);
904
+ }
905
+ lastReportedLoadState = aggregate.loadState;
906
+ dispatch({ type: 'modelsProgressed', models: aggregate });
907
+ },
908
+ setTimeout: io.setTimeout,
909
+ clearTimeout: io.clearTimeout,
910
+ });
911
+ }
912
+ // No duplicate error handling here: pipeline.load() never rejects for a
913
+ // model-load failure (pipeline.ts's runLoad reports failures through the
914
+ // onStateChange aggregate, settling loadState: 'error'); the reducer's
915
+ // 'modelsProgressed' handler above is the single place that turns that
916
+ // into phase 'error' + a MODEL_LOAD_FAILED SelfieCaptureFlowError.
917
+ await pipeline.load();
918
+ // A detach() while the load was in flight has already disposed this
919
+ // pipeline, nulled the field and reset the flag. Setting it now would
920
+ // tell the NEXT attach that the models are loaded when nothing is
921
+ // holding them — the same "waiting on a load nobody is running" stall
922
+ // this step exists to prevent, one session later. Checked here rather
923
+ // than at each call site so both attach and camera recovery are covered.
924
+ if (!active || generation !== attachGeneration)
925
+ return;
926
+ pipelineLoaded = true;
927
+ }
928
+ async function doAttach(el) {
929
+ const generation = attachGeneration;
930
+ // A detach() bumps attachGeneration, so an attach still in flight belongs to
931
+ // a session that no longer exists and must not block this one. Without the
932
+ // generation comparison the `attaching` latch rejected the RE-attach half of
933
+ // every detach+re-attach (React replacing the <video> on a retry), and
934
+ // SelfieCaptureSurface swallows attach() rejections -- so the new element
935
+ // silently never got a camera.
936
+ if (attaching && attachingGeneration === generation) {
937
+ throw new Error('attach() already in progress');
938
+ }
939
+ attaching = true;
940
+ attachingGeneration = generation;
941
+ // `active` alone cannot answer "is this attach still current?": a
942
+ // re-attach sets it back to true, so a superseded attach would sail past
943
+ // the checks below and finish against the element it was handed.
944
+ const superseded = () => !active || generation !== attachGeneration;
945
+ try {
946
+ if (internal.getState().error)
947
+ internal.setState({ error: null });
948
+ dispatch({ type: 'captureInitialized' });
949
+ if (!cameraHandle && !config.deferCameraAcquisition)
950
+ await acquireCameraStep(el);
951
+ // detach() during the awaits above: stop quietly instead of finishing.
952
+ if (superseded())
953
+ return;
954
+ if (!pipelineLoaded)
955
+ await loadPipelineStep(el);
956
+ if (superseded())
957
+ return;
958
+ attached = true;
959
+ }
960
+ catch (e) {
961
+ // A superseded attach unwinds silently: its failure says nothing about
962
+ // the session that replaced it, and writing `error` here would park the
963
+ // live session on a camera error it never hit.
964
+ if (superseded())
965
+ return;
966
+ // attach() rejects typed AND the store lands in the mapped error --
967
+ // one truth in both places (idCapture parity). Only `error` is written
968
+ // here (no raw `phase: 'error'`, per the Task-2 review): toPublicState's
969
+ // derivedPhase reads `error` directly, so the public phase surfaces
970
+ // 'error' either way, and internal `s.phase` is left for the reducer's
971
+ // own transitions to own (e.g. a not-yet-attached session never having
972
+ // left 'loading' is truer than a synthetic capture-phase jump).
973
+ const err = e instanceof CaptureAttachError
974
+ ? e
975
+ : new CaptureAttachError({
976
+ code: 'CAMERA_UNAVAILABLE',
977
+ recoverable: true,
978
+ cause: e,
979
+ });
980
+ internal.setState({ error: toSelfieCaptureError(err) });
981
+ throw err;
982
+ }
983
+ finally {
984
+ // Only the CURRENT generation may release the latch: a newer doAttach
985
+ // has already claimed it, and clearing it here would let a genuine
986
+ // concurrent attach() slip past the guard above.
987
+ if (generation === attachGeneration)
988
+ attaching = false;
989
+ }
990
+ }
991
+ return {
992
+ async attach(el) {
993
+ if (attached)
994
+ throw new Error('attach() called while already attached');
995
+ active = true;
996
+ videoEl = el;
997
+ await doAttach(el);
998
+ },
999
+ detach() {
1000
+ active = false;
1001
+ attached = false;
1002
+ clearAllTimers();
1003
+ // Orphans any in-flight runLivenessCheck (idCapture/controller.ts's
1004
+ // recaptureGeneration pattern): its captured `generation` will no
1005
+ // longer match on resume, so it bails instead of touching the machine
1006
+ // this detach() is about to reset.
1007
+ attachGeneration += 1;
1008
+ livenessGeneration += 1;
1009
+ frameLoop?.stop();
1010
+ frameLoop = null;
1011
+ trackingOnly = false;
1012
+ initialDelayOver = false;
1013
+ busy = false;
1014
+ operationStartedAt = null;
1015
+ captureStartedAt = null;
1016
+ lastHandledAt = 0;
1017
+ challengeRunner = null;
1018
+ challengeResultConsumed = false;
1019
+ livenessCheckInFlight = false;
1020
+ pipeline?.dispose();
1021
+ pipeline = null;
1022
+ pipelineLoaded = false;
1023
+ cameraHandle?.release();
1024
+ cameraHandle = null;
1025
+ videoEl = null;
1026
+ internal.setState((s) => ({
1027
+ ...createInitialSelfieCaptureState({ thresholds: config.thresholds }),
1028
+ // Divergence: accessRequested survives detach -- the latch means "a
1029
+ // request settled this session"; resetting it would regress the
1030
+ // ring intro on a StrictMode remount.
1031
+ camera: {
1032
+ ready: false,
1033
+ isRearFacing: false,
1034
+ accessRequested: s.camera.accessRequested,
1035
+ },
1036
+ capturedAttempt: null,
1037
+ capturedImageUrl: null,
1038
+ liveness: config.liveness ? createInitialLivenessMachineState() : null,
1039
+ challenge: null,
1040
+ livenessTimedOut: false,
1041
+ }));
1042
+ },
1043
+ getState() {
1044
+ if (!snapshot)
1045
+ snapshot = toPublicState(internal.getState());
1046
+ return snapshot;
1047
+ },
1048
+ subscribe(cb) {
1049
+ listeners.add(cb);
1050
+ return () => {
1051
+ listeners.delete(cb);
1052
+ };
1053
+ },
1054
+ actions: {
1055
+ async requestCamera() {
1056
+ if (!videoEl)
1057
+ throw new Error('requestCamera() requires attach() first');
1058
+ // Non-deferred mode (or a second call after the camera is already
1059
+ // held): no-op resolve, no re-acquisition.
1060
+ if (cameraHandle)
1061
+ return;
1062
+ // Both captured before the await, same reason as acquireCameraStep's:
1063
+ // a detach()+attach() during the acquisition replaces the session AND
1064
+ // reassigns `videoEl`, so the post-await work below would otherwise
1065
+ // run against the replacement — loading ITS pipeline, concurrently
1066
+ // with the attach that already owns that job.
1067
+ const generation = attachGeneration;
1068
+ const el = videoEl;
1069
+ try {
1070
+ await acquireCameraStep(el);
1071
+ }
1072
+ catch (e) {
1073
+ // Same normalization + single-truth store write as doAttach's catch
1074
+ // (error only, derivedPhase surfaces it publicly).
1075
+ const err = e instanceof CaptureAttachError
1076
+ ? e
1077
+ : new CaptureAttachError({
1078
+ code: 'CAMERA_UNAVAILABLE',
1079
+ recoverable: true,
1080
+ cause: e,
1081
+ });
1082
+ internal.setState({ error: toSelfieCaptureError(err) });
1083
+ throw err;
1084
+ }
1085
+ // The camera is back; the MODELS may not be. `doAttach` loads the
1086
+ // pipeline AFTER the camera, so an attach that died at the camera step
1087
+ // never reached it — and a `detach()` immediately before (React
1088
+ // replacing the <video>) has already disposed the one the previous
1089
+ // session built. Close the laptop lid mid-capture and reopen it and
1090
+ // that is exactly the sequence: macOS drops the camera,
1091
+ // `enumerateDevices()` returns nothing, the re-attach fails.
1092
+ //
1093
+ // Without this, recovery cleared the error and returned to 'loading'
1094
+ // with no pipeline behind it, so the overlay sat at "downloading 0%"
1095
+ // for ever — the same shape as the signature controller's retry bug.
1096
+ // Guarded on `pipelineLoaded` so the deferred-camera path, whose
1097
+ // attach DID load the models, never restarts a completed download.
1098
+ if (!active || generation !== attachGeneration)
1099
+ return;
1100
+ if (!pipelineLoaded)
1101
+ await loadPipelineStep(el);
1102
+ },
1103
+ start() {
1104
+ // Requires a live session, same as retry() below: enterCapturing()
1105
+ // spawns and STARTS a frame loop and arms timers, and detach() has
1106
+ // already run its cleanup, so anything created after it is orphaned.
1107
+ //
1108
+ // Guarded on `active` (attach() sets it FIRST, detach() clears it),
1109
+ // not `attached` (set LAST, after the pipeline load): models report
1110
+ // ready from inside that load, so an autoContinueAfterLoading overlay
1111
+ // can legitimately call start() while attach() is still finishing.
1112
+ // `attached` would drop it and strand the user on the loading screen.
1113
+ if (!active)
1114
+ return;
1115
+ dispatch({ type: 'captureStarted' });
1116
+ enterCapturing();
1117
+ // Overall kick-out from the start of the attempt (contract point 6;
1118
+ // sdk2 arms it on mount via useTimeout :836-843). The countdown
1119
+ // survives in-attempt retries — only challenge progress (the
1120
+ // kickoutResetKey in runEffects) or PASSED touches it.
1121
+ if (config.liveness)
1122
+ armKickout();
1123
+ },
1124
+ captureNow() {
1125
+ // Manual capture button (sdk2 SelfieCapture.tsx:461-467): draws the
1126
+ // CURRENT live frame straight from the video element -- no
1127
+ // translate/scale mirror flip. That asymmetry vs. the auto/gated
1128
+ // path's mirror-drawn snapshot is verbatim sdk2 (confirmed reading
1129
+ // the manual onClick handler directly), not a paraphrase-error in
1130
+ // this port.
1131
+ // Guarded to the 'capturing' phase: a stray call once a capture is
1132
+ // already committed (or hasn't started) must not re-draw over the
1133
+ // committed capture canvas or resurrect doCapture() outside its only
1134
+ // valid phase (doCapture() re-checks the same phase itself, but
1135
+ // bailing here also skips the pointless canvas draw).
1136
+ if (internal.getState().phase !== 'capturing')
1137
+ return;
1138
+ const el = videoEl;
1139
+ if (el) {
1140
+ captureCanvas.width = el.videoWidth;
1141
+ captureCanvas.height = el.videoHeight;
1142
+ captureCanvas.getContext('2d')?.drawImage(el, 0, 0);
1143
+ }
1144
+ doCapture();
1145
+ },
1146
+ captureManually(imageDataUrl) {
1147
+ const state = internal.getState();
1148
+ if (state.phase === 'completed' || state.phase === 'failed')
1149
+ return;
1150
+ // A hand-picked image cannot pass an on-device liveness check, and
1151
+ // committing one here would complete a LIVENESS stage with a photo
1152
+ // nothing verified — while leaving the machine stranded mid-ladder.
1153
+ // sdk2 drew the same line: its fallback screen belonged to the plain
1154
+ // selfie component, never to FaceLivenessCapture.
1155
+ if (state.liveness) {
1156
+ warn('[selfieCapture] captureManually() ignored: a liveness check is running, and a supplied image cannot satisfy it.');
1157
+ return;
1158
+ }
1159
+ const now = io.now();
1160
+ // sdk2's fallback capture is a user action with no detection behind
1161
+ // it, so the attempt is stamped 'N' (idCapture's runManualCapture
1162
+ // does the same for its own fallback path).
1163
+ const attempt = {
1164
+ autoCapture: 'N',
1165
+ captureTime: now.getTime() - (captureStartedAt ?? now).getTime(),
1166
+ operationTime: now.getTime() - (operationStartedAt ?? now).getTime(),
1167
+ };
1168
+ internal.setState({
1169
+ capturedAttempt: attempt,
1170
+ capturedImageUrl: imageDataUrl,
1171
+ });
1172
+ dispatch({
1173
+ type: 'selfieCapturedManually',
1174
+ dataUrl: imageDataUrl,
1175
+ capturedAt: now,
1176
+ });
1177
+ },
1178
+ startTracking() {
1179
+ if (!active || !internal.getState().models.ready)
1180
+ return;
1181
+ trackingOnly = true;
1182
+ initialDelayOver = true;
1183
+ busy = false;
1184
+ lastHandledAt = 0;
1185
+ clearTimer('capture:initialDelay');
1186
+ clearTimer('capture:fire');
1187
+ frameLoop?.stop();
1188
+ frameLoop = spawnLoop();
1189
+ frameLoop.start();
1190
+ },
1191
+ stopTracking() {
1192
+ if (!trackingOnly)
1193
+ return;
1194
+ trackingOnly = false;
1195
+ frameLoop?.stop();
1196
+ initialDelayOver = false;
1197
+ busy = false;
1198
+ clearTimer('capture:initialDelay');
1199
+ clearTimer('capture:fire');
1200
+ },
1201
+ setThrottleMs(ms) {
1202
+ throttleMs = ms;
1203
+ if (frameLoop?.running) {
1204
+ frameLoop.stop();
1205
+ frameLoop = spawnLoop();
1206
+ frameLoop.start();
1207
+ }
1208
+ },
1209
+ retry() {
1210
+ if (!active)
1211
+ return;
1212
+ // sdk2's retry remounts FaceLivenessCapture with a new `key`
1213
+ // (FaceLivenessWizard.tsx:402-409), which throws away that
1214
+ // component's whole reducer -- INCLUDING timesLivenessCheckFailed --
1215
+ // so the user gets a fresh set of liveness attempts. Rebuilding the
1216
+ // machine here is that remount's equivalent; without it a retry from
1217
+ // the lockout screen re-entered capture with the failure budget still
1218
+ // spent, and the next failed check re-locked immediately.
1219
+ if (config.liveness) {
1220
+ clearTimer('liveness:reset');
1221
+ clearTimer('liveness:kickout');
1222
+ clearTimer('liveness:kickoutGrace');
1223
+ // The challenge runner and its tick are NOT reducer state, so the
1224
+ // setState below cannot reach them -- runLivenessEffects runs only
1225
+ // from dispatchLiveness. Retrying out of CHALLENGE otherwise left
1226
+ // the discarded runner ticking, still able to fire
1227
+ // onChallengeComplete for an attempt the user had abandoned.
1228
+ clearTimer('challenge:tick');
1229
+ challengeRunner = null;
1230
+ challengeResultConsumed = false;
1231
+ // Orphan any check still in flight: its verdict would otherwise land
1232
+ // in the machine built below (the reducer's livenessChecked case is
1233
+ // unguarded), and its single-flight latch would block the fresh
1234
+ // attempt from checking at all until it settled.
1235
+ livenessGeneration += 1;
1236
+ livenessCheckInFlight = false;
1237
+ internal.setState({
1238
+ liveness: createInitialLivenessMachineState(),
1239
+ challenge: null,
1240
+ livenessTimedOut: false,
1241
+ });
1242
+ }
1243
+ dispatch({ type: 'retryRequested' });
1244
+ enterCapturing();
1245
+ // sdk2's retry remounts the component, so its useTimeout arms a fresh
1246
+ // countdown. Clearing the timer above without re-arming left a retried
1247
+ // session with no overall kick-out at all.
1248
+ if (config.liveness)
1249
+ armKickout();
1250
+ },
1251
+ },
1252
+ };
1253
+ }