@exige/web-scanner-sdk 0.2.28 → 0.2.29

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.
@@ -1,1507 +0,0 @@
1
- //#region src/sdk/errors.ts
2
- var e = class extends Error {
3
- code;
4
- constructor(e, t) {
5
- super(t), this.name = "ScannerError", this.code = e;
6
- }
7
- };
8
- function t() {
9
- return new e("canvas", "Canvas 2D is unavailable in this browser.");
10
- }
11
- //#endregion
12
- //#region src/sdk/license-codec.ts
13
- function n(e) {
14
- let t = e.replaceAll("-", "+").replaceAll("_", "/"), n = t + "=".repeat((4 - t.length % 4) % 4), r = atob(n), i = new Uint8Array(r.length);
15
- for (let e = 0; e < r.length; e += 1) i[e] = r.charCodeAt(e);
16
- return i;
17
- }
18
- //#endregion
19
- //#region src/sdk/license-public-key.ts
20
- var r = "uFpA_UXGk-1AjjG31cFP6cqXOQX0w2TnuR7Bl-msZ6I";
21
- //#endregion
22
- //#region src/sdk/license-runtime.ts
23
- function i() {
24
- return n(r);
25
- }
26
- //#endregion
27
- //#region src/sdk/license.ts
28
- var a = [
29
- "localhost",
30
- "127.0.0.1",
31
- "exige-scanner-sdk.vercel.app",
32
- "*.localhost",
33
- "*.exige.io",
34
- "*.ngrok.io",
35
- "*.ngrok.app",
36
- "*.ngrok.dev",
37
- "*.ngrok-free.app",
38
- "*.ngrok-free.dev"
39
- ], o = class extends Error {
40
- code;
41
- constructor(e, t) {
42
- super(t), this.name = "LicenseError", this.code = e;
43
- }
44
- }, s, c;
45
- function l(e) {
46
- return e.trim().toLowerCase().replace(/\.$/u, "");
47
- }
48
- function u() {
49
- let e = globalThis.location?.hostname;
50
- if (typeof e == "string") return l(e) || void 0;
51
- }
52
- function d() {
53
- return Math.floor(Date.now() / 1e3);
54
- }
55
- function f(e, t) {
56
- let n = l(t);
57
- if (n.startsWith("*.")) {
58
- let t = n.slice(2), r = t === "localhost";
59
- return !t.includes(".") && !r || t.startsWith(".") || t.includes("*") ? !1 : e === t || e.endsWith(`.${t}`);
60
- }
61
- return e === n;
62
- }
63
- function p(e) {
64
- let t = l(e);
65
- return !t || t.includes("*") ? !1 : a.some((e) => f(t, e));
66
- }
67
- function m(e) {
68
- return {
69
- customerId: "dev",
70
- domains: [e],
71
- exp: 4102444800,
72
- features: {
73
- scan: !0,
74
- ocr: !0,
75
- redaction: !0,
76
- vehicles: !0,
77
- torch: !0
78
- }
79
- };
80
- }
81
- function h(e) {
82
- return {
83
- customerId: e.customerId,
84
- domains: [...e.domains],
85
- exp: e.exp,
86
- features: { ...e.features }
87
- };
88
- }
89
- function g(e = "This license key is not a signed payload.") {
90
- return new o("malformed", e);
91
- }
92
- function _(e) {
93
- if (!e || typeof e != "object" || Array.isArray(e)) throw g();
94
- let t = e;
95
- if (typeof t.customerId != "string" || t.customerId.trim() === "" || t.customerId.length > 200) throw g("This license key is missing a customer id.");
96
- if (!Array.isArray(t.domains) || t.domains.some((e) => typeof e != "string")) throw g("This license key is missing a domain list.");
97
- if (typeof t.exp != "number" || !Number.isSafeInteger(t.exp) || t.exp <= 0) throw g("This license key is missing a Unix expiry.");
98
- if (!t.features || typeof t.features != "object" || Array.isArray(t.features)) throw g("This license key is missing feature flags.");
99
- let n = t.features, r = [...new Set(t.domains.map((e) => l(e)).filter(Boolean))].sort();
100
- return {
101
- customerId: t.customerId.trim(),
102
- domains: r,
103
- exp: t.exp,
104
- features: {
105
- scan: n.scan === !0,
106
- ocr: n.ocr === !0,
107
- redaction: n.redaction === !0,
108
- vehicles: n.vehicles === !0,
109
- torch: n.torch === !0
110
- }
111
- };
112
- }
113
- async function v(e, t) {
114
- let r = e.trim().split(".");
115
- if (r.length !== 2 || !r[0] || !r[1]) throw g();
116
- let i, a;
117
- try {
118
- i = n(r[0]), a = n(r[1]);
119
- } catch {
120
- throw g();
121
- }
122
- let s, c = !1;
123
- try {
124
- s = await crypto.subtle.importKey("raw", t.publicKey, { name: "Ed25519" }, !1, ["verify"]), c = await crypto.subtle.verify("Ed25519", s, a, i);
125
- } catch {
126
- c = !1;
127
- }
128
- if (!c) throw new o("invalid-signature", "This license key signature does not match the SDK public key.");
129
- let u;
130
- try {
131
- u = JSON.parse(new TextDecoder().decode(i));
132
- } catch {
133
- throw g();
134
- }
135
- let d = _(u);
136
- if (d.exp <= t.now) throw new o("expired", "This license key has expired.");
137
- let f = l(t.hostname);
138
- if (!f || !d.domains.includes(f)) throw new o("domain", `This license key is not valid for ${f || "this host"}.`);
139
- return d;
140
- }
141
- async function y(e) {
142
- let t = u();
143
- if (!t) throw new o("domain", "The license check requires a browser hostname.");
144
- let n = await v(e, {
145
- publicKey: i(),
146
- hostname: t,
147
- now: d()
148
- });
149
- return s = e.trim(), c = n, h(n);
150
- }
151
- function b() {
152
- let e = u();
153
- return c && e && c.domains.includes(e) && c.exp > d() ? h(c) : !s && e && p(e) ? h(m(e)) : null;
154
- }
155
- async function x(e) {
156
- let t = u();
157
- if (!t) throw new o("domain", "The license check requires a browser hostname.");
158
- if (!s) {
159
- if (p(t)) return h(m(t));
160
- throw new o("missing", "A license key is required. Call setLicenseKey() before using the scanner SDK.");
161
- }
162
- let n = await v(s, {
163
- publicKey: i(),
164
- hostname: t,
165
- now: d()
166
- });
167
- if (c = n, !n.features[e]) throw new o("feature", `This license key does not include the ${e} feature.`);
168
- return h(n);
169
- }
170
- //#endregion
171
- //#region src/sdk/model-download.ts
172
- var S = Symbol.for("exige.web-scanner-sdk.model-downloads");
173
- function C() {
174
- let e = globalThis;
175
- return e[S] || (e[S] = {
176
- active: /* @__PURE__ */ new Map(),
177
- listeners: /* @__PURE__ */ new Set(),
178
- cache: /* @__PURE__ */ new Map(),
179
- inflight: /* @__PURE__ */ new Map()
180
- }), e[S];
181
- }
182
- var w = C().active, T = C().listeners, E = C().cache, D = C().inflight;
183
- function ee(e) {
184
- let t = Number(e.headers.get("content-length"));
185
- return Number.isFinite(t) && t > 0 ? t : null;
186
- }
187
- function O() {
188
- if (w.size === 0) return {
189
- downloading: !1,
190
- loaded: 0,
191
- total: null
192
- };
193
- let e = 0, t = 0, n = !0;
194
- for (let r of w.values()) e += r.loaded, r.total == null ? n = !1 : t += r.total;
195
- return {
196
- downloading: !0,
197
- loaded: e,
198
- total: n ? t : null
199
- };
200
- }
201
- function te() {
202
- let e = O();
203
- for (let t of T) t(e);
204
- }
205
- function ne(e) {
206
- return e(O()), T.add(e), () => {
207
- T.delete(e);
208
- };
209
- }
210
- function k(e, t) {
211
- t.done ? w.delete(e) : w.set(e, {
212
- loaded: t.loaded,
213
- total: t.total
214
- }), te();
215
- }
216
- async function re(e, t) {
217
- let n = ee(e);
218
- if (!e.body) {
219
- let r = await e.arrayBuffer();
220
- return t?.({
221
- loaded: r.byteLength,
222
- total: n ?? r.byteLength
223
- }), r;
224
- }
225
- let r = e.body.getReader(), i = [], a = 0;
226
- for (;;) {
227
- let { done: e, value: o } = await r.read();
228
- if (e) break;
229
- o?.byteLength && (i.push(o), a += o.byteLength, t?.({
230
- loaded: a,
231
- total: n
232
- }));
233
- }
234
- let o = new Uint8Array(a), s = 0;
235
- for (let e of i) o.set(e, s), s += e.byteLength;
236
- return a === 0 && t?.({
237
- loaded: 0,
238
- total: n
239
- }), o.buffer;
240
- }
241
- async function ie(t, n) {
242
- let r = E.get(t);
243
- if (r) return r.slice(0);
244
- let i = D.get(t);
245
- if (i) return i.then((e) => e.slice(0));
246
- let a = (async () => {
247
- k(t, {
248
- loaded: 0,
249
- total: null
250
- });
251
- let r = await fetch(t, { cache: n?.cache });
252
- if (!r.ok) throw new e("model-http", `Model request failed with HTTP ${r.status}.`);
253
- return re(r, (e) => k(t, e));
254
- })();
255
- D.set(t, a);
256
- try {
257
- let e = await a;
258
- return E.set(t, e), e.slice(0);
259
- } finally {
260
- D.delete(t), w.has(t) && (w.delete(t), te());
261
- }
262
- }
263
- //#endregion
264
- //#region src/sdk/camera.ts
265
- function ae(e, t) {
266
- let { engine: n } = t;
267
- return [
268
- `${e}:`,
269
- ` engine: ${n.engine}/${n.browser}${n.iosWebKit ? " ios-webkit" : ""}`,
270
- ` ua: ${n.userAgent}`,
271
- ` video: ${t.videoWidth}x${t.videoHeight} readyState=${t.readyState}${t.paused ? " paused" : ""}${t.rendered ? "" : " hidden"}${t.connected ? "" : " disconnected"}`,
272
- ` track: ${t.trackReadyState}${t.trackEnabled ? "" : " disabled"}${t.trackMuted ? " muted" : ""}`,
273
- ` liveLuma: ${t.liveLuminance.toFixed(1)}`,
274
- ` mirrorLuma: ${t.mirrorLuminance.toFixed(1)}`,
275
- ` mirrorAgeMs: ${Number.isFinite(t.mirrorAgeMs) ? Math.round(t.mirrorAgeMs) : "none"}`,
276
- ` hasImageCapture: ${t.hasImageCapture}${t.engine.iosWebKit ? " (skipped on webkit)" : " (still capture)"}`,
277
- ` torch: ${t.torch.mode} supported=${t.torch.supported} on=${t.torch.on}`
278
- ].join("\n");
279
- }
280
- function oe(e) {
281
- let t = ["Exige scanner capture report", `time: ${e.capturedAt ?? (/* @__PURE__ */ new Date()).toISOString()}`];
282
- if (e.error && t.push(`error: ${e.error}`), e.captureMethod && t.push(`method: ${e.captureMethod}`), e.luminance !== void 0 && t.push(`luminance: ${e.luminance.toFixed(1)}`), e.fallbackReason && t.push(`fallback: ${e.fallbackReason}`), e.shutter && t.push(ae("shutter", e.shutter)), e.live && t.push(ae("live", e.live)), e.finder) {
283
- let n = e.finder;
284
- t.push([
285
- "finder:",
286
- ` state: ${n.state ?? "unknown"}`,
287
- ` confidence: ${n.confidence === void 0 ? "—" : n.confidence.toFixed(3)}`,
288
- ` stable: ${n.stableFrames ?? "—"}/${n.requiredStableFrames ?? "—"}`,
289
- ` detector: ${n.detector ?? "—"} ${n.modelStatus ?? ""}`.trim(),
290
- ` modelError: ${n.modelError ?? "—"}`,
291
- ` provider: ${n.modelProvider ?? "—"}`,
292
- ` note: ${n.modelNote ?? "—"}`,
293
- ` inferenceMs: ${n.inferenceMs === void 0 ? "—" : Math.round(n.inferenceMs)}`,
294
- ` source: ${n.sourceWidth ?? "—"}x${n.sourceHeight ?? "—"}`
295
- ].join("\n"));
296
- }
297
- return `${t.join("\n")}\n`;
298
- }
299
- function A(e = typeof navigator > "u" ? "" : navigator.userAgent, t = typeof navigator > "u" ? 0 : navigator.maxTouchPoints) {
300
- let n = /CriOS|Chrome/i.test(e) ? "chrome" : /EdgiOS|Edg/i.test(e) ? "edge" : /FxiOS|Firefox/i.test(e) ? "firefox" : /Safari/i.test(e) ? "safari" : "unknown", r = /iPhone|iPad|iPod/i.test(e) || /Macintosh/i.test(e) && t > 1, i = /CriOS|EdgiOS|FxiOS|OPiOS|Mercury/i.test(e), a = r || i;
301
- return {
302
- engine: a || /AppleWebKit/i.test(e) && !/Chrome|Chromium|Edg/i.test(e) ? "webkit" : /Chrome|Chromium|Edg/i.test(e) ? "blink" : /Gecko\//i.test(e) ? "gecko" : "unknown",
303
- browser: n,
304
- iosWebKit: a,
305
- userAgent: e
306
- };
307
- }
308
- function j(e) {
309
- return /Android/i.test(e.userAgent) && !e.iosWebKit;
310
- }
311
- function M(e = A()) {
312
- return e.engine === "webkit" && !j(e);
313
- }
314
- function se(e = "auto", t = A()) {
315
- return e === "system-camera" || e !== "live" && j(t);
316
- }
317
- function ce(e, t) {
318
- return t && !e.iosWebKit;
319
- }
320
- function N(e, t) {
321
- if (!e || !Number.isFinite(e)) return;
322
- let n = t?.max;
323
- if (!n || !Number.isFinite(n)) return Math.round(e);
324
- let r = t?.min && Number.isFinite(t.min) ? t.min : 1, i = t?.step && t.step > 0 ? t.step : 1, a = r + Math.round((Math.min(n, Math.max(r, e)) - r) / i) * i;
325
- return Math.round(Math.min(n, Math.max(r, a)));
326
- }
327
- function le(e) {
328
- let t = N(e?.imageWidth?.max ?? 0, e?.imageWidth), n = N(e?.imageHeight?.max ?? 0, e?.imageHeight);
329
- if (t && n) return t >= n ? { imageWidth: t } : { imageHeight: n };
330
- if (t) return { imageWidth: t };
331
- if (n) return { imageHeight: n };
332
- }
333
- function ue(e, t) {
334
- return !e.width || !e.height || !t.width || !t.height ? !1 : e.width * e.height > t.width * t.height * 1.15;
335
- }
336
- function de(e, t) {
337
- if (!e.width || !e.height || !t.width || !t.height) return !1;
338
- let n = e.width / e.height / (t.width / t.height);
339
- return n > .97 && n < 1.03;
340
- }
341
- var fe = 10, P = class {
342
- on = !1;
343
- darkCount = 0;
344
- brightCount = 0;
345
- turnOnLuminance;
346
- turnOffLuminance;
347
- darkSamples;
348
- brightSamples;
349
- constructor(e = {}) {
350
- this.turnOnLuminance = e.turnOnLuminance ?? 62, this.turnOffLuminance = e.turnOffLuminance ?? 155, this.darkSamples = e.darkSamples ?? 3, this.brightSamples = e.brightSamples ?? 8;
351
- }
352
- update(e) {
353
- if (!Number.isFinite(e) || e <= 10) {
354
- this.darkCount = 0, this.brightCount = 0;
355
- return;
356
- }
357
- if (!this.on) return this.brightCount = 0, this.darkCount = e <= this.turnOnLuminance ? this.darkCount + 1 : 0, this.darkCount < this.darkSamples ? void 0 : (this.darkCount = 0, this.on = !0, !0);
358
- if (this.darkCount = 0, this.brightCount = e >= this.turnOffLuminance ? this.brightCount + 1 : 0, !(this.brightCount < this.brightSamples)) return this.brightCount = 0, this.on = !1, !1;
359
- }
360
- getState() {
361
- return this.on;
362
- }
363
- };
364
- function F(e, t) {
365
- return t ? e === "alwaysOn" || e === "alwaysOff" ? {
366
- mode: e,
367
- supported: !0,
368
- on: e === "alwaysOn",
369
- visible: !1,
370
- mutable: !1,
371
- automatic: !1
372
- } : {
373
- mode: e,
374
- supported: !0,
375
- on: e === "defaultOn",
376
- visible: !0,
377
- mutable: e !== "auto",
378
- automatic: e === "auto"
379
- } : {
380
- mode: e,
381
- supported: !1,
382
- on: !1,
383
- visible: !1,
384
- mutable: !1,
385
- automatic: e === "auto"
386
- };
387
- }
388
- function I(e) {
389
- let t = Math.floor(e.length / 4);
390
- if (!t) return 0;
391
- let n = 0;
392
- for (let r = 0; r < t * 4; r += 4) n += e[r] * .299 + e[r + 1] * .587 + e[r + 2] * .114;
393
- return n / t;
394
- }
395
- function pe(e, t = 10) {
396
- if (e.length < 4) return !0;
397
- let n = Math.floor(e.length / 4), r = 0;
398
- for (let i = 0; i < n * 4; i += 4) e[i] * .299 + e[i + 1] * .587 + e[i + 2] * .114 > t * 2 && (r += 1);
399
- return I(e) <= t && r / n < .01;
400
- }
401
- function me(e, t, n) {
402
- if (!t || !n) return 0;
403
- let r = document.createElement("canvas");
404
- r.width = Math.min(32, t), r.height = Math.min(32, n);
405
- let i = r.getContext("2d", { willReadFrequently: !0 });
406
- return i ? (i.drawImage(e, 0, 0, r.width, r.height), I(i.getImageData(0, 0, r.width, r.height).data)) : 0;
407
- }
408
- function he(e) {
409
- return me(e, e.width, e.height);
410
- }
411
- function ge(e, t = 120) {
412
- let n = document.createElement("canvas"), r = n.getContext("2d"), i = typeof e.requestVideoFrameCallback == "function", a = !0, o = 0, s = 0, c = 0, l = 0, u = 0, d = () => {
413
- a && (o = i ? e.requestVideoFrameCallback(f) : requestAnimationFrame(f));
414
- };
415
- function f() {
416
- if (!a) return;
417
- let { videoWidth: i, videoHeight: o } = e, f = performance.now();
418
- r && i && o && f - s >= t && (s = f, l = me(e, i, o), l > 10 && ((n.width !== i || n.height !== o) && (n.width = i, n.height = o), r.drawImage(e, 0, 0, i, o), u = l, c = f)), d();
419
- }
420
- return d(), {
421
- stop() {
422
- a = !1, i ? e.cancelVideoFrameCallback?.(o) : cancelAnimationFrame(o);
423
- },
424
- getFrame: () => c ? n : void 0,
425
- getLiveLuminance: () => l,
426
- getMirrorLuminance: () => u,
427
- getMirrorAgeMs: () => c ? performance.now() - c : Infinity
428
- };
429
- }
430
- function _e(e) {
431
- let t = document.createElement("canvas");
432
- return t.width = e.width, t.height = e.height, t.getContext("2d")?.drawImage(e, 0, 0), t;
433
- }
434
- function ve(e) {
435
- return e.engine === "blink";
436
- }
437
- function L(e = {}, t = A()) {
438
- let n = { ideal: e.idealWidth ?? 3840 }, r = { ideal: e.idealHeight ?? 2160 };
439
- e.maxWidth && (n.max = e.maxWidth), e.maxHeight && (r.max = e.maxHeight);
440
- let i = {
441
- facingMode: { ideal: e.facingMode ?? "environment" },
442
- width: n,
443
- height: r,
444
- frameRate: {
445
- ideal: e.maxFrameRate ?? 30,
446
- max: e.maxFrameRate ?? 30
447
- }
448
- };
449
- return ve(t) && (i.resizeMode = { ideal: "none" }), {
450
- audio: !1,
451
- video: i
452
- };
453
- }
454
- function ye(e, t, n) {
455
- let r = n ? Math.min(1, n / Math.max(e, t)) : 1;
456
- return {
457
- width: Math.max(1, Math.round(e * r)),
458
- height: Math.max(1, Math.round(t * r))
459
- };
460
- }
461
- var R = 4096;
462
- function be(e, t) {
463
- let n = e.width, r = e.height, i = t?.width?.max, a = t?.height?.max;
464
- if (!n || !r || !i || !a) return;
465
- let o = Math.min(i / n, a / r);
466
- if (!(o <= 1.05)) return {
467
- width: { ideal: Math.round(n * o) },
468
- height: { ideal: Math.round(r * o) }
469
- };
470
- }
471
- async function xe(e) {
472
- let t = be(e.getSettings(), typeof e.getCapabilities == "function" ? e.getCapabilities() : void 0);
473
- if (t) try {
474
- await e.applyConstraints(t);
475
- } catch {}
476
- }
477
- async function Se(e) {
478
- try {
479
- return await createImageBitmap(e, {
480
- imageOrientation: "from-image",
481
- colorSpaceConversion: "none"
482
- });
483
- } catch {
484
- return await createImageBitmap(e);
485
- }
486
- }
487
- async function Ce(e) {
488
- try {
489
- await e.applyConstraints({ advanced: [{ pointsOfInterest: [{
490
- x: .5,
491
- y: .5
492
- }] }] }), await new Promise((e) => window.setTimeout(e, 180));
493
- } catch {}
494
- }
495
- async function z(e) {
496
- let n = await Se(e), r = ye(n.width, n.height, R), i = document.createElement("canvas");
497
- i.width = r.width, i.height = r.height;
498
- let a = i.getContext("2d");
499
- if (!a) throw n.close?.(), t();
500
- return a.imageSmoothingEnabled = r.width !== n.width || r.height !== n.height, a.imageSmoothingQuality = "high", a.drawImage(n, 0, 0, i.width, i.height), n.close?.(), i;
501
- }
502
- async function we(e) {
503
- let t = globalThis.ImageCapture;
504
- if (!t) return;
505
- await Ce(e);
506
- let n = new t(e), r = n.getPhotoCapabilities ? await n.getPhotoCapabilities() : void 0, i = le(r), a;
507
- try {
508
- a = await n.takePhoto(i);
509
- } catch {
510
- a = await n.takePhoto();
511
- }
512
- return {
513
- frame: await z(a),
514
- requested: i,
515
- photoMax: {
516
- width: r?.imageWidth?.max,
517
- height: r?.imageHeight?.max
518
- }
519
- };
520
- }
521
- function B(e, n) {
522
- if (!e.videoWidth || !e.videoHeight) throw Error("The camera is not ready to capture a frame.");
523
- let r = ye(e.videoWidth, e.videoHeight, n), i = document.createElement("canvas");
524
- i.width = r.width, i.height = r.height;
525
- let a = i.getContext("2d");
526
- if (!a) throw t();
527
- return a.drawImage(e, 0, 0, i.width, i.height), i;
528
- }
529
- function Te(e) {
530
- let t = A();
531
- return e.idealWidth || e.idealHeight || e.maxWidth || e.maxHeight ? [L(e, t)] : [
532
- L({
533
- ...e,
534
- idealWidth: 3840,
535
- idealHeight: 2160
536
- }, t),
537
- L({
538
- ...e,
539
- idealWidth: 2560,
540
- idealHeight: 1440
541
- }, t),
542
- L({
543
- ...e,
544
- idealWidth: 1920,
545
- idealHeight: 1080
546
- }, t)
547
- ];
548
- }
549
- async function Ee(t, n = {}) {
550
- await x("scan");
551
- let r = n.torch ?? "alwaysOff";
552
- if (r !== "alwaysOff" && await x("torch"), !window.isSecureContext && location.hostname !== "localhost") throw new e("secure-context", "Camera access requires HTTPS.");
553
- if (!navigator.mediaDevices?.getUserMedia) throw Error("Live camera access is unavailable. Use the native camera picker instead.");
554
- t.muted = !0, t.autoplay = !0, t.playsInline = !0, t.setAttribute("playsinline", "");
555
- let i, a;
556
- for (let e of Te(n)) try {
557
- i = await navigator.mediaDevices.getUserMedia(e);
558
- break;
559
- } catch (e) {
560
- if (a = e, !(e instanceof DOMException) || e.name !== "OverconstrainedError") throw e;
561
- }
562
- if (!i) throw a ?? /* @__PURE__ */ Error("No rear camera resolution is available.");
563
- t.srcObject = i, await t.play();
564
- let o = i.getVideoTracks()[0];
565
- if (!o) {
566
- for (let e of i.getTracks()) e.stop();
567
- throw Error("The camera did not provide a video track.");
568
- }
569
- await xe(o);
570
- let s = ge(t), c = "ImageCapture" in globalThis, l = F(r, (typeof o.getCapabilities == "function" ? o.getCapabilities() : void 0)?.torch === !0), u = !1, d = async (e) => {
571
- if (!l.supported || o.readyState !== "live") return !1;
572
- try {
573
- return await o.applyConstraints({ advanced: [{ torch: e }] }), l = {
574
- ...l,
575
- on: e
576
- }, !0;
577
- } catch {
578
- return l = {
579
- ...l,
580
- supported: !1,
581
- on: !1,
582
- visible: !1,
583
- mutable: !1
584
- }, !1;
585
- }
586
- };
587
- l.on && await d(!0);
588
- let f = r === "auto" && l.supported ? new P() : void 0, p = f ? window.setInterval(() => {
589
- if (u || !l.supported) return;
590
- let e = f.update(s.getLiveLuminance());
591
- e !== void 0 && e !== l.on && (u = !0, d(e).finally(() => {
592
- u = !1;
593
- }));
594
- }, 350) : 0, m = () => {
595
- let e = t.getBoundingClientRect();
596
- return {
597
- videoWidth: t.videoWidth,
598
- videoHeight: t.videoHeight,
599
- readyState: t.readyState,
600
- paused: t.paused,
601
- connected: t.isConnected,
602
- rendered: e.width > 0 && e.height > 0,
603
- trackReadyState: o.readyState ?? "missing",
604
- trackEnabled: o.enabled,
605
- trackMuted: o.muted,
606
- liveLuminance: s.getLiveLuminance(),
607
- mirrorLuminance: s.getMirrorLuminance(),
608
- mirrorAgeMs: s.getMirrorAgeMs(),
609
- hasImageCapture: c,
610
- torchMode: l.mode,
611
- torchSupported: l.supported,
612
- torchOn: l.on,
613
- torch: { ...l },
614
- engine: A()
615
- };
616
- };
617
- return {
618
- stream: i,
619
- get torchMode() {
620
- return l.mode;
621
- },
622
- get torchSupported() {
623
- return l.supported;
624
- },
625
- get torchOn() {
626
- return l.on;
627
- },
628
- capture: (e) => B(t, e),
629
- async capturePhoto() {
630
- let e, n = 0;
631
- try {
632
- e = B(t), n = he(e);
633
- } catch {
634
- e = void 0;
635
- }
636
- let r = s.getFrame(), i, a = !1, l = !1, u, d;
637
- if (ce(A(), c)) try {
638
- let e = await we(o);
639
- i = e?.frame, u = e?.requested, d = e?.photoMax;
640
- } catch {
641
- a = !0, i = void 0;
642
- }
643
- let f = {
644
- width: t.videoWidth,
645
- height: t.videoHeight
646
- }, p = i ? he(i) : 0, h = !!(i && p > 10 && ue(i, f));
647
- if (i && p > 10 && !h && (l = !0), h && i) return console.info("[exige-scanner] capture", {
648
- method: "image-capture",
649
- frame: `${i.width}×${i.height}`,
650
- video: `${t.videoWidth}×${t.videoHeight}`,
651
- photoMax: d ? `${d.width ?? "—"}×${d.height ?? "—"}` : void 0,
652
- photoRequest: u,
653
- aspectMatch: de(i, f)
654
- }), {
655
- frame: i,
656
- method: "image-capture",
657
- settings: o.getSettings(),
658
- luminance: p,
659
- diagnostics: m()
660
- };
661
- let g = e && n > 10 ? e : void 0, _ = g ?? (r ? _e(r) : void 0);
662
- if (!_) throw Error("The camera preview produced no visible pixels. Keep the scanner on screen, wait for the preview, and retake.");
663
- let v = l ? "image-capture-preview-size" : i ? "image-capture-empty" : a ? "image-capture-failed" : g ? void 0 : "video-frame-empty";
664
- return console.info("[exige-scanner] capture", {
665
- method: g ? "video-frame" : "live-mirror",
666
- frame: `${_.width}×${_.height}`,
667
- video: `${t.videoWidth}×${t.videoHeight}`,
668
- photoMax: d ? `${d.width ?? "—"}×${d.height ?? "—"}` : void 0,
669
- photoRequest: u,
670
- fallbackReason: v
671
- }), {
672
- frame: _,
673
- method: g ? "video-frame" : "live-mirror",
674
- settings: o.getSettings(),
675
- fallbackReason: v,
676
- luminance: g ? n : s.getMirrorLuminance(),
677
- diagnostics: m()
678
- };
679
- },
680
- getSettings: () => o.getSettings(),
681
- getDiagnostics: m,
682
- getTorchStatus: () => ({ ...l }),
683
- async setTorch(e) {
684
- return l.mutable ? d(e) : !1;
685
- },
686
- stop() {
687
- p && window.clearInterval(p), s.stop();
688
- for (let e of i.getTracks()) e.stop();
689
- t.srcObject === i && (t.srcObject = null);
690
- }
691
- };
692
- }
693
- function De() {
694
- let e = typeof navigator > "u" ? void 0 : navigator.userActivation;
695
- return !e || e.isActive;
696
- }
697
- async function Oe() {
698
- let e = document.createElement("input");
699
- return e.type = "file", e.accept = "image/*", e.capture = "environment", e.setAttribute("capture", "environment"), z(await new Promise((t, n) => {
700
- e.addEventListener("change", () => {
701
- let r = e.files?.[0];
702
- r ? t(r) : n(/* @__PURE__ */ Error("No photo was selected."));
703
- }, { once: !0 }), e.addEventListener("cancel", () => {
704
- n(/* @__PURE__ */ Error("No photo was selected."));
705
- }, { once: !0 }), e.click();
706
- }));
707
- }
708
- //#endregion
709
- //#region src/sdk/ort-runtime.ts
710
- var ke = new URL("./assets/ort-wasm-simd-threaded.jsep.wasm", import.meta.url), Ae = new URL("./assets/ort-wasm-simd-threaded.jsep.mjs", import.meta.url);
711
- function V() {
712
- return {
713
- wasm: ke.href,
714
- mjs: Ae.href
715
- };
716
- }
717
- function je(e) {
718
- return typeof e == "string" ? e.trim() || V() : e?.wasm.trim() && e.mjs.trim() ? {
719
- wasm: e.wasm.trim(),
720
- mjs: e.mjs.trim()
721
- } : V();
722
- }
723
- //#endregion
724
- //#region src/sdk/image.ts
725
- function H(e, t, n) {
726
- let r = n ? Math.min(1, n / Math.max(e, t)) : 1;
727
- return {
728
- width: Math.max(1, Math.round(e * r)),
729
- height: Math.max(1, Math.round(t * r))
730
- };
731
- }
732
- async function Me(e) {
733
- let t = URL.createObjectURL(e);
734
- try {
735
- let e = new Image();
736
- return e.src = t, await e.decode(), e;
737
- } finally {
738
- URL.revokeObjectURL(t);
739
- }
740
- }
741
- async function U(e, n = {}) {
742
- if (e instanceof HTMLCanvasElement && n.cloneCanvas === !1 && !n.maxDimension) return e;
743
- let r = document.createElement("canvas"), i = r.getContext("2d", { willReadFrequently: !0 });
744
- if (!i) throw t();
745
- if (e instanceof Blob) {
746
- if ("createImageBitmap" in window) try {
747
- let t = await createImageBitmap(e), a = H(t.width, t.height, n.maxDimension);
748
- return r.width = a.width, r.height = a.height, i.drawImage(t, 0, 0, a.width, a.height), t.close(), r;
749
- } catch {}
750
- e = await Me(e);
751
- }
752
- let a = e instanceof HTMLImageElement ? e.naturalWidth : e.width, o = e instanceof HTMLImageElement ? e.naturalHeight : e.height;
753
- if (!a || !o) throw Error("The image has no readable dimensions.");
754
- let s = H(a, o, n.maxDimension);
755
- return r.width = s.width, r.height = s.height, i.drawImage(e, 0, 0, s.width, s.height), r;
756
- }
757
- function Ne(e, t = "image/png", n = .92) {
758
- return new Promise((r, i) => e.toBlob((e) => e ? r(e) : i(/* @__PURE__ */ Error("Could not encode the image.")), t, n));
759
- }
760
- function Pe(e, t, n) {
761
- let r = Math.max(0, Math.min(t, e.x)), i = Math.max(0, Math.min(n, e.y));
762
- return {
763
- x: r,
764
- y: i,
765
- width: Math.max(0, Math.min(t - r, e.width)),
766
- height: Math.max(0, Math.min(n - i, e.height))
767
- };
768
- }
769
- //#endregion
770
- //#region src/sdk/scan.ts
771
- var Fe = "https://exige-scanner-sdk.vercel.app/models/docaligner-lcnet100-f4117b78.onnx", Ie = 1280;
772
- function Le(e, t, n) {
773
- if (n) return n;
774
- let r = Math.max(e, t), i = r / Math.max(1, Math.min(e, t)), a = Ve() ? 560 : 900;
775
- return i >= 1.6 ? Math.min(r, Math.max(a, Ie)) : a;
776
- }
777
- function W(e) {
778
- return e?.trim() || "https://exige-scanner-sdk.vercel.app/models/docaligner-lcnet100-f4117b78.onnx";
779
- }
780
- var Re = 3, G, ze = 0, K = /* @__PURE__ */ new Map();
781
- function q(e, t) {
782
- return Math.hypot(e.x - t.x, e.y - t.y);
783
- }
784
- function J(e) {
785
- return {
786
- ...e,
787
- edges: {
788
- top: {
789
- start: e.topLeft,
790
- end: e.topRight
791
- },
792
- right: {
793
- start: e.topRight,
794
- end: e.bottomRight
795
- },
796
- bottom: {
797
- start: e.bottomRight,
798
- end: e.bottomLeft
799
- },
800
- left: {
801
- start: e.bottomLeft,
802
- end: e.topLeft
803
- }
804
- }
805
- };
806
- }
807
- function Be(e, t) {
808
- let n = (e) => ({
809
- x: e.x / t,
810
- y: e.y / t
811
- });
812
- return {
813
- topLeft: n(e.topLeft),
814
- topRight: n(e.topRight),
815
- bottomRight: n(e.bottomRight),
816
- bottomLeft: n(e.bottomLeft)
817
- };
818
- }
819
- function Ve() {
820
- return typeof navigator > "u" ? !1 : navigator.maxTouchPoints > 0 || navigator.hardwareConcurrency <= 4 || typeof matchMedia == "function" && matchMedia("(pointer: coarse)").matches;
821
- }
822
- function He(t, n, r, i) {
823
- return new Promise((a, o) => {
824
- G || (G = new Worker(new URL("./assets/document-worker.js", import.meta.url), { type: "module" }), G.onmessage = (t) => {
825
- if (t.data.download?.url) {
826
- k(t.data.download.url, t.data.download);
827
- return;
828
- }
829
- let n = K.get(t.data.id);
830
- n && (K.delete(t.data.id), t.data.error ? n.reject(t.data.errorCode ? new e(t.data.errorCode, t.data.error) : Error(t.data.error)) : t.data.result ? n.resolve(t.data.result) : n.reject(/* @__PURE__ */ Error("The document worker returned no result.")));
831
- }, G.onerror = () => {
832
- let t = new e("worker", "The document worker could not start.");
833
- for (let e of K.values()) e.reject(t);
834
- K.clear(), G?.terminate(), G = void 0;
835
- });
836
- let s = ++ze;
837
- K.set(s, {
838
- resolve: a,
839
- reject: o
840
- });
841
- let c = t.slice().buffer;
842
- G.postMessage({
843
- id: s,
844
- pixels: c,
845
- width: n,
846
- height: r,
847
- modelUrl: W(i.modelUrl),
848
- heatmapThreshold: i.heatmapThreshold,
849
- cacheModel: i.cacheModel,
850
- ortWasmPaths: je(i.ortWasmPaths),
851
- preferWebGpu: i.preferWebGpu ?? M()
852
- }, [c]);
853
- });
854
- }
855
- async function Y(n, r) {
856
- let { width: i, height: a } = n, o = r.minDimension ?? 360;
857
- if (Math.min(i, a) < o) return {
858
- status: "low-quality",
859
- confidence: 0,
860
- message: `Use an image at least ${o}px on its shortest side.`,
861
- sourceWidth: i,
862
- sourceHeight: a
863
- };
864
- let s = Le(i, a, r.maxAnalysisDimension), c = Math.min(1, s / Math.max(i, a)), l = Math.max(1, Math.round(i * c)), u = Math.max(1, Math.round(a * c)), d;
865
- if (c === 1) {
866
- let e = n.getContext("2d", { willReadFrequently: !0 });
867
- if (!e) throw t();
868
- d = e.getImageData(0, 0, l, u).data;
869
- } else {
870
- let e = document.createElement("canvas");
871
- e.width = l, e.height = u;
872
- let r = e.getContext("2d", { willReadFrequently: !0 });
873
- if (!r) throw t();
874
- r.drawImage(n, 0, 0, e.width, e.height), d = r.getImageData(0, 0, e.width, e.height).data;
875
- }
876
- let f;
877
- if (r.useWorker !== !1 && typeof Worker < "u") try {
878
- f = await He(d, l, u, r);
879
- } catch (t) {
880
- if (t instanceof e && (t.code === "worker" || t.code === "model-http")) throw t;
881
- f = {
882
- sharpness: 20,
883
- detector: "ml",
884
- modelStatus: "failed",
885
- modelError: t instanceof Error ? t.message : "Document worker failed."
886
- };
887
- }
888
- else f = {
889
- sharpness: 20,
890
- detector: "ml",
891
- modelStatus: "failed",
892
- modelError: "ML detection requires a Web Worker."
893
- };
894
- let { sharpness: p, candidate: m, detector: h, modelStatus: g, modelProvider: _, modelError: v, modelNote: y, inferenceMs: b } = f, x = {
895
- detector: h,
896
- modelStatus: g,
897
- modelProvider: _,
898
- modelError: v,
899
- modelNote: y,
900
- inferenceMs: b
901
- };
902
- if (p < Re) return {
903
- status: "low-quality",
904
- confidence: Math.min(.3, p / 18),
905
- message: "The image is too soft or dark to resolve four document edges.",
906
- sourceWidth: i,
907
- sourceHeight: a,
908
- ...x
909
- };
910
- if (!m) return {
911
- status: "no-document",
912
- confidence: 0,
913
- message: "No document corners found. Place all four edges on a contrasting surface.",
914
- sourceWidth: i,
915
- sourceHeight: a,
916
- ...x
917
- };
918
- let S = Be(m.corners, c), C = J(S), w = r.minConfidence ?? .58;
919
- return m.confidence < w ? {
920
- status: "low-confidence",
921
- quad: C,
922
- corners: S,
923
- confidence: m.confidence,
924
- message: "Four possible corners were found, but the geometry is not reliable enough to crop.",
925
- sourceWidth: i,
926
- sourceHeight: a,
927
- ...x
928
- } : {
929
- status: "success",
930
- quad: C,
931
- corners: S,
932
- confidence: m.confidence,
933
- message: "Four document edges detected.",
934
- sourceWidth: i,
935
- sourceHeight: a,
936
- ...x
937
- };
938
- }
939
- function Ue(e, t) {
940
- let n = Math.max(1, Math.round(Math.max(q(e.topLeft, e.topRight), q(e.bottomLeft, e.bottomRight)))), r = Math.max(1, Math.round(Math.max(q(e.topLeft, e.bottomLeft), q(e.topRight, e.bottomRight)))), i = Math.min(1, t / Math.max(n, r));
941
- return {
942
- width: Math.max(1, Math.round(n * i)),
943
- height: Math.max(1, Math.round(r * i))
944
- };
945
- }
946
- function We(e, t, n, r, i) {
947
- let a = Math.max(0, Math.min(t - 1, r)), o = Math.max(0, Math.min(n - 1, i)), s = Math.floor(a), c = Math.floor(o), l = Math.min(t - 1, s + 1), u = Math.min(n - 1, c + 1), d = a - s, f = o - c, p = c * t, m = u * t, h = (t) => {
948
- let n = e[(p + s) * 4 + t] * (1 - d) + e[(p + l) * 4 + t] * d, r = e[(m + s) * 4 + t] * (1 - d) + e[(m + l) * 4 + t] * d;
949
- return Math.round(n * (1 - f) + r * f);
950
- };
951
- return [
952
- h(0),
953
- h(1),
954
- h(2),
955
- 255
956
- ];
957
- }
958
- function Ge(e, n, r) {
959
- let { width: i, height: a } = Ue(n, r), o = e.getContext("2d", { willReadFrequently: !0 });
960
- if (!o) throw t();
961
- let s = o.getImageData(0, 0, e.width, e.height), c = document.createElement("canvas");
962
- c.width = i, c.height = a;
963
- let l = c.getContext("2d");
964
- if (!l) throw t();
965
- let u = l.createImageData(i, a), { topLeft: d, topRight: f, bottomRight: p, bottomLeft: m } = n, h = f.x - p.x, g = m.x - p.x, _ = f.y - p.y, v = m.y - p.y, y = d.x - f.x + p.x - m.x, b = d.y - f.y + p.y - m.y, x = h * v - g * _, S = Math.abs(x) < 1e-4 ? 0 : (y * v - g * b) / x, C = Math.abs(x) < 1e-4 ? 0 : (h * b - y * _) / x, w = f.x - d.x + S * f.x, T = m.x - d.x + C * m.x, E = f.y - d.y + S * f.y, D = m.y - d.y + C * m.y;
966
- for (let t = 0; t < a; t += 1) {
967
- let n = t / Math.max(1, a - 1);
968
- for (let r = 0; r < i; r += 1) {
969
- let a = r / Math.max(1, i - 1), o = S * a + C * n + 1, c = (w * a + T * n + d.x) / o, l = (E * a + D * n + d.y) / o, [f, p, m, h] = We(s.data, e.width, e.height, c, l), g = (t * i + r) * 4;
970
- u.data[g] = f, u.data[g + 1] = p, u.data[g + 2] = m, u.data[g + 3] = h;
971
- }
972
- }
973
- return l.putImageData(u, 0, 0), c;
974
- }
975
- async function Ke(e, t = {}) {
976
- return await x("scan"), Y(await U(e, { cloneCanvas: !1 }), t);
977
- }
978
- async function qe(e, t, n = {}) {
979
- await x("scan");
980
- let r = await U(e, { cloneCanvas: !1 }), i = n.maxOutputDimension ?? 4096;
981
- return {
982
- status: "success",
983
- corners: t,
984
- quad: J(t),
985
- confidence: 1,
986
- message: "Captured with the document edges shown in the finder.",
987
- sourceWidth: r.width,
988
- sourceHeight: r.height,
989
- canvas: Ge(r, t, i)
990
- };
991
- }
992
- async function Je(e, t = {}) {
993
- await x("scan");
994
- let n = await U(e, { cloneCanvas: !1 }), r = await Y(n, t);
995
- if (r.status !== "success" || !r.corners) return r;
996
- let i = t.maxOutputDimension ?? 4096;
997
- return {
998
- ...r,
999
- canvas: Ge(n, r.corners, i),
1000
- message: "Four document edges detected and perspective-corrected."
1001
- };
1002
- }
1003
- function Ye(e) {
1004
- return e.status === "success" ? e.message : e.status === "low-quality" ? e.message.includes("shortest side") ? `${e.message} Take another photo.` : "That photo is too soft or dark to find a document. Take another photo in better light." : e.status === "low-confidence" ? "The page edges were not clear enough to crop. Take another photo with the whole page in frame." : `No document was found in that photo. Take another photo with the whole page in frame.${e.modelStatus === "failed" && e.modelError ? ` (${e.modelError})` : ""}`;
1005
- }
1006
- async function Xe(e, t = {}) {
1007
- let n = await Je(e, t);
1008
- return n.status === "success" ? n : {
1009
- ...n,
1010
- message: Ye(n)
1011
- };
1012
- }
1013
- //#endregion
1014
- //#region src/sdk/lighting.ts
1015
- function Ze(e, t) {
1016
- if (!e.length) return 0;
1017
- let n = [...e].sort((e, t) => e - t);
1018
- return n[Math.min(n.length - 1, Math.floor(n.length * t))];
1019
- }
1020
- function Qe(e, t, n, r = 12) {
1021
- if (!t || !n || e.length < t * n) return {
1022
- strong: !1,
1023
- strength: 0,
1024
- darkness: 0,
1025
- areaRatio: 0
1026
- };
1027
- let i = Math.min(r, t), a = Math.min(r, n), o = [];
1028
- for (let r = 0; r < a; r += 1) {
1029
- let s = Math.floor(r * n / a), c = Math.max(s + 1, Math.floor((r + 1) * n / a));
1030
- for (let n = 0; n < i; n += 1) {
1031
- let r = Math.floor(n * t / i), a = Math.max(r + 1, Math.floor((n + 1) * t / i)), l = 0, u = 0, d = 0;
1032
- for (let n = s; n < c; n += 1) for (let i = r; i < a; i += 1) {
1033
- let r = e[n * t + i];
1034
- l += r, u += r * r, d += 1;
1035
- }
1036
- let f = l / d;
1037
- o.push({
1038
- mean: f,
1039
- deviation: Math.sqrt(Math.max(0, u / d - f * f))
1040
- });
1041
- }
1042
- }
1043
- let s = Ze(o.map((e) => e.mean), .8), c = o.map((e) => s - e.mean >= 24 && e.mean >= 35), l = new Uint8Array(o.length), u = [];
1044
- for (let e = 0; e < o.length; e += 1) {
1045
- if (!c[e] || l[e]) continue;
1046
- let t = [], n = [e];
1047
- for (l[e] = 1; n.length;) {
1048
- let e = n.shift();
1049
- t.push(e);
1050
- let r = Math.floor(e / i), o = e % i;
1051
- for (let [e, t] of [
1052
- [o - 1, r],
1053
- [o + 1, r],
1054
- [o, r - 1],
1055
- [o, r + 1]
1056
- ]) {
1057
- if (e < 0 || e >= i || t < 0 || t >= a) continue;
1058
- let r = t * i + e;
1059
- c[r] && !l[r] && (l[r] = 1, n.push(r));
1060
- }
1061
- }
1062
- u.push(t);
1063
- }
1064
- let d = {
1065
- strong: !1,
1066
- strength: 0,
1067
- darkness: 0,
1068
- areaRatio: 0
1069
- };
1070
- for (let e of u) {
1071
- let t = e.length / o.length;
1072
- if (t < .06 || t > .75) continue;
1073
- let n = e.reduce((e, t) => e + s - o[t].mean, 0) / e.length, r = e.filter((e) => o[e].deviation >= 9).length / e.length;
1074
- if (r < .08 && n < 42) continue;
1075
- let c = e.map((e) => e % i), l = e.map((e) => Math.floor(e / i)), u = Math.min(...c), f = Math.max(...c), p = Math.min(...l), m = Math.max(...l), h = Math.max(0, u - 1) / i, g = Math.max(0, p - 1) / a, _ = Math.min(i, f + 1 + 1) / i, v = Math.min(a, m + 1 + 1) / a, y = n * Math.sqrt(t) * (.75 + Math.min(.25, r));
1076
- y > d.strength && (d = {
1077
- strong: y >= 10,
1078
- strength: y,
1079
- darkness: n,
1080
- areaRatio: t,
1081
- region: {
1082
- x: h,
1083
- y: g,
1084
- width: _ - h,
1085
- height: v - g
1086
- }
1087
- });
1088
- }
1089
- return d;
1090
- }
1091
- function $e(e, t, n, r, i, a, o) {
1092
- let s = Math.max(0, a - o), c = Math.min(r, a + o + 1), l = Math.max(0, i - o), u = Math.min(n, i + o + 1), d = Math.max(1, (u - l) * (c - s));
1093
- return (e[c * t + u] - e[s * t + u] - e[c * t + l] + e[s * t + l]) / d;
1094
- }
1095
- function X(e, t, n) {
1096
- let r = t + 1, i = new Uint32Array((t + 1) * (n + 1));
1097
- for (let a = 1; a <= n; a += 1) {
1098
- let n = 0;
1099
- for (let o = 1; o <= t; o += 1) n += e[(a - 1) * t + o - 1], i[a * r + o] = i[(a - 1) * r + o] + n;
1100
- }
1101
- return {
1102
- integral: i,
1103
- stride: r
1104
- };
1105
- }
1106
- function et(e, t, n, r = Math.max(12, Math.round(Math.max(t, n) / 32))) {
1107
- let { integral: i, stride: a } = X(e, t, n), o = new Uint8Array(e.length);
1108
- for (let s = 0; s < n; s += 1) for (let c = 0; c < t; c += 1) {
1109
- let l = $e(i, a, t, n, c, s, r);
1110
- o[s * t + c] = Math.max(0, Math.min(255, Math.round(e[s * t + c] * 235 / Math.max(24, l))));
1111
- }
1112
- return o;
1113
- }
1114
- function tt(e, t, n, r = Math.max(8, Math.round(Math.max(t, n) / 64)), i = .12) {
1115
- let { integral: a, stride: o } = X(e, t, n), s = new Uint8Array(e.length), c = 1 - i;
1116
- for (let i = 0; i < n; i += 1) for (let l = 0; l < t; l += 1) {
1117
- let u = $e(a, o, t, n, l, i, r);
1118
- s[i * t + l] = e[i * t + l] < u * c ? 0 : 255;
1119
- }
1120
- return s;
1121
- }
1122
- function nt(e, t, n) {
1123
- let r = [
1124
- e.topLeft,
1125
- e.topRight,
1126
- e.bottomRight,
1127
- e.bottomLeft
1128
- ], i = Math.max(0, Math.min(...r.map((e) => e.x))), a = Math.max(0, Math.min(...r.map((e) => e.y))), o = Math.min(t, Math.max(...r.map((e) => e.x))), s = Math.min(n, Math.max(...r.map((e) => e.y)));
1129
- return {
1130
- left: i,
1131
- top: a,
1132
- width: o - i,
1133
- height: s - a
1134
- };
1135
- }
1136
- function rt(e, t) {
1137
- let n = nt(t, e.width, e.height);
1138
- if (n.width <= 0 || n.height <= 0) return {
1139
- strong: !1,
1140
- strength: 0,
1141
- darkness: 0,
1142
- areaRatio: 0
1143
- };
1144
- let r = document.createElement("canvas");
1145
- r.width = 60, r.height = 60;
1146
- let i = r.getContext("2d", { willReadFrequently: !0 });
1147
- if (!i) return {
1148
- strong: !1,
1149
- strength: 0,
1150
- darkness: 0,
1151
- areaRatio: 0
1152
- };
1153
- i.drawImage(e, n.left, n.top, n.width, n.height, 0, 0, r.width, r.height);
1154
- let a = i.getImageData(0, 0, r.width, r.height).data, o = new Uint8Array(r.width * r.height);
1155
- for (let e = 0, t = 0; e < o.length; e += 1, t += 4) o[e] = Math.round(a[t] * .299 + a[t + 1] * .587 + a[t + 2] * .114);
1156
- return Qe(o, r.width, r.height);
1157
- }
1158
- //#endregion
1159
- //#region src/sdk/finder.ts
1160
- function it(e, t) {
1161
- return t.castShadow && (e.reason === "hold-still" || e.reason === "ready") ? t.hint ?? e.hint : e.hint;
1162
- }
1163
- async function at(e, t) {
1164
- let n = await e();
1165
- return t(), n;
1166
- }
1167
- function ot(e) {
1168
- return e === "alwaysOn" || e === "only" ? {
1169
- visible: !1,
1170
- checked: !0,
1171
- mutable: !1
1172
- } : e === "alwaysOff" ? {
1173
- visible: !1,
1174
- checked: !1,
1175
- mutable: !1
1176
- } : {
1177
- visible: !0,
1178
- checked: e === "defaultOn",
1179
- mutable: !0
1180
- };
1181
- }
1182
- function Z(e) {
1183
- return [
1184
- e.topLeft,
1185
- e.topRight,
1186
- e.bottomRight,
1187
- e.bottomLeft
1188
- ];
1189
- }
1190
- var st = 1600;
1191
- function ct(e = A()) {
1192
- return e.iosWebKit ? {
1193
- intervalMs: 70,
1194
- maxFrameDimension: 720,
1195
- maxAnalysisDimension: 720
1196
- } : {
1197
- intervalMs: 140,
1198
- maxFrameDimension: st,
1199
- maxAnalysisDimension: 520
1200
- };
1201
- }
1202
- function lt(e, t) {
1203
- let n = e.status === "success" && e.modelStatus !== "failed", r = {
1204
- status: e.status,
1205
- confidence: Number(e.confidence.toFixed(3)),
1206
- source: `${e.sourceWidth}×${e.sourceHeight}`
1207
- };
1208
- t?.width && t?.height && (r.video = `${t.width}×${t.height}`), e.modelStatus && (r.modelStatus = e.modelStatus), e.modelProvider && (r.provider = e.modelProvider), e.modelError && (r.modelError = e.modelError), e.modelNote && (r.modelNote = e.modelNote), e.inferenceMs !== void 0 && (r.inferenceMs = Math.round(e.inferenceMs)), !n && e.message && (r.message = e.message);
1209
- let i = n ? "document found" : e.modelStatus === "failed" ? "document not found (ML failed)" : `document not found (${e.status})`;
1210
- return {
1211
- level: n ? "info" : "warn",
1212
- key: [
1213
- i,
1214
- r.modelStatus ?? "",
1215
- r.modelError ?? "",
1216
- r.provider ?? "",
1217
- r.modelNote ?? "",
1218
- r.source,
1219
- r.video ?? ""
1220
- ].join("|"),
1221
- summary: i,
1222
- detail: r
1223
- };
1224
- }
1225
- function ut(e) {
1226
- let t = 0;
1227
- for (let n = 0; n < e.length; n += 1) {
1228
- let r = e[n], i = e[(n + 1) % e.length];
1229
- t += r.x * i.y - i.x * r.y;
1230
- }
1231
- return Math.abs(t) / 2;
1232
- }
1233
- function Q(e, t) {
1234
- return Math.hypot(e.x - t.x, e.y - t.y);
1235
- }
1236
- var $ = {
1237
- widthFill: 0,
1238
- heightFill: 0,
1239
- limitingFill: 0,
1240
- areaFill: 0,
1241
- aspectRatio: 1
1242
- };
1243
- function dt(e, t, n) {
1244
- let r = Z(e), i = r.map(({ x: e }) => e), a = r.map(({ y: e }) => e), o = (Math.max(...i) - Math.min(...i)) / Math.max(1, t), s = (Math.max(...a) - Math.min(...a)) / Math.max(1, n), [c, l, u, d] = r, f = Math.max(Q(c, l), Q(d, u)), p = Math.max(Q(c, d), Q(l, u));
1245
- return {
1246
- widthFill: o,
1247
- heightFill: s,
1248
- limitingFill: Math.max(o, s),
1249
- areaFill: ut(r) / Math.max(1, t * n),
1250
- aspectRatio: Math.max(f, p) / Math.max(1, Math.min(f, p))
1251
- };
1252
- }
1253
- function ft(e, t, n, r = {}) {
1254
- let i = t ? r.exitFillRatio ?? .64 : r.minFillRatio ?? .72, a = r.highAspectRatio ?? 2.2;
1255
- if (e.aspectRatio < a) return i;
1256
- let o = t ? r.highAspectExitFillRatio : r.highAspectFillRatio;
1257
- return Math.min(o ?? i + .08, 1 - n * 2);
1258
- }
1259
- function pt(e, t, n = {}) {
1260
- let r = n.confidenceThreshold ?? .72;
1261
- if (e.status !== "success" || !e.quad || e.confidence < r || !e.sourceWidth || !e.sourceHeight) return {
1262
- hint: "Place the document in the frame",
1263
- reason: "place-document",
1264
- fillRatio: 0,
1265
- fill: $,
1266
- readyForAutoCapture: !1
1267
- };
1268
- let i = Z(e.quad), a = dt(e.quad, e.sourceWidth, e.sourceHeight), o = a.limitingFill, s = t.previouslyReady ? n.exitEdgeMarginRatio ?? .005 : n.edgeMarginRatio ?? .015, c = e.sourceWidth * s, l = e.sourceHeight * s;
1269
- if (i.some(({ x: t, y: n }) => t <= c || t >= e.sourceWidth - c || n <= l || n >= e.sourceHeight - l)) return {
1270
- hint: "Move farther away",
1271
- reason: "move-farther-away",
1272
- fillRatio: o,
1273
- fill: a,
1274
- readyForAutoCapture: !1
1275
- };
1276
- let [u, d, f, p] = i, m = Q(u, d), h = Q(d, f), g = Q(f, p), _ = Q(p, u);
1277
- return Math.min(Math.min(m, g) / Math.max(1, Math.max(m, g)), Math.min(_, h) / Math.max(1, Math.max(_, h))) < (t.previouslyReady ? n.exitMinPerspectiveRatio ?? .4 : n.minPerspectiveRatio ?? .48) ? {
1278
- hint: "Hold the camera straight",
1279
- reason: "straighten-camera",
1280
- fillRatio: o,
1281
- fill: a,
1282
- readyForAutoCapture: !1
1283
- } : o < ft(a, t.previouslyReady === !0, s, n) ? {
1284
- hint: "Move closer",
1285
- reason: "move-closer",
1286
- fillRatio: o,
1287
- fill: a,
1288
- readyForAutoCapture: !1
1289
- } : {
1290
- hint: "Hold still",
1291
- reason: t.ready ? "ready" : "hold-still",
1292
- fillRatio: o,
1293
- fill: a,
1294
- readyForAutoCapture: t.ready
1295
- };
1296
- }
1297
- var mt = class {
1298
- previous;
1299
- count = 0;
1300
- ready = !1;
1301
- options;
1302
- constructor(e) {
1303
- this.options = e;
1304
- }
1305
- reset() {
1306
- this.previous = void 0, this.count = 0, this.ready = !1;
1307
- }
1308
- update(e) {
1309
- if (e.status !== "success" || !e.quad || e.confidence < this.options.confidenceThreshold) return this.reset(), {
1310
- stableFrames: 0,
1311
- ready: !1,
1312
- movement: Infinity
1313
- };
1314
- let t = Math.hypot(e.sourceWidth, e.sourceHeight), n = this.previous ? Math.max(...Z(e.quad).map((e, n) => {
1315
- let r = Z(this.previous)[n];
1316
- return Math.hypot(e.x - r.x, e.y - r.y) / Math.max(1, t);
1317
- })) : Infinity, r = this.options.exitCornerTolerance ?? Math.max(this.options.cornerTolerance, .036);
1318
- return this.ready && this.previous && n <= r ? this.count = Math.max(this.options.stableFrames, this.count + 1) : (this.ready = !1, this.count = this.previous && n <= this.options.cornerTolerance ? this.count + 1 : 1, this.count >= this.options.stableFrames && (this.ready = !0)), this.previous = e.quad, {
1319
- stableFrames: this.count,
1320
- ready: this.ready,
1321
- movement: n
1322
- };
1323
- }
1324
- };
1325
- function ht(e, n) {
1326
- let r = Math.min(1, n / Math.max(e.width, e.height)), i = document.createElement("canvas");
1327
- i.width = Math.max(1, Math.round(e.width * r)), i.height = Math.max(1, Math.round(e.height * r));
1328
- let a = i.getContext("2d");
1329
- if (!a) throw t();
1330
- return a.drawImage(e, 0, 0, i.width, i.height), i;
1331
- }
1332
- function gt() {
1333
- let e = window.AudioContext ?? window.webkitAudioContext;
1334
- if (!e) return;
1335
- let t = new e(), n = Math.round(t.sampleRate * .09), r = t.createBuffer(1, n, t.sampleRate), i = r.getChannelData(0);
1336
- for (let e = 0; e < n; e += 1) {
1337
- let n = Math.exp(-e / (t.sampleRate * .018));
1338
- i[e] = (Math.random() * 2 - 1) * n;
1339
- }
1340
- let a = t.createBufferSource(), o = t.createBiquadFilter(), s = t.createGain();
1341
- o.type = "bandpass", o.frequency.value = 1400, s.gain.value = .42, a.buffer = r, a.connect(o).connect(s).connect(t.destination), a.start(), a.onended = () => void t.close();
1342
- }
1343
- async function _t(e) {
1344
- let t = document.createElement("video");
1345
- return t.muted = !0, t.autoplay = !0, t.playsInline = !0, t.srcObject = e, await t.play(), t;
1346
- }
1347
- async function vt(t) {
1348
- await x("scan");
1349
- let n = ot(t.autoCapture), r = new mt({
1350
- stableFrames: t.stableFrames ?? 4,
1351
- confidenceThreshold: t.confidenceThreshold ?? .72,
1352
- cornerTolerance: t.cornerTolerance ?? .024,
1353
- exitCornerTolerance: t.exitCornerTolerance ?? .036
1354
- }), i = ct(), a = t.maxFrameDimension ?? i.maxFrameDimension, o = t.intervalMs ?? i.intervalMs, s = {
1355
- minDimension: 220,
1356
- maxAnalysisDimension: i.maxAnalysisDimension,
1357
- ...t.detection
1358
- }, c = typeof MediaStream < "u" && t.source instanceof MediaStream ? await _t(t.source) : t.source, l = !0, u = !1, d = !1, f = 0, p, m = "", h = 0, g = {
1359
- state: "detecting",
1360
- confidence: 0,
1361
- guidance: {
1362
- hint: "Place the document in the frame",
1363
- reason: "place-document",
1364
- fillRatio: 0,
1365
- fill: $,
1366
- readyForAutoCapture: !1
1367
- },
1368
- lighting: {
1369
- castShadow: !1,
1370
- strength: 0
1371
- },
1372
- stableFrames: 0,
1373
- requiredStableFrames: t.stableFrames ?? 4,
1374
- autoCapture: { ...n }
1375
- }, _ = () => c instanceof HTMLCanvasElement ? ht(c, a) : B(c, a), v = (e) => {
1376
- g = e, t.onStatus?.(e);
1377
- }, y = (e) => {
1378
- let t = lt(e, c instanceof HTMLVideoElement ? {
1379
- width: c.videoWidth,
1380
- height: c.videoHeight
1381
- } : {
1382
- width: c.width,
1383
- height: c.height
1384
- }), n = performance.now();
1385
- t.key === m && n - h < 2e3 || (m = t.key, h = n, console[t.level](`[exige-scanner] ${t.summary}`, t.detail));
1386
- }, b = () => {
1387
- l = !1, window.clearTimeout(f), c instanceof HTMLVideoElement && c !== t.source && (c.srcObject = null);
1388
- }, S = async (e = "manual") => {
1389
- if (u) throw Error("A finder capture is already in progress.");
1390
- u = !0;
1391
- let n;
1392
- try {
1393
- n = await at(t.captureFrame ?? _, () => {
1394
- v({
1395
- ...g,
1396
- state: "captured"
1397
- }), t.playShutterSound !== !1 && gt(), b();
1398
- });
1399
- } catch (e) {
1400
- throw u = !1, e instanceof Error ? e : /* @__PURE__ */ Error("The camera frame could not be captured.");
1401
- }
1402
- let r = {
1403
- frame: n,
1404
- detection: p,
1405
- reason: e
1406
- };
1407
- return await t.onCapture?.(r), r;
1408
- }, C = async () => {
1409
- if (l && !u) {
1410
- try {
1411
- let e = _(), i = await Ke(e, s);
1412
- p = i, y(i);
1413
- let a = i.quad ? rt(e, i.quad) : {
1414
- strong: !1,
1415
- strength: 0
1416
- }, o = a.strong ? {
1417
- castShadow: !0,
1418
- strength: a.strength,
1419
- hint: "Tilt to move the shadow off the page"
1420
- } : {
1421
- castShadow: !1,
1422
- strength: a.strength
1423
- }, c = r.update(i), l = pt(i, {
1424
- ...c,
1425
- previouslyReady: d
1426
- }, {
1427
- confidenceThreshold: t.confidenceThreshold ?? .72,
1428
- ...t.guidance
1429
- });
1430
- d = l.readyForAutoCapture;
1431
- let u = i.status !== "success" || l.reason === "place-document" ? "seeking" : l.readyForAutoCapture ? "ready" : "unstable";
1432
- if (v({
1433
- state: u,
1434
- confidence: i.confidence,
1435
- quad: i.quad,
1436
- guidance: l,
1437
- lighting: o,
1438
- stableFrames: c.stableFrames,
1439
- requiredStableFrames: g.requiredStableFrames,
1440
- autoCapture: { ...n },
1441
- sourceWidth: i.sourceWidth,
1442
- sourceHeight: i.sourceHeight,
1443
- detector: i.detector,
1444
- modelStatus: i.modelStatus,
1445
- modelProvider: i.modelProvider,
1446
- modelError: i.modelError,
1447
- modelNote: i.modelNote,
1448
- inferenceMs: i.inferenceMs
1449
- }), l.readyForAutoCapture && n.checked) try {
1450
- await S("auto");
1451
- return;
1452
- } catch (e) {
1453
- r.reset(), d = !1, t.onCaptureError?.(e instanceof Error ? e : /* @__PURE__ */ Error("Automatic capture failed."));
1454
- }
1455
- } catch (t) {
1456
- r.reset(), d = !1;
1457
- let i = t instanceof e ? {
1458
- detector: "ml",
1459
- modelStatus: "failed",
1460
- modelError: t.message
1461
- } : { modelError: t instanceof Error ? t.message : "Finder tick failed." };
1462
- y({
1463
- status: "no-document",
1464
- confidence: 0,
1465
- message: i.modelError ?? "Finder tick failed.",
1466
- sourceWidth: 0,
1467
- sourceHeight: 0,
1468
- ...i
1469
- }), v({
1470
- state: "seeking",
1471
- confidence: 0,
1472
- guidance: {
1473
- hint: "Place the document in the frame",
1474
- reason: "place-document",
1475
- fillRatio: 0,
1476
- fill: $,
1477
- readyForAutoCapture: !1
1478
- },
1479
- lighting: {
1480
- castShadow: !1,
1481
- strength: 0
1482
- },
1483
- stableFrames: 0,
1484
- requiredStableFrames: g.requiredStableFrames,
1485
- autoCapture: { ...n },
1486
- ...i
1487
- });
1488
- }
1489
- l && (f = window.setTimeout(() => void C(), o));
1490
- }
1491
- };
1492
- return t.onStatus?.(g), C(), {
1493
- stop: b,
1494
- capture: () => S("manual"),
1495
- setAutoCapture(e) {
1496
- return !n.mutable || u ? !1 : (n.checked = e, v({
1497
- ...g,
1498
- autoCapture: { ...n }
1499
- }), !0);
1500
- },
1501
- getStatus: () => g
1502
- };
1503
- }
1504
- //#endregion
1505
- export { I as A, o as B, R as C, De as D, oe as E, Ee as F, t as G, b as H, F as I, ie as L, Oe as M, M as N, j as O, se as P, ne as R, fe as S, A as T, y as U, x as V, e as W, Ye as _, pt as a, U as b, tt as c, Fe as d, qe as f, Xe as g, Je as h, dt as i, L as j, pe as k, Qe as l, W as m, ot as n, it as o, Ke as p, ft as r, vt as s, mt as t, et as u, Ne as v, B as w, P as x, Pe as y, a as z };
1506
-
1507
- //# sourceMappingURL=finder-BvBpdbHa.js.map