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

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 (106) hide show
  1. package/dist/Manager-BGfxEmyv.d.ts +19 -0
  2. package/dist/OpenViduLogger-BdPfiZO6.esm.js +3 -0
  3. package/dist/OpenViduLogger-CQyDxBvM.esm.js +803 -0
  4. package/dist/StateMachine-DRE1oH2B.d.ts +2 -0
  5. package/dist/addEvent-W0ORK0jT.esm.js +16 -0
  6. package/dist/chunk-C_Yo44FK.esm.js +49 -0
  7. package/dist/email.d.ts +264 -0
  8. package/dist/email.esm.js +479 -0
  9. package/dist/endpoints-BSTFaHYo.esm.js +1706 -0
  10. package/dist/flow.d.ts +578 -0
  11. package/dist/flow.esm.js +628 -0
  12. package/dist/index.d.ts +226 -0
  13. package/dist/index.esm.js +155 -0
  14. package/dist/lib-Bu9XGMBW.esm.js +11700 -0
  15. package/dist/permissionServices-I6vX6DBy.esm.js +72 -0
  16. package/dist/phone.d.ts +292 -0
  17. package/dist/phone.esm.js +550 -0
  18. package/dist/selfie.d.ts +759 -0
  19. package/dist/selfie.esm.js +995 -0
  20. package/dist/types-iZi2rawo.d.ts +5 -0
  21. package/dist/warmup-CEJTfxQr.d.ts +55 -0
  22. package/dist/xstate.esm-B_rda9yU.esm.js +3261 -0
  23. package/package.json +14 -11
  24. package/src/camera/cameraActor.ts +0 -21
  25. package/src/camera/cameraService.test.ts +0 -437
  26. package/src/camera/cameraService.ts +0 -165
  27. package/src/camera/cameraServices.test.ts +0 -66
  28. package/src/camera/cameraServices.ts +0 -26
  29. package/src/camera/cameraStateMachine.test.ts +0 -602
  30. package/src/camera/cameraStateMachine.ts +0 -264
  31. package/src/camera/index.ts +0 -5
  32. package/src/camera/types.ts +0 -17
  33. package/src/device/getBrowser.ts +0 -31
  34. package/src/device/getDeviceClass.ts +0 -29
  35. package/src/device/index.ts +0 -2
  36. package/src/email/__mocks__/emailMocks.ts +0 -59
  37. package/src/email/emailActor.ts +0 -15
  38. package/src/email/emailManager.test.ts +0 -573
  39. package/src/email/emailManager.ts +0 -427
  40. package/src/email/emailServices.ts +0 -66
  41. package/src/email/emailStateMachine.test.ts +0 -741
  42. package/src/email/emailStateMachine.ts +0 -367
  43. package/src/email/index.ts +0 -39
  44. package/src/email/types.ts +0 -60
  45. package/src/events/addEvent.ts +0 -20
  46. package/src/events/types.ts +0 -7
  47. package/src/flow/__mocks__/flowMocks.ts +0 -84
  48. package/src/flow/flowActor.ts +0 -13
  49. package/src/flow/flowAnalyzer.test.ts +0 -266
  50. package/src/flow/flowAnalyzer.ts +0 -37
  51. package/src/flow/flowCompletionService.ts +0 -21
  52. package/src/flow/flowManager.test.ts +0 -560
  53. package/src/flow/flowManager.ts +0 -235
  54. package/src/flow/flowServices.test.ts +0 -109
  55. package/src/flow/flowServices.ts +0 -13
  56. package/src/flow/flowStateMachine.test.ts +0 -334
  57. package/src/flow/flowStateMachine.ts +0 -182
  58. package/src/flow/index.ts +0 -21
  59. package/src/flow/moduleLoader.test.ts +0 -136
  60. package/src/flow/moduleLoader.ts +0 -73
  61. package/src/flow/orchestratedFlowManager.test.ts +0 -240
  62. package/src/flow/orchestratedFlowManager.ts +0 -231
  63. package/src/flow/orchestratedFlowStateMachine.test.ts +0 -199
  64. package/src/flow/orchestratedFlowStateMachine.ts +0 -325
  65. package/src/flow/types.ts +0 -434
  66. package/src/http/__mocks__/api.ts +0 -88
  67. package/src/http/api.test.ts +0 -231
  68. package/src/http/api.ts +0 -90
  69. package/src/http/endpoints.ts +0 -17
  70. package/src/index.ts +0 -33
  71. package/src/permissions/index.ts +0 -2
  72. package/src/permissions/permissionServices.ts +0 -31
  73. package/src/permissions/types.ts +0 -3
  74. package/src/phone/__mocks__/phoneMocks.ts +0 -71
  75. package/src/phone/index.ts +0 -39
  76. package/src/phone/phoneActor.ts +0 -15
  77. package/src/phone/phoneManager.test.ts +0 -393
  78. package/src/phone/phoneManager.ts +0 -458
  79. package/src/phone/phoneServices.ts +0 -98
  80. package/src/phone/phoneStateMachine.test.ts +0 -918
  81. package/src/phone/phoneStateMachine.ts +0 -422
  82. package/src/phone/types.ts +0 -83
  83. package/src/recordings/recordingsRepository.test.ts +0 -87
  84. package/src/recordings/recordingsRepository.ts +0 -48
  85. package/src/recordings/streamingEvents.ts +0 -10
  86. package/src/selfie/__mocks__/selfieMocks.ts +0 -26
  87. package/src/selfie/index.ts +0 -14
  88. package/src/selfie/selfieActor.ts +0 -17
  89. package/src/selfie/selfieErrorUtils.test.ts +0 -116
  90. package/src/selfie/selfieErrorUtils.ts +0 -66
  91. package/src/selfie/selfieManager.test.ts +0 -297
  92. package/src/selfie/selfieManager.ts +0 -301
  93. package/src/selfie/selfieServices.ts +0 -362
  94. package/src/selfie/selfieStateMachine.test.ts +0 -283
  95. package/src/selfie/selfieStateMachine.ts +0 -804
  96. package/src/selfie/selfieUploadService.test.ts +0 -90
  97. package/src/selfie/selfieUploadService.ts +0 -81
  98. package/src/selfie/types.ts +0 -103
  99. package/src/session/index.ts +0 -5
  100. package/src/session/sessionService.ts +0 -78
  101. package/src/setup.test.ts +0 -61
  102. package/src/setup.ts +0 -171
  103. package/tsconfig.json +0 -13
  104. package/tsdown.config.ts +0 -22
  105. package/vitest.config.ts +0 -37
  106. package/vitest.setup.ts +0 -135
@@ -0,0 +1,1706 @@
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 enableProdModeBeforeLoad() {
610
+ const { OpenViduLogger } = await import("./OpenViduLogger-BdPfiZO6.esm.js").then(__toDynamicImportESM(1));
611
+ OpenViduLogger.getInstance().enableProdMode();
612
+ }
613
+ async function loadOpenVidu() {
614
+ if (openViduImport) return openViduImport;
615
+ await enableProdModeBeforeLoad();
616
+ openViduImport = import("./lib-Bu9XGMBW.esm.js").then(__toDynamicImportESM(1));
617
+ return openViduImport;
618
+ }
619
+
620
+ //#endregion
621
+ //#region ../infra/src/providers/browser/OpenViduRecordingProvider.ts
622
+ function createHiddenContainer() {
623
+ const id = `inc_rec_${Math.random().toString(36).slice(2)}`;
624
+ const existing = document.getElementById(id);
625
+ if (existing) return {
626
+ id,
627
+ element: existing
628
+ };
629
+ const div = document.createElement("div");
630
+ div.id = id;
631
+ div.style.display = "none";
632
+ document.body.appendChild(div);
633
+ return {
634
+ id,
635
+ element: div
636
+ };
637
+ }
638
+ var OpenViduRecordingProvider = class {
639
+ async connect(params) {
640
+ const { OpenVidu } = await loadOpenVidu();
641
+ const container = createHiddenContainer();
642
+ const ov = new OpenVidu();
643
+ const session = ov.initSession();
644
+ const videoTrack = params.stream.getVideoTracks()[0];
645
+ const audioTrack = params.stream.getAudioTracks()[0];
646
+ const hasAudio = audioTrack !== void 0;
647
+ const publisher = ov.initPublisher(container.id, {
648
+ publishAudio: hasAudio,
649
+ audioSource: hasAudio ? audioTrack : false,
650
+ videoSource: videoTrack ?? false,
651
+ frameRate: 30
652
+ });
653
+ session.on("exception", (event) => {
654
+ const e = event;
655
+ params.events?.onSessionException?.({
656
+ name: e?.name,
657
+ message: e?.message,
658
+ sessionId: session.sessionId
659
+ });
660
+ });
661
+ publisher.on("streamCreated", () => {
662
+ params.events?.onPublisherCreated?.({
663
+ sessionId: session.sessionId,
664
+ streamId: publisher.stream?.streamId
665
+ });
666
+ });
667
+ await session.connect(params.sessionToken);
668
+ params.events?.onSessionConnected?.(session.sessionId);
669
+ try {
670
+ await session.publish(publisher);
671
+ } catch (error) {
672
+ const message = error instanceof Error ? error.message : String(error);
673
+ params.events?.onPublisherError?.({
674
+ message,
675
+ sessionId: session.sessionId,
676
+ streamId: publisher.stream?.streamId
677
+ });
678
+ throw error;
679
+ }
680
+ return {
681
+ sessionId: session.sessionId,
682
+ publisher: {
683
+ getStreamId: () => publisher.stream?.streamId,
684
+ replaceVideoTrack: async (track) => {
685
+ await publisher.replaceTrack(track);
686
+ },
687
+ destroy: () => {}
688
+ },
689
+ disconnect: async () => {
690
+ try {
691
+ session.disconnect();
692
+ params.stream.getTracks().forEach((t) => {
693
+ t.stop();
694
+ });
695
+ } finally {
696
+ params.events?.onSessionDisconnected?.(session.sessionId);
697
+ if (container.element.parentNode) container.element.parentNode.removeChild(container.element);
698
+ }
699
+ }
700
+ };
701
+ }
702
+ };
703
+
704
+ //#endregion
705
+ //#region ../infra/src/wasm/IdCaptureModelType.ts
706
+ let IdCaptureModelType = /* @__PURE__ */ function(IdCaptureModelType$1) {
707
+ IdCaptureModelType$1[IdCaptureModelType$1["IdCaptureV1x"] = 0] = "IdCaptureV1x";
708
+ IdCaptureModelType$1[IdCaptureModelType$1["IdCaptureV2x"] = 1] = "IdCaptureV2x";
709
+ IdCaptureModelType$1[IdCaptureModelType$1["IdCaptureV3x"] = 2] = "IdCaptureV3x";
710
+ return IdCaptureModelType$1;
711
+ }({});
712
+
713
+ //#endregion
714
+ //#region ../infra/src/wasm/Mutex.ts
715
+ var Semaphore = class {
716
+ constructor(maxConcurrent = 1) {
717
+ this.maxConcurrent = maxConcurrent;
718
+ this.current = 0;
719
+ this.queue = [];
720
+ }
721
+ async acquire() {
722
+ if (this.current < this.maxConcurrent) {
723
+ this.current++;
724
+ return Promise.resolve();
725
+ }
726
+ return new Promise((resolve) => {
727
+ this.queue.push(resolve);
728
+ });
729
+ }
730
+ release() {
731
+ this.current = Math.max(0, this.current - 1);
732
+ if (this.queue.length > 0 && this.current < this.maxConcurrent) {
733
+ this.current++;
734
+ const next = this.queue.shift();
735
+ if (next) next();
736
+ }
737
+ }
738
+ };
739
+ var Mutex = class {
740
+ constructor() {
741
+ this.semaphore = new Semaphore(1);
742
+ }
743
+ async lock() {
744
+ return this.semaphore.acquire();
745
+ }
746
+ unlock() {
747
+ this.semaphore.release();
748
+ }
749
+ async withLock(fn, ...args) {
750
+ await this.lock();
751
+ try {
752
+ return await fn(...args);
753
+ } finally {
754
+ this.unlock();
755
+ }
756
+ }
757
+ };
758
+
759
+ //#endregion
760
+ //#region ../infra/src/wasm/WasmPipelineType.ts
761
+ let WasmPipelineType = /* @__PURE__ */ function(WasmPipelineType$1) {
762
+ WasmPipelineType$1[WasmPipelineType$1["IdBlurGlarePipeline"] = 0] = "IdBlurGlarePipeline";
763
+ WasmPipelineType$1[WasmPipelineType$1["IdBarcodeAndTextQualityPipeline"] = 1] = "IdBarcodeAndTextQualityPipeline";
764
+ WasmPipelineType$1[WasmPipelineType$1["IdVideoSelfiePipeline"] = 2] = "IdVideoSelfiePipeline";
765
+ WasmPipelineType$1[WasmPipelineType$1["SelfieWithAggregationMetrics"] = 3] = "SelfieWithAggregationMetrics";
766
+ WasmPipelineType$1[WasmPipelineType$1["SelfieWithQualityMetrics"] = 4] = "SelfieWithQualityMetrics";
767
+ WasmPipelineType$1[WasmPipelineType$1["IdFaceDetectionPipeline"] = 5] = "IdFaceDetectionPipeline";
768
+ return WasmPipelineType$1;
769
+ }({});
770
+
771
+ //#endregion
772
+ //#region ../infra/src/wasm/mlWasmJSApi.ts
773
+ window.wasmArrayBuffer = null;
774
+ var MlWasmJSApi = class MlWasmJSApi {
775
+ constructor() {
776
+ this.versionsFile = null;
777
+ this.modelsBuffers = null;
778
+ this.inputImageBuffer = null;
779
+ this.wasmModule = null;
780
+ this.pipelineApiUtilities = null;
781
+ this.utilityApi = null;
782
+ this.idCaptureWasmApi = null;
783
+ this.faceDetectionWasmApi = null;
784
+ this.imageWidth_ = null;
785
+ this.imageHeight_ = null;
786
+ this.pipelines_ = null;
787
+ this.isInitialized_ = false;
788
+ this.inspectorOpened_ = false;
789
+ this.wasmCallMutex = new Mutex();
790
+ this.Module = null;
791
+ this.loadModule = async (glueCodePath) => {
792
+ this.Module = (await import(
793
+ /* @vite-ignore */
794
+ /* webpackIgnore: true */
795
+ glueCodePath
796
+ )).Module;
797
+ };
798
+ }
799
+ /**
800
+ * Initiallization method, use it when the application starts
801
+ * TODO: this method can return the list of promises to be awaited together with other initialization code
802
+ * @param {string} webLibPath - The path to the webassembly binary
803
+ * @param {string} webLibPathSimd - The path to the SIMD version webassembly binary
804
+ * @param {boolean} useSimd - Indicates whether SIMD optimizations should be used
805
+ * @param {string} versionsFile - The path to the file containing versioning information
806
+ * @param {Map.<WasmPipelineType, Array<string>>} pipelines - pipelines for initialization and corresponding models paths
807
+ * @returns {Promise<boolean>} A promise that resolves to a boolean indicating whether SIMD is enabled once the initialization is complete.
808
+ * @throws {Error} Throws an error if the initialization fails.
809
+ */
810
+ async initialize(webLibPath, webLibPathSimd, glueCodePath, useSimd, versionsFile, pipelines) {
811
+ await this.freeResources();
812
+ this.pipelines_ = pipelines;
813
+ this.versionsFile = versionsFile;
814
+ await this.loadModule(glueCodePath);
815
+ const simdIsEnabled = await this.loadWasm(useSimd, webLibPath, webLibPathSimd);
816
+ this.pipelineApiUtilities = new this.wasmModule.PipelineApiUtilities();
817
+ this.utilityApi = new this.wasmModule.UtilityApi();
818
+ this.idCaptureWasmApi = new this.wasmModule.IdCaptureApi();
819
+ this.faceDetectionWasmApi = new this.wasmModule.FaceDetectionApi();
820
+ this.isInitialized_ = true;
821
+ return simdIsEnabled;
822
+ }
823
+ static getInstance() {
824
+ if (!MlWasmJSApi.instance) MlWasmJSApi.instance = new MlWasmJSApi();
825
+ return MlWasmJSApi.instance;
826
+ }
827
+ /**
828
+ * Returns initialization status
829
+ * @returns
830
+ */
831
+ isInitialized() {
832
+ return this.pipelineApiUtilities != null && this.utilityApi != null && this.idCaptureWasmApi != null && this.faceDetectionWasmApi != null && this.isInitialized_;
833
+ }
834
+ /**
835
+ * Allocate shared memory for image buffers (RGBA format)
836
+ * Use it every time when the frame dimentions changes
837
+ * @param {number} imageWidth - image width
838
+ * @param {number} imageHeight - image height
839
+ */
840
+ async allocateImageBuffers(imageWidth, imageHeight) {
841
+ this.checkWasmInitialization("Unable to allocate image buffers, cpp API hasn't been initialized");
842
+ if (imageWidth && imageHeight && imageWidth == this.imageWidth_ && imageHeight == this.imageHeight_ && this.inputImageBuffer && imageWidth * imageHeight * 4 === this.inputImageBuffer.length) return;
843
+ this.imageWidth_ = imageWidth;
844
+ this.imageHeight_ = imageHeight;
845
+ this.inputImageBuffer = this.pipelineApiUtilities.allocateInputImageBuffer(imageWidth, imageHeight, 4);
846
+ }
847
+ async handleDetectionCallAndUpdateState(type) {
848
+ this.checkWasmInitialization("Unable to update pipeline state, cpp API hasn't been initialized");
849
+ this.pipelineApiUtilities.handleDetectionCallAndUpdateState(this.pipelineTypeToWasmEnum(type));
850
+ }
851
+ ens(image) {
852
+ this.checkWasmInitialization("Unable to encrypt the image, cpp API hasn't been initialized");
853
+ return this.utilityApi.ens(image);
854
+ }
855
+ isVirtualCamera(label) {
856
+ this.checkWasmInitialization("Unable to check if the camera is virtual, cpp API hasn't been initialized");
857
+ if (label) return this.utilityApi.isVirtualCamera(label);
858
+ return false;
859
+ }
860
+ estimatePerformance() {
861
+ this.checkWasmInitialization("Unable to estimate performance, cpp API hasn't been initialized");
862
+ return this.utilityApi.estimatePerformance();
863
+ }
864
+ async analyzeFrame(image) {
865
+ this.checkWasmInitialization("Unable to analyze the frame, cpp API hasn't been initialized");
866
+ await this.allocateImageBuffers(image.width, image.height);
867
+ this.inputImageBuffer.set(image.data);
868
+ this.utilityApi.analyzeFrame();
869
+ }
870
+ /**
871
+ * Free allocated memory
872
+ */
873
+ async freeResources() {
874
+ this.versionsFile = null;
875
+ this.modelsBuffers = null;
876
+ this.inputImageBuffer = null;
877
+ this.imageWidth_ = null;
878
+ this.imageHeight_ = null;
879
+ this.pipelines_ = null;
880
+ window.wasmArrayBuffer = null;
881
+ if (this.pipelineApiUtilities && typeof this.pipelineApiUtilities.delete === "function") {
882
+ this.pipelineApiUtilities.delete();
883
+ this.pipelineApiUtilities = null;
884
+ }
885
+ if (this.utilityApi && typeof this.utilityApi.delete === "function") {
886
+ this.utilityApi.delete();
887
+ this.utilityApi = null;
888
+ }
889
+ if (this.idCaptureWasmApi && typeof this.idCaptureWasmApi.delete === "function") {
890
+ this.idCaptureWasmApi.delete();
891
+ this.idCaptureWasmApi = null;
892
+ }
893
+ if (this.faceDetectionWasmApi && typeof this.faceDetectionWasmApi.delete === "function") {
894
+ this.faceDetectionWasmApi.delete();
895
+ this.faceDetectionWasmApi = null;
896
+ }
897
+ this.wasmModule = null;
898
+ this.isInitialized_ = false;
899
+ }
900
+ /**
901
+ * Clear pipeline state
902
+ */
903
+ resetPipeline(type) {
904
+ this.checkWasmInitialization("Unable to reset pipeline, cpp API hasn't been initialized");
905
+ this.pipelineApiUtilities.resetPipeline(this.pipelineTypeToWasmEnum(type));
906
+ }
907
+ /**
908
+ * Clear all pipelines states
909
+ */
910
+ resetAllPipelines() {
911
+ this.checkWasmInitialization("Unable to reset pipelines, cpp API hasn't been initialized");
912
+ for (const [type, model] of this.pipelines_) this.resetPipeline(type);
913
+ }
914
+ /**
915
+ * Clear all states, not related to ml pipelines
916
+ */
917
+ resetOther() {
918
+ this.checkWasmInitialization("Unable to reset other states, cpp API hasn't been initialized");
919
+ this.utilityApi.resetOther();
920
+ }
921
+ /**
922
+ * Full reset
923
+ */
924
+ reset() {
925
+ this.resetAllPipelines();
926
+ this.resetOther();
927
+ }
928
+ /**
929
+ * Process one frame using one of the pipelines
930
+ * @param {ImageData} image - input image
931
+ * @param {WasmPipelineType} type - pipeline type
932
+ * @returns
933
+ */
934
+ async process(image, type) {
935
+ this.checkWasmInitialization("Unable to process the image, cpp API hasn't been initialized");
936
+ if (this.inputImageBuffer === null) throw new Error("Unable to process the image, buffers haven't been allocated!");
937
+ this.inputImageBuffer.set(image.data);
938
+ switch (type) {
939
+ case WasmPipelineType.IdBlurGlarePipeline:
940
+ case WasmPipelineType.IdBarcodeAndTextQualityPipeline: return this.idCaptureWasmApi.runIdCapturePipeline(this.pipelineTypeToWasmEnum(type));
941
+ case WasmPipelineType.IdFaceDetectionPipeline: return this.faceDetectionWasmApi.runIdFaceDetectionPipeline();
942
+ case WasmPipelineType.IdVideoSelfiePipeline: return this.idCaptureWasmApi.runIdVideoSelfiePipeline();
943
+ case WasmPipelineType.SelfieWithAggregationMetrics:
944
+ case WasmPipelineType.SelfieWithQualityMetrics: return this.faceDetectionWasmApi.runSelfieFaceDetectionPipeline(this.pipelineTypeToWasmEnum(type));
945
+ default: throw new Error("Unknown pipeline type");
946
+ }
947
+ }
948
+ async runIdCapture(image) {
949
+ this.checkWasmInitialization("Unable to run Id Capture, cpp API hasn't been initialized");
950
+ if (this.inputImageBuffer === null) throw new Error("Unable to process the image, buffers haven't been allocated!");
951
+ this.inputImageBuffer.set(image.data);
952
+ return this.idCaptureWasmApi.runIdCapture();
953
+ }
954
+ async runSelfieCapture(image) {
955
+ this.checkWasmInitialization("Unable to run Selfie Capture, cpp API hasn't been initialized");
956
+ if (this.inputImageBuffer === null) throw new Error("Unable to process the image, buffers haven't been allocated!");
957
+ this.inputImageBuffer.set(image.data);
958
+ return this.faceDetectionWasmApi.runSelfieCapture();
959
+ }
960
+ async setFacePositionConstraints(type, minX, minY, maxX, maxY) {
961
+ this.checkWasmInitialization("Unable to set face position constraints, cpp API hasn't been initialized");
962
+ this.faceDetectionWasmApi.setFacePositionConstraints(this.pipelineTypeToWasmEnum(type), minX, minY, maxX, maxY);
963
+ }
964
+ async setFaceDetectionThresholds(type, brightnessThreshold, blurrinessThreshold, tiltRotationAngleThreshold, minMagicCropSize, autocaptureInterval, minFaceQualityScore, faceOcclusionThreshold) {
965
+ this.checkWasmInitialization("Unable to set face detection thresholds, cpp API hasn't been initialized");
966
+ this.faceDetectionWasmApi.setFaceDetectionThresholds(this.pipelineTypeToWasmEnum(type), brightnessThreshold, blurrinessThreshold, tiltRotationAngleThreshold, minMagicCropSize, autocaptureInterval, minFaceQualityScore, faceOcclusionThreshold);
967
+ }
968
+ async setFaceAttributesThresholds(type, headwearThreshold, lensesThreshold, closedEyesThreshold, maskThreshold) {
969
+ this.checkWasmInitialization("Unable to set face attributes thresholds, cpp API hasn't been initialized");
970
+ this.faceDetectionWasmApi.setFaceAttributesThresholds(this.pipelineTypeToWasmEnum(type), headwearThreshold, lensesThreshold, closedEyesThreshold, maskThreshold);
971
+ }
972
+ async setFaceChecksEnabled(type, isLensesCheckEnabled, isMaskCheckEnabled, isClosedEyesCheckEnabled, isHeadWearCheckEnabled, isOcclusionCheckEnabled) {
973
+ this.checkWasmInitialization("Unable to set face checks enabled flags, cpp API hasn't been initialized");
974
+ this.faceDetectionWasmApi.setFaceChecksEnabled(this.pipelineTypeToWasmEnum(type), isLensesCheckEnabled, isMaskCheckEnabled, isClosedEyesCheckEnabled, isHeadWearCheckEnabled, isOcclusionCheckEnabled);
975
+ }
976
+ async setFaceDetectionMode(type, isVideoSelfie) {
977
+ this.checkWasmInitialization("Unable to set face detection mode, cpp API hasn't been initialized");
978
+ this.faceDetectionWasmApi.setFaceDetectionMode(this.pipelineTypeToWasmEnum(type), isVideoSelfie);
979
+ }
980
+ async setFaceDetectionCallbacks(type, onFarAway, onTooClose, onTooManyFaces, onNoFace, onCapture, onGetReady, onGetReadyFinished, onCenterFace, onDark, onBlur, onFaceAngle, onBestShot, onLenses, onMask, onEyesClosed, onHeadWear, onSwitchToManualCapture, onFaceOccluded) {
981
+ this.checkWasmInitialization("Unable to set face detection callbacks, cpp API hasn't been initialized");
982
+ this.faceDetectionWasmApi.setFaceDetectionCallbacks(this.pipelineTypeToWasmEnum(type), onFarAway, onTooClose, onTooManyFaces, onNoFace, onCapture, onGetReady, onGetReadyFinished, onCenterFace, onDark, onBlur, onFaceAngle, onBestShot, onLenses, onMask, onEyesClosed, onHeadWear, onSwitchToManualCapture, onFaceOccluded);
983
+ }
984
+ async setIdCaptureThresholds(type, blurThreshold, blurChangeThreshold, glareThreshold, clsThreshold, sideThreshold, iouThreshold, idDetectedTimeout, autocaptureTimeout, framesAggregationInterval, minFaceIdQualityScore) {
985
+ this.checkWasmInitialization("Unable to set thresholds, cpp API hasn't been initialized");
986
+ this.idCaptureWasmApi.setIdCaptureThresholds(this.pipelineTypeToWasmEnum(type), blurThreshold, blurChangeThreshold, glareThreshold, clsThreshold, sideThreshold, iouThreshold, idDetectedTimeout, autocaptureTimeout, framesAggregationInterval, minFaceIdQualityScore);
987
+ }
988
+ async setIdCaptureCallbacks(type, onFarAway, onDetectionStarted, onMaskChange, onBlur, onGlare, onCapturing, onCapture, onBestFrame, onIDNotDetected, onSwitchToManualCapture, onIDTypeChange, onIDSideChange, onCapturingCounterValueChange) {
989
+ this.checkWasmInitialization("Unable to set callbacks, cpp API hasn't been initialized");
990
+ this.idCaptureWasmApi.setIdCaptureCallbacks(this.pipelineTypeToWasmEnum(type), onFarAway, onDetectionStarted, onMaskChange, onBlur, onGlare, onCapturing, onCapture, onBestFrame, onIDNotDetected, onSwitchToManualCapture, onIDTypeChange, onIDSideChange, onCapturingCounterValueChange);
991
+ }
992
+ async setIdCaptureGeometryParams(type, areaDown, areaUp, areaIOSPassportUp, areaIOSPassportDown, widthIOSUp, widthIOSDown, widthDown, widthUp, windowOuterWidth, windowOuterHeight, windowInnerWidth, windowInnerHeight) {
993
+ this.checkWasmInitialization("Unable to set geometry params, cpp API hasn't been initialized");
994
+ this.idCaptureWasmApi.setIdCaptureGeometryParams(this.pipelineTypeToWasmEnum(type), areaDown, areaUp, areaIOSPassportUp, areaIOSPassportDown, widthIOSUp, widthIOSDown, widthDown, widthUp, windowOuterWidth, windowOuterHeight, windowInnerWidth, windowInnerHeight);
995
+ }
996
+ async setIdCaptureConfigParams(type, isFixedMask, isIPhone14OrHigher, idType, isBlurCheckEnabled, isGlareCheckEnabled, isIdFaceQualityCheckEnabled, isIouCheckEnabled) {
997
+ this.checkWasmInitialization("Unable to set config params, cpp API hasn't been initialized");
998
+ this.idCaptureWasmApi.setIdCaptureConfigParams(this.pipelineTypeToWasmEnum(type), isFixedMask, isIPhone14OrHigher, idType, isBlurCheckEnabled, isGlareCheckEnabled, isIdFaceQualityCheckEnabled, isIouCheckEnabled);
999
+ }
1000
+ setIdCaptureModelType(pipelineType, modelType) {
1001
+ this.checkWasmInitialization("Unable to set model type, cpp API hasn't been initialized");
1002
+ this.idCaptureWasmApi.setIdCaptureModelType(this.pipelineTypeToWasmEnum(pipelineType), this.IdCaptureModelTypeToWasmEnum(modelType));
1003
+ }
1004
+ IdPerspectiveTransform(image, frameRect) {
1005
+ this.checkWasmInitialization("Unable to perform perspective transform, cpp API hasn't been initialized");
1006
+ return this.idCaptureWasmApi.IdPerspectiveTransform(image, frameRect);
1007
+ }
1008
+ async getVersions() {
1009
+ const text = await (await fetch(this.versionsFile)).text();
1010
+ return JSON.parse(text);
1011
+ }
1012
+ async loadWasm(useSimd, webLibPath, webLibPathSimd) {
1013
+ const libPath = useSimd ? webLibPathSimd : webLibPath;
1014
+ try {
1015
+ window.wasmArrayBuffer = await fetch(libPath).then((response) => response.arrayBuffer()).then((buffer) => new Uint8Array(buffer));
1016
+ this.wasmModule = await this.Module();
1017
+ } catch (e) {
1018
+ console.log(e, useSimd, "useSmd");
1019
+ if (useSimd) return await this.loadWasm(false, webLibPath, webLibPathSimd);
1020
+ else throw e;
1021
+ }
1022
+ return useSimd;
1023
+ }
1024
+ async loadModels() {
1025
+ this.checkWasmInitialization("Unable load the models, cpp API hasn't been initialized");
1026
+ const buffSizes = new this.wasmModule.PipelineTypeToIntMap();
1027
+ const modelData = /* @__PURE__ */ new Map();
1028
+ const loadedModels = /* @__PURE__ */ new Map();
1029
+ for (const [type, modelsPaths] of this.pipelines_) {
1030
+ const wasmType = this.pipelineTypeToWasmEnum(type);
1031
+ const pipelineBuffers = [];
1032
+ const sizes = new this.wasmModule.VectorInt();
1033
+ for (const path of modelsPaths) {
1034
+ if (!loadedModels.has(path)) {
1035
+ const model$1 = await fetch(path).then((response) => response.arrayBuffer()).then((buffer) => new Uint8Array(buffer));
1036
+ loadedModels.set(path, model$1);
1037
+ }
1038
+ const model = loadedModels.get(path);
1039
+ sizes.push_back(model.byteLength);
1040
+ pipelineBuffers.push(model);
1041
+ }
1042
+ buffSizes.set(wasmType, sizes);
1043
+ modelData.set(wasmType, pipelineBuffers);
1044
+ }
1045
+ this.modelsBuffers = this.pipelineApiUtilities.allocateModelsBuffers(buffSizes);
1046
+ for (const [type, data] of modelData) {
1047
+ const buffers = this.modelsBuffers?.get(type);
1048
+ for (let k = 0; k < buffers.size(); k++) {
1049
+ const buffer = buffers?.get(k);
1050
+ if (buffer) buffer.set(data[k]);
1051
+ else throw new Error("Unable to get model buffer from shared memory!");
1052
+ }
1053
+ }
1054
+ }
1055
+ async initializePipelines() {
1056
+ this.checkWasmInitialization("Unable to initialize pipelines, cpp API hasn't been initialized");
1057
+ if (!this.modelsBuffers) await this.loadModels();
1058
+ this.pipelineApiUtilities.initializePipelines();
1059
+ }
1060
+ async setProductionMode(productionMode) {
1061
+ this.checkWasmInitialization("Unable to set production mode, cpp API hasn't been initialized");
1062
+ this.utilityApi.setProductionMode(productionMode);
1063
+ }
1064
+ getPipelineState() {
1065
+ this.checkWasmInitialization("Unable to get pipeline state, cpp API hasn't been initialized");
1066
+ return this.pipelineApiUtilities.getPipelineState();
1067
+ }
1068
+ getCurrentPipeline() {
1069
+ this.checkWasmInitialization("Unable to get current pipeline, cpp API hasn't been initialized");
1070
+ return this.pipelineTypeFromWasmEnum(this.pipelineApiUtilities.getCurrentPipeline());
1071
+ }
1072
+ setSdkVersion(sdkVersion) {
1073
+ this.checkWasmInitialization("Unable to set sdk version, cpp API hasn't been initialized");
1074
+ this.utilityApi.setSdkVersion(sdkVersion);
1075
+ }
1076
+ setSdkPlatform(sdkPlatform) {
1077
+ this.checkWasmInitialization("Unable to set device type, cpp API hasn't been initialized");
1078
+ this.utilityApi.setSdkPlatform(sdkPlatform);
1079
+ }
1080
+ setDeviceInfo(deviceInfo, overrideExisting = true) {
1081
+ this.checkWasmInitialization("Unable to set device info, cpp API hasn't been initialized");
1082
+ this.utilityApi.setDeviceInfo(deviceInfo, overrideExisting);
1083
+ }
1084
+ setBrowserInfo(browserInfo, overrideExisting = true) {
1085
+ this.checkWasmInitialization("Unable to set browser info, cpp API hasn't been initialized");
1086
+ this.utilityApi.setBrowserInfo(browserInfo, overrideExisting);
1087
+ }
1088
+ setCameraInfo(cameraInfo, overrideExisting = true) {
1089
+ this.checkWasmInitialization("Unable to set camera info, cpp API hasn't been initialized");
1090
+ this.utilityApi.setCameraInfo(cameraInfo, overrideExisting);
1091
+ }
1092
+ setZc(zc) {
1093
+ this.checkWasmInitialization("Unable to set zc, cpp API hasn't been initialized");
1094
+ this.utilityApi.setZc(zc);
1095
+ }
1096
+ setMotionStatus(motionStatus) {
1097
+ this.checkWasmInitialization("Unable to set motion status, cpp API hasn't been initialized");
1098
+ this.utilityApi.setMotionStatus(motionStatus);
1099
+ }
1100
+ setMetadataField(key, value) {
1101
+ this.checkWasmInitialization("Unable to set metadata field, cpp API hasn't been initialized");
1102
+ this.utilityApi.setMetadataField(key, value);
1103
+ }
1104
+ setInspectorOpened(inspectorOpened) {
1105
+ this.inspectorOpened_ = inspectorOpened;
1106
+ }
1107
+ setBackgroundMode(backgroundMode) {
1108
+ this.checkWasmInitialization("Unable to set background mode, cpp API hasn't been initialized");
1109
+ this.utilityApi.setBackgroundMode(backgroundMode);
1110
+ }
1111
+ getCheck() {
1112
+ this.checkWasmInitialization("Unable to get check, cpp API hasn't been initialized");
1113
+ return this.utilityApi.getCheck();
1114
+ }
1115
+ getMetadata() {
1116
+ this.checkWasmInitialization("Unable to get metadata, cpp API hasn't been initialized");
1117
+ this.utilityApi.setInspectorOpened(this.inspectorOpened_);
1118
+ return this.utilityApi.getMetadata();
1119
+ }
1120
+ async prc() {
1121
+ this.checkWasmInitialization("Unable to prc, cpp API hasn't been initialized");
1122
+ return await this.wasmCallWrapper(this.utilityApi.prc.bind(this.utilityApi), []);
1123
+ }
1124
+ async poc(output) {
1125
+ this.checkWasmInitialization("Unable to poc, cpp API hasn't been initialized");
1126
+ await this.wasmCallWrapper(this.utilityApi.poc.bind(this.utilityApi), [output]);
1127
+ }
1128
+ async pc(deviceId) {
1129
+ this.checkWasmInitialization("Unable to pc, cpp API hasn't been initialized");
1130
+ await this.wasmCallWrapper(this.utilityApi.pc.bind(this.utilityApi), [deviceId]);
1131
+ }
1132
+ pipelineTypeToWasmEnum(type) {
1133
+ switch (type) {
1134
+ case WasmPipelineType.IdBlurGlarePipeline: return this.wasmModule.PipelineType.IdBlurGlarePipeline;
1135
+ case WasmPipelineType.IdBarcodeAndTextQualityPipeline: return this.wasmModule.PipelineType.IdBarcodeAndTextQualityPipeline;
1136
+ case WasmPipelineType.IdFaceDetectionPipeline: return this.wasmModule.PipelineType.IdFaceDetectionPipeline;
1137
+ case WasmPipelineType.IdVideoSelfiePipeline: return this.wasmModule.PipelineType.IdVideoSelfiePipeline;
1138
+ case WasmPipelineType.SelfieWithAggregationMetrics: return this.wasmModule.PipelineType.SelfieWithAggregationMetrics;
1139
+ case WasmPipelineType.SelfieWithQualityMetrics: return this.wasmModule.PipelineType.SelfieWithQualityMetrics;
1140
+ default: throw new Error("Unknown pipeline type");
1141
+ }
1142
+ }
1143
+ pipelineTypeFromWasmEnum(type) {
1144
+ switch (type) {
1145
+ case this.wasmModule.PipelineType.IdBlurGlarePipeline: return WasmPipelineType.IdBlurGlarePipeline;
1146
+ case this.wasmModule.IdBarcodeAndTextQualityPipeline: return WasmPipelineType.IdBarcodeAndTextQualityPipeline;
1147
+ case this.wasmModule.PipelineType.IdFaceDetectionPipeline: return WasmPipelineType.IdFaceDetectionPipeline;
1148
+ case this.wasmModule.PipelineType.IdVideoSelfiePipeline: return WasmPipelineType.IdVideoSelfiePipeline;
1149
+ case this.wasmModule.PipelineType.SelfieWithAggregationMetrics: return WasmPipelineType.SelfieWithAggregationMetrics;
1150
+ case this.wasmModule.PipelineType.SelfieWithQualityMetrics: return WasmPipelineType.SelfieWithQualityMetrics;
1151
+ default: throw new Error("Unknown pipeline type");
1152
+ }
1153
+ }
1154
+ IdCaptureModelTypeToWasmEnum(type) {
1155
+ switch (type) {
1156
+ case IdCaptureModelType.IdCaptureV1x: return this.wasmModule.IdCaptureModelType.IdCaptureV1x;
1157
+ case IdCaptureModelType.IdCaptureV2x: return this.wasmModule.IdCaptureModelType.IdCaptureV2x;
1158
+ case IdCaptureModelType.IdCaptureV3x: return this.wasmModule.IdCaptureModelType.IdCaptureV3x;
1159
+ default: throw new Error("Unknown Id Capture model type");
1160
+ }
1161
+ }
1162
+ IdCaptureModelTypeFromWasmEnum(type) {
1163
+ switch (type) {
1164
+ case this.wasmModule.IdCaptureModelType.IdCaptureV1x: return IdCaptureModelType.IdCaptureV1x;
1165
+ case this.wasmModule.IdCaptureModelType.IdCaptureV2x: return IdCaptureModelType.IdCaptureV2x;
1166
+ case this.wasmModule.IdCaptureModelType.IdCaptureV3x: return IdCaptureModelType.IdCaptureV3x;
1167
+ default: throw new Error("Unknown Id Capture model type");
1168
+ }
1169
+ }
1170
+ checkWasmInitialization(message) {
1171
+ if (!this.isInitialized()) throw new Error(message);
1172
+ }
1173
+ async wasmCallWrapper(wasmMethod, args = []) {
1174
+ return await this.wasmCallMutex.withLock(async (...args$1) => {
1175
+ let isFinished = false;
1176
+ try {
1177
+ while (true) {
1178
+ isFinished = wasmMethod(...args$1);
1179
+ if (isFinished) return;
1180
+ await new Promise((resolve) => setTimeout(resolve, 0));
1181
+ }
1182
+ } catch (e) {
1183
+ console.log("Error in wasmCallWrapper:", e);
1184
+ }
1185
+ }, ...args);
1186
+ }
1187
+ };
1188
+ var mlWasmJSApi_default = MlWasmJSApi.getInstance();
1189
+
1190
+ //#endregion
1191
+ //#region ../infra/src/wasm/warmup.ts
1192
+ /** Array of all available pipelines */
1193
+ const WASM_PIPELINES = ["selfie", "idCapture"];
1194
+ /**
1195
+ * Default model files for each pipeline.
1196
+ * These are the ONNX model files required by each ML pipeline.
1197
+ */
1198
+ const DEFAULT_PIPELINE_MODELS = {
1199
+ selfie: [
1200
+ "selfie_bf_angles_192x192_opset9_fp16.ortmodelv2",
1201
+ "face_attributes_v1_3_fp16.ortmodelv2",
1202
+ "mls_regressor_4773007c657b4f05a460321456740d0f_fp16.ortmodelv2",
1203
+ "face_occlusion_v0_1_fp16.ortmodelv2"
1204
+ ],
1205
+ idCapture: ["id_capture_2_01_fp16.ortmodelv2", "id_fiqa_19a81a0b9bf6492eb03b4667f6db4c85_fp16.ortmodelv2"]
1206
+ };
1207
+ let state = "idle";
1208
+ let loadingPromise = null;
1209
+ let wasmError = null;
1210
+ let loadedPipelines = [];
1211
+ let lastConfig = null;
1212
+ function mapPipelineToWasmType(pipeline) {
1213
+ switch (pipeline) {
1214
+ case "selfie": return WasmPipelineType.SelfieWithQualityMetrics;
1215
+ case "idCapture": return WasmPipelineType.IdBlurGlarePipeline;
1216
+ default: throw new Error(`Unknown pipeline: ${pipeline}`);
1217
+ }
1218
+ }
1219
+ /**
1220
+ * Derives the models base path from the WASM path.
1221
+ * Assumes models are in a 'models' subdirectory relative to the WASM binary location.
1222
+ * e.g., '/wasm/v2/binary.wasm' -> '/wasm/v2/models'
1223
+ */
1224
+ function deriveModelsBasePath(wasmPath) {
1225
+ const lastSlashIndex = wasmPath.lastIndexOf("/");
1226
+ if (lastSlashIndex === -1) return "models";
1227
+ return `${wasmPath.substring(0, lastSlashIndex)}/models`;
1228
+ }
1229
+ /**
1230
+ * Builds the pipelines map with model paths for WASM initialization.
1231
+ * @param pipelines - Array of pipeline types to initialize
1232
+ * @param modelsBasePath - Base path where model files are located
1233
+ * @param customModels - Optional custom model files per pipeline
1234
+ */
1235
+ function buildPipelinesMap(pipelines, modelsBasePath, customModels) {
1236
+ const pipelinesMap = /* @__PURE__ */ new Map();
1237
+ for (const pipeline of pipelines) {
1238
+ const wasmType = mapPipelineToWasmType(pipeline);
1239
+ if (!pipelinesMap.has(wasmType)) {
1240
+ const modelPaths = (customModels?.[pipeline] ?? DEFAULT_PIPELINE_MODELS[pipeline]).map((modelFile) => `${modelsBasePath}/${modelFile}`);
1241
+ pipelinesMap.set(wasmType, modelPaths);
1242
+ }
1243
+ }
1244
+ return pipelinesMap;
1245
+ }
1246
+ /**
1247
+ * Preloads WASM binary and ML models at app startup.
1248
+ * Runs asynchronously - app can continue while WASM loads in background.
1249
+ *
1250
+ * Model files are automatically loaded based on the pipeline type.
1251
+ * By default, models are expected in a 'models' subdirectory relative to the WASM binary.
1252
+ *
1253
+ * @param config - Configuration for WASM warmup
1254
+ * @returns Promise that resolves when WASM is ready
1255
+ *
1256
+ * @example
1257
+ * ```ts
1258
+ * // Basic usage - models loaded from /wasm/v2/models/
1259
+ * warmupWasm({
1260
+ * wasmPath: '/wasm/v2/ml-wasm.wasm',
1261
+ * glueCodePath: '/wasm/v2/ml-wasm.js',
1262
+ * pipelines: ['selfie', 'idCapture'],
1263
+ * });
1264
+ *
1265
+ * // With explicit models path
1266
+ * warmupWasm({
1267
+ * wasmPath: '/wasm/v2/ml-wasm.wasm',
1268
+ * glueCodePath: '/wasm/v2/ml-wasm.js',
1269
+ * modelsBasePath: 'https://cdn.example.com/wasm/v2/models',
1270
+ * pipelines: ['selfie'],
1271
+ * });
1272
+ * ```
1273
+ */
1274
+ async function warmupWasm(config) {
1275
+ const pipelines = config.pipelines ?? [...WASM_PIPELINES];
1276
+ const modelsBasePath = config.modelsBasePath ?? deriveModelsBasePath(config.wasmPath);
1277
+ if (state === "loading" && loadingPromise) return loadingPromise;
1278
+ if (state === "ready") {
1279
+ if (pipelines.filter((p) => !loadedPipelines.includes(p)).length === 0) return;
1280
+ if (!lastConfig) throw new Error("Cannot add pipelines: original warmup config not available");
1281
+ 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.");
1282
+ const combinedPipelines = [...new Set([...loadedPipelines, ...pipelines])];
1283
+ state = "loading";
1284
+ wasmError = null;
1285
+ loadingPromise = (async () => {
1286
+ try {
1287
+ const pipelinesMap = buildPipelinesMap(combinedPipelines, lastConfig.modelsBasePath ?? deriveModelsBasePath(lastConfig.wasmPath), lastConfig.pipelineModels);
1288
+ await mlWasmJSApi_default.initialize(lastConfig.wasmPath, lastConfig.wasmSimdPath ?? lastConfig.wasmPath, lastConfig.glueCodePath, lastConfig.useSimd ?? true, "", pipelinesMap);
1289
+ await mlWasmJSApi_default.loadModels();
1290
+ await mlWasmJSApi_default.initializePipelines();
1291
+ state = "ready";
1292
+ loadedPipelines = combinedPipelines;
1293
+ lastConfig = {
1294
+ ...lastConfig,
1295
+ pipelines: combinedPipelines
1296
+ };
1297
+ loadingPromise = null;
1298
+ } catch (error) {
1299
+ state = "error";
1300
+ wasmError = error instanceof Error ? error : new Error(String(error));
1301
+ loadingPromise = null;
1302
+ throw wasmError;
1303
+ }
1304
+ })();
1305
+ return loadingPromise;
1306
+ }
1307
+ state = "loading";
1308
+ wasmError = null;
1309
+ loadingPromise = (async () => {
1310
+ try {
1311
+ const pipelinesMap = buildPipelinesMap(pipelines, modelsBasePath, config.pipelineModels);
1312
+ await mlWasmJSApi_default.initialize(config.wasmPath, config.wasmSimdPath ?? config.wasmPath, config.glueCodePath, config.useSimd ?? true, "", pipelinesMap);
1313
+ await mlWasmJSApi_default.loadModels();
1314
+ await mlWasmJSApi_default.initializePipelines();
1315
+ state = "ready";
1316
+ loadedPipelines = [...pipelines];
1317
+ lastConfig = {
1318
+ ...config,
1319
+ pipelines
1320
+ };
1321
+ loadingPromise = null;
1322
+ } catch (error) {
1323
+ state = "error";
1324
+ wasmError = error instanceof Error ? error : new Error(String(error));
1325
+ loadingPromise = null;
1326
+ throw wasmError;
1327
+ }
1328
+ })();
1329
+ return loadingPromise;
1330
+ }
1331
+ /**
1332
+ * Returns the current warmup status.
1333
+ * Useful for showing loading indicators.
1334
+ *
1335
+ * @returns Current warmup status
1336
+ */
1337
+ function getWasmStatus() {
1338
+ return {
1339
+ isReady: state === "ready",
1340
+ isLoading: state === "loading",
1341
+ error: wasmError ?? void 0,
1342
+ loadedPipelines: [...loadedPipelines]
1343
+ };
1344
+ }
1345
+ /**
1346
+ * Returns true if WASM is fully initialized and ready.
1347
+ *
1348
+ * @returns True if WASM is ready
1349
+ */
1350
+ function isWasmReady() {
1351
+ return state === "ready";
1352
+ }
1353
+ /**
1354
+ * Returns a promise that resolves when WASM is ready.
1355
+ * - If ready: resolves immediately
1356
+ * - If loading: waits for completion, then resolves
1357
+ * - If not started: rejects with error
1358
+ *
1359
+ * @returns Promise that resolves when WASM is ready
1360
+ * @throws Error if WASM is in error state or was never started
1361
+ */
1362
+ function waitForWasm() {
1363
+ if (state === "ready") return Promise.resolve();
1364
+ if (state === "loading" && loadingPromise) return loadingPromise;
1365
+ if (state === "error") return Promise.reject(wasmError ?? /* @__PURE__ */ new Error("WASM initialization failed"));
1366
+ return Promise.reject(/* @__PURE__ */ new Error("WASM warmup was not started. Call warmupWasm() first."));
1367
+ }
1368
+
1369
+ //#endregion
1370
+ //#region ../infra/src/providers/wasm/BaseWasmProvider.ts
1371
+ /**
1372
+ * Base provider class that abstracts common WASM functionality.
1373
+ * This serves as a foundation for specific ML capability providers
1374
+ * like FaceDetectionProvider and IdCaptureProvider.
1375
+ */
1376
+ var BaseWasmProvider = class {
1377
+ /**
1378
+ * Creates a new BaseWasmProvider
1379
+ * @param pipelineType - The WASM pipeline type this provider uses
1380
+ */
1381
+ constructor(pipelineType) {
1382
+ this._isInitialized = false;
1383
+ this.pipelineType = pipelineType;
1384
+ }
1385
+ /**
1386
+ * Returns whether this provider has been initialized.
1387
+ */
1388
+ get initialized() {
1389
+ return this._isInitialized;
1390
+ }
1391
+ getPipelineType() {
1392
+ if (this.pipelineType === void 0) throw new Error(`${this.constructor.name} has no pipeline type configured.`);
1393
+ return this.pipelineType;
1394
+ }
1395
+ /**
1396
+ * Initializes the provider by ensuring WASM is loaded
1397
+ * @param config - Provider configuration
1398
+ * @param pipeline - The pipeline type to warm up ('selfie', 'idCapture', etc.)
1399
+ */
1400
+ async initializeBase(config, pipeline) {
1401
+ if (this._isInitialized) return;
1402
+ if (getWasmStatus().isLoading || isWasmReady()) await waitForWasm();
1403
+ else {
1404
+ if (!config.wasmPath || !config.glueCodePath) throw new Error("WASM path and glue code path are required. Call warmupWasm() first.");
1405
+ await warmupWasm({
1406
+ wasmPath: config.wasmPath,
1407
+ wasmSimdPath: config.wasmSimdPath,
1408
+ glueCodePath: config.glueCodePath,
1409
+ useSimd: config.useSimd,
1410
+ modelsBasePath: config.modelsBasePath,
1411
+ pipelines: [pipeline]
1412
+ });
1413
+ }
1414
+ this._isInitialized = true;
1415
+ }
1416
+ /**
1417
+ * Ensures the provider is initialized before performing operations.
1418
+ * @throws Error if not initialized
1419
+ */
1420
+ ensureInitialized() {
1421
+ if (!this._isInitialized) throw new Error(`${this.constructor.name} not initialized. Call initialize() first.`);
1422
+ }
1423
+ /**
1424
+ * Processes a frame through the WASM pipeline
1425
+ * @param image - Image data to process
1426
+ */
1427
+ async processFrame(image) {
1428
+ this.ensureInitialized();
1429
+ const pipelineType = this.getPipelineType();
1430
+ await mlWasmJSApi_default.allocateImageBuffers(image.width, image.height);
1431
+ await mlWasmJSApi_default.process(image, pipelineType);
1432
+ }
1433
+ /**
1434
+ * Resets the pipeline to its initial state.
1435
+ * Safe to call even if not initialized (no-op in that case).
1436
+ */
1437
+ reset() {
1438
+ if (this._isInitialized && this.pipelineType !== void 0) mlWasmJSApi_default.resetPipeline(this.pipelineType);
1439
+ }
1440
+ /**
1441
+ * Disposes of resources and resets initialization state.
1442
+ * Safe to call even if not initialized.
1443
+ */
1444
+ async dispose() {
1445
+ this.reset();
1446
+ this._isInitialized = false;
1447
+ }
1448
+ };
1449
+
1450
+ //#endregion
1451
+ //#region ../infra/src/providers/wasm/FaceDetectionProvider.ts
1452
+ var FaceDetectionProvider = class extends BaseWasmProvider {
1453
+ constructor() {
1454
+ super(WasmPipelineType.SelfieWithQualityMetrics);
1455
+ this.defaultThresholds = {
1456
+ frameMinX: 0,
1457
+ frameMinY: 0,
1458
+ frameMaxX: 1,
1459
+ frameMaxY: 1,
1460
+ brightnessThreshold: 50,
1461
+ blurrinessThreshold: 50,
1462
+ tiltRotationAngleThreshold: 15,
1463
+ minMagicCropSize: 200,
1464
+ headwearThreshold: .86,
1465
+ lensesThreshold: .95,
1466
+ closedEyesThreshold: .9,
1467
+ maskThreshold: .85,
1468
+ minFaceQualityScore: .63,
1469
+ faceOcclusionThreshold: .3
1470
+ };
1471
+ this.currentFrame = null;
1472
+ this.bestCanvas = null;
1473
+ this.bestFace = null;
1474
+ }
1475
+ async processFrame(image) {
1476
+ this.currentFrame = image;
1477
+ await super.processFrame(image);
1478
+ }
1479
+ async initialize(config) {
1480
+ await this.initializeBase(config, "selfie");
1481
+ this.applyDefaults(config.autocaptureInterval ?? 0);
1482
+ }
1483
+ setCallbacks(callbacks) {
1484
+ this.ensureInitialized();
1485
+ const onBestShotWrapper = (face) => {
1486
+ this.bestFace = face;
1487
+ if (this.currentFrame) {
1488
+ const frameCanvas = IncodeCanvas.fromImageData(this.currentFrame);
1489
+ this.bestCanvas = frameCanvas.clone() ?? frameCanvas;
1490
+ }
1491
+ callbacks.onBestShot?.(face);
1492
+ };
1493
+ const onCaptureWrapper = () => {
1494
+ let frameCanvas = this.bestCanvas;
1495
+ if (!frameCanvas && this.currentFrame) frameCanvas = IncodeCanvas.fromImageData(this.currentFrame);
1496
+ if (!frameCanvas) return;
1497
+ const faceCoordinates = this.bestFace ? this.formatFaceCoordinates(this.bestFace) : this.createDefaultFaceCoordinates(frameCanvas);
1498
+ try {
1499
+ frameCanvas.updateBase64Image();
1500
+ frameCanvas.updateBlob();
1501
+ } catch {}
1502
+ callbacks.onCapture?.(frameCanvas, faceCoordinates);
1503
+ this.bestCanvas = null;
1504
+ this.bestFace = null;
1505
+ };
1506
+ 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 ?? (() => {}));
1507
+ }
1508
+ setPositionConstraints(constraints) {
1509
+ this.ensureInitialized();
1510
+ mlWasmJSApi_default.setFacePositionConstraints(this.getPipelineType(), constraints.minX, constraints.minY, constraints.maxX, constraints.maxY);
1511
+ }
1512
+ applyDefaults(autocaptureInterval = 0) {
1513
+ this.ensureInitialized();
1514
+ this.setThresholds({
1515
+ brightnessThreshold: this.defaultThresholds.brightnessThreshold,
1516
+ blurrinessThreshold: this.defaultThresholds.blurrinessThreshold,
1517
+ tiltRotationAngleThreshold: this.defaultThresholds.tiltRotationAngleThreshold,
1518
+ minMagicCropSize: this.defaultThresholds.minMagicCropSize,
1519
+ autocaptureInterval,
1520
+ minFaceQualityScore: this.defaultThresholds.minFaceQualityScore,
1521
+ faceOcclusionThreshold: this.defaultThresholds.faceOcclusionThreshold
1522
+ });
1523
+ this.setPositionConstraints({
1524
+ minX: this.defaultThresholds.frameMinX,
1525
+ minY: this.defaultThresholds.frameMinY,
1526
+ maxX: this.defaultThresholds.frameMaxX,
1527
+ maxY: this.defaultThresholds.frameMaxY
1528
+ });
1529
+ this.setAttributesThresholds({
1530
+ headwearThreshold: this.defaultThresholds.headwearThreshold,
1531
+ lensesThreshold: this.defaultThresholds.lensesThreshold,
1532
+ closedEyesThreshold: this.defaultThresholds.closedEyesThreshold,
1533
+ maskThreshold: this.defaultThresholds.maskThreshold
1534
+ });
1535
+ }
1536
+ setAutocaptureInterval(interval) {
1537
+ this.ensureInitialized();
1538
+ if (!this.currentThresholds) {
1539
+ this.applyDefaults(interval);
1540
+ return;
1541
+ }
1542
+ this.setThresholds({
1543
+ ...this.currentThresholds,
1544
+ autocaptureInterval: interval
1545
+ });
1546
+ }
1547
+ setThresholds(thresholds) {
1548
+ this.ensureInitialized();
1549
+ this.currentThresholds = { ...thresholds };
1550
+ mlWasmJSApi_default.setFaceDetectionThresholds(this.getPipelineType(), thresholds.brightnessThreshold, thresholds.blurrinessThreshold, thresholds.tiltRotationAngleThreshold, thresholds.minMagicCropSize, thresholds.autocaptureInterval, thresholds.minFaceQualityScore, thresholds.faceOcclusionThreshold);
1551
+ }
1552
+ setAttributesThresholds(thresholds) {
1553
+ this.ensureInitialized();
1554
+ mlWasmJSApi_default.setFaceAttributesThresholds(this.getPipelineType(), thresholds.headwearThreshold, thresholds.lensesThreshold, thresholds.closedEyesThreshold, thresholds.maskThreshold);
1555
+ }
1556
+ setChecksEnabled(config) {
1557
+ this.ensureInitialized();
1558
+ mlWasmJSApi_default.setFaceChecksEnabled(this.getPipelineType(), config.lenses, config.mask, config.closedEyes, config.headWear, config.occlusion);
1559
+ }
1560
+ setVideoSelfieMode(enabled) {
1561
+ this.ensureInitialized();
1562
+ mlWasmJSApi_default.setFaceDetectionMode(this.getPipelineType(), enabled);
1563
+ }
1564
+ reset() {
1565
+ super.reset();
1566
+ this.currentFrame = null;
1567
+ this.bestCanvas = null;
1568
+ this.bestFace = null;
1569
+ }
1570
+ createDefaultFaceCoordinates(canvas) {
1571
+ return {
1572
+ rightEyeX: 0,
1573
+ rightEyeY: 0,
1574
+ leftEyeX: 0,
1575
+ leftEyeY: 0,
1576
+ noseTipX: 0,
1577
+ noseTipY: 0,
1578
+ rightMouthX: 0,
1579
+ rightMouthY: 0,
1580
+ mouthX: 0,
1581
+ mouthY: 0,
1582
+ x: 0,
1583
+ y: 0,
1584
+ width: canvas.width() ?? 0,
1585
+ height: canvas.height() ?? 0
1586
+ };
1587
+ }
1588
+ formatFaceCoordinates(face) {
1589
+ return {
1590
+ rightEyeX: face.rightEye.x,
1591
+ rightEyeY: face.rightEye.y,
1592
+ leftEyeX: face.leftEye.x,
1593
+ leftEyeY: face.leftEye.y,
1594
+ noseTipX: face.noseTip.x,
1595
+ noseTipY: face.noseTip.y,
1596
+ rightMouthX: face.rightMouthCorner.x,
1597
+ rightMouthY: face.rightMouthCorner.y,
1598
+ mouthX: face.leftMouthCorner.x,
1599
+ mouthY: face.leftMouthCorner.y,
1600
+ x: face.rect.x,
1601
+ y: face.rect.y,
1602
+ width: face.rect.width,
1603
+ height: face.rect.height
1604
+ };
1605
+ }
1606
+ };
1607
+
1608
+ //#endregion
1609
+ //#region ../infra/src/providers/wasm/WasmUtilProvider.ts
1610
+ var WasmUtilProvider = class WasmUtilProvider extends BaseWasmProvider {
1611
+ static async getInstance() {
1612
+ if (WasmUtilProvider.instance) return WasmUtilProvider.instance;
1613
+ if (WasmUtilProvider.initPromise) return WasmUtilProvider.initPromise;
1614
+ WasmUtilProvider.initPromise = (async () => {
1615
+ const instance = new WasmUtilProvider();
1616
+ await instance.initializeBase({}, "selfie");
1617
+ WasmUtilProvider.instance = instance;
1618
+ return instance;
1619
+ })();
1620
+ return WasmUtilProvider.initPromise;
1621
+ }
1622
+ static resetInstance() {
1623
+ WasmUtilProvider.instance = void 0;
1624
+ WasmUtilProvider.initPromise = void 0;
1625
+ }
1626
+ constructor() {
1627
+ super(void 0);
1628
+ }
1629
+ async initialize(config) {
1630
+ if (this.initialized) return;
1631
+ const pipeline = config.pipelines?.[0] ?? "selfie";
1632
+ await this.initializeBase(config, pipeline);
1633
+ }
1634
+ encryptImage(image) {
1635
+ return mlWasmJSApi_default.ens(image);
1636
+ }
1637
+ };
1638
+
1639
+ //#endregion
1640
+ //#region src/internal/http/api.ts
1641
+ let client = null;
1642
+ let currentToken = null;
1643
+ function setClient(httpClient) {
1644
+ client = httpClient;
1645
+ }
1646
+ function setToken(token) {
1647
+ currentToken = token;
1648
+ }
1649
+ function getApi() {
1650
+ if (!client) throw new Error("SDK not configured. Call setup({ apiURL: \"...\" }) first.");
1651
+ return client;
1652
+ }
1653
+ function resetApi() {
1654
+ client = null;
1655
+ currentToken = null;
1656
+ }
1657
+ function addTokenHeader(config) {
1658
+ if (!currentToken) return config ?? {};
1659
+ return {
1660
+ ...config,
1661
+ headers: {
1662
+ ...config?.headers,
1663
+ "X-Incode-Hardware-Id": currentToken
1664
+ }
1665
+ };
1666
+ }
1667
+ const api = {
1668
+ get(url, config) {
1669
+ return getApi().get(url, addTokenHeader(config));
1670
+ },
1671
+ post(url, data, config) {
1672
+ return getApi().post(url, data, addTokenHeader(config));
1673
+ },
1674
+ put(url, data, config) {
1675
+ return getApi().put(url, data, addTokenHeader(config));
1676
+ },
1677
+ patch(url, data, config) {
1678
+ return getApi().patch(url, data, addTokenHeader(config));
1679
+ },
1680
+ delete(url, config) {
1681
+ return getApi().delete(url, addTokenHeader(config));
1682
+ }
1683
+ };
1684
+
1685
+ //#endregion
1686
+ //#region src/internal/http/endpoints.ts
1687
+ const endpoints = {
1688
+ createSession: "/omni/start",
1689
+ flow: "/omni/onboarding/flow",
1690
+ events: "/omni/interview-events",
1691
+ selfie: "/omni/add/face",
1692
+ recordingCreateSessionV2: "/omni/recordings/create-session/v2",
1693
+ recordingStartV2: "/omni/recordings/record-start/v2",
1694
+ recordingStopV2: "/omni/recordings/record-stop/v2",
1695
+ phone: "/omni/add/phone",
1696
+ phoneInstant: "/omni/instant/add/phone",
1697
+ getPhone: "/omni/get/phone",
1698
+ startInfo: "/omni/start-info",
1699
+ sendSmsOtp: "/omni/send/sms-otp",
1700
+ compareOtp: "/omni/compare/otp",
1701
+ email: "/omni/add/email",
1702
+ getEmail: "/omni/get/email"
1703
+ };
1704
+
1705
+ //#endregion
1706
+ 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 };