biometry-react-components 1.4.0 → 2.0.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.
package/dist/index.js CHANGED
@@ -1,19 +1,60 @@
1
1
  'use strict';var jsxRuntime=require('react/jsx-runtime'),React=require('react');const DocScan = ({ rectWidth = 640, rectHeight = 400, onConfirmCapture, onCapture, className, style, noShadow = false, }) => {
2
+ var _a;
2
3
  const [isConfirming, setIsConfirming] = React.useState(false);
3
4
  const [capturedUrl, setCapturedUrl] = React.useState(null);
4
5
  const [capturedFile, setCapturedFile] = React.useState(null);
5
6
  const videoRef = React.useRef(null);
6
7
  const streamRef = React.useRef(null);
8
+ const [devices, setDevices] = React.useState([]);
9
+ const [selectedDeviceId, setSelectedDeviceId] = React.useState(null);
10
+ const [isFrontCamera, setIsFrontCamera] = React.useState(false);
11
+ const [capabilities, setCapabilities] = React.useState({});
12
+ const [torchOn, setTorchOn] = React.useState(false);
7
13
  const QUALITY_MULTIPLIER = 3;
8
14
  // Crop area (dashed area) as percentages
9
15
  const cropTop = 0.075, cropLeft = 0.075, cropWidth = 0.85, cropHeight = 0.85;
16
+ const getDevices = async () => {
17
+ try {
18
+ const all = await navigator.mediaDevices.enumerateDevices();
19
+ return all.filter((d) => d.kind === "videoinput");
20
+ }
21
+ catch (_a) {
22
+ return [];
23
+ }
24
+ };
25
+ React.useEffect(() => {
26
+ const handleDeviceChange = async () => {
27
+ const vids = await getDevices();
28
+ setDevices(vids);
29
+ if (selectedDeviceId && !vids.find((d) => d.deviceId === selectedDeviceId)) {
30
+ // Active device disconnected, clear it to fallback to default
31
+ setSelectedDeviceId(null);
32
+ }
33
+ };
34
+ navigator.mediaDevices.addEventListener("devicechange", handleDeviceChange);
35
+ return () => navigator.mediaDevices.removeEventListener("devicechange", handleDeviceChange);
36
+ }, [selectedDeviceId]);
10
37
  React.useEffect(() => {
11
38
  let isMounted = true;
12
39
  if (!isConfirming) {
13
40
  (async () => {
14
41
  try {
15
- const stream = await navigator.mediaDevices.getUserMedia({ video: { width: rectWidth, height: rectHeight } });
16
- if (videoRef.current && isMounted) {
42
+ const videoConstraints = {
43
+ width: rectWidth,
44
+ height: rectHeight,
45
+ };
46
+ if (selectedDeviceId) {
47
+ videoConstraints.deviceId = { exact: selectedDeviceId };
48
+ }
49
+ else {
50
+ videoConstraints.facingMode = "environment";
51
+ }
52
+ const stream = await navigator.mediaDevices.getUserMedia({ video: videoConstraints });
53
+ if (!isMounted) {
54
+ stream.getTracks().forEach((track) => track.stop());
55
+ return;
56
+ }
57
+ if (videoRef.current) {
17
58
  videoRef.current.srcObject = stream;
18
59
  videoRef.current.onloadedmetadata = () => {
19
60
  var _a;
@@ -21,6 +62,40 @@
21
62
  };
22
63
  }
23
64
  streamRef.current = stream;
65
+ const track = stream.getVideoTracks()[0];
66
+ if (track) {
67
+ if (track.getCapabilities) {
68
+ setCapabilities(track.getCapabilities());
69
+ }
70
+ const settings = track.getSettings();
71
+ let isFront = false;
72
+ if (settings.facingMode) {
73
+ isFront = settings.facingMode === "user";
74
+ }
75
+ else {
76
+ const allVids = await getDevices();
77
+ const currDev = allVids.find(d => d.deviceId === settings.deviceId);
78
+ if (currDev)
79
+ isFront = currDev.label.toLowerCase().includes("front");
80
+ }
81
+ if (isMounted)
82
+ setIsFrontCamera(isFront);
83
+ if (!selectedDeviceId) {
84
+ const currentId = track.getSettings().deviceId;
85
+ if (currentId && isMounted)
86
+ setSelectedDeviceId(currentId);
87
+ }
88
+ track.onended = async () => {
89
+ if (!isMounted)
90
+ return;
91
+ const vids = await getDevices();
92
+ setDevices(vids);
93
+ setSelectedDeviceId(null);
94
+ };
95
+ }
96
+ const vids = await getDevices();
97
+ if (isMounted)
98
+ setDevices(vids);
24
99
  }
25
100
  catch (err) {
26
101
  console.error(err);
@@ -34,7 +109,7 @@
34
109
  streamRef.current = null;
35
110
  }
36
111
  };
37
- }, [isConfirming, rectWidth, rectHeight]);
112
+ }, [isConfirming, rectWidth, rectHeight, selectedDeviceId]);
38
113
  const handleCapture = () => {
39
114
  const video = videoRef.current;
40
115
  if (!video)
@@ -49,18 +124,20 @@
49
124
  const targetAspect = rectWidth / rectHeight;
50
125
  let sx = 0, sy = 0, sw = video.videoWidth, sh = video.videoHeight;
51
126
  if (videoAspect > targetAspect) {
52
- // Video is wider than target: crop sides
53
127
  sw = video.videoHeight * targetAspect;
54
128
  sx = (video.videoWidth - sw) / 2;
55
129
  }
56
130
  else {
57
- // Video is taller than target: crop top/bottom
58
131
  sh = video.videoWidth / targetAspect;
59
132
  sy = (video.videoHeight - sh) / 2;
60
133
  }
61
134
  ctx.drawImage(video, sx, sy, sw, sh, 0, 0, canvas.width, canvas.height);
62
135
  canvas.toBlob((blob) => {
63
136
  if (blob) {
137
+ if (streamRef.current) {
138
+ streamRef.current.getTracks().forEach((track) => track.stop());
139
+ streamRef.current = null;
140
+ }
64
141
  const file = new File([blob], "document.jpg", { type: "image/jpeg" });
65
142
  setCapturedFile(file);
66
143
  setCapturedUrl(URL.createObjectURL(blob));
@@ -70,7 +147,7 @@
70
147
  onCapture(file);
71
148
  }
72
149
  catch (err) {
73
- console.error('onCapture callback threw:', err);
150
+ console.error(err);
74
151
  }
75
152
  }
76
153
  }
@@ -90,6 +167,53 @@
90
167
  setCapturedFile(null);
91
168
  setIsConfirming(false);
92
169
  };
170
+ const cycleCamera = (e) => {
171
+ e.stopPropagation();
172
+ if (devices.length <= 1)
173
+ return;
174
+ const currentIndex = devices.findIndex((d) => d.deviceId === selectedDeviceId);
175
+ const nextIndex = (currentIndex + 1) % devices.length;
176
+ setSelectedDeviceId(devices[nextIndex].deviceId);
177
+ setTorchOn(false);
178
+ };
179
+ const toggleTorch = async (e) => {
180
+ e.stopPropagation();
181
+ if (!streamRef.current)
182
+ return;
183
+ const track = streamRef.current.getVideoTracks()[0];
184
+ if (track && capabilities.torch) {
185
+ try {
186
+ const nextTorch = !torchOn;
187
+ await track.applyConstraints({ advanced: [{ torch: nextTorch }] });
188
+ setTorchOn(nextTorch);
189
+ }
190
+ catch (err) {
191
+ console.error("Torch toggle failed:", err);
192
+ }
193
+ }
194
+ };
195
+ const handleCameraAreaClick = async (e) => {
196
+ if (!streamRef.current)
197
+ return;
198
+ const track = streamRef.current.getVideoTracks()[0];
199
+ if (track && capabilities.focusMode) {
200
+ const focusType = capabilities.focusMode.includes("single-shot") ? "single-shot" : capabilities.focusMode.includes("manual") ? "manual" : null;
201
+ if (!focusType)
202
+ return;
203
+ const rect = e.currentTarget.getBoundingClientRect();
204
+ let x = (e.clientX - rect.left) / rect.width;
205
+ const y = (e.clientY - rect.top) / rect.height;
206
+ if (isFrontCamera) {
207
+ x = 1 - x;
208
+ }
209
+ try {
210
+ await track.applyConstraints({ advanced: [{ focusMode: focusType, pointsOfInterest: [{ x, y }] }] });
211
+ }
212
+ catch (err) {
213
+ console.error("Focus failed:", err);
214
+ }
215
+ }
216
+ };
93
217
  const wrapperStyle = {
94
218
  background: '#fff',
95
219
  borderRadius: noShadow ? 0 : 10,
@@ -112,6 +236,7 @@
112
236
  display: 'flex',
113
237
  alignItems: 'center',
114
238
  justifyContent: 'center',
239
+ cursor: ((_a = capabilities.focusMode) === null || _a === void 0 ? void 0 : _a.includes("manual")) ? "crosshair" : "default"
115
240
  };
116
241
  const defaultDashedArea = {
117
242
  position: 'absolute',
@@ -127,6 +252,7 @@
127
252
  display: 'flex',
128
253
  flexDirection: 'column',
129
254
  alignItems: 'center',
255
+ pointerEvents: 'none'
130
256
  };
131
257
  const defaultGuidanceText = {
132
258
  color: '#fff',
@@ -178,13 +304,34 @@
178
304
  transition: 'background 0.2s',
179
305
  margin: '0 8px',
180
306
  };
181
- return (jsxRuntime.jsx("div", { className: className, style: wrapperStyle, children: !isConfirming ? (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsxs("div", { className: "docscan-camera-area", style: defaultCameraArea, children: [jsxRuntime.jsx("video", { ref: videoRef, width: rectWidth - 40, height: rectHeight - 40, className: "docscan-video", style: {
307
+ const controlsOverlayStyle = {
308
+ position: 'absolute',
309
+ top: 8,
310
+ right: 8,
311
+ zIndex: 3,
312
+ display: 'flex',
313
+ flexDirection: 'column',
314
+ gap: 12,
315
+ };
316
+ const overlayBtnStyle = {
317
+ background: 'rgba(0,0,0,0.5)',
318
+ border: 'none',
319
+ borderRadius: '50%',
320
+ width: 36,
321
+ height: 36,
322
+ display: 'flex',
323
+ alignItems: 'center',
324
+ justifyContent: 'center',
325
+ cursor: 'pointer',
326
+ color: '#fff',
327
+ };
328
+ return (jsxRuntime.jsx("div", { className: className, style: wrapperStyle, children: !isConfirming ? (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsxs("div", { className: "docscan-camera-area", style: defaultCameraArea, onClick: handleCameraAreaClick, children: [jsxRuntime.jsxs("div", { style: controlsOverlayStyle, children: [devices.length > 1 && (jsxRuntime.jsx("button", { type: "button", onClick: cycleCamera, style: overlayBtnStyle, title: "Switch Camera", children: jsxRuntime.jsxs("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [jsxRuntime.jsx("path", { d: "M21 12A9 9 0 0 0 6 5.3L3 8" }), jsxRuntime.jsx("path", { d: "M21 3v5h-5" }), jsxRuntime.jsx("path", { d: "M3 12a9 9 0 0 0 15 6.7l3-2.7" }), jsxRuntime.jsx("path", { d: "M3 21v-5h5" })] }) })), capabilities.torch && (jsxRuntime.jsx("button", { type: "button", onClick: toggleTorch, style: { ...overlayBtnStyle, color: torchOn ? '#ffd700' : '#fff' }, title: "Toggle Flash", children: jsxRuntime.jsx("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: jsxRuntime.jsx("polygon", { points: "13 2 3 14 12 14 11 22 21 10 12 10 13 2" }) }) }))] }), jsxRuntime.jsx("video", { ref: videoRef, width: rectWidth - 40, height: rectHeight - 40, className: "docscan-video", style: {
182
329
  width: rectWidth - 40,
183
330
  height: rectHeight - 40,
184
331
  objectFit: 'cover',
185
332
  borderRadius: noShadow ? 0 : 8,
186
333
  zIndex: 0,
187
- transform: 'scaleX(-1)'
334
+ transform: isFrontCamera ? 'scaleX(-1)' : 'none'
188
335
  }, playsInline: true, muted: true, autoPlay: true }), jsxRuntime.jsx("div", { className: "docscan-dark-overlay", style: {
189
336
  position: 'absolute',
190
337
  top: 0,
@@ -194,6 +341,7 @@
194
341
  background: 'rgba(0,0,0,0.4)',
195
342
  zIndex: 1,
196
343
  borderRadius: noShadow ? 0 : 8,
344
+ pointerEvents: 'none'
197
345
  } }), jsxRuntime.jsx("div", { className: "docscan-dashed-area", style: defaultDashedArea, children: jsxRuntime.jsx("span", { className: "docscan-guidance-text", style: defaultGuidanceText, children: "Place your document here" }) })] }), jsxRuntime.jsx("button", { type: "button", className: "docscan-capture-btn", style: defaultCaptureButton, onClick: handleCapture, children: "Capture" })] })) : (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("div", { className: "docscan-preview", style: defaultPreview, children: capturedUrl && (jsxRuntime.jsx("img", { src: capturedUrl, alt: "Captured document", className: "docscan-preview-img", style: { maxWidth: '100%', maxHeight: '100%', borderRadius: 8 } })) }), jsxRuntime.jsx("div", { className: "docscan-confirm-text", style: defaultConfirmText, children: "Do you want to use this photo?" }), jsxRuntime.jsxs("div", { className: "docscan-confirm-btns", style: { display: 'flex', justifyContent: 'center', gap: 32, marginTop: 16, width: '100%' }, children: [jsxRuntime.jsx("button", { type: "button", "aria-label": "Retake", className: "docscan-icon-btn", style: defaultIconButton, onClick: handleDecline, onMouseOver: e => (e.currentTarget.style.background = 'rgba(211,47,47,0.12)'), onMouseOut: e => (e.currentTarget.style.background = 'none'), children: jsxRuntime.jsxs("svg", { width: "36", height: "36", viewBox: "0 0 36 36", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: [jsxRuntime.jsx("circle", { cx: "18", cy: "18", r: "18", fill: "#fff", fillOpacity: "0.15" }), jsxRuntime.jsx("path", { d: "M12 12L24 24", stroke: "#d32f2f", strokeWidth: "3", strokeLinecap: "round" }), jsxRuntime.jsx("path", { d: "M24 12L12 24", stroke: "#d32f2f", strokeWidth: "3", strokeLinecap: "round" })] }) }), jsxRuntime.jsx("button", { type: "button", "aria-label": "Confirm", className: "docscan-icon-btn", style: defaultIconButton, onClick: handleConfirm, onMouseOver: e => (e.currentTarget.style.background = 'rgba(56,142,60,0.12)'), onMouseOut: e => (e.currentTarget.style.background = 'none'), children: jsxRuntime.jsxs("svg", { width: "36", height: "36", viewBox: "0 0 36 36", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: [jsxRuntime.jsx("circle", { cx: "18", cy: "18", r: "18", fill: "#fff", fillOpacity: "0.15" }), jsxRuntime.jsx("path", { d: "M10 19L16 25L26 13", stroke: "#388e3c", strokeWidth: "3", strokeLinecap: "round", strokeLinejoin: "round" })] }) })] })] })) }));
198
346
  };const FaceCapture = ({ rectWidth = 360, rectHeight = 576, onConfirmCapture, onCapture, className, style, noShadow = false, }) => {
199
347
  const [isConfirming, setIsConfirming] = React.useState(false);
@@ -208,7 +356,11 @@
208
356
  (async () => {
209
357
  try {
210
358
  const stream = await navigator.mediaDevices.getUserMedia({ video: { width: rectWidth, height: rectHeight } });
211
- if (videoRef.current && isMounted) {
359
+ if (!isMounted) {
360
+ stream.getTracks().forEach((track) => track.stop());
361
+ return;
362
+ }
363
+ if (videoRef.current) {
212
364
  videoRef.current.srcObject = stream;
213
365
  videoRef.current.onloadedmetadata = () => {
214
366
  var _a;
@@ -242,6 +394,11 @@
242
394
  ctx.drawImage(video, 0, 0, rectWidth, rectHeight, 0, 0, rectWidth * QUALITY_MULTIPLIER, rectHeight * QUALITY_MULTIPLIER);
243
395
  canvas.toBlob((blob) => {
244
396
  if (blob) {
397
+ // Stop the stream immediately — don't wait for useEffect cleanup
398
+ if (streamRef.current) {
399
+ streamRef.current.getTracks().forEach((track) => track.stop());
400
+ streamRef.current = null;
401
+ }
245
402
  const file = new File([blob], "face.jpg", { type: "image/jpeg" });
246
403
  setCapturedFile(file);
247
404
  setCapturedUrl(URL.createObjectURL(blob));
@@ -7058,7 +7215,78 @@ function requireRecordRTC () {
7058
7215
  } (RecordRTC$1));
7059
7216
  return RecordRTC$1.exports;
7060
7217
  }var RecordRTCExports = /*@__PURE__*/ requireRecordRTC();
7061
- var RecordRTC = /*@__PURE__*/getDefaultExportFromCjs(RecordRTCExports);function getSupportedMimeType() {
7218
+ var RecordRTC = /*@__PURE__*/getDefaultExportFromCjs(RecordRTCExports);/**
7219
+ * Digit challenge and phrase helpers, kept in step with
7220
+ * biometry-angular-components `src/lib/utils/numbers.ts`. The two packages must
7221
+ * produce the same `phrase` for the same digits: it is compared against what the
7222
+ * voice engine recognised, so a divergence here is a verification failure with no
7223
+ * obvious cause.
7224
+ */
7225
+ /**
7226
+ * Digits a generated challenge may contain.
7227
+ *
7228
+ * `0` is deliberately absent. A server-issued challenge may still contain one
7229
+ * while the backend rolls out, and numbersToPhrase tolerates that — but nothing
7230
+ * we generate emits it.
7231
+ */
7232
+ const CHALLENGE_DIGITS = [1, 2, 3, 4, 5, 6, 7, 8, 9];
7233
+ /**
7234
+ * Enrolment prompts, taken verbatim from the vendor guide's published set.
7235
+ *
7236
+ * These are fixed, not random, and that is the point: random prompting is only
7237
+ * required at verification time. Presenting every user the same sequences is
7238
+ * also what makes cross-user calibration accurate — and calibration is what
7239
+ * sets our acceptance threshold (BM-449).
7240
+ *
7241
+ * The guide selects these specifically because they contain no duplicate
7242
+ * 2-digit contexts: biometric performance depends on co-articulation between
7243
+ * adjacent digits, and "321" and "123" are different contexts for "2". Drawing
7244
+ * enrolment prompts at random gives each user an arbitrary, unmeasured slice of
7245
+ * that space.
7246
+ *
7247
+ * Order matters: the first two are count-up and count-down, which the guide
7248
+ * uses to open its enrolment flow because they are the easiest to comply with.
7249
+ */
7250
+ const ENROLMENT_DIGIT_SEQUENCES = [
7251
+ [1, 2, 3, 4, 5, 6, 7, 8, 9],
7252
+ [9, 8, 7, 6, 5, 4, 3, 2, 1],
7253
+ [7, 1, 5, 2, 6, 3, 8, 4, 9],
7254
+ [6, 1, 8, 2, 9, 3, 5, 7, 4],
7255
+ [4, 7, 5, 9, 1, 6, 2, 8, 3],
7256
+ [5, 1, 9, 2, 7, 3, 6, 4, 8],
7257
+ [8, 1, 7, 2, 5, 3, 9, 4, 6],
7258
+ [2, 4, 1, 3, 7, 9, 6, 8, 5],
7259
+ ];
7260
+ /**
7261
+ * Render digits as the spoken words the engine expects in `phrase`.
7262
+ *
7263
+ * Lowercase, matching the Angular package and therefore the only casing that
7264
+ * has been exercised in production. The gateway forwards `phrase` to the engine
7265
+ * untouched, so the client's casing is what gets compared.
7266
+ *
7267
+ * `zero` is retained even though we no longer generate it: a server-issued
7268
+ * challenge may contain a 0, and rendering it as "0" would send a phrase the
7269
+ * engine cannot match at all. A digit outside 0–9 is passed through as-is
7270
+ * rather than silently becoming a word that was never displayed.
7271
+ */
7272
+ function numbersToPhrase(digits) {
7273
+ const words = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
7274
+ return digits.map(d => (d >= 0 && d <= 9 ? words[d] : String(d))).join(' ');
7275
+ }
7276
+ /**
7277
+ * `count` distinct digits drawn from CHALLENGE_DIGITS, in random order.
7278
+ *
7279
+ * Used for the face recorder's fallback challenge when the server issued none.
7280
+ * Enrolment does not call this — see ENROLMENT_DIGIT_SEQUENCES.
7281
+ */
7282
+ function generateRandomDigits(count) {
7283
+ const digits = [...CHALLENGE_DIGITS];
7284
+ for (let i = digits.length - 1; i > 0; i--) {
7285
+ const j = Math.floor(Math.random() * (i + 1));
7286
+ [digits[i], digits[j]] = [digits[j], digits[i]];
7287
+ }
7288
+ return digits.slice(0, count);
7289
+ }function getSupportedMimeType() {
7062
7290
  if (MediaRecorder.isTypeSupported('video/webm;codecs=vp9')) {
7063
7291
  return 'video/webm;codecs=vp9';
7064
7292
  }
@@ -7071,13 +7299,6 @@ var RecordRTC = /*@__PURE__*/getDefaultExportFromCjs(RecordRTCExports);function
7071
7299
  else {
7072
7300
  console.error("no suitable mimetype found for this device");
7073
7301
  }
7074
- }
7075
- function numberToWord(num) {
7076
- const words = ['ZERO', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE'];
7077
- return words[num] || 'ZERO';
7078
- }
7079
- function numbersToPhrase(numbers) {
7080
- return numbers.map(numberToWord).join(' ');
7081
7302
  }const VIDEO_LENGTH_MS = 7000;
7082
7303
  /**
7083
7304
  * Voice *enrollment* reads all ten digits aloud, which does not fit in the
@@ -7180,15 +7401,35 @@ const useRecorder = (stream, type, onStopRecording, lengthMs = VIDEO_LENGTH_MS)
7180
7401
  }
7181
7402
  };
7182
7403
  return { isRecording, startRecording, stopRecording, cancelRecording };
7183
- };const usePermissions = ({ rectWidth = 1920, rectHeight = 1080 } = {}) => {
7404
+ };// Video constraints are IDEAL-ONLY - never `min` (BM-530).
7405
+ //
7406
+ // Without a deviceId, getUserMedia considers every camera and returns one that
7407
+ // satisfies all required (min/max/exact) constraints. A hard `min` therefore
7408
+ // filters cameras: with `width.min: 1280` a 640x480 laptop webcam is silently
7409
+ // excluded and the browser falls back to whatever passes - typically a virtual
7410
+ // camera (OBS) that accepts any resolution - or, with no such camera, throws
7411
+ // OverconstrainedError, which used to surface as "Camera Permission Required".
7412
+ // Chrome's camera picker for the site is narrowed the same way.
7413
+ //
7414
+ // The old minimums survive as floors on the ideal (`idealSize`): an HD camera
7415
+ // is still steered to at least the same resolution as before, while a weaker
7416
+ // camera is accepted at its best mode instead of being rejected.
7417
+ const idealSize = (requested, floor, cap) => Math.max(floor, Math.min(requested, cap));
7418
+ const usePermissions = ({ rectWidth = 1920, rectHeight = 1080 } = {}) => {
7184
7419
  const [permission, setPermission] = React.useState(false);
7185
7420
  const [stream, setStream] = React.useState(null);
7186
7421
  const [isLoading, setIsLoading] = React.useState(true);
7422
+ // The stream is mirrored in a ref so stopStreamTracks and the unmount
7423
+ // cleanup act on the live stream rather than a stale closure, and so a
7424
+ // getUserMedia that resolves after unmount can be stopped immediately
7425
+ // (restored from 1.3.5, which 1.4.0 reverted).
7426
+ const streamRef = React.useRef(null);
7427
+ const isMountedRef = React.useRef(false);
7187
7428
  const stopStreamTracks = () => {
7188
- if (stream) {
7189
- stream.getTracks().forEach(track => {
7190
- track.stop();
7191
- });
7429
+ const currentStream = streamRef.current;
7430
+ if (currentStream) {
7431
+ currentStream.getTracks().forEach(track => track.stop());
7432
+ streamRef.current = null;
7192
7433
  setStream(null);
7193
7434
  }
7194
7435
  };
@@ -7204,12 +7445,12 @@ const useRecorder = (stream, type, onStopRecording, lengthMs = VIDEO_LENGTH_MS)
7204
7445
  noiseSuppression: true,
7205
7446
  autoGainControl: true,
7206
7447
  sampleRate: 48000,
7207
- channelCount: 2
7448
+ channelCount: 1 // Mono: the gateway downmixes with -ac 1 and the engine expects mono (BM-446)
7208
7449
  },
7209
7450
  video: {
7210
- width: { ideal: Math.min(rectWidth, 1920), min: 1280 },
7211
- height: { ideal: Math.min(rectHeight, 1080), min: 720 },
7212
- frameRate: { ideal: 30, min: 24 },
7451
+ width: { ideal: idealSize(rectWidth, 1280, 1920) },
7452
+ height: { ideal: idealSize(rectHeight, 720, 1080) },
7453
+ frameRate: { ideal: 30 },
7213
7454
  facingMode: 'user',
7214
7455
  aspectRatio: { ideal: rectWidth / rectHeight }
7215
7456
  }
@@ -7226,9 +7467,9 @@ const useRecorder = (stream, type, onStopRecording, lengthMs = VIDEO_LENGTH_MS)
7226
7467
  channelCount: 1
7227
7468
  },
7228
7469
  video: {
7229
- width: { ideal: Math.min(rectWidth, 1280), min: 640 },
7230
- height: { ideal: Math.min(rectHeight, 720), min: 480 },
7231
- frameRate: { ideal: 24, min: 15 },
7470
+ width: { ideal: idealSize(rectWidth, 640, 1280) },
7471
+ height: { ideal: idealSize(rectHeight, 480, 720) },
7472
+ frameRate: { ideal: 24 },
7232
7473
  facingMode: 'user',
7233
7474
  aspectRatio: { ideal: rectWidth / rectHeight }
7234
7475
  }
@@ -7244,33 +7485,54 @@ const useRecorder = (stream, type, onStopRecording, lengthMs = VIDEO_LENGTH_MS)
7244
7485
  channelCount: 1
7245
7486
  },
7246
7487
  video: {
7247
- width: { ideal: Math.min(rectWidth, 1280), min: 640 },
7248
- height: { ideal: Math.min(rectHeight, 720), min: 480 },
7249
- frameRate: { ideal: 20, min: 15 },
7488
+ width: { ideal: idealSize(rectWidth, 640, 1280) },
7489
+ height: { ideal: idealSize(rectHeight, 480, 720) },
7490
+ frameRate: { ideal: 20 },
7250
7491
  facingMode: 'user',
7251
7492
  aspectRatio: { ideal: rectWidth / rectHeight }
7252
7493
  }
7253
7494
  };
7254
7495
  };
7255
7496
  const requestPermissions = async () => {
7497
+ var _a, _b;
7256
7498
  try {
7257
7499
  setIsLoading(true);
7258
7500
  const constraints = getAdaptiveConstraints();
7259
7501
  const streamData = await navigator.mediaDevices.getUserMedia(constraints);
7260
7502
  console.log('Media stream obtained, active:', streamData.active);
7503
+ // Unmounted while getUserMedia was resolving: release the devices now,
7504
+ // otherwise the camera/mic indicator stays on with nothing holding it.
7505
+ if (!isMountedRef.current) {
7506
+ streamData.getTracks().forEach(track => track.stop());
7507
+ return;
7508
+ }
7509
+ streamRef.current = streamData;
7261
7510
  setPermission(true);
7262
7511
  setStream(streamData);
7263
7512
  }
7264
7513
  catch (err) {
7265
- console.error('Camera/mic permission denied:', err);
7266
- setPermission(false);
7514
+ // Not every failure is a denied permission: OverconstrainedError names
7515
+ // the failing rule, NotReadableError means the camera is busy.
7516
+ const e = err;
7517
+ console.error('biometry-react-components: getUserMedia failed:', e === null || e === void 0 ? void 0 : e.name, (_a = e === null || e === void 0 ? void 0 : e.constraint) !== null && _a !== void 0 ? _a : '', (_b = e === null || e === void 0 ? void 0 : e.message) !== null && _b !== void 0 ? _b : '');
7518
+ if (isMountedRef.current)
7519
+ setPermission(false);
7267
7520
  }
7268
7521
  finally {
7269
- setIsLoading(false);
7522
+ if (isMountedRef.current)
7523
+ setIsLoading(false);
7270
7524
  }
7271
7525
  };
7272
7526
  React.useEffect(() => {
7527
+ isMountedRef.current = true;
7273
7528
  void requestPermissions();
7529
+ return () => {
7530
+ isMountedRef.current = false;
7531
+ if (streamRef.current) {
7532
+ streamRef.current.getTracks().forEach(track => track.stop());
7533
+ streamRef.current = null;
7534
+ }
7535
+ };
7274
7536
  }, [rectWidth, rectHeight]);
7275
7537
  return { permission, stream, stopStreamTracks, requestPermissions, isLoading };
7276
7538
  };// spinner animation
@@ -7291,22 +7553,14 @@ if (typeof window !== 'undefined' && typeof console !== 'undefined') {
7291
7553
  console.log('MediaRecorder supported:', typeof MediaRecorder !== 'undefined');
7292
7554
  console.log('getUserMedia supported:', !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia));
7293
7555
  }
7294
- const RECORD_SECONDS$1 = VIDEO_LENGTH_MS / 1000;
7295
- const PREP_SECONDS$1 = 3;
7556
+ const DEFAULT_RECORD_SECONDS = VIDEO_LENGTH_MS / 1000;
7557
+ const DEFAULT_PREP_SECONDS = 3;
7296
7558
  const DIGITS_NUMBER$1 = 7;
7297
- function generateRandomDigits$1(count) {
7298
- const digits = Array.from({ length: 10 }, (_, i) => i);
7299
- for (let i = digits.length - 1; i > 0; i--) {
7300
- const j = Math.floor(Math.random() * (i + 1));
7301
- [digits[i], digits[j]] = [digits[j], digits[i]];
7302
- }
7303
- return digits.slice(0, count);
7304
- }
7305
- const FaceRecorder = ({ rectWidth = 360, rectHeight = 576, onConfirmRecording, onRecorded, className, style, noShadow = false, }) => {
7559
+ const FaceRecorder = ({ rectWidth = 360, rectHeight = 576, challengeDigits, recordingSeconds = DEFAULT_RECORD_SECONDS, countdownSeconds = DEFAULT_PREP_SECONDS, emitAudio = false, onConfirmRecording, onRecorded, className, style, noShadow = false, }) => {
7306
7560
  const [state, setState] = React.useState('preparation');
7307
- const [prepTimer, setPrepTimer] = React.useState(PREP_SECONDS$1);
7308
- const [recordTimer, setRecordTimer] = React.useState(RECORD_SECONDS$1);
7309
- const [digits, setDigits] = React.useState(generateRandomDigits$1(DIGITS_NUMBER$1));
7561
+ const [prepTimer, setPrepTimer] = React.useState(countdownSeconds);
7562
+ const [recordTimer, setRecordTimer] = React.useState(recordingSeconds);
7563
+ const [digits, setDigits] = React.useState(generateRandomDigits(DIGITS_NUMBER$1));
7310
7564
  const { permission, stream, stopStreamTracks, requestPermissions, isLoading } = usePermissions({ rectWidth, rectHeight });
7311
7565
  const [videoBlob, setVideoBlob] = React.useState(null);
7312
7566
  const [audioBlob, setAudioBlob] = React.useState(null);
@@ -7319,47 +7573,39 @@ const FaceRecorder = ({ rectWidth = 360, rectHeight = 576, onConfirmRecording, o
7319
7573
  const analyserRef = React.useRef(null);
7320
7574
  const audioCtxRef = React.useRef(null);
7321
7575
  const rafRef = React.useRef(null);
7322
- // Video recorder
7576
+ // Video recorder. This callback owns the transition to the review screen:
7577
+ // it used to live in the audio recorder's callback, which meant the component
7578
+ // could not reach 'result' at all unless a second recording existed (BM-461).
7579
+ const recordingMs = Math.max(1, Math.round(recordingSeconds * 1000));
7323
7580
  const { startRecording: startVideoRecording, cancelRecording: cancelVideoRecording } = useRecorder(stream, "video", (blob) => {
7324
- if (blob && blob.size > 0) {
7325
- setVideoBlob(blob);
7326
- const url = URL.createObjectURL(blob);
7327
- setVideoUrl(url);
7328
- }
7329
- else {
7330
- const dummyBlob = new Blob(['dummy video data'], { type: 'video/webm' });
7331
- setVideoBlob(dummyBlob);
7332
- const url = URL.createObjectURL(dummyBlob);
7333
- setVideoUrl(url);
7334
- }
7335
- });
7336
- // Audio recorder
7337
- const { startRecording: startAudioRecording, cancelRecording: cancelAudioRecording } = useRecorder(stream, "audio", (blob) => {
7338
- if (blob && blob.size > 0) {
7339
- setAudioBlob(blob);
7340
- }
7341
- else {
7342
- const dummyBlob = new Blob(['dummy audio data'], { type: 'audio/webm' });
7343
- setAudioBlob(dummyBlob);
7344
- }
7345
- // Only show result when both recordings are done
7346
- // Video callback will be called first, then audio
7347
7581
  stopStreamTracks();
7582
+ stopAudioVisualization();
7583
+ // A capture that produced nothing is a failure, not a success with an
7584
+ // empty file. This used to substitute a ~15-byte text Blob named
7585
+ // face-video.webm and carry on, so a camera that failed surfaced later as
7586
+ // an unexplained ML error instead of a retry here.
7587
+ if (!blob || blob.size === 0) {
7588
+ console.warn('face recorder: capture produced no video; returning to preparation');
7589
+ resetAfterFailedCapture();
7590
+ return;
7591
+ }
7592
+ setVideoBlob(blob);
7593
+ setVideoUrl(URL.createObjectURL(blob));
7348
7594
  setState('result');
7349
7595
  setIsConfirming(true);
7350
- stopAudioVisualization();
7351
- });
7596
+ }, recordingMs);
7597
+ // Audio recorder — only used when emitAudio is set; see FaceRecorderProps.
7598
+ const { startRecording: startAudioRecording, cancelRecording: cancelAudioRecording } = useRecorder(stream, "audio", (blob) => {
7599
+ setAudioBlob(blob && blob.size > 0 ? blob : null);
7600
+ }, recordingMs);
7352
7601
  React.useEffect(() => {
7353
7602
  // If we already notified for this recording, skip
7354
7603
  if (hasNotifiedRef.current)
7355
7604
  return;
7356
- if (videoBlob && audioBlob && onRecorded) {
7605
+ if (videoBlob && onRecorded) {
7357
7606
  hasNotifiedRef.current = true; // prevent double-calls
7358
- const videoFile = new File([videoBlob], 'face-video.webm', { type: videoBlob.type });
7359
- const audioFile = new File([audioBlob], 'face-audio.webm', { type: audioBlob.type });
7360
- const phrase = numbersToPhrase(digits);
7361
7607
  try {
7362
- onRecorded(videoFile, audioFile, phrase);
7608
+ onRecorded(buildRecording(videoBlob, audioBlob, digits));
7363
7609
  }
7364
7610
  catch (err) {
7365
7611
  // swallow errors from consumer callback to avoid breaking SDK logic
@@ -7394,10 +7640,10 @@ const FaceRecorder = ({ rectWidth = 360, rectHeight = 576, onConfirmRecording, o
7394
7640
  }
7395
7641
  else {
7396
7642
  setState('recording');
7397
- setPrepTimer(PREP_SECONDS$1);
7398
- // Start both video and audio recording simultaneously
7643
+ setPrepTimer(countdownSeconds);
7399
7644
  startVideoRecording();
7400
- startAudioRecording();
7645
+ if (emitAudio)
7646
+ startAudioRecording();
7401
7647
  }
7402
7648
  }
7403
7649
  }, [state, prepTimer]);
@@ -7426,9 +7672,41 @@ const FaceRecorder = ({ rectWidth = 360, rectHeight = 576, onConfirmRecording, o
7426
7672
  }
7427
7673
  }
7428
7674
  }, [state, recordTimer]);
7675
+ /**
7676
+ * Prefer the server-issued challenge; fall back to a generated one. Kept in
7677
+ * one place so every reset path applies the same rule.
7678
+ */
7679
+ const applyChallenge = () => {
7680
+ var _a;
7681
+ const issued = (_a = challengeDigits === null || challengeDigits === void 0 ? void 0 : challengeDigits.filter(d => Number.isInteger(d) && d >= 0 && d <= 9)) !== null && _a !== void 0 ? _a : [];
7682
+ setDigits(issued.length > 0 ? issued : generateRandomDigits(DIGITS_NUMBER$1));
7683
+ };
7684
+ /** Build the emitted payload; `audio` is omitted unless a blob exists. */
7685
+ const buildRecording = (video, audio, challenge) => ({
7686
+ file: new File([video], 'face-video.webm', { type: video.type }),
7687
+ ...(audio ? { audio: new File([audio], 'face-audio.webm', { type: audio.type }) } : {}),
7688
+ phrase: numbersToPhrase(challenge),
7689
+ });
7690
+ /** Return to the start after a capture that produced no usable video. */
7691
+ const resetAfterFailedCapture = () => {
7692
+ setVideoBlob(null);
7693
+ setAudioBlob(null);
7694
+ setVideoUrl(null);
7695
+ setIsConfirming(false);
7696
+ hasNotifiedRef.current = false;
7697
+ setState('preparation');
7698
+ applyChallenge();
7699
+ requestPermissions();
7700
+ };
7701
+ // Adopt a challenge that arrives (or changes) while idle; never mid-capture.
7702
+ React.useEffect(() => {
7703
+ if (state === 'preparation')
7704
+ applyChallenge();
7705
+ // eslint-disable-next-line react-hooks/exhaustive-deps
7706
+ }, [challengeDigits]);
7429
7707
  const startRecording = async () => {
7430
- setDigits(generateRandomDigits$1(DIGITS_NUMBER$1));
7431
- setRecordTimer(RECORD_SECONDS$1);
7708
+ applyChallenge();
7709
+ setRecordTimer(recordingSeconds);
7432
7710
  setState('countdown');
7433
7711
  };
7434
7712
  const handleCancel = () => {
@@ -7445,17 +7723,14 @@ const FaceRecorder = ({ rectWidth = 360, rectHeight = 576, onConfirmRecording, o
7445
7723
  setVideoBlob(null);
7446
7724
  setAudioBlob(null);
7447
7725
  // Reset digits for next recording
7448
- setDigits(generateRandomDigits$1(DIGITS_NUMBER$1));
7726
+ applyChallenge();
7449
7727
  // Restart the stream for cancellation
7450
7728
  requestPermissions();
7451
7729
  };
7452
7730
  const handleConfirm = () => {
7453
- if (videoBlob && audioBlob) {
7454
- // Create file objects
7455
- const videoFile = new File([videoBlob], 'face-video.webm', { type: videoBlob.type });
7456
- const audioFile = new File([audioBlob], 'face-audio.webm', { type: audioBlob.type });
7731
+ if (videoBlob) {
7457
7732
  // required callback in parent app
7458
- onConfirmRecording(videoFile, audioFile, numbersToPhrase(digits));
7733
+ onConfirmRecording(buildRecording(videoBlob, audioBlob, digits));
7459
7734
  // Clean up and reset state
7460
7735
  if (videoUrl)
7461
7736
  URL.revokeObjectURL(videoUrl);
@@ -7467,7 +7742,7 @@ const FaceRecorder = ({ rectWidth = 360, rectHeight = 576, onConfirmRecording, o
7467
7742
  // Reset notified flag
7468
7743
  hasNotifiedRef.current = false;
7469
7744
  // Reset digits for next recording
7470
- setDigits(generateRandomDigits$1(DIGITS_NUMBER$1));
7745
+ applyChallenge();
7471
7746
  // Restart stream for next recording
7472
7747
  requestPermissions();
7473
7748
  }
@@ -7483,7 +7758,7 @@ const FaceRecorder = ({ rectWidth = 360, rectHeight = 576, onConfirmRecording, o
7483
7758
  // Reset notified flag
7484
7759
  hasNotifiedRef.current = false;
7485
7760
  // Reset digits for next recording
7486
- setDigits(generateRandomDigits$1(DIGITS_NUMBER$1));
7761
+ applyChallenge();
7487
7762
  // Restart the stream for retake
7488
7763
  requestPermissions();
7489
7764
  };
@@ -7742,11 +8017,17 @@ const FaceRecorder = ({ rectWidth = 360, rectHeight = 576, onConfirmRecording, o
7742
8017
  const [permission, setPermission] = React.useState(false);
7743
8018
  const [stream, setStream] = React.useState(null);
7744
8019
  const [isLoading, setIsLoading] = React.useState(true);
8020
+ // The stream is mirrored in a ref so stopStreamTracks and the unmount
8021
+ // cleanup act on the live stream rather than a stale closure, and so a
8022
+ // getUserMedia that resolves after unmount can be stopped immediately
8023
+ // (restored from 1.3.5, which 1.4.0 reverted).
8024
+ const streamRef = React.useRef(null);
8025
+ const isMountedRef = React.useRef(false);
7745
8026
  const stopStreamTracks = () => {
7746
- if (stream) {
7747
- stream.getTracks().forEach(track => {
7748
- track.stop();
7749
- });
8027
+ const currentStream = streamRef.current;
8028
+ if (currentStream) {
8029
+ currentStream.getTracks().forEach(track => track.stop());
8030
+ streamRef.current = null;
7750
8031
  setStream(null);
7751
8032
  }
7752
8033
  };
@@ -7762,7 +8043,7 @@ const FaceRecorder = ({ rectWidth = 360, rectHeight = 576, onConfirmRecording, o
7762
8043
  noiseSuppression: true,
7763
8044
  autoGainControl: true,
7764
8045
  sampleRate: 48000,
7765
- channelCount: 2
8046
+ channelCount: 1 // Mono: the gateway downmixes with -ac 1 and the engine expects mono (BM-446)
7766
8047
  }
7767
8048
  };
7768
8049
  }
@@ -7794,19 +8075,36 @@ const FaceRecorder = ({ rectWidth = 360, rectHeight = 576, onConfirmRecording, o
7794
8075
  setIsLoading(true);
7795
8076
  const constraints = getAudioConstraints();
7796
8077
  const streamData = await navigator.mediaDevices.getUserMedia(constraints);
8078
+ // Unmounted while getUserMedia was resolving: release the devices now,
8079
+ // otherwise the camera/mic indicator stays on with nothing holding it.
8080
+ if (!isMountedRef.current) {
8081
+ streamData.getTracks().forEach(track => track.stop());
8082
+ return;
8083
+ }
8084
+ streamRef.current = streamData;
7797
8085
  setPermission(true);
7798
8086
  setStream(streamData);
7799
8087
  }
7800
8088
  catch (err) {
7801
8089
  console.error('Microphone permission denied:', err);
7802
- setPermission(false);
8090
+ if (isMountedRef.current)
8091
+ setPermission(false);
7803
8092
  }
7804
8093
  finally {
7805
- setIsLoading(false);
8094
+ if (isMountedRef.current)
8095
+ setIsLoading(false);
7806
8096
  }
7807
8097
  };
7808
8098
  React.useEffect(() => {
8099
+ isMountedRef.current = true;
7809
8100
  void requestPermissions();
8101
+ return () => {
8102
+ isMountedRef.current = false;
8103
+ if (streamRef.current) {
8104
+ streamRef.current.getTracks().forEach(track => track.stop());
8105
+ streamRef.current = null;
8106
+ }
8107
+ };
7810
8108
  }, []);
7811
8109
  return { permission, stream, stopStreamTracks, requestPermissions, isLoading };
7812
8110
  };// spinner animation
@@ -7824,25 +8122,30 @@ if (typeof document !== 'undefined') {
7824
8122
  }
7825
8123
  const RECORD_SECONDS = VOICE_ENROLL_LENGTH_MS / 1000;
7826
8124
  const PREP_SECONDS = 3;
7827
- // All ten digits. Voice enrollment builds a text-prompted digit voiceprint and
7828
- // the enrollment sample is expected to cover 0-9; verification later prompts a
7829
- // random subset. This was 10 until 1.2.7 shortened the recording to 7s and cut
7830
- // the prompt to match, which silently dropped three digits from every print
7831
- // while the README kept documenting ten (BM-407).
7832
- const DIGITS_NUMBER = 10;
7833
- function generateRandomDigits(count) {
7834
- const digits = Array.from({ length: 10 }, (_, i) => i);
7835
- for (let i = digits.length - 1; i > 0; i--) {
7836
- const j = Math.floor(Math.random() * (i + 1));
7837
- [digits[i], digits[j]] = [digits[j], digits[i]];
7838
- }
7839
- return digits.slice(0, count);
7840
- }
7841
- const VoiceRecorder = ({ rectWidth = 360, rectHeight, onConfirmRecording, onRecorded, className, style, noShadow = false, }) => {
8125
+ const DEFAULT_TAKES = 5;
8126
+ /**
8127
+ * Prompts come from ENROLMENT_DIGIT_SEQUENCES, not from a random draw.
8128
+ *
8129
+ * The published sequences are chosen to contain no duplicate 2-digit contexts,
8130
+ * and presenting every user the same set is what makes cross-user calibration
8131
+ * accurate — calibration being what sets the acceptance threshold (BM-449,
8132
+ * BM-450). Random enrolment prompts gave each user an arbitrary, unmeasured
8133
+ * slice of that space.
8134
+ */
8135
+ const DIGITS_NUMBER = ENROLMENT_DIGIT_SEQUENCES[0].length;
8136
+ const VoiceRecorder = ({ rectWidth = 360, rectHeight, takes = DEFAULT_TAKES, onConfirmRecording, onRecorded, className, style, noShadow = false, }) => {
7842
8137
  const [state, setState] = React.useState('preparation');
7843
8138
  const [prepTimer, setPrepTimer] = React.useState(PREP_SECONDS);
7844
8139
  const [recordTimer, setRecordTimer] = React.useState(RECORD_SECONDS);
7845
- const [digits, setDigits] = React.useState(generateRandomDigits(DIGITS_NUMBER));
8140
+ /** Takes confirmed so far; emitted together once `takes` are collected. */
8141
+ const [collected, setCollected] = React.useState([]);
8142
+ /**
8143
+ * The prompt for the take being collected, keyed on how many are already
8144
+ * confirmed — so a retake re-prompts the *same* sequence rather than drawing
8145
+ * a new one: the user is re-recording a take, not being given a different
8146
+ * task. Wraps if a consumer asks for more takes than there are sequences.
8147
+ */
8148
+ const digits = React.useMemo(() => [...ENROLMENT_DIGIT_SEQUENCES[collected.length % ENROLMENT_DIGIT_SEQUENCES.length]], [collected.length]);
7846
8149
  const [audioLevel, setAudioLevel] = React.useState(0);
7847
8150
  const [waveformData, setWaveformData] = React.useState([]);
7848
8151
  const { permission, stream, stopStreamTracks, requestPermissions, isLoading } = useAudioPermissions();
@@ -7854,29 +8157,33 @@ const VoiceRecorder = ({ rectWidth = 360, rectHeight, onConfirmRecording, onReco
7854
8157
  const animationFrameRef = React.useRef(null);
7855
8158
  const { startRecording: startHookRecording, cancelRecording } = useRecorder(stream, "audio", (blob) => {
7856
8159
  stopStreamTracks();
7857
- if (blob && blob.size > 0) {
7858
- setAudioBlob(blob);
7859
- const url = URL.createObjectURL(blob);
7860
- setAudioUrl(url);
7861
- setState('result');
7862
- setIsConfirming(true);
7863
- if (onRecorded) {
7864
- try {
7865
- const file = new File([blob], 'voice-recording.webm', { type: blob.type });
7866
- onRecorded(file, numbersToPhrase(digits));
7867
- }
7868
- catch (err) {
7869
- console.error('onRecorded callback threw:', err);
7870
- }
7871
- }
8160
+ // A take that produced nothing is a failure, not a success with an empty
8161
+ // file. This used to substitute a ~15-byte text Blob named
8162
+ // voice-recording.webm and present it for confirmation, so a failed
8163
+ // recording went into the voiceprint as garbage (BM-461).
8164
+ if (!blob || blob.size === 0) {
8165
+ console.warn('voice recorder: take produced no audio; returning to preparation');
8166
+ setAudioBlob(null);
8167
+ setAudioUrl(null);
8168
+ setIsConfirming(false);
8169
+ setState('preparation');
8170
+ requestPermissions();
8171
+ return;
7872
8172
  }
7873
- else {
7874
- const dummyBlob = new Blob(['dummy audio data'], { type: 'audio/webm' });
7875
- setAudioBlob(dummyBlob);
7876
- const url = URL.createObjectURL(dummyBlob);
7877
- setAudioUrl(url);
7878
- setState('result');
7879
- setIsConfirming(true);
8173
+ setAudioBlob(blob);
8174
+ setAudioUrl(URL.createObjectURL(blob));
8175
+ setState('result');
8176
+ setIsConfirming(true);
8177
+ if (onRecorded) {
8178
+ try {
8179
+ onRecorded({
8180
+ file: new File([blob], `voice-recording-${collected.length + 1}.webm`, { type: blob.type }),
8181
+ phrase: numbersToPhrase(digits),
8182
+ });
8183
+ }
8184
+ catch (err) {
8185
+ console.error('onRecorded callback threw:', err);
8186
+ }
7880
8187
  }
7881
8188
  }, VOICE_ENROLL_LENGTH_MS);
7882
8189
  // Audio visualization setup
@@ -7938,10 +8245,20 @@ const VoiceRecorder = ({ rectWidth = 360, rectHeight, onConfirmRecording, onReco
7938
8245
  }
7939
8246
  }, [state, recordTimer]);
7940
8247
  const startRecording = async () => {
7941
- setDigits(generateRandomDigits(DIGITS_NUMBER));
8248
+ // The prompt is derived from how many takes are confirmed, so there is
8249
+ // nothing to re-draw here — a retake deliberately re-prompts the same
8250
+ // sequence.
7942
8251
  setRecordTimer(RECORD_SECONDS);
7943
8252
  setState('countdown');
7944
8253
  };
8254
+ /**
8255
+ * Discards the take in flight, not the enrollment.
8256
+ *
8257
+ * Confirmed takes are kept: wiping `collected` here sent the user back to
8258
+ * take 1 with no warning and no undo, so the longer the enrollment the more a
8259
+ * stumble cost. Nothing is mixed across attempts — every take reads the same
8260
+ * `digits`, and the in-flight blob is released below rather than kept.
8261
+ */
7945
8262
  const handleCancel = () => {
7946
8263
  // Cancel the recording first
7947
8264
  cancelRecording();
@@ -7957,20 +8274,32 @@ const VoiceRecorder = ({ rectWidth = 360, rectHeight, onConfirmRecording, onReco
7957
8274
  requestPermissions();
7958
8275
  };
7959
8276
  const handleConfirm = () => {
7960
- if (audioBlob) {
7961
- const file = new File([audioBlob], 'voice-recording.webm', { type: audioBlob.type });
7962
- // required callback in parent app
7963
- onConfirmRecording(file, numbersToPhrase(digits));
7964
- // Clean up and reset state
7965
- if (audioUrl)
7966
- URL.revokeObjectURL(audioUrl);
7967
- setAudioUrl(null);
7968
- setAudioBlob(null);
7969
- setIsConfirming(false);
7970
- setState('preparation');
7971
- // Restart the stream for retake (yep.)
7972
- requestPermissions();
8277
+ if (!audioBlob)
8278
+ return;
8279
+ const take = {
8280
+ file: new File([audioBlob], `voice-recording-${collected.length + 1}.webm`, { type: audioBlob.type }),
8281
+ phrase: numbersToPhrase(digits),
8282
+ };
8283
+ const confirmed = [...collected, take];
8284
+ if (audioUrl)
8285
+ URL.revokeObjectURL(audioUrl);
8286
+ setAudioUrl(null);
8287
+ setAudioBlob(null);
8288
+ setIsConfirming(false);
8289
+ setState('preparation');
8290
+ // Emit only once every take is in: the consumer posts them together as one
8291
+ // enrollment, so a partial set is worse than none.
8292
+ if (confirmed.length >= takes) {
8293
+ setCollected([]);
8294
+ onConfirmRecording({
8295
+ files: confirmed.map(t => t.file),
8296
+ phrases: confirmed.map(t => t.phrase),
8297
+ });
8298
+ return;
7973
8299
  }
8300
+ // More takes to go: re-arm the mic so the next one can start immediately.
8301
+ setCollected(confirmed);
8302
+ requestPermissions();
7974
8303
  };
7975
8304
  const handleDecline = () => {
7976
8305
  if (audioUrl)
@@ -8151,13 +8480,13 @@ const VoiceRecorder = ({ rectWidth = 360, rectHeight, onConfirmRecording, onReco
8151
8480
  justifyContent: 'center',
8152
8481
  width: '100%',
8153
8482
  padding: '20px',
8154
- }, children: [state === 'preparation' && (jsxRuntime.jsx(jsxRuntime.Fragment, { children: jsxRuntime.jsx("div", { style: guidanceText, children: "Click Start to begin voice recording" }) })), state === 'countdown' && (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("div", { style: guidanceText, children: "Get ready to speak clearly" }), jsxRuntime.jsx("div", { style: prepTimerStyle, children: prepTimer })] })), state === 'recording' && (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("div", { style: waveformContainer, children: jsxRuntime.jsx("div", { style: {
8483
+ }, children: [state === 'preparation' && (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [takes > 1 && (jsxRuntime.jsxs("div", { style: { ...guidanceText, fontWeight: 600 }, children: ["Recording ", Math.min(collected.length + 1, takes), " of ", takes] })), jsxRuntime.jsx("div", { style: guidanceText, children: "Click Start to begin voice recording" })] })), state === 'countdown' && (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("div", { style: guidanceText, children: "Get ready to speak clearly" }), jsxRuntime.jsx("div", { style: prepTimerStyle, children: prepTimer })] })), state === 'recording' && (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("div", { style: waveformContainer, children: jsxRuntime.jsx("div", { style: {
8155
8484
  display: 'flex',
8156
8485
  alignItems: 'center',
8157
8486
  justifyContent: 'center',
8158
8487
  height: '120px',
8159
8488
  gap: '2px',
8160
- }, children: waveformData.map((value, index) => (jsxRuntime.jsx("div", { style: waveformBar(value / 255) }, index))) }) }), jsxRuntime.jsx("div", { style: timerStyle, children: recordTimer }), jsxRuntime.jsx("div", { style: guidanceText, children: "Speak clearly into your microphone" })] }))] })] }), jsxRuntime.jsx("div", { style: numberRow, children: (state === 'recording' ? digits : Array(DIGITS_NUMBER).fill('*')).map((num, i) => (jsxRuntime.jsx("div", { style: numberBox, children: num }, i))) }), state === 'preparation' && (jsxRuntime.jsx("button", { type: "button", style: actionButton, onClick: startRecording, children: "Start recording" })), state === 'recording' && (jsxRuntime.jsx("button", { type: "button", style: { ...actionButton, background: '#d32f2f' }, onClick: handleCancel, children: "Cancel" }))] })), state === 'processing' && (jsxRuntime.jsx(jsxRuntime.Fragment, { children: jsxRuntime.jsx("div", { className: "voicerecorder-processing", style: preview, children: jsxRuntime.jsxs("div", { style: {
8489
+ }, children: waveformData.map((value, index) => (jsxRuntime.jsx("div", { style: waveformBar(value / 255) }, index))) }) }), jsxRuntime.jsx("div", { style: timerStyle, children: recordTimer }), jsxRuntime.jsx("div", { style: guidanceText, children: "Speak clearly into your microphone" })] }))] })] }), jsxRuntime.jsx("div", { style: numberRow, children: (state === 'recording' ? digits : Array(DIGITS_NUMBER).fill('*')).map((num, i) => (jsxRuntime.jsx("div", { style: numberBox, children: num }, i))) }), state === 'preparation' && (jsxRuntime.jsx("button", { type: "button", style: actionButton, onClick: startRecording, children: "Start recording" })), state === 'recording' && (jsxRuntime.jsx("button", { type: "button", style: { ...actionButton, background: '#d32f2f' }, onClick: handleCancel, children: takes > 1 ? 'Discard this recording' : 'Cancel' }))] })), state === 'processing' && (jsxRuntime.jsx(jsxRuntime.Fragment, { children: jsxRuntime.jsx("div", { className: "voicerecorder-processing", style: preview, children: jsxRuntime.jsxs("div", { style: {
8161
8490
  display: 'flex',
8162
8491
  flexDirection: 'column',
8163
8492
  alignItems: 'center',
@@ -8184,4 +8513,4 @@ const VoiceRecorder = ({ rectWidth = 360, rectHeight, onConfirmRecording, onReco
8184
8513
  maxWidth: '300px',
8185
8514
  marginBottom: '16px',
8186
8515
  } })), jsxRuntime.jsx("div", { className: "voicerecorder-confirm-text", style: confirmText, children: "Do you want to use this recording?" }), jsxRuntime.jsxs("div", { className: "voicerecorder-confirm-btns", style: { display: 'flex', justifyContent: 'center', gap: 32, marginTop: 12, width: '100%' }, children: [jsxRuntime.jsx("button", { type: "button", "aria-label": "Retake", className: "voicerecorder-icon-btn", style: iconButton, onClick: handleDecline, onMouseOver: e => (e.currentTarget.style.background = 'rgba(211,47,47,0.12)'), onMouseOut: e => (e.currentTarget.style.background = 'none'), children: jsxRuntime.jsxs("svg", { width: "36", height: "36", viewBox: "0 0 36 36", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: [jsxRuntime.jsx("circle", { cx: "18", cy: "18", r: "18", fill: "#fff", fillOpacity: "0.15" }), jsxRuntime.jsx("path", { d: "M12 12L24 24", stroke: "#d32f2f", strokeWidth: "3", strokeLinecap: "round" }), jsxRuntime.jsx("path", { d: "M24 12L12 24", stroke: "#d32f2f", strokeWidth: "3", strokeLinecap: "round" })] }) }), jsxRuntime.jsx("button", { type: "button", "aria-label": "Confirm", className: "voicerecorder-icon-btn", style: iconButton, onClick: handleConfirm, onMouseOver: e => (e.currentTarget.style.background = 'rgba(56,142,60,0.12)'), onMouseOut: e => (e.currentTarget.style.background = 'none'), children: jsxRuntime.jsxs("svg", { width: "36", height: "36", viewBox: "0 0 36 36", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: [jsxRuntime.jsx("circle", { cx: "18", cy: "18", r: "18", fill: "#fff", fillOpacity: "0.15" }), jsxRuntime.jsx("path", { d: "M10 19L16 25L26 13", stroke: "#388e3c", strokeWidth: "3", strokeLinecap: "round", strokeLinejoin: "round" })] }) })] })] }) }))] }));
8187
- };exports.DocScan=DocScan;exports.FaceCapture=FaceCapture;exports.FaceRecorder=FaceRecorder;exports.VoiceRecorder=VoiceRecorder;exports.useAudioPermissions=useAudioPermissions;exports.usePermissions=usePermissions;exports.useRecorder=useRecorder;
8516
+ };exports.CHALLENGE_DIGITS=CHALLENGE_DIGITS;exports.DocScan=DocScan;exports.ENROLMENT_DIGIT_SEQUENCES=ENROLMENT_DIGIT_SEQUENCES;exports.FaceCapture=FaceCapture;exports.FaceRecorder=FaceRecorder;exports.VoiceRecorder=VoiceRecorder;exports.generateRandomDigits=generateRandomDigits;exports.numbersToPhrase=numbersToPhrase;exports.useAudioPermissions=useAudioPermissions;exports.usePermissions=usePermissions;exports.useRecorder=useRecorder;