@incodetech/core 2.0.0-alpha.1 → 2.0.0-alpha.3

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 (104) hide show
  1. package/dist/Manager-6BwbaI_H.d.ts +19 -0
  2. package/dist/StateMachine-7c1gcu94.d.ts +2 -0
  3. package/dist/addEvent-1Mi5CEiq.esm.js +16 -0
  4. package/dist/chunk-C_Yo44FK.esm.js +49 -0
  5. package/dist/email.d.ts +264 -0
  6. package/dist/email.esm.js +479 -0
  7. package/dist/endpoints-D_pUMaqA.esm.js +1701 -0
  8. package/dist/flow.d.ts +578 -0
  9. package/dist/flow.esm.js +628 -0
  10. package/dist/index.d.ts +226 -0
  11. package/dist/index.esm.js +155 -0
  12. package/dist/lib-CyIAFRfr.esm.js +12499 -0
  13. package/dist/permissionServices-CVR0Pq38.esm.js +72 -0
  14. package/dist/phone.d.ts +292 -0
  15. package/dist/phone.esm.js +550 -0
  16. package/dist/selfie.d.ts +758 -0
  17. package/dist/selfie.esm.js +978 -0
  18. package/dist/types-tq1ypYSL.d.ts +5 -0
  19. package/dist/warmup-Dr7OcFND.d.ts +55 -0
  20. package/dist/xstate.esm-B_rda9yU.esm.js +3261 -0
  21. package/package.json +14 -11
  22. package/src/camera/cameraActor.ts +0 -21
  23. package/src/camera/cameraService.test.ts +0 -437
  24. package/src/camera/cameraService.ts +0 -165
  25. package/src/camera/cameraServices.test.ts +0 -66
  26. package/src/camera/cameraServices.ts +0 -26
  27. package/src/camera/cameraStateMachine.test.ts +0 -602
  28. package/src/camera/cameraStateMachine.ts +0 -264
  29. package/src/camera/index.ts +0 -5
  30. package/src/camera/types.ts +0 -17
  31. package/src/device/getBrowser.ts +0 -31
  32. package/src/device/getDeviceClass.ts +0 -29
  33. package/src/device/index.ts +0 -2
  34. package/src/email/__mocks__/emailMocks.ts +0 -59
  35. package/src/email/emailActor.ts +0 -15
  36. package/src/email/emailManager.test.ts +0 -573
  37. package/src/email/emailManager.ts +0 -427
  38. package/src/email/emailServices.ts +0 -66
  39. package/src/email/emailStateMachine.test.ts +0 -741
  40. package/src/email/emailStateMachine.ts +0 -367
  41. package/src/email/index.ts +0 -39
  42. package/src/email/types.ts +0 -60
  43. package/src/events/addEvent.ts +0 -20
  44. package/src/events/types.ts +0 -7
  45. package/src/flow/__mocks__/flowMocks.ts +0 -84
  46. package/src/flow/flowActor.ts +0 -13
  47. package/src/flow/flowAnalyzer.test.ts +0 -266
  48. package/src/flow/flowAnalyzer.ts +0 -37
  49. package/src/flow/flowCompletionService.ts +0 -21
  50. package/src/flow/flowManager.test.ts +0 -560
  51. package/src/flow/flowManager.ts +0 -235
  52. package/src/flow/flowServices.test.ts +0 -109
  53. package/src/flow/flowServices.ts +0 -13
  54. package/src/flow/flowStateMachine.test.ts +0 -334
  55. package/src/flow/flowStateMachine.ts +0 -182
  56. package/src/flow/index.ts +0 -21
  57. package/src/flow/moduleLoader.test.ts +0 -136
  58. package/src/flow/moduleLoader.ts +0 -73
  59. package/src/flow/orchestratedFlowManager.test.ts +0 -240
  60. package/src/flow/orchestratedFlowManager.ts +0 -231
  61. package/src/flow/orchestratedFlowStateMachine.test.ts +0 -199
  62. package/src/flow/orchestratedFlowStateMachine.ts +0 -325
  63. package/src/flow/types.ts +0 -434
  64. package/src/http/__mocks__/api.ts +0 -88
  65. package/src/http/api.test.ts +0 -231
  66. package/src/http/api.ts +0 -90
  67. package/src/http/endpoints.ts +0 -17
  68. package/src/index.ts +0 -33
  69. package/src/permissions/index.ts +0 -2
  70. package/src/permissions/permissionServices.ts +0 -31
  71. package/src/permissions/types.ts +0 -3
  72. package/src/phone/__mocks__/phoneMocks.ts +0 -71
  73. package/src/phone/index.ts +0 -39
  74. package/src/phone/phoneActor.ts +0 -15
  75. package/src/phone/phoneManager.test.ts +0 -393
  76. package/src/phone/phoneManager.ts +0 -458
  77. package/src/phone/phoneServices.ts +0 -98
  78. package/src/phone/phoneStateMachine.test.ts +0 -918
  79. package/src/phone/phoneStateMachine.ts +0 -422
  80. package/src/phone/types.ts +0 -83
  81. package/src/recordings/recordingsRepository.test.ts +0 -87
  82. package/src/recordings/recordingsRepository.ts +0 -48
  83. package/src/recordings/streamingEvents.ts +0 -10
  84. package/src/selfie/__mocks__/selfieMocks.ts +0 -26
  85. package/src/selfie/index.ts +0 -14
  86. package/src/selfie/selfieActor.ts +0 -17
  87. package/src/selfie/selfieErrorUtils.test.ts +0 -116
  88. package/src/selfie/selfieErrorUtils.ts +0 -66
  89. package/src/selfie/selfieManager.test.ts +0 -297
  90. package/src/selfie/selfieManager.ts +0 -301
  91. package/src/selfie/selfieServices.ts +0 -362
  92. package/src/selfie/selfieStateMachine.test.ts +0 -283
  93. package/src/selfie/selfieStateMachine.ts +0 -804
  94. package/src/selfie/selfieUploadService.test.ts +0 -90
  95. package/src/selfie/selfieUploadService.ts +0 -81
  96. package/src/selfie/types.ts +0 -103
  97. package/src/session/index.ts +0 -5
  98. package/src/session/sessionService.ts +0 -78
  99. package/src/setup.test.ts +0 -61
  100. package/src/setup.ts +0 -171
  101. package/tsconfig.json +0 -13
  102. package/tsdown.config.ts +0 -22
  103. package/vitest.config.ts +0 -37
  104. package/vitest.setup.ts +0 -135
@@ -0,0 +1,1701 @@
1
+ import { a as __toDynamicImportESM } from "./chunk-C_Yo44FK.esm.js";
2
+
3
+ //#region ../infra/src/http/createApi.ts
4
+ var FetchHttpError = class extends Error {
5
+ constructor(status, statusText, url, method, headers, data) {
6
+ super(`HTTP ${status} ${statusText}`);
7
+ this.ok = false;
8
+ this.status = status;
9
+ this.statusText = statusText;
10
+ this.url = url;
11
+ this.method = method;
12
+ this.headers = headers;
13
+ this.data = data;
14
+ this.name = "FetchHttpError";
15
+ }
16
+ };
17
+ const buildQueryString = (query) => {
18
+ if (!query) return "";
19
+ const params = new URLSearchParams();
20
+ Object.entries(query).forEach(([key, value]) => {
21
+ if (value !== void 0 && value !== null) params.append(key, String(value));
22
+ });
23
+ const str = params.toString();
24
+ return str ? `?${str}` : "";
25
+ };
26
+ const buildUrl = (baseURL, url, query) => {
27
+ const queryString = buildQueryString(query);
28
+ if (url.startsWith("http://") || url.startsWith("https://")) return `${url}${queryString}`;
29
+ return `${baseURL.endsWith("/") ? baseURL.slice(0, -1) : baseURL}${url.startsWith("/") ? url : `/${url}`}${queryString}`;
30
+ };
31
+ const prepareBody = (body) => {
32
+ if (body === null || body === void 0) return null;
33
+ if (body instanceof FormData || body instanceof Blob || body instanceof ArrayBuffer) return body;
34
+ if (typeof body === "object") return JSON.stringify(body);
35
+ return String(body);
36
+ };
37
+ const parseResponse = async (response, parseType) => {
38
+ if (parseType === "response") return response;
39
+ if (parseType === "blob") return await response.blob();
40
+ if (parseType === "arrayBuffer") return await response.arrayBuffer();
41
+ if (parseType === "text") return await response.text();
42
+ const contentType = response.headers.get("content-type") ?? "";
43
+ if (parseType === "json" || contentType.includes("application/json")) try {
44
+ return await response.json();
45
+ } catch {
46
+ return await response.text();
47
+ }
48
+ return await response.text();
49
+ };
50
+ const DEFAULT_TIMEOUT = 3e4;
51
+ const createApi = (config) => {
52
+ const headers = {
53
+ "Content-Type": "application/json",
54
+ Accept: "application/json",
55
+ "api-version": "1.0",
56
+ ...config.customHeaders ?? {}
57
+ };
58
+ const defaults = {
59
+ baseURL: config.apiURL,
60
+ headers
61
+ };
62
+ const client$1 = {
63
+ defaults,
64
+ async request(requestConfig) {
65
+ const { method = "GET", url, headers: headers$1 = {}, query, params, body, signal, timeout = config.timeout ?? DEFAULT_TIMEOUT, parse } = requestConfig;
66
+ const fullUrl = buildUrl(defaults.baseURL, url, params ?? query);
67
+ const mergedHeaders = {
68
+ ...defaults.headers,
69
+ ...headers$1
70
+ };
71
+ const controller = new AbortController();
72
+ const abortSignal = signal ?? controller.signal;
73
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
74
+ try {
75
+ const requestBody = prepareBody(body);
76
+ let finalHeaders = mergedHeaders;
77
+ if (requestBody === null && (method === "POST" || method === "PUT" || method === "PATCH")) {
78
+ const { "Content-Type": _, ...headersWithoutContentType } = mergedHeaders;
79
+ finalHeaders = headersWithoutContentType;
80
+ }
81
+ const response = await fetch(fullUrl, {
82
+ method,
83
+ headers: finalHeaders,
84
+ body: requestBody,
85
+ signal: abortSignal
86
+ });
87
+ if (timeoutId) clearTimeout(timeoutId);
88
+ const responseHeaders = {};
89
+ response.headers.forEach((value, key) => {
90
+ responseHeaders[key] = value;
91
+ });
92
+ const data = await parseResponse(response, parse);
93
+ if (!response.ok) throw new FetchHttpError(response.status, response.statusText, fullUrl, method, responseHeaders, data);
94
+ return {
95
+ ok: true,
96
+ status: response.status,
97
+ statusText: response.statusText,
98
+ url: fullUrl,
99
+ headers: responseHeaders,
100
+ data
101
+ };
102
+ } catch (error) {
103
+ if (timeoutId) clearTimeout(timeoutId);
104
+ if (error instanceof FetchHttpError) throw error;
105
+ if (error instanceof Error && error.name === "AbortError") throw new FetchHttpError(0, "Request timeout", fullUrl, method, {}, null);
106
+ throw error;
107
+ }
108
+ },
109
+ get(url, config$1) {
110
+ return client$1.request({
111
+ ...config$1,
112
+ url,
113
+ method: "GET"
114
+ });
115
+ },
116
+ post(url, body, config$1) {
117
+ return client$1.request({
118
+ ...config$1,
119
+ url,
120
+ body,
121
+ method: "POST"
122
+ });
123
+ },
124
+ put(url, body, config$1) {
125
+ return client$1.request({
126
+ ...config$1,
127
+ url,
128
+ body,
129
+ method: "PUT"
130
+ });
131
+ },
132
+ patch(url, body, config$1) {
133
+ return client$1.request({
134
+ ...config$1,
135
+ url,
136
+ body,
137
+ method: "PATCH"
138
+ });
139
+ },
140
+ delete(url, config$1) {
141
+ return client$1.request({
142
+ ...config$1,
143
+ url,
144
+ method: "DELETE"
145
+ });
146
+ },
147
+ head(url, config$1) {
148
+ return client$1.request({
149
+ ...config$1,
150
+ url,
151
+ method: "HEAD"
152
+ });
153
+ },
154
+ options(url, config$1) {
155
+ return client$1.request({
156
+ ...config$1,
157
+ url,
158
+ method: "OPTIONS"
159
+ });
160
+ },
161
+ setHeader(name, value) {
162
+ defaults.headers[name] = value;
163
+ }
164
+ };
165
+ return client$1;
166
+ };
167
+ var createApi_default = createApi;
168
+
169
+ //#endregion
170
+ //#region ../infra/src/manager/Manager.ts
171
+ /**
172
+ * Creates a manager that wraps a state machine actor with a clean public API.
173
+ *
174
+ * The manager provides:
175
+ * - `getState()` - Returns the mapped public state
176
+ * - `subscribe()` - Listen to state changes
177
+ * - `stop()` - Stop the actor
178
+ * - Plus any custom API methods from `createApi`
179
+ *
180
+ * @template TMachine - The state machine type
181
+ * @template TMapState - Function type that maps raw snapshot to public state
182
+ * @template TCreateApi - Function type that creates the custom API
183
+ *
184
+ * @param options - Configuration options
185
+ * @param options.actor - The started actor instance
186
+ * @param options.mapState - Function to transform raw snapshot into public state
187
+ * @param options.createApi - Factory function to create custom API methods
188
+ *
189
+ * @returns Combined manager with base methods and custom API
190
+ *
191
+ * @example
192
+ * ```ts
193
+ * const manager = createManager({
194
+ * actor: createActor(myMachine).start(),
195
+ * mapState: (snapshot) => ({ status: snapshot.value }),
196
+ * createApi: ({ actor }) => ({
197
+ * doSomething() { actor.send({ type: 'DO_IT' }); }
198
+ * }),
199
+ * });
200
+ * ```
201
+ */
202
+ function createManager(options) {
203
+ const { actor, mapState, createApi: createApi$1 } = options;
204
+ function getSnapshot() {
205
+ return actor.getSnapshot();
206
+ }
207
+ function getState() {
208
+ return mapState(getSnapshot());
209
+ }
210
+ function subscribe(listener) {
211
+ const subscription = actor.subscribe(() => {
212
+ listener(getState());
213
+ });
214
+ return () => subscription.unsubscribe();
215
+ }
216
+ const api$1 = createApi$1({
217
+ actor,
218
+ getSnapshot
219
+ });
220
+ const base = {
221
+ getState,
222
+ subscribe,
223
+ stop() {
224
+ actor.stop();
225
+ }
226
+ };
227
+ return Object.defineProperties(base, Object.getOwnPropertyDescriptors(api$1));
228
+ }
229
+
230
+ //#endregion
231
+ //#region ../infra/src/media/camera.ts
232
+ async function requestCameraAccess(constraints) {
233
+ if (typeof navigator === "undefined" || !navigator.mediaDevices) throw new Error("MediaDevices API not available");
234
+ return navigator.mediaDevices.getUserMedia(constraints);
235
+ }
236
+ function stopCameraStream(stream) {
237
+ for (const track of stream.getTracks()) track.stop();
238
+ }
239
+
240
+ //#endregion
241
+ //#region ../infra/src/media/canvas.ts
242
+ /**
243
+ * Class representing a canvas element for image capture and manipulation.
244
+ */
245
+ var IncodeCanvas = class IncodeCanvas {
246
+ /**
247
+ * Creates an {@link IncodeCanvas} from a raw {@link ImageData} frame.
248
+ * @param imageData - Frame pixels in RGBA format
249
+ * @returns An {@link IncodeCanvas} containing the provided pixels
250
+ */
251
+ static fromImageData(imageData) {
252
+ const canvas = document.createElement("canvas");
253
+ canvas.width = imageData.width;
254
+ canvas.height = imageData.height;
255
+ const context = canvas.getContext("2d", { willReadFrequently: true });
256
+ if (!context) return new IncodeCanvas(canvas);
257
+ if ("putImageData" in context) context.putImageData(imageData, 0, 0);
258
+ return new IncodeCanvas(canvas);
259
+ }
260
+ /**
261
+ * Create a new canvas element.
262
+ * @param canvas_ - The canvas element to clone.
263
+ */
264
+ constructor(canvas_) {
265
+ this.base64Image = null;
266
+ this.blobData = null;
267
+ this.canvas = document.createElement("canvas");
268
+ this.canvas.width = canvas_.width;
269
+ this.canvas.height = canvas_.height;
270
+ const context = this.canvas.getContext("2d");
271
+ if (context) context.drawImage(canvas_, 0, 0);
272
+ }
273
+ /**
274
+ * Check if the current canvas is valid.
275
+ */
276
+ checkCanvas() {
277
+ return this.canvas && this.canvas.width > 1 && this.canvas.height > 1;
278
+ }
279
+ /**
280
+ * Release the data stored by IncodeCanvas.
281
+ */
282
+ release() {
283
+ if (!this.checkCanvas()) return;
284
+ this.canvas.width = 1;
285
+ this.canvas.height = 1;
286
+ this.canvas.getContext("2d")?.clearRect(0, 0, 1, 1);
287
+ this.base64Image = null;
288
+ this.blobData = null;
289
+ }
290
+ /**
291
+ * Get the width of the canvas.
292
+ */
293
+ width() {
294
+ if (!this.checkCanvas()) return null;
295
+ return this.canvas.width;
296
+ }
297
+ /**
298
+ * Get the height of the canvas.
299
+ */
300
+ height() {
301
+ if (!this.checkCanvas()) return null;
302
+ return this.canvas.height;
303
+ }
304
+ /**
305
+ * Set the width of the canvas.
306
+ */
307
+ setWidth(width) {
308
+ if (!this.checkCanvas()) return;
309
+ this.canvas.width = width;
310
+ }
311
+ /**
312
+ * Set the height of the canvas.
313
+ */
314
+ setHeight(height) {
315
+ if (!this.checkCanvas()) return;
316
+ this.canvas.height = height;
317
+ }
318
+ /**
319
+ * Clone the current canvas.
320
+ */
321
+ clone() {
322
+ if (!this.checkCanvas()) return null;
323
+ const cloned = new IncodeCanvas(this.canvas);
324
+ cloned.setBase64Image(this.base64Image);
325
+ return cloned;
326
+ }
327
+ /**
328
+ * Deep clone the current IncodeCanvas including blob data.
329
+ */
330
+ async deepClone() {
331
+ const cloned = this.clone();
332
+ if (!cloned) return null;
333
+ if (this.blobData) await cloned.setBlobData(this.blobData);
334
+ return cloned;
335
+ }
336
+ /**
337
+ * Returns the drawing context on the canvas.
338
+ */
339
+ getContext(contextId, contextAttributes) {
340
+ if (!this.checkCanvas()) return null;
341
+ const context = this.canvas.getContext(contextId, contextAttributes);
342
+ return context instanceof CanvasRenderingContext2D ? context : null;
343
+ }
344
+ /**
345
+ * Retrieves the image data from the canvas.
346
+ */
347
+ getImageData() {
348
+ if (!this.checkCanvas()) return null;
349
+ const context = this.canvas.getContext("2d", { willReadFrequently: true });
350
+ if (!context) return null;
351
+ return context.getImageData(0, 0, this.canvas.width, this.canvas.height);
352
+ }
353
+ /**
354
+ * Updates the base64 representation of the current canvas image.
355
+ */
356
+ updateBase64Image(jpegQuality = 1) {
357
+ if (!this.checkCanvas()) return;
358
+ this.base64Image = this.canvas.toDataURL("image/jpeg", jpegQuality);
359
+ }
360
+ /**
361
+ * Converts the current canvas element to a base64 string.
362
+ */
363
+ getBase64Image(jpegQuality = 1, includeDataURLPrefix = false) {
364
+ if (!this.checkCanvas()) return null;
365
+ if (this.base64Image === null) this.updateBase64Image(jpegQuality);
366
+ const base64Image = this.base64Image;
367
+ if (base64Image === null) return null;
368
+ if (includeDataURLPrefix) return base64Image;
369
+ const commaIndex = base64Image.indexOf(",");
370
+ if (commaIndex === -1) return base64Image;
371
+ return base64Image.slice(commaIndex + 1);
372
+ }
373
+ /**
374
+ * Sets the base64 representation of the current canvas image.
375
+ */
376
+ setBase64Image(base64Image) {
377
+ this.base64Image = base64Image;
378
+ }
379
+ /**
380
+ * Updates the Blob representation of the current canvas image.
381
+ */
382
+ updateBlob(jpegQuality = 1, includeDataURLPrefix = false) {
383
+ if (!this.checkCanvas()) return;
384
+ if (this.base64Image === null) this.updateBase64Image(jpegQuality);
385
+ const base64 = this.getBase64Image(jpegQuality, includeDataURLPrefix);
386
+ if (base64) this.blobData = IncodeCanvas.base64ToBlob(base64);
387
+ }
388
+ /**
389
+ * Converts a base64 string to a Blob and creates a URL for it.
390
+ */
391
+ static base64ToBlob(base64) {
392
+ try {
393
+ const binary = atob(base64);
394
+ const array = [];
395
+ for (let i = 0; i < binary.length; i++) array.push(binary.charCodeAt(i));
396
+ const blob = new Blob([new Uint8Array(array)]);
397
+ return {
398
+ blob,
399
+ url: URL.createObjectURL(blob)
400
+ };
401
+ } catch (error) {
402
+ console.error("Failed to convert base64 string to Blob:", error);
403
+ }
404
+ return null;
405
+ }
406
+ /**
407
+ * Retrieves the Blob data and its URL from the current canvas.
408
+ */
409
+ getBlobData(jpegQuality = 1, includeDataURLPrefix = false) {
410
+ if (!this.checkCanvas()) return null;
411
+ if (this.blobData === null) this.updateBlob(jpegQuality, includeDataURLPrefix);
412
+ return this.blobData;
413
+ }
414
+ /**
415
+ * Sets the Blob data of the current canvas image.
416
+ */
417
+ async setBlobData(blobData) {
418
+ const blobDataArrayBuffer = await blobData.blob.arrayBuffer();
419
+ this.blobData = {
420
+ blob: new Blob([blobDataArrayBuffer], { type: blobData.blob.type }),
421
+ url: blobData.url
422
+ };
423
+ }
424
+ /**
425
+ * Returns a resized canvas according to video element size.
426
+ */
427
+ getResizedCanvas(videoElementWidth, videoElementHeight) {
428
+ if (!this.checkCanvas()) return null;
429
+ const cameraOffsetX = Math.abs(videoElementWidth - window.innerWidth);
430
+ const resized = new IncodeCanvas(document.createElement("canvas"));
431
+ const canvasHeight = this.height();
432
+ if (!canvasHeight) return null;
433
+ const ratio = canvasHeight / videoElementHeight;
434
+ const newWidth = window.innerWidth;
435
+ const newHeight = window.innerHeight;
436
+ resized.setWidth(newWidth);
437
+ resized.setHeight(newHeight);
438
+ const context = resized.getContext("2d");
439
+ if (!context) {
440
+ console.error("Failed to get 2d context in getResizedCanvas method.");
441
+ return null;
442
+ }
443
+ context.drawImage(this.canvas, ratio * cameraOffsetX / 2, 0, ratio * newWidth, ratio * newHeight, 0, 0, newWidth, newHeight);
444
+ return resized;
445
+ }
446
+ };
447
+
448
+ //#endregion
449
+ //#region ../infra/src/media/permissions.ts
450
+ async function queryPermission(name) {
451
+ try {
452
+ if (typeof navigator === "undefined" || !navigator.permissions) return "prompt";
453
+ return (await navigator.permissions.query({ name })).state;
454
+ } catch {
455
+ return "prompt";
456
+ }
457
+ }
458
+ async function queryCameraPermission() {
459
+ return queryPermission("camera");
460
+ }
461
+
462
+ //#endregion
463
+ //#region ../infra/src/media/StreamCanvasCapture.ts
464
+ var StreamCanvasCapture = class {
465
+ constructor(stream, options) {
466
+ this.hasFrame = false;
467
+ this.disposed = false;
468
+ this.eventTarget = new EventTarget();
469
+ this.video = document.createElement("video");
470
+ this.video.srcObject = stream;
471
+ this.video.autoplay = true;
472
+ this.video.playsInline = true;
473
+ this.video.muted = true;
474
+ const settings = stream.getVideoTracks()[0]?.getSettings();
475
+ const width = options?.width ?? settings?.width ?? 640;
476
+ const height = options?.height ?? settings?.height ?? 480;
477
+ this.canvas = document.createElement("canvas");
478
+ this.canvas.width = width;
479
+ this.canvas.height = height;
480
+ this.ctx = this.canvas.getContext("2d", { willReadFrequently: true });
481
+ const fps = options?.fps ?? 10;
482
+ const intervalMs = fps > 0 ? Math.max(16, Math.floor(1e3 / fps)) : 0;
483
+ try {
484
+ this.video.play();
485
+ } catch {}
486
+ this.rafLoop(intervalMs);
487
+ }
488
+ addEventListener(type, listener, options) {
489
+ this.eventTarget.addEventListener(type, listener, options);
490
+ }
491
+ removeEventListener(type, listener, options) {
492
+ this.eventTarget.removeEventListener(type, listener, options);
493
+ }
494
+ /**
495
+ * Returns the latest cached frame as an {@link IncodeCanvas}.
496
+ */
497
+ getLatestCanvas() {
498
+ if (!this.hasFrame) this.tick();
499
+ if (!this.hasFrame) return null;
500
+ return new IncodeCanvas(this.canvas);
501
+ }
502
+ /**
503
+ * Returns the latest cached frame as raw {@link ImageData}.
504
+ */
505
+ getLatestFrame() {
506
+ if (!this.ctx) return null;
507
+ if (!this.hasFrame) this.tick();
508
+ if (!this.hasFrame) return null;
509
+ try {
510
+ return this.ctx.getImageData(0, 0, this.canvas.width, this.canvas.height);
511
+ } catch {
512
+ return null;
513
+ }
514
+ }
515
+ /**
516
+ * Disposes internal resources and stops the capture loop.
517
+ */
518
+ dispose() {
519
+ if (this.disposed) return;
520
+ this.disposed = true;
521
+ if (this.rafId !== void 0) {
522
+ window.cancelAnimationFrame(this.rafId);
523
+ this.rafId = void 0;
524
+ }
525
+ this.video.srcObject = null;
526
+ this.canvas.width = 0;
527
+ this.canvas.height = 0;
528
+ this.hasFrame = false;
529
+ }
530
+ rafLoop(intervalMs) {
531
+ const loop = (timeMs) => {
532
+ if (this.disposed) return;
533
+ if (intervalMs <= 0 || this.lastTickTimeMs === void 0 || timeMs - this.lastTickTimeMs >= intervalMs) {
534
+ this.lastTickTimeMs = timeMs;
535
+ const previousFrameTimeSeconds = this.lastFrameTimeSeconds;
536
+ this.tick();
537
+ const currentFrameTimeSeconds = this.video.currentTime;
538
+ if (previousFrameTimeSeconds === void 0) {
539
+ if (this.hasFrame) {
540
+ this.lastFrameTimeSeconds = currentFrameTimeSeconds;
541
+ this.eventTarget.dispatchEvent(new Event("frame"));
542
+ }
543
+ } else if (this.hasFrame && currentFrameTimeSeconds !== previousFrameTimeSeconds) {
544
+ this.lastFrameTimeSeconds = currentFrameTimeSeconds;
545
+ this.eventTarget.dispatchEvent(new Event("frame"));
546
+ }
547
+ }
548
+ this.rafId = window.requestAnimationFrame(loop);
549
+ };
550
+ this.rafId = window.requestAnimationFrame(loop);
551
+ }
552
+ tick() {
553
+ if (!this.ctx) return;
554
+ if (this.video.readyState < HTMLMediaElement.HAVE_CURRENT_DATA) return;
555
+ try {
556
+ this.ctx.drawImage(this.video, 0, 0, this.canvas.width, this.canvas.height);
557
+ this.hasFrame = true;
558
+ } catch {
559
+ this.hasFrame = false;
560
+ }
561
+ }
562
+ };
563
+
564
+ //#endregion
565
+ //#region ../infra/src/media/StreamCanvasProcessingSession.ts
566
+ var StreamCanvasProcessingSession = class {
567
+ /**
568
+ * Creates a processing session that reacts to `StreamCanvasCapture` frame events
569
+ * and drives a provider's `processFrame()` method with backpressure.
570
+ */
571
+ constructor(params) {
572
+ this.disposed = false;
573
+ this.isProcessing = false;
574
+ this.onFrameEvent = () => {
575
+ if (this.disposed || this.isProcessing) return;
576
+ const frame = this.capturer.getLatestFrame();
577
+ if (!frame) return;
578
+ this.onFrame?.(frame);
579
+ this.isProcessing = true;
580
+ this.provider.processFrame(frame).catch(() => {}).finally(() => {
581
+ this.isProcessing = false;
582
+ });
583
+ };
584
+ this.capturer = params.capturer;
585
+ this.provider = params.provider;
586
+ this.onFrame = params.onFrame;
587
+ this.capturer.addEventListener("frame", this.onFrameEvent);
588
+ }
589
+ /**
590
+ * Unsubscribes from frame events and resets the provider.
591
+ */
592
+ dispose() {
593
+ if (this.disposed) return;
594
+ this.disposed = true;
595
+ this.capturer.removeEventListener("frame", this.onFrameEvent);
596
+ this.provider.reset();
597
+ }
598
+ /**
599
+ * Returns whether the session has been disposed.
600
+ */
601
+ isDisposed() {
602
+ return this.disposed;
603
+ }
604
+ };
605
+
606
+ //#endregion
607
+ //#region ../infra/src/providers/browser/openviduLazy.ts
608
+ let openViduImport;
609
+ async function loadOpenVidu() {
610
+ if (openViduImport) return openViduImport;
611
+ openViduImport = import("./lib-CyIAFRfr.esm.js").then(__toDynamicImportESM(1));
612
+ return openViduImport;
613
+ }
614
+
615
+ //#endregion
616
+ //#region ../infra/src/providers/browser/OpenViduRecordingProvider.ts
617
+ function createHiddenContainer() {
618
+ const id = `inc_rec_${Math.random().toString(36).slice(2)}`;
619
+ const existing = document.getElementById(id);
620
+ if (existing) return {
621
+ id,
622
+ element: existing
623
+ };
624
+ const div = document.createElement("div");
625
+ div.id = id;
626
+ div.style.display = "none";
627
+ document.body.appendChild(div);
628
+ return {
629
+ id,
630
+ element: div
631
+ };
632
+ }
633
+ var OpenViduRecordingProvider = class {
634
+ async connect(params) {
635
+ const { OpenVidu } = await loadOpenVidu();
636
+ const container = createHiddenContainer();
637
+ const ov = new OpenVidu();
638
+ const session = ov.initSession();
639
+ const videoTrack = params.stream.getVideoTracks()[0];
640
+ const audioTrack = params.stream.getAudioTracks()[0];
641
+ const hasAudio = audioTrack !== void 0;
642
+ const publisher = ov.initPublisher(container.id, {
643
+ publishAudio: hasAudio,
644
+ audioSource: hasAudio ? audioTrack : void 0,
645
+ videoSource: videoTrack ?? void 0,
646
+ frameRate: 30
647
+ });
648
+ session.on("exception", (event) => {
649
+ const e = event;
650
+ params.events?.onSessionException?.({
651
+ name: e?.name,
652
+ message: e?.message,
653
+ sessionId: session.sessionId
654
+ });
655
+ });
656
+ publisher.on("streamCreated", () => {
657
+ params.events?.onPublisherCreated?.({
658
+ sessionId: session.sessionId,
659
+ streamId: publisher.stream?.streamId
660
+ });
661
+ });
662
+ await session.connect(params.sessionToken);
663
+ params.events?.onSessionConnected?.(session.sessionId);
664
+ try {
665
+ await session.publish(publisher);
666
+ } catch (error) {
667
+ const message = error instanceof Error ? error.message : String(error);
668
+ params.events?.onPublisherError?.({
669
+ message,
670
+ sessionId: session.sessionId,
671
+ streamId: publisher.stream?.streamId
672
+ });
673
+ throw error;
674
+ }
675
+ return {
676
+ sessionId: session.sessionId,
677
+ publisher: {
678
+ getStreamId: () => publisher.stream?.streamId,
679
+ replaceVideoTrack: async (track) => {
680
+ await publisher.replaceTrack(track);
681
+ },
682
+ destroy: () => {}
683
+ },
684
+ disconnect: async () => {
685
+ try {
686
+ session.disconnect();
687
+ params.stream.getTracks().forEach((t) => {
688
+ t.stop();
689
+ });
690
+ } finally {
691
+ params.events?.onSessionDisconnected?.(session.sessionId);
692
+ if (container.element.parentNode) container.element.parentNode.removeChild(container.element);
693
+ }
694
+ }
695
+ };
696
+ }
697
+ };
698
+
699
+ //#endregion
700
+ //#region ../infra/src/wasm/IdCaptureModelType.ts
701
+ let IdCaptureModelType = /* @__PURE__ */ function(IdCaptureModelType$1) {
702
+ IdCaptureModelType$1[IdCaptureModelType$1["IdCaptureV1x"] = 0] = "IdCaptureV1x";
703
+ IdCaptureModelType$1[IdCaptureModelType$1["IdCaptureV2x"] = 1] = "IdCaptureV2x";
704
+ IdCaptureModelType$1[IdCaptureModelType$1["IdCaptureV3x"] = 2] = "IdCaptureV3x";
705
+ return IdCaptureModelType$1;
706
+ }({});
707
+
708
+ //#endregion
709
+ //#region ../infra/src/wasm/Mutex.ts
710
+ var Semaphore = class {
711
+ constructor(maxConcurrent = 1) {
712
+ this.maxConcurrent = maxConcurrent;
713
+ this.current = 0;
714
+ this.queue = [];
715
+ }
716
+ async acquire() {
717
+ if (this.current < this.maxConcurrent) {
718
+ this.current++;
719
+ return Promise.resolve();
720
+ }
721
+ return new Promise((resolve) => {
722
+ this.queue.push(resolve);
723
+ });
724
+ }
725
+ release() {
726
+ this.current = Math.max(0, this.current - 1);
727
+ if (this.queue.length > 0 && this.current < this.maxConcurrent) {
728
+ this.current++;
729
+ const next = this.queue.shift();
730
+ if (next) next();
731
+ }
732
+ }
733
+ };
734
+ var Mutex = class {
735
+ constructor() {
736
+ this.semaphore = new Semaphore(1);
737
+ }
738
+ async lock() {
739
+ return this.semaphore.acquire();
740
+ }
741
+ unlock() {
742
+ this.semaphore.release();
743
+ }
744
+ async withLock(fn, ...args) {
745
+ await this.lock();
746
+ try {
747
+ return await fn(...args);
748
+ } finally {
749
+ this.unlock();
750
+ }
751
+ }
752
+ };
753
+
754
+ //#endregion
755
+ //#region ../infra/src/wasm/WasmPipelineType.ts
756
+ let WasmPipelineType = /* @__PURE__ */ function(WasmPipelineType$1) {
757
+ WasmPipelineType$1[WasmPipelineType$1["IdBlurGlarePipeline"] = 0] = "IdBlurGlarePipeline";
758
+ WasmPipelineType$1[WasmPipelineType$1["IdBarcodeAndTextQualityPipeline"] = 1] = "IdBarcodeAndTextQualityPipeline";
759
+ WasmPipelineType$1[WasmPipelineType$1["IdVideoSelfiePipeline"] = 2] = "IdVideoSelfiePipeline";
760
+ WasmPipelineType$1[WasmPipelineType$1["SelfieWithAggregationMetrics"] = 3] = "SelfieWithAggregationMetrics";
761
+ WasmPipelineType$1[WasmPipelineType$1["SelfieWithQualityMetrics"] = 4] = "SelfieWithQualityMetrics";
762
+ WasmPipelineType$1[WasmPipelineType$1["IdFaceDetectionPipeline"] = 5] = "IdFaceDetectionPipeline";
763
+ return WasmPipelineType$1;
764
+ }({});
765
+
766
+ //#endregion
767
+ //#region ../infra/src/wasm/mlWasmJSApi.ts
768
+ window.wasmArrayBuffer = null;
769
+ var MlWasmJSApi = class MlWasmJSApi {
770
+ constructor() {
771
+ this.versionsFile = null;
772
+ this.modelsBuffers = null;
773
+ this.inputImageBuffer = null;
774
+ this.wasmModule = null;
775
+ this.pipelineApiUtilities = null;
776
+ this.utilityApi = null;
777
+ this.idCaptureWasmApi = null;
778
+ this.faceDetectionWasmApi = null;
779
+ this.imageWidth_ = null;
780
+ this.imageHeight_ = null;
781
+ this.pipelines_ = null;
782
+ this.isInitialized_ = false;
783
+ this.inspectorOpened_ = false;
784
+ this.wasmCallMutex = new Mutex();
785
+ this.Module = null;
786
+ this.loadModule = async (glueCodePath) => {
787
+ this.Module = (await import(
788
+ /* @vite-ignore */
789
+ /* webpackIgnore: true */
790
+ glueCodePath
791
+ )).Module;
792
+ };
793
+ }
794
+ /**
795
+ * Initiallization method, use it when the application starts
796
+ * TODO: this method can return the list of promises to be awaited together with other initialization code
797
+ * @param {string} webLibPath - The path to the webassembly binary
798
+ * @param {string} webLibPathSimd - The path to the SIMD version webassembly binary
799
+ * @param {boolean} useSimd - Indicates whether SIMD optimizations should be used
800
+ * @param {string} versionsFile - The path to the file containing versioning information
801
+ * @param {Map.<WasmPipelineType, Array<string>>} pipelines - pipelines for initialization and corresponding models paths
802
+ * @returns {Promise<boolean>} A promise that resolves to a boolean indicating whether SIMD is enabled once the initialization is complete.
803
+ * @throws {Error} Throws an error if the initialization fails.
804
+ */
805
+ async initialize(webLibPath, webLibPathSimd, glueCodePath, useSimd, versionsFile, pipelines) {
806
+ await this.freeResources();
807
+ this.pipelines_ = pipelines;
808
+ this.versionsFile = versionsFile;
809
+ await this.loadModule(glueCodePath);
810
+ const simdIsEnabled = await this.loadWasm(useSimd, webLibPath, webLibPathSimd);
811
+ this.pipelineApiUtilities = new this.wasmModule.PipelineApiUtilities();
812
+ this.utilityApi = new this.wasmModule.UtilityApi();
813
+ this.idCaptureWasmApi = new this.wasmModule.IdCaptureApi();
814
+ this.faceDetectionWasmApi = new this.wasmModule.FaceDetectionApi();
815
+ this.isInitialized_ = true;
816
+ return simdIsEnabled;
817
+ }
818
+ static getInstance() {
819
+ if (!MlWasmJSApi.instance) MlWasmJSApi.instance = new MlWasmJSApi();
820
+ return MlWasmJSApi.instance;
821
+ }
822
+ /**
823
+ * Returns initialization status
824
+ * @returns
825
+ */
826
+ isInitialized() {
827
+ return this.pipelineApiUtilities != null && this.utilityApi != null && this.idCaptureWasmApi != null && this.faceDetectionWasmApi != null && this.isInitialized_;
828
+ }
829
+ /**
830
+ * Allocate shared memory for image buffers (RGBA format)
831
+ * Use it every time when the frame dimentions changes
832
+ * @param {number} imageWidth - image width
833
+ * @param {number} imageHeight - image height
834
+ */
835
+ async allocateImageBuffers(imageWidth, imageHeight) {
836
+ this.checkWasmInitialization("Unable to allocate image buffers, cpp API hasn't been initialized");
837
+ if (imageWidth && imageHeight && imageWidth == this.imageWidth_ && imageHeight == this.imageHeight_ && this.inputImageBuffer && imageWidth * imageHeight * 4 === this.inputImageBuffer.length) return;
838
+ this.imageWidth_ = imageWidth;
839
+ this.imageHeight_ = imageHeight;
840
+ this.inputImageBuffer = this.pipelineApiUtilities.allocateInputImageBuffer(imageWidth, imageHeight, 4);
841
+ }
842
+ async handleDetectionCallAndUpdateState(type) {
843
+ this.checkWasmInitialization("Unable to update pipeline state, cpp API hasn't been initialized");
844
+ this.pipelineApiUtilities.handleDetectionCallAndUpdateState(this.pipelineTypeToWasmEnum(type));
845
+ }
846
+ ens(image) {
847
+ this.checkWasmInitialization("Unable to encrypt the image, cpp API hasn't been initialized");
848
+ return this.utilityApi.ens(image);
849
+ }
850
+ isVirtualCamera(label) {
851
+ this.checkWasmInitialization("Unable to check if the camera is virtual, cpp API hasn't been initialized");
852
+ if (label) return this.utilityApi.isVirtualCamera(label);
853
+ return false;
854
+ }
855
+ estimatePerformance() {
856
+ this.checkWasmInitialization("Unable to estimate performance, cpp API hasn't been initialized");
857
+ return this.utilityApi.estimatePerformance();
858
+ }
859
+ async analyzeFrame(image) {
860
+ this.checkWasmInitialization("Unable to analyze the frame, cpp API hasn't been initialized");
861
+ await this.allocateImageBuffers(image.width, image.height);
862
+ this.inputImageBuffer.set(image.data);
863
+ this.utilityApi.analyzeFrame();
864
+ }
865
+ /**
866
+ * Free allocated memory
867
+ */
868
+ async freeResources() {
869
+ this.versionsFile = null;
870
+ this.modelsBuffers = null;
871
+ this.inputImageBuffer = null;
872
+ this.imageWidth_ = null;
873
+ this.imageHeight_ = null;
874
+ this.pipelines_ = null;
875
+ window.wasmArrayBuffer = null;
876
+ if (this.pipelineApiUtilities && typeof this.pipelineApiUtilities.delete === "function") {
877
+ this.pipelineApiUtilities.delete();
878
+ this.pipelineApiUtilities = null;
879
+ }
880
+ if (this.utilityApi && typeof this.utilityApi.delete === "function") {
881
+ this.utilityApi.delete();
882
+ this.utilityApi = null;
883
+ }
884
+ if (this.idCaptureWasmApi && typeof this.idCaptureWasmApi.delete === "function") {
885
+ this.idCaptureWasmApi.delete();
886
+ this.idCaptureWasmApi = null;
887
+ }
888
+ if (this.faceDetectionWasmApi && typeof this.faceDetectionWasmApi.delete === "function") {
889
+ this.faceDetectionWasmApi.delete();
890
+ this.faceDetectionWasmApi = null;
891
+ }
892
+ this.wasmModule = null;
893
+ this.isInitialized_ = false;
894
+ }
895
+ /**
896
+ * Clear pipeline state
897
+ */
898
+ resetPipeline(type) {
899
+ this.checkWasmInitialization("Unable to reset pipeline, cpp API hasn't been initialized");
900
+ this.pipelineApiUtilities.resetPipeline(this.pipelineTypeToWasmEnum(type));
901
+ }
902
+ /**
903
+ * Clear all pipelines states
904
+ */
905
+ resetAllPipelines() {
906
+ this.checkWasmInitialization("Unable to reset pipelines, cpp API hasn't been initialized");
907
+ for (const [type, model] of this.pipelines_) this.resetPipeline(type);
908
+ }
909
+ /**
910
+ * Clear all states, not related to ml pipelines
911
+ */
912
+ resetOther() {
913
+ this.checkWasmInitialization("Unable to reset other states, cpp API hasn't been initialized");
914
+ this.utilityApi.resetOther();
915
+ }
916
+ /**
917
+ * Full reset
918
+ */
919
+ reset() {
920
+ this.resetAllPipelines();
921
+ this.resetOther();
922
+ }
923
+ /**
924
+ * Process one frame using one of the pipelines
925
+ * @param {ImageData} image - input image
926
+ * @param {WasmPipelineType} type - pipeline type
927
+ * @returns
928
+ */
929
+ async process(image, type) {
930
+ this.checkWasmInitialization("Unable to process the image, cpp API hasn't been initialized");
931
+ if (this.inputImageBuffer === null) throw new Error("Unable to process the image, buffers haven't been allocated!");
932
+ this.inputImageBuffer.set(image.data);
933
+ switch (type) {
934
+ case WasmPipelineType.IdBlurGlarePipeline:
935
+ case WasmPipelineType.IdBarcodeAndTextQualityPipeline: return this.idCaptureWasmApi.runIdCapturePipeline(this.pipelineTypeToWasmEnum(type));
936
+ case WasmPipelineType.IdFaceDetectionPipeline: return this.faceDetectionWasmApi.runIdFaceDetectionPipeline();
937
+ case WasmPipelineType.IdVideoSelfiePipeline: return this.idCaptureWasmApi.runIdVideoSelfiePipeline();
938
+ case WasmPipelineType.SelfieWithAggregationMetrics:
939
+ case WasmPipelineType.SelfieWithQualityMetrics: return this.faceDetectionWasmApi.runSelfieFaceDetectionPipeline(this.pipelineTypeToWasmEnum(type));
940
+ default: throw new Error("Unknown pipeline type");
941
+ }
942
+ }
943
+ async runIdCapture(image) {
944
+ this.checkWasmInitialization("Unable to run Id Capture, cpp API hasn't been initialized");
945
+ if (this.inputImageBuffer === null) throw new Error("Unable to process the image, buffers haven't been allocated!");
946
+ this.inputImageBuffer.set(image.data);
947
+ return this.idCaptureWasmApi.runIdCapture();
948
+ }
949
+ async runSelfieCapture(image) {
950
+ this.checkWasmInitialization("Unable to run Selfie Capture, cpp API hasn't been initialized");
951
+ if (this.inputImageBuffer === null) throw new Error("Unable to process the image, buffers haven't been allocated!");
952
+ this.inputImageBuffer.set(image.data);
953
+ return this.faceDetectionWasmApi.runSelfieCapture();
954
+ }
955
+ async setFacePositionConstraints(type, minX, minY, maxX, maxY) {
956
+ this.checkWasmInitialization("Unable to set face position constraints, cpp API hasn't been initialized");
957
+ this.faceDetectionWasmApi.setFacePositionConstraints(this.pipelineTypeToWasmEnum(type), minX, minY, maxX, maxY);
958
+ }
959
+ async setFaceDetectionThresholds(type, brightnessThreshold, blurrinessThreshold, tiltRotationAngleThreshold, minMagicCropSize, autocaptureInterval, minFaceQualityScore, faceOcclusionThreshold) {
960
+ this.checkWasmInitialization("Unable to set face detection thresholds, cpp API hasn't been initialized");
961
+ this.faceDetectionWasmApi.setFaceDetectionThresholds(this.pipelineTypeToWasmEnum(type), brightnessThreshold, blurrinessThreshold, tiltRotationAngleThreshold, minMagicCropSize, autocaptureInterval, minFaceQualityScore, faceOcclusionThreshold);
962
+ }
963
+ async setFaceAttributesThresholds(type, headwearThreshold, lensesThreshold, closedEyesThreshold, maskThreshold) {
964
+ this.checkWasmInitialization("Unable to set face attributes thresholds, cpp API hasn't been initialized");
965
+ this.faceDetectionWasmApi.setFaceAttributesThresholds(this.pipelineTypeToWasmEnum(type), headwearThreshold, lensesThreshold, closedEyesThreshold, maskThreshold);
966
+ }
967
+ async setFaceChecksEnabled(type, isLensesCheckEnabled, isMaskCheckEnabled, isClosedEyesCheckEnabled, isHeadWearCheckEnabled, isOcclusionCheckEnabled) {
968
+ this.checkWasmInitialization("Unable to set face checks enabled flags, cpp API hasn't been initialized");
969
+ this.faceDetectionWasmApi.setFaceChecksEnabled(this.pipelineTypeToWasmEnum(type), isLensesCheckEnabled, isMaskCheckEnabled, isClosedEyesCheckEnabled, isHeadWearCheckEnabled, isOcclusionCheckEnabled);
970
+ }
971
+ async setFaceDetectionMode(type, isVideoSelfie) {
972
+ this.checkWasmInitialization("Unable to set face detection mode, cpp API hasn't been initialized");
973
+ this.faceDetectionWasmApi.setFaceDetectionMode(this.pipelineTypeToWasmEnum(type), isVideoSelfie);
974
+ }
975
+ async setFaceDetectionCallbacks(type, onFarAway, onTooClose, onTooManyFaces, onNoFace, onCapture, onGetReady, onGetReadyFinished, onCenterFace, onDark, onBlur, onFaceAngle, onBestShot, onLenses, onMask, onEyesClosed, onHeadWear, onSwitchToManualCapture, onFaceOccluded) {
976
+ this.checkWasmInitialization("Unable to set face detection callbacks, cpp API hasn't been initialized");
977
+ this.faceDetectionWasmApi.setFaceDetectionCallbacks(this.pipelineTypeToWasmEnum(type), onFarAway, onTooClose, onTooManyFaces, onNoFace, onCapture, onGetReady, onGetReadyFinished, onCenterFace, onDark, onBlur, onFaceAngle, onBestShot, onLenses, onMask, onEyesClosed, onHeadWear, onSwitchToManualCapture, onFaceOccluded);
978
+ }
979
+ async setIdCaptureThresholds(type, blurThreshold, blurChangeThreshold, glareThreshold, clsThreshold, sideThreshold, iouThreshold, idDetectedTimeout, autocaptureTimeout, framesAggregationInterval, minFaceIdQualityScore) {
980
+ this.checkWasmInitialization("Unable to set thresholds, cpp API hasn't been initialized");
981
+ this.idCaptureWasmApi.setIdCaptureThresholds(this.pipelineTypeToWasmEnum(type), blurThreshold, blurChangeThreshold, glareThreshold, clsThreshold, sideThreshold, iouThreshold, idDetectedTimeout, autocaptureTimeout, framesAggregationInterval, minFaceIdQualityScore);
982
+ }
983
+ async setIdCaptureCallbacks(type, onFarAway, onDetectionStarted, onMaskChange, onBlur, onGlare, onCapturing, onCapture, onBestFrame, onIDNotDetected, onSwitchToManualCapture, onIDTypeChange, onIDSideChange, onCapturingCounterValueChange) {
984
+ this.checkWasmInitialization("Unable to set callbacks, cpp API hasn't been initialized");
985
+ this.idCaptureWasmApi.setIdCaptureCallbacks(this.pipelineTypeToWasmEnum(type), onFarAway, onDetectionStarted, onMaskChange, onBlur, onGlare, onCapturing, onCapture, onBestFrame, onIDNotDetected, onSwitchToManualCapture, onIDTypeChange, onIDSideChange, onCapturingCounterValueChange);
986
+ }
987
+ async setIdCaptureGeometryParams(type, areaDown, areaUp, areaIOSPassportUp, areaIOSPassportDown, widthIOSUp, widthIOSDown, widthDown, widthUp, windowOuterWidth, windowOuterHeight, windowInnerWidth, windowInnerHeight) {
988
+ this.checkWasmInitialization("Unable to set geometry params, cpp API hasn't been initialized");
989
+ this.idCaptureWasmApi.setIdCaptureGeometryParams(this.pipelineTypeToWasmEnum(type), areaDown, areaUp, areaIOSPassportUp, areaIOSPassportDown, widthIOSUp, widthIOSDown, widthDown, widthUp, windowOuterWidth, windowOuterHeight, windowInnerWidth, windowInnerHeight);
990
+ }
991
+ async setIdCaptureConfigParams(type, isFixedMask, isIPhone14OrHigher, idType, isBlurCheckEnabled, isGlareCheckEnabled, isIdFaceQualityCheckEnabled, isIouCheckEnabled) {
992
+ this.checkWasmInitialization("Unable to set config params, cpp API hasn't been initialized");
993
+ this.idCaptureWasmApi.setIdCaptureConfigParams(this.pipelineTypeToWasmEnum(type), isFixedMask, isIPhone14OrHigher, idType, isBlurCheckEnabled, isGlareCheckEnabled, isIdFaceQualityCheckEnabled, isIouCheckEnabled);
994
+ }
995
+ setIdCaptureModelType(pipelineType, modelType) {
996
+ this.checkWasmInitialization("Unable to set model type, cpp API hasn't been initialized");
997
+ this.idCaptureWasmApi.setIdCaptureModelType(this.pipelineTypeToWasmEnum(pipelineType), this.IdCaptureModelTypeToWasmEnum(modelType));
998
+ }
999
+ IdPerspectiveTransform(image, frameRect) {
1000
+ this.checkWasmInitialization("Unable to perform perspective transform, cpp API hasn't been initialized");
1001
+ return this.idCaptureWasmApi.IdPerspectiveTransform(image, frameRect);
1002
+ }
1003
+ async getVersions() {
1004
+ const text = await (await fetch(this.versionsFile)).text();
1005
+ return JSON.parse(text);
1006
+ }
1007
+ async loadWasm(useSimd, webLibPath, webLibPathSimd) {
1008
+ const libPath = useSimd ? webLibPathSimd : webLibPath;
1009
+ try {
1010
+ window.wasmArrayBuffer = await fetch(libPath).then((response) => response.arrayBuffer()).then((buffer) => new Uint8Array(buffer));
1011
+ this.wasmModule = await this.Module();
1012
+ } catch (e) {
1013
+ console.log(e, useSimd, "useSmd");
1014
+ if (useSimd) return await this.loadWasm(false, webLibPath, webLibPathSimd);
1015
+ else throw e;
1016
+ }
1017
+ return useSimd;
1018
+ }
1019
+ async loadModels() {
1020
+ this.checkWasmInitialization("Unable load the models, cpp API hasn't been initialized");
1021
+ const buffSizes = new this.wasmModule.PipelineTypeToIntMap();
1022
+ const modelData = /* @__PURE__ */ new Map();
1023
+ const loadedModels = /* @__PURE__ */ new Map();
1024
+ for (const [type, modelsPaths] of this.pipelines_) {
1025
+ const wasmType = this.pipelineTypeToWasmEnum(type);
1026
+ const pipelineBuffers = [];
1027
+ const sizes = new this.wasmModule.VectorInt();
1028
+ for (const path of modelsPaths) {
1029
+ if (!loadedModels.has(path)) {
1030
+ const model$1 = await fetch(path).then((response) => response.arrayBuffer()).then((buffer) => new Uint8Array(buffer));
1031
+ loadedModels.set(path, model$1);
1032
+ }
1033
+ const model = loadedModels.get(path);
1034
+ sizes.push_back(model.byteLength);
1035
+ pipelineBuffers.push(model);
1036
+ }
1037
+ buffSizes.set(wasmType, sizes);
1038
+ modelData.set(wasmType, pipelineBuffers);
1039
+ }
1040
+ this.modelsBuffers = this.pipelineApiUtilities.allocateModelsBuffers(buffSizes);
1041
+ for (const [type, data] of modelData) {
1042
+ const buffers = this.modelsBuffers?.get(type);
1043
+ for (let k = 0; k < buffers.size(); k++) {
1044
+ const buffer = buffers?.get(k);
1045
+ if (buffer) buffer.set(data[k]);
1046
+ else throw new Error("Unable to get model buffer from shared memory!");
1047
+ }
1048
+ }
1049
+ }
1050
+ async initializePipelines() {
1051
+ this.checkWasmInitialization("Unable to initialize pipelines, cpp API hasn't been initialized");
1052
+ if (!this.modelsBuffers) await this.loadModels();
1053
+ this.pipelineApiUtilities.initializePipelines();
1054
+ }
1055
+ async setProductionMode(productionMode) {
1056
+ this.checkWasmInitialization("Unable to set production mode, cpp API hasn't been initialized");
1057
+ this.utilityApi.setProductionMode(productionMode);
1058
+ }
1059
+ getPipelineState() {
1060
+ this.checkWasmInitialization("Unable to get pipeline state, cpp API hasn't been initialized");
1061
+ return this.pipelineApiUtilities.getPipelineState();
1062
+ }
1063
+ getCurrentPipeline() {
1064
+ this.checkWasmInitialization("Unable to get current pipeline, cpp API hasn't been initialized");
1065
+ return this.pipelineTypeFromWasmEnum(this.pipelineApiUtilities.getCurrentPipeline());
1066
+ }
1067
+ setSdkVersion(sdkVersion) {
1068
+ this.checkWasmInitialization("Unable to set sdk version, cpp API hasn't been initialized");
1069
+ this.utilityApi.setSdkVersion(sdkVersion);
1070
+ }
1071
+ setSdkPlatform(sdkPlatform) {
1072
+ this.checkWasmInitialization("Unable to set device type, cpp API hasn't been initialized");
1073
+ this.utilityApi.setSdkPlatform(sdkPlatform);
1074
+ }
1075
+ setDeviceInfo(deviceInfo, overrideExisting = true) {
1076
+ this.checkWasmInitialization("Unable to set device info, cpp API hasn't been initialized");
1077
+ this.utilityApi.setDeviceInfo(deviceInfo, overrideExisting);
1078
+ }
1079
+ setBrowserInfo(browserInfo, overrideExisting = true) {
1080
+ this.checkWasmInitialization("Unable to set browser info, cpp API hasn't been initialized");
1081
+ this.utilityApi.setBrowserInfo(browserInfo, overrideExisting);
1082
+ }
1083
+ setCameraInfo(cameraInfo, overrideExisting = true) {
1084
+ this.checkWasmInitialization("Unable to set camera info, cpp API hasn't been initialized");
1085
+ this.utilityApi.setCameraInfo(cameraInfo, overrideExisting);
1086
+ }
1087
+ setZc(zc) {
1088
+ this.checkWasmInitialization("Unable to set zc, cpp API hasn't been initialized");
1089
+ this.utilityApi.setZc(zc);
1090
+ }
1091
+ setMotionStatus(motionStatus) {
1092
+ this.checkWasmInitialization("Unable to set motion status, cpp API hasn't been initialized");
1093
+ this.utilityApi.setMotionStatus(motionStatus);
1094
+ }
1095
+ setMetadataField(key, value) {
1096
+ this.checkWasmInitialization("Unable to set metadata field, cpp API hasn't been initialized");
1097
+ this.utilityApi.setMetadataField(key, value);
1098
+ }
1099
+ setInspectorOpened(inspectorOpened) {
1100
+ this.inspectorOpened_ = inspectorOpened;
1101
+ }
1102
+ setBackgroundMode(backgroundMode) {
1103
+ this.checkWasmInitialization("Unable to set background mode, cpp API hasn't been initialized");
1104
+ this.utilityApi.setBackgroundMode(backgroundMode);
1105
+ }
1106
+ getCheck() {
1107
+ this.checkWasmInitialization("Unable to get check, cpp API hasn't been initialized");
1108
+ return this.utilityApi.getCheck();
1109
+ }
1110
+ getMetadata() {
1111
+ this.checkWasmInitialization("Unable to get metadata, cpp API hasn't been initialized");
1112
+ this.utilityApi.setInspectorOpened(this.inspectorOpened_);
1113
+ return this.utilityApi.getMetadata();
1114
+ }
1115
+ async prc() {
1116
+ this.checkWasmInitialization("Unable to prc, cpp API hasn't been initialized");
1117
+ return await this.wasmCallWrapper(this.utilityApi.prc.bind(this.utilityApi), []);
1118
+ }
1119
+ async poc(output) {
1120
+ this.checkWasmInitialization("Unable to poc, cpp API hasn't been initialized");
1121
+ await this.wasmCallWrapper(this.utilityApi.poc.bind(this.utilityApi), [output]);
1122
+ }
1123
+ async pc(deviceId) {
1124
+ this.checkWasmInitialization("Unable to pc, cpp API hasn't been initialized");
1125
+ await this.wasmCallWrapper(this.utilityApi.pc.bind(this.utilityApi), [deviceId]);
1126
+ }
1127
+ pipelineTypeToWasmEnum(type) {
1128
+ switch (type) {
1129
+ case WasmPipelineType.IdBlurGlarePipeline: return this.wasmModule.PipelineType.IdBlurGlarePipeline;
1130
+ case WasmPipelineType.IdBarcodeAndTextQualityPipeline: return this.wasmModule.PipelineType.IdBarcodeAndTextQualityPipeline;
1131
+ case WasmPipelineType.IdFaceDetectionPipeline: return this.wasmModule.PipelineType.IdFaceDetectionPipeline;
1132
+ case WasmPipelineType.IdVideoSelfiePipeline: return this.wasmModule.PipelineType.IdVideoSelfiePipeline;
1133
+ case WasmPipelineType.SelfieWithAggregationMetrics: return this.wasmModule.PipelineType.SelfieWithAggregationMetrics;
1134
+ case WasmPipelineType.SelfieWithQualityMetrics: return this.wasmModule.PipelineType.SelfieWithQualityMetrics;
1135
+ default: throw new Error("Unknown pipeline type");
1136
+ }
1137
+ }
1138
+ pipelineTypeFromWasmEnum(type) {
1139
+ switch (type) {
1140
+ case this.wasmModule.PipelineType.IdBlurGlarePipeline: return WasmPipelineType.IdBlurGlarePipeline;
1141
+ case this.wasmModule.IdBarcodeAndTextQualityPipeline: return WasmPipelineType.IdBarcodeAndTextQualityPipeline;
1142
+ case this.wasmModule.PipelineType.IdFaceDetectionPipeline: return WasmPipelineType.IdFaceDetectionPipeline;
1143
+ case this.wasmModule.PipelineType.IdVideoSelfiePipeline: return WasmPipelineType.IdVideoSelfiePipeline;
1144
+ case this.wasmModule.PipelineType.SelfieWithAggregationMetrics: return WasmPipelineType.SelfieWithAggregationMetrics;
1145
+ case this.wasmModule.PipelineType.SelfieWithQualityMetrics: return WasmPipelineType.SelfieWithQualityMetrics;
1146
+ default: throw new Error("Unknown pipeline type");
1147
+ }
1148
+ }
1149
+ IdCaptureModelTypeToWasmEnum(type) {
1150
+ switch (type) {
1151
+ case IdCaptureModelType.IdCaptureV1x: return this.wasmModule.IdCaptureModelType.IdCaptureV1x;
1152
+ case IdCaptureModelType.IdCaptureV2x: return this.wasmModule.IdCaptureModelType.IdCaptureV2x;
1153
+ case IdCaptureModelType.IdCaptureV3x: return this.wasmModule.IdCaptureModelType.IdCaptureV3x;
1154
+ default: throw new Error("Unknown Id Capture model type");
1155
+ }
1156
+ }
1157
+ IdCaptureModelTypeFromWasmEnum(type) {
1158
+ switch (type) {
1159
+ case this.wasmModule.IdCaptureModelType.IdCaptureV1x: return IdCaptureModelType.IdCaptureV1x;
1160
+ case this.wasmModule.IdCaptureModelType.IdCaptureV2x: return IdCaptureModelType.IdCaptureV2x;
1161
+ case this.wasmModule.IdCaptureModelType.IdCaptureV3x: return IdCaptureModelType.IdCaptureV3x;
1162
+ default: throw new Error("Unknown Id Capture model type");
1163
+ }
1164
+ }
1165
+ checkWasmInitialization(message) {
1166
+ if (!this.isInitialized()) throw new Error(message);
1167
+ }
1168
+ async wasmCallWrapper(wasmMethod, args = []) {
1169
+ return await this.wasmCallMutex.withLock(async (...args$1) => {
1170
+ let isFinished = false;
1171
+ try {
1172
+ while (true) {
1173
+ isFinished = wasmMethod(...args$1);
1174
+ if (isFinished) return;
1175
+ await new Promise((resolve) => setTimeout(resolve, 0));
1176
+ }
1177
+ } catch (e) {
1178
+ console.log("Error in wasmCallWrapper:", e);
1179
+ }
1180
+ }, ...args);
1181
+ }
1182
+ };
1183
+ var mlWasmJSApi_default = MlWasmJSApi.getInstance();
1184
+
1185
+ //#endregion
1186
+ //#region ../infra/src/wasm/warmup.ts
1187
+ /** Array of all available pipelines */
1188
+ const WASM_PIPELINES = ["selfie", "idCapture"];
1189
+ /**
1190
+ * Default model files for each pipeline.
1191
+ * These are the ONNX model files required by each ML pipeline.
1192
+ */
1193
+ const DEFAULT_PIPELINE_MODELS = {
1194
+ selfie: [
1195
+ "selfie_bf_angles_192x192_opset9_fp16.ortmodelv2",
1196
+ "face_attributes_v1_3_fp16.ortmodelv2",
1197
+ "mls_regressor_4773007c657b4f05a460321456740d0f_fp16.ortmodelv2",
1198
+ "face_occlusion_v0_1_fp16.ortmodelv2"
1199
+ ],
1200
+ idCapture: ["id_capture_2_01_fp16.ortmodelv2", "id_fiqa_19a81a0b9bf6492eb03b4667f6db4c85_fp16.ortmodelv2"]
1201
+ };
1202
+ let state = "idle";
1203
+ let loadingPromise = null;
1204
+ let wasmError = null;
1205
+ let loadedPipelines = [];
1206
+ let lastConfig = null;
1207
+ function mapPipelineToWasmType(pipeline) {
1208
+ switch (pipeline) {
1209
+ case "selfie": return WasmPipelineType.SelfieWithQualityMetrics;
1210
+ case "idCapture": return WasmPipelineType.IdBlurGlarePipeline;
1211
+ default: throw new Error(`Unknown pipeline: ${pipeline}`);
1212
+ }
1213
+ }
1214
+ /**
1215
+ * Derives the models base path from the WASM path.
1216
+ * Assumes models are in a 'models' subdirectory relative to the WASM binary location.
1217
+ * e.g., '/wasm/v2/binary.wasm' -> '/wasm/v2/models'
1218
+ */
1219
+ function deriveModelsBasePath(wasmPath) {
1220
+ const lastSlashIndex = wasmPath.lastIndexOf("/");
1221
+ if (lastSlashIndex === -1) return "models";
1222
+ return `${wasmPath.substring(0, lastSlashIndex)}/models`;
1223
+ }
1224
+ /**
1225
+ * Builds the pipelines map with model paths for WASM initialization.
1226
+ * @param pipelines - Array of pipeline types to initialize
1227
+ * @param modelsBasePath - Base path where model files are located
1228
+ * @param customModels - Optional custom model files per pipeline
1229
+ */
1230
+ function buildPipelinesMap(pipelines, modelsBasePath, customModels) {
1231
+ const pipelinesMap = /* @__PURE__ */ new Map();
1232
+ for (const pipeline of pipelines) {
1233
+ const wasmType = mapPipelineToWasmType(pipeline);
1234
+ if (!pipelinesMap.has(wasmType)) {
1235
+ const modelPaths = (customModels?.[pipeline] ?? DEFAULT_PIPELINE_MODELS[pipeline]).map((modelFile) => `${modelsBasePath}/${modelFile}`);
1236
+ pipelinesMap.set(wasmType, modelPaths);
1237
+ }
1238
+ }
1239
+ return pipelinesMap;
1240
+ }
1241
+ /**
1242
+ * Preloads WASM binary and ML models at app startup.
1243
+ * Runs asynchronously - app can continue while WASM loads in background.
1244
+ *
1245
+ * Model files are automatically loaded based on the pipeline type.
1246
+ * By default, models are expected in a 'models' subdirectory relative to the WASM binary.
1247
+ *
1248
+ * @param config - Configuration for WASM warmup
1249
+ * @returns Promise that resolves when WASM is ready
1250
+ *
1251
+ * @example
1252
+ * ```ts
1253
+ * // Basic usage - models loaded from /wasm/v2/models/
1254
+ * warmupWasm({
1255
+ * wasmPath: '/wasm/v2/ml-wasm.wasm',
1256
+ * glueCodePath: '/wasm/v2/ml-wasm.js',
1257
+ * pipelines: ['selfie', 'idCapture'],
1258
+ * });
1259
+ *
1260
+ * // With explicit models path
1261
+ * warmupWasm({
1262
+ * wasmPath: '/wasm/v2/ml-wasm.wasm',
1263
+ * glueCodePath: '/wasm/v2/ml-wasm.js',
1264
+ * modelsBasePath: 'https://cdn.example.com/wasm/v2/models',
1265
+ * pipelines: ['selfie'],
1266
+ * });
1267
+ * ```
1268
+ */
1269
+ async function warmupWasm(config) {
1270
+ const pipelines = config.pipelines ?? [...WASM_PIPELINES];
1271
+ const modelsBasePath = config.modelsBasePath ?? deriveModelsBasePath(config.wasmPath);
1272
+ if (state === "loading" && loadingPromise) return loadingPromise;
1273
+ if (state === "ready") {
1274
+ if (pipelines.filter((p) => !loadedPipelines.includes(p)).length === 0) return;
1275
+ if (!lastConfig) throw new Error("Cannot add pipelines: original warmup config not available");
1276
+ if (lastConfig.wasmPath !== config.wasmPath || lastConfig.glueCodePath !== config.glueCodePath || (lastConfig.wasmSimdPath ?? lastConfig.wasmPath) !== (config.wasmSimdPath ?? config.wasmPath) || (lastConfig.useSimd ?? true) !== (config.useSimd ?? true)) throw new Error("Cannot add pipelines: WASM config mismatch. Use same wasmPath, glueCodePath, and useSimd settings.");
1277
+ const combinedPipelines = [...new Set([...loadedPipelines, ...pipelines])];
1278
+ state = "loading";
1279
+ wasmError = null;
1280
+ loadingPromise = (async () => {
1281
+ try {
1282
+ const pipelinesMap = buildPipelinesMap(combinedPipelines, lastConfig.modelsBasePath ?? deriveModelsBasePath(lastConfig.wasmPath), lastConfig.pipelineModels);
1283
+ await mlWasmJSApi_default.initialize(lastConfig.wasmPath, lastConfig.wasmSimdPath ?? lastConfig.wasmPath, lastConfig.glueCodePath, lastConfig.useSimd ?? true, "", pipelinesMap);
1284
+ await mlWasmJSApi_default.loadModels();
1285
+ await mlWasmJSApi_default.initializePipelines();
1286
+ state = "ready";
1287
+ loadedPipelines = combinedPipelines;
1288
+ lastConfig = {
1289
+ ...lastConfig,
1290
+ pipelines: combinedPipelines
1291
+ };
1292
+ loadingPromise = null;
1293
+ } catch (error) {
1294
+ state = "error";
1295
+ wasmError = error instanceof Error ? error : new Error(String(error));
1296
+ loadingPromise = null;
1297
+ throw wasmError;
1298
+ }
1299
+ })();
1300
+ return loadingPromise;
1301
+ }
1302
+ state = "loading";
1303
+ wasmError = null;
1304
+ loadingPromise = (async () => {
1305
+ try {
1306
+ const pipelinesMap = buildPipelinesMap(pipelines, modelsBasePath, config.pipelineModels);
1307
+ await mlWasmJSApi_default.initialize(config.wasmPath, config.wasmSimdPath ?? config.wasmPath, config.glueCodePath, config.useSimd ?? true, "", pipelinesMap);
1308
+ await mlWasmJSApi_default.loadModels();
1309
+ await mlWasmJSApi_default.initializePipelines();
1310
+ state = "ready";
1311
+ loadedPipelines = [...pipelines];
1312
+ lastConfig = {
1313
+ ...config,
1314
+ pipelines
1315
+ };
1316
+ loadingPromise = null;
1317
+ } catch (error) {
1318
+ state = "error";
1319
+ wasmError = error instanceof Error ? error : new Error(String(error));
1320
+ loadingPromise = null;
1321
+ throw wasmError;
1322
+ }
1323
+ })();
1324
+ return loadingPromise;
1325
+ }
1326
+ /**
1327
+ * Returns the current warmup status.
1328
+ * Useful for showing loading indicators.
1329
+ *
1330
+ * @returns Current warmup status
1331
+ */
1332
+ function getWasmStatus() {
1333
+ return {
1334
+ isReady: state === "ready",
1335
+ isLoading: state === "loading",
1336
+ error: wasmError ?? void 0,
1337
+ loadedPipelines: [...loadedPipelines]
1338
+ };
1339
+ }
1340
+ /**
1341
+ * Returns true if WASM is fully initialized and ready.
1342
+ *
1343
+ * @returns True if WASM is ready
1344
+ */
1345
+ function isWasmReady() {
1346
+ return state === "ready";
1347
+ }
1348
+ /**
1349
+ * Returns a promise that resolves when WASM is ready.
1350
+ * - If ready: resolves immediately
1351
+ * - If loading: waits for completion, then resolves
1352
+ * - If not started: rejects with error
1353
+ *
1354
+ * @returns Promise that resolves when WASM is ready
1355
+ * @throws Error if WASM is in error state or was never started
1356
+ */
1357
+ function waitForWasm() {
1358
+ if (state === "ready") return Promise.resolve();
1359
+ if (state === "loading" && loadingPromise) return loadingPromise;
1360
+ if (state === "error") return Promise.reject(wasmError ?? /* @__PURE__ */ new Error("WASM initialization failed"));
1361
+ return Promise.reject(/* @__PURE__ */ new Error("WASM warmup was not started. Call warmupWasm() first."));
1362
+ }
1363
+
1364
+ //#endregion
1365
+ //#region ../infra/src/providers/wasm/BaseWasmProvider.ts
1366
+ /**
1367
+ * Base provider class that abstracts common WASM functionality.
1368
+ * This serves as a foundation for specific ML capability providers
1369
+ * like FaceDetectionProvider and IdCaptureProvider.
1370
+ */
1371
+ var BaseWasmProvider = class {
1372
+ /**
1373
+ * Creates a new BaseWasmProvider
1374
+ * @param pipelineType - The WASM pipeline type this provider uses
1375
+ */
1376
+ constructor(pipelineType) {
1377
+ this._isInitialized = false;
1378
+ this.pipelineType = pipelineType;
1379
+ }
1380
+ /**
1381
+ * Returns whether this provider has been initialized.
1382
+ */
1383
+ get initialized() {
1384
+ return this._isInitialized;
1385
+ }
1386
+ getPipelineType() {
1387
+ if (this.pipelineType === void 0) throw new Error(`${this.constructor.name} has no pipeline type configured.`);
1388
+ return this.pipelineType;
1389
+ }
1390
+ /**
1391
+ * Initializes the provider by ensuring WASM is loaded
1392
+ * @param config - Provider configuration
1393
+ * @param pipeline - The pipeline type to warm up ('selfie', 'idCapture', etc.)
1394
+ */
1395
+ async initializeBase(config, pipeline) {
1396
+ if (this._isInitialized) return;
1397
+ if (getWasmStatus().isLoading || isWasmReady()) await waitForWasm();
1398
+ else {
1399
+ if (!config.wasmPath || !config.glueCodePath) throw new Error("WASM path and glue code path are required. Call warmupWasm() first.");
1400
+ await warmupWasm({
1401
+ wasmPath: config.wasmPath,
1402
+ wasmSimdPath: config.wasmSimdPath,
1403
+ glueCodePath: config.glueCodePath,
1404
+ useSimd: config.useSimd,
1405
+ modelsBasePath: config.modelsBasePath,
1406
+ pipelines: [pipeline]
1407
+ });
1408
+ }
1409
+ this._isInitialized = true;
1410
+ }
1411
+ /**
1412
+ * Ensures the provider is initialized before performing operations.
1413
+ * @throws Error if not initialized
1414
+ */
1415
+ ensureInitialized() {
1416
+ if (!this._isInitialized) throw new Error(`${this.constructor.name} not initialized. Call initialize() first.`);
1417
+ }
1418
+ /**
1419
+ * Processes a frame through the WASM pipeline
1420
+ * @param image - Image data to process
1421
+ */
1422
+ async processFrame(image) {
1423
+ this.ensureInitialized();
1424
+ const pipelineType = this.getPipelineType();
1425
+ await mlWasmJSApi_default.allocateImageBuffers(image.width, image.height);
1426
+ await mlWasmJSApi_default.process(image, pipelineType);
1427
+ }
1428
+ /**
1429
+ * Resets the pipeline to its initial state.
1430
+ * Safe to call even if not initialized (no-op in that case).
1431
+ */
1432
+ reset() {
1433
+ if (this._isInitialized && this.pipelineType !== void 0) mlWasmJSApi_default.resetPipeline(this.pipelineType);
1434
+ }
1435
+ /**
1436
+ * Disposes of resources and resets initialization state.
1437
+ * Safe to call even if not initialized.
1438
+ */
1439
+ async dispose() {
1440
+ this.reset();
1441
+ this._isInitialized = false;
1442
+ }
1443
+ };
1444
+
1445
+ //#endregion
1446
+ //#region ../infra/src/providers/wasm/FaceDetectionProvider.ts
1447
+ var FaceDetectionProvider = class extends BaseWasmProvider {
1448
+ constructor() {
1449
+ super(WasmPipelineType.SelfieWithQualityMetrics);
1450
+ this.defaultThresholds = {
1451
+ frameMinX: 0,
1452
+ frameMinY: 0,
1453
+ frameMaxX: 1,
1454
+ frameMaxY: 1,
1455
+ brightnessThreshold: 50,
1456
+ blurrinessThreshold: 50,
1457
+ tiltRotationAngleThreshold: 15,
1458
+ minMagicCropSize: 200,
1459
+ headwearThreshold: .86,
1460
+ lensesThreshold: .95,
1461
+ closedEyesThreshold: .9,
1462
+ maskThreshold: .85,
1463
+ minFaceQualityScore: .63,
1464
+ faceOcclusionThreshold: .3
1465
+ };
1466
+ this.currentFrame = null;
1467
+ this.bestCanvas = null;
1468
+ this.bestFace = null;
1469
+ }
1470
+ async processFrame(image) {
1471
+ this.currentFrame = image;
1472
+ await super.processFrame(image);
1473
+ }
1474
+ async initialize(config) {
1475
+ await this.initializeBase(config, "selfie");
1476
+ this.applyDefaults(config.autocaptureInterval ?? 0);
1477
+ }
1478
+ setCallbacks(callbacks) {
1479
+ this.ensureInitialized();
1480
+ const onBestShotWrapper = (face) => {
1481
+ this.bestFace = face;
1482
+ if (this.currentFrame) {
1483
+ const frameCanvas = IncodeCanvas.fromImageData(this.currentFrame);
1484
+ this.bestCanvas = frameCanvas.clone() ?? frameCanvas;
1485
+ }
1486
+ callbacks.onBestShot?.(face);
1487
+ };
1488
+ const onCaptureWrapper = () => {
1489
+ let frameCanvas = this.bestCanvas;
1490
+ if (!frameCanvas && this.currentFrame) frameCanvas = IncodeCanvas.fromImageData(this.currentFrame);
1491
+ if (!frameCanvas) return;
1492
+ const faceCoordinates = this.bestFace ? this.formatFaceCoordinates(this.bestFace) : this.createDefaultFaceCoordinates(frameCanvas);
1493
+ try {
1494
+ frameCanvas.updateBase64Image();
1495
+ frameCanvas.updateBlob();
1496
+ } catch {}
1497
+ callbacks.onCapture?.(frameCanvas, faceCoordinates);
1498
+ this.bestCanvas = null;
1499
+ this.bestFace = null;
1500
+ };
1501
+ mlWasmJSApi_default.setFaceDetectionCallbacks(this.getPipelineType(), callbacks.onFarAway ?? (() => {}), callbacks.onTooClose ?? (() => {}), callbacks.onTooManyFaces ?? (() => {}), callbacks.onNoFace ?? (() => {}), onCaptureWrapper, callbacks.onGetReady ?? (() => {}), callbacks.onGetReadyFinished ?? (() => {}), callbacks.onCenterFace ?? (() => {}), callbacks.onDark ?? (() => {}), callbacks.onBlur ?? (() => {}), callbacks.onFaceAngle ?? (() => {}), onBestShotWrapper, callbacks.onLenses ?? (() => {}), callbacks.onMask ?? (() => {}), callbacks.onEyesClosed ?? (() => {}), callbacks.onHeadWear ?? (() => {}), callbacks.onSwitchToManualCapture ?? (() => {}), callbacks.onFaceOccluded ?? (() => {}));
1502
+ }
1503
+ setPositionConstraints(constraints) {
1504
+ this.ensureInitialized();
1505
+ mlWasmJSApi_default.setFacePositionConstraints(this.getPipelineType(), constraints.minX, constraints.minY, constraints.maxX, constraints.maxY);
1506
+ }
1507
+ applyDefaults(autocaptureInterval = 0) {
1508
+ this.ensureInitialized();
1509
+ this.setThresholds({
1510
+ brightnessThreshold: this.defaultThresholds.brightnessThreshold,
1511
+ blurrinessThreshold: this.defaultThresholds.blurrinessThreshold,
1512
+ tiltRotationAngleThreshold: this.defaultThresholds.tiltRotationAngleThreshold,
1513
+ minMagicCropSize: this.defaultThresholds.minMagicCropSize,
1514
+ autocaptureInterval,
1515
+ minFaceQualityScore: this.defaultThresholds.minFaceQualityScore,
1516
+ faceOcclusionThreshold: this.defaultThresholds.faceOcclusionThreshold
1517
+ });
1518
+ this.setPositionConstraints({
1519
+ minX: this.defaultThresholds.frameMinX,
1520
+ minY: this.defaultThresholds.frameMinY,
1521
+ maxX: this.defaultThresholds.frameMaxX,
1522
+ maxY: this.defaultThresholds.frameMaxY
1523
+ });
1524
+ this.setAttributesThresholds({
1525
+ headwearThreshold: this.defaultThresholds.headwearThreshold,
1526
+ lensesThreshold: this.defaultThresholds.lensesThreshold,
1527
+ closedEyesThreshold: this.defaultThresholds.closedEyesThreshold,
1528
+ maskThreshold: this.defaultThresholds.maskThreshold
1529
+ });
1530
+ }
1531
+ setAutocaptureInterval(interval) {
1532
+ this.ensureInitialized();
1533
+ if (!this.currentThresholds) {
1534
+ this.applyDefaults(interval);
1535
+ return;
1536
+ }
1537
+ this.setThresholds({
1538
+ ...this.currentThresholds,
1539
+ autocaptureInterval: interval
1540
+ });
1541
+ }
1542
+ setThresholds(thresholds) {
1543
+ this.ensureInitialized();
1544
+ this.currentThresholds = { ...thresholds };
1545
+ mlWasmJSApi_default.setFaceDetectionThresholds(this.getPipelineType(), thresholds.brightnessThreshold, thresholds.blurrinessThreshold, thresholds.tiltRotationAngleThreshold, thresholds.minMagicCropSize, thresholds.autocaptureInterval, thresholds.minFaceQualityScore, thresholds.faceOcclusionThreshold);
1546
+ }
1547
+ setAttributesThresholds(thresholds) {
1548
+ this.ensureInitialized();
1549
+ mlWasmJSApi_default.setFaceAttributesThresholds(this.getPipelineType(), thresholds.headwearThreshold, thresholds.lensesThreshold, thresholds.closedEyesThreshold, thresholds.maskThreshold);
1550
+ }
1551
+ setChecksEnabled(config) {
1552
+ this.ensureInitialized();
1553
+ mlWasmJSApi_default.setFaceChecksEnabled(this.getPipelineType(), config.lenses, config.mask, config.closedEyes, config.headWear, config.occlusion);
1554
+ }
1555
+ setVideoSelfieMode(enabled) {
1556
+ this.ensureInitialized();
1557
+ mlWasmJSApi_default.setFaceDetectionMode(this.getPipelineType(), enabled);
1558
+ }
1559
+ reset() {
1560
+ super.reset();
1561
+ this.currentFrame = null;
1562
+ this.bestCanvas = null;
1563
+ this.bestFace = null;
1564
+ }
1565
+ createDefaultFaceCoordinates(canvas) {
1566
+ return {
1567
+ rightEyeX: 0,
1568
+ rightEyeY: 0,
1569
+ leftEyeX: 0,
1570
+ leftEyeY: 0,
1571
+ noseTipX: 0,
1572
+ noseTipY: 0,
1573
+ rightMouthX: 0,
1574
+ rightMouthY: 0,
1575
+ mouthX: 0,
1576
+ mouthY: 0,
1577
+ x: 0,
1578
+ y: 0,
1579
+ width: canvas.width() ?? 0,
1580
+ height: canvas.height() ?? 0
1581
+ };
1582
+ }
1583
+ formatFaceCoordinates(face) {
1584
+ return {
1585
+ rightEyeX: face.rightEye.x,
1586
+ rightEyeY: face.rightEye.y,
1587
+ leftEyeX: face.leftEye.x,
1588
+ leftEyeY: face.leftEye.y,
1589
+ noseTipX: face.noseTip.x,
1590
+ noseTipY: face.noseTip.y,
1591
+ rightMouthX: face.rightMouthCorner.x,
1592
+ rightMouthY: face.rightMouthCorner.y,
1593
+ mouthX: face.leftMouthCorner.x,
1594
+ mouthY: face.leftMouthCorner.y,
1595
+ x: face.rect.x,
1596
+ y: face.rect.y,
1597
+ width: face.rect.width,
1598
+ height: face.rect.height
1599
+ };
1600
+ }
1601
+ };
1602
+
1603
+ //#endregion
1604
+ //#region ../infra/src/providers/wasm/WasmUtilProvider.ts
1605
+ var WasmUtilProvider = class WasmUtilProvider extends BaseWasmProvider {
1606
+ static async getInstance() {
1607
+ if (WasmUtilProvider.instance) return WasmUtilProvider.instance;
1608
+ if (WasmUtilProvider.initPromise) return WasmUtilProvider.initPromise;
1609
+ WasmUtilProvider.initPromise = (async () => {
1610
+ const instance = new WasmUtilProvider();
1611
+ await instance.initializeBase({}, "selfie");
1612
+ WasmUtilProvider.instance = instance;
1613
+ return instance;
1614
+ })();
1615
+ return WasmUtilProvider.initPromise;
1616
+ }
1617
+ static resetInstance() {
1618
+ WasmUtilProvider.instance = void 0;
1619
+ WasmUtilProvider.initPromise = void 0;
1620
+ }
1621
+ constructor() {
1622
+ super(void 0);
1623
+ }
1624
+ async initialize(config) {
1625
+ if (this.initialized) return;
1626
+ const pipeline = config.pipelines?.[0] ?? "selfie";
1627
+ await this.initializeBase(config, pipeline);
1628
+ }
1629
+ encryptImage(image) {
1630
+ return mlWasmJSApi_default.ens(image);
1631
+ }
1632
+ };
1633
+
1634
+ //#endregion
1635
+ //#region src/http/api.ts
1636
+ let client = null;
1637
+ let currentToken = null;
1638
+ function setClient(httpClient) {
1639
+ client = httpClient;
1640
+ }
1641
+ function setToken(token) {
1642
+ currentToken = token;
1643
+ }
1644
+ function getApi() {
1645
+ if (!client) throw new Error("SDK not configured. Call setup({ apiURL: \"...\" }) first.");
1646
+ return client;
1647
+ }
1648
+ function resetApi() {
1649
+ client = null;
1650
+ currentToken = null;
1651
+ }
1652
+ function addTokenHeader(config) {
1653
+ if (!currentToken) return config ?? {};
1654
+ return {
1655
+ ...config,
1656
+ headers: {
1657
+ ...config?.headers,
1658
+ "X-Incode-Hardware-Id": currentToken
1659
+ }
1660
+ };
1661
+ }
1662
+ const api = {
1663
+ get(url, config) {
1664
+ return getApi().get(url, addTokenHeader(config));
1665
+ },
1666
+ post(url, data, config) {
1667
+ return getApi().post(url, data, addTokenHeader(config));
1668
+ },
1669
+ put(url, data, config) {
1670
+ return getApi().put(url, data, addTokenHeader(config));
1671
+ },
1672
+ patch(url, data, config) {
1673
+ return getApi().patch(url, data, addTokenHeader(config));
1674
+ },
1675
+ delete(url, config) {
1676
+ return getApi().delete(url, addTokenHeader(config));
1677
+ }
1678
+ };
1679
+
1680
+ //#endregion
1681
+ //#region src/http/endpoints.ts
1682
+ const endpoints = {
1683
+ createSession: "/omni/start",
1684
+ flow: "/omni/onboarding/flow",
1685
+ events: "/omni/interview-events",
1686
+ selfie: "/omni/add/face",
1687
+ recordingCreateSessionV2: "/omni/recordings/create-session/v2",
1688
+ recordingStartV2: "/omni/recordings/record-start/v2",
1689
+ recordingStopV2: "/omni/recordings/record-stop/v2",
1690
+ phone: "/omni/add/phone",
1691
+ phoneInstant: "/omni/instant/add/phone",
1692
+ getPhone: "/omni/get/phone",
1693
+ startInfo: "/omni/start-info",
1694
+ sendSmsOtp: "/omni/send/sms-otp",
1695
+ compareOtp: "/omni/compare/otp",
1696
+ email: "/omni/add/email",
1697
+ getEmail: "/omni/get/email"
1698
+ };
1699
+
1700
+ //#endregion
1701
+ export { createApi_default as _, setClient as a, FaceDetectionProvider as c, StreamCanvasProcessingSession as d, StreamCanvasCapture as f, createManager as g, stopCameraStream as h, resetApi as i, warmupWasm as l, requestCameraAccess as m, api as n, setToken as o, queryCameraPermission as p, getApi as r, WasmUtilProvider as s, endpoints as t, OpenViduRecordingProvider as u };