@idmission/websdk-core 0.2.0-rc.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +8 -1
  2. package/dist/client/IdmissionClient.d.ts +2 -0
  3. package/dist/client/IdmissionClient.d.ts.map +1 -1
  4. package/dist/client/IdmissionClient.js +3 -0
  5. package/dist/client/artifacts.d.ts +2 -0
  6. package/dist/client/artifacts.d.ts.map +1 -1
  7. package/dist/client/payload.d.ts.map +1 -1
  8. package/dist/client/payload.js +2 -1
  9. package/dist/client/types.d.ts +2 -0
  10. package/dist/client/types.d.ts.map +1 -1
  11. package/dist/documentCapture/autoCaptureEngine.d.ts +106 -0
  12. package/dist/documentCapture/autoCaptureEngine.d.ts.map +1 -0
  13. package/dist/documentCapture/autoCaptureEngine.js +456 -0
  14. package/dist/documentCapture/autoCaptureGeometry.d.ts +424 -0
  15. package/dist/documentCapture/autoCaptureGeometry.d.ts.map +1 -0
  16. package/dist/documentCapture/autoCaptureGeometry.js +394 -0
  17. package/dist/documentCapture/autoCaptureGuidance.d.ts +61 -0
  18. package/dist/documentCapture/autoCaptureGuidance.d.ts.map +1 -0
  19. package/dist/documentCapture/autoCaptureGuidance.js +73 -0
  20. package/dist/documentCapture/autoCaptureMetadata.d.ts +185 -0
  21. package/dist/documentCapture/autoCaptureMetadata.d.ts.map +1 -0
  22. package/dist/documentCapture/autoCaptureMetadata.js +197 -0
  23. package/dist/documentCapture/autoCaptureOptions.d.ts +212 -0
  24. package/dist/documentCapture/autoCaptureOptions.d.ts.map +1 -0
  25. package/dist/documentCapture/autoCaptureOptions.js +178 -0
  26. package/dist/documentCapture/autoCaptureShutter.d.ts +162 -0
  27. package/dist/documentCapture/autoCaptureShutter.d.ts.map +1 -0
  28. package/dist/documentCapture/autoCaptureShutter.js +183 -0
  29. package/dist/documentCapture/controller.d.ts +33 -1
  30. package/dist/documentCapture/controller.d.ts.map +1 -1
  31. package/dist/documentCapture/controller.js +604 -40
  32. package/dist/documentCapture/index.d.ts +8 -2
  33. package/dist/documentCapture/index.d.ts.map +1 -1
  34. package/dist/documentCapture/index.js +6 -0
  35. package/dist/documentCapture/reducer.d.ts +26 -1
  36. package/dist/documentCapture/reducer.d.ts.map +1 -1
  37. package/dist/documentCapture/reducer.js +43 -0
  38. package/dist/documentCapture/state.d.ts +118 -0
  39. package/dist/documentCapture/state.d.ts.map +1 -1
  40. package/dist/documentCapture/state.js +24 -0
  41. package/dist/idCapture/controller.d.ts +20 -0
  42. package/dist/idCapture/controller.d.ts.map +1 -1
  43. package/dist/idCapture/controller.js +42 -3
  44. package/dist/idCapture/index.d.ts +1 -1
  45. package/dist/idCapture/index.d.ts.map +1 -1
  46. package/dist/idCapture/index.js +12 -1
  47. package/dist/idCapture/pipeline.d.ts +30 -0
  48. package/dist/idCapture/pipeline.d.ts.map +1 -1
  49. package/dist/idCapture/pipeline.js +33 -10
  50. package/dist/models/DocumentDetection.d.ts +29 -1
  51. package/dist/models/DocumentDetection.d.ts.map +1 -1
  52. package/dist/models/DocumentDetection.js +37 -5
  53. package/dist/models/defaults/PoaDocumentDetectorLiteRT.d.ts +3 -0
  54. package/dist/models/defaults/PoaDocumentDetectorLiteRT.d.ts.map +1 -0
  55. package/dist/models/defaults/PoaDocumentDetectorLiteRT.js +15 -0
  56. package/dist/models/defaults/index.d.ts +4 -1
  57. package/dist/models/defaults/index.d.ts.map +1 -1
  58. package/dist/models/defaults/index.js +4 -0
  59. package/dist/models/preloadModels.d.ts +21 -14
  60. package/dist/models/preloadModels.d.ts.map +1 -1
  61. package/dist/models/preloadModels.js +10 -0
  62. package/dist/models/providers/litert/docDetectPrePost.d.ts.map +1 -1
  63. package/dist/models/providers/litert/docDetectPrePost.js +5 -0
  64. package/dist/selfieCapture/guidance.d.ts +49 -0
  65. package/dist/selfieCapture/guidance.d.ts.map +1 -1
  66. package/dist/selfieCapture/guidance.js +51 -0
  67. package/dist/selfieCapture/index.d.ts +1 -1
  68. package/dist/selfieCapture/index.d.ts.map +1 -1
  69. package/dist/selfieCapture/index.js +1 -1
  70. package/dist/signatureCapture/controller.d.ts.map +1 -1
  71. package/dist/signatureCapture/controller.js +71 -21
  72. package/dist/signatureCapture/pipeline.d.ts +14 -2
  73. package/dist/signatureCapture/pipeline.d.ts.map +1 -1
  74. package/dist/signatureCapture/pipeline.js +30 -7
  75. package/dist/signatureCapture/state.d.ts +15 -0
  76. package/dist/signatureCapture/state.d.ts.map +1 -1
  77. package/dist/version.d.ts +1 -1
  78. package/dist/version.d.ts.map +1 -1
  79. package/dist/version.js +1 -1
  80. package/dist/videoIdCapture/controller.d.ts.map +1 -1
  81. package/dist/videoIdCapture/controller.js +64 -3
  82. package/package.json +1 -1
@@ -18,17 +18,46 @@ import { createStore } from 'zustand/vanilla';
18
18
  import { acquireCamera, } from '../camera/acquireCamera';
19
19
  import { CaptureAttachError } from '../idCapture/errors';
20
20
  import { error, warn } from '../utils/logger';
21
+ import { createAutoCaptureEngine, } from './autoCaptureEngine';
22
+ import { computeGuideRect } from './autoCaptureGeometry';
23
+ import { advanceAutoCaptureShutter, createAutoCaptureShutterState, openManualBurst, retryAutoCaptureShutter, } from './autoCaptureShutter';
24
+ import { resolveAutoCapture } from './autoCaptureOptions';
25
+ import { accumulateFrame, buildAttemptMetadata, createAttemptAccumulator, retryAttempt, toFileMetadata, } from './autoCaptureMetadata';
21
26
  import { reduceDocumentCapture } from './reducer';
22
27
  import { buildEntries, createInitialDocumentCaptureState, toCapturedDocument, } from './state';
23
- /** Default frame grab: draw the current video frame and encode it as a JPEG. */
24
- function defaultCaptureFrame(video) {
28
+ /**
29
+ * The focus score of a frame nothing could rank.
30
+ *
31
+ * Below every real reading, including a genuine 0.0, so an unranked frame
32
+ * always loses to a measured one. It can still win when nothing is banked —
33
+ * an unranked frame beats no frame at all.
34
+ */
35
+ const UNRANKED_FOCUS = -1;
36
+ /**
37
+ * Default frame grab: crop the source to the guide rect and encode a JPEG.
38
+ *
39
+ * Cropped to the GUIDE RECT when the document declares an `aspectRatio`, so
40
+ * the submitted image is the rectangle the applicant was asked to fill rather
41
+ * than everything the sensor happened to see. Uncropped a 16:9 webcam submits
42
+ * a photo of the desk with the page in the middle, and even a phone submits
43
+ * ~20% of frame height the applicant never saw.
44
+ *
45
+ * This is the same rect the gate measures against, and that is deliberate:
46
+ * "what you framed is what you submit" only holds while the two agree.
47
+ *
48
+ * The `drawImage` is SYNCHRONOUS and must stay that way — `captureSource` can
49
+ * hand over the auto-capture engine's live frame canvas, which the next frame
50
+ * overwrites. Everything before the `toBlob` runs in the caller's own tick.
51
+ */
52
+ function defaultCaptureFrame(source, aspectRatio) {
53
+ const rect = computeGuideRect(source.width, source.height, aspectRatio);
25
54
  const canvas = document.createElement('canvas');
26
- canvas.width = video.videoWidth;
27
- canvas.height = video.videoHeight;
55
+ canvas.width = rect.width;
56
+ canvas.height = rect.height;
28
57
  const ctx = canvas.getContext('2d');
29
58
  if (!ctx)
30
59
  return Promise.resolve(null);
31
- ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
60
+ ctx.drawImage(source.image, rect.x, rect.y, rect.width, rect.height, 0, 0, rect.width, rect.height);
32
61
  return new Promise((resolve) => canvas.toBlob(resolve, 'image/jpeg', 0.95));
33
62
  }
34
63
  // `acquireCamera` rejects with a `CaptureAttachError` carrying the precise
@@ -60,6 +89,8 @@ export function createDocumentCaptureController(config) {
60
89
  const acquire = config.io?.acquireCamera ?? acquireCamera;
61
90
  const captureFrame = config.io?.captureFrame ?? defaultCaptureFrame;
62
91
  const createObjectUrl = config.io?.createObjectUrl ?? ((blob) => URL.createObjectURL(blob));
92
+ const makeAutoCaptureEngine = config.io?.createAutoCaptureEngine ?? createAutoCaptureEngine;
93
+ const createCanvas = config.io?.createCanvas ?? (() => document.createElement('canvas'));
63
94
  const store = createStore(() => createInitialDocumentCaptureState(buildEntries(config.documents ?? [], createObjectUrl)));
64
95
  const listeners = new Set();
65
96
  // Which document indices have already emitted each callback. Cleared for an
@@ -71,6 +102,94 @@ export function createDocumentCaptureController(config) {
71
102
  let attachedVideo = null;
72
103
  let camera = null;
73
104
  let disposed = false;
105
+ // One engine per opted-in document, created on first need and torn down when
106
+ // the loop should not be running. Documents without an `autoCapture` bag
107
+ // never construct one, so a manual-shutter flow downloads no models.
108
+ let engine = null;
109
+ let engineIndex = null;
110
+ /**
111
+ * The sharpest satisfied frame seen in the current burst window.
112
+ *
113
+ * ONE canvas, not a ring of them. Six full-resolution candidates would be
114
+ * ~50 MB at the 1079x1920 a phone hands us, and an oversized canvas backing
115
+ * store is exactly what got the tab killed under pinch zoom. Keeping only
116
+ * the best-so-far is O(1) and loses nothing: the loop only ever needs the
117
+ * maximum, never the history.
118
+ *
119
+ * Lazily allocated, so a flow that never opts into auto-capture pays
120
+ * nothing.
121
+ */
122
+ /**
123
+ * `manualBurstWindowMs` for the engine currently running, or 0 for none.
124
+ *
125
+ * Reset by `stopAutoCapture`, so a tap arriving after a teardown falls back
126
+ * to saving the live frame rather than opening a window against an engine
127
+ * that will never close it.
128
+ */
129
+ let manualBurstWindowForEngine = 0;
130
+ /**
131
+ * Wall-clock length of the burst window currently open, or 0 for none.
132
+ *
133
+ * Held rather than recomputed, so what the view sweeps cannot drift from
134
+ * what the shutter is actually counting: the frame count is fixed when the
135
+ * window opens, and the measured rate moves afterwards.
136
+ *
137
+ * One number rather than one per document, because only the current
138
+ * document can have a window open — `stopAutoCapture` clears it, and that
139
+ * runs on every index change.
140
+ */
141
+ let manualBurstMs = 0;
142
+ let bestFrameCanvas = null;
143
+ let bestFrameFocus = UNRANKED_FOCUS;
144
+ /**
145
+ * The diagnostics of the banked frame — ITS PAIR, not the latest reading.
146
+ *
147
+ * `boundingBox` and `framing` claim to describe the submitted artifact, and
148
+ * the burst window runs through unsatisfied frames on purpose, so the last
149
+ * frame the engine saw can be one the applicant never submitted. Banking the
150
+ * pixels and their measurements together is what keeps the two describing
151
+ * the same moment.
152
+ */
153
+ let bestFrameDiagnostics = null;
154
+ // Per document, because a second document is a fresh framing problem and
155
+ // therefore a fresh escape budget. Keyed rather than reset on advance so a
156
+ // granted escape survives `uploadCompleted` moving the index and back.
157
+ const shutterByIndex = new Map();
158
+ // Per document too. Created LAZILY on the first frame, so a document that
159
+ // never ran an engine has `null` here and reports its auto-capture fields
160
+ // absent rather than zeroed.
161
+ const accumulatorByIndex = new Map();
162
+ // The last torn-down engine's ring buffer, so the log outlives the capture
163
+ // that ended the loop. Replaced wholesale by the next engine's drain rather
164
+ // than appended to, so two sessions never interleave in one export.
165
+ let lastAutoCaptureLog = [];
166
+ const documentOpenedAt = new Map();
167
+ /**
168
+ * Stamp when a document first became the current one, for `operationTime`.
169
+ * Set on the first frame or the first capture, whichever comes first, so a
170
+ * manual-only document still reports one.
171
+ */
172
+ function markDocumentOpen(index) {
173
+ if (!documentOpenedAt.has(index)) {
174
+ documentOpenedAt.set(index, now().getTime());
175
+ }
176
+ }
177
+ function accumulatorFor(index) {
178
+ const existing = accumulatorByIndex.get(index);
179
+ if (existing)
180
+ return existing;
181
+ const fresh = createAttemptAccumulator();
182
+ accumulatorByIndex.set(index, fresh);
183
+ return fresh;
184
+ }
185
+ function shutterFor(index) {
186
+ const existing = shutterByIndex.get(index);
187
+ if (existing)
188
+ return existing;
189
+ const fresh = createAutoCaptureShutterState();
190
+ shutterByIndex.set(index, fresh);
191
+ return fresh;
192
+ }
74
193
  function publish() {
75
194
  const snapshot = store.getState();
76
195
  for (const listener of listeners) {
@@ -85,6 +204,440 @@ export function createDocumentCaptureController(config) {
85
204
  function dispatch(event) {
86
205
  store.setState((state) => reduceDocumentCapture(state, event), true);
87
206
  publish();
207
+ // The engine's own per-frame dispatches must not re-enter this — they
208
+ // cannot change whether the loop should run, and re-entering would rebuild
209
+ // the engine from inside its own callback.
210
+ if (event.type !== 'autoCaptureFrame' && event.type !== 'videoDimensions') {
211
+ syncAutoCapture();
212
+ }
213
+ }
214
+ function stopAutoCapture() {
215
+ // Drain the ring buffer BEFORE dropping the engine. #341 makes the log the
216
+ // actual deliverable of a tuning session, and an accepted capture is what
217
+ // tears the engine down — so without this, COPY/SAVE LOG returns an empty
218
+ // array at exactly the moment an operator reaches for it.
219
+ const drained = engine?.getDiagnosticsLog();
220
+ if (drained && drained.length > 0)
221
+ lastAutoCaptureLog = drained;
222
+ engine?.stop();
223
+ engine = null;
224
+ engineIndex = null;
225
+ // The banked frame belongs to the engine that produced it. Carrying it
226
+ // across a teardown would let a retry, or the next document, submit a
227
+ // picture taken before either began.
228
+ clearBestFrame();
229
+ // So does an open burst window. The window counts down on EVERY frame,
230
+ // satisfied or not — which is what makes it tolerate focus excursions —
231
+ // so one left open across a detach would resume counting against the next
232
+ // engine's frames and fire a capture on frames that satisfied nothing.
233
+ manualBurstWindowForEngine = 0;
234
+ manualBurstMs = 0;
235
+ for (const [index, shutter] of shutterByIndex) {
236
+ if (shutter.burstFramesRemaining === null &&
237
+ shutter.manualBurstFramesRemaining === null) {
238
+ continue;
239
+ }
240
+ shutterByIndex.set(index, {
241
+ ...shutter,
242
+ burstFramesRemaining: null,
243
+ manualBurstFramesRemaining: null,
244
+ });
245
+ }
246
+ }
247
+ /**
248
+ * Start, stop, or re-target the detection loop to match current state.
249
+ *
250
+ * Called from `dispatch` rather than from each transition site, because four
251
+ * unrelated events move the answer — the camera arriving, a capture landing
252
+ * (the preview is up, there is nothing to detect), a retry clearing it, and
253
+ * `uploadCompleted` advancing to a document with a different `autoCapture`
254
+ * bag. Deriving it in one place is what stops the loop surviving into a
255
+ * document that never opted in.
256
+ */
257
+ function syncAutoCapture() {
258
+ if (disposed || !attachedVideo) {
259
+ stopAutoCapture();
260
+ return;
261
+ }
262
+ const state = store.getState();
263
+ const index = state.currentIndex;
264
+ const entry = state.documents[index];
265
+ const wanted = state.camera.ready && entry && !entry.content
266
+ ? entry.item.autoCapture
267
+ : undefined;
268
+ if (!wanted) {
269
+ stopAutoCapture();
270
+ return;
271
+ }
272
+ if (engine && engineIndex === index)
273
+ return;
274
+ stopAutoCapture();
275
+ engineIndex = index;
276
+ // Resolved once per engine rather than once per frame: the bag is
277
+ // mount-time-only, so re-resolving 17 times a second only allocates.
278
+ const { manualFallbackAfterMs, burstWindowMs, manualBurstWindowMs } = resolveAutoCapture(wanted, undefined);
279
+ // The tap arrives outside the frame loop and needs the same resolved bag,
280
+ // so it is held rather than re-resolved from a document that may since
281
+ // have advanced.
282
+ manualBurstWindowForEngine = manualBurstWindowMs;
283
+ // Captured so a late frame from a torn-down engine can identify itself.
284
+ // `const` is fine despite the self-reference inside `onDiagnostics`: that
285
+ // closure cannot run until the engine exists, so the binding is always
286
+ // initialised by the time it is read.
287
+ const thisEngine = makeAutoCaptureEngine({
288
+ ...config.autoCaptureEngine,
289
+ autoCapture: wanted,
290
+ // Same rect the capture crops to — see defaultCaptureFrame.
291
+ aspectRatio: entry.item.aspectRatio,
292
+ onModelsChanged: (models) => dispatch({ type: 'autoCaptureModelsChanged', models }),
293
+ onDiagnostics: (diagnostics) => {
294
+ // A frame already past `runFrame`'s own `stopped` checks can still land
295
+ // here after the engine has been torn down — by a capture landing, a
296
+ // detach, or the index advancing. Acting on it would spend the escape
297
+ // budget for a document that is no longer on screen and, worse, fire a
298
+ // SECOND capture over the one just accepted (`captureNow`'s own guards
299
+ // clear the moment `capturing` goes false again).
300
+ if (engine !== thisEngine)
301
+ return;
302
+ dispatch({
303
+ type: 'videoDimensions',
304
+ videoWidth: diagnostics.videoWidth,
305
+ videoHeight: diagnostics.videoHeight,
306
+ });
307
+ dispatch({ type: 'autoCaptureFrame', diagnostics });
308
+ markDocumentOpen(index);
309
+ accumulatorByIndex.set(index, accumulateFrame(accumulatorFor(index), diagnostics));
310
+ // BEFORE the shutter: the frame that closes the burst window is itself
311
+ // a candidate, and banking after the decision would exclude it.
312
+ bankBestFrame(diagnostics, shutterFor(index).manualBurstFramesRemaining !== null);
313
+ runShutter(index, manualFallbackAfterMs, burstWindowMs, diagnostics);
314
+ },
315
+ });
316
+ engine = thisEngine;
317
+ engine.start(attachedVideo);
318
+ }
319
+ /**
320
+ * Bank this frame if it is the sharpest candidate so far.
321
+ *
322
+ * Copies out of the engine's live frame canvas, which the next frame
323
+ * overwrites — so this has to happen synchronously, on the same tick as the
324
+ * diagnostics that scored it.
325
+ *
326
+ * A frame with no focus reading (model absent, or the gates skipped the
327
+ * prediction) scores -1 and can only win if nothing else has: better to
328
+ * carry an unranked candidate than to carry none.
329
+ *
330
+ * `anyFrame` is the applicant's tap talking. Auto-capture may only ever
331
+ * submit a frame that passed every gate — that guarantee is the entire point
332
+ * of the workstream — but the tap is a human deciding this framing is good
333
+ * enough, and it usually arrives BECAUSE the gates are unhappy. Ranking only
334
+ * satisfied frames there would leave the bank empty on exactly the captures
335
+ * this is meant to sharpen.
336
+ */
337
+ function bankBestFrame(diagnostics, anyFrame) {
338
+ if (!anyFrame && !diagnostics.satisfied)
339
+ return;
340
+ const graded = engine?.getGradedFrame();
341
+ if (!graded || graded.width <= 0 || graded.height <= 0)
342
+ return;
343
+ const focus = diagnostics.focus ? diagnostics.focus.score : UNRANKED_FOCUS;
344
+ // Tests for banked CONTENT rather than for the element. `clearBestFrame`
345
+ // keeps the canvas and zeroes it, so checking the element alone would let
346
+ // the first frame after every retry be rejected — and this is the same
347
+ // condition `captureSource` reads, so the two cannot disagree.
348
+ const hasBanked = !!bestFrameCanvas && bestFrameCanvas.width > 0;
349
+ if (hasBanked) {
350
+ // AMONG UNRANKED FRAMES, THE LATEST WINS. Everywhere else a candidate
351
+ // has to strictly beat the bank.
352
+ //
353
+ // Unranked means the whole window scored -1: the focus model failed to
354
+ // load, or no frame in it had a detected box to crop a prediction from.
355
+ // One of them still has to win, and later is the better default, because
356
+ // the tap that opened the window is also what shook the phone — keeping
357
+ // the first would hand back the jostle itself.
358
+ //
359
+ // Ranked ties keep the bank, which is not a detail: a burst of equal
360
+ // scores would otherwise redraw a full-resolution canvas on every frame
361
+ // to arrive at the same picture.
362
+ const beatsBank = focus === UNRANKED_FOCUS
363
+ ? bestFrameFocus === UNRANKED_FOCUS
364
+ : focus > bestFrameFocus;
365
+ if (!beatsBank)
366
+ return;
367
+ }
368
+ if (!bestFrameCanvas)
369
+ bestFrameCanvas = createCanvas();
370
+ if (bestFrameCanvas.width !== graded.width ||
371
+ bestFrameCanvas.height !== graded.height) {
372
+ bestFrameCanvas.width = graded.width;
373
+ bestFrameCanvas.height = graded.height;
374
+ }
375
+ const ctx = bestFrameCanvas.getContext('2d');
376
+ if (!ctx)
377
+ return;
378
+ ctx.drawImage(graded, 0, 0);
379
+ bestFrameFocus = focus;
380
+ // Same assignment, same tick: the pair is what makes the metadata honest.
381
+ bestFrameDiagnostics = diagnostics;
382
+ }
383
+ /**
384
+ * Open the applicant's burst window, or report that there is none to open.
385
+ *
386
+ * False means "capture right now", which covers every case the window
387
+ * cannot serve: no engine, no measured frame rate to convert the window
388
+ * with, `manualBurstWindowMs: 0`, or a capture already in flight.
389
+ */
390
+ function openManualBurstFor(index) {
391
+ if (!engine || engineIndex !== index)
392
+ return false;
393
+ const state = store.getState();
394
+ if (state.capturing || !state.camera.ready)
395
+ return false;
396
+ const shutter = shutterFor(index);
397
+ // A second tap must not restart the wait it is impatient with.
398
+ if (shutter.manualBurstFramesRemaining !== null)
399
+ return true;
400
+ const frameRate = state.autoCapture?.frameRate ?? 0;
401
+ const next = openManualBurst(shutter, frameRate, manualBurstWindowForEngine);
402
+ if (next.manualBurstFramesRemaining === null)
403
+ return false;
404
+ // What the view sweeps. Derived from the FRAME COUNT, not from the setting
405
+ // it was converted out of, so the ring finishes when the shutter fires
406
+ // rather than a rounding error before it.
407
+ manualBurstMs = (next.manualBurstFramesRemaining / frameRate) * 1000;
408
+ shutterByIndex.set(index, next);
409
+ // Focus normally runs only on frames that already passed every other gate,
410
+ // which is the loop's biggest saving and is exactly wrong here: a tap
411
+ // arrives BECAUSE the gates are unhappy, so without this every frame in
412
+ // the window scores `null` and the ranking has nothing to rank. It stays
413
+ // on for the length of the window and no longer.
414
+ engine.setMeasureFocusEveryFrame(true);
415
+ publishShutter(index);
416
+ // Whatever the auto path banked belongs to the moment BEFORE the tap. The
417
+ // window is allowed to rank unsatisfied frames precisely because they are
418
+ // the applicant's own; letting a pre-tap satisfied frame win would submit
419
+ // a photo they did not take, and would do it while calling it 'Manual'.
420
+ clearBestFrame();
421
+ return true;
422
+ }
423
+ /** Drop the banked frame and release its backing store. */
424
+ function clearBestFrame() {
425
+ bestFrameFocus = UNRANKED_FOCUS;
426
+ bestFrameDiagnostics = null;
427
+ if (!bestFrameCanvas)
428
+ return;
429
+ // Zeroing frees the pixels; keeping the element avoids re-allocating one
430
+ // per attempt.
431
+ bestFrameCanvas.width = 0;
432
+ bestFrameCanvas.height = 0;
433
+ }
434
+ /**
435
+ * Advance the shutter for `index` and act on its decision.
436
+ *
437
+ * Runs AFTER the frame has been dispatched, so a consumer watching state sees
438
+ * the reading that fired the capture rather than the one before it.
439
+ */
440
+ function runShutter(index, manualFallbackAfterMs, burstWindowMs, diagnostics) {
441
+ const decision = advanceAutoCaptureShutter(shutterFor(index), {
442
+ satisfied: diagnostics.satisfied,
443
+ timeRunning: diagnostics.timeRunning,
444
+ frameRate: diagnostics.frameRate,
445
+ }, manualFallbackAfterMs, burstWindowMs);
446
+ shutterByIndex.set(index, decision.state);
447
+ if (decision.revealManualShutter)
448
+ publishShutter(index);
449
+ // The window closing is a state change the view renders: it holds the
450
+ // shutter pressed for as long as one is open.
451
+ if (decision.captureManual) {
452
+ engine?.setMeasureFocusEveryFrame(false);
453
+ manualBurstMs = 0;
454
+ publishShutter(index);
455
+ }
456
+ // `capture()` re-guards on `capturing` and on the camera, so a shutter that
457
+ // fires twice before the first frame grab resolves is a no-op, not a race.
458
+ if (decision.capture)
459
+ void captureNow('Auto', true);
460
+ // The applicant's own window closing. Still `'Manual'` — the tap is what
461
+ // took this photo, and the window only chose which of its frames to keep.
462
+ if (decision.captureManual)
463
+ void captureNow('Manual', true);
464
+ }
465
+ /** Mirror the shutter's public half onto state for the view to render. */
466
+ function publishShutter(index) {
467
+ const shutter = shutterByIndex.get(index);
468
+ if (!shutter)
469
+ return;
470
+ dispatch({
471
+ type: 'autoCaptureShutterChanged',
472
+ shutter: {
473
+ manualShutterAvailable: shutter.manualShutterAvailable,
474
+ manualBurstMs: shutter.manualBurstFramesRemaining !== null ? manualBurstMs : null,
475
+ },
476
+ });
477
+ }
478
+ /**
479
+ * Grab a frame and record HOW it was triggered.
480
+ *
481
+ * `'Auto'` vs `'Manual'` is the first honest use of that distinction in this
482
+ * SDK — `selfieCapture/controller.ts` stamps 'Y' even on its manual button —
483
+ * and it is what makes "auto-capture gave up" countable.
484
+ */
485
+ /**
486
+ * Which pixels this capture saves.
487
+ *
488
+ * An AUTO capture saves the frame the gates were measured on, not the live
489
+ * video. The loop draws a frame, then awaits detection and focus before the
490
+ * shutter sees its verdict — so by the time `captureNow` runs, the video
491
+ * element is an inference round-trip ahead of the image that was certified
492
+ * sharp and stable. At the 15-35 fps this model runs at that is 60-120 ms of
493
+ * hand motion between "in focus" and the shutter, and it is the difference
494
+ * between a focus gate that means something and one that grades a photo
495
+ * nobody submits.
496
+ *
497
+ * A MANUAL capture with no window keeps the live video: the tap is the
498
+ * applicant's intent, expressed at a moment of their choosing, and handing
499
+ * them a frame from before the tap would be the same bug pointed the other
500
+ * way. With `manualBurstWindowMs` set it reads the bank too — but that bank
501
+ * only ever holds frames from AFTER the tap, so the property survives.
502
+ *
503
+ * The engine's canvas is live and the next frame overwrites it, so this is
504
+ * only sound because the whole path from `onDiagnostics` to the `drawImage`
505
+ * inside `captureFrame` is synchronous — no `await` runs in between, so the
506
+ * loop cannot have advanced. `controller.test.ts` pins that.
507
+ */
508
+ /**
509
+ * The pixels this capture saves, WITH the diagnostics that describe them.
510
+ *
511
+ * Returned as one value on purpose. `boundingBox` and `framing` claim to
512
+ * describe the submitted artifact, and both the burst window and the JPEG
513
+ * encode let the loop advance between choosing a frame and finishing with
514
+ * it — so anything that re-reads "the latest frame" later is describing a
515
+ * different moment. Resolved together, synchronously, before either.
516
+ */
517
+ function captureSource(graded) {
518
+ const video = attachedVideo;
519
+ if (!video)
520
+ return null;
521
+ if (graded) {
522
+ // The sharpest frame of the burst window, when there is one. Firing on
523
+ // the frame that happened to close the window would be back to sampling
524
+ // focus at an arbitrary moment.
525
+ const banked = bestFrameCanvas;
526
+ if (banked && banked.width > 0 && banked.height > 0) {
527
+ return {
528
+ source: { image: banked, width: banked.width, height: banked.height },
529
+ acceptedFrame: bestFrameDiagnostics,
530
+ };
531
+ }
532
+ const graded = engine?.getGradedFrame();
533
+ if (graded) {
534
+ return {
535
+ source: { image: graded, width: graded.width, height: graded.height },
536
+ // Not banked, so the frame the engine last reported IS this one.
537
+ acceptedFrame: store.getState().autoCapture ?? null,
538
+ };
539
+ }
540
+ }
541
+ return {
542
+ source: { image: video, width: video.videoWidth, height: video.videoHeight },
543
+ acceptedFrame: null,
544
+ };
545
+ }
546
+ /**
547
+ * `graded` chooses the PIXELS: the frame the models measured, or the live
548
+ * video element.
549
+ *
550
+ * A separate argument from `mode` because the two stopped being the same
551
+ * question once the applicant's tap grew a window of its own. `mode` records
552
+ * who pressed the shutter and reaches the backend as `autoCapture` Y/N;
553
+ * `graded` records which pixels won, and a tap that waited out its window is
554
+ * `'Manual'` on graded pixels.
555
+ */
556
+ async function captureNow(mode, graded) {
557
+ if (disposed || !attachedVideo)
558
+ return;
559
+ const index = store.getState().currentIndex;
560
+ markDocumentOpen(index);
561
+ // A capture with no camera grabs an empty frame and reports a spurious
562
+ // CAPTURE_FAILED; a re-entrant one races two frames into one slot. The
563
+ // view guards both, but the controller is public API and a custom UI can
564
+ // call straight in — as, now, can the auto shutter.
565
+ const current = store.getState();
566
+ if (current.capturing || !current.camera.ready)
567
+ return;
568
+ // BEFORE the dispatch, which can re-enter `syncAutoCapture` and drop the
569
+ // engine whose canvas this is.
570
+ const chosen = captureSource(graded);
571
+ if (!chosen)
572
+ return;
573
+ const { source, acceptedFrame } = chosen;
574
+ dispatch({ type: 'captureRequested' });
575
+ try {
576
+ // The guide-rect crop is part of the OPT-IN. It is the right image for a
577
+ // flow that asked the applicant to fill a guide box, but for a 2.x
578
+ // integrator who passes `aspectRatio` and nothing else it silently
579
+ // changes the bytes they have been receiving since 2.4 — different
580
+ // dimensions, different field of view, into whatever their backend does
581
+ // with them. Spec §3.1: omitting `autoCapture` means today's behaviour.
582
+ const item = store.getState().documents[index]?.item;
583
+ const content = await captureFrame(source, item?.autoCapture ? item.aspectRatio : undefined);
584
+ // Detached mid-capture: dispatching now would mutate a dead controller's
585
+ // store and leak the object URL.
586
+ if (disposed)
587
+ return;
588
+ if (!content) {
589
+ dispatch({
590
+ type: 'captureFailed',
591
+ message: 'The camera returned no frame.',
592
+ });
593
+ return;
594
+ }
595
+ dispatch({
596
+ type: 'captureCompleted',
597
+ content,
598
+ contentUrl: createObjectUrl(content),
599
+ captureMode: mode,
600
+ captureMetadata: buildCaptureMetadata(index, mode, acceptedFrame),
601
+ });
602
+ emitLifecycle();
603
+ }
604
+ catch (error) {
605
+ dispatch({
606
+ type: 'captureFailed',
607
+ message: error instanceof Error ? error.message : String(error),
608
+ });
609
+ }
610
+ }
611
+ /**
612
+ * Why auto-capture was, or was not, the thing that fired (#377).
613
+ *
614
+ * The SDK can only report the reasons it can see. `disabled:flag`,
615
+ * `disabled:param` and `disabled:lateFlag` are host-side facts — the host
616
+ * simply does not bind `autoCapture` — so from here they are all
617
+ * `disabled:unconfigured`, and the host distinguishes them on channel B
618
+ * before aggregating. `disabled:lateFlag` is additionally warned about at
619
+ * the flow layer, where the change is actually observable.
620
+ */
621
+ function autoCaptureStatus(mode) {
622
+ const state = store.getState();
623
+ const entry = state.documents[state.currentIndex];
624
+ if (!entry?.item.autoCapture)
625
+ return 'disabled:unconfigured';
626
+ if (state.models.state === 'error')
627
+ return 'disabled:modelLoadFailed';
628
+ if (mode === 'Manual' && state.autoCaptureShutter?.manualShutterAvailable) {
629
+ return 'timedOutToManual';
630
+ }
631
+ return 'engaged';
632
+ }
633
+ function buildCaptureMetadata(index, mode, acceptedFrame) {
634
+ const openedAt = documentOpenedAt.get(index);
635
+ return buildAttemptMetadata(accumulatorByIndex.get(index) ?? null, {
636
+ captureMode: mode,
637
+ autoCaptureStatus: autoCaptureStatus(mode),
638
+ operationTime: openedAt === undefined ? null : Math.round(now().getTime() - openedAt),
639
+ acceptedFrame,
640
+ });
88
641
  }
89
642
  function currentEntry() {
90
643
  const state = store.getState();
@@ -155,9 +708,13 @@ export function createDocumentCaptureController(config) {
155
708
  // A pre-supplied blob is already "captured" as far as consumers are
156
709
  // concerned, so its callback fires as soon as the controller is live.
157
710
  emitLifecycle();
711
+ // Re-attach revives a detached controller whose camera is still live, so
712
+ // no `cameraReady` dispatch follows to start the loop for us.
713
+ syncAutoCapture();
158
714
  },
159
715
  detach() {
160
716
  disposed = true;
717
+ stopAutoCapture();
161
718
  camera?.release();
162
719
  camera = null;
163
720
  attachedVideo = null;
@@ -168,6 +725,12 @@ export function createDocumentCaptureController(config) {
168
725
  // detaches.
169
726
  },
170
727
  getState: () => store.getState(),
728
+ getAutoCaptureLog: () => {
729
+ // A running engine is always the fresher of the two; the retained copy
730
+ // only answers once the loop has stopped.
731
+ const live = engine?.getDiagnosticsLog();
732
+ return live && live.length > 0 ? live : lastAutoCaptureLog;
733
+ },
171
734
  subscribe(cb) {
172
735
  listeners.add(cb);
173
736
  return () => {
@@ -182,43 +745,22 @@ export function createDocumentCaptureController(config) {
182
745
  collectArtifacts: () => ({}),
183
746
  actions: {
184
747
  requestCamera,
185
- async capture() {
186
- if (disposed || !attachedVideo)
748
+ /**
749
+ * The applicant tapped.
750
+ *
751
+ * Pressing the screen moves the phone, so the frame the tap lands on is
752
+ * among the worst available. When an engine is running, the tap opens a
753
+ * short window and the sharpest frame in it is what gets saved — see
754
+ * `DEFAULT_MANUAL_BURST_WINDOW_MS`. Without an engine there is nothing
755
+ * to rank frames with, and this is the plain shutter it has always been.
756
+ */
757
+ capture: async () => {
758
+ if (disposed)
187
759
  return;
188
- // A capture with no camera grabs an empty frame and reports a spurious
189
- // CAPTURE_FAILED; a re-entrant one races two frames into one slot. The
190
- // view guards both, but the controller is public API and a custom UI
191
- // can call straight in.
192
- const current = store.getState();
193
- if (current.capturing || !current.camera.ready)
760
+ const index = store.getState().currentIndex;
761
+ if (openManualBurstFor(index))
194
762
  return;
195
- dispatch({ type: 'captureRequested' });
196
- try {
197
- const content = await captureFrame(attachedVideo);
198
- // Detached mid-capture: dispatching now would mutate a dead
199
- // controller's store and leak the object URL.
200
- if (disposed)
201
- return;
202
- if (!content) {
203
- dispatch({
204
- type: 'captureFailed',
205
- message: 'The camera returned no frame.',
206
- });
207
- return;
208
- }
209
- dispatch({
210
- type: 'captureCompleted',
211
- content,
212
- contentUrl: createObjectUrl(content),
213
- });
214
- emitLifecycle();
215
- }
216
- catch (error) {
217
- dispatch({
218
- type: 'captureFailed',
219
- message: error instanceof Error ? error.message : String(error),
220
- });
221
- }
763
+ await captureNow('Manual', false);
222
764
  },
223
765
  retry() {
224
766
  if (disposed)
@@ -228,7 +770,22 @@ export function createDocumentCaptureController(config) {
228
770
  uploadedFired.delete(index);
229
771
  // The "all uploaded" guarantee no longer holds once an entry reverts.
230
772
  allUploadedFired = false;
773
+ // Re-arms auto-capture and resets the escape budget, but leaves a
774
+ // granted escape granted — see retryAutoCaptureShutter.
775
+ const shutter = shutterByIndex.get(index);
776
+ if (shutter)
777
+ shutterByIndex.set(index, retryAutoCaptureShutter(shutter));
778
+ // `attemptCount` must survive the retry, or the upload channel reports
779
+ // every capture as first-try — which looks like a valid measurement.
780
+ const accumulator = accumulatorByIndex.get(index);
781
+ if (accumulator) {
782
+ accumulatorByIndex.set(index, retryAttempt(accumulator));
783
+ }
784
+ // The rejected attempt's best frame is exactly what the applicant is
785
+ // retrying to get away from.
786
+ clearBestFrame();
231
787
  dispatch({ type: 'retryCapture' });
788
+ publishShutter(index);
232
789
  },
233
790
  async upload() {
234
791
  if (disposed)
@@ -247,6 +804,13 @@ export function createDocumentCaptureController(config) {
247
804
  metadata.jobid = config.jobID;
248
805
  if (config.taskID)
249
806
  metadata.taskid = config.taskID;
807
+ // Channel A. A proven field — the backend signature-video trimmer
808
+ // already reads it on another document type — and a bounded one: see
809
+ // `toFileMetadata` on the 2 KB tusd/S3 cap and the non-ASCII mangling
810
+ // that make a scalar spine the only safe payload.
811
+ if (entry.captureMetadata) {
812
+ metadata.filemetadata = toFileMetadata(entry.captureMetadata);
813
+ }
250
814
  try {
251
815
  const documentId = await config.client.uploadDocument(entry.content, metadata);
252
816
  // Detached mid-upload (session drop, view unmount): advancing the