Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 | 16x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 26x 13x 13x 13x 13x 13x 13x 23x 1x 22x 1x 1x 21x 21x 21x 21x 21x 21x 21x 21x 15x 15x 15x 14x 1x 15x 13x 13x 13x 13x 13x 13x 13x 13x 45x 45x 30x 21x 24x 24x 6x 6x 6x 12x 12x 12x 14x 1x 13x 11x 13x 2x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 14x 14x 14x 14x 14x 14x 5x 9x 10x 10x 10x 4x 1x 1x 1x 1x 4x 1x 12x 2x 12x 12x 2x 12x 12x 2x 2x 10x 10x 10x 64x 45x 19x 8x 8x 19x 7x 12x 14x 2x 12x 9x 9x 9x 2x 2x 7x 7x 34x 25x 9x 9x 13x 13x 13x 9x 9x 3x 2x 3x 4x 1x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 66x 66x 35x 35x 7x 28x 28x 28x 21x 21x 2x 2x 19x 2x 2x 21x 4x 17x 16x 512x 512x 48x 26x 10x 16x 16x 16x 16x 16x 16x 16x 16x 12x 16x 16x 15x 15x 18x 9x 9x 9x 3x 6x 5x 1x 9x 9x 3x 9x 9x 9x 12x 1x 11x 11x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 16x 16x 16x 16x 21x 21x 16x 16x 16x 3x 16x 16x 13x 5x 17x 4x 4x 1x 1x 1x 3x 3x 3x 2x 1x 1x 14x 13x 11x 2x 2x 2x 17x 2x 2x 2x 8x 8x 8x 8x 8x 8x 29x 29x 8x 8x 8x 6x 6x 6x 6x 6x 6x 15x 15x 15x 15x 12x 12x 21x 21x 8x 17x 17x 17x 17x 2x 2x 17x 17x 9x 8x 8x 2x 2x 8x 8x 8x 17x 33x 33x 33x 33x 3x 3x 30x 30x 30x 30x 53x 33x 28x 28x 21x 16x 16x | import { Barcode, BarcodeWASMResult } from "../barcode"; import { ImageSettings } from "../imageSettings"; import { Parser } from "../parser"; // WARNING // ========== // The "engine" function is extracted and executed in isolation as a WebWorker in the browser. // We currently cannot use too advanced language features here as the code will not get transformed/polyfilled correctly // by Rollup and Babel as it might refer to other externally defined variables/functions. // This means we also cannot import and use variables from the rest of the project. // The used language features should be compatible with (supported by) the browsers mentioned in the documentation. // See rollup.config.js and .browserslistrc.worker for more details. // TODO: This should be fixed... // tslint:disable:no-any declare const self: any; declare const importScripts: (...urls: string[]) => Promise<void> | undefined; // Promise is used only during testing declare const postMessage: (message: any, transfer?: any[]) => void; // Defined here as we cannot use too recent typescript type definitions declare namespace WebAssembly { interface Instance { readonly exports: any; } interface WebAssemblyInstantiatedSource { instance: Instance; // tslint:disable-next-line:no-reserved-keywords module: {}; } } type FileSystemType = {}; export declare type Module = { HEAPU8: Uint8Array; lengthBytesUTF8(str: string): number; UTF8ToString(ptr: number): string; stringToUTF8(str: string, outPtr: number, maxBytesToWrite: number): void; _malloc(size: number): number; _free(ptr: number): void; _create_context( licenseKeyPointer: number, writableDataPathPointer: number, delayedRegistration: boolean, debug: boolean ): void; _scanner_settings_new_from_json( jsonSettingsPointer: number, blurryRecognitionEnabled: boolean, matrixScanEnabled: boolean, highQualitySingleFrameMode: boolean, gpuEnabled: boolean ): number; _scanner_image_settings_new(width: number, height: number, channels: number): void; _scanner_session_clear(): void; _can_hide_logo(): number; _scanner_scan(imageDataPointer: number): number; _parser_parse_string( parserType: number, stringDataPointer: number, stringDataLength: number, optionsPointer: number ): number; _create_blurry_table(symbologyPointer: number): void; canvas(): HTMLCanvasElement; instantiateWasm(importObject: object, successCallback: (instance: WebAssembly.Instance) => void): void; preRun(): Promise<void>; // Promise is used only during testing onRuntimeInitialized(): void; callMain(): void; }; declare let Module: Module; declare namespace FS { function syncfs(populate: boolean, callback: (e: any) => any): void; function mount(fsType: FileSystemType, opts: any, mountpoint: string): any; function mkdir(path: string, mode?: number): any; } declare const IDBFS: FileSystemType; // tslint:enable:no-any declare type ScanWorkUnit = { requestId: number; data: Uint8Array; highQualitySingleFrameMode: boolean; }; declare type ParseWorkUnit = { requestId: number; dataFormat: Parser.DataFormat; dataString: string; options: string; }; // tslint:disable:no-reserved-keywords export declare type EngineReceivedMessageData = | { type: "load-library"; deviceId: string; libraryLocation: string; path: string; preload: boolean; deviceModelName?: string; } | { type: "create-context"; licenseKey?: string; delayedRegistration: boolean } | { type: "settings"; settings: string; blurryRecognitionAvailable: boolean; blurryRecognitionRequiresUpdate: boolean; } | { type: "image-settings"; imageSettings: ImageSettings } | { type: "work"; requestId: number; data: Uint8Array; highQualitySingleFrameMode: boolean } | { type: "parse-string"; requestId: number; dataFormat: Parser.DataFormat; dataString: string; options: string } | { type: "clear-session" } | { type: "create-blurry-table"; symbology: Barcode.Symbology } | { type: "reset" }; // tslint:enable:no-reserved-keywords export declare type EngineSentMessageData = | ["status", string] | ["license-key-features", object] | ["work-result", { requestId: number; result: { scanResult: BarcodeWASMResult[] } }, Uint8Array] | ["work-error", { requestId: number; error: { errorCode: number; errorMessage: string } }, Uint8Array] | ["parse-string-result", { requestId: number; result: string }] | ["parse-string-error", { requestId: number; error: { errorCode: number; errorMessage: string } }] | ["create-blurry-table-result", Barcode.Symbology]; export interface EngineWorker extends Worker { onmessage: ((this: Worker, ev: MessageEvent & { data: EngineSentMessageData }) => void) | null; postMessage(message: EngineReceivedMessageData, transfer: Transferable[]): void; postMessage(message: EngineReceivedMessageData, options?: PostMessageOptions): void; } export declare type Engine = { loadLibrary( deviceId: string, libraryLocation: string, locationPath: string, preload: boolean, deviceModelName?: string ): Promise<void>; createContext(delayedRegistration: boolean, licenseKey?: string): void; setSettings(settings: string, blurryRecognitionAvailable: boolean, blurryRecognitionRequiresUpdate: boolean): void; setImageSettings(imageSettings: ImageSettings): void; workOnScanQueue(): void; workOnParseQueue(): void; addScanWorkUnit(scanWorkUnit: ScanWorkUnit): void; addParseWorkUnit(parseWorkUnit: ParseWorkUnit): void; clearSession(): void; createBlurryTable(symbology: Barcode.Symbology): void; reset(): void; }; /** * @returns Engine */ // tslint:disable-next-line:max-func-body-length export function engine(): Engine { const writableDataPathPreload: string = "/scandit_sync_folder_preload"; const writableDataPathStandard: string = "/scandit_sync_folder"; const scanQueue: ScanWorkUnit[] = []; const parseQueue: ParseWorkUnit[] = []; const gpuAccelerationAvailable: boolean = typeof self.OffscreenCanvas === "function"; let imageBufferPointer: number | undefined; let imageBufferSize: number | undefined; let preloading: boolean; let writableDataPath: string; let licenseKey: string; let settings: string | undefined; let imageSettings: ImageSettings | undefined; let blurryRecognitionAvailable: boolean = false; let scanWorkSubmitted: boolean = false; let loadingInProgress: boolean = false; let fileSystemSynced: boolean = false; let runtimeLoaded: boolean = false; let wasmReady: boolean = false; let scannerSettingsReady: boolean = false; let scannerImageSettingsReady: boolean = false; let contextAvailable: boolean = false; let fsSyncPromise: Promise<void>; let fsSyncInProgress: boolean = false; // Public // Promise is used only during testing function loadLibrary( deviceId: string, libraryLocation: string, locationPath: string, preload: boolean, deviceModelName?: string ): Promise<void> { function start(): void { if (!wasmReady && fileSystemSynced && runtimeLoaded) { loadingInProgress = false; wasmReady = true; Module.callMain(); postMessage(["status", "ready"]); workOnScanQueue(); workOnParseQueue(); } } if (loadingInProgress) { return Promise.resolve(); } if (wasmReady) { postMessage(["status", "ready"]); return Promise.resolve(); } loadingInProgress = true; const { jsURI, wasmURI } = getLibraryLocationURIs(libraryLocation); preloading = preload; writableDataPath = preload ? writableDataPathPreload : writableDataPathStandard; self.window = self.document = self; // Fix some Emscripten quirks self.path = locationPath; // Used by the Scandit SDK Engine library self.deviceModelName = deviceModelName; // Used by the Scandit SDK Engine library Module = <Module>(<unknown>{ arguments: [deviceId], canvas: gpuAccelerationAvailable ? new self.OffscreenCanvas(32, 32) : /* istanbul ignore next */ undefined, instantiateWasm: (importObject: object, successCallback: (instance: WebAssembly.Instance) => void) => { // wasmJSVersion is globally defined inside scandit-engine-sdk.min.js const wasmJSVersion: string = self.wasmJSVersion ?? "undefined"; // istanbul ignore if if (wasmJSVersion !== "%VERSION%") { console.error( `The Scandit SDK Engine library JS file found at ${jsURI} seems invalid: ` + `expected version doesn't match (received: ${wasmJSVersion}, expected: ${"%VERSION%"}). ` + `Please ensure the correct Scandit SDK Engine file (with correct version) is retrieved.` ); } if (typeof self.WebAssembly.instantiateStreaming === "function") { instantiateWebAssemblyStreaming(importObject, wasmURI, successCallback); } else { instantiateWebAssembly(importObject, wasmURI, successCallback); } return {}; }, noInitialRun: true, preRun: () => { try { FS.mkdir(writableDataPath); } catch (error) { // istanbul ignore next if (error.code !== "EEXIST") { throw error; } } FS.mount(IDBFS, {}, writableDataPath); return syncFS(true, true) .then(() => { fileSystemSynced = true; start(); }) .catch(console.error); }, onRuntimeInitialized: () => { runtimeLoaded = true; start(); }, }); function tryImportScripts(): Promise<void> { try { return importScripts(jsURI) ?? Promise.resolve(); } catch (error) { return Promise.reject(error); } } return retryWithExponentialBackoff(tryImportScripts, 250, 4000, (error) => { console.warn(error); console.warn(`Couldn't retrieve Scandit SDK Engine library at ${jsURI}, retrying...`); }).catch((error) => { console.error(error); console.error( `Couldn't retrieve Scandit SDK Engine library at ${jsURI}, did you configure the path for it correctly?` ); return Promise.resolve(error); // Promise is used only during testing }); } function createContext(delayedRegistration: boolean, newLicenseKey?: string): void { function completeCreateContext(): void { postMessage([ "license-key-features", { hiddenScanditLogoAllowed: Module._can_hide_logo() === 1, }, ]); workOnScanQueue(); workOnParseQueue(); } if (contextAvailable) { return completeCreateContext(); } if (newLicenseKey != null) { licenseKey = newLicenseKey; } if (licenseKey == null || delayedRegistration == null || !wasmReady) { return; } const licenseKeyLength: number = Module.lengthBytesUTF8(licenseKey) + 1; const licenseKeyPointer: number = Module._malloc(licenseKeyLength); Module.stringToUTF8(licenseKey, licenseKeyPointer, licenseKeyLength); const writableDataPathLength: number = Module.lengthBytesUTF8(writableDataPath) + 1; const writableDataPathPointer: number = Module._malloc(writableDataPathLength); Module.stringToUTF8(writableDataPath, writableDataPathPointer, writableDataPathLength); Module._create_context(licenseKeyPointer, writableDataPathPointer, delayedRegistration, false); Module._free(licenseKeyPointer); Module._free(writableDataPathPointer); contextAvailable = true; completeCreateContext(); } function setSettings( newSettings: string, newBlurryRecognitionAvailable: boolean, blurryRecognitionRequiresUpdate: boolean ): void { function completeSetSettings(): void { settings = newSettings; blurryRecognitionAvailable = newBlurryRecognitionAvailable; applySettings(); workOnScanQueue(); } settings = undefined; if (newBlurryRecognitionAvailable && blurryRecognitionRequiresUpdate) { syncFS(true).then(completeSetSettings).catch(completeSetSettings); } else { completeSetSettings(); } } function setImageSettings(newImageSettings: ImageSettings): void { imageSettings = newImageSettings; applyImageSettings(); workOnScanQueue(); } function augmentErrorInformation(error: { errorCode: number; errorMessage: string }): void { if (error.errorCode === 260) { let hostname: string; // istanbul ignore if if (location.href?.indexOf("blob:null/") === 0) { hostname = "localhost"; } else { hostname = new URL( location.pathname != null && location.pathname !== "" && !location.pathname.startsWith("/") ? /* istanbul ignore next */ location.pathname : location.origin ).hostname; } // istanbul ignore next if (hostname[0].startsWith("[") && hostname.endsWith("]")) { hostname = hostname.slice(1, -1); } error.errorMessage = error.errorMessage.replace("domain name", `domain name (${hostname})`); } // License Key related error codes from 6 to 25 and 260 if ( [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 260].includes(error.errorCode) && licenseKey != null && licenseKey.length > 0 ) { error.errorMessage += ` License Key: ${licenseKey.slice(0, 15)}...`; } } function processScanWorkUnit(scanWorkUnit: ScanWorkUnit): void { if (scanWorkUnit.highQualitySingleFrameMode) { applySettings(true, false); } const resultData: string = scanImage(scanWorkUnit.data); if (scanWorkUnit.highQualitySingleFrameMode) { applySettings(false, false); } const result: { scanResult?: BarcodeWASMResult[]; error?: { errorCode: number; errorMessage: string }; } = JSON.parse(resultData); if (result.error != null) { augmentErrorInformation(result.error); postMessage( [ "work-error", { requestId: scanWorkUnit.requestId, error: result.error, }, scanWorkUnit.data, ], [scanWorkUnit.data.buffer] ); } else { // istanbul ignore else if (result.scanResult != null) { Iif (result.scanResult.length > 0) { syncFS(false).catch( /* istanbul ignore next */ () => { // Ignored } ); } postMessage( [ "work-result", { requestId: scanWorkUnit.requestId, result, }, scanWorkUnit.data, ], [scanWorkUnit.data.buffer] ); } } } function workOnScanQueue(): void { if (!contextAvailable || !wasmReady || scanQueue.length === 0) { return; } if (settings != null && (!scannerSettingsReady || !scannerImageSettingsReady)) { // First submitted work unit applySettings(); applyImageSettings(); } if (settings == null || !scannerSettingsReady || !scannerImageSettingsReady) { return; } while (scanQueue.length !== 0) { if (scanQueue[0].highQualitySingleFrameMode && !blurryRecognitionAvailable) { break; } processScanWorkUnit(<ScanWorkUnit>scanQueue.shift()); } } function processParseWorkUnit(parseWorkUnit: ParseWorkUnit): void { const resultData: string = parseString(parseWorkUnit.dataFormat, parseWorkUnit.dataString, parseWorkUnit.options); const result: { result?: string; error?: { errorCode: number; errorMessage: string } } = JSON.parse(resultData); if (result.error != null) { augmentErrorInformation(result.error); postMessage([ "parse-string-error", { requestId: parseWorkUnit.requestId, error: result.error, }, ]); } else { // istanbul ignore else if (result.result != null) { postMessage([ "parse-string-result", { requestId: parseWorkUnit.requestId, result: result.result, }, ]); } } } function workOnParseQueue(): void { if (!contextAvailable || !wasmReady || parseQueue.length === 0) { return; } while (parseQueue.length !== 0) { processParseWorkUnit(<ParseWorkUnit>parseQueue.shift()); } } function addScanWorkUnit(scanWorkUnit: ScanWorkUnit): void { scanWorkSubmitted = true; scanQueue.push(scanWorkUnit); workOnScanQueue(); } function addParseWorkUnit(parseWorkUnit: ParseWorkUnit): void { parseQueue.push(parseWorkUnit); workOnParseQueue(); } function clearSession(): void { if (scannerSettingsReady) { Module._scanner_session_clear(); } } function createBlurryTable(symbology: Barcode.Symbology): void { function reportResult(): void { postMessage(["create-blurry-table-result", symbology]); } if (!contextAvailable || !wasmReady) { return; } const symbologyLength: number = Module.lengthBytesUTF8(symbology) + 1; const symbologyPointer: number = Module._malloc(symbologyLength); Module.stringToUTF8(symbology, symbologyPointer, symbologyLength); Module._create_blurry_table(symbologyPointer); Module._free(symbologyPointer); syncFS(false).then(reportResult).catch( // istanbul ignore next reportResult ); } function reset(): void { clearSession(); scanQueue.length = 0; parseQueue.length = 0; settings = undefined; imageSettings = undefined; scanWorkSubmitted = false; scannerSettingsReady = false; scannerImageSettingsReady = false; } // Private function retryWithExponentialBackoff<T>( handler: () => Promise<T>, backoffMs: number, maxBackoffMs: number, singleTryRejectionCallback: (error: Error) => void ): Promise<T> { return new Promise((resolve, reject) => { handler() .then(resolve) .catch((error) => { const newBackoffMs: number = backoffMs * 2; if (newBackoffMs > maxBackoffMs) { return reject(error); } singleTryRejectionCallback(error); setTimeout(() => { retryWithExponentialBackoff(handler, newBackoffMs, maxBackoffMs, singleTryRejectionCallback) .then(resolve) .catch(reject); }, backoffMs); }); }); } function getLibraryLocationURIs(libraryLocation: string): { jsURI: string; wasmURI: string } { let cdnURI: boolean = false; if (/^https?:\/\/([^\/.]*\.)*cdn.jsdelivr.net\//.test(libraryLocation)) { libraryLocation = "https://cdn.jsdelivr.net/npm/scandit-sdk@%VERSION%/build/"; cdnURI = true; } else if (/^https?:\/\/([^\/.]*\.)*unpkg.com\//.test(libraryLocation)) { libraryLocation = "https://unpkg.com/scandit-sdk@%VERSION%/build/"; cdnURI = true; } if (cdnURI) { return { jsURI: `${libraryLocation}scandit-engine-sdk.min.js`, wasmURI: `${libraryLocation}scandit-engine-sdk.wasm`, }; } return { jsURI: `${libraryLocation}scandit-engine-sdk.min.js?v=%VERSION%`, wasmURI: `${libraryLocation}scandit-engine-sdk.wasm?v=%VERSION%`, }; } function arrayBufferToHexString(arrayBuffer: ArrayBuffer): string { return Array.from(new Uint8Array(arrayBuffer)) .map((byteNumber) => { const byteHex: string = byteNumber.toString(16); return byteHex.length === 1 ? /* istanbul ignore next */ `0${byteHex}` : byteHex; }) .join(""); } function applySettings(highQualitySingleFrameMode: boolean = false, fsSyncSaveContextData: boolean = true): void { if (settings == null || !contextAvailable || !wasmReady || !scanWorkSubmitted) { return; } scannerSettingsReady = false; const parsedSettings: { matrixScanEnabled: boolean; gpuAcceleration: boolean; blurryRecognition: boolean; } = JSON.parse(settings); const settingsLength: number = Module.lengthBytesUTF8(settings) + 1; const settingsPointer: number = Module._malloc(settingsLength); Module.stringToUTF8(settings, settingsPointer, settingsLength); const resultPointer: number = Module._scanner_settings_new_from_json( settingsPointer, parsedSettings.blurryRecognition && blurryRecognitionAvailable, parsedSettings.matrixScanEnabled, highQualitySingleFrameMode, gpuAccelerationAvailable && parsedSettings.gpuAcceleration ); Module._free(settingsPointer); if (fsSyncSaveContextData) { syncFS(false).catch( /* istanbul ignore next */ () => { // Ignored } ); } const result: string = Module.UTF8ToString(resultPointer); if (result !== "") { scannerSettingsReady = true; console.debug(JSON.parse(result)); } } function applyImageSettings(): void { if (imageSettings == null || !wasmReady || !scanWorkSubmitted) { return; } scannerImageSettingsReady = false; let channels: number; // TODO: For now it's not possible to use imported variables as the worker doesn't have access at runtime if (imageSettings.format.valueOf() === 1) { // RGB_8U channels = 3; } else if (imageSettings.format.valueOf() === 2) { // RGBA_8U channels = 4; } else { // GRAY_8U channels = 1; } Module._scanner_image_settings_new(imageSettings.width, imageSettings.height, channels); if (imageBufferPointer != null) { Module._free(imageBufferPointer); } imageBufferSize = imageSettings.width * imageSettings.height * channels; imageBufferPointer = Module._malloc(imageBufferSize); scannerImageSettingsReady = true; } function scanImage(imageData: Uint8Array): string { if (imageData.length !== imageBufferSize) { // This could happen in unexpected situations and should be temporary return JSON.stringify({ scanResult: [] }); } Module.HEAPU8.set(imageData, imageBufferPointer); return Module.UTF8ToString(Module._scanner_scan(<number>imageBufferPointer)); } function parseString(dataFormat: Parser.DataFormat, dataString: string, options: string): string { const dataStringLength: number = Module.lengthBytesUTF8(dataString) + 1; const dataStringPointer: number = Module._malloc(dataStringLength); Module.stringToUTF8(dataString, dataStringPointer, dataStringLength); const optionsLength: number = Module.lengthBytesUTF8(options) + 1; const optionsPointer: number = Module._malloc(optionsLength); Module.stringToUTF8(options, optionsPointer, optionsLength); const resultPointer: number = Module._parser_parse_string( dataFormat.valueOf(), dataStringPointer, dataStringLength - 1, optionsPointer ); Module._free(dataStringPointer); Module._free(optionsPointer); return Module.UTF8ToString(resultPointer); } function verifiedWasmFetch(wasmURI: string, awaitFullResponse: boolean): Promise<Response> { function verifyResponseData(responseData: ArrayBuffer): void { // istanbul ignore else if (typeof crypto?.subtle?.digest === "function") { crypto.subtle.digest("SHA-256", responseData).then((hash) => { const hashString: string = arrayBufferToHexString(hash); // istanbul ignore if if (hashString !== "%ENGINE_WASM_HASH%") { console.error( `The Scandit SDK Engine library WASM file found at ${wasmURI} seems invalid: ` + `expected file hash doesn't match (received: ${hashString}, ` + `expected: ${"%ENGINE_WASM_HASH%"}). ` + `Please ensure the correct Scandit SDK Engine file (with correct version) is retrieved.` ); } }); } else { console.warn( "Insecure origin (see https://goo.gl/Y0ZkNV): " + `The hash of the Scandit SDK Engine library WASM file found at ${wasmURI} could not be verified` ); } } function tryFetch(): Promise<Response> { return new Promise((resolve, reject) => { fetch(wasmURI) .then((response) => { // istanbul ignore else if (response.ok) { response .clone() .arrayBuffer() .then((responseData) => { if (awaitFullResponse) { resolve(response); } verifyResponseData(responseData); }) .catch( // istanbul ignore next (error) => { if (awaitFullResponse) { reject(error); } } ); if (!awaitFullResponse) { resolve(response); } } else { reject(new Error("HTTP status code is not ok")); } }) .catch((error) => { reject(error); }); }); } return retryWithExponentialBackoff(tryFetch, 250, 4000, (error) => { console.warn(error); console.warn(`Couldn't retrieve Scandit SDK Engine library at ${wasmURI}, retrying...`); }).catch((error) => { console.error(error); console.error( `Couldn't retrieve/instantiate Scandit SDK Engine library at ${wasmURI}, ` + "did you configure the path for it correctly?" ); return Promise.reject(error); }); } function instantiateWebAssembly( importObject: object, wasmURI: string, successCallback: (instance: WebAssembly.Instance) => void ): void { verifiedWasmFetch(wasmURI, true) .then((response) => { return response.arrayBuffer(); }) .then((bytes) => { return self.WebAssembly.instantiate(bytes, importObject) .then((results: WebAssembly.WebAssemblyInstantiatedSource) => { successCallback(results.instance); }) .catch((error: Error) => { console.error(error); console.error( `Couldn't instantiate Scandit SDK Engine library at ${wasmURI}, ` + "did you configure the path for it correctly?" ); }); }) .catch( /* istanbul ignore next */ () => { // Ignored } ); } function instantiateWebAssemblyStreaming( importObject: object, wasmURI: string, successCallback: (instance: WebAssembly.Instance) => void ): void { verifiedWasmFetch(wasmURI, false) .then((response) => { self.WebAssembly.instantiateStreaming(response, importObject) .then((results: WebAssembly.WebAssemblyInstantiatedSource) => { successCallback(results.instance); }) .catch((error: Error) => { console.warn(error); console.warn( "WebAssembly streaming compile failed. " + "Falling back to ArrayBuffer instantiation (this will make things slower)" ); instantiateWebAssembly(importObject, wasmURI, successCallback); }); }) .catch( /* istanbul ignore next */ () => { // Ignored } ); } function syncFSMergePreloadedData(): Promise<number> { const fsObjectStoreName: string = "FILE_DATA"; let resolveCallback: (value: number | PromiseLike<number>) => void; let openDbSourceRequest: IDBOpenDBRequest; let openDbTargetRequest: IDBOpenDBRequest; function handleError(this: IDBOpenDBRequest | IDBTransaction | IDBRequest | { error: Error }): void { openDbSourceRequest?.result?.close(); openDbTargetRequest?.result?.close(); // this.error resolveCallback(0); } function performMerge(): void { try { const objects: { value: object; primaryKey: IDBValidKey }[] = []; const sourceTransaction: IDBTransaction = openDbSourceRequest.result.transaction(fsObjectStoreName, "readonly"); sourceTransaction.onerror = handleError; const cursorRequest: IDBRequest<IDBCursorWithValue | null> = sourceTransaction .objectStore(fsObjectStoreName) .openCursor(); cursorRequest.onsuccess = () => { const cursor: IDBCursorWithValue | null = cursorRequest.result; if (cursor == null) { try { let mergedObjectsCount: number = 0; const targetTransaction: IDBTransaction = openDbTargetRequest.result.transaction( fsObjectStoreName, "readwrite" ); const targetObjectStore: IDBObjectStore = targetTransaction.objectStore(fsObjectStoreName); targetTransaction.onerror = handleError; targetTransaction.oncomplete = () => { openDbSourceRequest.result.close(); openDbTargetRequest.result.close(); return resolveCallback(mergedObjectsCount); }; for (const object of objects) { const countRequest: IDBRequest<number> = targetObjectStore.count(object.primaryKey); countRequest.onsuccess = () => { if (countRequest.result === 0) { ++mergedObjectsCount; targetObjectStore.add(object.value, object.primaryKey); } }; } } catch (error) { // istanbul ignore next handleError.call({ error }); } } else { objects.push({ value: cursor.value, primaryKey: cursor.primaryKey .toString() .replace(`${writableDataPathPreload}/`, `${writableDataPathStandard}/`), }); cursor.continue(); } }; cursorRequest.onerror = handleError; } catch (error) { // istanbul ignore next handleError.call({ error }); } } return new Promise((resolve) => { resolveCallback = resolve; openDbSourceRequest = indexedDB.open(writableDataPathPreload); openDbSourceRequest.onupgradeneeded = () => { try { openDbSourceRequest.result.createObjectStore(fsObjectStoreName); } catch (error) { // Ignored } }; openDbSourceRequest.onsuccess = () => { if (!Array.from(openDbSourceRequest.result.objectStoreNames).includes(fsObjectStoreName)) { return resolve(0); } openDbTargetRequest = indexedDB.open(writableDataPathStandard); openDbTargetRequest.onupgradeneeded = () => { try { openDbTargetRequest.result.createObjectStore(fsObjectStoreName); } catch (error) { // Ignored } }; openDbTargetRequest.onsuccess = () => { performMerge(); }; openDbTargetRequest.onblocked = openDbTargetRequest.onerror = handleError; }; openDbSourceRequest.onblocked = openDbSourceRequest.onerror = handleError; }); } function syncFSPromisified(populate: boolean, initialPopulation: boolean): Promise<void> { fsSyncInProgress = true; return new Promise((resolve, reject) => { // Merge with data coming from preloading workers if needed (!preloading && populate ? syncFSMergePreloadedData() : Promise.resolve(0)) .then((mergedObjects) => { if (!preloading && populate && !initialPopulation && mergedObjects === 0) { fsSyncInProgress = false; return resolve(); } FS.syncfs(populate, (error) => { fsSyncInProgress = false; // istanbul ignore if if (error != null) { return reject(error); } resolve(); }); }) .catch(reject); }); } function syncFS(populate: boolean, initialPopulation: boolean = false): Promise<void> { // istanbul ignore if if (fsSyncInProgress) { return fsSyncPromise.then(() => { fsSyncPromise = syncFSPromisified(populate, initialPopulation); }); } else { fsSyncPromise = syncFSPromisified(populate, initialPopulation); return fsSyncPromise; } } return { loadLibrary, createContext, setSettings, setImageSettings, workOnScanQueue, workOnParseQueue, addScanWorkUnit, addParseWorkUnit, clearSession, createBlurryTable, reset, }; } // istanbul ignore next export function engineWorkerFunction(): void { const engineInstance: Engine = engine(); onmessage = (e) => { // Setting settings triggers license key verification and activation: delay until first frame processed const data: EngineReceivedMessageData = e.data; switch (data.type) { case "load-library": // tslint:disable-next-line: no-floating-promises engineInstance.loadLibrary(data.deviceId, data.libraryLocation, data.path, data.preload, data.deviceModelName); break; case "create-context": engineInstance.createContext(data.delayedRegistration, data.licenseKey); break; case "settings": engineInstance.setSettings( data.settings, data.blurryRecognitionAvailable, data.blurryRecognitionRequiresUpdate ); break; case "image-settings": engineInstance.setImageSettings(data.imageSettings); break; case "work": engineInstance.addScanWorkUnit({ requestId: data.requestId, data: data.data, highQualitySingleFrameMode: data.highQualitySingleFrameMode, }); break; case "parse-string": engineInstance.addParseWorkUnit({ requestId: data.requestId, dataFormat: data.dataFormat, dataString: data.dataString, options: data.options, }); break; case "clear-session": engineInstance.clearSession(); break; case "create-blurry-table": engineInstance.createBlurryTable(data.symbology); break; case "reset": engineInstance.reset(); break; default: break; } }; } export const engineWorkerBlob: Blob = new Blob( [`var Module;${engine.toString()}(${engineWorkerFunction.toString()})()`], { type: "text/javascript", } ); |