@kreuzberg/wasm 4.0.0-rc.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.
package/dist/index.js ADDED
@@ -0,0 +1,4308 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // ../../node_modules/.pnpm/tesseract-wasm@0.11.0/node_modules/tesseract-wasm/dist/lib.js
12
+ var lib_exports = {};
13
+ __export(lib_exports, {
14
+ OCRClient: () => OCRClient,
15
+ createOCREngine: () => createOCREngine,
16
+ layoutFlags: () => layoutFlags,
17
+ supportsFastBuild: () => supportsFastBuild
18
+ });
19
+ function isAllowedOrigin(allowedOrigins, origin) {
20
+ for (const allowedOrigin of allowedOrigins) {
21
+ if (origin === allowedOrigin || allowedOrigin === "*") {
22
+ return true;
23
+ }
24
+ if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) {
25
+ return true;
26
+ }
27
+ }
28
+ return false;
29
+ }
30
+ function expose(obj, ep = globalThis, allowedOrigins = ["*"]) {
31
+ ep.addEventListener("message", function callback(ev) {
32
+ if (!ev || !ev.data) {
33
+ return;
34
+ }
35
+ if (!isAllowedOrigin(allowedOrigins, ev.origin)) {
36
+ console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);
37
+ return;
38
+ }
39
+ const { id, type, path } = Object.assign({ path: [] }, ev.data);
40
+ const argumentList = (ev.data.argumentList || []).map(fromWireValue);
41
+ let returnValue;
42
+ try {
43
+ const parent = path.slice(0, -1).reduce((obj2, prop) => obj2[prop], obj);
44
+ const rawValue = path.reduce((obj2, prop) => obj2[prop], obj);
45
+ switch (type) {
46
+ case "GET":
47
+ {
48
+ returnValue = rawValue;
49
+ }
50
+ break;
51
+ case "SET":
52
+ {
53
+ parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);
54
+ returnValue = true;
55
+ }
56
+ break;
57
+ case "APPLY":
58
+ {
59
+ returnValue = rawValue.apply(parent, argumentList);
60
+ }
61
+ break;
62
+ case "CONSTRUCT":
63
+ {
64
+ const value = new rawValue(...argumentList);
65
+ returnValue = proxy(value);
66
+ }
67
+ break;
68
+ case "ENDPOINT":
69
+ {
70
+ const { port1, port2 } = new MessageChannel();
71
+ expose(obj, port2);
72
+ returnValue = transfer(port1, [port1]);
73
+ }
74
+ break;
75
+ case "RELEASE":
76
+ {
77
+ returnValue = void 0;
78
+ }
79
+ break;
80
+ default:
81
+ return;
82
+ }
83
+ } catch (value) {
84
+ returnValue = { value, [throwMarker]: 0 };
85
+ }
86
+ Promise.resolve(returnValue).catch((value) => {
87
+ return { value, [throwMarker]: 0 };
88
+ }).then((returnValue2) => {
89
+ const [wireValue, transferables] = toWireValue(returnValue2);
90
+ ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);
91
+ if (type === "RELEASE") {
92
+ ep.removeEventListener("message", callback);
93
+ closeEndPoint(ep);
94
+ if (finalizer in obj && typeof obj[finalizer] === "function") {
95
+ obj[finalizer]();
96
+ }
97
+ }
98
+ }).catch((error) => {
99
+ const [wireValue, transferables] = toWireValue({
100
+ value: new TypeError("Unserializable return value"),
101
+ [throwMarker]: 0
102
+ });
103
+ ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);
104
+ });
105
+ });
106
+ if (ep.start) {
107
+ ep.start();
108
+ }
109
+ }
110
+ function isMessagePort(endpoint) {
111
+ return endpoint.constructor.name === "MessagePort";
112
+ }
113
+ function closeEndPoint(endpoint) {
114
+ if (isMessagePort(endpoint))
115
+ endpoint.close();
116
+ }
117
+ function wrap(ep, target) {
118
+ return createProxy(ep, [], target);
119
+ }
120
+ function throwIfProxyReleased(isReleased) {
121
+ if (isReleased) {
122
+ throw new Error("Proxy has been released and is not useable");
123
+ }
124
+ }
125
+ function releaseEndpoint(ep) {
126
+ return requestResponseMessage(ep, {
127
+ type: "RELEASE"
128
+ }).then(() => {
129
+ closeEndPoint(ep);
130
+ });
131
+ }
132
+ function registerProxy(proxy2, ep) {
133
+ const newCount = (proxyCounter.get(ep) || 0) + 1;
134
+ proxyCounter.set(ep, newCount);
135
+ if (proxyFinalizers) {
136
+ proxyFinalizers.register(proxy2, ep, proxy2);
137
+ }
138
+ }
139
+ function unregisterProxy(proxy2) {
140
+ if (proxyFinalizers) {
141
+ proxyFinalizers.unregister(proxy2);
142
+ }
143
+ }
144
+ function createProxy(ep, path = [], target = function() {
145
+ }) {
146
+ let isProxyReleased = false;
147
+ const proxy2 = new Proxy(target, {
148
+ get(_target, prop) {
149
+ throwIfProxyReleased(isProxyReleased);
150
+ if (prop === releaseProxy) {
151
+ return () => {
152
+ unregisterProxy(proxy2);
153
+ releaseEndpoint(ep);
154
+ isProxyReleased = true;
155
+ };
156
+ }
157
+ if (prop === "then") {
158
+ if (path.length === 0) {
159
+ return { then: () => proxy2 };
160
+ }
161
+ const r = requestResponseMessage(ep, {
162
+ type: "GET",
163
+ path: path.map((p) => p.toString())
164
+ }).then(fromWireValue);
165
+ return r.then.bind(r);
166
+ }
167
+ return createProxy(ep, [...path, prop]);
168
+ },
169
+ set(_target, prop, rawValue) {
170
+ throwIfProxyReleased(isProxyReleased);
171
+ const [value, transferables] = toWireValue(rawValue);
172
+ return requestResponseMessage(ep, {
173
+ type: "SET",
174
+ path: [...path, prop].map((p) => p.toString()),
175
+ value
176
+ }, transferables).then(fromWireValue);
177
+ },
178
+ apply(_target, _thisArg, rawArgumentList) {
179
+ throwIfProxyReleased(isProxyReleased);
180
+ const last = path[path.length - 1];
181
+ if (last === createEndpoint) {
182
+ return requestResponseMessage(ep, {
183
+ type: "ENDPOINT"
184
+ }).then(fromWireValue);
185
+ }
186
+ if (last === "bind") {
187
+ return createProxy(ep, path.slice(0, -1));
188
+ }
189
+ const [argumentList, transferables] = processArguments(rawArgumentList);
190
+ return requestResponseMessage(ep, {
191
+ type: "APPLY",
192
+ path: path.map((p) => p.toString()),
193
+ argumentList
194
+ }, transferables).then(fromWireValue);
195
+ },
196
+ construct(_target, rawArgumentList) {
197
+ throwIfProxyReleased(isProxyReleased);
198
+ const [argumentList, transferables] = processArguments(rawArgumentList);
199
+ return requestResponseMessage(ep, {
200
+ type: "CONSTRUCT",
201
+ path: path.map((p) => p.toString()),
202
+ argumentList
203
+ }, transferables).then(fromWireValue);
204
+ }
205
+ });
206
+ registerProxy(proxy2, ep);
207
+ return proxy2;
208
+ }
209
+ function myFlat(arr) {
210
+ return Array.prototype.concat.apply([], arr);
211
+ }
212
+ function processArguments(argumentList) {
213
+ const processed = argumentList.map(toWireValue);
214
+ return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];
215
+ }
216
+ function transfer(obj, transfers) {
217
+ transferCache.set(obj, transfers);
218
+ return obj;
219
+ }
220
+ function proxy(obj) {
221
+ return Object.assign(obj, { [proxyMarker]: true });
222
+ }
223
+ function toWireValue(value) {
224
+ for (const [name, handler] of transferHandlers) {
225
+ if (handler.canHandle(value)) {
226
+ const [serializedValue, transferables] = handler.serialize(value);
227
+ return [
228
+ {
229
+ type: "HANDLER",
230
+ name,
231
+ value: serializedValue
232
+ },
233
+ transferables
234
+ ];
235
+ }
236
+ }
237
+ return [
238
+ {
239
+ type: "RAW",
240
+ value
241
+ },
242
+ transferCache.get(value) || []
243
+ ];
244
+ }
245
+ function fromWireValue(value) {
246
+ switch (value.type) {
247
+ case "HANDLER":
248
+ return transferHandlers.get(value.name).deserialize(value.value);
249
+ case "RAW":
250
+ return value.value;
251
+ }
252
+ }
253
+ function requestResponseMessage(ep, msg, transfers) {
254
+ return new Promise((resolve2) => {
255
+ const id = generateUUID();
256
+ ep.addEventListener("message", function l(ev) {
257
+ if (!ev.data || !ev.data.id || ev.data.id !== id) {
258
+ return;
259
+ }
260
+ ep.removeEventListener("message", l);
261
+ resolve2(ev.data);
262
+ });
263
+ if (ep.start) {
264
+ ep.start();
265
+ }
266
+ ep.postMessage(Object.assign({ id }, msg), transfers);
267
+ });
268
+ }
269
+ function generateUUID() {
270
+ return new Array(4).fill(0).map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)).join("-");
271
+ }
272
+ function nodeEndpoint(nep) {
273
+ const listeners = /* @__PURE__ */ new WeakMap();
274
+ return {
275
+ postMessage: nep.postMessage.bind(nep),
276
+ addEventListener: (_, eh) => {
277
+ const l = (data) => {
278
+ if ("handleEvent" in eh) {
279
+ eh.handleEvent({ data });
280
+ } else {
281
+ eh({ data });
282
+ }
283
+ };
284
+ nep.on("message", l);
285
+ listeners.set(eh, l);
286
+ },
287
+ removeEventListener: (_, eh) => {
288
+ const l = listeners.get(eh);
289
+ if (!l) {
290
+ return;
291
+ }
292
+ nep.off("message", l);
293
+ listeners.delete(eh);
294
+ },
295
+ start: nep.start && nep.start.bind(nep)
296
+ };
297
+ }
298
+ function imageDataFromBitmap(bitmap) {
299
+ let canvas;
300
+ if (typeof OffscreenCanvas !== "undefined") {
301
+ canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
302
+ } else if (typeof HTMLCanvasElement !== "undefined") {
303
+ const canvasEl = document.createElement("canvas");
304
+ canvasEl.width = bitmap.width;
305
+ canvasEl.height = bitmap.height;
306
+ canvas = canvasEl;
307
+ } else {
308
+ throw new Error("No canvas implementation available");
309
+ }
310
+ const context = canvas.getContext("2d");
311
+ context.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height);
312
+ return context.getImageData(0, 0, bitmap.width, bitmap.height);
313
+ }
314
+ function defaultWorkerURL() {
315
+ return new URL("./tesseract-worker.js", import.meta.url).href;
316
+ }
317
+ function createWebWorker(url) {
318
+ return new Worker(url);
319
+ }
320
+ function jsArrayFromStdVector(vec) {
321
+ const size = vec.size();
322
+ const result = [];
323
+ for (let i = 0; i < size; i++) {
324
+ result.push(vec.get(i));
325
+ }
326
+ return result;
327
+ }
328
+ function wasmSIMDSupported() {
329
+ const simdTest = Uint8Array.from([
330
+ 0,
331
+ 97,
332
+ 115,
333
+ 109,
334
+ 1,
335
+ 0,
336
+ 0,
337
+ 0,
338
+ 1,
339
+ 5,
340
+ 1,
341
+ 96,
342
+ 0,
343
+ 1,
344
+ 123,
345
+ 3,
346
+ 2,
347
+ 1,
348
+ 0,
349
+ 10,
350
+ 10,
351
+ 1,
352
+ 8,
353
+ 0,
354
+ 65,
355
+ 0,
356
+ 253,
357
+ 15,
358
+ 253,
359
+ 98,
360
+ 11
361
+ ]);
362
+ return WebAssembly.validate(simdTest);
363
+ }
364
+ function resolve(path, baseURL) {
365
+ return new URL(path, baseURL).href;
366
+ }
367
+ function supportsFastBuild() {
368
+ return wasmSIMDSupported();
369
+ }
370
+ async function createOCREngine({ wasmBinary, progressChannel } = {}) {
371
+ if (!wasmBinary) {
372
+ const wasmPath = supportsFastBuild() ? "./tesseract-core.wasm" : "./tesseract-core-fallback.wasm";
373
+ const wasmURL = resolve(wasmPath, import.meta.url);
374
+ const wasmBinaryResponse = await fetch(wasmURL);
375
+ wasmBinary = await wasmBinaryResponse.arrayBuffer();
376
+ }
377
+ const tessLib = await Module({ wasmBinary });
378
+ return new OCREngine(tessLib, progressChannel);
379
+ }
380
+ var proxyMarker, createEndpoint, releaseProxy, finalizer, throwMarker, isObject, proxyTransferHandler, throwTransferHandler, transferHandlers, proxyCounter, proxyFinalizers, transferCache, OCRClient, Module, layoutFlags, OCREngine;
381
+ var init_lib = __esm({
382
+ "../../node_modules/.pnpm/tesseract-wasm@0.11.0/node_modules/tesseract-wasm/dist/lib.js"() {
383
+ "use strict";
384
+ proxyMarker = /* @__PURE__ */ Symbol("Comlink.proxy");
385
+ createEndpoint = /* @__PURE__ */ Symbol("Comlink.endpoint");
386
+ releaseProxy = /* @__PURE__ */ Symbol("Comlink.releaseProxy");
387
+ finalizer = /* @__PURE__ */ Symbol("Comlink.finalizer");
388
+ throwMarker = /* @__PURE__ */ Symbol("Comlink.thrown");
389
+ isObject = (val) => typeof val === "object" && val !== null || typeof val === "function";
390
+ proxyTransferHandler = {
391
+ canHandle: (val) => isObject(val) && val[proxyMarker],
392
+ serialize(obj) {
393
+ const { port1, port2 } = new MessageChannel();
394
+ expose(obj, port1);
395
+ return [port2, [port2]];
396
+ },
397
+ deserialize(port) {
398
+ port.start();
399
+ return wrap(port);
400
+ }
401
+ };
402
+ throwTransferHandler = {
403
+ canHandle: (value) => isObject(value) && throwMarker in value,
404
+ serialize({ value }) {
405
+ let serialized;
406
+ if (value instanceof Error) {
407
+ serialized = {
408
+ isError: true,
409
+ value: {
410
+ message: value.message,
411
+ name: value.name,
412
+ stack: value.stack
413
+ }
414
+ };
415
+ } else {
416
+ serialized = { isError: false, value };
417
+ }
418
+ return [serialized, []];
419
+ },
420
+ deserialize(serialized) {
421
+ if (serialized.isError) {
422
+ throw Object.assign(new Error(serialized.value.message), serialized.value);
423
+ }
424
+ throw serialized.value;
425
+ }
426
+ };
427
+ transferHandlers = /* @__PURE__ */ new Map([
428
+ ["proxy", proxyTransferHandler],
429
+ ["throw", throwTransferHandler]
430
+ ]);
431
+ proxyCounter = /* @__PURE__ */ new WeakMap();
432
+ proxyFinalizers = "FinalizationRegistry" in globalThis && new FinalizationRegistry((ep) => {
433
+ const newCount = (proxyCounter.get(ep) || 0) - 1;
434
+ proxyCounter.set(ep, newCount);
435
+ if (newCount === 0) {
436
+ releaseEndpoint(ep);
437
+ }
438
+ });
439
+ transferCache = /* @__PURE__ */ new WeakMap();
440
+ OCRClient = class {
441
+ /**
442
+ * Initialize an OCR engine.
443
+ *
444
+ * This will start a Worker in which the OCR operations will actually be
445
+ * performed.
446
+ *
447
+ */
448
+ constructor({ createWorker = createWebWorker, wasmBinary, workerURL = defaultWorkerURL() } = {}) {
449
+ const worker = createWorker(workerURL);
450
+ this._worker = worker;
451
+ this._progressListeners = [];
452
+ const endpoint = "addEventListener" in worker ? worker : nodeEndpoint(worker);
453
+ const remote = wrap(endpoint);
454
+ const { port1, port2 } = new MessageChannel();
455
+ this._progressChannel = port1;
456
+ this._progressChannel.onmessage = (e) => {
457
+ const { progress } = e.data;
458
+ for (let listener of this._progressListeners) {
459
+ listener(progress);
460
+ }
461
+ };
462
+ this._ocrEngine = remote.createOCREngine({
463
+ wasmBinary
464
+ }, transfer(port2, [port2]));
465
+ }
466
+ async destroy() {
467
+ this._worker.terminate();
468
+ this._progressChannel.close();
469
+ }
470
+ /**
471
+ * Load a trained model for a specific language. This can be specified either
472
+ * as a URL to fetch or a buffer containing an already-loaded model.
473
+ */
474
+ async loadModel(model) {
475
+ const engine = await this._ocrEngine;
476
+ if (typeof model === "string") {
477
+ const response = await fetch(model);
478
+ model = await response.arrayBuffer();
479
+ }
480
+ return engine.loadModel(model);
481
+ }
482
+ /**
483
+ * Load an image into the OCR engine for processing.
484
+ */
485
+ async loadImage(image) {
486
+ if (typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) {
487
+ image = imageDataFromBitmap(image);
488
+ }
489
+ const engine = await this._ocrEngine;
490
+ return engine.loadImage(image);
491
+ }
492
+ /**
493
+ * Clear the current image and text recognition results.
494
+ *
495
+ * This will clear the loaded image data internally, but keep the text
496
+ * recognition model loaded.
497
+ *
498
+ * At present there is no way to shrink WebAssembly memory, so this will not
499
+ * return the memory used by the image to the OS/browser. To release memory,
500
+ * the web worker needs to be shut down via {@link destroy}.
501
+ */
502
+ async clearImage() {
503
+ const engine = await this._ocrEngine;
504
+ return engine.clearImage();
505
+ }
506
+ /**
507
+ * Perform layout analysis on the current image, if not already done, and
508
+ * return bounding boxes for a given unit of text.
509
+ *
510
+ * This operation is relatively cheap compared to text recognition, so can
511
+ * provide much faster results if only the location of lines/words etc. on
512
+ * the page is required, not the text content.
513
+ */
514
+ async getBoundingBoxes(unit) {
515
+ const engine = await this._ocrEngine;
516
+ return engine.getBoundingBoxes(unit);
517
+ }
518
+ /**
519
+ * Perform layout analysis and text recognition on the current image, if
520
+ * not already done, and return bounding boxes and text content for a given
521
+ * unit of text.
522
+ */
523
+ async getTextBoxes(unit, onProgress) {
524
+ const engine = await this._ocrEngine;
525
+ if (onProgress) {
526
+ this._addProgressListener(onProgress);
527
+ }
528
+ try {
529
+ return await engine.getTextBoxes(unit);
530
+ } finally {
531
+ if (onProgress) {
532
+ this._removeProgressListener(onProgress);
533
+ }
534
+ }
535
+ }
536
+ /**
537
+ * Perform layout analysis and text recognition on the current image, if
538
+ * not already done, and return the image's text as a string.
539
+ */
540
+ async getText(onProgress) {
541
+ const engine = await this._ocrEngine;
542
+ if (onProgress) {
543
+ this._addProgressListener(onProgress);
544
+ }
545
+ try {
546
+ return await engine.getText();
547
+ } finally {
548
+ if (onProgress) {
549
+ this._removeProgressListener(onProgress);
550
+ }
551
+ }
552
+ }
553
+ /**
554
+ * Perform layout analysis and text recognition on the current image, if
555
+ * not already done, and return the image's text in hOCR format (see
556
+ * https://en.wikipedia.org/wiki/HOCR).
557
+ */
558
+ async getHOCR(onProgress) {
559
+ const engine = await this._ocrEngine;
560
+ if (onProgress) {
561
+ this._addProgressListener(onProgress);
562
+ }
563
+ try {
564
+ return await engine.getHOCR();
565
+ } finally {
566
+ if (onProgress) {
567
+ this._removeProgressListener(onProgress);
568
+ }
569
+ }
570
+ }
571
+ /**
572
+ * Attempt to determine the orientation of the image.
573
+ *
574
+ * This currently uses a simplistic algorithm [1] which is designed for
575
+ * non-uppercase Latin text. It will likely perform badly for other scripts or
576
+ * if the text is all uppercase.
577
+ *
578
+ * [1] See http://www.leptonica.org/papers/skew-measurement.pdf
579
+ */
580
+ async getOrientation() {
581
+ const engine = await this._ocrEngine;
582
+ return engine.getOrientation();
583
+ }
584
+ _addProgressListener(listener) {
585
+ this._progressListeners.push(listener);
586
+ }
587
+ _removeProgressListener(listener) {
588
+ this._progressListeners = this._progressListeners.filter((l) => l !== listener);
589
+ }
590
+ };
591
+ Module = (() => {
592
+ var _scriptDir = import.meta.url;
593
+ return (function(Module2 = {}) {
594
+ var Module2 = typeof Module2 != "undefined" ? Module2 : {};
595
+ var readyPromiseResolve, readyPromiseReject;
596
+ Module2["ready"] = new Promise(function(resolve2, reject) {
597
+ readyPromiseResolve = resolve2;
598
+ readyPromiseReject = reject;
599
+ });
600
+ var moduleOverrides = Object.assign({}, Module2);
601
+ var thisProgram = "./this.program";
602
+ var ENVIRONMENT_IS_WEB = true;
603
+ var scriptDirectory = "";
604
+ function locateFile(path) {
605
+ if (Module2["locateFile"]) {
606
+ return Module2["locateFile"](path, scriptDirectory);
607
+ }
608
+ return scriptDirectory + path;
609
+ }
610
+ var readBinary;
611
+ {
612
+ if (typeof document != "undefined" && document.currentScript) {
613
+ scriptDirectory = document.currentScript.src;
614
+ }
615
+ if (_scriptDir) {
616
+ scriptDirectory = _scriptDir;
617
+ }
618
+ if (scriptDirectory.indexOf("blob:") !== 0) {
619
+ scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1);
620
+ } else {
621
+ scriptDirectory = "";
622
+ }
623
+ }
624
+ var out = Module2["print"] || console.log.bind(console);
625
+ var err = Module2["printErr"] || console.warn.bind(console);
626
+ Object.assign(Module2, moduleOverrides);
627
+ moduleOverrides = null;
628
+ if (Module2["arguments"]) Module2["arguments"];
629
+ if (Module2["thisProgram"]) thisProgram = Module2["thisProgram"];
630
+ if (Module2["quit"]) Module2["quit"];
631
+ var wasmBinary;
632
+ if (Module2["wasmBinary"]) wasmBinary = Module2["wasmBinary"];
633
+ Module2["noExitRuntime"] || true;
634
+ if (typeof WebAssembly != "object") {
635
+ abort("no native wasm support detected");
636
+ }
637
+ var wasmMemory;
638
+ var ABORT = false;
639
+ function assert(condition, text) {
640
+ if (!condition) {
641
+ abort(text);
642
+ }
643
+ }
644
+ var UTF8Decoder = typeof TextDecoder != "undefined" ? new TextDecoder("utf8") : void 0;
645
+ function UTF8ArrayToString(heapOrArray, idx, maxBytesToRead) {
646
+ var endIdx = idx + maxBytesToRead;
647
+ var endPtr = idx;
648
+ while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;
649
+ if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
650
+ return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
651
+ }
652
+ var str = "";
653
+ while (idx < endPtr) {
654
+ var u0 = heapOrArray[idx++];
655
+ if (!(u0 & 128)) {
656
+ str += String.fromCharCode(u0);
657
+ continue;
658
+ }
659
+ var u1 = heapOrArray[idx++] & 63;
660
+ if ((u0 & 224) == 192) {
661
+ str += String.fromCharCode((u0 & 31) << 6 | u1);
662
+ continue;
663
+ }
664
+ var u2 = heapOrArray[idx++] & 63;
665
+ if ((u0 & 240) == 224) {
666
+ u0 = (u0 & 15) << 12 | u1 << 6 | u2;
667
+ } else {
668
+ u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63;
669
+ }
670
+ if (u0 < 65536) {
671
+ str += String.fromCharCode(u0);
672
+ } else {
673
+ var ch = u0 - 65536;
674
+ str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
675
+ }
676
+ }
677
+ return str;
678
+ }
679
+ function UTF8ToString(ptr, maxBytesToRead) {
680
+ return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : "";
681
+ }
682
+ function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) {
683
+ if (!(maxBytesToWrite > 0)) return 0;
684
+ var startIdx = outIdx;
685
+ var endIdx = outIdx + maxBytesToWrite - 1;
686
+ for (var i = 0; i < str.length; ++i) {
687
+ var u = str.charCodeAt(i);
688
+ if (u >= 55296 && u <= 57343) {
689
+ var u1 = str.charCodeAt(++i);
690
+ u = 65536 + ((u & 1023) << 10) | u1 & 1023;
691
+ }
692
+ if (u <= 127) {
693
+ if (outIdx >= endIdx) break;
694
+ heap[outIdx++] = u;
695
+ } else if (u <= 2047) {
696
+ if (outIdx + 1 >= endIdx) break;
697
+ heap[outIdx++] = 192 | u >> 6;
698
+ heap[outIdx++] = 128 | u & 63;
699
+ } else if (u <= 65535) {
700
+ if (outIdx + 2 >= endIdx) break;
701
+ heap[outIdx++] = 224 | u >> 12;
702
+ heap[outIdx++] = 128 | u >> 6 & 63;
703
+ heap[outIdx++] = 128 | u & 63;
704
+ } else {
705
+ if (outIdx + 3 >= endIdx) break;
706
+ heap[outIdx++] = 240 | u >> 18;
707
+ heap[outIdx++] = 128 | u >> 12 & 63;
708
+ heap[outIdx++] = 128 | u >> 6 & 63;
709
+ heap[outIdx++] = 128 | u & 63;
710
+ }
711
+ }
712
+ heap[outIdx] = 0;
713
+ return outIdx - startIdx;
714
+ }
715
+ function stringToUTF8(str, outPtr, maxBytesToWrite) {
716
+ return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);
717
+ }
718
+ function lengthBytesUTF8(str) {
719
+ var len = 0;
720
+ for (var i = 0; i < str.length; ++i) {
721
+ var c = str.charCodeAt(i);
722
+ if (c <= 127) {
723
+ len++;
724
+ } else if (c <= 2047) {
725
+ len += 2;
726
+ } else if (c >= 55296 && c <= 57343) {
727
+ len += 4;
728
+ ++i;
729
+ } else {
730
+ len += 3;
731
+ }
732
+ }
733
+ return len;
734
+ }
735
+ var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
736
+ function updateMemoryViews() {
737
+ var b = wasmMemory.buffer;
738
+ Module2["HEAP8"] = HEAP8 = new Int8Array(b);
739
+ Module2["HEAP16"] = HEAP16 = new Int16Array(b);
740
+ Module2["HEAP32"] = HEAP32 = new Int32Array(b);
741
+ Module2["HEAPU8"] = HEAPU8 = new Uint8Array(b);
742
+ Module2["HEAPU16"] = HEAPU16 = new Uint16Array(b);
743
+ Module2["HEAPU32"] = HEAPU32 = new Uint32Array(b);
744
+ Module2["HEAPF32"] = HEAPF32 = new Float32Array(b);
745
+ Module2["HEAPF64"] = HEAPF64 = new Float64Array(b);
746
+ }
747
+ var wasmTable;
748
+ var __ATPRERUN__ = [];
749
+ var __ATINIT__ = [];
750
+ var __ATPOSTRUN__ = [];
751
+ function preRun() {
752
+ if (Module2["preRun"]) {
753
+ if (typeof Module2["preRun"] == "function") Module2["preRun"] = [Module2["preRun"]];
754
+ while (Module2["preRun"].length) {
755
+ addOnPreRun(Module2["preRun"].shift());
756
+ }
757
+ }
758
+ callRuntimeCallbacks(__ATPRERUN__);
759
+ }
760
+ function initRuntime() {
761
+ callRuntimeCallbacks(__ATINIT__);
762
+ }
763
+ function postRun() {
764
+ if (Module2["postRun"]) {
765
+ if (typeof Module2["postRun"] == "function") Module2["postRun"] = [Module2["postRun"]];
766
+ while (Module2["postRun"].length) {
767
+ addOnPostRun(Module2["postRun"].shift());
768
+ }
769
+ }
770
+ callRuntimeCallbacks(__ATPOSTRUN__);
771
+ }
772
+ function addOnPreRun(cb) {
773
+ __ATPRERUN__.unshift(cb);
774
+ }
775
+ function addOnInit(cb) {
776
+ __ATINIT__.unshift(cb);
777
+ }
778
+ function addOnPostRun(cb) {
779
+ __ATPOSTRUN__.unshift(cb);
780
+ }
781
+ var runDependencies = 0;
782
+ var dependenciesFulfilled = null;
783
+ function addRunDependency(id) {
784
+ runDependencies++;
785
+ if (Module2["monitorRunDependencies"]) {
786
+ Module2["monitorRunDependencies"](runDependencies);
787
+ }
788
+ }
789
+ function removeRunDependency(id) {
790
+ runDependencies--;
791
+ if (Module2["monitorRunDependencies"]) {
792
+ Module2["monitorRunDependencies"](runDependencies);
793
+ }
794
+ if (runDependencies == 0) {
795
+ if (dependenciesFulfilled) {
796
+ var callback = dependenciesFulfilled;
797
+ dependenciesFulfilled = null;
798
+ callback();
799
+ }
800
+ }
801
+ }
802
+ function abort(what) {
803
+ if (Module2["onAbort"]) {
804
+ Module2["onAbort"](what);
805
+ }
806
+ what = "Aborted(" + what + ")";
807
+ err(what);
808
+ ABORT = true;
809
+ what += ". Build with -sASSERTIONS for more info.";
810
+ var e = new WebAssembly.RuntimeError(what);
811
+ readyPromiseReject(e);
812
+ throw e;
813
+ }
814
+ var dataURIPrefix = "data:application/octet-stream;base64,";
815
+ function isDataURI(filename) {
816
+ return filename.startsWith(dataURIPrefix);
817
+ }
818
+ var wasmBinaryFile;
819
+ if (Module2["locateFile"]) {
820
+ wasmBinaryFile = "tesseract-core.wasm";
821
+ if (!isDataURI(wasmBinaryFile)) {
822
+ wasmBinaryFile = locateFile(wasmBinaryFile);
823
+ }
824
+ } else {
825
+ wasmBinaryFile = new URL("tesseract-core.wasm", import.meta.url).href;
826
+ }
827
+ function getBinary(file) {
828
+ try {
829
+ if (file == wasmBinaryFile && wasmBinary) {
830
+ return new Uint8Array(wasmBinary);
831
+ }
832
+ if (readBinary) ;
833
+ throw "both async and sync fetching of the wasm failed";
834
+ } catch (err2) {
835
+ abort(err2);
836
+ }
837
+ }
838
+ function getBinaryPromise() {
839
+ if (!wasmBinary && ENVIRONMENT_IS_WEB) {
840
+ if (typeof fetch == "function") {
841
+ return fetch(wasmBinaryFile, { credentials: "same-origin" }).then(function(response) {
842
+ if (!response["ok"]) {
843
+ throw "failed to load wasm binary file at '" + wasmBinaryFile + "'";
844
+ }
845
+ return response["arrayBuffer"]();
846
+ }).catch(function() {
847
+ return getBinary(wasmBinaryFile);
848
+ });
849
+ }
850
+ }
851
+ return Promise.resolve().then(function() {
852
+ return getBinary(wasmBinaryFile);
853
+ });
854
+ }
855
+ function createWasm() {
856
+ var info = { "a": wasmImports };
857
+ function receiveInstance(instance, module) {
858
+ var exports2 = instance.exports;
859
+ Module2["asm"] = exports2;
860
+ wasmMemory = Module2["asm"]["U"];
861
+ updateMemoryViews();
862
+ wasmTable = Module2["asm"]["X"];
863
+ addOnInit(Module2["asm"]["V"]);
864
+ removeRunDependency();
865
+ }
866
+ addRunDependency();
867
+ function receiveInstantiationResult(result) {
868
+ receiveInstance(result["instance"]);
869
+ }
870
+ function instantiateArrayBuffer(receiver) {
871
+ return getBinaryPromise().then(function(binary) {
872
+ return WebAssembly.instantiate(binary, info);
873
+ }).then(function(instance) {
874
+ return instance;
875
+ }).then(receiver, function(reason) {
876
+ err("failed to asynchronously prepare wasm: " + reason);
877
+ abort(reason);
878
+ });
879
+ }
880
+ function instantiateAsync() {
881
+ if (!wasmBinary && typeof WebAssembly.instantiateStreaming == "function" && !isDataURI(wasmBinaryFile) && typeof fetch == "function") {
882
+ return fetch(wasmBinaryFile, { credentials: "same-origin" }).then(function(response) {
883
+ var result = WebAssembly.instantiateStreaming(response, info);
884
+ return result.then(receiveInstantiationResult, function(reason) {
885
+ err("wasm streaming compile failed: " + reason);
886
+ err("falling back to ArrayBuffer instantiation");
887
+ return instantiateArrayBuffer(receiveInstantiationResult);
888
+ });
889
+ });
890
+ } else {
891
+ return instantiateArrayBuffer(receiveInstantiationResult);
892
+ }
893
+ }
894
+ if (Module2["instantiateWasm"]) {
895
+ try {
896
+ var exports = Module2["instantiateWasm"](info, receiveInstance);
897
+ return exports;
898
+ } catch (e) {
899
+ err("Module.instantiateWasm callback failed with error: " + e);
900
+ readyPromiseReject(e);
901
+ }
902
+ }
903
+ instantiateAsync().catch(readyPromiseReject);
904
+ return {};
905
+ }
906
+ function callRuntimeCallbacks(callbacks) {
907
+ while (callbacks.length > 0) {
908
+ callbacks.shift()(Module2);
909
+ }
910
+ }
911
+ function ExceptionInfo(excPtr) {
912
+ this.excPtr = excPtr;
913
+ this.ptr = excPtr - 24;
914
+ this.set_type = function(type) {
915
+ HEAPU32[this.ptr + 4 >> 2] = type;
916
+ };
917
+ this.get_type = function() {
918
+ return HEAPU32[this.ptr + 4 >> 2];
919
+ };
920
+ this.set_destructor = function(destructor) {
921
+ HEAPU32[this.ptr + 8 >> 2] = destructor;
922
+ };
923
+ this.get_destructor = function() {
924
+ return HEAPU32[this.ptr + 8 >> 2];
925
+ };
926
+ this.set_refcount = function(refcount) {
927
+ HEAP32[this.ptr >> 2] = refcount;
928
+ };
929
+ this.set_caught = function(caught) {
930
+ caught = caught ? 1 : 0;
931
+ HEAP8[this.ptr + 12 >> 0] = caught;
932
+ };
933
+ this.get_caught = function() {
934
+ return HEAP8[this.ptr + 12 >> 0] != 0;
935
+ };
936
+ this.set_rethrown = function(rethrown) {
937
+ rethrown = rethrown ? 1 : 0;
938
+ HEAP8[this.ptr + 13 >> 0] = rethrown;
939
+ };
940
+ this.get_rethrown = function() {
941
+ return HEAP8[this.ptr + 13 >> 0] != 0;
942
+ };
943
+ this.init = function(type, destructor) {
944
+ this.set_adjusted_ptr(0);
945
+ this.set_type(type);
946
+ this.set_destructor(destructor);
947
+ this.set_refcount(0);
948
+ this.set_caught(false);
949
+ this.set_rethrown(false);
950
+ };
951
+ this.add_ref = function() {
952
+ var value = HEAP32[this.ptr >> 2];
953
+ HEAP32[this.ptr >> 2] = value + 1;
954
+ };
955
+ this.release_ref = function() {
956
+ var prev = HEAP32[this.ptr >> 2];
957
+ HEAP32[this.ptr >> 2] = prev - 1;
958
+ return prev === 1;
959
+ };
960
+ this.set_adjusted_ptr = function(adjustedPtr) {
961
+ HEAPU32[this.ptr + 16 >> 2] = adjustedPtr;
962
+ };
963
+ this.get_adjusted_ptr = function() {
964
+ return HEAPU32[this.ptr + 16 >> 2];
965
+ };
966
+ this.get_exception_ptr = function() {
967
+ var isPointer = ___cxa_is_pointer_type(this.get_type());
968
+ if (isPointer) {
969
+ return HEAPU32[this.excPtr >> 2];
970
+ }
971
+ var adjusted = this.get_adjusted_ptr();
972
+ if (adjusted !== 0) return adjusted;
973
+ return this.excPtr;
974
+ };
975
+ }
976
+ function ___cxa_throw(ptr, type, destructor) {
977
+ var info = new ExceptionInfo(ptr);
978
+ info.init(type, destructor);
979
+ throw ptr;
980
+ }
981
+ function ___syscall_fcntl64(fd, cmd, varargs) {
982
+ return 0;
983
+ }
984
+ function ___syscall_getcwd(buf, size) {
985
+ }
986
+ function ___syscall_ioctl(fd, op, varargs) {
987
+ return 0;
988
+ }
989
+ function ___syscall_openat(dirfd, path, flags, varargs) {
990
+ }
991
+ function ___syscall_rmdir(path) {
992
+ }
993
+ function ___syscall_unlinkat(dirfd, path, flags) {
994
+ }
995
+ var structRegistrations = {};
996
+ function runDestructors(destructors) {
997
+ while (destructors.length) {
998
+ var ptr = destructors.pop();
999
+ var del = destructors.pop();
1000
+ del(ptr);
1001
+ }
1002
+ }
1003
+ function simpleReadValueFromPointer(pointer) {
1004
+ return this["fromWireType"](HEAP32[pointer >> 2]);
1005
+ }
1006
+ var awaitingDependencies = {};
1007
+ var registeredTypes = {};
1008
+ var typeDependencies = {};
1009
+ var char_0 = 48;
1010
+ var char_9 = 57;
1011
+ function makeLegalFunctionName(name) {
1012
+ if (void 0 === name) {
1013
+ return "_unknown";
1014
+ }
1015
+ name = name.replace(/[^a-zA-Z0-9_]/g, "$");
1016
+ var f = name.charCodeAt(0);
1017
+ if (f >= char_0 && f <= char_9) {
1018
+ return "_" + name;
1019
+ }
1020
+ return name;
1021
+ }
1022
+ function createNamedFunction(name, body) {
1023
+ name = makeLegalFunctionName(name);
1024
+ return function() {
1025
+ return body.apply(this, arguments);
1026
+ };
1027
+ }
1028
+ function extendError(baseErrorType, errorName) {
1029
+ var errorClass = createNamedFunction(errorName, function(message) {
1030
+ this.name = errorName;
1031
+ this.message = message;
1032
+ var stack = new Error(message).stack;
1033
+ if (stack !== void 0) {
1034
+ this.stack = this.toString() + "\n" + stack.replace(/^Error(:[^\n]*)?\n/, "");
1035
+ }
1036
+ });
1037
+ errorClass.prototype = Object.create(baseErrorType.prototype);
1038
+ errorClass.prototype.constructor = errorClass;
1039
+ errorClass.prototype.toString = function() {
1040
+ if (this.message === void 0) {
1041
+ return this.name;
1042
+ } else {
1043
+ return this.name + ": " + this.message;
1044
+ }
1045
+ };
1046
+ return errorClass;
1047
+ }
1048
+ var InternalError = void 0;
1049
+ function throwInternalError(message) {
1050
+ throw new InternalError(message);
1051
+ }
1052
+ function whenDependentTypesAreResolved(myTypes, dependentTypes, getTypeConverters) {
1053
+ myTypes.forEach(function(type) {
1054
+ typeDependencies[type] = dependentTypes;
1055
+ });
1056
+ function onComplete(typeConverters2) {
1057
+ var myTypeConverters = getTypeConverters(typeConverters2);
1058
+ if (myTypeConverters.length !== myTypes.length) {
1059
+ throwInternalError("Mismatched type converter count");
1060
+ }
1061
+ for (var i = 0; i < myTypes.length; ++i) {
1062
+ registerType(myTypes[i], myTypeConverters[i]);
1063
+ }
1064
+ }
1065
+ var typeConverters = new Array(dependentTypes.length);
1066
+ var unregisteredTypes = [];
1067
+ var registered = 0;
1068
+ dependentTypes.forEach((dt, i) => {
1069
+ if (registeredTypes.hasOwnProperty(dt)) {
1070
+ typeConverters[i] = registeredTypes[dt];
1071
+ } else {
1072
+ unregisteredTypes.push(dt);
1073
+ if (!awaitingDependencies.hasOwnProperty(dt)) {
1074
+ awaitingDependencies[dt] = [];
1075
+ }
1076
+ awaitingDependencies[dt].push(() => {
1077
+ typeConverters[i] = registeredTypes[dt];
1078
+ ++registered;
1079
+ if (registered === unregisteredTypes.length) {
1080
+ onComplete(typeConverters);
1081
+ }
1082
+ });
1083
+ }
1084
+ });
1085
+ if (0 === unregisteredTypes.length) {
1086
+ onComplete(typeConverters);
1087
+ }
1088
+ }
1089
+ function __embind_finalize_value_object(structType) {
1090
+ var reg = structRegistrations[structType];
1091
+ delete structRegistrations[structType];
1092
+ var rawConstructor = reg.rawConstructor;
1093
+ var rawDestructor = reg.rawDestructor;
1094
+ var fieldRecords = reg.fields;
1095
+ var fieldTypes = fieldRecords.map((field) => field.getterReturnType).concat(fieldRecords.map((field) => field.setterArgumentType));
1096
+ whenDependentTypesAreResolved([structType], fieldTypes, (fieldTypes2) => {
1097
+ var fields = {};
1098
+ fieldRecords.forEach((field, i) => {
1099
+ var fieldName = field.fieldName;
1100
+ var getterReturnType = fieldTypes2[i];
1101
+ var getter = field.getter;
1102
+ var getterContext = field.getterContext;
1103
+ var setterArgumentType = fieldTypes2[i + fieldRecords.length];
1104
+ var setter = field.setter;
1105
+ var setterContext = field.setterContext;
1106
+ fields[fieldName] = { read: (ptr) => {
1107
+ return getterReturnType["fromWireType"](getter(getterContext, ptr));
1108
+ }, write: (ptr, o) => {
1109
+ var destructors = [];
1110
+ setter(setterContext, ptr, setterArgumentType["toWireType"](destructors, o));
1111
+ runDestructors(destructors);
1112
+ } };
1113
+ });
1114
+ return [{ name: reg.name, "fromWireType": function(ptr) {
1115
+ var rv = {};
1116
+ for (var i in fields) {
1117
+ rv[i] = fields[i].read(ptr);
1118
+ }
1119
+ rawDestructor(ptr);
1120
+ return rv;
1121
+ }, "toWireType": function(destructors, o) {
1122
+ for (var fieldName in fields) {
1123
+ if (!(fieldName in o)) {
1124
+ throw new TypeError('Missing field: "' + fieldName + '"');
1125
+ }
1126
+ }
1127
+ var ptr = rawConstructor();
1128
+ for (fieldName in fields) {
1129
+ fields[fieldName].write(ptr, o[fieldName]);
1130
+ }
1131
+ if (destructors !== null) {
1132
+ destructors.push(rawDestructor, ptr);
1133
+ }
1134
+ return ptr;
1135
+ }, "argPackAdvance": 8, "readValueFromPointer": simpleReadValueFromPointer, destructorFunction: rawDestructor }];
1136
+ });
1137
+ }
1138
+ function __embind_register_bigint(primitiveType, name, size, minRange, maxRange) {
1139
+ }
1140
+ function getShiftFromSize(size) {
1141
+ switch (size) {
1142
+ case 1:
1143
+ return 0;
1144
+ case 2:
1145
+ return 1;
1146
+ case 4:
1147
+ return 2;
1148
+ case 8:
1149
+ return 3;
1150
+ default:
1151
+ throw new TypeError("Unknown type size: " + size);
1152
+ }
1153
+ }
1154
+ function embind_init_charCodes() {
1155
+ var codes = new Array(256);
1156
+ for (var i = 0; i < 256; ++i) {
1157
+ codes[i] = String.fromCharCode(i);
1158
+ }
1159
+ embind_charCodes = codes;
1160
+ }
1161
+ var embind_charCodes = void 0;
1162
+ function readLatin1String(ptr) {
1163
+ var ret = "";
1164
+ var c = ptr;
1165
+ while (HEAPU8[c]) {
1166
+ ret += embind_charCodes[HEAPU8[c++]];
1167
+ }
1168
+ return ret;
1169
+ }
1170
+ var BindingError = void 0;
1171
+ function throwBindingError(message) {
1172
+ throw new BindingError(message);
1173
+ }
1174
+ function registerType(rawType, registeredInstance, options = {}) {
1175
+ if (!("argPackAdvance" in registeredInstance)) {
1176
+ throw new TypeError("registerType registeredInstance requires argPackAdvance");
1177
+ }
1178
+ var name = registeredInstance.name;
1179
+ if (!rawType) {
1180
+ throwBindingError('type "' + name + '" must have a positive integer typeid pointer');
1181
+ }
1182
+ if (registeredTypes.hasOwnProperty(rawType)) {
1183
+ if (options.ignoreDuplicateRegistrations) {
1184
+ return;
1185
+ } else {
1186
+ throwBindingError("Cannot register type '" + name + "' twice");
1187
+ }
1188
+ }
1189
+ registeredTypes[rawType] = registeredInstance;
1190
+ delete typeDependencies[rawType];
1191
+ if (awaitingDependencies.hasOwnProperty(rawType)) {
1192
+ var callbacks = awaitingDependencies[rawType];
1193
+ delete awaitingDependencies[rawType];
1194
+ callbacks.forEach((cb) => cb());
1195
+ }
1196
+ }
1197
+ function __embind_register_bool(rawType, name, size, trueValue, falseValue) {
1198
+ var shift = getShiftFromSize(size);
1199
+ name = readLatin1String(name);
1200
+ registerType(rawType, { name, "fromWireType": function(wt) {
1201
+ return !!wt;
1202
+ }, "toWireType": function(destructors, o) {
1203
+ return o ? trueValue : falseValue;
1204
+ }, "argPackAdvance": 8, "readValueFromPointer": function(pointer) {
1205
+ var heap;
1206
+ if (size === 1) {
1207
+ heap = HEAP8;
1208
+ } else if (size === 2) {
1209
+ heap = HEAP16;
1210
+ } else if (size === 4) {
1211
+ heap = HEAP32;
1212
+ } else {
1213
+ throw new TypeError("Unknown boolean type size: " + name);
1214
+ }
1215
+ return this["fromWireType"](heap[pointer >> shift]);
1216
+ }, destructorFunction: null });
1217
+ }
1218
+ function ClassHandle_isAliasOf(other) {
1219
+ if (!(this instanceof ClassHandle)) {
1220
+ return false;
1221
+ }
1222
+ if (!(other instanceof ClassHandle)) {
1223
+ return false;
1224
+ }
1225
+ var leftClass = this.$$.ptrType.registeredClass;
1226
+ var left = this.$$.ptr;
1227
+ var rightClass = other.$$.ptrType.registeredClass;
1228
+ var right = other.$$.ptr;
1229
+ while (leftClass.baseClass) {
1230
+ left = leftClass.upcast(left);
1231
+ leftClass = leftClass.baseClass;
1232
+ }
1233
+ while (rightClass.baseClass) {
1234
+ right = rightClass.upcast(right);
1235
+ rightClass = rightClass.baseClass;
1236
+ }
1237
+ return leftClass === rightClass && left === right;
1238
+ }
1239
+ function shallowCopyInternalPointer(o) {
1240
+ return { count: o.count, deleteScheduled: o.deleteScheduled, preservePointerOnDelete: o.preservePointerOnDelete, ptr: o.ptr, ptrType: o.ptrType, smartPtr: o.smartPtr, smartPtrType: o.smartPtrType };
1241
+ }
1242
+ function throwInstanceAlreadyDeleted(obj) {
1243
+ function getInstanceTypeName(handle) {
1244
+ return handle.$$.ptrType.registeredClass.name;
1245
+ }
1246
+ throwBindingError(getInstanceTypeName(obj) + " instance already deleted");
1247
+ }
1248
+ var finalizationRegistry = false;
1249
+ function detachFinalizer(handle) {
1250
+ }
1251
+ function runDestructor($$) {
1252
+ if ($$.smartPtr) {
1253
+ $$.smartPtrType.rawDestructor($$.smartPtr);
1254
+ } else {
1255
+ $$.ptrType.registeredClass.rawDestructor($$.ptr);
1256
+ }
1257
+ }
1258
+ function releaseClassHandle($$) {
1259
+ $$.count.value -= 1;
1260
+ var toDelete = 0 === $$.count.value;
1261
+ if (toDelete) {
1262
+ runDestructor($$);
1263
+ }
1264
+ }
1265
+ function downcastPointer(ptr, ptrClass, desiredClass) {
1266
+ if (ptrClass === desiredClass) {
1267
+ return ptr;
1268
+ }
1269
+ if (void 0 === desiredClass.baseClass) {
1270
+ return null;
1271
+ }
1272
+ var rv = downcastPointer(ptr, ptrClass, desiredClass.baseClass);
1273
+ if (rv === null) {
1274
+ return null;
1275
+ }
1276
+ return desiredClass.downcast(rv);
1277
+ }
1278
+ var registeredPointers = {};
1279
+ function getInheritedInstanceCount() {
1280
+ return Object.keys(registeredInstances).length;
1281
+ }
1282
+ function getLiveInheritedInstances() {
1283
+ var rv = [];
1284
+ for (var k in registeredInstances) {
1285
+ if (registeredInstances.hasOwnProperty(k)) {
1286
+ rv.push(registeredInstances[k]);
1287
+ }
1288
+ }
1289
+ return rv;
1290
+ }
1291
+ var deletionQueue = [];
1292
+ function flushPendingDeletes() {
1293
+ while (deletionQueue.length) {
1294
+ var obj = deletionQueue.pop();
1295
+ obj.$$.deleteScheduled = false;
1296
+ obj["delete"]();
1297
+ }
1298
+ }
1299
+ var delayFunction = void 0;
1300
+ function setDelayFunction(fn) {
1301
+ delayFunction = fn;
1302
+ if (deletionQueue.length && delayFunction) {
1303
+ delayFunction(flushPendingDeletes);
1304
+ }
1305
+ }
1306
+ function init_embind() {
1307
+ Module2["getInheritedInstanceCount"] = getInheritedInstanceCount;
1308
+ Module2["getLiveInheritedInstances"] = getLiveInheritedInstances;
1309
+ Module2["flushPendingDeletes"] = flushPendingDeletes;
1310
+ Module2["setDelayFunction"] = setDelayFunction;
1311
+ }
1312
+ var registeredInstances = {};
1313
+ function getBasestPointer(class_, ptr) {
1314
+ if (ptr === void 0) {
1315
+ throwBindingError("ptr should not be undefined");
1316
+ }
1317
+ while (class_.baseClass) {
1318
+ ptr = class_.upcast(ptr);
1319
+ class_ = class_.baseClass;
1320
+ }
1321
+ return ptr;
1322
+ }
1323
+ function getInheritedInstance(class_, ptr) {
1324
+ ptr = getBasestPointer(class_, ptr);
1325
+ return registeredInstances[ptr];
1326
+ }
1327
+ function makeClassHandle(prototype, record) {
1328
+ if (!record.ptrType || !record.ptr) {
1329
+ throwInternalError("makeClassHandle requires ptr and ptrType");
1330
+ }
1331
+ var hasSmartPtrType = !!record.smartPtrType;
1332
+ var hasSmartPtr = !!record.smartPtr;
1333
+ if (hasSmartPtrType !== hasSmartPtr) {
1334
+ throwInternalError("Both smartPtrType and smartPtr must be specified");
1335
+ }
1336
+ record.count = { value: 1 };
1337
+ return attachFinalizer(Object.create(prototype, { $$: { value: record } }));
1338
+ }
1339
+ function RegisteredPointer_fromWireType(ptr) {
1340
+ var rawPointer = this.getPointee(ptr);
1341
+ if (!rawPointer) {
1342
+ this.destructor(ptr);
1343
+ return null;
1344
+ }
1345
+ var registeredInstance = getInheritedInstance(this.registeredClass, rawPointer);
1346
+ if (void 0 !== registeredInstance) {
1347
+ if (0 === registeredInstance.$$.count.value) {
1348
+ registeredInstance.$$.ptr = rawPointer;
1349
+ registeredInstance.$$.smartPtr = ptr;
1350
+ return registeredInstance["clone"]();
1351
+ } else {
1352
+ var rv = registeredInstance["clone"]();
1353
+ this.destructor(ptr);
1354
+ return rv;
1355
+ }
1356
+ }
1357
+ function makeDefaultHandle() {
1358
+ if (this.isSmartPointer) {
1359
+ return makeClassHandle(this.registeredClass.instancePrototype, { ptrType: this.pointeeType, ptr: rawPointer, smartPtrType: this, smartPtr: ptr });
1360
+ } else {
1361
+ return makeClassHandle(this.registeredClass.instancePrototype, { ptrType: this, ptr });
1362
+ }
1363
+ }
1364
+ var actualType = this.registeredClass.getActualType(rawPointer);
1365
+ var registeredPointerRecord = registeredPointers[actualType];
1366
+ if (!registeredPointerRecord) {
1367
+ return makeDefaultHandle.call(this);
1368
+ }
1369
+ var toType;
1370
+ if (this.isConst) {
1371
+ toType = registeredPointerRecord.constPointerType;
1372
+ } else {
1373
+ toType = registeredPointerRecord.pointerType;
1374
+ }
1375
+ var dp = downcastPointer(rawPointer, this.registeredClass, toType.registeredClass);
1376
+ if (dp === null) {
1377
+ return makeDefaultHandle.call(this);
1378
+ }
1379
+ if (this.isSmartPointer) {
1380
+ return makeClassHandle(toType.registeredClass.instancePrototype, { ptrType: toType, ptr: dp, smartPtrType: this, smartPtr: ptr });
1381
+ } else {
1382
+ return makeClassHandle(toType.registeredClass.instancePrototype, { ptrType: toType, ptr: dp });
1383
+ }
1384
+ }
1385
+ function attachFinalizer(handle) {
1386
+ if ("undefined" === typeof FinalizationRegistry) {
1387
+ attachFinalizer = (handle2) => handle2;
1388
+ return handle;
1389
+ }
1390
+ finalizationRegistry = new FinalizationRegistry((info) => {
1391
+ releaseClassHandle(info.$$);
1392
+ });
1393
+ attachFinalizer = (handle2) => {
1394
+ var $$ = handle2.$$;
1395
+ var hasSmartPtr = !!$$.smartPtr;
1396
+ if (hasSmartPtr) {
1397
+ var info = { $$ };
1398
+ finalizationRegistry.register(handle2, info, handle2);
1399
+ }
1400
+ return handle2;
1401
+ };
1402
+ detachFinalizer = (handle2) => finalizationRegistry.unregister(handle2);
1403
+ return attachFinalizer(handle);
1404
+ }
1405
+ function ClassHandle_clone() {
1406
+ if (!this.$$.ptr) {
1407
+ throwInstanceAlreadyDeleted(this);
1408
+ }
1409
+ if (this.$$.preservePointerOnDelete) {
1410
+ this.$$.count.value += 1;
1411
+ return this;
1412
+ } else {
1413
+ var clone = attachFinalizer(Object.create(Object.getPrototypeOf(this), { $$: { value: shallowCopyInternalPointer(this.$$) } }));
1414
+ clone.$$.count.value += 1;
1415
+ clone.$$.deleteScheduled = false;
1416
+ return clone;
1417
+ }
1418
+ }
1419
+ function ClassHandle_delete() {
1420
+ if (!this.$$.ptr) {
1421
+ throwInstanceAlreadyDeleted(this);
1422
+ }
1423
+ if (this.$$.deleteScheduled && !this.$$.preservePointerOnDelete) {
1424
+ throwBindingError("Object already scheduled for deletion");
1425
+ }
1426
+ detachFinalizer(this);
1427
+ releaseClassHandle(this.$$);
1428
+ if (!this.$$.preservePointerOnDelete) {
1429
+ this.$$.smartPtr = void 0;
1430
+ this.$$.ptr = void 0;
1431
+ }
1432
+ }
1433
+ function ClassHandle_isDeleted() {
1434
+ return !this.$$.ptr;
1435
+ }
1436
+ function ClassHandle_deleteLater() {
1437
+ if (!this.$$.ptr) {
1438
+ throwInstanceAlreadyDeleted(this);
1439
+ }
1440
+ if (this.$$.deleteScheduled && !this.$$.preservePointerOnDelete) {
1441
+ throwBindingError("Object already scheduled for deletion");
1442
+ }
1443
+ deletionQueue.push(this);
1444
+ if (deletionQueue.length === 1 && delayFunction) {
1445
+ delayFunction(flushPendingDeletes);
1446
+ }
1447
+ this.$$.deleteScheduled = true;
1448
+ return this;
1449
+ }
1450
+ function init_ClassHandle() {
1451
+ ClassHandle.prototype["isAliasOf"] = ClassHandle_isAliasOf;
1452
+ ClassHandle.prototype["clone"] = ClassHandle_clone;
1453
+ ClassHandle.prototype["delete"] = ClassHandle_delete;
1454
+ ClassHandle.prototype["isDeleted"] = ClassHandle_isDeleted;
1455
+ ClassHandle.prototype["deleteLater"] = ClassHandle_deleteLater;
1456
+ }
1457
+ function ClassHandle() {
1458
+ }
1459
+ function ensureOverloadTable(proto, methodName, humanName) {
1460
+ if (void 0 === proto[methodName].overloadTable) {
1461
+ var prevFunc = proto[methodName];
1462
+ proto[methodName] = function() {
1463
+ if (!proto[methodName].overloadTable.hasOwnProperty(arguments.length)) {
1464
+ throwBindingError("Function '" + humanName + "' called with an invalid number of arguments (" + arguments.length + ") - expects one of (" + proto[methodName].overloadTable + ")!");
1465
+ }
1466
+ return proto[methodName].overloadTable[arguments.length].apply(this, arguments);
1467
+ };
1468
+ proto[methodName].overloadTable = [];
1469
+ proto[methodName].overloadTable[prevFunc.argCount] = prevFunc;
1470
+ }
1471
+ }
1472
+ function exposePublicSymbol(name, value, numArguments) {
1473
+ if (Module2.hasOwnProperty(name)) {
1474
+ if (void 0 === numArguments || void 0 !== Module2[name].overloadTable && void 0 !== Module2[name].overloadTable[numArguments]) {
1475
+ throwBindingError("Cannot register public name '" + name + "' twice");
1476
+ }
1477
+ ensureOverloadTable(Module2, name, name);
1478
+ if (Module2.hasOwnProperty(numArguments)) {
1479
+ throwBindingError("Cannot register multiple overloads of a function with the same number of arguments (" + numArguments + ")!");
1480
+ }
1481
+ Module2[name].overloadTable[numArguments] = value;
1482
+ } else {
1483
+ Module2[name] = value;
1484
+ if (void 0 !== numArguments) {
1485
+ Module2[name].numArguments = numArguments;
1486
+ }
1487
+ }
1488
+ }
1489
+ function RegisteredClass(name, constructor, instancePrototype, rawDestructor, baseClass, getActualType, upcast, downcast) {
1490
+ this.name = name;
1491
+ this.constructor = constructor;
1492
+ this.instancePrototype = instancePrototype;
1493
+ this.rawDestructor = rawDestructor;
1494
+ this.baseClass = baseClass;
1495
+ this.getActualType = getActualType;
1496
+ this.upcast = upcast;
1497
+ this.downcast = downcast;
1498
+ this.pureVirtualFunctions = [];
1499
+ }
1500
+ function upcastPointer(ptr, ptrClass, desiredClass) {
1501
+ while (ptrClass !== desiredClass) {
1502
+ if (!ptrClass.upcast) {
1503
+ throwBindingError("Expected null or instance of " + desiredClass.name + ", got an instance of " + ptrClass.name);
1504
+ }
1505
+ ptr = ptrClass.upcast(ptr);
1506
+ ptrClass = ptrClass.baseClass;
1507
+ }
1508
+ return ptr;
1509
+ }
1510
+ function constNoSmartPtrRawPointerToWireType(destructors, handle) {
1511
+ if (handle === null) {
1512
+ if (this.isReference) {
1513
+ throwBindingError("null is not a valid " + this.name);
1514
+ }
1515
+ return 0;
1516
+ }
1517
+ if (!handle.$$) {
1518
+ throwBindingError('Cannot pass "' + embindRepr(handle) + '" as a ' + this.name);
1519
+ }
1520
+ if (!handle.$$.ptr) {
1521
+ throwBindingError("Cannot pass deleted object as a pointer of type " + this.name);
1522
+ }
1523
+ var handleClass = handle.$$.ptrType.registeredClass;
1524
+ var ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass);
1525
+ return ptr;
1526
+ }
1527
+ function genericPointerToWireType(destructors, handle) {
1528
+ var ptr;
1529
+ if (handle === null) {
1530
+ if (this.isReference) {
1531
+ throwBindingError("null is not a valid " + this.name);
1532
+ }
1533
+ if (this.isSmartPointer) {
1534
+ ptr = this.rawConstructor();
1535
+ if (destructors !== null) {
1536
+ destructors.push(this.rawDestructor, ptr);
1537
+ }
1538
+ return ptr;
1539
+ } else {
1540
+ return 0;
1541
+ }
1542
+ }
1543
+ if (!handle.$$) {
1544
+ throwBindingError('Cannot pass "' + embindRepr(handle) + '" as a ' + this.name);
1545
+ }
1546
+ if (!handle.$$.ptr) {
1547
+ throwBindingError("Cannot pass deleted object as a pointer of type " + this.name);
1548
+ }
1549
+ if (!this.isConst && handle.$$.ptrType.isConst) {
1550
+ throwBindingError("Cannot convert argument of type " + (handle.$$.smartPtrType ? handle.$$.smartPtrType.name : handle.$$.ptrType.name) + " to parameter type " + this.name);
1551
+ }
1552
+ var handleClass = handle.$$.ptrType.registeredClass;
1553
+ ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass);
1554
+ if (this.isSmartPointer) {
1555
+ if (void 0 === handle.$$.smartPtr) {
1556
+ throwBindingError("Passing raw pointer to smart pointer is illegal");
1557
+ }
1558
+ switch (this.sharingPolicy) {
1559
+ case 0:
1560
+ if (handle.$$.smartPtrType === this) {
1561
+ ptr = handle.$$.smartPtr;
1562
+ } else {
1563
+ throwBindingError("Cannot convert argument of type " + (handle.$$.smartPtrType ? handle.$$.smartPtrType.name : handle.$$.ptrType.name) + " to parameter type " + this.name);
1564
+ }
1565
+ break;
1566
+ case 1:
1567
+ ptr = handle.$$.smartPtr;
1568
+ break;
1569
+ case 2:
1570
+ if (handle.$$.smartPtrType === this) {
1571
+ ptr = handle.$$.smartPtr;
1572
+ } else {
1573
+ var clonedHandle = handle["clone"]();
1574
+ ptr = this.rawShare(ptr, Emval.toHandle(function() {
1575
+ clonedHandle["delete"]();
1576
+ }));
1577
+ if (destructors !== null) {
1578
+ destructors.push(this.rawDestructor, ptr);
1579
+ }
1580
+ }
1581
+ break;
1582
+ default:
1583
+ throwBindingError("Unsupporting sharing policy");
1584
+ }
1585
+ }
1586
+ return ptr;
1587
+ }
1588
+ function nonConstNoSmartPtrRawPointerToWireType(destructors, handle) {
1589
+ if (handle === null) {
1590
+ if (this.isReference) {
1591
+ throwBindingError("null is not a valid " + this.name);
1592
+ }
1593
+ return 0;
1594
+ }
1595
+ if (!handle.$$) {
1596
+ throwBindingError('Cannot pass "' + embindRepr(handle) + '" as a ' + this.name);
1597
+ }
1598
+ if (!handle.$$.ptr) {
1599
+ throwBindingError("Cannot pass deleted object as a pointer of type " + this.name);
1600
+ }
1601
+ if (handle.$$.ptrType.isConst) {
1602
+ throwBindingError("Cannot convert argument of type " + handle.$$.ptrType.name + " to parameter type " + this.name);
1603
+ }
1604
+ var handleClass = handle.$$.ptrType.registeredClass;
1605
+ var ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass);
1606
+ return ptr;
1607
+ }
1608
+ function RegisteredPointer_getPointee(ptr) {
1609
+ if (this.rawGetPointee) {
1610
+ ptr = this.rawGetPointee(ptr);
1611
+ }
1612
+ return ptr;
1613
+ }
1614
+ function RegisteredPointer_destructor(ptr) {
1615
+ if (this.rawDestructor) {
1616
+ this.rawDestructor(ptr);
1617
+ }
1618
+ }
1619
+ function RegisteredPointer_deleteObject(handle) {
1620
+ if (handle !== null) {
1621
+ handle["delete"]();
1622
+ }
1623
+ }
1624
+ function init_RegisteredPointer() {
1625
+ RegisteredPointer.prototype.getPointee = RegisteredPointer_getPointee;
1626
+ RegisteredPointer.prototype.destructor = RegisteredPointer_destructor;
1627
+ RegisteredPointer.prototype["argPackAdvance"] = 8;
1628
+ RegisteredPointer.prototype["readValueFromPointer"] = simpleReadValueFromPointer;
1629
+ RegisteredPointer.prototype["deleteObject"] = RegisteredPointer_deleteObject;
1630
+ RegisteredPointer.prototype["fromWireType"] = RegisteredPointer_fromWireType;
1631
+ }
1632
+ function RegisteredPointer(name, registeredClass, isReference, isConst, isSmartPointer, pointeeType, sharingPolicy, rawGetPointee, rawConstructor, rawShare, rawDestructor) {
1633
+ this.name = name;
1634
+ this.registeredClass = registeredClass;
1635
+ this.isReference = isReference;
1636
+ this.isConst = isConst;
1637
+ this.isSmartPointer = isSmartPointer;
1638
+ this.pointeeType = pointeeType;
1639
+ this.sharingPolicy = sharingPolicy;
1640
+ this.rawGetPointee = rawGetPointee;
1641
+ this.rawConstructor = rawConstructor;
1642
+ this.rawShare = rawShare;
1643
+ this.rawDestructor = rawDestructor;
1644
+ if (!isSmartPointer && registeredClass.baseClass === void 0) {
1645
+ if (isConst) {
1646
+ this["toWireType"] = constNoSmartPtrRawPointerToWireType;
1647
+ this.destructorFunction = null;
1648
+ } else {
1649
+ this["toWireType"] = nonConstNoSmartPtrRawPointerToWireType;
1650
+ this.destructorFunction = null;
1651
+ }
1652
+ } else {
1653
+ this["toWireType"] = genericPointerToWireType;
1654
+ }
1655
+ }
1656
+ function replacePublicSymbol(name, value, numArguments) {
1657
+ if (!Module2.hasOwnProperty(name)) {
1658
+ throwInternalError("Replacing nonexistant public symbol");
1659
+ }
1660
+ if (void 0 !== Module2[name].overloadTable && void 0 !== numArguments) {
1661
+ Module2[name].overloadTable[numArguments] = value;
1662
+ } else {
1663
+ Module2[name] = value;
1664
+ Module2[name].argCount = numArguments;
1665
+ }
1666
+ }
1667
+ function dynCallLegacy(sig, ptr, args) {
1668
+ var f = Module2["dynCall_" + sig];
1669
+ return args && args.length ? f.apply(null, [ptr].concat(args)) : f.call(null, ptr);
1670
+ }
1671
+ function getWasmTableEntry(funcPtr) {
1672
+ return wasmTable.get(funcPtr);
1673
+ }
1674
+ function dynCall(sig, ptr, args) {
1675
+ if (sig.includes("j")) {
1676
+ return dynCallLegacy(sig, ptr, args);
1677
+ }
1678
+ var rtn = getWasmTableEntry(ptr).apply(null, args);
1679
+ return rtn;
1680
+ }
1681
+ function getDynCaller(sig, ptr) {
1682
+ var argCache = [];
1683
+ return function() {
1684
+ argCache.length = 0;
1685
+ Object.assign(argCache, arguments);
1686
+ return dynCall(sig, ptr, argCache);
1687
+ };
1688
+ }
1689
+ function embind__requireFunction(signature, rawFunction) {
1690
+ signature = readLatin1String(signature);
1691
+ function makeDynCaller() {
1692
+ if (signature.includes("j")) {
1693
+ return getDynCaller(signature, rawFunction);
1694
+ }
1695
+ return getWasmTableEntry(rawFunction);
1696
+ }
1697
+ var fp = makeDynCaller();
1698
+ if (typeof fp != "function") {
1699
+ throwBindingError("unknown function pointer with signature " + signature + ": " + rawFunction);
1700
+ }
1701
+ return fp;
1702
+ }
1703
+ var UnboundTypeError = void 0;
1704
+ function getTypeName(type) {
1705
+ var ptr = ___getTypeName(type);
1706
+ var rv = readLatin1String(ptr);
1707
+ _free(ptr);
1708
+ return rv;
1709
+ }
1710
+ function throwUnboundTypeError(message, types) {
1711
+ var unboundTypes = [];
1712
+ var seen = {};
1713
+ function visit(type) {
1714
+ if (seen[type]) {
1715
+ return;
1716
+ }
1717
+ if (registeredTypes[type]) {
1718
+ return;
1719
+ }
1720
+ if (typeDependencies[type]) {
1721
+ typeDependencies[type].forEach(visit);
1722
+ return;
1723
+ }
1724
+ unboundTypes.push(type);
1725
+ seen[type] = true;
1726
+ }
1727
+ types.forEach(visit);
1728
+ throw new UnboundTypeError(message + ": " + unboundTypes.map(getTypeName).join([", "]));
1729
+ }
1730
+ function __embind_register_class(rawType, rawPointerType, rawConstPointerType, baseClassRawType, getActualTypeSignature, getActualType, upcastSignature, upcast, downcastSignature, downcast, name, destructorSignature, rawDestructor) {
1731
+ name = readLatin1String(name);
1732
+ getActualType = embind__requireFunction(getActualTypeSignature, getActualType);
1733
+ if (upcast) {
1734
+ upcast = embind__requireFunction(upcastSignature, upcast);
1735
+ }
1736
+ if (downcast) {
1737
+ downcast = embind__requireFunction(downcastSignature, downcast);
1738
+ }
1739
+ rawDestructor = embind__requireFunction(destructorSignature, rawDestructor);
1740
+ var legalFunctionName = makeLegalFunctionName(name);
1741
+ exposePublicSymbol(legalFunctionName, function() {
1742
+ throwUnboundTypeError("Cannot construct " + name + " due to unbound types", [baseClassRawType]);
1743
+ });
1744
+ whenDependentTypesAreResolved([rawType, rawPointerType, rawConstPointerType], baseClassRawType ? [baseClassRawType] : [], function(base) {
1745
+ base = base[0];
1746
+ var baseClass;
1747
+ var basePrototype;
1748
+ if (baseClassRawType) {
1749
+ baseClass = base.registeredClass;
1750
+ basePrototype = baseClass.instancePrototype;
1751
+ } else {
1752
+ basePrototype = ClassHandle.prototype;
1753
+ }
1754
+ var constructor = createNamedFunction(legalFunctionName, function() {
1755
+ if (Object.getPrototypeOf(this) !== instancePrototype) {
1756
+ throw new BindingError("Use 'new' to construct " + name);
1757
+ }
1758
+ if (void 0 === registeredClass.constructor_body) {
1759
+ throw new BindingError(name + " has no accessible constructor");
1760
+ }
1761
+ var body = registeredClass.constructor_body[arguments.length];
1762
+ if (void 0 === body) {
1763
+ throw new BindingError("Tried to invoke ctor of " + name + " with invalid number of parameters (" + arguments.length + ") - expected (" + Object.keys(registeredClass.constructor_body).toString() + ") parameters instead!");
1764
+ }
1765
+ return body.apply(this, arguments);
1766
+ });
1767
+ var instancePrototype = Object.create(basePrototype, { constructor: { value: constructor } });
1768
+ constructor.prototype = instancePrototype;
1769
+ var registeredClass = new RegisteredClass(name, constructor, instancePrototype, rawDestructor, baseClass, getActualType, upcast, downcast);
1770
+ var referenceConverter = new RegisteredPointer(name, registeredClass, true, false, false);
1771
+ var pointerConverter = new RegisteredPointer(name + "*", registeredClass, false, false, false);
1772
+ var constPointerConverter = new RegisteredPointer(name + " const*", registeredClass, false, true, false);
1773
+ registeredPointers[rawType] = { pointerType: pointerConverter, constPointerType: constPointerConverter };
1774
+ replacePublicSymbol(legalFunctionName, constructor);
1775
+ return [referenceConverter, pointerConverter, constPointerConverter];
1776
+ });
1777
+ }
1778
+ function heap32VectorToArray(count, firstElement) {
1779
+ var array = [];
1780
+ for (var i = 0; i < count; i++) {
1781
+ array.push(HEAPU32[firstElement + i * 4 >> 2]);
1782
+ }
1783
+ return array;
1784
+ }
1785
+ function craftInvokerFunction(humanName, argTypes, classType, cppInvokerFunc, cppTargetFunc) {
1786
+ var argCount = argTypes.length;
1787
+ if (argCount < 2) {
1788
+ throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!");
1789
+ }
1790
+ var isClassMethodFunc = argTypes[1] !== null && classType !== null;
1791
+ var needsDestructorStack = false;
1792
+ for (var i = 1; i < argTypes.length; ++i) {
1793
+ if (argTypes[i] !== null && argTypes[i].destructorFunction === void 0) {
1794
+ needsDestructorStack = true;
1795
+ break;
1796
+ }
1797
+ }
1798
+ var returns = argTypes[0].name !== "void";
1799
+ var expectedArgCount = argCount - 2;
1800
+ var argsWired = new Array(expectedArgCount);
1801
+ var invokerFuncArgs = [];
1802
+ var destructors = [];
1803
+ return function() {
1804
+ if (arguments.length !== expectedArgCount) {
1805
+ throwBindingError("function " + humanName + " called with " + arguments.length + " arguments, expected " + expectedArgCount + " args!");
1806
+ }
1807
+ destructors.length = 0;
1808
+ var thisWired;
1809
+ invokerFuncArgs.length = isClassMethodFunc ? 2 : 1;
1810
+ invokerFuncArgs[0] = cppTargetFunc;
1811
+ if (isClassMethodFunc) {
1812
+ thisWired = argTypes[1]["toWireType"](destructors, this);
1813
+ invokerFuncArgs[1] = thisWired;
1814
+ }
1815
+ for (var i2 = 0; i2 < expectedArgCount; ++i2) {
1816
+ argsWired[i2] = argTypes[i2 + 2]["toWireType"](destructors, arguments[i2]);
1817
+ invokerFuncArgs.push(argsWired[i2]);
1818
+ }
1819
+ var rv = cppInvokerFunc.apply(null, invokerFuncArgs);
1820
+ function onDone(rv2) {
1821
+ if (needsDestructorStack) {
1822
+ runDestructors(destructors);
1823
+ } else {
1824
+ for (var i3 = isClassMethodFunc ? 1 : 2; i3 < argTypes.length; i3++) {
1825
+ var param = i3 === 1 ? thisWired : argsWired[i3 - 2];
1826
+ if (argTypes[i3].destructorFunction !== null) {
1827
+ argTypes[i3].destructorFunction(param);
1828
+ }
1829
+ }
1830
+ }
1831
+ if (returns) {
1832
+ return argTypes[0]["fromWireType"](rv2);
1833
+ }
1834
+ }
1835
+ return onDone(rv);
1836
+ };
1837
+ }
1838
+ function __embind_register_class_constructor(rawClassType, argCount, rawArgTypesAddr, invokerSignature, invoker, rawConstructor) {
1839
+ assert(argCount > 0);
1840
+ var rawArgTypes = heap32VectorToArray(argCount, rawArgTypesAddr);
1841
+ invoker = embind__requireFunction(invokerSignature, invoker);
1842
+ whenDependentTypesAreResolved([], [rawClassType], function(classType) {
1843
+ classType = classType[0];
1844
+ var humanName = "constructor " + classType.name;
1845
+ if (void 0 === classType.registeredClass.constructor_body) {
1846
+ classType.registeredClass.constructor_body = [];
1847
+ }
1848
+ if (void 0 !== classType.registeredClass.constructor_body[argCount - 1]) {
1849
+ throw new BindingError("Cannot register multiple constructors with identical number of parameters (" + (argCount - 1) + ") for class '" + classType.name + "'! Overload resolution is currently only performed using the parameter count, not actual type info!");
1850
+ }
1851
+ classType.registeredClass.constructor_body[argCount - 1] = () => {
1852
+ throwUnboundTypeError("Cannot construct " + classType.name + " due to unbound types", rawArgTypes);
1853
+ };
1854
+ whenDependentTypesAreResolved([], rawArgTypes, function(argTypes) {
1855
+ argTypes.splice(1, 0, null);
1856
+ classType.registeredClass.constructor_body[argCount - 1] = craftInvokerFunction(humanName, argTypes, null, invoker, rawConstructor);
1857
+ return [];
1858
+ });
1859
+ return [];
1860
+ });
1861
+ }
1862
+ function __embind_register_class_function(rawClassType, methodName, argCount, rawArgTypesAddr, invokerSignature, rawInvoker, context, isPureVirtual) {
1863
+ var rawArgTypes = heap32VectorToArray(argCount, rawArgTypesAddr);
1864
+ methodName = readLatin1String(methodName);
1865
+ rawInvoker = embind__requireFunction(invokerSignature, rawInvoker);
1866
+ whenDependentTypesAreResolved([], [rawClassType], function(classType) {
1867
+ classType = classType[0];
1868
+ var humanName = classType.name + "." + methodName;
1869
+ if (methodName.startsWith("@@")) {
1870
+ methodName = Symbol[methodName.substring(2)];
1871
+ }
1872
+ if (isPureVirtual) {
1873
+ classType.registeredClass.pureVirtualFunctions.push(methodName);
1874
+ }
1875
+ function unboundTypesHandler() {
1876
+ throwUnboundTypeError("Cannot call " + humanName + " due to unbound types", rawArgTypes);
1877
+ }
1878
+ var proto = classType.registeredClass.instancePrototype;
1879
+ var method = proto[methodName];
1880
+ if (void 0 === method || void 0 === method.overloadTable && method.className !== classType.name && method.argCount === argCount - 2) {
1881
+ unboundTypesHandler.argCount = argCount - 2;
1882
+ unboundTypesHandler.className = classType.name;
1883
+ proto[methodName] = unboundTypesHandler;
1884
+ } else {
1885
+ ensureOverloadTable(proto, methodName, humanName);
1886
+ proto[methodName].overloadTable[argCount - 2] = unboundTypesHandler;
1887
+ }
1888
+ whenDependentTypesAreResolved([], rawArgTypes, function(argTypes) {
1889
+ var memberFunction = craftInvokerFunction(humanName, argTypes, classType, rawInvoker, context);
1890
+ if (void 0 === proto[methodName].overloadTable) {
1891
+ memberFunction.argCount = argCount - 2;
1892
+ proto[methodName] = memberFunction;
1893
+ } else {
1894
+ proto[methodName].overloadTable[argCount - 2] = memberFunction;
1895
+ }
1896
+ return [];
1897
+ });
1898
+ return [];
1899
+ });
1900
+ }
1901
+ var emval_free_list = [];
1902
+ var emval_handle_array = [{}, { value: void 0 }, { value: null }, { value: true }, { value: false }];
1903
+ function __emval_decref(handle) {
1904
+ if (handle > 4 && 0 === --emval_handle_array[handle].refcount) {
1905
+ emval_handle_array[handle] = void 0;
1906
+ emval_free_list.push(handle);
1907
+ }
1908
+ }
1909
+ function count_emval_handles() {
1910
+ var count = 0;
1911
+ for (var i = 5; i < emval_handle_array.length; ++i) {
1912
+ if (emval_handle_array[i] !== void 0) {
1913
+ ++count;
1914
+ }
1915
+ }
1916
+ return count;
1917
+ }
1918
+ function get_first_emval() {
1919
+ for (var i = 5; i < emval_handle_array.length; ++i) {
1920
+ if (emval_handle_array[i] !== void 0) {
1921
+ return emval_handle_array[i];
1922
+ }
1923
+ }
1924
+ return null;
1925
+ }
1926
+ function init_emval() {
1927
+ Module2["count_emval_handles"] = count_emval_handles;
1928
+ Module2["get_first_emval"] = get_first_emval;
1929
+ }
1930
+ var Emval = { toValue: (handle) => {
1931
+ if (!handle) {
1932
+ throwBindingError("Cannot use deleted val. handle = " + handle);
1933
+ }
1934
+ return emval_handle_array[handle].value;
1935
+ }, toHandle: (value) => {
1936
+ switch (value) {
1937
+ case void 0:
1938
+ return 1;
1939
+ case null:
1940
+ return 2;
1941
+ case true:
1942
+ return 3;
1943
+ case false:
1944
+ return 4;
1945
+ default: {
1946
+ var handle = emval_free_list.length ? emval_free_list.pop() : emval_handle_array.length;
1947
+ emval_handle_array[handle] = { refcount: 1, value };
1948
+ return handle;
1949
+ }
1950
+ }
1951
+ } };
1952
+ function __embind_register_emval(rawType, name) {
1953
+ name = readLatin1String(name);
1954
+ registerType(rawType, { name, "fromWireType": function(handle) {
1955
+ var rv = Emval.toValue(handle);
1956
+ __emval_decref(handle);
1957
+ return rv;
1958
+ }, "toWireType": function(destructors, value) {
1959
+ return Emval.toHandle(value);
1960
+ }, "argPackAdvance": 8, "readValueFromPointer": simpleReadValueFromPointer, destructorFunction: null });
1961
+ }
1962
+ function enumReadValueFromPointer(name, shift, signed) {
1963
+ switch (shift) {
1964
+ case 0:
1965
+ return function(pointer) {
1966
+ var heap = signed ? HEAP8 : HEAPU8;
1967
+ return this["fromWireType"](heap[pointer]);
1968
+ };
1969
+ case 1:
1970
+ return function(pointer) {
1971
+ var heap = signed ? HEAP16 : HEAPU16;
1972
+ return this["fromWireType"](heap[pointer >> 1]);
1973
+ };
1974
+ case 2:
1975
+ return function(pointer) {
1976
+ var heap = signed ? HEAP32 : HEAPU32;
1977
+ return this["fromWireType"](heap[pointer >> 2]);
1978
+ };
1979
+ default:
1980
+ throw new TypeError("Unknown integer type: " + name);
1981
+ }
1982
+ }
1983
+ function __embind_register_enum(rawType, name, size, isSigned) {
1984
+ var shift = getShiftFromSize(size);
1985
+ name = readLatin1String(name);
1986
+ function ctor() {
1987
+ }
1988
+ ctor.values = {};
1989
+ registerType(rawType, { name, constructor: ctor, "fromWireType": function(c) {
1990
+ return this.constructor.values[c];
1991
+ }, "toWireType": function(destructors, c) {
1992
+ return c.value;
1993
+ }, "argPackAdvance": 8, "readValueFromPointer": enumReadValueFromPointer(name, shift, isSigned), destructorFunction: null });
1994
+ exposePublicSymbol(name, ctor);
1995
+ }
1996
+ function requireRegisteredType(rawType, humanName) {
1997
+ var impl = registeredTypes[rawType];
1998
+ if (void 0 === impl) {
1999
+ throwBindingError(humanName + " has unknown type " + getTypeName(rawType));
2000
+ }
2001
+ return impl;
2002
+ }
2003
+ function __embind_register_enum_value(rawEnumType, name, enumValue) {
2004
+ var enumType = requireRegisteredType(rawEnumType, "enum");
2005
+ name = readLatin1String(name);
2006
+ var Enum = enumType.constructor;
2007
+ var Value = Object.create(enumType.constructor.prototype, { value: { value: enumValue }, constructor: { value: createNamedFunction(enumType.name + "_" + name, function() {
2008
+ }) } });
2009
+ Enum.values[enumValue] = Value;
2010
+ Enum[name] = Value;
2011
+ }
2012
+ function embindRepr(v) {
2013
+ if (v === null) {
2014
+ return "null";
2015
+ }
2016
+ var t = typeof v;
2017
+ if (t === "object" || t === "array" || t === "function") {
2018
+ return v.toString();
2019
+ } else {
2020
+ return "" + v;
2021
+ }
2022
+ }
2023
+ function floatReadValueFromPointer(name, shift) {
2024
+ switch (shift) {
2025
+ case 2:
2026
+ return function(pointer) {
2027
+ return this["fromWireType"](HEAPF32[pointer >> 2]);
2028
+ };
2029
+ case 3:
2030
+ return function(pointer) {
2031
+ return this["fromWireType"](HEAPF64[pointer >> 3]);
2032
+ };
2033
+ default:
2034
+ throw new TypeError("Unknown float type: " + name);
2035
+ }
2036
+ }
2037
+ function __embind_register_float(rawType, name, size) {
2038
+ var shift = getShiftFromSize(size);
2039
+ name = readLatin1String(name);
2040
+ registerType(rawType, { name, "fromWireType": function(value) {
2041
+ return value;
2042
+ }, "toWireType": function(destructors, value) {
2043
+ return value;
2044
+ }, "argPackAdvance": 8, "readValueFromPointer": floatReadValueFromPointer(name, shift), destructorFunction: null });
2045
+ }
2046
+ function integerReadValueFromPointer(name, shift, signed) {
2047
+ switch (shift) {
2048
+ case 0:
2049
+ return signed ? function readS8FromPointer(pointer) {
2050
+ return HEAP8[pointer];
2051
+ } : function readU8FromPointer(pointer) {
2052
+ return HEAPU8[pointer];
2053
+ };
2054
+ case 1:
2055
+ return signed ? function readS16FromPointer(pointer) {
2056
+ return HEAP16[pointer >> 1];
2057
+ } : function readU16FromPointer(pointer) {
2058
+ return HEAPU16[pointer >> 1];
2059
+ };
2060
+ case 2:
2061
+ return signed ? function readS32FromPointer(pointer) {
2062
+ return HEAP32[pointer >> 2];
2063
+ } : function readU32FromPointer(pointer) {
2064
+ return HEAPU32[pointer >> 2];
2065
+ };
2066
+ default:
2067
+ throw new TypeError("Unknown integer type: " + name);
2068
+ }
2069
+ }
2070
+ function __embind_register_integer(primitiveType, name, size, minRange, maxRange) {
2071
+ name = readLatin1String(name);
2072
+ var shift = getShiftFromSize(size);
2073
+ var fromWireType = (value) => value;
2074
+ if (minRange === 0) {
2075
+ var bitshift = 32 - 8 * size;
2076
+ fromWireType = (value) => value << bitshift >>> bitshift;
2077
+ }
2078
+ var isUnsignedType = name.includes("unsigned");
2079
+ var checkAssertions = (value, toTypeName) => {
2080
+ };
2081
+ var toWireType;
2082
+ if (isUnsignedType) {
2083
+ toWireType = function(destructors, value) {
2084
+ checkAssertions(value, this.name);
2085
+ return value >>> 0;
2086
+ };
2087
+ } else {
2088
+ toWireType = function(destructors, value) {
2089
+ checkAssertions(value, this.name);
2090
+ return value;
2091
+ };
2092
+ }
2093
+ registerType(primitiveType, { name, "fromWireType": fromWireType, "toWireType": toWireType, "argPackAdvance": 8, "readValueFromPointer": integerReadValueFromPointer(name, shift, minRange !== 0), destructorFunction: null });
2094
+ }
2095
+ function __embind_register_memory_view(rawType, dataTypeIndex, name) {
2096
+ var typeMapping = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array];
2097
+ var TA = typeMapping[dataTypeIndex];
2098
+ function decodeMemoryView(handle) {
2099
+ handle = handle >> 2;
2100
+ var heap = HEAPU32;
2101
+ var size = heap[handle];
2102
+ var data = heap[handle + 1];
2103
+ return new TA(heap.buffer, data, size);
2104
+ }
2105
+ name = readLatin1String(name);
2106
+ registerType(rawType, { name, "fromWireType": decodeMemoryView, "argPackAdvance": 8, "readValueFromPointer": decodeMemoryView }, { ignoreDuplicateRegistrations: true });
2107
+ }
2108
+ function __embind_register_std_string(rawType, name) {
2109
+ name = readLatin1String(name);
2110
+ var stdStringIsUTF8 = name === "std::string";
2111
+ registerType(rawType, { name, "fromWireType": function(value) {
2112
+ var length = HEAPU32[value >> 2];
2113
+ var payload = value + 4;
2114
+ var str;
2115
+ if (stdStringIsUTF8) {
2116
+ var decodeStartPtr = payload;
2117
+ for (var i = 0; i <= length; ++i) {
2118
+ var currentBytePtr = payload + i;
2119
+ if (i == length || HEAPU8[currentBytePtr] == 0) {
2120
+ var maxRead = currentBytePtr - decodeStartPtr;
2121
+ var stringSegment = UTF8ToString(decodeStartPtr, maxRead);
2122
+ if (str === void 0) {
2123
+ str = stringSegment;
2124
+ } else {
2125
+ str += String.fromCharCode(0);
2126
+ str += stringSegment;
2127
+ }
2128
+ decodeStartPtr = currentBytePtr + 1;
2129
+ }
2130
+ }
2131
+ } else {
2132
+ var a = new Array(length);
2133
+ for (var i = 0; i < length; ++i) {
2134
+ a[i] = String.fromCharCode(HEAPU8[payload + i]);
2135
+ }
2136
+ str = a.join("");
2137
+ }
2138
+ _free(value);
2139
+ return str;
2140
+ }, "toWireType": function(destructors, value) {
2141
+ if (value instanceof ArrayBuffer) {
2142
+ value = new Uint8Array(value);
2143
+ }
2144
+ var length;
2145
+ var valueIsOfTypeString = typeof value == "string";
2146
+ if (!(valueIsOfTypeString || value instanceof Uint8Array || value instanceof Uint8ClampedArray || value instanceof Int8Array)) {
2147
+ throwBindingError("Cannot pass non-string to std::string");
2148
+ }
2149
+ if (stdStringIsUTF8 && valueIsOfTypeString) {
2150
+ length = lengthBytesUTF8(value);
2151
+ } else {
2152
+ length = value.length;
2153
+ }
2154
+ var base = _malloc(4 + length + 1);
2155
+ var ptr = base + 4;
2156
+ HEAPU32[base >> 2] = length;
2157
+ if (stdStringIsUTF8 && valueIsOfTypeString) {
2158
+ stringToUTF8(value, ptr, length + 1);
2159
+ } else {
2160
+ if (valueIsOfTypeString) {
2161
+ for (var i = 0; i < length; ++i) {
2162
+ var charCode = value.charCodeAt(i);
2163
+ if (charCode > 255) {
2164
+ _free(ptr);
2165
+ throwBindingError("String has UTF-16 code units that do not fit in 8 bits");
2166
+ }
2167
+ HEAPU8[ptr + i] = charCode;
2168
+ }
2169
+ } else {
2170
+ for (var i = 0; i < length; ++i) {
2171
+ HEAPU8[ptr + i] = value[i];
2172
+ }
2173
+ }
2174
+ }
2175
+ if (destructors !== null) {
2176
+ destructors.push(_free, base);
2177
+ }
2178
+ return base;
2179
+ }, "argPackAdvance": 8, "readValueFromPointer": simpleReadValueFromPointer, destructorFunction: function(ptr) {
2180
+ _free(ptr);
2181
+ } });
2182
+ }
2183
+ var UTF16Decoder = typeof TextDecoder != "undefined" ? new TextDecoder("utf-16le") : void 0;
2184
+ function UTF16ToString(ptr, maxBytesToRead) {
2185
+ var endPtr = ptr;
2186
+ var idx = endPtr >> 1;
2187
+ var maxIdx = idx + maxBytesToRead / 2;
2188
+ while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx;
2189
+ endPtr = idx << 1;
2190
+ if (endPtr - ptr > 32 && UTF16Decoder) return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr));
2191
+ var str = "";
2192
+ for (var i = 0; !(i >= maxBytesToRead / 2); ++i) {
2193
+ var codeUnit = HEAP16[ptr + i * 2 >> 1];
2194
+ if (codeUnit == 0) break;
2195
+ str += String.fromCharCode(codeUnit);
2196
+ }
2197
+ return str;
2198
+ }
2199
+ function stringToUTF16(str, outPtr, maxBytesToWrite) {
2200
+ if (maxBytesToWrite === void 0) {
2201
+ maxBytesToWrite = 2147483647;
2202
+ }
2203
+ if (maxBytesToWrite < 2) return 0;
2204
+ maxBytesToWrite -= 2;
2205
+ var startPtr = outPtr;
2206
+ var numCharsToWrite = maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length;
2207
+ for (var i = 0; i < numCharsToWrite; ++i) {
2208
+ var codeUnit = str.charCodeAt(i);
2209
+ HEAP16[outPtr >> 1] = codeUnit;
2210
+ outPtr += 2;
2211
+ }
2212
+ HEAP16[outPtr >> 1] = 0;
2213
+ return outPtr - startPtr;
2214
+ }
2215
+ function lengthBytesUTF16(str) {
2216
+ return str.length * 2;
2217
+ }
2218
+ function UTF32ToString(ptr, maxBytesToRead) {
2219
+ var i = 0;
2220
+ var str = "";
2221
+ while (!(i >= maxBytesToRead / 4)) {
2222
+ var utf32 = HEAP32[ptr + i * 4 >> 2];
2223
+ if (utf32 == 0) break;
2224
+ ++i;
2225
+ if (utf32 >= 65536) {
2226
+ var ch = utf32 - 65536;
2227
+ str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
2228
+ } else {
2229
+ str += String.fromCharCode(utf32);
2230
+ }
2231
+ }
2232
+ return str;
2233
+ }
2234
+ function stringToUTF32(str, outPtr, maxBytesToWrite) {
2235
+ if (maxBytesToWrite === void 0) {
2236
+ maxBytesToWrite = 2147483647;
2237
+ }
2238
+ if (maxBytesToWrite < 4) return 0;
2239
+ var startPtr = outPtr;
2240
+ var endPtr = startPtr + maxBytesToWrite - 4;
2241
+ for (var i = 0; i < str.length; ++i) {
2242
+ var codeUnit = str.charCodeAt(i);
2243
+ if (codeUnit >= 55296 && codeUnit <= 57343) {
2244
+ var trailSurrogate = str.charCodeAt(++i);
2245
+ codeUnit = 65536 + ((codeUnit & 1023) << 10) | trailSurrogate & 1023;
2246
+ }
2247
+ HEAP32[outPtr >> 2] = codeUnit;
2248
+ outPtr += 4;
2249
+ if (outPtr + 4 > endPtr) break;
2250
+ }
2251
+ HEAP32[outPtr >> 2] = 0;
2252
+ return outPtr - startPtr;
2253
+ }
2254
+ function lengthBytesUTF32(str) {
2255
+ var len = 0;
2256
+ for (var i = 0; i < str.length; ++i) {
2257
+ var codeUnit = str.charCodeAt(i);
2258
+ if (codeUnit >= 55296 && codeUnit <= 57343) ++i;
2259
+ len += 4;
2260
+ }
2261
+ return len;
2262
+ }
2263
+ function __embind_register_std_wstring(rawType, charSize, name) {
2264
+ name = readLatin1String(name);
2265
+ var decodeString, encodeString, getHeap, lengthBytesUTF, shift;
2266
+ if (charSize === 2) {
2267
+ decodeString = UTF16ToString;
2268
+ encodeString = stringToUTF16;
2269
+ lengthBytesUTF = lengthBytesUTF16;
2270
+ getHeap = () => HEAPU16;
2271
+ shift = 1;
2272
+ } else if (charSize === 4) {
2273
+ decodeString = UTF32ToString;
2274
+ encodeString = stringToUTF32;
2275
+ lengthBytesUTF = lengthBytesUTF32;
2276
+ getHeap = () => HEAPU32;
2277
+ shift = 2;
2278
+ }
2279
+ registerType(rawType, { name, "fromWireType": function(value) {
2280
+ var length = HEAPU32[value >> 2];
2281
+ var HEAP = getHeap();
2282
+ var str;
2283
+ var decodeStartPtr = value + 4;
2284
+ for (var i = 0; i <= length; ++i) {
2285
+ var currentBytePtr = value + 4 + i * charSize;
2286
+ if (i == length || HEAP[currentBytePtr >> shift] == 0) {
2287
+ var maxReadBytes = currentBytePtr - decodeStartPtr;
2288
+ var stringSegment = decodeString(decodeStartPtr, maxReadBytes);
2289
+ if (str === void 0) {
2290
+ str = stringSegment;
2291
+ } else {
2292
+ str += String.fromCharCode(0);
2293
+ str += stringSegment;
2294
+ }
2295
+ decodeStartPtr = currentBytePtr + charSize;
2296
+ }
2297
+ }
2298
+ _free(value);
2299
+ return str;
2300
+ }, "toWireType": function(destructors, value) {
2301
+ if (!(typeof value == "string")) {
2302
+ throwBindingError("Cannot pass non-string to C++ string type " + name);
2303
+ }
2304
+ var length = lengthBytesUTF(value);
2305
+ var ptr = _malloc(4 + length + charSize);
2306
+ HEAPU32[ptr >> 2] = length >> shift;
2307
+ encodeString(value, ptr + 4, length + charSize);
2308
+ if (destructors !== null) {
2309
+ destructors.push(_free, ptr);
2310
+ }
2311
+ return ptr;
2312
+ }, "argPackAdvance": 8, "readValueFromPointer": simpleReadValueFromPointer, destructorFunction: function(ptr) {
2313
+ _free(ptr);
2314
+ } });
2315
+ }
2316
+ function __embind_register_value_object(rawType, name, constructorSignature, rawConstructor, destructorSignature, rawDestructor) {
2317
+ structRegistrations[rawType] = { name: readLatin1String(name), rawConstructor: embind__requireFunction(constructorSignature, rawConstructor), rawDestructor: embind__requireFunction(destructorSignature, rawDestructor), fields: [] };
2318
+ }
2319
+ function __embind_register_value_object_field(structType, fieldName, getterReturnType, getterSignature, getter, getterContext, setterArgumentType, setterSignature, setter, setterContext) {
2320
+ structRegistrations[structType].fields.push({ fieldName: readLatin1String(fieldName), getterReturnType, getter: embind__requireFunction(getterSignature, getter), getterContext, setterArgumentType, setter: embind__requireFunction(setterSignature, setter), setterContext });
2321
+ }
2322
+ function __embind_register_void(rawType, name) {
2323
+ name = readLatin1String(name);
2324
+ registerType(rawType, { isVoid: true, name, "argPackAdvance": 0, "fromWireType": function() {
2325
+ return void 0;
2326
+ }, "toWireType": function(destructors, o) {
2327
+ return void 0;
2328
+ } });
2329
+ }
2330
+ var nowIsMonotonic = true;
2331
+ function __emscripten_get_now_is_monotonic() {
2332
+ return nowIsMonotonic;
2333
+ }
2334
+ function emval_lookupTypes(argCount, argTypes) {
2335
+ var a = new Array(argCount);
2336
+ for (var i = 0; i < argCount; ++i) {
2337
+ a[i] = requireRegisteredType(HEAPU32[argTypes + i * 4 >> 2], "parameter " + i);
2338
+ }
2339
+ return a;
2340
+ }
2341
+ function __emval_call(handle, argCount, argTypes, argv) {
2342
+ handle = Emval.toValue(handle);
2343
+ var types = emval_lookupTypes(argCount, argTypes);
2344
+ var args = new Array(argCount);
2345
+ for (var i = 0; i < argCount; ++i) {
2346
+ var type = types[i];
2347
+ args[i] = type["readValueFromPointer"](argv);
2348
+ argv += type["argPackAdvance"];
2349
+ }
2350
+ var rv = handle.apply(void 0, args);
2351
+ return Emval.toHandle(rv);
2352
+ }
2353
+ function __emval_incref(handle) {
2354
+ if (handle > 4) {
2355
+ emval_handle_array[handle].refcount += 1;
2356
+ }
2357
+ }
2358
+ function __emval_take_value(type, arg) {
2359
+ type = requireRegisteredType(type, "_emval_take_value");
2360
+ var v = type["readValueFromPointer"](arg);
2361
+ return Emval.toHandle(v);
2362
+ }
2363
+ function readI53FromI64(ptr) {
2364
+ return HEAPU32[ptr >> 2] + HEAP32[ptr + 4 >> 2] * 4294967296;
2365
+ }
2366
+ function __gmtime_js(time, tmPtr) {
2367
+ var date = new Date(readI53FromI64(time) * 1e3);
2368
+ HEAP32[tmPtr >> 2] = date.getUTCSeconds();
2369
+ HEAP32[tmPtr + 4 >> 2] = date.getUTCMinutes();
2370
+ HEAP32[tmPtr + 8 >> 2] = date.getUTCHours();
2371
+ HEAP32[tmPtr + 12 >> 2] = date.getUTCDate();
2372
+ HEAP32[tmPtr + 16 >> 2] = date.getUTCMonth();
2373
+ HEAP32[tmPtr + 20 >> 2] = date.getUTCFullYear() - 1900;
2374
+ HEAP32[tmPtr + 24 >> 2] = date.getUTCDay();
2375
+ var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);
2376
+ var yday = (date.getTime() - start) / (1e3 * 60 * 60 * 24) | 0;
2377
+ HEAP32[tmPtr + 28 >> 2] = yday;
2378
+ }
2379
+ function __isLeapYear(year) {
2380
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
2381
+ }
2382
+ var __MONTH_DAYS_LEAP_CUMULATIVE = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];
2383
+ var __MONTH_DAYS_REGULAR_CUMULATIVE = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
2384
+ function __yday_from_date(date) {
2385
+ var isLeapYear = __isLeapYear(date.getFullYear());
2386
+ var monthDaysCumulative = isLeapYear ? __MONTH_DAYS_LEAP_CUMULATIVE : __MONTH_DAYS_REGULAR_CUMULATIVE;
2387
+ var yday = monthDaysCumulative[date.getMonth()] + date.getDate() - 1;
2388
+ return yday;
2389
+ }
2390
+ function __localtime_js(time, tmPtr) {
2391
+ var date = new Date(readI53FromI64(time) * 1e3);
2392
+ HEAP32[tmPtr >> 2] = date.getSeconds();
2393
+ HEAP32[tmPtr + 4 >> 2] = date.getMinutes();
2394
+ HEAP32[tmPtr + 8 >> 2] = date.getHours();
2395
+ HEAP32[tmPtr + 12 >> 2] = date.getDate();
2396
+ HEAP32[tmPtr + 16 >> 2] = date.getMonth();
2397
+ HEAP32[tmPtr + 20 >> 2] = date.getFullYear() - 1900;
2398
+ HEAP32[tmPtr + 24 >> 2] = date.getDay();
2399
+ var yday = __yday_from_date(date) | 0;
2400
+ HEAP32[tmPtr + 28 >> 2] = yday;
2401
+ HEAP32[tmPtr + 36 >> 2] = -(date.getTimezoneOffset() * 60);
2402
+ var start = new Date(date.getFullYear(), 0, 1);
2403
+ var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();
2404
+ var winterOffset = start.getTimezoneOffset();
2405
+ var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset)) | 0;
2406
+ HEAP32[tmPtr + 32 >> 2] = dst;
2407
+ }
2408
+ function __mktime_js(tmPtr) {
2409
+ var date = new Date(HEAP32[tmPtr + 20 >> 2] + 1900, HEAP32[tmPtr + 16 >> 2], HEAP32[tmPtr + 12 >> 2], HEAP32[tmPtr + 8 >> 2], HEAP32[tmPtr + 4 >> 2], HEAP32[tmPtr >> 2], 0);
2410
+ var dst = HEAP32[tmPtr + 32 >> 2];
2411
+ var guessedOffset = date.getTimezoneOffset();
2412
+ var start = new Date(date.getFullYear(), 0, 1);
2413
+ var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();
2414
+ var winterOffset = start.getTimezoneOffset();
2415
+ var dstOffset = Math.min(winterOffset, summerOffset);
2416
+ if (dst < 0) {
2417
+ HEAP32[tmPtr + 32 >> 2] = Number(summerOffset != winterOffset && dstOffset == guessedOffset);
2418
+ } else if (dst > 0 != (dstOffset == guessedOffset)) {
2419
+ var nonDstOffset = Math.max(winterOffset, summerOffset);
2420
+ var trueOffset = dst > 0 ? dstOffset : nonDstOffset;
2421
+ date.setTime(date.getTime() + (trueOffset - guessedOffset) * 6e4);
2422
+ }
2423
+ HEAP32[tmPtr + 24 >> 2] = date.getDay();
2424
+ var yday = __yday_from_date(date) | 0;
2425
+ HEAP32[tmPtr + 28 >> 2] = yday;
2426
+ HEAP32[tmPtr >> 2] = date.getSeconds();
2427
+ HEAP32[tmPtr + 4 >> 2] = date.getMinutes();
2428
+ HEAP32[tmPtr + 8 >> 2] = date.getHours();
2429
+ HEAP32[tmPtr + 12 >> 2] = date.getDate();
2430
+ HEAP32[tmPtr + 16 >> 2] = date.getMonth();
2431
+ HEAP32[tmPtr + 20 >> 2] = date.getYear();
2432
+ return date.getTime() / 1e3 | 0;
2433
+ }
2434
+ function allocateUTF8(str) {
2435
+ var size = lengthBytesUTF8(str) + 1;
2436
+ var ret = _malloc(size);
2437
+ if (ret) stringToUTF8Array(str, HEAP8, ret, size);
2438
+ return ret;
2439
+ }
2440
+ function __tzset_js(timezone, daylight, tzname) {
2441
+ var currentYear = (/* @__PURE__ */ new Date()).getFullYear();
2442
+ var winter = new Date(currentYear, 0, 1);
2443
+ var summer = new Date(currentYear, 6, 1);
2444
+ var winterOffset = winter.getTimezoneOffset();
2445
+ var summerOffset = summer.getTimezoneOffset();
2446
+ var stdTimezoneOffset = Math.max(winterOffset, summerOffset);
2447
+ HEAPU32[timezone >> 2] = stdTimezoneOffset * 60;
2448
+ HEAP32[daylight >> 2] = Number(winterOffset != summerOffset);
2449
+ function extractZone(date) {
2450
+ var match = date.toTimeString().match(/\(([A-Za-z ]+)\)$/);
2451
+ return match ? match[1] : "GMT";
2452
+ }
2453
+ var winterName = extractZone(winter);
2454
+ var summerName = extractZone(summer);
2455
+ var winterNamePtr = allocateUTF8(winterName);
2456
+ var summerNamePtr = allocateUTF8(summerName);
2457
+ if (summerOffset < winterOffset) {
2458
+ HEAPU32[tzname >> 2] = winterNamePtr;
2459
+ HEAPU32[tzname + 4 >> 2] = summerNamePtr;
2460
+ } else {
2461
+ HEAPU32[tzname >> 2] = summerNamePtr;
2462
+ HEAPU32[tzname + 4 >> 2] = winterNamePtr;
2463
+ }
2464
+ }
2465
+ function _abort() {
2466
+ abort("");
2467
+ }
2468
+ function _emscripten_date_now() {
2469
+ return Date.now();
2470
+ }
2471
+ var _emscripten_get_now;
2472
+ _emscripten_get_now = () => performance.now();
2473
+ function _emscripten_memcpy_big(dest, src, num) {
2474
+ HEAPU8.copyWithin(dest, src, src + num);
2475
+ }
2476
+ function getHeapMax() {
2477
+ return 1073741824;
2478
+ }
2479
+ function emscripten_realloc_buffer(size) {
2480
+ var b = wasmMemory.buffer;
2481
+ try {
2482
+ wasmMemory.grow(size - b.byteLength + 65535 >>> 16);
2483
+ updateMemoryViews();
2484
+ return 1;
2485
+ } catch (e) {
2486
+ }
2487
+ }
2488
+ function _emscripten_resize_heap(requestedSize) {
2489
+ var oldSize = HEAPU8.length;
2490
+ requestedSize = requestedSize >>> 0;
2491
+ var maxHeapSize = getHeapMax();
2492
+ if (requestedSize > maxHeapSize) {
2493
+ return false;
2494
+ }
2495
+ let alignUp = (x, multiple) => x + (multiple - x % multiple) % multiple;
2496
+ for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
2497
+ var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
2498
+ overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);
2499
+ var newSize = Math.min(maxHeapSize, alignUp(Math.max(requestedSize, overGrownHeapSize), 65536));
2500
+ var replacement = emscripten_realloc_buffer(newSize);
2501
+ if (replacement) {
2502
+ return true;
2503
+ }
2504
+ }
2505
+ return false;
2506
+ }
2507
+ var ENV = {};
2508
+ function getExecutableName() {
2509
+ return thisProgram || "./this.program";
2510
+ }
2511
+ function getEnvStrings() {
2512
+ if (!getEnvStrings.strings) {
2513
+ var lang = (typeof navigator == "object" && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8";
2514
+ var env = { "USER": "web_user", "LOGNAME": "web_user", "PATH": "/", "PWD": "/", "HOME": "/home/web_user", "LANG": lang, "_": getExecutableName() };
2515
+ for (var x in ENV) {
2516
+ if (ENV[x] === void 0) delete env[x];
2517
+ else env[x] = ENV[x];
2518
+ }
2519
+ var strings = [];
2520
+ for (var x in env) {
2521
+ strings.push(x + "=" + env[x]);
2522
+ }
2523
+ getEnvStrings.strings = strings;
2524
+ }
2525
+ return getEnvStrings.strings;
2526
+ }
2527
+ function writeAsciiToMemory(str, buffer, dontAddNull) {
2528
+ for (var i = 0; i < str.length; ++i) {
2529
+ HEAP8[buffer++ >> 0] = str.charCodeAt(i);
2530
+ }
2531
+ if (!dontAddNull) HEAP8[buffer >> 0] = 0;
2532
+ }
2533
+ function _environ_get(__environ, environ_buf) {
2534
+ var bufSize = 0;
2535
+ getEnvStrings().forEach(function(string, i) {
2536
+ var ptr = environ_buf + bufSize;
2537
+ HEAPU32[__environ + i * 4 >> 2] = ptr;
2538
+ writeAsciiToMemory(string, ptr);
2539
+ bufSize += string.length + 1;
2540
+ });
2541
+ return 0;
2542
+ }
2543
+ function _environ_sizes_get(penviron_count, penviron_buf_size) {
2544
+ var strings = getEnvStrings();
2545
+ HEAPU32[penviron_count >> 2] = strings.length;
2546
+ var bufSize = 0;
2547
+ strings.forEach(function(string) {
2548
+ bufSize += string.length + 1;
2549
+ });
2550
+ HEAPU32[penviron_buf_size >> 2] = bufSize;
2551
+ return 0;
2552
+ }
2553
+ function _fd_close(fd) {
2554
+ return 52;
2555
+ }
2556
+ function _fd_read(fd, iov, iovcnt, pnum) {
2557
+ return 52;
2558
+ }
2559
+ function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {
2560
+ return 70;
2561
+ }
2562
+ var printCharBuffers = [null, [], []];
2563
+ function printChar(stream, curr) {
2564
+ var buffer = printCharBuffers[stream];
2565
+ if (curr === 0 || curr === 10) {
2566
+ (stream === 1 ? out : err)(UTF8ArrayToString(buffer, 0));
2567
+ buffer.length = 0;
2568
+ } else {
2569
+ buffer.push(curr);
2570
+ }
2571
+ }
2572
+ function _fd_write(fd, iov, iovcnt, pnum) {
2573
+ var num = 0;
2574
+ for (var i = 0; i < iovcnt; i++) {
2575
+ var ptr = HEAPU32[iov >> 2];
2576
+ var len = HEAPU32[iov + 4 >> 2];
2577
+ iov += 8;
2578
+ for (var j = 0; j < len; j++) {
2579
+ printChar(fd, HEAPU8[ptr + j]);
2580
+ }
2581
+ num += len;
2582
+ }
2583
+ HEAPU32[pnum >> 2] = num;
2584
+ return 0;
2585
+ }
2586
+ function __arraySum(array, index) {
2587
+ var sum = 0;
2588
+ for (var i = 0; i <= index; sum += array[i++]) {
2589
+ }
2590
+ return sum;
2591
+ }
2592
+ var __MONTH_DAYS_LEAP = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
2593
+ var __MONTH_DAYS_REGULAR = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
2594
+ function __addDays(date, days) {
2595
+ var newDate = new Date(date.getTime());
2596
+ while (days > 0) {
2597
+ var leap = __isLeapYear(newDate.getFullYear());
2598
+ var currentMonth = newDate.getMonth();
2599
+ var daysInCurrentMonth = (leap ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR)[currentMonth];
2600
+ if (days > daysInCurrentMonth - newDate.getDate()) {
2601
+ days -= daysInCurrentMonth - newDate.getDate() + 1;
2602
+ newDate.setDate(1);
2603
+ if (currentMonth < 11) {
2604
+ newDate.setMonth(currentMonth + 1);
2605
+ } else {
2606
+ newDate.setMonth(0);
2607
+ newDate.setFullYear(newDate.getFullYear() + 1);
2608
+ }
2609
+ } else {
2610
+ newDate.setDate(newDate.getDate() + days);
2611
+ return newDate;
2612
+ }
2613
+ }
2614
+ return newDate;
2615
+ }
2616
+ function intArrayFromString(stringy, dontAddNull, length) {
2617
+ var len = length > 0 ? length : lengthBytesUTF8(stringy) + 1;
2618
+ var u8array = new Array(len);
2619
+ var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
2620
+ if (dontAddNull) u8array.length = numBytesWritten;
2621
+ return u8array;
2622
+ }
2623
+ function writeArrayToMemory(array, buffer) {
2624
+ HEAP8.set(array, buffer);
2625
+ }
2626
+ function _strftime(s, maxsize, format, tm) {
2627
+ var tm_zone = HEAP32[tm + 40 >> 2];
2628
+ var date = { tm_sec: HEAP32[tm >> 2], tm_min: HEAP32[tm + 4 >> 2], tm_hour: HEAP32[tm + 8 >> 2], tm_mday: HEAP32[tm + 12 >> 2], tm_mon: HEAP32[tm + 16 >> 2], tm_year: HEAP32[tm + 20 >> 2], tm_wday: HEAP32[tm + 24 >> 2], tm_yday: HEAP32[tm + 28 >> 2], tm_isdst: HEAP32[tm + 32 >> 2], tm_gmtoff: HEAP32[tm + 36 >> 2], tm_zone: tm_zone ? UTF8ToString(tm_zone) : "" };
2629
+ var pattern = UTF8ToString(format);
2630
+ var EXPANSION_RULES_1 = { "%c": "%a %b %d %H:%M:%S %Y", "%D": "%m/%d/%y", "%F": "%Y-%m-%d", "%h": "%b", "%r": "%I:%M:%S %p", "%R": "%H:%M", "%T": "%H:%M:%S", "%x": "%m/%d/%y", "%X": "%H:%M:%S", "%Ec": "%c", "%EC": "%C", "%Ex": "%m/%d/%y", "%EX": "%H:%M:%S", "%Ey": "%y", "%EY": "%Y", "%Od": "%d", "%Oe": "%e", "%OH": "%H", "%OI": "%I", "%Om": "%m", "%OM": "%M", "%OS": "%S", "%Ou": "%u", "%OU": "%U", "%OV": "%V", "%Ow": "%w", "%OW": "%W", "%Oy": "%y" };
2631
+ for (var rule in EXPANSION_RULES_1) {
2632
+ pattern = pattern.replace(new RegExp(rule, "g"), EXPANSION_RULES_1[rule]);
2633
+ }
2634
+ var WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
2635
+ var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
2636
+ function leadingSomething(value, digits, character) {
2637
+ var str = typeof value == "number" ? value.toString() : value || "";
2638
+ while (str.length < digits) {
2639
+ str = character[0] + str;
2640
+ }
2641
+ return str;
2642
+ }
2643
+ function leadingNulls(value, digits) {
2644
+ return leadingSomething(value, digits, "0");
2645
+ }
2646
+ function compareByDay(date1, date2) {
2647
+ function sgn(value) {
2648
+ return value < 0 ? -1 : value > 0 ? 1 : 0;
2649
+ }
2650
+ var compare;
2651
+ if ((compare = sgn(date1.getFullYear() - date2.getFullYear())) === 0) {
2652
+ if ((compare = sgn(date1.getMonth() - date2.getMonth())) === 0) {
2653
+ compare = sgn(date1.getDate() - date2.getDate());
2654
+ }
2655
+ }
2656
+ return compare;
2657
+ }
2658
+ function getFirstWeekStartDate(janFourth) {
2659
+ switch (janFourth.getDay()) {
2660
+ case 0:
2661
+ return new Date(janFourth.getFullYear() - 1, 11, 29);
2662
+ case 1:
2663
+ return janFourth;
2664
+ case 2:
2665
+ return new Date(janFourth.getFullYear(), 0, 3);
2666
+ case 3:
2667
+ return new Date(janFourth.getFullYear(), 0, 2);
2668
+ case 4:
2669
+ return new Date(janFourth.getFullYear(), 0, 1);
2670
+ case 5:
2671
+ return new Date(janFourth.getFullYear() - 1, 11, 31);
2672
+ case 6:
2673
+ return new Date(janFourth.getFullYear() - 1, 11, 30);
2674
+ }
2675
+ }
2676
+ function getWeekBasedYear(date2) {
2677
+ var thisDate = __addDays(new Date(date2.tm_year + 1900, 0, 1), date2.tm_yday);
2678
+ var janFourthThisYear = new Date(thisDate.getFullYear(), 0, 4);
2679
+ var janFourthNextYear = new Date(thisDate.getFullYear() + 1, 0, 4);
2680
+ var firstWeekStartThisYear = getFirstWeekStartDate(janFourthThisYear);
2681
+ var firstWeekStartNextYear = getFirstWeekStartDate(janFourthNextYear);
2682
+ if (compareByDay(firstWeekStartThisYear, thisDate) <= 0) {
2683
+ if (compareByDay(firstWeekStartNextYear, thisDate) <= 0) {
2684
+ return thisDate.getFullYear() + 1;
2685
+ }
2686
+ return thisDate.getFullYear();
2687
+ }
2688
+ return thisDate.getFullYear() - 1;
2689
+ }
2690
+ var EXPANSION_RULES_2 = { "%a": function(date2) {
2691
+ return WEEKDAYS[date2.tm_wday].substring(0, 3);
2692
+ }, "%A": function(date2) {
2693
+ return WEEKDAYS[date2.tm_wday];
2694
+ }, "%b": function(date2) {
2695
+ return MONTHS[date2.tm_mon].substring(0, 3);
2696
+ }, "%B": function(date2) {
2697
+ return MONTHS[date2.tm_mon];
2698
+ }, "%C": function(date2) {
2699
+ var year = date2.tm_year + 1900;
2700
+ return leadingNulls(year / 100 | 0, 2);
2701
+ }, "%d": function(date2) {
2702
+ return leadingNulls(date2.tm_mday, 2);
2703
+ }, "%e": function(date2) {
2704
+ return leadingSomething(date2.tm_mday, 2, " ");
2705
+ }, "%g": function(date2) {
2706
+ return getWeekBasedYear(date2).toString().substring(2);
2707
+ }, "%G": function(date2) {
2708
+ return getWeekBasedYear(date2);
2709
+ }, "%H": function(date2) {
2710
+ return leadingNulls(date2.tm_hour, 2);
2711
+ }, "%I": function(date2) {
2712
+ var twelveHour = date2.tm_hour;
2713
+ if (twelveHour == 0) twelveHour = 12;
2714
+ else if (twelveHour > 12) twelveHour -= 12;
2715
+ return leadingNulls(twelveHour, 2);
2716
+ }, "%j": function(date2) {
2717
+ return leadingNulls(date2.tm_mday + __arraySum(__isLeapYear(date2.tm_year + 1900) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, date2.tm_mon - 1), 3);
2718
+ }, "%m": function(date2) {
2719
+ return leadingNulls(date2.tm_mon + 1, 2);
2720
+ }, "%M": function(date2) {
2721
+ return leadingNulls(date2.tm_min, 2);
2722
+ }, "%n": function() {
2723
+ return "\n";
2724
+ }, "%p": function(date2) {
2725
+ if (date2.tm_hour >= 0 && date2.tm_hour < 12) {
2726
+ return "AM";
2727
+ }
2728
+ return "PM";
2729
+ }, "%S": function(date2) {
2730
+ return leadingNulls(date2.tm_sec, 2);
2731
+ }, "%t": function() {
2732
+ return " ";
2733
+ }, "%u": function(date2) {
2734
+ return date2.tm_wday || 7;
2735
+ }, "%U": function(date2) {
2736
+ var days = date2.tm_yday + 7 - date2.tm_wday;
2737
+ return leadingNulls(Math.floor(days / 7), 2);
2738
+ }, "%V": function(date2) {
2739
+ var val = Math.floor((date2.tm_yday + 7 - (date2.tm_wday + 6) % 7) / 7);
2740
+ if ((date2.tm_wday + 371 - date2.tm_yday - 2) % 7 <= 2) {
2741
+ val++;
2742
+ }
2743
+ if (!val) {
2744
+ val = 52;
2745
+ var dec31 = (date2.tm_wday + 7 - date2.tm_yday - 1) % 7;
2746
+ if (dec31 == 4 || dec31 == 5 && __isLeapYear(date2.tm_year % 400 - 1)) {
2747
+ val++;
2748
+ }
2749
+ } else if (val == 53) {
2750
+ var jan1 = (date2.tm_wday + 371 - date2.tm_yday) % 7;
2751
+ if (jan1 != 4 && (jan1 != 3 || !__isLeapYear(date2.tm_year))) val = 1;
2752
+ }
2753
+ return leadingNulls(val, 2);
2754
+ }, "%w": function(date2) {
2755
+ return date2.tm_wday;
2756
+ }, "%W": function(date2) {
2757
+ var days = date2.tm_yday + 7 - (date2.tm_wday + 6) % 7;
2758
+ return leadingNulls(Math.floor(days / 7), 2);
2759
+ }, "%y": function(date2) {
2760
+ return (date2.tm_year + 1900).toString().substring(2);
2761
+ }, "%Y": function(date2) {
2762
+ return date2.tm_year + 1900;
2763
+ }, "%z": function(date2) {
2764
+ var off = date2.tm_gmtoff;
2765
+ var ahead = off >= 0;
2766
+ off = Math.abs(off) / 60;
2767
+ off = off / 60 * 100 + off % 60;
2768
+ return (ahead ? "+" : "-") + String("0000" + off).slice(-4);
2769
+ }, "%Z": function(date2) {
2770
+ return date2.tm_zone;
2771
+ }, "%%": function() {
2772
+ return "%";
2773
+ } };
2774
+ pattern = pattern.replace(/%%/g, "\0\0");
2775
+ for (var rule in EXPANSION_RULES_2) {
2776
+ if (pattern.includes(rule)) {
2777
+ pattern = pattern.replace(new RegExp(rule, "g"), EXPANSION_RULES_2[rule](date));
2778
+ }
2779
+ }
2780
+ pattern = pattern.replace(/\0\0/g, "%");
2781
+ var bytes = intArrayFromString(pattern, false);
2782
+ if (bytes.length > maxsize) {
2783
+ return 0;
2784
+ }
2785
+ writeArrayToMemory(bytes, s);
2786
+ return bytes.length - 1;
2787
+ }
2788
+ function _strftime_l(s, maxsize, format, tm, loc) {
2789
+ return _strftime(s, maxsize, format, tm);
2790
+ }
2791
+ InternalError = Module2["InternalError"] = extendError(Error, "InternalError");
2792
+ embind_init_charCodes();
2793
+ BindingError = Module2["BindingError"] = extendError(Error, "BindingError");
2794
+ init_ClassHandle();
2795
+ init_embind();
2796
+ init_RegisteredPointer();
2797
+ UnboundTypeError = Module2["UnboundTypeError"] = extendError(Error, "UnboundTypeError");
2798
+ init_emval();
2799
+ var wasmImports = { "e": ___cxa_throw, "s": ___syscall_fcntl64, "F": ___syscall_getcwd, "H": ___syscall_ioctl, "t": ___syscall_openat, "B": ___syscall_rmdir, "C": ___syscall_unlinkat, "g": __embind_finalize_value_object, "y": __embind_register_bigint, "Q": __embind_register_bool, "k": __embind_register_class, "j": __embind_register_class_constructor, "a": __embind_register_class_function, "P": __embind_register_emval, "w": __embind_register_enum, "q": __embind_register_enum_value, "v": __embind_register_float, "d": __embind_register_integer, "b": __embind_register_memory_view, "u": __embind_register_std_string, "o": __embind_register_std_wstring, "i": __embind_register_value_object, "c": __embind_register_value_object_field, "R": __embind_register_void, "J": __emscripten_get_now_is_monotonic, "T": __emval_call, "f": __emval_decref, "p": __emval_incref, "m": __emval_take_value, "K": __gmtime_js, "L": __localtime_js, "M": __mktime_js, "N": __tzset_js, "h": _abort, "l": _emscripten_date_now, "I": _emscripten_get_now, "O": _emscripten_memcpy_big, "A": _emscripten_resize_heap, "D": _environ_get, "E": _environ_sizes_get, "n": _fd_close, "G": _fd_read, "x": _fd_seek, "r": _fd_write, "S": _strftime, "z": _strftime_l };
2800
+ createWasm();
2801
+ var _malloc = function() {
2802
+ return (_malloc = Module2["asm"]["W"]).apply(null, arguments);
2803
+ };
2804
+ var _free = function() {
2805
+ return (_free = Module2["asm"]["Y"]).apply(null, arguments);
2806
+ };
2807
+ var ___getTypeName = Module2["___getTypeName"] = function() {
2808
+ return (___getTypeName = Module2["___getTypeName"] = Module2["asm"]["Z"]).apply(null, arguments);
2809
+ };
2810
+ Module2["__embind_initialize_bindings"] = function() {
2811
+ return (Module2["__embind_initialize_bindings"] = Module2["asm"]["_"]).apply(null, arguments);
2812
+ };
2813
+ var ___cxa_is_pointer_type = function() {
2814
+ return (___cxa_is_pointer_type = Module2["asm"]["$"]).apply(null, arguments);
2815
+ };
2816
+ Module2["dynCall_jiji"] = function() {
2817
+ return (Module2["dynCall_jiji"] = Module2["asm"]["aa"]).apply(null, arguments);
2818
+ };
2819
+ Module2["dynCall_viijii"] = function() {
2820
+ return (Module2["dynCall_viijii"] = Module2["asm"]["ba"]).apply(null, arguments);
2821
+ };
2822
+ Module2["dynCall_iiiiij"] = function() {
2823
+ return (Module2["dynCall_iiiiij"] = Module2["asm"]["ca"]).apply(null, arguments);
2824
+ };
2825
+ Module2["dynCall_iiiiijj"] = function() {
2826
+ return (Module2["dynCall_iiiiijj"] = Module2["asm"]["da"]).apply(null, arguments);
2827
+ };
2828
+ Module2["dynCall_iiiiiijj"] = function() {
2829
+ return (Module2["dynCall_iiiiiijj"] = Module2["asm"]["ea"]).apply(null, arguments);
2830
+ };
2831
+ Module2["dynCall_jijii"] = function() {
2832
+ return (Module2["dynCall_jijii"] = Module2["asm"]["fa"]).apply(null, arguments);
2833
+ };
2834
+ Module2["dynCall_vijii"] = function() {
2835
+ return (Module2["dynCall_vijii"] = Module2["asm"]["ga"]).apply(null, arguments);
2836
+ };
2837
+ Module2["dynCall_jij"] = function() {
2838
+ return (Module2["dynCall_jij"] = Module2["asm"]["ha"]).apply(null, arguments);
2839
+ };
2840
+ Module2["dynCall_iij"] = function() {
2841
+ return (Module2["dynCall_iij"] = Module2["asm"]["ia"]).apply(null, arguments);
2842
+ };
2843
+ Module2["dynCall_viji"] = function() {
2844
+ return (Module2["dynCall_viji"] = Module2["asm"]["ja"]).apply(null, arguments);
2845
+ };
2846
+ Module2["dynCall_jii"] = function() {
2847
+ return (Module2["dynCall_jii"] = Module2["asm"]["ka"]).apply(null, arguments);
2848
+ };
2849
+ var calledRun;
2850
+ dependenciesFulfilled = function runCaller() {
2851
+ if (!calledRun) run();
2852
+ if (!calledRun) dependenciesFulfilled = runCaller;
2853
+ };
2854
+ function run() {
2855
+ if (runDependencies > 0) {
2856
+ return;
2857
+ }
2858
+ preRun();
2859
+ if (runDependencies > 0) {
2860
+ return;
2861
+ }
2862
+ function doRun() {
2863
+ if (calledRun) return;
2864
+ calledRun = true;
2865
+ Module2["calledRun"] = true;
2866
+ if (ABORT) return;
2867
+ initRuntime();
2868
+ readyPromiseResolve(Module2);
2869
+ if (Module2["onRuntimeInitialized"]) Module2["onRuntimeInitialized"]();
2870
+ postRun();
2871
+ }
2872
+ if (Module2["setStatus"]) {
2873
+ Module2["setStatus"]("Running...");
2874
+ setTimeout(function() {
2875
+ setTimeout(function() {
2876
+ Module2["setStatus"]("");
2877
+ }, 1);
2878
+ doRun();
2879
+ }, 1);
2880
+ } else {
2881
+ doRun();
2882
+ }
2883
+ }
2884
+ if (Module2["preInit"]) {
2885
+ if (typeof Module2["preInit"] == "function") Module2["preInit"] = [Module2["preInit"]];
2886
+ while (Module2["preInit"].length > 0) {
2887
+ Module2["preInit"].pop()();
2888
+ }
2889
+ }
2890
+ run();
2891
+ function wasmSIMDSupported2() {
2892
+ const simdTest = Uint8Array.from([0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65, 0, 253, 15, 253, 98, 11]);
2893
+ return WebAssembly.validate(simdTest);
2894
+ }
2895
+ if (wasmSIMDSupported2()) {
2896
+ ENV.DOTPRODUCT = "sse";
2897
+ }
2898
+ return Module2.ready;
2899
+ });
2900
+ })();
2901
+ layoutFlags = {
2902
+ StartOfLine: 1,
2903
+ EndOfLine: 2
2904
+ };
2905
+ OCREngine = class {
2906
+ /**
2907
+ * Initialize the OCREngine.
2908
+ *
2909
+ * Use {@link createOCREngine} rather than calling this directly.
2910
+ *
2911
+ * @param tessLib - Emscripten entry point for the compiled WebAssembly module.
2912
+ * @param progressChannel - Channel used to report progress
2913
+ * updates when OCREngine is run on a background thread
2914
+ */
2915
+ constructor(tessLib, progressChannel) {
2916
+ this._tesseractLib = tessLib;
2917
+ this._engine = new tessLib.OCREngine();
2918
+ this._modelLoaded = false;
2919
+ this._imageLoaded = false;
2920
+ this._progressChannel = progressChannel;
2921
+ }
2922
+ /**
2923
+ * Shut down the OCR engine and free up resources.
2924
+ */
2925
+ destroy() {
2926
+ this._engine.delete();
2927
+ this._engine = null;
2928
+ }
2929
+ /**
2930
+ * Get the value, represented as a string, of a Tesseract configuration variable.
2931
+ *
2932
+ * See {@link setVariable} for available variables.
2933
+ */
2934
+ getVariable(name) {
2935
+ const result = this._engine.getVariable(name);
2936
+ if (!result.success) {
2937
+ throw new Error(`Unable to get variable ${name}`);
2938
+ }
2939
+ return result.value;
2940
+ }
2941
+ /**
2942
+ * Set the value of a Tesseract configuration variable.
2943
+ *
2944
+ * For a list of configuration variables, see
2945
+ * https://github.com/tesseract-ocr/tesseract/blob/677f5822f247ccb12b4e026265e88b959059fb59/src/ccmain/tesseractclass.cpp#L53
2946
+ *
2947
+ * If you have Tesseract installed locally, executing `tesseract --print-parameters`
2948
+ * will also display a list of configuration variables.
2949
+ */
2950
+ setVariable(name, value) {
2951
+ const result = this._engine.setVariable(name, value);
2952
+ if (result.error) {
2953
+ throw new Error(`Unable to set variable ${name}`);
2954
+ }
2955
+ }
2956
+ /**
2957
+ * Load a trained text recognition model.
2958
+ */
2959
+ loadModel(model) {
2960
+ const modelArray = model instanceof ArrayBuffer ? new Uint8Array(model) : model;
2961
+ const result = this._engine.loadModel(modelArray);
2962
+ if (result.error) {
2963
+ throw new Error("Text recognition model failed to load");
2964
+ }
2965
+ this._modelLoaded = true;
2966
+ }
2967
+ /**
2968
+ * Load a document image for processing by subsequent operations.
2969
+ *
2970
+ * This is a cheap operation as expensive processing is deferred until
2971
+ * bounding boxes or text content is requested.
2972
+ */
2973
+ loadImage(image) {
2974
+ let imageData;
2975
+ if (typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) {
2976
+ imageData = imageDataFromBitmap(image);
2977
+ } else {
2978
+ imageData = image;
2979
+ }
2980
+ if (imageData.data.length < imageData.width * imageData.height * 4) {
2981
+ throw new Error("Image data length does not match width/height");
2982
+ }
2983
+ if (imageData.width <= 0 || imageData.height <= 0) {
2984
+ throw new Error("Image width or height is zero");
2985
+ }
2986
+ this._engine.clearImage();
2987
+ const engineImage = new this._tesseractLib.Image(imageData.width, imageData.height);
2988
+ const engineImageBuf = engineImage.data();
2989
+ engineImageBuf.set(new Uint32Array(imageData.data.buffer));
2990
+ const result = this._engine.loadImage(engineImage);
2991
+ engineImage.delete();
2992
+ if (result.error) {
2993
+ throw new Error("Failed to load image");
2994
+ }
2995
+ this._imageLoaded = true;
2996
+ }
2997
+ /**
2998
+ * Clear the current image and text recognition results.
2999
+ *
3000
+ * This will clear the loaded image data internally, but keep the text
3001
+ * recognition model loaded.
3002
+ *
3003
+ * At present there is no way to shrink WebAssembly memory, so this will not
3004
+ * return the memory used by the image to the OS/browser. To release memory,
3005
+ * the `OCREngine` instance needs to be destroyed via {@link destroy}.
3006
+ */
3007
+ clearImage() {
3008
+ this._engine.clearImage();
3009
+ this._imageLoaded = false;
3010
+ }
3011
+ /**
3012
+ * Perform layout analysis on the current image, if not already done, and
3013
+ * return bounding boxes for a given unit of text.
3014
+ *
3015
+ * This operation is relatively cheap compared to text recognition, so can
3016
+ * provide much faster results if only the location of lines/words etc. on
3017
+ * the page is required, not the text content. This operation can also be
3018
+ * performed before a text recognition model is loaded.
3019
+ *
3020
+ * This method may return a different number/positions of words on a line
3021
+ * compared to {@link getTextBoxes} due to the simpler analysis. After full
3022
+ * OCR has been performed by {@link getTextBoxes} or {@link getText}, this
3023
+ * method should return the same results.
3024
+ */
3025
+ getBoundingBoxes(unit) {
3026
+ this._checkImageLoaded();
3027
+ const textUnit = this._textUnitForUnit(unit);
3028
+ return jsArrayFromStdVector(this._engine.getBoundingBoxes(textUnit));
3029
+ }
3030
+ /**
3031
+ * Perform layout analysis and text recognition on the current image, if
3032
+ * not already done, and return bounding boxes and text content for a given
3033
+ * unit of text.
3034
+ *
3035
+ * A text recognition model must be loaded with {@link loadModel} before this
3036
+ * is called.
3037
+ */
3038
+ getTextBoxes(unit, onProgress) {
3039
+ this._checkImageLoaded();
3040
+ this._checkModelLoaded();
3041
+ const textUnit = this._textUnitForUnit(unit);
3042
+ return jsArrayFromStdVector(this._engine.getTextBoxes(textUnit, (progress) => {
3043
+ var _a;
3044
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress(progress);
3045
+ (_a = this._progressChannel) === null || _a === void 0 ? void 0 : _a.postMessage({ progress });
3046
+ }));
3047
+ }
3048
+ /**
3049
+ * Perform layout analysis and text recognition on the current image, if
3050
+ * not already done, and return the page text as a string.
3051
+ *
3052
+ * A text recognition model must be loaded with {@link loadModel} before this
3053
+ * is called.
3054
+ */
3055
+ getText(onProgress) {
3056
+ this._checkImageLoaded();
3057
+ this._checkModelLoaded();
3058
+ return this._engine.getText((progress) => {
3059
+ var _a;
3060
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress(progress);
3061
+ (_a = this._progressChannel) === null || _a === void 0 ? void 0 : _a.postMessage({ progress });
3062
+ });
3063
+ }
3064
+ /**
3065
+ * Perform layout analysis and text recognition on the current image, if
3066
+ * not already done, and return the page text in hOCR format.
3067
+ *
3068
+ * A text recognition model must be loaded with {@link loadModel} before this
3069
+ * is called.
3070
+ */
3071
+ getHOCR(onProgress) {
3072
+ this._checkImageLoaded();
3073
+ this._checkModelLoaded();
3074
+ return this._engine.getHOCR((progress) => {
3075
+ var _a;
3076
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress(progress);
3077
+ (_a = this._progressChannel) === null || _a === void 0 ? void 0 : _a.postMessage({ progress });
3078
+ });
3079
+ }
3080
+ /**
3081
+ * Attempt to determine the orientation of the document image in degrees.
3082
+ *
3083
+ * This currently uses a simplistic algorithm [1] which is designed for
3084
+ * non-uppercase Latin text. It will likely perform badly for other scripts or
3085
+ * if the text is all uppercase.
3086
+ *
3087
+ * [1] See http://www.leptonica.org/papers/skew-measurement.pdf
3088
+ */
3089
+ getOrientation() {
3090
+ this._checkImageLoaded();
3091
+ return this._engine.getOrientation();
3092
+ }
3093
+ _checkModelLoaded() {
3094
+ if (!this._modelLoaded) {
3095
+ throw new Error("No text recognition model loaded");
3096
+ }
3097
+ }
3098
+ _checkImageLoaded() {
3099
+ if (!this._imageLoaded) {
3100
+ throw new Error("No image loaded");
3101
+ }
3102
+ }
3103
+ _textUnitForUnit(unit) {
3104
+ const { TextUnit } = this._tesseractLib;
3105
+ switch (unit) {
3106
+ case "word":
3107
+ return TextUnit.Word;
3108
+ case "line":
3109
+ return TextUnit.Line;
3110
+ default:
3111
+ throw new Error("Invalid text unit");
3112
+ }
3113
+ }
3114
+ };
3115
+ }
3116
+ });
3117
+
3118
+ // typescript/adapters/wasm-adapter.ts
3119
+ var MAX_FILE_SIZE = 512 * 1024 * 1024;
3120
+ function isNumberOrNull(value) {
3121
+ return typeof value === "number" || value === null;
3122
+ }
3123
+ function isStringOrNull(value) {
3124
+ return typeof value === "string" || value === null;
3125
+ }
3126
+ function isBoolean(value) {
3127
+ return typeof value === "boolean";
3128
+ }
3129
+ async function fileToUint8Array(file) {
3130
+ try {
3131
+ if (file.size > MAX_FILE_SIZE) {
3132
+ throw new Error(
3133
+ `File size (${file.size} bytes) exceeds maximum (${MAX_FILE_SIZE} bytes). Maximum file size is 512 MB.`
3134
+ );
3135
+ }
3136
+ const arrayBuffer = await file.arrayBuffer();
3137
+ return new Uint8Array(arrayBuffer);
3138
+ } catch (error) {
3139
+ throw new Error(`Failed to read file: ${error instanceof Error ? error.message : String(error)}`);
3140
+ }
3141
+ }
3142
+ function configToJS(config) {
3143
+ if (!config) {
3144
+ return {};
3145
+ }
3146
+ const normalized = {};
3147
+ const normalizeValue = (value) => {
3148
+ if (value === null || value === void 0) {
3149
+ return null;
3150
+ }
3151
+ if (typeof value === "object") {
3152
+ if (Array.isArray(value)) {
3153
+ return value.map(normalizeValue);
3154
+ }
3155
+ const obj = value;
3156
+ const normalized2 = {};
3157
+ for (const [key, val] of Object.entries(obj)) {
3158
+ const normalizedVal = normalizeValue(val);
3159
+ if (normalizedVal !== null && normalizedVal !== void 0) {
3160
+ normalized2[key] = normalizedVal;
3161
+ }
3162
+ }
3163
+ return Object.keys(normalized2).length > 0 ? normalized2 : null;
3164
+ }
3165
+ return value;
3166
+ };
3167
+ for (const [key, value] of Object.entries(config)) {
3168
+ const normalizedValue = normalizeValue(value);
3169
+ if (normalizedValue !== null && normalizedValue !== void 0) {
3170
+ normalized[key] = normalizedValue;
3171
+ }
3172
+ }
3173
+ return normalized;
3174
+ }
3175
+ function jsToExtractionResult(jsValue) {
3176
+ if (!jsValue || typeof jsValue !== "object") {
3177
+ throw new Error("Invalid extraction result: value is not an object");
3178
+ }
3179
+ const result = jsValue;
3180
+ const mimeType = typeof result.mimeType === "string" ? result.mimeType : typeof result.mime_type === "string" ? result.mime_type : null;
3181
+ if (typeof result.content !== "string") {
3182
+ throw new Error("Invalid extraction result: missing or invalid content");
3183
+ }
3184
+ if (typeof mimeType !== "string") {
3185
+ throw new Error("Invalid extraction result: missing or invalid mimeType");
3186
+ }
3187
+ if (!result.metadata || typeof result.metadata !== "object") {
3188
+ throw new Error("Invalid extraction result: missing or invalid metadata");
3189
+ }
3190
+ const tables = [];
3191
+ if (Array.isArray(result.tables)) {
3192
+ for (const table of result.tables) {
3193
+ if (table && typeof table === "object") {
3194
+ const t = table;
3195
+ if (Array.isArray(t.cells) && t.cells.every((row) => Array.isArray(row) && row.every((cell) => typeof cell === "string")) && typeof t.markdown === "string" && typeof t.pageNumber === "number") {
3196
+ tables.push({
3197
+ cells: t.cells,
3198
+ markdown: t.markdown,
3199
+ pageNumber: t.pageNumber
3200
+ });
3201
+ }
3202
+ }
3203
+ }
3204
+ }
3205
+ const chunks = Array.isArray(result.chunks) ? result.chunks.map((chunk) => {
3206
+ if (!chunk || typeof chunk !== "object") {
3207
+ throw new Error("Invalid chunk structure");
3208
+ }
3209
+ const c = chunk;
3210
+ if (typeof c.content !== "string") {
3211
+ throw new Error("Invalid chunk: missing content");
3212
+ }
3213
+ if (!c.metadata || typeof c.metadata !== "object") {
3214
+ throw new Error("Invalid chunk: missing metadata");
3215
+ }
3216
+ const metadata = c.metadata;
3217
+ let embedding = null;
3218
+ if (Array.isArray(c.embedding)) {
3219
+ if (!c.embedding.every((item) => typeof item === "number")) {
3220
+ throw new Error("Invalid chunk: embedding must contain only numbers");
3221
+ }
3222
+ embedding = c.embedding;
3223
+ }
3224
+ if (typeof metadata.charStart !== "number") {
3225
+ throw new Error("Invalid chunk metadata: charStart must be a number");
3226
+ }
3227
+ if (typeof metadata.charEnd !== "number") {
3228
+ throw new Error("Invalid chunk metadata: charEnd must be a number");
3229
+ }
3230
+ if (!isNumberOrNull(metadata.tokenCount)) {
3231
+ throw new Error("Invalid chunk metadata: tokenCount must be a number or null");
3232
+ }
3233
+ if (typeof metadata.chunkIndex !== "number") {
3234
+ throw new Error("Invalid chunk metadata: chunkIndex must be a number");
3235
+ }
3236
+ if (typeof metadata.totalChunks !== "number") {
3237
+ throw new Error("Invalid chunk metadata: totalChunks must be a number");
3238
+ }
3239
+ return {
3240
+ content: c.content,
3241
+ embedding,
3242
+ metadata: {
3243
+ charStart: metadata.charStart,
3244
+ charEnd: metadata.charEnd,
3245
+ tokenCount: metadata.tokenCount,
3246
+ chunkIndex: metadata.chunkIndex,
3247
+ totalChunks: metadata.totalChunks
3248
+ }
3249
+ };
3250
+ }) : null;
3251
+ const images = Array.isArray(result.images) ? result.images.map((image) => {
3252
+ if (!image || typeof image !== "object") {
3253
+ throw new Error("Invalid image structure");
3254
+ }
3255
+ const img = image;
3256
+ if (!(img.data instanceof Uint8Array)) {
3257
+ throw new Error("Invalid image: data must be Uint8Array");
3258
+ }
3259
+ if (typeof img.format !== "string") {
3260
+ throw new Error("Invalid image: missing format");
3261
+ }
3262
+ if (typeof img.imageIndex !== "number") {
3263
+ throw new Error("Invalid image: imageIndex must be a number");
3264
+ }
3265
+ if (!isNumberOrNull(img.pageNumber)) {
3266
+ throw new Error("Invalid image: pageNumber must be a number or null");
3267
+ }
3268
+ if (!isNumberOrNull(img.width)) {
3269
+ throw new Error("Invalid image: width must be a number or null");
3270
+ }
3271
+ if (!isNumberOrNull(img.height)) {
3272
+ throw new Error("Invalid image: height must be a number or null");
3273
+ }
3274
+ if (!isNumberOrNull(img.bitsPerComponent)) {
3275
+ throw new Error("Invalid image: bitsPerComponent must be a number or null");
3276
+ }
3277
+ if (!isBoolean(img.isMask)) {
3278
+ throw new Error("Invalid image: isMask must be a boolean");
3279
+ }
3280
+ if (!isStringOrNull(img.colorspace)) {
3281
+ throw new Error("Invalid image: colorspace must be a string or null");
3282
+ }
3283
+ if (!isStringOrNull(img.description)) {
3284
+ throw new Error("Invalid image: description must be a string or null");
3285
+ }
3286
+ return {
3287
+ data: img.data,
3288
+ format: img.format,
3289
+ imageIndex: img.imageIndex,
3290
+ pageNumber: img.pageNumber,
3291
+ width: img.width,
3292
+ height: img.height,
3293
+ colorspace: img.colorspace,
3294
+ bitsPerComponent: img.bitsPerComponent,
3295
+ isMask: img.isMask,
3296
+ description: img.description,
3297
+ ocrResult: img.ocrResult ? jsToExtractionResult(img.ocrResult) : null
3298
+ };
3299
+ }) : null;
3300
+ let detectedLanguages = null;
3301
+ const detectedLanguagesRaw = Array.isArray(result.detectedLanguages) ? result.detectedLanguages : result.detected_languages;
3302
+ if (Array.isArray(detectedLanguagesRaw)) {
3303
+ if (!detectedLanguagesRaw.every((lang) => typeof lang === "string")) {
3304
+ throw new Error("Invalid result: detectedLanguages must contain only strings");
3305
+ }
3306
+ detectedLanguages = detectedLanguagesRaw;
3307
+ }
3308
+ return {
3309
+ content: result.content,
3310
+ mimeType,
3311
+ metadata: result.metadata ?? {},
3312
+ tables,
3313
+ detectedLanguages,
3314
+ chunks,
3315
+ images
3316
+ };
3317
+ }
3318
+ function wrapWasmError(error, context) {
3319
+ if (error instanceof Error) {
3320
+ return new Error(`Error ${context}: ${error.message}`, {
3321
+ cause: error
3322
+ });
3323
+ }
3324
+ const message = String(error);
3325
+ return new Error(`Error ${context}: ${message}`);
3326
+ }
3327
+ function isValidExtractionResult(value) {
3328
+ if (!value || typeof value !== "object") {
3329
+ return false;
3330
+ }
3331
+ const obj = value;
3332
+ return typeof obj.content === "string" && (typeof obj.mimeType === "string" || typeof obj.mime_type === "string") && obj.metadata !== null && typeof obj.metadata === "object" && Array.isArray(obj.tables);
3333
+ }
3334
+
3335
+ // typescript/ocr/registry.ts
3336
+ var ocrBackendRegistry = /* @__PURE__ */ new Map();
3337
+ function registerOcrBackend(backend) {
3338
+ if (!backend) {
3339
+ throw new Error("Backend cannot be null or undefined");
3340
+ }
3341
+ if (typeof backend.name !== "function") {
3342
+ throw new Error("Backend must implement name() method");
3343
+ }
3344
+ if (typeof backend.supportedLanguages !== "function") {
3345
+ throw new Error("Backend must implement supportedLanguages() method");
3346
+ }
3347
+ if (typeof backend.processImage !== "function") {
3348
+ throw new Error("Backend must implement processImage() method");
3349
+ }
3350
+ const backendName = backend.name();
3351
+ if (!backendName || typeof backendName !== "string") {
3352
+ throw new Error("Backend name must be a non-empty string");
3353
+ }
3354
+ if (ocrBackendRegistry.has(backendName)) {
3355
+ console.warn(`OCR backend "${backendName}" is already registered and will be replaced`);
3356
+ }
3357
+ ocrBackendRegistry.set(backendName, backend);
3358
+ }
3359
+ function getOcrBackend(name) {
3360
+ return ocrBackendRegistry.get(name);
3361
+ }
3362
+ function listOcrBackends() {
3363
+ return Array.from(ocrBackendRegistry.keys());
3364
+ }
3365
+ async function unregisterOcrBackend(name) {
3366
+ const backend = ocrBackendRegistry.get(name);
3367
+ if (!backend) {
3368
+ throw new Error(
3369
+ `OCR backend "${name}" is not registered. Available backends: ${Array.from(ocrBackendRegistry.keys()).join(", ")}`
3370
+ );
3371
+ }
3372
+ if (typeof backend.shutdown === "function") {
3373
+ try {
3374
+ await backend.shutdown();
3375
+ } catch (error) {
3376
+ console.warn(
3377
+ `Error shutting down OCR backend "${name}": ${error instanceof Error ? error.message : String(error)}`
3378
+ );
3379
+ }
3380
+ }
3381
+ ocrBackendRegistry.delete(name);
3382
+ }
3383
+ async function clearOcrBackends() {
3384
+ const backends = Array.from(ocrBackendRegistry.entries());
3385
+ for (const [name, backend] of backends) {
3386
+ if (typeof backend.shutdown === "function") {
3387
+ try {
3388
+ await backend.shutdown();
3389
+ } catch (error) {
3390
+ console.warn(
3391
+ `Error shutting down OCR backend "${name}": ${error instanceof Error ? error.message : String(error)}`
3392
+ );
3393
+ }
3394
+ }
3395
+ }
3396
+ ocrBackendRegistry.clear();
3397
+ }
3398
+
3399
+ // typescript/ocr/tesseract-wasm-backend.ts
3400
+ var TesseractWasmBackend = class {
3401
+ /** Tesseract WASM client instance */
3402
+ client = null;
3403
+ /** Track which models are currently loaded to avoid redundant loads */
3404
+ loadedLanguages = /* @__PURE__ */ new Set();
3405
+ /** Cache for language availability validation */
3406
+ supportedLangsCache = null;
3407
+ /** Progress callback for UI updates */
3408
+ progressCallback = null;
3409
+ /** Base URL for training data CDN */
3410
+ CDN_BASE_URL = "https://cdn.jsdelivr.net/npm/tesseract-wasm@0.11.0/dist";
3411
+ /**
3412
+ * Return the unique name of this OCR backend
3413
+ *
3414
+ * @returns Backend identifier "tesseract-wasm"
3415
+ */
3416
+ name() {
3417
+ return "tesseract-wasm";
3418
+ }
3419
+ /**
3420
+ * Return list of supported language codes
3421
+ *
3422
+ * Returns a curated list of commonly available Tesseract language models.
3423
+ * Tesseract supports many more languages through custom models.
3424
+ *
3425
+ * @returns Array of ISO 639-1/2/3 language codes
3426
+ */
3427
+ supportedLanguages() {
3428
+ if (this.supportedLangsCache) {
3429
+ return this.supportedLangsCache;
3430
+ }
3431
+ this.supportedLangsCache = [
3432
+ // Major languages
3433
+ "eng",
3434
+ // English
3435
+ "deu",
3436
+ // German
3437
+ "fra",
3438
+ // French
3439
+ "spa",
3440
+ // Spanish
3441
+ "ita",
3442
+ // Italian
3443
+ "por",
3444
+ // Portuguese
3445
+ "nld",
3446
+ // Dutch
3447
+ "rus",
3448
+ // Russian
3449
+ "jpn",
3450
+ // Japanese
3451
+ "kor",
3452
+ // Korean
3453
+ "chi_sim",
3454
+ // Chinese (Simplified)
3455
+ "chi_tra",
3456
+ // Chinese (Traditional)
3457
+ // Additional European languages
3458
+ "pol",
3459
+ // Polish
3460
+ "tur",
3461
+ // Turkish
3462
+ "swe",
3463
+ // Swedish
3464
+ "dan",
3465
+ // Danish
3466
+ "fin",
3467
+ // Finnish
3468
+ "nor",
3469
+ // Norwegian
3470
+ "ces",
3471
+ // Czech
3472
+ "slk",
3473
+ // Slovak
3474
+ "ron",
3475
+ // Romanian
3476
+ "hun",
3477
+ // Hungarian
3478
+ "hrv",
3479
+ // Croatian
3480
+ "srp",
3481
+ // Serbian
3482
+ "bul",
3483
+ // Bulgarian
3484
+ "ukr",
3485
+ // Ukrainian
3486
+ "ell",
3487
+ // Greek
3488
+ // Asian languages
3489
+ "ara",
3490
+ // Arabic
3491
+ "heb",
3492
+ // Hebrew
3493
+ "hin",
3494
+ // Hindi
3495
+ "tha",
3496
+ // Thai
3497
+ "vie",
3498
+ // Vietnamese
3499
+ "mkd",
3500
+ // Macedonian
3501
+ "ben",
3502
+ // Bengali
3503
+ "tam",
3504
+ // Tamil
3505
+ "tel",
3506
+ // Telugu
3507
+ "kan",
3508
+ // Kannada
3509
+ "mal",
3510
+ // Malayalam
3511
+ "mya",
3512
+ // Burmese
3513
+ "khm",
3514
+ // Khmer
3515
+ "lao",
3516
+ // Lao
3517
+ "sin"
3518
+ // Sinhala
3519
+ ];
3520
+ return this.supportedLangsCache;
3521
+ }
3522
+ /**
3523
+ * Initialize the OCR backend
3524
+ *
3525
+ * Creates the Tesseract WASM client instance. This is called once when
3526
+ * the backend is registered with the extraction pipeline.
3527
+ *
3528
+ * The actual model loading happens in processImage() on-demand to avoid
3529
+ * loading all models upfront.
3530
+ *
3531
+ * @throws {Error} If tesseract-wasm is not available or initialization fails
3532
+ *
3533
+ * @example
3534
+ * ```typescript
3535
+ * const backend = new TesseractWasmBackend();
3536
+ * try {
3537
+ * await backend.initialize();
3538
+ * } catch (error) {
3539
+ * console.error('Failed to initialize OCR:', error);
3540
+ * }
3541
+ * ```
3542
+ */
3543
+ async initialize() {
3544
+ if (this.client) {
3545
+ return;
3546
+ }
3547
+ try {
3548
+ const tesseractModule = await this.loadTesseractWasm();
3549
+ if (!tesseractModule || typeof tesseractModule.OCRClient !== "function") {
3550
+ throw new Error("tesseract-wasm OCRClient not found. Ensure tesseract-wasm is installed and available.");
3551
+ }
3552
+ this.client = new tesseractModule.OCRClient();
3553
+ this.loadedLanguages.clear();
3554
+ } catch (error) {
3555
+ const message = error instanceof Error ? error.message : String(error);
3556
+ throw new Error(`Failed to initialize TesseractWasmBackend: ${message}`);
3557
+ }
3558
+ }
3559
+ /**
3560
+ * Process image bytes and extract text via OCR
3561
+ *
3562
+ * Handles image loading, model loading, OCR processing, and result formatting.
3563
+ * Automatically loads the language model on first use and caches it for subsequent calls.
3564
+ *
3565
+ * @param imageBytes - Raw image data (Uint8Array) or Base64-encoded string
3566
+ * @param language - ISO 639-2/3 language code (e.g., "eng", "deu")
3567
+ * @returns Promise resolving to OCR result with content and metadata
3568
+ * @throws {Error} If image processing fails, model loading fails, or language is unsupported
3569
+ *
3570
+ * @example
3571
+ * ```typescript
3572
+ * const backend = new TesseractWasmBackend();
3573
+ * await backend.initialize();
3574
+ *
3575
+ * const imageBuffer = fs.readFileSync('scanned.png');
3576
+ * const result = await backend.processImage(
3577
+ * new Uint8Array(imageBuffer),
3578
+ * 'eng'
3579
+ * );
3580
+ *
3581
+ * console.log(result.content); // Extracted text
3582
+ * console.log(result.metadata.confidence); // OCR confidence score
3583
+ * ```
3584
+ */
3585
+ async processImage(imageBytes, language) {
3586
+ if (!this.client) {
3587
+ throw new Error("TesseractWasmBackend not initialized. Call initialize() first.");
3588
+ }
3589
+ const supported = this.supportedLanguages();
3590
+ const normalizedLang = language.toLowerCase();
3591
+ const isSupported = supported.some((lang) => lang.toLowerCase() === normalizedLang);
3592
+ if (!isSupported) {
3593
+ throw new Error(`Language "${language}" is not supported. Supported languages: ${supported.join(", ")}`);
3594
+ }
3595
+ try {
3596
+ if (!this.loadedLanguages.has(normalizedLang)) {
3597
+ this.reportProgress(10);
3598
+ await this.loadLanguageModel(normalizedLang);
3599
+ this.loadedLanguages.add(normalizedLang);
3600
+ this.reportProgress(30);
3601
+ }
3602
+ this.reportProgress(40);
3603
+ const imageBitmap = await this.convertToImageBitmap(imageBytes);
3604
+ this.reportProgress(50);
3605
+ await this.client.loadImage(imageBitmap);
3606
+ this.reportProgress(70);
3607
+ const text = await this.client.getText();
3608
+ const confidence = await this.getConfidenceScore();
3609
+ const pageMetadata = await this.getPageMetadata();
3610
+ this.reportProgress(90);
3611
+ return {
3612
+ content: text,
3613
+ mime_type: "text/plain",
3614
+ metadata: {
3615
+ language: normalizedLang,
3616
+ confidence,
3617
+ ...pageMetadata
3618
+ },
3619
+ tables: []
3620
+ // Tesseract-wasm doesn't provide structured table detection
3621
+ };
3622
+ } catch (error) {
3623
+ const message = error instanceof Error ? error.message : String(error);
3624
+ throw new Error(`OCR processing failed for language "${language}": ${message}`);
3625
+ } finally {
3626
+ this.reportProgress(100);
3627
+ }
3628
+ }
3629
+ /**
3630
+ * Shutdown the OCR backend and release resources
3631
+ *
3632
+ * Properly cleans up the Tesseract WASM client, freeing memory and Web Workers.
3633
+ * Called when the backend is unregistered or the application shuts down.
3634
+ *
3635
+ * @throws {Error} If cleanup fails (errors are logged but not critical)
3636
+ *
3637
+ * @example
3638
+ * ```typescript
3639
+ * const backend = new TesseractWasmBackend();
3640
+ * await backend.initialize();
3641
+ * // ... use backend ...
3642
+ * await backend.shutdown(); // Clean up resources
3643
+ * ```
3644
+ */
3645
+ async shutdown() {
3646
+ try {
3647
+ if (this.client) {
3648
+ if (typeof this.client.destroy === "function") {
3649
+ this.client.destroy();
3650
+ }
3651
+ if (typeof this.client.terminate === "function") {
3652
+ this.client.terminate();
3653
+ }
3654
+ this.client = null;
3655
+ }
3656
+ this.loadedLanguages.clear();
3657
+ this.supportedLangsCache = null;
3658
+ this.progressCallback = null;
3659
+ } catch (error) {
3660
+ console.warn(
3661
+ `Warning during TesseractWasmBackend shutdown: ${error instanceof Error ? error.message : String(error)}`
3662
+ );
3663
+ }
3664
+ }
3665
+ /**
3666
+ * Set a progress callback for UI updates
3667
+ *
3668
+ * Allows the UI to display progress during OCR processing.
3669
+ * The callback will be called with values from 0 to 100.
3670
+ *
3671
+ * @param callback - Function to call with progress percentage
3672
+ *
3673
+ * @example
3674
+ * ```typescript
3675
+ * const backend = new TesseractWasmBackend();
3676
+ * backend.setProgressCallback((progress) => {
3677
+ * console.log(`OCR Progress: ${progress}%`);
3678
+ * document.getElementById('progress-bar').style.width = `${progress}%`;
3679
+ * });
3680
+ * ```
3681
+ */
3682
+ setProgressCallback(callback) {
3683
+ this.progressCallback = callback;
3684
+ }
3685
+ /**
3686
+ * Load language model from CDN
3687
+ *
3688
+ * Fetches the training data for a specific language from jsDelivr CDN.
3689
+ * This is an MVP approach - models are cached by the browser.
3690
+ *
3691
+ * @param language - ISO 639-2/3 language code
3692
+ * @throws {Error} If model download fails or language is not available
3693
+ *
3694
+ * @internal
3695
+ */
3696
+ async loadLanguageModel(language) {
3697
+ if (!this.client) {
3698
+ throw new Error("Client not initialized");
3699
+ }
3700
+ const modelFilename = `${language}.traineddata`;
3701
+ const modelUrl = `${this.CDN_BASE_URL}/${modelFilename}`;
3702
+ try {
3703
+ await this.client.loadModel(modelUrl);
3704
+ } catch (error) {
3705
+ const message = error instanceof Error ? error.message : String(error);
3706
+ throw new Error(`Failed to load model for language "${language}" from ${modelUrl}: ${message}`);
3707
+ }
3708
+ }
3709
+ /**
3710
+ * Convert image bytes or Base64 string to ImageBitmap
3711
+ *
3712
+ * Handles both Uint8Array and Base64-encoded image data, converting to
3713
+ * ImageBitmap format required by Tesseract WASM.
3714
+ *
3715
+ * @param imageBytes - Image data as Uint8Array or Base64 string
3716
+ * @returns Promise resolving to ImageBitmap
3717
+ * @throws {Error} If conversion fails (browser API not available or invalid image data)
3718
+ *
3719
+ * @internal
3720
+ */
3721
+ async convertToImageBitmap(imageBytes) {
3722
+ if (typeof createImageBitmap === "undefined") {
3723
+ throw new Error("createImageBitmap is not available. TesseractWasmBackend requires a browser environment.");
3724
+ }
3725
+ try {
3726
+ let bytes = imageBytes;
3727
+ if (typeof imageBytes === "string") {
3728
+ const binaryString = atob(imageBytes);
3729
+ bytes = new Uint8Array(binaryString.length);
3730
+ for (let i = 0; i < binaryString.length; i++) {
3731
+ bytes[i] = binaryString.charCodeAt(i);
3732
+ }
3733
+ }
3734
+ const blob = new Blob([bytes]);
3735
+ const imageBitmap = await createImageBitmap(blob);
3736
+ return imageBitmap;
3737
+ } catch (error) {
3738
+ const message = error instanceof Error ? error.message : String(error);
3739
+ throw new Error(`Failed to convert image bytes to ImageBitmap: ${message}`);
3740
+ }
3741
+ }
3742
+ /**
3743
+ * Get confidence score from OCR result
3744
+ *
3745
+ * Attempts to retrieve confidence score from Tesseract.
3746
+ * Returns a safe default if unavailable.
3747
+ *
3748
+ * @returns Confidence score between 0 and 1
3749
+ *
3750
+ * @internal
3751
+ */
3752
+ async getConfidenceScore() {
3753
+ try {
3754
+ if (this.client && typeof this.client.getConfidence === "function") {
3755
+ const confidence = await this.client.getConfidence();
3756
+ return confidence > 1 ? confidence / 100 : confidence;
3757
+ }
3758
+ } catch {
3759
+ }
3760
+ return 0.9;
3761
+ }
3762
+ /**
3763
+ * Get page metadata from OCR result
3764
+ *
3765
+ * Retrieves additional metadata like image dimensions and processing info.
3766
+ *
3767
+ * @returns Metadata object (may be empty if unavailable)
3768
+ *
3769
+ * @internal
3770
+ */
3771
+ async getPageMetadata() {
3772
+ try {
3773
+ if (this.client && typeof this.client.getPageMetadata === "function") {
3774
+ return await this.client.getPageMetadata();
3775
+ }
3776
+ } catch {
3777
+ }
3778
+ return {};
3779
+ }
3780
+ /**
3781
+ * Dynamically load tesseract-wasm module
3782
+ *
3783
+ * Uses dynamic import to load tesseract-wasm only when needed,
3784
+ * avoiding hard dependency in browser environments where it may not be bundled.
3785
+ *
3786
+ * @returns tesseract-wasm module object
3787
+ * @throws {Error} If module cannot be imported
3788
+ *
3789
+ * @internal
3790
+ */
3791
+ async loadTesseractWasm() {
3792
+ try {
3793
+ const module = await Promise.resolve().then(() => (init_lib(), lib_exports));
3794
+ return module;
3795
+ } catch (error) {
3796
+ const message = error instanceof Error ? error.message : String(error);
3797
+ throw new Error(
3798
+ `Failed to import tesseract-wasm. Ensure it is installed via: npm install tesseract-wasm. Error: ${message}`
3799
+ );
3800
+ }
3801
+ }
3802
+ /**
3803
+ * Report progress to progress callback
3804
+ *
3805
+ * Internal helper for notifying progress updates during OCR processing.
3806
+ *
3807
+ * @param progress - Progress percentage (0-100)
3808
+ *
3809
+ * @internal
3810
+ */
3811
+ reportProgress(progress) {
3812
+ if (this.progressCallback) {
3813
+ try {
3814
+ this.progressCallback(Math.min(100, Math.max(0, progress)));
3815
+ } catch {
3816
+ }
3817
+ }
3818
+ }
3819
+ };
3820
+
3821
+ // typescript/runtime.ts
3822
+ function detectRuntime() {
3823
+ if (typeof globalThis.Deno !== "undefined") {
3824
+ return "deno";
3825
+ }
3826
+ if (typeof globalThis.Bun !== "undefined") {
3827
+ return "bun";
3828
+ }
3829
+ if (typeof process !== "undefined" && process.versions && process.versions.node) {
3830
+ return "node";
3831
+ }
3832
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
3833
+ return "browser";
3834
+ }
3835
+ return "unknown";
3836
+ }
3837
+ function isBrowser() {
3838
+ return detectRuntime() === "browser";
3839
+ }
3840
+ function isNode() {
3841
+ return detectRuntime() === "node";
3842
+ }
3843
+ function isDeno() {
3844
+ return detectRuntime() === "deno";
3845
+ }
3846
+ function isBun() {
3847
+ return detectRuntime() === "bun";
3848
+ }
3849
+ function isWebEnvironment() {
3850
+ const runtime = detectRuntime();
3851
+ return runtime === "browser";
3852
+ }
3853
+ function isServerEnvironment() {
3854
+ const runtime = detectRuntime();
3855
+ return runtime === "node" || runtime === "deno" || runtime === "bun";
3856
+ }
3857
+ function hasFileApi() {
3858
+ return typeof window !== "undefined" && typeof File !== "undefined" && typeof Blob !== "undefined";
3859
+ }
3860
+ function hasBlob() {
3861
+ return typeof Blob !== "undefined";
3862
+ }
3863
+ function hasWorkers() {
3864
+ return typeof Worker !== "undefined";
3865
+ }
3866
+ function hasSharedArrayBuffer() {
3867
+ return typeof SharedArrayBuffer !== "undefined";
3868
+ }
3869
+ function hasModuleWorkers() {
3870
+ if (!hasWorkers()) {
3871
+ return false;
3872
+ }
3873
+ try {
3874
+ const blob = new Blob(['console.log("test")'], {
3875
+ type: "application/javascript"
3876
+ });
3877
+ const workerUrl = URL.createObjectURL(blob);
3878
+ try {
3879
+ return true;
3880
+ } finally {
3881
+ URL.revokeObjectURL(workerUrl);
3882
+ }
3883
+ } catch {
3884
+ return false;
3885
+ }
3886
+ }
3887
+ function hasWasm() {
3888
+ return typeof WebAssembly !== "undefined" && WebAssembly.instantiate !== void 0;
3889
+ }
3890
+ function hasWasmStreaming() {
3891
+ return typeof WebAssembly !== "undefined" && WebAssembly.instantiateStreaming !== void 0;
3892
+ }
3893
+ function hasBigInt() {
3894
+ try {
3895
+ const test = BigInt("1");
3896
+ return typeof test === "bigint";
3897
+ } catch {
3898
+ return false;
3899
+ }
3900
+ }
3901
+ function getRuntimeVersion() {
3902
+ const runtime = detectRuntime();
3903
+ switch (runtime) {
3904
+ case "node":
3905
+ return process.version?.substring(1);
3906
+ // Remove 'v' prefix
3907
+ case "deno": {
3908
+ const deno = globalThis.Deno;
3909
+ const version = deno?.version;
3910
+ return version?.deno;
3911
+ }
3912
+ case "bun": {
3913
+ const bun = globalThis.Bun;
3914
+ return bun?.version;
3915
+ }
3916
+ default:
3917
+ return void 0;
3918
+ }
3919
+ }
3920
+ function getWasmCapabilities() {
3921
+ const runtime = detectRuntime();
3922
+ const version = getRuntimeVersion();
3923
+ const capabilities = {
3924
+ runtime,
3925
+ hasWasm: hasWasm(),
3926
+ hasWasmStreaming: hasWasmStreaming(),
3927
+ hasFileApi: hasFileApi(),
3928
+ hasBlob: hasBlob(),
3929
+ hasWorkers: hasWorkers(),
3930
+ hasSharedArrayBuffer: hasSharedArrayBuffer(),
3931
+ hasModuleWorkers: hasModuleWorkers(),
3932
+ hasBigInt: hasBigInt(),
3933
+ ...version !== void 0 ? { runtimeVersion: version } : {}
3934
+ };
3935
+ return capabilities;
3936
+ }
3937
+ function getRuntimeInfo() {
3938
+ const runtime = detectRuntime();
3939
+ const capabilities = getWasmCapabilities();
3940
+ return {
3941
+ runtime,
3942
+ isBrowser: isBrowser(),
3943
+ isNode: isNode(),
3944
+ isDeno: isDeno(),
3945
+ isBun: isBun(),
3946
+ isWeb: isWebEnvironment(),
3947
+ isServer: isServerEnvironment(),
3948
+ runtimeVersion: getRuntimeVersion(),
3949
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : "N/A",
3950
+ capabilities
3951
+ };
3952
+ }
3953
+
3954
+ // typescript/index.ts
3955
+ var wasm = null;
3956
+ var initialized = false;
3957
+ var initializationError = null;
3958
+ var initializationPromise = null;
3959
+ async function initWasm() {
3960
+ if (initialized) {
3961
+ return;
3962
+ }
3963
+ if (initializationPromise) {
3964
+ return initializationPromise;
3965
+ }
3966
+ initializationPromise = (async () => {
3967
+ try {
3968
+ if (!hasWasm()) {
3969
+ throw new Error("WebAssembly is not supported in this environment");
3970
+ }
3971
+ let wasmModule;
3972
+ try {
3973
+ wasmModule = await import("../pkg/kreuzberg_wasm.js");
3974
+ } catch {
3975
+ wasmModule = await import("./kreuzberg_wasm.js");
3976
+ }
3977
+ wasm = wasmModule;
3978
+ if (wasm && typeof wasm.default === "function") {
3979
+ await wasm.default();
3980
+ }
3981
+ initialized = true;
3982
+ initializationError = null;
3983
+ } catch (error) {
3984
+ initializationError = error instanceof Error ? error : new Error(String(error));
3985
+ throw wrapWasmError(error, "initializing Kreuzberg WASM module");
3986
+ }
3987
+ })();
3988
+ return initializationPromise;
3989
+ }
3990
+ function isInitialized() {
3991
+ return initialized;
3992
+ }
3993
+ function getVersion() {
3994
+ if (!initialized) {
3995
+ throw new Error("WASM module not initialized. Call initWasm() first.");
3996
+ }
3997
+ if (!wasm) {
3998
+ throw new Error("WASM module not loaded. Call initWasm() first.");
3999
+ }
4000
+ return wasm.version();
4001
+ }
4002
+ function getInitializationError() {
4003
+ return initializationError;
4004
+ }
4005
+ async function extractBytes(data, mimeType, config) {
4006
+ if (!initialized) {
4007
+ throw new Error("WASM module not initialized. Call initWasm() first.");
4008
+ }
4009
+ if (!wasm) {
4010
+ throw new Error("WASM module not loaded. Call initWasm() first.");
4011
+ }
4012
+ try {
4013
+ if (!data || data.length === 0) {
4014
+ throw new Error("Document data cannot be empty");
4015
+ }
4016
+ if (!mimeType) {
4017
+ throw new Error("MIME type is required");
4018
+ }
4019
+ const normalizedConfig = configToJS(config ?? null);
4020
+ const result = await wasm.extractBytes(data, mimeType, normalizedConfig);
4021
+ if (!result) {
4022
+ throw new Error("Invalid extraction result: no result from WASM module");
4023
+ }
4024
+ return jsToExtractionResult(result);
4025
+ } catch (error) {
4026
+ throw wrapWasmError(error, "extracting from bytes");
4027
+ }
4028
+ }
4029
+ async function extractFile(path, mimeType, config) {
4030
+ if (!initialized) {
4031
+ throw new Error("WASM module not initialized. Call initWasm() first.");
4032
+ }
4033
+ if (!wasm) {
4034
+ throw new Error("WASM module not loaded. Call initWasm() first.");
4035
+ }
4036
+ try {
4037
+ if (!path) {
4038
+ throw new Error("File path is required");
4039
+ }
4040
+ const runtime = detectRuntime();
4041
+ if (runtime === "browser") {
4042
+ throw new Error("Use extractBytes with fileToUint8Array for browser environments");
4043
+ }
4044
+ let fileData;
4045
+ if (runtime === "node") {
4046
+ const { readFile } = await import("fs/promises");
4047
+ const buffer = await readFile(path);
4048
+ fileData = new Uint8Array(buffer);
4049
+ } else if (runtime === "deno") {
4050
+ const deno = globalThis.Deno;
4051
+ fileData = await deno.readFile(path);
4052
+ } else if (runtime === "bun") {
4053
+ const { readFile } = await import("fs/promises");
4054
+ const buffer = await readFile(path);
4055
+ fileData = new Uint8Array(buffer);
4056
+ } else {
4057
+ throw new Error(`Unsupported runtime for file extraction: ${runtime}`);
4058
+ }
4059
+ let detectedMimeType = mimeType;
4060
+ if (!detectedMimeType) {
4061
+ detectedMimeType = wasm.detectMimeFromBytes(fileData);
4062
+ }
4063
+ if (!detectedMimeType) {
4064
+ throw new Error("Could not detect MIME type for file. Please provide mimeType parameter.");
4065
+ }
4066
+ detectedMimeType = wasm.normalizeMimeType(detectedMimeType);
4067
+ return await extractBytes(fileData, detectedMimeType, config);
4068
+ } catch (error) {
4069
+ throw wrapWasmError(error, `extracting from file: ${path}`);
4070
+ }
4071
+ }
4072
+ async function extractFromFile(file, mimeType, config) {
4073
+ if (!initialized) {
4074
+ throw new Error("WASM module not initialized. Call initWasm() first.");
4075
+ }
4076
+ if (!wasm) {
4077
+ throw new Error("WASM module not loaded. Call initWasm() first.");
4078
+ }
4079
+ try {
4080
+ const bytes = await fileToUint8Array(file);
4081
+ let type = mimeType ?? (file instanceof File ? file.type : "application/octet-stream");
4082
+ type = wasm.normalizeMimeType(type);
4083
+ return await extractBytes(bytes, type, config);
4084
+ } catch (error) {
4085
+ throw wrapWasmError(error, `extracting from ${file instanceof File ? "file" : "blob"}`);
4086
+ }
4087
+ }
4088
+ function extractBytesSync(data, mimeType, config) {
4089
+ if (!initialized) {
4090
+ throw new Error("WASM module not initialized. Call initWasm() first.");
4091
+ }
4092
+ if (!wasm) {
4093
+ throw new Error("WASM module not loaded. Call initWasm() first.");
4094
+ }
4095
+ try {
4096
+ if (!data || data.length === 0) {
4097
+ throw new Error("Document data cannot be empty");
4098
+ }
4099
+ if (!mimeType) {
4100
+ throw new Error("MIME type is required");
4101
+ }
4102
+ const normalizedConfig = configToJS(config ?? null);
4103
+ const result = wasm.extractBytesSync(data, mimeType, normalizedConfig);
4104
+ if (!result) {
4105
+ throw new Error("Invalid extraction result: no result from WASM module");
4106
+ }
4107
+ return jsToExtractionResult(result);
4108
+ } catch (error) {
4109
+ throw wrapWasmError(error, "extracting from bytes (sync)");
4110
+ }
4111
+ }
4112
+ async function batchExtractBytes(files, config) {
4113
+ if (!initialized) {
4114
+ throw new Error("WASM module not initialized. Call initWasm() first.");
4115
+ }
4116
+ if (!wasm) {
4117
+ throw new Error("WASM module not loaded. Call initWasm() first.");
4118
+ }
4119
+ try {
4120
+ if (!Array.isArray(files)) {
4121
+ throw new Error("Files parameter must be an array");
4122
+ }
4123
+ if (files.length === 0) {
4124
+ throw new Error("Files array cannot be empty");
4125
+ }
4126
+ const dataList = [];
4127
+ const mimeTypes = [];
4128
+ for (let i = 0; i < files.length; i += 1) {
4129
+ const file = files[i];
4130
+ if (!file || typeof file !== "object") {
4131
+ throw new Error(`Invalid file at index ${i}: must be an object with data and mimeType`);
4132
+ }
4133
+ const f = file;
4134
+ if (!(f.data instanceof Uint8Array)) {
4135
+ throw new Error(`Invalid file at index ${i}: data must be Uint8Array`);
4136
+ }
4137
+ if (typeof f.mimeType !== "string") {
4138
+ throw new Error(`Invalid file at index ${i}: mimeType must be a string`);
4139
+ }
4140
+ if (f.data.length === 0) {
4141
+ throw new Error(`Invalid file at index ${i}: data cannot be empty`);
4142
+ }
4143
+ dataList.push(f.data);
4144
+ mimeTypes.push(f.mimeType);
4145
+ }
4146
+ const normalizedConfig = configToJS(config ?? null);
4147
+ const results = await wasm.batchExtractBytes(dataList, mimeTypes, normalizedConfig);
4148
+ if (!Array.isArray(results)) {
4149
+ throw new Error("Invalid batch extraction result: expected array");
4150
+ }
4151
+ return results.map((result, index) => {
4152
+ if (!result) {
4153
+ throw new Error(`Invalid extraction result at index ${index}: no result from WASM module`);
4154
+ }
4155
+ return jsToExtractionResult(result);
4156
+ });
4157
+ } catch (error) {
4158
+ throw wrapWasmError(error, "batch extracting from bytes");
4159
+ }
4160
+ }
4161
+ function batchExtractBytesSync(files, config) {
4162
+ if (!initialized) {
4163
+ throw new Error("WASM module not initialized. Call initWasm() first.");
4164
+ }
4165
+ if (!wasm) {
4166
+ throw new Error("WASM module not loaded. Call initWasm() first.");
4167
+ }
4168
+ try {
4169
+ if (!Array.isArray(files)) {
4170
+ throw new Error("Files parameter must be an array");
4171
+ }
4172
+ if (files.length === 0) {
4173
+ throw new Error("Files array cannot be empty");
4174
+ }
4175
+ const dataList = [];
4176
+ const mimeTypes = [];
4177
+ for (let i = 0; i < files.length; i += 1) {
4178
+ const file = files[i];
4179
+ if (!file || typeof file !== "object") {
4180
+ throw new Error(`Invalid file at index ${i}: must be an object with data and mimeType`);
4181
+ }
4182
+ const f = file;
4183
+ if (!(f.data instanceof Uint8Array)) {
4184
+ throw new Error(`Invalid file at index ${i}: data must be Uint8Array`);
4185
+ }
4186
+ if (typeof f.mimeType !== "string") {
4187
+ throw new Error(`Invalid file at index ${i}: mimeType must be a string`);
4188
+ }
4189
+ if (f.data.length === 0) {
4190
+ throw new Error(`Invalid file at index ${i}: data cannot be empty`);
4191
+ }
4192
+ dataList.push(f.data);
4193
+ mimeTypes.push(f.mimeType);
4194
+ }
4195
+ const normalizedConfig = configToJS(config ?? null);
4196
+ const results = wasm.batchExtractBytesSync(dataList, mimeTypes, normalizedConfig);
4197
+ if (!Array.isArray(results)) {
4198
+ throw new Error("Invalid batch extraction result: expected array");
4199
+ }
4200
+ return results.map((result, index) => {
4201
+ if (!result) {
4202
+ throw new Error(`Invalid extraction result at index ${index}: no result from WASM module`);
4203
+ }
4204
+ return jsToExtractionResult(result);
4205
+ });
4206
+ } catch (error) {
4207
+ throw wrapWasmError(error, "batch extracting from bytes (sync)");
4208
+ }
4209
+ }
4210
+ async function batchExtractFiles(files, config) {
4211
+ if (!initialized) {
4212
+ throw new Error("WASM module not initialized. Call initWasm() first.");
4213
+ }
4214
+ try {
4215
+ if (!Array.isArray(files)) {
4216
+ throw new Error("Files parameter must be an array");
4217
+ }
4218
+ if (files.length === 0) {
4219
+ throw new Error("Files array cannot be empty");
4220
+ }
4221
+ const byteFiles = [];
4222
+ for (let i = 0; i < files.length; i += 1) {
4223
+ const file = files[i];
4224
+ if (!(file instanceof File)) {
4225
+ throw new Error(`Invalid file at index ${i}: must be a File object`);
4226
+ }
4227
+ const bytes = await fileToUint8Array(file);
4228
+ byteFiles.push({
4229
+ data: bytes,
4230
+ mimeType: file.type || "application/octet-stream"
4231
+ });
4232
+ }
4233
+ return await batchExtractBytes(byteFiles, config);
4234
+ } catch (error) {
4235
+ throw wrapWasmError(error, "batch extracting from files");
4236
+ }
4237
+ }
4238
+ async function enableOcr() {
4239
+ if (!initialized) {
4240
+ throw new Error("WASM module not initialized. Call initWasm() first.");
4241
+ }
4242
+ if (!isBrowser()) {
4243
+ throw new Error(
4244
+ "OCR is only available in browser environments. TesseractWasmBackend requires Web Workers and createImageBitmap."
4245
+ );
4246
+ }
4247
+ try {
4248
+ const backend = new TesseractWasmBackend();
4249
+ await backend.initialize();
4250
+ registerOcrBackend(backend);
4251
+ } catch (error) {
4252
+ const message = error instanceof Error ? error.message : String(error);
4253
+ throw new Error(`Failed to enable OCR: ${message}`);
4254
+ }
4255
+ }
4256
+ export {
4257
+ TesseractWasmBackend,
4258
+ batchExtractBytes,
4259
+ batchExtractBytesSync,
4260
+ batchExtractFiles,
4261
+ clearOcrBackends,
4262
+ configToJS,
4263
+ detectRuntime,
4264
+ enableOcr,
4265
+ extractBytes,
4266
+ extractBytesSync,
4267
+ extractFile,
4268
+ extractFromFile,
4269
+ fileToUint8Array,
4270
+ getInitializationError,
4271
+ getOcrBackend,
4272
+ getRuntimeInfo,
4273
+ getRuntimeVersion,
4274
+ getVersion,
4275
+ getWasmCapabilities,
4276
+ hasBigInt,
4277
+ hasBlob,
4278
+ hasFileApi,
4279
+ hasModuleWorkers,
4280
+ hasSharedArrayBuffer,
4281
+ hasWasm,
4282
+ hasWasmStreaming,
4283
+ hasWorkers,
4284
+ initWasm,
4285
+ isBrowser,
4286
+ isBun,
4287
+ isDeno,
4288
+ isInitialized,
4289
+ isNode,
4290
+ isServerEnvironment,
4291
+ isValidExtractionResult,
4292
+ isWebEnvironment,
4293
+ jsToExtractionResult,
4294
+ listOcrBackends,
4295
+ registerOcrBackend,
4296
+ unregisterOcrBackend,
4297
+ wrapWasmError
4298
+ };
4299
+ /*! Bundled license information:
4300
+
4301
+ tesseract-wasm/dist/lib.js:
4302
+ (**
4303
+ * @license
4304
+ * Copyright 2019 Google LLC
4305
+ * SPDX-License-Identifier: Apache-2.0
4306
+ *)
4307
+ */
4308
+ //# sourceMappingURL=index.js.map