@sekyro/web 0.1.0-rc.3 → 0.1.0-rc.5
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/CHANGELOG.md +30 -0
- package/README.md +44 -0
- package/dist/{capture-session-v3-CvIfcwST.d.ts → capture-session-v3-Okq0EQHG.d.ts} +38 -2
- package/dist/{capture-session-v3-COIO_F2w.d.cts → capture-session-v3-UQU_WjO2.d.cts} +38 -2
- package/dist/{chunk-FIXX2AXC.js → chunk-SGDXLAXR.js} +309 -10
- package/dist/chunk-SGDXLAXR.js.map +1 -0
- package/dist/{chunk-7TC6TOZ4.js → chunk-TG5IE552.js} +37 -4
- package/dist/chunk-TG5IE552.js.map +1 -0
- package/dist/client/index.cjs.map +1 -1
- package/dist/client/index.d.cts +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/core/index.cjs +36 -3
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +2 -2
- package/dist/core/index.d.ts +2 -2
- package/dist/core/index.js +1 -1
- package/dist/{create-verification-CswF2As-.d.ts → create-verification-CA-3szPI.d.cts} +108 -8
- package/dist/{create-verification-CP18eq1Q.d.cts → create-verification-c98uAxbl.d.ts} +108 -8
- package/dist/{hosted-client-BpvBqu9f.d.cts → hosted-client-DWzCRYJK.d.cts} +14 -1
- package/dist/{hosted-client-BpvBqu9f.d.ts → hosted-client-DWzCRYJK.d.ts} +14 -1
- package/dist/index.cjs +384 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +25 -3
- package/dist/index.d.ts +25 -3
- package/dist/index.js +61 -4
- package/dist/index.js.map +1 -1
- package/dist/internal/index.cjs +261 -11
- package/dist/internal/index.cjs.map +1 -1
- package/dist/internal/index.d.cts +4 -4
- package/dist/internal/index.d.ts +4 -4
- package/dist/internal/index.js +12 -2
- package/dist/internal/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-7TC6TOZ4.js.map +0 -1
- package/dist/chunk-FIXX2AXC.js.map +0 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { p as DeviceClass, i as CaptureState, b as CaptureArtifacts, c as CaptureErrorKind } from '../capture-session-v3-UQU_WjO2.cjs';
|
|
2
2
|
export { C as CENTERED_FACTOR, a as CIRCLE_RADIUS_FACTOR, I as IN_CIRCLE_FACTOR } from '../capture-constraints-BujkZcfb.cjs';
|
|
3
|
-
import {
|
|
4
|
-
export { A as AttestationError,
|
|
5
|
-
import { C as CheckReason, c as HostedSessionView, d as HostedStepView, h as SessionView, b as CheckType } from '../hosted-client-
|
|
3
|
+
import { o as VerificationResult } from '../create-verification-CA-3szPI.cjs';
|
|
4
|
+
export { A as AttestationError, w as CLIP_MIME_ALLOWLIST, x as CaptureEngine, H as HostedClientLike, y as LivenessCaptureInternalHandle, z as LivenessCaptureInternals, B as LivenessFlowDeps, E as LivenessFlowOutcome, F as PRELOAD_BLAZE_INIT_TIMEOUT_MS, I as PRELOAD_BUDGET_MS, J as PROCESSING_POLL_DELAY_MS, K as PROCESSING_POLL_MAX, M as REGISTRY_RETRY_DELAY_MS, N as SubmitExecutor, O as SubmitRuntime, T as TRANSPORT_REPLAY_ATTEMPTS, Q as TRANSPORT_REPLAY_DELAY_MS, U as VerificationInternals, W as createLivenessCaptureInternal, X as createVerificationInternal, Y as mapEngineState, Z as mapErrorKind, _ as mapGuidanceHint, $ as preloadedDetectorFactory, a0 as randomUuid, a1 as resetLivenessAssetsForTests, a2 as runLivenessFlow, a3 as runSubmission, a4 as setPreloadLoaderForTests } from '../create-verification-CA-3szPI.cjs';
|
|
5
|
+
import { C as CheckReason, c as HostedSessionView, d as HostedStepView, h as SessionView, b as CheckType } from '../hosted-client-DWzCRYJK.cjs';
|
|
6
6
|
import '../detect-worker-CKXHlXx9.cjs';
|
|
7
7
|
|
|
8
8
|
/** Physical geometry the scanner frames (ISO/IEC 7810 / ICAO 9303). */
|
package/dist/internal/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { p as DeviceClass, i as CaptureState, b as CaptureArtifacts, c as CaptureErrorKind } from '../capture-session-v3-Okq0EQHG.js';
|
|
2
2
|
export { C as CENTERED_FACTOR, a as CIRCLE_RADIUS_FACTOR, I as IN_CIRCLE_FACTOR } from '../capture-constraints-BujkZcfb.js';
|
|
3
|
-
import {
|
|
4
|
-
export { A as AttestationError,
|
|
5
|
-
import { C as CheckReason, c as HostedSessionView, d as HostedStepView, h as SessionView, b as CheckType } from '../hosted-client-
|
|
3
|
+
import { o as VerificationResult } from '../create-verification-c98uAxbl.js';
|
|
4
|
+
export { A as AttestationError, w as CLIP_MIME_ALLOWLIST, x as CaptureEngine, H as HostedClientLike, y as LivenessCaptureInternalHandle, z as LivenessCaptureInternals, B as LivenessFlowDeps, E as LivenessFlowOutcome, F as PRELOAD_BLAZE_INIT_TIMEOUT_MS, I as PRELOAD_BUDGET_MS, J as PROCESSING_POLL_DELAY_MS, K as PROCESSING_POLL_MAX, M as REGISTRY_RETRY_DELAY_MS, N as SubmitExecutor, O as SubmitRuntime, T as TRANSPORT_REPLAY_ATTEMPTS, Q as TRANSPORT_REPLAY_DELAY_MS, U as VerificationInternals, W as createLivenessCaptureInternal, X as createVerificationInternal, Y as mapEngineState, Z as mapErrorKind, _ as mapGuidanceHint, $ as preloadedDetectorFactory, a0 as randomUuid, a1 as resetLivenessAssetsForTests, a2 as runLivenessFlow, a3 as runSubmission, a4 as setPreloadLoaderForTests } from '../create-verification-c98uAxbl.js';
|
|
5
|
+
import { C as CheckReason, c as HostedSessionView, d as HostedStepView, h as SessionView, b as CheckType } from '../hosted-client-DWzCRYJK.js';
|
|
6
6
|
import '../detect-worker-CKXHlXx9.js';
|
|
7
7
|
|
|
8
8
|
/** Physical geometry the scanner frames (ISO/IEC 7810 / ICAO 9303). */
|
package/dist/internal/index.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
2
|
AttestationError,
|
|
3
3
|
CLIP_MIME_ALLOWLIST,
|
|
4
|
+
PRELOAD_BLAZE_INIT_TIMEOUT_MS,
|
|
5
|
+
PRELOAD_BUDGET_MS,
|
|
4
6
|
PROCESSING_POLL_DELAY_MS,
|
|
5
7
|
PROCESSING_POLL_MAX,
|
|
6
8
|
REGISTRY_RETRY_DELAY_MS,
|
|
@@ -21,12 +23,15 @@ import {
|
|
|
21
23
|
mapGuidanceHint,
|
|
22
24
|
mapSessionResult,
|
|
23
25
|
mergeSessionView,
|
|
26
|
+
preloadedDetectorFactory,
|
|
24
27
|
randomUuid,
|
|
28
|
+
resetLivenessAssetsForTests,
|
|
25
29
|
resetTurnstileForTests,
|
|
26
30
|
runLivenessFlow,
|
|
27
31
|
runSubmission,
|
|
32
|
+
setPreloadLoaderForTests,
|
|
28
33
|
stepOf
|
|
29
|
-
} from "../chunk-
|
|
34
|
+
} from "../chunk-SGDXLAXR.js";
|
|
30
35
|
import {
|
|
31
36
|
CENTERED_FACTOR,
|
|
32
37
|
CIRCLE_RADIUS_FACTOR,
|
|
@@ -34,7 +39,7 @@ import {
|
|
|
34
39
|
classifyDevice,
|
|
35
40
|
mapGetUserMediaError,
|
|
36
41
|
probeDevice
|
|
37
|
-
} from "../chunk-
|
|
42
|
+
} from "../chunk-TG5IE552.js";
|
|
38
43
|
import "../chunk-YVFF4Q4G.js";
|
|
39
44
|
import "../chunk-NWF46H7K.js";
|
|
40
45
|
import {
|
|
@@ -608,6 +613,8 @@ export {
|
|
|
608
613
|
IN_CIRCLE_FACTOR,
|
|
609
614
|
MRZ_BAND_DEFAULTS,
|
|
610
615
|
MR_DOC_CATALOG,
|
|
616
|
+
PRELOAD_BLAZE_INIT_TIMEOUT_MS,
|
|
617
|
+
PRELOAD_BUDGET_MS,
|
|
611
618
|
PROCESSING_POLL_DELAY_MS,
|
|
612
619
|
PROCESSING_POLL_MAX,
|
|
613
620
|
REGISTRY_RETRY_DELAY_MS,
|
|
@@ -632,14 +639,17 @@ export {
|
|
|
632
639
|
mapGuidanceHint,
|
|
633
640
|
mapSessionResult,
|
|
634
641
|
mergeSessionView,
|
|
642
|
+
preloadedDetectorFactory,
|
|
635
643
|
quadAreaFrac,
|
|
636
644
|
quadBounds,
|
|
637
645
|
quadIou,
|
|
638
646
|
quadTiltRatio,
|
|
639
647
|
randomUuid,
|
|
648
|
+
resetLivenessAssetsForTests,
|
|
640
649
|
resetTurnstileForTests,
|
|
641
650
|
runLivenessFlow,
|
|
642
651
|
runSubmission,
|
|
652
|
+
setPreloadLoaderForTests,
|
|
643
653
|
specularFraction,
|
|
644
654
|
stepOf,
|
|
645
655
|
warmDocDetector
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/doc/mrz-band.ts","../../src/core/doc/frame-analysis.ts","../../src/core/doc/feedback-aggregator.ts","../../src/core/doc/capture-session-doc.ts"],"sourcesContent":["// MRZ-band detector (Task 37 round 3) — the passport path's detection signal.\n//\n// WHY: edge/contour detection (scanic) fails on passport data pages — an open\n// booklet's page edges are white-on-white, so quads lock late or onto the\n// wrong rectangle (operator field finding, twice). The industry-standard\n// approach (Scanbot/Regula/Dynamsoft; PyImageSearch's classic blackhat\n// pipeline; YOLO-MRZ) is to detect the MRZ ITSELF: two 44-char lines of\n// high-contrast OCR-B strokes — the one feature of a passport that is\n// reliably detectable in any framing. This is the pure-JS analog of the\n// blackhat+gradient pipeline: per-row horizontal-stroke density with a\n// column-coverage requirement, then the tallest qualifying row run.\n//\n// Deterministic, allocation-light, no wasm: ~2ms on a 480px frame in node —\n// cheap enough to run at full doc cadence on LOW devices.\n\nexport interface MrzBand {\n x: number;\n y: number;\n width: number;\n height: number;\n /** Mean qualifying-row stroke density (diagnostics/telemetry). */\n density: number;\n}\n\nexport interface MrzBandThresholds {\n /** Luma step that counts as a text stroke edge. */\n EDGE_LUMA_DELTA: number;\n /** Min fraction of a row's pixels that are stroke edges to qualify. */\n MIN_ROW_DENSITY: number;\n /** Row must have stroke edges spread across ≥ this fraction of 12 columns. */\n MIN_COLUMN_COVERAGE: number;\n /** Band width (stroke x-extent) as a fraction of frame width. */\n MIN_WIDTH_FRAC: number;\n /** Band height bounds as fractions of frame height (2–3 OCR-B lines). */\n MIN_HEIGHT_FRAC: number;\n MAX_HEIGHT_FRAC: number;\n /** Rows this close together merge into one band (inter-line gap). */\n ROW_MERGE_GAP: number;\n}\n\n/** Frozen defaults (goldens in test/doc/mrz-band.test.ts — retune together). */\nexport const MRZ_BAND_DEFAULTS: Readonly<MrzBandThresholds> = Object.freeze({\n EDGE_LUMA_DELTA: 40,\n MIN_ROW_DENSITY: 0.08,\n MIN_COLUMN_COVERAGE: 0.6,\n MIN_WIDTH_FRAC: 0.55,\n MIN_HEIGHT_FRAC: 0.02,\n MAX_HEIGHT_FRAC: 0.16,\n ROW_MERGE_GAP: 18,\n});\n\nconst COLUMN_BUCKETS = 12;\n\n/**\n * Detect the MRZ stroke band on a (≤480px) grayscale-able frame. Returns the\n * tight band rect in frame pixels, or null when no qualifying band exists\n * (no MRZ in view, or only a partial/narrow slice of one).\n */\nexport function detectMrzBand(\n frame: ImageData,\n overrides: Partial<MrzBandThresholds> = {},\n): MrzBand | null {\n const t = { ...MRZ_BAND_DEFAULTS, ...overrides };\n const { data, width, height } = frame;\n if (width < 32 || height < 32) return null;\n\n // Per-row: stroke-edge count + column coverage + x-extent.\n const qualifies = new Array<boolean>(height).fill(false);\n const density = new Float32Array(height);\n const minX = new Int32Array(height).fill(width);\n const maxX = new Int32Array(height).fill(-1);\n\n const bucketWidth = width / COLUMN_BUCKETS;\n const buckets = new Array<boolean>(COLUMN_BUCKETS);\n for (let y = 0; y < height; y++) {\n let edges = 0;\n buckets.fill(false);\n const rowOffset = y * width * 4;\n let previousLuma =\n 0.299 * (data[rowOffset] ?? 0) +\n 0.587 * (data[rowOffset + 1] ?? 0) +\n 0.114 * (data[rowOffset + 2] ?? 0);\n for (let x = 1; x < width; x++) {\n const i = rowOffset + x * 4;\n const luma =\n 0.299 * (data[i] ?? 0) + 0.587 * (data[i + 1] ?? 0) + 0.114 * (data[i + 2] ?? 0);\n if (Math.abs(luma - previousLuma) >= t.EDGE_LUMA_DELTA) {\n edges += 1;\n buckets[Math.min(COLUMN_BUCKETS - 1, Math.floor(x / bucketWidth))] = true;\n if (x < (minX[y] as number)) minX[y] = x;\n if (x > (maxX[y] as number)) maxX[y] = x;\n }\n previousLuma = luma;\n }\n density[y] = edges / width;\n const coverage = buckets.filter(Boolean).length / COLUMN_BUCKETS;\n qualifies[y] =\n density[y]! >= t.MIN_ROW_DENSITY &&\n coverage >= t.MIN_COLUMN_COVERAGE &&\n (maxX[y] as number) - (minX[y] as number) >= t.MIN_WIDTH_FRAC * width;\n }\n\n // Merge qualifying rows across the inter-line gap; keep the best band.\n let best: { top: number; bottom: number; rows: number } | null = null;\n let runTop = -1;\n let lastQualifying = -1;\n let runRows = 0;\n const flush = (bottom: number) => {\n if (runTop < 0) return;\n const bandHeight = bottom - runTop + 1;\n if (\n bandHeight >= t.MIN_HEIGHT_FRAC * height &&\n bandHeight <= t.MAX_HEIGHT_FRAC * height &&\n runRows >= 4 && // at least a few real stroke rows, not a lone edge\n (best === null || runRows > best.rows)\n ) {\n best = { top: runTop, bottom, rows: runRows };\n }\n runTop = -1;\n runRows = 0;\n };\n for (let y = 0; y < height; y++) {\n if (qualifies[y]) {\n if (runTop < 0) runTop = y;\n else if (y - lastQualifying > t.ROW_MERGE_GAP) {\n flush(lastQualifying);\n runTop = y;\n }\n lastQualifying = y;\n runRows += 1;\n }\n }\n flush(lastQualifying);\n if (best === null) return null;\n const band = best as { top: number; bottom: number; rows: number };\n\n // Tight x-extent + mean density over the band's qualifying rows.\n let x1 = width;\n let x2 = -1;\n let densitySum = 0;\n let densityRows = 0;\n for (let y = band.top; y <= band.bottom; y++) {\n if (!qualifies[y]) continue;\n if ((minX[y] as number) < x1) x1 = minX[y] as number;\n if ((maxX[y] as number) > x2) x2 = maxX[y] as number;\n densitySum += density[y] as number;\n densityRows += 1;\n }\n if (x2 - x1 < t.MIN_WIDTH_FRAC * width) return null;\n return {\n x: x1,\n y: band.top,\n width: x2 - x1,\n height: band.bottom - band.top + 1,\n density: densityRows > 0 ? densitySum / densityRows : 0,\n };\n}\n","// Doc frame analysis (capture v2, Task-37 round 4) — the BlinkID-inspired\n// PER-FRAME status vector: independent framing / lighting / blur / glare /\n// tilt verdicts instead of a single collapsed guidance key. Pure and\n// deterministic: inputs are the detection (quad or MRZ band rect-as-quad),\n// the doc-region crop's quality measures, and static thresholds — no clocks,\n// no I/O. The FeedbackAggregator votes over these statuses; DocGateV1's\n// integrator/stability logic consumes `framingOk`/`qualityOk`.\nimport { EXPOSURE_BAND } from \"../v3/frame-quality\";\nimport { aspectBand, type DocFormat } from \"./doc-catalog\";\nimport {\n DOC_GATE_V1_DEFAULTS,\n type DocGateThresholds,\n type DocQuad,\n quadAreaFrac,\n quadBounds,\n} from \"./doc-gate-v1\";\n\nexport type FramingStatus =\n | \"no_document\"\n | \"too_far\"\n | \"too_close\"\n | \"edge_clipped\"\n | \"wrong_shape\"\n | \"tilted\"\n | \"ok\";\n\nexport type LightingStatus = \"too_dark\" | \"too_bright\" | \"ok\";\nexport type BlurStatus = \"blurry\" | \"ok\";\nexport type GlareStatus = \"glare\" | \"ok\";\n\n/** The per-frame analysis vector (every axis judged independently). */\nexport interface DocFrameAnalysis {\n framing: FramingStatus;\n lighting: LightingStatus;\n blur: BlurStatus;\n glare: GlareStatus;\n /** All-clear: every axis ok — the gate's integrator/stability input. */\n acceptable: boolean;\n}\n\nexport interface DocFrameMeasures {\n /** frame-quality sharpness on the doc-region crop (0..1). */\n sharpness: number;\n /** frame-quality exposure on the doc-region crop (0..1). */\n exposure: number;\n /** Mean crop luma (0..255) — picks too_dark vs too_bright. */\n meanLuma: number;\n /** Fraction of crop pixels at/above the specular ceiling (0..1). */\n specularFraction: number;\n}\n\n/** Analysis thresholds beyond the gate's — frozen defaults (round 4). */\nexport const DOC_ANALYSIS_DEFAULTS = Object.freeze({\n /** Doc area fraction above which the camera is too close (capture would crop). */\n MAX_AREA_FRAC: 0.92,\n /** Opposite-side length ratio beyond which the view is too oblique. */\n TILT_MAX_SIDE_RATIO: 1.3,\n /** Specular-pixel fraction at/above which the frame reads as glare. */\n GLARE_MAX_SPECULAR_FRAC: 0.025,\n});\n\n/** Fraction of crop pixels with luma ≥ 252 — cheap specular-highlight measure. */\nexport function specularFraction(crop: ImageData): number {\n const { data, width, height } = crop;\n const pixels = width * height;\n if (pixels === 0) return 0;\n let hot = 0;\n for (let i = 0; i < pixels; i++) {\n const o = i * 4;\n // Rec.601 luma, integer-ish — a specular blowout saturates all channels.\n const luma =\n 0.299 * (data[o] ?? 0) + 0.587 * (data[o + 1] ?? 0) + 0.114 * (data[o + 2] ?? 0);\n if (luma >= 252) hot++;\n }\n return hot / pixels;\n}\n\n/** Opposite-side length ratio of the quad (1 = fronto-parallel). */\nexport function quadTiltRatio(quad: DocQuad): number {\n const len = (a: { x: number; y: number }, b: { x: number; y: number }) =>\n Math.hypot(b.x - a.x, b.y - a.y);\n const top = len(quad.topLeft, quad.topRight);\n const bottom = len(quad.bottomLeft, quad.bottomRight);\n const left = len(quad.topLeft, quad.bottomLeft);\n const right = len(quad.topRight, quad.bottomRight);\n const h = Math.max(top, bottom) / Math.max(1e-6, Math.min(top, bottom));\n const v = Math.max(left, right) / Math.max(1e-6, Math.min(left, right));\n return Math.max(h, v);\n}\n\n/**\n * Judge one frame. `detectionMode` mirrors the gate: ID-1 quads carry\n * area/aspect/tilt semantics; ID-3 MRZ bands carry width-fraction semantics\n * (band rects are axis-aligned, so tilt/aspect checks are band-specific).\n */\nexport function analyzeDocFrame(input: {\n format: DocFormat;\n quad: DocQuad | null;\n frameWidth: number;\n frameHeight: number;\n measures: DocFrameMeasures;\n thresholds?: Partial<DocGateThresholds>;\n}): DocFrameAnalysis {\n const t = { ...DOC_GATE_V1_DEFAULTS, ...input.thresholds };\n const a = DOC_ANALYSIS_DEFAULTS;\n const { quad, frameWidth, frameHeight, measures } = input;\n const bandMode = input.format === \"ID-3\";\n\n let framing: FramingStatus = \"ok\";\n if (quad === null) {\n framing = \"no_document\";\n } else if (bandMode) {\n const bounds = quadBounds(quad);\n const widthFrac = frameWidth > 0 ? bounds.width / frameWidth : 0;\n const aspect = bounds.height > 0 ? bounds.width / bounds.height : 0;\n if (widthFrac < t.ID3_BAND_MIN_WIDTH_FRAC) framing = \"too_far\";\n else if (edgeClipped(quad, frameWidth, frameHeight, t.EDGE_CLIP_MARGIN_PX)) {\n framing = \"edge_clipped\";\n } else if (aspect < t.ID3_BAND_ASPECT_MIN || aspect > t.ID3_BAND_ASPECT_MAX) {\n framing = \"wrong_shape\";\n }\n } else {\n const areaFrac = quadAreaFrac(quad, frameWidth, frameHeight);\n const band = aspectBand(input.format);\n const bounds = quadBounds(quad);\n const aspect =\n Math.max(bounds.width, bounds.height) / Math.max(1e-6, Math.min(bounds.width, bounds.height));\n if (areaFrac < t.MIN_AREA_FRAC) framing = \"too_far\";\n else if (areaFrac > a.MAX_AREA_FRAC) framing = \"too_close\";\n else if (edgeClipped(quad, frameWidth, frameHeight, t.EDGE_CLIP_MARGIN_PX)) {\n framing = \"edge_clipped\";\n } else if (Math.abs(aspect - band.center) > band.tolerance) framing = \"wrong_shape\";\n else if (quadTiltRatio(quad) > a.TILT_MAX_SIDE_RATIO) framing = \"tilted\";\n }\n\n const lighting: LightingStatus =\n measures.exposure >= t.GUIDE_EXPOSURE\n ? \"ok\"\n : measures.meanLuma < (EXPOSURE_BAND[0] + EXPOSURE_BAND[1]) / 2\n ? \"too_dark\"\n : \"too_bright\";\n const blur: BlurStatus = measures.sharpness >= t.GUIDE_SHARPNESS ? \"ok\" : \"blurry\";\n const glare: GlareStatus =\n measures.specularFraction >= a.GLARE_MAX_SPECULAR_FRAC ? \"glare\" : \"ok\";\n\n return {\n framing,\n lighting,\n blur,\n glare,\n acceptable: framing === \"ok\" && lighting === \"ok\" && blur === \"ok\" && glare === \"ok\",\n };\n}\n\nfunction edgeClipped(\n quad: DocQuad,\n frameWidth: number,\n frameHeight: number,\n margin: number,\n): boolean {\n const pts = [quad.topLeft, quad.topRight, quad.bottomRight, quad.bottomLeft];\n return pts.some(\n (p) => p.x <= margin || p.y <= margin || p.x >= frameWidth - margin || p.y >= frameHeight - margin,\n );\n}\n","// Feedback aggregator (capture v2, Task-37 round 4) — the BlinkID-inspired\n// anti-flicker layer between per-frame analysis and the UI: each frame VOTES\n// for a feedback state; votes decay exponentially over a sliding window and\n// the DOMINANT state wins, but never before the current state's minimum\n// display duration has elapsed. Success states bypass voting entirely.\n//\n// 100% deterministic: the clock is an input (`nowMs`), the decay math is\n// closed-form — golden-testable tick sequences, no timers.\nimport type { DocFrameAnalysis } from \"./frame-analysis\";\n\n/** Feedback vocabulary (dcv2.* message keys on the hosted side). */\nexport type DocFeedbackKey =\n | \"sensing\"\n | \"too_far\"\n | \"too_close\"\n | \"edge_clipped\"\n | \"wrong_shape\"\n | \"tilted\"\n | \"too_dark\"\n | \"too_bright\"\n | \"blurry\"\n | \"glare\"\n | \"hold_still\"\n | \"processing\"\n | \"side_captured\"\n | \"captured\";\n\n/** Reticle rendering mode per feedback state (the stage maps to visuals). */\nexport type ReticleType = \"searching\" | \"coaching\" | \"locking\" | \"processing\" | \"flip\" | \"done\";\n\nexport interface DocFeedbackState {\n key: DocFeedbackKey;\n reticle: ReticleType;\n /** The state holds the UI at least this long (ms) before a switch. */\n minDurationMs: number;\n}\n\nexport const DOC_FEEDBACK_STATES: Readonly<Record<DocFeedbackKey, DocFeedbackState>> =\n Object.freeze({\n sensing: { key: \"sensing\", reticle: \"searching\", minDurationMs: 900 },\n too_far: { key: \"too_far\", reticle: \"coaching\", minDurationMs: 1400 },\n too_close: { key: \"too_close\", reticle: \"coaching\", minDurationMs: 1400 },\n edge_clipped: { key: \"edge_clipped\", reticle: \"coaching\", minDurationMs: 1400 },\n wrong_shape: { key: \"wrong_shape\", reticle: \"coaching\", minDurationMs: 1400 },\n tilted: { key: \"tilted\", reticle: \"coaching\", minDurationMs: 1400 },\n too_dark: { key: \"too_dark\", reticle: \"coaching\", minDurationMs: 1400 },\n too_bright: { key: \"too_bright\", reticle: \"coaching\", minDurationMs: 1400 },\n blurry: { key: \"blurry\", reticle: \"coaching\", minDurationMs: 1400 },\n glare: { key: \"glare\", reticle: \"coaching\", minDurationMs: 1400 },\n hold_still: { key: \"hold_still\", reticle: \"locking\", minDurationMs: 900 },\n processing: { key: \"processing\", reticle: \"processing\", minDurationMs: 800 },\n side_captured: { key: \"side_captured\", reticle: \"flip\", minDurationMs: 2600 },\n captured: { key: \"captured\", reticle: \"done\", minDurationMs: 800 },\n });\n\n/** Frame analysis → the feedback vote it casts (worst axis speaks). */\nexport function feedbackVoteOf(analysis: DocFrameAnalysis): DocFeedbackKey {\n if (analysis.framing === \"no_document\") return \"sensing\";\n if (analysis.framing === \"too_far\") return \"too_far\";\n if (analysis.framing === \"too_close\") return \"too_close\";\n if (analysis.framing === \"edge_clipped\") return \"edge_clipped\";\n if (analysis.framing === \"wrong_shape\") return \"wrong_shape\";\n if (analysis.framing === \"tilted\") return \"tilted\";\n if (analysis.lighting === \"too_dark\") return \"too_dark\";\n if (analysis.lighting === \"too_bright\") return \"too_bright\";\n if (analysis.glare === \"glare\") return \"glare\";\n if (analysis.blur === \"blurry\") return \"blurry\";\n return \"hold_still\";\n}\n\ninterface Vote {\n key: DocFeedbackKey;\n atMs: number;\n}\n\n/** Sliding vote window + exponential decay + per-state minimum hold. */\nexport class DocFeedbackAggregator {\n private votes: Vote[] = [];\n private current: DocFeedbackState = DOC_FEEDBACK_STATES.sensing;\n private currentSinceMs: number | null = null;\n\n constructor(\n private readonly windowMs = 2600,\n /** Per-second decay factor — recent frames outvote stale ones. */\n private readonly decayPerSecond = 0.35,\n ) {}\n\n reset(): void {\n this.votes = [];\n this.current = DOC_FEEDBACK_STATES.sensing;\n this.currentSinceMs = null;\n }\n\n /** Force a terminal/choreography state (capture fired, side flip, upload). */\n force(key: Extract<DocFeedbackKey, \"processing\" | \"side_captured\" | \"captured\">, nowMs: number): DocFeedbackState {\n this.votes = [];\n this.current = DOC_FEEDBACK_STATES[key];\n this.currentSinceMs = nowMs;\n return this.current;\n }\n\n /** Cast this frame's vote and return the (possibly held) winning state. */\n tick(vote: DocFeedbackKey, nowMs: number): DocFeedbackState {\n if (this.currentSinceMs === null) this.currentSinceMs = nowMs;\n this.votes.push({ key: vote, atMs: nowMs });\n this.votes = this.votes.filter((v) => nowMs - v.atMs <= this.windowMs);\n\n // Hold the current state through its minimum display duration.\n if (nowMs - this.currentSinceMs < this.current.minDurationMs) return this.current;\n\n const scores = new Map<DocFeedbackKey, number>();\n for (const v of this.votes) {\n const ageSeconds = (nowMs - v.atMs) / 1000;\n const weight = this.decayPerSecond ** ageSeconds; // 1 now → decays with age\n scores.set(v.key, (scores.get(v.key) ?? 0) + weight);\n }\n let winner: DocFeedbackKey = this.current.key;\n let best = -1;\n for (const [key, score] of scores) {\n if (score > best) {\n best = score;\n winner = key;\n }\n }\n if (winner !== this.current.key) {\n this.current = DOC_FEEDBACK_STATES[winner];\n this.currentSinceMs = nowMs;\n }\n return this.current;\n }\n}\n","// CaptureSessionDoc (Task 34) — the THIN document twin of CaptureSessionV3:\n// environment-facing camera, a 480px detect snapshot at the device profile's\n// cadence, DocGateV1 ticks, and on `ready` an UNCROPPED full-resolution still\n// (gate round 2: client-side quad cropping cut the MRZ when corners were off;\n// kyc-docs-v2 runs its own detector/warp — the client's job is timing, not\n// geometry). Same event contract SHAPE as CaptureSessionV3\n// (`statechange | checks | guidance | artifacts | error`) so hosts bind it\n// with the same hook pattern. Every effect is seam-injectable for tests; the\n// gate itself stays 100% deterministic (clock = tick input).\nimport { mapGetUserMediaError } from \"../media\";\nimport type { CaptureArtifacts, CaptureErrorKind, CaptureState } from \"../types\";\nimport { classifyDevice, type DeviceClass, probeDevice } from \"../v3/device-profile\";\nimport { exposure, meanLuma, sharpness } from \"../v3/frame-quality\";\nimport {\n DocFeedbackAggregator,\n type DocFeedbackState,\n feedbackVoteOf,\n} from \"./feedback-aggregator\";\nimport { analyzeDocFrame, type DocFrameAnalysis, specularFraction } from \"./frame-analysis\";\nimport type { DocFormat, DocSide } from \"./doc-catalog\";\nimport {\n DOC_DETECT_WIDTH,\n DocGateV1,\n type DocGateThresholds,\n type DocGateTick,\n type DocQuad,\n} from \"./doc-gate-v1\";\nimport { detectMrzBand } from \"./mrz-band\";\n\n/**\n * LAZY scanic load (route-budget contract): the vendored detector is ~39KiB gz\n * and must NOT ride the host's session-shell bundle — it is dynamically\n * imported on the FIRST detect tick (the camera-permission prompt gives the\n * fetch plenty of cover). Tests inject `opts.detect` and never touch this.\n */\nlet scanicDetect: ((image: ImageData) => Promise<DocQuad | null>) | null = null;\nasync function lazyScanicDetect(image: ImageData): Promise<DocQuad | null> {\n if (scanicDetect === null) {\n const module_ = await import(\"./detector-scanic\");\n scanicDetect = module_.detectQuad;\n }\n return scanicDetect(image);\n}\n\n/**\n * ID-3 detection (round 3): the MRZ stroke band, NOT page-edge quads — an\n * open booklet's page edges are white-on-white and defeat contour detection\n * (operator field finding, twice). The band rect becomes the gate's \"quad\"\n * (ID-3 band-mode geometry). Pure JS — no scanic on the passport path.\n */\nasync function mrzBandDetect(image: ImageData): Promise<DocQuad | null> {\n const band = detectMrzBand(image);\n if (band === null) return null;\n return {\n topLeft: { x: band.x, y: band.y },\n topRight: { x: band.x + band.width, y: band.y },\n bottomRight: { x: band.x + band.width, y: band.y + band.height },\n bottomLeft: { x: band.x, y: band.y + band.height },\n };\n}\n\n/**\n * Pre-fetch + cache the scanic chunk (call when the scan surface MOUNTS, before\n * the camera is even granted) so the first detect tick pays no chunk-fetch\n * latency. Fire-and-forget; failures fall back to the lazy path.\n */\nexport function warmDocDetector(): void {\n if (scanicDetect !== null) return;\n void import(\"./detector-scanic\")\n .then((module_) => {\n scanicDetect = module_.detectQuad;\n })\n .catch(() => undefined);\n}\n\n/** Doc detect cadence per device class — scanic @480px is ~3–8× a face tick,\n * so the doc loop paces slower than the face profiles (findings §1: 2–5 Hz). */\nexport const DOC_CADENCE_HZ: Readonly<Record<DeviceClass, number>> = Object.freeze({\n LOW: 3,\n MID: 5,\n HIGH: 6,\n});\n\nexport interface DocChecksPayload {\n engine: \"docv1\";\n /** Gate integrator 0..1 — the overlay ring. */\n p: number;\n plausible: boolean;\n stableTicks: number;\n quad: DocQuad | null;\n /** Detect-frame size the quad coordinates live in (overlay scaling). */\n frameWidth: number;\n frameHeight: number;\n /** Capture-v2 per-frame status vector (framing/lighting/blur/glare). */\n analysis: DocFrameAnalysis;\n}\n\n/** Artifacts: `keyframe` = the full-res still of the framed side (JPEG). */\nexport type DocArtifacts = CaptureArtifacts & { side?: DocSide };\n\nexport interface CaptureSessionDocEvents {\n statechange: { state: CaptureState };\n checks: DocChecksPayload;\n /** dcv1.* message KEY — hosts translate; never prose. Deduped. */\n guidance: { key: string };\n /** Capture-v2 AGGREGATED feedback (time-decay voted, min-duration held) —\n * the stage's message + reticle channel. Deduped on state key. */\n feedback: DocFeedbackState;\n artifacts: DocArtifacts;\n error: { kind: CaptureErrorKind; retryable: boolean };\n}\n\nexport interface CaptureSessionDocOptions {\n /** Host-owned <video playsInline muted>. */\n video: HTMLVideoElement;\n format?: DocFormat;\n /** Side label stamped on the artifacts event (recto→verso sequencing). */\n side?: DocSide;\n thresholds?: Partial<DocGateThresholds>;\n deviceClass?: DeviceClass;\n // ── seams (production defaults in parens) ─────────────────────────────────\n /** (navigator.mediaDevices.getUserMedia — environment camera) */\n getUserMedia?: (constraints: MediaStreamConstraints) => Promise<MediaStream>;\n /** (vendored scanic detectQuad) */\n detect?: (image: ImageData) => Promise<DocQuad | null>;\n /** (canvas downscale of the live video to the 480px detect frame) */\n grabDetectFrame?: (video: HTMLVideoElement, targetWidth: number) => ImageData | null;\n /** (full-res canvas still → JPEG blob + preview; quad passed for telemetry) */\n captureStill?: (\n video: HTMLVideoElement,\n quad: DocQuad,\n detectSize: { width: number; height: number },\n ) => Promise<{ blob: Blob; previewDataUrl: string }>;\n /** (performance.now) */\n now?: () => number;\n /** (setTimeout/clearTimeout) — the cadence pacer. */\n setTimer?: (fn: () => void, ms: number) => ReturnType<typeof setTimeout>;\n clearTimer?: (id: ReturnType<typeof setTimeout>) => void;\n}\n\ntype Handler<K extends keyof CaptureSessionDocEvents> = (\n payload: CaptureSessionDocEvents[K],\n) => void;\n\nexport class CaptureSessionDoc {\n private readonly opts: CaptureSessionDocOptions;\n private readonly gate: DocGateV1;\n private readonly cadenceMs: number;\n private readonly handlers = new Map<string, Set<(payload: never) => void>>();\n private stream: MediaStream | null = null;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private state: CaptureState = \"idle\";\n private lastGuidance: string | null = null;\n private attempt = 0;\n private capturing = false;\n private readonly feedback = new DocFeedbackAggregator();\n private lastFeedbackKey: string | null = null;\n\n constructor(opts: CaptureSessionDocOptions) {\n this.opts = opts;\n this.gate = new DocGateV1(opts.format ?? \"ID-1\", opts.thresholds);\n const deviceClass = opts.deviceClass ?? classifyDevice(probeDevice());\n this.cadenceMs = 1000 / DOC_CADENCE_HZ[deviceClass];\n }\n\n on<K extends keyof CaptureSessionDocEvents>(event: K, handler: Handler<K>): () => void {\n let set = this.handlers.get(event);\n if (!set) {\n set = new Set();\n this.handlers.set(event, set);\n }\n set.add(handler as (payload: never) => void);\n return () => set?.delete(handler as (payload: never) => void);\n }\n\n private emit<K extends keyof CaptureSessionDocEvents>(\n event: K,\n payload: CaptureSessionDocEvents[K],\n ): void {\n for (const handler of [...(this.handlers.get(event) ?? [])]) {\n (handler as Handler<K>)(payload);\n }\n }\n\n async start(): Promise<void> {\n const attempt = ++this.attempt;\n this.gate.reset();\n this.feedback.reset();\n this.lastFeedbackKey = null;\n this.lastGuidance = null;\n this.capturing = false;\n this.setState(\"preflight\");\n try {\n const getUserMedia =\n this.opts.getUserMedia ??\n ((constraints: MediaStreamConstraints) =>\n navigator.mediaDevices.getUserMedia(constraints));\n this.setState(\"acquiring\");\n this.stream = await getUserMedia({\n audio: false,\n video: {\n facingMode: { ideal: \"environment\" },\n width: { ideal: 1920 },\n height: { ideal: 1080 },\n },\n });\n if (attempt !== this.attempt) {\n for (const track of this.stream.getTracks()) track.stop();\n return;\n }\n this.opts.video.srcObject = this.stream;\n await this.opts.video.play().catch(() => undefined);\n this.setState(\"positioning\");\n this.scheduleTick(attempt);\n } catch (err) {\n const kind = mapGetUserMediaError(err);\n this.setState(\"error\");\n this.emit(\"error\", { kind, retryable: true });\n }\n }\n\n /** Restart the gate for another side / a retake (same stream). */\n rearm(side?: DocSide): void {\n if (side !== undefined) this.opts.side = side;\n this.gate.reset();\n this.feedback.reset();\n this.lastFeedbackKey = null;\n this.lastGuidance = null;\n this.capturing = false;\n if (this.state === \"captured\") {\n this.setState(\"positioning\");\n this.scheduleTick(this.attempt);\n }\n }\n\n destroy(): void {\n this.attempt += 1;\n if (this.timer !== null) (this.opts.clearTimer ?? clearTimeout)(this.timer);\n this.timer = null;\n if (this.stream) for (const track of this.stream.getTracks()) track.stop();\n this.stream = null;\n this.opts.video.srcObject = null;\n }\n\n private setState(state: CaptureState): void {\n this.state = state;\n this.emit(\"statechange\", { state });\n }\n\n private scheduleTick(attempt: number): void {\n const setTimer = this.opts.setTimer ?? setTimeout;\n this.timer = setTimer(() => void this.tick(attempt), this.cadenceMs);\n }\n\n private async tick(attempt: number): Promise<void> {\n if (attempt !== this.attempt || this.state !== \"positioning\" || this.capturing) return;\n const now = this.opts.now ?? (() => performance.now());\n const grab = this.opts.grabDetectFrame ?? defaultGrabDetectFrame;\n const detect =\n this.opts.detect ??\n ((this.opts.format ?? \"ID-1\") === \"ID-3\" ? mrzBandDetect : lazyScanicDetect);\n\n const frame = grab(this.opts.video, DOC_DETECT_WIDTH);\n if (frame === null) {\n this.scheduleTick(attempt);\n return;\n }\n let quad: DocQuad | null = null;\n try {\n quad = await detect(frame);\n } catch {\n quad = null; // a detector hiccup is a no-doc tick, never a crash\n }\n if (attempt !== this.attempt) return;\n\n const crop = quad !== null ? cropQuadRegion(frame, quad) : frame;\n const atMs = now();\n const measures = {\n sharpness: sharpness(crop),\n exposure: exposure(crop),\n meanLuma: meanLuma(crop),\n specularFraction: specularFraction(crop),\n };\n const analysis = analyzeDocFrame({\n format: this.opts.format ?? \"ID-1\",\n quad,\n frameWidth: frame.width,\n frameHeight: frame.height,\n measures,\n ...(this.opts.thresholds !== undefined ? { thresholds: this.opts.thresholds } : {}),\n });\n const tick = this.gate.tick({\n timestampMs: atMs,\n quad,\n quality: measures,\n frameWidth: frame.width,\n frameHeight: frame.height,\n });\n this.emit(\"checks\", {\n engine: \"docv1\",\n p: tick.p,\n plausible: tick.plausible,\n stableTicks: tick.stableTicks,\n quad: tick.quad,\n frameWidth: frame.width,\n frameHeight: frame.height,\n analysis,\n });\n // Capture-v2 feedback: time-decay voted + min-duration held (anti-flicker).\n const feedbackState = this.feedback.tick(feedbackVoteOf(analysis), atMs);\n if (feedbackState.key !== this.lastFeedbackKey) {\n this.lastFeedbackKey = feedbackState.key;\n this.emit(\"feedback\", feedbackState);\n }\n if (tick.guidanceKey !== this.lastGuidance) {\n this.lastGuidance = tick.guidanceKey;\n this.emit(\"guidance\", { key: tick.guidanceKey });\n }\n\n if (tick.ready && quad !== null) {\n const processing = this.feedback.force(\"processing\", atMs);\n this.lastFeedbackKey = processing.key;\n this.emit(\"feedback\", processing);\n await this.fire(attempt, quad, {\n width: frame.width,\n height: frame.height,\n tickSharpness: measures.sharpness,\n });\n return;\n }\n this.scheduleTick(attempt);\n }\n\n /**\n * BEST-FRAME capture window (capture-v2): the first ready tick captures a\n * candidate immediately, then up to CAPTURE_EXTRA_CANDIDATES more stills are\n * taken at CAPTURE_CANDIDATE_SPACING_MS while the user holds — each scored\n * by the live detect-tick sharpness at its capture moment — and the SHARPEST\n * wins. Beats first-acceptable-frame capture without decoding stills.\n */\n private async fire(\n attempt: number,\n quad: DocQuad,\n detectSize: { width: number; height: number; tickSharpness: number },\n ): Promise<void> {\n this.capturing = true;\n const capture = this.opts.captureStill ?? defaultCaptureStill;\n const grab = this.opts.grabDetectFrame ?? defaultGrabDetectFrame;\n const setTimer = this.opts.setTimer ?? setTimeout;\n const size = { width: detectSize.width, height: detectSize.height };\n try {\n let best = {\n still: await capture(this.opts.video, quad, size),\n sharpness: detectSize.tickSharpness,\n };\n for (let i = 0; i < CAPTURE_EXTRA_CANDIDATES; i++) {\n await new Promise<void>((resolve) => {\n setTimer(() => resolve(), CAPTURE_CANDIDATE_SPACING_MS);\n });\n if (attempt !== this.attempt) return;\n const frame = grab(this.opts.video, DOC_DETECT_WIDTH);\n if (frame === null) continue;\n const candidateSharpness = sharpness(cropQuadRegion(frame, quad));\n if (candidateSharpness > best.sharpness * CAPTURE_IMPROVEMENT_MIN_RATIO) {\n const still = await capture(this.opts.video, quad, size);\n if (attempt !== this.attempt) return;\n best = { still, sharpness: candidateSharpness };\n }\n }\n if (attempt !== this.attempt) return;\n this.setState(\"captured\");\n this.emit(\"artifacts\", {\n keyframe: best.still.blob,\n previewDataUrl: best.still.previewDataUrl,\n ...(this.opts.side !== undefined ? { side: this.opts.side } : {}),\n });\n } catch {\n if (attempt !== this.attempt) return;\n // Still capture failed (canvas/encode) — rearm the gate and keep coaching.\n this.capturing = false;\n this.gate.reset();\n this.scheduleTick(attempt);\n }\n }\n}\n\n/** Best-frame window: 2 extra candidates, 260ms apart, ≥8% sharper to replace. */\nexport const CAPTURE_EXTRA_CANDIDATES = 2;\nexport const CAPTURE_CANDIDATE_SPACING_MS = 260;\nconst CAPTURE_IMPROVEMENT_MIN_RATIO = 1.08;\n\n/** Downscale the live video to the detect width (aspect preserved). */\nfunction defaultGrabDetectFrame(video: HTMLVideoElement, targetWidth: number): ImageData | null {\n const vw = video.videoWidth;\n const vh = video.videoHeight;\n if (vw === 0 || vh === 0) return null;\n const scale = Math.min(1, targetWidth / vw);\n const width = Math.round(vw * scale);\n const height = Math.round(vh * scale);\n const canvas = document.createElement(\"canvas\");\n canvas.width = width;\n canvas.height = height;\n const context = canvas.getContext(\"2d\", { willReadFrequently: true });\n if (context === null) return null;\n context.drawImage(video, 0, 0, width, height);\n return context.getImageData(0, 0, width, height);\n}\n\n/**\n * Capture the FULL-RES frame (gate-timed, UNCROPPED — operator gate round 2):\n * client-side quad cropping cut the MRZ whenever the detected corners were\n * slightly off, and kyc-docs-v2 runs its OWN detector/warp on the server —\n * the client's job is TIMING (fire when framed/steady), not geometry. The\n * quad/detectSize params stay in the seam signature for telemetry/tests.\n */\nasync function defaultCaptureStill(\n video: HTMLVideoElement,\n _quad: DocQuad,\n _detectSize: { width: number; height: number },\n): Promise<{ blob: Blob; previewDataUrl: string }> {\n const canvas = document.createElement(\"canvas\");\n canvas.width = Math.max(1, video.videoWidth);\n canvas.height = Math.max(1, video.videoHeight);\n const context = canvas.getContext(\"2d\");\n if (context === null) throw new Error(\"2d context unavailable\");\n context.drawImage(video, 0, 0, canvas.width, canvas.height);\n const blob = await new Promise<Blob>((resolve, reject) => {\n canvas.toBlob((b) => (b ? resolve(b) : reject(new Error(\"toBlob failed\"))), \"image/jpeg\", 0.92);\n });\n return { blob, previewDataUrl: canvas.toDataURL(\"image/jpeg\", 0.85) };\n}\n\n/** Quad-bbox crop of the DETECT frame — the quality measures run on this. */\nfunction cropQuadRegion(frame: ImageData, quad: DocQuad): ImageData {\n const xs = [quad.topLeft.x, quad.topRight.x, quad.bottomRight.x, quad.bottomLeft.x];\n const ys = [quad.topLeft.y, quad.topRight.y, quad.bottomRight.y, quad.bottomLeft.y];\n const x1 = Math.max(0, Math.floor(Math.min(...xs)));\n const y1 = Math.max(0, Math.floor(Math.min(...ys)));\n const x2 = Math.min(frame.width, Math.ceil(Math.max(...xs)));\n const y2 = Math.min(frame.height, Math.ceil(Math.max(...ys)));\n const width = Math.max(1, x2 - x1);\n const height = Math.max(1, y2 - y1);\n const data = new Uint8ClampedArray(width * height * 4);\n for (let row = 0; row < height; row++) {\n const src = ((y1 + row) * frame.width + x1) * 4;\n data.set(frame.data.subarray(src, src + width * 4), row * width * 4);\n }\n return { data, width, height, colorSpace: frame.colorSpace } as ImageData;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCO,IAAM,oBAAiD,OAAO,OAAO;AAAA,EAC1E,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB,qBAAqB;AAAA,EACrB,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB,eAAe;AACjB,CAAC;AAED,IAAM,iBAAiB;AAOhB,SAAS,cACd,OACA,YAAwC,CAAC,GACzB;AAChB,QAAM,IAAI,EAAE,GAAG,mBAAmB,GAAG,UAAU;AAC/C,QAAM,EAAE,MAAM,OAAO,OAAO,IAAI;AAChC,MAAI,QAAQ,MAAM,SAAS,GAAI,QAAO;AAGtC,QAAM,YAAY,IAAI,MAAe,MAAM,EAAE,KAAK,KAAK;AACvD,QAAM,UAAU,IAAI,aAAa,MAAM;AACvC,QAAM,OAAO,IAAI,WAAW,MAAM,EAAE,KAAK,KAAK;AAC9C,QAAM,OAAO,IAAI,WAAW,MAAM,EAAE,KAAK,EAAE;AAE3C,QAAM,cAAc,QAAQ;AAC5B,QAAM,UAAU,IAAI,MAAe,cAAc;AACjD,WAAS,IAAI,GAAG,IAAI,QAAQ,KAAK;AAC/B,QAAI,QAAQ;AACZ,YAAQ,KAAK,KAAK;AAClB,UAAM,YAAY,IAAI,QAAQ;AAC9B,QAAI,eACF,SAAS,KAAK,SAAS,KAAK,KAC5B,SAAS,KAAK,YAAY,CAAC,KAAK,KAChC,SAAS,KAAK,YAAY,CAAC,KAAK;AAClC,aAAS,IAAI,GAAG,IAAI,OAAO,KAAK;AAC9B,YAAM,IAAI,YAAY,IAAI;AAC1B,YAAM,OACJ,SAAS,KAAK,CAAC,KAAK,KAAK,SAAS,KAAK,IAAI,CAAC,KAAK,KAAK,SAAS,KAAK,IAAI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GAAI,cAAc,IAAI;AAAA,EAChG,CAAC;AACD,SAAO,EAAE,MAAM,gBAAgB,OAAO,UAAU,cAAc,IAAI,EAAE;AACtE;AAGA,SAAS,eAAe,OAAkB,MAA0B;AAClE,QAAM,KAAK,CAAC,KAAK,QAAQ,GAAG,KAAK,SAAS,GAAG,KAAK,YAAY,GAAG,KAAK,WAAW,CAAC;AAClF,QAAM,KAAK,CAAC,KAAK,QAAQ,GAAG,KAAK,SAAS,GAAG,KAAK,YAAY,GAAG,KAAK,WAAW,CAAC;AAClF,QAAM,KAAK,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,IAAI,GAAG,EAAE,CAAC,CAAC;AAClD,QAAM,KAAK,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,IAAI,GAAG,EAAE,CAAC,CAAC;AAClD,QAAM,KAAK,KAAK,IAAI,MAAM,OAAO,KAAK,KAAK,KAAK,IAAI,GAAG,EAAE,CAAC,CAAC;AAC3D,QAAM,KAAK,KAAK,IAAI,MAAM,QAAQ,KAAK,KAAK,KAAK,IAAI,GAAG,EAAE,CAAC,CAAC;AAC5D,QAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,EAAE;AACjC,QAAM,SAAS,KAAK,IAAI,GAAG,KAAK,EAAE;AAClC,QAAM,OAAO,IAAI,kBAAkB,QAAQ,SAAS,CAAC;AACrD,WAAS,MAAM,GAAG,MAAM,QAAQ,OAAO;AACrC,UAAM,QAAQ,KAAK,OAAO,MAAM,QAAQ,MAAM;AAC9C,SAAK,IAAI,MAAM,KAAK,SAAS,KAAK,MAAM,QAAQ,CAAC,GAAG,MAAM,QAAQ,CAAC;AAAA,EACrE;AACA,SAAO,EAAE,MAAM,OAAO,QAAQ,YAAY,MAAM,WAAW;AAC7D;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/core/doc/mrz-band.ts","../../src/core/doc/frame-analysis.ts","../../src/core/doc/feedback-aggregator.ts","../../src/core/doc/capture-session-doc.ts"],"sourcesContent":["// MRZ-band detector (Task 37 round 3) — the passport path's detection signal.\n//\n// WHY: edge/contour detection (scanic) fails on passport data pages — an open\n// booklet's page edges are white-on-white, so quads lock late or onto the\n// wrong rectangle (operator field finding, twice). The industry-standard\n// approach (Scanbot/Regula/Dynamsoft; PyImageSearch's classic blackhat\n// pipeline; YOLO-MRZ) is to detect the MRZ ITSELF: two 44-char lines of\n// high-contrast OCR-B strokes — the one feature of a passport that is\n// reliably detectable in any framing. This is the pure-JS analog of the\n// blackhat+gradient pipeline: per-row horizontal-stroke density with a\n// column-coverage requirement, then the tallest qualifying row run.\n//\n// Deterministic, allocation-light, no wasm: ~2ms on a 480px frame in node —\n// cheap enough to run at full doc cadence on LOW devices.\n\nexport interface MrzBand {\n x: number;\n y: number;\n width: number;\n height: number;\n /** Mean qualifying-row stroke density (diagnostics/telemetry). */\n density: number;\n}\n\nexport interface MrzBandThresholds {\n /** Luma step that counts as a text stroke edge. */\n EDGE_LUMA_DELTA: number;\n /** Min fraction of a row's pixels that are stroke edges to qualify. */\n MIN_ROW_DENSITY: number;\n /** Row must have stroke edges spread across ≥ this fraction of 12 columns. */\n MIN_COLUMN_COVERAGE: number;\n /** Band width (stroke x-extent) as a fraction of frame width. */\n MIN_WIDTH_FRAC: number;\n /** Band height bounds as fractions of frame height (2–3 OCR-B lines). */\n MIN_HEIGHT_FRAC: number;\n MAX_HEIGHT_FRAC: number;\n /** Rows this close together merge into one band (inter-line gap). */\n ROW_MERGE_GAP: number;\n}\n\n/** Frozen defaults (goldens in test/doc/mrz-band.test.ts — retune together). */\nexport const MRZ_BAND_DEFAULTS: Readonly<MrzBandThresholds> = Object.freeze({\n EDGE_LUMA_DELTA: 40,\n MIN_ROW_DENSITY: 0.08,\n MIN_COLUMN_COVERAGE: 0.6,\n MIN_WIDTH_FRAC: 0.55,\n MIN_HEIGHT_FRAC: 0.02,\n MAX_HEIGHT_FRAC: 0.16,\n ROW_MERGE_GAP: 18,\n});\n\nconst COLUMN_BUCKETS = 12;\n\n/**\n * Detect the MRZ stroke band on a (≤480px) grayscale-able frame. Returns the\n * tight band rect in frame pixels, or null when no qualifying band exists\n * (no MRZ in view, or only a partial/narrow slice of one).\n */\nexport function detectMrzBand(\n frame: ImageData,\n overrides: Partial<MrzBandThresholds> = {},\n): MrzBand | null {\n const t = { ...MRZ_BAND_DEFAULTS, ...overrides };\n const { data, width, height } = frame;\n if (width < 32 || height < 32) return null;\n\n // Per-row: stroke-edge count + column coverage + x-extent.\n const qualifies = new Array<boolean>(height).fill(false);\n const density = new Float32Array(height);\n const minX = new Int32Array(height).fill(width);\n const maxX = new Int32Array(height).fill(-1);\n\n const bucketWidth = width / COLUMN_BUCKETS;\n const buckets = new Array<boolean>(COLUMN_BUCKETS);\n for (let y = 0; y < height; y++) {\n let edges = 0;\n buckets.fill(false);\n const rowOffset = y * width * 4;\n let previousLuma =\n 0.299 * (data[rowOffset] ?? 0) +\n 0.587 * (data[rowOffset + 1] ?? 0) +\n 0.114 * (data[rowOffset + 2] ?? 0);\n for (let x = 1; x < width; x++) {\n const i = rowOffset + x * 4;\n const luma =\n 0.299 * (data[i] ?? 0) + 0.587 * (data[i + 1] ?? 0) + 0.114 * (data[i + 2] ?? 0);\n if (Math.abs(luma - previousLuma) >= t.EDGE_LUMA_DELTA) {\n edges += 1;\n buckets[Math.min(COLUMN_BUCKETS - 1, Math.floor(x / bucketWidth))] = true;\n if (x < (minX[y] as number)) minX[y] = x;\n if (x > (maxX[y] as number)) maxX[y] = x;\n }\n previousLuma = luma;\n }\n density[y] = edges / width;\n const coverage = buckets.filter(Boolean).length / COLUMN_BUCKETS;\n qualifies[y] =\n density[y]! >= t.MIN_ROW_DENSITY &&\n coverage >= t.MIN_COLUMN_COVERAGE &&\n (maxX[y] as number) - (minX[y] as number) >= t.MIN_WIDTH_FRAC * width;\n }\n\n // Merge qualifying rows across the inter-line gap; keep the best band.\n let best: { top: number; bottom: number; rows: number } | null = null;\n let runTop = -1;\n let lastQualifying = -1;\n let runRows = 0;\n const flush = (bottom: number) => {\n if (runTop < 0) return;\n const bandHeight = bottom - runTop + 1;\n if (\n bandHeight >= t.MIN_HEIGHT_FRAC * height &&\n bandHeight <= t.MAX_HEIGHT_FRAC * height &&\n runRows >= 4 && // at least a few real stroke rows, not a lone edge\n (best === null || runRows > best.rows)\n ) {\n best = { top: runTop, bottom, rows: runRows };\n }\n runTop = -1;\n runRows = 0;\n };\n for (let y = 0; y < height; y++) {\n if (qualifies[y]) {\n if (runTop < 0) runTop = y;\n else if (y - lastQualifying > t.ROW_MERGE_GAP) {\n flush(lastQualifying);\n runTop = y;\n }\n lastQualifying = y;\n runRows += 1;\n }\n }\n flush(lastQualifying);\n if (best === null) return null;\n const band = best as { top: number; bottom: number; rows: number };\n\n // Tight x-extent + mean density over the band's qualifying rows.\n let x1 = width;\n let x2 = -1;\n let densitySum = 0;\n let densityRows = 0;\n for (let y = band.top; y <= band.bottom; y++) {\n if (!qualifies[y]) continue;\n if ((minX[y] as number) < x1) x1 = minX[y] as number;\n if ((maxX[y] as number) > x2) x2 = maxX[y] as number;\n densitySum += density[y] as number;\n densityRows += 1;\n }\n if (x2 - x1 < t.MIN_WIDTH_FRAC * width) return null;\n return {\n x: x1,\n y: band.top,\n width: x2 - x1,\n height: band.bottom - band.top + 1,\n density: densityRows > 0 ? densitySum / densityRows : 0,\n };\n}\n","// Doc frame analysis (capture v2, Task-37 round 4) — the BlinkID-inspired\n// PER-FRAME status vector: independent framing / lighting / blur / glare /\n// tilt verdicts instead of a single collapsed guidance key. Pure and\n// deterministic: inputs are the detection (quad or MRZ band rect-as-quad),\n// the doc-region crop's quality measures, and static thresholds — no clocks,\n// no I/O. The FeedbackAggregator votes over these statuses; DocGateV1's\n// integrator/stability logic consumes `framingOk`/`qualityOk`.\nimport { EXPOSURE_BAND } from \"../v3/frame-quality\";\nimport { aspectBand, type DocFormat } from \"./doc-catalog\";\nimport {\n DOC_GATE_V1_DEFAULTS,\n type DocGateThresholds,\n type DocQuad,\n quadAreaFrac,\n quadBounds,\n} from \"./doc-gate-v1\";\n\nexport type FramingStatus =\n | \"no_document\"\n | \"too_far\"\n | \"too_close\"\n | \"edge_clipped\"\n | \"wrong_shape\"\n | \"tilted\"\n | \"ok\";\n\nexport type LightingStatus = \"too_dark\" | \"too_bright\" | \"ok\";\nexport type BlurStatus = \"blurry\" | \"ok\";\nexport type GlareStatus = \"glare\" | \"ok\";\n\n/** The per-frame analysis vector (every axis judged independently). */\nexport interface DocFrameAnalysis {\n framing: FramingStatus;\n lighting: LightingStatus;\n blur: BlurStatus;\n glare: GlareStatus;\n /** All-clear: every axis ok — the gate's integrator/stability input. */\n acceptable: boolean;\n}\n\nexport interface DocFrameMeasures {\n /** frame-quality sharpness on the doc-region crop (0..1). */\n sharpness: number;\n /** frame-quality exposure on the doc-region crop (0..1). */\n exposure: number;\n /** Mean crop luma (0..255) — picks too_dark vs too_bright. */\n meanLuma: number;\n /** Fraction of crop pixels at/above the specular ceiling (0..1). */\n specularFraction: number;\n}\n\n/** Analysis thresholds beyond the gate's — frozen defaults (round 4). */\nexport const DOC_ANALYSIS_DEFAULTS = Object.freeze({\n /** Doc area fraction above which the camera is too close (capture would crop). */\n MAX_AREA_FRAC: 0.92,\n /** Opposite-side length ratio beyond which the view is too oblique. */\n TILT_MAX_SIDE_RATIO: 1.3,\n /** Specular-pixel fraction at/above which the frame reads as glare. */\n GLARE_MAX_SPECULAR_FRAC: 0.025,\n});\n\n/** Fraction of crop pixels with luma ≥ 252 — cheap specular-highlight measure. */\nexport function specularFraction(crop: ImageData): number {\n const { data, width, height } = crop;\n const pixels = width * height;\n if (pixels === 0) return 0;\n let hot = 0;\n for (let i = 0; i < pixels; i++) {\n const o = i * 4;\n // Rec.601 luma, integer-ish — a specular blowout saturates all channels.\n const luma =\n 0.299 * (data[o] ?? 0) + 0.587 * (data[o + 1] ?? 0) + 0.114 * (data[o + 2] ?? 0);\n if (luma >= 252) hot++;\n }\n return hot / pixels;\n}\n\n/** Opposite-side length ratio of the quad (1 = fronto-parallel). */\nexport function quadTiltRatio(quad: DocQuad): number {\n const len = (a: { x: number; y: number }, b: { x: number; y: number }) =>\n Math.hypot(b.x - a.x, b.y - a.y);\n const top = len(quad.topLeft, quad.topRight);\n const bottom = len(quad.bottomLeft, quad.bottomRight);\n const left = len(quad.topLeft, quad.bottomLeft);\n const right = len(quad.topRight, quad.bottomRight);\n const h = Math.max(top, bottom) / Math.max(1e-6, Math.min(top, bottom));\n const v = Math.max(left, right) / Math.max(1e-6, Math.min(left, right));\n return Math.max(h, v);\n}\n\n/**\n * Judge one frame. `detectionMode` mirrors the gate: ID-1 quads carry\n * area/aspect/tilt semantics; ID-3 MRZ bands carry width-fraction semantics\n * (band rects are axis-aligned, so tilt/aspect checks are band-specific).\n */\nexport function analyzeDocFrame(input: {\n format: DocFormat;\n quad: DocQuad | null;\n frameWidth: number;\n frameHeight: number;\n measures: DocFrameMeasures;\n thresholds?: Partial<DocGateThresholds>;\n}): DocFrameAnalysis {\n const t = { ...DOC_GATE_V1_DEFAULTS, ...input.thresholds };\n const a = DOC_ANALYSIS_DEFAULTS;\n const { quad, frameWidth, frameHeight, measures } = input;\n const bandMode = input.format === \"ID-3\";\n\n let framing: FramingStatus = \"ok\";\n if (quad === null) {\n framing = \"no_document\";\n } else if (bandMode) {\n const bounds = quadBounds(quad);\n const widthFrac = frameWidth > 0 ? bounds.width / frameWidth : 0;\n const aspect = bounds.height > 0 ? bounds.width / bounds.height : 0;\n if (widthFrac < t.ID3_BAND_MIN_WIDTH_FRAC) framing = \"too_far\";\n else if (edgeClipped(quad, frameWidth, frameHeight, t.EDGE_CLIP_MARGIN_PX)) {\n framing = \"edge_clipped\";\n } else if (aspect < t.ID3_BAND_ASPECT_MIN || aspect > t.ID3_BAND_ASPECT_MAX) {\n framing = \"wrong_shape\";\n }\n } else {\n const areaFrac = quadAreaFrac(quad, frameWidth, frameHeight);\n const band = aspectBand(input.format);\n const bounds = quadBounds(quad);\n const aspect =\n Math.max(bounds.width, bounds.height) / Math.max(1e-6, Math.min(bounds.width, bounds.height));\n if (areaFrac < t.MIN_AREA_FRAC) framing = \"too_far\";\n else if (areaFrac > a.MAX_AREA_FRAC) framing = \"too_close\";\n else if (edgeClipped(quad, frameWidth, frameHeight, t.EDGE_CLIP_MARGIN_PX)) {\n framing = \"edge_clipped\";\n } else if (Math.abs(aspect - band.center) > band.tolerance) framing = \"wrong_shape\";\n else if (quadTiltRatio(quad) > a.TILT_MAX_SIDE_RATIO) framing = \"tilted\";\n }\n\n const lighting: LightingStatus =\n measures.exposure >= t.GUIDE_EXPOSURE\n ? \"ok\"\n : measures.meanLuma < (EXPOSURE_BAND[0] + EXPOSURE_BAND[1]) / 2\n ? \"too_dark\"\n : \"too_bright\";\n const blur: BlurStatus = measures.sharpness >= t.GUIDE_SHARPNESS ? \"ok\" : \"blurry\";\n const glare: GlareStatus =\n measures.specularFraction >= a.GLARE_MAX_SPECULAR_FRAC ? \"glare\" : \"ok\";\n\n return {\n framing,\n lighting,\n blur,\n glare,\n acceptable: framing === \"ok\" && lighting === \"ok\" && blur === \"ok\" && glare === \"ok\",\n };\n}\n\nfunction edgeClipped(\n quad: DocQuad,\n frameWidth: number,\n frameHeight: number,\n margin: number,\n): boolean {\n const pts = [quad.topLeft, quad.topRight, quad.bottomRight, quad.bottomLeft];\n return pts.some(\n (p) => p.x <= margin || p.y <= margin || p.x >= frameWidth - margin || p.y >= frameHeight - margin,\n );\n}\n","// Feedback aggregator (capture v2, Task-37 round 4) — the BlinkID-inspired\n// anti-flicker layer between per-frame analysis and the UI: each frame VOTES\n// for a feedback state; votes decay exponentially over a sliding window and\n// the DOMINANT state wins, but never before the current state's minimum\n// display duration has elapsed. Success states bypass voting entirely.\n//\n// 100% deterministic: the clock is an input (`nowMs`), the decay math is\n// closed-form — golden-testable tick sequences, no timers.\nimport type { DocFrameAnalysis } from \"./frame-analysis\";\n\n/** Feedback vocabulary (dcv2.* message keys on the hosted side). */\nexport type DocFeedbackKey =\n | \"sensing\"\n | \"too_far\"\n | \"too_close\"\n | \"edge_clipped\"\n | \"wrong_shape\"\n | \"tilted\"\n | \"too_dark\"\n | \"too_bright\"\n | \"blurry\"\n | \"glare\"\n | \"hold_still\"\n | \"processing\"\n | \"side_captured\"\n | \"captured\";\n\n/** Reticle rendering mode per feedback state (the stage maps to visuals). */\nexport type ReticleType = \"searching\" | \"coaching\" | \"locking\" | \"processing\" | \"flip\" | \"done\";\n\nexport interface DocFeedbackState {\n key: DocFeedbackKey;\n reticle: ReticleType;\n /** The state holds the UI at least this long (ms) before a switch. */\n minDurationMs: number;\n}\n\nexport const DOC_FEEDBACK_STATES: Readonly<Record<DocFeedbackKey, DocFeedbackState>> =\n Object.freeze({\n sensing: { key: \"sensing\", reticle: \"searching\", minDurationMs: 900 },\n too_far: { key: \"too_far\", reticle: \"coaching\", minDurationMs: 1400 },\n too_close: { key: \"too_close\", reticle: \"coaching\", minDurationMs: 1400 },\n edge_clipped: { key: \"edge_clipped\", reticle: \"coaching\", minDurationMs: 1400 },\n wrong_shape: { key: \"wrong_shape\", reticle: \"coaching\", minDurationMs: 1400 },\n tilted: { key: \"tilted\", reticle: \"coaching\", minDurationMs: 1400 },\n too_dark: { key: \"too_dark\", reticle: \"coaching\", minDurationMs: 1400 },\n too_bright: { key: \"too_bright\", reticle: \"coaching\", minDurationMs: 1400 },\n blurry: { key: \"blurry\", reticle: \"coaching\", minDurationMs: 1400 },\n glare: { key: \"glare\", reticle: \"coaching\", minDurationMs: 1400 },\n hold_still: { key: \"hold_still\", reticle: \"locking\", minDurationMs: 900 },\n processing: { key: \"processing\", reticle: \"processing\", minDurationMs: 800 },\n side_captured: { key: \"side_captured\", reticle: \"flip\", minDurationMs: 2600 },\n captured: { key: \"captured\", reticle: \"done\", minDurationMs: 800 },\n });\n\n/** Frame analysis → the feedback vote it casts (worst axis speaks). */\nexport function feedbackVoteOf(analysis: DocFrameAnalysis): DocFeedbackKey {\n if (analysis.framing === \"no_document\") return \"sensing\";\n if (analysis.framing === \"too_far\") return \"too_far\";\n if (analysis.framing === \"too_close\") return \"too_close\";\n if (analysis.framing === \"edge_clipped\") return \"edge_clipped\";\n if (analysis.framing === \"wrong_shape\") return \"wrong_shape\";\n if (analysis.framing === \"tilted\") return \"tilted\";\n if (analysis.lighting === \"too_dark\") return \"too_dark\";\n if (analysis.lighting === \"too_bright\") return \"too_bright\";\n if (analysis.glare === \"glare\") return \"glare\";\n if (analysis.blur === \"blurry\") return \"blurry\";\n return \"hold_still\";\n}\n\ninterface Vote {\n key: DocFeedbackKey;\n atMs: number;\n}\n\n/** Sliding vote window + exponential decay + per-state minimum hold. */\nexport class DocFeedbackAggregator {\n private votes: Vote[] = [];\n private current: DocFeedbackState = DOC_FEEDBACK_STATES.sensing;\n private currentSinceMs: number | null = null;\n\n constructor(\n private readonly windowMs = 2600,\n /** Per-second decay factor — recent frames outvote stale ones. */\n private readonly decayPerSecond = 0.35,\n ) {}\n\n reset(): void {\n this.votes = [];\n this.current = DOC_FEEDBACK_STATES.sensing;\n this.currentSinceMs = null;\n }\n\n /** Force a terminal/choreography state (capture fired, side flip, upload). */\n force(key: Extract<DocFeedbackKey, \"processing\" | \"side_captured\" | \"captured\">, nowMs: number): DocFeedbackState {\n this.votes = [];\n this.current = DOC_FEEDBACK_STATES[key];\n this.currentSinceMs = nowMs;\n return this.current;\n }\n\n /** Cast this frame's vote and return the (possibly held) winning state. */\n tick(vote: DocFeedbackKey, nowMs: number): DocFeedbackState {\n if (this.currentSinceMs === null) this.currentSinceMs = nowMs;\n this.votes.push({ key: vote, atMs: nowMs });\n this.votes = this.votes.filter((v) => nowMs - v.atMs <= this.windowMs);\n\n // Hold the current state through its minimum display duration.\n if (nowMs - this.currentSinceMs < this.current.minDurationMs) return this.current;\n\n const scores = new Map<DocFeedbackKey, number>();\n for (const v of this.votes) {\n const ageSeconds = (nowMs - v.atMs) / 1000;\n const weight = this.decayPerSecond ** ageSeconds; // 1 now → decays with age\n scores.set(v.key, (scores.get(v.key) ?? 0) + weight);\n }\n let winner: DocFeedbackKey = this.current.key;\n let best = -1;\n for (const [key, score] of scores) {\n if (score > best) {\n best = score;\n winner = key;\n }\n }\n if (winner !== this.current.key) {\n this.current = DOC_FEEDBACK_STATES[winner];\n this.currentSinceMs = nowMs;\n }\n return this.current;\n }\n}\n","// CaptureSessionDoc (Task 34) — the THIN document twin of CaptureSessionV3:\n// environment-facing camera, a 480px detect snapshot at the device profile's\n// cadence, DocGateV1 ticks, and on `ready` an UNCROPPED full-resolution still\n// (gate round 2: client-side quad cropping cut the MRZ when corners were off;\n// kyc-docs-v2 runs its own detector/warp — the client's job is timing, not\n// geometry). Same event contract SHAPE as CaptureSessionV3\n// (`statechange | checks | guidance | artifacts | error`) so hosts bind it\n// with the same hook pattern. Every effect is seam-injectable for tests; the\n// gate itself stays 100% deterministic (clock = tick input).\nimport { mapGetUserMediaError } from \"../media\";\nimport type { CaptureArtifacts, CaptureErrorKind, CaptureState } from \"../types\";\nimport { classifyDevice, type DeviceClass, probeDevice } from \"../v3/device-profile\";\nimport { exposure, meanLuma, sharpness } from \"../v3/frame-quality\";\nimport {\n DocFeedbackAggregator,\n type DocFeedbackState,\n feedbackVoteOf,\n} from \"./feedback-aggregator\";\nimport { analyzeDocFrame, type DocFrameAnalysis, specularFraction } from \"./frame-analysis\";\nimport type { DocFormat, DocSide } from \"./doc-catalog\";\nimport {\n DOC_DETECT_WIDTH,\n DocGateV1,\n type DocGateThresholds,\n type DocGateTick,\n type DocQuad,\n} from \"./doc-gate-v1\";\nimport { detectMrzBand } from \"./mrz-band\";\n\n/**\n * LAZY scanic load (route-budget contract): the vendored detector is ~39KiB gz\n * and must NOT ride the host's session-shell bundle — it is dynamically\n * imported on the FIRST detect tick (the camera-permission prompt gives the\n * fetch plenty of cover). Tests inject `opts.detect` and never touch this.\n */\nlet scanicDetect: ((image: ImageData) => Promise<DocQuad | null>) | null = null;\nasync function lazyScanicDetect(image: ImageData): Promise<DocQuad | null> {\n if (scanicDetect === null) {\n const module_ = await import(\"./detector-scanic\");\n scanicDetect = module_.detectQuad;\n }\n return scanicDetect(image);\n}\n\n/**\n * ID-3 detection (round 3): the MRZ stroke band, NOT page-edge quads — an\n * open booklet's page edges are white-on-white and defeat contour detection\n * (operator field finding, twice). The band rect becomes the gate's \"quad\"\n * (ID-3 band-mode geometry). Pure JS — no scanic on the passport path.\n */\nasync function mrzBandDetect(image: ImageData): Promise<DocQuad | null> {\n const band = detectMrzBand(image);\n if (band === null) return null;\n return {\n topLeft: { x: band.x, y: band.y },\n topRight: { x: band.x + band.width, y: band.y },\n bottomRight: { x: band.x + band.width, y: band.y + band.height },\n bottomLeft: { x: band.x, y: band.y + band.height },\n };\n}\n\n/**\n * Pre-fetch + cache the scanic chunk (call when the scan surface MOUNTS, before\n * the camera is even granted) so the first detect tick pays no chunk-fetch\n * latency. Fire-and-forget; failures fall back to the lazy path.\n */\nexport function warmDocDetector(): void {\n if (scanicDetect !== null) return;\n void import(\"./detector-scanic\")\n .then((module_) => {\n scanicDetect = module_.detectQuad;\n })\n .catch(() => undefined);\n}\n\n/** Doc detect cadence per device class — scanic @480px is ~3–8× a face tick,\n * so the doc loop paces slower than the face profiles (findings §1: 2–5 Hz). */\nexport const DOC_CADENCE_HZ: Readonly<Record<DeviceClass, number>> = Object.freeze({\n LOW: 3,\n MID: 5,\n HIGH: 6,\n});\n\nexport interface DocChecksPayload {\n engine: \"docv1\";\n /** Gate integrator 0..1 — the overlay ring. */\n p: number;\n plausible: boolean;\n stableTicks: number;\n quad: DocQuad | null;\n /** Detect-frame size the quad coordinates live in (overlay scaling). */\n frameWidth: number;\n frameHeight: number;\n /** Capture-v2 per-frame status vector (framing/lighting/blur/glare). */\n analysis: DocFrameAnalysis;\n}\n\n/** Artifacts: `keyframe` = the full-res still of the framed side (JPEG). */\nexport type DocArtifacts = CaptureArtifacts & { side?: DocSide };\n\nexport interface CaptureSessionDocEvents {\n statechange: { state: CaptureState };\n checks: DocChecksPayload;\n /** dcv1.* message KEY — hosts translate; never prose. Deduped. */\n guidance: { key: string };\n /** Capture-v2 AGGREGATED feedback (time-decay voted, min-duration held) —\n * the stage's message + reticle channel. Deduped on state key. */\n feedback: DocFeedbackState;\n artifacts: DocArtifacts;\n error: { kind: CaptureErrorKind; retryable: boolean };\n}\n\nexport interface CaptureSessionDocOptions {\n /** Host-owned <video playsInline muted>. */\n video: HTMLVideoElement;\n format?: DocFormat;\n /** Side label stamped on the artifacts event (recto→verso sequencing). */\n side?: DocSide;\n thresholds?: Partial<DocGateThresholds>;\n deviceClass?: DeviceClass;\n // ── seams (production defaults in parens) ─────────────────────────────────\n /** (navigator.mediaDevices.getUserMedia — environment camera) */\n getUserMedia?: (constraints: MediaStreamConstraints) => Promise<MediaStream>;\n /** (vendored scanic detectQuad) */\n detect?: (image: ImageData) => Promise<DocQuad | null>;\n /** (canvas downscale of the live video to the 480px detect frame) */\n grabDetectFrame?: (video: HTMLVideoElement, targetWidth: number) => ImageData | null;\n /** (full-res canvas still → JPEG blob + preview; quad passed for telemetry) */\n captureStill?: (\n video: HTMLVideoElement,\n quad: DocQuad,\n detectSize: { width: number; height: number },\n ) => Promise<{ blob: Blob; previewDataUrl: string }>;\n /** (performance.now) */\n now?: () => number;\n /** (setTimeout/clearTimeout) — the cadence pacer. */\n setTimer?: (fn: () => void, ms: number) => ReturnType<typeof setTimeout>;\n clearTimer?: (id: ReturnType<typeof setTimeout>) => void;\n}\n\ntype Handler<K extends keyof CaptureSessionDocEvents> = (\n payload: CaptureSessionDocEvents[K],\n) => void;\n\nexport class CaptureSessionDoc {\n private readonly opts: CaptureSessionDocOptions;\n private readonly gate: DocGateV1;\n private readonly cadenceMs: number;\n private readonly handlers = new Map<string, Set<(payload: never) => void>>();\n private stream: MediaStream | null = null;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private state: CaptureState = \"idle\";\n private lastGuidance: string | null = null;\n private attempt = 0;\n private capturing = false;\n private readonly feedback = new DocFeedbackAggregator();\n private lastFeedbackKey: string | null = null;\n\n constructor(opts: CaptureSessionDocOptions) {\n this.opts = opts;\n this.gate = new DocGateV1(opts.format ?? \"ID-1\", opts.thresholds);\n const deviceClass = opts.deviceClass ?? classifyDevice(probeDevice());\n this.cadenceMs = 1000 / DOC_CADENCE_HZ[deviceClass];\n }\n\n on<K extends keyof CaptureSessionDocEvents>(event: K, handler: Handler<K>): () => void {\n let set = this.handlers.get(event);\n if (!set) {\n set = new Set();\n this.handlers.set(event, set);\n }\n set.add(handler as (payload: never) => void);\n return () => set?.delete(handler as (payload: never) => void);\n }\n\n private emit<K extends keyof CaptureSessionDocEvents>(\n event: K,\n payload: CaptureSessionDocEvents[K],\n ): void {\n for (const handler of [...(this.handlers.get(event) ?? [])]) {\n (handler as Handler<K>)(payload);\n }\n }\n\n async start(): Promise<void> {\n const attempt = ++this.attempt;\n this.gate.reset();\n this.feedback.reset();\n this.lastFeedbackKey = null;\n this.lastGuidance = null;\n this.capturing = false;\n this.setState(\"preflight\");\n try {\n const getUserMedia =\n this.opts.getUserMedia ??\n ((constraints: MediaStreamConstraints) =>\n navigator.mediaDevices.getUserMedia(constraints));\n this.setState(\"acquiring\");\n this.stream = await getUserMedia({\n audio: false,\n video: {\n facingMode: { ideal: \"environment\" },\n width: { ideal: 1920 },\n height: { ideal: 1080 },\n },\n });\n if (attempt !== this.attempt) {\n for (const track of this.stream.getTracks()) track.stop();\n return;\n }\n this.opts.video.srcObject = this.stream;\n await this.opts.video.play().catch(() => undefined);\n this.setState(\"positioning\");\n this.scheduleTick(attempt);\n } catch (err) {\n const kind = mapGetUserMediaError(err);\n this.setState(\"error\");\n this.emit(\"error\", { kind, retryable: true });\n }\n }\n\n /** Restart the gate for another side / a retake (same stream). */\n rearm(side?: DocSide): void {\n if (side !== undefined) this.opts.side = side;\n this.gate.reset();\n this.feedback.reset();\n this.lastFeedbackKey = null;\n this.lastGuidance = null;\n this.capturing = false;\n if (this.state === \"captured\") {\n this.setState(\"positioning\");\n this.scheduleTick(this.attempt);\n }\n }\n\n destroy(): void {\n this.attempt += 1;\n if (this.timer !== null) (this.opts.clearTimer ?? clearTimeout)(this.timer);\n this.timer = null;\n if (this.stream) for (const track of this.stream.getTracks()) track.stop();\n this.stream = null;\n this.opts.video.srcObject = null;\n }\n\n private setState(state: CaptureState): void {\n this.state = state;\n this.emit(\"statechange\", { state });\n }\n\n private scheduleTick(attempt: number): void {\n const setTimer = this.opts.setTimer ?? setTimeout;\n this.timer = setTimer(() => void this.tick(attempt), this.cadenceMs);\n }\n\n private async tick(attempt: number): Promise<void> {\n if (attempt !== this.attempt || this.state !== \"positioning\" || this.capturing) return;\n const now = this.opts.now ?? (() => performance.now());\n const grab = this.opts.grabDetectFrame ?? defaultGrabDetectFrame;\n const detect =\n this.opts.detect ??\n ((this.opts.format ?? \"ID-1\") === \"ID-3\" ? mrzBandDetect : lazyScanicDetect);\n\n const frame = grab(this.opts.video, DOC_DETECT_WIDTH);\n if (frame === null) {\n this.scheduleTick(attempt);\n return;\n }\n let quad: DocQuad | null = null;\n try {\n quad = await detect(frame);\n } catch {\n quad = null; // a detector hiccup is a no-doc tick, never a crash\n }\n if (attempt !== this.attempt) return;\n\n const crop = quad !== null ? cropQuadRegion(frame, quad) : frame;\n const atMs = now();\n const measures = {\n sharpness: sharpness(crop),\n exposure: exposure(crop),\n meanLuma: meanLuma(crop),\n specularFraction: specularFraction(crop),\n };\n const analysis = analyzeDocFrame({\n format: this.opts.format ?? \"ID-1\",\n quad,\n frameWidth: frame.width,\n frameHeight: frame.height,\n measures,\n ...(this.opts.thresholds !== undefined ? { thresholds: this.opts.thresholds } : {}),\n });\n const tick = this.gate.tick({\n timestampMs: atMs,\n quad,\n quality: measures,\n frameWidth: frame.width,\n frameHeight: frame.height,\n });\n this.emit(\"checks\", {\n engine: \"docv1\",\n p: tick.p,\n plausible: tick.plausible,\n stableTicks: tick.stableTicks,\n quad: tick.quad,\n frameWidth: frame.width,\n frameHeight: frame.height,\n analysis,\n });\n // Capture-v2 feedback: time-decay voted + min-duration held (anti-flicker).\n const feedbackState = this.feedback.tick(feedbackVoteOf(analysis), atMs);\n if (feedbackState.key !== this.lastFeedbackKey) {\n this.lastFeedbackKey = feedbackState.key;\n this.emit(\"feedback\", feedbackState);\n }\n if (tick.guidanceKey !== this.lastGuidance) {\n this.lastGuidance = tick.guidanceKey;\n this.emit(\"guidance\", { key: tick.guidanceKey });\n }\n\n if (tick.ready && quad !== null) {\n const processing = this.feedback.force(\"processing\", atMs);\n this.lastFeedbackKey = processing.key;\n this.emit(\"feedback\", processing);\n await this.fire(attempt, quad, {\n width: frame.width,\n height: frame.height,\n tickSharpness: measures.sharpness,\n });\n return;\n }\n this.scheduleTick(attempt);\n }\n\n /**\n * BEST-FRAME capture window (capture-v2): the first ready tick captures a\n * candidate immediately, then up to CAPTURE_EXTRA_CANDIDATES more stills are\n * taken at CAPTURE_CANDIDATE_SPACING_MS while the user holds — each scored\n * by the live detect-tick sharpness at its capture moment — and the SHARPEST\n * wins. Beats first-acceptable-frame capture without decoding stills.\n */\n private async fire(\n attempt: number,\n quad: DocQuad,\n detectSize: { width: number; height: number; tickSharpness: number },\n ): Promise<void> {\n this.capturing = true;\n const capture = this.opts.captureStill ?? defaultCaptureStill;\n const grab = this.opts.grabDetectFrame ?? defaultGrabDetectFrame;\n const setTimer = this.opts.setTimer ?? setTimeout;\n const size = { width: detectSize.width, height: detectSize.height };\n try {\n let best = {\n still: await capture(this.opts.video, quad, size),\n sharpness: detectSize.tickSharpness,\n };\n for (let i = 0; i < CAPTURE_EXTRA_CANDIDATES; i++) {\n await new Promise<void>((resolve) => {\n setTimer(() => resolve(), CAPTURE_CANDIDATE_SPACING_MS);\n });\n if (attempt !== this.attempt) return;\n const frame = grab(this.opts.video, DOC_DETECT_WIDTH);\n if (frame === null) continue;\n const candidateSharpness = sharpness(cropQuadRegion(frame, quad));\n if (candidateSharpness > best.sharpness * CAPTURE_IMPROVEMENT_MIN_RATIO) {\n const still = await capture(this.opts.video, quad, size);\n if (attempt !== this.attempt) return;\n best = { still, sharpness: candidateSharpness };\n }\n }\n if (attempt !== this.attempt) return;\n this.setState(\"captured\");\n this.emit(\"artifacts\", {\n keyframe: best.still.blob,\n previewDataUrl: best.still.previewDataUrl,\n ...(this.opts.side !== undefined ? { side: this.opts.side } : {}),\n });\n } catch {\n if (attempt !== this.attempt) return;\n // Still capture failed (canvas/encode) — rearm the gate and keep coaching.\n this.capturing = false;\n this.gate.reset();\n this.scheduleTick(attempt);\n }\n }\n}\n\n/** Best-frame window: 2 extra candidates, 260ms apart, ≥8% sharper to replace. */\nexport const CAPTURE_EXTRA_CANDIDATES = 2;\nexport const CAPTURE_CANDIDATE_SPACING_MS = 260;\nconst CAPTURE_IMPROVEMENT_MIN_RATIO = 1.08;\n\n/** Downscale the live video to the detect width (aspect preserved). */\nfunction defaultGrabDetectFrame(video: HTMLVideoElement, targetWidth: number): ImageData | null {\n const vw = video.videoWidth;\n const vh = video.videoHeight;\n if (vw === 0 || vh === 0) return null;\n const scale = Math.min(1, targetWidth / vw);\n const width = Math.round(vw * scale);\n const height = Math.round(vh * scale);\n const canvas = document.createElement(\"canvas\");\n canvas.width = width;\n canvas.height = height;\n const context = canvas.getContext(\"2d\", { willReadFrequently: true });\n if (context === null) return null;\n context.drawImage(video, 0, 0, width, height);\n return context.getImageData(0, 0, width, height);\n}\n\n/**\n * Capture the FULL-RES frame (gate-timed, UNCROPPED — operator gate round 2):\n * client-side quad cropping cut the MRZ whenever the detected corners were\n * slightly off, and kyc-docs-v2 runs its OWN detector/warp on the server —\n * the client's job is TIMING (fire when framed/steady), not geometry. The\n * quad/detectSize params stay in the seam signature for telemetry/tests.\n */\nasync function defaultCaptureStill(\n video: HTMLVideoElement,\n _quad: DocQuad,\n _detectSize: { width: number; height: number },\n): Promise<{ blob: Blob; previewDataUrl: string }> {\n const canvas = document.createElement(\"canvas\");\n canvas.width = Math.max(1, video.videoWidth);\n canvas.height = Math.max(1, video.videoHeight);\n const context = canvas.getContext(\"2d\");\n if (context === null) throw new Error(\"2d context unavailable\");\n context.drawImage(video, 0, 0, canvas.width, canvas.height);\n const blob = await new Promise<Blob>((resolve, reject) => {\n canvas.toBlob((b) => (b ? resolve(b) : reject(new Error(\"toBlob failed\"))), \"image/jpeg\", 0.92);\n });\n return { blob, previewDataUrl: canvas.toDataURL(\"image/jpeg\", 0.85) };\n}\n\n/** Quad-bbox crop of the DETECT frame — the quality measures run on this. */\nfunction cropQuadRegion(frame: ImageData, quad: DocQuad): ImageData {\n const xs = [quad.topLeft.x, quad.topRight.x, quad.bottomRight.x, quad.bottomLeft.x];\n const ys = [quad.topLeft.y, quad.topRight.y, quad.bottomRight.y, quad.bottomLeft.y];\n const x1 = Math.max(0, Math.floor(Math.min(...xs)));\n const y1 = Math.max(0, Math.floor(Math.min(...ys)));\n const x2 = Math.min(frame.width, Math.ceil(Math.max(...xs)));\n const y2 = Math.min(frame.height, Math.ceil(Math.max(...ys)));\n const width = Math.max(1, x2 - x1);\n const height = Math.max(1, y2 - y1);\n const data = new Uint8ClampedArray(width * height * 4);\n for (let row = 0; row < height; row++) {\n const src = ((y1 + row) * frame.width + x1) * 4;\n data.set(frame.data.subarray(src, src + width * 4), row * width * 4);\n }\n return { data, width, height, colorSpace: frame.colorSpace } as ImageData;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCO,IAAM,oBAAiD,OAAO,OAAO;AAAA,EAC1E,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB,qBAAqB;AAAA,EACrB,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB,eAAe;AACjB,CAAC;AAED,IAAM,iBAAiB;AAOhB,SAAS,cACd,OACA,YAAwC,CAAC,GACzB;AAChB,QAAM,IAAI,EAAE,GAAG,mBAAmB,GAAG,UAAU;AAC/C,QAAM,EAAE,MAAM,OAAO,OAAO,IAAI;AAChC,MAAI,QAAQ,MAAM,SAAS,GAAI,Q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K,KAAK,IAAI,GAAG,EAAE,CAAC,CAAC;AAC3D,QAAM,KAAK,KAAK,IAAI,MAAM,QAAQ,KAAK,KAAK,KAAK,IAAI,GAAG,EAAE,CAAC,CAAC;AAC5D,QAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,EAAE;AACjC,QAAM,SAAS,KAAK,IAAI,GAAG,KAAK,EAAE;AAClC,QAAM,OAAO,IAAI,kBAAkB,QAAQ,SAAS,CAAC;AACrD,WAAS,MAAM,GAAG,MAAM,QAAQ,OAAO;AACrC,UAAM,QAAQ,KAAK,OAAO,MAAM,QAAQ,MAAM;AAC9C,SAAK,IAAI,MAAM,KAAK,SAAS,KAAK,MAAM,QAAQ,CAAC,GAAG,MAAM,QAAQ,CAAC;AAAA,EACrE;AACA,SAAO,EAAE,MAAM,OAAO,QAAQ,YAAY,MAAM,WAAW;AAC7D;","names":[]}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/capture-constraints.ts","../src/core/media.ts","../src/core/clip-recorder.ts","../src/core/keyframe.ts","../src/core/v3/device-profile.ts","../src/core/v3/detect-scheduler.ts","../src/core/v3/face-gate-v3.ts","../src/core/v3/capture-session-v3.ts"],"sourcesContent":["// Shared capture helpers — used by BOTH the (now sole) v3 engine and the\n// hosted gate-debug overlay. Extracted from the former v1 capture-session.ts\n// when the v1 engine was removed: the camera constraint tier + the mobile\n// heuristic are engine-agnostic, and the gate-geometry factors feed the\n// hosted debug overlay's tolerance rings. Zero React, calibration-pinned.\n\n/** getUserMedia constraint tier — 720p-class on every device since 2026-07-06.\n * The v2 FAS-CLIP liveness head loses its texture cues below ~720p: the SAME\n * genuine clip scores heads 0.0001 at 720x1280 vs 0.355 at the old 480x360\n * mobile tier, which pushed real users into review (first observed live on\n * staging 2026-07-06; falsified on corpus clips the same day). Dimensions are\n * sensor-relative (landscape); mobile browsers deliver portrait via rotation\n * metadata, which the liveness service's decoder applies (cv2\n * ORIENTATION_AUTO). `isMobile` is kept for call-site compat and future\n * divergence — both tiers are 720p today. Bitrate pairs with VIDEO_BPS in\n * clip-recorder.ts (2.5 Mbps). */\nexport function buildCaptureConstraints(\n isMobile: boolean,\n facingMode: \"user\" | \"environment\",\n): MediaStreamConstraints {\n void isMobile;\n return {\n video: {\n width: { ideal: 1280, max: 1280 },\n height: { ideal: 720, max: 720 },\n facingMode: facingMode,\n frameRate: { ideal: 24, max: 30 },\n },\n audio: false,\n };\n}\n\n/** v1 mobile heuristic (FaceCaptureV2.tsx L216-224). */\nexport function detectIsMobile(): boolean {\n if (typeof window === \"undefined\" || typeof navigator === \"undefined\") return false;\n return (\n window.innerWidth <= 768 ||\n /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(\n String(navigator.userAgent ?? \"\"),\n )\n );\n}\n\n// ── gate geometry factors ─────────────────────────────────────────────────────\n// The calibration-pinned gate math the hosted `?debug=gate` overlay derives its\n// tolerance rings from (lib/gate-geometry-constants.ts). Kept exported here after\n// the v1 FaceGate was removed so the overlay never restates them as literals.\n\n/** Gate radius as a fraction of the guidance circle (v1 L501: circleSize × 0.45). */\nexport const CIRCLE_RADIUS_FACTOR = 0.45;\n/** `inCircle` tolerance as a fraction of the gate radius (v1 L508: r × 0.9). */\nexport const IN_CIRCLE_FACTOR = 0.9;\n/** `centered` tolerance as a fraction of the gate radius (v1 L509: r × 0.4). */\nexport const CENTERED_FACTOR = 0.4;\n","// PORTED byte-identical from kyc-ibtikar/lib/faceCaptureV2/media.ts (calibration-pinned\n// capture contract — spec §6 / risk 1). Do NOT edit without a calibration re-validation.\n\n// Pure, framework-free helpers for FaceCaptureV2. No React, minimal DOM.\n\n/** MP4-first ladder: one container (H.264 MP4) covers iOS/macOS Safari + Chrome 130+.\n * WebM/VP9→VP8 only as the Firefox/older-Chromium fallback. */\nexport const MIME_CANDIDATES = [\n \"video/mp4;codecs=avc1.42E01E,mp4a.40.2\",\n \"video/mp4;codecs=avc1.42E01E\",\n \"video/mp4\",\n \"video/webm;codecs=vp9,opus\",\n \"video/webm;codecs=vp9\",\n \"video/webm;codecs=vp8,opus\",\n \"video/webm;codecs=vp8\",\n \"video/webm\",\n] as const;\n\nexport type CameraErrorKind =\n | \"permission\"\n | \"notfound\"\n | \"inuse\"\n | \"overconstrained\"\n | \"insecure\"\n | \"unsupported\"\n | \"generic\";\n\n/** First supported candidate, or \"\" to let the browser pick its own default. */\nexport function pickMimeType(): string {\n const MR = (globalThis as unknown as { MediaRecorder?: { isTypeSupported?: (t: string) => boolean } })\n .MediaRecorder;\n if (!MR || typeof MR.isTypeSupported !== \"function\") return \"\";\n return MIME_CANDIDATES.find((t) => MR.isTypeSupported!(t)) ?? \"\";\n}\n\n/** Default clip container when pickMimeType() === \"\" — NEVER .bin/octet-stream (REVIEW FIX 5).\n * Prefer the first webm in the ladder the browser most likely defaults to. */\nexport const DEFAULT_CLIP_MIME = \"video/webm\";\n\n/** Branch on err.name (never the message). TypeError ⇒ navigator.mediaDevices was undefined\n * (insecure/unsupported context) — surfaced as \"insecure\". */\nexport function mapGetUserMediaError(err: unknown): CameraErrorKind {\n if (err instanceof TypeError) return \"insecure\";\n const name = (err as { name?: string })?.name ?? \"\";\n switch (name) {\n case \"NotAllowedError\":\n case \"PermissionDeniedError\":\n return \"permission\";\n case \"NotFoundError\":\n case \"DevicesNotFoundError\":\n return \"notfound\";\n case \"NotReadableError\":\n case \"TrackStartError\":\n return \"inuse\";\n case \"OverconstrainedError\":\n case \"ConstraintNotSatisfiedError\":\n return \"overconstrained\";\n default:\n return \"generic\";\n }\n}\n\nexport function cameraPreflight(): \"INSECURE_CONTEXT\" | \"UNSUPPORTED\" | \"OK\" {\n const w = globalThis as unknown as { window?: { isSecureContext?: boolean }; navigator?: Navigator };\n if (typeof w.window !== \"undefined\" && w.window.isSecureContext === false)\n return \"INSECURE_CONTEXT\";\n const md = (w.navigator as Navigator | undefined)?.mediaDevices as\n | { getUserMedia?: unknown }\n | undefined;\n if (!md || typeof md.getUserMedia !== \"function\") return \"UNSUPPORTED\";\n return \"OK\";\n}\n\n/** iOS Safari (and any browser) may lack MediaRecorder entirely — detect BEFORE prompting\n * for the camera so we can fall back to the v1 single-photo path (REVIEW FIX 1). */\nexport function isMediaRecorderSupported(): boolean {\n const MR = (globalThis as unknown as { MediaRecorder?: { isTypeSupported?: unknown } }).MediaRecorder;\n return typeof MR !== \"undefined\" && typeof (MR as { isTypeSupported?: unknown }).isTypeSupported === \"function\";\n}\n\nexport const MAX_CLIP_BYTES = 8 * 1024 * 1024; // 8 MB hard cap (shared with the /api/liveness/v2 contract)\nexport function isClipTooLarge(blob: Blob): boolean {\n return blob.size > MAX_CLIP_BYTES;\n}\n\nexport function extForMime(mime: string): string {\n const m = (mime || \"\").toLowerCase();\n if (m.startsWith(\"image/jpeg\")) return \"jpg\";\n if (m.startsWith(\"video/mp4\")) return \"mp4\";\n if (m.startsWith(\"video/webm\")) return \"webm\";\n // Never .bin — default to the clip container we actually record (REVIEW FIX 5).\n return \"webm\";\n}\n\n/** Build the exact multipart body /api/liveness/v2 expects: fields `token`, files `clip` + `keyframe`.\n * Caller must NOT set Content-Type — the browser adds the boundary. */\nexport function buildLivenessV2FormData(args: {\n token: string;\n clip: Blob;\n keyframe: Blob;\n ts?: number;\n}): FormData {\n const { token, clip, keyframe } = args;\n const ts = args.ts ?? Date.now();\n const clipType = clip.type || DEFAULT_CLIP_MIME;\n const kfType = keyframe.type || \"image/jpeg\";\n const fd = new FormData();\n fd.append(\"token\", token);\n fd.append(\"clip\", new File([clip], `liveness-${ts}.${extForMime(clipType)}`, { type: clipType }));\n fd.append(\"keyframe\", new File([keyframe], `keyframe-${ts}.${extForMime(kfType)}`, { type: kfType }));\n return fd;\n}\n","// De-hooked port of kyc-ibtikar/lib/faceCaptureV2/useClipRecorder.ts (calibration-pinned\n// capture contract — spec §6 / risk 1). Framework-free class: useRef → private fields,\n// useCallback(start) → record(), stopAndCleanup + the unmount useEffect → stop().\n// Behavior is the v1 hook's, VERBATIM (iOS workarounds included). Source line references\n// (kyc-ibtikar/lib/faceCaptureV2/useClipRecorder.ts):\n// - constants CLIP_MS / TIMESLICE_MS / STOP_GRACE_MS / VIDEO_BPS ............ L10-13\n// - ClipError(kind, msg?) .................................................. L15-21\n// - guarded double MediaRecorder construction (REVIEW FIX 1) ............... L47-63\n// - single-settle guard + timer clearing ................................... L66-71\n// - finalize: Blob(type = recorder.mimeType || picked || DEFAULT_CLIP_MIME)\n// + post-hoc size-cap check .............................................. L73-82\n// - incremental 8MB cap enforcement on dataavailable (REVIEW FIX 7) ........ L84-100\n// - onstop → finalize, onerror → generic, guarded start(TIMESLICE_MS) ...... L101-109\n// - hard stop at CLIP_MS + iOS stop-grace finalize (REVIEW FIX 3) .......... L111-124\n// - teardown: clear timers, stop recorder, stop ALL tracks (REVIEW FIX 8) .. L128-145\n// V2 additions on top of the verbatim behavior (both zero-impact on clip bytes, both\n// required because a class instance outlives one recording where v1's hook state was\n// remounted fresh): a re-entrancy guard in record(), and clearing stale timers when a\n// new recording starts. See the record() JSDoc.\n// Do NOT edit without a calibration re-validation.\nimport {\n pickMimeType,\n isClipTooLarge,\n MAX_CLIP_BYTES,\n DEFAULT_CLIP_MIME,\n type CameraErrorKind,\n} from \"./media\";\n\nexport const CLIP_MS = 2500; // 2.5s, within the 2.0–3.0s target window\nexport const TIMESLICE_MS = 1000; // periodic dataavailable — iOS reliability workaround\nexport const STOP_GRACE_MS = 1500; // iOS: if onstop never fires, finalize from chunks\n// 2.5 Mbps pairs with the 720p capture tier (capture-session.ts): 1.5 Mbps at\n// 720p over-compresses exactly the texture the FAS-CLIP head needs. ~0.8MB per\n// 2.5s clip — well under the 8MB client cap / 15MB server caps.\nexport const VIDEO_BPS = 2_500_000;\n\nexport type ClipErrorKind = CameraErrorKind | \"cliptoolarge\";\n\nexport class ClipError extends Error {\n kind: ClipErrorKind;\n constructor(kind: ClipErrorKind, msg?: string) {\n super(msg ?? kind);\n this.kind = kind;\n }\n}\n\nexport interface ClipResult {\n blob: Blob;\n /** Container mime the clip was finalized with (recorder.mimeType || picked || DEFAULT_CLIP_MIME). */\n mimeType: string;\n}\n\nexport class ClipRecorder {\n private recorder: MediaRecorder | null = null;\n private stream: MediaStream | null = null; // own field so teardown can stop tracks (REVIEW FIX 8)\n private chunks: Blob[] = [];\n private bytes = 0;\n private hardStopTimer: ReturnType<typeof setTimeout> | null = null;\n private graceTimer: ReturnType<typeof setTimeout> | null = null;\n private settled = false;\n\n private clearTimers(): void {\n if (this.hardStopTimer) clearTimeout(this.hardStopTimer);\n if (this.graceTimer) clearTimeout(this.graceTimer);\n this.hardStopTimer = null;\n this.graceTimer = null;\n }\n\n /** Records CLIP_MS of the stream. Resolves with the clip blob + its container mime;\n * rejects with ClipError. Behavior contract is the v1 hook's `start`, verbatim\n * (iOS workarounds included).\n *\n * ONE RECORDING AT A TIME: chunk/byte/timer state is shared per instance, so a\n * second record() while one is in flight rejects ClipError(\"generic\") instead of\n * corrupting the in-flight clip. (v2 guard — v1's hook was gated by its owning\n * component; a class API invites reuse. Zero impact on clip bytes.)\n *\n * `onStopped` (optional) fires ONCE the moment the CLIP_MS recording window\n * elapses (the hard-stop), BEFORE finalize — which on iOS can lag up to\n * STOP_GRACE_MS while onstop flushes the last chunk. It lets the host freeze\n * the display on the already-captured keyframe the instant recording ends,\n * instead of waiting for the blob. PURE NOTIFICATION — it does not touch\n * timers, chunks, or the finalize path, so it is calibration-neutral (no\n * effect on clip bytes). Never fires on a rejected capture (error /\n * cliptoolarge settle before the hard-stop and clear the timer). */\n record(stream: MediaStream, onStopped?: () => void): Promise<ClipResult> {\n if (this.recorder && !this.settled) {\n return Promise.reject(\n new ClipError(\n \"generic\",\n \"record() called while a recording is in flight — ClipRecorder handles one recording at a time\",\n ),\n );\n }\n this.recorder = null; // so a failed construction below never blocks a retry\n // De-hooking correction (zero impact on clip bytes): v1 got fresh refs per hook\n // mount, so a previous recording's post-settle grace timer (the hard-stop callback\n // arms it AFTER settle cleared timers — v1-verbatim) could never leak into a new\n // one. On a reused instance it would fire mid-flight, settle the fresh state, and\n // clear the new hard-stop timer — so drop stale timers before starting.\n this.clearTimers();\n this.chunks = [];\n this.bytes = 0;\n this.settled = false;\n this.stream = stream;\n const picked = pickMimeType();\n\n return new Promise<ClipResult>((resolve, reject) => {\n // Guarded construction — iOS Safari may lack MediaRecorder entirely (REVIEW FIX 1).\n let recorder: MediaRecorder;\n try {\n recorder = new MediaRecorder(\n stream,\n picked\n ? { mimeType: picked, videoBitsPerSecond: VIDEO_BPS }\n : { videoBitsPerSecond: VIDEO_BPS },\n );\n } catch {\n try {\n recorder = new MediaRecorder(stream); // last resort: browser defaults\n } catch {\n reject(new ClipError(\"unsupported\"));\n return;\n }\n }\n this.recorder = recorder;\n\n const settle = (fn: () => void) => {\n if (this.settled) return;\n this.settled = true;\n this.clearTimers();\n fn();\n };\n\n const finalize = () =>\n settle(() => {\n const type = recorder.mimeType || picked || DEFAULT_CLIP_MIME;\n const blob = new Blob(this.chunks, { type });\n if (isClipTooLarge(blob)) {\n reject(new ClipError(\"cliptoolarge\"));\n return;\n }\n resolve({ blob, mimeType: type });\n });\n\n recorder.ondataavailable = (e: BlobEvent) => {\n if (e.data && e.data.size) {\n this.chunks.push(e.data);\n this.bytes += e.data.size;\n // Enforce the 8MB cap INCREMENTALLY — stop + reject as soon as exceeded (REVIEW FIX 7).\n if (this.bytes > MAX_CLIP_BYTES) {\n settle(() => {\n try {\n if (recorder.state !== \"inactive\") recorder.stop();\n } catch {\n /* noop */\n }\n reject(new ClipError(\"cliptoolarge\"));\n });\n }\n }\n };\n recorder.onstop = finalize;\n recorder.onerror = () => settle(() => reject(new ClipError(\"generic\")));\n\n try {\n recorder.start(TIMESLICE_MS);\n } catch {\n settle(() => reject(new ClipError(\"generic\")));\n return;\n }\n\n // Hard stop at CLIP_MS; gate on state, not on frame count.\n this.hardStopTimer = setTimeout(() => {\n // Recording window elapsed — the clip is DONE. Notify BEFORE finalize\n // (which may lag on iOS) so the host can freeze on the keyframe now.\n // Guarded by `settled`: an error/cliptoolarge before the hard-stop has\n // already cleared this timer, so this only runs for a real stop.\n if (!this.settled) onStopped?.();\n if (recorder.state !== \"inactive\") {\n try {\n recorder.stop();\n } catch {\n finalize();\n }\n // iOS safety-net: onstop may never fire — finalize from chunks (REVIEW FIX 3).\n this.graceTimer = setTimeout(finalize, STOP_GRACE_MS);\n } else {\n finalize();\n }\n }, CLIP_MS);\n });\n }\n\n /** Idempotent teardown: stop recorder + ALL tracks (v1 `stopAndCleanup` + the unmount\n * effect). Optional `stream` override mirrors v1's `stopAndCleanup(stream?)`.\n *\n * MID-RECORDING SEMANTICS (verbatim v1): calling stop() while a record() is in\n * flight may LATER resolve the pending promise with a TRUNCATED clip (recorder.stop()\n * fires onstop → finalize from whatever chunks arrived so far), or — because this\n * method clears the hard-stop/grace timers — never settle it at all if onstop never\n * fires (the iOS grace path has been torn down). Callers MUST NOT treat a resolution\n * arriving after stop() as a full CLIP_MS clip, and must not await a record()\n * promise past stop() without their own timeout. (Task 4's CaptureSession owns\n * sequencing on top of this contract.) */\n stop(stream?: MediaStream | null): void {\n this.clearTimers();\n const rec = this.recorder;\n if (rec && rec.state !== \"inactive\") {\n try {\n rec.stop();\n } catch {\n /* noop */\n }\n }\n this.recorder = null;\n const s = stream ?? this.stream;\n s?.getTracks().forEach((t) => t.stop());\n this.stream = null;\n }\n}\n","// PORTED byte-identical from kyc-ibtikar/lib/faceCaptureV2/keyframe.ts (calibration-pinned\n// capture contract — spec §6 / risk 1). Do NOT edit without a calibration re-validation.\n\n// Grab ONE mirrored frontal keyframe from the live <video> into a JPEG Blob (a file part,\n// not a dataURL). Mirror matches the selfie preview (front camera), same as FaceCapture v1.\nexport function captureMirroredKeyframe(\n video: HTMLVideoElement,\n canvas: HTMLCanvasElement,\n quality = 0.92,\n): Promise<Blob> {\n return new Promise((resolve, reject) => {\n const w = video.videoWidth;\n const h = video.videoHeight;\n if (!w || !h) {\n reject(new Error(\"video-not-ready\"));\n return;\n }\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) {\n reject(new Error(\"no-2d-context\"));\n return;\n }\n canvas.width = w;\n canvas.height = h;\n ctx.scale(-1, 1);\n ctx.drawImage(video, -w, 0);\n canvas.toBlob(\n (blob) => (blob ? resolve(blob) : reject(new Error(\"empty-keyframe\"))),\n \"image/jpeg\",\n quality,\n );\n });\n}\n","// Device profiles (Task 9) — LOW/MID/HIGH from a boot probe, refined by the\n// first measured detect times. Profiles adapt DETECTION cost only (cadence,\n// downscale input width, animation richness): clip constraints are NOT here —\n// the 720p/2.5Mbps floor is global (locked decision 1) and lives in the v1\n// constraint builder both engines share.\n\nexport type DeviceClass = \"LOW\" | \"MID\" | \"HIGH\";\n\nexport interface DeviceProfile {\n /** Detection cadence — the scheduler's pace. */\n cadenceHz: number;\n /** Downscaled snapshot width handed to the detector. */\n inputWidth: number;\n /** Chrome hint: 'reduced' tones down ticks/breathe on LOW even without\n * prefers-reduced-motion. */\n animations: \"full\" | \"reduced\";\n}\n\nexport const DEVICE_PROFILES: Readonly<Record<DeviceClass, Readonly<DeviceProfile>>> =\n Object.freeze({\n LOW: Object.freeze({ cadenceHz: 5, inputWidth: 128, animations: \"reduced\" as const }),\n MID: Object.freeze({ cadenceHz: 8, inputWidth: 160, animations: \"full\" as const }),\n HIGH: Object.freeze({ cadenceHz: 10, inputWidth: 192, animations: \"full\" as const }),\n });\n\nexport interface DeviceProbe {\n cores: number;\n /** null where the UA hides it — iOS Safari NEVER exposes deviceMemory\n * (field lesson: a 2GB default classified every iPhone LOW). Unknown is\n * treated as NEUTRAL (4GB): never demotes to LOW on its own, never\n * promotes to HIGH; the dynamic profiler corrects truly slow devices. */\n memGB: number | null;\n /** WebAssembly SIMD available (informs wasm-tier expectations/telemetry). */\n simd: boolean;\n}\n\n/** Canonical WASM SIMD feature-test module (validates only where SIMD is\n * supported) — the standard wasm-feature-detect bytes. */\nconst SIMD_TEST_BYTES = new Uint8Array([\n 0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65, 0, 253,\n 15, 253, 98, 11,\n]);\n\nexport function probeDevice(): DeviceProbe {\n const nav = typeof navigator === \"undefined\" ? undefined : navigator;\n let simd = false;\n try {\n simd = typeof WebAssembly !== \"undefined\" && WebAssembly.validate(SIMD_TEST_BYTES);\n } catch {\n simd = false;\n }\n return {\n cores: nav?.hardwareConcurrency ?? 2,\n memGB: (nav as { deviceMemory?: number } | undefined)?.deviceMemory ?? null,\n simd,\n };\n}\n\n/** Static class: LOW (<4 cores or <3GB), HIGH (≥8 cores AND ≥6GB), else MID.\n * Unknown memory counts as a neutral 4GB (see DeviceProbe.memGB). */\nexport function classifyDevice(probe: DeviceProbe): DeviceClass {\n const memGB = probe.memGB ?? 4;\n if (probe.cores < 4 || memGB < 3) return \"LOW\";\n if (probe.cores >= 8 && memGB >= 6) return \"HIGH\";\n return \"MID\";\n}\n\nconst ORDER: DeviceClass[] = [\"LOW\", \"MID\", \"HIGH\"];\n\n/** Dynamic refinement: after the FIRST 10 measured detect ticks, a mean over\n * 70ms demotes straight to LOW; under 25ms promotes ONE class — at most one\n * adjustment ever (no oscillation). */\nexport class DeviceProfiler {\n private current: DeviceClass;\n private readonly samples: number[] = [];\n private adjusted = false;\n\n constructor(initial: DeviceClass) {\n this.current = initial;\n }\n\n get deviceClass(): DeviceClass {\n return this.current;\n }\n\n get profile(): DeviceProfile {\n return DEVICE_PROFILES[this.current];\n }\n\n record(detectMs: number): DeviceClass {\n if (this.adjusted || this.samples.length >= 10) return this.current;\n this.samples.push(detectMs);\n if (this.samples.length < 10) return this.current;\n this.adjusted = true;\n const mean = this.samples.reduce((sum, value) => sum + value, 0) / this.samples.length;\n if (mean > 70) {\n this.current = \"LOW\";\n } else if (mean < 25) {\n const index = ORDER.indexOf(this.current);\n this.current = ORDER[Math.min(ORDER.length - 1, index + 1)] ?? this.current;\n }\n return this.current;\n }\n}\n","// Detect scheduler (Task 9) — paces the detection pass at the profile's\n// cadence, preferring requestVideoFrameCallback (runs only when a REAL camera\n// frame arrived) with a plain interval fallback. A tick whose predecessor is\n// still in flight is SKIPPED — never queued (no backlog on a slow device) —\n// and counted as a degrade for telemetry.\n\nexport interface DetectSchedulerOptions {\n /** Ticks per second (profile cadenceHz). */\n cadenceHz: number;\n /** One detection pass — the scheduler awaits it and measures wall time. */\n run: () => Promise<void>;\n /** When provided AND it exposes requestVideoFrameCallback, ticks ride real\n * camera frames (throttled to the cadence) instead of a timer. */\n video?: HTMLVideoElement;\n /** Injectable clock (tests) — defaults to performance.now. */\n now?: () => number;\n}\n\ninterface VideoFrameCallbackTarget {\n requestVideoFrameCallback?: (callback: () => void) => number;\n cancelVideoFrameCallback?: (id: number) => void;\n}\n\n/** Rolling window for meanDetectMs. */\nconst STATS_WINDOW = 20;\n\nexport class DetectScheduler {\n private readonly options: DetectSchedulerOptions;\n private readonly periodMs: number;\n private timer: ReturnType<typeof setInterval> | null = null;\n private frameCallbackId: number | null = null;\n private running = false;\n private busy = false;\n private lastRunAt = Number.NEGATIVE_INFINITY;\n private degradeCount = 0;\n private readonly durations: number[] = [];\n\n constructor(options: DetectSchedulerOptions) {\n this.options = options;\n this.periodMs = 1000 / options.cadenceHz;\n }\n\n start(): void {\n if (this.running) return;\n this.running = true;\n const video = this.options.video as VideoFrameCallbackTarget | undefined;\n if (typeof video?.requestVideoFrameCallback === \"function\") {\n const loop = () => {\n if (!this.running) return;\n this.frameCallbackId = video.requestVideoFrameCallback?.(() => {\n this.frameCallbackId = null;\n // Throttle: camera frames arrive faster than the cadence.\n if (this.now() - this.lastRunAt >= this.periodMs) this.tick();\n loop();\n }) as number;\n };\n loop();\n return;\n }\n this.timer = setInterval(() => this.tick(), this.periodMs);\n }\n\n stop(): void {\n this.running = false;\n if (this.timer !== null) {\n clearInterval(this.timer);\n this.timer = null;\n }\n if (this.frameCallbackId !== null) {\n (this.options.video as VideoFrameCallbackTarget | undefined)?.cancelVideoFrameCallback?.(\n this.frameCallbackId,\n );\n this.frameCallbackId = null;\n }\n }\n\n stats(): { degradeCount: number; meanDetectMs: number } {\n const meanDetectMs =\n this.durations.length === 0\n ? 0\n : this.durations.reduce((sum, value) => sum + value, 0) / this.durations.length;\n return { degradeCount: this.degradeCount, meanDetectMs };\n }\n\n private now(): number {\n return this.options.now?.() ?? performance.now();\n }\n\n private tick(): void {\n if (!this.running) return;\n if (this.busy) {\n // Skip-when-busy: no queue growth on slow devices; telemetry counts it.\n this.degradeCount += 1;\n return;\n }\n this.busy = true;\n this.lastRunAt = this.now();\n const startedAt = this.now();\n this.options\n .run()\n .catch(() => undefined) // a failed pass must never kill the loop\n .finally(() => {\n this.busy = false;\n this.durations.push(this.now() - startedAt);\n if (this.durations.length > STATS_WINDOW) this.durations.shift();\n });\n }\n}\n","// FaceGateV3 (Task 8) — the v3 gate: scale-invariant, landmark-aware,\n// continuous-quality, gentle-drain. PARALLEL to the calibration-pinned v1\n// FaceGate (face-gate.ts) — nothing here feeds or alters v1's math.\n//\n// Design deltas vs v1 (the two field complaints this kills):\n// - the gate point is the EYE MIDPOINT when the tier provides eyes (humans\n// center their EYES, detectors center their BBOX — v1's bbox-center gate\n// read a centered face as \"high\"); box-only tiers get a documented\n// 0.12×height upward shift instead;\n// - progress is a CONTINUOUS integrator (rise 0.9/s on good quality, fall\n// 0.25/s on bad) instead of v1's ±counters — a wobble dips the progress\n// slightly instead of resetting the attempt.\n//\n// q AGGREGATION = MIN over factors (operator ruling 2026-07-12, replacing\n// the original 7-factor PRODUCT). Field finding: with a product, seven\n// factors each at a decent 0.85 gave q≈0.32 — progress DRAINED while every\n// factor sat above its guidance threshold, so the chrome said \"hold still\"\n// and the only discoverable escape was leaning unnaturally close (size,\n// centering falloff (∝IOD) and crop sharpness all improve together with\n// proximity). min() makes q the same quantity guidance reasons about — the\n// worst factor — so \"no complaint\" ⇔ \"progress rises\" by construction, one\n// genuinely bad factor still blocks (non-compensatory), and many mediocre\n// factors (the low-end-device reality: noisy sensor, dim room, wide FOV)\n// are no longer multiplied into failure.\n//\n// 100% deterministic: the clock is a tick INPUT (timestampMs); nothing here\n// reads Date.now or performance.now.\nimport type { FaceObservation } from \"./detector\";\nimport { EXPOSURE_BAND } from \"./frame-quality\";\n\nexport interface V3GateThresholds {\n /** q at/above which progress rises; below it progress falls. */\n Q_GOOD: number;\n /** Integrator slopes, per second. */\n RISE_PER_S: number;\n FALL_PER_S: number;\n /** Centering falloff radius = this × IOD (scale-invariant). The plan's\n * formula is 0.45 × IOD × 3 — the 0.45 echoes v1's CIRCLE_RADIUS_FACTOR\n * heritage — folded here to 1.35 × IOD. */\n CENTER_FALLOFF_IOD_MULTIPLE: number;\n /** Box-only tiers: gate point = bbox center shifted UP by this × height\n * (the documented bbox-vs-eyes offset heuristic). */\n BOX_EYE_OFFSET_FACTOR: number;\n /** Box-only IOD proxy = this × box width. */\n IOD_BOX_PROXY_FACTOR: number;\n /** IOD / frame short side: ideal band + hard limits. */\n SIZE_IDEAL_MIN: number;\n SIZE_IDEAL_MAX: number;\n SIZE_HARD_MIN: number;\n SIZE_HARD_MAX: number;\n /** Eye-line roll (deg) that zeroes the pose factor. */\n ROLL_MAX_DEG: number;\n /** Center velocity that zeroes the motion factor, in IOD-per-second. */\n MOTION_VELOCITY_IOD_PER_S: number;\n /** Velocity-EMA time constant (seconds) — the EMA weight is derived per\n * tick as 1−exp(−dt/τ), so the smoothing HORIZON is cadence-invariant:\n * a LOW device detecting at 5 Hz gets the same effective smoothing as a\n * HIGH device at 10 Hz (a fixed per-sample alpha under-smoothed exactly\n * the jittery low-cadence ticks that needed it most). */\n MOTION_TAU_S: number;\n /** Velocities at/below this (IOD/s) count as stillness — absorbs detector\n * box jitter (largest on LOW's 128px input) before it reaches the EMA. */\n MOTION_DEADBAND_IOD_PER_S: number;\n /** ready = p ≥ 1 AND no bad tick (q < Q_GOOD) left in this window after\n * TRIMMING: with ≥3 samples the single worst is dropped, so one flaky tick\n * (5 Hz LOW cadence = only 2–3 samples per window) cannot veto an\n * otherwise-ready user, while a SECOND bad tick (a real sustained wobble)\n * still blocks. The readiness bar is Q_GOOD itself — the level the\n * integrator rises on — so any input that fills the ring also fires it. */\n READY_WINDOW_MS: number;\n /** Per-factor guidance trigger levels (lowest failing factor speaks). */\n GUIDE_SIZE: number;\n GUIDE_CENTERING: number;\n GUIDE_POSE: number;\n GUIDE_EXPOSURE: number;\n GUIDE_SHARPNESS: number;\n GUIDE_MOTION: number;\n}\n\n/** Defaults — retuned 2026-07-12 (operator ruling superseding the 2026-07\n * freeze; the capture Task-15 refit set must be split at this boundary):\n * Q_GOOD 0.55→0.6 so it aligns with the 0.6 guidance thresholds under\n * min-q (\"no complaint\" ⇔ \"progress rises\"); SIZE_IDEAL_MIN 0.16→0.12 —\n * wide-FOV front cameras (common low-end) put an arm's-length face below\n * 0.16, silently forcing lean-in; the 720p clip floor keeps a 0.12-IOD\n * face fully resolvable server-side. */\nexport const V3_GATE_DEFAULTS: Readonly<V3GateThresholds> = Object.freeze({\n Q_GOOD: 0.6,\n RISE_PER_S: 0.9,\n FALL_PER_S: 0.25,\n CENTER_FALLOFF_IOD_MULTIPLE: 1.35,\n BOX_EYE_OFFSET_FACTOR: 0.12,\n IOD_BOX_PROXY_FACTOR: 0.42,\n SIZE_IDEAL_MIN: 0.12,\n SIZE_IDEAL_MAX: 0.3,\n SIZE_HARD_MIN: 0.08,\n SIZE_HARD_MAX: 0.45,\n ROLL_MAX_DEG: 25,\n MOTION_VELOCITY_IOD_PER_S: 0.5,\n MOTION_TAU_S: 0.4,\n MOTION_DEADBAND_IOD_PER_S: 0.1,\n READY_WINDOW_MS: 500,\n // (READY_MEAN_Q, the former 0.75 window MEAN, is gone — 2026-10-17 field\n // bug: a steady q anywhere in [Q_GOOD, 0.75) saturated p at 1, passed every\n // guide (\"hold still\") and could never reach the mean, so the ring sat full\n // and green with nothing recording. Readiness now checks the window against\n // Q_GOOD, which keeps the one-flaky-tick forgiveness and the second-bad-tick\n // block without a dead band above the rise threshold.)\n GUIDE_SIZE: 0.6,\n GUIDE_CENTERING: 0.6,\n GUIDE_POSE: 0.6,\n GUIDE_EXPOSURE: 0.6,\n GUIDE_SHARPNESS: 0.35,\n GUIDE_MOTION: 0.5,\n});\n\nexport interface V3GateQuality {\n /** From frame-quality.sharpness on the face crop. */\n sharpness: number;\n /** From frame-quality.exposure on the face crop. */\n exposure: number;\n /** Mean crop luma — picks more_light vs too_bright guidance. */\n meanLuma: number;\n}\n\nexport interface V3GateTickInput {\n timestampMs: number;\n observation: FaceObservation | null;\n quality: V3GateQuality;\n frameWidth: number;\n frameHeight: number;\n}\n\nexport type V3GateFactor =\n | \"presence\"\n | \"centering\"\n | \"size\"\n | \"pose\"\n | \"sharpness\"\n | \"exposure\"\n | \"motion\";\n\n/** Per-tick output — the telemetry + chrome contract. */\nexport interface V3GateTick {\n at: number;\n /** Instantaneous quality 0..1 (MIN over the factors — the worst factor). */\n q: number;\n /** Integrated progress 0..1. */\n p: number;\n factors: Record<V3GateFactor, number>;\n /** fcv3.* message key for the lowest failing factor (host translates). */\n guidanceKey: string;\n /** Fire signal: p ≥ 1 AND no second bad tick (q < Q_GOOD) in READY_WINDOW_MS. */\n ready: boolean;\n}\n\nconst clamp01 = (value: number) => Math.min(1, Math.max(0, value));\n\nexport class FaceGateV3 {\n private readonly t: V3GateThresholds;\n private p = 0;\n private lastTickAt: number | null = null;\n private lastCenter: { x: number; y: number; at: number } | null = null;\n private velocityEma = 0;\n private qWindow: Array<{ at: number; q: number }> = [];\n\n constructor(overrides: Partial<V3GateThresholds> = {}) {\n this.t = { ...V3_GATE_DEFAULTS, ...overrides };\n }\n\n reset(): void {\n this.p = 0;\n this.lastTickAt = null;\n this.lastCenter = null;\n this.velocityEma = 0;\n this.qWindow = [];\n this.lastSizeDirection = \"ideal\";\n }\n\n tick(input: V3GateTickInput): V3GateTick {\n const { observation, quality, timestampMs } = input;\n const dtSeconds =\n this.lastTickAt === null\n ? 0\n : Math.max(0, (timestampMs - this.lastTickAt) / 1000);\n this.lastTickAt = timestampMs;\n\n const factors: Record<V3GateFactor, number> = {\n presence: 0,\n centering: 0,\n size: 0,\n pose: 0,\n sharpness: clamp01(quality.sharpness),\n exposure: clamp01(quality.exposure),\n motion: 1,\n };\n\n if (observation !== null) {\n factors.presence = 1;\n const geometry = this.geometryOf(observation, input);\n factors.centering = geometry.centering;\n factors.size = geometry.size;\n factors.pose = geometry.pose;\n factors.motion = this.motionOf(\n geometry.center,\n geometry.iod,\n timestampMs,\n );\n } else {\n // No face: the motion history must not survive to the next sighting\n // (a re-acquired face \"jumping\" from its old position is not motion,\n // and a stale pre-loss velocity EMA must not penalize re-acquisition).\n this.lastCenter = null;\n this.velocityEma = 0;\n }\n\n // Worst factor IS the quality (see header) — presence 0 zeroes it exactly\n // as the old product did; the compensatory many-mediocre penalty is gone.\n const q = Math.min(\n factors.presence,\n factors.centering,\n factors.size,\n factors.pose,\n factors.sharpness,\n factors.exposure,\n factors.motion,\n );\n\n // Integrator: gentle drain — bad ticks pull p down at FALL×(1−q), never\n // reset it (the v1 counter-reset feel this replaces).\n this.p = clamp01(\n this.p +\n (q >= this.t.Q_GOOD\n ? this.t.RISE_PER_S * q\n : -this.t.FALL_PER_S * (1 - q)) *\n dtSeconds,\n );\n\n // Sustained-quality window (prevents luck-firing through a wobble).\n // TRIMMED: with ≥3 samples the single worst is dropped — at LOW's 5 Hz\n // cadence a window holds 2–3 ticks, and one jittery detection must not\n // veto a user who is otherwise steadily ready. Every remaining sample must\n // be a GOOD tick (q ≥ Q_GOOD, the integrator's own rise level): a second\n // bad tick blocks, and — by construction — any steady input that fills\n // the ring is ready the moment the window is clean (no dead band where\n // p = 1, guidance says hold_still and nothing fires; 2026-10-17).\n this.qWindow.push({ at: timestampMs, q });\n this.qWindow = this.qWindow.filter(\n (entry) => entry.at >= timestampMs - this.t.READY_WINDOW_MS,\n );\n let windowSamples = this.qWindow.map((entry) => entry.q);\n if (windowSamples.length >= 3) {\n const worst = Math.min(...windowSamples);\n const worstIndex = windowSamples.indexOf(worst);\n windowSamples = windowSamples.filter((_, index) => index !== worstIndex);\n }\n const ready =\n this.p >= 1 && windowSamples.every((sample) => sample >= this.t.Q_GOOD);\n\n return {\n at: timestampMs,\n q,\n p: this.p,\n factors,\n guidanceKey: this.guidanceOf(factors, quality, q),\n ready,\n };\n }\n\n private geometryOf(\n observation: FaceObservation,\n input: V3GateTickInput,\n ): {\n center: { x: number; y: number };\n iod: number;\n centering: number;\n size: number;\n pose: number;\n } {\n const { box, eyes } = observation;\n const frameCenter = { x: input.frameWidth / 2, y: input.frameHeight / 2 };\n const shortSide = Math.min(input.frameWidth, input.frameHeight);\n\n // Gate point: eye midpoint, or the bbox center shifted UP so box-only\n // tiers behave like eye tiers (BOX_EYE_OFFSET heuristic).\n const center =\n eyes !== undefined\n ? {\n x: (eyes.left.x + eyes.right.x) / 2,\n y: (eyes.left.y + eyes.right.y) / 2,\n }\n : {\n x: box.x + box.width / 2,\n y:\n box.y +\n box.height / 2 -\n this.t.BOX_EYE_OFFSET_FACTOR * box.height,\n };\n const iod =\n eyes !== undefined\n ? Math.hypot(eyes.right.x - eyes.left.x, eyes.right.y - eyes.left.y)\n : this.t.IOD_BOX_PROXY_FACTOR * box.width;\n\n // Smooth, SCALE-INVARIANT centering falloff: distance measured in IODs.\n const distance = Math.hypot(\n center.x - frameCenter.x,\n center.y - frameCenter.y,\n );\n const centering =\n iod <= 0\n ? 0\n : 1 - clamp01(distance / (this.t.CENTER_FALLOFF_IOD_MULTIPLE * iod));\n\n // Size factor from IOD relative to the frame short side.\n const ratio = shortSide > 0 ? iod / shortSide : 0;\n this.lastSizeDirection =\n ratio < this.t.SIZE_IDEAL_MIN\n ? \"far\"\n : ratio > this.t.SIZE_IDEAL_MAX\n ? \"close\"\n : \"ideal\";\n let size: number;\n if (ratio < this.t.SIZE_HARD_MIN || ratio > this.t.SIZE_HARD_MAX) {\n size = 0;\n } else if (ratio < this.t.SIZE_IDEAL_MIN) {\n size =\n (ratio - this.t.SIZE_HARD_MIN) /\n (this.t.SIZE_IDEAL_MIN - this.t.SIZE_HARD_MIN);\n } else if (ratio > this.t.SIZE_IDEAL_MAX) {\n size =\n (this.t.SIZE_HARD_MAX - ratio) /\n (this.t.SIZE_HARD_MAX - this.t.SIZE_IDEAL_MAX);\n } else {\n size = 1;\n }\n\n // Pose from the eye-line roll; box-only tiers stay neutral (no signal).\n let pose = 1;\n if (eyes !== undefined) {\n const rollDeg =\n (Math.abs(\n Math.atan2(eyes.right.y - eyes.left.y, eyes.right.x - eyes.left.x),\n ) *\n 180) /\n Math.PI;\n pose = 1 - clamp01(rollDeg / this.t.ROLL_MAX_DEG);\n }\n\n return { center, iod, centering, size, pose };\n }\n\n private motionOf(\n center: { x: number; y: number },\n iod: number,\n at: number,\n ): number {\n const previous = this.lastCenter;\n this.lastCenter = { ...center, at };\n if (previous === null || iod <= 0) return 1;\n const dtSeconds = (at - previous.at) / 1000;\n if (dtSeconds <= 0) return 1;\n let velocityIodPerS =\n Math.hypot(center.x - previous.x, center.y - previous.y) /\n iod /\n dtSeconds;\n // Deadband: sub-jitter velocities are stillness. Detector boxes quantize\n // hardest on LOW's 128px input, where a ±1px wobble at 5 Hz reads as\n // ~0.25 IOD/s — half the zeroing velocity — despite a rock-steady user.\n if (velocityIodPerS <= this.t.MOTION_DEADBAND_IOD_PER_S)\n velocityIodPerS = 0;\n // Time-constant EMA: alpha derived from dt so the smoothing horizon is\n // the same at 5 Hz and 10 Hz (see MOTION_TAU_S).\n const alpha = 1 - Math.exp(-dtSeconds / this.t.MOTION_TAU_S);\n this.velocityEma = alpha * velocityIodPerS + (1 - alpha) * this.velocityEma;\n return 1 - clamp01(this.velocityEma / this.t.MOTION_VELOCITY_IOD_PER_S);\n }\n\n /** Lowest failing factor speaks — fixed priority (diagnostic, incl. light):\n * presence → size → centering → pose → exposure → sharpness → hold.\n *\n * HONESTY FALLBACK (operator ruling 2026-07-12): when every factor clears\n * its guide threshold but q (= min factor) is still below Q_GOOD — i.e.\n * progress is DRAINING — \"hold still\" would be a lie (\"Perfect\" while\n * nothing advances; the field symptom was users discovering by accident\n * that only leaning in fires the gate). In that state the WORST factor\n * speaks even though it passed its guide level, so the user always hears\n * the change that actually unblocks recording. */\n private guidanceOf(\n factors: Record<V3GateFactor, number>,\n quality: V3GateQuality,\n q: number,\n ): string {\n if (factors.presence <= 0) return \"fcv3.no_face\";\n if (factors.size < this.t.GUIDE_SIZE) return this.sizeGuidance();\n if (factors.centering < this.t.GUIDE_CENTERING) return \"fcv3.center_face\";\n if (factors.pose < this.t.GUIDE_POSE) return \"fcv3.straighten\";\n if (factors.exposure < this.t.GUIDE_EXPOSURE)\n return this.exposureGuidance(quality);\n if (factors.sharpness < this.t.GUIDE_SHARPNESS) return \"fcv3.steady_camera\";\n if (factors.motion < this.t.GUIDE_MOTION) return \"fcv3.hold_still\";\n if (q < this.t.Q_GOOD) {\n // All guides pass but progress drains — coach the worst factor anyway.\n const coachable: Array<[V3GateFactor, string]> = [\n [\"size\", this.sizeGuidance()],\n [\"centering\", \"fcv3.center_face\"],\n [\"pose\", \"fcv3.straighten\"],\n [\"exposure\", this.exposureGuidance(quality)],\n [\"sharpness\", \"fcv3.steady_camera\"],\n [\"motion\", \"fcv3.hold_still\"],\n ];\n let worst = coachable[0] as [V3GateFactor, string];\n for (const entry of coachable) {\n if (factors[entry[0]] < factors[worst[0]]) worst = entry;\n }\n return worst[1];\n }\n return \"fcv3.hold_still\";\n }\n\n /** Direction from the size band set THIS tick (never inverted at the hard\n * limits: past SIZE_HARD_MAX the direction is 'close' → move_back). */\n private sizeGuidance(): string {\n return this.lastSizeDirection === \"far\"\n ? \"fcv3.come_closer\"\n : \"fcv3.move_back\";\n }\n\n /** Band midpoint — direction only (tracks EXPOSURE_BAND automatically). */\n private exposureGuidance(quality: V3GateQuality): string {\n const bandMid = (EXPOSURE_BAND[0] + EXPOSURE_BAND[1]) / 2;\n return quality.meanLuma < bandMid ? \"fcv3.more_light\" : \"fcv3.too_bright\";\n }\n\n /** Which side of the ideal band the last size measurement fell on. */\n private lastSizeDirection: \"far\" | \"close\" | \"ideal\" = \"ideal\";\n}\n","// CaptureSessionV3 (Task 10) — the v3 engine behind the v1 event surface\n// (`statechange | guidance | checks | artifacts | error`), plus ONE v3-only\n// chrome event (`frozen`, fired at recording-stop so the host can freeze the\n// display on the keyframe before the clip finalizes), so hosts bind it with\n// minimal changes. PARALLEL module: it REUSES v1's building blocks AS\n// IMPORTS — ClipRecorder (the 720p/2.5Mbps clip floor lives in ONE place),\n// captureMirroredKeyframe, buildCaptureConstraints, the camera error taxonomy\n// — and touches no v1 file.\n//\n// v3 deltas: detector LADDER (native → blaze; the face-api floor was dropped\n// 2026-07-09) on an adaptive scheduler with device profiles; FaceGateV3\n// (eye-midpoint, continuous\n// integrator); keyframe BEST-OF-N (sharpest of up to 4 candidates in the\n// first 600ms of the capture window); `checks` carries a v3 payload\n// discriminated on `engine: 'v3'` (no v1 counters).\n//\n// Supersession: retry()/switchCamera()/destroy() bump the attempt token —\n// in-flight async continuations from an old attempt observe the bump and\n// stop (the v1 pattern, ported; see capture-session.ts header).\nimport { buildCaptureConstraints, detectIsMobile } from \"../capture-constraints\";\nimport { ClipRecorder, type ClipResult } from \"../clip-recorder\";\nimport { captureMirroredKeyframe } from \"../keyframe\";\nimport { cameraPreflight, isClipTooLarge, mapGetUserMediaError } from \"../media\";\nimport type { CaptureArtifacts, CaptureErrorKind, CaptureState } from \"../types\";\nimport {\n createDetector as createLadderDetector,\n type Detector,\n DetectorLadderError,\n intrinsicSize,\n} from \"./detector\";\nimport { WorkerDetectorProxy, type WorkerLike, workerOffloadSupported } from \"./detect-worker\";\nimport {\n classifyDevice,\n type DeviceClass,\n DeviceProfiler,\n probeDevice,\n} from \"./device-profile\";\nimport { DetectScheduler } from \"./detect-scheduler\";\nimport {\n FaceGateV3,\n type V3GateFactor,\n type V3GateQuality,\n type V3GateThresholds,\n} from \"./face-gate-v3\";\nimport { exposure, meanLuma, sharpness } from \"./frame-quality\";\n\n/** Best-of-N keyframe window: up to 4 candidates over the first 600ms. */\nexport const KEYFRAME_CANDIDATES = 4;\nexport const KEYFRAME_WINDOW_MS = 600;\n\nexport interface V3ChecksPayload {\n engine: \"v3\";\n /** Gate integrator 0..1 — the ring drives off this directly. */\n progress: number;\n /** Instantaneous quality 0..1. */\n q: number;\n factors: Record<V3GateFactor, number>;\n /** Attempt ordinal (bumps on retry/switchCamera). */\n attempt: number;\n}\n\nexport interface CaptureSessionV3Events {\n statechange: { state: CaptureState };\n checks: V3ChecksPayload;\n /** fcv3.* message KEY — hosts translate; never prose. Deduped. */\n guidance: { key: string };\n artifacts: CaptureArtifacts;\n error: { kind: CaptureErrorKind; retryable: boolean };\n /** v3-only, CHROME-only (no data flows here): fires the instant the clip\n * recording window ends — BEFORE the blob finalizes (iOS onstop can lag up\n * to STOP_GRACE_MS). Carries the already-captured keyframe's JPEG data URL so\n * the host can freeze the display on the still immediately instead of leaving\n * the live feed running while the clip flushes. Clip mode only (photo mode\n * goes straight to `artifacts`). A host that ignores it is unaffected. */\n frozen: { previewDataUrl: string };\n}\n\nexport type V3TelemetryEvent =\n | { type: \"detector\"; tier: Detector[\"tier\"]; fallbackReason?: string }\n | { type: \"profile\"; staticClass: DeviceClass; activeClass: DeviceClass; simd: boolean }\n | { type: \"fired\"; timeToGateMs: number; degradeCount: number; meanDetectMs: number }\n | { type: \"error\"; kind: CaptureErrorKind; fallbackReason?: string };\n\ninterface KeyframeCandidate {\n blob: Blob;\n previewDataUrl: string;\n sharpness: number;\n}\n\n/** Challenge-clip artifact for the Phase 3 escalation path. */\nexport interface EscalationClipArtifact {\n clip: Blob;\n clipMimeType: string;\n}\n\n/** INERT Phase 3 seam (docs/superpowers/specs/2026-07-07-active-liveness-\n * escalation-spec.md): when the server settles a liveness verdict in the\n * REVIEW band it may mint ONE gesture challenge; the host then asks the\n * engine for a challenge clip through this hook. Typed and documented NOW so\n * capture-v3+ starts from a design — NEVER invoked anywhere in the current\n * flow (pinned by a test). */\nexport interface EscalationHook {\n onBorderline(challenge: \"blink\" | \"turn\"): Promise<EscalationClipArtifact>;\n}\n\nexport interface CaptureSessionV3Options {\n /** Host-owned <video playsInline muted> — same iOS contract as v1. */\n video: HTMLVideoElement;\n /** v3 assets base (tasks-vision wasm + tflite); default /models-v3. */\n v3AssetBaseUrl?: string;\n mode?: \"clip\" | \"photo\";\n /** FaceGateV3 threshold overrides (Phase 2 tuning). */\n thresholds?: Partial<V3GateThresholds>;\n telemetry?: (event: V3TelemetryEvent) => void;\n facingMode?: \"user\" | \"environment\";\n /** Static class override (tests / host pinning); default = boot probe. */\n deviceClass?: DeviceClass;\n // ── seams (production defaults in parens) ─────────────────────────────────\n /** (detector ladder) */\n createDetector?: () => Promise<Detector>;\n /** (fresh ClipRecorder per attempt) */\n createRecorder?: () => Pick<ClipRecorder, \"record\" | \"stop\">;\n /** (navigator.mediaDevices.getUserMedia) */\n getUserMedia?: (constraints: MediaStreamConstraints) => Promise<MediaStream>;\n /** (mirrored canvas keyframe + downscaled Laplacian sharpness) */\n captureKeyframe?: (video: HTMLVideoElement) => Promise<KeyframeCandidate>;\n /** (downscaled face-crop sharpness/exposure via canvas) */\n measureQuality?: (\n video: HTMLVideoElement,\n box: { x: number; y: number; width: number; height: number },\n ) => V3GateQuality;\n /** (reused canvas at profile.inputWidth; falls back to the raw video where\n * canvas is unavailable) */\n makeSnapshot?: (video: HTMLVideoElement, targetWidth: number) => CanvasImageSource;\n /** Worker offload opt-in (Task 9): when provided AND the platform supports\n * it (OffscreenCanvas + createImageBitmap + Worker), detection runs\n * worker-side through WorkerDetectorProxy. Hosts own Worker construction\n * (bundler-specific `new Worker(new URL(...))`). */\n createWorker?: () => WorkerLike;\n /** INERT (Phase 3 escalation seam — see EscalationHook). Accepted and\n * retained, never called in Phases 1–2. */\n escalation?: EscalationHook;\n /** (performance.now) */\n now?: () => number;\n}\n\ntype Handler<K extends keyof CaptureSessionV3Events> = (\n payload: CaptureSessionV3Events[K],\n) => void;\n\nconst NEUTRAL_QUALITY: V3GateQuality = { sharpness: 1, exposure: 1, meanLuma: 128 };\n\nexport class CaptureSessionV3 {\n private readonly options: CaptureSessionV3Options;\n private readonly handlers = new Map<string, Set<(payload: never) => void>>();\n private stateValue: CaptureState = \"idle\";\n private attempt = 0;\n private facing: \"user\" | \"environment\";\n private stream: MediaStream | null = null;\n private detector: Detector | null = null;\n private scheduler: DetectScheduler | null = null;\n private gate: FaceGateV3 | null = null;\n private profiler: DeviceProfiler | null = null;\n private lastGuidanceKey: string | null = null;\n private positioningStartedAt = 0;\n private fired = false;\n private carriedDegrade = 0;\n private carriedMeans: number[] = [];\n\n constructor(options: CaptureSessionV3Options) {\n this.options = options;\n this.facing = options.facingMode ?? \"user\";\n }\n\n get state(): CaptureState {\n return this.stateValue;\n }\n\n on<K extends keyof CaptureSessionV3Events>(event: K, handler: Handler<K>): () => void {\n let set = this.handlers.get(event);\n if (!set) {\n set = new Set();\n this.handlers.set(event, set);\n }\n set.add(handler as (payload: never) => void);\n return () => set?.delete(handler as (payload: never) => void);\n }\n\n private emit<K extends keyof CaptureSessionV3Events>(\n event: K,\n payload: CaptureSessionV3Events[K],\n ): void {\n for (const handler of [...(this.handlers.get(event) ?? [])]) {\n (handler as Handler<K>)(payload);\n }\n }\n\n async start(): Promise<void> {\n this.attempt += 1;\n await this.run(this.attempt);\n }\n\n /** Full reset + camera restart — the documented recovery path (v1 parity). */\n retry(): void {\n this.teardownAttempt();\n void this.start();\n }\n\n switchCamera(): void {\n this.facing = this.facing === \"user\" ? \"environment\" : \"user\";\n this.teardownAttempt();\n void this.start();\n }\n\n destroy(): void {\n this.attempt += 1; // supersede in-flight continuations\n this.teardownAttempt();\n this.detector?.destroy();\n this.detector = null;\n this.options.video.srcObject = null;\n }\n\n // ── attempt lifecycle ──────────────────────────────────────────────────────\n\n private async run(attempt: number): Promise<void> {\n const { options } = this;\n this.fired = false;\n this.lastGuidanceKey = null;\n this.carriedDegrade = 0;\n this.carriedMeans = [];\n this.setState(\"preflight\");\n const preflight = cameraPreflight();\n if (preflight !== \"OK\") {\n this.fail(preflight === \"INSECURE_CONTEXT\" ? \"insecure\" : \"unsupported\");\n return;\n }\n\n this.setState(\"acquiring\");\n const getUserMedia =\n options.getUserMedia ??\n ((constraints: MediaStreamConstraints) => navigator.mediaDevices.getUserMedia(constraints));\n let stream: MediaStream;\n try {\n // The 720p/2.5Mbps floor: v1's constraint builder, imported — never forked.\n stream = await getUserMedia(buildCaptureConstraints(detectIsMobile(), this.facing));\n } catch (err) {\n if (attempt !== this.attempt) return;\n this.fail(mapGetUserMediaError(err));\n return;\n }\n if (attempt !== this.attempt) {\n for (const track of stream.getTracks()) track.stop();\n return;\n }\n this.stream = stream;\n options.video.srcObject = stream;\n await options.video.play().catch(() => undefined);\n // play() awaited — a retry/destroy may have superseded this attempt while\n // it was suspended; continuing would overwrite the LIVE attempt's\n // profiler/gate/scheduler with stale ones (review S2-2).\n if (attempt !== this.attempt) return;\n\n if (this.detector === null) {\n const ladderOptions = {\n ...(options.v3AssetBaseUrl !== undefined\n ? { v3AssetBaseUrl: options.v3AssetBaseUrl }\n : {}),\n };\n const create =\n options.createDetector ??\n (options.createWorker !== undefined && workerOffloadSupported()\n ? async () => {\n // Worker offload (Task 9): the ladder runs WORKER-side; a\n // failed/hung init falls back to the in-thread ladder.\n try {\n return await WorkerDetectorProxy.create(\n (options.createWorker as () => WorkerLike)(),\n ladderOptions,\n );\n } catch {\n return createLadderDetector(ladderOptions);\n }\n }\n : () => createLadderDetector(ladderOptions));\n let created: Detector;\n try {\n created = await create();\n } catch (err) {\n // With the face-api floor gone, the ladder REJECTS once exhausted\n // (DetectorLadderError) — and any throwing seam is likewise a models\n // failure. Surface a retryable error{kind:'models'} (never a hang),\n // carrying the per-tier reasons for telemetry so a blaze init failure\n // stays observable in the field.\n if (attempt === this.attempt) {\n this.fail(\n \"models\",\n err instanceof DetectorLadderError ? err.fallbackReason : describeError(err),\n );\n }\n return;\n }\n // Resolve into a LOCAL first: assigning a detector into a superseded\n // (or destroyed) session would leak it — destroy() already nulled the\n // field, and a racing attempt may have created its own (review S2-3).\n if (attempt !== this.attempt) {\n created.destroy();\n return;\n }\n this.detector = created;\n this.options.telemetry?.({\n type: \"detector\",\n tier: created.tier,\n ...(created.fallbackReason !== undefined\n ? { fallbackReason: created.fallbackReason }\n : {}),\n });\n }\n\n const probe = probeDevice();\n const staticClass = options.deviceClass ?? classifyDevice(probe);\n this.profiler = new DeviceProfiler(staticClass);\n this.options.telemetry?.({\n type: \"profile\",\n staticClass,\n activeClass: this.profiler.deviceClass,\n simd: probe.simd,\n });\n\n this.gate = new FaceGateV3(options.thresholds ?? {});\n this.setState(\"positioning\");\n this.positioningStartedAt = this.now();\n this.startScheduler(attempt);\n }\n\n /** Chrome hint (Task 11): 'reduced' on LOW even without the media query. */\n get animations(): \"full\" | \"reduced\" {\n return this.profiler?.profile.animations ?? \"full\";\n }\n\n private startScheduler(attempt: number): void {\n const profiler = this.profiler;\n if (profiler === null) return;\n if (this.scheduler !== null) {\n // A dynamic profile change replaces the scheduler — carry its stats so\n // the `fired` telemetry keeps the PRE-adjustment struggle visible.\n const stats = this.scheduler.stats();\n this.carriedDegrade += stats.degradeCount;\n if (stats.meanDetectMs > 0) this.carriedMeans.push(stats.meanDetectMs);\n this.scheduler.stop();\n }\n const scheduler = new DetectScheduler({\n cadenceHz: profiler.profile.cadenceHz,\n video: this.options.video,\n ...(this.options.now !== undefined ? { now: this.options.now } : {}),\n run: () => this.detectTick(attempt),\n });\n this.scheduler = scheduler;\n scheduler.start();\n }\n\n private async detectTick(attempt: number): Promise<void> {\n const { detector, gate, profiler } = this;\n const video = this.options.video;\n if (attempt !== this.attempt || detector === null || gate === null || profiler === null)\n return;\n if (this.fired || video.videoWidth === 0) return;\n\n const before = profiler.deviceClass;\n const t0 = this.now();\n // Profile-adaptive DOWNSCALE: the detector sees an inputWidth-wide\n // snapshot, never the full 720p frame (the profile system's perf win);\n // stream-px normalization scales the observation back up.\n const source =\n this.options.makeSnapshot?.(video, profiler.profile.inputWidth) ??\n this.defaultSnapshot(video, profiler.profile.inputWidth);\n let observation: Awaited<ReturnType<Detector[\"detect\"]>> = null;\n try {\n observation = await detector.detect(source, video.videoWidth, video.videoHeight);\n } catch {\n observation = null; // detectors never reject by contract; belt-and-braces\n }\n if (attempt !== this.attempt || this.fired) return;\n profiler.record(this.now() - t0);\n if (profiler.deviceClass !== before) this.startScheduler(attempt); // cadence follows the class\n\n const quality =\n observation === null\n ? NEUTRAL_QUALITY\n : (this.options.measureQuality?.(video, observation.box) ??\n this.defaultQuality(video, observation.box));\n\n const tick = gate.tick({\n timestampMs: this.now(),\n observation,\n quality,\n frameWidth: video.videoWidth,\n frameHeight: video.videoHeight,\n });\n this.emit(\"checks\", {\n engine: \"v3\",\n progress: tick.p,\n q: tick.q,\n factors: tick.factors,\n attempt,\n });\n if (tick.guidanceKey !== this.lastGuidanceKey) {\n this.lastGuidanceKey = tick.guidanceKey;\n this.emit(\"guidance\", { key: tick.guidanceKey });\n }\n if (tick.ready && this.stateValue === \"positioning\") {\n this.fired = true;\n void this.fire(attempt);\n }\n }\n\n private async fire(attempt: number): Promise<void> {\n const { options } = this;\n const scheduler = this.scheduler;\n scheduler?.stop();\n const stats = scheduler?.stats() ?? { degradeCount: 0, meanDetectMs: 0 };\n const means = [...this.carriedMeans, ...(stats.meanDetectMs > 0 ? [stats.meanDetectMs] : [])];\n options.telemetry?.({\n type: \"fired\",\n timeToGateMs: this.now() - this.positioningStartedAt,\n degradeCount: this.carriedDegrade + stats.degradeCount,\n meanDetectMs:\n means.length === 0 ? 0 : means.reduce((sum, value) => sum + value, 0) / means.length,\n });\n\n const mode = options.mode ?? \"clip\";\n const bestOf = this.collectKeyframes(attempt);\n if (mode === \"photo\") {\n const best = await bestOf;\n if (attempt !== this.attempt) return;\n if (best === null) {\n this.fail(\"generic\");\n return;\n }\n this.finishCapture({ keyframe: best.blob, previewDataUrl: best.previewDataUrl });\n return;\n }\n\n this.setState(\"recording\");\n const recorder = options.createRecorder?.() ?? new ClipRecorder();\n const stream = this.stream;\n if (stream === null) {\n this.fail(\"generic\");\n return;\n }\n // The keyframe (the face_match selfie) resolves within the first 600ms —\n // well before the 2.5s clip ends. Latch it so the recording-STOP callback\n // below can emit `frozen` immediately, letting the host freeze the display\n // on the still without waiting for the clip blob to finalize (iOS lag).\n let frozenBest: KeyframeCandidate | null = null;\n void bestOf.then(\n (candidate) => {\n frozenBest = candidate;\n },\n () => {},\n );\n const onRecordingStopped = (): void => {\n if (attempt !== this.attempt) return; // superseded (retry/switch/destroy)\n if (frozenBest !== null) {\n this.emit(\"frozen\", { previewDataUrl: frozenBest.previewDataUrl });\n }\n };\n let clip: ClipResult;\n let best: KeyframeCandidate | null;\n try {\n [clip, best] = await Promise.all([recorder.record(stream, onRecordingStopped), bestOf]);\n } catch (err) {\n if (attempt !== this.attempt) return;\n const kind = (err as { kind?: CaptureErrorKind }).kind;\n this.fail(kind === \"cliptoolarge\" ? \"cliptoolarge\" : \"recorder\");\n return;\n }\n if (attempt !== this.attempt) return;\n if (isClipTooLarge(clip.blob)) {\n this.fail(\"cliptoolarge\");\n return;\n }\n if (best === null) {\n this.fail(\"generic\");\n return;\n }\n this.finishCapture({\n clip: clip.blob,\n clipMimeType: clip.mimeType,\n keyframe: best.blob,\n previewDataUrl: best.previewDataUrl,\n });\n }\n\n /** Up to KEYFRAME_CANDIDATES mirrored frames over KEYFRAME_WINDOW_MS —\n * sharpest wins (reuses frame-quality.sharpness via the capture seam). */\n private async collectKeyframes(attempt: number): Promise<KeyframeCandidate | null> {\n const capture = this.options.captureKeyframe ?? ((video) => this.defaultKeyframe(video));\n const stepMs = KEYFRAME_WINDOW_MS / (KEYFRAME_CANDIDATES - 1);\n let best: KeyframeCandidate | null = null;\n for (let i = 0; i < KEYFRAME_CANDIDATES; i += 1) {\n if (attempt !== this.attempt) return best;\n try {\n const candidate = await capture(this.options.video);\n if (best === null || candidate.sharpness > best.sharpness) best = candidate;\n } catch {\n // a failed candidate never sinks the capture — keep the best so far\n }\n if (i < KEYFRAME_CANDIDATES - 1) await delay(stepMs);\n }\n return best;\n }\n\n private finishCapture(artifacts: CaptureArtifacts): void {\n this.stopTracks(); // privacy posture: camera off the moment we have artifacts\n this.setState(\"captured\");\n this.emit(\"artifacts\", artifacts);\n }\n\n // ── defaults for the canvas-bound seams ────────────────────────────────────\n\n private async defaultKeyframe(video: HTMLVideoElement): Promise<KeyframeCandidate> {\n const canvas = document.createElement(\"canvas\");\n const blob = await captureMirroredKeyframe(video, canvas);\n const previewDataUrl = canvas.toDataURL(\"image/jpeg\", 0.92);\n return { blob, previewDataUrl, sharpness: this.centerSharpness(video) };\n }\n\n /** Reused downscale canvas — falls back to the raw video where canvas 2D\n * is unavailable (jsdom) so tests and exotic hosts keep detecting. */\n private snapshotCanvas: HTMLCanvasElement | null = null;\n private defaultSnapshot(video: HTMLVideoElement, targetWidth: number): CanvasImageSource {\n try {\n const canvas = this.snapshotCanvas ?? document.createElement(\"canvas\");\n const scale = targetWidth / Math.max(1, video.videoWidth);\n const width = Math.max(1, Math.round(video.videoWidth * scale));\n const height = Math.max(1, Math.round(video.videoHeight * scale));\n const ctx = canvas.getContext(\"2d\");\n if (ctx === null) return video;\n if (canvas.width !== width) canvas.width = width;\n if (canvas.height !== height) canvas.height = height;\n ctx.drawImage(video, 0, 0, width, height);\n this.snapshotCanvas = canvas;\n return canvas;\n } catch {\n return video;\n }\n }\n\n private defaultQuality(\n video: HTMLVideoElement,\n box: { x: number; y: number; width: number; height: number },\n ): V3GateQuality {\n const crop = cropImageData(video, box, 96);\n if (crop === null) return NEUTRAL_QUALITY;\n return { sharpness: sharpness(crop), exposure: exposure(crop), meanLuma: meanLuma(crop) };\n }\n\n private centerSharpness(video: HTMLVideoElement): number {\n const size = intrinsicSize(video);\n const crop = cropImageData(\n video,\n { x: size.width * 0.25, y: size.height * 0.25, width: size.width * 0.5, height: size.height * 0.5 },\n 96,\n );\n return crop === null ? 0 : sharpness(crop);\n }\n\n // ── teardown ──────────────────────────────────────────────────────────────\n\n private teardownAttempt(): void {\n // No token bump here: retry()/switchCamera() call start() synchronously\n // right after, and START's own bump supersedes; destroy() bumps itself.\n this.scheduler?.stop();\n this.scheduler = null;\n this.gate = null;\n this.stopTracks();\n }\n\n private stopTracks(): void {\n if (this.stream === null) return;\n for (const track of this.stream.getTracks()) track.stop();\n this.stream = null;\n }\n\n private fail(kind: CaptureErrorKind, fallbackReason?: string): void {\n this.scheduler?.stop();\n this.stopTracks();\n this.setState(\"error\");\n this.options.telemetry?.({\n type: \"error\",\n kind,\n ...(fallbackReason !== undefined ? { fallbackReason } : {}),\n });\n // v1 canRetry semantics (capture-session.ts L424).\n this.emit(\"error\", { kind, retryable: kind !== \"insecure\" && kind !== \"unsupported\" });\n }\n\n private setState(state: CaptureState): void {\n this.stateValue = state;\n this.emit(\"statechange\", { state });\n }\n\n private now(): number {\n return this.options.now?.() ?? performance.now();\n }\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction describeError(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/** Downscaled face-crop ImageData for the quality measures; null where canvas\n * is unavailable (jsdom) — callers fall back to neutral quality. */\nfunction cropImageData(\n video: HTMLVideoElement,\n box: { x: number; y: number; width: number; height: number },\n targetWidth: number,\n): ImageData | null {\n try {\n const canvas = document.createElement(\"canvas\");\n const scale = targetWidth / Math.max(1, box.width);\n canvas.width = Math.max(1, Math.round(box.width * scale));\n canvas.height = Math.max(1, Math.round(box.height * scale));\n const ctx = canvas.getContext(\"2d\");\n if (ctx === null) return null;\n ctx.drawImage(\n video,\n box.x,\n box.y,\n box.width,\n box.height,\n 0,\n 0,\n canvas.width,\n canvas.height,\n );\n return ctx.getImageData(0, 0, canvas.width, canvas.height);\n } catch {\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBO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