@sekyro/web 0.1.0-rc.6 → 0.1.0-rc.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +3 -3
  3. package/README.md +4 -4
  4. package/dist/chunk-B45J4KC3.js +1 -0
  5. package/dist/chunk-BMA36W2W.js +1 -0
  6. package/dist/chunk-FPXL63KZ.js +1 -0
  7. package/dist/chunk-IYUOYINS.js +1 -0
  8. package/dist/chunk-P7ECRN47.js +1 -0
  9. package/dist/chunk-SXZCL5NO.js +1 -0
  10. package/dist/chunk-YOB4ZTYN.js +1 -0
  11. package/dist/chunk-YQBK6OIM.js +1 -0
  12. package/dist/client/index.cjs +1 -357
  13. package/dist/client/index.d.cts +2 -2
  14. package/dist/client/index.d.ts +2 -2
  15. package/dist/client/index.js +1 -15
  16. package/dist/core/index.cjs +1 -1639
  17. package/dist/core/index.js +1 -139
  18. package/dist/core/v3/detect-worker.cjs +1 -392
  19. package/dist/core/v3/detect-worker.js +1 -13
  20. package/dist/{create-verification-BKc9NFQj.d.cts → create-verification-C2JhOO6Y.d.cts} +94 -16
  21. package/dist/{create-verification-DjcMZHAQ.d.ts → create-verification-CGazwtAh.d.ts} +94 -16
  22. package/dist/detector-scanic-VQFFXKTL.js +1 -0
  23. package/dist/{hosted-client-DJXq_CB9.d.ts → hosted-client-kBeq-mnJ.d.cts} +164 -11
  24. package/dist/{hosted-client-DJXq_CB9.d.cts → hosted-client-kBeq-mnJ.d.ts} +164 -11
  25. package/dist/index.cjs +1 -3030
  26. package/dist/index.d.cts +2 -2
  27. package/dist/index.d.ts +2 -2
  28. package/dist/index.js +1 -85
  29. package/dist/internal/index.cjs +1 -4439
  30. package/dist/internal/index.d.cts +10 -7
  31. package/dist/internal/index.d.ts +10 -7
  32. package/dist/internal/index.js +1 -657
  33. package/dist/popup/index.cjs +1 -76
  34. package/dist/popup/index.js +1 -11
  35. package/dist/scanic-ml-stub-KW7IZHUT.js +1 -0
  36. package/package.json +5 -8
  37. package/sbom.cdx.json +195 -0
  38. package/dist/chunk-MWNFSNMP.js +0 -52
  39. package/dist/chunk-MWNFSNMP.js.map +0 -1
  40. package/dist/chunk-NILNKLK6.js +0 -50
  41. package/dist/chunk-NILNKLK6.js.map +0 -1
  42. package/dist/chunk-NWF46H7K.js +0 -359
  43. package/dist/chunk-NWF46H7K.js.map +0 -1
  44. package/dist/chunk-R3SJQHYU.js +0 -1173
  45. package/dist/chunk-R3SJQHYU.js.map +0 -1
  46. package/dist/chunk-TG5IE552.js +0 -1128
  47. package/dist/chunk-TG5IE552.js.map +0 -1
  48. package/dist/chunk-WY6U7AIK.js +0 -193
  49. package/dist/chunk-WY6U7AIK.js.map +0 -1
  50. package/dist/chunk-YVFF4Q4G.js +0 -327
  51. package/dist/chunk-YVFF4Q4G.js.map +0 -1
  52. package/dist/client/index.cjs.map +0 -1
  53. package/dist/client/index.js.map +0 -1
  54. package/dist/core/index.cjs.map +0 -1
  55. package/dist/core/index.js.map +0 -1
  56. package/dist/core/v3/detect-worker.cjs.map +0 -1
  57. package/dist/core/v3/detect-worker.js.map +0 -1
  58. package/dist/detector-scanic-4C6IEW2K.js +0 -787
  59. package/dist/detector-scanic-4C6IEW2K.js.map +0 -1
  60. package/dist/index.cjs.map +0 -1
  61. package/dist/index.js.map +0 -1
  62. package/dist/internal/index.cjs.map +0 -1
  63. package/dist/internal/index.js.map +0 -1
  64. package/dist/popup/index.cjs.map +0 -1
  65. package/dist/popup/index.js.map +0 -1
  66. package/dist/scanic-ml-stub-S2OZ6HEF.js +0 -10
  67. package/dist/scanic-ml-stub-S2OZ6HEF.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,3030 +1 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var src_exports = {};
32
- __export(src_exports, {
33
- DEFAULT_API_ORIGIN: () => DEFAULT_API_ORIGIN,
34
- HostedApiError: () => HostedApiError,
35
- KNOWN_CODES: () => KNOWN_CODES,
36
- SEKYRO_EVENTS: () => SEKYRO_EVENTS,
37
- createLivenessCapture: () => createLivenessCapture,
38
- createVerification: () => createVerification,
39
- getLivenessAssetsStatus: () => getLivenessAssetsStatus,
40
- hasMultipleCameras: () => hasMultipleCameras,
41
- isKnownCode: () => isKnownCode,
42
- openHosted: () => openHosted,
43
- preloadLivenessAssets: () => preloadLivenessAssets,
44
- queryCameraPermission: () => queryCameraPermission,
45
- releaseLivenessAssets: () => releaseLivenessAssets,
46
- subscribeCameraPermission: () => subscribeCameraPermission,
47
- subscribeLivenessAssets: () => subscribeLivenessAssets
48
- });
49
- module.exports = __toCommonJS(src_exports);
50
-
51
- // src/core/capture-constraints.ts
52
- function buildCaptureConstraints(isMobile, facingMode) {
53
- void isMobile;
54
- return {
55
- video: {
56
- width: { ideal: 1280, max: 1280 },
57
- height: { ideal: 720, max: 720 },
58
- facingMode,
59
- frameRate: { ideal: 24, max: 30 }
60
- },
61
- audio: false
62
- };
63
- }
64
- function detectIsMobile() {
65
- if (typeof window === "undefined" || typeof navigator === "undefined") return false;
66
- return window.innerWidth <= 768 || /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
67
- String(navigator.userAgent ?? "")
68
- );
69
- }
70
-
71
- // src/core/media.ts
72
- var MIME_CANDIDATES = [
73
- "video/mp4;codecs=avc1.42E01E,mp4a.40.2",
74
- "video/mp4;codecs=avc1.42E01E",
75
- "video/mp4",
76
- "video/webm;codecs=vp9,opus",
77
- "video/webm;codecs=vp9",
78
- "video/webm;codecs=vp8,opus",
79
- "video/webm;codecs=vp8",
80
- "video/webm"
81
- ];
82
- function pickMimeType() {
83
- const MR = globalThis.MediaRecorder;
84
- if (!MR || typeof MR.isTypeSupported !== "function") return "";
85
- return MIME_CANDIDATES.find((t) => MR.isTypeSupported(t)) ?? "";
86
- }
87
- var DEFAULT_CLIP_MIME = "video/webm";
88
- function mapGetUserMediaError(err) {
89
- if (err instanceof TypeError) return "insecure";
90
- const name = err?.name ?? "";
91
- switch (name) {
92
- case "NotAllowedError":
93
- case "PermissionDeniedError":
94
- return "permission";
95
- case "NotFoundError":
96
- case "DevicesNotFoundError":
97
- return "notfound";
98
- case "NotReadableError":
99
- case "TrackStartError":
100
- return "inuse";
101
- case "OverconstrainedError":
102
- case "ConstraintNotSatisfiedError":
103
- return "overconstrained";
104
- default:
105
- return "generic";
106
- }
107
- }
108
- function cameraPreflight() {
109
- const w = globalThis;
110
- if (typeof w.window !== "undefined" && w.window.isSecureContext === false)
111
- return "INSECURE_CONTEXT";
112
- const md = w.navigator?.mediaDevices;
113
- if (!md || typeof md.getUserMedia !== "function") return "UNSUPPORTED";
114
- return "OK";
115
- }
116
- function isMediaRecorderSupported() {
117
- const MR = globalThis.MediaRecorder;
118
- return typeof MR !== "undefined" && typeof MR.isTypeSupported === "function";
119
- }
120
- var MAX_CLIP_BYTES = 8 * 1024 * 1024;
121
- function isClipTooLarge(blob) {
122
- return blob.size > MAX_CLIP_BYTES;
123
- }
124
-
125
- // src/core/clip-recorder.ts
126
- var CLIP_MS = 2500;
127
- var TIMESLICE_MS = 1e3;
128
- var STOP_GRACE_MS = 1500;
129
- var VIDEO_BPS = 25e5;
130
- var ClipError = class extends Error {
131
- constructor(kind, msg) {
132
- super(msg ?? kind);
133
- this.kind = kind;
134
- }
135
- };
136
- var ClipRecorder = class {
137
- constructor() {
138
- this.recorder = null;
139
- this.stream = null;
140
- // own field so teardown can stop tracks (REVIEW FIX 8)
141
- this.chunks = [];
142
- this.bytes = 0;
143
- this.hardStopTimer = null;
144
- this.graceTimer = null;
145
- this.settled = false;
146
- }
147
- clearTimers() {
148
- if (this.hardStopTimer) clearTimeout(this.hardStopTimer);
149
- if (this.graceTimer) clearTimeout(this.graceTimer);
150
- this.hardStopTimer = null;
151
- this.graceTimer = null;
152
- }
153
- /** Records CLIP_MS of the stream. Resolves with the clip blob + its container mime;
154
- * rejects with ClipError. Behavior contract is the v1 hook's `start`, verbatim
155
- * (iOS workarounds included).
156
- *
157
- * ONE RECORDING AT A TIME: chunk/byte/timer state is shared per instance, so a
158
- * second record() while one is in flight rejects ClipError("generic") instead of
159
- * corrupting the in-flight clip. (v2 guard — v1's hook was gated by its owning
160
- * component; a class API invites reuse. Zero impact on clip bytes.)
161
- *
162
- * `onStopped` (optional) fires ONCE the moment the CLIP_MS recording window
163
- * elapses (the hard-stop), BEFORE finalize — which on iOS can lag up to
164
- * STOP_GRACE_MS while onstop flushes the last chunk. It lets the host freeze
165
- * the display on the already-captured keyframe the instant recording ends,
166
- * instead of waiting for the blob. PURE NOTIFICATION — it does not touch
167
- * timers, chunks, or the finalize path, so it is calibration-neutral (no
168
- * effect on clip bytes). Never fires on a rejected capture (error /
169
- * cliptoolarge settle before the hard-stop and clear the timer). */
170
- record(stream, onStopped) {
171
- if (this.recorder && !this.settled) {
172
- return Promise.reject(
173
- new ClipError(
174
- "generic",
175
- "record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time"
176
- )
177
- );
178
- }
179
- this.recorder = null;
180
- this.clearTimers();
181
- this.chunks = [];
182
- this.bytes = 0;
183
- this.settled = false;
184
- this.stream = stream;
185
- const picked = pickMimeType();
186
- return new Promise((resolve, reject) => {
187
- let recorder;
188
- try {
189
- recorder = new MediaRecorder(
190
- stream,
191
- picked ? { mimeType: picked, videoBitsPerSecond: VIDEO_BPS } : { videoBitsPerSecond: VIDEO_BPS }
192
- );
193
- } catch {
194
- try {
195
- recorder = new MediaRecorder(stream);
196
- } catch {
197
- reject(new ClipError("unsupported"));
198
- return;
199
- }
200
- }
201
- this.recorder = recorder;
202
- const settle = (fn) => {
203
- if (this.settled) return;
204
- this.settled = true;
205
- this.clearTimers();
206
- fn();
207
- };
208
- const finalize = () => settle(() => {
209
- const type = recorder.mimeType || picked || DEFAULT_CLIP_MIME;
210
- const blob = new Blob(this.chunks, { type });
211
- if (isClipTooLarge(blob)) {
212
- reject(new ClipError("cliptoolarge"));
213
- return;
214
- }
215
- resolve({ blob, mimeType: type });
216
- });
217
- recorder.ondataavailable = (e) => {
218
- if (e.data && e.data.size) {
219
- this.chunks.push(e.data);
220
- this.bytes += e.data.size;
221
- if (this.bytes > MAX_CLIP_BYTES) {
222
- settle(() => {
223
- try {
224
- if (recorder.state !== "inactive") recorder.stop();
225
- } catch {
226
- }
227
- reject(new ClipError("cliptoolarge"));
228
- });
229
- }
230
- }
231
- };
232
- recorder.onstop = finalize;
233
- recorder.onerror = () => settle(() => reject(new ClipError("generic")));
234
- try {
235
- recorder.start(TIMESLICE_MS);
236
- } catch {
237
- settle(() => reject(new ClipError("generic")));
238
- return;
239
- }
240
- this.hardStopTimer = setTimeout(() => {
241
- if (!this.settled) onStopped?.();
242
- if (recorder.state !== "inactive") {
243
- try {
244
- recorder.stop();
245
- } catch {
246
- finalize();
247
- }
248
- this.graceTimer = setTimeout(finalize, STOP_GRACE_MS);
249
- } else {
250
- finalize();
251
- }
252
- }, CLIP_MS);
253
- });
254
- }
255
- /** Idempotent teardown: stop recorder + ALL tracks (v1 `stopAndCleanup` + the unmount
256
- * effect). Optional `stream` override mirrors v1's `stopAndCleanup(stream?)`.
257
- *
258
- * MID-RECORDING SEMANTICS (verbatim v1): calling stop() while a record() is in
259
- * flight may LATER resolve the pending promise with a TRUNCATED clip (recorder.stop()
260
- * fires onstop → finalize from whatever chunks arrived so far), or — because this
261
- * method clears the hard-stop/grace timers — never settle it at all if onstop never
262
- * fires (the iOS grace path has been torn down). Callers MUST NOT treat a resolution
263
- * arriving after stop() as a full CLIP_MS clip, and must not await a record()
264
- * promise past stop() without their own timeout. (Task 4's CaptureSession owns
265
- * sequencing on top of this contract.) */
266
- stop(stream) {
267
- this.clearTimers();
268
- const rec = this.recorder;
269
- if (rec && rec.state !== "inactive") {
270
- try {
271
- rec.stop();
272
- } catch {
273
- }
274
- }
275
- this.recorder = null;
276
- const s = stream ?? this.stream;
277
- s?.getTracks().forEach((t) => t.stop());
278
- this.stream = null;
279
- }
280
- };
281
-
282
- // src/core/keyframe.ts
283
- function captureMirroredKeyframe(video, canvas, quality = 0.92) {
284
- return new Promise((resolve, reject) => {
285
- const w = video.videoWidth;
286
- const h = video.videoHeight;
287
- if (!w || !h) {
288
- reject(new Error("video-not-ready"));
289
- return;
290
- }
291
- const ctx = canvas.getContext("2d");
292
- if (!ctx) {
293
- reject(new Error("no-2d-context"));
294
- return;
295
- }
296
- canvas.width = w;
297
- canvas.height = h;
298
- ctx.scale(-1, 1);
299
- ctx.drawImage(video, -w, 0);
300
- canvas.toBlob(
301
- (blob) => blob ? resolve(blob) : reject(new Error("empty-keyframe")),
302
- "image/jpeg",
303
- quality
304
- );
305
- });
306
- }
307
-
308
- // src/core/v3/detector-blaze.ts
309
- var BLAZE_INIT_TIMEOUT_MS = 1e4;
310
- var BlazeDetector = class _BlazeDetector {
311
- constructor(inner, fallbackReason) {
312
- this.tier = "blaze";
313
- this.inner = inner;
314
- if (fallbackReason !== void 0) this.fallbackReason = fallbackReason;
315
- }
316
- static async create(assetBaseUrl, fallbackReason) {
317
- const vision = await import("@mediapipe/tasks-vision");
318
- const fileset = await vision.FilesetResolver.forVisionTasks(assetBaseUrl);
319
- const inner = await vision.FaceDetector.createFromOptions(fileset, {
320
- baseOptions: {
321
- modelAssetPath: `${assetBaseUrl}/blaze_face_short_range.tflite`,
322
- // CPU delegate — the iOS-Safari-safe path (see header). NEVER 'GPU'.
323
- delegate: "CPU"
324
- },
325
- runningMode: "IMAGE"
326
- });
327
- return new _BlazeDetector(inner, fallbackReason);
328
- }
329
- async detect(source, sourceWidth, sourceHeight) {
330
- let detections;
331
- try {
332
- detections = this.inner.detect(source).detections;
333
- } catch {
334
- return null;
335
- }
336
- const best = pickMostConfident(detections);
337
- if (best?.boundingBox === void 0) return null;
338
- const size = intrinsicSize(source);
339
- const eyes = extractEyes(best.keypoints, size);
340
- const observation = {
341
- box: {
342
- x: best.boundingBox.originX,
343
- y: best.boundingBox.originY,
344
- width: best.boundingBox.width,
345
- height: best.boundingBox.height
346
- },
347
- ...eyes !== void 0 ? { eyes } : {},
348
- score: best.categories[0]?.score ?? 0
349
- };
350
- return toStreamPixels(observation, source, sourceWidth, sourceHeight);
351
- }
352
- destroy() {
353
- try {
354
- this.inner.close();
355
- } catch {
356
- }
357
- }
358
- };
359
- function pickMostConfident(detections) {
360
- let best;
361
- let bestScore = -1;
362
- for (const detection of detections) {
363
- const score = detection.categories[0]?.score ?? 0;
364
- if (score > bestScore) {
365
- best = detection;
366
- bestScore = score;
367
- }
368
- }
369
- return best;
370
- }
371
- function extractEyes(keypoints, size) {
372
- const a = keypoints?.[0];
373
- const b = keypoints?.[1];
374
- if (a === void 0 || b === void 0) return void 0;
375
- const toSource = (p) => ({ x: p.x * size.width, y: p.y * size.height });
376
- const [pa, pb] = [toSource(a), toSource(b)];
377
- return pa.x <= pb.x ? { left: pa, right: pb } : { left: pb, right: pa };
378
- }
379
-
380
- // src/core/v3/detector-native.ts
381
- function smokeSource() {
382
- if (typeof OffscreenCanvas === "function") return new OffscreenCanvas(2, 2);
383
- const canvas = document.createElement("canvas");
384
- canvas.width = 2;
385
- canvas.height = 2;
386
- return canvas;
387
- }
388
- async function probeNativeDetector() {
389
- const ctor = globalThis.FaceDetector;
390
- if (typeof ctor !== "function") return { ok: false, reason: "unsupported" };
391
- try {
392
- const instance = new ctor({ fastMode: true, maxDetectedFaces: 1 });
393
- await instance.detect(smokeSource());
394
- return { ok: true, instance };
395
- } catch (err) {
396
- return { ok: false, reason: `smoke_failed:${err instanceof Error ? err.message : String(err)}` };
397
- }
398
- }
399
- var NativeDetector = class {
400
- constructor(inner, fallbackReason) {
401
- this.tier = "native";
402
- this.inner = inner;
403
- if (fallbackReason !== void 0) this.fallbackReason = fallbackReason;
404
- }
405
- async detect(source, sourceWidth, sourceHeight) {
406
- let faces;
407
- try {
408
- faces = await this.inner.detect(source);
409
- } catch {
410
- return null;
411
- }
412
- const face = faces[0];
413
- if (face === void 0) return null;
414
- const eyes = extractEyes2(face.landmarks);
415
- const observation = {
416
- box: {
417
- x: face.boundingBox.x,
418
- y: face.boundingBox.y,
419
- width: face.boundingBox.width,
420
- height: face.boundingBox.height
421
- },
422
- ...eyes !== void 0 ? { eyes } : {},
423
- // The Shape Detection API exposes no confidence — the smoke-tested
424
- // native tier treats any detection as confident.
425
- score: 1
426
- };
427
- return toStreamPixels(observation, source, sourceWidth, sourceHeight);
428
- }
429
- destroy() {
430
- }
431
- };
432
- function extractEyes2(landmarks) {
433
- if (landmarks === void 0) return void 0;
434
- const eyePoints = landmarks.filter((landmark) => landmark.type === "eye").map((landmark) => landmark.locations[0]).filter((point) => point !== void 0);
435
- const [a, b] = eyePoints;
436
- if (a === void 0 || b === void 0) return void 0;
437
- return a.x <= b.x ? { left: a, right: b } : { left: b, right: a };
438
- }
439
-
440
- // src/core/v3/detector.ts
441
- var DEFAULT_V3_ASSET_BASE_URL = "/models-v3";
442
- var DEFAULT_TIER_ORDER = ["native", "blaze"];
443
- var DetectorLadderError = class extends Error {
444
- constructor(fallbackReason) {
445
- super(`no detector tier available (${fallbackReason})`);
446
- this.name = "DetectorLadderError";
447
- this.fallbackReason = fallbackReason;
448
- }
449
- };
450
- function intrinsicSize(source) {
451
- const candidate = source;
452
- if (typeof candidate.videoWidth === "number" && candidate.videoWidth > 0) {
453
- return { width: candidate.videoWidth, height: candidate.videoHeight ?? 0 };
454
- }
455
- if (typeof candidate.naturalWidth === "number" && candidate.naturalWidth > 0) {
456
- return { width: candidate.naturalWidth, height: candidate.naturalHeight ?? 0 };
457
- }
458
- const width = typeof candidate.width === "number" ? candidate.width : 0;
459
- const height = typeof candidate.height === "number" ? candidate.height : 0;
460
- return { width, height };
461
- }
462
- function toStreamPixels(observation, source, streamWidth, streamHeight) {
463
- const size = intrinsicSize(source);
464
- const scaleX = size.width > 0 ? streamWidth / size.width : 1;
465
- const scaleY = size.height > 0 ? streamHeight / size.height : 1;
466
- const scalePoint = (p) => ({ x: p.x * scaleX, y: p.y * scaleY });
467
- return {
468
- box: {
469
- x: observation.box.x * scaleX,
470
- y: observation.box.y * scaleY,
471
- width: observation.box.width * scaleX,
472
- height: observation.box.height * scaleY
473
- },
474
- ...observation.eyes !== void 0 ? { eyes: { left: scalePoint(observation.eyes.left), right: scalePoint(observation.eyes.right) } } : {},
475
- score: observation.score
476
- };
477
- }
478
- function describeError(err) {
479
- return err instanceof Error ? err.message : String(err);
480
- }
481
- async function createDetector(options) {
482
- const order = options.preferred ?? DEFAULT_TIER_ORDER;
483
- const reasons = [];
484
- for (const tier of order) {
485
- if (tier === "native") {
486
- const probed = await probeNativeDetector();
487
- if (probed.ok) {
488
- return new NativeDetector(probed.instance, reasonOf(reasons));
489
- }
490
- reasons.push(`native:${probed.reason}`);
491
- continue;
492
- }
493
- try {
494
- return await withTimeout(
495
- BlazeDetector.create(
496
- options.v3AssetBaseUrl ?? DEFAULT_V3_ASSET_BASE_URL,
497
- reasonOf(reasons)
498
- ),
499
- options.blazeInitTimeoutMs ?? BLAZE_INIT_TIMEOUT_MS
500
- );
501
- } catch (err) {
502
- reasons.push(
503
- err instanceof InitTimeoutError ? "blaze:blaze_init_timeout" : `blaze:${describeError(err)}`
504
- );
505
- }
506
- }
507
- throw new DetectorLadderError(reasonOf(reasons) ?? "no_tier_available");
508
- }
509
- function reasonOf(reasons) {
510
- return reasons.length > 0 ? reasons.join("; ") : void 0;
511
- }
512
- var InitTimeoutError = class extends Error {
513
- };
514
- function withTimeout(promise, deadlineMs) {
515
- return new Promise((resolvePromise, rejectPromise) => {
516
- const timer = setTimeout(() => {
517
- rejectPromise(new InitTimeoutError(`init exceeded ${deadlineMs}ms`));
518
- promise.then(
519
- (value) => value.destroy(),
520
- () => void 0
521
- );
522
- }, deadlineMs);
523
- promise.then(
524
- (value) => {
525
- clearTimeout(timer);
526
- resolvePromise(value);
527
- },
528
- (err) => {
529
- clearTimeout(timer);
530
- rejectPromise(err);
531
- }
532
- );
533
- });
534
- }
535
-
536
- // src/core/v3/detect-worker.ts
537
- var WORKER_PROTOCOL_VERSION = 1;
538
- function workerOffloadSupported() {
539
- return typeof OffscreenCanvas === "function" && typeof createImageBitmap === "function" && typeof Worker === "function";
540
- }
541
- function installWorkerDetectorHost(scope, deps = {}) {
542
- const create = deps.createDetector ?? createDetector;
543
- let detector = null;
544
- scope.onmessage = (event) => {
545
- const message = event.data;
546
- if (message.v !== WORKER_PROTOCOL_VERSION) {
547
- message.bitmap?.close?.();
548
- return;
549
- }
550
- if (message.type === "init") {
551
- void create(message.options).then((created) => {
552
- detector = created;
553
- const ready = {
554
- v: WORKER_PROTOCOL_VERSION,
555
- type: "ready",
556
- tier: created.tier,
557
- ...created.fallbackReason !== void 0 ? { fallbackReason: created.fallbackReason } : {}
558
- };
559
- scope.postMessage(ready);
560
- });
561
- return;
562
- }
563
- if (message.type === "detect") {
564
- const respond = (observation) => {
565
- const result = {
566
- v: WORKER_PROTOCOL_VERSION,
567
- type: "result",
568
- id: message.id,
569
- observation
570
- };
571
- scope.postMessage(result);
572
- message.bitmap.close?.();
573
- };
574
- if (detector === null) {
575
- respond(null);
576
- return;
577
- }
578
- void detector.detect(message.bitmap, message.streamWidth, message.streamHeight).then(respond, () => respond(null));
579
- }
580
- };
581
- }
582
- if (typeof self !== "undefined" && typeof self.importScripts === "function") {
583
- installWorkerDetectorHost(self);
584
- }
585
- var WorkerDetectorProxy = class _WorkerDetectorProxy {
586
- constructor(worker, ready) {
587
- this.pending = /* @__PURE__ */ new Map();
588
- this.nextId = 1;
589
- this.worker = worker;
590
- this.tier = ready.tier;
591
- if (ready.fallbackReason !== void 0) this.fallbackReason = ready.fallbackReason;
592
- worker.addEventListener("message", (event) => {
593
- const message = event.data;
594
- if (message.v !== WORKER_PROTOCOL_VERSION || message.type !== "result") return;
595
- const resolve = this.pending.get(message.id);
596
- this.pending.delete(message.id);
597
- resolve?.(message.observation);
598
- });
599
- }
600
- static create(worker, options, readyTimeoutMs = 1e4) {
601
- return new Promise((resolve, reject) => {
602
- const timer = setTimeout(() => {
603
- worker.removeEventListener("message", onReady);
604
- worker.terminate();
605
- reject(new Error(`worker detector not ready within ${readyTimeoutMs}ms`));
606
- }, readyTimeoutMs);
607
- const onReady = (event) => {
608
- const message = event.data;
609
- if (message.v !== WORKER_PROTOCOL_VERSION || message.type !== "ready") return;
610
- clearTimeout(timer);
611
- worker.removeEventListener("message", onReady);
612
- resolve(new _WorkerDetectorProxy(worker, message));
613
- };
614
- worker.addEventListener("message", onReady);
615
- const init = { v: WORKER_PROTOCOL_VERSION, type: "init", options };
616
- worker.postMessage(init);
617
- });
618
- }
619
- async detect(source, sourceWidth, sourceHeight) {
620
- let bitmap;
621
- try {
622
- if (typeof ImageBitmap !== "undefined" && source instanceof ImageBitmap) {
623
- bitmap = source;
624
- } else if (typeof createImageBitmap === "function") {
625
- bitmap = await createImageBitmap(source);
626
- } else {
627
- bitmap = source;
628
- }
629
- } catch {
630
- return null;
631
- }
632
- const id = this.nextId;
633
- this.nextId += 1;
634
- return new Promise((resolve) => {
635
- this.pending.set(id, resolve);
636
- const message = {
637
- v: WORKER_PROTOCOL_VERSION,
638
- type: "detect",
639
- id,
640
- bitmap,
641
- streamWidth: sourceWidth,
642
- streamHeight: sourceHeight
643
- };
644
- this.worker.postMessage(message, [bitmap]);
645
- });
646
- }
647
- destroy() {
648
- for (const resolve of this.pending.values()) resolve(null);
649
- this.pending.clear();
650
- this.worker.terminate();
651
- }
652
- };
653
-
654
- // src/core/v3/device-profile.ts
655
- var DEVICE_PROFILES = Object.freeze({
656
- LOW: Object.freeze({ cadenceHz: 5, inputWidth: 128, animations: "reduced" }),
657
- MID: Object.freeze({ cadenceHz: 8, inputWidth: 160, animations: "full" }),
658
- HIGH: Object.freeze({ cadenceHz: 10, inputWidth: 192, animations: "full" })
659
- });
660
- var SIMD_TEST_BYTES = new Uint8Array([
661
- 0,
662
- 97,
663
- 115,
664
- 109,
665
- 1,
666
- 0,
667
- 0,
668
- 0,
669
- 1,
670
- 5,
671
- 1,
672
- 96,
673
- 0,
674
- 1,
675
- 123,
676
- 3,
677
- 2,
678
- 1,
679
- 0,
680
- 10,
681
- 10,
682
- 1,
683
- 8,
684
- 0,
685
- 65,
686
- 0,
687
- 253,
688
- 15,
689
- 253,
690
- 98,
691
- 11
692
- ]);
693
- function probeDevice() {
694
- const nav = typeof navigator === "undefined" ? void 0 : navigator;
695
- let simd = false;
696
- try {
697
- simd = typeof WebAssembly !== "undefined" && WebAssembly.validate(SIMD_TEST_BYTES);
698
- } catch {
699
- simd = false;
700
- }
701
- return {
702
- cores: nav?.hardwareConcurrency ?? 2,
703
- memGB: nav?.deviceMemory ?? null,
704
- simd
705
- };
706
- }
707
- function classifyDevice(probe) {
708
- const memGB = probe.memGB ?? 4;
709
- if (probe.cores < 4 || memGB < 3) return "LOW";
710
- if (probe.cores >= 8 && memGB >= 6) return "HIGH";
711
- return "MID";
712
- }
713
- var ORDER = ["LOW", "MID", "HIGH"];
714
- var DeviceProfiler = class {
715
- constructor(initial) {
716
- this.samples = [];
717
- this.adjusted = false;
718
- this.current = initial;
719
- }
720
- get deviceClass() {
721
- return this.current;
722
- }
723
- get profile() {
724
- return DEVICE_PROFILES[this.current];
725
- }
726
- record(detectMs) {
727
- if (this.adjusted || this.samples.length >= 10) return this.current;
728
- this.samples.push(detectMs);
729
- if (this.samples.length < 10) return this.current;
730
- this.adjusted = true;
731
- const mean = this.samples.reduce((sum, value) => sum + value, 0) / this.samples.length;
732
- if (mean > 70) {
733
- this.current = "LOW";
734
- } else if (mean < 25) {
735
- const index = ORDER.indexOf(this.current);
736
- this.current = ORDER[Math.min(ORDER.length - 1, index + 1)] ?? this.current;
737
- }
738
- return this.current;
739
- }
740
- };
741
-
742
- // src/core/v3/detect-scheduler.ts
743
- var STATS_WINDOW = 20;
744
- var DetectScheduler = class {
745
- constructor(options) {
746
- this.timer = null;
747
- this.frameCallbackId = null;
748
- this.running = false;
749
- this.busy = false;
750
- this.lastRunAt = Number.NEGATIVE_INFINITY;
751
- this.degradeCount = 0;
752
- this.durations = [];
753
- this.options = options;
754
- this.periodMs = 1e3 / options.cadenceHz;
755
- }
756
- start() {
757
- if (this.running) return;
758
- this.running = true;
759
- const video = this.options.video;
760
- if (typeof video?.requestVideoFrameCallback === "function") {
761
- const loop = () => {
762
- if (!this.running) return;
763
- this.frameCallbackId = video.requestVideoFrameCallback?.(() => {
764
- this.frameCallbackId = null;
765
- if (this.now() - this.lastRunAt >= this.periodMs) this.tick();
766
- loop();
767
- });
768
- };
769
- loop();
770
- return;
771
- }
772
- this.timer = setInterval(() => this.tick(), this.periodMs);
773
- }
774
- stop() {
775
- this.running = false;
776
- if (this.timer !== null) {
777
- clearInterval(this.timer);
778
- this.timer = null;
779
- }
780
- if (this.frameCallbackId !== null) {
781
- this.options.video?.cancelVideoFrameCallback?.(
782
- this.frameCallbackId
783
- );
784
- this.frameCallbackId = null;
785
- }
786
- }
787
- stats() {
788
- const meanDetectMs = this.durations.length === 0 ? 0 : this.durations.reduce((sum, value) => sum + value, 0) / this.durations.length;
789
- return { degradeCount: this.degradeCount, meanDetectMs };
790
- }
791
- now() {
792
- return this.options.now?.() ?? performance.now();
793
- }
794
- tick() {
795
- if (!this.running) return;
796
- if (this.busy) {
797
- this.degradeCount += 1;
798
- return;
799
- }
800
- this.busy = true;
801
- this.lastRunAt = this.now();
802
- const startedAt = this.now();
803
- this.options.run().catch(() => void 0).finally(() => {
804
- this.busy = false;
805
- this.durations.push(this.now() - startedAt);
806
- if (this.durations.length > STATS_WINDOW) this.durations.shift();
807
- });
808
- }
809
- };
810
-
811
- // src/core/v3/frame-quality.ts
812
- var SHARP_REF = 180;
813
- var EXPOSURE_BAND = [100, 190];
814
- var EXPOSURE_FALLOFF = 64;
815
- function lumaAt(data, index) {
816
- return 0.299 * (data[index] ?? 0) + 0.587 * (data[index + 1] ?? 0) + 0.114 * (data[index + 2] ?? 0);
817
- }
818
- function meanLuma(image) {
819
- const { data, width, height } = image;
820
- const pixels = width * height;
821
- if (pixels === 0) return 0;
822
- let sum = 0;
823
- for (let i = 0; i < pixels; i += 1) sum += lumaAt(data, i * 4);
824
- return sum / pixels;
825
- }
826
- function sharpness(image) {
827
- const { data, width, height } = image;
828
- if (width < 3 || height < 3) return 0;
829
- const gray = new Float32Array(width * height);
830
- for (let i = 0; i < gray.length; i += 1) gray[i] = lumaAt(data, i * 4);
831
- let sum = 0;
832
- let sumSquares = 0;
833
- let count = 0;
834
- for (let y = 1; y < height - 1; y += 1) {
835
- for (let x = 1; x < width - 1; x += 1) {
836
- const i = y * width + x;
837
- const response = (gray[i - width] ?? 0) + (gray[i - 1] ?? 0) + (gray[i + 1] ?? 0) + (gray[i + width] ?? 0) - 4 * (gray[i] ?? 0);
838
- sum += response;
839
- sumSquares += response * response;
840
- count += 1;
841
- }
842
- }
843
- if (count === 0) return 0;
844
- const mean = sum / count;
845
- const variance = sumSquares / count - mean * mean;
846
- return Math.min(1, Math.max(0, variance) / SHARP_REF);
847
- }
848
- function exposure(image) {
849
- const mean = meanLuma(image);
850
- const [low, high] = EXPOSURE_BAND;
851
- const distance = mean < low ? low - mean : mean > high ? mean - high : 0;
852
- return Math.max(0, 1 - distance / EXPOSURE_FALLOFF);
853
- }
854
-
855
- // src/core/v3/face-gate-v3.ts
856
- var V3_GATE_DEFAULTS = Object.freeze({
857
- Q_GOOD: 0.6,
858
- RISE_PER_S: 0.9,
859
- FALL_PER_S: 0.25,
860
- CENTER_FALLOFF_IOD_MULTIPLE: 1.35,
861
- BOX_EYE_OFFSET_FACTOR: 0.12,
862
- IOD_BOX_PROXY_FACTOR: 0.42,
863
- SIZE_IDEAL_MIN: 0.12,
864
- SIZE_IDEAL_MAX: 0.3,
865
- SIZE_HARD_MIN: 0.08,
866
- SIZE_HARD_MAX: 0.45,
867
- ROLL_MAX_DEG: 25,
868
- MOTION_VELOCITY_IOD_PER_S: 0.5,
869
- MOTION_TAU_S: 0.4,
870
- MOTION_DEADBAND_IOD_PER_S: 0.1,
871
- READY_WINDOW_MS: 500,
872
- // (READY_MEAN_Q, the former 0.75 window MEAN, is gone — 2026-10-17 field
873
- // bug: a steady q anywhere in [Q_GOOD, 0.75) saturated p at 1, passed every
874
- // guide ("hold still") and could never reach the mean, so the ring sat full
875
- // and green with nothing recording. Readiness now checks the window against
876
- // Q_GOOD, which keeps the one-flaky-tick forgiveness and the second-bad-tick
877
- // block without a dead band above the rise threshold.)
878
- GUIDE_SIZE: 0.6,
879
- GUIDE_CENTERING: 0.6,
880
- GUIDE_POSE: 0.6,
881
- GUIDE_EXPOSURE: 0.6,
882
- GUIDE_SHARPNESS: 0.35,
883
- GUIDE_MOTION: 0.5
884
- });
885
- var clamp01 = (value) => Math.min(1, Math.max(0, value));
886
- var FaceGateV3 = class {
887
- constructor(overrides = {}) {
888
- this.p = 0;
889
- this.lastTickAt = null;
890
- this.lastCenter = null;
891
- this.velocityEma = 0;
892
- this.qWindow = [];
893
- /** Which side of the ideal band the last size measurement fell on. */
894
- this.lastSizeDirection = "ideal";
895
- this.t = { ...V3_GATE_DEFAULTS, ...overrides };
896
- }
897
- reset() {
898
- this.p = 0;
899
- this.lastTickAt = null;
900
- this.lastCenter = null;
901
- this.velocityEma = 0;
902
- this.qWindow = [];
903
- this.lastSizeDirection = "ideal";
904
- }
905
- tick(input) {
906
- const { observation, quality, timestampMs } = input;
907
- const dtSeconds = this.lastTickAt === null ? 0 : Math.max(0, (timestampMs - this.lastTickAt) / 1e3);
908
- this.lastTickAt = timestampMs;
909
- const factors = {
910
- presence: 0,
911
- centering: 0,
912
- size: 0,
913
- pose: 0,
914
- sharpness: clamp01(quality.sharpness),
915
- exposure: clamp01(quality.exposure),
916
- motion: 1
917
- };
918
- if (observation !== null) {
919
- factors.presence = 1;
920
- const geometry = this.geometryOf(observation, input);
921
- factors.centering = geometry.centering;
922
- factors.size = geometry.size;
923
- factors.pose = geometry.pose;
924
- factors.motion = this.motionOf(
925
- geometry.center,
926
- geometry.iod,
927
- timestampMs
928
- );
929
- } else {
930
- this.lastCenter = null;
931
- this.velocityEma = 0;
932
- }
933
- const q = Math.min(
934
- factors.presence,
935
- factors.centering,
936
- factors.size,
937
- factors.pose,
938
- factors.sharpness,
939
- factors.exposure,
940
- factors.motion
941
- );
942
- this.p = clamp01(
943
- this.p + (q >= this.t.Q_GOOD ? this.t.RISE_PER_S * q : -this.t.FALL_PER_S * (1 - q)) * dtSeconds
944
- );
945
- this.qWindow.push({ at: timestampMs, q });
946
- this.qWindow = this.qWindow.filter(
947
- (entry) => entry.at >= timestampMs - this.t.READY_WINDOW_MS
948
- );
949
- let windowSamples = this.qWindow.map((entry) => entry.q);
950
- if (windowSamples.length >= 3) {
951
- const worst = Math.min(...windowSamples);
952
- const worstIndex = windowSamples.indexOf(worst);
953
- windowSamples = windowSamples.filter((_, index) => index !== worstIndex);
954
- }
955
- const ready = this.p >= 1 && windowSamples.every((sample) => sample >= this.t.Q_GOOD);
956
- return {
957
- at: timestampMs,
958
- q,
959
- p: this.p,
960
- factors,
961
- guidanceKey: this.guidanceOf(factors, quality, q),
962
- ready,
963
- accepted: q >= this.t.Q_GOOD
964
- };
965
- }
966
- geometryOf(observation, input) {
967
- const { box, eyes } = observation;
968
- const frameCenter = { x: input.frameWidth / 2, y: input.frameHeight / 2 };
969
- const shortSide = Math.min(input.frameWidth, input.frameHeight);
970
- const center = eyes !== void 0 ? {
971
- x: (eyes.left.x + eyes.right.x) / 2,
972
- y: (eyes.left.y + eyes.right.y) / 2
973
- } : {
974
- x: box.x + box.width / 2,
975
- y: box.y + box.height / 2 - this.t.BOX_EYE_OFFSET_FACTOR * box.height
976
- };
977
- const iod = eyes !== void 0 ? Math.hypot(eyes.right.x - eyes.left.x, eyes.right.y - eyes.left.y) : this.t.IOD_BOX_PROXY_FACTOR * box.width;
978
- const distance = Math.hypot(
979
- center.x - frameCenter.x,
980
- center.y - frameCenter.y
981
- );
982
- const centering = iod <= 0 ? 0 : 1 - clamp01(distance / (this.t.CENTER_FALLOFF_IOD_MULTIPLE * iod));
983
- const ratio = shortSide > 0 ? iod / shortSide : 0;
984
- this.lastSizeDirection = ratio < this.t.SIZE_IDEAL_MIN ? "far" : ratio > this.t.SIZE_IDEAL_MAX ? "close" : "ideal";
985
- let size;
986
- if (ratio < this.t.SIZE_HARD_MIN || ratio > this.t.SIZE_HARD_MAX) {
987
- size = 0;
988
- } else if (ratio < this.t.SIZE_IDEAL_MIN) {
989
- size = (ratio - this.t.SIZE_HARD_MIN) / (this.t.SIZE_IDEAL_MIN - this.t.SIZE_HARD_MIN);
990
- } else if (ratio > this.t.SIZE_IDEAL_MAX) {
991
- size = (this.t.SIZE_HARD_MAX - ratio) / (this.t.SIZE_HARD_MAX - this.t.SIZE_IDEAL_MAX);
992
- } else {
993
- size = 1;
994
- }
995
- let pose = 1;
996
- if (eyes !== void 0) {
997
- const rollDeg = Math.abs(
998
- Math.atan2(eyes.right.y - eyes.left.y, eyes.right.x - eyes.left.x)
999
- ) * 180 / Math.PI;
1000
- pose = 1 - clamp01(rollDeg / this.t.ROLL_MAX_DEG);
1001
- }
1002
- return { center, iod, centering, size, pose };
1003
- }
1004
- motionOf(center, iod, at) {
1005
- const previous = this.lastCenter;
1006
- this.lastCenter = { ...center, at };
1007
- if (previous === null || iod <= 0) return 1;
1008
- const dtSeconds = (at - previous.at) / 1e3;
1009
- if (dtSeconds <= 0) return 1;
1010
- let velocityIodPerS = Math.hypot(center.x - previous.x, center.y - previous.y) / iod / dtSeconds;
1011
- if (velocityIodPerS <= this.t.MOTION_DEADBAND_IOD_PER_S)
1012
- velocityIodPerS = 0;
1013
- const alpha = 1 - Math.exp(-dtSeconds / this.t.MOTION_TAU_S);
1014
- this.velocityEma = alpha * velocityIodPerS + (1 - alpha) * this.velocityEma;
1015
- return 1 - clamp01(this.velocityEma / this.t.MOTION_VELOCITY_IOD_PER_S);
1016
- }
1017
- /** Lowest failing factor speaks — fixed priority (diagnostic, incl. light):
1018
- * presence → size → centering → pose → exposure → sharpness → hold.
1019
- *
1020
- * HONESTY FALLBACK (operator ruling 2026-07-12): when every factor clears
1021
- * its guide threshold but q (= min factor) is still below Q_GOOD — i.e.
1022
- * progress is DRAINING — "hold still" would be a lie ("Perfect" while
1023
- * nothing advances; the field symptom was users discovering by accident
1024
- * that only leaning in fires the gate). In that state the WORST factor
1025
- * speaks even though it passed its guide level, so the user always hears
1026
- * the change that actually unblocks recording. */
1027
- guidanceOf(factors, quality, q) {
1028
- if (factors.presence <= 0) return "fcv3.no_face";
1029
- if (factors.size < this.t.GUIDE_SIZE) return this.sizeGuidance();
1030
- if (factors.centering < this.t.GUIDE_CENTERING) return "fcv3.center_face";
1031
- if (factors.pose < this.t.GUIDE_POSE) return "fcv3.straighten";
1032
- if (factors.exposure < this.t.GUIDE_EXPOSURE)
1033
- return this.exposureGuidance(quality);
1034
- if (factors.sharpness < this.t.GUIDE_SHARPNESS) return "fcv3.steady_camera";
1035
- if (factors.motion < this.t.GUIDE_MOTION) return "fcv3.hold_still";
1036
- if (q < this.t.Q_GOOD) {
1037
- const coachable = [
1038
- ["size", this.sizeGuidance()],
1039
- ["centering", "fcv3.center_face"],
1040
- ["pose", "fcv3.straighten"],
1041
- ["exposure", this.exposureGuidance(quality)],
1042
- ["sharpness", "fcv3.steady_camera"],
1043
- ["motion", "fcv3.hold_still"]
1044
- ];
1045
- let worst = coachable[0];
1046
- for (const entry of coachable) {
1047
- if (factors[entry[0]] < factors[worst[0]]) worst = entry;
1048
- }
1049
- return worst[1];
1050
- }
1051
- return "fcv3.hold_still";
1052
- }
1053
- /** Direction from the size band set THIS tick (never inverted at the hard
1054
- * limits: past SIZE_HARD_MAX the direction is 'close' → move_back). */
1055
- sizeGuidance() {
1056
- return this.lastSizeDirection === "far" ? "fcv3.come_closer" : "fcv3.move_back";
1057
- }
1058
- /** Band midpoint — direction only (tracks EXPOSURE_BAND automatically). */
1059
- exposureGuidance(quality) {
1060
- const bandMid = (EXPOSURE_BAND[0] + EXPOSURE_BAND[1]) / 2;
1061
- return quality.meanLuma < bandMid ? "fcv3.more_light" : "fcv3.too_bright";
1062
- }
1063
- };
1064
-
1065
- // src/core/v3/capture-session-v3.ts
1066
- var KEYFRAME_CANDIDATES = 4;
1067
- var KEYFRAME_WINDOW_MS = 600;
1068
- var NEUTRAL_QUALITY = { sharpness: 1, exposure: 1, meanLuma: 128 };
1069
- var CaptureSessionV3 = class {
1070
- constructor(options) {
1071
- this.handlers = /* @__PURE__ */ new Map();
1072
- this.stateValue = "idle";
1073
- this.attempt = 0;
1074
- this.stream = null;
1075
- this.detector = null;
1076
- this.scheduler = null;
1077
- this.gate = null;
1078
- this.profiler = null;
1079
- this.lastGuidanceKey = null;
1080
- this.positioningStartedAt = 0;
1081
- // Face-capture timing marks of the CURRENT attempt (engine clock; reset per run).
1082
- this.cameraRequestedAt = null;
1083
- this.cameraReadyAt = null;
1084
- this.faceAcquiredAt = null;
1085
- this.captureCompleteAt = null;
1086
- this.fired = false;
1087
- this.carriedDegrade = 0;
1088
- this.carriedMeans = [];
1089
- /** Reused downscale canvas — falls back to the raw video where canvas 2D
1090
- * is unavailable (jsdom) so tests and exotic hosts keep detecting. */
1091
- this.snapshotCanvas = null;
1092
- this.options = options;
1093
- this.facing = options.facingMode ?? "user";
1094
- }
1095
- get state() {
1096
- return this.stateValue;
1097
- }
1098
- on(event, handler) {
1099
- let set = this.handlers.get(event);
1100
- if (!set) {
1101
- set = /* @__PURE__ */ new Set();
1102
- this.handlers.set(event, set);
1103
- }
1104
- set.add(handler);
1105
- return () => set?.delete(handler);
1106
- }
1107
- emit(event, payload) {
1108
- for (const handler of [...this.handlers.get(event) ?? []]) {
1109
- handler(payload);
1110
- }
1111
- }
1112
- async start(options = {}) {
1113
- if (options.facingMode !== void 0) this.facing = options.facingMode;
1114
- this.attempt += 1;
1115
- await this.run(this.attempt);
1116
- }
1117
- /** The camera the current/next attempt requests (start option, switchCamera toggles). */
1118
- get facingMode() {
1119
- return this.facing;
1120
- }
1121
- /** Full reset + camera restart — the documented recovery path (v1 parity). */
1122
- retry() {
1123
- this.teardownAttempt();
1124
- void this.start();
1125
- }
1126
- switchCamera() {
1127
- this.facing = this.facing === "user" ? "environment" : "user";
1128
- this.teardownAttempt();
1129
- void this.start();
1130
- }
1131
- destroy() {
1132
- this.attempt += 1;
1133
- this.teardownAttempt();
1134
- this.detector?.destroy();
1135
- this.detector = null;
1136
- this.options.video.srcObject = null;
1137
- }
1138
- // ── attempt lifecycle ──────────────────────────────────────────────────────
1139
- async run(attempt) {
1140
- const { options } = this;
1141
- this.fired = false;
1142
- this.lastGuidanceKey = null;
1143
- this.carriedDegrade = 0;
1144
- this.carriedMeans = [];
1145
- this.cameraRequestedAt = null;
1146
- this.cameraReadyAt = null;
1147
- this.faceAcquiredAt = null;
1148
- this.captureCompleteAt = null;
1149
- this.setState("preflight");
1150
- const preflight = cameraPreflight();
1151
- if (preflight !== "OK") {
1152
- this.fail(preflight === "INSECURE_CONTEXT" ? "insecure" : "unsupported");
1153
- return;
1154
- }
1155
- this.setState("acquiring");
1156
- const getUserMedia = options.getUserMedia ?? ((constraints) => navigator.mediaDevices.getUserMedia(constraints));
1157
- let stream;
1158
- this.cameraRequestedAt = this.now();
1159
- try {
1160
- stream = await getUserMedia(buildCaptureConstraints(detectIsMobile(), this.facing));
1161
- } catch (err) {
1162
- if (attempt !== this.attempt) return;
1163
- this.fail(mapGetUserMediaError(err));
1164
- return;
1165
- }
1166
- if (attempt !== this.attempt) {
1167
- for (const track of stream.getTracks()) track.stop();
1168
- return;
1169
- }
1170
- this.stream = stream;
1171
- options.video.srcObject = stream;
1172
- await options.video.play().catch(() => void 0);
1173
- if (attempt !== this.attempt) return;
1174
- this.cameraReadyAt = this.now();
1175
- if (this.detector === null) {
1176
- const ladderOptions = {
1177
- ...options.v3AssetBaseUrl !== void 0 ? { v3AssetBaseUrl: options.v3AssetBaseUrl } : {}
1178
- };
1179
- const create = options.createDetector ?? (options.createWorker !== void 0 && workerOffloadSupported() ? async () => {
1180
- try {
1181
- return await WorkerDetectorProxy.create(
1182
- options.createWorker(),
1183
- ladderOptions
1184
- );
1185
- } catch {
1186
- return createDetector(ladderOptions);
1187
- }
1188
- } : () => createDetector(ladderOptions));
1189
- let created;
1190
- try {
1191
- created = await create();
1192
- } catch (err) {
1193
- if (attempt === this.attempt) {
1194
- this.fail(
1195
- "models",
1196
- err instanceof DetectorLadderError ? err.fallbackReason : describeError2(err)
1197
- );
1198
- }
1199
- return;
1200
- }
1201
- if (attempt !== this.attempt) {
1202
- created.destroy();
1203
- return;
1204
- }
1205
- this.detector = created;
1206
- this.options.telemetry?.({
1207
- type: "detector",
1208
- tier: created.tier,
1209
- ...created.fallbackReason !== void 0 ? { fallbackReason: created.fallbackReason } : {}
1210
- });
1211
- }
1212
- const probe = probeDevice();
1213
- const staticClass = options.deviceClass ?? classifyDevice(probe);
1214
- this.profiler = new DeviceProfiler(staticClass);
1215
- this.options.telemetry?.({
1216
- type: "profile",
1217
- staticClass,
1218
- activeClass: this.profiler.deviceClass,
1219
- simd: probe.simd
1220
- });
1221
- this.gate = new FaceGateV3(options.thresholds ?? {});
1222
- this.setState("positioning");
1223
- this.positioningStartedAt = this.now();
1224
- this.startScheduler(attempt);
1225
- }
1226
- /** Chrome hint (Task 11): 'reduced' on LOW even without the media query. */
1227
- get animations() {
1228
- return this.profiler?.profile.animations ?? "full";
1229
- }
1230
- startScheduler(attempt) {
1231
- const profiler = this.profiler;
1232
- if (profiler === null) return;
1233
- if (this.scheduler !== null) {
1234
- const stats = this.scheduler.stats();
1235
- this.carriedDegrade += stats.degradeCount;
1236
- if (stats.meanDetectMs > 0) this.carriedMeans.push(stats.meanDetectMs);
1237
- this.scheduler.stop();
1238
- }
1239
- const scheduler = new DetectScheduler({
1240
- cadenceHz: profiler.profile.cadenceHz,
1241
- video: this.options.video,
1242
- ...this.options.now !== void 0 ? { now: this.options.now } : {},
1243
- run: () => this.detectTick(attempt)
1244
- });
1245
- this.scheduler = scheduler;
1246
- scheduler.start();
1247
- }
1248
- async detectTick(attempt) {
1249
- const { detector, gate, profiler } = this;
1250
- const video = this.options.video;
1251
- if (attempt !== this.attempt || detector === null || gate === null || profiler === null)
1252
- return;
1253
- if (this.fired || video.videoWidth === 0) return;
1254
- const before = profiler.deviceClass;
1255
- const t0 = this.now();
1256
- const source = this.options.makeSnapshot?.(video, profiler.profile.inputWidth) ?? this.defaultSnapshot(video, profiler.profile.inputWidth);
1257
- let observation = null;
1258
- try {
1259
- observation = await detector.detect(source, video.videoWidth, video.videoHeight);
1260
- } catch {
1261
- observation = null;
1262
- }
1263
- if (attempt !== this.attempt || this.fired) return;
1264
- profiler.record(this.now() - t0);
1265
- if (profiler.deviceClass !== before) this.startScheduler(attempt);
1266
- const quality = observation === null ? NEUTRAL_QUALITY : this.options.measureQuality?.(video, observation.box) ?? this.defaultQuality(video, observation.box);
1267
- const tick = gate.tick({
1268
- timestampMs: this.now(),
1269
- observation,
1270
- quality,
1271
- frameWidth: video.videoWidth,
1272
- frameHeight: video.videoHeight
1273
- });
1274
- if (tick.accepted && this.faceAcquiredAt === null) this.faceAcquiredAt = tick.at;
1275
- this.emit("checks", {
1276
- engine: "v3",
1277
- progress: tick.p,
1278
- q: tick.q,
1279
- factors: tick.factors,
1280
- attempt
1281
- });
1282
- if (tick.guidanceKey !== this.lastGuidanceKey) {
1283
- this.lastGuidanceKey = tick.guidanceKey;
1284
- this.emit("guidance", { key: tick.guidanceKey });
1285
- }
1286
- if (tick.ready && this.stateValue === "positioning") {
1287
- this.fired = true;
1288
- this.captureCompleteAt = tick.at;
1289
- void this.fire(attempt);
1290
- }
1291
- }
1292
- async fire(attempt) {
1293
- const { options } = this;
1294
- const scheduler = this.scheduler;
1295
- scheduler?.stop();
1296
- const stats = scheduler?.stats() ?? { degradeCount: 0, meanDetectMs: 0 };
1297
- const means = [...this.carriedMeans, ...stats.meanDetectMs > 0 ? [stats.meanDetectMs] : []];
1298
- options.telemetry?.({
1299
- type: "fired",
1300
- timeToGateMs: this.now() - this.positioningStartedAt,
1301
- degradeCount: this.carriedDegrade + stats.degradeCount,
1302
- meanDetectMs: means.length === 0 ? 0 : means.reduce((sum, value) => sum + value, 0) / means.length
1303
- });
1304
- const mode = options.mode ?? "clip";
1305
- const bestOf = this.collectKeyframes(attempt);
1306
- if (mode === "photo") {
1307
- const best2 = await bestOf;
1308
- if (attempt !== this.attempt) return;
1309
- if (best2 === null) {
1310
- this.fail("generic");
1311
- return;
1312
- }
1313
- this.finishCapture({ keyframe: best2.blob, previewDataUrl: best2.previewDataUrl });
1314
- return;
1315
- }
1316
- this.setState("recording");
1317
- const recorder = options.createRecorder?.() ?? new ClipRecorder();
1318
- const stream = this.stream;
1319
- if (stream === null) {
1320
- this.fail("generic");
1321
- return;
1322
- }
1323
- let frozenBest = null;
1324
- void bestOf.then(
1325
- (candidate) => {
1326
- frozenBest = candidate;
1327
- },
1328
- () => {
1329
- }
1330
- );
1331
- const onRecordingStopped = () => {
1332
- if (attempt !== this.attempt) return;
1333
- if (frozenBest !== null) {
1334
- this.emit("frozen", { previewDataUrl: frozenBest.previewDataUrl });
1335
- }
1336
- };
1337
- let clip;
1338
- let best;
1339
- try {
1340
- [clip, best] = await Promise.all([recorder.record(stream, onRecordingStopped), bestOf]);
1341
- } catch (err) {
1342
- if (attempt !== this.attempt) return;
1343
- const kind = err.kind;
1344
- this.fail(kind === "cliptoolarge" ? "cliptoolarge" : "recorder");
1345
- return;
1346
- }
1347
- if (attempt !== this.attempt) return;
1348
- if (isClipTooLarge(clip.blob)) {
1349
- this.fail("cliptoolarge");
1350
- return;
1351
- }
1352
- if (best === null) {
1353
- this.fail("generic");
1354
- return;
1355
- }
1356
- this.finishCapture({
1357
- clip: clip.blob,
1358
- clipMimeType: clip.mimeType,
1359
- keyframe: best.blob,
1360
- previewDataUrl: best.previewDataUrl
1361
- });
1362
- }
1363
- /** Up to KEYFRAME_CANDIDATES mirrored frames over KEYFRAME_WINDOW_MS —
1364
- * sharpest wins (reuses frame-quality.sharpness via the capture seam). */
1365
- async collectKeyframes(attempt) {
1366
- const capture = this.options.captureKeyframe ?? ((video) => this.defaultKeyframe(video));
1367
- const stepMs = KEYFRAME_WINDOW_MS / (KEYFRAME_CANDIDATES - 1);
1368
- let best = null;
1369
- for (let i = 0; i < KEYFRAME_CANDIDATES; i += 1) {
1370
- if (attempt !== this.attempt) return best;
1371
- try {
1372
- const candidate = await capture(this.options.video);
1373
- if (best === null || candidate.sharpness > best.sharpness) best = candidate;
1374
- } catch {
1375
- }
1376
- if (i < KEYFRAME_CANDIDATES - 1) await delay(stepMs);
1377
- }
1378
- return best;
1379
- }
1380
- finishCapture(artifacts) {
1381
- this.stopTracks();
1382
- this.setState("captured");
1383
- const timing = this.captureTiming();
1384
- this.emit("artifacts", timing === void 0 ? artifacts : { ...artifacts, timing });
1385
- }
1386
- /** The attempt's capture-phase timing (whole ms, ≥ 0); undefined when no mark landed. */
1387
- captureTiming() {
1388
- const span = (from, to) => from !== null && to !== null ? Math.max(0, Math.round(to - from)) : void 0;
1389
- const cameraReadyMs = span(this.cameraRequestedAt, this.cameraReadyAt);
1390
- const faceAcquireMs = span(this.cameraReadyAt, this.faceAcquiredAt);
1391
- const captureMs = span(this.faceAcquiredAt, this.captureCompleteAt);
1392
- const timing = {
1393
- ...cameraReadyMs !== void 0 ? { cameraReadyMs } : {},
1394
- ...faceAcquireMs !== void 0 ? { faceAcquireMs } : {},
1395
- ...captureMs !== void 0 ? { captureMs } : {}
1396
- };
1397
- return Object.keys(timing).length > 0 ? timing : void 0;
1398
- }
1399
- // ── defaults for the canvas-bound seams ────────────────────────────────────
1400
- async defaultKeyframe(video) {
1401
- const canvas = document.createElement("canvas");
1402
- const blob = await captureMirroredKeyframe(video, canvas);
1403
- const previewDataUrl = canvas.toDataURL("image/jpeg", 0.92);
1404
- return { blob, previewDataUrl, sharpness: this.centerSharpness(video) };
1405
- }
1406
- defaultSnapshot(video, targetWidth) {
1407
- try {
1408
- const canvas = this.snapshotCanvas ?? document.createElement("canvas");
1409
- const scale = targetWidth / Math.max(1, video.videoWidth);
1410
- const width = Math.max(1, Math.round(video.videoWidth * scale));
1411
- const height = Math.max(1, Math.round(video.videoHeight * scale));
1412
- const ctx = canvas.getContext("2d");
1413
- if (ctx === null) return video;
1414
- if (canvas.width !== width) canvas.width = width;
1415
- if (canvas.height !== height) canvas.height = height;
1416
- ctx.drawImage(video, 0, 0, width, height);
1417
- this.snapshotCanvas = canvas;
1418
- return canvas;
1419
- } catch {
1420
- return video;
1421
- }
1422
- }
1423
- defaultQuality(video, box) {
1424
- const crop = cropImageData(video, box, 96);
1425
- if (crop === null) return NEUTRAL_QUALITY;
1426
- return { sharpness: sharpness(crop), exposure: exposure(crop), meanLuma: meanLuma(crop) };
1427
- }
1428
- centerSharpness(video) {
1429
- const size = intrinsicSize(video);
1430
- const crop = cropImageData(
1431
- video,
1432
- { x: size.width * 0.25, y: size.height * 0.25, width: size.width * 0.5, height: size.height * 0.5 },
1433
- 96
1434
- );
1435
- return crop === null ? 0 : sharpness(crop);
1436
- }
1437
- // ── teardown ──────────────────────────────────────────────────────────────
1438
- teardownAttempt() {
1439
- this.scheduler?.stop();
1440
- this.scheduler = null;
1441
- this.gate = null;
1442
- this.stopTracks();
1443
- }
1444
- stopTracks() {
1445
- if (this.stream === null) return;
1446
- for (const track of this.stream.getTracks()) track.stop();
1447
- this.stream = null;
1448
- }
1449
- fail(kind, fallbackReason) {
1450
- this.scheduler?.stop();
1451
- this.stopTracks();
1452
- this.setState("error");
1453
- this.options.telemetry?.({
1454
- type: "error",
1455
- kind,
1456
- ...fallbackReason !== void 0 ? { fallbackReason } : {}
1457
- });
1458
- this.emit("error", { kind, retryable: kind !== "insecure" && kind !== "unsupported" });
1459
- }
1460
- setState(state) {
1461
- this.stateValue = state;
1462
- this.emit("statechange", { state });
1463
- }
1464
- now() {
1465
- return this.options.now?.() ?? performance.now();
1466
- }
1467
- };
1468
- function delay(ms) {
1469
- return new Promise((resolve) => setTimeout(resolve, ms));
1470
- }
1471
- function describeError2(err) {
1472
- return err instanceof Error ? err.message : String(err);
1473
- }
1474
- function cropImageData(video, box, targetWidth) {
1475
- try {
1476
- const canvas = document.createElement("canvas");
1477
- const scale = targetWidth / Math.max(1, box.width);
1478
- canvas.width = Math.max(1, Math.round(box.width * scale));
1479
- canvas.height = Math.max(1, Math.round(box.height * scale));
1480
- const ctx = canvas.getContext("2d");
1481
- if (ctx === null) return null;
1482
- ctx.drawImage(
1483
- video,
1484
- box.x,
1485
- box.y,
1486
- box.width,
1487
- box.height,
1488
- 0,
1489
- 0,
1490
- canvas.width,
1491
- canvas.height
1492
- );
1493
- return ctx.getImageData(0, 0, canvas.width, canvas.height);
1494
- } catch {
1495
- return null;
1496
- }
1497
- }
1498
-
1499
- // src/verification/emitter.ts
1500
- function createEmitter() {
1501
- const handlers = /* @__PURE__ */ new Map();
1502
- return {
1503
- on(event, handler) {
1504
- let set = handlers.get(event);
1505
- if (set === void 0) {
1506
- set = /* @__PURE__ */ new Set();
1507
- handlers.set(event, set);
1508
- }
1509
- const h = handler;
1510
- set.add(h);
1511
- return () => {
1512
- set?.delete(h);
1513
- };
1514
- },
1515
- emit(event, payload) {
1516
- const set = handlers.get(event);
1517
- if (set === void 0) return;
1518
- for (const handler of [...set]) {
1519
- handler(payload);
1520
- }
1521
- },
1522
- clear() {
1523
- handlers.clear();
1524
- }
1525
- };
1526
- }
1527
-
1528
- // src/capture/preload.ts
1529
- var PRELOAD_BLAZE_INIT_TIMEOUT_MS = 12e4;
1530
- var PRELOAD_BUDGET_MS = 13e4;
1531
- var IDLE_TIMEOUT_MS = 3e3;
1532
- var IDLE_FALLBACK_MS = 1200;
1533
- var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("@sekyro/web.preload.v1");
1534
- function registry() {
1535
- const host = globalThis;
1536
- host[REGISTRY_KEY] ?? (host[REGISTRY_KEY] = /* @__PURE__ */ new Map());
1537
- return host[REGISTRY_KEY];
1538
- }
1539
- function normalizeBase(assetBaseUrl) {
1540
- const base = (assetBaseUrl ?? DEFAULT_V3_ASSET_BASE_URL).replace(/\/+$/, "");
1541
- return base === "" ? "/" : base;
1542
- }
1543
- function entryFor(base) {
1544
- const map = registry();
1545
- let entry = map.get(base);
1546
- if (entry === void 0) {
1547
- entry = { status: "idle", promise: null, scheduled: null, detectorPromise: null, detector: null, listeners: /* @__PURE__ */ new Set() };
1548
- map.set(base, entry);
1549
- }
1550
- return entry;
1551
- }
1552
- function setStatus(entry, next) {
1553
- if (entry.status === next) return;
1554
- entry.status = next;
1555
- for (const listener of [...entry.listeners]) listener(next);
1556
- }
1557
- var defaultLoader = (base) => createDetector({ preferred: ["blaze"], v3AssetBaseUrl: base, blazeInitTimeoutMs: PRELOAD_BLAZE_INIT_TIMEOUT_MS });
1558
- var loader = defaultLoader;
1559
- function canCapture() {
1560
- return typeof window !== "undefined" && typeof navigator !== "undefined" && typeof navigator.mediaDevices?.getUserMedia === "function";
1561
- }
1562
- function saveDataOn() {
1563
- return navigator.connection?.saveData === true;
1564
- }
1565
- function scheduleIdle(run) {
1566
- const w = window;
1567
- if (typeof w.requestIdleCallback === "function") {
1568
- const handle = w.requestIdleCallback(run, { timeout: IDLE_TIMEOUT_MS });
1569
- return () => w.cancelIdleCallback?.(handle);
1570
- }
1571
- const timer = setTimeout(run, IDLE_FALLBACK_MS);
1572
- return () => clearTimeout(timer);
1573
- }
1574
- function schedule(entry, base) {
1575
- let resolve;
1576
- const promise = new Promise((res) => {
1577
- resolve = res;
1578
- });
1579
- let done = false;
1580
- let cancel = () => void 0;
1581
- const scheduled = {
1582
- promise,
1583
- settle: (outcome) => {
1584
- if (done) return;
1585
- done = true;
1586
- cancel();
1587
- if (entry.scheduled === scheduled) entry.scheduled = null;
1588
- resolve(outcome);
1589
- }
1590
- };
1591
- entry.scheduled = scheduled;
1592
- cancel = scheduleIdle(() => {
1593
- if (done) return;
1594
- scheduled.settle(begin(entry, base));
1595
- });
1596
- return promise;
1597
- }
1598
- function begin(entry, base) {
1599
- if ((entry.status === "loading" || entry.status === "ready") && entry.promise !== null) return entry.promise;
1600
- setStatus(entry, "loading");
1601
- const detectorPromise = new Promise((resolve) => resolve(loader(base)));
1602
- entry.detectorPromise = detectorPromise;
1603
- let timer;
1604
- const budget = new Promise((_, reject) => {
1605
- timer = setTimeout(() => {
1606
- detectorPromise.then((late) => late.destroy(), () => void 0);
1607
- reject(new Error(`detector preload exceeded ${PRELOAD_BUDGET_MS} ms`));
1608
- }, PRELOAD_BUDGET_MS);
1609
- });
1610
- const settled = Promise.race([detectorPromise, budget]).then(
1611
- (detector) => {
1612
- if (entry.detectorPromise !== detectorPromise) {
1613
- detector.destroy();
1614
- return entry.status;
1615
- }
1616
- entry.detector = detector;
1617
- setStatus(entry, "ready");
1618
- return "ready";
1619
- },
1620
- (err) => {
1621
- if (entry.detectorPromise === detectorPromise) {
1622
- entry.detectorPromise = null;
1623
- entry.detector = null;
1624
- setStatus(entry, "failed");
1625
- console.warn("[@sekyro/web] face-detector preload failed:", err);
1626
- }
1627
- return entry.status;
1628
- }
1629
- );
1630
- const promise = settled.finally(() => clearTimeout(timer));
1631
- entry.promise = promise;
1632
- entry.scheduled?.settle(promise);
1633
- return promise;
1634
- }
1635
- function preloadLivenessAssets(options = {}) {
1636
- if (!canCapture()) return Promise.resolve("idle");
1637
- const base = normalizeBase(options.assetBaseUrl);
1638
- const entry = entryFor(base);
1639
- if (options.respectSaveData === true && saveDataOn()) return Promise.resolve(entry.status);
1640
- if ((entry.status === "loading" || entry.status === "ready") && entry.promise !== null) return entry.promise;
1641
- if (options.idle === true) return entry.scheduled?.promise ?? schedule(entry, base);
1642
- return begin(entry, base);
1643
- }
1644
- function getLivenessAssetsStatus(assetBaseUrl) {
1645
- return registry().get(normalizeBase(assetBaseUrl))?.status ?? "idle";
1646
- }
1647
- function subscribeLivenessAssets(listener, assetBaseUrl) {
1648
- const entry = entryFor(normalizeBase(assetBaseUrl));
1649
- entry.listeners.add(listener);
1650
- return () => {
1651
- entry.listeners.delete(listener);
1652
- };
1653
- }
1654
- function releaseLivenessAssets(assetBaseUrl) {
1655
- const entry = registry().get(normalizeBase(assetBaseUrl));
1656
- if (entry === void 0) return;
1657
- entry.scheduled?.settle("idle");
1658
- entry.detector?.destroy();
1659
- entry.detector = null;
1660
- entry.detectorPromise = null;
1661
- entry.promise = null;
1662
- setStatus(entry, "idle");
1663
- }
1664
- function nonOwningView(shared) {
1665
- return {
1666
- get tier() {
1667
- return shared.tier;
1668
- },
1669
- get fallbackReason() {
1670
- return shared.fallbackReason;
1671
- },
1672
- detect: (...args) => shared.detect(...args),
1673
- destroy: () => {
1674
- }
1675
- };
1676
- }
1677
- function preloadedDetectorFactory(assetBaseUrl) {
1678
- const base = normalizeBase(assetBaseUrl);
1679
- const entry = registry().get(base);
1680
- if (entry === void 0 || entry.detector === null && entry.detectorPromise === null && entry.scheduled === null) {
1681
- return void 0;
1682
- }
1683
- return async () => {
1684
- if (entry.scheduled !== null) void begin(entry, base);
1685
- let waitingOn = entry.promise;
1686
- while (entry.detector === null && waitingOn !== null) {
1687
- await waitingOn;
1688
- if (entry.promise === waitingOn) break;
1689
- waitingOn = entry.promise;
1690
- }
1691
- return entry.detector !== null ? nonOwningView(entry.detector) : createDetector({ v3AssetBaseUrl: base });
1692
- };
1693
- }
1694
-
1695
- // src/capture/wake-lock.ts
1696
- function wakeLockApi() {
1697
- if (typeof navigator === "undefined" || !("wakeLock" in navigator)) return null;
1698
- const api = navigator.wakeLock;
1699
- return typeof api?.request === "function" ? api : null;
1700
- }
1701
- function isVisible() {
1702
- return typeof document === "undefined" || document.visibilityState === "visible";
1703
- }
1704
- function releaseQuietly(sentinel) {
1705
- try {
1706
- void sentinel.release().catch(() => void 0);
1707
- } catch {
1708
- }
1709
- }
1710
- function createScreenWakeLock(options = {}) {
1711
- if (options.enabled === false) return { setActive: () => void 0 };
1712
- let wanted = false;
1713
- let sentinel = null;
1714
- let inFlight = false;
1715
- let listening = false;
1716
- const acquire = () => {
1717
- if (!wanted || inFlight || sentinel !== null && !sentinel.released) return;
1718
- const api = wakeLockApi();
1719
- if (api === null || !isVisible()) return;
1720
- let request;
1721
- try {
1722
- request = api.request("screen");
1723
- } catch {
1724
- return;
1725
- }
1726
- inFlight = true;
1727
- request.then(
1728
- (granted) => {
1729
- inFlight = false;
1730
- if (!wanted) {
1731
- releaseQuietly(granted);
1732
- return;
1733
- }
1734
- sentinel = granted;
1735
- granted.addEventListener?.("release", () => {
1736
- if (sentinel === granted) sentinel = null;
1737
- });
1738
- },
1739
- () => {
1740
- inFlight = false;
1741
- }
1742
- );
1743
- };
1744
- const onVisibilityChange = () => {
1745
- if (isVisible()) acquire();
1746
- };
1747
- const listen = (on) => {
1748
- if (typeof document === "undefined" || on === listening) return;
1749
- listening = on;
1750
- if (on) document.addEventListener("visibilitychange", onVisibilityChange);
1751
- else document.removeEventListener("visibilitychange", onVisibilityChange);
1752
- };
1753
- return {
1754
- setActive: (active) => {
1755
- wanted = active;
1756
- if (active) {
1757
- if (wakeLockApi() === null) return;
1758
- listen(true);
1759
- acquire();
1760
- return;
1761
- }
1762
- listen(false);
1763
- if (sentinel !== null) {
1764
- const held = sentinel;
1765
- sentinel = null;
1766
- releaseQuietly(held);
1767
- }
1768
- }
1769
- };
1770
- }
1771
-
1772
- // src/capture/create-liveness-capture.ts
1773
- function mapGuidanceHint(key) {
1774
- switch (key) {
1775
- case "fcv3.no_face":
1776
- case "fcv3.center_face":
1777
- case "fcv3.straighten":
1778
- return "center";
1779
- case "fcv3.come_closer":
1780
- return "closer";
1781
- case "fcv3.move_back":
1782
- return "farther";
1783
- case "fcv3.more_light":
1784
- case "fcv3.too_bright":
1785
- return "light";
1786
- case "fcv3.hold_still":
1787
- case "fcv3.steady_camera":
1788
- return "still";
1789
- default:
1790
- return null;
1791
- }
1792
- }
1793
- function mapEngineState(state) {
1794
- switch (state) {
1795
- case "preflight":
1796
- case "acquiring":
1797
- return "starting";
1798
- case "positioning":
1799
- return "gating";
1800
- case "idle":
1801
- case "recording":
1802
- case "captured":
1803
- case "error":
1804
- return state;
1805
- default: {
1806
- const unhandled = state;
1807
- throw new Error(`mapEngineState: unhandled state ${unhandled}`);
1808
- }
1809
- }
1810
- }
1811
- function mapErrorKind(kind) {
1812
- switch (kind) {
1813
- case "permission":
1814
- case "notfound":
1815
- case "inuse":
1816
- case "insecure":
1817
- case "unsupported":
1818
- return kind;
1819
- case "overconstrained":
1820
- case "generic":
1821
- case "models":
1822
- case "cliptoolarge":
1823
- case "recorder":
1824
- return "generic";
1825
- default: {
1826
- const unhandled = kind;
1827
- throw new Error(`mapErrorKind: unhandled kind ${unhandled}`);
1828
- }
1829
- }
1830
- }
1831
- function createLivenessCaptureInternal(options, internals = {}) {
1832
- const now = internals.now ?? (() => performance.now());
1833
- const emitter = createEmitter();
1834
- const degraded = !isMediaRecorderSupported();
1835
- const hostSeams = internals.engineOptions;
1836
- const preloadAware = hostSeams?.createDetector === void 0 && hostSeams?.createWorker === void 0 ? {
1837
- createDetector: () => {
1838
- const warmed = preloadedDetectorFactory(options.assetBaseUrl);
1839
- return warmed !== void 0 ? warmed() : createDetector(
1840
- options.assetBaseUrl !== void 0 ? { v3AssetBaseUrl: options.assetBaseUrl } : {}
1841
- );
1842
- }
1843
- } : {};
1844
- const engineOptions = {
1845
- video: options.video,
1846
- mode: degraded ? "photo" : "clip",
1847
- ...options.facing !== void 0 ? { facingMode: options.facing } : {},
1848
- ...options.assetBaseUrl !== void 0 ? { v3AssetBaseUrl: options.assetBaseUrl } : {},
1849
- ...internals.engineOptions ?? {},
1850
- ...preloadAware
1851
- };
1852
- const engine = internals.createEngine?.(engineOptions) ?? new CaptureSessionV3(engineOptions);
1853
- let state = "idle";
1854
- let hint = null;
1855
- let progress = 0;
1856
- let faceDetected = false;
1857
- let animations = "full";
1858
- let recordingStartedAt = null;
1859
- let frozenAt = null;
1860
- let frameWidth = 0;
1861
- let frameHeight = 0;
1862
- const latchFrameSize = () => {
1863
- if (options.video.videoWidth > 0 && options.video.videoHeight > 0) {
1864
- frameWidth = options.video.videoWidth;
1865
- frameHeight = options.video.videoHeight;
1866
- }
1867
- };
1868
- const wakeLock = createScreenWakeLock({ enabled: options.keepScreenAwake !== false });
1869
- const setState = (next) => {
1870
- state = next;
1871
- wakeLock.setActive(next === "starting" || next === "gating" || next === "recording");
1872
- emitter.emit("state", next);
1873
- };
1874
- const emitGate = () => emitter.emit("gate", { progress, hint, faceDetected });
1875
- const syncProfile = () => {
1876
- const next = engine.animations ?? "full";
1877
- if (next === animations) return;
1878
- animations = next;
1879
- emitter.emit("profile", { animations });
1880
- };
1881
- const unsubscribes = [
1882
- engine.on("statechange", ({ state: engineState }) => {
1883
- const next = mapEngineState(engineState);
1884
- if (next === "starting" && state !== "starting") {
1885
- hint = null;
1886
- progress = 0;
1887
- faceDetected = false;
1888
- recordingStartedAt = null;
1889
- frozenAt = null;
1890
- frameWidth = 0;
1891
- frameHeight = 0;
1892
- }
1893
- setState(next);
1894
- syncProfile();
1895
- if (next === "recording") {
1896
- latchFrameSize();
1897
- recordingStartedAt = now();
1898
- hint = "hold";
1899
- progress = 1;
1900
- emitGate();
1901
- }
1902
- }),
1903
- engine.on("checks", (payload) => {
1904
- latchFrameSize();
1905
- progress = payload.progress;
1906
- faceDetected = payload.factors.presence > 0;
1907
- emitGate();
1908
- syncProfile();
1909
- }),
1910
- engine.on("guidance", ({ key }) => {
1911
- hint = mapGuidanceHint(key);
1912
- emitGate();
1913
- }),
1914
- engine.on("frozen", ({ previewDataUrl }) => {
1915
- frozenAt = now();
1916
- emitter.emit("frozen", { previewDataUrl });
1917
- }),
1918
- engine.on("artifacts", (artifacts) => {
1919
- const clipMs = recordingStartedAt !== null && frozenAt !== null ? Math.max(0, Math.round(frozenAt - recordingStartedAt)) : void 0;
1920
- emitter.emit("captured", {
1921
- keyframe: artifacts.keyframe,
1922
- ...artifacts.clip !== void 0 ? { clip: artifacts.clip } : {},
1923
- ...artifacts.clipMimeType !== void 0 ? { clipMime: artifacts.clipMimeType } : {},
1924
- width: options.video.videoWidth || frameWidth,
1925
- height: options.video.videoHeight || frameHeight,
1926
- ...clipMs !== void 0 ? { clipMs } : {},
1927
- captureChannel: detectIsMobile() ? "mobile" : "desktop",
1928
- ...degraded ? { degraded: "NO_RECORDER" } : {},
1929
- engine: "v3",
1930
- // Face-capture timing: the engine's marks, forwarded flat (absent → absent).
1931
- ...artifacts.timing?.cameraReadyMs !== void 0 ? { cameraReadyMs: artifacts.timing.cameraReadyMs } : {},
1932
- ...artifacts.timing?.faceAcquireMs !== void 0 ? { faceAcquireMs: artifacts.timing.faceAcquireMs } : {},
1933
- ...artifacts.timing?.captureMs !== void 0 ? { captureMs: artifacts.timing.captureMs } : {}
1934
- });
1935
- }),
1936
- engine.on("error", ({ kind, retryable }) => {
1937
- emitter.emit("error", { kind: mapErrorKind(kind), retryable });
1938
- })
1939
- ];
1940
- const handle = {
1941
- get state() {
1942
- return state;
1943
- },
1944
- on: (event, handler) => emitter.on(event, handler),
1945
- start: (startOptions) => engine.start(startOptions?.facing !== void 0 ? { facingMode: startOptions.facing } : {}),
1946
- retry: () => engine.retry(),
1947
- switchCamera: () => engine.switchCamera(),
1948
- destroy: () => {
1949
- for (const unsubscribe of unsubscribes) unsubscribe();
1950
- wakeLock.setActive(false);
1951
- engine.destroy();
1952
- emitter.clear();
1953
- }
1954
- };
1955
- return {
1956
- handle,
1957
- setFlowState: (next) => {
1958
- if (state !== next) setState(next);
1959
- }
1960
- };
1961
- }
1962
- function createLivenessCapture(options) {
1963
- return createLivenessCaptureInternal(options).handle;
1964
- }
1965
-
1966
- // src/capture/camera-probe.ts
1967
- async function permissionStatus() {
1968
- try {
1969
- if (typeof navigator === "undefined" || typeof navigator.permissions?.query !== "function") return null;
1970
- return await navigator.permissions.query({ name: "camera" });
1971
- } catch {
1972
- return null;
1973
- }
1974
- }
1975
- function asState(state) {
1976
- return state === "granted" || state === "prompt" || state === "denied" ? state : "unknown";
1977
- }
1978
- async function queryCameraPermission() {
1979
- const status = await permissionStatus();
1980
- return status === null ? "unknown" : asState(status.state);
1981
- }
1982
- function subscribeCameraPermission(listener) {
1983
- let stopped = false;
1984
- let status = null;
1985
- const onChange = () => {
1986
- if (!stopped && status !== null) listener(asState(status.state));
1987
- };
1988
- void permissionStatus().then((resolved) => {
1989
- if (stopped) return;
1990
- status = resolved;
1991
- listener(resolved === null ? "unknown" : asState(resolved.state));
1992
- resolved?.addEventListener?.("change", onChange);
1993
- });
1994
- return () => {
1995
- stopped = true;
1996
- status?.removeEventListener?.("change", onChange);
1997
- };
1998
- }
1999
- async function hasMultipleCameras() {
2000
- if (typeof navigator === "undefined") return false;
2001
- const ua = String(navigator.userAgent ?? "");
2002
- if (/Android|iPhone|iPad|iPod/i.test(ua)) return true;
2003
- if (/Macintosh/.test(ua) && (navigator.maxTouchPoints ?? 0) > 1) return true;
2004
- try {
2005
- const devices = await navigator.mediaDevices?.enumerateDevices?.() ?? [];
2006
- return devices.filter((device) => device.kind === "videoinput").length >= 2;
2007
- } catch {
2008
- return false;
2009
- }
2010
- }
2011
-
2012
- // src/client/errors.ts
2013
- var KNOWN_CODES = [
2014
- // auth / addressing (session-token.guard, controllers' own-session guards)
2015
- "session_token_invalid",
2016
- // 401 — missing/invalid/expired/revoked token
2017
- "session_token_required",
2018
- // 403 — non-session-token principal on a hosted route (defensive)
2019
- "session_token_session_mismatch",
2020
- // 403 — route :id differs from the token's bound session
2021
- "session_not_found",
2022
- // 404 — token's session missing/foreign (findOwned)
2023
- // rate limiting (session-token.guard — per-token + per-IP buckets)
2024
- "rate_limit_exceeded",
2025
- // 429 + Retry-After header (seconds)
2026
- // consent gate (Task 0 — submit AND media presign/complete)
2027
- "consent_required",
2028
- // 409 — record consent before uploading/submitting
2029
- // submit flow (sessions.service.submitCheck)
2030
- "session_not_active",
2031
- // 409 — session is terminal/review; no further submissions
2032
- "check_not_found",
2033
- // 404 — session has no such checkType
2034
- "check_already_finalized",
2035
- // 409 — re-submit of a terminal/review check
2036
- "check_out_of_order",
2037
- // 409 — only the frontier check accepts a submission
2038
- "check_type_unsupported",
2039
- // 400 — no registered executor for the checkType
2040
- "force_outcome_forbidden",
2041
- // 403 — forceOutcome on a live session (plan D-C)
2042
- "attestation_invalid",
2043
- // 400 (Task 1) — Turnstile/attestation failed; reload and retry
2044
- "nni_locked",
2045
- // 409 (Plan A Task 2) — session is bound to a server-provided NNI; a different client NNI was sent
2046
- // media (media.service)
2047
- "media_content_type_not_allowed",
2048
- // 400 — outside the per-kind MIME allowlist
2049
- "media_too_large",
2050
- // 413 — over the per-kind byte cap
2051
- "media_key_invalid",
2052
- // 400 — not a well-formed pending key
2053
- "media_key_forbidden",
2054
- // 403 — key names another session's pending space
2055
- "media_not_found",
2056
- // 404 — no uploaded object behind the key
2057
- "media_unreadable",
2058
- // 422 — magic-byte sniff rejected the object
2059
- "media_session_invalid",
2060
- // 400 — sessionId unusable as a key segment (never in practice)
2061
- // idempotency (idempotency.interceptor — Task 2)
2062
- "idempotency_key_collision",
2063
- // 409 — same key, different body hash
2064
- "idempotency_in_progress",
2065
- // 409 — concurrent identical request mid-flight (client auto-retries)
2066
- "idempotency_key_required",
2067
- // 400 — only on @Idempotent({required:true}) routes (none hosted yet)
2068
- // validation + fallback
2069
- "validation_error",
2070
- // 400 — ValibotPipe rejection (camelToSnake of 'ValidationError')
2071
- "internal_error",
2072
- // 500 — unhandled server error
2073
- // client-synthesized (never sent by the backend)
2074
- "unknown_error",
2075
- // unparseable (non-JSON) response body — error OR 2xx (defensive)
2076
- "upload_failed",
2077
- // the bare Spaces PUT answered non-2xx
2078
- "network_error",
2079
- // fetch rejected: connection drop / DNS / CORS / mid-transfer (status 0)
2080
- "timeout"
2081
- // AbortSignal.timeout fired — API calls 30 s default, Spaces PUT 15 min (status 0)
2082
- ];
2083
- function isKnownCode(code) {
2084
- return KNOWN_CODES.includes(code);
2085
- }
2086
- var HostedApiError = class extends Error {
2087
- constructor(args) {
2088
- super(args.message);
2089
- this.name = "HostedApiError";
2090
- this.status = args.status;
2091
- this.code = args.code;
2092
- if (args.retryAfterSeconds !== void 0) this.retryAfterSeconds = args.retryAfterSeconds;
2093
- }
2094
- };
2095
-
2096
- // src/client/hosted-client.ts
2097
- var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
2098
- var SPACES_PUT_TIMEOUT_MS = 9e5;
2099
- var UPLOAD_ERROR_SNIPPET_CHARS = 200;
2100
- var IN_PROGRESS_RETRY_ATTEMPTS = 5;
2101
- var IN_PROGRESS_RETRY_DELAY_MS = 400;
2102
- function stripMimeParams(contentType) {
2103
- return (contentType.split(";")[0] ?? "").trim();
2104
- }
2105
- var MEDIA_INPUT_FIELD = {
2106
- liveness: "clipKey",
2107
- face_match: "imageKey",
2108
- doc_ocr: "imageKey"
2109
- };
2110
- var HostedClient = class {
2111
- constructor(opts) {
2112
- this.sessionId = null;
2113
- this.bootstrap = null;
2114
- this.apiOrigin = opts.apiOrigin.replace(/\/+$/, "");
2115
- this.sessionToken = opts.sessionToken;
2116
- const impl = opts.fetch;
2117
- this.fetchImpl = (input, init) => (impl ?? globalThis.fetch).call(globalThis, input, init);
2118
- this.requestTimeoutMs = opts.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
2119
- this.retryAttempts = opts.inProgressRetry?.attempts ?? IN_PROGRESS_RETRY_ATTEMPTS;
2120
- this.retryDelayMs = opts.inProgressRetry?.delayMs ?? IN_PROGRESS_RETRY_DELAY_MS;
2121
- }
2122
- /** Token-addressed bootstrap — the hosted page's first call. Caches the sessionId. */
2123
- async getSession() {
2124
- const view = await this.api("GET", "/hosted/session");
2125
- this.sessionId = view.sessionId;
2126
- return view;
2127
- }
2128
- /**
2129
- * Record consent once (201; an idempotent replay answers 200 with
2130
- * `alreadyRecorded: true`). Until recorded, media presign/complete AND check
2131
- * submission answer 409 `consent_required`.
2132
- */
2133
- async recordConsent(locale) {
2134
- return this.api("POST", "/hosted/consent", { body: { locale } });
2135
- }
2136
- /**
2137
- * Presign a Spaces PUT for a new pending object. `contentType` is stripped of
2138
- * MIME parameters defensively (the allowlist holds bare types; the engine's
2139
- * `clipMimeType` carries codec params) — PUT with the SAME bare type, or the
2140
- * signed-header check rejects the upload.
2141
- */
2142
- async presign(kind, contentType, contentLength) {
2143
- const id = await this.ensureSessionId();
2144
- const body = { kind, contentType: stripMimeParams(contentType), contentLength };
2145
- return this.api("POST", `/sessions/${id}/media`, { body });
2146
- }
2147
- /**
2148
- * Bare PUT to the presigned Spaces URL: EXACTLY the signed headers — the
2149
- * declared Content-Type and the blob body. NO `x-session-token` (the
2150
- * signature IS the credential; an extra header breaks nothing but leaks the
2151
- * token to a third-party host) and no JSON envelope.
2152
- *
2153
- * `contentType` is param-stripped here too (idempotent for bare types): the
2154
- * presign strips internally, so a caller composing manually with the engine's
2155
- * parameterful `clipMimeType` would otherwise sign `video/webm` but PUT
2156
- * `video/webm;codecs=…` — a signed-header mismatch S3 rejects at runtime.
2157
- *
2158
- * Timeout: 15 min (`AbortSignal.timeout(900_000)`, matching the presign TTL)
2159
- * rather than the API calls' 30 s — a 15 MB clip on a slow link legitimately
2160
- * exceeds 30 s, but a stalled in-flight socket must still be bounded (the TTL
2161
- * alone only bounds when a PUT can START).
2162
- *
2163
- * Failures are ALWAYS typed: non-2xx throws {@link HostedApiError} with the
2164
- * client-synthesized `upload_failed` (message carries a truncated S3 body
2165
- * snippet — e.g. SignatureDoesNotMatch); a mid-transfer drop → `network_error`;
2166
- * the timeout → `timeout`.
2167
- */
2168
- async uploadToSpaces(uploadUrl, blob, contentType) {
2169
- let res;
2170
- try {
2171
- res = await this.fetchImpl(uploadUrl, {
2172
- method: "PUT",
2173
- headers: { "content-type": stripMimeParams(contentType) },
2174
- body: blob,
2175
- signal: AbortSignal.timeout(SPACES_PUT_TIMEOUT_MS)
2176
- });
2177
- } catch (err) {
2178
- throw asTransportError(err);
2179
- }
2180
- if (!res.ok) {
2181
- const snippet = (await res.text().catch(() => "")).slice(0, UPLOAD_ERROR_SNIPPET_CHARS);
2182
- throw new HostedApiError({
2183
- status: res.status,
2184
- code: "upload_failed",
2185
- message: `media upload failed (HTTP ${res.status})${snippet ? `: ${snippet}` : ""}`
2186
- });
2187
- }
2188
- }
2189
- /** Finalize an upload: the backend sniffs + promotes; returns the PROMOTED key to submit. */
2190
- async completeMedia(key) {
2191
- const id = await this.ensureSessionId();
2192
- return this.api("POST", `/sessions/${id}/media/complete`, {
2193
- body: { key }
2194
- });
2195
- }
2196
- /**
2197
- * Submit one check. Sends `{input, forceOutcome?}` (SubmitCheckSchema) and the
2198
- * optional `x-idempotency-key` header. Returns the whitelisted SessionView.
2199
- */
2200
- async submitCheck(checkType, input, opts = {}) {
2201
- const id = await this.ensureSessionId();
2202
- const body = {
2203
- input,
2204
- ...opts.forceOutcome !== void 0 ? { forceOutcome: opts.forceOutcome } : {}
2205
- };
2206
- return this.api("POST", `/sessions/${id}/checks/${checkType}`, {
2207
- body,
2208
- ...opts.idempotencyKey !== void 0 ? { idempotencyKey: opts.idempotencyKey } : {}
2209
- });
2210
- }
2211
- /**
2212
- * Convenience composition: presign → PUT → complete → submit, passing the
2213
- * PROMOTED key (from complete's response — never the pending presign key)
2214
- * into the check's media input field (`clipKey` for liveness, `imageKey` for
2215
- * face_match/doc_ocr). `extraInput` carries the remaining input fields
2216
- * (liveness `attestation`, doc_ocr `side`). The media content type is
2217
- * param-stripped ONCE and used for both presign and PUT, so the signed
2218
- * header always matches.
2219
- */
2220
- async uploadAndSubmit(checkType, media, extraInput, opts = {}) {
2221
- const bareType = stripMimeParams(media.contentType);
2222
- const presigned = await this.presign(media.kind, bareType, media.blob.size);
2223
- await this.uploadToSpaces(presigned.uploadUrl, media.blob, bareType);
2224
- const completed = await this.completeMedia(presigned.key);
2225
- const input = {
2226
- ...extraInput,
2227
- [MEDIA_INPUT_FIELD[checkType]]: completed.key
2228
- };
2229
- return this.submitCheck(checkType, input, opts);
2230
- }
2231
- // ── transport ──────────────────────────────────────────────────────────────
2232
- /** The token's own sessionId — cached from getSession(), lazily bootstrapped. */
2233
- async ensureSessionId() {
2234
- if (this.sessionId !== null) return this.sessionId;
2235
- this.bootstrap ?? (this.bootstrap = this.getSession().finally(() => {
2236
- this.bootstrap = null;
2237
- }));
2238
- return (await this.bootstrap).sessionId;
2239
- }
2240
- /**
2241
- * One API request: `${apiOrigin}/api/v2${path}`, `x-session-token` always,
2242
- * AbortSignal timeout (30 s default), `{success, data}` unwrap on 2xx, flat
2243
- * `{code, message}` → {@link HostedApiError} on non-2xx. EVERY failure is
2244
- * typed: a rejected fetch → `network_error`, the timeout → `timeout`, an
2245
- * unparseable 2xx body → `unknown_error` — the page never sees a raw
2246
- * TypeError/DOMException. The ONLY automatic retry is 409
2247
- * `idempotency_in_progress` (bounded, short delay).
2248
- */
2249
- async api(method, path, opts = {}) {
2250
- const url = `${this.apiOrigin}/api/v2${path}`;
2251
- const headers = { "x-session-token": this.sessionToken };
2252
- if (opts.body !== void 0) headers["content-type"] = "application/json";
2253
- if (opts.idempotencyKey !== void 0) headers["x-idempotency-key"] = opts.idempotencyKey;
2254
- for (let attempt = 0; ; attempt++) {
2255
- let res;
2256
- try {
2257
- res = await this.fetchImpl(url, {
2258
- method,
2259
- headers,
2260
- ...opts.body !== void 0 ? { body: JSON.stringify(opts.body) } : {},
2261
- signal: AbortSignal.timeout(this.requestTimeoutMs)
2262
- });
2263
- } catch (err2) {
2264
- throw asTransportError(err2);
2265
- }
2266
- if (res.ok) {
2267
- let raw;
2268
- try {
2269
- raw = await res.json();
2270
- } catch {
2271
- throw new HostedApiError({
2272
- status: res.status,
2273
- code: "unknown_error",
2274
- message: `response body was not valid JSON (HTTP ${res.status})`
2275
- });
2276
- }
2277
- return unwrap(raw);
2278
- }
2279
- const err = await parseErrorResponse(res);
2280
- if (err.code === "idempotency_in_progress" && attempt < this.retryAttempts) {
2281
- if (this.retryDelayMs > 0) await sleep(this.retryDelayMs);
2282
- continue;
2283
- }
2284
- throw err;
2285
- }
2286
- }
2287
- };
2288
- function asTransportError(err) {
2289
- const name = typeof err === "object" && err !== null ? err.name : void 0;
2290
- if (name === "TimeoutError") {
2291
- return new HostedApiError({ status: 0, code: "timeout", message: "request timed out" });
2292
- }
2293
- const detail = err instanceof Error ? err.message : String(err);
2294
- return new HostedApiError({
2295
- status: 0,
2296
- code: "network_error",
2297
- message: `network request failed: ${detail}`
2298
- });
2299
- }
2300
- function unwrap(raw) {
2301
- if (raw !== null && typeof raw === "object" && "success" in raw && "data" in raw) {
2302
- return raw.data;
2303
- }
2304
- return raw;
2305
- }
2306
- async function parseErrorResponse(res) {
2307
- let code = "unknown_error";
2308
- let message = `request failed (HTTP ${res.status})`;
2309
- try {
2310
- const body = await res.json();
2311
- if (body !== null && typeof body === "object") {
2312
- const env = body;
2313
- if (typeof env.code === "string" && env.code.length > 0) code = env.code;
2314
- if (typeof env.message === "string" && env.message.length > 0) message = env.message;
2315
- }
2316
- } catch {
2317
- }
2318
- const retryAfterRaw = res.headers.get("retry-after");
2319
- const retryAfter = retryAfterRaw === null ? Number.NaN : Number.parseInt(retryAfterRaw, 10);
2320
- return new HostedApiError({
2321
- status: res.status,
2322
- code,
2323
- message,
2324
- ...Number.isFinite(retryAfter) && retryAfter >= 0 ? { retryAfterSeconds: retryAfter } : {}
2325
- });
2326
- }
2327
- function sleep(ms) {
2328
- return new Promise((resolve) => setTimeout(resolve, ms));
2329
- }
2330
-
2331
- // src/verification/result.ts
2332
- var RETRYABLE_REASONS = /* @__PURE__ */ new Set([
2333
- "no_face",
2334
- "media_unreadable",
2335
- "clip_too_short",
2336
- "no_face_source",
2337
- "side_missing",
2338
- "unreadable",
2339
- "registry_unavailable",
2340
- "otp_mismatch",
2341
- "otp_expired",
2342
- "otp_send_failed"
2343
- ]);
2344
- var BIOMETRIC_CHECKS = /* @__PURE__ */ new Set(["liveness", "face_match"]);
2345
- function isExecutable(step) {
2346
- return step !== void 0 && (step.state === "pending" || step.state === "input_required");
2347
- }
2348
- function isTerminalView(view) {
2349
- return view.status !== "created" && view.status !== "in_progress";
2350
- }
2351
- function frontierStep(view) {
2352
- return view.steps.find((step) => isExecutable(step));
2353
- }
2354
- function stepOf(view, checkType) {
2355
- return view.steps.find((step) => step.checkType === checkType);
2356
- }
2357
- function mergeSessionView(prev, next, submitted) {
2358
- const byType = new Map(prev.steps.map((step) => [step.checkType, step]));
2359
- const steps = next.steps.map((step) => {
2360
- const before = byType.get(step.checkType);
2361
- const attemptsBefore = before?.attemptsRemaining ?? 0;
2362
- const merged = {
2363
- ...before ?? {},
2364
- checkType: step.checkType,
2365
- state: step.state,
2366
- attemptsRemaining: step.checkType === submitted ? Math.max(0, attemptsBefore - 1) : attemptsBefore
2367
- };
2368
- if (step.reason !== void 0) merged.reason = step.reason;
2369
- else delete merged.reason;
2370
- return merged;
2371
- });
2372
- return { ...prev, status: next.status, outcome: next.outcome, steps, expiresAt: next.expiresAt };
2373
- }
2374
- function unavailable(sessionId, reason) {
2375
- return reason === void 0 ? { sessionId, status: "unavailable" } : { sessionId, status: "unavailable", reason };
2376
- }
2377
- function withReason(sessionId, status, reason) {
2378
- return reason === void 0 ? { sessionId, status } : { sessionId, status, reason };
2379
- }
2380
- function mapSessionResult(view, opts) {
2381
- const { sessionId } = view;
2382
- switch (view.status) {
2383
- case "completed":
2384
- if (view.outcome === "approved") return { sessionId, status: "approved" };
2385
- if (view.outcome === "review") return withReason(sessionId, "review", reasonIn(view, "review"));
2386
- return withReason(sessionId, "rejected", reasonIn(view, "failed"));
2387
- case "failed":
2388
- return withReason(sessionId, "rejected", reasonIn(view, "failed"));
2389
- case "review_pending":
2390
- return withReason(sessionId, "review", reasonIn(view, "review"));
2391
- case "expired":
2392
- return unavailable(sessionId);
2393
- case "created":
2394
- case "in_progress":
2395
- break;
2396
- default: {
2397
- const unhandled = view.status;
2398
- throw new Error(`mapSessionResult: unhandled status ${unhandled}`);
2399
- }
2400
- }
2401
- const parked = view.steps.find(
2402
- (step) => BIOMETRIC_CHECKS.has(step.checkType) && step.state === "input_required" && step.reason !== void 0
2403
- );
2404
- if (parked?.reason !== void 0) {
2405
- const canRetry = opts.autoRetry && RETRYABLE_REASONS.has(parked.reason) && parked.attemptsRemaining > 0;
2406
- return {
2407
- sessionId,
2408
- status: canRetry ? "retry" : "rejected",
2409
- reason: parked.reason,
2410
- attemptsRemaining: parked.attemptsRemaining
2411
- };
2412
- }
2413
- if (frontierStep(view) === void 0 && view.steps.some((step) => step.state === "review")) {
2414
- return withReason(sessionId, "review", reasonIn(view, "review"));
2415
- }
2416
- return unavailable(sessionId);
2417
- }
2418
- function reasonIn(view, state) {
2419
- return view.steps.find((step) => step.state === state && step.reason !== void 0)?.reason;
2420
- }
2421
-
2422
- // src/verification/liveness-flow.ts
2423
- var CLIP_MIME_ALLOWLIST = ["video/webm", "video/mp4"];
2424
- var KEYFRAME_MIME = "image/jpeg";
2425
- var TRANSPORT_REPLAY_ATTEMPTS = 2;
2426
- var TRANSPORT_REPLAY_DELAY_MS = 1e3;
2427
- var MAX_RETRY_AFTER_MS = 1e4;
2428
- var RESYNC_REENTRY_MAX = 3;
2429
- var TRANSPORT_CODES = /* @__PURE__ */ new Set([
2430
- "network_error",
2431
- "timeout",
2432
- "upload_failed",
2433
- "unknown_error",
2434
- "rate_limit_exceeded"
2435
- ]);
2436
- var RESYNC_CODES = /* @__PURE__ */ new Set([
2437
- "session_not_active",
2438
- "check_not_found",
2439
- "check_already_finalized",
2440
- "check_out_of_order"
2441
- ]);
2442
- var AttestationError = class extends Error {
2443
- constructor(message) {
2444
- super(message);
2445
- this.name = "AttestationError";
2446
- }
2447
- };
2448
- async function runSubmission(rt, executor, hooks = {}) {
2449
- let key = rt.uuid();
2450
- let consentRecovered = false;
2451
- let attestationRetried = false;
2452
- let transportReplays = 0;
2453
- for (; ; ) {
2454
- try {
2455
- return await executor(rt.client, key);
2456
- } catch (err) {
2457
- if (err instanceof AttestationError) {
2458
- if (attestationRetried) throw err;
2459
- attestationRetried = true;
2460
- hooks.onAttestationInvalid?.();
2461
- key = rt.uuid();
2462
- continue;
2463
- }
2464
- if (!(err instanceof HostedApiError)) throw err;
2465
- if (err.code === "consent_required" && !consentRecovered) {
2466
- consentRecovered = true;
2467
- await rt.ensureConsent({ force: true });
2468
- key = rt.uuid();
2469
- continue;
2470
- }
2471
- if (err.code === "attestation_invalid" && !attestationRetried) {
2472
- attestationRetried = true;
2473
- hooks.onAttestationInvalid?.();
2474
- key = rt.uuid();
2475
- continue;
2476
- }
2477
- if (TRANSPORT_CODES.has(err.code) && transportReplays < TRANSPORT_REPLAY_ATTEMPTS) {
2478
- transportReplays += 1;
2479
- const retryAfterMs = err.retryAfterSeconds !== void 0 ? err.retryAfterSeconds * 1e3 : void 0;
2480
- await rt.sleep(
2481
- retryAfterMs !== void 0 ? Math.min(retryAfterMs, MAX_RETRY_AFTER_MS) : TRANSPORT_REPLAY_DELAY_MS
2482
- );
2483
- continue;
2484
- }
2485
- throw err;
2486
- }
2487
- }
2488
- }
2489
- var LIVENESS_CHAINABLE = /* @__PURE__ */ new Set(["passed", "review", "processing", "skipped"]);
2490
- async function runLivenessFlow(deps) {
2491
- const { artifacts } = deps;
2492
- const clip = artifacts.clip;
2493
- const bareMime = stripMimeParams(artifacts.clipMime ?? "");
2494
- if (artifacts.degraded === "NO_RECORDER" || clip === void 0 || !CLIP_MIME_ALLOWLIST.includes(bareMime)) {
2495
- return { kind: "unavailable", reason: "no_recorder" };
2496
- }
2497
- const submitLiveness = buildLivenessSubmit(deps, clip, bareMime);
2498
- const submitFaceMatch = buildFaceMatchSubmit(deps, artifacts.keyframe);
2499
- let livenessSubmitted = false;
2500
- let faceMatchSubmitted = false;
2501
- let livenessChainable = true;
2502
- let resyncs = 0;
2503
- for (; ; ) {
2504
- if (deps.isCancelled()) return { kind: "cancelled" };
2505
- const view = deps.getView();
2506
- if (isTerminalView(view)) return { kind: "settled" };
2507
- const frontier = frontierStep(view)?.checkType;
2508
- const next = frontier === "liveness" && !livenessSubmitted ? "liveness" : frontier === "face_match" && !faceMatchSubmitted && livenessChainable ? "face_match" : null;
2509
- if (next === null) return { kind: "settled" };
2510
- try {
2511
- if (next === "liveness") {
2512
- livenessSubmitted = true;
2513
- const response = await submitLiveness();
2514
- if (deps.isCancelled()) return { kind: "cancelled" };
2515
- deps.applySubmit(response, "liveness");
2516
- const state = stepOf(deps.getView(), "liveness")?.state;
2517
- livenessChainable = state === void 0 || LIVENESS_CHAINABLE.has(state);
2518
- } else {
2519
- faceMatchSubmitted = true;
2520
- const response = await submitFaceMatch();
2521
- if (deps.isCancelled()) return { kind: "cancelled" };
2522
- deps.applySubmit(response, "face_match");
2523
- }
2524
- } catch (err) {
2525
- if (deps.isCancelled()) return { kind: "cancelled" };
2526
- const outcome = classifyFailure(err);
2527
- if (outcome.kind !== "resync" || resyncs >= RESYNC_REENTRY_MAX) return outcome;
2528
- resyncs += 1;
2529
- await deps.refreshView();
2530
- }
2531
- }
2532
- }
2533
- function buildLivenessSubmit(deps, clip, bareMime) {
2534
- let clipKey = null;
2535
- let attestation = null;
2536
- return () => runSubmission(
2537
- deps,
2538
- async (client, idempotencyKey) => {
2539
- if (clipKey === null) {
2540
- deps.onPhase("uploading");
2541
- const presigned = await client.presign("clip", bareMime, clip.size);
2542
- await client.uploadToSpaces(presigned.uploadUrl, clip, bareMime);
2543
- clipKey = (await client.completeMedia(presigned.key)).key;
2544
- }
2545
- if (attestation === null) {
2546
- try {
2547
- attestation = await deps.getAttestation();
2548
- } catch (err) {
2549
- throw new AttestationError(err instanceof Error ? err.message : String(err));
2550
- }
2551
- }
2552
- deps.onPhase("checking");
2553
- return client.submitCheck(
2554
- "liveness",
2555
- {
2556
- clipKey,
2557
- attestation,
2558
- captureChannel: deps.artifacts.captureChannel,
2559
- capture: captureInputOf(deps.artifacts)
2560
- },
2561
- { idempotencyKey }
2562
- );
2563
- },
2564
- {
2565
- onAttestationInvalid: () => {
2566
- attestation = null;
2567
- }
2568
- }
2569
- );
2570
- }
2571
- function captureInputOf(artifacts) {
2572
- return {
2573
- ...artifacts.engine !== void 0 ? { engine: artifacts.engine } : {},
2574
- width: artifacts.width,
2575
- height: artifacts.height,
2576
- ...artifacts.clipMs !== void 0 ? { clipMs: artifacts.clipMs } : {},
2577
- ...artifacts.cameraReadyMs !== void 0 ? { cameraReadyMs: artifacts.cameraReadyMs } : {},
2578
- ...artifacts.faceAcquireMs !== void 0 ? { faceAcquireMs: artifacts.faceAcquireMs } : {},
2579
- ...artifacts.captureMs !== void 0 ? { captureMs: artifacts.captureMs } : {}
2580
- };
2581
- }
2582
- function buildFaceMatchSubmit(deps, keyframe) {
2583
- let imageKey = null;
2584
- return () => runSubmission(deps, async (client, idempotencyKey) => {
2585
- if (imageKey === null) {
2586
- deps.onPhase("uploading");
2587
- const presigned = await client.presign("image", KEYFRAME_MIME, keyframe.size);
2588
- await client.uploadToSpaces(presigned.uploadUrl, keyframe, KEYFRAME_MIME);
2589
- imageKey = (await client.completeMedia(presigned.key)).key;
2590
- }
2591
- deps.onPhase("checking");
2592
- return client.submitCheck("face_match", { imageKey }, { idempotencyKey });
2593
- });
2594
- }
2595
- function classifyFailure(err) {
2596
- if (err instanceof AttestationError) return { kind: "unavailable", reason: "attestation" };
2597
- if (err instanceof HostedApiError) {
2598
- if (err.code === "attestation_invalid") return { kind: "unavailable", reason: "attestation" };
2599
- if (RESYNC_CODES.has(err.code)) return { kind: "resync" };
2600
- }
2601
- return { kind: "unavailable", reason: "network" };
2602
- }
2603
-
2604
- // src/verification/turnstile.ts
2605
- var TURNSTILE_SCRIPT_SRC = "https://challenges.cloudflare.com/turnstile/v0/api.js";
2606
- var TURNSTILE_EXECUTE_TIMEOUT_MS = 3e4;
2607
- function installedApi() {
2608
- return window.turnstile;
2609
- }
2610
- var loaderPromise = null;
2611
- function loadTurnstile() {
2612
- loaderPromise ?? (loaderPromise = new Promise((resolve, reject) => {
2613
- const present = installedApi();
2614
- if (present) {
2615
- resolve(present);
2616
- return;
2617
- }
2618
- const script = document.createElement("script");
2619
- script.src = TURNSTILE_SCRIPT_SRC;
2620
- script.async = true;
2621
- script.onload = () => {
2622
- const api = installedApi();
2623
- if (api) {
2624
- resolve(api);
2625
- } else {
2626
- loaderPromise = null;
2627
- reject(new Error("Turnstile script loaded but exposed no API"));
2628
- }
2629
- };
2630
- script.onerror = () => {
2631
- loaderPromise = null;
2632
- script.remove();
2633
- reject(new Error("Turnstile script failed to load"));
2634
- };
2635
- document.head.appendChild(script);
2636
- }));
2637
- return loaderPromise;
2638
- }
2639
- function abortError() {
2640
- return new Error("Turnstile challenge aborted");
2641
- }
2642
- async function executeTurnstile(siteKey, opts = {}) {
2643
- const timeoutMs = opts.timeoutMs ?? TURNSTILE_EXECUTE_TIMEOUT_MS;
2644
- const signal = opts.signal;
2645
- if (signal?.aborted) throw abortError();
2646
- const api = await loadTurnstile();
2647
- if (signal?.aborted) throw abortError();
2648
- const container = document.createElement("div");
2649
- document.body.appendChild(container);
2650
- let widgetId;
2651
- let timer;
2652
- let onAbort;
2653
- try {
2654
- return await new Promise((resolve, reject) => {
2655
- timer = setTimeout(
2656
- () => reject(new Error(`Turnstile challenge timed out (${timeoutMs} ms)`)),
2657
- timeoutMs
2658
- );
2659
- if (signal !== void 0) {
2660
- onAbort = () => reject(abortError());
2661
- signal.addEventListener("abort", onAbort, { once: true });
2662
- }
2663
- widgetId = api.render(container, {
2664
- sitekey: siteKey,
2665
- execution: "execute",
2666
- appearance: "execute",
2667
- callback: resolve,
2668
- "error-callback": (code) => {
2669
- reject(new Error(`Turnstile challenge failed${code ? ` (${code})` : ""}`));
2670
- }
2671
- });
2672
- if (widgetId === void 0) {
2673
- reject(new Error("Turnstile render returned no widget id"));
2674
- return;
2675
- }
2676
- api.execute(widgetId);
2677
- });
2678
- } finally {
2679
- clearTimeout(timer);
2680
- if (signal !== void 0 && onAbort !== void 0) signal.removeEventListener("abort", onAbort);
2681
- if (widgetId !== void 0) {
2682
- try {
2683
- api.remove(widgetId);
2684
- } catch {
2685
- }
2686
- }
2687
- container.remove();
2688
- }
2689
- }
2690
-
2691
- // src/verification/create-verification.ts
2692
- var DEFAULT_API_ORIGIN = "https://api.sekyro.ai";
2693
- var REGISTRY_RETRY_DELAY_MS = 5e3;
2694
- var PROCESSING_POLL_DELAY_MS = 1500;
2695
- var PROCESSING_POLL_MAX = 10;
2696
- function defaultSleep(ms) {
2697
- return new Promise((resolve) => setTimeout(resolve, ms));
2698
- }
2699
- function randomUuid() {
2700
- const c = globalThis.crypto;
2701
- if (c !== void 0 && typeof c.randomUUID === "function") return c.randomUUID();
2702
- const bytes = new Uint8Array(16);
2703
- if (c !== void 0 && typeof c.getRandomValues === "function") c.getRandomValues(bytes);
2704
- else for (let i = 0; i < 16; i += 1) bytes[i] = Math.floor(Math.random() * 256);
2705
- bytes[6] = (bytes[6] ?? 0) & 15 | 64;
2706
- bytes[8] = (bytes[8] ?? 0) & 63 | 128;
2707
- const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
2708
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
2709
- }
2710
- function createVerification(options) {
2711
- return createVerificationInternal(options, {});
2712
- }
2713
- function createVerificationInternal(options, internals) {
2714
- const apiOrigin = options.apiOrigin ?? DEFAULT_API_ORIGIN;
2715
- const autoRetry = options.autoRetry ?? true;
2716
- const rearm = options.rearm ?? "auto";
2717
- const client = internals.client ?? new HostedClient({
2718
- apiOrigin,
2719
- sessionToken: options.clientToken,
2720
- ...options.fetch !== void 0 ? { fetch: options.fetch } : {}
2721
- });
2722
- const sleep2 = internals.sleep ?? defaultSleep;
2723
- const uuid = internals.uuid ?? randomUuid;
2724
- const getTurnstileToken = internals.getTurnstileToken ?? executeTurnstile;
2725
- const emitter = createEmitter();
2726
- let destroyed = false;
2727
- const lifetime = new AbortController();
2728
- let view = null;
2729
- let bootstrap = null;
2730
- const setView = (next) => {
2731
- view = next;
2732
- emitter.emit("view", next);
2733
- };
2734
- const ensureView = () => {
2735
- if (view !== null) return Promise.resolve(view);
2736
- bootstrap ?? (bootstrap = client.getSession().then((next) => {
2737
- setView(next);
2738
- return next;
2739
- }).finally(() => {
2740
- bootstrap = null;
2741
- }));
2742
- return bootstrap;
2743
- };
2744
- const refreshView = async () => {
2745
- const next = await client.getSession();
2746
- setView(next);
2747
- return next;
2748
- };
2749
- const applySubmit = (response, submitted) => {
2750
- if (view !== null) setView(mergeSessionView(view, response, submitted));
2751
- };
2752
- let consentInFlight = null;
2753
- const recordConsent = async (force) => {
2754
- const current = await ensureView();
2755
- if (!force && current.consentRecorded) return;
2756
- await client.recordConsent(options.locale);
2757
- if (view !== null) setView({ ...view, consentRecorded: true });
2758
- };
2759
- const ensureConsent = (opts) => {
2760
- if (opts?.force === true) return recordConsent(true);
2761
- consentInFlight ?? (consentInFlight = recordConsent(false).finally(() => {
2762
- consentInFlight = null;
2763
- }));
2764
- return consentInFlight;
2765
- };
2766
- const runtime = {
2767
- client,
2768
- ensureConsent: (opts) => ensureConsent(opts),
2769
- sleep: sleep2,
2770
- uuid
2771
- };
2772
- let terminalEmitted = false;
2773
- const emitResult = (result) => {
2774
- if (result.status === "approved" || result.status === "rejected" || result.status === "review") {
2775
- if (terminalEmitted) return;
2776
- terminalEmitted = true;
2777
- }
2778
- emitter.emit("result", result);
2779
- };
2780
- let registry2 = null;
2781
- let registryFailed = false;
2782
- let registryUnbound = false;
2783
- const submitRegistry = () => runSubmission(
2784
- runtime,
2785
- (c, idempotencyKey) => (
2786
- // `{}` input: the session is bound to a SERVER-provided NNI (Plan A Task 2).
2787
- c.submitCheck("population_registry", {}, { idempotencyKey })
2788
- )
2789
- );
2790
- const runRegistry = async () => {
2791
- try {
2792
- const current = await ensureView();
2793
- if (isTerminalView(current) || frontierStep(current)?.checkType !== "population_registry") {
2794
- return;
2795
- }
2796
- if (current.nniBound !== true) {
2797
- registryUnbound = true;
2798
- return;
2799
- }
2800
- await ensureConsent();
2801
- applySubmit(await submitRegistry(), "population_registry");
2802
- const step = view === null ? void 0 : stepOf(view, "population_registry");
2803
- if (step?.state === "input_required" && step.reason === "registry_unavailable" && step.attemptsRemaining > 0) {
2804
- await sleep2(REGISTRY_RETRY_DELAY_MS);
2805
- if (destroyed) return;
2806
- applySubmit(await submitRegistry(), "population_registry");
2807
- }
2808
- } catch {
2809
- registryFailed = true;
2810
- return;
2811
- }
2812
- if (view !== null && isTerminalView(view)) emitResult(mapSessionResult(view, { autoRetry }));
2813
- };
2814
- const startRegistry = () => {
2815
- registry2 ?? (registry2 = runRegistry());
2816
- return registry2;
2817
- };
2818
- const getAttestation = async () => {
2819
- const current = await ensureView();
2820
- const siteKey = current.turnstileSiteKey;
2821
- if (siteKey === null) return { sandbox: true };
2822
- return {
2823
- channel: "hosted_web",
2824
- siteKey,
2825
- turnstileToken: await getTurnstileToken(siteKey, { signal: lifetime.signal })
2826
- };
2827
- };
2828
- let active = null;
2829
- let chain = Promise.resolve();
2830
- let chainDepth = 0;
2831
- const settleProcessing = async () => {
2832
- let current = await ensureView();
2833
- for (let i = 0; i < PROCESSING_POLL_MAX && !destroyed && !isTerminalView(current) && frontierStep(current) === void 0 && current.steps.some((step) => step.state === "processing"); i += 1) {
2834
- await sleep2(PROCESSING_POLL_DELAY_MS);
2835
- if (destroyed) break;
2836
- current = await refreshView();
2837
- }
2838
- return current;
2839
- };
2840
- const runFlow = async (bound, artifacts, capturedAttempt) => {
2841
- const { capture } = bound;
2842
- const isCancelled = () => destroyed;
2843
- const ownsHandle = () => bound.alive && bound.attempt === capturedAttempt;
2844
- const setPhase = (phase) => {
2845
- if (ownsHandle()) capture.setFlowState(phase);
2846
- };
2847
- const finish = (result) => {
2848
- if (isCancelled()) return;
2849
- emitResult(result);
2850
- if (!ownsHandle()) return;
2851
- if (result.status === "retry" && rearm === "auto") {
2852
- capture.handle.retry();
2853
- return;
2854
- }
2855
- capture.setFlowState("done");
2856
- };
2857
- if (artifacts.degraded === "NO_RECORDER") {
2858
- const sessionId = view?.sessionId ?? (await ensureView().catch(() => null))?.sessionId ?? "";
2859
- finish(unavailable(sessionId, "no_recorder"));
2860
- return;
2861
- }
2862
- setPhase("uploading");
2863
- try {
2864
- await startRegistry();
2865
- if (isCancelled()) return;
2866
- let current = await ensureView();
2867
- if (!isTerminalView(current)) {
2868
- if (frontierStep(current)?.checkType === "population_registry") {
2869
- finish(
2870
- unavailable(
2871
- current.sessionId,
2872
- registryUnbound ? "nni_unbound" : registryFailed ? "network" : "registry_unavailable"
2873
- )
2874
- );
2875
- return;
2876
- }
2877
- await ensureConsent();
2878
- if (isCancelled()) return;
2879
- const outcome = await runLivenessFlow({
2880
- ...runtime,
2881
- artifacts,
2882
- getAttestation,
2883
- getView: () => view ?? current,
2884
- refreshView,
2885
- applySubmit,
2886
- onPhase: setPhase,
2887
- isCancelled
2888
- });
2889
- if (isCancelled()) return;
2890
- if (outcome.kind === "unavailable") {
2891
- finish(unavailable(current.sessionId, outcome.reason));
2892
- return;
2893
- }
2894
- if (outcome.kind === "resync") await refreshView();
2895
- current = await settleProcessing();
2896
- }
2897
- finish(mapSessionResult(current, { autoRetry }));
2898
- } catch {
2899
- if (isCancelled()) return;
2900
- finish(unavailable(view?.sessionId ?? "", "network"));
2901
- }
2902
- };
2903
- const enqueueFlow = (bound, artifacts) => {
2904
- const capturedAttempt = bound.attempt;
2905
- if (chainDepth > 0 && bound.alive) {
2906
- bound.capture.setFlowState("uploading");
2907
- }
2908
- chainDepth += 1;
2909
- chain = chain.then(() => runFlow(bound, artifacts, capturedAttempt)).finally(() => {
2910
- chainDepth -= 1;
2911
- }).catch(() => void 0);
2912
- };
2913
- const liveness = (captureOptions) => {
2914
- active?.capture.handle.destroy();
2915
- if (active !== null) active.alive = false;
2916
- const capture = createLivenessCaptureInternal(captureOptions, internals.capture);
2917
- const bound = { capture, alive: true, attempt: 0 };
2918
- active = bound;
2919
- capture.handle.on("state", (state) => {
2920
- if (state === "starting") bound.attempt += 1;
2921
- });
2922
- capture.handle.on("captured", (artifacts) => {
2923
- void Promise.resolve().then(() => enqueueFlow(bound, artifacts));
2924
- });
2925
- const inner = capture.handle;
2926
- return {
2927
- get state() {
2928
- return inner.state;
2929
- },
2930
- on: (event, handler) => inner.on(event, handler),
2931
- start: (startOptions) => inner.start(startOptions),
2932
- retry: () => inner.retry(),
2933
- switchCamera: () => inner.switchCamera(),
2934
- destroy: () => {
2935
- bound.alive = false;
2936
- if (active === bound) active = null;
2937
- inner.destroy();
2938
- }
2939
- };
2940
- };
2941
- return {
2942
- consent: () => ensureConsent(),
2943
- startRegistry,
2944
- liveness,
2945
- voiceClips: async () => {
2946
- if (destroyed) return null;
2947
- try {
2948
- const current = await ensureView();
2949
- if (destroyed) return null;
2950
- return current.voice ?? null;
2951
- } catch {
2952
- return null;
2953
- }
2954
- },
2955
- on: (event, handler) => emitter.on(event, handler),
2956
- destroy: () => {
2957
- destroyed = true;
2958
- lifetime.abort();
2959
- if (active !== null) {
2960
- active.alive = false;
2961
- active.capture.handle.destroy();
2962
- active = null;
2963
- }
2964
- emitter.clear();
2965
- }
2966
- };
2967
- }
2968
-
2969
- // src/popup/index.ts
2970
- var SEKYRO_EVENTS = [
2971
- "session.completed",
2972
- "session.failed",
2973
- "session.review_pending",
2974
- "session.expired",
2975
- "session.cancelled"
2976
- ];
2977
- var WINDOW_NAME = "sekyro-verify";
2978
- var WINDOW_FEATURES = "width=480,height=720,noopener=false";
2979
- var EVENT_NAMES = new Set(SEKYRO_EVENTS);
2980
- function isSekyroEvent(data) {
2981
- if (data === null || typeof data !== "object") return false;
2982
- const d = data;
2983
- return d.source === "sekyro" && d.version === 1 && typeof d.sessionId === "string" && typeof d.event === "string" && EVENT_NAMES.has(d.event);
2984
- }
2985
- function open(opts) {
2986
- const origin = new URL(opts.hostedUrl).origin;
2987
- const popup = window.open(opts.hostedUrl, WINDOW_NAME, WINDOW_FEATURES);
2988
- if (!popup) return { error: "popup_blocked" };
2989
- const listener = (ev) => {
2990
- if (ev.source !== popup) return;
2991
- if (ev.origin !== origin) return;
2992
- if (!isSekyroEvent(ev.data)) return;
2993
- const { source, version, event, sessionId } = ev.data;
2994
- opts.onEvent({ source, version, event, sessionId });
2995
- };
2996
- window.addEventListener("message", listener);
2997
- return {
2998
- close() {
2999
- window.removeEventListener("message", listener);
3000
- popup.close();
3001
- }
3002
- };
3003
- }
3004
- function openHosted(hostedUrl, opts) {
3005
- if (opts.mode === "redirect") {
3006
- window.location.assign(hostedUrl);
3007
- return { close() {
3008
- } };
3009
- }
3010
- return open({ hostedUrl, onEvent: opts.onEvent ?? (() => void 0) });
3011
- }
3012
- // Annotate the CommonJS export names for ESM import in node:
3013
- 0 && (module.exports = {
3014
- DEFAULT_API_ORIGIN,
3015
- HostedApiError,
3016
- KNOWN_CODES,
3017
- SEKYRO_EVENTS,
3018
- createLivenessCapture,
3019
- createVerification,
3020
- getLivenessAssetsStatus,
3021
- hasMultipleCameras,
3022
- isKnownCode,
3023
- openHosted,
3024
- preloadLivenessAssets,
3025
- queryCameraPermission,
3026
- releaseLivenessAssets,
3027
- subscribeCameraPermission,
3028
- subscribeLivenessAssets
3029
- });
3030
- //# sourceMappingURL=index.cjs.map
1
+ "use strict";var Xt=Object.create;var ne=Object.defineProperty;var $t=Object.getOwnPropertyDescriptor;var Zt=Object.getOwnPropertyNames;var jt=Object.getPrototypeOf,Qt=Object.prototype.hasOwnProperty;var Jt=(t,e)=>{for(var n in e)ne(t,n,{get:e[n],enumerable:!0})},$e=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Zt(e))!Qt.call(t,i)&&i!==n&&ne(t,i,{get:()=>e[i],enumerable:!(r=$t(e,i))||r.enumerable});return t};var en=(t,e,n)=>(n=t!=null?Xt(jt(t)):{},$e(e||!t||!t.__esModule?ne(n,"default",{value:t,enumerable:!0}):n,t)),tn=t=>$e(ne({},"__esModule",{value:!0}),t);var kr={};Jt(kr,{DEFAULT_API_ORIGIN:()=>Ke,HostedApiError:()=>_,KNOWN_CODES:()=>He,SEKYRO_EVENTS:()=>Be,createLivenessCapture:()=>Mt,createVerification:()=>Kt,getLivenessAssetsStatus:()=>wt,hasMultipleCameras:()=>Dt,isKnownCode:()=>Pt,openHosted:()=>Bt,preloadLivenessAssets:()=>St,queryCameraPermission:()=>At,releaseLivenessAssets:()=>Et,subscribeCameraPermission:()=>Ot,subscribeLivenessAssets:()=>_t});module.exports=tn(kr);function Ze(t,e){return{video:{width:{ideal:1280,max:1280},height:{ideal:720,max:720},facingMode:e,frameRate:{ideal:24,max:30}},audio:!1}}function N(){return typeof window>"u"||typeof navigator>"u"?!1:window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(String(navigator.userAgent??""))}var nn=["video/mp4;codecs=avc1.42E01E,mp4a.40.2","video/mp4;codecs=avc1.42E01E","video/mp4","video/webm;codecs=vp9,opus","video/webm;codecs=vp9","video/webm;codecs=vp8,opus","video/webm;codecs=vp8","video/webm"];function je(){let t=globalThis.MediaRecorder;return!t||typeof t.isTypeSupported!="function"?"":nn.find(e=>t.isTypeSupported(e))??""}var Qe="video/webm";function Je(t){if(t instanceof TypeError)return"insecure";switch(t?.name??""){case"NotAllowedError":case"PermissionDeniedError":return"permission";case"NotFoundError":case"DevicesNotFoundError":return"notfound";case"NotReadableError":case"TrackStartError":return"inuse";case"OverconstrainedError":case"ConstraintNotSatisfiedError":return"overconstrained";default:return"generic"}}function et(){let t=globalThis;if(typeof t.window<"u"&&t.window.isSecureContext===!1)return"INSECURE_CONTEXT";let e=t.navigator?.mediaDevices;return!e||typeof e.getUserMedia!="function"?"UNSUPPORTED":"OK"}function tt(){let t=globalThis.MediaRecorder;return typeof t<"u"&&typeof t.isTypeSupported=="function"}var Te=8*1024*1024;function re(t){return t.size>Te}var nt="0.1.0-rc.7";var rt="sekyro.did",it;function st(){let t=globalThis.crypto;try{if(typeof t?.randomUUID=="function")return t.randomUUID()}catch{}try{if(typeof t?.getRandomValues=="function"){let e=t.getRandomValues(new Uint8Array(16));return Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}}catch{}}function rn(){try{let t=localStorage.getItem(rt);if(t)return t;let e=st();return e!==void 0&&localStorage.setItem(rt,e),e}catch{return it??(it=st()),it}}async function sn(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,n=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),r=await t.digest("SHA-256",new TextEncoder().encode(n));return Array.from(new Uint8Array(r),i=>i.toString(16).padStart(2,"0")).join("").slice(0,32)}function on(t){let e=new TextEncoder().encode(t),n="";for(let r of e)n+=String.fromCharCode(r);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function an(t){let e,n;return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(r){r&&(e=r.slice(0,128))},async deviceHeader(){try{n??(n=sn().catch(()=>""));let r=[];navigator.webdriver&&r.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&r.push("headless");let i=await n,s=rn(),o={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...s?[{kind:"web_local",value:s.slice(0,128)}]:[],...i?[{kind:"web_fp",value:i}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...e?{cameraLabel:e}:{},...r.length?{signals:r}:{}};return on(JSON.stringify(o))}catch{return}}}}var ke=Symbol.for("sekyro.web.clientContext"),Re=globalThis,ie=Re[ke]??(Re[ke]=an({sdk:`@sekyro/web@${nt}`}));function ot(t){try{let e=t.getVideoTracks?.()[0];e&&ie.noteCameraLabel(e.label)}catch{}}var cn=2500,un=1e3,ln=1500,at=25e5,A=class extends Error{constructor(e,n){super(n??e),this.kind=e}},se=class{constructor(){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.settled=!1}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.hardStopTimer=null,this.graceTimer=null}record(e,n){if(this.recorder&&!this.settled)return Promise.reject(new A("generic","record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time"));this.recorder=null,this.clearTimers(),this.chunks=[],this.bytes=0,this.settled=!1,this.stream=e;let r=je();return new Promise((i,s)=>{let o;try{o=new MediaRecorder(e,r?{mimeType:r,videoBitsPerSecond:at}:{videoBitsPerSecond:at})}catch{try{o=new MediaRecorder(e)}catch{s(new A("unsupported"));return}}this.recorder=o;let a=l=>{this.settled||(this.settled=!0,this.clearTimers(),l())},c=()=>a(()=>{let l=o.mimeType||r||Qe,u=new Blob(this.chunks,{type:l});if(re(u)){s(new A("cliptoolarge"));return}i({blob:u,mimeType:l})});o.ondataavailable=l=>{l.data&&l.data.size&&(this.chunks.push(l.data),this.bytes+=l.data.size,this.bytes>Te&&a(()=>{try{o.state!=="inactive"&&o.stop()}catch{}s(new A("cliptoolarge"))}))},o.onstop=c,o.onerror=()=>a(()=>s(new A("generic")));try{o.start(un)}catch{a(()=>s(new A("generic")));return}this.hardStopTimer=setTimeout(()=>{if(this.settled||n?.(),o.state!=="inactive"){try{o.stop()}catch{c()}this.graceTimer=setTimeout(c,ln)}else c()},cn)})}stop(e){this.clearTimers();let n=this.recorder;if(n&&n.state!=="inactive")try{n.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(i=>i.stop()),this.stream=null}};function ct(t,e,n=.92){return new Promise((r,i)=>{let s=t.videoWidth,o=t.videoHeight;if(!s||!o){i(new Error("video-not-ready"));return}let a=e.getContext("2d");if(!a){i(new Error("no-2d-context"));return}e.width=s,e.height=o,a.scale(-1,1),a.drawImage(t,-s,0),e.toBlob(c=>c?r(c):i(new Error("empty-keyframe")),"image/jpeg",n)})}var ut=1e4,oe=class t{constructor(e,n){this.tier="blaze";this.inner=e,n!==void 0&&(this.fallbackReason=n)}static async create(e,n){let r=await import("@mediapipe/tasks-vision"),i=await r.FilesetResolver.forVisionTasks(e),s=await r.FaceDetector.createFromOptions(i,{baseOptions:{modelAssetPath:`${e}/blaze_face_short_range.tflite`,delegate:"CPU"},runningMode:"IMAGE"});return new t(s,n)}async detect(e,n,r){let i;try{i=this.inner.detect(e).detections}catch{return null}let s=dn(i);if(s?.boundingBox===void 0)return null;let o=W(e),a=pn(s.keypoints,o),c={box:{x:s.boundingBox.originX,y:s.boundingBox.originY,width:s.boundingBox.width,height:s.boundingBox.height},...a!==void 0?{eyes:a}:{},score:s.categories[0]?.score??0};return ae(c,e,n,r)}destroy(){try{this.inner.close()}catch{}}};function dn(t){let e,n=-1;for(let r of t){let i=r.categories[0]?.score??0;i>n&&(e=r,n=i)}return e}function pn(t,e){let n=t?.[0],r=t?.[1];if(n===void 0||r===void 0)return;let i=a=>({x:a.x*e.width,y:a.y*e.height}),[s,o]=[i(n),i(r)];return s.x<=o.x?{left:s,right:o}:{left:o,right:s}}function mn(){if(typeof OffscreenCanvas=="function")return new OffscreenCanvas(2,2);let t=document.createElement("canvas");return t.width=2,t.height=2,t}async function lt(){let t=globalThis.FaceDetector;if(typeof t!="function")return{ok:!1,reason:"unsupported"};try{let e=new t({fastMode:!0,maxDetectedFaces:1});return await e.detect(mn()),{ok:!0,instance:e}}catch(e){return{ok:!1,reason:`smoke_failed:${e instanceof Error?e.message:String(e)}`}}}var ce=class{constructor(e,n){this.tier="native";this.inner=e,n!==void 0&&(this.fallbackReason=n)}async detect(e,n,r){let i;try{i=await this.inner.detect(e)}catch{return null}let s=i[0];if(s===void 0)return null;let o=fn(s.landmarks),a={box:{x:s.boundingBox.x,y:s.boundingBox.y,width:s.boundingBox.width,height:s.boundingBox.height},...o!==void 0?{eyes:o}:{},score:1};return ae(a,e,n,r)}destroy(){}};function fn(t){if(t===void 0)return;let e=t.filter(i=>i.type==="eye").map(i=>i.locations[0]).filter(i=>i!==void 0),[n,r]=e;if(!(n===void 0||r===void 0))return n.x<=r.x?{left:n,right:r}:{left:r,right:n}}var Me="/models-v3",hn=["native","blaze"],G=class extends Error{constructor(e){super(`no detector tier available (${e})`),this.name="DetectorLadderError",this.fallbackReason=e}};function W(t){let e=t;if(typeof e.videoWidth=="number"&&e.videoWidth>0)return{width:e.videoWidth,height:e.videoHeight??0};if(typeof e.naturalWidth=="number"&&e.naturalWidth>0)return{width:e.naturalWidth,height:e.naturalHeight??0};let n=typeof e.width=="number"?e.width:0,r=typeof e.height=="number"?e.height:0;return{width:n,height:r}}function ae(t,e,n,r){let i=W(e),s=i.width>0?n/i.width:1,o=i.height>0?r/i.height:1,a=c=>({x:c.x*s,y:c.y*o});return{box:{x:t.box.x*s,y:t.box.y*o,width:t.box.width*s,height:t.box.height*o},...t.eyes!==void 0?{eyes:{left:a(t.eyes.left),right:a(t.eyes.right)}}:{},score:t.score}}function yn(t){return t instanceof Error?t.message:String(t)}async function R(t){let e=t.preferred??hn,n=[];for(let r of e){if(r==="native"){let i=await lt();if(i.ok)return new ce(i.instance,xe(n));n.push(`native:${i.reason}`);continue}try{return await vn(oe.create(t.v3AssetBaseUrl??Me,xe(n)),t.blazeInitTimeoutMs??ut)}catch(i){n.push(i instanceof ue?"blaze:blaze_init_timeout":`blaze:${yn(i)}`)}}throw new G(xe(n)??"no_tier_available")}function xe(t){return t.length>0?t.join("; "):void 0}var ue=class extends Error{};function vn(t,e){return new Promise((n,r)=>{let i=setTimeout(()=>{r(new ue(`init exceeded ${e}ms`)),t.then(s=>s.destroy(),()=>{})},e);t.then(s=>{clearTimeout(i),n(s)},s=>{clearTimeout(i),r(s)})})}var L=1;function dt(){return typeof OffscreenCanvas=="function"&&typeof createImageBitmap=="function"&&typeof Worker=="function"}function gn(t,e={}){let n=e.createDetector??R,r=null;t.onmessage=i=>{let s=i.data;if(s.v!==L){s.bitmap?.close?.();return}if(s.type==="init"){n(s.options).then(o=>{r=o;let a={v:L,type:"ready",tier:o.tier,...o.fallbackReason!==void 0?{fallbackReason:o.fallbackReason}:{}};t.postMessage(a)});return}if(s.type==="detect"){let o=a=>{let c={v:L,type:"result",id:s.id,observation:a};t.postMessage(c),s.bitmap.close?.()};if(r===null){o(null);return}r.detect(s.bitmap,s.streamWidth,s.streamHeight).then(o,()=>o(null))}}}typeof self<"u"&&typeof self.importScripts=="function"&&gn(self);var le=class t{constructor(e,n){this.pending=new Map;this.nextId=1;this.worker=e,this.tier=n.tier,n.fallbackReason!==void 0&&(this.fallbackReason=n.fallbackReason),e.addEventListener("message",r=>{let i=r.data;if(i.v!==L||i.type!=="result")return;let s=this.pending.get(i.id);this.pending.delete(i.id),s?.(i.observation)})}static create(e,n,r=1e4){return new Promise((i,s)=>{let o=setTimeout(()=>{e.removeEventListener("message",a),e.terminate(),s(new Error(`worker detector not ready within ${r}ms`))},r),a=l=>{let u=l.data;u.v!==L||u.type!=="ready"||(clearTimeout(o),e.removeEventListener("message",a),i(new t(e,u)))};e.addEventListener("message",a);let c={v:L,type:"init",options:n};e.postMessage(c)})}async detect(e,n,r){let i;try{typeof ImageBitmap<"u"&&e instanceof ImageBitmap?i=e:typeof createImageBitmap=="function"?i=await createImageBitmap(e):i=e}catch{return null}let s=this.nextId;return this.nextId+=1,new Promise(o=>{this.pending.set(s,o);let a={v:L,type:"detect",id:s,bitmap:i,streamWidth:n,streamHeight:r};this.worker.postMessage(a,[i])})}destroy(){for(let e of this.pending.values())e(null);this.pending.clear(),this.worker.terminate()}};var bn=Object.freeze({LOW:Object.freeze({cadenceHz:5,inputWidth:128,animations:"reduced"}),MID:Object.freeze({cadenceHz:8,inputWidth:160,animations:"full"}),HIGH:Object.freeze({cadenceHz:10,inputWidth:192,animations:"full"})}),Sn=new Uint8Array([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,15,253,98,11]);function pt(){let t=typeof navigator>"u"?void 0:navigator,e=!1;try{e=typeof WebAssembly<"u"&&WebAssembly.validate(Sn)}catch{e=!1}return{cores:t?.hardwareConcurrency??2,memGB:t?.deviceMemory??null,simd:e}}function mt(t){let e=t.memGB??4;return t.cores<4||e<3?"LOW":t.cores>=8&&e>=6?"HIGH":"MID"}var Ie=["LOW","MID","HIGH"],de=class{constructor(e){this.samples=[];this.adjusted=!1;this.current=e}get deviceClass(){return this.current}get profile(){return bn[this.current]}record(e){if(this.adjusted||this.samples.length>=10)return this.current;if(this.samples.push(e),this.samples.length<10)return this.current;this.adjusted=!0;let n=this.samples.reduce((r,i)=>r+i,0)/this.samples.length;if(n>70)this.current="LOW";else if(n<25){let r=Ie.indexOf(this.current);this.current=Ie[Math.min(Ie.length-1,r+1)]??this.current}return this.current}};var pe=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let n=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),n()}))};n();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((n,r)=>n+r,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var me=[100,190],wn=64;function ft(t,e){return .299*(t[e]??0)+.587*(t[e+1]??0)+.114*(t[e+2]??0)}function Ae(t){let{data:e,width:n,height:r}=t,i=n*r;if(i===0)return 0;let s=0;for(let o=0;o<i;o+=1)s+=ft(e,o*4);return s/i}function Oe(t){let{data:e,width:n,height:r}=t;if(n<3||r<3)return 0;let i=new Float32Array(n*r);for(let u=0;u<i.length;u+=1)i[u]=ft(e,u*4);let s=0,o=0,a=0;for(let u=1;u<r-1;u+=1)for(let p=1;p<n-1;p+=1){let f=u*n+p,v=(i[f-n]??0)+(i[f-1]??0)+(i[f+1]??0)+(i[f+n]??0)-4*(i[f]??0);s+=v,o+=v*v,a+=1}if(a===0)return 0;let c=s/a,l=o/a-c*c;return Math.min(1,Math.max(0,l)/180)}function ht(t){let e=Ae(t),[n,r]=me,i=e<n?n-e:e>r?e-r:0;return Math.max(0,1-i/wn)}var _n=Object.freeze({Q_GOOD:.6,RISE_PER_S:.9,FALL_PER_S:.25,CENTER_FALLOFF_IOD_MULTIPLE:1.35,BOX_EYE_OFFSET_FACTOR:.12,IOD_BOX_PROXY_FACTOR:.42,SIZE_IDEAL_MIN:.12,SIZE_IDEAL_MAX:.3,SIZE_HARD_MIN:.08,SIZE_HARD_MAX:.45,ROLL_MAX_DEG:25,MOTION_VELOCITY_IOD_PER_S:.5,MOTION_TAU_S:.4,MOTION_DEADBAND_IOD_PER_S:.1,READY_WINDOW_MS:500,GUIDE_SIZE:.6,GUIDE_CENTERING:.6,GUIDE_POSE:.6,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,GUIDE_MOTION:.5}),U=t=>Math.min(1,Math.max(0,t)),fe=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={..._n,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:n,quality:r,timestampMs:i}=e,s=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let o={presence:0,centering:0,size:0,pose:0,sharpness:U(r.sharpness),exposure:U(r.exposure),motion:1};if(n!==null){o.presence=1;let u=this.geometryOf(n,e);o.centering=u.centering,o.size=u.size,o.pose=u.pose,o.motion=this.motionOf(u.center,u.iod,i)}else this.lastCenter=null,this.velocityEma=0;let a=Math.min(o.presence,o.centering,o.size,o.pose,o.sharpness,o.exposure,o.motion);this.p=U(this.p+(a>=this.t.Q_GOOD?this.t.RISE_PER_S*a:-this.t.FALL_PER_S*(1-a))*s),this.qWindow.push({at:i,q:a}),this.qWindow=this.qWindow.filter(u=>u.at>=i-this.t.READY_WINDOW_MS);let c=this.qWindow.map(u=>u.q);if(c.length>=3){let u=Math.min(...c),p=c.indexOf(u);c=c.filter((f,v)=>v!==p)}let l=this.p>=1&&c.every(u=>u>=this.t.Q_GOOD);return{at:i,q:a,p:this.p,factors:o,guidanceKey:this.guidanceOf(o,r,a),ready:l,accepted:a>=this.t.Q_GOOD}}geometryOf(e,n){let{box:r,eyes:i}=e,s={x:n.frameWidth/2,y:n.frameHeight/2},o=Math.min(n.frameWidth,n.frameHeight),a=i!==void 0?{x:(i.left.x+i.right.x)/2,y:(i.left.y+i.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},c=i!==void 0?Math.hypot(i.right.x-i.left.x,i.right.y-i.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,l=Math.hypot(a.x-s.x,a.y-s.y),u=c<=0?0:1-U(l/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*c)),p=o>0?c/o:0;this.lastSizeDirection=p<this.t.SIZE_IDEAL_MIN?"far":p>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;p<this.t.SIZE_HARD_MIN||p>this.t.SIZE_HARD_MAX?f=0:p<this.t.SIZE_IDEAL_MIN?f=(p-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):p>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-p)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let v=1;if(i!==void 0){let y=Math.abs(Math.atan2(i.right.y-i.left.y,i.right.x-i.left.x))*180/Math.PI;v=1-U(y/this.t.ROLL_MAX_DEG)}return{center:a,iod:c,centering:u,size:f,pose:v}}motionOf(e,n,r){let i=this.lastCenter;if(this.lastCenter={...e,at:r},i===null||n<=0)return 1;let s=(r-i.at)/1e3;if(s<=0)return 1;let o=Math.hypot(e.x-i.x,e.y-i.y)/n/s;o<=this.t.MOTION_DEADBAND_IOD_PER_S&&(o=0);let a=1-Math.exp(-s/this.t.MOTION_TAU_S);return this.velocityEma=a*o+(1-a)*this.velocityEma,1-U(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,n,r){if(e.presence<=0)return"fcv3.no_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(n);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(r<this.t.Q_GOOD){let i=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(n)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],s=i[0];for(let o of i)e[o[0]]<e[s[0]]&&(s=o);return s[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let n=(me[0]+me[1])/2;return e.meanLuma<n?"fcv3.more_light":"fcv3.too_bright"}};var De=4,En=600,yt={sharpness:1,exposure:1,meanLuma:128},he=class{constructor(e){this.handlers=new Map;this.stateValue="idle";this.attempt=0;this.stream=null;this.detector=null;this.scheduler=null;this.gate=null;this.profiler=null;this.lastGuidanceKey=null;this.positioningStartedAt=0;this.cameraRequestedAt=null;this.cameraReadyAt=null;this.faceAcquiredAt=null;this.captureCompleteAt=null;this.fired=!1;this.carriedDegrade=0;this.carriedMeans=[];this.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,n){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(n),()=>r?.delete(n)}emit(e,n){for(let r of[...this.handlers.get(e)??[]])r(n)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:n}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.setState("preflight");let r=et();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported");return}this.setState("acquiring");let i=n.getUserMedia??(c=>navigator.mediaDevices.getUserMedia(c)),s;this.cameraRequestedAt=this.now();try{s=await i(Ze(N(),this.facing))}catch(c){if(e!==this.attempt)return;this.fail(Je(c));return}if(ot(s),e!==this.attempt){for(let c of s.getTracks())c.stop();return}if(this.stream=s,n.video.srcObject=s,await n.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let c={...n.v3AssetBaseUrl!==void 0?{v3AssetBaseUrl:n.v3AssetBaseUrl}:{}},l=n.createDetector??(n.createWorker!==void 0&&dt()?async()=>{try{return await le.create(n.createWorker(),c)}catch{return R(c)}}:()=>R(c)),u;try{u=await l()}catch(p){e===this.attempt&&this.fail("models",p instanceof G?p.fallbackReason:Tn(p));return}if(e!==this.attempt){u.destroy();return}this.detector=u,this.options.telemetry?.({type:"detector",tier:u.tier,...u.fallbackReason!==void 0?{fallbackReason:u.fallbackReason}:{}})}let o=pt(),a=n.deviceClass??mt(o);this.profiler=new de(a),this.options.telemetry?.({type:"profile",staticClass:a,activeClass:this.profiler.deviceClass,simd:o.simd}),this.gate=new fe(n.thresholds??{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let n=this.profiler;if(n===null)return;if(this.scheduler!==null){let i=this.scheduler.stats();this.carriedDegrade+=i.degradeCount,i.meanDetectMs>0&&this.carriedMeans.push(i.meanDetectMs),this.scheduler.stop()}let r=new pe({cadenceHz:n.profile.cadenceHz,video:this.options.video,...this.options.now!==void 0?{now:this.options.now}:{},run:()=>this.detectTick(e)});this.scheduler=r,r.start()}async detectTick(e){let{detector:n,gate:r,profiler:i}=this,s=this.options.video;if(e!==this.attempt||n===null||r===null||i===null||this.fired||s.videoWidth===0)return;let o=i.deviceClass,a=this.now(),c=this.options.makeSnapshot?.(s,i.profile.inputWidth)??this.defaultSnapshot(s,i.profile.inputWidth),l=null;try{l=await n.detect(c,s.videoWidth,s.videoHeight)}catch{l=null}if(e!==this.attempt||this.fired)return;i.record(this.now()-a),i.deviceClass!==o&&this.startScheduler(e);let u=l===null?yt:this.options.measureQuality?.(s,l.box)??this.defaultQuality(s,l.box),p=r.tick({timestampMs:this.now(),observation:l,quality:u,frameWidth:s.videoWidth,frameHeight:s.videoHeight});p.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=p.at),this.emit("checks",{engine:"v3",progress:p.p,q:p.q,factors:p.factors,attempt:e}),p.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=p.guidanceKey,this.emit("guidance",{key:p.guidanceKey})),p.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=p.at,this.fire(e))}async fire(e){let{options:n}=this,r=this.scheduler;r?.stop();let i=r?.stats()??{degradeCount:0,meanDetectMs:0},s=[...this.carriedMeans,...i.meanDetectMs>0?[i.meanDetectMs]:[]];n.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+i.degradeCount,meanDetectMs:s.length===0?0:s.reduce((y,g)=>y+g,0)/s.length});let o=n.mode??"clip",a=this.collectKeyframes(e);if(o==="photo"){let y=await a;if(e!==this.attempt)return;if(y===null){this.fail("generic");return}this.finishCapture({keyframe:y.blob,previewDataUrl:y.previewDataUrl});return}this.setState("recording");let c=n.createRecorder?.()??new se,l=this.stream;if(l===null){this.fail("generic");return}let u=null;a.then(y=>{u=y},()=>{});let p=()=>{e===this.attempt&&u!==null&&this.emit("frozen",{previewDataUrl:u.previewDataUrl})},f,v;try{[f,v]=await Promise.all([c.record(l,p),a])}catch(y){if(e!==this.attempt)return;let g=y.kind;this.fail(g==="cliptoolarge"?"cliptoolarge":"recorder");return}if(e===this.attempt){if(re(f.blob)){this.fail("cliptoolarge");return}if(v===null){this.fail("generic");return}this.finishCapture({clip:f.blob,clipMimeType:f.mimeType,keyframe:v.blob,previewDataUrl:v.previewDataUrl})}}async collectKeyframes(e){let n=this.options.captureKeyframe??(s=>this.defaultKeyframe(s)),r=En/(De-1),i=null;for(let s=0;s<De;s+=1){if(e!==this.attempt)return i;try{let o=await n(this.options.video);(i===null||o.sharpness>i.sharpness)&&(i=o)}catch{}s<De-1&&await Cn(r)}return i}finishCapture(e){this.stopTracks(),this.setState("captured");let n=this.captureTiming();this.emit("artifacts",n===void 0?e:{...e,timing:n})}captureTiming(){let e=(o,a)=>o!==null&&a!==null?Math.max(0,Math.round(a-o)):void 0,n=e(this.cameraRequestedAt,this.cameraReadyAt),r=e(this.cameraReadyAt,this.faceAcquiredAt),i=e(this.faceAcquiredAt,this.captureCompleteAt),s={...n!==void 0?{cameraReadyMs:n}:{},...r!==void 0?{faceAcquireMs:r}:{},...i!==void 0?{captureMs:i}:{}};return Object.keys(s).length>0?s:void 0}async defaultKeyframe(e){let n=document.createElement("canvas"),r=await ct(e,n),i=n.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:i,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,n){try{let r=this.snapshotCanvas??document.createElement("canvas"),i=n/Math.max(1,e.videoWidth),s=Math.max(1,Math.round(e.videoWidth*i)),o=Math.max(1,Math.round(e.videoHeight*i)),a=r.getContext("2d");return a===null?e:(r.width!==s&&(r.width=s),r.height!==o&&(r.height=o),a.drawImage(e,0,0,s,o),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,n){let r=vt(e,n,96);return r===null?yt:{sharpness:Oe(r),exposure:ht(r),meanLuma:Ae(r)}}centerSharpness(e){let n=W(e),r=vt(e,{x:n.width*.25,y:n.height*.25,width:n.width*.5,height:n.height*.5},96);return r===null?0:Oe(r)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.gate=null,this.stopTracks()}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,n){this.scheduler?.stop(),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,...n!==void 0?{fallbackReason:n}:{}}),this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported"})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}};function Cn(t){return new Promise(e=>setTimeout(e,t))}function Tn(t){return t instanceof Error?t.message:String(t)}function vt(t,e,n){try{let r=document.createElement("canvas"),i=n/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*i)),r.height=Math.max(1,Math.round(e.height*i));let s=r.getContext("2d");return s===null?null:(s.drawImage(t,e.x,e.y,e.width,e.height,0,0,r.width,r.height),s.getImageData(0,0,r.width,r.height))}catch{return null}}function ye(){let t=new Map;return{on(e,n){let r=t.get(e);r===void 0&&(r=new Set,t.set(e,r));let i=n;return r.add(i),()=>{r?.delete(i)}},emit(e,n){let r=t.get(e);if(r!==void 0)for(let i of[...r])i(n)},clear(){t.clear()}}}var kn=12e4,gt=13e4,Rn=3e3,xn=1200,ve=Symbol.for("@sekyro/web.preload.v1");function be(){let t=globalThis;return t[ve]??(t[ve]=new Map),t[ve]}function q(t){let e=(t??Me).replace(/\/+$/,"");return e===""?"/":e}function bt(t){let e=be(),n=e.get(t);return n===void 0&&(n={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},e.set(t,n)),n}function ge(t,e){if(t.status!==e){t.status=e;for(let n of[...t.listeners])n(e)}}var Mn=t=>R({preferred:["blaze"],v3AssetBaseUrl:t,blazeInitTimeoutMs:kn}),In=Mn;function An(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function On(){return navigator.connection?.saveData===!0}function Dn(t){let e=window;if(typeof e.requestIdleCallback=="function"){let r=e.requestIdleCallback(t,{timeout:Rn});return()=>e.cancelIdleCallback?.(r)}let n=setTimeout(t,xn);return()=>clearTimeout(n)}function Pn(t,e){let n,r=new Promise(a=>{n=a}),i=!1,s=()=>{},o={promise:r,settle:a=>{i||(i=!0,s(),t.scheduled===o&&(t.scheduled=null),n(a))}};return t.scheduled=o,s=Dn(()=>{i||o.settle(Pe(t,e))}),r}function Pe(t,e){if((t.status==="loading"||t.status==="ready")&&t.promise!==null)return t.promise;ge(t,"loading");let n=new Promise(a=>a(In(e)));t.detectorPromise=n;let r,i=new Promise((a,c)=>{r=setTimeout(()=>{n.then(l=>l.destroy(),()=>{}),c(new Error(`detector preload exceeded ${gt} ms`))},gt)}),o=Promise.race([n,i]).then(a=>t.detectorPromise!==n?(a.destroy(),t.status):(t.detector=a,ge(t,"ready"),"ready"),a=>(t.detectorPromise===n&&(t.detectorPromise=null,t.detector=null,ge(t,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",a)),t.status)).finally(()=>clearTimeout(r));return t.promise=o,t.scheduled?.settle(o),o}function St(t={}){if(!An())return Promise.resolve("idle");let e=q(t.assetBaseUrl),n=bt(e);return t.respectSaveData===!0&&On()?Promise.resolve(n.status):(n.status==="loading"||n.status==="ready")&&n.promise!==null?n.promise:t.idle===!0?n.scheduled?.promise??Pn(n,e):Pe(n,e)}function wt(t){return be().get(q(t))?.status??"idle"}function _t(t,e){let n=bt(q(e));return n.listeners.add(t),()=>{n.listeners.delete(t)}}function Et(t){let e=be().get(q(t));e!==void 0&&(e.scheduled?.settle("idle"),e.detector?.destroy(),e.detector=null,e.detectorPromise=null,e.promise=null,ge(e,"idle"))}function Ln(t){return{get tier(){return t.tier},get fallbackReason(){return t.fallbackReason},detect:(...e)=>t.detect(...e),destroy:()=>{}}}function Ct(t){let e=q(t),n=be().get(e);if(!(n===void 0||n.detector===null&&n.detectorPromise===null&&n.scheduled===null))return async()=>{n.scheduled!==null&&Pe(n,e);let r=n.promise;for(;n.detector===null&&r!==null&&(await r,n.promise!==r);)r=n.promise;return n.detector!==null?Ln(n.detector):R({v3AssetBaseUrl:e})}}function Tt(){if(typeof navigator>"u"||!("wakeLock"in navigator))return null;let t=navigator.wakeLock;return typeof t?.request=="function"?t:null}function kt(){return typeof document>"u"||document.visibilityState==="visible"}function Rt(t){try{t.release().catch(()=>{})}catch{}}function xt(t={}){if(t.enabled===!1)return{setActive:()=>{}};let e=!1,n=null,r=!1,i=!1,s=()=>{if(!e||r||n!==null&&!n.released)return;let c=Tt();if(c===null||!kt())return;let l;try{l=c.request("screen")}catch{return}r=!0,l.then(u=>{if(r=!1,!e){Rt(u);return}n=u,u.addEventListener?.("release",()=>{n===u&&(n=null)})},()=>{r=!1})},o=()=>{kt()&&s()},a=c=>{typeof document>"u"||c===i||(i=c,c?document.addEventListener("visibilitychange",o):document.removeEventListener("visibilitychange",o))};return{setActive:c=>{if(e=c,c){if(Tt()===null)return;a(!0),s();return}if(a(!1),n!==null){let l=n;n=null,Rt(l)}}}}function Vn(t){switch(t){case"fcv3.no_face":case"fcv3.center_face":case"fcv3.straighten":return"center";case"fcv3.come_closer":return"closer";case"fcv3.move_back":return"farther";case"fcv3.more_light":case"fcv3.too_bright":return"light";case"fcv3.hold_still":case"fcv3.steady_camera":return"still";default:return null}}function Hn(t){switch(t){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";case"idle":case"recording":case"captured":case"error":return t;default:{let e=t;throw new Error(`mapEngineState: unhandled state ${e}`)}}}function Fn(t){switch(t){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return t;case"overconstrained":case"generic":case"models":case"cliptoolarge":case"recorder":return"generic";default:{let e=t;throw new Error(`mapErrorKind: unhandled kind ${e}`)}}}function Le(t,e={}){let n=e.now??(()=>performance.now()),r=ye(),i=!tt(),s=e.engineOptions,o=s?.createDetector===void 0&&s?.createWorker===void 0?{createDetector:()=>{let m=Ct(t.assetBaseUrl);return m!==void 0?m():R(t.assetBaseUrl!==void 0?{v3AssetBaseUrl:t.assetBaseUrl}:{})}}:{},a={video:t.video,mode:i?"photo":"clip",...t.facing!==void 0?{facingMode:t.facing}:{},...t.assetBaseUrl!==void 0?{v3AssetBaseUrl:t.assetBaseUrl}:{},...e.engineOptions??{},...o},c=e.createEngine?.(a)??new he(a),l="idle",u=null,p=0,f=!1,v="full",y=null,g=null,C=0,D=0,V=()=>{t.video.videoWidth>0&&t.video.videoHeight>0&&(C=t.video.videoWidth,D=t.video.videoHeight)},K=xt({enabled:t.keepScreenAwake!==!1}),P=m=>{l=m,K.setActive(m==="starting"||m==="gating"||m==="recording"),r.emit("state",m)},H=()=>r.emit("gate",{progress:p,hint:u,faceDetected:f}),B=()=>{let m=c.animations??"full";m!==v&&(v=m,r.emit("profile",{animations:v}))},J=[c.on("statechange",({state:m})=>{let E=Hn(m);E==="starting"&&l!=="starting"&&(u=null,p=0,f=!1,y=null,g=null,C=0,D=0),P(E),B(),E==="recording"&&(V(),y=n(),u="hold",p=1,H())}),c.on("checks",m=>{V(),p=m.progress,f=m.factors.presence>0,H(),B()}),c.on("guidance",({key:m})=>{u=Vn(m),H()}),c.on("frozen",({previewDataUrl:m})=>{g=n(),r.emit("frozen",{previewDataUrl:m})}),c.on("artifacts",m=>{let E=y!==null&&g!==null?Math.max(0,Math.round(g-y)):void 0;r.emit("captured",{keyframe:m.keyframe,...m.clip!==void 0?{clip:m.clip}:{},...m.clipMimeType!==void 0?{clipMime:m.clipMimeType}:{},width:t.video.videoWidth||C,height:t.video.videoHeight||D,...E!==void 0?{clipMs:E}:{},captureChannel:N()?"mobile":"desktop",...i?{degraded:"NO_RECORDER"}:{},engine:"v3",...m.timing?.cameraReadyMs!==void 0?{cameraReadyMs:m.timing.cameraReadyMs}:{},...m.timing?.faceAcquireMs!==void 0?{faceAcquireMs:m.timing.faceAcquireMs}:{},...m.timing?.captureMs!==void 0?{captureMs:m.timing.captureMs}:{}})}),c.on("error",({kind:m,retryable:E})=>{r.emit("error",{kind:Fn(m),retryable:E})})];return{handle:{get state(){return l},on:(m,E)=>r.on(m,E),start:m=>c.start(m?.facing!==void 0?{facingMode:m.facing}:{}),retry:()=>c.retry(),switchCamera:()=>c.switchCamera(),destroy:()=>{for(let m of J)m();K.setActive(!1),c.destroy(),r.clear()}},setFlowState:m=>{l!==m&&P(m)}}}function Mt(t){return Le(t).handle}async function It(){try{return typeof navigator>"u"||typeof navigator.permissions?.query!="function"?null:await navigator.permissions.query({name:"camera"})}catch{return null}}function Ve(t){return t==="granted"||t==="prompt"||t==="denied"?t:"unknown"}async function At(){let t=await It();return t===null?"unknown":Ve(t.state)}function Ot(t){let e=!1,n=null,r=()=>{!e&&n!==null&&t(Ve(n.state))};return It().then(i=>{e||(n=i,t(i===null?"unknown":Ve(i.state)),i?.addEventListener?.("change",r))}),()=>{e=!0,n?.removeEventListener?.("change",r)}}async function Dt(){if(typeof navigator>"u")return!1;let t=String(navigator.userAgent??"");if(/Android|iPhone|iPad|iPod/i.test(t)||/Macintosh/.test(t)&&(navigator.maxTouchPoints??0)>1)return!0;try{return(await navigator.mediaDevices?.enumerateDevices?.()??[]).filter(n=>n.kind==="videoinput").length>=2}catch{return!1}}var He=["session_token_invalid","session_token_required","session_token_session_mismatch","session_not_found","rate_limit_exceeded","consent_required","session_not_active","check_not_found","check_already_finalized","check_out_of_order","check_type_unsupported","force_outcome_forbidden","attestation_invalid","inference_unavailable","mobile_required","nni_locked","method_required","method_locked","document_nni_mismatch","media_content_type_not_allowed","media_too_large","media_key_invalid","media_key_forbidden","media_not_found","media_unreadable","media_session_invalid","idempotency_key_collision","idempotency_in_progress","idempotency_key_required","validation_error","internal_error","unknown_error","upload_failed","network_error","timeout"];function Pt(t){return He.includes(t)}var _=class extends Error{constructor(e){super(e.message),this.name="HostedApiError",this.status=e.status,this.code=e.code,e.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=e.retryAfterSeconds)}};var Nn=3e4,Un=9e5,Kn=200,Bn=5,Wn=400;function z(t){return(t.split(";")[0]??"").trim()}var Gn={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},Se=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let n=e.fetch;this.fetchImpl=(r,i)=>(n??globalThis.fetch).call(globalThis,r,i),this.requestTimeoutMs=e.requestTimeoutMs??Nn,this.retryAttempts=e.inProgressRetry?.attempts??Bn,this.retryDelayMs=e.inProgressRetry?.delayMs??Wn}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e}})}async selectMethod(e){let n=await this.api("POST","/hosted/method",{body:{method:e}});return this.sessionId=n.sessionId,n}async presign(e,n,r){let i=await this.ensureSessionId(),s={kind:e,contentType:z(n),contentLength:r};return this.api("POST",`/sessions/${i}/media`,{body:s})}async uploadToSpaces(e,n,r){let i;try{i=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":z(r)},body:n,signal:AbortSignal.timeout(Un)})}catch(s){throw Lt(s)}if(!i.ok){let s=(await i.text().catch(()=>"")).slice(0,Kn);throw new _({status:i.status,code:"upload_failed",message:`media upload failed (HTTP ${i.status})${s?`: ${s}`:""}`})}}async completeMedia(e){let n=await this.ensureSessionId();return this.api("POST",`/sessions/${n}/media/complete`,{body:{key:e}})}async submitCheck(e,n,r={}){let i=await this.ensureSessionId(),s={input:n,...r.forceOutcome!==void 0?{forceOutcome:r.forceOutcome}:{}};return this.api("POST",`/sessions/${i}/checks/${e}`,{body:s,...r.idempotencyKey!==void 0?{idempotencyKey:r.idempotencyKey}:{}})}async uploadAndSubmit(e,n,r,i={}){let s=z(n.contentType),o=await this.presign(n.kind,s,n.blob.size);await this.uploadToSpaces(o.uploadUrl,n.blob,s);let a=await this.completeMedia(o.key),c={...r,[Gn[e]]:a.key};return this.submitCheck(e,c,i)}async ensureSessionId(){return this.sessionId!==null?this.sessionId:(this.bootstrap??(this.bootstrap=this.getSession().finally(()=>{this.bootstrap=null})),(await this.bootstrap).sessionId)}async api(e,n,r={}){let i=`${this.apiOrigin}/api/v2${n}`,s={"x-session-token":this.sessionToken};r.body!==void 0&&(s["content-type"]="application/json"),r.idempotencyKey!==void 0&&(s["x-idempotency-key"]=r.idempotencyKey);try{let o=ie.timezone();o!==void 0&&(s["sekyro-client-timezone"]=o)}catch{}try{let o=await ie.deviceHeader();o!==void 0&&(s["sekyro-client-device"]=o)}catch{}for(let o=0;;o++){let a;try{a=await this.fetchImpl(i,{method:e,headers:s,...r.body!==void 0?{body:JSON.stringify(r.body)}:{},signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(l){throw Lt(l)}if(a.ok){let l;try{l=await a.json()}catch{throw new _({status:a.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${a.status})`})}return qn(l)}let c=await zn(a);if(c.code==="idempotency_in_progress"&&o<this.retryAttempts){this.retryDelayMs>0&&await Yn(this.retryDelayMs);continue}throw c}}};function Lt(t){if((typeof t=="object"&&t!==null?t.name:void 0)==="TimeoutError")return new _({status:0,code:"timeout",message:"request timed out"});let n=t instanceof Error?t.message:String(t);return new _({status:0,code:"network_error",message:`network request failed: ${n}`})}function qn(t){return t!==null&&typeof t=="object"&&"success"in t&&"data"in t?t.data:t}async function zn(t){let e="unknown_error",n=`request failed (HTTP ${t.status})`,r=Number.NaN;try{let o=await t.json();if(o!==null&&typeof o=="object"){let a=o;typeof a.code=="string"&&a.code.length>0&&(e=a.code),typeof a.message=="string"&&a.message.length>0&&(n=a.message),typeof a.retryAfterSeconds=="number"&&(r=a.retryAfterSeconds)}}catch{}let i=t.headers.get("retry-after"),s=i===null?Math.floor(r):Number.parseInt(i,10);return new _({status:t.status,code:e,message:n,...Number.isFinite(s)&&s>=0?{retryAfterSeconds:s}:{}})}function Yn(t){return new Promise(e=>setTimeout(e,t))}var Xn=new Set(["no_face","media_unreadable","clip_too_short","no_face_source","side_missing","unreadable","registry_unavailable","otp_mismatch","otp_expired","otp_send_failed","document_type_not_accepted","age_unverifiable","liveness_inconclusive","match_inconclusive","document_authenticity"]);function $(t){let e=t.methodChoice;return e===void 0||!e.available||e.selected!==null||O(t)?.checkType==="phone_otp"?null:e}var $n=new Set(["liveness","face_match"]);function Z(t){return t!==void 0&&(t.state==="pending"||t.state==="input_required")}function M(t){return t.status!=="created"&&t.status!=="in_progress"}function O(t){return t.steps.find(e=>Z(e))}function I(t,e){return t.steps.find(n=>n.checkType===e)}function Fe(t,e){let n=e.steps.find(i=>i.checkType==="liveness"),r=e.steps.find(i=>i.checkType==="face_match");return I(t,"face_match")?.state==="pending"&&(n?.state==="passed"||n?.state==="review")&&r!==void 0&&r.state!=="pending"&&r.state!=="skipped"}function Vt(t,e,n){let r=new Map(t.steps.map(o=>[o.checkType,o])),i=n==="liveness"&&Fe(t,e),s=e.steps.map(o=>{let a=r.get(o.checkType),c=a?.attemptsRemaining??0,l={...a??{},checkType:o.checkType,state:o.state,attemptsRemaining:o.checkType===n||o.checkType==="face_match"&&i?Math.max(0,c-1):c};return o.reason!==void 0?l.reason=o.reason:delete l.reason,o.attemptsExhausted!==void 0?l.attemptsExhausted=o.attemptsExhausted:delete l.attemptsExhausted,l});return{...t,status:e.status,outcome:e.outcome,failureReason:e.failureReason,steps:s,expiresAt:e.expiresAt}}function x(t,e){return e===void 0?{sessionId:t,status:"unavailable"}:{sessionId:t,status:"unavailable",reason:e}}function Y(t,e,n){return n===void 0?{sessionId:t,status:e}:{sessionId:t,status:e,reason:n}}function Ne(t,e){let{sessionId:n}=t;switch(t.status){case"completed":return t.outcome==="approved"?{sessionId:n,status:"approved"}:t.outcome==="review"?Y(n,"review",X(t,"review")):Y(n,"rejected",X(t,"failed"));case"failed":{let i=Y(n,"rejected",t.failureReason??X(t,"failed"));return t.failureReason==="device_cooldown"&&t.retryAfter!==void 0&&(i.retryAfter=t.retryAfter),i}case"review_pending":return Y(n,"review",X(t,"review"));case"expired":return x(n);case"created":case"in_progress":break;default:{let i=t.status;throw new Error(`mapSessionResult: unhandled status ${i}`)}}let r=t.steps.find(i=>$n.has(i.checkType)&&i.state==="input_required"&&i.reason!==void 0);if(r?.reason==="mobile_required")return x(n,"mobile_required");if(r?.reason!==void 0){let i=e.autoRetry&&Xn.has(r.reason)&&r.attemptsRemaining>0;return{sessionId:n,status:i?"retry":"rejected",reason:r.reason,attemptsRemaining:r.attemptsRemaining}}return O(t)===void 0&&t.steps.some(i=>i.state==="review")?Y(n,"review",X(t,"review")):x(n)}function X(t,e){return t.steps.find(n=>n.state===e&&n.reason!==void 0)?.reason}var Zn=["video/webm","video/mp4"],Ht="image/jpeg",jn=2,Qn=1e3,Jn=1e4,er=3,tr=10,nr=30,rr=3,ir=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),sr=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order"]),j=class extends Error{constructor(){super("verification destroyed"),this.name="FlowCancelledError"}};function or(t){let e=t.steps.findIndex(r=>r.checkType==="liveness");return e<0?!1:t.steps.slice(e+1).find(r=>Z(r))?.checkType==="face_match"}var Q=class extends Error{constructor(e){super(e),this.name="AttestationError"}};async function we(t,e,n={}){let r=t.uuid(),i=!1,s=!1,o=0,a=0;for(;;)try{return await e(t.client,r)}catch(c){if(c instanceof Q){if(s)throw c;s=!0,n.onAttestationInvalid?.(),r=t.uuid();continue}if(!(c instanceof _))throw c;if(c.code==="consent_required"&&!i){i=!0,await t.ensureConsent({force:!0}),r=t.uuid();continue}if(c.code==="attestation_invalid"&&!s){s=!0,n.onAttestationInvalid?.(),r=t.uuid();continue}if(c.code==="inference_unavailable"&&a<er){a+=1;let l=Math.min(c.retryAfterSeconds??tr,nr);t.onBusy?.({attempt:a,retryAfterSeconds:l}),await t.sleep(l*1e3),n.onAttestationInvalid?.(),r=t.uuid();continue}if(ir.has(c.code)&&o<jn){o+=1;let l=c.retryAfterSeconds!==void 0?c.retryAfterSeconds*1e3:void 0;await t.sleep(l!==void 0?Math.min(l,Jn):Qn);continue}throw c}}var ar=new Set(["passed","review","processing","skipped"]);async function Ft(t){let{artifacts:e}=t,n=e.clip,r=z(e.clipMime??"");if(e.degraded==="NO_RECORDER"||n===void 0||!Zn.includes(r))return{kind:"unavailable",reason:"no_recorder"};let i=cr(t,e.keyframe),s=ur(t,n,r,i),o=lr(t,i),a=!1,c=!1,l=!0,u=0;for(;;){if(t.isCancelled())return{kind:"cancelled"};let p=t.getView();if(M(p))return{kind:"settled"};let f=O(p)?.checkType,v=f==="liveness"&&!a?"liveness":f==="face_match"&&!c&&l?"face_match":null;if(v===null)return{kind:"settled"};if(v==="liveness"&&e.captureChannel==="desktop"&&I(p,"liveness")?.requiresMobile===!0)return{kind:"unavailable",reason:"mobile_required"};try{if(v==="liveness"){a=!0;let y=await s();if(t.isCancelled())return{kind:"cancelled"};c=Fe(p,y),t.applySubmit(y,"liveness");let g=I(t.getView(),"liveness")?.state;l=g===void 0||ar.has(g)}else{c=!0;let y=await o();if(t.isCancelled())return{kind:"cancelled"};t.applySubmit(y,"face_match")}}catch(y){if(t.isCancelled()||y instanceof j)return{kind:"cancelled"};let g=pr(y);if(g.kind!=="resync"||u>=rr)return g;u+=1,await t.refreshView()}}}function cr(t,e){let n=null,r=null,i=()=>n!==null?Promise.resolve(n):(r??(r=(async()=>{let s=await t.client.presign("image",Ht,e.size);return await t.client.uploadToSpaces(s.uploadUrl,e,Ht),n=(await t.client.completeMedia(s.key)).key,n})().finally(()=>{r=null})),r);return{ensure:i,attempt:()=>i().catch(()=>null),current:()=>n}}function ur(t,e,n,r){let i=null,s,o=null;return()=>we(t,async(a,c)=>{if(i===null||s===void 0){if(t.isCancelled())throw new j;s===void 0&&!or(t.getView())&&(s=null),t.onPhase("uploading");let[l,u]=await Promise.all([i!==null?Promise.resolve(i):(async()=>{let p=await a.presign("clip",n,e.size);return await a.uploadToSpaces(p.uploadUrl,e,n),(await a.completeMedia(p.key)).key})(),s!==void 0?Promise.resolve(s===null?null:s.imageKey):r.attempt()]);i=l,s===void 0&&(s=u===null?null:{imageKey:u})}if(o===null)try{o=await t.getAttestation()}catch(l){throw new Q(l instanceof Error?l.message:String(l))}return t.onPhase("checking"),a.submitCheck("liveness",{clipKey:i,attestation:o,captureChannel:t.artifacts.captureChannel,capture:dr(t.artifacts),...s!==null?{faceMatch:s}:{}},{idempotencyKey:c})},{onAttestationInvalid:()=>{o=null}})}function lr(t,e){return()=>we(t,async(n,r)=>{if(e.current()===null){if(t.isCancelled())throw new j;t.onPhase("uploading")}let i=await e.ensure();return t.onPhase("checking"),n.submitCheck("face_match",{imageKey:i},{idempotencyKey:r})})}function dr(t){return{...t.engine!==void 0?{engine:t.engine}:{},width:t.width,height:t.height,...t.clipMs!==void 0?{clipMs:t.clipMs}:{},...t.cameraReadyMs!==void 0?{cameraReadyMs:t.cameraReadyMs}:{},...t.faceAcquireMs!==void 0?{faceAcquireMs:t.faceAcquireMs}:{},...t.captureMs!==void 0?{captureMs:t.captureMs}:{}}}function pr(t){if(t instanceof Q)return{kind:"unavailable",reason:"attestation"};if(t instanceof _){if(t.code==="attestation_invalid")return{kind:"unavailable",reason:"attestation"};if(t.code==="method_required")return{kind:"unavailable",reason:"method_required"};if(t.code==="inference_unavailable")return{kind:"unavailable",reason:"inference_unavailable"};if(t.code==="mobile_required")return{kind:"unavailable",reason:"mobile_required"};if(sr.has(t.code))return{kind:"resync"}}return{kind:"unavailable",reason:"network"}}var mr="https://challenges.cloudflare.com/turnstile/v0/api.js";function Nt(){return window.turnstile}var _e=null;function fr(){return _e??(_e=new Promise((t,e)=>{let n=Nt();if(n){t(n);return}let r=document.createElement("script");r.src=mr,r.async=!0,r.onload=()=>{let i=Nt();i?t(i):(_e=null,e(new Error("Turnstile script loaded but exposed no API")))},r.onerror=()=>{_e=null,r.remove(),e(new Error("Turnstile script failed to load"))},document.head.appendChild(r)})),_e}function Ue(){return new Error("Turnstile challenge aborted")}async function Ut(t,e={}){let n=e.timeoutMs??3e4,r=e.signal;if(r?.aborted)throw Ue();let i=await fr();if(r?.aborted)throw Ue();let s=document.createElement("div");document.body.appendChild(s);let o,a,c;try{return await new Promise((l,u)=>{if(a=setTimeout(()=>u(new Error(`Turnstile challenge timed out (${n} ms)`)),n),r!==void 0&&(c=()=>u(Ue()),r.addEventListener("abort",c,{once:!0})),o=i.render(s,{sitekey:t,execution:"execute",appearance:"execute",callback:l,"error-callback":p=>{u(new Error(`Turnstile challenge failed${p?` (${p})`:""}`))}}),o===void 0){u(new Error("Turnstile render returned no widget id"));return}i.execute(o)})}finally{if(clearTimeout(a),r!==void 0&&c!==void 0&&r.removeEventListener("abort",c),o!==void 0)try{i.remove(o)}catch{}s.remove()}}var Ke="https://api.sekyro.ai",hr=5e3,yr=1500,vr=10;function gr(t){return new Promise(e=>setTimeout(e,t))}function br(){let t=globalThis.crypto;if(t!==void 0&&typeof t.randomUUID=="function")return t.randomUUID();let e=new Uint8Array(16);if(t!==void 0&&typeof t.getRandomValues=="function")t.getRandomValues(e);else for(let r=0;r<16;r+=1)e[r]=Math.floor(Math.random()*256);e[6]=(e[6]??0)&15|64,e[8]=(e[8]??0)&63|128;let n=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function Kt(t){return Sr(t,{})}function Sr(t,e){let n=t.apiOrigin??Ke,r=t.autoRetry??!0,i=t.rearm??"auto",s=e.client??new Se({apiOrigin:n,sessionToken:t.clientToken,...t.fetch!==void 0?{fetch:t.fetch}:{}}),o=e.sleep??gr,a=e.uuid??br,c=e.getTurnstileToken??Ut,l=ye(),u=!1,p=new AbortController,f=null,v=null,y=d=>{f=d,l.emit("view",d)},g=()=>f!==null?Promise.resolve(f):(v??(v=s.getSession().then(d=>(y(d),d)).finally(()=>{v=null})),v),C=async()=>{let d=await s.getSession();return y(d),d},D=(d,h)=>{f!==null&&y(Vt(f,d,h))},V=null,K=async d=>{let h=await g();!d&&h.consentRecorded||(await s.recordConsent(t.locale),f!==null&&y({...f,consentRecorded:!0}))},P=d=>d?.force===!0?K(!0):(V??(V=K(!1).finally(()=>{V=null})),V),H={client:s,ensureConsent:d=>P(d),sleep:o,uuid:a,onBusy:d=>{u||l.emit("busy",d)}},B=!1,J=d=>{if(d.status==="approved"||d.status==="rejected"||d.status==="review"){if(B)return;B=!0}l.emit("result",d)},Ee=async d=>{let h=f;d&&(h=await C().catch(()=>f));let S=h===null?null:$(h);return S!==null&&!u&&l.emit("method",S),S!==null},m=null,E=!1,We=!1,Ge=()=>we(H,(d,h)=>d.submitCheck("population_registry",{},{idempotencyKey:h})),qe=d=>d.nniBound===!0||I(d,"population_registry")?.nniFromDocument===!0,Wt=async()=>{try{let d=await g();if(M(d)||$(d)!==null||O(d)?.checkType!=="population_registry")return;if(!qe(d)&&I(d,"population_registry")?.nniFromDocument===void 0&&(d=await C()),!qe(d)){We=!0;return}await P(),D(await Ge(),"population_registry");let h=f===null?void 0:I(f,"population_registry");if(h?.state==="input_required"&&h.reason==="registry_unavailable"&&h.attemptsRemaining>0){if(await o(hr),u)return;D(await Ge(),"population_registry")}}catch(d){if(d instanceof _&&d.code==="method_required"){await C().catch(()=>{});return}E=!0;return}f!==null&&M(f)&&J(Ne(f,{autoRetry:r}))},ze=()=>(m??(m=Wt()),m),Gt=async()=>{let h=(await g()).turnstileSiteKey;return h===null?{sandbox:!0}:{channel:"hosted_web",siteKey:h,turnstileToken:await c(h,{signal:p.signal})}},T=null,Ye=Promise.resolve(),Ce=0,qt=async()=>{let d=await g();for(let h=0;h<vr&&!u&&!M(d)&&O(d)===void 0&&d.steps.some(S=>S.state==="processing")&&(await o(yr),!u);h+=1)d=await C();return d},zt=async(d,h,S)=>{let{capture:k}=d,w=()=>u,ee=()=>d.alive&&d.attempt===S,Xe=b=>{ee()&&k.setFlowState(b)},F=b=>{if(!w()&&(J(b),!!ee())){if(b.status==="retry"&&i==="auto"){k.handle.retry();return}k.setFlowState("done")}};if(h.degraded==="NO_RECORDER"){let b=f?.sessionId??(await g().catch(()=>null))?.sessionId??"";F(x(b,"no_recorder"));return}Xe("uploading");try{if(await ze(),w())return;let b=await g();if(!M(b)&&$(b)!==null){await Ee(!1),F(x(b.sessionId,"method_required"));return}if(!M(b)){if(O(b)?.checkType==="population_registry"){F(x(b.sessionId,We?"nni_unbound":E?"network":"registry_unavailable"));return}if(await P(),w())return;let te=await Ft({...H,artifacts:h,getAttestation:Gt,getView:()=>f??b,refreshView:C,applySubmit:D,onPhase:Xe,isCancelled:w});if(w())return;if(te.kind==="unavailable"){if(te.reason==="method_required"&&await Ee(!0),w())return;F(x(b.sessionId,te.reason));return}te.kind==="resync"&&await C(),b=await qt()}F(Ne(b,{autoRetry:r}))}catch{if(w())return;F(x(f?.sessionId??"","network"))}},Yt=(d,h)=>{let S=d.attempt;Ce>0&&d.alive&&d.capture.setFlowState("uploading"),Ce+=1,Ye=Ye.then(()=>zt(d,h,S)).finally(()=>{Ce-=1}).catch(()=>{})};return{consent:()=>P(),startRegistry:ze,methodChoice:async()=>{if(u)return null;try{let d=await g();return u?null:$(d)}catch{return null}},selectMethod:async d=>{let h=await s.selectMethod(d);u||y(h)},mobileRequired:async()=>{if(u)return!1;try{let d=await g();if(u||M(d))return!1;let h=I(d,"liveness");return Z(h)&&h?.requiresMobile===!0&&!N()}catch{return!1}},liveness:d=>{T?.capture.handle.destroy(),T!==null&&(T.alive=!1);let h=Le(d,e.capture),S={capture:h,alive:!0,attempt:0};T=S,h.handle.on("state",w=>{w==="starting"&&(S.attempt+=1)}),h.handle.on("captured",w=>{Promise.resolve().then(()=>Yt(S,w))});let k=h.handle;return{get state(){return k.state},on:(w,ee)=>k.on(w,ee),start:w=>k.start(w),retry:()=>k.retry(),switchCamera:()=>k.switchCamera(),destroy:()=>{S.alive=!1,T===S&&(T=null),k.destroy()}}},voiceClips:async()=>{if(u)return null;try{let d=await g();return u?null:d.voice??null}catch{return null}},on:(d,h)=>l.on(d,h),destroy:()=>{u=!0,p.abort(),T!==null&&(T.alive=!1,T.capture.handle.destroy(),T=null),l.clear()}}}var Be=["session.completed","session.failed","session.review_pending","session.expired","session.cancelled"],wr="sekyro-verify",_r="width=480,height=720,noopener=false",Er=new Set(Be);function Cr(t){if(t===null||typeof t!="object")return!1;let e=t;return e.source==="sekyro"&&e.version===1&&typeof e.sessionId=="string"&&typeof e.event=="string"&&Er.has(e.event)}function Tr(t){let e=new URL(t.hostedUrl).origin,n=window.open(t.hostedUrl,wr,_r);if(!n)return{error:"popup_blocked"};let r=i=>{if(i.source!==n||i.origin!==e||!Cr(i.data))return;let{source:s,version:o,event:a,sessionId:c}=i.data;t.onEvent({source:s,version:o,event:a,sessionId:c})};return window.addEventListener("message",r),{close(){window.removeEventListener("message",r),n.close()}}}function Bt(t,e){return e.mode==="redirect"?(window.location.assign(t),{close(){}}):Tr({hostedUrl:t,onEvent:e.onEvent??(()=>{})})}0&&(module.exports={DEFAULT_API_ORIGIN,HostedApiError,KNOWN_CODES,SEKYRO_EVENTS,createLivenessCapture,createVerification,getLivenessAssetsStatus,hasMultipleCameras,isKnownCode,openHosted,preloadLivenessAssets,queryCameraPermission,releaseLivenessAssets,subscribeCameraPermission,subscribeLivenessAssets});