diff --git a/.gitignore b/.gitignore index 516d053..bed50ce 100644 --- a/.gitignore +++ b/.gitignore @@ -45,7 +45,6 @@ yarn.lock /src /doc /Web.config -/samples.url /samples /temp /public diff --git a/Api Reference.url b/Api Reference.url index c790c25..ba9188f 100644 --- a/Api Reference.url +++ b/Api Reference.url @@ -1,2 +1,2 @@ [InternetShortcut] -URL=https://www.dynamsoft.com/help/Barcode-Reader-WASM/ \ No newline at end of file +URL=https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.2.11 \ No newline at end of file diff --git a/README.md b/README.md index f28e0c0..42f9f69 100644 --- a/README.md +++ b/README.md @@ -1,56 +1,56 @@ -# Barcode Reader for Your Website +# Barcode Reader for Your Website - User Guide -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. With its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. +[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. ![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) ![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) ![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) ![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) -Once integrated, your users can open your website in a browser, access their cameras and read barcodes directly from the video input. +Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. -In this guide, you will learn step by step on how to integrate this library into your website. +In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. Table of Contents * [Hello World - Simplest Implementation](#hello-world---simplest-implementation) * [Building your own page](#building-your-own-page) - * [Include the library](#include-the-library) - * [Configure the library](#configure-the-library) - * [Interact with the library](#interact-with-the-library) + * [Include the SDK](#include-the-sdk) + * [Configure the SDK](#configure-the-sdk) + * [Interact with the SDK](#interact-with-the-sdk) * [Customize the UI](#customize-the-ui-optional) * [API Documentation](#api-documentation) * [System Requirements](#system-requirements) -* [Advanced Usage](#advanced-usage) * [How to Upgrade](#how-to-upgrade) +* [Next Steps](#next-steps) **Popular Examples** -* Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.2/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.0.2&utm_source=github) -* Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-angular.html?ver=9.0.2&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.2/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.0.2&utm_source=github) -* React App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.0.2&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.2/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.0.2&utm_source=github) -* Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.0.2&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.2/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.0.2&utm_source=github) -* PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.0.2&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.2/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.0.2&utm_source=github) -* Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/use-cases.html?ver=latest#read-the-pdf417-barcode-on-the-drivers-license?ver=9.0.2&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.2/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.0.2&utm_source=github) -* Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/use-cases.html?ver=latest#read-barcodes-and-fill-form-fields?ver=9.0.2&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.2/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.0.2&utm_source=github) +* Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.11/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.2.11&utm_source=github) +* Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-angular.html?ver=9.2.11&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.11/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.2.11&utm_source=github) +* React App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.2.11&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.11/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.2.11&utm_source=github) +* Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.2.11&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.11/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.2.11&utm_source=github) +* PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.2.11&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.11/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.2.11&utm_source=github) +* Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/use-cases.html?ver=latest#read-the-pdf417-barcode-on-the-drivers-license?ver=9.2.11&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.11/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.2.11&utm_source=github) +* Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/use-cases.html?ver=latest#read-barcodes-and-fill-form-fields?ver=9.2.11&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.11/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.2.11&utm_source=github) You can also: -* Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.0.2&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -* Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.0.2&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.0.2/) +* Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.2.11&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) +* Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.2.11&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.2.11/) ## Hello World - Simplest Implementation -Let's start with the "Hello World" example of the library which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. +Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. * Basic Requirements * Internet connection * [A supported browser](#system-requirements) * Camera access -### Step One: Check the code of the example +### Understand the code The complete code of the "Hello World" example is shown below @@ -59,11 +59,11 @@ The complete code of the "Hello World" example is shown below - + + ``` * UNPKG ```html - + ``` -#### Host the library yourself +#### Host the SDK yourself -Besides using the CDN, you can also download the library and host its files on your own website / server before including it in your application. +Besides using the CDN, you can also download the SDK and host its files on your own website / server before including it in your application. -Options to download the library: +Options to download the SDK: * From the website - Download the JavaScript Package + Download the JavaScript Package * yarn @@ -171,10 +171,10 @@ Options to download the library: npm install dynamsoft-javascript-barcode --save ``` -Depending on how you downloaded the library and where you put it, you can typically include it like this: +Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: ```html - + ``` or @@ -183,42 +183,46 @@ or ``` -Read more on [how to host the library](https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/advanced-usage.html?ver=9.0.2&utm_source=github&product=dbr&package=js#hosting-the-library). +or + +```ts +import { BarcodeScanner } from 'dynamsoft-javascript-barcode'; +``` -### Configure the library +### Configure the SDK -Before using the library, you need to configure a few things. +Before using the SDK, you need to configure a few things. #### Specify the license -The library requires a license to work, use the API `license` to specify a license key. +The SDK requires a license to work, use the API `license` to specify a license key. ```javascript Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; ``` -To test the library, you can request a 30-day trial license via the [customer portal](https://www.dynamsoft.com/customer/license/trialLicense?ver=9.0.2&utm_source=github&product=dbr&package=js). +To test the SDK, you can request a 30-day trial license via the [customer portal](https://www.dynamsoft.com/customer/license/trialLicense?ver=9.2.11&utm_source=github&product=dbr&package=js). -> If you registered a Dynamsoft account and downloaded the library from the official website, Dynamsoft will generate a 30-day trial license for you and put the license key into all the samples that come with the library. +> If you registered a Dynamsoft account and downloaded the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you and put the license key into all the samples that come with the SDK. #### Specify the location of the "engine" files This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file. -The purpose is to tell the library where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: +The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: ```javascript //The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.0.2/dist/"; +Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.2.11/dist/"; ``` -### Interact with the library +### Interact with the SDK #### Create a `BarcodeScanner` object -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the library. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. +You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the SDK. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. -To use the library, we first create a `BarcodeScanner` object. +To use the SDK, we first create a `BarcodeScanner` object. ```javascript Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; @@ -258,16 +262,19 @@ await scanner.setResolution(1280, 720); ```javascript // Sets up the scanner behavior let scanSettings = await scanner.getScanSettings(); -// Disregards duplicated results found in a specified time period (in milliseconds) -scanSettings.duplicateForgetTime = 5000; -// Sets a scan interval in milliseconds so the library may release the CPU from time to time +// Disregards duplicated results found in a specified time period (in milliseconds). +scanSettings.duplicateForgetTime = 5000; // The default is 3000 +// Sets a scan interval in milliseconds so the SDK may release the CPU from time to time. // (setting this value larger is a simple way to save battery power and reduce device heating). -scanSettings.intervalTime = 100; +scanSettings.intervalTime = 100; // The default is 0. +// Sets captureAndDecodeInParallel to false, which tells the SDK not to acquire the next frame while decoding the first. +// This is another way to save battery power and is recommended on low-end phones. However, it does slow down the decoding speed. +scanSettings.captureAndDecodeInParallel = false; // The default is true. await scanner.updateScanSettings(scanSettings); ``` ```javascript -// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance" and "coverage" +// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance", "coverage", "dense" and "distance" await scanner.updateRuntimeSettings("speed"); // Makes changes to the template. The code below demonstrates how to specify enabled symbologies @@ -286,8 +293,6 @@ As you can see from the above code snippets, there are three types of configurat * `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. -> Find the full list of the runtime settings here. - ```javascript await barcodeScanner.updateRuntimeSettings("speed"); //await barcodeScanner.updateRuntimeSettings("balance"); //alternative @@ -303,7 +308,9 @@ As you can see from the above code snippets, there are three types of configurat Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - See also [settings samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/parameter-settings.html?ver=9.0.2&utm_source=github). + See also [settings samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/parameter-settings.html?ver=9.2.11&utm_source=github). + +> Find the full list of the runtime settings here. ### Customize the UI (optional) @@ -332,7 +339,7 @@ The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr. document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button ``` -* Build the UI element into your own web page and specify it with the API `setUIElement(HTMLElement)`. +* Build the UI element from scratch and connect it to the SDK with the API `setUIElement(HTMLElement)`. * Embed the video @@ -361,7 +368,7 @@ The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr. * Add the camera list and resolution list - If the class names for these lists match the default ones, `dce-sel-camera` and `dce-sel-resolution` , the library will automatically populate the lists and handle the camera/resolution switching. + If the class names for these lists match the default ones, `dce-sel-camera` and `dce-sel-resolution` , the SDK will automatically populate the lists and handle the camera/resolution switching. ```html
@@ -373,7 +380,7 @@ The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr. [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) ```html -
+

@@ -383,39 +390,47 @@ The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr. [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - > By default, 8 hard-coded resolutions are populated as options. You can show only a custom set of options by hardcoding them. + > By default, only 3 hard-coded resolutions (3840 x 2160, 1920 x 1080, 1280 x 720), are populated as options. You can show a customized set of options by hardcoding them. ```html ``` [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the library will then use it to show the actual resolution. + > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the cloest supported resolution. As a result, the selected resolution may not be the actual resolution. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the SDK will then use it to show the **actual resolution**. -See also [UI customization samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/ui-customization.html?ver=9.0.2&utm_source=github). + See also [UI customization samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/ui-customization.html?ver=9.2.11&utm_source=github). ## API Documentation -You can check out the detailed documentation about the APIs of the library at -[https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.0.2](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.0.2). +You can check out the detailed documentation about the APIs of the SDK at +[https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.2.11](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.2.11). ## System Requirements -This library requires the following features which are supported by all modern mainstream browsers: +DBR requires the following features to work: + +* Secure context (HTTPS deployment) + + When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons + + * Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. + > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. + + * Dynamsoft License requires a secure context to work. * `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - The above four features are required for the library to work. + The above four features are required for the SDK to work. * `MediaDevices`/`getUserMedia` - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/BarcodeScanner.html?ver=9.0.2&utm_source=github#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. + This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/BarcodeScanner.html?ver=9.2.11&utm_source=github#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. * `getSettings` @@ -432,16 +447,20 @@ The following table is a list of supported browsers based on the above requireme 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - 2 On Edge, due to strict Same-origin policy, you must host the library files on the same domain as your web page. + 2 On Edge, due to strict Same-origin policy, you must host the SDK files on the same domain as your web page. - 3 Safari 11.2.2 ~ 11.2.6 are not supported. + 3 Safari v11.x already has the required features, but it has many other issues, so we recommend v12+. -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the library. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. +Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. -## Advanced Usage +## How to Upgrade -In addition to the above basic settings, the library has many more settings and options that you can adjust to best suit your usage. To read more, please see [advanced usage](https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/advanced-usage.html?ver=9.0.2&utm_source=github). +If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/programming/javascript/upgrade-guide/?ver=9.2.11&utm_source=github). -## How to Upgrade +## Next Steps + +Now that you have got the SDK integrated, you can choose to move forward in the following directions -If you want to upgrade the library from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/programming/javascript/upgrade-guide/?ver=9.0.2&utm_source=github). +1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=latest) +2. Learn how to make use of the [SDK features](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/explore-features/index.html?ver=latest) +3. See how the SDK works in [Popular Use Cases](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-cases/index.html?ver=latest) diff --git a/dist/dbr-9.0.2.browser.worker.js b/dist/dbr-9.0.2.browser.worker.js deleted file mode 100644 index f302744..0000000 --- a/dist/dbr-9.0.2.browser.worker.js +++ /dev/null @@ -1,11 +0,0 @@ -/*! - * Dynamsoft JavaScript Library - * @product Dynamsoft Barcode Reader JS Edition - * @website http://www.dynamsoft.com - * @copyright Copyright 2022, Dynamsoft Corporation - * @author Dynamsoft - * @version 9.0.2 (js 20220505) - * @fileoverview Dynamsoft JavaScript Library for Barcode Reader - * More info on DBR JS: https://www.dynamsoft.com/barcode-reader/sdk-javascript/ - */ -!function(){"use strict";const e=self,t=e=>e&&"object"==typeof e&&"function"==typeof e.then;class r extends Promise{constructor(e){let r,n;super(((e,t)=>{r=e,n=t})),this._s="pending",this.resolve=e=>{this.isPending&&(t(e)?this.task=e:(this._s="fulfilled",r(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",n(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let r;this._task=e,t(e)?r=e:"function"==typeof e&&(r=new Promise(e)),r&&(async()=>{try{const t=await r;e===this._task&&this.resolve(t)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}}var n=function(){try{if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof webkitIndexedDB)return webkitIndexedDB;if("undefined"!=typeof mozIndexedDB)return mozIndexedDB;if("undefined"!=typeof OIndexedDB)return OIndexedDB;if("undefined"!=typeof msIndexedDB)return msIndexedDB}catch(e){return}}();function o(e,t){e=e||[],t=t||{};try{return new Blob(e,t)}catch(o){if("TypeError"!==o.name)throw o;for(var r=new("undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder),n=0;n=43)}})).catch((function(){return!1}))}(e).then((function(e){return u=e,u}))}function y(e){var t=l[e.name],r={};r.promise=new Promise((function(e,t){r.resolve=e,r.reject=t})),t.deferredOperations.push(r),t.dbReady?t.dbReady=t.dbReady.then((function(){return r.promise})):t.dbReady=r.promise}function p(e){var t=l[e.name].deferredOperations.pop();if(t)return t.resolve(),t.promise}function b(e,t){var r=l[e.name].deferredOperations.pop();if(r)return r.reject(t),r.promise}function v(e,t){return new Promise((function(r,o){if(l[e.name]=l[e.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},e.db){if(!t)return r(e.db);y(e),e.db.close()}var a=[e.name];t&&a.push(e.version);var s=n.open.apply(n,a);t&&(s.onupgradeneeded=function(t){var r=s.result;try{r.createObjectStore(e.storeName),t.oldVersion<=1&&r.createObjectStore(d)}catch(r){if("ConstraintError"!==r.name)throw r;console.warn('The database "'+e.name+'" has been upgraded from version '+t.oldVersion+" to version "+t.newVersion+', but the storage "'+e.storeName+'" already exists.')}}),s.onerror=function(e){e.preventDefault(),o(s.error)},s.onsuccess=function(){var t=s.result;t.onversionchange=function(e){e.target.close()},r(t),p(e)}}))}function w(e){return v(e,!1)}function _(e){return v(e,!0)}function S(e,t){if(!e.db)return!0;var r=!e.db.objectStoreNames.contains(e.storeName),n=e.versione.db.version;if(n&&(e.version!==t&&console.warn('The database "'+e.name+"\" can't be downgraded from version "+e.db.version+" to version "+e.version+"."),e.version=e.db.version),o||r){if(r){var a=e.db.version+1;a>e.version&&(e.version=a)}return!0}return!1}function k(e){var t=function(e){for(var t=e.length,r=new ArrayBuffer(t),n=new Uint8Array(r),o=0;o0&&(!e.db||"InvalidStateError"===o.name||"NotFoundError"===o.name))return Promise.resolve().then((()=>{if(!e.db||"NotFoundError"===o.name&&!e.db.objectStoreNames.contains(e.storeName)&&e.version<=e.db.version)return e.db&&(e.version=e.db.version+1),_(e)})).then((()=>function(e){y(e);for(var t=l[e.name],r=t.forages,n=0;n(e.db=t,S(e)?_(e):t))).then((n=>{e.db=t.db=n;for(var o=0;o{throw b(e,t),t}))}(e).then((function(){D(e,t,r,n-1)})))).catch(r);r(o)}}var M={_driver:"asyncStorage",_initStorage:function(e){var t=this,r={db:null};if(e)for(var n in e)r[n]=e[n];var o=l[r.name];o||(o={forages:[],db:null,dbReady:null,deferredOperations:[]},l[r.name]=o),o.forages.push(t),t._initReady||(t._initReady=t.ready,t.ready=I);var a=[];function s(){return Promise.resolve()}for(var i=0;i{const r=l[e.name],n=r.forages;r.db=t;for(var o=0;o{if(!t.objectStoreNames.contains(e.storeName))return;const r=t.version+1;y(e);const o=l[e.name],a=o.forages;t.close();for(let e=0;e{const a=n.open(e.name,r);a.onerror=e=>{a.result.close(),o(e)},a.onupgradeneeded=()=>{a.result.deleteObjectStore(e.storeName)},a.onsuccess=()=>{const e=a.result;e.close(),t(e)}}));return s.then((e=>{o.db=e;for(let t=0;t{throw(b(e,t)||Promise.resolve()).catch((()=>{})),t}))})):t.then((t=>{y(e);const r=l[e.name],o=r.forages;t.close();for(var a=0;a{var o=n.deleteDatabase(e.name);o.onerror=()=>{const e=o.result;e&&e.close(),r(o.error)},o.onblocked=()=>{console.warn('dropInstance blocked for database "'+e.name+'" until all open connections are closed')},o.onsuccess=()=>{const e=o.result;e&&e.close(),t(e)}}));return s.then((e=>{r.db=e;for(var t=0;t{throw(b(e,t)||Promise.resolve()).catch((()=>{})),t}))}))}else o=Promise.reject("Invalid arguments");return a(o,t),o}};const x=new Map;function C(e,t){let r=e.name+"/";return e.storeName!==t.storeName&&(r+=e.storeName+"/"),r}var P={_driver:"tempStorageWrapper",_initStorage:async function(e){const t={};if(e)for(let r in e)t[r]=e[r];const r=t.keyPrefix=C(e,this._defaultConfig);this._dbInfo=t,x.has(r)||x.set(r,new Map)},getItem:function(e,t){e=i(e);const r=this.ready().then((()=>x.get(this._dbInfo.keyPrefix).get(e)));return a(r,t),r},setItem:function(e,t,r){e=i(e);const n=this.ready().then((()=>(void 0===t&&(t=null),x.get(this._dbInfo.keyPrefix).set(e,t),t)));return a(n,r),n},removeItem:function(e,t){e=i(e);const r=this.ready().then((()=>{x.get(this._dbInfo.keyPrefix).delete(e)}));return a(r,t),r},clear:function(e){const t=this.ready().then((()=>{const e=this._dbInfo.keyPrefix;x.has(e)&&x.delete(e)}));return a(t,e),t},length:function(e){const t=this.ready().then((()=>x.get(this._dbInfo.keyPrefix).size));return a(t,e),t},keys:function(e){const t=this.ready().then((()=>[...x.get(this._dbInfo.keyPrefix).keys()]));return a(t,e),t},dropInstance:function(e,t){if(t=c.apply(this,arguments),!(e="function"!=typeof e&&e||{}).name){const t=this.config();e.name=e.name||t.name,e.storeName=e.storeName||t.storeName}let r;return r=e.name?new Promise((t=>{e.storeName?t(C(e,this._defaultConfig)):t(`${e.name}/`)})).then((e=>{x.delete(e)})):Promise.reject("Invalid arguments"),a(r,t),r}};const N=(e,t)=>{const r=e.length;let n=0;for(;n{}))}config(e){if("object"==typeof e){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(let t in e){if("storeName"===t&&(e[t]=e[t].replace(/\W/g,"_")),"version"===t&&"number"!=typeof e[t])return new Error("Database version must be a number.");this._config[t]=e[t]}return!("driver"in e)||!e.driver||this.setDriver(this._config.driver)}return"string"==typeof e?this._config[e]:this._config}defineDriver(e,t,r){const n=new Promise((function(t,r){try{const n=e._driver,o=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!e._driver)return void r(o);const s=F.concat("_initStorage");for(let t=0,n=s.length;t(null===t._ready&&(t._ready=t._initDriver()),t._ready)));return s(r,e,e),r}setDriver(e,t,r){const n=this;R(e)||(e=[e]);const o=this._getSupportedDrivers(e);function a(){n._config.driver=n.driver()}function i(e){return n._extend(e),a(),n._ready=n._initStorage(n._config),n._ready}const c=null!==this._driverSet?this._driverSet.catch((()=>Promise.resolve())):Promise.resolve();return this._driverSet=c.then((()=>{const e=o[0];return n._dbInfo=null,n._ready=null,n.getDriver(e).then((e=>{n._driver=e._driver,a(),n._wrapLibraryMethodsWithReady(),n._initDriver=function(e){return function(){let t=0;return function r(){for(;t{a();const e=new Error("No available storage method found.");return n._driverSet=Promise.reject(e),n._driverSet})),s(this._driverSet,t,r),this._driverSet}supports(e){return!!B[e]}_extend(e){J(this,e)}_getSupportedDrivers(e){const t=[];for(let r=0,n=e.length;r{let n,o,a,s,i,c,d,u,l,f,m=e.btoa,h=e.atob,g=t.bd;const y=["https://mlts.dynamsoft.com/","https://slts.dynamsoft.com/"];let p,b,v,w,_,S,k,I,D,M,x,C,P,N,R,T,B,E,O=y,j=!1,F=Promise.resolve(),A=t.log&&((...e)=>{try{t.log.apply(null,e)}catch(e){setTimeout((()=>{throw e}),0)}})||(()=>{}),U=g&&A||(()=>{}),J=e=>e.join(""),W={a:[80,88,27,82,145,164,199,211],b:[187,87,89,128,150,44,190,213],c:[89,51,74,53,99,72,82,118],d:[99,181,118,158,215,103,76,117],e:[99,51,86,105,100,71,120,108],f:[97,87,49,119,98,51,74,48,83,50,86,53],g:[81,85,86,84,76,85,100,68,84,81,32,32],h:[90,87,53,106,99,110,108,119,100,65,32,32],i:[90,71,86,106,99,110,108,119,100,65,32,32],j:[97,88,89,32],k:[29,83,122,137,5,180,157,114],l:[100,71,70,110,84,71,86,117,90,51,82,111]},z=()=>e[J(W.c)][J(W.e)][J(W.f)]("raw",new Uint8Array(W.a.concat(W.b,W.d,W.k)),J(W.g),!0,[J(W.h),J(W.i)]),L=async t=>{if(e[J(W.c)]&&e[J(W.c)][J(W.e)]&&e[J(W.c)][J(W.e)][J(W.f)]){let r=h(t),n=new Uint8Array(r.length);for(let e=0;e{if(e[J(W.c)]&&e[J(W.c)][J(W.e)]&&e[J(W.c)][J(W.e)][J(W.f)]){let r=new Uint8Array(t.length);for(let e=0;eh(h(e.replace(/\n/g,"+").replace(/\s/g,"=")).substring(1)),Z=e=>m(String.fromCharCode(97+25*Math.random())+m(e)).replace(/\+/g,"\n").replace(/=/g," "),K=()=>{if(R)return R;if(e.crypto){let t=new Uint8Array(36);e.crypto.getRandomValues(t);let r="";for(let e=0;e<36;++e){let n=t[e]%36;r+=n<10?n:String.fromCharCode(n+87)}return r}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},G="Failed to connect to the Dynamsoft License Server. The cached license has expired. Please get connected to the network as soon as possible or contact the site administrator for more information.",X="Failed to connect to the Dynamsoft License Server: network timed out. Check your Internet connection or [contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.",q="Failed to connect to the Dynamsoft License Server: network timed out. Check your Internet connection or contact the site administrator for more information.",Y="Failed to connect to the Dynamsoft License Server: network connection error. Check your Internet connection or [contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.",Q="Failed to connect to the Dynamsoft License Server: network connection error. Check your Internet connection or contact the site administrator for more information.",ee="Your system date and time appear to have been changed, causing the license to fail. Please correct the system data and time and try again.",te=async()=>{await(async()=>{S||(S=H)})(),J=e=>h(String.fromCharCode.apply(null,e).replace(/\n/g,"+").replace(/\s/g,"="));{let e=await S.createInstance({name:n+"jshello"});await e.setItem(n+"jshello","available")}if(I=await S.createInstance({name:"dynamltsinfo"}),D=R?null:m(m("v2")+String.fromCharCode(d.charCodeAt(d.length/2)+1)+m(d)),M=m(String.fromCharCode(s.charCodeAt(0)+10)+m(n)+m(s)+a+m(""+c)),!R){try{let e=await I.getItem(D);e&&([u,w]=JSON.parse(await V(e)))}catch(e){}try{null==u&&(u=K())}catch(e){}}k=await S.createInstance({name:"dynamdlsuns"+m(m("v2"))+m(String.fromCharCode(s.charCodeAt(0)+10)+m(n)+m(s)+a+m(""+c))});try{i=await I.getItem(M)}catch(e){}},re=async e=>{T||(T=(async()=>{try{let t={pd:n,vm:a,dt:c||"browser",ed:"javascript",cu:u,ad:d,os:l,fn:f};v&&(t.rmk=v),s&&(t=-1!=s.indexOf("-")?{...t,hs:s}:{...t,og:s});let r={};if(w&&!R){let e=await I.getItem(D);e&&([u,w]=JSON.parse(await V(e))),r["lts-time"]=w}b&&(t.sp=b);let o=await Promise.race([(async()=>{let n,o=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ");w&&!R&&(I.setItem(D,await Z(JSON.stringify([u,o]))),w=o);let a,s="auth/?ext="+encodeURIComponent(m(JSON.stringify(t))),c=!1,d=!1,l=async e=>{if(e&&!e.ok)try{let t=await e.text();if(t){let e=JSON.parse(t);e.errorCode&&(a=e,e.errorCode>100&&e.errorCode<200&&(i=null,c=!0,d=!0))}}catch(e){}};try{n=await Promise.race([fetch(O[0]+s,{headers:r,cache:e?"reload":"default",mode:"cors"}),new Promise(((e,t)=>setTimeout(t,1e4)))]),await l(n)}catch(e){}if(!(i||n&&n.ok||c))try{n=await Promise.race([fetch(O[1]+s,{headers:r,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await l(n)}catch(e){}if(!(i||n&&n.ok||c))try{n=await Promise.race([fetch(O[0]+s,{headers:r,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await l(n)}catch(e){}a&&151==a.errorCode&&(R||I.removeItem(D),I.removeItem(M),u=K(),t.cu=u,w=void 0,s="auth/?ext="+encodeURIComponent(m(JSON.stringify(t))),n=await Promise.race([fetch(O[0]+s,{headers:r,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await l(n));(()=>{if(!n||!n.ok){let e;d&&I.setItem(M,""),a?111==a.errorCode?e=a.message:(e=a.message.trim(),e.endsWith(".")||(e+="."),e=p?`An error occurred during authorization: ${e} [Contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.`:`An error occurred during authorization: ${e} Contact the site administrator for more information.`):e=p?Y:Q;let t=Error(e);throw a&&a.errorCode&&(t.ltsErrorCode=a.errorCode),t}})();let f=await n.text();try{w||R||(I.setItem(D,await Z(JSON.stringify([u,o]))),w=o),I.setItem(M,f)}catch(e){}return f})(),new Promise(((e,t)=>{let r;r=p?X:q,setTimeout((()=>t(new Error(r))),i?3e3:15e3)}))]);i=o}catch(e){g&&console.error(e),_=e}T=null})()),await T,B||(B=Date.now()+6e4)},ne=async()=>{E||(E=(async()=>{if(U(u),!i){if(!j)throw A(_.message),_;return}let e={dm:d};g&&(e.bd=!0),e.brtk=!0,e.ls=O[0],s&&(e.hs=s),e.cu=u,f&&(e.fn=f),n&&(e.pd=n),c&&(e.dt=c),l&&(e.os=l),U(i);try{let t=JSON.parse(await L(i));t.ba&&(e.ba=t.ba),t.usu&&(e.usu=t.usu),t.trial&&(e.trial=t.trial),t.its&&(e.its=t.its),1==e.trial&&t.msg?e.msg=t.msg:_?e.msg=_.message||_:t.msg&&(e.msg=t.msg),e.ar=t.in,e.bafc=!!_}catch(e){}U(e);try{await x(e)}catch(e){}await oe(),j||(j=!0),E=null})()),await E},oe=async()=>{let e=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),t=await P();if(U(t),t&&t(F=F.then((async()=>{let r=!1;try{let n=await k.keys();if(t||(ae.isFulfilled?e&&(n=n.filter((t=>t{const a=new XMLHttpRequest;a.responseType="json",a.timeout=3e4,a.onload=()=>{r&&ae.resolve(),t({ok:!0})},a.onerror=a.ontimeout=a.onabort=()=>{t({ok:!1,status:a.status})},a.open("POST",e,!0),a.send(o.join(";"))}));if(!n.ok)throw new Error("verify failed. Status Code: "+n.status);for(let e=0;e{n=e.pd,o=e.v,a=o.split(".")[0],e.dt&&(c=e.dt),d=e.dm,s=e.l||"",l="string"!=typeof e.os?JSON.stringify(e.os):e.os,f=e.fn,"string"==typeof f&&(f=f.substring(0,50)),e.ls&&e.ls.length&&(O=e.ls,1==O.length&&O.push(O[0])),p=y===O&&(!s||"200001"===s||s.startsWith("200001-")),b=e.sp,v=e.rmk,e.lf&&(S=e.lf),e.lsu&&(u=R=e.lsu),e.fdaa&&(L=e.fdaa),e.feab&&($=e.feab),x=e.updl,C=e.mnet,P=e.mxet,await te(),await re(),await ne(),(!_||_.ltsErrorCode>=102&&_.ltsErrorCode<=120)&&ie(null,!0)},c:async()=>{let e=new Date,t=e.kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),r=await C(),n=await P();if(n&&nne()))}},s:async(e,t,r,n)=>{try{let e;if(t.startsWith("{")&&t.endsWith("}")){if(v){let e=JSON.parse(t);e.rmk=v,t=JSON.stringify(e)}e=await $(t)}else e=t;e?await k.setItem(r,e):U("ept ecpt")}catch(e){}n&&await ie(r),se&&clearTimeout(se),se=setTimeout((async()=>{await ie()}),36e4)},p:ae,r:async()=>{ae.isPending&&B&&B{await re,Z=e.trial,K=e.msg,Module[Q].init(JSON.stringify(e))},ae=()=>Module[Q].getMinExpireTime(),se=()=>Module[Q].getMaxExpireTime(),ie=new Map,ce=0,de=async function(t){const r=t.data?t.data:t,n=r.id,o=r.instanceID,a=r.body;switch(!V||"decodeBuffer"!=r.type&&"decodeFileInMemory"!=r.type||await G.c(),r.type){case"loadWasm":try{z=r.bd,L=r.engineResourcePath,Y=r.bUseFullFeature,$=r.v;let t=r.dm,n=r.l;V=r.brtk;let o,a=r.bptk;(async()=>{if(ne)throw"can't load wasm twice";ne=!0,ue("wasm loading...");let t=Date.now();await new Promise((async t=>{e.KModule=e.Module={locateFile:function(e){return"libDynamsoftBarcodeReader.wasm"==e?L+"dbr-"+$+(Y?".full":"")+".wasm":L+e},print:e=>{ue(e)},printErr:e=>{console.error(e),ue(e)},onRuntimeInitialized:t},importScripts(L+"dbr-"+$+(Y?".full":"")+".wasm.js")})),ue("wasm initialized, cost "+(Date.now()-t)+" ms"),Module=KModule,re.resolve()})();let s=async()=>{try{G=X({log:ue,bd:z}),e.scsd=G.s,r.pd="dbr",r.updl=oe,r.mnet=ae,r.mxet=se,await G.i(r)}catch(e){if(!a)throw e;V=!1,await i(),o=e.ltsErrorCode,K=e.message||e}},i=async()=>{let e={pk:n,dm:t};z&&(e.bd=!0),await oe(e)};V?await s():await i(),q.postMessage({type:"load",success:!0,version:Module[Q].getVersion(),trial:Z,ltsErrorCode:o,message:K})}catch(e){let t=e&&e.message;q.postMessage({type:"load",success:!1,ltsErrorCode:e&&e.ltsErrorCode,message:t,trial:Z,stack:z&&e?e.stack:null})}break;case"createInstance":{const e=ce++;try{let t=new Module[Q](r.bScanner,e);ie.set(e,t);let n=JSON.parse(t.getRuntimeSettings());r.bScanner?(n.localizationModes=[2,0,0,0,0,0,0,0],n.deblurLevel=0):(n.expectedBarcodesCount=512,n.scaleDownThreshold=1e5,n.timeout=1e5),Y||(n.barcodeFormatIds=238028799),t.updateRuntimeSettings(JSON.stringify(n))}catch(e){fe(e,n);break}q.postMessage({type:"task",id:n,body:{success:!0,instanceID:e}});break}case"destroyContext":try{if(!ie.get(o))break;ie.get(o).delete(),ie.delete(o)}catch(e){fe(e,n);break}q.postMessage({type:"task",id:n,body:{success:!0}});break;case"decodeBuffer":{let e,t,r,s,i=Date.now();try{e=z?Date.now():0,c=a.buffer,(d=a.stride*a.height)>ee&&(te&&Module._free(te),te=Module._malloc(d),ee=d),Module.HEAPU8.set(c.subarray(0,d),te),t=z?Date.now():0,s=JSON.parse(ie.get(o).decodeBufferPtr(te,a.width,a.height,a.stride,a.format,!(!a.config||!a.config.bScanner))),r=Date.now()}catch(e){fe(e,n);break}G&&G.p.isPending&&await Promise.race([G.p,new Promise((e=>setTimeout(e,500)))]),q.postMessage({type:"task",id:n,body:{success:!0,decodeReturn:s,buffer:a.buffer,duration:Date.now()-i}},[a.buffer.buffer]),le(["timeWorkerGetMsg: "+i,"timeBeforeSendBufferToWasm: "+e+" "+(e-i),"timeBeforeDecode: "+t+" "+(t-e),"timeFinishDecode: "+r+" "+(r-t)].join("\n"));break}case"decodeFileInMemory":{let e,t,r;try{t=z?Date.now():0,e=JSON.parse(ie.get(o).decodeFileInMemory(a.bytes)),r=z?Date.now():0}catch(e){fe(e,n);break}q.postMessage({type:"task",id:n,body:{success:!0,decodeReturn:e,duration:r-t}});break}case"clearMapDecodeRecord":try{ie.get(o).clearMapDecodeRecord()}catch(e){fe(e,n);break}q.postMessage({type:"task",id:n,body:{success:!0}});break;case"getRuntimeSettings":{let e;try{e=ie.get(o).getRuntimeSettings()}catch(e){fe(e,n);break}q.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}case"updateRuntimeSettings":{let e;try{e=JSON.parse(ie.get(o).updateRuntimeSettings(a.settings))}catch(e){fe(e,n);break}q.postMessage({type:"task",id:n,body:{success:!0,updateReturn:e}});break}case"resetRuntimeSettings":try{let e=ie.get(o);e.resetRuntimeSettings();let t=JSON.parse(e.getRuntimeSettings());e.bScanner?(t.localizationModes=[2,0,0,0,0,0,0,0],t.deblurLevel=0,t.barcodeZoneMinDistanceToImageBorders=9):(t.expectedBarcodesCount=512,t.scaleDownThreshold=1e5,t.timeout=1e5),Y||(t.barcodeFormatIds=238028799),e.updateRuntimeSettings(JSON.stringify(t))}catch(e){fe(t,n);break}q.postMessage({type:"task",id:n,body:{success:!0}});break;case"outputRuntimeSettingsToString":{let e;try{e=ie.get(o).outputSettingsToString()}catch(e){fe(e,n);break}q.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}case"initRuntimeSettingsWithString":{let e;try{e=JSON.parse(ie.get(o).initRuntimeSettingsWithString(a.settings))}catch(e){fe(e,n);break}q.postMessage({type:"task",id:n,body:{success:!0,initReturn:e}});break}case"getIntermediateResults":{let e=[];try{var s=ie.get(o).getIntermediateResults(),i=JSON.parse(s,((t,r)=>{if("bytes"===t&&"ptr"in r&&"length"in r){var n=r,o=n.ptr,a=n.length;let t=Module[Q].getBytes(o,a);return t=t.slice(0),e.push(t.buffer),t}return r}))}catch(e){fe(e,n);break}q.postMessage({type:"task",id:n,body:{success:!0,results:i}},e),ie.get(o).freeIntermediateResults();break}case"setModeArgument":{let e;try{e=JSON.parse(ie.get(o).setModeArgument(a.modeName,a.index,a.argumentName,a.argumentValue))}catch(e){fe(e,n);break}q.postMessage({type:"task",id:n,body:{success:!0,setReturn:e}});break}case"getModeArgument":{let e;try{e=JSON.parse(ie.get(o).getModeArgument(a.modeName,a.index,a.argumentName))}catch(e){fe(e,n);break}q.postMessage({type:"task",id:n,body:{success:!0,getReturn:e}});break}case"updateScanSettings":try{let e=ie.get(o),t=a.settings;e.duplicateForgetTime=t.duplicateForgetTime,e.oneDRememberFrameCount=t.oneDRememberFrameCount,e.oneDTrustFrameCount=t.oneDTrustFrameCount}catch(e){fe(e,n);break}q.postMessage({type:"task",id:n,body:{success:!0}});break;case"getScanSettings":{let e={};try{let t=ie.get(o);e.duplicateForgetTime=t.duplicateForgetTime,e.oneDRememberFrameCount=t.oneDRememberFrameCount,e.oneDTrustFrameCount=t.oneDTrustFrameCount}catch(e){fe(e,n);break}q.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}case"keepAlive":G&&await G.r();break;default:console.warn("Unmatched task: ",t)}var c,d};q.onmessage=de;let ue=e=>{q.postMessage({type:"log",message:e})},le=e=>{z&&ue(e)},fe=(e,t)=>{q.postMessage({type:"task",id:t,body:{success:!1,message:e.message,stack:e.stack}}),setTimeout((()=>{throw e}),0)}}(); diff --git a/dist/dbr-9.0.2.wasm b/dist/dbr-9.0.2.wasm deleted file mode 100644 index 19f4f3a..0000000 Binary files a/dist/dbr-9.0.2.wasm and /dev/null differ diff --git a/dist/dbr-9.2.11.browser.worker.js b/dist/dbr-9.2.11.browser.worker.js new file mode 100644 index 0000000..30ad523 --- /dev/null +++ b/dist/dbr-9.2.11.browser.worker.js @@ -0,0 +1,11 @@ +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft Barcode Reader JS Edition + * @website http://www.dynamsoft.com + * @copyright Copyright 2022, Dynamsoft Corporation + * @author Dynamsoft + * @version 9.2.11 (js 20220727) + * @fileoverview Dynamsoft JavaScript Library for Barcode Reader + * More info on DBR JS: https://www.dynamsoft.com/barcode-reader/sdk-javascript/ + */ +!function(){"use strict";const e="undefined"==typeof self,t=e?{}:self,r=e=>e&&"object"==typeof e&&"function"==typeof e.then;class n extends Promise{constructor(e){let t,n;super(((e,r)=>{t=e,n=r})),this._s="pending",this.resolve=e=>{this.isPending&&(r(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",n(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,r(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const r=await t;e===this._task&&this.resolve(r)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}}let o,i,s,a,c;if("undefined"!=typeof navigator&&(o=navigator,i=o.userAgent,s=o.platform,a=o.mediaDevices),!e){const e={init:function(){this.browser=this.searchString(this.dataBrowser)||"unknownBrowser",this.version=this.searchVersion(i)||this.searchVersion(o.appVersion)||0,this.OS=this.searchString(this.dataOS)||"unknownOS","Linux"==this.OS&&-1!=i.indexOf("Windows NT")&&(this.OS="HarmonyOS")},searchString:function(e){for(let t=0;t66||"Safari"===c.browser&&c.version>13||"OPR"===c.browser&&c.version>43||"Edge"===c.browser&&c.version>15;var u=function(){try{if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof webkitIndexedDB)return webkitIndexedDB;if("undefined"!=typeof mozIndexedDB)return mozIndexedDB;if("undefined"!=typeof OIndexedDB)return OIndexedDB;if("undefined"!=typeof msIndexedDB)return msIndexedDB}catch(e){return}}();function l(e,t){e=e||[],t=t||{};try{return new Blob(e,t)}catch(o){if("TypeError"!==o.name)throw o;for(var r=new("undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder),n=0;n=43)}})).catch((function(){return!1}))}(e).then((function(e){return p=e,p}))}function k(e){var t=b[e.name],r={};r.promise=new Promise((function(e,t){r.resolve=e,r.reject=t})),t.deferredOperations.push(r),t.dbReady?t.dbReady=t.dbReady.then((function(){return r.promise})):t.dbReady=r.promise}function I(e){var t=b[e.name].deferredOperations.pop();if(t)return t.resolve(),t.promise}function x(e,t){var r=b[e.name].deferredOperations.pop();if(r)return r.reject(t),r.promise}function M(e,t){return new Promise((function(r,n){if(b[e.name]=b[e.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},e.db){if(!t)return r(e.db);k(e),e.db.close()}var o=[e.name];t&&o.push(e.version);var i=u.open.apply(u,o);t&&(i.onupgradeneeded=function(t){var r=i.result;try{r.createObjectStore(e.storeName),t.oldVersion<=1&&r.createObjectStore(y)}catch(r){if("ConstraintError"!==r.name)throw r;console.warn('The database "'+e.name+'" has been upgraded from version '+t.oldVersion+" to version "+t.newVersion+', but the storage "'+e.storeName+'" already exists.')}}),i.onerror=function(e){e.preventDefault(),n(i.error)},i.onsuccess=function(){var t=i.result;t.onversionchange=function(e){e.target.close()},r(t),I(e)}}))}function D(e){return M(e,!1)}function C(e){return M(e,!0)}function P(e,t){if(!e.db)return!0;var r=!e.db.objectStoreNames.contains(e.storeName),n=e.versione.db.version;if(n&&(e.version!==t&&console.warn('The database "'+e.name+"\" can't be downgraded from version "+e.db.version+" to version "+e.version+"."),e.version=e.db.version),o||r){if(r){var i=e.db.version+1;i>e.version&&(e.version=i)}return!0}return!1}function N(e){var t=function(e){for(var t=e.length,r=new ArrayBuffer(t),n=new Uint8Array(r),o=0;o0&&(!e.db||"InvalidStateError"===o.name||"NotFoundError"===o.name))return Promise.resolve().then((()=>{if(!e.db||"NotFoundError"===o.name&&!e.db.objectStoreNames.contains(e.storeName)&&e.version<=e.db.version)return e.db&&(e.version=e.db.version+1),C(e)})).then((()=>function(e){k(e);for(var t=b[e.name],r=t.forages,n=0;n(e.db=t,P(e)?C(e):t))).then((n=>{e.db=t.db=n;for(var o=0;o{throw x(e,t),t}))}(e).then((function(){O(e,t,r,n-1)})))).catch(r);r(o)}}var B={_driver:"asyncStorage",_initStorage:function(e){var t=this,r={db:null};if(e)for(var n in e)r[n]=e[n];var o=b[r.name];o||(o={forages:[],db:null,dbReady:null,deferredOperations:[]},b[r.name]=o),o.forages.push(t),t._initReady||(t._initReady=t.ready,t.ready=R);var i=[];function s(){return Promise.resolve()}for(var a=0;a{const r=b[e.name],n=r.forages;r.db=t;for(var o=0;o{if(!t.objectStoreNames.contains(e.storeName))return;const r=t.version+1;k(e);const n=b[e.name],o=n.forages;t.close();for(let e=0;e{const o=u.open(e.name,r);o.onerror=e=>{o.result.close(),n(e)},o.onupgradeneeded=()=>{o.result.deleteObjectStore(e.storeName)},o.onsuccess=()=>{const e=o.result;e.close(),t(e)}}));return i.then((e=>{n.db=e;for(let t=0;t{throw(x(e,t)||Promise.resolve()).catch((()=>{})),t}))})):t.then((t=>{k(e);const r=b[e.name],n=r.forages;t.close();for(var o=0;o{var n=u.deleteDatabase(e.name);n.onerror=()=>{const e=n.result;e&&e.close(),r(n.error)},n.onblocked=()=>{console.warn('dropInstance blocked for database "'+e.name+'" until all open connections are closed')},n.onsuccess=()=>{const e=n.result;e&&e.close(),t(e)}}));return i.then((e=>{r.db=e;for(var t=0;t{throw(x(e,t)||Promise.resolve()).catch((()=>{})),t}))}))}else n=Promise.reject("Invalid arguments");return f(n,t),n}};const E=new Map;function T(e,t){let r=e.name+"/";return e.storeName!==t.storeName&&(r+=e.storeName+"/"),r}var F={_driver:"tempStorageWrapper",_initStorage:async function(e){const t={};if(e)for(let r in e)t[r]=e[r];const r=t.keyPrefix=T(e,this._defaultConfig);this._dbInfo=t,E.has(r)||E.set(r,new Map)},getItem:function(e,t){e=m(e);const r=this.ready().then((()=>E.get(this._dbInfo.keyPrefix).get(e)));return f(r,t),r},setItem:function(e,t,r){e=m(e);const n=this.ready().then((()=>(void 0===t&&(t=null),E.get(this._dbInfo.keyPrefix).set(e,t),t)));return f(n,r),n},removeItem:function(e,t){e=m(e);const r=this.ready().then((()=>{E.get(this._dbInfo.keyPrefix).delete(e)}));return f(r,t),r},clear:function(e){const t=this.ready().then((()=>{const e=this._dbInfo.keyPrefix;E.has(e)&&E.delete(e)}));return f(t,e),t},length:function(e){const t=this.ready().then((()=>E.get(this._dbInfo.keyPrefix).size));return f(t,e),t},keys:function(e){const t=this.ready().then((()=>[...E.get(this._dbInfo.keyPrefix).keys()]));return f(t,e),t},dropInstance:function(e,t){if(t=g.apply(this,arguments),!(e="function"!=typeof e&&e||{}).name){const t=this.config();e.name=e.name||t.name,e.storeName=e.storeName||t.storeName}let r;return r=e.name?new Promise((t=>{e.storeName?t(T(e,this._defaultConfig)):t(`${e.name}/`)})).then((e=>{E.delete(e)})):Promise.reject("Invalid arguments"),f(r,t),r}};const j=(e,t)=>{const r=e.length;let n=0;for(;n{}))}config(e){if("object"==typeof e){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(let t in e){if("storeName"===t&&(e[t]=e[t].replace(/\W/g,"_")),"version"===t&&"number"!=typeof e[t])return new Error("Database version must be a number.");this._config[t]=e[t]}return!("driver"in e)||!e.driver||this.setDriver(this._config.driver)}return"string"==typeof e?this._config[e]:this._config}defineDriver(e,t,r){const n=new Promise((function(t,r){try{const n=e._driver,o=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!e._driver)return void r(o);const i=z.concat("_initStorage");for(let t=0,n=i.length;t(null===t._ready&&(t._ready=t._initDriver()),t._ready)));return h(r,e,e),r}setDriver(e,t,r){const n=this;A(e)||(e=[e]);const o=this._getSupportedDrivers(e);function i(){n._config.driver=n.driver()}function s(e){return n._extend(e),i(),n._ready=n._initStorage(n._config),n._ready}const a=null!==this._driverSet?this._driverSet.catch((()=>Promise.resolve())):Promise.resolve();return this._driverSet=a.then((()=>{const e=o[0];return n._dbInfo=null,n._ready=null,n.getDriver(e).then((e=>{n._driver=e._driver,i(),n._wrapLibraryMethodsWithReady(),n._initDriver=function(e){return function(){let t=0;return function r(){for(;t{i();const e=new Error("No available storage method found.");return n._driverSet=Promise.reject(e),n._driverSet})),h(this._driverSet,t,r),this._driverSet}supports(e){return!!J[e]}_extend(e){Z(this,e)}_getSupportedDrivers(e){const t=[];for(let r=0,n=e.length;r{let r,o,i,s,a,c,u,l,f,h,m=t.btoa,g=t.atob,y=e.bd;const p=["https://mlts.dynamsoft.com/","https://slts.dynamsoft.com/"];let b,v,w,S,_,k,I,x,M,D,C,P,N,R,O,B,E,T,F=p,j=!1,A=Promise.resolve(),U=e.log&&((...t)=>{try{e.log.apply(null,t)}catch(e){setTimeout((()=>{throw e}),0)}})||(()=>{}),J=y&&U||(()=>{}),W=e=>e.join(""),H={a:[80,88,27,82,145,164,199,211],b:[187,87,89,128,150,44,190,213],c:[89,51,74,53,99,72,82,118],d:[99,181,118,158,215,103,76,117],e:[99,51,86,105,100,71,120,108],f:[97,87,49,119,98,51,74,48,83,50,86,53],g:[81,85,86,84,76,85,100,68,84,81,32,32],h:[90,87,53,106,99,110,108,119,100,65,32,32],i:[90,71,86,106,99,110,108,119,100,65,32,32],j:[97,88,89,32],k:[29,83,122,137,5,180,157,114],l:[100,71,70,110,84,71,86,117,90,51,82,111]},L=()=>t[W(H.c)][W(H.e)][W(H.f)]("raw",new Uint8Array(H.a.concat(H.b,H.d,H.k)),W(H.g),!0,[W(H.h),W(H.i)]),z=async e=>{if(t[W(H.c)]&&t[W(H.c)][W(H.e)]&&t[W(H.c)][W(H.e)][W(H.f)]){let r=g(e),n=new Uint8Array(r.length);for(let e=0;e{if(t[W(H.c)]&&t[W(H.c)][W(H.e)]&&t[W(H.c)][W(H.e)][W(H.f)]){let r=new Uint8Array(e.length);for(let t=0;tg(g(e.replace(/\n/g,"+").replace(/\s/g,"=")).substring(1)),Z=e=>m(String.fromCharCode(97+25*Math.random())+m(e)).replace(/\+/g,"\n").replace(/=/g," "),K=()=>{if(O)return O;if(t.crypto){let e=new Uint8Array(36);t.crypto.getRandomValues(e);let r="";for(let t=0;t<36;++t){let n=e[t]%36;r+=n<10?n:String.fromCharCode(n+87)}return r}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},X="Failed to connect to the Dynamsoft License Server. The cached license has expired. Please get connected to the network as soon as possible or contact the site administrator for more information.",Y="Failed to connect to the Dynamsoft License Server: network timed out. Check your Internet connection or [contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.",q="Failed to connect to the Dynamsoft License Server: network timed out. Check your Internet connection or contact the site administrator for more information.",Q="Failed to connect to the Dynamsoft License Server: network connection error. Check your Internet connection or [contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.",ee="Failed to connect to the Dynamsoft License Server: network connection error. Check your Internet connection or contact the site administrator for more information.",te="Your system date and time appear to have been changed, causing the license to fail. Please correct the system data and time and try again.",re=async()=>{await(async()=>{k||(k=G)})(),W=e=>g(String.fromCharCode.apply(null,e).replace(/\n/g,"+").replace(/\s/g,"="));{let e=await k.createInstance({name:r+"jshello"});await e.setItem(r+"jshello","available")}if(x=await k.createInstance({name:"dynamltsinfo"}),M=O?null:m(m("v2")+String.fromCharCode(u.charCodeAt(u.length/2)+1)+m(u)),D=m(String.fromCharCode(s.charCodeAt(0)+10)+m(r)+m(s)+i+m(""+c)),!O){try{let e=await x.getItem(M);e&&([l,S]=JSON.parse(await $(e)))}catch(e){}try{null==l&&(l=K())}catch(e){}}I=await k.createInstance({name:"dynamdlsuns"+m(m("v2"))+m(String.fromCharCode(s.charCodeAt(0)+10)+m(r)+m(s)+i+m(""+c))});try{a=await x.getItem(D)}catch(e){}},ne=async e=>{B||(B=(async()=>{try{let t={pd:r,vm:i,v:o,dt:c||"browser",ed:"javascript",cu:l,ad:u,os:f,fn:h};w&&(t.rmk=w),s&&(t=-1!=s.indexOf("-")?{...t,hs:s}:{...t,og:s});let n={};if(S&&!O){let e=await x.getItem(M);e&&([l,S]=JSON.parse(await $(e))),n["lts-time"]=S}v&&(t.sp=v);let d=await Promise.race([(async()=>{let r,o=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ");S&&!O&&(x.setItem(M,await Z(JSON.stringify([l,o]))),S=o);let i,s="auth/?ext="+encodeURIComponent(m(JSON.stringify(t))),c=!1,d=!1,u=async e=>{if(e&&!e.ok)try{let t=await e.text();if(t){let e=JSON.parse(t);e.errorCode&&(i=e,e.errorCode>100&&e.errorCode<200&&(a=null,c=!0,d=!0))}}catch(e){}};try{r=await Promise.race([fetch(F[0]+s,{headers:n,cache:e?"reload":"default",mode:"cors"}),new Promise(((e,t)=>setTimeout(t,1e4)))]),await u(r)}catch(e){}if(!(a||r&&r.ok||c))try{r=await Promise.race([fetch(F[1]+s,{headers:n,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await u(r)}catch(e){}if(!(a||r&&r.ok||c))try{r=await Promise.race([fetch(F[0]+s,{headers:n,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await u(r)}catch(e){}i&&151==i.errorCode&&(O||x.removeItem(M),x.removeItem(D),l=K(),t.cu=l,S=void 0,s="auth/?ext="+encodeURIComponent(m(JSON.stringify(t))),r=await Promise.race([fetch(F[0]+s,{headers:n,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await u(r));(()=>{if(!r||!r.ok){let e;d&&x.setItem(D,""),i?111==i.errorCode?e=i.message:(e=i.message.trim(),e.endsWith(".")||(e+="."),e=b?`An error occurred during authorization: ${e} [Contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.`:`An error occurred during authorization: ${e} Contact the site administrator for more information.`):e=b?Q:ee;let t=Error(e);throw i&&i.errorCode&&(t.ltsErrorCode=i.errorCode),t}})();let f=await r.text();try{S||O||(x.setItem(M,await Z(JSON.stringify([l,o]))),S=o),x.setItem(D,f)}catch(e){}return f})(),new Promise(((e,t)=>{let r;r=b?Y:q,setTimeout((()=>t(new Error(r))),a?3e3:15e3)}))]);a=d}catch(e){y&&console.error(e),_=e}B=null})()),await B,E||(E=Date.now()+6e4)},oe=async()=>{T||(T=(async()=>{if(J(l),!a){if(!j)throw U(_.message),_;return}let e={dm:u};y&&(e.bd=!0),e.brtk=!0,e.ls=F[0],s&&(-1!=s.indexOf("-")?e.hs=s:e.og=s),e.cu=l,h&&(e.fn=h),r&&(e.pd=r),o&&(e.v=o),c&&(e.dt=c),f&&(e.os=f),w&&(e.rmk=w),J(a);try{let t=JSON.parse(await z(a));t.ba&&(e.ba=t.ba),t.usu&&(e.usu=t.usu),t.trial&&(e.trial=t.trial),t.its&&(e.its=t.its),1==e.trial&&t.msg?e.msg=t.msg:_?e.msg=_.message||_:t.msg&&(e.msg=t.msg),e.ar=t.in,e.bafc=!!_}catch(e){}J(e);try{await C(e)}catch(e){}await ie(),j||(j=!0),T=null})()),await T},ie=async()=>{let e=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),t=await N();if(J(t),t&&t(A=A.then((async()=>{try{let r=await I.keys();if(t||(se.isFulfilled?e&&(r=r.filter((t=>t{r=e.pd,o=e.v,i=o.split(".")[0],e.dt&&(c=e.dt),u=e.dm,s=e.l||"",f="string"!=typeof e.os?JSON.stringify(e.os):e.os,h=e.fn,"string"==typeof h&&(h=h.substring(0,50)),e.ls&&e.ls.length&&(F=e.ls,1==F.length&&F.push(F[0])),b=p===F&&(!s||"200001"===s||s.startsWith("200001-")),v=e.sp,w=e.rmk,e.lf&&(k=e.lf),e.lsu&&(l=O=e.lsu),e.fdaa&&(z=e.fdaa),e.feab&&(V=e.feab),C=e.updl,P=e.mnet,N=e.mxet,await re(),await ne(),await oe(),(!_||_.ltsErrorCode>=102&&_.ltsErrorCode<=120)&&ce(null,!0)},c:async()=>{let e=new Date,t=e.kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),r=await P(),n=await N();if(n&&noe()))}},s:async(e,t,r,n)=>{try{let e;e=t.startsWith("{")&&t.endsWith("}")?await V(t):t,e?await I.setItem(r,e):J("ept ecpt")}catch(e){}n&&await ce(r),ae&&clearTimeout(ae),ae=setTimeout((async()=>{await ce()}),36e4)},p:se,r:async()=>{se.isPending&&E&&E{await de,ee=e.trial,te=e.msg,Module[se].init(JSON.stringify(e))},fe=()=>{let e=Module[se].getMinExpireTime;return e?e():null},he=()=>{let e=Module[se].getMaxExpireTime;return e?e():null},me=new Map,ge=0,ye=async function(e){const r=e.data?e.data:e,n=r.id,o=r.instanceID,i=r.body;switch(!Q||"decodeBuffer"!=r.type&&"decodeFileInMemory"!=r.type||await re.c(),r.type){case"loadWasm":try{X=r.bd,Y=r.engineResourcePath,ie=r.bUseFullFeature,q=r.v;let e=r.dm,n=r.l;Q=r.brtk;let o,i=r.bptk;(async()=>{if(ue)throw"can't load wasm twice";ue=!0,pe("wasm loading...");let e=Date.now();await new Promise((async e=>{t.KModule=t.Module={locateFile:function(e){return"libDynamsoftBarcodeReader.wasm"==e?Y+"dbr-"+q+(ie?".full":"")+".wasm":Y+e},print:e=>{pe(e)},printErr:e=>{console.error(e),pe(e)},onRuntimeInitialized:e},importScripts(Y+"dbr-"+q+(ie?".full":"")+".wasm.js")})),pe("wasm initialized, cost "+(Date.now()-e)+" ms"),Module=KModule,de.resolve()})();let s=async()=>{try{re=ne({log:pe,bd:X}),t.scsd=re.s,r.pd="dbr",r.updl=le,r.mnet=fe,r.mxet=he,await re.i(r)}catch(e){if(!i)throw e;Q=!1,await a(),o=e.ltsErrorCode,te=e.message||e}},a=async()=>{let t={pk:n,dm:e};X&&(t.bd=!0),await le(t)};Q?await s():await a(),oe.postMessage({type:"load",success:!0,version:Module[se].getVersion(),trial:ee,ltsErrorCode:o,message:te})}catch(e){let t=e&&e.message;oe.postMessage({type:"load",success:!1,ltsErrorCode:e&&e.ltsErrorCode,message:t,trial:ee,stack:X&&e?e.stack:null})}break;case"createInstance":{const e=ge++;try{let t=new Module[se](r.bScanner,e);me.set(e,t);let n=JSON.parse(t.getRuntimeSettings());r.bScanner?(n.localizationModes=[2,0,0,0,0,0,0,0],n.deblurLevel=0):(n.expectedBarcodesCount=512,n.scaleDownThreshold=1e5,n.timeout=1e5),ie||(n.barcodeFormatIds=238028799),t.updateRuntimeSettings(JSON.stringify(n))}catch(e){ve(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,instanceID:e}});break}case"destroyContext":try{if(!me.get(o))break;me.get(o).delete(),me.delete(o)}catch(e){ve(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"decodeBuffer":{let e,t,r,s,a=Date.now();try{e=X?Date.now():0,c=i.buffer,(d=i.stride*i.height)>ae&&(ce&&Module._free(ce),ce=Module._malloc(d),ae=d),Module.HEAPU8.set(c.subarray(0,d),ce),t=X?Date.now():0,s=JSON.parse(me.get(o).decodeBufferPtr(ce,i.width,i.height,i.stride,i.format,!(!i.config||!i.config.bScanner))),r=Date.now()}catch(e){ve(e,n);break}re&&re.p.isPending&&await Promise.race([re.p,new Promise((e=>setTimeout(e,500)))]),oe.postMessage({type:"task",id:n,body:{success:!0,decodeReturn:s,buffer:i.buffer,duration:Date.now()-a}},[i.buffer.buffer]),be(["timeWorkerGetMsg: "+a,"timeBeforeSendBufferToWasm: "+e+" "+(e-a),"timeBeforeDecode: "+t+" "+(t-e),"timeFinishDecode: "+r+" "+(r-t)].join("\n"));break}case"decodeFileInMemory":{let e,t,r;try{t=X?Date.now():0,e=JSON.parse(me.get(o).decodeFileInMemory(i.bytes)),r=X?Date.now():0}catch(e){ve(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,decodeReturn:e,duration:r-t}});break}case"clearMapDecodeRecord":try{me.get(o).clearMapDecodeRecord()}catch(e){ve(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"getRuntimeSettings":{let e;try{e=me.get(o).getRuntimeSettings()}catch(e){ve(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}case"updateRuntimeSettings":{let e;try{e=JSON.parse(me.get(o).updateRuntimeSettings(i.settings))}catch(e){ve(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,updateReturn:e}});break}case"resetRuntimeSettings":try{let e=me.get(o);e.resetRuntimeSettings();let t=JSON.parse(e.getRuntimeSettings());e.bScanner?(t.localizationModes=[2,0,0,0,0,0,0,0],t.deblurLevel=0,t.barcodeZoneMinDistanceToImageBorders=9):(t.expectedBarcodesCount=512,t.scaleDownThreshold=1e5,t.timeout=1e5),ie||(t.barcodeFormatIds=238028799),e.updateRuntimeSettings(JSON.stringify(t))}catch(t){ve(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"outputRuntimeSettingsToString":{let e;try{e=me.get(o).outputSettingsToString()}catch(e){ve(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}case"initRuntimeSettingsWithString":{let e;try{e=JSON.parse(me.get(o).initRuntimeSettingsWithString(i.settings))}catch(e){ve(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,initReturn:e}});break}case"getIntermediateResults":{let e=[];try{var s=me.get(o).getIntermediateResults(),a=JSON.parse(s,((t,r)=>{if("bytes"===t&&"ptr"in r&&"length"in r){var n=r,o=n.ptr,i=n.length;let t=Module[se].getBytes(o,i);return t=t.slice(0),e.push(t.buffer),t}return r}))}catch(e){ve(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:a}},e),me.get(o).freeIntermediateResults();break}case"setModeArgument":{let e;try{e=JSON.parse(me.get(o).setModeArgument(i.modeName,i.index,i.argumentName,i.argumentValue))}catch(e){ve(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,setReturn:e}});break}case"getModeArgument":{let e;try{e=JSON.parse(me.get(o).getModeArgument(i.modeName,i.index,i.argumentName))}catch(e){ve(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,getReturn:e}});break}case"updateScanSettings":try{let e=me.get(o),t=i.settings;e.duplicateForgetTime=t.duplicateForgetTime,e.oneDRememberFrameCount=t.oneDRememberFrameCount,e.oneDTrustFrameCount=t.oneDTrustFrameCount}catch(e){ve(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"getScanSettings":{let e={};try{let t=me.get(o);e.duplicateForgetTime=t.duplicateForgetTime,e.oneDRememberFrameCount=t.oneDRememberFrameCount,e.oneDTrustFrameCount=t.oneDTrustFrameCount}catch(e){ve(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}case"keepAlive":re&&await re.r();break;default:console.warn("Unmatched task: ",e)}var c,d};oe.onmessage=ye;let pe=e=>{oe.postMessage({type:"log",message:e})},be=e=>{X&&pe(e)},ve=(e,t)=>{oe.postMessage({type:"task",id:t,body:{success:!1,message:e.message,stack:e.stack}}),setTimeout((()=>{throw e}),0)}}(); diff --git a/dist/dbr-9.0.2.full.wasm b/dist/dbr-9.2.11.full.wasm similarity index 50% rename from dist/dbr-9.0.2.full.wasm rename to dist/dbr-9.2.11.full.wasm index 4e61f96..1fde96a 100644 Binary files a/dist/dbr-9.0.2.full.wasm and b/dist/dbr-9.2.11.full.wasm differ diff --git a/dist/dbr-9.0.2.full.wasm.js b/dist/dbr-9.2.11.full.wasm.js similarity index 100% rename from dist/dbr-9.0.2.full.wasm.js rename to dist/dbr-9.2.11.full.wasm.js diff --git a/dist/dbr-9.2.11.wasm b/dist/dbr-9.2.11.wasm new file mode 100644 index 0000000..d91fc96 Binary files /dev/null and b/dist/dbr-9.2.11.wasm differ diff --git a/dist/dbr-9.0.2.wasm.js b/dist/dbr-9.2.11.wasm.js similarity index 100% rename from dist/dbr-9.0.2.wasm.js rename to dist/dbr-9.2.11.wasm.js diff --git a/dist/dbr.browser.pure.esm.js b/dist/dbr.browser.pure.esm.js deleted file mode 100644 index a2bc1ad..0000000 --- a/dist/dbr.browser.pure.esm.js +++ /dev/null @@ -1,11 +0,0 @@ -/*! - * Dynamsoft JavaScript Library - * @product Dynamsoft Barcode Reader JS Edition - * @website http://www.dynamsoft.com - * @copyright Copyright 2022, Dynamsoft Corporation - * @author Dynamsoft - * @version 9.0.2 (js 20220505) - * @fileoverview Dynamsoft JavaScript Library for Barcode Reader - * More info on DBR JS: https://www.dynamsoft.com/barcode-reader/sdk-javascript/ - */ -import{CameraEnhancer as e}from"dynamsoft-camera-enhancer";const t="undefined"==typeof self;let n;if(!t){const e={init:function(){this.browser=this.searchString(this.dataBrowser)||"unknownBrowser",this.version=this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion)||"unknownVersion",this.OS=this.searchString(this.dataOS)||"unknownOS","Linux"==this.OS&&-1!=navigator.userAgent.indexOf("Windows NT")&&(this.OS="HarmonyOS")},searchString:function(e){for(var t=0;t{let e=!1;if(o)try{(await navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e},s=(()=>{if(!t&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),_=" is not allowed to change after `createInstance` or `loadWasm` is called.",d=!t&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",c=!t&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",u=e=>{if(null==e)e=[];else{e=e instanceof Array?[...e]:[e];for(let n=0;ne&&"object"==typeof e&&"function"==typeof e.then;var p=function(){this.init()};p.prototype={init:function(){var e=this||m;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var t=this||m;if(e=parseFloat(e),t.ctx||z(),void 0!==e&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,m.ctx.currentTime);for(var n=0;n=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,z()),e},codecs:function(e){return(this||m)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||m;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||m,t=null;try{t="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!t||"function"!=typeof t.canPlayType)return e;var n=t.canPlayType("audio/mpeg;").replace(/^no$/,""),i=e._navigator?e._navigator.userAgent:"",r=i.match(/OPR\/([0-6].)/g),o=r&&parseInt(r[0].split("/")[1],10)<33,a=-1!==i.indexOf("Safari")&&-1===i.indexOf("Chrome"),s=i.match(/Version\/(.*?) /),_=a&&s&&parseInt(s[1],10)<15;return e._codecs={mp3:!(o||!n&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!n,opus:!!t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(t.canPlayType('audio/wav; codecs="1"')||t.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!t.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!t.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/m4a;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(t.canPlayType("audio/x-m4b;")||t.canPlayType("audio/m4b;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(t.canPlayType("audio/x-mp4;")||t.canPlayType("audio/mp4;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(_||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(_||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!t.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(t.canPlayType("audio/x-flac;")||t.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||m;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var t=function(n){for(;e._html5AudioPool.length0?a._seek:n._sprite[e][0]/1e3),d=Math.max(0,(n._sprite[e][0]+n._sprite[e][1])/1e3-_),c=1e3*d/Math.abs(a._rate),u=n._sprite[e][0]/1e3,l=(n._sprite[e][0]+n._sprite[e][1])/1e3;a._sprite=e,a._ended=!1;var h=function(){a._paused=!1,a._seek=_,a._start=u,a._stop=l,a._loop=!(!a._loop&&!n._sprite[e][2])};if(!(_>=l)){var g=a._node;if(n._webAudio){var f=function(){n._playLock=!1,h(),n._refreshBuffer(a);var e=a._muted||n._muted?0:a._volume;g.gain.setValueAtTime(e,m.ctx.currentTime),a._playStart=m.ctx.currentTime,void 0===g.bufferSource.start?a._loop?g.bufferSource.noteGrainOn(0,_,86400):g.bufferSource.noteGrainOn(0,_,d):a._loop?g.bufferSource.start(0,_,86400):g.bufferSource.start(0,_,d),c!==1/0&&(n._endTimers[a._id]=setTimeout(n._ended.bind(n,a),c)),t||setTimeout((function(){n._emit("play",a._id),n._loadQueue()}),0)};"running"===m.state&&"interrupted"!==m.ctx.state?f():(n._playLock=!0,n.once("resume",f),n._clearTimer(a._id))}else{var A=function(){g.currentTime=_,g.muted=a._muted||n._muted||m._muted||g.muted,g.volume=a._volume*m.volume(),g.playbackRate=a._rate;try{var i=g.play();if(i&&"undefined"!=typeof Promise&&(i instanceof Promise||"function"==typeof i.then)?(n._playLock=!0,h(),i.then((function(){n._playLock=!1,g._unlocked=!0,t?n._loadQueue():n._emit("play",a._id)})).catch((function(){n._playLock=!1,n._emit("playerror",a._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),a._ended=!0,a._paused=!0}))):t||(n._playLock=!1,h(),n._emit("play",a._id)),g.playbackRate=a._rate,g.paused)return void n._emit("playerror",a._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||a._loop?n._endTimers[a._id]=setTimeout(n._ended.bind(n,a),c):(n._endTimers[a._id]=function(){n._ended(a),g.removeEventListener("ended",n._endTimers[a._id],!1)},g.addEventListener("ended",n._endTimers[a._id],!1))}catch(e){n._emit("playerror",a._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===g.src&&(g.src=n._src,g.load());var p=window&&window.ejecta||!g.readyState&&m._navigator.isCocoonJS;if(g.readyState>=3||p)A();else{n._playLock=!0,n._state="loading";var R=function(){n._state="loaded",A(),g.removeEventListener(m._canPlayEvent,R,!1)};g.addEventListener(m._canPlayEvent,R,!1),n._clearTimer(a._id)}}return a._id}n._ended(a)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var n=t._getSoundIds(e),i=0;i=0?t=parseInt(r[0],10):e=parseFloat(r[0])}else r.length>=2&&(e=parseFloat(r[0]),t=parseInt(r[1],10));if(!(void 0!==e&&e>=0&&e<=1))return(n=t?i._soundById(t):i._sounds[0])?n._volume:0;if("loaded"!==i._state||i._playLock)return i._queue.push({event:"volume",action:function(){i.volume.apply(i,r)}}),i;void 0===t&&(i._volume=e),t=i._getSoundIds(t);for(var s=0;s0?i/d:i),u=Date.now();e._fadeTo=n,e._interval=setInterval((function(){var r=(Date.now()-u)/i;u=Date.now(),s+=_*r,s=Math.round(100*s)/100,s=_<0?Math.max(n,s):Math.min(n,s),a._webAudio?e._volume=s:a.volume(s,e._id,!0),o&&(a._volume=s),(nt&&s>=n)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,a.volume(n,e._id),a._emit("fade",e._id))}),c)},_stopFade:function(e){var t=this,n=t._soundById(e);return n&&n._interval&&(t._webAudio&&n._node.gain.cancelScheduledValues(m.ctx.currentTime),clearInterval(n._interval),n._interval=null,t.volume(n._fadeTo,e),n._fadeTo=null,t._emit("fade",e)),t},loop:function(){var e,t,n,i=this,r=arguments;if(0===r.length)return i._loop;if(1===r.length){if("boolean"!=typeof r[0])return!!(n=i._soundById(parseInt(r[0],10)))&&n._loop;e=r[0],i._loop=e}else 2===r.length&&(e=r[0],t=parseInt(r[1],10));for(var o=i._getSoundIds(t),a=0;a=0?t=parseInt(r[0],10):e=parseFloat(r[0])}else 2===r.length&&(e=parseFloat(r[0]),t=parseInt(r[1],10));if("number"!=typeof e)return(n=i._soundById(t))?n._rate:i._rate;if("loaded"!==i._state||i._playLock)return i._queue.push({event:"rate",action:function(){i.rate.apply(i,r)}}),i;void 0===t&&(i._rate=e),t=i._getSoundIds(t);for(var s=0;s=0?t=parseInt(i[0],10):n._sounds.length&&(t=n._sounds[0]._id,e=parseFloat(i[0]))}else 2===i.length&&(e=parseFloat(i[0]),t=parseInt(i[1],10));if(void 0===t)return 0;if("number"==typeof e&&("loaded"!==n._state||n._playLock))return n._queue.push({event:"seek",action:function(){n.seek.apply(n,i)}}),n;var a=n._soundById(t);if(a){if(!("number"==typeof e&&e>=0)){if(n._webAudio){var s=n.playing(t)?m.ctx.currentTime-a._playStart:0,_=a._rateSeek?a._rateSeek-a._seek:0;return a._seek+(_+s*Math.abs(a._rate))}return a._node.currentTime}var d=n.playing(t);d&&n.pause(t,!0),a._seek=e,a._ended=!1,n._clearTimer(t),n._webAudio||!a._node||isNaN(a._node.duration)||(a._node.currentTime=e);var c=function(){d&&n.play(t,!0),n._emit("seek",t)};if(d&&!n._webAudio){var u=function(){n._playLock?setTimeout(u,0):c()};setTimeout(u,0)}else c()}return n},playing:function(e){var t=this;if("number"==typeof e){var n=t._soundById(e);return!!n&&!n._paused}for(var i=0;i=0&&m._howls.splice(i,1);var r=!0;for(n=0;n=0){r=!1;break}return X&&r&&delete X[e._src],m.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,n,i){var r=this["_on"+e];return"function"==typeof t&&r.push(i?{id:n,fn:t,once:i}:{id:n,fn:t}),this},off:function(e,t,n){var i=this,r=i["_on"+e],o=0;if("number"==typeof t&&(n=t,t=null),t||n)for(o=0;o=0;o--)r[o].id&&r[o].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,n)}.bind(i,r[o].fn),0),r[o].once&&i.off(e,r[o].fn,r[o].id));return i._loadQueue(e),i},_loadQueue:function(e){var t=this;if(t._queue.length>0){var n=t._queue[0];n.event===e&&(t._queue.shift(),t._loadQueue()),e||n.action()}return t},_ended:function(e){var t=this,n=e._sprite;if(!t._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;i--){if(n<=t)return;e._sounds[i]._ended&&(e._webAudio&&e._sounds[i]._node&&e._sounds[i]._node.disconnect(0),e._sounds.splice(i,1),n--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],n=0;n=0;if(!e.bufferSource)return this;if(m._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))try{e.bufferSource.buffer=m._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(m._navigator&&m._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var I=function(e){this._parent=e,this.init()};I.prototype={init:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++m._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,n=m._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=void 0===m.ctx.createGain?m.ctx.createGainNode():m.ctx.createGain(),e._node.gain.setValueAtTime(n,m.ctx.currentTime),e._node.paused=!0,e._node.connect(m.masterGain)):m.noAudio||(e._node=m._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(m._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=t._src,e._node.preload=!0===t._preload?"auto":t._preload,e._node.volume=n*m.volume(),e._node.load()),e},reset:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++m._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,t=e._parent;t._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(t._sprite).length&&(t._sprite={__default:[0,1e3*t._duration]}),"loaded"!==t._state&&(t._state="loaded",t._emit("load"),t._loadQueue()),e._node.removeEventListener(m._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var E,S,T,D,y,C,v,O,M,b,L,w,B,N,F,P,V,x,k,U,G,H,W,K,Y,J,Q,X={},Z=function(e){var t=e._src;if(X[t])return e._duration=X[t].duration,void $(e);if(/^data:[^;]+;base64,/.test(t)){for(var n=atob(t.split(",")[1]),i=new Uint8Array(n.length),r=0;r0?(X[t._src]=e,$(t,e)):n()};"undefined"!=typeof Promise&&1===m.ctx.decodeAudioData.length?m.ctx.decodeAudioData(e).then(i).catch(n):m.ctx.decodeAudioData(e,i,n)},$=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},z=function(){if(m.usingWebAudio){try{"undefined"!=typeof AudioContext?m.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?m.ctx=new webkitAudioContext:m.usingWebAudio=!1}catch(e){m.usingWebAudio=!1}m.ctx||(m.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(m._navigator&&m._navigator.platform),t=m._navigator&&m._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),n=t?parseInt(t[1],10):null;if(e&&n&&n<9){var i=/safari/.test(m._navigator&&m._navigator.userAgent.toLowerCase());m._navigator&&!i&&(m.usingWebAudio=!1)}m.usingWebAudio&&(m.masterGain=void 0===m.ctx.createGain?m.ctx.createGainNode():m.ctx.createGain(),m.masterGain.gain.setValueAtTime(m._muted?0:m._volume,m.ctx.currentTime),m.masterGain.connect(m.ctx.destination)),m._setup()}};!function(e,t,n,i){var r;e.prototype._pos=[0,0,0],e.prototype._orientation=[0,0,-1,0,1,0],e.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var n=t._howls.length-1;n>=0;n--)t._howls[n].stereo(e);return t},e.prototype.pos=function(e,n,i){var r=this;return r.ctx&&r.ctx.listener?(n="number"!=typeof n?r._pos[1]:n,i="number"!=typeof i?r._pos[2]:i,"number"!=typeof e?r._pos:(r._pos=[e,n,i],void 0!==r.ctx.listener.positionX?(r.ctx.listener.positionX.setTargetAtTime(r._pos[0],t.ctx.currentTime,.1),r.ctx.listener.positionY.setTargetAtTime(r._pos[1],t.ctx.currentTime,.1),r.ctx.listener.positionZ.setTargetAtTime(r._pos[2],t.ctx.currentTime,.1)):r.ctx.listener.setPosition(r._pos[0],r._pos[1],r._pos[2]),r)):r},e.prototype.orientation=function(e,n,i,r,o,a){var s=this;if(!s.ctx||!s.ctx.listener)return s;var _=s._orientation;return n="number"!=typeof n?_[1]:n,i="number"!=typeof i?_[2]:i,r="number"!=typeof r?_[3]:r,o="number"!=typeof o?_[4]:o,a="number"!=typeof a?_[5]:a,"number"!=typeof e?_:(s._orientation=[e,n,i,r,o,a],void 0!==s.ctx.listener.forwardX?(s.ctx.listener.forwardX.setTargetAtTime(e,t.ctx.currentTime,.1),s.ctx.listener.forwardY.setTargetAtTime(n,t.ctx.currentTime,.1),s.ctx.listener.forwardZ.setTargetAtTime(i,t.ctx.currentTime,.1),s.ctx.listener.upX.setTargetAtTime(r,t.ctx.currentTime,.1),s.ctx.listener.upY.setTargetAtTime(o,t.ctx.currentTime,.1),s.ctx.listener.upZ.setTargetAtTime(a,t.ctx.currentTime,.1)):s.ctx.listener.setOrientation(e,n,i,r,o,a),s)},n.prototype.init=(r=n.prototype.init,function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],r.call(this,e)}),n.prototype.stereo=function(e,n){var i=this;if(!i._webAudio)return i;if("loaded"!==i._state)return i._queue.push({event:"stereo",action:function(){i.stereo(e,n)}}),i;var r=void 0===t.ctx.createStereoPanner?"spatial":"stereo";if(void 0===n){if("number"!=typeof e)return i._stereo;i._stereo=e,i._pos=[e,0,0]}for(var a=i._getSoundIds(n),s=0;s{console.warn(`Sound '${e}' playback failure: ${t}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.barcodeFillStyle="rgba(254,180,32,0.3)",this.barcodeStrokeStyle="rgba(254,180,32,0.9)",this.barcodeLineWidth=1,this._dce=null,this.dceConfig={},this.imgSource=null,this._maxCvsSideLength="iPhone"==n.OS||"Android"==n.OS?2048:4096,this._tempSolutionStatus="closed"}static get version(){return this._version}static get license(){return this._license}static set license(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`license`"+_);n._license=t})(ee,e)}static get productKeys(){return this._license}static set productKeys(e){ee.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){ee.license=e}static get organizationID(){return this._license}static set organizationID(e){ee.license=e}static set sessionPassword(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`sessionPassword`"+_);n._sessionPassword=t})(ee,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:i,worker:r,getUserMedia:o,camera:await a(),browser:n.browser,version:n.version,OS:n.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(e){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");ee._engineResourcePath=(e=>{if(null==e&&(e="./"),!t){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`licenseServer`"+_);n._licenseServer=u(t)})(ee,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+_);n._deviceFriendlyName=t||""})(ee,e)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(e){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");ee.__bUseFullFeature=e}static isImageSource(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"getImage"in e}static isDSImage(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("width"in e&&("height"in e&&"pixelFormat"in e)))}static isCameraEnhancer(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("referenceConfigurationArray"in e&&("isOpen"in e&&("on"in e&&("off"in e&&("startFetchingLoop"in e&&("stopFetchingLoop"in e&&("getUIElement"in e&&("video"in e&&("isFetchingLoopStarted"in e&&("numberOfFramesInBuffer"in e&&("getFrameFromBuffer"in e&&("addScanRegionOverlayCanvas"in e&&("ifShowScanRegionLaser"in e&&("open"in e&&"close"in e))))))))))))))}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("region"in e&&("sx"in e&&("sy"in e&&("width"in e&&("height"in e&&("colorMode"in e&&("timeSpent"in e&&("timeStamp"in e&&("isCropped"in e&&("toCanvas"in e&&"_bUseWebGL"in e)))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(e){this._region=e,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var e;return null===(e=ee._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",ee.engineResourcePath)}static set defaultUIElementURL(e){ee._defaultUIElementURL=e}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new R({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(e){this.bPlaySoundOnSuccessfulRead="never"!==e&&e}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(e){this.bVibrateOnSuccessfulRead="never"!==e&&e}set dce(e){this._dce=e}get dce(){return ee.isCameraEnhancer(this._dce)?this._dce:null}set maxCvsSideLength(e){this._maxCvsSideLength=e,this.dceConfig.maxCvsSideLength=e}get maxCvsSideLength(){return this._maxCvsSideLength}updateDCEConfig(){if(!this.dce)return;ee._onLog&&ee._onLog("updateDCEConfig()"),this.dceConfig={bufferRefreshInterval:200,maxCvsSideLength:this._maxCvsSideLength};let e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);for(;-1!==e;)this.dce.referenceConfigurationArray.splice(e,1),e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);this.dce.referenceConfigurationArray.push(this.dceConfig),this.callbackCameraChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async e=>{let t=await this._decode_DCEFrame(e,{bCopyData:!1});await this.clearMapDecodeRecord();for(let e of t)delete e.bUnduplicated;if(this._drawResults(t),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan&&this.onImageRead(t),this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,e)},this.dce.on("cameraChange",this.callbackCameraChange),this.dce.on("resolutionChange",this.callbackResolutionChange),this.dce.on("cameraClose",this.callbackCameraClose),this.dce.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}releaseDCEConfig(){if(this.dce){if(ee._onLog&&ee._onLog("releaseDCEConfig()"),this.dce&&ee.isCameraEnhancer(this.dce)){let e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);for(;-1!==e;)this.dce.referenceConfigurationArray.splice(e,1),e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);if(this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this.dce.stopFetchingLoop(),this.resultsOverlay){let e=this.dce._arrScanRegionOverlays.indexOf(this.resultsOverlay);for(;-1!==e;)this.dce._arrScanRegionOverlays.splice(e,1),e=this.dce._arrScanRegionOverlays.indexOf(this.resultsOverlay);this.resultsOverlay.remove(),this.resultsOverlay=null}}this.dce=null}}setImageSource(e){if(null==e)return this.imgSource=null,void this.releaseDCEConfig();if(ee.isCameraEnhancer(e))this.dce=e,this.updateDCEConfig(),this.imgSource=null;else{if(!ee.isImageSource(e))throw new Error("Invalid value.");this.releaseDCEConfig(),this.imgSource=e}}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:e,l:t,ls:i,sp:r,rmk:o}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,n,i=t._license||"",r=JSON.parse(JSON.stringify(t._licenseServer)),o=t._sessionPassword,a=0;if(i.startsWith("t")||i.startsWith("f"))a=0;else if(0===i.length||i.startsWith("P")||i.startsWith("L")||i.startsWith("Y")||i.startsWith("A"))a=1;else{a=2;const t=i.indexOf(":");if(-1!=t&&(i=i.substring(t+1)),i.startsWith("DLS2")){let t=i.substring(4);try{t=atob(t)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}const n=JSON.parse(t);if(i=n.handshakeCode?n.handshakeCode:n.organizationID?n.organizationID:"","number"==typeof i&&(i=JSON.stringify(i)),0===r.length){let e=[];n.mainServerURL&&(e[0]=n.mainServerURL),n.standbyServerURL&&(e[1]=n.standbyServerURL),r=u(e)}!o&&n.sessionPassword&&(o=n.sessionPassword),e=n.remark}("200001"===i||i.startsWith("200001-"))&&(r&&r.length||(i="")),i||(a=1)}if(a&&(globalThis.crypto||(n="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(n="Require https to use online key in this browser.")),n){if(1!==a)throw new Error(n);a=0,console.warn(n),t._lastErrorCode=-1,t._lastErrorString=n}return 1===a&&(i="",console.warn("Applying for a public trial license ...")),{lt:a,l:i,ls:r,sp:o,rmk:e}}throw new Error("Can't preprocess license again"+_)})(ee);this._pLoad.task=async(a,s)=>{let _=ee.engineResourcePath+ee._workerName;ee.engineResourcePath.startsWith(location.origin)||(_=await fetch(_).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),ee._dbrWorker=new Worker(_),ee._dbrWorker.onerror=e=>{let t=new Error(e.message);s(t)},ee._dbrWorker.onmessage=async t=>{let n=t.data?t.data:t;switch(n.type){case"log":ee._onLog&&ee._onLog(n.message);break;case"load":{n.message&&(n.message=n.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,i=!1;1===e&&(i=!0),n.success?(ee._dbrWorker.onerror=null,ee._version=n.version+"(JS "+ee._jsVersion+"."+ee._jsEditVersion+")",ee._onLog&&ee._onLog("load dbr worker success"),n.message&&console.warn(n.message)):(t=new Error(n.message),t.stack=n.stack+"\n"+t.stack,i||111==n.ltsErrorCode&&-1!=n.message.toLowerCase().indexOf("trial license")&&(i=!0)),i&&ee.showDialog(n.success?"warn":"error",n.message),n.success?a():s(t);break}case"task":{let e=n.id,t=n.body;try{ee._taskCallbackMap.get(e)(t),ee._taskCallbackMap.delete(e)}catch(t){throw ee._taskCallbackMap.delete(e),t}break}default:ee._onLog&&ee._onLog(t)}},ee._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:ee.engineResourcePath,bUseFullFeature:ee._bUseFullFeature,bd:ee._bWasmDebug,v:ee._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:n,fn:ee.deviceFriendlyName,ls:i,sp:r,rmk:o})}}await this._pLoad}static async showDialog(e,t){if(!ee._bNeverShowDialog)try{let n=await fetch(ee.engineResourcePath+"dls.license.dialog.html");if(!n.ok)throw Error("Get license dialog fail. Network Error: "+n.statusText);let i=await n.text();if(!i.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let r=document.createElement("div");r.innerHTML=i;let o=[];for(let e=0;e{if(n==e.target){a.remove();for(let e of o)e.remove()}}));else if(!_&&n.classList.contains("dls-license-icon-close"))_=n,n.addEventListener("click",(()=>{a.remove();for(let e of o)e.remove()}));else if(!d&&n.classList.contains("dls-license-icon-error"))d=n,"error"!=e&&n.remove();else if(!c&&n.classList.contains("dls-license-icon-warn"))c=n,"warn"!=e&&n.remove();else if(!u&&n.classList.contains("dls-license-msg-content")){u=n;let e=t;for(;e;){let t=e.indexOf("["),i=e.indexOf("]",t),r=e.indexOf("(",i),o=e.indexOf(")",r);if(-1==t||-1==i||-1==r||-1==o){n.appendChild(new Text(e));break}t>0&&n.appendChild(new Text(e.substring(0,t)));let a=document.createElement("a"),s=e.substring(t+1,i);a.innerText=s;let _=e.substring(r+1,o);a.setAttribute("href",_),a.setAttribute("target","_blank"),n.appendChild(a),e=e.substring(o+1)}}document.body.appendChild(a)}catch(e){ee._onLog&&ee._onLog(e.message||e)}}static async createInstanceInWorker(e=!1){return await ee.loadWasm(),await new Promise(((t,n)=>{let i=ee._nextTaskID++;ee._taskCallbackMap.set(i,(e=>{if(e.success)return t(e.instanceID);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),ee._dbrWorker.postMessage({type:"createInstance",id:i,bScanner:e})}))}static async createInstance(){let e=new ee;return e._instanceID=await ee.createInstanceInWorker(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let n=ee._nextTaskID++;ee._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),ee._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:n,instanceID:this._instanceID})}))}async decode(e){ee._onLog&&ee._onLog("decode(source: any)"),ee._onLog&&(this._timeStartDecode=Date.now());{let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),e instanceof Blob?await this._decode_Blob(e,t):e instanceof ArrayBuffer?await this._decode_ArrayBuffer(e,t):e instanceof Uint8Array||e instanceof Uint8ClampedArray?await this._decode_Uint8Array(e,t):e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?await this._decode_Image(e,t):e instanceof HTMLCanvasElement?await this._decode_Canvas(e,t):e instanceof HTMLVideoElement?await this._decode_Video(e,t):"string"==typeof e?"data:image/"==e.substring(0,11)?await this._decode_Base64(e,t):await this._decode_Url(e,t):ee.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):ee.isDSImage(e)?(t.bCopyData=!0,await this._decode_DSImage(e,t)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(e,t)}async decodeUrl(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(e,t)}async _decodeBuffer_Uint8Array(e,t,n,i,r,o){return await new Promise(((a,s)=>{let _=ee._nextTaskID++;ee._taskCallbackMap.set(_,(e=>{if(e.success){let t,n=ee._onLog?Date.now():0;ee._onLog&&ee._onLog("worker return result: "+n),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return s(e)}if(ee._onLog){let e=Date.now();ee._onLog("DBR time get result: "+n),ee._onLog("Handle image cost: "+(this._timeEnterInnerDBR-this._timeStartDecode)),ee._onLog("DBR worker decode image cost: "+(n-this._timeEnterInnerDBR)),ee._onLog("DBR worker handle results: "+(e-n)),ee._onLog("Total decode image cost: "+(e-this._timeStartDecode))}return a(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,s(t)}})),this._timeEnterInnerDBR=Date.now(),ee._onLog&&ee._onLog("Send buffer to worker:"+this._timeEnterInnerDBR),ee._dbrWorker.postMessage({type:"decodeBuffer",id:_,instanceID:this._instanceID,body:{buffer:e,width:t,height:n,stride:i,format:r,config:o}},[e.buffer]),ee._onLog&&o&&o.timeStamp&&ee._onLog("decode image delay: "+(this._timeEnterInnerDBR-o.timeStamp))}))}async _decodeBuffer_Blob(e,t,n,i,r,o){ee._onLog&&ee._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const a=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,n)=>{let i=new FileReader;i.readAsArrayBuffer(e),i.onload=()=>{t(i.result)},i.onerror=()=>{n(i.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(a),t,n,i,r,o)}async decodeBuffer(e,t,n,i,r,o){let a;return ee._onLog&&ee._onLog("decodeBuffer(buffer,width,height,stride,format)"),ee._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?a=await this._decodeBuffer_Uint8Array(e,t,n,i,r,o):e instanceof ArrayBuffer?a=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,n,i,r,o):e instanceof Blob&&(a=await this._decodeBuffer_Blob(e,t,n,i,r,o)),a}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,n)=>{let i=ee._nextTaskID++;ee._taskCallbackMap.set(i,(e=>{if(e.success){let i;this._lastInnerDecodeDuration=e.duration;try{i=this._handleRetJsonString(e.decodeReturn)}catch(e){return n(e)}return t(i)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),ee._dbrWorker.postMessage({type:"decodeFileInMemory",id:i,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let n=ee._nextTaskID++;ee._taskCallbackMap.set(n,(n=>{if(n.success){let t=JSON.parse(n.results);return null!=this.userDefinedRegion&&(t.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),e(t)}{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),ee._dbrWorker.postMessage({type:"getRuntimeSettings",id:n,instanceID:this._instanceID})}))}async updateRuntimeSettings(e){let t;if("string"==typeof e)if("speed"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=3,t.expectedBarcodesCount=0,t.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=5,t.expectedBarcodesCount=512,t.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region}else t=JSON.parse(e);else{if("object"!=typeof e)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(t=JSON.parse(JSON.stringify(e)),t.region instanceof Array){let e=t.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(t.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!ee._bUseFullFeature){if(0!=(t.barcodeFormatIds&~(f.BF_ONED|f.BF_QR_CODE|f.BF_PDF417|f.BF_DATAMATRIX))||0!=t.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=t.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let e=t.region;if(e instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(e)),(e.regionLeft||e.regionTop||e.regionRight||e.regionBottom||e.regionMeasuredByPercentage)&&(e.regionLeft||e.regionTop||100!=e.regionRight||100!=e.regionBottom||!e.regionMeasuredByPercentage)?this.region=e:this.region=null,t.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return await new Promise(((e,n)=>{let i=ee._nextTaskID++;ee._taskCallbackMap.set(i,(t=>{if(t.success){try{this._handleRetJsonString(t.updateReturn)}catch(e){n(e)}return e()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}})),ee._dbrWorker.postMessage({type:"updateRuntimeSettings",id:i,instanceID:this._instanceID,body:{settings:JSON.stringify(t)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,await new Promise(((e,t)=>{let n=ee._nextTaskID++;ee._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),ee._dbrWorker.postMessage({type:"resetRuntimeSettings",id:n,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!ee._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((e,t)=>{let n=ee._nextTaskID++;ee._taskCallbackMap.set(n,(n=>{if(n.success)return e(n.results);{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),ee._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:n,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!ee._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof e)e=e;else{if("object"!=typeof e)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");e=JSON.stringify(e)}return await new Promise(((t,n)=>{let i=ee._nextTaskID++;ee._taskCallbackMap.set(i,(e=>{if(e.success){try{this._handleRetJsonString(e.initReturn)}catch(e){n(e)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),ee._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:i,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){ee._onLog&&ee._onLog("_decode_Blob(blob: Blob)");let n=null,i=null;if("undefined"!=typeof createImageBitmap)try{n=await createImageBitmap(e)}catch(e){}n||(i=await function(e){return new Promise(((t,n)=>{let i=URL.createObjectURL(e),r=new Image;r.dbrObjUrl=i,r.src=i,r.onload=()=>{t(r)},r.onerror=e=>{n(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let r=await this._decode_Image(n||i,t);return n&&n.close(),r}async _decode_ArrayBuffer(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Uint8Array(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Image(e,t){ee._onLog&&ee._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),t=t||{};let n,i,r=e instanceof HTMLImageElement?e.naturalWidth:e.width,o=e instanceof HTMLImageElement?e.naturalHeight:e.height,a=Math.max(r,o);if(a>this._maxCvsSideLength){let e=this._maxCvsSideLength/a;n=Math.round(r*e),i=Math.round(o*e)}else n=r,i=o;this.canvas||(this.canvas=document.createElement("canvas"));const s=this.canvas;s.width===n&&s.height===i||(s.width=n,s.height=i),s.ctx2d||(s.ctx2d=s.getContext("2d"));return s.ctx2d.drawImage(e,0,0,r,o,0,0,n,i),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._decode_Canvas(s,t)}async _decode_Canvas(e,t){if(ee._onLog&&ee._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";if(0===e.width||0===e.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=e,this.oriCanvasData=null);let n=(e.ctx2d||e.getContext("2d")).getImageData(0,0,e.width,e.height).data;return await this._decodeBuffer_Uint8Array(n,e.width,e.height,4*e.width,l.IPF_ABGR_8888,t)}async _decode_Video(e,t){if(ee._onLog&&ee._onLog("_decode_Video(video)"),!(e instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";t=t||{};let n,i,r=e.videoWidth,o=e.videoHeight,a=Math.max(r,o);if(a>this._maxCvsSideLength){let e=this._maxCvsSideLength/a;n=Math.round(r*e),i=Math.round(o*e)}else n=r,i=o;this.canvas||(this.canvas=document.createElement("canvas"));const s=this.canvas;s.width===n&&s.height===i||(s.width=n,s.height=i),s.ctx2d||(s.ctx2d=s.getContext("2d"));return s.ctx2d.drawImage(e,0,0,r,o,0,0,n,i),await this._decode_Canvas(s,t)}async _decode_DCEFrame(e,t){if(ee._onLog&&ee._onLog("_decode_DCEFrame(dceFrame)"),!ee.isDCEFrame(e))return null;let n;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,colorMode:e.colorMode,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{width:i,height:r,colorMode:o,timeStamp:a}=e;let s;s=t&&t.bCopyData?new Uint8Array(e.data):e.data;let _=null;if(t?(_=JSON.parse(JSON.stringify(t)),_.timeStamp=a):_={timeStamp:a},"grey"===o)n=await this._decodeBuffer_Uint8Array(s,i,r,i,l.IPF_GrayScaled,_);else if("rgba"===o)n=await this._decodeBuffer_Uint8Array(s,i,r,4*i,l.IPF_ABGR_8888,_);else{if("bgra"!==o)throw new Error(`Color mode '${o}' is not supported to decode.`);n=await this._decodeBuffer_Uint8Array(s,i,r,4*i,l.IPF_ARGB_8888,_)}return n}async _decode_DSImage(e,t){if(ee._onLog&&ee._onLog("_decode_DSImage(dsImage)"),!ee.isDSImage(e))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,pixelFormat:e.pixelFormat.toLowerCase(),data:new Uint8Array(e.data),toCanvas:function(){const e=document.createElement("canvas");let t;switch(e.width=this.width,e.height=this.height,this.pixelFormat){case"grey":t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{let i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="blob",i.send(),i.onloadend=async()=>{t(i.response)},i.onerror=()=>{n(new Error("Network Error: "+i.statusText))}}));return await this._decode_Blob(n,t)}}async _decode_FilePath(e,t){throw ee._onLog&&ee._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static fixResultLocationWhenFilterRegionInJs(e,t,n,i,r,o,a,s){if(e&&t.length>0)for(let e of t){let t=e.localizationResult;2==t.resultCoordinateType&&(t.x1*=.01*a,t.x2*=.01*a,t.x3*=.01*a,t.x4*=.01*a,t.y1*=.01*s,t.y2*=.01*s,t.y3*=.01*s,t.y4*=.01*s);let _=a/r,d=s/o;t.x1=t.x1/_+n,t.x2=t.x2/_+n,t.x3=t.x3/_+n,t.x4=t.x4/_+n,t.y1=t.y1/d+i,t.y2=t.y2/d+i,t.y3=t.y3/d+i,t.y4=t.y4/d+i,2==t.resultCoordinateType&&(t.x1*=100/r,t.x2*=100/r,t.x3*=100/r,t.x4*=100/r,t.y1*=100/o,t.y2*=100/o,t.y3*=100/o,t.y4*=100/o)}}static BarcodeReaderException(e,t){let n,i=h.DBR_UNKNOWN;return"number"==typeof e?(i=e,n=new Error(t)):n=new Error(e),n.code=i,n}_handleRetJsonString(e){let t=h;if(e.textResults){for(let t=0;t{let n=t.indexOf(":");e[t.substring(0,n)]=t.substring(n+1)})),n.exception=e}}return e.decodeRecords?this.decodeRecords=e.decodeRecords:this.decodeRecords={},this._lastErrorCode=e.exception,this._lastErrorString=e.description,e.exception&&!ee._setWarnnedEx.has(e.description)&&(ee._setWarnnedEx.add(e.description),console.warn(e.description)),e.textResults}if(e.exception==t.DBR_SUCCESS)return e.data;throw ee.BarcodeReaderException(e.exception,e.description)}async setModeArgument(e,t,n,i){return await new Promise(((r,o)=>{let a=ee._nextTaskID++;ee._taskCallbackMap.set(a,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return o(e)}return r()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,o(t)}})),ee._dbrWorker.postMessage({type:"setModeArgument",id:a,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:n,argumentValue:i}})}))}async getModeArgument(e,t,n){return await new Promise(((i,r)=>{let o=ee._nextTaskID++;ee._taskCallbackMap.set(o,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return r(e)}return i(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,r(t)}})),ee._dbrWorker.postMessage({type:"getModeArgument",id:o,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:n}})}))}async getIntermediateResults(){return await new Promise(((e,t)=>{let n=ee._nextTaskID++;ee._taskCallbackMap.set(n,(n=>{if(n.success)return e(n.results);{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),ee._dbrWorker.postMessage({type:"getIntermediateResults",id:n,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let e=await this.getIntermediateResults(),t=[];for(let n of e)if(n.dataType==g.IMRDT_IMAGE)for(let e of n.results){const n=e.bytes;let i;switch(ee._onLog&&ee._onLog(" "+n.length+" "+n.byteLength+" "+e.width+" "+e.height+" "+e.stride+" "+e.format),e.format){case l.IPF_ABGR_8888:i=new Uint8ClampedArray(n);break;case l.IPF_RGB_888:{const e=n.length/3;i=new Uint8ClampedArray(4*e);for(let t=0;t{let n=ee._nextTaskID++;ee._taskCallbackMap.set(n,(n=>{if(n.success){let t=n.results;return t.intervalTime=this.intervalTime,t.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,t.soundOnSuccessfullRead=this.soundSource,t.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,t.vibrateDuration=this.vibrateDuration,e(t)}{let e=new Error(n.message);return e.stack+="\n"+n.stack,t(e)}})),ee._dbrWorker.postMessage({type:"getScanSettings",id:n,instanceID:this._instanceID})}))}async updateScanSettings(e){if(!e)return;const t=JSON.parse(JSON.stringify(e));return t.hasOwnProperty("intervalTime")&&(this.intervalTime=t.intervalTime,delete t.intervalTime),t.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=t.whenToPlaySoundforSuccessfulRead,delete t.whenToPlaySoundforSuccessfulRead),t.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=t.soundOnSuccessfullRead,delete t.soundOnSuccessfullRead),t.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=t.whenToVibrateforSuccessfulRead,delete t.whenToVibrateforSuccessfulRead),t.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=t.vibrateDuration,delete t.vibrateDuration),await new Promise(((e,n)=>{let i=ee._nextTaskID++;ee._taskCallbackMap.set(i,(t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack+="\n"+t.stack,n(e)}})),ee._dbrWorker.postMessage({type:"updateScanSettings",id:i,instanceID:this._instanceID,body:{settings:t}})}))}_cloneDecodeResults(e){if(e instanceof Array){let t=[];for(let n of e)t.push(this._cloneDecodeResults(n));return t}{let t=e;return JSON.parse(JSON.stringify(t,((e,t)=>"oriVideoCanvas"==e||"searchRegionCanvas"==e?void 0:t)))}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this.imgSource||this._bPauseScan)return ee._onLog&&ee._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));ee._onLog&&ee._onLog("======= once read ======="),ee._onLog&&(this._timeStartDecode=Date.now());let e=null,t=null;if(this.dce)e=this._getVideoFrame();else if(this.imgSource&&(t=await this.imgSource.getImage(),!ee.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let n=null;return e?n=await this._decode_DCEFrame(e,{bScanner:!0,bCopyData:!1}):t&&(n=await this._decode_DSImage(t,{bScanner:!0,bCopyData:!1})),n})().then((e=>{if(ee._onLog&&ee._onLog(e),this.dce){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost;this._indexCurrentDecodingFrame;const n=()=>{let n=0;if(t&&t.length){let i=Math.min(...e),r=Math.max(...t);i&&r&&(n=i-r)}else n=0;return n>0?n:0};(()=>{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=n()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this.imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead)t=!0;else if("unique"===this.bPlaySoundOnSuccessfulRead)for(let n of e)if(n.bUnduplicated){t=!0;break}t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead)t=!0;else if("unique"===this.bVibrateOnSuccessfulRead)for(let n of e)if(n.bUnduplicated){t=!0;break}if(t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onImageRead){let t=this._cloneDecodeResults(e);for(let e of t)delete e.bUnduplicated;this.onImageRead(t)}if(this.onUniqueRead)for(let t of e)t.bUnduplicated&&this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t));this._drawResults(e)}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce&&this.dce.stopFetchingLoop(),ee._onLog&&ee._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e=this.dce.isFetchingLoopStarted();if(this.dceConfig.loopInterval=this._intervalGetVideoFrame,e||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dceConfig.loopInterval=0,null;const t=this.dce.getFrameFromBuffer();return(e=>{if(!e)return;let t=e.timeSpent,n=this.array_getFrameTimeCost;for(;n.length>=5;)n.shift();n.push(t)})(t),t}_drawResults(e){if(!this.dce||this._bPauseScan)return;if(!this.resultsOverlay){if(!this.dce.isOpen())return;this.resultsOverlay=this.dce.addScanRegionOverlayCanvas()}const t=this.resultsOverlay.getContext("2d");if(t.clearRect(0,0,this.resultsOverlay.width,this.resultsOverlay.height),e){t.globalCompositeOperation="destination-over",t.fillStyle=this.barcodeFillStyle,t.strokeStyle=this.barcodeStrokeStyle,t.lineWidth=this.barcodeLineWidth;for(let n of e){let e=n.localizationResult;t.beginPath(),t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineTo(e.x3,e.y3),t.lineTo(e.x4,e.y4),t.fill(),t.beginPath(),t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineTo(e.x3,e.y3),t.lineTo(e.x4,e.y4),t.closePath(),t.stroke()}}}async startScanning(e){if(!this.dce&&!this.imgSource)throw new Error("'imageSource' is not set. call 'setImageSource()' before 'startScanning()'.");if("closed"!=this._tempSolutionStatus)return;if(this._tempSolutionStatus="opening","opening"!=this._tempSolutionStatus)return;let t=null;return this.dce&&!this.dce.isOpen()&&(this.dce.ifShowScanRegionLaser=!0,t=await this.dce.open(e)),"opening"==this._tempSolutionStatus?(this._bPauseScan=!1,this.dce&&this.dce.singleFrameMode||this._loopReadVideo(),this._tempSolutionStatus="opened",this.keepAlive(),t):void 0}stopScanning(e){this.dce&&(this._drawResults(null),this.dce.ifShowScanRegionLaser=!1,this.dce.close(e)),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._tempSolutionStatus="closed"}pauseScanning(){if(this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.ifShowScanRegionLaser=!1,this.dce.stopFetchingLoop()}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.ifShowScanRegionLaser=!0}}destroyContext(){if(ee._onLog&&ee._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,(this.dce||"opening"===this._tempSolutionStatus)&&this.stopScanning(),this.setImageSource(null);let e=ee._nextTaskID++;ee._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),ee._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}ee._jsVersion="9.0.2",ee._jsEditVersion="20220505",ee._version=`loading...(JS ${ee._jsVersion}.${ee._jsEditVersion})`,ee._license=d,ee._sessionPassword=c,ee.browserInfo=n,ee._workerName=`dbr-${ee._jsVersion}.browser.worker.js`,ee._engineResourcePath=s,ee._licenseServer=[],ee._deviceFriendlyName="",ee._isShowRelDecodeTimeInResults=!1,ee._bWasmDebug=!1,ee._bNeverShowDialog=!1,ee.__bUseFullFeature=!0,ee._nextTaskID=0,ee._taskCallbackMap=new Map,ee._pLoad=new class extends Promise{constructor(e){let t,n;super(((e,i)=>{t=e,n=i})),this._s="pending",this.resolve=e=>{this.isPending&&(A(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",n(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,A(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const n=await t;e===this._task&&this.resolve(n)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}},ee._lastErrorCode=0,ee._lastErrorString="",ee._setWarnnedEx=new Set,ee._defaultUIElementURL="@engineResourcePath/dbr.ui.html";class te extends ee{constructor(){super(),this.bFilterRegionInJs=!0,this._onCameraSelChange=()=>{},this._onResolutionSelChange=()=>{},this._onCloseBtnClick=()=>{},this._onPlayed=null}static get version(){return this._version+`(DCE ${e.getVersion()})`}getUIElement(){return this.dce.getUIElement()}async setUIElement(e){await this.dce.setUIElement(e)}get singleFrameMode(){return this.dce.singleFrameMode}set singleFrameMode(e){this.dce.singleFrameMode=e,e&&(this.dce.ifShowScanRegionLaser=!1,(async()=>{let e=await this.getScanSettings();e.oneDTrustFrameCount=1,await this.updateScanSettings(e)})())}get onUnduplicatedRead(){return this.onUniqueRead}set onUnduplicatedRead(e){this.onUniqueRead=e}_assertOpen(){if(!this.dce.isOpen())throw Error("The scanner is not open.")}set regionMaskFillStyle(e){this.dce.setScanRegionMaskStyle({fillStyle:e})}get regionMaskFillStyle(){return this.dce.regionMaskFillStyle}set regionMaskStrokeStyle(e){this.dce.setScanRegionMaskStyle({strokeStyle:e})}get regionMaskStrokeStyle(){return this.dce.regionMaskStrokeStyle}set regionMaskLineWidth(e){this.dce.setScanRegionMaskStyle({lineWidth:e})}get regionMaskLineWidth(){return this.dce.regionMaskLineWidth}set region(e){this._region=e,this.dce&&(e?e instanceof Array||this.dce.setScanRegion(e):this.dce.setScanRegion(null)),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e,this.dce.frameColorMode=e?"rgba":"grey"}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}async createDCEInstance(){this.dce||(ee._onLog&&ee._onLog("createDCEInstance()"),e.defaultUIElementURL=null,this.dce=await e.createInstance(),this.dce.refreshInterval=200,this.dce.frameColorMode="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this.dce.on("cameraChange",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("resolutionChange",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("cameraClose",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1})),this.dce.on("singleFrameAcquired",(async e=>{if(!e)return;if(!e.data)return;let t;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,colorMode:e.colorMode,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{data:n,region:i,sx:r,sy:o,width:a,height:s,colorMode:_,timeStamp:d}=e,c={timeStamp:d};if("grey"===_)t=await this._decodeBuffer_Uint8Array(n,a,s,a,l.IPF_GrayScaled,c);else if("rgba"===_)t=await this._decodeBuffer_Uint8Array(n,a,s,4*a,l.IPF_ABGR_8888,c);else{if("bgra"!==_)throw new Error(`Color mode '${_}' is not supported.`);t=await this._decodeBuffer_Uint8Array(n,a,s,4*a,l.IPF_ARGB_8888,c)}await this.clearMapDecodeRecord();for(let e of t)delete e.bUnduplicated;if(this._drawResults(t),ee.fixResultLocationWhenFilterRegionInJs(i,t,r,o,a,s,a,s),this.onFrameRead&&this.isOpen()&&!this._bPauseScan&&this.onFrameRead(t),this.onUniqueRead&&this.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,e)})))}set maxCvsSideLength(e){this._maxCvsSideLength=e,this.dce.maxCvsSideLength=e}get maxCvsSideLength(){return this._maxCvsSideLength}static async createInstance(e){let t=new te;await t.createDCEInstance(),t._instanceID=await te.createInstanceInWorker(!0),"string"==typeof e&&(e=JSON.parse(e));for(let n in e)t[n]=e[n];return await t.setUIElement(te.defaultUIElementURL),t.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),t.singleFrameMode||await t.updateRuntimeSettings("single"),t}async decodeCurrentFrame(e){this._assertOpen();let t=null;e&&e.region&&(t=e.region);const n=this.dce._getVideoFrame(t);return this._decode_DCEFrame(n)}static isRegionNormalPreset(e){return 0==e.regionLeft&&0==e.regionTop&&0==e.regionRight&&0==e.regionBottom&&0==e.regionMeasuredByPercentage}async updateRuntimeSettings(e){let t;if("string"==typeof e)if("speed"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region)}else if("balance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.deblurLevel=3,t.expectedBarcodesCount=512,t.localizationModes=[2,16,0,0,0,0,0,0],t.timeout=1e5}else if("coverage"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.deblurLevel=5,t.expectedBarcodesCount=512,t.scaleDownThreshold=1e5,t.localizationModes=[2,16,4,8,0,0,0,0],t.timeout=1e5}else if("single"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,te.isRegionNormalPreset(e.region)?t.region=null:t.region=e.region,t.expectedBarcodesCount=1,t.localizationModes=[16,2,0,0,0,0,0,0],t.barcodeZoneMinDistanceToImageBorders=0}else t=JSON.parse(e);else{if("object"!=typeof e)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(t=JSON.parse(JSON.stringify(e)),t.region instanceof Array){let n=e.region;[n.regionLeft,n.regionTop,n.regionLeft,n.regionBottom,n.regionMeasuredByPercentage].some((e=>void 0!==e))&&(t.region={regionLeft:n.regionLeft||0,regionTop:n.regionTop||0,regionRight:n.regionRight||0,regionBottom:n.regionBottom||0,regionMeasuredByPercentage:n.regionMeasuredByPercentage||0})}}if(!ee._bUseFullFeature){if(0!=(t.barcodeFormatIds&~(f.BF_ONED|f.BF_QR_CODE|f.BF_PDF417|f.BF_DATAMATRIX))||0!=t.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=t.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}{let e=t.region;if(this.bFilterRegionInJs?this.userDefinedRegion=JSON.parse(JSON.stringify(e)):this.userDefinedRegion=null,e instanceof Array)if(e.length){for(let t=0;t{let i=ee._nextTaskID++;ee._taskCallbackMap.set(i,(t=>{if(t.success){try{this._handleRetJsonString(t.updateReturn)}catch(e){n(e)}return e()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}})),ee._dbrWorker.postMessage({type:"updateRuntimeSettings",id:i,instanceID:this._instanceID,body:{settings:JSON.stringify(t)}})})),"single"==e&&(await this.setModeArgument("BinarizationModes",0,"EnableFillBinaryVacancy","0"),await this.setModeArgument("LocalizationModes",0,"ScanDirection","2"),await this.setModeArgument("BinarizationModes",0,"BlockSizeX","71"),await this.setModeArgument("BinarizationModes",0,"BlockSizeY","71"))}_bindUI(){if(!this.getUIElement())throw new Error("Need to define `UIElement` before opening.");if(this.dce._bindUI(),!this.dce.video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'")}_unbindUI(){this.dce._unbindUI()}set onPlayed(e){this.dce.off("played",this._onPlayed),this._onPlayed=e,this.dce.on("played",this._onPlayed)}get onPlayed(){return this._onPlayed}async getAllCameras(){return this.dce.getAllCameras()}async getCurrentCamera(){return this.dce.getSelectedCamera()}async setCurrentCamera(e){return this.dce.selectCamera(e)}getResolution(){return this.dce.getResolution()}async setResolution(e,t){return this.dce.setResolution(e,t)}getVideoSettings(){return this.dce.getVideoSettings()}updateVideoSettings(e){return this.dce.updateVideoSettings(e)}isOpen(){return this.dce&&this.dce.isOpen()}setVideoFit(e){return this.dce&&this.dce.setVideoFit(e)}set ifShowScanRegionMask(e){this.dce&&(this.dce.ifShowScanRegionMask=e)}get ifShowScanRegionMask(){return this.dce&&this.dce.ifShowScanRegionMask}stop(){this.dce.stop(),this.dce.hideScanRegionLaser(),this.dce.hideViewDecorator(),this.dce.hideScanRegionOverlays(),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}pause(){this._drawResults(null),this.dce.pause()}async play(e,t,n){this.dce.ifShowScanRegionLaser=!0;return await this.dce.play(e,t,n)}pauseScan(){this._assertOpen(),this._drawResults(null),this._bPauseScan=!0,this.dce.ifShowScanRegionLaser=!1}resumeScan(){this._assertOpen(),this._bPauseScan=!1,this.dce.ifShowScanRegionLaser=!0}getCapabilities(){return this.dce.getCapabilities()}getCameraSettings(){return this.dce.getCameraSettings()}getConstraints(){return this.dce.getConstraints()}async applyConstraints(e){return this.dce.applyConstraints(e)}async turnOnTorch(){return this.dce.turnOnTorch()}async turnOffTorch(){return this.dce.turnOffTorch()}async setColorTemperature(e){return this.dce.setColorTemperature(e)}async setExposureCompensation(e){return this.dce.setExposureCompensation(e)}async setZoom(e){return this.dce.setZoom(e)}async setFrameRate(e){return this.dce.setFrameRate(e)}getFrameRate(){return this.dce.getFrameRate()}async setFocus(e,t){return this.dce.setFocus(e,t)}getFocus(){return this.dce.getFocus()}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),void this._drawResults(null);if(!this.isOpen())return this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce.video||this.dce.video.paused||this._bPauseScan)return ee._onLog&&ee._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));ee._onLog&&ee._onLog("======= once read ======="),ee._onLog&&(this._timeStartDecode=Date.now());const e=this._getVideoFrame();if(!e)return this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let t;e._bUseWebGL||"grey"!==e.colorMode||(this.dce.frameColorMode="rgba"),this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,colorMode:e.colorMode,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{data:n,region:i,sx:r,sy:o,width:a,height:s,colorMode:_,timeStamp:d}=e,c={timeStamp:d};if("grey"===_)t=await this._decodeBuffer_Uint8Array(n,a,s,a,l.IPF_GrayScaled,c);else if("rgba"===_)t=await this._decodeBuffer_Uint8Array(n,a,s,4*a,l.IPF_ABGR_8888,c);else{if("bgra"!==_)throw new Error(`Color mode '${_}' is not supported.`);t=await this._decodeBuffer_Uint8Array(n,a,s,4*a,l.IPF_ARGB_8888,c)}return this.dce&&this.dce.video&&!this.dce.video.paused&&this._drawResults(t),ee.fixResultLocationWhenFilterRegionInJs(i,t,r,o,a,s,a,s),t})().then((e=>{ee._onLog&&ee._onLog(e);let t=this.array_decodeFrameTimeCost,n=this.array_getFrameTimeCost,i=this._indexCurrentDecodingFrame;if((()=>{if(this.region instanceof Array){for(t[i]&&t[i]instanceof Array||(t[i]=[]);t[i].length>=5;)t[i].shift();t[i].push(this._lastInnerDecodeDuration)}else{for(;t.length>=5;)t.shift();t.push(this._lastInnerDecodeDuration)}})(),this._intervalGetVideoFrame=(()=>{let e=0;if(this.region instanceof Array){let r=0,o=0;r=i+1>=this.region.length?0:i+1,o=r+1>=this.region.length?0:r+1,e=t[r]&&t[r].length&&n[o]&&n[o].length?Math.min(...t[r])-Math.max(...n[o]):0}else if(n&&n.length){let i=Math.min(...t),r=Math.max(...n);i&&r&&(e=i-r)}else e=0;return e>0?e:0})()+this.intervalTime,this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead)t=!0;else if("unique"===this.bPlaySoundOnSuccessfulRead)for(let n of e)if(n.bUnduplicated){t=!0;break}t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead)t=!0;else if("unique"===this.bVibrateOnSuccessfulRead)for(let n of e)if(n.bUnduplicated){t=!0;break}if(t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onFrameRead){let t=this._cloneDecodeResults(e);for(let e of t)delete e.bUnduplicated;this.onFrameRead(t)}if(this.onUniqueRead)for(let t of e)t.bUnduplicated&&this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t))}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce.stopFetchingLoop(),ee._onLog&&ee._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e=this.dce.isFetchingLoopStarted();if(this.dce.loopInterval=this._intervalGetVideoFrame,e||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dce.loopInterval=0,null;const t=this.dce.getFrameFromBuffer();return(e=>{if(!e)return;let t=e.timeSpent,n=this.array_getFrameTimeCost;for(;n.length>=5;)n.shift();n.push(t)})(t),t}async open(){this._bindUI();let e=await this.dce.open();return this._bPauseScan=!1,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.dce.ifShowScanRegionLaser=!0,this._loopReadVideo()),this.keepAlive(),e}async openVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open();return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideo()),this.keepAlive(),e}close(){this.dce.close(),this._bPauseScan=!0}async show(){this._bindUI();const e=await this.dce.open(!0);return this._bPauseScan=!1,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.dce.ifShowScanRegionLaser=!0,this._loopReadVideo()),this.keepAlive(),e}async showVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open(!0);return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideo()),this.keepAlive(),e}hide(){this.dce.close(!0),this._bPauseScan=!0}destroyContext(){this.close(),this.bDestroyed||super.destroyContext()}}!function(e){e[e.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",e[e.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",e[e.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",e[e.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",e[e.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",e[e.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",e[e.BICM_SKIP=0]="BICM_SKIP",e[e.BICM_REV=2147483648]="BICM_REV"}(E||(E={})),function(e){e[e.BCM_AUTO=1]="BCM_AUTO",e[e.BCM_GENERAL=2]="BCM_GENERAL",e[e.BCM_SKIP=0]="BCM_SKIP",e[e.BCM_REV=2147483648]="BCM_REV"}(S||(S={})),function(e){e[e.BF2_NULL=0]="BF2_NULL",e[e.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",e[e.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",e[e.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",e[e.BF2_POSTNET=2097152]="BF2_POSTNET",e[e.BF2_PLANET=4194304]="BF2_PLANET",e[e.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",e[e.BF2_RM4SCC=16777216]="BF2_RM4SCC",e[e.BF2_DOTCODE=2]="BF2_DOTCODE",e[e.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",e[e.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",e[e.BF2_PHARMACODE=12]="BF2_PHARMACODE"}(T||(T={})),function(e){e[e.BM_AUTO=1]="BM_AUTO",e[e.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",e[e.BM_SKIP=0]="BM_SKIP",e[e.BM_THRESHOLD=4]="BM_THRESHOLD",e[e.BM_REV=2147483648]="BM_REV"}(D||(D={})),function(e){e[e.ECCM_CONTRAST=1]="ECCM_CONTRAST"}(y||(y={})),function(e){e[e.CFM_GENERAL=1]="CFM_GENERAL"}(C||(C={})),function(e){e[e.CCM_AUTO=1]="CCM_AUTO",e[e.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",e[e.CCM_SKIP=0]="CCM_SKIP",e[e.CCM_REV=2147483648]="CCM_REV"}(v||(v={})),function(e){e[e.CICM_GENERAL=1]="CICM_GENERAL",e[e.CICM_SKIP=0]="CICM_SKIP",e[e.CICM_REV=2147483648]="CICM_REV"}(O||(O={})),function(e){e[e.CM_IGNORE=1]="CM_IGNORE",e[e.CM_OVERWRITE=2]="CM_OVERWRITE"}(M||(M={})),function(e){e[e.DM_SKIP=0]="DM_SKIP",e[e.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",e[e.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",e[e.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",e[e.DM_SMOOTHING=8]="DM_SMOOTHING",e[e.DM_MORPHING=16]="DM_MORPHING",e[e.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",e[e.DM_SHARPENING=64]="DM_SHARPENING",e[e.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",e[e.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING"}(b||(b={})),function(e){e[e.DRM_AUTO=1]="DRM_AUTO",e[e.DRM_GENERAL=2]="DRM_GENERAL",e[e.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",e[e.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",e[e.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",e[e.DRM_SKIP=0]="DRM_SKIP",e[e.DRM_REV=2147483648]="DRM_REV"}(L||(L={})),function(e){e[e.DPMCRM_AUTO=1]="DPMCRM_AUTO",e[e.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",e[e.DPMCRM_SKIP=0]="DPMCRM_SKIP",e[e.DPMCRM_REV=2147483648]="DPMCRM_REV"}(w||(w={})),function(e){e[e.GTM_INVERTED=1]="GTM_INVERTED",e[e.GTM_ORIGINAL=2]="GTM_ORIGINAL",e[e.GTM_SKIP=0]="GTM_SKIP",e[e.GTM_REV=2147483648]="GTM_REV"}(B||(B={})),function(e){e[e.IPM_AUTO=1]="IPM_AUTO",e[e.IPM_GENERAL=2]="IPM_GENERAL",e[e.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",e[e.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",e[e.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",e[e.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",e[e.IPM_SKIP=0]="IPM_SKIP",e[e.IPM_REV=2147483648]="IPM_REV"}(N||(N={})),function(e){e[e.IRSM_MEMORY=1]="IRSM_MEMORY",e[e.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",e[e.IRSM_BOTH=4]="IRSM_BOTH"}(F||(F={})),function(e){e[e.IRT_NO_RESULT=0]="IRT_NO_RESULT",e[e.IRT_ORIGINAL_IMAGE=1]="IRT_ORIGINAL_IMAGE",e[e.IRT_COLOUR_CLUSTERED_IMAGE=2]="IRT_COLOUR_CLUSTERED_IMAGE",e[e.IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE=4]="IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE",e[e.IRT_TRANSFORMED_GRAYSCALE_IMAGE=8]="IRT_TRANSFORMED_GRAYSCALE_IMAGE",e[e.IRT_PREDETECTED_REGION=16]="IRT_PREDETECTED_REGION",e[e.IRT_PREPROCESSED_IMAGE=32]="IRT_PREPROCESSED_IMAGE",e[e.IRT_BINARIZED_IMAGE=64]="IRT_BINARIZED_IMAGE",e[e.IRT_TEXT_ZONE=128]="IRT_TEXT_ZONE",e[e.IRT_CONTOUR=256]="IRT_CONTOUR",e[e.IRT_LINE_SEGMENT=512]="IRT_LINE_SEGMENT",e[e.IRT_FORM=1024]="IRT_FORM",e[e.IRT_SEGMENTATION_BLOCK=2048]="IRT_SEGMENTATION_BLOCK",e[e.IRT_TYPED_BARCODE_ZONE=4096]="IRT_TYPED_BARCODE_ZONE",e[e.IRT_PREDETECTED_QUADRILATERAL=8192]="IRT_PREDETECTED_QUADRILATERAL"}(P||(P={})),function(e){e[e.LM_SKIP=0]="LM_SKIP",e[e.LM_AUTO=1]="LM_AUTO",e[e.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",e[e.LM_LINES=8]="LM_LINES",e[e.LM_STATISTICS=4]="LM_STATISTICS",e[e.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",e[e.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",e[e.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",e[e.LM_CENTRE=128]="LM_CENTRE",e[e.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",e[e.LM_REV=2147483648]="LM_REV"}(V||(V={})),function(e){e[e.PDFRM_RASTER=1]="PDFRM_RASTER",e[e.PDFRM_AUTO=2]="PDFRM_AUTO",e[e.PDFRM_VECTOR=4]="PDFRM_VECTOR",e[e.PDFRM_REV=2147483648]="PDFRM_REV"}(x||(x={})),function(e){e[e.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",e[e.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",e[e.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",e[e.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(k||(k={})),function(e){e[e.RPM_AUTO=1]="RPM_AUTO",e[e.RPM_GENERAL=2]="RPM_GENERAL",e[e.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",e[e.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",e[e.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",e[e.RPM_SKIP=0]="RPM_SKIP",e[e.RPM_REV=2147483648]="RPM_REV"}(U||(U={})),function(e){e[e.RCT_PIXEL=1]="RCT_PIXEL",e[e.RCT_PERCENTAGE=2]="RCT_PERCENTAGE"}(G||(G={})),function(e){e[e.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",e[e.RT_RAW_TEXT=1]="RT_RAW_TEXT",e[e.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",e[e.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT"}(H||(H={})),function(e){e[e.SUM_AUTO=1]="SUM_AUTO",e[e.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",e[e.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",e[e.SUM_SKIP=0]="SUM_SKIP",e[e.SUM_REV=2147483648]="SUM_REV"}(W||(W={})),function(e){e[e.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",e[e.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",e[e.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",e[e.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",e[e.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",e[e.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED"}(K||(K={})),function(e){e[e.TFM_AUTO=1]="TFM_AUTO",e[e.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",e[e.TFM_SKIP=0]="TFM_SKIP",e[e.TFM_REV=2147483648]="TFM_REV"}(Y||(Y={})),function(e){e[e.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",e[e.TROM_POSITION=2]="TROM_POSITION",e[e.TROM_FORMAT=4]="TROM_FORMAT",e[e.TROM_SKIP=0]="TROM_SKIP",e[e.TROM_REV=2147483648]="TROM_REV"}(J||(J={})),function(e){e[e.TDM_AUTO=1]="TDM_AUTO",e[e.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",e[e.TDM_SKIP=0]="TDM_SKIP",e[e.TDM_REV=2147483648]="TDM_REV"}(Q||(Q={}));export{ee as BarcodeReader,te as BarcodeScanner,E as EnumBarcodeColourMode,S as EnumBarcodeComplementMode,f as EnumBarcodeFormat,T as EnumBarcodeFormat_2,D as EnumBinarizationMode,y as EnumClarityCalculationMethod,C as EnumClarityFilterMode,v as EnumColourClusteringMode,O as EnumColourConversionMode,M as EnumConflictMode,w as EnumDPMCodeReadingMode,b as EnumDeblurMode,L as EnumDeformationResistingMode,h as EnumErrorCode,B as EnumGrayscaleTransformationMode,g as EnumIMResultDataType,l as EnumImagePixelFormat,N as EnumImagePreprocessingMode,F as EnumIntermediateResultSavingMode,P as EnumIntermediateResultType,V as EnumLocalizationMode,x as EnumPDFReadingMode,k as EnumQRCodeErrorCorrectionLevel,U as EnumRegionPredetectionMode,G as EnumResultCoordinateType,H as EnumResultType,W as EnumScaleUpMode,K as EnumTerminatePhase,Y as EnumTextFilterMode,J as EnumTextResultOrderMode,Q as EnumTextureDetectionMode}; diff --git a/dist/dbr.browser.pure.js b/dist/dbr.browser.pure.js deleted file mode 100644 index 9c409f8..0000000 --- a/dist/dbr.browser.pure.js +++ /dev/null @@ -1,11 +0,0 @@ -/*! - * Dynamsoft JavaScript Library - * @product Dynamsoft Barcode Reader JS Edition - * @website http://www.dynamsoft.com - * @copyright Copyright 2022, Dynamsoft Corporation - * @author Dynamsoft - * @version 9.0.2 (js 20220505) - * @fileoverview Dynamsoft JavaScript Library for Barcode Reader - * More info on DBR JS: https://www.dynamsoft.com/barcode-reader/sdk-javascript/ - */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("dynamsoft-camera-enhancer")):"function"==typeof define&&define.amd?define(["exports","dynamsoft-camera-enhancer"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).Dynamsoft=e.Dynamsoft||{},e.Dynamsoft.DBR={}),e.Dynamsoft.DCE)}(this,(function(e,t){"use strict";const n="undefined"==typeof self;let r;if(!n){const e={init:function(){this.browser=this.searchString(this.dataBrowser)||"unknownBrowser",this.version=this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion)||"unknownVersion",this.OS=this.searchString(this.dataOS)||"unknownOS","Linux"==this.OS&&-1!=navigator.userAgent.indexOf("Windows NT")&&(this.OS="HarmonyOS")},searchString:function(e){for(var t=0;t{let e=!1;if(a)try{(await navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e},d=(()=>{if(!n&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),_=" is not allowed to change after `createInstance` or `loadWasm` is called.",u=!n&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",c=!n&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",l=e=>{if(null==e)e=[];else{e=e instanceof Array?[...e]:[e];for(let t=0;te&&"object"==typeof e&&"function"==typeof e.then;var p=function(){this.init()};p.prototype={init:function(){var e=this||R;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var t=this||R;if(e=parseFloat(e),t.ctx||ee(),void 0!==e&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,R.ctx.currentTime);for(var n=0;n=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,ee()),e},codecs:function(e){return(this||R)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||R;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||R,t=null;try{t="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!t||"function"!=typeof t.canPlayType)return e;var n=t.canPlayType("audio/mpeg;").replace(/^no$/,""),r=e._navigator?e._navigator.userAgent:"",i=r.match(/OPR\/([0-6].)/g),o=i&&parseInt(i[0].split("/")[1],10)<33,a=-1!==r.indexOf("Safari")&&-1===r.indexOf("Chrome"),s=r.match(/Version\/(.*?) /),d=a&&s&&parseInt(s[1],10)<15;return e._codecs={mp3:!(o||!n&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!n,opus:!!t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(t.canPlayType('audio/wav; codecs="1"')||t.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!t.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!t.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/m4a;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(t.canPlayType("audio/x-m4b;")||t.canPlayType("audio/m4b;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(t.canPlayType("audio/x-mp4;")||t.canPlayType("audio/mp4;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(d||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(d||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!t.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(t.canPlayType("audio/x-flac;")||t.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||R;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var t=function(n){for(;e._html5AudioPool.length0?a._seek:n._sprite[e][0]/1e3),_=Math.max(0,(n._sprite[e][0]+n._sprite[e][1])/1e3-d),u=1e3*_/Math.abs(a._rate),c=n._sprite[e][0]/1e3,l=(n._sprite[e][0]+n._sprite[e][1])/1e3;a._sprite=e,a._ended=!1;var h=function(){a._paused=!1,a._seek=d,a._start=c,a._stop=l,a._loop=!(!a._loop&&!n._sprite[e][2])};if(!(d>=l)){var g=a._node;if(n._webAudio){var m=function(){n._playLock=!1,h(),n._refreshBuffer(a);var e=a._muted||n._muted?0:a._volume;g.gain.setValueAtTime(e,R.ctx.currentTime),a._playStart=R.ctx.currentTime,void 0===g.bufferSource.start?a._loop?g.bufferSource.noteGrainOn(0,d,86400):g.bufferSource.noteGrainOn(0,d,_):a._loop?g.bufferSource.start(0,d,86400):g.bufferSource.start(0,d,_),u!==1/0&&(n._endTimers[a._id]=setTimeout(n._ended.bind(n,a),u)),t||setTimeout((function(){n._emit("play",a._id),n._loadQueue()}),0)};"running"===R.state&&"interrupted"!==R.ctx.state?m():(n._playLock=!0,n.once("resume",m),n._clearTimer(a._id))}else{var f=function(){g.currentTime=d,g.muted=a._muted||n._muted||R._muted||g.muted,g.volume=a._volume*R.volume(),g.playbackRate=a._rate;try{var r=g.play();if(r&&"undefined"!=typeof Promise&&(r instanceof Promise||"function"==typeof r.then)?(n._playLock=!0,h(),r.then((function(){n._playLock=!1,g._unlocked=!0,t?n._loadQueue():n._emit("play",a._id)})).catch((function(){n._playLock=!1,n._emit("playerror",a._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),a._ended=!0,a._paused=!0}))):t||(n._playLock=!1,h(),n._emit("play",a._id)),g.playbackRate=a._rate,g.paused)return void n._emit("playerror",a._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||a._loop?n._endTimers[a._id]=setTimeout(n._ended.bind(n,a),u):(n._endTimers[a._id]=function(){n._ended(a),g.removeEventListener("ended",n._endTimers[a._id],!1)},g.addEventListener("ended",n._endTimers[a._id],!1))}catch(e){n._emit("playerror",a._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===g.src&&(g.src=n._src,g.load());var A=window&&window.ejecta||!g.readyState&&R._navigator.isCocoonJS;if(g.readyState>=3||A)f();else{n._playLock=!0,n._state="loading";var p=function(){n._state="loaded",f(),g.removeEventListener(R._canPlayEvent,p,!1)};g.addEventListener(R._canPlayEvent,p,!1),n._clearTimer(a._id)}}return a._id}n._ended(a)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var n=t._getSoundIds(e),r=0;r=0?t=parseInt(i[0],10):e=parseFloat(i[0])}else i.length>=2&&(e=parseFloat(i[0]),t=parseInt(i[1],10));if(!(void 0!==e&&e>=0&&e<=1))return(n=t?r._soundById(t):r._sounds[0])?n._volume:0;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"volume",action:function(){r.volume.apply(r,i)}}),r;void 0===t&&(r._volume=e),t=r._getSoundIds(t);for(var s=0;s0?r/_:r),c=Date.now();e._fadeTo=n,e._interval=setInterval((function(){var i=(Date.now()-c)/r;c=Date.now(),s+=d*i,s=Math.round(100*s)/100,s=d<0?Math.max(n,s):Math.min(n,s),a._webAudio?e._volume=s:a.volume(s,e._id,!0),o&&(a._volume=s),(nt&&s>=n)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,a.volume(n,e._id),a._emit("fade",e._id))}),u)},_stopFade:function(e){var t=this,n=t._soundById(e);return n&&n._interval&&(t._webAudio&&n._node.gain.cancelScheduledValues(R.ctx.currentTime),clearInterval(n._interval),n._interval=null,t.volume(n._fadeTo,e),n._fadeTo=null,t._emit("fade",e)),t},loop:function(){var e,t,n,r=this,i=arguments;if(0===i.length)return r._loop;if(1===i.length){if("boolean"!=typeof i[0])return!!(n=r._soundById(parseInt(i[0],10)))&&n._loop;e=i[0],r._loop=e}else 2===i.length&&(e=i[0],t=parseInt(i[1],10));for(var o=r._getSoundIds(t),a=0;a=0?t=parseInt(i[0],10):e=parseFloat(i[0])}else 2===i.length&&(e=parseFloat(i[0]),t=parseInt(i[1],10));if("number"!=typeof e)return(n=r._soundById(t))?n._rate:r._rate;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"rate",action:function(){r.rate.apply(r,i)}}),r;void 0===t&&(r._rate=e),t=r._getSoundIds(t);for(var s=0;s=0?t=parseInt(r[0],10):n._sounds.length&&(t=n._sounds[0]._id,e=parseFloat(r[0]))}else 2===r.length&&(e=parseFloat(r[0]),t=parseInt(r[1],10));if(void 0===t)return 0;if("number"==typeof e&&("loaded"!==n._state||n._playLock))return n._queue.push({event:"seek",action:function(){n.seek.apply(n,r)}}),n;var a=n._soundById(t);if(a){if(!("number"==typeof e&&e>=0)){if(n._webAudio){var s=n.playing(t)?R.ctx.currentTime-a._playStart:0,d=a._rateSeek?a._rateSeek-a._seek:0;return a._seek+(d+s*Math.abs(a._rate))}return a._node.currentTime}var _=n.playing(t);_&&n.pause(t,!0),a._seek=e,a._ended=!1,n._clearTimer(t),n._webAudio||!a._node||isNaN(a._node.duration)||(a._node.currentTime=e);var u=function(){_&&n.play(t,!0),n._emit("seek",t)};if(_&&!n._webAudio){var c=function(){n._playLock?setTimeout(c,0):u()};setTimeout(c,0)}else u()}return n},playing:function(e){var t=this;if("number"==typeof e){var n=t._soundById(e);return!!n&&!n._paused}for(var r=0;r=0&&R._howls.splice(r,1);var i=!0;for(n=0;n=0){i=!1;break}return Z&&i&&delete Z[e._src],R.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,n,r){var i=this["_on"+e];return"function"==typeof t&&i.push(r?{id:n,fn:t,once:r}:{id:n,fn:t}),this},off:function(e,t,n){var r=this,i=r["_on"+e],o=0;if("number"==typeof t&&(n=t,t=null),t||n)for(o=0;o=0;o--)i[o].id&&i[o].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,n)}.bind(r,i[o].fn),0),i[o].once&&r.off(e,i[o].fn,i[o].id));return r._loadQueue(e),r},_loadQueue:function(e){var t=this;if(t._queue.length>0){var n=t._queue[0];n.event===e&&(t._queue.shift(),t._loadQueue()),e||n.action()}return t},_ended:function(e){var t=this,n=e._sprite;if(!t._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;r--){if(n<=t)return;e._sounds[r]._ended&&(e._webAudio&&e._sounds[r]._node&&e._sounds[r]._node.disconnect(0),e._sounds.splice(r,1),n--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],n=0;n=0;if(!e.bufferSource)return this;if(R._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))try{e.bufferSource.buffer=R._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(R._navigator&&R._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var I=function(e){this._parent=e,this.init()};I.prototype={init:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++R._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,n=R._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=void 0===R.ctx.createGain?R.ctx.createGainNode():R.ctx.createGain(),e._node.gain.setValueAtTime(n,R.ctx.currentTime),e._node.paused=!0,e._node.connect(R.masterGain)):R.noAudio||(e._node=R._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(R._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=t._src,e._node.preload=!0===t._preload?"auto":t._preload,e._node.volume=n*R.volume(),e._node.load()),e},reset:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++R._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,t=e._parent;t._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(t._sprite).length&&(t._sprite={__default:[0,1e3*t._duration]}),"loaded"!==t._state&&(t._state="loaded",t._emit("load"),t._loadQueue()),e._node.removeEventListener(R._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var S,T,D,y,C,v,M,O,b,L,w,B,F,N,P,V,x,k,U,G,H,W,K,Y,Q,J,X,Z={},j=function(e){var t=e._src;if(Z[t])return e._duration=Z[t].duration,void $(e);if(/^data:[^;]+;base64,/.test(t)){for(var n=atob(t.split(",")[1]),r=new Uint8Array(n.length),i=0;i0?(Z[t._src]=e,$(t,e)):n()};"undefined"!=typeof Promise&&1===R.ctx.decodeAudioData.length?R.ctx.decodeAudioData(e).then(r).catch(n):R.ctx.decodeAudioData(e,r,n)},$=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},ee=function(){if(R.usingWebAudio){try{"undefined"!=typeof AudioContext?R.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?R.ctx=new webkitAudioContext:R.usingWebAudio=!1}catch(e){R.usingWebAudio=!1}R.ctx||(R.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(R._navigator&&R._navigator.platform),t=R._navigator&&R._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),n=t?parseInt(t[1],10):null;if(e&&n&&n<9){var r=/safari/.test(R._navigator&&R._navigator.userAgent.toLowerCase());R._navigator&&!r&&(R.usingWebAudio=!1)}R.usingWebAudio&&(R.masterGain=void 0===R.ctx.createGain?R.ctx.createGainNode():R.ctx.createGain(),R.masterGain.gain.setValueAtTime(R._muted?0:R._volume,R.ctx.currentTime),R.masterGain.connect(R.ctx.destination)),R._setup()}};!function(e,t,n,r){var i;e.prototype._pos=[0,0,0],e.prototype._orientation=[0,0,-1,0,1,0],e.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var n=t._howls.length-1;n>=0;n--)t._howls[n].stereo(e);return t},e.prototype.pos=function(e,n,r){var i=this;return i.ctx&&i.ctx.listener?(n="number"!=typeof n?i._pos[1]:n,r="number"!=typeof r?i._pos[2]:r,"number"!=typeof e?i._pos:(i._pos=[e,n,r],void 0!==i.ctx.listener.positionX?(i.ctx.listener.positionX.setTargetAtTime(i._pos[0],t.ctx.currentTime,.1),i.ctx.listener.positionY.setTargetAtTime(i._pos[1],t.ctx.currentTime,.1),i.ctx.listener.positionZ.setTargetAtTime(i._pos[2],t.ctx.currentTime,.1)):i.ctx.listener.setPosition(i._pos[0],i._pos[1],i._pos[2]),i)):i},e.prototype.orientation=function(e,n,r,i,o,a){var s=this;if(!s.ctx||!s.ctx.listener)return s;var d=s._orientation;return n="number"!=typeof n?d[1]:n,r="number"!=typeof r?d[2]:r,i="number"!=typeof i?d[3]:i,o="number"!=typeof o?d[4]:o,a="number"!=typeof a?d[5]:a,"number"!=typeof e?d:(s._orientation=[e,n,r,i,o,a],void 0!==s.ctx.listener.forwardX?(s.ctx.listener.forwardX.setTargetAtTime(e,t.ctx.currentTime,.1),s.ctx.listener.forwardY.setTargetAtTime(n,t.ctx.currentTime,.1),s.ctx.listener.forwardZ.setTargetAtTime(r,t.ctx.currentTime,.1),s.ctx.listener.upX.setTargetAtTime(i,t.ctx.currentTime,.1),s.ctx.listener.upY.setTargetAtTime(o,t.ctx.currentTime,.1),s.ctx.listener.upZ.setTargetAtTime(a,t.ctx.currentTime,.1)):s.ctx.listener.setOrientation(e,n,r,i,o,a),s)},n.prototype.init=(i=n.prototype.init,function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],i.call(this,e)}),n.prototype.stereo=function(e,n){var r=this;if(!r._webAudio)return r;if("loaded"!==r._state)return r._queue.push({event:"stereo",action:function(){r.stereo(e,n)}}),r;var i=void 0===t.ctx.createStereoPanner?"spatial":"stereo";if(void 0===n){if("number"!=typeof e)return r._stereo;r._stereo=e,r._pos=[e,0,0]}for(var a=r._getSoundIds(n),s=0;s{console.warn(`Sound '${e}' playback failure: ${t}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.barcodeFillStyle="rgba(254,180,32,0.3)",this.barcodeStrokeStyle="rgba(254,180,32,0.9)",this.barcodeLineWidth=1,this._dce=null,this.dceConfig={},this.imgSource=null,this._maxCvsSideLength="iPhone"==r.OS||"Android"==r.OS?2048:4096,this._tempSolutionStatus="closed"}static get version(){return this._version}static get license(){return this._license}static set license(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`license`"+_);n._license=t})(te,e)}static get productKeys(){return this._license}static set productKeys(e){te.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){te.license=e}static get organizationID(){return this._license}static set organizationID(e){te.license=e}static set sessionPassword(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`sessionPassword`"+_);n._sessionPassword=t})(te,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:i,worker:o,getUserMedia:a,camera:await s(),browser:r.browser,version:r.version,OS:r.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(e){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");te._engineResourcePath=(e=>{if(null==e&&(e="./"),!n){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`licenseServer`"+_);n._licenseServer=l(t)})(te,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+_);n._deviceFriendlyName=t||""})(te,e)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(e){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");te.__bUseFullFeature=e}static isImageSource(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"getImage"in e}static isDSImage(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("width"in e&&("height"in e&&"pixelFormat"in e)))}static isCameraEnhancer(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("referenceConfigurationArray"in e&&("isOpen"in e&&("on"in e&&("off"in e&&("startFetchingLoop"in e&&("stopFetchingLoop"in e&&("getUIElement"in e&&("video"in e&&("isFetchingLoopStarted"in e&&("numberOfFramesInBuffer"in e&&("getFrameFromBuffer"in e&&("addScanRegionOverlayCanvas"in e&&("ifShowScanRegionLaser"in e&&("open"in e&&"close"in e))))))))))))))}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("region"in e&&("sx"in e&&("sy"in e&&("width"in e&&("height"in e&&("colorMode"in e&&("timeSpent"in e&&("timeStamp"in e&&("isCropped"in e&&("toCanvas"in e&&"_bUseWebGL"in e)))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(e){this._region=e,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var e;return null===(e=te._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",te.engineResourcePath)}static set defaultUIElementURL(e){te._defaultUIElementURL=e}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new E({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(e){this.bPlaySoundOnSuccessfulRead="never"!==e&&e}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(e){this.bVibrateOnSuccessfulRead="never"!==e&&e}set dce(e){this._dce=e}get dce(){return te.isCameraEnhancer(this._dce)?this._dce:null}set maxCvsSideLength(e){this._maxCvsSideLength=e,this.dceConfig.maxCvsSideLength=e}get maxCvsSideLength(){return this._maxCvsSideLength}updateDCEConfig(){if(!this.dce)return;te._onLog&&te._onLog("updateDCEConfig()"),this.dceConfig={bufferRefreshInterval:200,maxCvsSideLength:this._maxCvsSideLength};let e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);for(;-1!==e;)this.dce.referenceConfigurationArray.splice(e,1),e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);this.dce.referenceConfigurationArray.push(this.dceConfig),this.callbackCameraChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async e=>{let t=await this._decode_DCEFrame(e,{bCopyData:!1});await this.clearMapDecodeRecord();for(let e of t)delete e.bUnduplicated;if(this._drawResults(t),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan&&this.onImageRead(t),this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,e)},this.dce.on("cameraChange",this.callbackCameraChange),this.dce.on("resolutionChange",this.callbackResolutionChange),this.dce.on("cameraClose",this.callbackCameraClose),this.dce.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}releaseDCEConfig(){if(this.dce){if(te._onLog&&te._onLog("releaseDCEConfig()"),this.dce&&te.isCameraEnhancer(this.dce)){let e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);for(;-1!==e;)this.dce.referenceConfigurationArray.splice(e,1),e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);if(this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this.dce.stopFetchingLoop(),this.resultsOverlay){let e=this.dce._arrScanRegionOverlays.indexOf(this.resultsOverlay);for(;-1!==e;)this.dce._arrScanRegionOverlays.splice(e,1),e=this.dce._arrScanRegionOverlays.indexOf(this.resultsOverlay);this.resultsOverlay.remove(),this.resultsOverlay=null}}this.dce=null}}setImageSource(e){if(null==e)return this.imgSource=null,void this.releaseDCEConfig();if(te.isCameraEnhancer(e))this.dce=e,this.updateDCEConfig(),this.imgSource=null;else{if(!te.isImageSource(e))throw new Error("Invalid value.");this.releaseDCEConfig(),this.imgSource=e}}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:e,l:t,ls:n,sp:i,rmk:o}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,n,r=t._license||"",i=JSON.parse(JSON.stringify(t._licenseServer)),o=t._sessionPassword,a=0;if(r.startsWith("t")||r.startsWith("f"))a=0;else if(0===r.length||r.startsWith("P")||r.startsWith("L")||r.startsWith("Y")||r.startsWith("A"))a=1;else{a=2;const t=r.indexOf(":");if(-1!=t&&(r=r.substring(t+1)),r.startsWith("DLS2")){let t=r.substring(4);try{t=atob(t)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}const n=JSON.parse(t);if(r=n.handshakeCode?n.handshakeCode:n.organizationID?n.organizationID:"","number"==typeof r&&(r=JSON.stringify(r)),0===i.length){let e=[];n.mainServerURL&&(e[0]=n.mainServerURL),n.standbyServerURL&&(e[1]=n.standbyServerURL),i=l(e)}!o&&n.sessionPassword&&(o=n.sessionPassword),e=n.remark}("200001"===r||r.startsWith("200001-"))&&(i&&i.length||(r="")),r||(a=1)}if(a&&(globalThis.crypto||(n="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(n="Require https to use online key in this browser.")),n){if(1!==a)throw new Error(n);a=0,console.warn(n),t._lastErrorCode=-1,t._lastErrorString=n}return 1===a&&(r="",console.warn("Applying for a public trial license ...")),{lt:a,l:r,ls:i,sp:o,rmk:e}}throw new Error("Can't preprocess license again"+_)})(te);this._pLoad.task=async(a,s)=>{let d=te.engineResourcePath+te._workerName;te.engineResourcePath.startsWith(location.origin)||(d=await fetch(d).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),te._dbrWorker=new Worker(d),te._dbrWorker.onerror=e=>{let t=new Error(e.message);s(t)},te._dbrWorker.onmessage=async t=>{let n=t.data?t.data:t;switch(n.type){case"log":te._onLog&&te._onLog(n.message);break;case"load":{n.message&&(n.message=n.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,r=!1;1===e&&(r=!0),n.success?(te._dbrWorker.onerror=null,te._version=n.version+"(JS "+te._jsVersion+"."+te._jsEditVersion+")",te._onLog&&te._onLog("load dbr worker success"),n.message&&console.warn(n.message)):(t=new Error(n.message),t.stack=n.stack+"\n"+t.stack,r||111==n.ltsErrorCode&&-1!=n.message.toLowerCase().indexOf("trial license")&&(r=!0)),r&&te.showDialog(n.success?"warn":"error",n.message),n.success?a():s(t);break}case"task":{let e=n.id,t=n.body;try{te._taskCallbackMap.get(e)(t),te._taskCallbackMap.delete(e)}catch(t){throw te._taskCallbackMap.delete(e),t}break}default:te._onLog&&te._onLog(t)}},te._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:te.engineResourcePath,bUseFullFeature:te._bUseFullFeature,bd:te._bWasmDebug,v:te._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:r,fn:te.deviceFriendlyName,ls:n,sp:i,rmk:o})}}await this._pLoad}static async showDialog(e,t){if(!te._bNeverShowDialog)try{let n=await fetch(te.engineResourcePath+"dls.license.dialog.html");if(!n.ok)throw Error("Get license dialog fail. Network Error: "+n.statusText);let r=await n.text();if(!r.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let i=document.createElement("div");i.innerHTML=r;let o=[];for(let e=0;e{if(n==e.target){a.remove();for(let e of o)e.remove()}}));else if(!d&&n.classList.contains("dls-license-icon-close"))d=n,n.addEventListener("click",(()=>{a.remove();for(let e of o)e.remove()}));else if(!_&&n.classList.contains("dls-license-icon-error"))_=n,"error"!=e&&n.remove();else if(!u&&n.classList.contains("dls-license-icon-warn"))u=n,"warn"!=e&&n.remove();else if(!c&&n.classList.contains("dls-license-msg-content")){c=n;let e=t;for(;e;){let t=e.indexOf("["),r=e.indexOf("]",t),i=e.indexOf("(",r),o=e.indexOf(")",i);if(-1==t||-1==r||-1==i||-1==o){n.appendChild(new Text(e));break}t>0&&n.appendChild(new Text(e.substring(0,t)));let a=document.createElement("a"),s=e.substring(t+1,r);a.innerText=s;let d=e.substring(i+1,o);a.setAttribute("href",d),a.setAttribute("target","_blank"),n.appendChild(a),e=e.substring(o+1)}}document.body.appendChild(a)}catch(e){te._onLog&&te._onLog(e.message||e)}}static async createInstanceInWorker(e=!1){return await te.loadWasm(),await new Promise(((t,n)=>{let r=te._nextTaskID++;te._taskCallbackMap.set(r,(e=>{if(e.success)return t(e.instanceID);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),te._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}static async createInstance(){let e=new te;return e._instanceID=await te.createInstanceInWorker(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let n=te._nextTaskID++;te._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),te._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:n,instanceID:this._instanceID})}))}async decode(e){te._onLog&&te._onLog("decode(source: any)"),te._onLog&&(this._timeStartDecode=Date.now());{let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),e instanceof Blob?await this._decode_Blob(e,t):e instanceof ArrayBuffer?await this._decode_ArrayBuffer(e,t):e instanceof Uint8Array||e instanceof Uint8ClampedArray?await this._decode_Uint8Array(e,t):e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?await this._decode_Image(e,t):e instanceof HTMLCanvasElement?await this._decode_Canvas(e,t):e instanceof HTMLVideoElement?await this._decode_Video(e,t):"string"==typeof e?"data:image/"==e.substring(0,11)?await this._decode_Base64(e,t):await this._decode_Url(e,t):te.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):te.isDSImage(e)?(t.bCopyData=!0,await this._decode_DSImage(e,t)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(e,t)}async decodeUrl(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(e,t)}async _decodeBuffer_Uint8Array(e,t,n,r,i,o){return await new Promise(((a,s)=>{let d=te._nextTaskID++;te._taskCallbackMap.set(d,(e=>{if(e.success){let t,n=te._onLog?Date.now():0;te._onLog&&te._onLog("worker return result: "+n),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return s(e)}if(te._onLog){let e=Date.now();te._onLog("DBR time get result: "+n),te._onLog("Handle image cost: "+(this._timeEnterInnerDBR-this._timeStartDecode)),te._onLog("DBR worker decode image cost: "+(n-this._timeEnterInnerDBR)),te._onLog("DBR worker handle results: "+(e-n)),te._onLog("Total decode image cost: "+(e-this._timeStartDecode))}return a(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,s(t)}})),this._timeEnterInnerDBR=Date.now(),te._onLog&&te._onLog("Send buffer to worker:"+this._timeEnterInnerDBR),te._dbrWorker.postMessage({type:"decodeBuffer",id:d,instanceID:this._instanceID,body:{buffer:e,width:t,height:n,stride:r,format:i,config:o}},[e.buffer]),te._onLog&&o&&o.timeStamp&&te._onLog("decode image delay: "+(this._timeEnterInnerDBR-o.timeStamp))}))}async _decodeBuffer_Blob(e,t,n,r,i,o){te._onLog&&te._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const a=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,n)=>{let r=new FileReader;r.readAsArrayBuffer(e),r.onload=()=>{t(r.result)},r.onerror=()=>{n(r.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(a),t,n,r,i,o)}async decodeBuffer(e,t,n,r,i,o){let a;return te._onLog&&te._onLog("decodeBuffer(buffer,width,height,stride,format)"),te._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?a=await this._decodeBuffer_Uint8Array(e,t,n,r,i,o):e instanceof ArrayBuffer?a=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,n,r,i,o):e instanceof Blob&&(a=await this._decodeBuffer_Blob(e,t,n,r,i,o)),a}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,n)=>{let r=te._nextTaskID++;te._taskCallbackMap.set(r,(e=>{if(e.success){let r;this._lastInnerDecodeDuration=e.duration;try{r=this._handleRetJsonString(e.decodeReturn)}catch(e){return n(e)}return t(r)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),te._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let n=te._nextTaskID++;te._taskCallbackMap.set(n,(n=>{if(n.success){let t=JSON.parse(n.results);return null!=this.userDefinedRegion&&(t.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),e(t)}{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),te._dbrWorker.postMessage({type:"getRuntimeSettings",id:n,instanceID:this._instanceID})}))}async updateRuntimeSettings(t){let n;if("string"==typeof t)if("speed"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,n.region=e.region,n.deblurLevel=3,n.expectedBarcodesCount=0,n.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,n.region=e.region,n.deblurLevel=5,n.expectedBarcodesCount=512,n.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,n.region=e.region}else n=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(n=JSON.parse(JSON.stringify(t)),n.region instanceof Array){let e=n.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(n.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!te._bUseFullFeature){if(0!=(n.barcodeFormatIds&~(e.EnumBarcodeFormat.BF_ONED|e.EnumBarcodeFormat.BF_QR_CODE|e.EnumBarcodeFormat.BF_PDF417|e.EnumBarcodeFormat.BF_DATAMATRIX))||0!=n.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=n.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let e=n.region;if(e instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(e)),(e.regionLeft||e.regionTop||e.regionRight||e.regionBottom||e.regionMeasuredByPercentage)&&(e.regionLeft||e.regionTop||100!=e.regionRight||100!=e.regionBottom||!e.regionMeasuredByPercentage)?this.region=e:this.region=null,n.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return await new Promise(((e,t)=>{let r=te._nextTaskID++;te._taskCallbackMap.set(r,(n=>{if(n.success){try{this._handleRetJsonString(n.updateReturn)}catch(e){t(e)}return e()}{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),te._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(n)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,await new Promise(((e,t)=>{let n=te._nextTaskID++;te._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),te._dbrWorker.postMessage({type:"resetRuntimeSettings",id:n,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!te._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((e,t)=>{let n=te._nextTaskID++;te._taskCallbackMap.set(n,(n=>{if(n.success)return e(n.results);{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),te._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:n,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!te._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof e)e=e;else{if("object"!=typeof e)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");e=JSON.stringify(e)}return await new Promise(((t,n)=>{let r=te._nextTaskID++;te._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.initReturn)}catch(e){n(e)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),te._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){te._onLog&&te._onLog("_decode_Blob(blob: Blob)");let n=null,r=null;if("undefined"!=typeof createImageBitmap)try{n=await createImageBitmap(e)}catch(e){}n||(r=await function(e){return new Promise(((t,n)=>{let r=URL.createObjectURL(e),i=new Image;i.dbrObjUrl=r,i.src=r,i.onload=()=>{t(i)},i.onerror=e=>{n(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let i=await this._decode_Image(n||r,t);return n&&n.close(),i}async _decode_ArrayBuffer(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Uint8Array(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Image(e,t){te._onLog&&te._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),t=t||{};let n,r,i=e instanceof HTMLImageElement?e.naturalWidth:e.width,o=e instanceof HTMLImageElement?e.naturalHeight:e.height,a=Math.max(i,o);if(a>this._maxCvsSideLength){let e=this._maxCvsSideLength/a;n=Math.round(i*e),r=Math.round(o*e)}else n=i,r=o;this.canvas||(this.canvas=document.createElement("canvas"));const s=this.canvas;s.width===n&&s.height===r||(s.width=n,s.height=r),s.ctx2d||(s.ctx2d=s.getContext("2d"));return s.ctx2d.drawImage(e,0,0,i,o,0,0,n,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._decode_Canvas(s,t)}async _decode_Canvas(t,n){if(te._onLog&&te._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if(0===t.width||0===t.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=t,this.oriCanvasData=null);let r=(t.ctx2d||t.getContext("2d")).getImageData(0,0,t.width,t.height).data;return await this._decodeBuffer_Uint8Array(r,t.width,t.height,4*t.width,e.EnumImagePixelFormat.IPF_ABGR_8888,n)}async _decode_Video(e,t){if(te._onLog&&te._onLog("_decode_Video(video)"),!(e instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";t=t||{};let n,r,i=e.videoWidth,o=e.videoHeight,a=Math.max(i,o);if(a>this._maxCvsSideLength){let e=this._maxCvsSideLength/a;n=Math.round(i*e),r=Math.round(o*e)}else n=i,r=o;this.canvas||(this.canvas=document.createElement("canvas"));const s=this.canvas;s.width===n&&s.height===r||(s.width=n,s.height=r),s.ctx2d||(s.ctx2d=s.getContext("2d"));return s.ctx2d.drawImage(e,0,0,i,o,0,0,n,r),await this._decode_Canvas(s,t)}async _decode_DCEFrame(t,n){if(te._onLog&&te._onLog("_decode_DCEFrame(dceFrame)"),!te.isDCEFrame(t))return null;let r;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{width:i,height:o,colorMode:a,timeStamp:s}=t;let d;d=n&&n.bCopyData?new Uint8Array(t.data):t.data;let _=null;if(n?(_=JSON.parse(JSON.stringify(n)),_.timeStamp=s):_={timeStamp:s},"grey"===a)r=await this._decodeBuffer_Uint8Array(d,i,o,i,e.EnumImagePixelFormat.IPF_GrayScaled,_);else if("rgba"===a)r=await this._decodeBuffer_Uint8Array(d,i,o,4*i,e.EnumImagePixelFormat.IPF_ABGR_8888,_);else{if("bgra"!==a)throw new Error(`Color mode '${a}' is not supported to decode.`);r=await this._decodeBuffer_Uint8Array(d,i,o,4*i,e.EnumImagePixelFormat.IPF_ARGB_8888,_)}return r}async _decode_DSImage(t,n){if(te._onLog&&te._onLog("_decode_DSImage(dsImage)"),!te.isDSImage(t))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat.toLowerCase(),data:new Uint8Array(t.data),toCanvas:function(){const e=document.createElement("canvas");let t;switch(e.width=this.width,e.height=this.height,this.pixelFormat){case"grey":t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{let r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="blob",r.send(),r.onloadend=async()=>{t(r.response)},r.onerror=()=>{n(new Error("Network Error: "+r.statusText))}}));return await this._decode_Blob(n,t)}}async _decode_FilePath(e,t){throw te._onLog&&te._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static fixResultLocationWhenFilterRegionInJs(e,t,n,r,i,o,a,s){if(e&&t.length>0)for(let e of t){let t=e.localizationResult;2==t.resultCoordinateType&&(t.x1*=.01*a,t.x2*=.01*a,t.x3*=.01*a,t.x4*=.01*a,t.y1*=.01*s,t.y2*=.01*s,t.y3*=.01*s,t.y4*=.01*s);let d=a/i,_=s/o;t.x1=t.x1/d+n,t.x2=t.x2/d+n,t.x3=t.x3/d+n,t.x4=t.x4/d+n,t.y1=t.y1/_+r,t.y2=t.y2/_+r,t.y3=t.y3/_+r,t.y4=t.y4/_+r,2==t.resultCoordinateType&&(t.x1*=100/i,t.x2*=100/i,t.x3*=100/i,t.x4*=100/i,t.y1*=100/o,t.y2*=100/o,t.y3*=100/o,t.y4*=100/o)}}static BarcodeReaderException(t,n){let r,i=e.EnumErrorCode.DBR_UNKNOWN;return"number"==typeof t?(i=t,r=new Error(n)):r=new Error(t),r.code=i,r}_handleRetJsonString(t){let n=e.EnumErrorCode;if(t.textResults){for(let e=0;e{let n=t.indexOf(":");e[t.substring(0,n)]=t.substring(n+1)})),n.exception=e}}return t.decodeRecords?this.decodeRecords=t.decodeRecords:this.decodeRecords={},this._lastErrorCode=t.exception,this._lastErrorString=t.description,t.exception&&!te._setWarnnedEx.has(t.description)&&(te._setWarnnedEx.add(t.description),console.warn(t.description)),t.textResults}if(t.exception==n.DBR_SUCCESS)return t.data;throw te.BarcodeReaderException(t.exception,t.description)}async setModeArgument(e,t,n,r){return await new Promise(((i,o)=>{let a=te._nextTaskID++;te._taskCallbackMap.set(a,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return o(e)}return i()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,o(t)}})),te._dbrWorker.postMessage({type:"setModeArgument",id:a,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:n,argumentValue:r}})}))}async getModeArgument(e,t,n){return await new Promise(((r,i)=>{let o=te._nextTaskID++;te._taskCallbackMap.set(o,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return i(e)}return r(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),te._dbrWorker.postMessage({type:"getModeArgument",id:o,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:n}})}))}async getIntermediateResults(){return await new Promise(((e,t)=>{let n=te._nextTaskID++;te._taskCallbackMap.set(n,(n=>{if(n.success)return e(n.results);{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),te._dbrWorker.postMessage({type:"getIntermediateResults",id:n,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let t=await this.getIntermediateResults(),n=[];for(let r of t)if(r.dataType==e.EnumIMResultDataType.IMRDT_IMAGE)for(let t of r.results){const r=t.bytes;let i;switch(te._onLog&&te._onLog(" "+r.length+" "+r.byteLength+" "+t.width+" "+t.height+" "+t.stride+" "+t.format),t.format){case e.EnumImagePixelFormat.IPF_ABGR_8888:i=new Uint8ClampedArray(r);break;case e.EnumImagePixelFormat.IPF_RGB_888:{const e=r.length/3;i=new Uint8ClampedArray(4*e);for(let t=0;t{let n=te._nextTaskID++;te._taskCallbackMap.set(n,(n=>{if(n.success){let t=n.results;return t.intervalTime=this.intervalTime,t.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,t.soundOnSuccessfullRead=this.soundSource,t.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,t.vibrateDuration=this.vibrateDuration,e(t)}{let e=new Error(n.message);return e.stack+="\n"+n.stack,t(e)}})),te._dbrWorker.postMessage({type:"getScanSettings",id:n,instanceID:this._instanceID})}))}async updateScanSettings(e){if(!e)return;const t=JSON.parse(JSON.stringify(e));return t.hasOwnProperty("intervalTime")&&(this.intervalTime=t.intervalTime,delete t.intervalTime),t.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=t.whenToPlaySoundforSuccessfulRead,delete t.whenToPlaySoundforSuccessfulRead),t.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=t.soundOnSuccessfullRead,delete t.soundOnSuccessfullRead),t.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=t.whenToVibrateforSuccessfulRead,delete t.whenToVibrateforSuccessfulRead),t.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=t.vibrateDuration,delete t.vibrateDuration),await new Promise(((e,n)=>{let r=te._nextTaskID++;te._taskCallbackMap.set(r,(t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack+="\n"+t.stack,n(e)}})),te._dbrWorker.postMessage({type:"updateScanSettings",id:r,instanceID:this._instanceID,body:{settings:t}})}))}_cloneDecodeResults(e){if(e instanceof Array){let t=[];for(let n of e)t.push(this._cloneDecodeResults(n));return t}{let t=e;return JSON.parse(JSON.stringify(t,((e,t)=>"oriVideoCanvas"==e||"searchRegionCanvas"==e?void 0:t)))}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this.imgSource||this._bPauseScan)return te._onLog&&te._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));te._onLog&&te._onLog("======= once read ======="),te._onLog&&(this._timeStartDecode=Date.now());let e=null,t=null;if(this.dce)e=this._getVideoFrame();else if(this.imgSource&&(t=await this.imgSource.getImage(),!te.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let n=null;return e?n=await this._decode_DCEFrame(e,{bScanner:!0,bCopyData:!1}):t&&(n=await this._decode_DSImage(t,{bScanner:!0,bCopyData:!1})),n})().then((e=>{if(te._onLog&&te._onLog(e),this.dce){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost;this._indexCurrentDecodingFrame;const n=()=>{let n=0;if(t&&t.length){let r=Math.min(...e),i=Math.max(...t);r&&i&&(n=r-i)}else n=0;return n>0?n:0};(()=>{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=n()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this.imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead)t=!0;else if("unique"===this.bPlaySoundOnSuccessfulRead)for(let n of e)if(n.bUnduplicated){t=!0;break}t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead)t=!0;else if("unique"===this.bVibrateOnSuccessfulRead)for(let n of e)if(n.bUnduplicated){t=!0;break}if(t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onImageRead){let t=this._cloneDecodeResults(e);for(let e of t)delete e.bUnduplicated;this.onImageRead(t)}if(this.onUniqueRead)for(let t of e)t.bUnduplicated&&this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t));this._drawResults(e)}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce&&this.dce.stopFetchingLoop(),te._onLog&&te._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e=this.dce.isFetchingLoopStarted();if(this.dceConfig.loopInterval=this._intervalGetVideoFrame,e||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dceConfig.loopInterval=0,null;const t=this.dce.getFrameFromBuffer();return(e=>{if(!e)return;let t=e.timeSpent,n=this.array_getFrameTimeCost;for(;n.length>=5;)n.shift();n.push(t)})(t),t}_drawResults(e){if(!this.dce||this._bPauseScan)return;if(!this.resultsOverlay){if(!this.dce.isOpen())return;this.resultsOverlay=this.dce.addScanRegionOverlayCanvas()}const t=this.resultsOverlay.getContext("2d");if(t.clearRect(0,0,this.resultsOverlay.width,this.resultsOverlay.height),e){t.globalCompositeOperation="destination-over",t.fillStyle=this.barcodeFillStyle,t.strokeStyle=this.barcodeStrokeStyle,t.lineWidth=this.barcodeLineWidth;for(let n of e){let e=n.localizationResult;t.beginPath(),t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineTo(e.x3,e.y3),t.lineTo(e.x4,e.y4),t.fill(),t.beginPath(),t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineTo(e.x3,e.y3),t.lineTo(e.x4,e.y4),t.closePath(),t.stroke()}}}async startScanning(e){if(!this.dce&&!this.imgSource)throw new Error("'imageSource' is not set. call 'setImageSource()' before 'startScanning()'.");if("closed"!=this._tempSolutionStatus)return;if(this._tempSolutionStatus="opening","opening"!=this._tempSolutionStatus)return;let t=null;return this.dce&&!this.dce.isOpen()&&(this.dce.ifShowScanRegionLaser=!0,t=await this.dce.open(e)),"opening"==this._tempSolutionStatus?(this._bPauseScan=!1,this.dce&&this.dce.singleFrameMode||this._loopReadVideo(),this._tempSolutionStatus="opened",this.keepAlive(),t):void 0}stopScanning(e){this.dce&&(this._drawResults(null),this.dce.ifShowScanRegionLaser=!1,this.dce.close(e)),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._tempSolutionStatus="closed"}pauseScanning(){if(this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.ifShowScanRegionLaser=!1,this.dce.stopFetchingLoop()}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.ifShowScanRegionLaser=!0}}destroyContext(){if(te._onLog&&te._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,(this.dce||"opening"===this._tempSolutionStatus)&&this.stopScanning(),this.setImageSource(null);let e=te._nextTaskID++;te._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),te._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}te._jsVersion="9.0.2",te._jsEditVersion="20220505",te._version=`loading...(JS ${te._jsVersion}.${te._jsEditVersion})`,te._license=u,te._sessionPassword=c,te.browserInfo=r,te._workerName=`dbr-${te._jsVersion}.browser.worker.js`,te._engineResourcePath=d,te._licenseServer=[],te._deviceFriendlyName="",te._isShowRelDecodeTimeInResults=!1,te._bWasmDebug=!1,te._bNeverShowDialog=!1,te.__bUseFullFeature=!0,te._nextTaskID=0,te._taskCallbackMap=new Map,te._pLoad=new class extends Promise{constructor(e){let t,n;super(((e,r)=>{t=e,n=r})),this._s="pending",this.resolve=e=>{this.isPending&&(A(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",n(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,A(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const n=await t;e===this._task&&this.resolve(n)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}},te._lastErrorCode=0,te._lastErrorString="",te._setWarnnedEx=new Set,te._defaultUIElementURL="@engineResourcePath/dbr.ui.html";class ne extends te{constructor(){super(),this.bFilterRegionInJs=!0,this._onCameraSelChange=()=>{},this._onResolutionSelChange=()=>{},this._onCloseBtnClick=()=>{},this._onPlayed=null}static get version(){return this._version+`(DCE ${t.CameraEnhancer.getVersion()})`}getUIElement(){return this.dce.getUIElement()}async setUIElement(e){await this.dce.setUIElement(e)}get singleFrameMode(){return this.dce.singleFrameMode}set singleFrameMode(e){this.dce.singleFrameMode=e,e&&(this.dce.ifShowScanRegionLaser=!1,(async()=>{let e=await this.getScanSettings();e.oneDTrustFrameCount=1,await this.updateScanSettings(e)})())}get onUnduplicatedRead(){return this.onUniqueRead}set onUnduplicatedRead(e){this.onUniqueRead=e}_assertOpen(){if(!this.dce.isOpen())throw Error("The scanner is not open.")}set regionMaskFillStyle(e){this.dce.setScanRegionMaskStyle({fillStyle:e})}get regionMaskFillStyle(){return this.dce.regionMaskFillStyle}set regionMaskStrokeStyle(e){this.dce.setScanRegionMaskStyle({strokeStyle:e})}get regionMaskStrokeStyle(){return this.dce.regionMaskStrokeStyle}set regionMaskLineWidth(e){this.dce.setScanRegionMaskStyle({lineWidth:e})}get regionMaskLineWidth(){return this.dce.regionMaskLineWidth}set region(e){this._region=e,this.dce&&(e?e instanceof Array||this.dce.setScanRegion(e):this.dce.setScanRegion(null)),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e,this.dce.frameColorMode=e?"rgba":"grey"}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}async createDCEInstance(){this.dce||(te._onLog&&te._onLog("createDCEInstance()"),t.CameraEnhancer.defaultUIElementURL=null,this.dce=await t.CameraEnhancer.createInstance(),this.dce.refreshInterval=200,this.dce.frameColorMode="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this.dce.on("cameraChange",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("resolutionChange",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("cameraClose",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1})),this.dce.on("singleFrameAcquired",(async t=>{if(!t)return;if(!t.data)return;let n;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{data:r,region:i,sx:o,sy:a,width:s,height:d,colorMode:_,timeStamp:u}=t,c={timeStamp:u};if("grey"===_)n=await this._decodeBuffer_Uint8Array(r,s,d,s,e.EnumImagePixelFormat.IPF_GrayScaled,c);else if("rgba"===_)n=await this._decodeBuffer_Uint8Array(r,s,d,4*s,e.EnumImagePixelFormat.IPF_ABGR_8888,c);else{if("bgra"!==_)throw new Error(`Color mode '${_}' is not supported.`);n=await this._decodeBuffer_Uint8Array(r,s,d,4*s,e.EnumImagePixelFormat.IPF_ARGB_8888,c)}await this.clearMapDecodeRecord();for(let e of n)delete e.bUnduplicated;if(this._drawResults(n),te.fixResultLocationWhenFilterRegionInJs(i,n,o,a,s,d,s,d),this.onFrameRead&&this.isOpen()&&!this._bPauseScan&&this.onFrameRead(n),this.onUniqueRead&&this.isOpen()&&!this._bPauseScan)for(let e of n)this.onUniqueRead(e.barcodeText,e)})))}set maxCvsSideLength(e){this._maxCvsSideLength=e,this.dce.maxCvsSideLength=e}get maxCvsSideLength(){return this._maxCvsSideLength}static async createInstance(e){let t=new ne;await t.createDCEInstance(),t._instanceID=await ne.createInstanceInWorker(!0),"string"==typeof e&&(e=JSON.parse(e));for(let n in e)t[n]=e[n];return await t.setUIElement(ne.defaultUIElementURL),t.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),t.singleFrameMode||await t.updateRuntimeSettings("single"),t}async decodeCurrentFrame(e){this._assertOpen();let t=null;e&&e.region&&(t=e.region);const n=this.dce._getVideoFrame(t);return this._decode_DCEFrame(n)}static isRegionNormalPreset(e){return 0==e.regionLeft&&0==e.regionTop&&0==e.regionRight&&0==e.regionBottom&&0==e.regionMeasuredByPercentage}async updateRuntimeSettings(t){let n;if("string"==typeof t)if("speed"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(n.region=e.region)}else if("balance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(n.region=e.region),n.deblurLevel=3,n.expectedBarcodesCount=512,n.localizationModes=[2,16,0,0,0,0,0,0],n.timeout=1e5}else if("coverage"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(n.region=e.region),n.deblurLevel=5,n.expectedBarcodesCount=512,n.scaleDownThreshold=1e5,n.localizationModes=[2,16,4,8,0,0,0,0],n.timeout=1e5}else if("single"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,ne.isRegionNormalPreset(e.region)?n.region=null:n.region=e.region,n.expectedBarcodesCount=1,n.localizationModes=[16,2,0,0,0,0,0,0],n.barcodeZoneMinDistanceToImageBorders=0}else n=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(n=JSON.parse(JSON.stringify(t)),n.region instanceof Array){let e=t.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(n.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!te._bUseFullFeature){if(0!=(n.barcodeFormatIds&~(e.EnumBarcodeFormat.BF_ONED|e.EnumBarcodeFormat.BF_QR_CODE|e.EnumBarcodeFormat.BF_PDF417|e.EnumBarcodeFormat.BF_DATAMATRIX))||0!=n.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=n.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}{let e=n.region;if(this.bFilterRegionInJs?this.userDefinedRegion=JSON.parse(JSON.stringify(e)):this.userDefinedRegion=null,e instanceof Array)if(e.length){for(let t=0;t{let r=te._nextTaskID++;te._taskCallbackMap.set(r,(n=>{if(n.success){try{this._handleRetJsonString(n.updateReturn)}catch(e){t(e)}return e()}{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),te._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(n)}})})),"single"==t&&(await this.setModeArgument("BinarizationModes",0,"EnableFillBinaryVacancy","0"),await this.setModeArgument("LocalizationModes",0,"ScanDirection","2"),await this.setModeArgument("BinarizationModes",0,"BlockSizeX","71"),await this.setModeArgument("BinarizationModes",0,"BlockSizeY","71"))}_bindUI(){if(!this.getUIElement())throw new Error("Need to define `UIElement` before opening.");if(this.dce._bindUI(),!this.dce.video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'")}_unbindUI(){this.dce._unbindUI()}set onPlayed(e){this.dce.off("played",this._onPlayed),this._onPlayed=e,this.dce.on("played",this._onPlayed)}get onPlayed(){return this._onPlayed}async getAllCameras(){return this.dce.getAllCameras()}async getCurrentCamera(){return this.dce.getSelectedCamera()}async setCurrentCamera(e){return this.dce.selectCamera(e)}getResolution(){return this.dce.getResolution()}async setResolution(e,t){return this.dce.setResolution(e,t)}getVideoSettings(){return this.dce.getVideoSettings()}updateVideoSettings(e){return this.dce.updateVideoSettings(e)}isOpen(){return this.dce&&this.dce.isOpen()}setVideoFit(e){return this.dce&&this.dce.setVideoFit(e)}set ifShowScanRegionMask(e){this.dce&&(this.dce.ifShowScanRegionMask=e)}get ifShowScanRegionMask(){return this.dce&&this.dce.ifShowScanRegionMask}stop(){this.dce.stop(),this.dce.hideScanRegionLaser(),this.dce.hideViewDecorator(),this.dce.hideScanRegionOverlays(),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}pause(){this._drawResults(null),this.dce.pause()}async play(e,t,n){this.dce.ifShowScanRegionLaser=!0;return await this.dce.play(e,t,n)}pauseScan(){this._assertOpen(),this._drawResults(null),this._bPauseScan=!0,this.dce.ifShowScanRegionLaser=!1}resumeScan(){this._assertOpen(),this._bPauseScan=!1,this.dce.ifShowScanRegionLaser=!0}getCapabilities(){return this.dce.getCapabilities()}getCameraSettings(){return this.dce.getCameraSettings()}getConstraints(){return this.dce.getConstraints()}async applyConstraints(e){return this.dce.applyConstraints(e)}async turnOnTorch(){return this.dce.turnOnTorch()}async turnOffTorch(){return this.dce.turnOffTorch()}async setColorTemperature(e){return this.dce.setColorTemperature(e)}async setExposureCompensation(e){return this.dce.setExposureCompensation(e)}async setZoom(e){return this.dce.setZoom(e)}async setFrameRate(e){return this.dce.setFrameRate(e)}getFrameRate(){return this.dce.getFrameRate()}async setFocus(e,t){return this.dce.setFocus(e,t)}getFocus(){return this.dce.getFocus()}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),void this._drawResults(null);if(!this.isOpen())return this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce.video||this.dce.video.paused||this._bPauseScan)return te._onLog&&te._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));te._onLog&&te._onLog("======= once read ======="),te._onLog&&(this._timeStartDecode=Date.now());const t=this._getVideoFrame();if(!t)return this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let n;t._bUseWebGL||"grey"!==t.colorMode||(this.dce.frameColorMode="rgba"),this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{data:r,region:i,sx:o,sy:a,width:s,height:d,colorMode:_,timeStamp:u}=t,c={timeStamp:u};if("grey"===_)n=await this._decodeBuffer_Uint8Array(r,s,d,s,e.EnumImagePixelFormat.IPF_GrayScaled,c);else if("rgba"===_)n=await this._decodeBuffer_Uint8Array(r,s,d,4*s,e.EnumImagePixelFormat.IPF_ABGR_8888,c);else{if("bgra"!==_)throw new Error(`Color mode '${_}' is not supported.`);n=await this._decodeBuffer_Uint8Array(r,s,d,4*s,e.EnumImagePixelFormat.IPF_ARGB_8888,c)}return this.dce&&this.dce.video&&!this.dce.video.paused&&this._drawResults(n),te.fixResultLocationWhenFilterRegionInJs(i,n,o,a,s,d,s,d),n})().then((e=>{te._onLog&&te._onLog(e);let t=this.array_decodeFrameTimeCost,n=this.array_getFrameTimeCost,r=this._indexCurrentDecodingFrame;if((()=>{if(this.region instanceof Array){for(t[r]&&t[r]instanceof Array||(t[r]=[]);t[r].length>=5;)t[r].shift();t[r].push(this._lastInnerDecodeDuration)}else{for(;t.length>=5;)t.shift();t.push(this._lastInnerDecodeDuration)}})(),this._intervalGetVideoFrame=(()=>{let e=0;if(this.region instanceof Array){let i=0,o=0;i=r+1>=this.region.length?0:r+1,o=i+1>=this.region.length?0:i+1,e=t[i]&&t[i].length&&n[o]&&n[o].length?Math.min(...t[i])-Math.max(...n[o]):0}else if(n&&n.length){let r=Math.min(...t),i=Math.max(...n);r&&i&&(e=r-i)}else e=0;return e>0?e:0})()+this.intervalTime,this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead)t=!0;else if("unique"===this.bPlaySoundOnSuccessfulRead)for(let n of e)if(n.bUnduplicated){t=!0;break}t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead)t=!0;else if("unique"===this.bVibrateOnSuccessfulRead)for(let n of e)if(n.bUnduplicated){t=!0;break}if(t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onFrameRead){let t=this._cloneDecodeResults(e);for(let e of t)delete e.bUnduplicated;this.onFrameRead(t)}if(this.onUniqueRead)for(let t of e)t.bUnduplicated&&this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t))}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce.stopFetchingLoop(),te._onLog&&te._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e=this.dce.isFetchingLoopStarted();if(this.dce.loopInterval=this._intervalGetVideoFrame,e||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dce.loopInterval=0,null;const t=this.dce.getFrameFromBuffer();return(e=>{if(!e)return;let t=e.timeSpent,n=this.array_getFrameTimeCost;for(;n.length>=5;)n.shift();n.push(t)})(t),t}async open(){this._bindUI();let e=await this.dce.open();return this._bPauseScan=!1,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.dce.ifShowScanRegionLaser=!0,this._loopReadVideo()),this.keepAlive(),e}async openVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open();return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideo()),this.keepAlive(),e}close(){this.dce.close(),this._bPauseScan=!0}async show(){this._bindUI();const e=await this.dce.open(!0);return this._bPauseScan=!1,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.dce.ifShowScanRegionLaser=!0,this._loopReadVideo()),this.keepAlive(),e}async showVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open(!0);return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideo()),this.keepAlive(),e}hide(){this.dce.close(!0),this._bPauseScan=!0}destroyContext(){this.close(),this.bDestroyed||super.destroyContext()}}e.EnumBarcodeColourMode=void 0,(S=e.EnumBarcodeColourMode||(e.EnumBarcodeColourMode={}))[S.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",S[S.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",S[S.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",S[S.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",S[S.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",S[S.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",S[S.BICM_SKIP=0]="BICM_SKIP",S[S.BICM_REV=2147483648]="BICM_REV",e.EnumBarcodeComplementMode=void 0,(T=e.EnumBarcodeComplementMode||(e.EnumBarcodeComplementMode={}))[T.BCM_AUTO=1]="BCM_AUTO",T[T.BCM_GENERAL=2]="BCM_GENERAL",T[T.BCM_SKIP=0]="BCM_SKIP",T[T.BCM_REV=2147483648]="BCM_REV",e.EnumBarcodeFormat_2=void 0,(D=e.EnumBarcodeFormat_2||(e.EnumBarcodeFormat_2={}))[D.BF2_NULL=0]="BF2_NULL",D[D.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",D[D.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",D[D.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",D[D.BF2_POSTNET=2097152]="BF2_POSTNET",D[D.BF2_PLANET=4194304]="BF2_PLANET",D[D.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",D[D.BF2_RM4SCC=16777216]="BF2_RM4SCC",D[D.BF2_DOTCODE=2]="BF2_DOTCODE",D[D.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",D[D.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",D[D.BF2_PHARMACODE=12]="BF2_PHARMACODE",e.EnumBinarizationMode=void 0,(y=e.EnumBinarizationMode||(e.EnumBinarizationMode={}))[y.BM_AUTO=1]="BM_AUTO",y[y.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",y[y.BM_SKIP=0]="BM_SKIP",y[y.BM_THRESHOLD=4]="BM_THRESHOLD",y[y.BM_REV=2147483648]="BM_REV",e.EnumClarityCalculationMethod=void 0,(C=e.EnumClarityCalculationMethod||(e.EnumClarityCalculationMethod={}))[C.ECCM_CONTRAST=1]="ECCM_CONTRAST",e.EnumClarityFilterMode=void 0,(v=e.EnumClarityFilterMode||(e.EnumClarityFilterMode={}))[v.CFM_GENERAL=1]="CFM_GENERAL",e.EnumColourClusteringMode=void 0,(M=e.EnumColourClusteringMode||(e.EnumColourClusteringMode={}))[M.CCM_AUTO=1]="CCM_AUTO",M[M.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",M[M.CCM_SKIP=0]="CCM_SKIP",M[M.CCM_REV=2147483648]="CCM_REV",e.EnumColourConversionMode=void 0,(O=e.EnumColourConversionMode||(e.EnumColourConversionMode={}))[O.CICM_GENERAL=1]="CICM_GENERAL",O[O.CICM_SKIP=0]="CICM_SKIP",O[O.CICM_REV=2147483648]="CICM_REV",e.EnumConflictMode=void 0,(b=e.EnumConflictMode||(e.EnumConflictMode={}))[b.CM_IGNORE=1]="CM_IGNORE",b[b.CM_OVERWRITE=2]="CM_OVERWRITE",e.EnumDeblurMode=void 0,(L=e.EnumDeblurMode||(e.EnumDeblurMode={}))[L.DM_SKIP=0]="DM_SKIP",L[L.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",L[L.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",L[L.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",L[L.DM_SMOOTHING=8]="DM_SMOOTHING",L[L.DM_MORPHING=16]="DM_MORPHING",L[L.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",L[L.DM_SHARPENING=64]="DM_SHARPENING",L[L.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",L[L.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",e.EnumDeformationResistingMode=void 0,(w=e.EnumDeformationResistingMode||(e.EnumDeformationResistingMode={}))[w.DRM_AUTO=1]="DRM_AUTO",w[w.DRM_GENERAL=2]="DRM_GENERAL",w[w.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",w[w.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",w[w.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",w[w.DRM_SKIP=0]="DRM_SKIP",w[w.DRM_REV=2147483648]="DRM_REV",e.EnumDPMCodeReadingMode=void 0,(B=e.EnumDPMCodeReadingMode||(e.EnumDPMCodeReadingMode={}))[B.DPMCRM_AUTO=1]="DPMCRM_AUTO",B[B.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",B[B.DPMCRM_SKIP=0]="DPMCRM_SKIP",B[B.DPMCRM_REV=2147483648]="DPMCRM_REV",e.EnumGrayscaleTransformationMode=void 0,(F=e.EnumGrayscaleTransformationMode||(e.EnumGrayscaleTransformationMode={}))[F.GTM_INVERTED=1]="GTM_INVERTED",F[F.GTM_ORIGINAL=2]="GTM_ORIGINAL",F[F.GTM_SKIP=0]="GTM_SKIP",F[F.GTM_REV=2147483648]="GTM_REV",e.EnumImagePreprocessingMode=void 0,(N=e.EnumImagePreprocessingMode||(e.EnumImagePreprocessingMode={}))[N.IPM_AUTO=1]="IPM_AUTO",N[N.IPM_GENERAL=2]="IPM_GENERAL",N[N.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",N[N.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",N[N.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",N[N.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",N[N.IPM_SKIP=0]="IPM_SKIP",N[N.IPM_REV=2147483648]="IPM_REV",e.EnumIntermediateResultSavingMode=void 0,(P=e.EnumIntermediateResultSavingMode||(e.EnumIntermediateResultSavingMode={}))[P.IRSM_MEMORY=1]="IRSM_MEMORY",P[P.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",P[P.IRSM_BOTH=4]="IRSM_BOTH",e.EnumIntermediateResultType=void 0,(V=e.EnumIntermediateResultType||(e.EnumIntermediateResultType={}))[V.IRT_NO_RESULT=0]="IRT_NO_RESULT",V[V.IRT_ORIGINAL_IMAGE=1]="IRT_ORIGINAL_IMAGE",V[V.IRT_COLOUR_CLUSTERED_IMAGE=2]="IRT_COLOUR_CLUSTERED_IMAGE",V[V.IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE=4]="IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE",V[V.IRT_TRANSFORMED_GRAYSCALE_IMAGE=8]="IRT_TRANSFORMED_GRAYSCALE_IMAGE",V[V.IRT_PREDETECTED_REGION=16]="IRT_PREDETECTED_REGION",V[V.IRT_PREPROCESSED_IMAGE=32]="IRT_PREPROCESSED_IMAGE",V[V.IRT_BINARIZED_IMAGE=64]="IRT_BINARIZED_IMAGE",V[V.IRT_TEXT_ZONE=128]="IRT_TEXT_ZONE",V[V.IRT_CONTOUR=256]="IRT_CONTOUR",V[V.IRT_LINE_SEGMENT=512]="IRT_LINE_SEGMENT",V[V.IRT_FORM=1024]="IRT_FORM",V[V.IRT_SEGMENTATION_BLOCK=2048]="IRT_SEGMENTATION_BLOCK",V[V.IRT_TYPED_BARCODE_ZONE=4096]="IRT_TYPED_BARCODE_ZONE",V[V.IRT_PREDETECTED_QUADRILATERAL=8192]="IRT_PREDETECTED_QUADRILATERAL",e.EnumLocalizationMode=void 0,(x=e.EnumLocalizationMode||(e.EnumLocalizationMode={}))[x.LM_SKIP=0]="LM_SKIP",x[x.LM_AUTO=1]="LM_AUTO",x[x.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",x[x.LM_LINES=8]="LM_LINES",x[x.LM_STATISTICS=4]="LM_STATISTICS",x[x.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",x[x.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",x[x.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",x[x.LM_CENTRE=128]="LM_CENTRE",x[x.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",x[x.LM_REV=2147483648]="LM_REV",e.EnumPDFReadingMode=void 0,(k=e.EnumPDFReadingMode||(e.EnumPDFReadingMode={}))[k.PDFRM_RASTER=1]="PDFRM_RASTER",k[k.PDFRM_AUTO=2]="PDFRM_AUTO",k[k.PDFRM_VECTOR=4]="PDFRM_VECTOR",k[k.PDFRM_REV=2147483648]="PDFRM_REV",e.EnumQRCodeErrorCorrectionLevel=void 0,(U=e.EnumQRCodeErrorCorrectionLevel||(e.EnumQRCodeErrorCorrectionLevel={}))[U.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",U[U.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",U[U.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",U[U.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q",e.EnumRegionPredetectionMode=void 0,(G=e.EnumRegionPredetectionMode||(e.EnumRegionPredetectionMode={}))[G.RPM_AUTO=1]="RPM_AUTO",G[G.RPM_GENERAL=2]="RPM_GENERAL",G[G.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",G[G.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",G[G.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",G[G.RPM_SKIP=0]="RPM_SKIP",G[G.RPM_REV=2147483648]="RPM_REV",e.EnumResultCoordinateType=void 0,(H=e.EnumResultCoordinateType||(e.EnumResultCoordinateType={}))[H.RCT_PIXEL=1]="RCT_PIXEL",H[H.RCT_PERCENTAGE=2]="RCT_PERCENTAGE",e.EnumResultType=void 0,(W=e.EnumResultType||(e.EnumResultType={}))[W.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",W[W.RT_RAW_TEXT=1]="RT_RAW_TEXT",W[W.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",W[W.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT",e.EnumScaleUpMode=void 0,(K=e.EnumScaleUpMode||(e.EnumScaleUpMode={}))[K.SUM_AUTO=1]="SUM_AUTO",K[K.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",K[K.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",K[K.SUM_SKIP=0]="SUM_SKIP",K[K.SUM_REV=2147483648]="SUM_REV",e.EnumTerminatePhase=void 0,(Y=e.EnumTerminatePhase||(e.EnumTerminatePhase={}))[Y.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",Y[Y.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",Y[Y.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",Y[Y.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",Y[Y.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",Y[Y.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED",e.EnumTextFilterMode=void 0,(Q=e.EnumTextFilterMode||(e.EnumTextFilterMode={}))[Q.TFM_AUTO=1]="TFM_AUTO",Q[Q.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",Q[Q.TFM_SKIP=0]="TFM_SKIP",Q[Q.TFM_REV=2147483648]="TFM_REV",e.EnumTextResultOrderMode=void 0,(J=e.EnumTextResultOrderMode||(e.EnumTextResultOrderMode={}))[J.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",J[J.TROM_POSITION=2]="TROM_POSITION",J[J.TROM_FORMAT=4]="TROM_FORMAT",J[J.TROM_SKIP=0]="TROM_SKIP",J[J.TROM_REV=2147483648]="TROM_REV",e.EnumTextureDetectionMode=void 0,(X=e.EnumTextureDetectionMode||(e.EnumTextureDetectionMode={}))[X.TDM_AUTO=1]="TDM_AUTO",X[X.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",X[X.TDM_SKIP=0]="TDM_SKIP",X[X.TDM_REV=2147483648]="TDM_REV",e.BarcodeReader=te,e.BarcodeScanner=ne,Object.defineProperty(e,"__esModule",{value:!0})})); diff --git a/dist/dbr.browser.pure.mjs b/dist/dbr.browser.pure.mjs deleted file mode 100644 index a2bc1ad..0000000 --- a/dist/dbr.browser.pure.mjs +++ /dev/null @@ -1,11 +0,0 @@ -/*! - * Dynamsoft JavaScript Library - * @product Dynamsoft Barcode Reader JS Edition - * @website http://www.dynamsoft.com - * @copyright Copyright 2022, Dynamsoft Corporation - * @author Dynamsoft - * @version 9.0.2 (js 20220505) - * @fileoverview Dynamsoft JavaScript Library for Barcode Reader - * More info on DBR JS: https://www.dynamsoft.com/barcode-reader/sdk-javascript/ - */ -import{CameraEnhancer as e}from"dynamsoft-camera-enhancer";const t="undefined"==typeof self;let n;if(!t){const e={init:function(){this.browser=this.searchString(this.dataBrowser)||"unknownBrowser",this.version=this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion)||"unknownVersion",this.OS=this.searchString(this.dataOS)||"unknownOS","Linux"==this.OS&&-1!=navigator.userAgent.indexOf("Windows NT")&&(this.OS="HarmonyOS")},searchString:function(e){for(var t=0;t{let e=!1;if(o)try{(await navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e},s=(()=>{if(!t&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),_=" is not allowed to change after `createInstance` or `loadWasm` is called.",d=!t&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",c=!t&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",u=e=>{if(null==e)e=[];else{e=e instanceof Array?[...e]:[e];for(let n=0;ne&&"object"==typeof e&&"function"==typeof e.then;var p=function(){this.init()};p.prototype={init:function(){var e=this||m;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var t=this||m;if(e=parseFloat(e),t.ctx||z(),void 0!==e&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,m.ctx.currentTime);for(var n=0;n=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,z()),e},codecs:function(e){return(this||m)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||m;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||m,t=null;try{t="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!t||"function"!=typeof t.canPlayType)return e;var n=t.canPlayType("audio/mpeg;").replace(/^no$/,""),i=e._navigator?e._navigator.userAgent:"",r=i.match(/OPR\/([0-6].)/g),o=r&&parseInt(r[0].split("/")[1],10)<33,a=-1!==i.indexOf("Safari")&&-1===i.indexOf("Chrome"),s=i.match(/Version\/(.*?) /),_=a&&s&&parseInt(s[1],10)<15;return e._codecs={mp3:!(o||!n&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!n,opus:!!t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(t.canPlayType('audio/wav; codecs="1"')||t.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!t.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!t.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/m4a;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(t.canPlayType("audio/x-m4b;")||t.canPlayType("audio/m4b;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(t.canPlayType("audio/x-mp4;")||t.canPlayType("audio/mp4;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(_||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(_||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!t.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(t.canPlayType("audio/x-flac;")||t.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||m;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var t=function(n){for(;e._html5AudioPool.length0?a._seek:n._sprite[e][0]/1e3),d=Math.max(0,(n._sprite[e][0]+n._sprite[e][1])/1e3-_),c=1e3*d/Math.abs(a._rate),u=n._sprite[e][0]/1e3,l=(n._sprite[e][0]+n._sprite[e][1])/1e3;a._sprite=e,a._ended=!1;var h=function(){a._paused=!1,a._seek=_,a._start=u,a._stop=l,a._loop=!(!a._loop&&!n._sprite[e][2])};if(!(_>=l)){var g=a._node;if(n._webAudio){var f=function(){n._playLock=!1,h(),n._refreshBuffer(a);var e=a._muted||n._muted?0:a._volume;g.gain.setValueAtTime(e,m.ctx.currentTime),a._playStart=m.ctx.currentTime,void 0===g.bufferSource.start?a._loop?g.bufferSource.noteGrainOn(0,_,86400):g.bufferSource.noteGrainOn(0,_,d):a._loop?g.bufferSource.start(0,_,86400):g.bufferSource.start(0,_,d),c!==1/0&&(n._endTimers[a._id]=setTimeout(n._ended.bind(n,a),c)),t||setTimeout((function(){n._emit("play",a._id),n._loadQueue()}),0)};"running"===m.state&&"interrupted"!==m.ctx.state?f():(n._playLock=!0,n.once("resume",f),n._clearTimer(a._id))}else{var A=function(){g.currentTime=_,g.muted=a._muted||n._muted||m._muted||g.muted,g.volume=a._volume*m.volume(),g.playbackRate=a._rate;try{var i=g.play();if(i&&"undefined"!=typeof Promise&&(i instanceof Promise||"function"==typeof i.then)?(n._playLock=!0,h(),i.then((function(){n._playLock=!1,g._unlocked=!0,t?n._loadQueue():n._emit("play",a._id)})).catch((function(){n._playLock=!1,n._emit("playerror",a._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),a._ended=!0,a._paused=!0}))):t||(n._playLock=!1,h(),n._emit("play",a._id)),g.playbackRate=a._rate,g.paused)return void n._emit("playerror",a._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||a._loop?n._endTimers[a._id]=setTimeout(n._ended.bind(n,a),c):(n._endTimers[a._id]=function(){n._ended(a),g.removeEventListener("ended",n._endTimers[a._id],!1)},g.addEventListener("ended",n._endTimers[a._id],!1))}catch(e){n._emit("playerror",a._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===g.src&&(g.src=n._src,g.load());var p=window&&window.ejecta||!g.readyState&&m._navigator.isCocoonJS;if(g.readyState>=3||p)A();else{n._playLock=!0,n._state="loading";var R=function(){n._state="loaded",A(),g.removeEventListener(m._canPlayEvent,R,!1)};g.addEventListener(m._canPlayEvent,R,!1),n._clearTimer(a._id)}}return a._id}n._ended(a)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var n=t._getSoundIds(e),i=0;i=0?t=parseInt(r[0],10):e=parseFloat(r[0])}else r.length>=2&&(e=parseFloat(r[0]),t=parseInt(r[1],10));if(!(void 0!==e&&e>=0&&e<=1))return(n=t?i._soundById(t):i._sounds[0])?n._volume:0;if("loaded"!==i._state||i._playLock)return i._queue.push({event:"volume",action:function(){i.volume.apply(i,r)}}),i;void 0===t&&(i._volume=e),t=i._getSoundIds(t);for(var s=0;s0?i/d:i),u=Date.now();e._fadeTo=n,e._interval=setInterval((function(){var r=(Date.now()-u)/i;u=Date.now(),s+=_*r,s=Math.round(100*s)/100,s=_<0?Math.max(n,s):Math.min(n,s),a._webAudio?e._volume=s:a.volume(s,e._id,!0),o&&(a._volume=s),(nt&&s>=n)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,a.volume(n,e._id),a._emit("fade",e._id))}),c)},_stopFade:function(e){var t=this,n=t._soundById(e);return n&&n._interval&&(t._webAudio&&n._node.gain.cancelScheduledValues(m.ctx.currentTime),clearInterval(n._interval),n._interval=null,t.volume(n._fadeTo,e),n._fadeTo=null,t._emit("fade",e)),t},loop:function(){var e,t,n,i=this,r=arguments;if(0===r.length)return i._loop;if(1===r.length){if("boolean"!=typeof r[0])return!!(n=i._soundById(parseInt(r[0],10)))&&n._loop;e=r[0],i._loop=e}else 2===r.length&&(e=r[0],t=parseInt(r[1],10));for(var o=i._getSoundIds(t),a=0;a=0?t=parseInt(r[0],10):e=parseFloat(r[0])}else 2===r.length&&(e=parseFloat(r[0]),t=parseInt(r[1],10));if("number"!=typeof e)return(n=i._soundById(t))?n._rate:i._rate;if("loaded"!==i._state||i._playLock)return i._queue.push({event:"rate",action:function(){i.rate.apply(i,r)}}),i;void 0===t&&(i._rate=e),t=i._getSoundIds(t);for(var s=0;s=0?t=parseInt(i[0],10):n._sounds.length&&(t=n._sounds[0]._id,e=parseFloat(i[0]))}else 2===i.length&&(e=parseFloat(i[0]),t=parseInt(i[1],10));if(void 0===t)return 0;if("number"==typeof e&&("loaded"!==n._state||n._playLock))return n._queue.push({event:"seek",action:function(){n.seek.apply(n,i)}}),n;var a=n._soundById(t);if(a){if(!("number"==typeof e&&e>=0)){if(n._webAudio){var s=n.playing(t)?m.ctx.currentTime-a._playStart:0,_=a._rateSeek?a._rateSeek-a._seek:0;return a._seek+(_+s*Math.abs(a._rate))}return a._node.currentTime}var d=n.playing(t);d&&n.pause(t,!0),a._seek=e,a._ended=!1,n._clearTimer(t),n._webAudio||!a._node||isNaN(a._node.duration)||(a._node.currentTime=e);var c=function(){d&&n.play(t,!0),n._emit("seek",t)};if(d&&!n._webAudio){var u=function(){n._playLock?setTimeout(u,0):c()};setTimeout(u,0)}else c()}return n},playing:function(e){var t=this;if("number"==typeof e){var n=t._soundById(e);return!!n&&!n._paused}for(var i=0;i=0&&m._howls.splice(i,1);var r=!0;for(n=0;n=0){r=!1;break}return X&&r&&delete X[e._src],m.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,n,i){var r=this["_on"+e];return"function"==typeof t&&r.push(i?{id:n,fn:t,once:i}:{id:n,fn:t}),this},off:function(e,t,n){var i=this,r=i["_on"+e],o=0;if("number"==typeof t&&(n=t,t=null),t||n)for(o=0;o=0;o--)r[o].id&&r[o].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,n)}.bind(i,r[o].fn),0),r[o].once&&i.off(e,r[o].fn,r[o].id));return i._loadQueue(e),i},_loadQueue:function(e){var t=this;if(t._queue.length>0){var n=t._queue[0];n.event===e&&(t._queue.shift(),t._loadQueue()),e||n.action()}return t},_ended:function(e){var t=this,n=e._sprite;if(!t._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;i--){if(n<=t)return;e._sounds[i]._ended&&(e._webAudio&&e._sounds[i]._node&&e._sounds[i]._node.disconnect(0),e._sounds.splice(i,1),n--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],n=0;n=0;if(!e.bufferSource)return this;if(m._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))try{e.bufferSource.buffer=m._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(m._navigator&&m._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var I=function(e){this._parent=e,this.init()};I.prototype={init:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++m._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,n=m._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=void 0===m.ctx.createGain?m.ctx.createGainNode():m.ctx.createGain(),e._node.gain.setValueAtTime(n,m.ctx.currentTime),e._node.paused=!0,e._node.connect(m.masterGain)):m.noAudio||(e._node=m._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(m._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=t._src,e._node.preload=!0===t._preload?"auto":t._preload,e._node.volume=n*m.volume(),e._node.load()),e},reset:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++m._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,t=e._parent;t._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(t._sprite).length&&(t._sprite={__default:[0,1e3*t._duration]}),"loaded"!==t._state&&(t._state="loaded",t._emit("load"),t._loadQueue()),e._node.removeEventListener(m._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var E,S,T,D,y,C,v,O,M,b,L,w,B,N,F,P,V,x,k,U,G,H,W,K,Y,J,Q,X={},Z=function(e){var t=e._src;if(X[t])return e._duration=X[t].duration,void $(e);if(/^data:[^;]+;base64,/.test(t)){for(var n=atob(t.split(",")[1]),i=new Uint8Array(n.length),r=0;r0?(X[t._src]=e,$(t,e)):n()};"undefined"!=typeof Promise&&1===m.ctx.decodeAudioData.length?m.ctx.decodeAudioData(e).then(i).catch(n):m.ctx.decodeAudioData(e,i,n)},$=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},z=function(){if(m.usingWebAudio){try{"undefined"!=typeof AudioContext?m.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?m.ctx=new webkitAudioContext:m.usingWebAudio=!1}catch(e){m.usingWebAudio=!1}m.ctx||(m.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(m._navigator&&m._navigator.platform),t=m._navigator&&m._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),n=t?parseInt(t[1],10):null;if(e&&n&&n<9){var i=/safari/.test(m._navigator&&m._navigator.userAgent.toLowerCase());m._navigator&&!i&&(m.usingWebAudio=!1)}m.usingWebAudio&&(m.masterGain=void 0===m.ctx.createGain?m.ctx.createGainNode():m.ctx.createGain(),m.masterGain.gain.setValueAtTime(m._muted?0:m._volume,m.ctx.currentTime),m.masterGain.connect(m.ctx.destination)),m._setup()}};!function(e,t,n,i){var r;e.prototype._pos=[0,0,0],e.prototype._orientation=[0,0,-1,0,1,0],e.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var n=t._howls.length-1;n>=0;n--)t._howls[n].stereo(e);return t},e.prototype.pos=function(e,n,i){var r=this;return r.ctx&&r.ctx.listener?(n="number"!=typeof n?r._pos[1]:n,i="number"!=typeof i?r._pos[2]:i,"number"!=typeof e?r._pos:(r._pos=[e,n,i],void 0!==r.ctx.listener.positionX?(r.ctx.listener.positionX.setTargetAtTime(r._pos[0],t.ctx.currentTime,.1),r.ctx.listener.positionY.setTargetAtTime(r._pos[1],t.ctx.currentTime,.1),r.ctx.listener.positionZ.setTargetAtTime(r._pos[2],t.ctx.currentTime,.1)):r.ctx.listener.setPosition(r._pos[0],r._pos[1],r._pos[2]),r)):r},e.prototype.orientation=function(e,n,i,r,o,a){var s=this;if(!s.ctx||!s.ctx.listener)return s;var _=s._orientation;return n="number"!=typeof n?_[1]:n,i="number"!=typeof i?_[2]:i,r="number"!=typeof r?_[3]:r,o="number"!=typeof o?_[4]:o,a="number"!=typeof a?_[5]:a,"number"!=typeof e?_:(s._orientation=[e,n,i,r,o,a],void 0!==s.ctx.listener.forwardX?(s.ctx.listener.forwardX.setTargetAtTime(e,t.ctx.currentTime,.1),s.ctx.listener.forwardY.setTargetAtTime(n,t.ctx.currentTime,.1),s.ctx.listener.forwardZ.setTargetAtTime(i,t.ctx.currentTime,.1),s.ctx.listener.upX.setTargetAtTime(r,t.ctx.currentTime,.1),s.ctx.listener.upY.setTargetAtTime(o,t.ctx.currentTime,.1),s.ctx.listener.upZ.setTargetAtTime(a,t.ctx.currentTime,.1)):s.ctx.listener.setOrientation(e,n,i,r,o,a),s)},n.prototype.init=(r=n.prototype.init,function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],r.call(this,e)}),n.prototype.stereo=function(e,n){var i=this;if(!i._webAudio)return i;if("loaded"!==i._state)return i._queue.push({event:"stereo",action:function(){i.stereo(e,n)}}),i;var r=void 0===t.ctx.createStereoPanner?"spatial":"stereo";if(void 0===n){if("number"!=typeof e)return i._stereo;i._stereo=e,i._pos=[e,0,0]}for(var a=i._getSoundIds(n),s=0;s{console.warn(`Sound '${e}' playback failure: ${t}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.barcodeFillStyle="rgba(254,180,32,0.3)",this.barcodeStrokeStyle="rgba(254,180,32,0.9)",this.barcodeLineWidth=1,this._dce=null,this.dceConfig={},this.imgSource=null,this._maxCvsSideLength="iPhone"==n.OS||"Android"==n.OS?2048:4096,this._tempSolutionStatus="closed"}static get version(){return this._version}static get license(){return this._license}static set license(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`license`"+_);n._license=t})(ee,e)}static get productKeys(){return this._license}static set productKeys(e){ee.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){ee.license=e}static get organizationID(){return this._license}static set organizationID(e){ee.license=e}static set sessionPassword(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`sessionPassword`"+_);n._sessionPassword=t})(ee,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:i,worker:r,getUserMedia:o,camera:await a(),browser:n.browser,version:n.version,OS:n.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(e){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");ee._engineResourcePath=(e=>{if(null==e&&(e="./"),!t){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`licenseServer`"+_);n._licenseServer=u(t)})(ee,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+_);n._deviceFriendlyName=t||""})(ee,e)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(e){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");ee.__bUseFullFeature=e}static isImageSource(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"getImage"in e}static isDSImage(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("width"in e&&("height"in e&&"pixelFormat"in e)))}static isCameraEnhancer(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("referenceConfigurationArray"in e&&("isOpen"in e&&("on"in e&&("off"in e&&("startFetchingLoop"in e&&("stopFetchingLoop"in e&&("getUIElement"in e&&("video"in e&&("isFetchingLoopStarted"in e&&("numberOfFramesInBuffer"in e&&("getFrameFromBuffer"in e&&("addScanRegionOverlayCanvas"in e&&("ifShowScanRegionLaser"in e&&("open"in e&&"close"in e))))))))))))))}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("region"in e&&("sx"in e&&("sy"in e&&("width"in e&&("height"in e&&("colorMode"in e&&("timeSpent"in e&&("timeStamp"in e&&("isCropped"in e&&("toCanvas"in e&&"_bUseWebGL"in e)))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(e){this._region=e,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var e;return null===(e=ee._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",ee.engineResourcePath)}static set defaultUIElementURL(e){ee._defaultUIElementURL=e}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new R({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(e){this.bPlaySoundOnSuccessfulRead="never"!==e&&e}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(e){this.bVibrateOnSuccessfulRead="never"!==e&&e}set dce(e){this._dce=e}get dce(){return ee.isCameraEnhancer(this._dce)?this._dce:null}set maxCvsSideLength(e){this._maxCvsSideLength=e,this.dceConfig.maxCvsSideLength=e}get maxCvsSideLength(){return this._maxCvsSideLength}updateDCEConfig(){if(!this.dce)return;ee._onLog&&ee._onLog("updateDCEConfig()"),this.dceConfig={bufferRefreshInterval:200,maxCvsSideLength:this._maxCvsSideLength};let e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);for(;-1!==e;)this.dce.referenceConfigurationArray.splice(e,1),e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);this.dce.referenceConfigurationArray.push(this.dceConfig),this.callbackCameraChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async e=>{let t=await this._decode_DCEFrame(e,{bCopyData:!1});await this.clearMapDecodeRecord();for(let e of t)delete e.bUnduplicated;if(this._drawResults(t),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan&&this.onImageRead(t),this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,e)},this.dce.on("cameraChange",this.callbackCameraChange),this.dce.on("resolutionChange",this.callbackResolutionChange),this.dce.on("cameraClose",this.callbackCameraClose),this.dce.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}releaseDCEConfig(){if(this.dce){if(ee._onLog&&ee._onLog("releaseDCEConfig()"),this.dce&&ee.isCameraEnhancer(this.dce)){let e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);for(;-1!==e;)this.dce.referenceConfigurationArray.splice(e,1),e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);if(this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this.dce.stopFetchingLoop(),this.resultsOverlay){let e=this.dce._arrScanRegionOverlays.indexOf(this.resultsOverlay);for(;-1!==e;)this.dce._arrScanRegionOverlays.splice(e,1),e=this.dce._arrScanRegionOverlays.indexOf(this.resultsOverlay);this.resultsOverlay.remove(),this.resultsOverlay=null}}this.dce=null}}setImageSource(e){if(null==e)return this.imgSource=null,void this.releaseDCEConfig();if(ee.isCameraEnhancer(e))this.dce=e,this.updateDCEConfig(),this.imgSource=null;else{if(!ee.isImageSource(e))throw new Error("Invalid value.");this.releaseDCEConfig(),this.imgSource=e}}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:e,l:t,ls:i,sp:r,rmk:o}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,n,i=t._license||"",r=JSON.parse(JSON.stringify(t._licenseServer)),o=t._sessionPassword,a=0;if(i.startsWith("t")||i.startsWith("f"))a=0;else if(0===i.length||i.startsWith("P")||i.startsWith("L")||i.startsWith("Y")||i.startsWith("A"))a=1;else{a=2;const t=i.indexOf(":");if(-1!=t&&(i=i.substring(t+1)),i.startsWith("DLS2")){let t=i.substring(4);try{t=atob(t)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}const n=JSON.parse(t);if(i=n.handshakeCode?n.handshakeCode:n.organizationID?n.organizationID:"","number"==typeof i&&(i=JSON.stringify(i)),0===r.length){let e=[];n.mainServerURL&&(e[0]=n.mainServerURL),n.standbyServerURL&&(e[1]=n.standbyServerURL),r=u(e)}!o&&n.sessionPassword&&(o=n.sessionPassword),e=n.remark}("200001"===i||i.startsWith("200001-"))&&(r&&r.length||(i="")),i||(a=1)}if(a&&(globalThis.crypto||(n="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(n="Require https to use online key in this browser.")),n){if(1!==a)throw new Error(n);a=0,console.warn(n),t._lastErrorCode=-1,t._lastErrorString=n}return 1===a&&(i="",console.warn("Applying for a public trial license ...")),{lt:a,l:i,ls:r,sp:o,rmk:e}}throw new Error("Can't preprocess license again"+_)})(ee);this._pLoad.task=async(a,s)=>{let _=ee.engineResourcePath+ee._workerName;ee.engineResourcePath.startsWith(location.origin)||(_=await fetch(_).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),ee._dbrWorker=new Worker(_),ee._dbrWorker.onerror=e=>{let t=new Error(e.message);s(t)},ee._dbrWorker.onmessage=async t=>{let n=t.data?t.data:t;switch(n.type){case"log":ee._onLog&&ee._onLog(n.message);break;case"load":{n.message&&(n.message=n.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,i=!1;1===e&&(i=!0),n.success?(ee._dbrWorker.onerror=null,ee._version=n.version+"(JS "+ee._jsVersion+"."+ee._jsEditVersion+")",ee._onLog&&ee._onLog("load dbr worker success"),n.message&&console.warn(n.message)):(t=new Error(n.message),t.stack=n.stack+"\n"+t.stack,i||111==n.ltsErrorCode&&-1!=n.message.toLowerCase().indexOf("trial license")&&(i=!0)),i&&ee.showDialog(n.success?"warn":"error",n.message),n.success?a():s(t);break}case"task":{let e=n.id,t=n.body;try{ee._taskCallbackMap.get(e)(t),ee._taskCallbackMap.delete(e)}catch(t){throw ee._taskCallbackMap.delete(e),t}break}default:ee._onLog&&ee._onLog(t)}},ee._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:ee.engineResourcePath,bUseFullFeature:ee._bUseFullFeature,bd:ee._bWasmDebug,v:ee._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:n,fn:ee.deviceFriendlyName,ls:i,sp:r,rmk:o})}}await this._pLoad}static async showDialog(e,t){if(!ee._bNeverShowDialog)try{let n=await fetch(ee.engineResourcePath+"dls.license.dialog.html");if(!n.ok)throw Error("Get license dialog fail. Network Error: "+n.statusText);let i=await n.text();if(!i.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let r=document.createElement("div");r.innerHTML=i;let o=[];for(let e=0;e{if(n==e.target){a.remove();for(let e of o)e.remove()}}));else if(!_&&n.classList.contains("dls-license-icon-close"))_=n,n.addEventListener("click",(()=>{a.remove();for(let e of o)e.remove()}));else if(!d&&n.classList.contains("dls-license-icon-error"))d=n,"error"!=e&&n.remove();else if(!c&&n.classList.contains("dls-license-icon-warn"))c=n,"warn"!=e&&n.remove();else if(!u&&n.classList.contains("dls-license-msg-content")){u=n;let e=t;for(;e;){let t=e.indexOf("["),i=e.indexOf("]",t),r=e.indexOf("(",i),o=e.indexOf(")",r);if(-1==t||-1==i||-1==r||-1==o){n.appendChild(new Text(e));break}t>0&&n.appendChild(new Text(e.substring(0,t)));let a=document.createElement("a"),s=e.substring(t+1,i);a.innerText=s;let _=e.substring(r+1,o);a.setAttribute("href",_),a.setAttribute("target","_blank"),n.appendChild(a),e=e.substring(o+1)}}document.body.appendChild(a)}catch(e){ee._onLog&&ee._onLog(e.message||e)}}static async createInstanceInWorker(e=!1){return await ee.loadWasm(),await new Promise(((t,n)=>{let i=ee._nextTaskID++;ee._taskCallbackMap.set(i,(e=>{if(e.success)return t(e.instanceID);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),ee._dbrWorker.postMessage({type:"createInstance",id:i,bScanner:e})}))}static async createInstance(){let e=new ee;return e._instanceID=await ee.createInstanceInWorker(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let n=ee._nextTaskID++;ee._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),ee._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:n,instanceID:this._instanceID})}))}async decode(e){ee._onLog&&ee._onLog("decode(source: any)"),ee._onLog&&(this._timeStartDecode=Date.now());{let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),e instanceof Blob?await this._decode_Blob(e,t):e instanceof ArrayBuffer?await this._decode_ArrayBuffer(e,t):e instanceof Uint8Array||e instanceof Uint8ClampedArray?await this._decode_Uint8Array(e,t):e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?await this._decode_Image(e,t):e instanceof HTMLCanvasElement?await this._decode_Canvas(e,t):e instanceof HTMLVideoElement?await this._decode_Video(e,t):"string"==typeof e?"data:image/"==e.substring(0,11)?await this._decode_Base64(e,t):await this._decode_Url(e,t):ee.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):ee.isDSImage(e)?(t.bCopyData=!0,await this._decode_DSImage(e,t)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(e,t)}async decodeUrl(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(e,t)}async _decodeBuffer_Uint8Array(e,t,n,i,r,o){return await new Promise(((a,s)=>{let _=ee._nextTaskID++;ee._taskCallbackMap.set(_,(e=>{if(e.success){let t,n=ee._onLog?Date.now():0;ee._onLog&&ee._onLog("worker return result: "+n),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return s(e)}if(ee._onLog){let e=Date.now();ee._onLog("DBR time get result: "+n),ee._onLog("Handle image cost: "+(this._timeEnterInnerDBR-this._timeStartDecode)),ee._onLog("DBR worker decode image cost: "+(n-this._timeEnterInnerDBR)),ee._onLog("DBR worker handle results: "+(e-n)),ee._onLog("Total decode image cost: "+(e-this._timeStartDecode))}return a(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,s(t)}})),this._timeEnterInnerDBR=Date.now(),ee._onLog&&ee._onLog("Send buffer to worker:"+this._timeEnterInnerDBR),ee._dbrWorker.postMessage({type:"decodeBuffer",id:_,instanceID:this._instanceID,body:{buffer:e,width:t,height:n,stride:i,format:r,config:o}},[e.buffer]),ee._onLog&&o&&o.timeStamp&&ee._onLog("decode image delay: "+(this._timeEnterInnerDBR-o.timeStamp))}))}async _decodeBuffer_Blob(e,t,n,i,r,o){ee._onLog&&ee._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const a=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,n)=>{let i=new FileReader;i.readAsArrayBuffer(e),i.onload=()=>{t(i.result)},i.onerror=()=>{n(i.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(a),t,n,i,r,o)}async decodeBuffer(e,t,n,i,r,o){let a;return ee._onLog&&ee._onLog("decodeBuffer(buffer,width,height,stride,format)"),ee._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?a=await this._decodeBuffer_Uint8Array(e,t,n,i,r,o):e instanceof ArrayBuffer?a=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,n,i,r,o):e instanceof Blob&&(a=await this._decodeBuffer_Blob(e,t,n,i,r,o)),a}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,n)=>{let i=ee._nextTaskID++;ee._taskCallbackMap.set(i,(e=>{if(e.success){let i;this._lastInnerDecodeDuration=e.duration;try{i=this._handleRetJsonString(e.decodeReturn)}catch(e){return n(e)}return t(i)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),ee._dbrWorker.postMessage({type:"decodeFileInMemory",id:i,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let n=ee._nextTaskID++;ee._taskCallbackMap.set(n,(n=>{if(n.success){let t=JSON.parse(n.results);return null!=this.userDefinedRegion&&(t.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),e(t)}{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),ee._dbrWorker.postMessage({type:"getRuntimeSettings",id:n,instanceID:this._instanceID})}))}async updateRuntimeSettings(e){let t;if("string"==typeof e)if("speed"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=3,t.expectedBarcodesCount=0,t.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=5,t.expectedBarcodesCount=512,t.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region}else t=JSON.parse(e);else{if("object"!=typeof e)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(t=JSON.parse(JSON.stringify(e)),t.region instanceof Array){let e=t.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(t.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!ee._bUseFullFeature){if(0!=(t.barcodeFormatIds&~(f.BF_ONED|f.BF_QR_CODE|f.BF_PDF417|f.BF_DATAMATRIX))||0!=t.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=t.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let e=t.region;if(e instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(e)),(e.regionLeft||e.regionTop||e.regionRight||e.regionBottom||e.regionMeasuredByPercentage)&&(e.regionLeft||e.regionTop||100!=e.regionRight||100!=e.regionBottom||!e.regionMeasuredByPercentage)?this.region=e:this.region=null,t.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return await new Promise(((e,n)=>{let i=ee._nextTaskID++;ee._taskCallbackMap.set(i,(t=>{if(t.success){try{this._handleRetJsonString(t.updateReturn)}catch(e){n(e)}return e()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}})),ee._dbrWorker.postMessage({type:"updateRuntimeSettings",id:i,instanceID:this._instanceID,body:{settings:JSON.stringify(t)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,await new Promise(((e,t)=>{let n=ee._nextTaskID++;ee._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),ee._dbrWorker.postMessage({type:"resetRuntimeSettings",id:n,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!ee._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((e,t)=>{let n=ee._nextTaskID++;ee._taskCallbackMap.set(n,(n=>{if(n.success)return e(n.results);{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),ee._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:n,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!ee._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof e)e=e;else{if("object"!=typeof e)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");e=JSON.stringify(e)}return await new Promise(((t,n)=>{let i=ee._nextTaskID++;ee._taskCallbackMap.set(i,(e=>{if(e.success){try{this._handleRetJsonString(e.initReturn)}catch(e){n(e)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),ee._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:i,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){ee._onLog&&ee._onLog("_decode_Blob(blob: Blob)");let n=null,i=null;if("undefined"!=typeof createImageBitmap)try{n=await createImageBitmap(e)}catch(e){}n||(i=await function(e){return new Promise(((t,n)=>{let i=URL.createObjectURL(e),r=new Image;r.dbrObjUrl=i,r.src=i,r.onload=()=>{t(r)},r.onerror=e=>{n(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let r=await this._decode_Image(n||i,t);return n&&n.close(),r}async _decode_ArrayBuffer(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Uint8Array(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Image(e,t){ee._onLog&&ee._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),t=t||{};let n,i,r=e instanceof HTMLImageElement?e.naturalWidth:e.width,o=e instanceof HTMLImageElement?e.naturalHeight:e.height,a=Math.max(r,o);if(a>this._maxCvsSideLength){let e=this._maxCvsSideLength/a;n=Math.round(r*e),i=Math.round(o*e)}else n=r,i=o;this.canvas||(this.canvas=document.createElement("canvas"));const s=this.canvas;s.width===n&&s.height===i||(s.width=n,s.height=i),s.ctx2d||(s.ctx2d=s.getContext("2d"));return s.ctx2d.drawImage(e,0,0,r,o,0,0,n,i),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._decode_Canvas(s,t)}async _decode_Canvas(e,t){if(ee._onLog&&ee._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";if(0===e.width||0===e.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=e,this.oriCanvasData=null);let n=(e.ctx2d||e.getContext("2d")).getImageData(0,0,e.width,e.height).data;return await this._decodeBuffer_Uint8Array(n,e.width,e.height,4*e.width,l.IPF_ABGR_8888,t)}async _decode_Video(e,t){if(ee._onLog&&ee._onLog("_decode_Video(video)"),!(e instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";t=t||{};let n,i,r=e.videoWidth,o=e.videoHeight,a=Math.max(r,o);if(a>this._maxCvsSideLength){let e=this._maxCvsSideLength/a;n=Math.round(r*e),i=Math.round(o*e)}else n=r,i=o;this.canvas||(this.canvas=document.createElement("canvas"));const s=this.canvas;s.width===n&&s.height===i||(s.width=n,s.height=i),s.ctx2d||(s.ctx2d=s.getContext("2d"));return s.ctx2d.drawImage(e,0,0,r,o,0,0,n,i),await this._decode_Canvas(s,t)}async _decode_DCEFrame(e,t){if(ee._onLog&&ee._onLog("_decode_DCEFrame(dceFrame)"),!ee.isDCEFrame(e))return null;let n;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,colorMode:e.colorMode,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{width:i,height:r,colorMode:o,timeStamp:a}=e;let s;s=t&&t.bCopyData?new Uint8Array(e.data):e.data;let _=null;if(t?(_=JSON.parse(JSON.stringify(t)),_.timeStamp=a):_={timeStamp:a},"grey"===o)n=await this._decodeBuffer_Uint8Array(s,i,r,i,l.IPF_GrayScaled,_);else if("rgba"===o)n=await this._decodeBuffer_Uint8Array(s,i,r,4*i,l.IPF_ABGR_8888,_);else{if("bgra"!==o)throw new Error(`Color mode '${o}' is not supported to decode.`);n=await this._decodeBuffer_Uint8Array(s,i,r,4*i,l.IPF_ARGB_8888,_)}return n}async _decode_DSImage(e,t){if(ee._onLog&&ee._onLog("_decode_DSImage(dsImage)"),!ee.isDSImage(e))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,pixelFormat:e.pixelFormat.toLowerCase(),data:new Uint8Array(e.data),toCanvas:function(){const e=document.createElement("canvas");let t;switch(e.width=this.width,e.height=this.height,this.pixelFormat){case"grey":t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{let i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="blob",i.send(),i.onloadend=async()=>{t(i.response)},i.onerror=()=>{n(new Error("Network Error: "+i.statusText))}}));return await this._decode_Blob(n,t)}}async _decode_FilePath(e,t){throw ee._onLog&&ee._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static fixResultLocationWhenFilterRegionInJs(e,t,n,i,r,o,a,s){if(e&&t.length>0)for(let e of t){let t=e.localizationResult;2==t.resultCoordinateType&&(t.x1*=.01*a,t.x2*=.01*a,t.x3*=.01*a,t.x4*=.01*a,t.y1*=.01*s,t.y2*=.01*s,t.y3*=.01*s,t.y4*=.01*s);let _=a/r,d=s/o;t.x1=t.x1/_+n,t.x2=t.x2/_+n,t.x3=t.x3/_+n,t.x4=t.x4/_+n,t.y1=t.y1/d+i,t.y2=t.y2/d+i,t.y3=t.y3/d+i,t.y4=t.y4/d+i,2==t.resultCoordinateType&&(t.x1*=100/r,t.x2*=100/r,t.x3*=100/r,t.x4*=100/r,t.y1*=100/o,t.y2*=100/o,t.y3*=100/o,t.y4*=100/o)}}static BarcodeReaderException(e,t){let n,i=h.DBR_UNKNOWN;return"number"==typeof e?(i=e,n=new Error(t)):n=new Error(e),n.code=i,n}_handleRetJsonString(e){let t=h;if(e.textResults){for(let t=0;t{let n=t.indexOf(":");e[t.substring(0,n)]=t.substring(n+1)})),n.exception=e}}return e.decodeRecords?this.decodeRecords=e.decodeRecords:this.decodeRecords={},this._lastErrorCode=e.exception,this._lastErrorString=e.description,e.exception&&!ee._setWarnnedEx.has(e.description)&&(ee._setWarnnedEx.add(e.description),console.warn(e.description)),e.textResults}if(e.exception==t.DBR_SUCCESS)return e.data;throw ee.BarcodeReaderException(e.exception,e.description)}async setModeArgument(e,t,n,i){return await new Promise(((r,o)=>{let a=ee._nextTaskID++;ee._taskCallbackMap.set(a,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return o(e)}return r()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,o(t)}})),ee._dbrWorker.postMessage({type:"setModeArgument",id:a,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:n,argumentValue:i}})}))}async getModeArgument(e,t,n){return await new Promise(((i,r)=>{let o=ee._nextTaskID++;ee._taskCallbackMap.set(o,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return r(e)}return i(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,r(t)}})),ee._dbrWorker.postMessage({type:"getModeArgument",id:o,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:n}})}))}async getIntermediateResults(){return await new Promise(((e,t)=>{let n=ee._nextTaskID++;ee._taskCallbackMap.set(n,(n=>{if(n.success)return e(n.results);{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),ee._dbrWorker.postMessage({type:"getIntermediateResults",id:n,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let e=await this.getIntermediateResults(),t=[];for(let n of e)if(n.dataType==g.IMRDT_IMAGE)for(let e of n.results){const n=e.bytes;let i;switch(ee._onLog&&ee._onLog(" "+n.length+" "+n.byteLength+" "+e.width+" "+e.height+" "+e.stride+" "+e.format),e.format){case l.IPF_ABGR_8888:i=new Uint8ClampedArray(n);break;case l.IPF_RGB_888:{const e=n.length/3;i=new Uint8ClampedArray(4*e);for(let t=0;t{let n=ee._nextTaskID++;ee._taskCallbackMap.set(n,(n=>{if(n.success){let t=n.results;return t.intervalTime=this.intervalTime,t.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,t.soundOnSuccessfullRead=this.soundSource,t.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,t.vibrateDuration=this.vibrateDuration,e(t)}{let e=new Error(n.message);return e.stack+="\n"+n.stack,t(e)}})),ee._dbrWorker.postMessage({type:"getScanSettings",id:n,instanceID:this._instanceID})}))}async updateScanSettings(e){if(!e)return;const t=JSON.parse(JSON.stringify(e));return t.hasOwnProperty("intervalTime")&&(this.intervalTime=t.intervalTime,delete t.intervalTime),t.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=t.whenToPlaySoundforSuccessfulRead,delete t.whenToPlaySoundforSuccessfulRead),t.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=t.soundOnSuccessfullRead,delete t.soundOnSuccessfullRead),t.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=t.whenToVibrateforSuccessfulRead,delete t.whenToVibrateforSuccessfulRead),t.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=t.vibrateDuration,delete t.vibrateDuration),await new Promise(((e,n)=>{let i=ee._nextTaskID++;ee._taskCallbackMap.set(i,(t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack+="\n"+t.stack,n(e)}})),ee._dbrWorker.postMessage({type:"updateScanSettings",id:i,instanceID:this._instanceID,body:{settings:t}})}))}_cloneDecodeResults(e){if(e instanceof Array){let t=[];for(let n of e)t.push(this._cloneDecodeResults(n));return t}{let t=e;return JSON.parse(JSON.stringify(t,((e,t)=>"oriVideoCanvas"==e||"searchRegionCanvas"==e?void 0:t)))}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this.imgSource||this._bPauseScan)return ee._onLog&&ee._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));ee._onLog&&ee._onLog("======= once read ======="),ee._onLog&&(this._timeStartDecode=Date.now());let e=null,t=null;if(this.dce)e=this._getVideoFrame();else if(this.imgSource&&(t=await this.imgSource.getImage(),!ee.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let n=null;return e?n=await this._decode_DCEFrame(e,{bScanner:!0,bCopyData:!1}):t&&(n=await this._decode_DSImage(t,{bScanner:!0,bCopyData:!1})),n})().then((e=>{if(ee._onLog&&ee._onLog(e),this.dce){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost;this._indexCurrentDecodingFrame;const n=()=>{let n=0;if(t&&t.length){let i=Math.min(...e),r=Math.max(...t);i&&r&&(n=i-r)}else n=0;return n>0?n:0};(()=>{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=n()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this.imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead)t=!0;else if("unique"===this.bPlaySoundOnSuccessfulRead)for(let n of e)if(n.bUnduplicated){t=!0;break}t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead)t=!0;else if("unique"===this.bVibrateOnSuccessfulRead)for(let n of e)if(n.bUnduplicated){t=!0;break}if(t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onImageRead){let t=this._cloneDecodeResults(e);for(let e of t)delete e.bUnduplicated;this.onImageRead(t)}if(this.onUniqueRead)for(let t of e)t.bUnduplicated&&this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t));this._drawResults(e)}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce&&this.dce.stopFetchingLoop(),ee._onLog&&ee._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e=this.dce.isFetchingLoopStarted();if(this.dceConfig.loopInterval=this._intervalGetVideoFrame,e||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dceConfig.loopInterval=0,null;const t=this.dce.getFrameFromBuffer();return(e=>{if(!e)return;let t=e.timeSpent,n=this.array_getFrameTimeCost;for(;n.length>=5;)n.shift();n.push(t)})(t),t}_drawResults(e){if(!this.dce||this._bPauseScan)return;if(!this.resultsOverlay){if(!this.dce.isOpen())return;this.resultsOverlay=this.dce.addScanRegionOverlayCanvas()}const t=this.resultsOverlay.getContext("2d");if(t.clearRect(0,0,this.resultsOverlay.width,this.resultsOverlay.height),e){t.globalCompositeOperation="destination-over",t.fillStyle=this.barcodeFillStyle,t.strokeStyle=this.barcodeStrokeStyle,t.lineWidth=this.barcodeLineWidth;for(let n of e){let e=n.localizationResult;t.beginPath(),t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineTo(e.x3,e.y3),t.lineTo(e.x4,e.y4),t.fill(),t.beginPath(),t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineTo(e.x3,e.y3),t.lineTo(e.x4,e.y4),t.closePath(),t.stroke()}}}async startScanning(e){if(!this.dce&&!this.imgSource)throw new Error("'imageSource' is not set. call 'setImageSource()' before 'startScanning()'.");if("closed"!=this._tempSolutionStatus)return;if(this._tempSolutionStatus="opening","opening"!=this._tempSolutionStatus)return;let t=null;return this.dce&&!this.dce.isOpen()&&(this.dce.ifShowScanRegionLaser=!0,t=await this.dce.open(e)),"opening"==this._tempSolutionStatus?(this._bPauseScan=!1,this.dce&&this.dce.singleFrameMode||this._loopReadVideo(),this._tempSolutionStatus="opened",this.keepAlive(),t):void 0}stopScanning(e){this.dce&&(this._drawResults(null),this.dce.ifShowScanRegionLaser=!1,this.dce.close(e)),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._tempSolutionStatus="closed"}pauseScanning(){if(this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.ifShowScanRegionLaser=!1,this.dce.stopFetchingLoop()}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.ifShowScanRegionLaser=!0}}destroyContext(){if(ee._onLog&&ee._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,(this.dce||"opening"===this._tempSolutionStatus)&&this.stopScanning(),this.setImageSource(null);let e=ee._nextTaskID++;ee._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),ee._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}ee._jsVersion="9.0.2",ee._jsEditVersion="20220505",ee._version=`loading...(JS ${ee._jsVersion}.${ee._jsEditVersion})`,ee._license=d,ee._sessionPassword=c,ee.browserInfo=n,ee._workerName=`dbr-${ee._jsVersion}.browser.worker.js`,ee._engineResourcePath=s,ee._licenseServer=[],ee._deviceFriendlyName="",ee._isShowRelDecodeTimeInResults=!1,ee._bWasmDebug=!1,ee._bNeverShowDialog=!1,ee.__bUseFullFeature=!0,ee._nextTaskID=0,ee._taskCallbackMap=new Map,ee._pLoad=new class extends Promise{constructor(e){let t,n;super(((e,i)=>{t=e,n=i})),this._s="pending",this.resolve=e=>{this.isPending&&(A(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",n(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,A(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const n=await t;e===this._task&&this.resolve(n)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}},ee._lastErrorCode=0,ee._lastErrorString="",ee._setWarnnedEx=new Set,ee._defaultUIElementURL="@engineResourcePath/dbr.ui.html";class te extends ee{constructor(){super(),this.bFilterRegionInJs=!0,this._onCameraSelChange=()=>{},this._onResolutionSelChange=()=>{},this._onCloseBtnClick=()=>{},this._onPlayed=null}static get version(){return this._version+`(DCE ${e.getVersion()})`}getUIElement(){return this.dce.getUIElement()}async setUIElement(e){await this.dce.setUIElement(e)}get singleFrameMode(){return this.dce.singleFrameMode}set singleFrameMode(e){this.dce.singleFrameMode=e,e&&(this.dce.ifShowScanRegionLaser=!1,(async()=>{let e=await this.getScanSettings();e.oneDTrustFrameCount=1,await this.updateScanSettings(e)})())}get onUnduplicatedRead(){return this.onUniqueRead}set onUnduplicatedRead(e){this.onUniqueRead=e}_assertOpen(){if(!this.dce.isOpen())throw Error("The scanner is not open.")}set regionMaskFillStyle(e){this.dce.setScanRegionMaskStyle({fillStyle:e})}get regionMaskFillStyle(){return this.dce.regionMaskFillStyle}set regionMaskStrokeStyle(e){this.dce.setScanRegionMaskStyle({strokeStyle:e})}get regionMaskStrokeStyle(){return this.dce.regionMaskStrokeStyle}set regionMaskLineWidth(e){this.dce.setScanRegionMaskStyle({lineWidth:e})}get regionMaskLineWidth(){return this.dce.regionMaskLineWidth}set region(e){this._region=e,this.dce&&(e?e instanceof Array||this.dce.setScanRegion(e):this.dce.setScanRegion(null)),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e,this.dce.frameColorMode=e?"rgba":"grey"}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}async createDCEInstance(){this.dce||(ee._onLog&&ee._onLog("createDCEInstance()"),e.defaultUIElementURL=null,this.dce=await e.createInstance(),this.dce.refreshInterval=200,this.dce.frameColorMode="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this.dce.on("cameraChange",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("resolutionChange",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("cameraClose",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1})),this.dce.on("singleFrameAcquired",(async e=>{if(!e)return;if(!e.data)return;let t;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,colorMode:e.colorMode,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{data:n,region:i,sx:r,sy:o,width:a,height:s,colorMode:_,timeStamp:d}=e,c={timeStamp:d};if("grey"===_)t=await this._decodeBuffer_Uint8Array(n,a,s,a,l.IPF_GrayScaled,c);else if("rgba"===_)t=await this._decodeBuffer_Uint8Array(n,a,s,4*a,l.IPF_ABGR_8888,c);else{if("bgra"!==_)throw new Error(`Color mode '${_}' is not supported.`);t=await this._decodeBuffer_Uint8Array(n,a,s,4*a,l.IPF_ARGB_8888,c)}await this.clearMapDecodeRecord();for(let e of t)delete e.bUnduplicated;if(this._drawResults(t),ee.fixResultLocationWhenFilterRegionInJs(i,t,r,o,a,s,a,s),this.onFrameRead&&this.isOpen()&&!this._bPauseScan&&this.onFrameRead(t),this.onUniqueRead&&this.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,e)})))}set maxCvsSideLength(e){this._maxCvsSideLength=e,this.dce.maxCvsSideLength=e}get maxCvsSideLength(){return this._maxCvsSideLength}static async createInstance(e){let t=new te;await t.createDCEInstance(),t._instanceID=await te.createInstanceInWorker(!0),"string"==typeof e&&(e=JSON.parse(e));for(let n in e)t[n]=e[n];return await t.setUIElement(te.defaultUIElementURL),t.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),t.singleFrameMode||await t.updateRuntimeSettings("single"),t}async decodeCurrentFrame(e){this._assertOpen();let t=null;e&&e.region&&(t=e.region);const n=this.dce._getVideoFrame(t);return this._decode_DCEFrame(n)}static isRegionNormalPreset(e){return 0==e.regionLeft&&0==e.regionTop&&0==e.regionRight&&0==e.regionBottom&&0==e.regionMeasuredByPercentage}async updateRuntimeSettings(e){let t;if("string"==typeof e)if("speed"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region)}else if("balance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.deblurLevel=3,t.expectedBarcodesCount=512,t.localizationModes=[2,16,0,0,0,0,0,0],t.timeout=1e5}else if("coverage"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.deblurLevel=5,t.expectedBarcodesCount=512,t.scaleDownThreshold=1e5,t.localizationModes=[2,16,4,8,0,0,0,0],t.timeout=1e5}else if("single"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,te.isRegionNormalPreset(e.region)?t.region=null:t.region=e.region,t.expectedBarcodesCount=1,t.localizationModes=[16,2,0,0,0,0,0,0],t.barcodeZoneMinDistanceToImageBorders=0}else t=JSON.parse(e);else{if("object"!=typeof e)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(t=JSON.parse(JSON.stringify(e)),t.region instanceof Array){let n=e.region;[n.regionLeft,n.regionTop,n.regionLeft,n.regionBottom,n.regionMeasuredByPercentage].some((e=>void 0!==e))&&(t.region={regionLeft:n.regionLeft||0,regionTop:n.regionTop||0,regionRight:n.regionRight||0,regionBottom:n.regionBottom||0,regionMeasuredByPercentage:n.regionMeasuredByPercentage||0})}}if(!ee._bUseFullFeature){if(0!=(t.barcodeFormatIds&~(f.BF_ONED|f.BF_QR_CODE|f.BF_PDF417|f.BF_DATAMATRIX))||0!=t.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=t.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}{let e=t.region;if(this.bFilterRegionInJs?this.userDefinedRegion=JSON.parse(JSON.stringify(e)):this.userDefinedRegion=null,e instanceof Array)if(e.length){for(let t=0;t{let i=ee._nextTaskID++;ee._taskCallbackMap.set(i,(t=>{if(t.success){try{this._handleRetJsonString(t.updateReturn)}catch(e){n(e)}return e()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}})),ee._dbrWorker.postMessage({type:"updateRuntimeSettings",id:i,instanceID:this._instanceID,body:{settings:JSON.stringify(t)}})})),"single"==e&&(await this.setModeArgument("BinarizationModes",0,"EnableFillBinaryVacancy","0"),await this.setModeArgument("LocalizationModes",0,"ScanDirection","2"),await this.setModeArgument("BinarizationModes",0,"BlockSizeX","71"),await this.setModeArgument("BinarizationModes",0,"BlockSizeY","71"))}_bindUI(){if(!this.getUIElement())throw new Error("Need to define `UIElement` before opening.");if(this.dce._bindUI(),!this.dce.video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'")}_unbindUI(){this.dce._unbindUI()}set onPlayed(e){this.dce.off("played",this._onPlayed),this._onPlayed=e,this.dce.on("played",this._onPlayed)}get onPlayed(){return this._onPlayed}async getAllCameras(){return this.dce.getAllCameras()}async getCurrentCamera(){return this.dce.getSelectedCamera()}async setCurrentCamera(e){return this.dce.selectCamera(e)}getResolution(){return this.dce.getResolution()}async setResolution(e,t){return this.dce.setResolution(e,t)}getVideoSettings(){return this.dce.getVideoSettings()}updateVideoSettings(e){return this.dce.updateVideoSettings(e)}isOpen(){return this.dce&&this.dce.isOpen()}setVideoFit(e){return this.dce&&this.dce.setVideoFit(e)}set ifShowScanRegionMask(e){this.dce&&(this.dce.ifShowScanRegionMask=e)}get ifShowScanRegionMask(){return this.dce&&this.dce.ifShowScanRegionMask}stop(){this.dce.stop(),this.dce.hideScanRegionLaser(),this.dce.hideViewDecorator(),this.dce.hideScanRegionOverlays(),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}pause(){this._drawResults(null),this.dce.pause()}async play(e,t,n){this.dce.ifShowScanRegionLaser=!0;return await this.dce.play(e,t,n)}pauseScan(){this._assertOpen(),this._drawResults(null),this._bPauseScan=!0,this.dce.ifShowScanRegionLaser=!1}resumeScan(){this._assertOpen(),this._bPauseScan=!1,this.dce.ifShowScanRegionLaser=!0}getCapabilities(){return this.dce.getCapabilities()}getCameraSettings(){return this.dce.getCameraSettings()}getConstraints(){return this.dce.getConstraints()}async applyConstraints(e){return this.dce.applyConstraints(e)}async turnOnTorch(){return this.dce.turnOnTorch()}async turnOffTorch(){return this.dce.turnOffTorch()}async setColorTemperature(e){return this.dce.setColorTemperature(e)}async setExposureCompensation(e){return this.dce.setExposureCompensation(e)}async setZoom(e){return this.dce.setZoom(e)}async setFrameRate(e){return this.dce.setFrameRate(e)}getFrameRate(){return this.dce.getFrameRate()}async setFocus(e,t){return this.dce.setFocus(e,t)}getFocus(){return this.dce.getFocus()}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),void this._drawResults(null);if(!this.isOpen())return this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce.video||this.dce.video.paused||this._bPauseScan)return ee._onLog&&ee._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));ee._onLog&&ee._onLog("======= once read ======="),ee._onLog&&(this._timeStartDecode=Date.now());const e=this._getVideoFrame();if(!e)return this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let t;e._bUseWebGL||"grey"!==e.colorMode||(this.dce.frameColorMode="rgba"),this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,colorMode:e.colorMode,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{data:n,region:i,sx:r,sy:o,width:a,height:s,colorMode:_,timeStamp:d}=e,c={timeStamp:d};if("grey"===_)t=await this._decodeBuffer_Uint8Array(n,a,s,a,l.IPF_GrayScaled,c);else if("rgba"===_)t=await this._decodeBuffer_Uint8Array(n,a,s,4*a,l.IPF_ABGR_8888,c);else{if("bgra"!==_)throw new Error(`Color mode '${_}' is not supported.`);t=await this._decodeBuffer_Uint8Array(n,a,s,4*a,l.IPF_ARGB_8888,c)}return this.dce&&this.dce.video&&!this.dce.video.paused&&this._drawResults(t),ee.fixResultLocationWhenFilterRegionInJs(i,t,r,o,a,s,a,s),t})().then((e=>{ee._onLog&&ee._onLog(e);let t=this.array_decodeFrameTimeCost,n=this.array_getFrameTimeCost,i=this._indexCurrentDecodingFrame;if((()=>{if(this.region instanceof Array){for(t[i]&&t[i]instanceof Array||(t[i]=[]);t[i].length>=5;)t[i].shift();t[i].push(this._lastInnerDecodeDuration)}else{for(;t.length>=5;)t.shift();t.push(this._lastInnerDecodeDuration)}})(),this._intervalGetVideoFrame=(()=>{let e=0;if(this.region instanceof Array){let r=0,o=0;r=i+1>=this.region.length?0:i+1,o=r+1>=this.region.length?0:r+1,e=t[r]&&t[r].length&&n[o]&&n[o].length?Math.min(...t[r])-Math.max(...n[o]):0}else if(n&&n.length){let i=Math.min(...t),r=Math.max(...n);i&&r&&(e=i-r)}else e=0;return e>0?e:0})()+this.intervalTime,this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead)t=!0;else if("unique"===this.bPlaySoundOnSuccessfulRead)for(let n of e)if(n.bUnduplicated){t=!0;break}t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead)t=!0;else if("unique"===this.bVibrateOnSuccessfulRead)for(let n of e)if(n.bUnduplicated){t=!0;break}if(t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onFrameRead){let t=this._cloneDecodeResults(e);for(let e of t)delete e.bUnduplicated;this.onFrameRead(t)}if(this.onUniqueRead)for(let t of e)t.bUnduplicated&&this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t))}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce.stopFetchingLoop(),ee._onLog&&ee._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e=this.dce.isFetchingLoopStarted();if(this.dce.loopInterval=this._intervalGetVideoFrame,e||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dce.loopInterval=0,null;const t=this.dce.getFrameFromBuffer();return(e=>{if(!e)return;let t=e.timeSpent,n=this.array_getFrameTimeCost;for(;n.length>=5;)n.shift();n.push(t)})(t),t}async open(){this._bindUI();let e=await this.dce.open();return this._bPauseScan=!1,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.dce.ifShowScanRegionLaser=!0,this._loopReadVideo()),this.keepAlive(),e}async openVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open();return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideo()),this.keepAlive(),e}close(){this.dce.close(),this._bPauseScan=!0}async show(){this._bindUI();const e=await this.dce.open(!0);return this._bPauseScan=!1,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.dce.ifShowScanRegionLaser=!0,this._loopReadVideo()),this.keepAlive(),e}async showVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open(!0);return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideo()),this.keepAlive(),e}hide(){this.dce.close(!0),this._bPauseScan=!0}destroyContext(){this.close(),this.bDestroyed||super.destroyContext()}}!function(e){e[e.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",e[e.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",e[e.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",e[e.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",e[e.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",e[e.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",e[e.BICM_SKIP=0]="BICM_SKIP",e[e.BICM_REV=2147483648]="BICM_REV"}(E||(E={})),function(e){e[e.BCM_AUTO=1]="BCM_AUTO",e[e.BCM_GENERAL=2]="BCM_GENERAL",e[e.BCM_SKIP=0]="BCM_SKIP",e[e.BCM_REV=2147483648]="BCM_REV"}(S||(S={})),function(e){e[e.BF2_NULL=0]="BF2_NULL",e[e.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",e[e.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",e[e.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",e[e.BF2_POSTNET=2097152]="BF2_POSTNET",e[e.BF2_PLANET=4194304]="BF2_PLANET",e[e.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",e[e.BF2_RM4SCC=16777216]="BF2_RM4SCC",e[e.BF2_DOTCODE=2]="BF2_DOTCODE",e[e.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",e[e.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",e[e.BF2_PHARMACODE=12]="BF2_PHARMACODE"}(T||(T={})),function(e){e[e.BM_AUTO=1]="BM_AUTO",e[e.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",e[e.BM_SKIP=0]="BM_SKIP",e[e.BM_THRESHOLD=4]="BM_THRESHOLD",e[e.BM_REV=2147483648]="BM_REV"}(D||(D={})),function(e){e[e.ECCM_CONTRAST=1]="ECCM_CONTRAST"}(y||(y={})),function(e){e[e.CFM_GENERAL=1]="CFM_GENERAL"}(C||(C={})),function(e){e[e.CCM_AUTO=1]="CCM_AUTO",e[e.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",e[e.CCM_SKIP=0]="CCM_SKIP",e[e.CCM_REV=2147483648]="CCM_REV"}(v||(v={})),function(e){e[e.CICM_GENERAL=1]="CICM_GENERAL",e[e.CICM_SKIP=0]="CICM_SKIP",e[e.CICM_REV=2147483648]="CICM_REV"}(O||(O={})),function(e){e[e.CM_IGNORE=1]="CM_IGNORE",e[e.CM_OVERWRITE=2]="CM_OVERWRITE"}(M||(M={})),function(e){e[e.DM_SKIP=0]="DM_SKIP",e[e.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",e[e.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",e[e.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",e[e.DM_SMOOTHING=8]="DM_SMOOTHING",e[e.DM_MORPHING=16]="DM_MORPHING",e[e.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",e[e.DM_SHARPENING=64]="DM_SHARPENING",e[e.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",e[e.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING"}(b||(b={})),function(e){e[e.DRM_AUTO=1]="DRM_AUTO",e[e.DRM_GENERAL=2]="DRM_GENERAL",e[e.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",e[e.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",e[e.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",e[e.DRM_SKIP=0]="DRM_SKIP",e[e.DRM_REV=2147483648]="DRM_REV"}(L||(L={})),function(e){e[e.DPMCRM_AUTO=1]="DPMCRM_AUTO",e[e.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",e[e.DPMCRM_SKIP=0]="DPMCRM_SKIP",e[e.DPMCRM_REV=2147483648]="DPMCRM_REV"}(w||(w={})),function(e){e[e.GTM_INVERTED=1]="GTM_INVERTED",e[e.GTM_ORIGINAL=2]="GTM_ORIGINAL",e[e.GTM_SKIP=0]="GTM_SKIP",e[e.GTM_REV=2147483648]="GTM_REV"}(B||(B={})),function(e){e[e.IPM_AUTO=1]="IPM_AUTO",e[e.IPM_GENERAL=2]="IPM_GENERAL",e[e.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",e[e.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",e[e.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",e[e.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",e[e.IPM_SKIP=0]="IPM_SKIP",e[e.IPM_REV=2147483648]="IPM_REV"}(N||(N={})),function(e){e[e.IRSM_MEMORY=1]="IRSM_MEMORY",e[e.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",e[e.IRSM_BOTH=4]="IRSM_BOTH"}(F||(F={})),function(e){e[e.IRT_NO_RESULT=0]="IRT_NO_RESULT",e[e.IRT_ORIGINAL_IMAGE=1]="IRT_ORIGINAL_IMAGE",e[e.IRT_COLOUR_CLUSTERED_IMAGE=2]="IRT_COLOUR_CLUSTERED_IMAGE",e[e.IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE=4]="IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE",e[e.IRT_TRANSFORMED_GRAYSCALE_IMAGE=8]="IRT_TRANSFORMED_GRAYSCALE_IMAGE",e[e.IRT_PREDETECTED_REGION=16]="IRT_PREDETECTED_REGION",e[e.IRT_PREPROCESSED_IMAGE=32]="IRT_PREPROCESSED_IMAGE",e[e.IRT_BINARIZED_IMAGE=64]="IRT_BINARIZED_IMAGE",e[e.IRT_TEXT_ZONE=128]="IRT_TEXT_ZONE",e[e.IRT_CONTOUR=256]="IRT_CONTOUR",e[e.IRT_LINE_SEGMENT=512]="IRT_LINE_SEGMENT",e[e.IRT_FORM=1024]="IRT_FORM",e[e.IRT_SEGMENTATION_BLOCK=2048]="IRT_SEGMENTATION_BLOCK",e[e.IRT_TYPED_BARCODE_ZONE=4096]="IRT_TYPED_BARCODE_ZONE",e[e.IRT_PREDETECTED_QUADRILATERAL=8192]="IRT_PREDETECTED_QUADRILATERAL"}(P||(P={})),function(e){e[e.LM_SKIP=0]="LM_SKIP",e[e.LM_AUTO=1]="LM_AUTO",e[e.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",e[e.LM_LINES=8]="LM_LINES",e[e.LM_STATISTICS=4]="LM_STATISTICS",e[e.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",e[e.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",e[e.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",e[e.LM_CENTRE=128]="LM_CENTRE",e[e.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",e[e.LM_REV=2147483648]="LM_REV"}(V||(V={})),function(e){e[e.PDFRM_RASTER=1]="PDFRM_RASTER",e[e.PDFRM_AUTO=2]="PDFRM_AUTO",e[e.PDFRM_VECTOR=4]="PDFRM_VECTOR",e[e.PDFRM_REV=2147483648]="PDFRM_REV"}(x||(x={})),function(e){e[e.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",e[e.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",e[e.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",e[e.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(k||(k={})),function(e){e[e.RPM_AUTO=1]="RPM_AUTO",e[e.RPM_GENERAL=2]="RPM_GENERAL",e[e.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",e[e.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",e[e.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",e[e.RPM_SKIP=0]="RPM_SKIP",e[e.RPM_REV=2147483648]="RPM_REV"}(U||(U={})),function(e){e[e.RCT_PIXEL=1]="RCT_PIXEL",e[e.RCT_PERCENTAGE=2]="RCT_PERCENTAGE"}(G||(G={})),function(e){e[e.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",e[e.RT_RAW_TEXT=1]="RT_RAW_TEXT",e[e.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",e[e.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT"}(H||(H={})),function(e){e[e.SUM_AUTO=1]="SUM_AUTO",e[e.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",e[e.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",e[e.SUM_SKIP=0]="SUM_SKIP",e[e.SUM_REV=2147483648]="SUM_REV"}(W||(W={})),function(e){e[e.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",e[e.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",e[e.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",e[e.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",e[e.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",e[e.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED"}(K||(K={})),function(e){e[e.TFM_AUTO=1]="TFM_AUTO",e[e.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",e[e.TFM_SKIP=0]="TFM_SKIP",e[e.TFM_REV=2147483648]="TFM_REV"}(Y||(Y={})),function(e){e[e.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",e[e.TROM_POSITION=2]="TROM_POSITION",e[e.TROM_FORMAT=4]="TROM_FORMAT",e[e.TROM_SKIP=0]="TROM_SKIP",e[e.TROM_REV=2147483648]="TROM_REV"}(J||(J={})),function(e){e[e.TDM_AUTO=1]="TDM_AUTO",e[e.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",e[e.TDM_SKIP=0]="TDM_SKIP",e[e.TDM_REV=2147483648]="TDM_REV"}(Q||(Q={}));export{ee as BarcodeReader,te as BarcodeScanner,E as EnumBarcodeColourMode,S as EnumBarcodeComplementMode,f as EnumBarcodeFormat,T as EnumBarcodeFormat_2,D as EnumBinarizationMode,y as EnumClarityCalculationMethod,C as EnumClarityFilterMode,v as EnumColourClusteringMode,O as EnumColourConversionMode,M as EnumConflictMode,w as EnumDPMCodeReadingMode,b as EnumDeblurMode,L as EnumDeformationResistingMode,h as EnumErrorCode,B as EnumGrayscaleTransformationMode,g as EnumIMResultDataType,l as EnumImagePixelFormat,N as EnumImagePreprocessingMode,F as EnumIntermediateResultSavingMode,P as EnumIntermediateResultType,V as EnumLocalizationMode,x as EnumPDFReadingMode,k as EnumQRCodeErrorCorrectionLevel,U as EnumRegionPredetectionMode,G as EnumResultCoordinateType,H as EnumResultType,W as EnumScaleUpMode,K as EnumTerminatePhase,Y as EnumTextFilterMode,J as EnumTextResultOrderMode,Q as EnumTextureDetectionMode}; diff --git a/dist/dbr.js b/dist/dbr.js index 1938188..3420de7 100644 --- a/dist/dbr.js +++ b/dist/dbr.js @@ -4,19 +4,18 @@ * @website http://www.dynamsoft.com * @copyright Copyright 2022, Dynamsoft Corporation * @author Dynamsoft - * @version 9.0.2 (js 20220505) + * @version 9.2.11 (js 20220727) * @fileoverview Dynamsoft JavaScript Library for Barcode Reader * More info on DBR JS: https://www.dynamsoft.com/barcode-reader/sdk-javascript/ */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).Dynamsoft=e.Dynamsoft||{},e.Dynamsoft.DBR={}))}(this,(function(e){"use strict";const t="undefined"==typeof self;let i;if(!t){const e={init:function(){this.browser=this.searchString(this.dataBrowser)||"unknownBrowser",this.version=this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion)||"unknownVersion",this.OS=this.searchString(this.dataOS)||"unknownOS","Linux"==this.OS&&-1!=navigator.userAgent.indexOf("Windows NT")&&(this.OS="HarmonyOS")},searchString:function(e){for(var t=0;t{let e=!1;if(r)try{(await navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e},a=(()=>{if(!t&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),d=" is not allowed to change after `createInstance` or `loadWasm` is called.",l=!t&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",c=!t&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",h=e=>{if(null==e)e=[];else{e=e instanceof Array?[...e]:[e];for(let i=0;ie&&"object"==typeof e&&"function"==typeof e.then;var p=function(){this.init()};p.prototype={init:function(){var e=this||v;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var t=this||v;if(e=parseFloat(e),t.ctx||C(),void 0!==e&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,v.ctx.currentTime);for(var i=0;i=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,C()),e},codecs:function(e){return(this||v)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||v;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||v,t=null;try{t="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!t||"function"!=typeof t.canPlayType)return e;var i=t.canPlayType("audio/mpeg;").replace(/^no$/,""),n=e._navigator?e._navigator.userAgent:"",o=n.match(/OPR\/([0-6].)/g),r=o&&parseInt(o[0].split("/")[1],10)<33,s=-1!==n.indexOf("Safari")&&-1===n.indexOf("Chrome"),a=n.match(/Version\/(.*?) /),d=s&&a&&parseInt(a[1],10)<15;return e._codecs={mp3:!(r||!i&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!i,opus:!!t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(t.canPlayType('audio/wav; codecs="1"')||t.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!t.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!t.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/m4a;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(t.canPlayType("audio/x-m4b;")||t.canPlayType("audio/m4b;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(t.canPlayType("audio/x-mp4;")||t.canPlayType("audio/mp4;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(d||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(d||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!t.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(t.canPlayType("audio/x-flac;")||t.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||v;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var t=function(i){for(;e._html5AudioPool.length0?s._seek:i._sprite[e][0]/1e3),l=Math.max(0,(i._sprite[e][0]+i._sprite[e][1])/1e3-d),c=1e3*l/Math.abs(s._rate),h=i._sprite[e][0]/1e3,_=(i._sprite[e][0]+i._sprite[e][1])/1e3;s._sprite=e,s._ended=!1;var u=function(){s._paused=!1,s._seek=d,s._start=h,s._stop=_,s._loop=!(!s._loop&&!i._sprite[e][2])};if(!(d>=_)){var g=s._node;if(i._webAudio){var m=function(){i._playLock=!1,u(),i._refreshBuffer(s);var e=s._muted||i._muted?0:s._volume;g.gain.setValueAtTime(e,v.ctx.currentTime),s._playStart=v.ctx.currentTime,void 0===g.bufferSource.start?s._loop?g.bufferSource.noteGrainOn(0,d,86400):g.bufferSource.noteGrainOn(0,d,l):s._loop?g.bufferSource.start(0,d,86400):g.bufferSource.start(0,d,l),c!==1/0&&(i._endTimers[s._id]=setTimeout(i._ended.bind(i,s),c)),t||setTimeout((function(){i._emit("play",s._id),i._loadQueue()}),0)};"running"===v.state&&"interrupted"!==v.ctx.state?m():(i._playLock=!0,i.once("resume",m),i._clearTimer(s._id))}else{var f=function(){g.currentTime=d,g.muted=s._muted||i._muted||v._muted||g.muted,g.volume=s._volume*v.volume(),g.playbackRate=s._rate;try{var n=g.play();if(n&&"undefined"!=typeof Promise&&(n instanceof Promise||"function"==typeof n.then)?(i._playLock=!0,u(),n.then((function(){i._playLock=!1,g._unlocked=!0,t?i._loadQueue():i._emit("play",s._id)})).catch((function(){i._playLock=!1,i._emit("playerror",s._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),s._ended=!0,s._paused=!0}))):t||(i._playLock=!1,u(),i._emit("play",s._id)),g.playbackRate=s._rate,g.paused)return void i._emit("playerror",s._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||s._loop?i._endTimers[s._id]=setTimeout(i._ended.bind(i,s),c):(i._endTimers[s._id]=function(){i._ended(s),g.removeEventListener("ended",i._endTimers[s._id],!1)},g.addEventListener("ended",i._endTimers[s._id],!1))}catch(e){i._emit("playerror",s._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===g.src&&(g.src=i._src,g.load());var p=window&&window.ejecta||!g.readyState&&v._navigator.isCocoonJS;if(g.readyState>=3||p)f();else{i._playLock=!0,i._state="loading";var A=function(){i._state="loaded",f(),g.removeEventListener(v._canPlayEvent,A,!1)};g.addEventListener(v._canPlayEvent,A,!1),i._clearTimer(s._id)}}return s._id}i._ended(s)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var i=t._getSoundIds(e),n=0;n=0?t=parseInt(o[0],10):e=parseFloat(o[0])}else o.length>=2&&(e=parseFloat(o[0]),t=parseInt(o[1],10));if(!(void 0!==e&&e>=0&&e<=1))return(i=t?n._soundById(t):n._sounds[0])?i._volume:0;if("loaded"!==n._state||n._playLock)return n._queue.push({event:"volume",action:function(){n.volume.apply(n,o)}}),n;void 0===t&&(n._volume=e),t=n._getSoundIds(t);for(var a=0;a0?n/l:n),h=Date.now();e._fadeTo=i,e._interval=setInterval((function(){var o=(Date.now()-h)/n;h=Date.now(),a+=d*o,a=Math.round(100*a)/100,a=d<0?Math.max(i,a):Math.min(i,a),s._webAudio?e._volume=a:s.volume(a,e._id,!0),r&&(s._volume=a),(it&&a>=i)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,s.volume(i,e._id),s._emit("fade",e._id))}),c)},_stopFade:function(e){var t=this,i=t._soundById(e);return i&&i._interval&&(t._webAudio&&i._node.gain.cancelScheduledValues(v.ctx.currentTime),clearInterval(i._interval),i._interval=null,t.volume(i._fadeTo,e),i._fadeTo=null,t._emit("fade",e)),t},loop:function(){var e,t,i,n=this,o=arguments;if(0===o.length)return n._loop;if(1===o.length){if("boolean"!=typeof o[0])return!!(i=n._soundById(parseInt(o[0],10)))&&i._loop;e=o[0],n._loop=e}else 2===o.length&&(e=o[0],t=parseInt(o[1],10));for(var r=n._getSoundIds(t),s=0;s=0?t=parseInt(o[0],10):e=parseFloat(o[0])}else 2===o.length&&(e=parseFloat(o[0]),t=parseInt(o[1],10));if("number"!=typeof e)return(i=n._soundById(t))?i._rate:n._rate;if("loaded"!==n._state||n._playLock)return n._queue.push({event:"rate",action:function(){n.rate.apply(n,o)}}),n;void 0===t&&(n._rate=e),t=n._getSoundIds(t);for(var a=0;a=0?t=parseInt(n[0],10):i._sounds.length&&(t=i._sounds[0]._id,e=parseFloat(n[0]))}else 2===n.length&&(e=parseFloat(n[0]),t=parseInt(n[1],10));if(void 0===t)return 0;if("number"==typeof e&&("loaded"!==i._state||i._playLock))return i._queue.push({event:"seek",action:function(){i.seek.apply(i,n)}}),i;var s=i._soundById(t);if(s){if(!("number"==typeof e&&e>=0)){if(i._webAudio){var a=i.playing(t)?v.ctx.currentTime-s._playStart:0,d=s._rateSeek?s._rateSeek-s._seek:0;return s._seek+(d+a*Math.abs(s._rate))}return s._node.currentTime}var l=i.playing(t);l&&i.pause(t,!0),s._seek=e,s._ended=!1,i._clearTimer(t),i._webAudio||!s._node||isNaN(s._node.duration)||(s._node.currentTime=e);var c=function(){l&&i.play(t,!0),i._emit("seek",t)};if(l&&!i._webAudio){var h=function(){i._playLock?setTimeout(h,0):c()};setTimeout(h,0)}else c()}return i},playing:function(e){var t=this;if("number"==typeof e){var i=t._soundById(e);return!!i&&!i._paused}for(var n=0;n=0&&v._howls.splice(n,1);var o=!0;for(i=0;i=0){o=!1;break}return S&&o&&delete S[e._src],v.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,i,n){var o=this["_on"+e];return"function"==typeof t&&o.push(n?{id:i,fn:t,once:n}:{id:i,fn:t}),this},off:function(e,t,i){var n=this,o=n["_on"+e],r=0;if("number"==typeof t&&(i=t,t=null),t||i)for(r=0;r=0;r--)o[r].id&&o[r].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,i)}.bind(n,o[r].fn),0),o[r].once&&n.off(e,o[r].fn,o[r].id));return n._loadQueue(e),n},_loadQueue:function(e){var t=this;if(t._queue.length>0){var i=t._queue[0];i.event===e&&(t._queue.shift(),t._loadQueue()),e||i.action()}return t},_ended:function(e){var t=this,i=e._sprite;if(!t._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;n--){if(i<=t)return;e._sounds[n]._ended&&(e._webAudio&&e._sounds[n]._node&&e._sounds[n]._node.disconnect(0),e._sounds.splice(n,1),i--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],i=0;i=0;if(!e.bufferSource)return this;if(v._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))try{e.bufferSource.buffer=v._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(v._navigator&&v._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var R=function(e){this._parent=e,this.init()};R.prototype={init:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++v._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,i=v._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=void 0===v.ctx.createGain?v.ctx.createGainNode():v.ctx.createGain(),e._node.gain.setValueAtTime(i,v.ctx.currentTime),e._node.paused=!0,e._node.connect(v.masterGain)):v.noAudio||(e._node=v._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(v._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=t._src,e._node.preload=!0===t._preload?"auto":t._preload,e._node.volume=i*v.volume(),e._node.load()),e},reset:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++v._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,t=e._parent;t._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(t._sprite).length&&(t._sprite={__default:[0,1e3*t._duration]}),"loaded"!==t._state&&(t._state="loaded",t._emit("load"),t._loadQueue()),e._node.removeEventListener(v._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var S={},E=function(e){var t=e._src;if(S[t])return e._duration=S[t].duration,void T(e);if(/^data:[^;]+;base64,/.test(t)){for(var i=atob(t.split(",")[1]),n=new Uint8Array(i.length),o=0;o0?(S[t._src]=e,T(t,e)):i()};"undefined"!=typeof Promise&&1===v.ctx.decodeAudioData.length?v.ctx.decodeAudioData(e).then(n).catch(i):v.ctx.decodeAudioData(e,n,i)},T=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},C=function(){if(v.usingWebAudio){try{"undefined"!=typeof AudioContext?v.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?v.ctx=new webkitAudioContext:v.usingWebAudio=!1}catch(e){v.usingWebAudio=!1}v.ctx||(v.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(v._navigator&&v._navigator.platform),t=v._navigator&&v._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),i=t?parseInt(t[1],10):null;if(e&&i&&i<9){var n=/safari/.test(v._navigator&&v._navigator.userAgent.toLowerCase());v._navigator&&!n&&(v.usingWebAudio=!1)}v.usingWebAudio&&(v.masterGain=void 0===v.ctx.createGain?v.ctx.createGainNode():v.ctx.createGain(),v.masterGain.gain.setValueAtTime(v._muted?0:v._volume,v.ctx.currentTime),v.masterGain.connect(v.ctx.destination)),v._setup()}};!function(e,t,i,n){var o;e.prototype._pos=[0,0,0],e.prototype._orientation=[0,0,-1,0,1,0],e.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var i=t._howls.length-1;i>=0;i--)t._howls[i].stereo(e);return t},e.prototype.pos=function(e,i,n){var o=this;return o.ctx&&o.ctx.listener?(i="number"!=typeof i?o._pos[1]:i,n="number"!=typeof n?o._pos[2]:n,"number"!=typeof e?o._pos:(o._pos=[e,i,n],void 0!==o.ctx.listener.positionX?(o.ctx.listener.positionX.setTargetAtTime(o._pos[0],t.ctx.currentTime,.1),o.ctx.listener.positionY.setTargetAtTime(o._pos[1],t.ctx.currentTime,.1),o.ctx.listener.positionZ.setTargetAtTime(o._pos[2],t.ctx.currentTime,.1)):o.ctx.listener.setPosition(o._pos[0],o._pos[1],o._pos[2]),o)):o},e.prototype.orientation=function(e,i,n,o,r,s){var a=this;if(!a.ctx||!a.ctx.listener)return a;var d=a._orientation;return i="number"!=typeof i?d[1]:i,n="number"!=typeof n?d[2]:n,o="number"!=typeof o?d[3]:o,r="number"!=typeof r?d[4]:r,s="number"!=typeof s?d[5]:s,"number"!=typeof e?d:(a._orientation=[e,i,n,o,r,s],void 0!==a.ctx.listener.forwardX?(a.ctx.listener.forwardX.setTargetAtTime(e,t.ctx.currentTime,.1),a.ctx.listener.forwardY.setTargetAtTime(i,t.ctx.currentTime,.1),a.ctx.listener.forwardZ.setTargetAtTime(n,t.ctx.currentTime,.1),a.ctx.listener.upX.setTargetAtTime(o,t.ctx.currentTime,.1),a.ctx.listener.upY.setTargetAtTime(r,t.ctx.currentTime,.1),a.ctx.listener.upZ.setTargetAtTime(s,t.ctx.currentTime,.1)):a.ctx.listener.setOrientation(e,i,n,o,r,s),a)},i.prototype.init=(o=i.prototype.init,function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],o.call(this,e)}),i.prototype.stereo=function(e,i){var n=this;if(!n._webAudio)return n;if("loaded"!==n._state)return n._queue.push({event:"stereo",action:function(){n.stereo(e,i)}}),n;var o=void 0===t.ctx.createStereoPanner?"spatial":"stereo";if(void 0===i){if("number"!=typeof e)return n._stereo;n._stereo=e,n._pos=[e,0,0]}for(var s=n._getSoundIds(i),a=0;a{console.warn(`Sound '${e}' playback failure: ${t}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.barcodeFillStyle="rgba(254,180,32,0.3)",this.barcodeStrokeStyle="rgba(254,180,32,0.9)",this.barcodeLineWidth=1,this._dce=null,this.dceConfig={},this.imgSource=null,this._maxCvsSideLength="iPhone"==i.OS||"Android"==i.OS?2048:4096,this._tempSolutionStatus="closed"}static get version(){return this._version}static get license(){return this._license}static set license(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`license`"+d);i._license=t})(w,e)}static get productKeys(){return this._license}static set productKeys(e){w.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){w.license=e}static get organizationID(){return this._license}static set organizationID(e){w.license=e}static set sessionPassword(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`sessionPassword`"+d);i._sessionPassword=t})(w,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:n,worker:o,getUserMedia:r,camera:await s(),browser:i.browser,version:i.version,OS:i.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(e){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");w._engineResourcePath=(e=>{if(null==e&&(e="./"),!t){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+d);i._licenseServer=h(t)})(w,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+d);i._deviceFriendlyName=t||""})(w,e)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(e){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");w.__bUseFullFeature=e}static isImageSource(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"getImage"in e}static isDSImage(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("width"in e&&("height"in e&&"pixelFormat"in e)))}static isCameraEnhancer(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("referenceConfigurationArray"in e&&("isOpen"in e&&("on"in e&&("off"in e&&("startFetchingLoop"in e&&("stopFetchingLoop"in e&&("getUIElement"in e&&("video"in e&&("isFetchingLoopStarted"in e&&("numberOfFramesInBuffer"in e&&("getFrameFromBuffer"in e&&("addScanRegionOverlayCanvas"in e&&("ifShowScanRegionLaser"in e&&("open"in e&&"close"in e))))))))))))))}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("region"in e&&("sx"in e&&("sy"in e&&("width"in e&&("height"in e&&("colorMode"in e&&("timeSpent"in e&&("timeStamp"in e&&("isCropped"in e&&("toCanvas"in e&&"_bUseWebGL"in e)))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(e){this._region=e,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var e;return null===(e=w._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",w.engineResourcePath)}static set defaultUIElementURL(e){w._defaultUIElementURL=e}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new A({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(e){this.bPlaySoundOnSuccessfulRead="never"!==e&&e}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(e){this.bVibrateOnSuccessfulRead="never"!==e&&e}set dce(e){this._dce=e}get dce(){return w.isCameraEnhancer(this._dce)?this._dce:null}set maxCvsSideLength(e){this._maxCvsSideLength=e,this.dceConfig.maxCvsSideLength=e}get maxCvsSideLength(){return this._maxCvsSideLength}updateDCEConfig(){if(!this.dce)return;w._onLog&&w._onLog("updateDCEConfig()"),this.dceConfig={bufferRefreshInterval:200,maxCvsSideLength:this._maxCvsSideLength};let e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);for(;-1!==e;)this.dce.referenceConfigurationArray.splice(e,1),e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);this.dce.referenceConfigurationArray.push(this.dceConfig),this.callbackCameraChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async e=>{let t=await this._decode_DCEFrame(e,{bCopyData:!1});await this.clearMapDecodeRecord();for(let e of t)delete e.bUnduplicated;if(this._drawResults(t),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan&&this.onImageRead(t),this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,e)},this.dce.on("cameraChange",this.callbackCameraChange),this.dce.on("resolutionChange",this.callbackResolutionChange),this.dce.on("cameraClose",this.callbackCameraClose),this.dce.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}releaseDCEConfig(){if(this.dce){if(w._onLog&&w._onLog("releaseDCEConfig()"),this.dce&&w.isCameraEnhancer(this.dce)){let e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);for(;-1!==e;)this.dce.referenceConfigurationArray.splice(e,1),e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);if(this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this.dce.stopFetchingLoop(),this.resultsOverlay){let e=this.dce._arrScanRegionOverlays.indexOf(this.resultsOverlay);for(;-1!==e;)this.dce._arrScanRegionOverlays.splice(e,1),e=this.dce._arrScanRegionOverlays.indexOf(this.resultsOverlay);this.resultsOverlay.remove(),this.resultsOverlay=null}}this.dce=null}}setImageSource(e){if(null==e)return this.imgSource=null,void this.releaseDCEConfig();if(w.isCameraEnhancer(e))this.dce=e,this.updateDCEConfig(),this.imgSource=null;else{if(!w.isImageSource(e))throw new Error("Invalid value.");this.releaseDCEConfig(),this.imgSource=e}}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:e,l:t,ls:n,sp:o,rmk:r}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,i,n=t._license||"",o=JSON.parse(JSON.stringify(t._licenseServer)),r=t._sessionPassword,s=0;if(n.startsWith("t")||n.startsWith("f"))s=0;else if(0===n.length||n.startsWith("P")||n.startsWith("L")||n.startsWith("Y")||n.startsWith("A"))s=1;else{s=2;const t=n.indexOf(":");if(-1!=t&&(n=n.substring(t+1)),n.startsWith("DLS2")){let t=n.substring(4);try{t=atob(t)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}const i=JSON.parse(t);if(n=i.handshakeCode?i.handshakeCode:i.organizationID?i.organizationID:"","number"==typeof n&&(n=JSON.stringify(n)),0===o.length){let e=[];i.mainServerURL&&(e[0]=i.mainServerURL),i.standbyServerURL&&(e[1]=i.standbyServerURL),o=h(e)}!r&&i.sessionPassword&&(r=i.sessionPassword),e=i.remark}("200001"===n||n.startsWith("200001-"))&&(o&&o.length||(n="")),n||(s=1)}if(s&&(globalThis.crypto||(i="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(i="Require https to use online key in this browser.")),i){if(1!==s)throw new Error(i);s=0,console.warn(i),t._lastErrorCode=-1,t._lastErrorString=i}return 1===s&&(n="",console.warn("Applying for a public trial license ...")),{lt:s,l:n,ls:o,sp:r,rmk:e}}throw new Error("Can't preprocess license again"+d)})(w);this._pLoad.task=async(s,a)=>{let d=w.engineResourcePath+w._workerName;w.engineResourcePath.startsWith(location.origin)||(d=await fetch(d).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),w._dbrWorker=new Worker(d),w._dbrWorker.onerror=e=>{let t=new Error(e.message);a(t)},w._dbrWorker.onmessage=async t=>{let i=t.data?t.data:t;switch(i.type){case"log":w._onLog&&w._onLog(i.message);break;case"load":{i.message&&(i.message=i.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,n=!1;1===e&&(n=!0),i.success?(w._dbrWorker.onerror=null,w._version=i.version+"(JS "+w._jsVersion+"."+w._jsEditVersion+")",w._onLog&&w._onLog("load dbr worker success"),i.message&&console.warn(i.message)):(t=new Error(i.message),t.stack=i.stack+"\n"+t.stack,n||111==i.ltsErrorCode&&-1!=i.message.toLowerCase().indexOf("trial license")&&(n=!0)),n&&w.showDialog(i.success?"warn":"error",i.message),i.success?s():a(t);break}case"task":{let e=i.id,t=i.body;try{w._taskCallbackMap.get(e)(t),w._taskCallbackMap.delete(e)}catch(t){throw w._taskCallbackMap.delete(e),t}break}default:w._onLog&&w._onLog(t)}},w._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:w.engineResourcePath,bUseFullFeature:w._bUseFullFeature,bd:w._bWasmDebug,v:w._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:i,fn:w.deviceFriendlyName,ls:n,sp:o,rmk:r})}}await this._pLoad}static async showDialog(e,t){if(!w._bNeverShowDialog)try{let i=await fetch(w.engineResourcePath+"dls.license.dialog.html");if(!i.ok)throw Error("Get license dialog fail. Network Error: "+i.statusText);let n=await i.text();if(!n.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let o=document.createElement("div");o.innerHTML=n;let r=[];for(let e=0;e{if(i==e.target){s.remove();for(let e of r)e.remove()}}));else if(!d&&i.classList.contains("dls-license-icon-close"))d=i,i.addEventListener("click",(()=>{s.remove();for(let e of r)e.remove()}));else if(!l&&i.classList.contains("dls-license-icon-error"))l=i,"error"!=e&&i.remove();else if(!c&&i.classList.contains("dls-license-icon-warn"))c=i,"warn"!=e&&i.remove();else if(!h&&i.classList.contains("dls-license-msg-content")){h=i;let e=t;for(;e;){let t=e.indexOf("["),n=e.indexOf("]",t),o=e.indexOf("(",n),r=e.indexOf(")",o);if(-1==t||-1==n||-1==o||-1==r){i.appendChild(new Text(e));break}t>0&&i.appendChild(new Text(e.substring(0,t)));let s=document.createElement("a"),a=e.substring(t+1,n);s.innerText=a;let d=e.substring(o+1,r);s.setAttribute("href",d),s.setAttribute("target","_blank"),i.appendChild(s),e=e.substring(r+1)}}document.body.appendChild(s)}catch(e){w._onLog&&w._onLog(e.message||e)}}static async createInstanceInWorker(e=!1){return await w.loadWasm(),await new Promise(((t,i)=>{let n=w._nextTaskID++;w._taskCallbackMap.set(n,(e=>{if(e.success)return t(e.instanceID);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),w._dbrWorker.postMessage({type:"createInstance",id:n,bScanner:e})}))}static async createInstance(){let e=new w;return e._instanceID=await w.createInstanceInWorker(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let i=w._nextTaskID++;w._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),w._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:i,instanceID:this._instanceID})}))}async decode(e){w._onLog&&w._onLog("decode(source: any)"),w._onLog&&(this._timeStartDecode=Date.now());{let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),e instanceof Blob?await this._decode_Blob(e,t):e instanceof ArrayBuffer?await this._decode_ArrayBuffer(e,t):e instanceof Uint8Array||e instanceof Uint8ClampedArray?await this._decode_Uint8Array(e,t):e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?await this._decode_Image(e,t):e instanceof HTMLCanvasElement?await this._decode_Canvas(e,t):e instanceof HTMLVideoElement?await this._decode_Video(e,t):"string"==typeof e?"data:image/"==e.substring(0,11)?await this._decode_Base64(e,t):await this._decode_Url(e,t):w.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):w.isDSImage(e)?(t.bCopyData=!0,await this._decode_DSImage(e,t)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(e,t)}async decodeUrl(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(e,t)}async _decodeBuffer_Uint8Array(e,t,i,n,o,r){return await new Promise(((s,a)=>{let d=w._nextTaskID++;w._taskCallbackMap.set(d,(e=>{if(e.success){let t,i=w._onLog?Date.now():0;w._onLog&&w._onLog("worker return result: "+i),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return a(e)}if(w._onLog){let e=Date.now();w._onLog("DBR time get result: "+i),w._onLog("Handle image cost: "+(this._timeEnterInnerDBR-this._timeStartDecode)),w._onLog("DBR worker decode image cost: "+(i-this._timeEnterInnerDBR)),w._onLog("DBR worker handle results: "+(e-i)),w._onLog("Total decode image cost: "+(e-this._timeStartDecode))}return s(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}})),this._timeEnterInnerDBR=Date.now(),w._onLog&&w._onLog("Send buffer to worker:"+this._timeEnterInnerDBR),w._dbrWorker.postMessage({type:"decodeBuffer",id:d,instanceID:this._instanceID,body:{buffer:e,width:t,height:i,stride:n,format:o,config:r}},[e.buffer]),w._onLog&&r&&r.timeStamp&&w._onLog("decode image delay: "+(this._timeEnterInnerDBR-r.timeStamp))}))}async _decodeBuffer_Blob(e,t,i,n,o,r){w._onLog&&w._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const s=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,i)=>{let n=new FileReader;n.readAsArrayBuffer(e),n.onload=()=>{t(n.result)},n.onerror=()=>{i(n.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(s),t,i,n,o,r)}async decodeBuffer(e,t,i,n,o,r){let s;return w._onLog&&w._onLog("decodeBuffer(buffer,width,height,stride,format)"),w._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?s=await this._decodeBuffer_Uint8Array(e,t,i,n,o,r):e instanceof ArrayBuffer?s=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,i,n,o,r):e instanceof Blob&&(s=await this._decodeBuffer_Blob(e,t,i,n,o,r)),s}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,i)=>{let n=w._nextTaskID++;w._taskCallbackMap.set(n,(e=>{if(e.success){let n;this._lastInnerDecodeDuration=e.duration;try{n=this._handleRetJsonString(e.decodeReturn)}catch(e){return i(e)}return t(n)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),w._dbrWorker.postMessage({type:"decodeFileInMemory",id:n,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let i=w._nextTaskID++;w._taskCallbackMap.set(i,(i=>{if(i.success){let t=JSON.parse(i.results);return null!=this.userDefinedRegion&&(t.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),e(t)}{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),w._dbrWorker.postMessage({type:"getRuntimeSettings",id:i,instanceID:this._instanceID})}))}async updateRuntimeSettings(t){let i;if("string"==typeof t)if("speed"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region,i.deblurLevel=3,i.expectedBarcodesCount=0,i.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region,i.deblurLevel=5,i.expectedBarcodesCount=512,i.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region}else i=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(i=JSON.parse(JSON.stringify(t)),i.region instanceof Array){let e=i.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(i.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!w._bUseFullFeature){if(0!=(i.barcodeFormatIds&~(e.EnumBarcodeFormat.BF_ONED|e.EnumBarcodeFormat.BF_QR_CODE|e.EnumBarcodeFormat.BF_PDF417|e.EnumBarcodeFormat.BF_DATAMATRIX))||0!=i.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=i.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let e=i.region;if(e instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(e)),(e.regionLeft||e.regionTop||e.regionRight||e.regionBottom||e.regionMeasuredByPercentage)&&(e.regionLeft||e.regionTop||100!=e.regionRight||100!=e.regionBottom||!e.regionMeasuredByPercentage)?this.region=e:this.region=null,i.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return await new Promise(((e,t)=>{let n=w._nextTaskID++;w._taskCallbackMap.set(n,(i=>{if(i.success){try{this._handleRetJsonString(i.updateReturn)}catch(e){t(e)}return e()}{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),w._dbrWorker.postMessage({type:"updateRuntimeSettings",id:n,instanceID:this._instanceID,body:{settings:JSON.stringify(i)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,await new Promise(((e,t)=>{let i=w._nextTaskID++;w._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),w._dbrWorker.postMessage({type:"resetRuntimeSettings",id:i,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!w._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((e,t)=>{let i=w._nextTaskID++;w._taskCallbackMap.set(i,(i=>{if(i.success)return e(i.results);{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),w._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:i,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!w._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof e)e=e;else{if("object"!=typeof e)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");e=JSON.stringify(e)}return await new Promise(((t,i)=>{let n=w._nextTaskID++;w._taskCallbackMap.set(n,(e=>{if(e.success){try{this._handleRetJsonString(e.initReturn)}catch(e){i(e)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),w._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:n,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){w._onLog&&w._onLog("_decode_Blob(blob: Blob)");let i=null,n=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(e)}catch(e){}i||(n=await function(e){return new Promise(((t,i)=>{let n=URL.createObjectURL(e),o=new Image;o.dbrObjUrl=n,o.src=n,o.onload=()=>{t(o)},o.onerror=e=>{i(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let o=await this._decode_Image(i||n,t);return i&&i.close(),o}async _decode_ArrayBuffer(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Uint8Array(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Image(e,t){w._onLog&&w._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),t=t||{};let i,n,o=e instanceof HTMLImageElement?e.naturalWidth:e.width,r=e instanceof HTMLImageElement?e.naturalHeight:e.height,s=Math.max(o,r);if(s>this._maxCvsSideLength){let e=this._maxCvsSideLength/s;i=Math.round(o*e),n=Math.round(r*e)}else i=o,n=r;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d"));return a.ctx2d.drawImage(e,0,0,o,r,0,0,i,n),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._decode_Canvas(a,t)}async _decode_Canvas(t,i){if(w._onLog&&w._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if(0===t.width||0===t.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=t,this.oriCanvasData=null);let n=(t.ctx2d||t.getContext("2d")).getImageData(0,0,t.width,t.height).data;return await this._decodeBuffer_Uint8Array(n,t.width,t.height,4*t.width,e.EnumImagePixelFormat.IPF_ABGR_8888,i)}async _decode_Video(e,t){if(w._onLog&&w._onLog("_decode_Video(video)"),!(e instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";t=t||{};let i,n,o=e.videoWidth,r=e.videoHeight,s=Math.max(o,r);if(s>this._maxCvsSideLength){let e=this._maxCvsSideLength/s;i=Math.round(o*e),n=Math.round(r*e)}else i=o,n=r;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d"));return a.ctx2d.drawImage(e,0,0,o,r,0,0,i,n),await this._decode_Canvas(a,t)}async _decode_DCEFrame(t,i){if(w._onLog&&w._onLog("_decode_DCEFrame(dceFrame)"),!w.isDCEFrame(t))return null;let n;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{width:o,height:r,colorMode:s,timeStamp:a}=t;let d;d=i&&i.bCopyData?new Uint8Array(t.data):t.data;let l=null;if(i?(l=JSON.parse(JSON.stringify(i)),l.timeStamp=a):l={timeStamp:a},"grey"===s)n=await this._decodeBuffer_Uint8Array(d,o,r,o,e.EnumImagePixelFormat.IPF_GrayScaled,l);else if("rgba"===s)n=await this._decodeBuffer_Uint8Array(d,o,r,4*o,e.EnumImagePixelFormat.IPF_ABGR_8888,l);else{if("bgra"!==s)throw new Error(`Color mode '${s}' is not supported to decode.`);n=await this._decodeBuffer_Uint8Array(d,o,r,4*o,e.EnumImagePixelFormat.IPF_ARGB_8888,l)}return n}async _decode_DSImage(t,i){if(w._onLog&&w._onLog("_decode_DSImage(dsImage)"),!w.isDSImage(t))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat.toLowerCase(),data:new Uint8Array(t.data),toCanvas:function(){const e=document.createElement("canvas");let t;switch(e.width=this.width,e.height=this.height,this.pixelFormat){case"grey":t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{let n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="blob",n.send(),n.onloadend=async()=>{t(n.response)},n.onerror=()=>{i(new Error("Network Error: "+n.statusText))}}));return await this._decode_Blob(i,t)}}async _decode_FilePath(e,t){throw w._onLog&&w._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static fixResultLocationWhenFilterRegionInJs(e,t,i,n,o,r,s,a){if(e&&t.length>0)for(let e of t){let t=e.localizationResult;2==t.resultCoordinateType&&(t.x1*=.01*s,t.x2*=.01*s,t.x3*=.01*s,t.x4*=.01*s,t.y1*=.01*a,t.y2*=.01*a,t.y3*=.01*a,t.y4*=.01*a);let d=s/o,l=a/r;t.x1=t.x1/d+i,t.x2=t.x2/d+i,t.x3=t.x3/d+i,t.x4=t.x4/d+i,t.y1=t.y1/l+n,t.y2=t.y2/l+n,t.y3=t.y3/l+n,t.y4=t.y4/l+n,2==t.resultCoordinateType&&(t.x1*=100/o,t.x2*=100/o,t.x3*=100/o,t.x4*=100/o,t.y1*=100/r,t.y2*=100/r,t.y3*=100/r,t.y4*=100/r)}}static BarcodeReaderException(t,i){let n,o=e.EnumErrorCode.DBR_UNKNOWN;return"number"==typeof t?(o=t,n=new Error(i)):n=new Error(t),n.code=o,n}_handleRetJsonString(t){let i=e.EnumErrorCode;if(t.textResults){for(let e=0;e{let i=t.indexOf(":");e[t.substring(0,i)]=t.substring(i+1)})),i.exception=e}}return t.decodeRecords?this.decodeRecords=t.decodeRecords:this.decodeRecords={},this._lastErrorCode=t.exception,this._lastErrorString=t.description,t.exception&&!w._setWarnnedEx.has(t.description)&&(w._setWarnnedEx.add(t.description),console.warn(t.description)),t.textResults}if(t.exception==i.DBR_SUCCESS)return t.data;throw w.BarcodeReaderException(t.exception,t.description)}async setModeArgument(e,t,i,n){return await new Promise(((o,r)=>{let s=w._nextTaskID++;w._taskCallbackMap.set(s,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return r(e)}return o()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,r(t)}})),w._dbrWorker.postMessage({type:"setModeArgument",id:s,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i,argumentValue:n}})}))}async getModeArgument(e,t,i){return await new Promise(((n,o)=>{let r=w._nextTaskID++;w._taskCallbackMap.set(r,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return o(e)}return n(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,o(t)}})),w._dbrWorker.postMessage({type:"getModeArgument",id:r,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i}})}))}async getIntermediateResults(){return await new Promise(((e,t)=>{let i=w._nextTaskID++;w._taskCallbackMap.set(i,(i=>{if(i.success)return e(i.results);{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),w._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let t=await this.getIntermediateResults(),i=[];for(let n of t)if(n.dataType==e.EnumIMResultDataType.IMRDT_IMAGE)for(let t of n.results){const n=t.bytes;let o;switch(w._onLog&&w._onLog(" "+n.length+" "+n.byteLength+" "+t.width+" "+t.height+" "+t.stride+" "+t.format),t.format){case e.EnumImagePixelFormat.IPF_ABGR_8888:o=new Uint8ClampedArray(n);break;case e.EnumImagePixelFormat.IPF_RGB_888:{const e=n.length/3;o=new Uint8ClampedArray(4*e);for(let t=0;t{let i=w._nextTaskID++;w._taskCallbackMap.set(i,(i=>{if(i.success){let t=i.results;return t.intervalTime=this.intervalTime,t.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,t.soundOnSuccessfullRead=this.soundSource,t.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,t.vibrateDuration=this.vibrateDuration,e(t)}{let e=new Error(i.message);return e.stack+="\n"+i.stack,t(e)}})),w._dbrWorker.postMessage({type:"getScanSettings",id:i,instanceID:this._instanceID})}))}async updateScanSettings(e){if(!e)return;const t=JSON.parse(JSON.stringify(e));return t.hasOwnProperty("intervalTime")&&(this.intervalTime=t.intervalTime,delete t.intervalTime),t.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=t.whenToPlaySoundforSuccessfulRead,delete t.whenToPlaySoundforSuccessfulRead),t.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=t.soundOnSuccessfullRead,delete t.soundOnSuccessfullRead),t.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=t.whenToVibrateforSuccessfulRead,delete t.whenToVibrateforSuccessfulRead),t.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=t.vibrateDuration,delete t.vibrateDuration),await new Promise(((e,i)=>{let n=w._nextTaskID++;w._taskCallbackMap.set(n,(t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack+="\n"+t.stack,i(e)}})),w._dbrWorker.postMessage({type:"updateScanSettings",id:n,instanceID:this._instanceID,body:{settings:t}})}))}_cloneDecodeResults(e){if(e instanceof Array){let t=[];for(let i of e)t.push(this._cloneDecodeResults(i));return t}{let t=e;return JSON.parse(JSON.stringify(t,((e,t)=>"oriVideoCanvas"==e||"searchRegionCanvas"==e?void 0:t)))}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this.imgSource||this._bPauseScan)return w._onLog&&w._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));w._onLog&&w._onLog("======= once read ======="),w._onLog&&(this._timeStartDecode=Date.now());let e=null,t=null;if(this.dce)e=this._getVideoFrame();else if(this.imgSource&&(t=await this.imgSource.getImage(),!w.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let i=null;return e?i=await this._decode_DCEFrame(e,{bScanner:!0,bCopyData:!1}):t&&(i=await this._decode_DSImage(t,{bScanner:!0,bCopyData:!1})),i})().then((e=>{if(w._onLog&&w._onLog(e),this.dce){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost;this._indexCurrentDecodingFrame;const i=()=>{let i=0;if(t&&t.length){let n=Math.min(...e),o=Math.max(...t);n&&o&&(i=n-o)}else i=0;return i>0?i:0};(()=>{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=i()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this.imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead)t=!0;else if("unique"===this.bPlaySoundOnSuccessfulRead)for(let i of e)if(i.bUnduplicated){t=!0;break}t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead)t=!0;else if("unique"===this.bVibrateOnSuccessfulRead)for(let i of e)if(i.bUnduplicated){t=!0;break}if(t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onImageRead){let t=this._cloneDecodeResults(e);for(let e of t)delete e.bUnduplicated;this.onImageRead(t)}if(this.onUniqueRead)for(let t of e)t.bUnduplicated&&this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t));this._drawResults(e)}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce&&this.dce.stopFetchingLoop(),w._onLog&&w._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e=this.dce.isFetchingLoopStarted();if(this.dceConfig.loopInterval=this._intervalGetVideoFrame,e||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dceConfig.loopInterval=0,null;const t=this.dce.getFrameFromBuffer();return(e=>{if(!e)return;let t=e.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(t)})(t),t}_drawResults(e){if(!this.dce||this._bPauseScan)return;if(!this.resultsOverlay){if(!this.dce.isOpen())return;this.resultsOverlay=this.dce.addScanRegionOverlayCanvas()}const t=this.resultsOverlay.getContext("2d");if(t.clearRect(0,0,this.resultsOverlay.width,this.resultsOverlay.height),e){t.globalCompositeOperation="destination-over",t.fillStyle=this.barcodeFillStyle,t.strokeStyle=this.barcodeStrokeStyle,t.lineWidth=this.barcodeLineWidth;for(let i of e){let e=i.localizationResult;t.beginPath(),t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineTo(e.x3,e.y3),t.lineTo(e.x4,e.y4),t.fill(),t.beginPath(),t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineTo(e.x3,e.y3),t.lineTo(e.x4,e.y4),t.closePath(),t.stroke()}}}async startScanning(e){if(!this.dce&&!this.imgSource)throw new Error("'imageSource' is not set. call 'setImageSource()' before 'startScanning()'.");if("closed"!=this._tempSolutionStatus)return;if(this._tempSolutionStatus="opening","opening"!=this._tempSolutionStatus)return;let t=null;return this.dce&&!this.dce.isOpen()&&(this.dce.ifShowScanRegionLaser=!0,t=await this.dce.open(e)),"opening"==this._tempSolutionStatus?(this._bPauseScan=!1,this.dce&&this.dce.singleFrameMode||this._loopReadVideo(),this._tempSolutionStatus="opened",this.keepAlive(),t):void 0}stopScanning(e){this.dce&&(this._drawResults(null),this.dce.ifShowScanRegionLaser=!1,this.dce.close(e)),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._tempSolutionStatus="closed"}pauseScanning(){if(this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.ifShowScanRegionLaser=!1,this.dce.stopFetchingLoop()}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.ifShowScanRegionLaser=!0}}destroyContext(){if(w._onLog&&w._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,(this.dce||"opening"===this._tempSolutionStatus)&&this.stopScanning(),this.setImageSource(null);let e=w._nextTaskID++;w._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),w._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}} +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).Dynamsoft=e.Dynamsoft||{},e.Dynamsoft.DBR={}))}(this,(function(e){"use strict";const t="undefined"==typeof self;let i,r,n,o,s;if("undefined"!=typeof navigator&&(i=navigator,r=i.userAgent,n=i.platform,o=i.mediaDevices),!t){const e={init:function(){this.browser=this.searchString(this.dataBrowser)||"unknownBrowser",this.version=this.searchVersion(r)||this.searchVersion(i.appVersion)||0,this.OS=this.searchString(this.dataOS)||"unknownOS","Linux"==this.OS&&-1!=r.indexOf("Windows NT")&&(this.OS="HarmonyOS")},searchString:function(e){for(let t=0;t{let e=!1;if(h)try{(await o.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===s.browser&&s.version>66||"Safari"===s.browser&&s.version>13||"OPR"===s.browser&&s.version>43||"Edge"===s.browser&&s.version;const u=(()=>{if(!t&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),d=" is not allowed to change after `createInstance` or `loadWasm` is called.",f=!t&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",g=!t&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",_=e=>{if(null==e)e=[];else{e=e instanceof Array?[...e]:[e];for(let i=0;ie&&"object"==typeof e&&"function"==typeof e.then;var b=function(){this.init()};b.prototype={init:function(){var e=this||C;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var t=this||C;if(e=parseFloat(e),t.ctx||R(),void 0!==e&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,C.ctx.currentTime);for(var i=0;i=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,R()),e},codecs:function(e){return(this||C)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||C;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||C,t=null;try{t="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!t||"function"!=typeof t.canPlayType)return e;var i=t.canPlayType("audio/mpeg;").replace(/^no$/,""),r=e._navigator?e._navigator.userAgent:"",n=r.match(/OPR\/([0-6].)/g),o=n&&parseInt(n[0].split("/")[1],10)<33,s=-1!==r.indexOf("Safari")&&-1===r.indexOf("Chrome"),a=r.match(/Version\/(.*?) /),l=s&&a&&parseInt(a[1],10)<15;return e._codecs={mp3:!(o||!i&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!i,opus:!!t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(t.canPlayType('audio/wav; codecs="1"')||t.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!t.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!t.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/m4a;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(t.canPlayType("audio/x-m4b;")||t.canPlayType("audio/m4b;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(t.canPlayType("audio/x-mp4;")||t.canPlayType("audio/mp4;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(l||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(l||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!t.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(t.canPlayType("audio/x-flac;")||t.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||C;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var t=function(i){for(;e._html5AudioPool.length0?s._seek:i._sprite[e][0]/1e3),h=Math.max(0,(i._sprite[e][0]+i._sprite[e][1])/1e3-l),c=1e3*h/Math.abs(s._rate),u=i._sprite[e][0]/1e3,d=(i._sprite[e][0]+i._sprite[e][1])/1e3;s._sprite=e,s._ended=!1;var f=function(){s._paused=!1,s._seek=l,s._start=u,s._stop=d,s._loop=!(!s._loop&&!i._sprite[e][2])};if(!(l>=d)){var g=s._node;if(i._webAudio){var _=function(){i._playLock=!1,f(),i._refreshBuffer(s);var e=s._muted||i._muted?0:s._volume;g.gain.setValueAtTime(e,C.ctx.currentTime),s._playStart=C.ctx.currentTime,void 0===g.bufferSource.start?s._loop?g.bufferSource.noteGrainOn(0,l,86400):g.bufferSource.noteGrainOn(0,l,h):s._loop?g.bufferSource.start(0,l,86400):g.bufferSource.start(0,l,h),c!==1/0&&(i._endTimers[s._id]=setTimeout(i._ended.bind(i,s),c)),t||setTimeout((function(){i._emit("play",s._id),i._loadQueue()}),0)};"running"===C.state&&"interrupted"!==C.ctx.state?_():(i._playLock=!0,i.once("resume",_),i._clearTimer(s._id))}else{var p=function(){g.currentTime=l,g.muted=s._muted||i._muted||C._muted||g.muted,g.volume=s._volume*C.volume(),g.playbackRate=s._rate;try{var r=g.play();if(r&&"undefined"!=typeof Promise&&(r instanceof Promise||"function"==typeof r.then)?(i._playLock=!0,f(),r.then((function(){i._playLock=!1,g._unlocked=!0,t?i._loadQueue():i._emit("play",s._id)})).catch((function(){i._playLock=!1,i._emit("playerror",s._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),s._ended=!0,s._paused=!0}))):t||(i._playLock=!1,f(),i._emit("play",s._id)),g.playbackRate=s._rate,g.paused)return void i._emit("playerror",s._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||s._loop?i._endTimers[s._id]=setTimeout(i._ended.bind(i,s),c):(i._endTimers[s._id]=function(){i._ended(s),g.removeEventListener("ended",i._endTimers[s._id],!1)},g.addEventListener("ended",i._endTimers[s._id],!1))}catch(e){i._emit("playerror",s._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===g.src&&(g.src=i._src,g.load());var m=window&&window.ejecta||!g.readyState&&C._navigator.isCocoonJS;if(g.readyState>=3||m)p();else{i._playLock=!0,i._state="loading";var v=function(){i._state="loaded",p(),g.removeEventListener(C._canPlayEvent,v,!1)};g.addEventListener(C._canPlayEvent,v,!1),i._clearTimer(s._id)}}return s._id}i._ended(s)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var i=t._getSoundIds(e),r=0;r=0?t=parseInt(n[0],10):e=parseFloat(n[0])}else n.length>=2&&(e=parseFloat(n[0]),t=parseInt(n[1],10));if(!(void 0!==e&&e>=0&&e<=1))return(i=t?r._soundById(t):r._sounds[0])?i._volume:0;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"volume",action:function(){r.volume.apply(r,n)}}),r;void 0===t&&(r._volume=e),t=r._getSoundIds(t);for(var a=0;a0?r/h:r),u=Date.now();e._fadeTo=i,e._interval=setInterval((function(){var n=(Date.now()-u)/r;u=Date.now(),a+=l*n,a=Math.round(100*a)/100,a=l<0?Math.max(i,a):Math.min(i,a),s._webAudio?e._volume=a:s.volume(a,e._id,!0),o&&(s._volume=a),(it&&a>=i)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,s.volume(i,e._id),s._emit("fade",e._id))}),c)},_stopFade:function(e){var t=this,i=t._soundById(e);return i&&i._interval&&(t._webAudio&&i._node.gain.cancelScheduledValues(C.ctx.currentTime),clearInterval(i._interval),i._interval=null,t.volume(i._fadeTo,e),i._fadeTo=null,t._emit("fade",e)),t},loop:function(){var e,t,i,r=this,n=arguments;if(0===n.length)return r._loop;if(1===n.length){if("boolean"!=typeof n[0])return!!(i=r._soundById(parseInt(n[0],10)))&&i._loop;e=n[0],r._loop=e}else 2===n.length&&(e=n[0],t=parseInt(n[1],10));for(var o=r._getSoundIds(t),s=0;s=0?t=parseInt(n[0],10):e=parseFloat(n[0])}else 2===n.length&&(e=parseFloat(n[0]),t=parseInt(n[1],10));if("number"!=typeof e)return(i=r._soundById(t))?i._rate:r._rate;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"rate",action:function(){r.rate.apply(r,n)}}),r;void 0===t&&(r._rate=e),t=r._getSoundIds(t);for(var a=0;a=0?t=parseInt(r[0],10):i._sounds.length&&(t=i._sounds[0]._id,e=parseFloat(r[0]))}else 2===r.length&&(e=parseFloat(r[0]),t=parseInt(r[1],10));if(void 0===t)return 0;if("number"==typeof e&&("loaded"!==i._state||i._playLock))return i._queue.push({event:"seek",action:function(){i.seek.apply(i,r)}}),i;var s=i._soundById(t);if(s){if(!("number"==typeof e&&e>=0)){if(i._webAudio){var a=i.playing(t)?C.ctx.currentTime-s._playStart:0,l=s._rateSeek?s._rateSeek-s._seek:0;return s._seek+(l+a*Math.abs(s._rate))}return s._node.currentTime}var h=i.playing(t);h&&i.pause(t,!0),s._seek=e,s._ended=!1,i._clearTimer(t),i._webAudio||!s._node||isNaN(s._node.duration)||(s._node.currentTime=e);var c=function(){h&&i.play(t,!0),i._emit("seek",t)};if(h&&!i._webAudio){var u=function(){i._playLock?setTimeout(u,0):c()};setTimeout(u,0)}else c()}return i},playing:function(e){var t=this;if("number"==typeof e){var i=t._soundById(e);return!!i&&!i._paused}for(var r=0;r=0&&C._howls.splice(r,1);var n=!0;for(i=0;i=0){n=!1;break}return x&&n&&delete x[e._src],C.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,i,r){var n=this["_on"+e];return"function"==typeof t&&n.push(r?{id:i,fn:t,once:r}:{id:i,fn:t}),this},off:function(e,t,i){var r=this,n=r["_on"+e],o=0;if("number"==typeof t&&(i=t,t=null),t||i)for(o=0;o=0;o--)n[o].id&&n[o].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,i)}.bind(r,n[o].fn),0),n[o].once&&r.off(e,n[o].fn,n[o].id));return r._loadQueue(e),r},_loadQueue:function(e){var t=this;if(t._queue.length>0){var i=t._queue[0];i.event===e&&(t._queue.shift(),t._loadQueue()),e||i.action()}return t},_ended:function(e){var t=this,i=e._sprite;if(!t._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;r--){if(i<=t)return;e._sounds[r]._ended&&(e._webAudio&&e._sounds[r]._node&&e._sounds[r]._node.disconnect(0),e._sounds.splice(r,1),i--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],i=0;i=0;if(!e.bufferSource)return this;if(C._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))try{e.bufferSource.buffer=C._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(C._navigator&&C._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var T=function(e){this._parent=e,this.init()};T.prototype={init:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++C._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,i=C._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=void 0===C.ctx.createGain?C.ctx.createGainNode():C.ctx.createGain(),e._node.gain.setValueAtTime(i,C.ctx.currentTime),e._node.paused=!0,e._node.connect(C.masterGain)):C.noAudio||(e._node=C._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(C._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=t._src,e._node.preload=!0===t._preload?"auto":t._preload,e._node.volume=i*C.volume(),e._node.load()),e},reset:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++C._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,t=e._parent;t._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(t._sprite).length&&(t._sprite={__default:[0,1e3*t._duration]}),"loaded"!==t._state&&(t._state="loaded",t._emit("load"),t._loadQueue()),e._node.removeEventListener(C._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var x={},E=function(e){var t=e._src;if(x[t])return e._duration=x[t].duration,void O(e);if(/^data:[^;]+;base64,/.test(t)){for(var i=atob(t.split(",")[1]),r=new Uint8Array(i.length),n=0;n0?(x[t._src]=e,O(t,e)):i()};"undefined"!=typeof Promise&&1===C.ctx.decodeAudioData.length?C.ctx.decodeAudioData(e).then(r).catch(i):C.ctx.decodeAudioData(e,r,i)},O=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},R=function(){if(C.usingWebAudio){try{"undefined"!=typeof AudioContext?C.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?C.ctx=new webkitAudioContext:C.usingWebAudio=!1}catch(e){C.usingWebAudio=!1}C.ctx||(C.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(C._navigator&&C._navigator.platform),t=C._navigator&&C._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),i=t?parseInt(t[1],10):null;if(e&&i&&i<9){var r=/safari/.test(C._navigator&&C._navigator.userAgent.toLowerCase());C._navigator&&!r&&(C.usingWebAudio=!1)}C.usingWebAudio&&(C.masterGain=void 0===C.ctx.createGain?C.ctx.createGainNode():C.ctx.createGain(),C.masterGain.gain.setValueAtTime(C._muted?0:C._volume,C.ctx.currentTime),C.masterGain.connect(C.ctx.destination)),C._setup()}};!function(e,t,i,r){var n;e.prototype._pos=[0,0,0],e.prototype._orientation=[0,0,-1,0,1,0],e.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var i=t._howls.length-1;i>=0;i--)t._howls[i].stereo(e);return t},e.prototype.pos=function(e,i,r){var n=this;return n.ctx&&n.ctx.listener?(i="number"!=typeof i?n._pos[1]:i,r="number"!=typeof r?n._pos[2]:r,"number"!=typeof e?n._pos:(n._pos=[e,i,r],void 0!==n.ctx.listener.positionX?(n.ctx.listener.positionX.setTargetAtTime(n._pos[0],t.ctx.currentTime,.1),n.ctx.listener.positionY.setTargetAtTime(n._pos[1],t.ctx.currentTime,.1),n.ctx.listener.positionZ.setTargetAtTime(n._pos[2],t.ctx.currentTime,.1)):n.ctx.listener.setPosition(n._pos[0],n._pos[1],n._pos[2]),n)):n},e.prototype.orientation=function(e,i,r,n,o,s){var a=this;if(!a.ctx||!a.ctx.listener)return a;var l=a._orientation;return i="number"!=typeof i?l[1]:i,r="number"!=typeof r?l[2]:r,n="number"!=typeof n?l[3]:n,o="number"!=typeof o?l[4]:o,s="number"!=typeof s?l[5]:s,"number"!=typeof e?l:(a._orientation=[e,i,r,n,o,s],void 0!==a.ctx.listener.forwardX?(a.ctx.listener.forwardX.setTargetAtTime(e,t.ctx.currentTime,.1),a.ctx.listener.forwardY.setTargetAtTime(i,t.ctx.currentTime,.1),a.ctx.listener.forwardZ.setTargetAtTime(r,t.ctx.currentTime,.1),a.ctx.listener.upX.setTargetAtTime(n,t.ctx.currentTime,.1),a.ctx.listener.upY.setTargetAtTime(o,t.ctx.currentTime,.1),a.ctx.listener.upZ.setTargetAtTime(s,t.ctx.currentTime,.1)):a.ctx.listener.setOrientation(e,i,r,n,o,s),a)},i.prototype.init=(n=i.prototype.init,function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],n.call(this,e)}),i.prototype.stereo=function(e,i){var r=this;if(!r._webAudio)return r;if("loaded"!==r._state)return r._queue.push({event:"stereo",action:function(){r.stereo(e,i)}}),r;var n=void 0===t.ctx.createStereoPanner?"spatial":"stereo";if(void 0===i){if("number"!=typeof e)return r._stereo;r._stereo=e,r._pos=[e,0,0]}for(var s=r._getSoundIds(i),a=0;a{console.warn(`Sound '${e}' playback failure: ${t}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.captureAndDecodeInParallel=!0,this.barcodeFillStyle="rgba(254,180,32,0.3)",this.barcodeStrokeStyle="rgba(254,180,32,0.9)",this.barcodeLineWidth=1,this._dce=null,this._imgSource=null,this._maxCvsSideLength=D,this._tempSolutionStatus="closed"}static get version(){return this._version}static get license(){return this._license}static set license(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`license`"+d);i._license=t})(M,e)}static get productKeys(){return this._license}static set productKeys(e){M.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){M.license=e}static get organizationID(){return this._license}static set organizationID(e){M.license=e}static set sessionPassword(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`sessionPassword`"+d);i._sessionPassword=t})(M,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:a,worker:l,getUserMedia:h,camera:await c(),browser:s.browser,version:s.version,OS:s.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(e){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");M._engineResourcePath=(e=>{if(null==e&&(e="./"),!t){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+d);i._licenseServer=_(t)})(M,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+d);i._deviceFriendlyName=t||""})(M,e)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(e){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");M.__bUseFullFeature=e}static isImageSource(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"getImage"in e}static isDSImage(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("width"in e&&("height"in e&&"pixelFormat"in e)))}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("region"in e&&("sx"in e&&("sy"in e&&("width"in e&&("height"in e&&("colorMode"in e&&("timeSpent"in e&&("timeStamp"in e&&("isCropped"in e&&("toCanvas"in e&&("_sWidth"in e&&("_sHeight"in e&&"_bUseWebGL"in e)))))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(e){this._region=e,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var e;return null===(e=M._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",M.engineResourcePath)}static set defaultUIElementURL(e){M._defaultUIElementURL=e}static _fireHTTPSWarnning(){M.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{M.onWarning&&M.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new w({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(e){this.bPlaySoundOnSuccessfulRead="never"!==e&&e}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(e){this.bVibrateOnSuccessfulRead="never"!==e&&e}set dce(e){this._dce=e}get dce(){return!this._dce||this._dce.isDisposed?null:this._dce}set maxCvsSideLength(e){this._maxCvsSideLength=e,this._dceControler&&this._dceControler.setDisiredValue(this,"maxCvsSideLength",e)}get maxCvsSideLength(){return this._maxCvsSideLength}async _registerDCEControler(){if(!this.dce)return;M._onLog&&M._onLog("_registerDCEControler()");const e=this.dce;this._dceControler=e._createControler();const t=this._dceControler;t.register(this),t.setDisiredValue(this,"refreshInterval",200),t.setDisiredValue(this,"maxCvsSideLength",this._maxCvsSideLength);try{ResizeObserver}catch(e){"ReferenceError"===e.name&&window&&(window.ResizeObserver=void 0)}const i=e.getUIElement(),r=this.dce.constructor;if("@engineResourcePath/dce.ui.html"===r._defaultUIElementURL)try{i?i===t._innerSetUI&&(await e.setUIElement(`${r.engineResourcePath}dce.ui.html`),t._innerSetUI=e.getUIElement()):(await e.setUIElement(`${r.engineResourcePath}dbr.ui.html`),t._innerSetUI=e.getUIElement())}catch(t){await e.setUIElement(r.defaultUIElementURL)}else i||await e.setUIElement(r.defaultUIElementURL);this.callbackCameraChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async e=>{let t=await this._decode_DCEFrame(e,{bCopyData:!1});if(await this.clearMapDecodeRecord(),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(t);this.onImageRead(e)}if(this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e));const{sx:i,sy:r,width:n,height:o,_sWidth:s,_sHeight:a}=e;M.recalculateResultLocation(t,i,r,s,a,n,o),this._drawResults(t)},e.on("cameraChange",this.callbackCameraChange),e.on("resolutionChange",this.callbackResolutionChange),e.on("cameraClose",this.callbackCameraClose),e.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}_logoutDCEControler(){this.dce&&this._dceControler&&(M._onLog&&M._onLog("_logoutDCEControler()"),this._dceControler.logout(this),this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this._dceControler=null,this.dce=null)}async setImageSource(e,t){if(null==e)return this._imgSource=null,this._logoutDCEControler(),void(this._drawingItemNamespace=null);if(e&&e.isCameraEnhancer)this.dce=e,await this._registerDCEControler(),this._imgSource=null;else{if(!M.isImageSource(e))throw new Error("Invalid value.");this._logoutDCEControler(),this._imgSource=e}t&&t.resultsHighlightBaseShapes&&(this._drawingItemNamespace=t.resultsHighlightBaseShapes)}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:e,l:t,ls:i,sp:r,rmk:n}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,i,r=t._license||"",n=JSON.parse(JSON.stringify(t._licenseServer)),o=t._sessionPassword,s=0;if(r.startsWith("t")||r.startsWith("f"))s=0;else if(0===r.length||r.startsWith("P")||r.startsWith("L")||r.startsWith("Y")||r.startsWith("A"))s=1;else{s=2;const t=r.indexOf(":");if(-1!=t&&(r=r.substring(t+1)),r.startsWith("DLS2")){let t=r.substring(4);try{t=atob(t)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}const i=JSON.parse(t);if(r=i.handshakeCode?i.handshakeCode:i.organizationID?i.organizationID:"","number"==typeof r&&(r=JSON.stringify(r)),0===n.length){let e=[];i.mainServerURL&&(e[0]=i.mainServerURL),i.standbyServerURL&&(e[1]=i.standbyServerURL),n=_(e)}!o&&i.sessionPassword&&(o=i.sessionPassword),e=i.remark}("200001"===r||r.startsWith("200001-"))&&(n&&n.length||(r="")),r||(s=1)}if(s&&(globalThis.crypto||(i="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(i="Require https to use online key in this browser.")),i){if(1!==s)throw new Error(i);s=0,console.warn(i),t._lastErrorCode=-1,t._lastErrorString=i}return 1===s&&(r="",console.warn("Applying for a public trial license ...")),{lt:s,l:r,ls:n,sp:o,rmk:e}}throw new Error("Can't preprocess license again"+d)})(M);this._pLoad.task=async(o,a)=>{let l=M.engineResourcePath+M._workerName;M.engineResourcePath.startsWith(location.origin)||(l=await fetch(l).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),M._dbrWorker=new Worker(l),M._dbrWorker.onerror=e=>{let t=new Error(e.message);a(t)},M._dbrWorker.onmessage=async t=>{let i=t.data?t.data:t;switch(i.type){case"log":M._onLog&&M._onLog(i.message);break;case"load":{i.message&&(i.message=i.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,r=!1;1===e&&(r=!0),i.success?(M._dbrWorker.onerror=null,M._version=i.version+"(JS "+M._jsVersion+"."+M._jsEditVersion+")",M._onLog&&M._onLog("load dbr worker success"),i.message&&console.warn(i.message)):(t=new Error(i.message),t.stack=i.stack+"\n"+t.stack,r||111==i.ltsErrorCode&&-1!=i.message.toLowerCase().indexOf("trial license")&&(r=!0)),r&&M.showDialog(i.success?"warn":"error",i.message),i.success?o():a(t);break}case"task":{let e=i.id,t=i.body;try{M._taskCallbackMap.get(e)(t),M._taskCallbackMap.delete(e)}catch(t){throw M._taskCallbackMap.delete(e),t}break}default:M._onLog&&M._onLog(t)}},M._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:M.engineResourcePath,bUseFullFeature:M._bUseFullFeature,bd:M._bWasmDebug,v:M._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:s,fn:M.deviceFriendlyName,ls:i,sp:r,rmk:n})}}await this._pLoad}static async showDialog(e,t){await(async(e,t,i)=>{if(!e._bNeverShowDialog)try{let r=await fetch(e.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let n=await r.text();if(!n.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let o=document.createElement("div");o.innerHTML=n;let s=[];for(let e=0;e{if(e==t.target){a.remove();for(let e of s)e.remove()}}));else if(!h&&e.classList.contains("dls-license-icon-close"))h=e,e.addEventListener("click",(()=>{a.remove();for(let e of s)e.remove()}));else if(!c&&e.classList.contains("dls-license-icon-error"))c=e,"error"!=t&&e.remove();else if(!u&&e.classList.contains("dls-license-icon-warn"))u=e,"warn"!=t&&e.remove();else if(!d&&e.classList.contains("dls-license-msg-content")){d=e;let t=i;for(;t;){let i=t.indexOf("["),r=t.indexOf("]",i),n=t.indexOf("(",r),o=t.indexOf(")",n);if(-1==i||-1==r||-1==n||-1==o){e.appendChild(new Text(t));break}i>0&&e.appendChild(new Text(t.substring(0,i)));let s=document.createElement("a"),a=t.substring(i+1,r);s.innerText=a;let l=t.substring(n+1,o);s.setAttribute("href",l),s.setAttribute("target","_blank"),e.appendChild(s),t=t.substring(o+1)}}document.body.appendChild(a)}catch(t){e._onLog&&e._onLog(t.message||t)}})(this,e,t)}static async createInstanceInWorker(e=!1){return await M.loadWasm(),await new Promise(((t,i)=>{let r=M._nextTaskID++;M._taskCallbackMap.set(r,(e=>{if(e.success)return t(e.instanceID);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),M._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}static async createInstance(){let e=new M;return e._instanceID=await M.createInstanceInWorker(),M._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let i=M._nextTaskID++;M._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),M._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:i,instanceID:this._instanceID})}))}async decode(e){M._onLog&&M._onLog("decode(source: any)"),M._onLog&&(this._timeStartDecode=Date.now());{let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),e instanceof Blob?await this._decode_Blob(e,t):e instanceof ArrayBuffer?await this._decode_ArrayBuffer(e,t):e instanceof Uint8Array||e instanceof Uint8ClampedArray?await this._decode_Uint8Array(e,t):e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?await this._decode_Image(e,t):e instanceof HTMLCanvasElement?await this._decode_Canvas(e,t):e instanceof HTMLVideoElement?await this._decode_Video(e,t):"string"==typeof e?"data:image/"==e.substring(0,11)?await this._decode_Base64(e,t):await this._decode_Url(e,t):M.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):M.isDSImage(e)?(t.bCopyData=!0,await this._decode_DSImage(e,t)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(e,t)}async decodeUrl(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(e,t)}async _decodeBuffer_Uint8Array(e,t,i,r,n,o){return await new Promise(((s,a)=>{let l=M._nextTaskID++;M._taskCallbackMap.set(l,(e=>{if(e.success){let t,i=M._onLog?Date.now():0;M._onLog&&M._onLog("worker return result: "+i),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return a(e)}if(M._onLog){let e=Date.now();M._onLog("DBR time get result: "+i),M._onLog("Handle image cost: "+(this._timeEnterInnerDBR-this._timeStartDecode)),M._onLog("DBR worker decode image cost: "+(i-this._timeEnterInnerDBR)),M._onLog("DBR worker handle results: "+(e-i)),M._onLog("Total decode image cost: "+(e-this._timeStartDecode))}return s(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}})),this._timeEnterInnerDBR=Date.now(),M._onLog&&M._onLog("Send buffer to worker:"+this._timeEnterInnerDBR),M._dbrWorker.postMessage({type:"decodeBuffer",id:l,instanceID:this._instanceID,body:{buffer:e,width:t,height:i,stride:r,format:n,config:o}},[e.buffer]),M._onLog&&o&&o.timeStamp&&M._onLog("decode image delay: "+(this._timeEnterInnerDBR-o.timeStamp))}))}async _decodeBuffer_Blob(e,t,i,r,n,o){M._onLog&&M._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const s=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,i)=>{let r=new FileReader;r.readAsArrayBuffer(e),r.onload=()=>{t(r.result)},r.onerror=()=>{i(r.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(s),t,i,r,n,o)}async decodeBuffer(e,t,i,r,n,o){let s;return M._onLog&&M._onLog("decodeBuffer(buffer,width,height,stride,format)"),M._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?s=await this._decodeBuffer_Uint8Array(e,t,i,r,n,o):e instanceof ArrayBuffer?s=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,i,r,n,o):e instanceof Blob&&(s=await this._decodeBuffer_Blob(e,t,i,r,n,o)),s}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,i)=>{let r=M._nextTaskID++;M._taskCallbackMap.set(r,(e=>{if(e.success){let r;this._lastInnerDecodeDuration=e.duration;try{r=this._handleRetJsonString(e.decodeReturn)}catch(e){return i(e)}return t(r)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),M._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let i=M._nextTaskID++;M._taskCallbackMap.set(i,(i=>{if(i.success){let t=JSON.parse(i.results);return null!=this.userDefinedRegion&&(t.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),e(t)}{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),M._dbrWorker.postMessage({type:"getRuntimeSettings",id:i,instanceID:this._instanceID})}))}async updateRuntimeSettings(t){let i;if("string"==typeof t)if("speed"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region,i.deblurLevel=3,i.expectedBarcodesCount=0,i.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region,i.deblurLevel=5,i.expectedBarcodesCount=512,i.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region}else if("dense"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region,i.deblurLevel=9,i.expectedBarcodesCount=0,i.localizationModes=[2,8,0,0,0,0,0,0]}else if("distance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region,i.deblurLevel=3,i.expectedBarcodesCount=0,i.localizationModes=[2,8,0,0,0,0,0,0]}else i=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(i=JSON.parse(JSON.stringify(t)),i.region instanceof Array){let e=i.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(i.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!M._bUseFullFeature){if(0!=(i.barcodeFormatIds&~(e.EnumBarcodeFormat.BF_ONED|e.EnumBarcodeFormat.BF_QR_CODE|e.EnumBarcodeFormat.BF_PDF417|e.EnumBarcodeFormat.BF_DATAMATRIX))||0!=i.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=i.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let e=i.region;if(e instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(e)),(e.regionLeft||e.regionTop||e.regionRight||e.regionBottom||e.regionMeasuredByPercentage)&&(e.regionLeft||e.regionTop||100!=e.regionRight||100!=e.regionBottom||!e.regionMeasuredByPercentage)?this.region=e:this.region=null,i.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return await new Promise(((e,t)=>{let r=M._nextTaskID++;M._taskCallbackMap.set(r,(i=>{if(i.success){try{this._handleRetJsonString(i.updateReturn)}catch(e){t(e)}return e()}{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),M._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(i)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=D,await new Promise(((e,t)=>{let i=M._nextTaskID++;M._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),M._dbrWorker.postMessage({type:"resetRuntimeSettings",id:i,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!M._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((e,t)=>{let i=M._nextTaskID++;M._taskCallbackMap.set(i,(i=>{if(i.success)return e(i.results);{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),M._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:i,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!M._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof e)e=e;else{if("object"!=typeof e)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");e=JSON.stringify(e)}return await new Promise(((t,i)=>{let r=M._nextTaskID++;M._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.initReturn)}catch(e){i(e)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),M._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){M._onLog&&M._onLog("_decode_Blob(blob: Blob)");let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(e)}catch(e){}i||(r=await function(e){return new Promise(((t,i)=>{let r=URL.createObjectURL(e),n=new Image;n.dbrObjUrl=r,n.src=r,n.onload=()=>{t(n)},n.onerror=e=>{i(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let n=await this._decode_Image(i||r,t);return i&&i.close(),n}async _decode_ArrayBuffer(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Uint8Array(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Image(e,t){M._onLog&&M._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),t=t||{};let i,r,n=e instanceof HTMLImageElement?e.naturalWidth:e.width,o=e instanceof HTMLImageElement?e.naturalHeight:e.height,s=Math.max(n,o);if(s>this._maxCvsSideLength){let e=this._maxCvsSideLength/s;i=Math.round(n*e),r=Math.round(o*e)}else i=n,r=o;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d"));return a.ctx2d.drawImage(e,0,0,n,o,0,0,i,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._decode_Canvas(a,t)}async _decode_Canvas(t,i){if(M._onLog&&M._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if(0===t.width||0===t.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=t,this.oriCanvasData=null);let r=(t.ctx2d||t.getContext("2d")).getImageData(0,0,t.width,t.height).data;return await this._decodeBuffer_Uint8Array(r,t.width,t.height,4*t.width,e.EnumImagePixelFormat.IPF_ABGR_8888,i)}async _decode_Video(e,t){if(M._onLog&&M._onLog("_decode_Video(video)"),!(e instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";t=t||{};let i,r,n=e.videoWidth,o=e.videoHeight,s=Math.max(n,o);if(s>this._maxCvsSideLength){let e=this._maxCvsSideLength/s;i=Math.round(n*e),r=Math.round(o*e)}else i=n,r=o;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d"));return a.ctx2d.drawImage(e,0,0,n,o,0,0,i,r),await this._decode_Canvas(a,t)}async _decode_DCEFrame(t,i){if(M._onLog&&M._onLog("_decode_DCEFrame(dceFrame)"),!M.isDCEFrame(t))return[];let r=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{width:n,height:o,colorMode:s,timeStamp:a}=t;let l;l=i&&i.bCopyData?new Uint8Array(t.data):t.data;let h=null;if(i?(h=JSON.parse(JSON.stringify(i)),h.timeStamp=a):h={timeStamp:a},"grey"===s)r=await this._decodeBuffer_Uint8Array(l,n,o,n,e.EnumImagePixelFormat.IPF_GrayScaled,h);else if("rgba"===s)r=await this._decodeBuffer_Uint8Array(l,n,o,4*n,e.EnumImagePixelFormat.IPF_ABGR_8888,h);else{if("bgra"!==s)throw new Error(`Color mode '${s}' is not supported to decode.`);r=await this._decodeBuffer_Uint8Array(l,n,o,4*n,e.EnumImagePixelFormat.IPF_ARGB_8888,h)}return r}async _decode_DSImage(t,i){if(M._onLog&&M._onLog("_decode_DSImage(dsImage)"),!M.isDSImage(t))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat.toLowerCase(),data:new Uint8Array(t.data),toCanvas:function(){const e=document.createElement("canvas");let t;switch(e.width=this.width,e.height=this.height,this.pixelFormat){case"grey":t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{let r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="blob",r.send(),r.onloadend=async()=>{t(r.response)},r.onerror=()=>{i(new Error("Network Error: "+r.statusText))}}));return await this._decode_Blob(i,t)}}async _decode_FilePath(e,t){throw M._onLog&&M._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static recalculateResultLocation(e,t,i,r,n,o,s){if(e.length>0)for(let a of e){let e=a.localizationResult;2==e.resultCoordinateType&&(e.x1*=.01*o,e.x2*=.01*o,e.x3*=.01*o,e.x4*=.01*o,e.y1*=.01*s,e.y2*=.01*s,e.y3*=.01*s,e.y4*=.01*s);let l=o/r,h=s/n;e.x1=e.x1/l+t,e.x2=e.x2/l+t,e.x3=e.x3/l+t,e.x4=e.x4/l+t,e.y1=e.y1/h+i,e.y2=e.y2/h+i,e.y3=e.y3/h+i,e.y4=e.y4/h+i,2==e.resultCoordinateType&&(e.x1*=100/r,e.x2*=100/r,e.x3*=100/r,e.x4*=100/r,e.y1*=100/n,e.y2*=100/n,e.y3*=100/n,e.y4*=100/n)}}static BarcodeReaderException(t,i){let r,n=e.EnumErrorCode.DBR_UNKNOWN;return"number"==typeof t?(n=t,r=new Error(i)):r=new Error(t),r.code=n,r}_handleRetJsonString(t){let i=e.EnumErrorCode;if(t.textResults){for(let e=0;e{let i=t.indexOf(":");e[t.substring(0,i)]=t.substring(i+1)})),i.exception=e}}return t.decodeRecords?this.decodeRecords=t.decodeRecords:this.decodeRecords={},this._lastErrorCode=t.exception,this._lastErrorString=t.description,t.exception&&!M._setWarnnedEx.has(t.description)&&(M._setWarnnedEx.add(t.description),console.warn(t.description)),t.textResults}if(t.exception==i.DBR_SUCCESS)return t.data;throw M.BarcodeReaderException(t.exception,t.description)}async setModeArgument(e,t,i,r){return await new Promise(((n,o)=>{let s=M._nextTaskID++;M._taskCallbackMap.set(s,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return o(e)}return n()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,o(t)}})),M._dbrWorker.postMessage({type:"setModeArgument",id:s,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i,argumentValue:r}})}))}async getModeArgument(e,t,i){return await new Promise(((r,n)=>{let o=M._nextTaskID++;M._taskCallbackMap.set(o,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return n(e)}return r(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),M._dbrWorker.postMessage({type:"getModeArgument",id:o,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i}})}))}async getIntermediateResults(){return await new Promise(((e,t)=>{let i=M._nextTaskID++;M._taskCallbackMap.set(i,(i=>{if(i.success)return e(i.results);{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),M._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let t=await this.getIntermediateResults(),i=[];for(let r of t)if(r.dataType==e.EnumIMResultDataType.IMRDT_IMAGE)for(let t of r.results){const r=t.bytes;let n;switch(M._onLog&&M._onLog(" "+r.length+" "+r.byteLength+" "+t.width+" "+t.height+" "+t.stride+" "+t.format),t.format){case e.EnumImagePixelFormat.IPF_ABGR_8888:n=new Uint8ClampedArray(r);break;case e.EnumImagePixelFormat.IPF_RGB_888:{const e=r.length/3;n=new Uint8ClampedArray(4*e);for(let t=0;t{let i=M._nextTaskID++;M._taskCallbackMap.set(i,(i=>{if(i.success){let t=i.results;return t.intervalTime=this.intervalTime,t.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,t.soundOnSuccessfullRead=this.soundSource,t.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,t.vibrateDuration=this.vibrateDuration,t.captureAndDecodeInParallel=this.captureAndDecodeInParallel,e(t)}{let e=new Error(i.message);return e.stack+="\n"+i.stack,t(e)}})),M._dbrWorker.postMessage({type:"getScanSettings",id:i,instanceID:this._instanceID})}))}async updateScanSettings(e){if(!e)return;const t=JSON.parse(JSON.stringify(e));return t.hasOwnProperty("intervalTime")&&(this.intervalTime=Math.max(t.intervalTime,0),delete t.intervalTime),t.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=t.whenToPlaySoundforSuccessfulRead,delete t.whenToPlaySoundforSuccessfulRead),t.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=t.soundOnSuccessfullRead,delete t.soundOnSuccessfullRead),t.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=t.whenToVibrateforSuccessfulRead,delete t.whenToVibrateforSuccessfulRead),t.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=t.vibrateDuration,delete t.vibrateDuration),t.hasOwnProperty("captureAndDecodeInParallel")&&(this.captureAndDecodeInParallel=t.captureAndDecodeInParallel,delete t.captureAndDecodeInParallel),await new Promise(((e,i)=>{let r=M._nextTaskID++;M._taskCallbackMap.set(r,(t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack+="\n"+t.stack,i(e)}})),M._dbrWorker.postMessage({type:"updateScanSettings",id:r,instanceID:this._instanceID,body:{settings:t}})}))}_cloneDecodeResults(e){if(e instanceof Array){let t=[];for(let i of e)t.push(this._cloneDecodeResults(i));return t}{let t=e,i=JSON.parse(JSON.stringify(t,((e,t)=>"oriVideoCanvas"==e||"searchRegionCanvas"==e?void 0:t)));return i}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this._imgSource||this._bPauseScan)return M._onLog&&M._onLog("Scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));M._onLog&&M._onLog("======= once read ======="),M._onLog&&(this._timeStartDecode=Date.now());let e=null,t=null;if(this.dce)e=this._getVideoFrame();else if(this._imgSource&&(t=await this._imgSource.getImage(),!M.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let i=[];if(e){i=await this._decode_DCEFrame(e,{bScanner:!0,bCopyData:!1});let t=null;if(i&&i.length){const{sx:r,sy:n,width:o,height:s,_sWidth:a,_sHeight:l}=e;t=i.map((e=>({localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),M.recalculateResultLocation(t,r,n,a,l,o,s)}this._drawResults(t)}else t&&(i=await this._decode_DSImage(t,{bScanner:!0,bCopyData:!1}));return i})().then((e=>{if(M._onLog&&M._onLog(e),this.dce&&this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost;const i=()=>{let i=0;if(t&&t.length){let r=Math.min(...e),n=Math.max(...t);r&&n&&(i=r-n)}else i=0;return i>0?i:0};(()=>{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=i()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this._imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead)t=!0;else if("unique"===this.bPlaySoundOnSuccessfulRead)for(let i of e)if(0==i.resultsType){t=!0;break}t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead)t=!0;else if("unique"===this.bVibrateOnSuccessfulRead)for(let i of e)if(0==i.resultsType){t=!0;break}if(t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onImageRead){let t=this._cloneDecodeResults(e);for(let e of t)0!=e.resultsType&&1!=e.resultsType||this.onImageRead(t);this.onImageRead(t)}if(this.onUniqueRead)for(let t of e)0==t.resultsType&&this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t))}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),M._onLog&&M._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){if(this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",this._intervalGetVideoFrame),!this.dce.numberOfFramesInBuffer)return this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",0),null;e=this.dce.getFrameFromBuffer();const t=e=>{if(!e)return;let t=e.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(t)};t(e)}else this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),e=this.dce.getFrame();return e}_drawResults(e){if(!this.dce||this._bPauseScan||!this._drawingItemNamespace||!this._drawingItemNamespace.DT_Polygon)return;if(!this._dbrDrawingLayer){if(!this.dce.isOpen())return;this._dbrDrawingLayer=this.dce.getDrawingLayer(3)}const t=this._dbrDrawingLayer;if(t.clearDrawingItems(),e&&e.length)for(let i of e){const e=i.localizationResult,r=new this._drawingItemNamespace.DT_Polygon([{x:e.x1,y:e.y1},{x:e.x2,y:e.y2},{x:e.x3,y:e.y3},{x:e.x4,y:e.y4}]);t.addDrawingItem(r)}}async startScanning(e){if(!this.dce&&!this._imgSource)throw new Error("'imageSource' is not set. call 'setImageSource()' before 'startScanning()'.");if("closed"!=this._tempSolutionStatus)return;if(this._tempSolutionStatus="opening","opening"!=this._tempSolutionStatus)return;let t=null;return this.dce&&(this.dce.isOpen()?(e&&this.dce.appendAndShowUI(),t=JSON.parse(JSON.stringify(this.dce.playCallbackInfo))):t=await this.dce.open(e),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"close"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())),"opening"==this._tempSolutionStatus?(this._bPauseScan=!1,this.dce&&this.dce.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),0)),this._tempSolutionStatus="opened",this.keepAlive(),t):void 0}stopScanning(e){this.dce&&(this._drawResults(null),this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"close",e))),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._tempSolutionStatus="closed"}pauseScanning(e){if(e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"stopFetchingLoop"))}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.startFetchingLoop(),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(M._onLog&&M._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,(this.dce||"opening"===this._tempSolutionStatus)&&this.stopScanning(),this.setImageSource(null);let e=M._nextTaskID++;M._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),M._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}M._jsVersion="9.2.11",M._jsEditVersion="20220727",M._version=`loading...(JS ${M._jsVersion}.${M._jsEditVersion})`,M._license=f,M._sessionPassword=g,M.browserInfo=s,M._workerName=`dbr-${M._jsVersion}.browser.worker.js`,M._engineResourcePath=u,M._licenseServer=[],M._deviceFriendlyName="",M._isShowRelDecodeTimeInResults=!1,M._bWasmDebug=!1,M._bNeverShowDialog=!1,M.__bUseFullFeature=!0,M._nextTaskID=0,M._taskCallbackMap=new Map,M._pLoad=new class extends Promise{constructor(e){let t,i;super(((e,r)=>{t=e,i=r})),this._s="pending",this.resolve=e=>{this.isPending&&(S(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",i(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,S(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const i=await t;e===this._task&&this.resolve(i)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}},M._lastErrorCode=0,M._lastErrorString="",M._setWarnnedEx=new Set,M._defaultUIElementURL="@engineResourcePath/dbr.ui.html";var L={653:(e,t,i)=>{var r,n,o,s,a,l,h,c,u,d,f,g,_,p,m,v,y,S,b,C,w,T=T||{version:"5.2.1"};if(t.fabric=T,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?T.document=document:T.document=document.implementation.createHTMLDocument(""),T.window=window;else{var x=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;T.document=x.document,T.jsdomImplForWrapper=i(898).implForWrapper,T.nodeCanvas=i(245).Canvas,T.window=x,DOMParser=T.window.DOMParser}function E(e,t){var i=e.canvas,r=t.targetCanvas,n=r.getContext("2d");n.translate(0,r.height),n.scale(1,-1);var o=i.height-r.height;n.drawImage(i,0,o,r.width,r.height,0,0,r.width,r.height)}function A(e,t){var i=t.targetCanvas.getContext("2d"),r=t.destinationWidth,n=t.destinationHeight,o=r*n*4,s=new Uint8Array(this.imageBuffer,0,o),a=new Uint8ClampedArray(this.imageBuffer,0,o);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,s);var l=new ImageData(a,r,n);i.putImageData(l,0,0)}T.isTouchSupported="ontouchstart"in T.window||"ontouchstart"in T.document||T.window&&T.window.navigator&&T.window.navigator.maxTouchPoints>0,T.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,T.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],T.DPI=96,T.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",T.commaWsp="(?:\\s+,?\\s*|,\\s*)",T.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,T.reNonWord=/[ \n\.,;!\?\-]/,T.fontPaths={},T.iMatrix=[1,0,0,1,0,0],T.svgNS="http://www.w3.org/2000/svg",T.perfLimitSizeTotal=2097152,T.maxCacheSideLimit=4096,T.minCacheSideLimit=256,T.charWidthsCache={},T.textureSize=2048,T.disableStyleCopyPaste=!1,T.enableGLFiltering=!0,T.devicePixelRatio=T.window.devicePixelRatio||T.window.webkitDevicePixelRatio||T.window.mozDevicePixelRatio||1,T.browserShadowBlurConstant=1,T.arcToSegmentsCache={},T.boundsOfCurveCache={},T.cachesBoundsOfCurve=!0,T.forceGLPutImageData=!1,T.initFilterBackend=function(){return T.enableGLFiltering&&T.isWebglSupported&&T.isWebglSupported(T.textureSize)?(console.log("max texture size: "+T.maxTextureSize),new T.WebglFilterBackend({tileSize:T.textureSize})):T.Canvas2dFilterBackend?new T.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=T),function(){function e(e,t){if(this.__eventListeners[e]){var i=this.__eventListeners[e];t?i[i.indexOf(t)]=!1:T.util.array.fill(i,!1)}}function t(e,t){var i=function(){t.apply(this,arguments),this.off(e,i)}.bind(this);this.on(e,i)}T.Observable={fire:function(e,t){if(!this.__eventListeners)return this;var i=this.__eventListeners[e];if(!i)return this;for(var r=0,n=i.length;r-1||!!t&&this._objects.some((function(t){return"function"==typeof t.contains&&t.contains(e,!0)}))},complexity:function(){return this._objects.reduce((function(e,t){return e+(t.complexity?t.complexity():0)}),0)}},T.CommonMethods={_setOptions:function(e){for(var t in e)this.set(t,e[t])},_initGradient:function(e,t){!e||!e.colorStops||e instanceof T.Gradient||this.set(t,new T.Gradient(e))},_initPattern:function(e,t,i){!e||!e.source||e instanceof T.Pattern?i&&i():this.set(t,new T.Pattern(e,i))},_setObject:function(e){for(var t in e)this._set(t,e[t])},set:function(e,t){return"object"==typeof e?this._setObject(e):this._set(e,t),this},_set:function(e,t){this[e]=t},toggle:function(e){var t=this.get(e);return"boolean"==typeof t&&this.set(e,!t),this},get:function(e){return this[e]}},r=t,n=Math.sqrt,o=Math.atan2,s=Math.pow,a=Math.PI/180,l=Math.PI/2,T.util={cos:function(e){if(0===e)return 1;switch(e<0&&(e=-e),e/l){case 1:case 3:return 0;case 2:return-1}return Math.cos(e)},sin:function(e){if(0===e)return 0;var t=1;switch(e<0&&(t=-1),e/l){case 1:return t;case 2:return 0;case 3:return-t}return Math.sin(e)},removeFromArray:function(e,t){var i=e.indexOf(t);return-1!==i&&e.splice(i,1),e},getRandomInt:function(e,t){return Math.floor(Math.random()*(t-e+1))+e},degreesToRadians:function(e){return e*a},radiansToDegrees:function(e){return e/a},rotatePoint:function(e,t,i){var r=new T.Point(e.x-t.x,e.y-t.y),n=T.util.rotateVector(r,i);return new T.Point(n.x,n.y).addEquals(t)},rotateVector:function(e,t){var i=T.util.sin(t),r=T.util.cos(t);return{x:e.x*r-e.y*i,y:e.x*i+e.y*r}},createVector:function(e,t){return new T.Point(t.x-e.x,t.y-e.y)},calcAngleBetweenVectors:function(e,t){return Math.acos((e.x*t.x+e.y*t.y)/(Math.hypot(e.x,e.y)*Math.hypot(t.x,t.y)))},getHatVector:function(e){return new T.Point(e.x,e.y).multiply(1/Math.hypot(e.x,e.y))},getBisector:function(e,t,i){var r=T.util.createVector(e,t),n=T.util.createVector(e,i),o=T.util.calcAngleBetweenVectors(r,n),s=o*(0===T.util.calcAngleBetweenVectors(T.util.rotateVector(r,o),n)?1:-1)/2;return{vector:T.util.getHatVector(T.util.rotateVector(r,s)),angle:o}},projectStrokeOnPoints:function(e,t,i){var r=[],n=t.strokeWidth/2,o=t.strokeUniform?new T.Point(1/t.scaleX,1/t.scaleY):new T.Point(1,1),s=function(e){var t=n/Math.hypot(e.x,e.y);return new T.Point(e.x*t*o.x,e.y*t*o.y)};return e.length<=1||e.forEach((function(a,l){var h,c,u=new T.Point(a.x,a.y);0===l?(c=e[l+1],h=i?s(T.util.createVector(c,u)).addEquals(u):e[e.length-1]):l===e.length-1?(h=e[l-1],c=i?s(T.util.createVector(h,u)).addEquals(u):e[0]):(h=e[l-1],c=e[l+1]);var d,f,g=T.util.getBisector(u,h,c),_=g.vector,p=g.angle;if("miter"===t.strokeLineJoin&&(d=-n/Math.sin(p/2),f=new T.Point(_.x*d*o.x,_.y*d*o.y),Math.hypot(f.x,f.y)/n<=t.strokeMiterLimit))return r.push(u.add(f)),void r.push(u.subtract(f));d=-n*Math.SQRT2,f=new T.Point(_.x*d*o.x,_.y*d*o.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(e,t,i){return i?new T.Point(t[0]*e.x+t[2]*e.y,t[1]*e.x+t[3]*e.y):new T.Point(t[0]*e.x+t[2]*e.y+t[4],t[1]*e.x+t[3]*e.y+t[5])},makeBoundingBoxFromPoints:function(e,t){if(t)for(var i=0;i0&&(t>r?t-=r:t=0,i>r?i-=r:i=0);var n,o=!0,s=e.getImageData(t,i,2*r||1,2*r||1),a=s.data.length;for(n=3;n=n?o-n:2*Math.PI-(n-o)}function o(e,t,i){for(var o=i[1],s=i[2],a=i[3],l=i[4],h=i[5],c=function(e,t,i,o,s,a,l){var h=Math.PI,c=l*h/180,u=T.util.sin(c),d=T.util.cos(c),f=0,g=0,_=-d*e*.5-u*t*.5,p=-d*t*.5+u*e*.5,m=(i=Math.abs(i))*i,v=(o=Math.abs(o))*o,y=p*p,S=_*_,b=m*v-m*y-v*S,C=0;if(b<0){var w=Math.sqrt(1-b/(m*v));i*=w,o*=w}else C=(s===a?-1:1)*Math.sqrt(b/(m*y+v*S));var x=C*i*p/o,E=-C*o*_/i,A=d*x-u*E+.5*e,I=u*x+d*E+.5*t,O=n(1,0,(_-x)/i,(p-E)/o),R=n((_-x)/i,(p-E)/o,(-_-x)/i,(-p-E)/o);0===a&&R>0?R-=2*h:1===a&&R<0&&(R+=2*h);for(var D=Math.ceil(Math.abs(R/h*2)),M=[],L=R/D,P=8/3*Math.sin(L/4)*Math.sin(L/4)/Math.sin(L/2),F=O+L,k=0;kC)for(var x=1,E=_.length;x2;for(t=t||0,h&&(a=e[2].xe[i-2].x?1:n.x===e[i-2].x?0:-1,l=n.y>e[i-2].y?1:n.y===e[i-2].y?0:-1),r.push(["L",n.x+a*t,n.y+l*t]),r},T.util.getPathSegmentsInfo=d,T.util.getBoundsOfCurve=function(t,i,r,n,o,s,a,l){var h;if(T.cachesBoundsOfCurve&&(h=e.call(arguments),T.boundsOfCurveCache[h]))return T.boundsOfCurveCache[h];var c,u,d,f,g,_,p,m,v=Math.sqrt,y=Math.min,S=Math.max,b=Math.abs,C=[],w=[[],[]];u=6*t-12*r+6*o,c=-3*t+9*r-9*o+3*a,d=3*r-3*t;for(var x=0;x<2;++x)if(x>0&&(u=6*i-12*n+6*s,c=-3*i+9*n-9*s+3*l,d=3*n-3*i),b(c)<1e-12){if(b(u)<1e-12)continue;0<(f=-d/u)&&f<1&&C.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(m=v(p)))/(2*c))&&g<1&&C.push(g),0<(_=(-u-m)/(2*c))&&_<1&&C.push(_));for(var E,A,I,O=C.length,R=O;O--;)E=(I=1-(f=C[O]))*I*I*t+3*I*I*f*r+3*I*f*f*o+f*f*f*a,w[0][O]=E,A=I*I*I*i+3*I*I*f*n+3*I*f*f*s+f*f*f*l,w[1][O]=A;w[0][R]=t,w[1][R]=i,w[0][R+1]=a,w[1][R+1]=l;var D=[{x:y.apply(null,w[0]),y:y.apply(null,w[1])},{x:S.apply(null,w[0]),y:S.apply(null,w[1])}];return T.cachesBoundsOfCurve&&(T.boundsOfCurveCache[h]=D),D},T.util.getPointOnPath=function(e,t,i){i||(i=d(e));for(var r=0;t-i[r].length>0&&r1e-4;)i=l(o),n=o,(r=s(h.x,h.y,i.x,i.y))+a>t?(o-=c,c/=2):(h=i,o+=c,a+=r);return i.angle=u(n),i}(o,t)}},T.util.transformPath=function(e,t,i){return i&&(t=T.util.multiplyTransformMatrices(t,[1,0,0,1,-i.x,-i.y])),e.map((function(e){for(var i=e.slice(0),r={},n=1;n=t}))}}}(),function(){function e(t,i,r){if(r)if(!T.isLikelyNode&&i instanceof Element)t=i;else if(i instanceof Array){t=[];for(var n=0,o=i.length;n57343)return e.charAt(t);if(55296<=i&&i<=56319){if(e.length<=t+1)throw"High surrogate without following low surrogate";var r=e.charCodeAt(t+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return e.charAt(t)+e.charAt(t+1)}if(0===t)throw"Low surrogate without preceding high surrogate";var n=e.charCodeAt(t-1);if(55296>n||n>56319)throw"Low surrogate without preceding high surrogate";return!1}T.util.string={camelize:function(e){return e.replace(/-+(.)?/g,(function(e,t){return t?t.toUpperCase():""}))},capitalize:function(e,t){return e.charAt(0).toUpperCase()+(t?e.slice(1):e.slice(1).toLowerCase())},escapeXml:function(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(t){var i,r=0,n=[];for(r=0;r-1?e.prototype[n]=function(e){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var n=t[e].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==e)return n}}(n):e.prototype[n]=t[n],i&&(t.toString!==Object.prototype.toString&&(e.prototype.toString=t.toString),t.valueOf!==Object.prototype.valueOf&&(e.prototype.valueOf=t.valueOf))};function n(){}function o(t){for(var i=null,r=this;r.constructor.superclass;){var n=r.constructor.superclass.prototype[t];if(r[t]!==n){i=n;break}r=r.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,e.call(arguments,1)):i.call(this):console.log("tried to callSuper "+t+", method not found in prototype chain",this)}T.util.createClass=function(){var i=null,s=e.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof s[0]&&(i=s.shift()),a.superclass=i,a.subclasses=[],i&&(n.prototype=i.prototype,a.prototype=new n,i.subclasses.push(a));for(var l=0,h=s.length;l-1||"touch"===e.pointerType},d="string"==typeof(u=T.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,_=function(e){return e},d?_=function(e,t){return e.style.opacity=t,e}:f&&(_=function(e,t){var i=e.style;return e.currentStyle&&!e.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(t=t>=.9999?"":"alpha(opacity="+100*t+")",i.filter=i.filter.replace(g,t)):i.filter+=" alpha(opacity="+100*t+")",e}),T.util.setStyle=function(e,t){var i=e.style;if(!i)return e;if("string"==typeof t)return e.style.cssText+=";"+t,t.indexOf("opacity")>-1?_(e,t.match(/opacity:\s*(\d?\.?\d*)/)[1]):e;for(var r in t)"opacity"===r?_(e,t[r]):i["float"===r||"cssFloat"===r?void 0===i.styleFloat?"cssFloat":"styleFloat":r]=t[r];return e},function(){var e,t,i,r,n=Array.prototype.slice,o=function(e){return n.call(e,0)};try{e=o(T.document.childNodes)instanceof Array}catch(e){}function s(e,t){var i=T.document.createElement(e);for(var r in t)"class"===r?i.className=t[r]:"for"===r?i.htmlFor=t[r]:i.setAttribute(r,t[r]);return i}function a(e){for(var t=0,i=0,r=T.document.documentElement,n=T.document.body||{scrollLeft:0,scrollTop:0};e&&(e.parentNode||e.host)&&((e=e.parentNode||e.host)===T.document?(t=n.scrollLeft||r.scrollLeft||0,i=n.scrollTop||r.scrollTop||0):(t+=e.scrollLeft||0,i+=e.scrollTop||0),1!==e.nodeType||"fixed"!==e.style.position););return{left:t,top:i}}e||(o=function(e){for(var t=new Array(e.length),i=e.length;i--;)t[i]=e[i];return t}),t=T.document.defaultView&&T.document.defaultView.getComputedStyle?function(e,t){var i=T.document.defaultView.getComputedStyle(e,null);return i?i[t]:void 0}:function(e,t){var i=e.style[t];return!i&&e.currentStyle&&(i=e.currentStyle[t]),i},i=T.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",T.util.makeElementUnselectable=function(e){return void 0!==e.onselectstart&&(e.onselectstart=T.util.falseFunction),r?e.style[r]="none":"string"==typeof e.unselectable&&(e.unselectable="on"),e},T.util.makeElementSelectable=function(e){return void 0!==e.onselectstart&&(e.onselectstart=null),r?e.style[r]="":"string"==typeof e.unselectable&&(e.unselectable=""),e},T.util.setImageSmoothing=function(e,t){e.imageSmoothingEnabled=e.imageSmoothingEnabled||e.webkitImageSmoothingEnabled||e.mozImageSmoothingEnabled||e.msImageSmoothingEnabled||e.oImageSmoothingEnabled,e.imageSmoothingEnabled=t},T.util.getById=function(e){return"string"==typeof e?T.document.getElementById(e):e},T.util.toArray=o,T.util.addClass=function(e,t){e&&-1===(" "+e.className+" ").indexOf(" "+t+" ")&&(e.className+=(e.className?" ":"")+t)},T.util.makeElement=s,T.util.wrapElement=function(e,t,i){return"string"==typeof t&&(t=s(t,i)),e.parentNode&&e.parentNode.replaceChild(t,e),t.appendChild(e),t},T.util.getScrollLeftTop=a,T.util.getElementOffset=function(e){var i,r,n=e&&e.ownerDocument,o={left:0,top:0},s={left:0,top:0},l={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!n)return s;for(var h in l)s[l[h]]+=parseInt(t(e,h),10)||0;return i=n.documentElement,void 0!==e.getBoundingClientRect&&(o=e.getBoundingClientRect()),r=a(e),{left:o.left+r.left-(i.clientLeft||0)+s.left,top:o.top+r.top-(i.clientTop||0)+s.top}},T.util.getNodeCanvas=function(e){var t=T.jsdomImplForWrapper(e);return t._canvas||t._image},T.util.cleanUpJsdomNode=function(e){if(T.isLikelyNode){var t=T.jsdomImplForWrapper(e);t&&(t._image=null,t._canvas=null,t._currentSrc=null,t._attributes=null,t._classList=null)}}}(),function(){function e(){}T.util.request=function(t,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",n=i.onComplete||function(){},o=new T.window.XMLHttpRequest,s=i.body||i.parameters;return o.onreadystatechange=function(){4===o.readyState&&(n(o),o.onreadystatechange=e)},"GET"===r&&(s=null,"string"==typeof i.parameters&&(t=function(e,t){return e+(/\?/.test(e)?"&":"?")+t}(t,i.parameters))),o.open(r,t,!0),"POST"!==r&&"PUT"!==r||o.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),o.send(s),o}}(),T.log=console.log,T.warn=console.warn,function(){var e=T.util.object.extend,t=T.util.object.clone,i=[];function r(){return!1}function n(e,t,i,r){return-i*Math.cos(e/r*(Math.PI/2))+i+t}T.util.object.extend(i,{cancelAll:function(){var e=this.splice(0);return e.forEach((function(e){e.cancel()})),e},cancelByCanvas:function(e){if(!e)return[];var t=this.filter((function(t){return"object"==typeof t.target&&t.target.canvas===e}));return t.forEach((function(e){e.cancel()})),t},cancelByTarget:function(e){var t=this.findAnimationsByTarget(e);return t.forEach((function(e){e.cancel()})),t},findAnimationIndex:function(e){return this.indexOf(this.findAnimation(e))},findAnimation:function(e){return this.find((function(t){return t.cancel===e}))},findAnimationsByTarget:function(e){return e?this.filter((function(t){return t.target===e})):[]}});var o=T.window.requestAnimationFrame||T.window.webkitRequestAnimationFrame||T.window.mozRequestAnimationFrame||T.window.oRequestAnimationFrame||T.window.msRequestAnimationFrame||function(e){return T.window.setTimeout(e,1e3/60)},s=T.window.cancelAnimationFrame||T.window.clearTimeout;function a(){return o.apply(T.window,arguments)}T.util.animate=function(i){i||(i={});var o,s=!1,l=function(){var e=T.runningAnimations.indexOf(o);return e>-1&&T.runningAnimations.splice(e,1)[0]};return o=e(t(i),{cancel:function(){return s=!0,l()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),T.runningAnimations.push(o),a((function(e){var t,h=e||+new Date,c=i.duration||500,u=h+c,d=i.onChange||r,f=i.abort||r,g=i.onComplete||r,_=i.easing||n,p="startValue"in i&&i.startValue.length>0,m="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?m.map((function(e,t){return v[t]-m[t]})):v-m);i.onStart&&i.onStart(),function e(i){var r=(t=i||+new Date)>u?c:t-h,n=r/c,S=p?m.map((function(e,t){return _(r,m[t],y[t],c)})):_(r,m,y,c),b=p?Math.abs((S[0]-m[0])/y[0]):Math.abs((S-m)/y);if(o.currentValue=p?S.slice():S,o.completionRate=b,o.durationRate=n,!s){if(!f(S,b,n))return t>u?(o.currentValue=p?v.slice():v,o.completionRate=1,o.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void l()):(d(S,b,n),void a(e));l()}}(h)})),o.cancel},T.util.requestAnimFrame=a,T.util.cancelAnimFrame=function(){return s.apply(T.window,arguments)},T.runningAnimations=i}(),function(){function e(e,t,i){var r="rgba("+parseInt(e[0]+i*(t[0]-e[0]),10)+","+parseInt(e[1]+i*(t[1]-e[1]),10)+","+parseInt(e[2]+i*(t[2]-e[2]),10);return(r+=","+(e&&t?parseFloat(e[3]+i*(t[3]-e[3])):1))+")"}T.util.animateColor=function(t,i,r,n){var o=new T.Color(t).getSource(),s=new T.Color(i).getSource(),a=n.onComplete,l=n.onChange;return n=n||{},T.util.animate(T.util.object.extend(n,{duration:r||500,startValue:o,endValue:s,byValue:s,easing:function(t,i,r,o){return e(i,r,n.colorEasing?n.colorEasing(t,o):1-Math.cos(t/o*(Math.PI/2)))},onComplete:function(t,i,r){if(a)return a(e(s,s,0),i,r)},onChange:function(t,i,r){if(l){if(Array.isArray(t))return l(e(t,t,0),i,r);l(t,i,r)}}}))}}(),function(){function e(e,t,i,r){return e-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===e||"xlink:href"===e||"font"===e)return i;if("imageSmoothing"===e)return"optimizeQuality"===i;a=l?i.map(o):o(i,n)}}else i="";return!l&&isNaN(a)?i:a}function f(e){return new RegExp("^("+e.join("|")+")\\b","i")}function g(e,t){var i,r,n,o,s=[];for(n=0,o=t.length;n1;)l.shift(),h=t.util.multiplyTransformMatrices(h,l[0]);return h}}();var v=new RegExp("^\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*$");function y(e){if(!t.svgViewBoxElementsRegEx.test(e.nodeName))return{};var i,r,n,s,a,l,h=e.getAttribute("viewBox"),c=1,u=1,d=e.getAttribute("width"),f=e.getAttribute("height"),g=e.getAttribute("x")||0,_=e.getAttribute("y")||0,p=e.getAttribute("preserveAspectRatio")||"",m=!h||!(h=h.match(v)),y=!d||!f||"100%"===d||"100%"===f,S=m&&y,b={},C="",w=0,T=0;if(b.width=0,b.height=0,b.toBeParsed=S,m&&(g||_)&&e.parentNode&&"#document"!==e.parentNode.nodeName&&(C=" translate("+o(g)+" "+o(_)+") ",a=(e.getAttribute("transform")||"")+C,e.setAttribute("transform",a),e.removeAttribute("x"),e.removeAttribute("y")),S)return b;if(m)return b.width=o(d),b.height=o(f),b;if(i=-parseFloat(h[1]),r=-parseFloat(h[2]),n=parseFloat(h[3]),s=parseFloat(h[4]),b.minX=i,b.minY=r,b.viewBoxWidth=n,b.viewBoxHeight=s,y?(b.width=n,b.height=s):(b.width=o(d),b.height=o(f),c=b.width/n,u=b.height/s),"none"!==(p=t.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),w=b.width-n*c,T=b.height-s*c,"Mid"===p.alignX&&(w/=2),"Mid"===p.alignY&&(T/=2),"Min"===p.alignX&&(w=0),"Min"===p.alignY&&(T=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===_)return b;if((g||_)&&"#document"!==e.parentNode.nodeName&&(C=" translate("+o(g)+" "+o(_)+") "),a=C+" matrix("+c+" 0 0 "+u+" "+(i*c+w)+" "+(r*u+T)+") ","svg"===e.nodeName){for(l=e.ownerDocument.createElementNS(t.svgNS,"g");e.firstChild;)l.appendChild(e.firstChild);e.appendChild(l)}else(l=e).removeAttribute("x"),l.removeAttribute("y"),a=l.getAttribute("transform")+a;return l.setAttribute("transform",a),b}function S(e,t){var i="xlink:href",r=m(e,t.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&S(e,r),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(e){r&&!t.hasAttribute(e)&&r.hasAttribute(e)&&t.setAttribute(e,r.getAttribute(e))})),!t.children.length)for(var n=r.cloneNode(!0);n.firstChild;)t.appendChild(n.firstChild);t.removeAttribute(i)}t.parseSVGDocument=function(e,i,n,o){if(e){!function(e){for(var i=g(e,["use","svg:use"]),r=0;i.length&&re.x&&this.y>e.y},gte:function(e){return this.x>=e.x&&this.y>=e.y},lerp:function(e,t){return void 0===t&&(t=.5),t=Math.max(Math.min(1,t),0),new i(this.x+(e.x-this.x)*t,this.y+(e.y-this.y)*t)},distanceFrom:function(e){var t=this.x-e.x,i=this.y-e.y;return Math.sqrt(t*t+i*i)},midPointFrom:function(e){return this.lerp(e)},min:function(e){return new i(Math.min(this.x,e.x),Math.min(this.y,e.y))},max:function(e){return new i(Math.max(this.x,e.x),Math.max(this.y,e.y))},toString:function(){return this.x+","+this.y},setXY:function(e,t){return this.x=e,this.y=t,this},setX:function(e){return this.x=e,this},setY:function(e){return this.y=e,this},setFromPoint:function(e){return this.x=e.x,this.y=e.y,this},swap:function(e){var t=this.x,i=this.y;this.x=e.x,this.y=e.y,e.x=t,e.y=i},clone:function(){return new i(this.x,this.y)}})}(t),function(e){var t=e.fabric||(e.fabric={});function i(e){this.status=e,this.points=[]}t.Intersection?t.warn("fabric.Intersection is already defined"):(t.Intersection=i,t.Intersection.prototype={constructor:i,appendPoint:function(e){return this.points.push(e),this},appendPoints:function(e){return this.points=this.points.concat(e),this}},t.Intersection.intersectLineLine=function(e,r,n,o){var s,a=(o.x-n.x)*(e.y-n.y)-(o.y-n.y)*(e.x-n.x),l=(r.x-e.x)*(e.y-n.y)-(r.y-e.y)*(e.x-n.x),h=(o.y-n.y)*(r.x-e.x)-(o.x-n.x)*(r.y-e.y);if(0!==h){var c=a/h,u=l/h;0<=c&&c<=1&&0<=u&&u<=1?(s=new i("Intersection")).appendPoint(new t.Point(e.x+c*(r.x-e.x),e.y+c*(r.y-e.y))):s=new i}else s=new i(0===a||0===l?"Coincident":"Parallel");return s},t.Intersection.intersectLinePolygon=function(e,t,r){var n,o,s,a,l=new i,h=r.length;for(a=0;a0&&(l.status="Intersection"),l},t.Intersection.intersectPolygonPolygon=function(e,t){var r,n=new i,o=e.length;for(r=0;r0&&(n.status="Intersection"),n},t.Intersection.intersectPolygonRectangle=function(e,r,n){var o=r.min(n),s=r.max(n),a=new t.Point(s.x,o.y),l=new t.Point(o.x,s.y),h=i.intersectLinePolygon(o,a,e),c=i.intersectLinePolygon(a,s,e),u=i.intersectLinePolygon(s,l,e),d=i.intersectLinePolygon(l,o,e),f=new i;return f.appendPoints(h.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(t),function(e){var t=e.fabric||(e.fabric={});function i(e){e?this._tryParsingColor(e):this.setSource([0,0,0,1])}function r(e,t,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e}t.Color?t.warn("fabric.Color is already defined."):(t.Color=i,t.Color.prototype={_tryParsingColor:function(e){var t;e in i.colorNameMap&&(e=i.colorNameMap[e]),"transparent"===e&&(t=[255,255,255,0]),t||(t=i.sourceFromHex(e)),t||(t=i.sourceFromRgb(e)),t||(t=i.sourceFromHsl(e)),t||(t=[0,0,0,1]),t&&this.setSource(t)},_rgbToHsl:function(e,i,r){e/=255,i/=255,r/=255;var n,o,s,a=t.util.array.max([e,i,r]),l=t.util.array.min([e,i,r]);if(s=(a+l)/2,a===l)n=o=0;else{var h=a-l;switch(o=s>.5?h/(2-a-l):h/(a+l),a){case e:n=(i-r)/h+(i0)-(e<0)||+e};function f(e,t){var i=e.angle+u(Math.atan2(t.y,t.x))+360;return Math.round(i%360/45)}function g(e,i){var r=i.transform.target,n=r.canvas,o=t.util.object.clone(i);o.target=r,n&&n.fire("object:"+e,o),r.fire(e,i)}function _(e,t){var i=t.canvas,r=e[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function p(e){return e.originX===h&&e.originY===h}function m(e,t,i){var r=e.lockScalingX,n=e.lockScalingY;return!((!r||!n)&&(t||!r&&!n||!i)&&(!r||"x"!==t)&&(!n||"y"!==t))}function v(e,t,i,r){return{e,transform:t,pointer:{x:i,y:r}}}function y(e){return function(t,i,r,n){var o=i.target,s=o.getCenterPoint(),a=o.translateToOriginPoint(s,i.originX,i.originY),l=e(t,i,r,n);return o.setPositionByOrigin(a,i.originX,i.originY),l}}function S(e,t){return function(i,r,n,o){var s=t(i,r,n,o);return s&&g(e,v(i,r,n,o)),s}}function b(e,i,r,n,o){var s=e.target,a=s.controls[e.corner],l=s.canvas.getZoom(),h=s.padding/l,c=s.toLocalPoint(new t.Point(n,o),i,r);return c.x>=h&&(c.x-=h),c.x<=-h&&(c.x+=h),c.y>=h&&(c.y-=h),c.y<=h&&(c.y+=h),c.x-=a.offsetX,c.y-=a.offsetY,c}function C(e){return e.flipX!==e.flipY}function w(e,t,i,r,n){if(0!==e[t]){var o=n/e._getTransformedDimensions()[r]*e[i];e.set(i,o)}}function T(e,t,i,r){var n,h=t.target,c=h._getTransformedDimensions(0,h.skewY),d=b(t,t.originX,t.originY,i,r),f=Math.abs(2*d.x)-c.x,g=h.skewX;f<2?n=0:(n=u(Math.atan2(f/h.scaleX,c.y/h.scaleY)),t.originX===o&&t.originY===l&&(n=-n),t.originX===a&&t.originY===s&&(n=-n),C(h)&&(n=-n));var _=g!==n;if(_){var p=h._getTransformedDimensions().y;h.set("skewX",n),w(h,"skewY","scaleY","y",p)}return _}function x(e,t,i,r){var n,h=t.target,c=h._getTransformedDimensions(h.skewX,0),d=b(t,t.originX,t.originY,i,r),f=Math.abs(2*d.y)-c.y,g=h.skewY;f<2?n=0:(n=u(Math.atan2(f/h.scaleY,c.x/h.scaleX)),t.originX===o&&t.originY===l&&(n=-n),t.originX===a&&t.originY===s&&(n=-n),C(h)&&(n=-n));var _=g!==n;if(_){var p=h._getTransformedDimensions().x;h.set("skewY",n),w(h,"skewX","scaleX","x",p)}return _}function E(e,t,i,r,n){n=n||{};var o,s,a,l,h,u,f=t.target,g=f.lockScalingX,v=f.lockScalingY,y=n.by,S=_(e,f),C=m(f,y,S),w=t.gestureScale;if(C)return!1;if(w)s=t.scaleX*w,a=t.scaleY*w;else{if(o=b(t,t.originX,t.originY,i,r),h="y"!==y?d(o.x):1,u="x"!==y?d(o.y):1,t.signX||(t.signX=h),t.signY||(t.signY=u),f.lockScalingFlip&&(t.signX!==h||t.signY!==u))return!1;if(l=f._getTransformedDimensions(),S&&!y){var T=Math.abs(o.x)+Math.abs(o.y),x=t.original,E=T/(Math.abs(l.x*x.scaleX/f.scaleX)+Math.abs(l.y*x.scaleY/f.scaleY));s=x.scaleX*E,a=x.scaleY*E}else s=Math.abs(o.x*f.scaleX/l.x),a=Math.abs(o.y*f.scaleY/l.y);p(t)&&(s*=2,a*=2),t.signX!==h&&"y"!==y&&(t.originX=c[t.originX],s*=-1,t.signX=h),t.signY!==u&&"x"!==y&&(t.originY=c[t.originY],a*=-1,t.signY=u)}var A=f.scaleX,I=f.scaleY;return y?("x"===y&&f.set("scaleX",s),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",s),!v&&f.set("scaleY",a)),A!==f.scaleX||I!==f.scaleY}n.scaleCursorStyleHandler=function(e,t,r){var n=_(e,r),o="";if(0!==t.x&&0===t.y?o="x":0===t.x&&0!==t.y&&(o="y"),m(r,o,n))return"not-allowed";var s=f(r,t);return i[s]+"-resize"},n.skewCursorStyleHandler=function(e,t,i){var n="not-allowed";if(0!==t.x&&i.lockSkewingY)return n;if(0!==t.y&&i.lockSkewingX)return n;var o=f(i,t)%4;return r[o]+"-resize"},n.scaleSkewCursorStyleHandler=function(e,t,i){return e[i.canvas.altActionKey]?n.skewCursorStyleHandler(e,t,i):n.scaleCursorStyleHandler(e,t,i)},n.rotationWithSnapping=S("rotating",y((function(e,t,i,r){var n=t,o=n.target,s=o.translateToOriginPoint(o.getCenterPoint(),n.originX,n.originY);if(o.lockRotation)return!1;var a,l=Math.atan2(n.ey-s.y,n.ex-s.x),h=Math.atan2(r-s.y,i-s.x),c=u(h-l+n.theta);if(o.snapAngle>0){var d=o.snapAngle,f=o.snapThreshold||d,g=Math.ceil(c/d)*d,_=Math.floor(c/d)*d;Math.abs(c-_)0?o:a:(c>0&&(n=u===s?o:a),c<0&&(n=u===s?a:o),C(l)&&(n=n===o?a:o)),t.originX=n,S("skewing",y(T))(e,t,i,r))},n.skewHandlerY=function(e,t,i,r){var n,a=t.target,c=a.skewY,u=t.originX;return!a.lockSkewingY&&(0===c?n=b(t,h,h,i,r).y>0?s:l:(c>0&&(n=u===o?s:l),c<0&&(n=u===o?l:s),C(a)&&(n=n===s?l:s)),t.originY=n,S("skewing",y(x))(e,t,i,r))},n.dragHandler=function(e,t,i,r){var n=t.target,o=i-t.offsetX,s=r-t.offsetY,a=!n.get("lockMovementX")&&n.left!==o,l=!n.get("lockMovementY")&&n.top!==s;return a&&n.set("left",o),l&&n.set("top",s),(a||l)&&g("moving",v(e,t,i,r)),a||l},n.scaleOrSkewActionName=function(e,t,i){var r=e[i.canvas.altActionKey];return 0===t.x?r?"skewX":"scaleY":0===t.y?r?"skewY":"scaleX":void 0},n.rotationStyleHandler=function(e,t,i){return i.lockRotation?"not-allowed":t.cursorStyle},n.fireEvent=g,n.wrapWithFixedAnchor=y,n.wrapWithFireEvent=S,n.getLocalPoint=b,t.controlsUtils=n}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.degreesToRadians,r=t.controlsUtils;r.renderCircleControl=function(e,t,i,r,n){r=r||{};var o,s=this.sizeX||r.cornerSize||n.cornerSize,a=this.sizeY||r.cornerSize||n.cornerSize,l=void 0!==r.transparentCorners?r.transparentCorners:n.transparentCorners,h=l?"stroke":"fill",c=!l&&(r.cornerStrokeColor||n.cornerStrokeColor),u=t,d=i;e.save(),e.fillStyle=r.cornerColor||n.cornerColor,e.strokeStyle=r.cornerStrokeColor||n.cornerStrokeColor,s>a?(o=s,e.scale(1,a/s),d=i*s/a):a>s?(o=a,e.scale(s/a,1),u=t*a/s):o=s,e.lineWidth=1,e.beginPath(),e.arc(u,d,o/2,0,2*Math.PI,!1),e[h](),c&&e.stroke(),e.restore()},r.renderSquareControl=function(e,t,r,n,o){n=n||{};var s=this.sizeX||n.cornerSize||o.cornerSize,a=this.sizeY||n.cornerSize||o.cornerSize,l=void 0!==n.transparentCorners?n.transparentCorners:o.transparentCorners,h=l?"stroke":"fill",c=!l&&(n.cornerStrokeColor||o.cornerStrokeColor),u=s/2,d=a/2;e.save(),e.fillStyle=n.cornerColor||o.cornerColor,e.strokeStyle=n.cornerStrokeColor||o.cornerStrokeColor,e.lineWidth=1,e.translate(t,r),e.rotate(i(o.angle)),e[h+"Rect"](-u,-d,s,a),c&&e.strokeRect(-u,-d,s,a),e.restore()}}(t),function(e){var t=e.fabric||(e.fabric={});t.Control=function(e){for(var t in e)this[t]=e[t]},t.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(e,t){return t.cursorStyle},getActionName:function(e,t){return t.actionName},getVisibility:function(e,t){var i=e._controlsVisibility;return i&&void 0!==i[t]?i[t]:this.visible},setVisibility:function(e){this.visible=e},positionHandler:function(e,i){return t.util.transformPoint({x:this.x*e.x+this.offsetX,y:this.y*e.y+this.offsetY},i)},calcCornerCoords:function(e,i,r,n,o){var s,a,l,h,c=o?this.touchSizeX:this.sizeX,u=o?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-t.util.degreesToRadians(e),_=Math.PI/2-d-t.util.degreesToRadians(e);s=f*t.util.cos(g),a=f*t.util.sin(g),l=f*t.util.cos(_),h=f*t.util.sin(_)}else f=.7071067812*(c&&u?c:i),g=t.util.degreesToRadians(45-e),s=l=f*t.util.cos(g),a=h=f*t.util.sin(g);return{tl:{x:r-h,y:n-l},tr:{x:r+s,y:n-a},bl:{x:r-s,y:n+a},br:{x:r+h,y:n+l}}},render:function(e,i,r,n,o){"circle"===((n=n||{}).cornerStyle||o.cornerStyle)?t.controlsUtils.renderCircleControl.call(this,e,i,r,n,o):t.controlsUtils.renderSquareControl.call(this,e,i,r,n,o)}}}(t),function(){function e(e,t){var i,r,n,o,s=e.getAttribute("style"),a=e.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,s){var l=s.split(/\s*;\s*/);for(""===l[l.length-1]&&l.pop(),o=l.length;o--;){var h=l[o].split(/\s*:\s*/),c=h[0].trim(),u=h[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(n=u)}}return i||(i=e.getAttribute("stop-color")||"rgb(0,0,0)"),n||(n=e.getAttribute("stop-opacity")),r=(i=new T.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*t,{offset:a,color:i.toRgb(),opacity:n}}var t=T.util.object.clone;T.Gradient=T.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(e){e||(e={}),e.coords||(e.coords={});var t,i=this;Object.keys(e).forEach((function(t){i[t]=e[t]})),this.id?this.id+="_"+T.Object.__uid++:this.id=T.Object.__uid++,t={x1:e.coords.x1||0,y1:e.coords.y1||0,x2:e.coords.x2||0,y2:e.coords.y2||0},"radial"===this.type&&(t.r1=e.coords.r1||0,t.r2=e.coords.r2||0),this.coords=t,this.colorStops=e.colorStops.slice()},addColorStop:function(e){for(var t in e){var i=new T.Color(e[t]);this.colorStops.push({offset:parseFloat(t),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(e){var t={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return T.util.populateWithProperties(this,t,e),t},toSVG:function(e,i){var r,n,o,s,a=t(this.coords,!0),l=(i=i||{},t(this.colorStops,!0)),h=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():T.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(l.sort((function(e,t){return e.offset-t.offset})),"objectBoundingBox"===g?(u/=e.width,d/=e.height):(u+=e.width/2,d+=e.height/2),"path"===e.type&&"percentage"!==this.gradientUnits&&(u-=e.pathOffset.x,d-=e.pathOffset.y),c[4]-=u,c[5]-=d,s='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',s+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+T.util.matrixToSVG(c)+'" ',"linear"===this.type?o=["\n']:"radial"===this.type&&(o=["\n']),"radial"===this.type){if(h)for((l=l.concat()).reverse(),r=0,n=l.length;r0){var p=_/Math.max(a.r1,a.r2);for(r=0,n=l.length;r\n')}return o.push("linear"===this.type?"\n":"\n"),o.join("")},toLive:function(e){var t,i,r,n=T.util.object.clone(this.coords);if(this.type){for("linear"===this.type?t=e.createLinearGradient(n.x1,n.y1,n.x2,n.y2):"radial"===this.type&&(t=e.createRadialGradient(n.x1,n.y1,n.r1,n.x2,n.y2,n.r2)),i=0,r=this.colorStops.length;i1?1:o,isNaN(o)&&(o=1);var s,a,l,h,c=t.getElementsByTagName("stop"),u="userSpaceOnUse"===t.getAttribute("gradientUnits")?"pixels":"percentage",d=t.getAttribute("gradientTransform")||"",f=[],g=0,_=0;for("linearGradient"===t.nodeName||"LINEARGRADIENT"===t.nodeName?(s="linear",a=function(e){return{x1:e.getAttribute("x1")||0,y1:e.getAttribute("y1")||0,x2:e.getAttribute("x2")||"100%",y2:e.getAttribute("y2")||0}}(t)):(s="radial",a=function(e){return{x1:e.getAttribute("fx")||e.getAttribute("cx")||"50%",y1:e.getAttribute("fy")||e.getAttribute("cy")||"50%",r1:0,x2:e.getAttribute("cx")||"50%",y2:e.getAttribute("cy")||"50%",r2:e.getAttribute("r")||"50%"}}(t)),l=c.length;l--;)f.push(e(c[l],o));return h=T.parseTransformAttribute(d),function(e,t,i,r){var n,o;Object.keys(t).forEach((function(e){"Infinity"===(n=t[e])?o=1:"-Infinity"===n?o=0:(o=parseFloat(t[e],10),"string"==typeof n&&/^(\d+\.\d+)%|(\d+)%$/.test(n)&&(o*=.01,"pixels"===r&&("x1"!==e&&"x2"!==e&&"r2"!==e||(o*=i.viewBoxWidth||i.width),"y1"!==e&&"y2"!==e||(o*=i.viewBoxHeight||i.height)))),t[e]=o}))}(0,a,n,u),"pixels"===u&&(g=-i.left,_=-i.top),new T.Gradient({id:t.getAttribute("id"),type:s,coords:a,colorStops:f,gradientUnits:u,gradientTransform:h,offsetX:g,offsetY:_})}})}(),m=T.util.toFixed,T.Pattern=T.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(e,t){if(e||(e={}),this.id=T.Object.__uid++,this.setOptions(e),!e.source||e.source&&"string"!=typeof e.source)t&&t(this);else{var i=this;this.source=T.util.createImage(),T.util.loadImage(e.source,(function(e,r){i.source=e,t&&t(i,r)}),null,this.crossOrigin)}},toObject:function(e){var t,i,r=T.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?t=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(t=this.source.toDataURL()),i={type:"pattern",source:t,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:m(this.offsetX,r),offsetY:m(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},T.util.populateWithProperties(this,i,e),i},toSVG:function(e){var t="function"==typeof this.source?this.source():this.source,i=t.width/e.width,r=t.height/e.height,n=this.offsetX/e.width,o=this.offsetY/e.height,s="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(r=1,o&&(r+=Math.abs(o))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,n&&(i+=Math.abs(n))),t.src?s=t.src:t.toDataURL&&(s=t.toDataURL()),'\n\n\n'},setOptions:function(e){for(var t in e)this[t]=e[t]},toLive:function(e){var t=this.source;if(!t)return"";if(void 0!==t.src){if(!t.complete)return"";if(0===t.naturalWidth||0===t.naturalHeight)return""}return e.createPattern(t,this.repeat)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.toFixed;t.Shadow?t.warn("fabric.Shadow is already defined."):(t.Shadow=t.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(e){for(var i in"string"==typeof e&&(e=this._parseShadow(e)),e)this[i]=e[i];this.id=t.Object.__uid++},_parseShadow:function(e){var i=e.trim(),r=t.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(t.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(r[1],10)||0,offsetY:parseFloat(r[2],10)||0,blur:parseFloat(r[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(e){var r=40,n=40,o=t.Object.NUM_FRACTION_DIGITS,s=t.util.rotateVector({x:this.offsetX,y:this.offsetY},t.util.degreesToRadians(-e.angle)),a=new t.Color(this.color);return e.width&&e.height&&(r=100*i((Math.abs(s.x)+this.blur)/e.width,o)+20,n=100*i((Math.abs(s.y)+this.blur)/e.height,o)+20),e.flipX&&(s.x*=-1),e.flipY&&(s.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var e={},i=t.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(t){this[t]!==i[t]&&(e[t]=this[t])}),this),e}}),t.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(t),function(){if(T.StaticCanvas)T.warn("fabric.StaticCanvas is already defined.");else{var e=T.util.object.extend,t=T.util.getElementOffset,i=T.util.removeFromArray,r=T.util.toFixed,n=T.util.transformPoint,o=T.util.invertTransform,s=T.util.getNodeCanvas,a=T.util.createCanvasElement,l=new Error("Could not initialize `canvas` element");T.StaticCanvas=T.util.createClass(T.CommonMethods,{initialize:function(e,t){t||(t={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(e,t)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:T.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(e,t){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(e),this._initOptions(t),this.interactive||this._initRetinaScaling(),t.overlayImage&&this.setOverlayImage(t.overlayImage,i),t.backgroundImage&&this.setBackgroundImage(t.backgroundImage,i),t.backgroundColor&&this.setBackgroundColor(t.backgroundColor,i),t.overlayColor&&this.setOverlayColor(t.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return T.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,T.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var e=T.devicePixelRatio;this.__initRetinaScaling(e,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(e,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(e,t,i){t.setAttribute("width",this.width*e),t.setAttribute("height",this.height*e),i.scale(e,e)},calcOffset:function(){return this._offset=t(this.lowerCanvasEl),this},setOverlayImage:function(e,t,i){return this.__setBgOverlayImage("overlayImage",e,t,i)},setBackgroundImage:function(e,t,i){return this.__setBgOverlayImage("backgroundImage",e,t,i)},setOverlayColor:function(e,t){return this.__setBgOverlayColor("overlayColor",e,t)},setBackgroundColor:function(e,t){return this.__setBgOverlayColor("backgroundColor",e,t)},__setBgOverlayImage:function(e,t,i,r){return"string"==typeof t?T.util.loadImage(t,(function(t,n){if(t){var o=new T.Image(t,r);this[e]=o,o.canvas=this}i&&i(t,n)}),this,r&&r.crossOrigin):(r&&t.setOptions(r),this[e]=t,t&&(t.canvas=this),i&&i(t,!1)),this},__setBgOverlayColor:function(e,t,i){return this[e]=t,this._initGradient(t,e),this._initPattern(t,e,i),this},_createCanvasElement:function(){var e=a();if(!e)throw l;if(e.style||(e.style={}),void 0===e.getContext)throw l;return e},_initOptions:function(e){var t=this.lowerCanvasEl;this._setOptions(e),this.width=this.width||parseInt(t.width,10)||0,this.height=this.height||parseInt(t.height,10)||0,this.lowerCanvasEl.style&&(t.width=this.width,t.height=this.height,t.style.width=this.width+"px",t.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(e){e&&e.getContext?this.lowerCanvasEl=e:this.lowerCanvasEl=T.util.getById(e)||this._createCanvasElement(),T.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(e,t){return this.setDimensions({width:e},t)},setHeight:function(e,t){return this.setDimensions({height:e},t)},setDimensions:function(e,t){var i;for(var r in t=t||{},e)i=e[r],t.cssOnly||(this._setBackstoreDimension(r,e[r]),i+="px",this.hasLostContext=!0),t.backstoreOnly||this._setCssDimension(r,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),t.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(e,t){return this.lowerCanvasEl[e]=t,this.upperCanvasEl&&(this.upperCanvasEl[e]=t),this.cacheCanvasEl&&(this.cacheCanvasEl[e]=t),this[e]=t,this},_setCssDimension:function(e,t){return this.lowerCanvasEl.style[e]=t,this.upperCanvasEl&&(this.upperCanvasEl.style[e]=t),this.wrapperEl&&(this.wrapperEl.style[e]=t),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(e){var t,i,r,n=this._activeObject,o=this.backgroundImage,s=this.overlayImage;for(this.viewportTransform=e,i=0,r=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",t),this._setSVGObjects(i,t),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",t),i.push(""),i.join("")},_setSVGPreamble:function(e,t){t.suppressPreamble||e.push('\n','\n')},_setSVGHeader:function(e,t){var i,n=t.width||this.width,o=t.height||this.height,s='viewBox="0 0 '+this.width+" "+this.height+'" ',a=T.Object.NUM_FRACTION_DIGITS;t.viewBox?s='viewBox="'+t.viewBox.x+" "+t.viewBox.y+" "+t.viewBox.width+" "+t.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,s='viewBox="'+r(-i[4]/i[0],a)+" "+r(-i[5]/i[3],a)+" "+r(this.width/i[0],a)+" "+r(this.height/i[3],a)+'" '),e.push("\n',"Created with Fabric.js ",T.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(t),"\n")},createSVGClipPathMarkup:function(e){var t=this.clipPath;return t?(t.clipPathId="CLIPPATH_"+T.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(e.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var e=this;return["background","overlay"].map((function(t){var i=e[t+"Color"];if(i&&i.toLive){var r=e[t+"Vpt"],n=e.viewportTransform,o={width:e.width/(r?n[0]:1),height:e.height/(r?n[3]:1)};return i.toSVG(o,{additionalTransform:r?T.util.matrixToSVG(n):""})}})).join("")},createSVGFontFacesMarkup:function(){var e,t,i,r,n,o,s,a,l="",h={},c=T.fontPaths,u=[];for(this._objects.forEach((function e(t){u.push(t),t._objects&&t._objects.forEach(e)})),s=0,a=u.length;s',"\n",l,"","\n"].join("")),l},_setSVGObjects:function(e,t){var i,r,n,o=this._objects;for(r=0,n=o.length;r\n")}else e.push('\n")},sendToBack:function(e){if(!e)return this;var t,r,n,o=this._activeObject;if(e===o&&"activeSelection"===e.type)for(t=(n=o._objects).length;t--;)r=n[t],i(this._objects,r),this._objects.unshift(r);else i(this._objects,e),this._objects.unshift(e);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(e){if(!e)return this;var t,r,n,o=this._activeObject;if(e===o&&"activeSelection"===e.type)for(n=o._objects,t=0;t0+h&&(s=o-1,i(this._objects,n),this._objects.splice(s,0,n)),h++;else 0!==(o=this._objects.indexOf(e))&&(s=this._findNewLowerIndex(e,o,t),i(this._objects,e),this._objects.splice(s,0,e));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(e,t,i){var r,n;if(i){for(r=t,n=t-1;n>=0;--n)if(e.intersectsWithObject(this._objects[n])||e.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(e)){r=n;break}}else r=t-1;return r},bringForward:function(e,t){if(!e)return this;var r,n,o,s,a,l=this._activeObject,h=0;if(e===l&&"activeSelection"===e.type)for(r=(a=l._objects).length;r--;)n=a[r],(o=this._objects.indexOf(n))"}}),e(T.StaticCanvas.prototype,T.Observable),e(T.StaticCanvas.prototype,T.Collection),e(T.StaticCanvas.prototype,T.DataURLExporter),e(T.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(e){var t=a();if(!t||!t.getContext)return null;var i=t.getContext("2d");return i&&"setLineDash"===e?void 0!==i.setLineDash:null}}),T.StaticCanvas.prototype.toJSON=T.StaticCanvas.prototype.toObject,T.isLikelyNode&&(T.StaticCanvas.prototype.createPNGStream=function(){var e=s(this.lowerCanvasEl);return e&&e.createPNGStream()},T.StaticCanvas.prototype.createJPEGStream=function(e){var t=s(this.lowerCanvasEl);return t&&t.createJPEGStream(e)})}}(),T.BaseBrush=T.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(e){e.strokeStyle=this.color,e.lineWidth=this.width,e.lineCap=this.strokeLineCap,e.miterLimit=this.strokeMiterLimit,e.lineJoin=this.strokeLineJoin,e.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(e){var t=this.canvas.viewportTransform;e.save(),e.transform(t[0],t[1],t[2],t[3],t[4],t[5])},_setShadow:function(){if(this.shadow){var e=this.canvas,t=this.shadow,i=e.contextTop,r=e.getZoom();e&&e._isRetinaScaling()&&(r*=T.devicePixelRatio),i.shadowColor=t.color,i.shadowBlur=t.blur*r,i.shadowOffsetX=t.offsetX*r,i.shadowOffsetY=t.offsetY*r}},needsFullRender:function(){return new T.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var e=this.canvas.contextTop;e.shadowColor="",e.shadowBlur=e.shadowOffsetX=e.shadowOffsetY=0},_isOutSideCanvas:function(e){return e.x<0||e.x>this.canvas.getWidth()||e.y<0||e.y>this.canvas.getHeight()}}),T.PencilBrush=T.util.createClass(T.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(e){this.canvas=e,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(e,t,i){var r=t.midPointFrom(i);return e.quadraticCurveTo(t.x,t.y,r.x,r.y),r},onMouseDown:function(e,t){this.canvas._isMainEvent(t.e)&&(this.drawStraightLine=t.e[this.straightLineKey],this._prepareForDrawing(e),this._captureDrawingPath(e),this._render())},onMouseMove:function(e,t){if(this.canvas._isMainEvent(t.e)&&(this.drawStraightLine=t.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(e))&&this._captureDrawingPath(e)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,r=i.length,n=this.canvas.contextTop;this._saveAndTransform(n),this.oldEnd&&(n.beginPath(),n.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(n,i[r-2],i[r-1],!0),n.stroke(),n.restore()}},onMouseUp:function(e){return!this.canvas._isMainEvent(e.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(e){var t=new T.Point(e.x,e.y);this._reset(),this._addPoint(t),this.canvas.contextTop.moveTo(t.x,t.y)},_addPoint:function(e){return!(this._points.length>1&&e.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(e),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(e){var t=new T.Point(e.x,e.y);return this._addPoint(t)},_render:function(e){var t,i,r=this._points[0],n=this._points[1];if(e=e||this.canvas.contextTop,this._saveAndTransform(e),e.beginPath(),2===this._points.length&&r.x===n.x&&r.y===n.y){var o=this.width/1e3;r=new T.Point(r.x,r.y),n=new T.Point(n.x,n.y),r.x-=o,n.x+=o}for(e.moveTo(r.x,r.y),t=1,i=this._points.length;t=n&&(s=e[i],a.push(s));return a.push(e[o]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var e=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(e))this.canvas.requestRenderAll();else{var t=this.createPath(e);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:t}),this.canvas.add(t),this.canvas.requestRenderAll(),t.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:t})}}}),T.CircleBrush=T.util.createClass(T.BaseBrush,{width:10,initialize:function(e){this.canvas=e,this.points=[]},drawDot:function(e){var t=this.addPoint(e),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,t),i.restore()},dot:function(e,t){e.fillStyle=t.fill,e.beginPath(),e.arc(t.x,t.y,t.radius,0,2*Math.PI,!1),e.closePath(),e.fill()},onMouseDown:function(e){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(e)},_render:function(){var e,t,i=this.canvas.contextTop,r=this.points;for(this._saveAndTransform(i),e=0,t=r.length;e0&&!this.preserveObjectStacking){t=[],i=[];for(var n=0,o=this._objects.length;n1&&(this._activeObject._objects=i),t.push.apply(t,i)}else t=this._objects;return t},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var e=this.contextContainer;return this.renderCanvas(e,this._chooseObjectsToRender()),this},renderTopLayer:function(e){e.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(e),this.contextTopDirty=!0),e.restore()},renderTop:function(){var e=this.contextTop;return this.clearContext(e),this.renderTopLayer(e),this.fire("after:render"),this},_normalizePointer:function(e,t){var i=e.calcTransformMatrix(),r=T.util.invertTransform(i),n=this.restorePointerVpt(t);return T.util.transformPoint(n,r)},isTargetTransparent:function(e,t,i){if(e.shouldCache()&&e._cacheCanvas&&e!==this._activeObject){var r=this._normalizePointer(e,{x:t,y:i}),n=Math.max(e.cacheTranslationX+r.x*e.zoomX,0),o=Math.max(e.cacheTranslationY+r.y*e.zoomY,0);return T.util.isTransparent(e._cacheContext,Math.round(n),Math.round(o),this.targetFindTolerance)}var s=this.contextCache,a=e.selectionBackgroundColor,l=this.viewportTransform;return e.selectionBackgroundColor="",this.clearContext(s),s.save(),s.transform(l[0],l[1],l[2],l[3],l[4],l[5]),e.render(s),s.restore(),e.selectionBackgroundColor=a,T.util.isTransparent(s,t,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(e){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(t){return!0===e[t]})):e[this.selectionKey]},_shouldClearSelection:function(e,t){var i=this.getActiveObjects(),r=this._activeObject;return!t||t&&r&&i.length>1&&-1===i.indexOf(t)&&r!==t&&!this._isSelectionKeyPressed(e)||t&&!t.evented||t&&!t.selectable&&r&&r!==t},_shouldCenterTransform:function(e,t,i){var r;if(e)return"scale"===t||"scaleX"===t||"scaleY"===t||"resizing"===t?r=this.centeredScaling||e.centeredScaling:"rotate"===t&&(r=this.centeredRotation||e.centeredRotation),r?!i:i},_getOriginFromCorner:function(e,t){var i={x:e.originX,y:e.originY};return"ml"===t||"tl"===t||"bl"===t?i.x="right":"mr"!==t&&"tr"!==t&&"br"!==t||(i.x="left"),"tl"===t||"mt"===t||"tr"===t?i.y="bottom":"bl"!==t&&"mb"!==t&&"br"!==t||(i.y="top"),i},_getActionFromCorner:function(e,t,i,r){if(!t||!e)return"drag";var n=r.controls[t];return n.getActionName(i,n,r)},_setupCurrentTransform:function(e,i,r){if(i){var n=this.getPointer(e),o=i.__corner,s=i.controls[o],a=r&&o?s.getActionHandler(e,i,s):T.controlsUtils.dragHandler,l=this._getActionFromCorner(r,o,e,i),h=this._getOriginFromCorner(i,o),c=e[this.centeredKey],u={target:i,action:l,actionHandler:a,corner:o,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:n.x-i.left,offsetY:n.y-i.top,originX:h.x,originY:h.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:t(i.angle),width:i.width*i.scaleX,shiftKey:e.shiftKey,altKey:c,original:T.util.saveObjectTransform(i)};this._shouldCenterTransform(i,l,c)&&(u.originX="center",u.originY="center"),u.original.originX=h.x,u.original.originY=h.y,this._currentTransform=u,this._beforeTransform(e)}},setCursor:function(e){this.upperCanvasEl.style.cursor=e},_drawSelection:function(e){var t=this._groupSelector,i=new T.Point(t.ex,t.ey),r=T.util.transformPoint(i,this.viewportTransform),n=new T.Point(t.ex+t.left,t.ey+t.top),o=T.util.transformPoint(n,this.viewportTransform),s=Math.min(r.x,o.x),a=Math.min(r.y,o.y),l=Math.max(r.x,o.x),h=Math.max(r.y,o.y),c=this.selectionLineWidth/2;this.selectionColor&&(e.fillStyle=this.selectionColor,e.fillRect(s,a,l-s,h-a)),this.selectionLineWidth&&this.selectionBorderColor&&(e.lineWidth=this.selectionLineWidth,e.strokeStyle=this.selectionBorderColor,s+=c,a+=c,l-=c,h-=c,T.Object.prototype._setLineDash.call(this,e,this.selectionDashArray),e.strokeRect(s,a,l-s,h-a))},findTarget:function(e,t){if(!this.skipTargetFind){var r,n,o=this.getPointer(e,!0),s=this._activeObject,a=this.getActiveObjects(),l=i(e),h=a.length>1&&!t||1===a.length;if(this.targets=[],h&&s._findTargetCorner(o,l))return s;if(a.length>1&&!t&&s===this._searchPossibleTargets([s],o))return s;if(1===a.length&&s===this._searchPossibleTargets([s],o)){if(!this.preserveObjectStacking)return s;r=s,n=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,o);return e[this.altSelectionKey]&&c&&r&&c!==r&&(c=r,this.targets=n),c}},_checkTarget:function(e,t,i){if(t&&t.visible&&t.evented&&t.containsPoint(e)){if(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing)return!0;if(!this.isTargetTransparent(t,i.x,i.y))return!0}},_searchPossibleTargets:function(e,t){for(var i,r,n=e.length;n--;){var o=e[n],s=o.group?this._normalizePointer(o.group,t):t;if(this._checkTarget(s,o,t)){(i=e[n]).subTargetCheck&&i instanceof T.Group&&(r=this._searchPossibleTargets(i._objects,t))&&this.targets.push(r);break}}return i},restorePointerVpt:function(e){return T.util.transformPoint(e,T.util.invertTransform(this.viewportTransform))},getPointer:function(t,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var r,n=e(t),o=this.upperCanvasEl,s=o.getBoundingClientRect(),a=s.width||0,l=s.height||0;a&&l||("top"in s&&"bottom"in s&&(l=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(a=Math.abs(s.right-s.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,i||(n=this.restorePointerVpt(n));var h=this.getRetinaScaling();return 1!==h&&(n.x/=h,n.y/=h),r=0===a||0===l?{width:1,height:1}:{width:o.width/a,height:o.height/l},{x:n.x*r.width,y:n.y*r.height}},_createUpperCanvas:function(){var e=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),t=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),T.util.addClass(i,"upper-canvas "+e),this.wrapperEl.appendChild(i),this._copyCanvasStyle(t,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=T.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),T.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),T.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(e){var t=this.width||e.width,i=this.height||e.height;T.util.setStyle(e,{position:"absolute",width:t+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),e.width=t,e.height=i,T.util.makeElementUnselectable(e)},_copyCanvasStyle:function(e,t){t.style.cssText=e.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var e=this._activeObject;return e?"activeSelection"===e.type&&e._objects?e._objects.slice(0):[e]:[]},_onObjectRemoved:function(e){e===this._activeObject&&(this.fire("before:selection:cleared",{target:e}),this._discardActiveObject(),this.fire("selection:cleared",{target:e}),e.fire("deselected")),e===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",e)},_fireSelectionEvents:function(e,t){var i=!1,r=this.getActiveObjects(),n=[],o=[];e.forEach((function(e){-1===r.indexOf(e)&&(i=!0,e.fire("deselected",{e:t,target:e}),o.push(e))})),r.forEach((function(r){-1===e.indexOf(r)&&(i=!0,r.fire("selected",{e:t,target:r}),n.push(r))})),e.length>0&&r.length>0?i&&this.fire("selection:updated",{e:t,selected:n,deselected:o}):r.length>0?this.fire("selection:created",{e:t,selected:n}):e.length>0&&this.fire("selection:cleared",{e:t,deselected:o})},setActiveObject:function(e,t){var i=this.getActiveObjects();return this._setActiveObject(e,t),this._fireSelectionEvents(i,t),this},_setActiveObject:function(e,t){return this._activeObject!==e&&!!this._discardActiveObject(t,e)&&!e.onSelect({e:t})&&(this._activeObject=e,!0)},_discardActiveObject:function(e,t){var i=this._activeObject;if(i){if(i.onDeselect({e,object:t}))return!1;this._activeObject=null}return!0},discardActiveObject:function(e){var t=this.getActiveObjects(),i=this.getActiveObject();return t.length&&this.fire("before:selection:cleared",{target:i,e}),this._discardActiveObject(e),this._fireSelectionEvents(t,e),this},dispose:function(){var e=this.wrapperEl;return this.removeListeners(),e.removeChild(this.upperCanvasEl),e.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(e){T.util.cleanUpJsdomNode(this[e]),this[e]=void 0}.bind(this)),e.parentNode&&e.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,T.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(e){var t=this._activeObject;t&&t._renderControls(e)},_toObject:function(e,t,i){var r=this._realizeGroupTransformOnObject(e),n=this.callSuper("_toObject",e,t,i);return this._unwindGroupTransformOnObject(e,r),n},_realizeGroupTransformOnObject:function(e){if(e.group&&"activeSelection"===e.group.type&&this._activeObject===e.group){var t={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){t[i]=e[i]})),T.util.addTransformToObject(e,this._activeObject.calcOwnMatrix()),t}return null},_unwindGroupTransformOnObject:function(e,t){t&&e.set(t)},_setSVGObject:function(e,t,i){var r=this._realizeGroupTransformOnObject(t);this.callSuper("_setSVGObject",e,t,i),this._unwindGroupTransformOnObject(t,r)},setViewportTransform:function(e){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),T.StaticCanvas.prototype.setViewportTransform.call(this,e)}}),T.StaticCanvas)"prototype"!==r&&(T.Canvas[r]=T.StaticCanvas[r])}(),function(){var e=T.util.addListener,t=T.util.removeListener,i={passive:!1};function r(e,t){return e.button&&e.button===t-1}T.util.object.extend(T.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(e,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(e,t){var r=this.upperCanvasEl,n=this._getEventPrefix();e(T.window,"resize",this._onResize),e(r,n+"down",this._onMouseDown),e(r,n+"move",this._onMouseMove,i),e(r,n+"out",this._onMouseOut),e(r,n+"enter",this._onMouseEnter),e(r,"wheel",this._onMouseWheel),e(r,"contextmenu",this._onContextMenu),e(r,"dblclick",this._onDoubleClick),e(r,"dragover",this._onDragOver),e(r,"dragenter",this._onDragEnter),e(r,"dragleave",this._onDragLeave),e(r,"drop",this._onDrop),this.enablePointerEvents||e(r,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&t in eventjs&&(eventjs[t](r,"gesture",this._onGesture),eventjs[t](r,"drag",this._onDrag),eventjs[t](r,"orientation",this._onOrientationChange),eventjs[t](r,"shake",this._onShake),eventjs[t](r,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(t,"remove");var e=this._getEventPrefix();t(T.document,e+"up",this._onMouseUp),t(T.document,"touchend",this._onTouchEnd,i),t(T.document,e+"move",this._onMouseMove,i),t(T.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(e,t){this.__onTransformGesture&&this.__onTransformGesture(e,t)},_onDrag:function(e,t){this.__onDrag&&this.__onDrag(e,t)},_onMouseWheel:function(e){this.__onMouseWheel(e)},_onMouseOut:function(e){var t=this._hoveredTarget;this.fire("mouse:out",{target:t,e}),this._hoveredTarget=null,t&&t.fire("mouseout",{e});var i=this;this._hoveredTargets.forEach((function(r){i.fire("mouse:out",{target:t,e}),r&&t.fire("mouseout",{e})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(e){e.isEditing&&e.hiddenTextarea.focus()}))},_onMouseEnter:function(e){this._currentTransform||this.findTarget(e)||(this.fire("mouse:over",{target:null,e}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(e,t){this.__onOrientationChange&&this.__onOrientationChange(e,t)},_onShake:function(e,t){this.__onShake&&this.__onShake(e,t)},_onLongPress:function(e,t){this.__onLongPress&&this.__onLongPress(e,t)},_onDragOver:function(e){e.preventDefault();var t=this._simpleEventHandler("dragover",e);this._fireEnterLeaveEvents(t,e)},_onDrop:function(e){return this._simpleEventHandler("drop:before",e),this._simpleEventHandler("drop",e)},_onContextMenu:function(e){return this.stopContextMenu&&(e.stopPropagation(),e.preventDefault()),!1},_onDoubleClick:function(e){this._cacheTransformEventData(e),this._handleEvent(e,"dblclick"),this._resetTransformEventData(e)},getPointerId:function(e){var t=e.changedTouches;return t?t[0]&&t[0].identifier:this.enablePointerEvents?e.pointerId:-1},_isMainEvent:function(e){return!0===e.isPrimary||!1!==e.isPrimary&&("touchend"===e.type&&0===e.touches.length||!e.changedTouches||e.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(r){r.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(r)),this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,o=this._getEventPrefix();e(T.document,"touchend",this._onTouchEnd,i),e(T.document,"touchmove",this._onMouseMove,i),t(n,o+"down",this._onMouseDown)},_onMouseDown:function(r){this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,o=this._getEventPrefix();t(n,o+"move",this._onMouseMove,i),e(T.document,o+"up",this._onMouseUp),e(T.document,o+"move",this._onMouseMove,i)},_onTouchEnd:function(r){if(!(r.touches.length>0)){this.__onMouseUp(r),this._resetTransformEventData(),this.mainTouchId=null;var n=this._getEventPrefix();t(T.document,"touchend",this._onTouchEnd,i),t(T.document,"touchmove",this._onMouseMove,i);var o=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){e(o.upperCanvasEl,n+"down",o._onMouseDown),o._willAddMouseDown=0}),400)}},_onMouseUp:function(r){this.__onMouseUp(r),this._resetTransformEventData();var n=this.upperCanvasEl,o=this._getEventPrefix();this._isMainEvent(r)&&(t(T.document,o+"up",this._onMouseUp),t(T.document,o+"move",this._onMouseMove,i),e(n,o+"move",this._onMouseMove,i))},_onMouseMove:function(e){!this.allowTouchScrolling&&e.preventDefault&&e.preventDefault(),this.__onMouseMove(e)},_onResize:function(){this.calcOffset()},_shouldRender:function(e){var t=this._activeObject;return!!(!!t!=!!e||t&&e&&t!==e)||(t&&t.isEditing,!1)},__onMouseUp:function(e){var t,i=this._currentTransform,n=this._groupSelector,o=!1,s=!n||0===n.left&&0===n.top;if(this._cacheTransformEventData(e),t=this._target,this._handleEvent(e,"up:before"),r(e,3))this.fireRightClick&&this._handleEvent(e,"up",3,s);else{if(r(e,2))return this.fireMiddleClick&&this._handleEvent(e,"up",2,s),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(e);else if(this._isMainEvent(e)){if(i&&(this._finalizeCurrentTransform(e),o=i.actionPerformed),!s){var a=t===this._activeObject;this._maybeGroupObjects(e),o||(o=this._shouldRender(t)||!a&&t===this._activeObject)}var l,h;if(t){if(l=t._findTargetCorner(this.getPointer(e,!0),T.util.isTouchEvent(e)),t.selectable&&t!==this._activeObject&&"up"===t.activeOn)this.setActiveObject(t,e),o=!0;else{var c=t.controls[l],u=c&&c.getMouseUpHandler(e,t,c);u&&u(e,i,(h=this.getPointer(e)).x,h.y)}t.isMoving=!1}if(i&&(i.target!==t||i.corner!==l)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(e,t,c);h=h||this.getPointer(e),f&&f(e,i,h.x,h.y)}this._setCursorFromEvent(e,t),this._handleEvent(e,"up",1,s),this._groupSelector=null,this._currentTransform=null,t&&(t.__corner=0),o?this.requestRenderAll():s||this.renderTop()}}},_simpleEventHandler:function(e,t){var i=this.findTarget(t),r=this.targets,n={e:t,target:i,subTargets:r};if(this.fire(e,n),i&&i.fire(e,n),!r)return i;for(var o=0;o1&&(t=new T.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(t,e))},_collectObjects:function(e){for(var t,i=[],r=this._groupSelector.ex,n=this._groupSelector.ey,o=r+this._groupSelector.left,s=n+this._groupSelector.top,a=new T.Point(v(r,o),v(n,s)),l=new T.Point(y(r,o),y(n,s)),h=!this.selectionFullyContained,c=r===o&&n===s,u=this._objects.length;u--&&!((t=this._objects[u])&&t.selectable&&t.visible&&(h&&t.intersectsWithRect(a,l,!0)||t.isContainedWithinRect(a,l,!0)||h&&t.containsPoint(a,null,!0)||h&&t.containsPoint(l,null,!0))&&(i.push(t),c)););return i.length>1&&(i=i.filter((function(t){return!t.onSelect({e})}))),i},_maybeGroupObjects:function(e){this.selection&&this._groupSelector&&this._groupSelectedObjects(e),this.setCursor(this.defaultCursor),this._groupSelector=null}}),T.util.object.extend(T.StaticCanvas.prototype,{toDataURL:function(e){e||(e={});var t=e.format||"png",i=e.quality||1,r=(e.multiplier||1)*(e.enableRetinaScaling?this.getRetinaScaling():1),n=this.toCanvasElement(r,e);return T.util.toDataURL(n,t,i)},toCanvasElement:function(e,t){e=e||1;var i=((t=t||{}).width||this.width)*e,r=(t.height||this.height)*e,n=this.getZoom(),o=this.width,s=this.height,a=n*e,l=this.viewportTransform,h=(l[4]-(t.left||0))*e,c=(l[5]-(t.top||0))*e,u=this.interactive,d=[a,0,0,a,h,c],f=this.enableRetinaScaling,g=T.util.createCanvasElement(),_=this.contextTop;return g.width=i,g.height=r,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=r,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=l,this.width=o,this.height=s,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=_,g}}),T.util.object.extend(T.StaticCanvas.prototype,{loadFromJSON:function(e,t,i){if(e){var r="string"==typeof e?JSON.parse(e):T.util.object.clone(e),n=this,o=r.clipPath,s=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete r.clipPath,this._enlivenObjects(r.objects,(function(e){n.clear(),n._setBgOverlay(r,(function(){o?n._enlivenObjects([o],(function(i){n.clipPath=i[0],n.__setupCanvas.call(n,r,e,s,t)})):n.__setupCanvas.call(n,r,e,s,t)}))}),i),this}},__setupCanvas:function(e,t,i,r){var n=this;t.forEach((function(e,t){n.insertAt(e,t)})),this.renderOnAddRemove=i,delete e.objects,delete e.backgroundImage,delete e.overlayImage,delete e.background,delete e.overlay,this._setOptions(e),this.renderAll(),r&&r()},_setBgOverlay:function(e,t){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(e.backgroundImage||e.overlayImage||e.background||e.overlay){var r=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&t&&t()};this.__setBgOverlay("backgroundImage",e.backgroundImage,i,r),this.__setBgOverlay("overlayImage",e.overlayImage,i,r),this.__setBgOverlay("backgroundColor",e.background,i,r),this.__setBgOverlay("overlayColor",e.overlay,i,r)}else t&&t()},__setBgOverlay:function(e,t,i,r){var n=this;if(!t)return i[e]=!0,void(r&&r());"backgroundImage"===e||"overlayImage"===e?T.util.enlivenObjects([t],(function(t){n[e]=t[0],i[e]=!0,r&&r()})):this["set"+T.util.string.capitalize(e,!0)](t,(function(){i[e]=!0,r&&r()}))},_enlivenObjects:function(e,t,i){e&&0!==e.length?T.util.enlivenObjects(e,(function(e){t&&t(e)}),null,i):t&&t([])},_toDataURL:function(e,t){this.clone((function(i){t(i.toDataURL(e))}))},_toDataURLWithMultiplier:function(e,t,i){this.clone((function(r){i(r.toDataURLWithMultiplier(e,t))}))},clone:function(e,t){var i=JSON.stringify(this.toJSON(t));this.cloneWithoutData((function(t){t.loadFromJSON(i,(function(){e&&e(t)}))}))},cloneWithoutData:function(e){var t=T.util.createCanvasElement();t.width=this.width,t.height=this.height;var i=new T.Canvas(t);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),e&&e(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):e&&e(i)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend,r=t.util.object.clone,n=t.util.toFixed,o=t.util.string.capitalize,s=t.util.degreesToRadians,a=!t.isLikelyNode;t.Object||(t.Object=t.util.createClass(t.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(e){e&&this.setOptions(e)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=t.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(e){var i=t.perfLimitSizeTotal,r=e.width,n=e.height,o=t.maxCacheSideLimit,s=t.minCacheSideLimit;if(r<=o&&n<=o&&r*n<=i)return rc&&(e.zoomX/=r/c,e.width=c,e.capped=!0),n>u&&(e.zoomY/=n/u,e.height=u,e.capped=!0),e},_getCacheCanvasDimensions:function(){var e=this.getTotalObjectScaling(),t=this._getTransformedDimensions(0,0),i=t.x*e.scaleX/this.scaleX,r=t.y*e.scaleY/this.scaleY;return{width:i+2,height:r+2,zoomX:e.scaleX,zoomY:e.scaleY,x:i,y:r}},_updateCacheCanvas:function(){var e=this.canvas;if(this.noScaleCache&&e&&e._currentTransform){var i=e._currentTransform.target,r=e._currentTransform.action;if(this===i&&r.slice&&"scale"===r.slice(0,5))return!1}var n,o,s=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),l=t.minCacheSideLimit,h=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=h!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,_=f||g,p=0,m=0,v=!1;if(f){var y=this._cacheCanvas.width,S=this._cacheCanvas.height,b=h>y||c>S;v=b||(h<.9*y||c<.9*S)&&y>l&&S>l,b&&!a.capped&&(h>l||c>l)&&(p=.1*h,m=.1*c)}return this instanceof t.Text&&this.path&&(_=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,m+=this.getHeightOfLine(0)*this.zoomY),!!_&&(v?(s.width=Math.ceil(h+p),s.height=Math.ceil(c+m)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,s.width,s.height)),n=a.x/2,o=a.y/2,this.cacheTranslationX=Math.round(s.width/2-n)+n,this.cacheTranslationY=Math.round(s.height/2-o)+o,this.cacheWidth=h,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(e){this._setOptions(e),this._initGradient(e.fill,"fill"),this._initGradient(e.stroke,"stroke"),this._initPattern(e.fill,"fill"),this._initPattern(e.stroke,"stroke")},transform:function(e){var t=this.group&&!this.group._transformDone||this.group&&this.canvas&&e===this.canvas.contextTop,i=this.calcTransformMatrix(!t);e.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(e){var i=t.Object.NUM_FRACTION_DIGITS,r={type:this.type,version:t.version,originX:this.originX,originY:this.originY,left:n(this.left,i),top:n(this.top,i),width:n(this.width,i),height:n(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:n(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:n(this.strokeMiterLimit,i),scaleX:n(this.scaleX,i),scaleY:n(this.scaleY,i),angle:n(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:n(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:n(this.skewX,i),skewY:n(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(r.clipPath=this.clipPath.toObject(e),r.clipPath.inverted=this.clipPath.inverted,r.clipPath.absolutePositioned=this.clipPath.absolutePositioned),t.util.populateWithProperties(this,r,e),this.includeDefaultValues||(r=this._removeDefaultValues(r)),r},toDatalessObject:function(e){return this.toObject(e)},_removeDefaultValues:function(e){var i=t.util.getKlass(e.type).prototype;return i.stateProperties.forEach((function(t){"left"!==t&&"top"!==t&&(e[t]===i[t]&&delete e[t],Array.isArray(e[t])&&Array.isArray(i[t])&&0===e[t].length&&0===i[t].length&&delete e[t])})),e},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var e=t.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(e.scaleX),scaleY:Math.abs(e.scaleY)}},getTotalObjectScaling:function(){var e=this.getObjectScaling(),t=e.scaleX,i=e.scaleY;if(this.canvas){var r=this.canvas.getZoom(),n=this.canvas.getRetinaScaling();t*=r*n,i*=r*n}return{scaleX:t,scaleY:i}},getObjectOpacity:function(){var e=this.opacity;return this.group&&(e*=this.group.getObjectOpacity()),e},_set:function(e,i){var r="scaleX"===e||"scaleY"===e,n=this[e]!==i,o=!1;return r&&(i=this._constrainScale(i)),"scaleX"===e&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===e&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==e||!i||i instanceof t.Shadow?"dirty"===e&&this.group&&this.group.set("dirty",i):i=new t.Shadow(i),this[e]=i,n&&(o=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(e)>-1?(this.dirty=!0,o&&this.group.set("dirty",!0)):o&&this.stateProperties.indexOf(e)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:t.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(e){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(e.save(),this._setupCompositeOperation(e),this.drawSelectionBackground(e),this.transform(e),this._setOpacity(e),this._setShadow(e,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(e)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(e),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),e.restore())},renderCache:function(e){e=e||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,e.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(e,i){if(e.save(),i.inverted?e.globalCompositeOperation="destination-out":e.globalCompositeOperation="destination-in",i.absolutePositioned){var r=t.util.invertTransform(this.calcTransformMatrix());e.transform(r[0],r[1],r[2],r[3],r[4],r[5])}i.transform(e),e.scale(1/i.zoomX,1/i.zoomY),e.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),e.restore()},drawObject:function(e,t){var i=this.fill,r=this.stroke;t?(this.fill="black",this.stroke="",this._setClippingProperties(e)):this._renderBackground(e),this._render(e),this._drawClipPath(e,this.clipPath),this.fill=i,this.stroke=r},_drawClipPath:function(e,t){t&&(t.canvas=this.canvas,t.shouldCache(),t._transformDone=!0,t.renderCache({forClipping:!0}),this.drawClipPathOnCache(e,t))},drawCacheOnCanvas:function(e){e.scale(1/this.zoomX,1/this.zoomY),e.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(e){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!e&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!e){var t=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-t/2,-i/2,t,i)}return!0}return!1},_renderBackground:function(e){if(this.backgroundColor){var t=this._getNonTransformedDimensions();e.fillStyle=this.backgroundColor,e.fillRect(-t.x/2,-t.y/2,t.x,t.y),this._removeShadow(e)}},_setOpacity:function(e){this.group&&!this.group._transformDone?e.globalAlpha=this.getObjectOpacity():e.globalAlpha*=this.opacity},_setStrokeStyles:function(e,t){var i=t.stroke;i&&(e.lineWidth=t.strokeWidth,e.lineCap=t.strokeLineCap,e.lineDashOffset=t.strokeDashOffset,e.lineJoin=t.strokeLineJoin,e.miterLimit=t.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(e,i):(e.strokeStyle=i.toLive(e,this),this._applyPatternGradientTransform(e,i)):e.strokeStyle=t.stroke)},_setFillStyles:function(e,t){var i=t.fill;i&&(i.toLive?(e.fillStyle=i.toLive(e,this),this._applyPatternGradientTransform(e,t.fill)):e.fillStyle=i)},_setClippingProperties:function(e){e.globalAlpha=1,e.strokeStyle="transparent",e.fillStyle="#000000"},_setLineDash:function(e,t){t&&0!==t.length&&(1&t.length&&t.push.apply(t,t),e.setLineDash(t))},_renderControls:function(e,i){var r,n,o,a=this.getViewportTransform(),l=this.calcTransformMatrix();n=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,o=void 0!==i.hasControls?i.hasControls:this.hasControls,l=t.util.multiplyTransformMatrices(a,l),r=t.util.qrDecompose(l),e.save(),e.translate(r.translateX,r.translateY),e.lineWidth=1*this.borderScaleFactor,this.group||(e.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(r.angle-=180),e.rotate(s(this.group?r.angle:this.angle)),i.forActiveSelection||this.group?n&&this.drawBordersInGroup(e,r,i):n&&this.drawBorders(e,i),o&&this.drawControls(e,i),e.restore()},_setShadow:function(e){if(this.shadow){var i,r=this.shadow,n=this.canvas,o=n&&n.viewportTransform[0]||1,s=n&&n.viewportTransform[3]||1;i=r.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),n&&n._isRetinaScaling()&&(o*=t.devicePixelRatio,s*=t.devicePixelRatio),e.shadowColor=r.color,e.shadowBlur=r.blur*t.browserShadowBlurConstant*(o+s)*(i.scaleX+i.scaleY)/4,e.shadowOffsetX=r.offsetX*o*i.scaleX,e.shadowOffsetY=r.offsetY*s*i.scaleY}},_removeShadow:function(e){this.shadow&&(e.shadowColor="",e.shadowBlur=e.shadowOffsetX=e.shadowOffsetY=0)},_applyPatternGradientTransform:function(e,t){if(!t||!t.toLive)return{offsetX:0,offsetY:0};var i=t.gradientTransform||t.patternTransform,r=-this.width/2+t.offsetX||0,n=-this.height/2+t.offsetY||0;return"percentage"===t.gradientUnits?e.transform(this.width,0,0,this.height,r,n):e.transform(1,0,0,1,r,n),i&&e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:r,offsetY:n}},_renderPaintInOrder:function(e){"stroke"===this.paintFirst?(this._renderStroke(e),this._renderFill(e)):(this._renderFill(e),this._renderStroke(e))},_render:function(){},_renderFill:function(e){this.fill&&(e.save(),this._setFillStyles(e,this),"evenodd"===this.fillRule?e.fill("evenodd"):e.fill(),e.restore())},_renderStroke:function(e){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(e),e.save(),this.strokeUniform&&this.group){var t=this.getObjectScaling();e.scale(1/t.scaleX,1/t.scaleY)}else this.strokeUniform&&e.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(e,this.strokeDashArray),this._setStrokeStyles(e,this),e.stroke(),e.restore()}},_applyPatternForTransformedGradient:function(e,i){var r,n=this._limitCacheSize(this._getCacheCanvasDimensions()),o=t.util.createCanvasElement(),s=this.canvas.getRetinaScaling(),a=n.x/this.scaleX/s,l=n.y/this.scaleY/s;o.width=a,o.height=l,(r=o.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,l),r.lineTo(0,l),r.closePath(),r.translate(a/2,l/2),r.scale(n.zoomX/this.scaleX/s,n.zoomY/this.scaleY/s),this._applyPatternGradientTransform(r,i),r.fillStyle=i.toLive(e),r.fill(),e.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),e.scale(s*this.scaleX/n.zoomX,s*this.scaleY/n.zoomY),e.strokeStyle=r.createPattern(o,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var e=t.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",e.scaleX),this.set("scaleY",e.scaleY),this.angle=e.angle,this.skewX=e.skewX,this.skewY=0}},_removeTransformMatrix:function(e){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=t.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,e&&(this.scaleX*=e.scaleX,this.scaleY*=e.scaleY,this.cropX=e.cropX,this.cropY=e.cropY,i.x+=e.offsetLeft,i.y+=e.offsetTop,this.width=e.width,this.height=e.height),this.setPositionByOrigin(i,"center","center")},clone:function(e,i){var r=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(r,e):t.Object._fromObject("Object",r,e)},cloneAsImage:function(e,i){var r=this.toCanvasElement(i);return e&&e(new t.Image(r)),this},toCanvasElement:function(e){e||(e={});var i=t.util,r=i.saveObjectTransform(this),n=this.group,o=this.shadow,s=Math.abs,a=(e.multiplier||1)*(e.enableRetinaScaling?t.devicePixelRatio:1);delete this.group,e.withoutTransform&&i.resetObjectTransform(this),e.withoutShadow&&(this.shadow=null);var l,h,c,u,d=t.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,_={x:0,y:0};g&&(h=g.blur,l=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),_.x=2*Math.round(s(g.offsetX)+h)*s(l.scaleX),_.y=2*Math.round(s(g.offsetY)+h)*s(l.scaleY)),c=f.width+_.x,u=f.height+_.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new t.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===e.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new t.Point(p.width/2,p.height/2),"center","center");var m=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,e);return this.shadow=o,this.set("canvas",m),n&&(this.group=n),this.set(r).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(e){return e||(e={}),t.util.toDataURL(this.toCanvasElement(e),e.format||"png",e.quality||1)},isType:function(e){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===e},complexity:function(){return 1},toJSON:function(e){return this.toObject(e)},rotate:function(e){var t=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return t&&this._setOriginToCenter(),this.set("angle",e),t&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(e,i){i=i||this.canvas.getPointer(e);var r=new t.Point(i.x,i.y),n=this._getLeftTopCoords();return this.angle&&(r=t.util.rotatePoint(r,n,s(-this.angle))),{x:r.x-n.x,y:r.y-n.y}},_setupCompositeOperation:function(e){this.globalCompositeOperation&&(e.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){t.runningAnimations&&t.runningAnimations.cancelByTarget(this)}}),t.util.createAccessors&&t.util.createAccessors(t.Object),i(t.Object.prototype,t.Observable),t.Object.NUM_FRACTION_DIGITS=2,t.Object.ENLIVEN_PROPS=["clipPath"],t.Object._fromObject=function(e,i,n,o){var s=t[e];i=r(i,!0),t.util.enlivenPatterns([i.fill,i.stroke],(function(e){void 0!==e[0]&&(i.fill=e[0]),void 0!==e[1]&&(i.stroke=e[1]),t.util.enlivenObjectEnlivables(i,i,(function(){var e=o?new s(i[o],i):new s(i);n&&n(e)}))}))},t.Object.__uid=0)}(t),S=T.util.degreesToRadians,b={left:-.5,center:0,right:.5},C={top:-.5,center:0,bottom:.5},T.util.object.extend(T.Object.prototype,{translateToGivenOrigin:function(e,t,i,r,n){var o,s,a,l=e.x,h=e.y;return"string"==typeof t?t=b[t]:t-=.5,"string"==typeof r?r=b[r]:r-=.5,"string"==typeof i?i=C[i]:i-=.5,"string"==typeof n?n=C[n]:n-=.5,s=n-i,((o=r-t)||s)&&(a=this._getTransformedDimensions(),l=e.x+o*a.x,h=e.y+s*a.y),new T.Point(l,h)},translateToCenterPoint:function(e,t,i){var r=this.translateToGivenOrigin(e,t,i,"center","center");return this.angle?T.util.rotatePoint(r,e,S(this.angle)):r},translateToOriginPoint:function(e,t,i){var r=this.translateToGivenOrigin(e,"center","center",t,i);return this.angle?T.util.rotatePoint(r,e,S(this.angle)):r},getCenterPoint:function(){var e=new T.Point(this.left,this.top);return this.translateToCenterPoint(e,this.originX,this.originY)},getPointByOrigin:function(e,t){var i=this.getCenterPoint();return this.translateToOriginPoint(i,e,t)},toLocalPoint:function(e,t,i){var r,n,o=this.getCenterPoint();return r=void 0!==t&&void 0!==i?this.translateToGivenOrigin(o,"center","center",t,i):new T.Point(this.left,this.top),n=new T.Point(e.x,e.y),this.angle&&(n=T.util.rotatePoint(n,o,-S(this.angle))),n.subtractEquals(r)},setPositionByOrigin:function(e,t,i){var r=this.translateToCenterPoint(e,t,i),n=this.translateToOriginPoint(r,this.originX,this.originY);this.set("left",n.x),this.set("top",n.y)},adjustPosition:function(e){var t,i,r=S(this.angle),n=this.getScaledWidth(),o=T.util.cos(r)*n,s=T.util.sin(r)*n;t="string"==typeof this.originX?b[this.originX]:this.originX-.5,i="string"==typeof e?b[e]:e-.5,this.left+=o*(i-t),this.top+=s*(i-t),this.setCoords(),this.originX=e},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var e=this.getCenterPoint();this.originX="center",this.originY="center",this.left=e.x,this.top=e.y},_resetOrigin:function(){var e=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=e.x,this.top=e.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var e=T.util,t=e.degreesToRadians,i=e.multiplyTransformMatrices,r=e.transformPoint;e.object.extend(T.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(e,t){return t?e?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),e?this.aCoords:this.lineCoords)},getCoords:function(e,t){return i=this._getCoords(e,t),[new T.Point(i.tl.x,i.tl.y),new T.Point(i.tr.x,i.tr.y),new T.Point(i.br.x,i.br.y),new T.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(e,t,i,r){var n=this.getCoords(i,r);return"Intersection"===T.Intersection.intersectPolygonRectangle(n,e,t).status},intersectsWithObject:function(e,t,i){return"Intersection"===T.Intersection.intersectPolygonPolygon(this.getCoords(t,i),e.getCoords(t,i)).status||e.isContainedWithinObject(this,t,i)||this.isContainedWithinObject(e,t,i)},isContainedWithinObject:function(e,t,i){for(var r=this.getCoords(t,i),n=t?e.aCoords:e.lineCoords,o=0,s=e._getImageLines(n);o<4;o++)if(!e.containsPoint(r[o],s))return!1;return!0},isContainedWithinRect:function(e,t,i,r){var n=this.getBoundingRect(i,r);return n.left>=e.x&&n.left+n.width<=t.x&&n.top>=e.y&&n.top+n.height<=t.y},containsPoint:function(e,t,i,r){var n=this._getCoords(i,r),o=(t=t||this._getImageLines(n),this._findCrossPoints(e,t));return 0!==o&&o%2==1},isOnScreen:function(e){if(!this.canvas)return!1;var t=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,e).some((function(e){return e.x<=i.x&&e.x>=t.x&&e.y<=i.y&&e.y>=t.y}))||!!this.intersectsWithRect(t,i,!0,e)||this._containsCenterOfCanvas(t,i,e)},_containsCenterOfCanvas:function(e,t,i){var r={x:(e.x+t.x)/2,y:(e.y+t.y)/2};return!!this.containsPoint(r,null,!0,i)},isPartiallyOnScreen:function(e){if(!this.canvas)return!1;var t=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(t,i,!0,e)||this.getCoords(!0,e).every((function(e){return(e.x>=i.x||e.x<=t.x)&&(e.y>=i.y||e.y<=t.y)}))&&this._containsCenterOfCanvas(t,i,e)},_getImageLines:function(e){return{topline:{o:e.tl,d:e.tr},rightline:{o:e.tr,d:e.br},bottomline:{o:e.br,d:e.bl},leftline:{o:e.bl,d:e.tl}}},_findCrossPoints:function(e,t){var i,r,n,o=0;for(var s in t)if(!((n=t[s]).o.y=e.y&&n.d.y>=e.y||(n.o.x===n.d.x&&n.o.x>=e.x?r=n.o.x:(i=(n.d.y-n.o.y)/(n.d.x-n.o.x),r=-(e.y-0*e.x-(n.o.y-i*n.o.x))/(0-i)),r>=e.x&&(o+=1),2!==o)))break;return o},getBoundingRect:function(t,i){var r=this.getCoords(t,i);return e.makeBoundingBoxFromPoints(r)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(e){return Math.abs(e)\n')}},toSVG:function(e){return this._createBaseSVGMarkup(this._toSVG(e),{reviver:e})},toClipPathSVG:function(e){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(e),{reviver:e})},_createBaseClipPathSVGMarkup:function(e,t){var i=(t=t||{}).reviver,r=t.additionalTransform||"",n=[this.getSvgTransform(!0,r),this.getSvgCommons()].join(""),o=e.indexOf("COMMON_PARTS");return e[o]=n,i?i(e.join("")):e.join("")},_createBaseSVGMarkup:function(e,t){var i,r,n=(t=t||{}).noStyle,o=t.reviver,s=n?"":'style="'+this.getSvgStyles()+'" ',a=t.withShadow?'style="'+this.getSvgFilter()+'" ':"",l=this.clipPath,h=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=l&&l.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],_=e.indexOf("COMMON_PARTS"),p=t.additionalTransform;return l&&(l.clipPathId="CLIPPATH_"+T.Object.__uid++,r='\n'+l.toClipPathSVG(o)+"\n"),c&&g.push("\n"),g.push("\n"),i=[s,h,n?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),e[_]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),l&&g.push(r),g.push(e.join("")),g.push("\n"),c&&g.push("\n"),o?o(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var e=T.util.object.extend,t="stateProperties";function i(t,i,r){var n={};r.forEach((function(e){n[e]=t[e]})),e(t[i],n,!0)}function r(e,t,i){if(e===t)return!0;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(var n=0,o=e.length;n=0;l--)if(n=a[l],this.isControlVisible(n)&&(r=this._getImageLines(t?this.oCoords[n].touchCorner:this.oCoords[n].corner),0!==(i=this._findCrossPoints({x:o,y:s},r))&&i%2==1))return this.__corner=n,n;return!1},forEachControl:function(e){for(var t in this.controls)e(this.controls[t],t,this)},_setCornerCoords:function(){var e=this.oCoords;for(var t in e){var i=this.controls[t];e[t].corner=i.calcCornerCoords(this.angle,this.cornerSize,e[t].x,e[t].y,!1),e[t].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,e[t].x,e[t].y,!0)}},drawSelectionBackground:function(t){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;t.save();var i=this.getCenterPoint(),r=this._calculateCurrentDimensions(),n=this.canvas.viewportTransform;return t.translate(i.x,i.y),t.scale(1/n[0],1/n[3]),t.rotate(e(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-r.x/2,-r.y/2,r.x,r.y),t.restore(),this},drawBorders:function(e,t){t=t||{};var i=this._calculateCurrentDimensions(),r=this.borderScaleFactor,n=i.x+r,o=i.y+r,s=void 0!==t.hasControls?t.hasControls:this.hasControls,a=!1;return e.save(),e.strokeStyle=t.borderColor||this.borderColor,this._setLineDash(e,t.borderDashArray||this.borderDashArray),e.strokeRect(-n/2,-o/2,n,o),s&&(e.beginPath(),this.forEachControl((function(t,i,r){t.withConnection&&t.getVisibility(r,i)&&(a=!0,e.moveTo(t.x*n,t.y*o),e.lineTo(t.x*n+t.offsetX,t.y*o+t.offsetY))})),a&&e.stroke()),e.restore(),this},drawBordersInGroup:function(e,t,i){i=i||{};var r=T.util.sizeAfterTransform(this.width,this.height,t),n=this.strokeWidth,o=this.strokeUniform,s=this.borderScaleFactor,a=r.x+n*(o?this.canvas.getZoom():t.scaleX)+s,l=r.y+n*(o?this.canvas.getZoom():t.scaleY)+s;return e.save(),this._setLineDash(e,i.borderDashArray||this.borderDashArray),e.strokeStyle=i.borderColor||this.borderColor,e.strokeRect(-a/2,-l/2,a,l),e.restore(),this},drawControls:function(e,t){t=t||{},e.save();var i,r,n=this.canvas.getRetinaScaling();return e.setTransform(n,0,0,n,0,0),e.strokeStyle=e.fillStyle=t.cornerColor||this.cornerColor,this.transparentCorners||(e.strokeStyle=t.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(e,t.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(n,o,s){r=s.oCoords[o],n.getVisibility(s,o)&&(i&&(r=T.util.transformPoint(r,i)),n.render(e,r.x,r.y,t,s))})),e.restore(),this},isControlVisible:function(e){return this.controls[e]&&this.controls[e].getVisibility(this,e)},setControlVisible:function(e,t){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[e]=t,this},setControlsVisibility:function(e){for(var t in e||(e={}),e)this.setControlVisible(t,e[t]);return this},onDeselect:function(){},onSelect:function(){}})}(),T.util.object.extend(T.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(e,t){var i=function(){},r=(t=t||{}).onComplete||i,n=t.onChange||i,o=this;return T.util.animate({target:this,startValue:e.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(t){e.set("left",t),o.requestRenderAll(),n()},onComplete:function(){e.setCoords(),r()}})},fxCenterObjectV:function(e,t){var i=function(){},r=(t=t||{}).onComplete||i,n=t.onChange||i,o=this;return T.util.animate({target:this,startValue:e.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(t){e.set("top",t),o.requestRenderAll(),n()},onComplete:function(){e.setCoords(),r()}})},fxRemove:function(e,t){var i=function(){},r=(t=t||{}).onComplete||i,n=t.onChange||i,o=this;return T.util.animate({target:this,startValue:e.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(t){e.set("opacity",t),o.requestRenderAll(),n()},onComplete:function(){o.remove(e),r()}})}}),T.util.object.extend(T.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var e,t,i=[],r=[];for(e in arguments[0])i.push(e);for(var n=0,o=i.length;n-1||n&&o.colorProperties.indexOf(n[1])>-1,a=n?this.get(n[0])[n[1]]:this.get(e);"from"in i||(i.from=a),s||(t=~t.indexOf("=")?a+parseFloat(t.replace("=","")):parseFloat(t));var l={target:this,startValue:i.from,endValue:t,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(e,t,r){return i.abort.call(o,e,t,r)},onChange:function(t,s,a){n?o[n[0]][n[1]]=t:o.set(e,t),r||i.onChange&&i.onChange(t,s,a)},onComplete:function(e,t,n){r||(o.setCoords(),i.onComplete&&i.onComplete(e,t,n))}};return s?T.util.animateColor(l.startValue,l.endValue,l.duration,l):T.util.animate(l)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend,r=t.util.object.clone,n={x1:1,x2:1,y1:1,y2:1};function o(e,t){var i=e.origin,r=e.axis1,n=e.axis2,o=e.dimension,s=t.nearest,a=t.center,l=t.farthest;return function(){switch(this.get(i)){case s:return Math.min(this.get(r),this.get(n));case a:return Math.min(this.get(r),this.get(n))+.5*this.get(o);case l:return Math.max(this.get(r),this.get(n))}}}t.Line?t.warn("fabric.Line is already defined"):(t.Line=t.util.createClass(t.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:t.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(e,t){e||(e=[0,0,0,0]),this.callSuper("initialize",t),this.set("x1",e[0]),this.set("y1",e[1]),this.set("x2",e[2]),this.set("y2",e[3]),this._setWidthHeight(t)},_setWidthHeight:function(e){e||(e={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in e?e.left:this._getLeftToOriginX(),this.top="top"in e?e.top:this._getTopToOriginY()},_set:function(e,t){return this.callSuper("_set",e,t),void 0!==n[e]&&this._setWidthHeight(),this},_getLeftToOriginX:o({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:o({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(e){e.beginPath();var t=this.calcLinePoints();e.moveTo(t.x1,t.y1),e.lineTo(t.x2,t.y2),e.lineWidth=this.strokeWidth;var i=e.strokeStyle;e.strokeStyle=this.stroke||e.fillStyle,this.stroke&&this._renderStroke(e),e.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(e){return i(this.callSuper("toObject",e),this.calcLinePoints())},_getNonTransformedDimensions:function(){var e=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(e.y-=this.strokeWidth),0===this.height&&(e.x-=this.strokeWidth)),e},calcLinePoints:function(){var e=this.x1<=this.x2?-1:1,t=this.y1<=this.y2?-1:1,i=e*this.width*.5,r=t*this.height*.5;return{x1:i,x2:e*this.width*-.5,y1:r,y2:t*this.height*-.5}},_toSVG:function(){var e=this.calcLinePoints();return["\n']}}),t.Line.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),t.Line.fromElement=function(e,r,n){n=n||{};var o=t.parseAttributes(e,t.Line.ATTRIBUTE_NAMES),s=[o.x1||0,o.y1||0,o.x2||0,o.y2||0];r(new t.Line(s,i(o,n)))},t.Line.fromObject=function(e,i){var n=r(e,!0);n.points=[e.x1,e.y1,e.x2,e.y2],t.Object._fromObject("Line",n,(function(e){delete e.points,i&&i(e)}),"points")})}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.degreesToRadians;t.Circle?t.warn("fabric.Circle is already defined."):(t.Circle=t.util.createClass(t.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:t.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(e,t){return this.callSuper("_set",e,t),"radius"===e&&this.setRadius(t),this},toObject:function(e){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(e))},_toSVG:function(){var e,r=(this.endAngle-this.startAngle)%360;if(0===r)e=["\n'];else{var n=i(this.startAngle),o=i(this.endAngle),s=this.radius;e=['180?"1":"0")+" 1"," "+t.util.cos(o)*s+" "+t.util.sin(o)*s,'" ',"COMMON_PARTS"," />\n"]}return e},_render:function(e){e.beginPath(),e.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(e)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(e){return this.radius=e,this.set("width",2*e).set("height",2*e)}}),t.Circle.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),t.Circle.fromElement=function(e,i){var r,n=t.parseAttributes(e,t.Circle.ATTRIBUTE_NAMES);if(!("radius"in(r=n)&&r.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");n.left=(n.left||0)-n.radius,n.top=(n.top||0)-n.radius,i(new t.Circle(n))},t.Circle.fromObject=function(e,i){t.Object._fromObject("Circle",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={});t.Triangle?t.warn("fabric.Triangle is already defined"):(t.Triangle=t.util.createClass(t.Object,{type:"triangle",width:100,height:100,_render:function(e){var t=this.width/2,i=this.height/2;e.beginPath(),e.moveTo(-t,i),e.lineTo(0,-i),e.lineTo(t,i),e.closePath(),this._renderPaintInOrder(e)},_toSVG:function(){var e=this.width/2,t=this.height/2;return["']}}),t.Triangle.fromObject=function(e,i){return t.Object._fromObject("Triangle",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={}),i=2*Math.PI;t.Ellipse?t.warn("fabric.Ellipse is already defined."):(t.Ellipse=t.util.createClass(t.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:t.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(e){this.callSuper("initialize",e),this.set("rx",e&&e.rx||0),this.set("ry",e&&e.ry||0)},_set:function(e,t){switch(this.callSuper("_set",e,t),e){case"rx":this.rx=t,this.set("width",2*t);break;case"ry":this.ry=t,this.set("height",2*t)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(e){return this.callSuper("toObject",["rx","ry"].concat(e))},_toSVG:function(){return["\n']},_render:function(e){e.beginPath(),e.save(),e.transform(1,0,0,this.ry/this.rx,0,0),e.arc(0,0,this.rx,0,i,!1),e.restore(),this._renderPaintInOrder(e)}}),t.Ellipse.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),t.Ellipse.fromElement=function(e,i){var r=t.parseAttributes(e,t.Ellipse.ATTRIBUTE_NAMES);r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,i(new t.Ellipse(r))},t.Ellipse.fromObject=function(e,i){t.Object._fromObject("Ellipse",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend;t.Rect?t.warn("fabric.Rect is already defined"):(t.Rect=t.util.createClass(t.Object,{stateProperties:t.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:t.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(e){this.callSuper("initialize",e),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(e){var t=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,r=this.width,n=this.height,o=-this.width/2,s=-this.height/2,a=0!==t||0!==i,l=.4477152502;e.beginPath(),e.moveTo(o+t,s),e.lineTo(o+r-t,s),a&&e.bezierCurveTo(o+r-l*t,s,o+r,s+l*i,o+r,s+i),e.lineTo(o+r,s+n-i),a&&e.bezierCurveTo(o+r,s+n-l*i,o+r-l*t,s+n,o+r-t,s+n),e.lineTo(o+t,s+n),a&&e.bezierCurveTo(o+l*t,s+n,o,s+n-l*i,o,s+n-i),e.lineTo(o,s+i),a&&e.bezierCurveTo(o,s+l*i,o+l*t,s,o+t,s),e.closePath(),this._renderPaintInOrder(e)},toObject:function(e){return this.callSuper("toObject",["rx","ry"].concat(e))},_toSVG:function(){return["\n']}}),t.Rect.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),t.Rect.fromElement=function(e,r,n){if(!e)return r(null);n=n||{};var o=t.parseAttributes(e,t.Rect.ATTRIBUTE_NAMES);o.left=o.left||0,o.top=o.top||0,o.height=o.height||0,o.width=o.width||0;var s=new t.Rect(i(n?t.util.object.clone(n):{},o));s.visible=s.visible&&s.width>0&&s.height>0,r(s)},t.Rect.fromObject=function(e,i){return t.Object._fromObject("Rect",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend,r=t.util.array.min,n=t.util.array.max,o=t.util.toFixed,s=t.util.projectStrokeOnPoints;t.Polyline?t.warn("fabric.Polyline is already defined"):(t.Polyline=t.util.createClass(t.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:t.Object.prototype.cacheProperties.concat("points"),initialize:function(e,t){t=t||{},this.points=e||[],this.callSuper("initialize",t),this._setPositionDimensions(t)},_projectStrokeOnPoints:function(){return s(this.points,this,!0)},_setPositionDimensions:function(e){var t,i=this._calcDimensions(e),r=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-r,this.height=i.height-r,e.fromSVG||(t=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+r/2,y:i.top-this.strokeWidth/2+r/2},"left","top",this.originX,this.originY)),void 0===e.left&&(this.left=e.fromSVG?i.left:t.x),void 0===e.top&&(this.top=e.fromSVG?i.top:t.y),this.pathOffset={x:i.left+this.width/2+r/2,y:i.top+this.height/2+r/2}},_calcDimensions:function(){var e=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,t=r(e,"x")||0,i=r(e,"y")||0;return{left:t,top:i,width:(n(e,"x")||0)-t,height:(n(e,"y")||0)-i}},toObject:function(e){return i(this.callSuper("toObject",e),{points:this.points.concat()})},_toSVG:function(){for(var e=[],i=this.pathOffset.x,r=this.pathOffset.y,n=t.Object.NUM_FRACTION_DIGITS,s=0,a=this.points.length;s\n']},commonRender:function(e){var t,i=this.points.length,r=this.pathOffset.x,n=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;e.beginPath(),e.moveTo(this.points[0].x-r,this.points[0].y-n);for(var o=0;o"},toObject:function(e){return n(this.callSuper("toObject",e),{path:this.path.map((function(e){return e.slice()}))})},toDatalessObject:function(e){var t=this.toObject(["sourcePath"].concat(e));return t.sourcePath&&delete t.path,t},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var e=t.Object.NUM_FRACTION_DIGITS;return" translate("+s(-this.pathOffset.x,e)+", "+s(-this.pathOffset.y,e)+")"},toClipPathSVG:function(e){var t=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:e,additionalTransform:t})},toSVG:function(e){var t=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:e,additionalTransform:t})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var e,n,o=[],s=[],a=0,l=0,h=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(e){var i=!!this.group;return this._restoreObjectsState(),t.util.resetObjectTransform(this),e&&(i&&t.util.removeTransformFromObject(e,this.group.calcTransformMatrix()),this._objects.push(e),e.group=this,e._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(e){return this._restoreObjectsState(),t.util.resetObjectTransform(this),this.remove(e),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(e){this.dirty=!0,e.group=this,e._set("canvas",this.canvas)},_onObjectRemoved:function(e){this.dirty=!0,delete e.group},_set:function(e,i){var r=this._objects.length;if(this.useSetOnGroup)for(;r--;)this._objects[r].setOnGroup(e,i);if("canvas"===e)for(;r--;)this._objects[r]._set(e,i);t.Object.prototype._set.call(this,e,i)},toObject:function(e){var i=this.includeDefaultValues,r=this._objects.filter((function(e){return!e.excludeFromExport})).map((function(t){var r=t.includeDefaultValues;t.includeDefaultValues=i;var n=t.toObject(e);return t.includeDefaultValues=r,n})),n=t.Object.prototype.toObject.call(this,e);return n.objects=r,n},toDatalessObject:function(e){var i,r=this.sourcePath;if(r)i=r;else{var n=this.includeDefaultValues;i=this._objects.map((function(t){var i=t.includeDefaultValues;t.includeDefaultValues=n;var r=t.toDatalessObject(e);return t.includeDefaultValues=i,r}))}var o=t.Object.prototype.toDatalessObject.call(this,e);return o.objects=i,o},render:function(e){this._transformDone=!0,this.callSuper("render",e),this._transformDone=!1},shouldCache:function(){var e=t.Object.prototype.shouldCache.call(this);if(e)for(var i=0,r=this._objects.length;i\n"],i=0,r=this._objects.length;i\n"),t},getSvgStyles:function(){var e=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",t=this.visible?"":" visibility: hidden;";return[e,this.getSvgFilter(),t].join("")},toClipPathSVG:function(e){for(var t=[],i=0,r=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(e,t,i){e.save(),e.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",e,t),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var r=0,n=this._objects.length;r\n','\t\n',"\n"),s=' clip-path="url(#imageCrop_'+l+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var h=this.fill;this.fill=null,e=["\t\n'],this.fill=h}return"fill"!==this.paintFirst?t.concat(e,i):t.concat(i,e)},getSrc:function(e){var t=e?this._element:this._originalElement;return t?t.toDataURL?t.toDataURL():this.srcFromAttribute?t.getAttribute("src"):t.src:this.src||""},setSrc:function(e,t,i){return T.util.loadImage(e,(function(e,r){this.setElement(e,i),this._setWidthHeight(),t&&t(this,r)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var e=this.resizeFilter,t=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),r=i.scaleX,n=i.scaleY,o=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!e||r>t&&n>t)return this._element=o,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=n);T.filterBackend||(T.filterBackend=T.initFilterBackend());var s=T.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,l=o.width,h=o.height;s.width=l,s.height=h,this._element=s,this._lastScaleX=e.scaleX=r,this._lastScaleY=e.scaleY=n,T.filterBackend.applyFilters([e],o,l,h,this._element,a),this._filterScalingX=s.width/this._originalElement.width,this._filterScalingY=s.height/this._originalElement.height},applyFilters:function(e){if(e=(e=e||this.filters||[]).filter((function(e){return e&&!e.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===e.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var t=this._originalElement,i=t.naturalWidth||t.width,r=t.naturalHeight||t.height;if(this._element===this._originalElement){var n=T.util.createCanvasElement();n.width=i,n.height=r,this._element=n,this._filteredEl=n}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,r),this._lastScaleX=1,this._lastScaleY=1;return T.filterBackend||(T.filterBackend=T.initFilterBackend()),T.filterBackend.applyFilters(e,this._originalElement,i,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(e){T.util.setImageSmoothing(e,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(e),this._renderPaintInOrder(e)},drawCacheOnCanvas:function(e){T.util.setImageSmoothing(e,this.imageSmoothing),T.Object.prototype.drawCacheOnCanvas.call(this,e)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(e){var t=this._element;if(t){var i=this._filterScalingX,r=this._filterScalingY,n=this.width,o=this.height,s=Math.min,a=Math.max,l=a(this.cropX,0),h=a(this.cropY,0),c=t.naturalWidth||t.width,u=t.naturalHeight||t.height,d=l*i,f=h*r,g=s(n*i,c-d),_=s(o*r,u-f),p=-n/2,m=-o/2,v=s(n,c/i-l),y=s(o,u/r-h);t&&e.drawImage(t,d,f,g,_,p,m,v,y)}},_needsResize:function(){var e=this.getTotalObjectScaling();return e.scaleX!==this._lastScaleX||e.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(e,t){this.setElement(T.util.getById(e),t),T.util.addClass(this.getElement(),T.Image.CSS_CANVAS)},_initConfig:function(e){e||(e={}),this.setOptions(e),this._setWidthHeight(e)},_initFilters:function(e,t){e&&e.length?T.util.enlivenObjects(e,(function(e){t&&t(e)}),"fabric.Image.filters"):t&&t()},_setWidthHeight:function(e){e||(e={});var t=this.getElement();this.width=e.width||t.naturalWidth||t.width||0,this.height=e.height||t.naturalHeight||t.height||0},parsePreserveAspectRatioAttribute:function(){var e,t=T.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,r=this._element.height,n=1,o=1,s=0,a=0,l=0,h=0,c=this.width,u=this.height,d={width:c,height:u};return!t||"none"===t.alignX&&"none"===t.alignY?(n=c/i,o=u/r):("meet"===t.meetOrSlice&&(e=(c-i*(n=o=T.util.findScaleToFit(this._element,d)))/2,"Min"===t.alignX&&(s=-e),"Max"===t.alignX&&(s=e),e=(u-r*o)/2,"Min"===t.alignY&&(a=-e),"Max"===t.alignY&&(a=e)),"slice"===t.meetOrSlice&&(e=i-c/(n=o=T.util.findScaleToCover(this._element,d)),"Mid"===t.alignX&&(l=e/2),"Max"===t.alignX&&(l=e),e=r-u/o,"Mid"===t.alignY&&(h=e/2),"Max"===t.alignY&&(h=e),i=c/n,r=u/o)),{width:i,height:r,scaleX:n,scaleY:o,offsetLeft:s,offsetTop:a,cropX:l,cropY:h}}}),T.Image.CSS_CANVAS="canvas-img",T.Image.prototype.getSvgSrc=T.Image.prototype.getSrc,T.Image.fromObject=function(e,t){var i=T.util.object.clone(e);T.util.loadImage(i.src,(function(e,r){r?t&&t(null,!0):T.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],T.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],T.util.enlivenObjectEnlivables(i,i,(function(){var r=new T.Image(e,i);t(r,!1)}))}))}))}),null,i.crossOrigin)},T.Image.fromURL=function(e,t,i){T.util.loadImage(e,(function(e,r){t&&t(new T.Image(e,i),r)}),null,i&&i.crossOrigin)},T.Image.ATTRIBUTE_NAMES=T.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),T.Image.fromElement=function(e,i,r){var n=T.parseAttributes(e,T.Image.ATTRIBUTE_NAMES);T.Image.fromURL(n["xlink:href"],i,t(r?T.util.object.clone(r):{},n))})}(t),T.util.object.extend(T.Object.prototype,{_getAngleValueForStraighten:function(){var e=this.angle%360;return e>0?90*Math.round((e-1)/90):90*Math.round(e/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(e){var t=function(){},i=(e=e||{}).onComplete||t,r=e.onChange||t,n=this;return T.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(e){n.rotate(e),r()},onComplete:function(){n.setCoords(),i()}})}}),T.util.object.extend(T.StaticCanvas.prototype,{straightenObject:function(e){return e.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(e){return e.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function e(e,t){var i="precision "+t+" float;\nvoid main(){}",r=e.createShader(e.FRAGMENT_SHADER);return e.shaderSource(r,i),e.compileShader(r),!!e.getShaderParameter(r,e.COMPILE_STATUS)}function t(e){e&&e.tileSize&&(this.tileSize=e.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}T.isWebglSupported=function(t){if(T.isLikelyNode)return!1;t=t||T.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),n=!1;if(r){T.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),n=T.maxTextureSize>=t;for(var o=["highp","mediump","lowp"],s=0;s<3;s++)if(e(r,o[s])){T.webGlPrecision=o[s];break}}return this.isSupported=n,n},T.WebglFilterBackend=t,t.prototype={tileSize:2048,resources:{},setupGLContext:function(e,t){this.dispose(),this.createWebGLCanvas(e,t),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(e,t)},chooseFastestCopyGLTo2DMethod:function(e,t){var i,r=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(e){i=!1}var n="undefined"!=typeof ArrayBuffer,o="undefined"!=typeof Uint8ClampedArray;if(r&&i&&n&&o){var s=T.util.createCanvasElement(),a=new ArrayBuffer(e*t*4);if(T.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=A);var l,h,c={imageBuffer:a,destinationWidth:e,destinationHeight:t,targetCanvas:s};s.width=e,s.height=t,l=window.performance.now(),E.call(c,this.gl,c),h=window.performance.now()-l,l=window.performance.now(),A.call(c,this.gl,c),h>window.performance.now()-l?(this.imageBuffer=a,this.copyGLTo2D=A):this.copyGLTo2D=E}},createWebGLCanvas:function(e,t){var i=T.util.createCanvasElement();i.width=e,i.height=t;var r={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},n=i.getContext("webgl",r);n||(n=i.getContext("experimental-webgl",r)),n&&(n.clearColor(0,0,0,0),this.canvas=i,this.gl=n)},applyFilters:function(e,t,i,r,n,o){var s,a=this.gl;o&&(s=this.getCachedTexture(o,t));var l={originalWidth:t.width||t.originalWidth,originalHeight:t.height||t.originalHeight,sourceWidth:i,sourceHeight:r,destinationWidth:i,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,i,r,!s&&t),targetTexture:this.createTexture(a,i,r),originalTexture:s||this.createTexture(a,i,r,!s&&t),passes:e.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},h=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,h),e.forEach((function(e){e&&e.applyTo(l)})),function(e){var t=e.targetCanvas,i=t.width,r=t.height,n=e.destinationWidth,o=e.destinationHeight;i===n&&r===o||(t.width=n,t.height=o)}(l),this.copyGLTo2D(a,l),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(l.sourceTexture),a.deleteTexture(l.targetTexture),a.deleteFramebuffer(h),n.getContext("2d").setTransform(1,0,0,1,0,0),l},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(e,t,i,r){var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),r?e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r):e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,i,0,e.RGBA,e.UNSIGNED_BYTE,null),n},getCachedTexture:function(e,t){if(this.textureCache[e])return this.textureCache[e];var i=this.createTexture(this.gl,t.width,t.height,t);return this.textureCache[e]=i,i},evictCachesForKey:function(e){this.textureCache[e]&&(this.gl.deleteTexture(this.textureCache[e]),delete this.textureCache[e])},copyGLTo2D:E,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var e=this.gl,t={renderer:"",vendor:""};if(!e)return t;var i=e.getExtension("WEBGL_debug_renderer_info");if(i){var r=e.getParameter(i.UNMASKED_RENDERER_WEBGL),n=e.getParameter(i.UNMASKED_VENDOR_WEBGL);r&&(t.renderer=r.toLowerCase()),n&&(t.vendor=n.toLowerCase())}return this.gpuInfo=t,t}}}(),function(){var e=function(){};function t(){}T.Canvas2dFilterBackend=t,t.prototype={evictCachesForKey:e,dispose:e,clearWebGLCaches:e,resources:{},applyFilters:function(e,t,i,r,n){var o=n.getContext("2d");o.drawImage(t,0,0,i,r);var s={sourceWidth:i,sourceHeight:r,imageData:o.getImageData(0,0,i,r),originalEl:t,originalImageData:o.getImageData(0,0,i,r),canvasEl:n,ctx:o,filterBackend:this};return e.forEach((function(e){e.applyTo(s)})),s.imageData.width===i&&s.imageData.height===r||(n.width=s.imageData.width,n.height=s.imageData.height),o.putImageData(s.imageData,0,0),s}}}(),T.Image=T.Image||{},T.Image.filters=T.Image.filters||{},T.Image.filters.BaseFilter=T.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(e){e&&this.setOptions(e)},setOptions:function(e){for(var t in e)this[t]=e[t]},createProgram:function(e,t,i){t=t||this.fragmentSource,i=i||this.vertexSource,"highp"!==T.webGlPrecision&&(t=t.replace(/precision highp float/g,"precision "+T.webGlPrecision+" float"));var r=e.createShader(e.VERTEX_SHADER);if(e.shaderSource(r,i),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+e.getShaderInfoLog(r));var n=e.createShader(e.FRAGMENT_SHADER);if(e.shaderSource(n,t),e.compileShader(n),!e.getShaderParameter(n,e.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+e.getShaderInfoLog(n));var o=e.createProgram();if(e.attachShader(o,r),e.attachShader(o,n),e.linkProgram(o),!e.getProgramParameter(o,e.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+e.getProgramInfoLog(o));var s=this.getAttributeLocations(e,o),a=this.getUniformLocations(e,o)||{};return a.uStepW=e.getUniformLocation(o,"uStepW"),a.uStepH=e.getUniformLocation(o,"uStepH"),{program:o,attributeLocations:s,uniformLocations:a}},getAttributeLocations:function(e,t){return{aPosition:e.getAttribLocation(t,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(e,t,i){var r=t.aPosition,n=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,n),e.enableVertexAttribArray(r),e.vertexAttribPointer(r,2,e.FLOAT,!1,0,0),e.bufferData(e.ARRAY_BUFFER,i,e.STATIC_DRAW)},_setupFrameBuffer:function(e){var t,i,r=e.context;e.passes>1?(t=e.destinationWidth,i=e.destinationHeight,e.sourceWidth===t&&e.sourceHeight===i||(r.deleteTexture(e.targetTexture),e.targetTexture=e.filterBackend.createTexture(r,t,i)),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e.targetTexture,0)):(r.bindFramebuffer(r.FRAMEBUFFER,null),r.finish())},_swapTextures:function(e){e.passes--,e.pass++;var t=e.targetTexture;e.targetTexture=e.sourceTexture,e.sourceTexture=t},isNeutralState:function(){var e=this.mainParameter,t=T.Image.filters[this.type].prototype;if(e){if(Array.isArray(t[e])){for(var i=t[e].length;i--;)if(this[e][i]!==t[e][i])return!1;return!0}return t[e]===this[e]}return!1},applyTo:function(e){e.webgl?(this._setupFrameBuffer(e),this.applyToWebGL(e),this._swapTextures(e)):this.applyTo2d(e)},retrieveShader:function(e){return e.programCache.hasOwnProperty(this.type)||(e.programCache[this.type]=this.createProgram(e.context)),e.programCache[this.type]},applyToWebGL:function(e){var t=e.context,i=this.retrieveShader(e);0===e.pass&&e.originalTexture?t.bindTexture(t.TEXTURE_2D,e.originalTexture):t.bindTexture(t.TEXTURE_2D,e.sourceTexture),t.useProgram(i.program),this.sendAttributeData(t,i.attributeLocations,e.aPosition),t.uniform1f(i.uniformLocations.uStepW,1/e.sourceWidth),t.uniform1f(i.uniformLocations.uStepH,1/e.sourceHeight),this.sendUniformData(t,i.uniformLocations),t.viewport(0,0,e.destinationWidth,e.destinationHeight),t.drawArrays(t.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(e,t,i){e.activeTexture(i),e.bindTexture(e.TEXTURE_2D,t),e.activeTexture(e.TEXTURE0)},unbindAdditionalTexture:function(e,t){e.activeTexture(t),e.bindTexture(e.TEXTURE_2D,null),e.activeTexture(e.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(e){this[this.mainParameter]=e},sendUniformData:function(){},createHelpLayer:function(e){if(!e.helpLayer){var t=document.createElement("canvas");t.width=e.sourceWidth,t.height=e.sourceHeight,e.helpLayer=t}},toObject:function(){var e={type:this.type},t=this.mainParameter;return t&&(e[t]=this[t]),e},toJSON:function(){return this.toObject()}}),T.Image.filters.BaseFilter.fromObject=function(e,t){var i=new T.Image.filters[e.type](e);return t&&t(i),i},function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.ColorMatrix=r(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(e){this.callSuper("initialize",e),this.matrix=this.matrix.slice(0)},applyTo2d:function(e){var t,i,r,n,o,s=e.imageData.data,a=s.length,l=this.matrix,h=this.colorsOnly;for(o=0;o=S||s<0||s>=y||(l=4*(a*y+s),h=p[f*m+d],t+=_[l]*h,i+=_[l+1]*h,r+=_[l+2]*h,w||(n+=_[l+3]*h));C[o]=t,C[o+1]=i,C[o+2]=r,C[o+3]=w?_[o+3]:n}e.imageData=b},getUniformLocations:function(e,t){return{uMatrix:e.getUniformLocation(t,"uMatrix"),uOpaque:e.getUniformLocation(t,"uOpaque"),uHalfSize:e.getUniformLocation(t,"uHalfSize"),uSize:e.getUniformLocation(t,"uSize")}},sendUniformData:function(e,t){e.uniform1fv(t.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),t.Image.filters.Convolute.fromObject=t.Image.filters.BaseFilter.fromObject}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.Grayscale=r(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(e){var t,i,r=e.imageData.data,n=r.length,o=this.mode;for(t=0;th[0]&&n>h[1]&&o>h[2]&&r 0.0) {\n"+this.fragmentSource[e]+"}\n}"},retrieveShader:function(e){var t,i=this.type+"_"+this.mode;return e.programCache.hasOwnProperty(i)||(t=this.buildSource(this.mode),e.programCache[i]=this.createProgram(e.context,t)),e.programCache[i]},applyTo2d:function(e){var i,r,n,o,s,a,l,h=e.imageData.data,c=h.length,u=1-this.alpha;i=(l=new t.Color(this.color).getSource())[0]*this.alpha,r=l[1]*this.alpha,n=l[2]*this.alpha;for(var d=0;d=e||t<=-e)return 0;if(t<1.1920929e-7&&t>-1.1920929e-7)return 1;var i=(t*=Math.PI)/e;return a(t)/t*a(i)/i}},applyTo2d:function(e){var t=e.imageData,i=this.scaleX,r=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/r;var n,o=t.width,a=t.height,l=s(o*i),h=s(a*r);"sliceHack"===this.resizeType?n=this.sliceByTwo(e,o,a,l,h):"hermite"===this.resizeType?n=this.hermiteFastResize(e,o,a,l,h):"bilinear"===this.resizeType?n=this.bilinearFiltering(e,o,a,l,h):"lanczos"===this.resizeType&&(n=this.lanczosResize(e,o,a,l,h)),e.imageData=n},sliceByTwo:function(e,i,n,o,s){var a,l,h=e.imageData,c=.5,u=!1,d=!1,f=i*c,g=n*c,_=t.filterBackend.resources,p=0,m=0,v=i,y=0;for(_.sliceByTwo||(_.sliceByTwo=document.createElement("canvas")),((a=_.sliceByTwo).width<1.5*i||a.height=t)){M=r(1e3*o(T-b.x)),S[M]||(S[M]={});for(var P=C.y-y;P<=C.y+y;P++)P<0||P>=s||(L=r(1e3*o(P-b.y)),S[M][L]||(S[M][L]=f(n(i(M*p,2)+i(L*m,2))/1e3)),(x=S[M][L])>0&&(A+=x,I+=x*c[E=4*(P*t+T)],O+=x*c[E+1],R+=x*c[E+2],D+=x*c[E+3]))}d[E=4*(w*a+l)]=I/A,d[E+1]=O/A,d[E+2]=R/A,d[E+3]=D/A}return++l1&&L<-1||(y=2*L*L*L-3*L*L+1)>0&&(x+=y*f[3+(M=4*(D+A*t))],b+=y,f[M+3]<255&&(y=y*f[M+3]/250),C+=y*f[M],w+=y*f[M+1],T+=y*f[M+2],S+=y)}_[v]=C/S,_[v+1]=w/S,_[v+2]=T/S,_[v+3]=x/b}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),t.Image.filters.Resize.fromObject=t.Image.filters.BaseFilter.fromObject}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.Contrast=r(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(e){if(0!==this.contrast){var t,i=e.imageData.data,r=i.length,n=Math.floor(255*this.contrast),o=259*(n+255)/(255*(259-n));for(t=0;t1&&(t=1/this.aspectRatio):this.aspectRatio<1&&(t=this.aspectRatio),e=t*this.blur*.12,this.horizontal?i[0]=e:i[1]=e,i}}),i.Blur.fromObject=t.Image.filters.BaseFilter.fromObject}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.Gamma=r(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(e){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,e)},applyTo2d:function(e){var t,i=e.imageData.data,r=this.gamma,n=i.length,o=1/r[0],s=1/r[1],a=1/r[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),t=0,n=256;t'},_getCacheCanvasDimensions:function(){var e=this.callSuper("_getCacheCanvasDimensions"),t=this.fontSize;return e.width+=t*e.zoomX,e.height+=t*e.zoomY,e},_render:function(e){var t=this.path;t&&!t.isNotVisible()&&t._render(e),this._setTextStyles(e),this._renderTextLinesBackground(e),this._renderTextDecoration(e,"underline"),this._renderText(e),this._renderTextDecoration(e,"overline"),this._renderTextDecoration(e,"linethrough")},_renderText:function(e){"stroke"===this.paintFirst?(this._renderTextStroke(e),this._renderTextFill(e)):(this._renderTextFill(e),this._renderTextStroke(e))},_setTextStyles:function(e,t,i){if(e.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":e.textBaseline="middle";break;case"ascender":e.textBaseline="top";break;case"descender":e.textBaseline="bottom"}e.font=this._getFontDeclaration(t,i)},calcTextWidth:function(){for(var e=this.getLineWidth(0),t=1,i=this._textLines.length;te&&(e=r)}return e},_renderTextLine:function(e,t,i,r,n,o){this._renderChars(e,t,i,r,n,o)},_renderTextLinesBackground:function(e){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var t,i,r,n,o,s,a,l=e.fillStyle,h=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,_=this._textLines.length;g<_;g++)if(t=this.getHeightOfLine(g),this.textBackgroundColor||this.styleHas("textBackgroundColor",g)){r=this._textLines[g],i=this._getLineLeftOffset(g),d=0,u=0,n=this.getValueOfPropertyAt(g,0,"textBackgroundColor");for(var p=0,m=r.length;p=0:ia?u%=a:u<0&&(u+=a),this._setGraphemeOnPath(u,o,s),u+=o.kernedWidth}return{width:l,numOfSpaces:0}},_setGraphemeOnPath:function(e,i,r){var n=e+i.kernedWidth/2,o=this.path,s=t.util.getPointOnPath(o.path,n,o.segmentsInfo);i.renderLeft=s.x-r.x,i.renderTop=s.y-r.y,i.angle=s.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(e,t,i,r,n){var o,s=this.getCompleteStyleDeclaration(t,i),a=r?this.getCompleteStyleDeclaration(t,i-1):{},l=this._measureChar(e,s,r,a),h=l.kernedWidth,c=l.width;0!==this.charSpacing&&(c+=o=this._getWidthOfCharSpacing(),h+=o);var u={width:c,left:0,height:s.fontSize,kernedWidth:h,deltaY:s.deltaY};if(i>0&&!n){var d=this.__charBounds[t][i-1];u.left=d.left+d.width+l.kernedWidth-l.width}return u},getHeightOfLine:function(e){if(this.__lineHeights[e])return this.__lineHeights[e];for(var t=this._textLines[e],i=this.getHeightOfChar(e,0),r=1,n=t.length;r0){var A=v+o+u;"rtl"===this.direction&&(A=this.width-A-d),h&&m&&(e.fillStyle=m,e.fillRect(A,c+C*r+s,d,this.fontSize/15)),u=f.left,d=f.width,h=g,m=p,r=n,s=a}else d+=f.kernedWidth;A=v+o+u,"rtl"===this.direction&&(A=this.width-A-d),e.fillStyle=p,g&&p&&e.fillRect(A,c+C*r+s,d-b,this.fontSize/15),y+=i}else y+=i;this._removeShadow(e)}},_getFontDeclaration:function(e,i){var r=e||this,n=this.fontFamily,o=t.Text.genericFonts.indexOf(n.toLowerCase())>-1,s=void 0===n||n.indexOf("'")>-1||n.indexOf(",")>-1||n.indexOf('"')>-1||o?r.fontFamily:'"'+r.fontFamily+'"';return[t.isLikelyNode?r.fontWeight:r.fontStyle,t.isLikelyNode?r.fontStyle:r.fontWeight,i?this.CACHE_FONT_SIZE+"px":r.fontSize+"px",s].join(" ")},render:function(e){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",e)))},_splitTextIntoLines:function(e){for(var i=e.split(this._reNewline),r=new Array(i.length),n=["\n"],o=[],s=0;s-1&&(e.underline=!0),e.textDecoration.indexOf("line-through")>-1&&(e.linethrough=!0),e.textDecoration.indexOf("overline")>-1&&(e.overline=!0),delete e.textDecoration)}T.IText=T.util.createClass(T.Text,T.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(e,t){this.callSuper("initialize",e,t),this.initBehavior()},setSelectionStart:function(e){e=Math.max(e,0),this._updateAndFire("selectionStart",e)},setSelectionEnd:function(e){e=Math.min(e,this.text.length),this._updateAndFire("selectionEnd",e)},_updateAndFire:function(e,t){this[e]!==t&&(this._fireSelectionChanged(),this[e]=t),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(e){this.clearContextTop(),this.callSuper("render",e),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(e){this.callSuper("_render",e)},clearContextTop:function(e){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this.canvas.contextTop,i=this.canvas.viewportTransform;t.save(),t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(t),this._clearTextArea(t),e||t.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this._getCursorBoundaries(),t=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(e,t):this.renderSelection(e,t),t.restore()}},_clearTextArea:function(e){var t=this.width+4,i=this.height+4;e.clearRect(-t/2,-i/2,t,i)},_getCursorBoundaries:function(e){void 0===e&&(e=this.selectionStart);var t=this._getLeftOffset(),i=this._getTopOffset(),r=this._getCursorBoundariesOffsets(e);return{left:t,top:i,leftOffset:r.left,topOffset:r.top}},_getCursorBoundariesOffsets:function(e){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var t,i,r,n,o=0,s=0,a=this.get2DCursorLocation(e);r=a.charIndex,i=a.lineIndex;for(var l=0;l0?s:0)},"rtl"===this.direction&&(n.left*=-1),this.cursorOffsetCache=n,this.cursorOffsetCache},renderCursor:function(e,t){var i=this.get2DCursorLocation(),r=i.lineIndex,n=i.charIndex>0?i.charIndex-1:0,o=this.getValueOfPropertyAt(r,n,"fontSize"),s=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/s,l=e.topOffset,h=this.getValueOfPropertyAt(r,n,"deltaY");l+=(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-o*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(e,t),t.fillStyle=this.cursorColor||this.getValueOfPropertyAt(r,n,"fill"),t.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,t.fillRect(e.left+e.leftOffset-a/2,l+e.top+h,a,o)},renderSelection:function(e,t){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,r=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,n=-1!==this.textAlign.indexOf("justify"),o=this.get2DCursorLocation(i),s=this.get2DCursorLocation(r),a=o.lineIndex,l=s.lineIndex,h=o.charIndex<0?0:o.charIndex,c=s.charIndex<0?0:s.charIndex,u=a;u<=l;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),_=0,p=0;if(u===a&&(_=this.__charBounds[a][h].left),u>=a&&u1)&&(g/=this.lineHeight);var v=e.left+f+_,y=p-_,S=g,b=0;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",S=1,b=g):t.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),t.fillRect(v,e.top+e.topOffset+b,y,S),e.topOffset+=d}},getCurrentCharFontSize:function(){var e=this._getCurrentCharIndex();return this.getValueOfPropertyAt(e.l,e.c,"fontSize")},getCurrentCharColor:function(){var e=this._getCurrentCharIndex();return this.getValueOfPropertyAt(e.l,e.c,"fill")},_getCurrentCharIndex:function(){var e=this.get2DCursorLocation(this.selectionStart,!0),t=e.charIndex>0?e.charIndex-1:0;return{l:e.lineIndex,c:t}}}),T.IText.fromObject=function(t,i){if(e(t),t.styles)for(var r in t.styles)for(var n in t.styles[r])e(t.styles[r][n]);T.Object._fromObject("IText",t,i,"text")}}(),w=T.util.object.clone,T.util.object.extend(T.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var e=this;this.on("added",(function(){var t=e.canvas;t&&(t._hasITextHandlers||(t._hasITextHandlers=!0,e._initCanvasHandlers(t)),t._iTextInstances=t._iTextInstances||[],t._iTextInstances.push(e))}))},initRemovedHandler:function(){var e=this;this.on("removed",(function(){var t=e.canvas;t&&(t._iTextInstances=t._iTextInstances||[],T.util.removeFromArray(t._iTextInstances,e),0===t._iTextInstances.length&&(t._hasITextHandlers=!1,e._removeCanvasHandlers(t)))}))},_initCanvasHandlers:function(e){e._mouseUpITextHandler=function(){e._iTextInstances&&e._iTextInstances.forEach((function(e){e.__isMousedown=!1}))},e.on("mouse:up",e._mouseUpITextHandler)},_removeCanvasHandlers:function(e){e.off("mouse:up",e._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(e,t,i,r){var n;return n={isAborted:!1,abort:function(){this.isAborted=!0}},e.animate("_currentCursorOpacity",t,{duration:i,onComplete:function(){n.isAborted||e[r]()},onChange:function(){e.canvas&&e.selectionStart===e.selectionEnd&&e.renderCursorOrSelection()},abort:function(){return n.isAborted}}),n},_onTickComplete:function(){var e=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){e._currentTickCompleteState=e._animateCursor(e,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(e){var t=this,i=e?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){t._tick()}),i)},abortCursorAnimation:function(){var e=this._currentTickState||this._currentTickCompleteState,t=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,e&&t&&t.clearContext(t.contextTop||t.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(e){var t=0,i=e-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)t++,i--;for(;/\S/.test(this._text[i])&&i>-1;)t++,i--;return e-t},findWordBoundaryRight:function(e){var t=0,i=e;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)t++,i++;for(;/\S/.test(this._text[i])&&i-1;)t++,i--;return e-t},findLineBoundaryRight:function(e){for(var t=0,i=e;!/\n/.test(this._text[i])&&i0&&rthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=t):(this.selectionStart=t,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===r||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(e,t,i){var r=i.slice(0,e),n=T.util.string.graphemeSplit(r).length;if(e===t)return{selectionStart:n,selectionEnd:n};var o=i.slice(e,t);return{selectionStart:n,selectionEnd:n+T.util.string.graphemeSplit(o).length}},fromGraphemeToStringSelection:function(e,t,i){var r=i.slice(0,e).join("").length;return e===t?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+i.slice(e,t).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var e=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=e.selectionStart,this.hiddenTextarea.selectionEnd=e.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var e=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=e.selectionEnd,this.inCompositionMode||(this.selectionStart=e.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var e=this._calcTextareaPosition();this.hiddenTextarea.style.left=e.left,this.hiddenTextarea.style.top=e.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var e=this.inCompositionMode?this.compositionStart:this.selectionStart,t=this._getCursorBoundaries(e),i=this.get2DCursorLocation(e),r=i.lineIndex,n=i.charIndex,o=this.getValueOfPropertyAt(r,n,"fontSize")*this.lineHeight,s=t.leftOffset,a=this.calcTransformMatrix(),l={x:t.left+s,y:t.top+t.topOffset+o},h=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/h,d=c.height/h,f=u-o,g=d-o,_=c.clientWidth/u,p=c.clientHeight/d;return l=T.util.transformPoint(l,a),(l=T.util.transformPoint(l,this.canvas.viewportTransform)).x*=_,l.y*=p,l.x<0&&(l.x=0),l.x>f&&(l.x=f),l.y<0&&(l.y=0),l.y>g&&(l.y=g),l.x+=this.canvas._offset.left,l.y+=this.canvas._offset.top,{left:l.x+"px",top:l.y+"px",fontSize:o+"px",charHeight:o}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var e=this._textBeforeEdit!==this.text,t=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,t&&(t.blur&&t.blur(),t.parentNode&&t.parentNode.removeChild(t)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),e&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),e&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var e in this.styles)this._textLines[e]||delete this.styles[e]},removeStyleFromTo:function(e,t){var i,r,n=this.get2DCursorLocation(e,!0),o=this.get2DCursorLocation(t,!0),s=n.lineIndex,a=n.charIndex,l=o.lineIndex,h=o.charIndex;if(s!==l){if(this.styles[s])for(i=a;i=h&&(r[c-d]=r[u],delete r[u])}},shiftLineStyles:function(e,t){var i=w(this.styles);for(var r in this.styles){var n=parseInt(r,10);n>e&&(this.styles[n+t]=i[n],i[n-t]||delete this.styles[n])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(e,t,i,r){var n,o={},s=!1,a=this._unwrappedTextLines[e].length===t;for(var l in i||(i=1),this.shiftLineStyles(e,i),this.styles[e]&&(n=this.styles[e][0===t?t:t-1]),this.styles[e]){var h=parseInt(l,10);h>=t&&(s=!0,o[h-t]=this.styles[e][l],a&&0===t||delete this.styles[e][l])}var c=!1;for(s&&!a&&(this.styles[e+i]=o,c=!0),c&&i--;i>0;)r&&r[i-1]?this.styles[e+i]={0:w(r[i-1])}:n?this.styles[e+i]={0:w(n)}:delete this.styles[e+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(e,t,i,r){this.styles||(this.styles={});var n=this.styles[e],o=n?w(n):{};for(var s in i||(i=1),o){var a=parseInt(s,10);a>=t&&(n[a+i]=o[a],o[a-i]||delete n[a])}if(this._forceClearCache=!0,r)for(;i--;)Object.keys(r[i]).length&&(this.styles[e]||(this.styles[e]={}),this.styles[e][t+i]=w(r[i]));else if(n)for(var l=n[t?t-1:1];l&&i--;)this.styles[e][t+i]=w(l)},insertNewStyleBlock:function(e,t,i){for(var r=this.get2DCursorLocation(t,!0),n=[0],o=0,s=0;s0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,n[0],i),i=i&&i.slice(n[0]+1)),o&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+n[0],o),s=1;s0?this.insertCharStyleObject(r.lineIndex+s,0,n[s],i):i&&this.styles[r.lineIndex+s]&&i[0]&&(this.styles[r.lineIndex+s][0]=i[0]),i=i&&i.slice(n[s]+1);n[s]>0&&this.insertCharStyleObject(r.lineIndex+s,0,n[s],i)},setSelectionStartEndWithShift:function(e,t,i){i<=e?(t===e?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=e),this.selectionStart=i):i>e&&ie?this.selectionStart=e:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>e?this.selectionEnd=e:this.selectionEnd<0&&(this.selectionEnd=0)}}),T.util.object.extend(T.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(e){if(this.canvas){this.__newClickTime=+new Date;var t=e.pointer;this.isTripleClick(t)&&(this.fire("tripleclick",e),this._stopEvent(e.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=t,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(e){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===e.x&&this.__lastPointer.y===e.y},_stopEvent:function(e){e.preventDefault&&e.preventDefault(),e.stopPropagation&&e.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(e){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(e.e))},tripleClickHandler:function(e){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(e.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(e){!this.canvas||!this.editable||e.e.button&&1!==e.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(e.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(e){!this.canvas||!this.editable||e.e.button&&1!==e.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(e){if(this.__isMousedown=!1,!(!this.editable||this.group||e.transform&&e.transform.actionPerformed||e.e.button&&1!==e.e.button)){if(this.canvas){var t=this.canvas._activeObject;if(t&&t!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(e.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(e){var t=this.getSelectionStartFromPointer(e),i=this.selectionStart,r=this.selectionEnd;e.shiftKey?this.setSelectionStartEndWithShift(i,r,t):(this.selectionStart=t,this.selectionEnd=t),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(e){for(var t,i=this.getLocalPointer(e),r=0,n=0,o=0,s=0,a=0,l=0,h=this._textLines.length;l0&&(s+=this._textLines[l-1].length+this.missingNewlineOffset(l-1));n=this._getLineLeftOffset(a)*this.scaleX,t=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+n);for(var c=0,u=t.length;co||s<0?0:1);return this.flipX&&(a=n-a),a>this._text.length&&(a=this._text.length),a}}),T.util.object.extend(T.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=T.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var e=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+e.top+"; left: "+e.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+e.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):T.document.body.appendChild(this.hiddenTextarea),T.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),T.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),T.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),T.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),T.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),T.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(T.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(e){if(this.isEditing){var t="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(e.keyCode in t)this[t[e.keyCode]](e);else{if(!(e.keyCode in this.ctrlKeysMapDown)||!e.ctrlKey&&!e.metaKey)return;this[this.ctrlKeysMapDown[e.keyCode]](e)}e.stopImmediatePropagation(),e.preventDefault(),e.keyCode>=33&&e.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(e){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:e.keyCode in this.ctrlKeysMapUp&&(e.ctrlKey||e.metaKey)&&(this[this.ctrlKeysMapUp[e.keyCode]](e),e.stopImmediatePropagation(),e.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(e){var t=this.fromPaste;if(this.fromPaste=!1,e&&e.stopPropagation(),this.isEditing){var i,r,n,o,s,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,l=this._text.length,h=a.length,c=h-l,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),_=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):h0&&(r+=(i=this.__charBounds[e][t-1]).left+i.width),r},getDownCursorOffset:function(e,t){var i=this._getSelectionForOffset(e,t),r=this.get2DCursorLocation(i),n=r.lineIndex;if(n===this._textLines.length-1||e.metaKey||34===e.keyCode)return this._text.length-i;var o=r.charIndex,s=this._getWidthBeforeCursor(n,o),a=this._getIndexOnLine(n+1,s);return this._textLines[n].slice(o).length+a+1+this.missingNewlineOffset(n)},_getSelectionForOffset:function(e,t){return e.shiftKey&&this.selectionStart!==this.selectionEnd&&t?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(e,t){var i=this._getSelectionForOffset(e,t),r=this.get2DCursorLocation(i),n=r.lineIndex;if(0===n||e.metaKey||33===e.keyCode)return-i;var o=r.charIndex,s=this._getWidthBeforeCursor(n,o),a=this._getIndexOnLine(n-1,s),l=this._textLines[n].slice(0,o),h=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-l.length+(1-h)},_getIndexOnLine:function(e,t){for(var i,r,n=this._textLines[e],o=this._getLineLeftOffset(e),s=0,a=0,l=n.length;at){r=!0;var h=o-i,c=o,u=Math.abs(h-t);s=Math.abs(c-t)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",e)},moveCursorUp:function(e){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",e)},_moveCursorUpOrDown:function(e,t){var i=this["get"+e+"CursorOffset"](t,"right"===this._selectionDirection);t.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(e){var t="left"===this._selectionDirection?this.selectionStart+e:this.selectionEnd+e;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,t),0!==e},moveCursorWithoutShift:function(e){return e<0?(this.selectionStart+=e,this.selectionEnd=this.selectionStart):(this.selectionEnd+=e,this.selectionStart=this.selectionEnd),0!==e},moveCursorLeft:function(e){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",e)},_move:function(e,t,i){var r;if(e.altKey)r=this["findWordBoundary"+i](this[t]);else{if(!e.metaKey&&35!==e.keyCode&&36!==e.keyCode)return this[t]+="Left"===i?-1:1,!0;r=this["findLineBoundary"+i](this[t])}if(void 0!==typeof r&&this[t]!==r)return this[t]=r,!0},_moveLeft:function(e,t){return this._move(e,t,"Left")},_moveRight:function(e,t){return this._move(e,t,"Right")},moveCursorLeftWithoutShift:function(e){var t=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(t=this._moveLeft(e,"selectionStart")),this.selectionEnd=this.selectionStart,t},moveCursorLeftWithShift:function(e){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(e,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(e,"selectionStart")):void 0},moveCursorRight:function(e){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",e)},_moveCursorLeftOrRight:function(e,t){var i="moveCursor"+e+"With";this._currentCursorOpacity=1,t.shiftKey?i+="Shift":i+="outShift",this[i](t)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(e){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(e,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(e,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(e){var t=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(t=this._moveRight(e,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,t},removeChars:function(e,t){void 0===t&&(t=e+1),this.removeStyleFromTo(e,t),this._text.splice(e,t-e),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(e,t,i,r){void 0===r&&(r=i),r>i&&this.removeStyleFromTo(i,r);var n=T.util.string.graphemeSplit(e);this.insertNewStyleBlock(n,i,t),this._text=[].concat(this._text.slice(0,i),n,this._text.slice(r)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var e=T.util.toFixed,t=/ +/g;T.util.object.extend(T.Text.prototype,{_toSVG:function(){var e=this._getSVGLeftTopOffsets(),t=this._getSVGTextAndBg(e.textTop,e.textLeft);return this._wrapSVGTextAndBg(t)},toSVG:function(e){return this._createBaseSVGMarkup(this._toSVG(),{reviver:e,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(e){var t=this.getSvgTextDecoration(this);return[e.textBgRects.join(""),'\t\t",e.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(e,t){var i,r=[],n=[],o=e;this._setSVGBg(n);for(var s=0,a=this._textLines.length;s",T.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(e,t,i,r){var n,o,s,a,l,h=this.getHeightOfLine(t),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[t];r+=h*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,_=f.length-1;g<=_;g++)l=g===_||this.charSpacing,u+=f[g],s=this.__charBounds[t][g],0===d?(i+=s.kernedWidth-s.width,d+=s.width):d+=s.kernedWidth,c&&!l&&this._reSpaceAndTab.test(f[g])&&(l=!0),l||(n=n||this.getCompleteStyleDeclaration(t,g),o=this.getCompleteStyleDeclaration(t,g+1),l=this._hasStyleChangedForSvg(n,o)),l&&(a=this._getStyleDeclaration(t,g)||{},e.push(this._createTextCharSpan(u,a,i,r)),u="",n=o,i+=d,d=0)},_pushTextBgRect:function(t,i,r,n,o,s){var a=T.Object.NUM_FRACTION_DIGITS;t.push("\t\t\n')},_setSVGTextLineBg:function(e,t,i,r){for(var n,o,s=this._textLines[t],a=this.getHeightOfLine(t)/this.lineHeight,l=0,h=0,c=this.getValueOfPropertyAt(t,0,"textBackgroundColor"),u=0,d=s.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(e){for(var t=0,i=0,r=0,n={},o=0;o0?(i=0,r++,t++):!this.splitByGrapheme&&this._reSpaceAndTab.test(e.graphemeText[r])&&o>0&&(i++,r++),n[o]={line:t,offset:i},r+=e.graphemeLines[o].length,i+=e.graphemeLines[o].length;return n},styleHas:function(e,i){if(this._styleMap&&!this.isWrapping){var r=this._styleMap[i];r&&(i=r.line)}return t.Text.prototype.styleHas.call(this,e,i)},isEmptyStyles:function(e){if(!this.styles)return!0;var t,i,r=0,n=!1,o=this._styleMap[e],s=this._styleMap[e+1];for(var a in o&&(e=o.line,r=o.offset),s&&(n=s.line===e,t=s.offset),i=void 0===e?this.styles:{line:this.styles[e]})for(var l in i[a])if(l>=r&&(!n||lr&&!p?(a.push(l),l=[],o=f,p=!0):o+=m,p||s||l.push(d),l=l.concat(c),g=s?0:this._measureWord([d],i,u),u++,p=!1,f>_&&(_=f);return v&&a.push(l),_+n>this.dynamicMinWidth&&(this.dynamicMinWidth=_-m+n),a},isEndOfWrapping:function(e){return!this._styleMap[e+1]||this._styleMap[e+1].line!==this._styleMap[e].line},missingNewlineOffset:function(e){return this.splitByGrapheme?this.isEndOfWrapping(e)?1:0:1},_splitTextIntoLines:function(e){for(var i=t.Text.prototype._splitTextIntoLines.call(this,e),r=this._wrapText(i.lines,this.width),n=new Array(r.length),o=0;o{},898:()=>{},245:()=>{}},P={};function F(e){var t=P[e];if(void 0!==t)return t.exports;var i=P[e]={exports:{}};return L[e](i,i.exports,F),i.exports}F.d=(e,t)=>{for(var i in t)F.o(t,i)&&!F.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},F.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var k={};(()=>{let e;F.d(k,{R:()=>e}),e="undefined"!=typeof document&&"undefined"!=typeof window?F(653).fabric:{version:"5.2.1"}})();var B=k.R; /*! * Dynamsoft JavaScript Library * @product Dynamsoft Camera Enhancer JS Edition * @website https://www.dynamsoft.com * @copyright Copyright 2022, Dynamsoft Corporation * @author Dynamsoft - * @version 2.3.2 (js 20220321) + * @version 3.0.0 (js 20220726) * @fileoverview Dynamsoft JavaScript Library for Camera Enhancer * More info on DCE JS: https://www.dynamsoft.com/camera-enhancer/docs/programming/javascript/?ver=latest - */ -function D(e,t,i,n){return new(i||(i=Promise))((function(o,r){function s(e){try{d(n.next(e))}catch(e){r(e)}}function a(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}d((n=n.apply(e,t||[])).next())}))}w._jsVersion="9.0.2",w._jsEditVersion="20220505",w._version=`loading...(JS ${w._jsVersion}.${w._jsEditVersion})`,w._license=l,w._sessionPassword=c,w.browserInfo=i,w._workerName=`dbr-${w._jsVersion}.browser.worker.js`,w._engineResourcePath=a,w._licenseServer=[],w._deviceFriendlyName="",w._isShowRelDecodeTimeInResults=!1,w._bWasmDebug=!1,w._bNeverShowDialog=!1,w.__bUseFullFeature=!0,w._nextTaskID=0,w._taskCallbackMap=new Map,w._pLoad=new class extends Promise{constructor(e){let t,i;super(((e,n)=>{t=e,i=n})),this._s="pending",this.resolve=e=>{this.isPending&&(f(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",i(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,f(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const i=await t;e===this._task&&this.resolve(i)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}},w._lastErrorCode=0,w._lastErrorString="",w._setWarnnedEx=new Set,w._defaultUIElementURL="@engineResourcePath/dbr.ui.html";const M="undefined"==typeof self;class b{constructor(){this._maxCvsSideLength=void 0,this._defaultMaxCvsSideLength=null,this.predefinedResolutions=[{width:160,height:120},{width:320,height:240},{width:480,height:360},{width:640,height:480},{width:800,height:600},{width:960,height:720},{width:1280,height:720},{width:1920,height:1080},{width:2560,height:1440},{width:3840,height:2160}],this.mapCameraResolutions=new Map,this._bWebGLSupported=!0,this._singleFrameMode=!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia),this._cvsSingleFrameMode=null,this._imgWidth=0,this._imgHeight=0,this._singleFrameModeIpt=null,this._clickIptSingleFrameMode=()=>{if(this.singleFrameMode){if(!this._singleFrameModeIpt){const e=document.createElement("input");this._singleFrameModeIpt=e,e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.addEventListener("change",(()=>D(this,void 0,void 0,(function*(){const t=e.files[0];e.value="";const i=yield(e=>D(this,void 0,void 0,(function*(){let t=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(t=yield createImageBitmap(e),t)return t}catch(t){}var n;return t||(i=yield(n=e,new Promise(((e,t)=>{let i=URL.createObjectURL(n),o=new Image;o.dbrObjUrl=i,o.src=i,o.onload=()=>{e(o)},o.onerror=e=>{t(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}})))),i})))(t),n=i instanceof HTMLImageElement?i.naturalWidth:i.width,o=i instanceof HTMLImageElement?i.naturalHeight:i.height;this._imgWidth=n,this._imgHeight=o,(e=>{if(!this._cvsSingleFrameMode){if(this._cvsSingleFrameMode=document.createElement("canvas"),this._cvsSingleFrameMode.className="cvs-single-frame-mode",this._cvsSingleFrameMode.addEventListener("click",this._clickIptSingleFrameMode),this._cvsSingleFrameMode.style.cursor="pointer",this._cvsSingleFrameMode.setAttribute("title","Take a photo"),!this._video)throw new Error("'video' is null.");this._video.after(this._cvsSingleFrameMode)}const t=this._cvsSingleFrameMode;t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.left="0",t.style.top="0",t.style.objectFit="contain",t.width==n&&t.height==o||(t.width=n,t.height=o);let i=t.getContext("2d");i.clearRect(0,0,t.width,t.height),i.drawImage(e,0,0)})(i),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e);const r=(e=>{const t=Date.now();if(0===n||0===o)return null;const i=this._scanRegion,r=this.getFrameSize(n,o,i,this.maxCvsSideLength);if(!r)return null;let s,a;s=n!==r.sWidth||o!==r.sHeight,a=r.sWidth!==r.dWidth||r.sHeight!==r.dHeight;const d=(()=>!(!this._bWebGLSupported||a))(),l={data:null,region:i?JSON.parse(JSON.stringify(i)):null,sx:r.sx,sy:r.sy,width:r.dWidth,height:r.dHeight,colorMode:null,timeSpent:null,timeStamp:null,isCropped:s,toCanvas:this.toCanvas,_bUseWebGL:null},c=this._getImageData(e,n,o,r,null,{targetColorMode:this.frameColorMode,bUseWebGL:d});if(!c)return null;const h=Date.now();return b._onLog&&b._onLog("DCE: _getVideoFrame(region?) END: "+h),l.data=c.data,l.colorMode=c.colorMode,l._bUseWebGL=c._bUseWebGL,l.timeSpent=h-t,l.timeStamp=h,l})(i),s=this.mapCameraEvents.get("singleFrameAcquired");for(let e of s)try{const t={data:new Uint8Array(r.data),region:JSON.parse(JSON.stringify(r.region)),sx:r.sx,sy:r.sy,width:r.width,height:r.height,colorMode:r.colorMode,timeSpent:r.timeSpent,timeStamp:r.timeStamp,isCropped:r.isCropped,toCanvas:r.toCanvas,_bUseWebGL:r._bUseWebGL};yield e(t)}catch(e){console.error(e)}})))),e.style.position="fixed",e.style.left="-1px",e.style.top="-1px",e.style.width="1px",e.style.height="1px",e.style.backgroundColor="transparent",e.style.color="transparent",document.body.appendChild(e)}this._singleFrameModeIpt.click()}},this.styleEls=[],this._frameColorMode=void 0,this._defaultFrameColorMode="RGBA",this.currentFSColorMode="rgba",this.ifReuseArrayBufferView=!1,this.maxVideoCvsLength=3,this.canvas=null,this.videoGlCvs=null,this.videoGl=null,this.glImgData=null,this.webglTexture=null,this.webglProgramInfo=null,this.webglBuffers=null,this.toCanvas=function(){const e=document.createElement("canvas");let t;if(e.width=this.width,e.height=this.height,"grey"===this.colorMode){t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;eD(this,void 0,void 0,(function*(){yield this.selectCamera(this._selCam.value),this._bOpen||this.stop()})),this._onResolutionSelChange=()=>D(this,void 0,void 0,(function*(){let e,t;if(this._selRsl&&-1!=this._selRsl.selectedIndex){let i=this._selRsl.options[this._selRsl.selectedIndex];e=i.getAttribute("data-width"),t=i.getAttribute("data-height")}yield this.setResolution(e,t),this._bOpen||this.stop()})),this._onCloseBtnClick=()=>{this.close(!0)},this._bOpen=!1,this.videoSrc=null,this.videoSettings={video:{width:{ideal:1280},height:{ideal:720},facingMode:{ideal:"environment"}}},this.iPlayRound=0,this.promisePlay=null,this._ifSaveLastUsedCamera=!1,this.ifSkipCameraInspection=!1,this._allCameras=[],this._currentCamera=null,this._videoTrack=null,this._lastDeviceId=void 0,this._vc_bPlayingVideoBeforeHide=!1,this._ev_documentHideEvent=()=>{"visible"===document.visibilityState?this._vc_bPlayingVideoBeforeHide&&("Firefox"==b.browserInfo.browser?this.play():this._video.play(),this._vc_bPlayingVideoBeforeHide=!1):this._video&&!this._video.paused&&(this._vc_bPlayingVideoBeforeHide=!0,this._video.pause())},this._video=null,this.videoFit="contain",this._cvsScanRegion=null,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=2,this._bShowScanRegionMask=!0,this._bShowScanRegionLaser=!1,this._scanRegion=null,this._arrScanRegionOverlays=[],this._cvsViewDecorator=null,this._decoratorType=[],this._decoratorArea=null,this._viewDecoratorInfo={rectangle:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},focus:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},crossline:{lineWidth:2,strokeStyle:"rgb(254,142,20)"},crosshair:{lineWidth:4,strokeStyle:"rgb(254,142,20)"}},this._croppingRegions=void 0,this._defaultCroppingRegions=[null],this.bIncreaseRegionIndexAuto=!0,this._croppingRegionIndex=0,this._loopInterval=void 0,this._defaultLoopInterval=0,this._maxNumberOfFramesInBuffer=void 0,this._defaultMaxNumberOfFramesInBuffer=1,this._frameQueue=[],this._bFetchingLoopStarted=!1,this._bStoppedByPause=!1,this._refreshInterval=void 0,this._defaultRefreshInterval=-1,this._updateCanvasTimeout=500,this.referenceConfigurationArray=[],this._onWindowResize=()=>{this._resizeTimeoutId&&clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=setTimeout((()=>{this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e)}),this._updateCanvasTimeout)},this.bDestroyed=!1,this.mapCameraEvents=new Map([["cameraOpen",[]],["cameraClose",[]],["cameraChange",[]],["resolutionChange",[]],["played",[]],["singleFrameAcquired",[]],["frameAddedToBuffer",[]]])}static getVersion(){return this._version}static detectEnvironment(){return D(this,void 0,void 0,(function*(){let e={wasm:"undefined"!=typeof WebAssembly&&("undefined"==typeof navigator||!(/Safari/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&/\(.+\s11_2_([2-6]).*\)/.test(navigator.userAgent))),worker:!("undefined"==typeof Worker),getUserMedia:!("undefined"==typeof navigator||!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia),camera:!1,browser:this.browserInfo.browser,version:this.browserInfo.version,OS:this.browserInfo.OS};if(e.getUserMedia)try{(yield navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e.camera=!0}catch(e){}return e}))}static set engineResourcePath(e){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");if(null==e&&(e="./"),M)b._engineResourcePath=e;else{let t=document.createElement("a");t.href=e,b._engineResourcePath=t.href}this._engineResourcePath.endsWith("/")||(b._engineResourcePath+="/")}static get engineResourcePath(){return this._engineResourcePath}static isStorageAvailable(e){let t;try{t=window[e];const i="__storage_test__";return t.setItem(i,i),t.removeItem(i),!0}catch(e){return e instanceof DOMException&&(22===e.code||1014===e.code||"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)&&t&&0!==t.length}}set maxCvsSideLength(e){if(e<=0)throw new Error("The 'maxCvsSideLength' should be greater than 0.");this._maxCvsSideLength=e}get maxCvsSideLength(){return void 0!==this._maxCvsSideLength?this._maxCvsSideLength:this.referenceConfigurationArray&&1===this.referenceConfigurationArray.length&&this.referenceConfigurationArray[0].hasOwnProperty("maxCvsSideLength")?this.referenceConfigurationArray[0].maxCvsSideLength:this._defaultMaxCvsSideLength}static set defaultUIElementURL(e){b._defaultUIElementURL=e}static get defaultUIElementURL(){var e;return null===(e=b._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",b.engineResourcePath)}getUIElement(){return this.UIElement}setUIElement(e){return D(this,void 0,void 0,(function*(){if(this._bOpen)throw new Error("It is not allowed to change the UIElement when the camera is open.");if("string"==typeof e||e instanceof String){if(!e.trim().startsWith("<")){let t=yield fetch(e);if(!t.ok)throw Error("setUIElement(elementOrUrl): Network Error: "+t.statusText);e=yield t.text()}if(!e.trim().startsWith("<"))throw Error("setUIElement(elementOrUrl): Can't get valid HTMLElement.");let t=document.createElement("div");t.innerHTML=e;for(let e=0;e','','',''].join(""),this._optGotRsl=this._optGotRsl||this._selRsl.options[0])):!this._optGotRsl&&t.classList.contains("dce-opt-gotResolution")?this._optGotRsl=t:!this._btnClose&&t.classList.contains("dce-btn-close")&&(this._btnClose=t);if(!this._video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'");this.singleFrameMode?(this._video&&(this._video.addEventListener("click",this._clickIptSingleFrameMode),this._video.style.cursor="pointer",this._video.setAttribute("title","Take a photo")),this._divScanArea&&(this._divScanArea.addEventListener("click",this._clickIptSingleFrameMode),this._divScanArea.style.cursor="pointer",this._divScanArea.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="")):this._bgLoading&&(this._bgLoading.style.display=""),this._selCam&&this._selCam.addEventListener("change",this._onCameraSelChange),this._selRsl&&this._selRsl.addEventListener("change",this._onResolutionSelChange),this._btnClose&&this._btnClose.addEventListener("click",this._onCloseBtnClick),document.addEventListener("visibilitychange",this._ev_documentHideEvent),window.addEventListener("resize",this._onWindowResize)}_unbindUI(){this.singleFrameMode?(this._video&&(this._video.removeEventListener("click",this._clickIptSingleFrameMode),this._video.style.cursor="",this._video.removeAttribute("title")),this._divScanArea&&(this._divScanArea.removeEventListener("click",this._clickIptSingleFrameMode),this._divScanArea.style.cursor="",this._divScanArea.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._bgLoading&&(this._bgLoading.style.display="none"),this._selCam&&this._selCam.removeEventListener("change",this._onCameraSelChange),this._selRsl&&this._selRsl.removeEventListener("change",this._onResolutionSelChange),this._btnClose&&this._btnClose.removeEventListener("click",this._onCloseBtnClick),this._cvsViewDecorator&&(this._cvsViewDecorator.removeEventListener("click",this._clickIptSingleFrameMode),this._cvsViewDecorator.style.cursor="",this._cvsViewDecorator.removeAttribute("title"));for(let e of this._arrScanRegionOverlays)e&&(e.removeEventListener("click",this._clickIptSingleFrameMode),e.style.cursor="",e.removeAttribute("title"));this.hideScanRegionLaser(),this.hideViewDecorator(),this.hideScanRegionOverlays(),this._video&&(this._video.onloadedmetadata=null,this._video.remove()),this._video=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._divScanArea=null,this._divScanLight=null,this._cvsScanRegion&&(this._cvsScanRegion.remove(),this._cvsScanRegion=null),this._singleFrameModeIpt&&(this._singleFrameModeIpt.remove(),this._singleFrameModeIpt=null),this._cvsSingleFrameMode&&(this._cvsSingleFrameMode.remove(),this._cvsSingleFrameMode=null),document.removeEventListener("visibilitychange",this._ev_documentHideEvent),window.removeEventListener("resize",this._onWindowResize)}set bOpen(e){if(this._bOpen=e,e){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e);this._bShowScanRegionMask?this.showScanRegionMask():this.hideScanRegionMask(),this._bShowScanRegionLaser?this.showScanRegionLaser():this.hideScanRegionLaser(),this.showViewDecorator(),this._cvsViewDecorator&&(this._cvsViewDecorator.addEventListener("click",this._clickIptSingleFrameMode),this._cvsViewDecorator.style.cursor="pointer",this._cvsViewDecorator.setAttribute("title","Take a photo")),this.showScanRegionOverlays();for(let e of this._arrScanRegionOverlays)e&&(e.addEventListener("click",this._clickIptSingleFrameMode),e.style.cursor="pointer",e.setAttribute("title","Take a photo"))}}_assertOpen(){if(!this._bOpen)throw Error("The camera is not open.")}set ifSaveLastUsedCamera(e){e?b.isStorageAvailable("localStorage")?this._ifSaveLastUsedCamera=!0:(this._ifSaveLastUsedCamera=!1,console.warn("Local storage is unavailable")):this._ifSaveLastUsedCamera=!1}get ifSaveLastUsedCamera(){return this._ifSaveLastUsedCamera}get video(){return this._video}setVideoFit(e){if(e=e.toLowerCase(),!["contain","cover"].includes(e))throw new Error(`It is not allowed to set '${e}'.`);if(this.videoFit=e,this._video&&(this._video.style.objectFit=e,!this.singleFrameMode)){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e)}}getVideoFit(){return this.videoFit}set ifShowScanRegionMask(e){this._bShowScanRegionMask=e,e?this.showScanRegionMask():this.hideScanRegionMask()}get ifShowScanRegionMask(){return this._bShowScanRegionMask}showScanRegionMask(){this._cvsScanRegion&&"none"==this._cvsScanRegion.style.display&&(this._cvsScanRegion.style.display="")}hideScanRegionMask(){this._cvsScanRegion&&(this._cvsScanRegion.style.display="none")}set ifShowScanRegionLaser(e){this._bShowScanRegionLaser=e,e?this.showScanRegionLaser():this.hideScanRegionLaser()}get ifShowScanRegionLaser(){return this._bShowScanRegionLaser}showScanRegionLaser(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="")}hideScanRegionLaser(){this._divScanLight&&(this._divScanLight.style.display="none")}_checkValidRegion(e){return!(null!==e&&(!e||!(e.hasOwnProperty("regionLeft")&&e.hasOwnProperty("regionTop")&&e.hasOwnProperty("regionRight")&&e.hasOwnProperty("regionBottom")&&e.hasOwnProperty("regionMeasuredByPercentage"))||e.regionLeft<0||e.regionTop<0||e.regionRight<0||e.regionBottom<0||e.regionMeasuredByPercentage&&(e.regionLeft>100||e.regionTop>100||e.regionRight>100||e.regionBottom>100)))}set scanRegion(e){if(!this._checkValidRegion(e))throw new Error("The region is invalid.");this._scanRegion=JSON.parse(JSON.stringify(e)),this._updateScanRegionCanvas(),this._updateScanAreaDiv();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e)}setScanRegion(e){this.scanRegion=e}getScanRegion(){return JSON.parse(JSON.stringify(this._scanRegion))}addScanRegionOverlayCanvas(){this._assertOpen();const e=document.createElement("canvas");if(e.className="cvs-scan-region-overlay-"+this._arrScanRegionOverlays.length,this.singleFrameMode&&(e.addEventListener("click",this._clickIptSingleFrameMode),e.style.cursor="pointer",e.setAttribute("title","Take a photo")),this._updateScanRegionOverlay(e),this._arrScanRegionOverlays.length>0){const t=this._arrScanRegionOverlays.length;this._arrScanRegionOverlays[t-1].after(e)}else if(this._cvsScanRegion)this._cvsScanRegion.before(e);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(e);else{if(!this._video)throw new Error("'video' is null.");this._video.after(e)}return this._arrScanRegionOverlays.push(e),e}_updateScanRegionOverlay(e){if(!e)return;let t,i,n;if(this.singleFrameMode)t=this._imgWidth,i=this._imgHeight,n="contain";else{if(!this._video)return;t=this._video.videoWidth,i=this._video.videoHeight,n=this.getVideoFit()}if(t<=0||i<=0)return e.width=0,void(e.height=0);const o=this._getRegionInPixels(t,i,this._scanRegion),r=this.getFrameSize(t,i,this._scanRegion,this.maxCvsSideLength).dWidth,s=this.getFrameSize(t,i,this._scanRegion,this.maxCvsSideLength).dHeight;e.width==r&&e.height==s||(e.width=r,e.height=s);const a=window.getComputedStyle(this._video),d=parseFloat(a.width),l=parseFloat(a.height),c=d/l,h=t/i;let _,u,g,m,f=1;if("contain"===n)c{const e=parseFloat(window.getComputedStyle(this._video).width),o=parseFloat(window.getComputedStyle(this._video).height);let r,s={regionBottom:i,regionRight:t,regionLeft:0,regionTop:0,regionMeasuredByPercentage:!1};return"cover"===n?e/othis.maxNumberOfFramesInBuffer;)this._frameQueue.shift()}get maxNumberOfFramesInBuffer(){return void 0!==this._maxNumberOfFramesInBuffer?this._maxNumberOfFramesInBuffer:this.referenceConfigurationArray&&1===this.referenceConfigurationArray.length&&this.referenceConfigurationArray[0].hasOwnProperty("maxNumberOfFramesInBuffer")?this.referenceConfigurationArray[0].maxNumberOfFramesInBuffer:this._defaultMaxNumberOfFramesInBuffer}get numberOfFramesInBuffer(){return this._frameQueue.length}set refreshInterval(e){this._refreshInterval=e}get refreshInterval(){return void 0!==this._refreshInterval?this._refreshInterval:this.referenceConfigurationArray&&1===this.referenceConfigurationArray.length&&this.referenceConfigurationArray[0].hasOwnProperty("refreshInterval")?this.referenceConfigurationArray[0].refreshInterval:this._defaultRefreshInterval}isContextDestroyed(){return this.bDestroyed}static createInstance(e){return D(this,void 0,void 0,(function*(){let t=new b;("string"==typeof e||e instanceof String)&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return yield t.setUIElement(b.defaultUIElementURL),this._hasEngineResourceLoaded=!0,t}))}play(e,t,i){return D(this,void 0,void 0,(function*(){if(this._video&&this.videoSrc){yield new Promise(((e,t)=>{this._video.onloadedmetadata=()=>D(this,void 0,void 0,(function*(){this._video&&(this._video.onloadedmetadata=null,yield this._video.play(),e())})),"string"==typeof this.videoSrc||this.videoSrc instanceof String?this._video.src=this.videoSrc:this._video.srcObject=this.videoSrc,setTimeout((()=>t(new Error("Failed to play video. Timeout."))),4e3)}));let e={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};const t=this.mapCameraEvents.get("played");for(let i of t){const t=JSON.parse(JSON.stringify(e));setTimeout((()=>i(t)),0)}return e}if(this.singleFrameMode)return this._clickIptSingleFrameMode(),{width:0,height:0,deviceId:null};if(!this._video)return null;const n=++this.iPlayRound;let o=null,r=0,s=0;return this._currentCamera&&(o=this._currentCamera.deviceId),this._video&&(r=this._video.videoWidth,s=this._video.videoHeight),this.promisePlay&&(yield this.promisePlay,nD(this,void 0,void 0,(function*(){var n;try{this._video&&this._video.srcObject&&this.stop(),b._onLog&&b._onLog("DCE: ======before video========");const a=()=>{if(!this._video)throw _&&_.getTracks().forEach((e=>{e.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null.")},d=this.getVideoSettings();let l;"boolean"==typeof d.video&&(d.video={});const c=["rear","back","rück","arrière","trasera","trás","traseira","posteriore","后面","後面","背面","后置","後置","背置","задней","الخلفية","후","arka","achterzijde","หลัง","baksidan","bagside","sau","bak","tylny","takakamera","belakang","אחורית","πίσω","spate","hátsó","zadní","darrere","zadná","задня","stražnja","belakang","बैक"],h=()=>{for(let e of this._allCameras){let t=e.label.toLowerCase();if(t&&c.some((e=>-1!=t.indexOf(e)))&&/\b0(\b)?/.test(t)){delete d.video.facingMode,d.video.deviceId={ideal:e.deviceId};break}}d.video.deviceId||-1==["Android","HarmonyOS"].indexOf(b.browserInfo.OS)||(delete d.video.facingMode,d.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})};if(e)delete d.video.facingMode,d.video.deviceId={exact:e};else if(d.video.deviceId);else if(this._lastDeviceId)delete d.video.facingMode,d.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&b.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete d.video.facingMode,d.video.deviceId={exact:window.localStorage.getItem("dce_last_camera_id")};const I=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),y=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));I&&y&&(d.video.width=I,d.video.height=y)}else if(this.ifSkipCameraInspection);else if(d.video.facingMode){if(yield this.getAllCameras(),!this._video)return null;let T=d.video.facingMode;T instanceof Array&&T.length&&(T=T[0]),T=T.exact||T.ideal||T,"environment"===T&&(l=!!d.video.facingMode,h())}let _;t&&(d.video.width={ideal:t}),i&&(d.video.height={ideal:i}),b._onLog&&b._onLog("DCE: ======try getUserMedia========");let u,g=[0,500],m=null,f=null;function p(e){return D(this,void 0,void 0,(function*(){for(let t of g){a(),t&&(yield new Promise((e=>setTimeout(e,t)))),a();{const t=e.video.deviceId;f=t?t.exact||t.ideal||t:null}try{b._onLog&&b._onLog("DCE: ask "+JSON.stringify(e)),_=yield navigator.mediaDevices.getUserMedia(e),a();break}catch(e){m=e,b._onLog&&b._onLog("DCE: "+e.message||e)}}}))}if(yield p(d),_||(b._onLog&&b._onLog("DCE: ======try getUserMedia again========"),u=JSON.parse(JSON.stringify(d)),"object"==typeof u.video&&("iPhone"==b.browserInfo.OS?(t>=1280||i>=1280?u.video.width=1280:t>=640||i>=640?u.video.width=640:(t<640||i<640)&&(u.video.width=320),delete u.video.height):l&&!d.video.deviceId?(delete u.video.facingMode,this._allCameras.length&&(u.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):u.video=!0),b._onLog&&b._onLog("DCE: "+u),yield p(u)),_||(g=[1e3,2e3],yield p(d)),_||(yield p(u)),!_)throw m;const v=()=>{const e=_.getVideoTracks();let t,i;if(e.length&&(t=this._videoTrack=e[0]),this._video&&t){const e=t.getSettings();if(e)for(let n of this._allCameras)if(e.deviceId===n.deviceId){n._checked=!0,n.label=t.label,i=n;break}if(!i&&f)for(let e of this._allCameras)if(f==e.deviceId){t.label&&(e._checked=!0,e.label=t.label),i=e;break}}this._currentCamera=i};if(yield this.getAllCameras(),a(),l){v(),h();let C=d.video.deviceId;C&&(C=C.exact||C.ideal||C);let w=null===(n=this._currentCamera)||void 0===n?void 0:n.deviceId;!C||w&&C==w||(_.getTracks().forEach((e=>{e.stop()})),g=[0,500,1e3,2e3],yield p(d))}a();const A=()=>D(this,void 0,void 0,(function*(){b._onLog&&b._onLog("======play video========"),yield new Promise(((e,t)=>{a(),this._video.onloadedmetadata=()=>D(this,void 0,void 0,(function*(){a(),this._video.onloadedmetadata=null,yield this._video.play(),e()})),this._video.srcObject=_,setTimeout((()=>t(new Error("Failed to play video. Timeout."))),4e3)}))}));yield A(),a(),b._onLog&&b._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const R=this._video.videoWidth+"x"+this._video.videoHeight;this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",this._video.videoWidth),this._optGotRsl.setAttribute("data-height",this._video.videoHeight),this._optGotRsl.innerText=R,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),b._onLog&&b._onLog("DCE: got "+R),v(),a(),this._renderSelCameraInfo();const S={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};S.deviceId&&(this._lastDeviceId=S.deviceId,this.ifSaveLastUsedCamera&&b.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),d.video.width&&d.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(d.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(d.video.height)))));const E=this.mapCameraEvents.get("played");for(let M of E){const L=JSON.parse(JSON.stringify(S));setTimeout((()=>M(L)),0)}if(o&&o!=S.deviceId){const O=this.mapCameraEvents.get("cameraChange");for(let F of O){const B=JSON.parse(JSON.stringify(S));setTimeout((()=>F(B)),0)}}if(r&&s&&(r!=S.width||s!=S.height)){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let N of this._arrScanRegionOverlays)N&&this._updateScanRegionOverlay(N);const P=this.mapCameraEvents.get("resolutionChange");for(let x of P){const V=JSON.parse(JSON.stringify(S));setTimeout((()=>x(V)),0)}}return this.promisePlay=null,S}catch(k){throw this.promisePlay=null,k}})))(),yield this.promisePlay)}))}resume(){return D(this,void 0,void 0,(function*(){this._assertOpen(),yield this.play(),this._bStoppedByPause&&(this._bStoppedByPause=!1,this.startFetchingLoop()),this._bShowScanRegionLaser&&this.showScanRegionLaser()}))}pause(){this._bOpen||console.warn("The camera is not open."),this._video&&this._video.pause(),this._bFetchingLoopStarted&&(this.stopFetchingLoop(),this._bStoppedByPause=!0),this._bShowScanRegionLaser&&this.hideScanRegionLaser()}close(e){if(!this._video)return;this.stop(),this._unbindUI(),e&&(this.UIElement.style.display="none"),this.stopFetchingLoop(),this.bOpen=!1;const t=this.mapCameraEvents.get("cameraClose");for(let e of t){const t={width:0,height:0,deviceId:null};setTimeout((()=>e(t)),0)}}open(e){return D(this,void 0,void 0,(function*(){this._bindUI(),e&&(this.UIElement.parentNode||(this.UIElement.style.position="fixed",this.UIElement.style.left="0",this.UIElement.style.top="0",document.body.append(this.UIElement)),"none"==this.UIElement.style.display&&(this.UIElement.style.display=""));let t=yield this.play();this.bOpen=!0;const i=this.mapCameraEvents.get("cameraOpen");for(let e of i){const i=JSON.parse(JSON.stringify(t));setTimeout((()=>e(i)),0)}return t}))}stop(){this._video&&this._video.srcObject&&(b._onLog&&b._onLog("DCE: ======stop video========"),this._video.srcObject.getTracks().forEach((e=>{e.stop()})),this._video.srcObject=null,this._videoTrack=null,this._currentCamera=null),this._video&&this.videoSrc&&(b._onLog&&b._onLog("DCE: ======stop existing video========"),this._video.pause(),this._video.currentTime=0),this._bgLoading&&(this._bgLoading.style.animationPlayState=""),this._frameQueue.length=0}getAllCameras(){return D(this,void 0,void 0,(function*(){let e=yield navigator.mediaDevices.enumerateDevices();if(!e[0].deviceId){let t=yield navigator.mediaDevices.getUserMedia({video:!0});e=yield navigator.mediaDevices.enumerateDevices(),t.getTracks().forEach((e=>{e.stop()})),t=null}const t=[],i=[];if(this._allCameras)for(let e of this._allCameras)e._checked&&i.push(e);for(let n=0;n{const i=this.mapCameraResolutions.get(e);if(!i||!i.length)return!1;for(let e of i)if(e[0]===t.width&&e[1]===t.height)return!0;return!1},n=(e,t,i)=>D(this,void 0,void 0,(function*(){const n={video:{deviceId:{exact:e},width:{ideal:t},height:{ideal:i}}};let o=null;try{o=yield navigator.mediaDevices.getUserMedia(n)}catch(n){return null}if(!o)return null;const r=o.getVideoTracks();let s=null;try{const e=r[0].getSettings();s={width:e.width,height:e.height}}catch(n){const e=document.createElement("video");e.srcObject=o,s={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return r.forEach((e=>{e.stop()})),s}));if(!this._bOpen){const o=this.videoSettings.video.deviceId;if(!o)return null;if(t=o.hasOwnProperty("exact")?this.videoSettings.video.deviceId.exact:o.hasOwnProperty("ideal")?this.videoSettings.video.deviceId.ideal:this.videoSettings.video.deviceId,!t)return null;let r=this.mapCameraResolutions.get(t);if(r&&!e)return this.mapCameraResolutions.get(t);this.mapCameraResolutions.set(t,[]),r=this.mapCameraResolutions.get(t);for(let e of this.predefinedResolutions){const o=yield n(t,e.width,e.height);o&&!i(t,o)&&r.push([o.width,o.height])}return r}if(this._currentCamera){t=this._currentCamera.deviceId;let n=this.mapCameraResolutions.get(t);if(n&&!e)return this.mapCameraResolutions.get(t);this.mapCameraResolutions.set(t,[]),n=this.mapCameraResolutions.get(t);const o=this.getConstraints();for(let e of this.predefinedResolutions){yield this._videoTrack.applyConstraints({width:{ideal:e.width},height:{ideal:e.height}});const o=this._videoTrack.getSettings(),r={width:o.width,height:o.height};i(t,r)||n.push([r.width,r.height])}return yield this._videoTrack.applyConstraints(o),n}return null}))}on(e,t){if(!this.mapCameraEvents.has(e))throw new Error(`Event '${e}' is not exists.`);const i=this.mapCameraEvents.get(e);i.includes(t)||i.push(t)}off(e,t){if(!this.mapCameraEvents.has(e))throw new Error(`Event '${e}' is not exists.`);const i=this.mapCameraEvents.get(e),n=i.indexOf(t);-1!==n&&i.splice(n,1)}getVideoSettings(){return JSON.parse(JSON.stringify(this.videoSettings))}updateVideoSettings(e){return this.videoSettings=JSON.parse(JSON.stringify(e)),this._lastDeviceId=null,this._bOpen?this.play():Promise.resolve()}isOpen(){return this._bOpen}getCapabilities(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOnTorch()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error('"_videoTrack" is null.');return this._videoTrack.getCapabilities?this._videoTrack.getCapabilities():{}}getCameraSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCameraSettings()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error('"_videoTrack" is null.');return this._videoTrack.getSettings()}getConstraints(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getConstraints()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error('"_videoTrack" is null.');return this._videoTrack.getConstraints()}applyConstraints(e){return D(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'applyConstraints()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error('"_videoTrack" is null.');if(!this._videoTrack.applyConstraints)throw Error("Not supported.");return yield this._videoTrack.applyConstraints(e)}))}turnOnTorch(){return D(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOnTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return yield this._videoTrack.applyConstraints({advanced:[{torch:!0}]});throw Error("Not supported.")}))}turnOffTorch(){return D(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOffTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return yield this._videoTrack.applyConstraints({advanced:[{torch:!1}]});throw Error("Not supported.")}))}setColorTemperature(e){return D(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setColorTemperature()' is unavailable in singleFrameMode.");let t=this.getCapabilities().colorTemperature;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),yield this._videoTrack.applyConstraints({advanced:[{colorTemperature:e}]})}))}setExposureCompensation(e){return D(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setExposureCompensation()' is unavailable in singleFrameMode.");let t=this.getCapabilities().exposureCompensation;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),yield this._videoTrack.applyConstraints({advanced:[{exposureCompensation:e}]})}))}setZoom(e){return D(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setZoom()' is unavailable in singleFrameMode.");let t=this.getCapabilities().zoom;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),yield this._videoTrack.applyConstraints({advanced:[{zoom:e}]})}))}setFrameRate(e){return D(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFrameRate()' is unavailable in singleFrameMode.");let t=this.getCapabilities().frameRate;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),yield this._videoTrack.applyConstraints({width:{ideal:Math.max(this._video.videoWidth,this._video.videoHeight)},frameRate:e})}))}getFrameRate(){return this.getCameraSettings().frameRate}setFocus(e,t){return D(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFocus()' is unavailable in singleFrameMode.");const i=this.getCapabilities().focusMode,n=this.getCapabilities().focusDistance;if(!i||!i.includes(e)||!n)throw Error("Not supported.");return t?(tn.max&&(t=n.max),yield this._videoTrack.applyConstraints({advanced:[{focusMode:e,focusDistance:t}]})):yield this._videoTrack.applyConstraints({advanced:[{focusMode:e}]})}))}getFocus(){const e=this.getCameraSettings().focusMode;return"continuous"===e?{mode:e}:{mode:e,distance:this.getCameraSettings().focusDistance}}getFrameSize(e,t,i,n){if(!e||!t)return null;let o,r,s,a,d=e,l=t;const c={regionLeft:0,regionTop:0,regionRight:d,regionBottom:l,regionMeasuredByPercentage:!1};i?(i.regionMeasuredByPercentage?(c.regionLeft=i.regionLeft*d/100,c.regionTop=i.regionTop*l/100,c.regionRight=i.regionRight*d/100,c.regionBottom=i.regionBottom*l/100):(c.regionLeft=i.regionLeft,c.regionTop=i.regionTop,c.regionRight=i.regionRight,c.regionBottom=i.regionBottom),o=c.regionLeft,r=c.regionTop,d=Math.round(c.regionRight-c.regionLeft),l=Math.round(c.regionBottom-c.regionTop)):(o=0,r=0);const h=Math.max(d,l);if(n&&n>0&&h>n){const e=n/h;d>l?(s=n,a=Math.round(l*e)):(s=Math.round(d*e),a=n)}else s=d,a=l;return s<=0||a<=0?null:{sx:o,sy:r,sWidth:d,sHeight:l,dWidth:s,dHeight:a}}getFrame(){if(this.singleFrameMode)throw Error("'getFrame()' is unavailable in singleFrameMode.");if(this._assertOpen(),this.singleFrameMode)throw new Error("'getFrame()' is unavailable in singleFrameMode.");return this._getVideoFrame(this._scanRegion)}_getVideoFrame(e,t){if(this.bDestroyed)throw Error("The 'CameraEnhancer' instance has been destroyed.");if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getVideoFrame()' is unavailable in singleFrameMode.");const i=Date.now();b._onLog&&b._onLog("DCE: _getVideoFrame(region?) START: "+i);const n=this._video.videoWidth,o=this._video.videoHeight;if(0===n||0===o)return null;const r=this.getFrameSize(n,o,e,this.maxCvsSideLength);if(!r)return null;let s,a;s=n!==r.sWidth||o!==r.sHeight,a=r.sWidth!==r.dWidth||r.sHeight!==r.dHeight;const d=(()=>!(!this._bWebGLSupported||a))(),l={data:null,region:e?JSON.parse(JSON.stringify(e)):null,sx:r.sx,sy:r.sy,width:r.dWidth,height:r.dHeight,colorMode:null,timeSpent:null,timeStamp:null,isCropped:s,toCanvas:this.toCanvas,_bUseWebGL:null},c=this._getImageData(this._video,n,o,r,t,{targetColorMode:this.frameColorMode,bUseWebGL:d});if(!c)return null;const h=Date.now();return b._onLog&&b._onLog("DCE: _getVideoFrame(region?) END: "+h),l.data=c.data,l.colorMode=c.colorMode,l._bUseWebGL=c._bUseWebGL,l.timeSpent=h-i,l.timeStamp=h,l}_getImageData(e,t,i,n,o,r){if(this.bDestroyed)throw Error("The 'CameraEnhancer' instance has been destroyed.");if(!t||!i)return null;b._onLog&&b._onLog("DCE: _getImageData() START: "+Date.now());const{sx:s,sy:a,sWidth:d,sHeight:l,dWidth:c,dHeight:h}=n;let _;if(_=r&&r.targetColorMode?r.targetColorMode.toLowerCase():"rgba",r&&r.bUseWebGL){this.videoGlCvs||(this.videoGlCvs=document.createElement("canvas"));const d=this.videoGlCvs;d.width==t&&d.height==i||(d.width=t,d.height=i,this.videoGl&&this.videoGl.viewport(0,0,t,i));const l=this.videoGl||d.getContext("webgl",{antialias:!1})||d.getContext("experimental-webgl",{antialias:!1});if(!l){this.videoGl=null,this._bWebGLSupported=!1;let s=null;return r?(s=JSON.parse(JSON.stringify(r)),s.bUseWebGL=!1):s={bUseWebGL:!1},this._getImageData(e,t,i,n,o,s)}if(l.enable(l.SCISSOR_TEST),l.scissor(s,a,c,h),!this.videoGl||_!==this.currentFSColorMode){this.videoGl=l;const e=e=>{const t=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,t),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,1,1,-1,1]),e.STATIC_DRAW);const i=e.createBuffer();return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,i),e.bufferData(e.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,0,2,3]),e.STATIC_DRAW),{position:t,indices:i}},t=e=>{const t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),t},i=(e,t,i)=>{const o=n(e,e.VERTEX_SHADER,t),r=n(e,e.FRAGMENT_SHADER,i),s=e.createProgram();return e.attachShader(s,o),e.attachShader(s,r),e.linkProgram(s),e.getProgramParameter(s,e.LINK_STATUS)?s:(alert("Unable to initialize the shader program: "+e.getProgramInfoLog(s)),null)},n=(e,t,i)=>{const n=e.createShader(t);return e.shaderSource(n,i),e.compileShader(n),e.getShaderParameter(n,e.COMPILE_STATUS)?n:(alert("An error occurred compiling the shaders: "+e.getShaderInfoLog(n)),e.deleteShader(n),null)},o="\n attribute mediump vec2 aVertexPosition;\n varying mediump vec2 vDirection;\n \n void main( void )\n {\n gl_Position = vec4(aVertexPosition, 1.0, 1.0) * 2.0;\n vDirection = aVertexPosition;\n }\n ";let r;r=["rgba","rbga","grba","gbra","brga","bgra"].includes(_)?_.slice(0,3):"rgb";const s=i(l,o,`\n precision mediump float;\n\n varying mediump vec2 vDirection;\n uniform sampler2D uSampler;\n uniform lowp float uColorFactor;\n \n void main(void)\n {\n vec4 sample = texture2D(uSampler, vec2(vDirection.x * 0.5 + 0.5, vDirection.y * 0.5 + 0.5));\n lowp float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${r} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `);this.webglProgramInfo={program:s,attribLocations:{vertexPosition:l.getAttribLocation(s,"aVertexPosition")},uniformLocations:{uSampler:l.getUniformLocation(s,"uSampler"),uColorFactor:l.getUniformLocation(s,"uColorFactor")}},this.webglBuffers=e(l),this.webglTexture=t(l),this.currentFSColorMode=_}const u=(e,t,i)=>{const n=e.RGBA,o=e.RGBA,r=e.UNSIGNED_BYTE;e.bindTexture(e.TEXTURE_2D,t),e.texImage2D(e.TEXTURE_2D,0,n,o,r,i)},g=(e,t,i,n)=>{e.clearColor(0,0,0,1),e.clearDepth(1),e.enable(e.DEPTH_TEST),e.depthFunc(e.LEQUAL),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,i.indices),e.useProgram(t.program);{const n=2,o=e.FLOAT,r=!1,s=0,a=0;e.bindBuffer(e.ARRAY_BUFFER,i.position),e.vertexAttribPointer(t.attribLocations.vertexPosition,n,o,r,s,a),e.enableVertexAttribArray(t.attribLocations.vertexPosition)}e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,n),e.uniform1i(t.uniformLocations.uSampler,0),e.uniform1f(t.uniformLocations.uColorFactor,"grey"===_||"grey32"===_?1:0);const o=e.UNSIGNED_SHORT;e.drawElements(e.TRIANGLES,6,o,0)};let m;if(u(l,this.webglTexture,e),g(l,this.webglProgramInfo,this.webglBuffers,this.webglTexture),o){if(o.length=this.croppingRegions.length||this._croppingRegionIndex<0)throw new Error("The 'croppingRegionIndex' is out of bounds.");e=this.croppingRegions[this._croppingRegionIndex],this.bIncreaseRegionIndexAuto&&++this._croppingRegionIndex>=this.croppingRegions.length&&(this._croppingRegionIndex=0)}return e}_fetchingLoop(e){if(this.bDestroyed)return void this.stopFetchingLoop();if(!this._bOpen||!this.isFetchingLoopStarted())return void this.stopFetchingLoop();if(this._video.paused)return b._onLog&&b._onLog("DCE: Video is paused. Ask in 1s."),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),void(this._frameLoopTimeoutId=setTimeout((()=>{this._fetchingLoop(!0)}),1e3));const t=()=>{b._onLog&&b._onLog("DCE: start fetching a frame: "+Date.now());const e=this.getCurrentRegion();let t=this._getVideoFrame(e);if(!t)return void(b._onLog&&b._onLog("DCE: get a invalid frame, abandon it: "+Date.now()));for(;this._frameQueue&&this._frameQueue.length>=this.maxNumberOfFramesInBuffer;)this._frameQueue.shift();this._frameQueue.push(t),b._onLog&&b._onLog("DCE: finish fetching a frame: "+Date.now());const i=this.mapCameraEvents.get("frameAddedToBuffer");for(let e of i)setTimeout(e,0)},i=()=>{this._frameLoopTimeoutId2&&clearTimeout(this._frameLoopTimeoutId2),this.refreshInterval<=0||(this._frameLoopTimeoutId2=setTimeout((()=>{this.bDestroyed?this.stopFetchingLoop():this._bOpen&&this.isFetchingLoopStarted()?this._video.paused?this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId):(b._onLog&&b._onLog("DCE: second timeout executes: "+Date.now()),t(),i()):this.stopFetchingLoop()}),this.refreshInterval))};e&&(this._frameQueue.length0&&i()):this.refreshInterval>0?(t(),i()):0===this.refreshInterval?t():this.refreshInterval),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameLoopTimeoutId=setTimeout((()=>{this._fetchingLoop(!0)}),this.loopInterval)}startFetchingLoop(){if(this.bDestroyed)throw Error("The DCE instance has been destroyed.");if(this._assertOpen(),this.singleFrameMode)throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");if(this._video.paused)throw Error("The video is paused.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,b._onLog&&b._onLog("start fetching loop: "+Date.now()),this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(b._onLog&&b._onLog("stop fetching loop: "+Date.now()),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameQueue.length=0,this._bFetchingLoopStarted=!1)}getFrameFromBuffer(e){return this._frameQueue&&this._frameQueue.length?e?e{if(!M&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),b._defaultUIElementURL="@engineResourcePath/dce.ui.html";class L extends w{constructor(){super(),this.bFilterRegionInJs=!0,this._onCameraSelChange=()=>{},this._onResolutionSelChange=()=>{},this._onCloseBtnClick=()=>{},this._onPlayed=null}static get version(){return this._version+`(DCE ${b.getVersion()})`}getUIElement(){return this.dce.getUIElement()}async setUIElement(e){await this.dce.setUIElement(e)}get singleFrameMode(){return this.dce.singleFrameMode}set singleFrameMode(e){this.dce.singleFrameMode=e,e&&(this.dce.ifShowScanRegionLaser=!1,(async()=>{let e=await this.getScanSettings();e.oneDTrustFrameCount=1,await this.updateScanSettings(e)})())}get onUnduplicatedRead(){return this.onUniqueRead}set onUnduplicatedRead(e){this.onUniqueRead=e}_assertOpen(){if(!this.dce.isOpen())throw Error("The scanner is not open.")}set regionMaskFillStyle(e){this.dce.setScanRegionMaskStyle({fillStyle:e})}get regionMaskFillStyle(){return this.dce.regionMaskFillStyle}set regionMaskStrokeStyle(e){this.dce.setScanRegionMaskStyle({strokeStyle:e})}get regionMaskStrokeStyle(){return this.dce.regionMaskStrokeStyle}set regionMaskLineWidth(e){this.dce.setScanRegionMaskStyle({lineWidth:e})}get regionMaskLineWidth(){return this.dce.regionMaskLineWidth}set region(e){this._region=e,this.dce&&(e?e instanceof Array||this.dce.setScanRegion(e):this.dce.setScanRegion(null)),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e,this.dce.frameColorMode=e?"rgba":"grey"}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}async createDCEInstance(){this.dce||(w._onLog&&w._onLog("createDCEInstance()"),b.defaultUIElementURL=null,this.dce=await b.createInstance(),this.dce.refreshInterval=200,this.dce.frameColorMode="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this.dce.on("cameraChange",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("resolutionChange",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("cameraClose",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1})),this.dce.on("singleFrameAcquired",(async t=>{if(!t)return;if(!t.data)return;let i;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{data:n,region:o,sx:r,sy:s,width:a,height:d,colorMode:l,timeStamp:c}=t,h={timeStamp:c};if("grey"===l)i=await this._decodeBuffer_Uint8Array(n,a,d,a,e.EnumImagePixelFormat.IPF_GrayScaled,h);else if("rgba"===l)i=await this._decodeBuffer_Uint8Array(n,a,d,4*a,e.EnumImagePixelFormat.IPF_ABGR_8888,h);else{if("bgra"!==l)throw new Error(`Color mode '${l}' is not supported.`);i=await this._decodeBuffer_Uint8Array(n,a,d,4*a,e.EnumImagePixelFormat.IPF_ARGB_8888,h)}await this.clearMapDecodeRecord();for(let e of i)delete e.bUnduplicated;if(this._drawResults(i),w.fixResultLocationWhenFilterRegionInJs(o,i,r,s,a,d,a,d),this.onFrameRead&&this.isOpen()&&!this._bPauseScan&&this.onFrameRead(i),this.onUniqueRead&&this.isOpen()&&!this._bPauseScan)for(let e of i)this.onUniqueRead(e.barcodeText,e)})))}set maxCvsSideLength(e){this._maxCvsSideLength=e,this.dce.maxCvsSideLength=e}get maxCvsSideLength(){return this._maxCvsSideLength}static async createInstance(e){let t=new L;await t.createDCEInstance(),t._instanceID=await L.createInstanceInWorker(!0),"string"==typeof e&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return await t.setUIElement(L.defaultUIElementURL),t.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),t.singleFrameMode||await t.updateRuntimeSettings("single"),t}async decodeCurrentFrame(e){this._assertOpen();let t=null;e&&e.region&&(t=e.region);const i=this.dce._getVideoFrame(t);return this._decode_DCEFrame(i)}static isRegionNormalPreset(e){return 0==e.regionLeft&&0==e.regionTop&&0==e.regionRight&&0==e.regionBottom&&0==e.regionMeasuredByPercentage}async updateRuntimeSettings(t){let i;if("string"==typeof t)if("speed"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region)}else if("balance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region),i.deblurLevel=3,i.expectedBarcodesCount=512,i.localizationModes=[2,16,0,0,0,0,0,0],i.timeout=1e5}else if("coverage"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region),i.deblurLevel=5,i.expectedBarcodesCount=512,i.scaleDownThreshold=1e5,i.localizationModes=[2,16,4,8,0,0,0,0],i.timeout=1e5}else if("single"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,L.isRegionNormalPreset(e.region)?i.region=null:i.region=e.region,i.expectedBarcodesCount=1,i.localizationModes=[16,2,0,0,0,0,0,0],i.barcodeZoneMinDistanceToImageBorders=0}else i=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(i=JSON.parse(JSON.stringify(t)),i.region instanceof Array){let e=t.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(i.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!w._bUseFullFeature){if(0!=(i.barcodeFormatIds&~(e.EnumBarcodeFormat.BF_ONED|e.EnumBarcodeFormat.BF_QR_CODE|e.EnumBarcodeFormat.BF_PDF417|e.EnumBarcodeFormat.BF_DATAMATRIX))||0!=i.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=i.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}{let e=i.region;if(this.bFilterRegionInJs?this.userDefinedRegion=JSON.parse(JSON.stringify(e)):this.userDefinedRegion=null,e instanceof Array)if(e.length){for(let t=0;t{let n=w._nextTaskID++;w._taskCallbackMap.set(n,(i=>{if(i.success){try{this._handleRetJsonString(i.updateReturn)}catch(e){t(e)}return e()}{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),w._dbrWorker.postMessage({type:"updateRuntimeSettings",id:n,instanceID:this._instanceID,body:{settings:JSON.stringify(i)}})})),"single"==t&&(await this.setModeArgument("BinarizationModes",0,"EnableFillBinaryVacancy","0"),await this.setModeArgument("LocalizationModes",0,"ScanDirection","2"),await this.setModeArgument("BinarizationModes",0,"BlockSizeX","71"),await this.setModeArgument("BinarizationModes",0,"BlockSizeY","71"))}_bindUI(){if(!this.getUIElement())throw new Error("Need to define `UIElement` before opening.");if(this.dce._bindUI(),!this.dce.video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'")}_unbindUI(){this.dce._unbindUI()}set onPlayed(e){this.dce.off("played",this._onPlayed),this._onPlayed=e,this.dce.on("played",this._onPlayed)}get onPlayed(){return this._onPlayed}async getAllCameras(){return this.dce.getAllCameras()}async getCurrentCamera(){return this.dce.getSelectedCamera()}async setCurrentCamera(e){return this.dce.selectCamera(e)}getResolution(){return this.dce.getResolution()}async setResolution(e,t){return this.dce.setResolution(e,t)}getVideoSettings(){return this.dce.getVideoSettings()}updateVideoSettings(e){return this.dce.updateVideoSettings(e)}isOpen(){return this.dce&&this.dce.isOpen()}setVideoFit(e){return this.dce&&this.dce.setVideoFit(e)}set ifShowScanRegionMask(e){this.dce&&(this.dce.ifShowScanRegionMask=e)}get ifShowScanRegionMask(){return this.dce&&this.dce.ifShowScanRegionMask}stop(){this.dce.stop(),this.dce.hideScanRegionLaser(),this.dce.hideViewDecorator(),this.dce.hideScanRegionOverlays(),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}pause(){this._drawResults(null),this.dce.pause()}async play(e,t,i){this.dce.ifShowScanRegionLaser=!0;return await this.dce.play(e,t,i)}pauseScan(){this._assertOpen(),this._drawResults(null),this._bPauseScan=!0,this.dce.ifShowScanRegionLaser=!1}resumeScan(){this._assertOpen(),this._bPauseScan=!1,this.dce.ifShowScanRegionLaser=!0}getCapabilities(){return this.dce.getCapabilities()}getCameraSettings(){return this.dce.getCameraSettings()}getConstraints(){return this.dce.getConstraints()}async applyConstraints(e){return this.dce.applyConstraints(e)}async turnOnTorch(){return this.dce.turnOnTorch()}async turnOffTorch(){return this.dce.turnOffTorch()}async setColorTemperature(e){return this.dce.setColorTemperature(e)}async setExposureCompensation(e){return this.dce.setExposureCompensation(e)}async setZoom(e){return this.dce.setZoom(e)}async setFrameRate(e){return this.dce.setFrameRate(e)}getFrameRate(){return this.dce.getFrameRate()}async setFocus(e,t){return this.dce.setFocus(e,t)}getFocus(){return this.dce.getFocus()}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),void this._drawResults(null);if(!this.isOpen())return this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce.video||this.dce.video.paused||this._bPauseScan)return w._onLog&&w._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));w._onLog&&w._onLog("======= once read ======="),w._onLog&&(this._timeStartDecode=Date.now());const t=this._getVideoFrame();if(!t)return this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let i;t._bUseWebGL||"grey"!==t.colorMode||(this.dce.frameColorMode="rgba"),this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{data:n,region:o,sx:r,sy:s,width:a,height:d,colorMode:l,timeStamp:c}=t,h={timeStamp:c};if("grey"===l)i=await this._decodeBuffer_Uint8Array(n,a,d,a,e.EnumImagePixelFormat.IPF_GrayScaled,h);else if("rgba"===l)i=await this._decodeBuffer_Uint8Array(n,a,d,4*a,e.EnumImagePixelFormat.IPF_ABGR_8888,h);else{if("bgra"!==l)throw new Error(`Color mode '${l}' is not supported.`);i=await this._decodeBuffer_Uint8Array(n,a,d,4*a,e.EnumImagePixelFormat.IPF_ARGB_8888,h)}return this.dce&&this.dce.video&&!this.dce.video.paused&&this._drawResults(i),w.fixResultLocationWhenFilterRegionInJs(o,i,r,s,a,d,a,d),i})().then((e=>{w._onLog&&w._onLog(e);let t=this.array_decodeFrameTimeCost,i=this.array_getFrameTimeCost,n=this._indexCurrentDecodingFrame;if((()=>{if(this.region instanceof Array){for(t[n]&&t[n]instanceof Array||(t[n]=[]);t[n].length>=5;)t[n].shift();t[n].push(this._lastInnerDecodeDuration)}else{for(;t.length>=5;)t.shift();t.push(this._lastInnerDecodeDuration)}})(),this._intervalGetVideoFrame=(()=>{let e=0;if(this.region instanceof Array){let o=0,r=0;o=n+1>=this.region.length?0:n+1,r=o+1>=this.region.length?0:o+1,e=t[o]&&t[o].length&&i[r]&&i[r].length?Math.min(...t[o])-Math.max(...i[r]):0}else if(i&&i.length){let n=Math.min(...t),o=Math.max(...i);n&&o&&(e=n-o)}else e=0;return e>0?e:0})()+this.intervalTime,this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead)t=!0;else if("unique"===this.bPlaySoundOnSuccessfulRead)for(let i of e)if(i.bUnduplicated){t=!0;break}t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead)t=!0;else if("unique"===this.bVibrateOnSuccessfulRead)for(let i of e)if(i.bUnduplicated){t=!0;break}if(t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onFrameRead){let t=this._cloneDecodeResults(e);for(let e of t)delete e.bUnduplicated;this.onFrameRead(t)}if(this.onUniqueRead)for(let t of e)t.bUnduplicated&&this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t))}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce.stopFetchingLoop(),w._onLog&&w._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e=this.dce.isFetchingLoopStarted();if(this.dce.loopInterval=this._intervalGetVideoFrame,e||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dce.loopInterval=0,null;const t=this.dce.getFrameFromBuffer();return(e=>{if(!e)return;let t=e.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(t)})(t),t}async open(){this._bindUI();let e=await this.dce.open();return this._bPauseScan=!1,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.dce.ifShowScanRegionLaser=!0,this._loopReadVideo()),this.keepAlive(),e}async openVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open();return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideo()),this.keepAlive(),e}close(){this.dce.close(),this._bPauseScan=!0}async show(){this._bindUI();const e=await this.dce.open(!0);return this._bPauseScan=!1,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.dce.ifShowScanRegionLaser=!0,this._loopReadVideo()),this.keepAlive(),e}async showVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open(!0);return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideo()),this.keepAlive(),e}hide(){this.dce.close(!0),this._bPauseScan=!0}destroyContext(){this.close(),this.bDestroyed||super.destroyContext()}}var O,F,B,P,N,x,V,k,U,G,W,H,J,K,Q,Y,j,X,Z,q,z,$,ee,te,ie,ne,oe;e.EnumBarcodeColourMode=void 0,(O=e.EnumBarcodeColourMode||(e.EnumBarcodeColourMode={}))[O.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",O[O.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",O[O.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",O[O.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",O[O.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",O[O.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",O[O.BICM_SKIP=0]="BICM_SKIP",O[O.BICM_REV=2147483648]="BICM_REV",e.EnumBarcodeComplementMode=void 0,(F=e.EnumBarcodeComplementMode||(e.EnumBarcodeComplementMode={}))[F.BCM_AUTO=1]="BCM_AUTO",F[F.BCM_GENERAL=2]="BCM_GENERAL",F[F.BCM_SKIP=0]="BCM_SKIP",F[F.BCM_REV=2147483648]="BCM_REV",e.EnumBarcodeFormat_2=void 0,(B=e.EnumBarcodeFormat_2||(e.EnumBarcodeFormat_2={}))[B.BF2_NULL=0]="BF2_NULL",B[B.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",B[B.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",B[B.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",B[B.BF2_POSTNET=2097152]="BF2_POSTNET",B[B.BF2_PLANET=4194304]="BF2_PLANET",B[B.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",B[B.BF2_RM4SCC=16777216]="BF2_RM4SCC",B[B.BF2_DOTCODE=2]="BF2_DOTCODE",B[B.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",B[B.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",B[B.BF2_PHARMACODE=12]="BF2_PHARMACODE",e.EnumBinarizationMode=void 0,(P=e.EnumBinarizationMode||(e.EnumBinarizationMode={}))[P.BM_AUTO=1]="BM_AUTO",P[P.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",P[P.BM_SKIP=0]="BM_SKIP",P[P.BM_THRESHOLD=4]="BM_THRESHOLD",P[P.BM_REV=2147483648]="BM_REV",e.EnumClarityCalculationMethod=void 0,(N=e.EnumClarityCalculationMethod||(e.EnumClarityCalculationMethod={}))[N.ECCM_CONTRAST=1]="ECCM_CONTRAST",e.EnumClarityFilterMode=void 0,(x=e.EnumClarityFilterMode||(e.EnumClarityFilterMode={}))[x.CFM_GENERAL=1]="CFM_GENERAL",e.EnumColourClusteringMode=void 0,(V=e.EnumColourClusteringMode||(e.EnumColourClusteringMode={}))[V.CCM_AUTO=1]="CCM_AUTO",V[V.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",V[V.CCM_SKIP=0]="CCM_SKIP",V[V.CCM_REV=2147483648]="CCM_REV",e.EnumColourConversionMode=void 0,(k=e.EnumColourConversionMode||(e.EnumColourConversionMode={}))[k.CICM_GENERAL=1]="CICM_GENERAL",k[k.CICM_SKIP=0]="CICM_SKIP",k[k.CICM_REV=2147483648]="CICM_REV",e.EnumConflictMode=void 0,(U=e.EnumConflictMode||(e.EnumConflictMode={}))[U.CM_IGNORE=1]="CM_IGNORE",U[U.CM_OVERWRITE=2]="CM_OVERWRITE",e.EnumDeblurMode=void 0,(G=e.EnumDeblurMode||(e.EnumDeblurMode={}))[G.DM_SKIP=0]="DM_SKIP",G[G.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",G[G.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",G[G.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",G[G.DM_SMOOTHING=8]="DM_SMOOTHING",G[G.DM_MORPHING=16]="DM_MORPHING",G[G.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",G[G.DM_SHARPENING=64]="DM_SHARPENING",G[G.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",G[G.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",e.EnumDeformationResistingMode=void 0,(W=e.EnumDeformationResistingMode||(e.EnumDeformationResistingMode={}))[W.DRM_AUTO=1]="DRM_AUTO",W[W.DRM_GENERAL=2]="DRM_GENERAL",W[W.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",W[W.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",W[W.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",W[W.DRM_SKIP=0]="DRM_SKIP",W[W.DRM_REV=2147483648]="DRM_REV",e.EnumDPMCodeReadingMode=void 0,(H=e.EnumDPMCodeReadingMode||(e.EnumDPMCodeReadingMode={}))[H.DPMCRM_AUTO=1]="DPMCRM_AUTO",H[H.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",H[H.DPMCRM_SKIP=0]="DPMCRM_SKIP",H[H.DPMCRM_REV=2147483648]="DPMCRM_REV",e.EnumGrayscaleTransformationMode=void 0,(J=e.EnumGrayscaleTransformationMode||(e.EnumGrayscaleTransformationMode={}))[J.GTM_INVERTED=1]="GTM_INVERTED",J[J.GTM_ORIGINAL=2]="GTM_ORIGINAL",J[J.GTM_SKIP=0]="GTM_SKIP",J[J.GTM_REV=2147483648]="GTM_REV",e.EnumImagePreprocessingMode=void 0,(K=e.EnumImagePreprocessingMode||(e.EnumImagePreprocessingMode={}))[K.IPM_AUTO=1]="IPM_AUTO",K[K.IPM_GENERAL=2]="IPM_GENERAL",K[K.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",K[K.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",K[K.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",K[K.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",K[K.IPM_SKIP=0]="IPM_SKIP",K[K.IPM_REV=2147483648]="IPM_REV",e.EnumIntermediateResultSavingMode=void 0,(Q=e.EnumIntermediateResultSavingMode||(e.EnumIntermediateResultSavingMode={}))[Q.IRSM_MEMORY=1]="IRSM_MEMORY",Q[Q.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",Q[Q.IRSM_BOTH=4]="IRSM_BOTH",e.EnumIntermediateResultType=void 0,(Y=e.EnumIntermediateResultType||(e.EnumIntermediateResultType={}))[Y.IRT_NO_RESULT=0]="IRT_NO_RESULT",Y[Y.IRT_ORIGINAL_IMAGE=1]="IRT_ORIGINAL_IMAGE",Y[Y.IRT_COLOUR_CLUSTERED_IMAGE=2]="IRT_COLOUR_CLUSTERED_IMAGE",Y[Y.IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE=4]="IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE",Y[Y.IRT_TRANSFORMED_GRAYSCALE_IMAGE=8]="IRT_TRANSFORMED_GRAYSCALE_IMAGE",Y[Y.IRT_PREDETECTED_REGION=16]="IRT_PREDETECTED_REGION",Y[Y.IRT_PREPROCESSED_IMAGE=32]="IRT_PREPROCESSED_IMAGE",Y[Y.IRT_BINARIZED_IMAGE=64]="IRT_BINARIZED_IMAGE",Y[Y.IRT_TEXT_ZONE=128]="IRT_TEXT_ZONE",Y[Y.IRT_CONTOUR=256]="IRT_CONTOUR",Y[Y.IRT_LINE_SEGMENT=512]="IRT_LINE_SEGMENT",Y[Y.IRT_FORM=1024]="IRT_FORM",Y[Y.IRT_SEGMENTATION_BLOCK=2048]="IRT_SEGMENTATION_BLOCK",Y[Y.IRT_TYPED_BARCODE_ZONE=4096]="IRT_TYPED_BARCODE_ZONE",Y[Y.IRT_PREDETECTED_QUADRILATERAL=8192]="IRT_PREDETECTED_QUADRILATERAL",e.EnumLocalizationMode=void 0,(j=e.EnumLocalizationMode||(e.EnumLocalizationMode={}))[j.LM_SKIP=0]="LM_SKIP",j[j.LM_AUTO=1]="LM_AUTO",j[j.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",j[j.LM_LINES=8]="LM_LINES",j[j.LM_STATISTICS=4]="LM_STATISTICS",j[j.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",j[j.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",j[j.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",j[j.LM_CENTRE=128]="LM_CENTRE",j[j.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",j[j.LM_REV=2147483648]="LM_REV",e.EnumPDFReadingMode=void 0,(X=e.EnumPDFReadingMode||(e.EnumPDFReadingMode={}))[X.PDFRM_RASTER=1]="PDFRM_RASTER",X[X.PDFRM_AUTO=2]="PDFRM_AUTO",X[X.PDFRM_VECTOR=4]="PDFRM_VECTOR",X[X.PDFRM_REV=2147483648]="PDFRM_REV",e.EnumQRCodeErrorCorrectionLevel=void 0,(Z=e.EnumQRCodeErrorCorrectionLevel||(e.EnumQRCodeErrorCorrectionLevel={}))[Z.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",Z[Z.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",Z[Z.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",Z[Z.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q",e.EnumRegionPredetectionMode=void 0,(q=e.EnumRegionPredetectionMode||(e.EnumRegionPredetectionMode={}))[q.RPM_AUTO=1]="RPM_AUTO",q[q.RPM_GENERAL=2]="RPM_GENERAL",q[q.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",q[q.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",q[q.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",q[q.RPM_SKIP=0]="RPM_SKIP",q[q.RPM_REV=2147483648]="RPM_REV",e.EnumResultCoordinateType=void 0,(z=e.EnumResultCoordinateType||(e.EnumResultCoordinateType={}))[z.RCT_PIXEL=1]="RCT_PIXEL",z[z.RCT_PERCENTAGE=2]="RCT_PERCENTAGE",e.EnumResultType=void 0,($=e.EnumResultType||(e.EnumResultType={}))[$.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",$[$.RT_RAW_TEXT=1]="RT_RAW_TEXT",$[$.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",$[$.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT",e.EnumScaleUpMode=void 0,(ee=e.EnumScaleUpMode||(e.EnumScaleUpMode={}))[ee.SUM_AUTO=1]="SUM_AUTO",ee[ee.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",ee[ee.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",ee[ee.SUM_SKIP=0]="SUM_SKIP",ee[ee.SUM_REV=2147483648]="SUM_REV",e.EnumTerminatePhase=void 0,(te=e.EnumTerminatePhase||(e.EnumTerminatePhase={}))[te.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",te[te.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",te[te.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",te[te.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",te[te.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",te[te.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED",e.EnumTextFilterMode=void 0,(ie=e.EnumTextFilterMode||(e.EnumTextFilterMode={}))[ie.TFM_AUTO=1]="TFM_AUTO",ie[ie.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",ie[ie.TFM_SKIP=0]="TFM_SKIP",ie[ie.TFM_REV=2147483648]="TFM_REV",e.EnumTextResultOrderMode=void 0,(ne=e.EnumTextResultOrderMode||(e.EnumTextResultOrderMode={}))[ne.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",ne[ne.TROM_POSITION=2]="TROM_POSITION",ne[ne.TROM_FORMAT=4]="TROM_FORMAT",ne[ne.TROM_SKIP=0]="TROM_SKIP",ne[ne.TROM_REV=2147483648]="TROM_REV",e.EnumTextureDetectionMode=void 0,(oe=e.EnumTextureDetectionMode||(e.EnumTextureDetectionMode={}))[oe.TDM_AUTO=1]="TDM_AUTO",oe[oe.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",oe[oe.TDM_SKIP=0]="TDM_SKIP",oe[oe.TDM_REV=2147483648]="TDM_REV",e.BarcodeReader=w,e.BarcodeScanner=L,Object.defineProperty(e,"__esModule",{value:!0})})); + */function j(e,t,i,r){return new(i||(i=Promise))((function(n,o){function s(e){try{l(r.next(e))}catch(e){o(e)}}function a(e){try{l(r.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}l((r=r.apply(e,t||[])).next())}))}const N="undefined"==typeof self;let V,U,G,W,H;if("undefined"!=typeof navigator&&(V=navigator,U=V.userAgent,G=V.platform,W=V.mediaDevices),!N){const e={init:function(){this.browser=this.searchString(this.dataBrowser)||"unknownBrowser",this.version=this.searchVersion(U)||this.searchVersion(V.appVersion)||0,this.OS=this.searchString(this.dataOS)||"unknownOS","Linux"==this.OS&&-1!=U.indexOf("Windows NT")&&(this.OS="HarmonyOS")},searchString:function(e){for(let t=0;t{let e=!1;if(z)try{(await W.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===H.browser&&H.version>66||"Safari"===H.browser&&H.version>13||"OPR"===H.browser&&H.version>43||"Edge"===H.browser&&H.version;const J=(()=>{if(!N&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})();class q{constructor(e,t){this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapStyle=new Map,this.mapEvents=new Map([["select",[]],["deselect",[]]]),this.isDrawingItem=!0,this._setFabricObject(e),this._mediaType=e.type,this.styleSelector="default",this.styleId=t;for(let e of q.arrStyleSelectors)this._mapStyle.set(e,null)}get mediaType(){return this._mediaType}get drawingLayerId(){return this._drawingLayerId}_setFabricObject(e){this._fabricObject=e;const t=this.mapEvents;this._fabricObject.onSelect=()=>{this.styleSelector="selected";const e=this.mapEvents.get("select");for(let t of e)t&&t.apply(this)},this._fabricObject.onDeselect=()=>{this.styleSelector="default";const e=t.get("deselect");for(let t of e)t&&t.apply(this)},e.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}on(e,t,i){const r=this.mapEvents.get(e);r.includes(t)||r.push(t)}off(e,t){const i=this.mapEvents.get(e),r=i.indexOf(t);-1!==r&&i.splice(r,1)}_setEditable(e){const t=this._fabricObject;e?(t.selectable=!0,t.evented=!0,t.hasControls=!0):(t.selectable=!1,t.evented=!1,t.hasControls=!1)}_extendSet(e,t){return!1}_extendGet(e){}set(e,t){this._extendSet(e,t)||("x"===e?this._fabricObject.set("left",t):"y"===e?this._fabricObject.set("top",t):this._fabricObject.set(e,t)),["vertices","left","top","width","height","scaleX","scaleY","skewX","skewY","padding","angle","strokeWidth"].includes(e)&&this._fabricObject.setCoords()}get(e){let t=this._extendGet(e);return void 0===t&&(t="x"===e?this._fabricObject.get("left"):"y"===e?this._fabricObject.get("top"):this._fabricObject.get(e)),t}}function Q(e,t,i){let r=i.points[this.pointIndex].x-i.pathOffset.x,n=i.points[this.pointIndex].y-i.pathOffset.y;return B.util.transformPoint({x:r,y:n},B.util.multiplyTransformMatrices(i.canvas.viewportTransform,i.calcTransformMatrix()))}function Z(e){let t=new B.Point(e.strokeUniform?1/e.scaleX:1,e.strokeUniform?1/e.scaleY:1).multiply(e.strokeWidth);return new B.Point(e.width+t.x,e.height+t.y)}function $(e,t,i,r){let n=t.target,o=n.controls[n.__corner],s=n.toLocalPoint(new B.Point(i,r),"center","center"),a=Z(n),l=n._getTransformedDimensions(0,0),h={x:s.x*a.x/l.x+n.pathOffset.x,y:s.y*a.y/l.y+n.pathOffset.y};return n.points[o.pointIndex]=h,!0}function ee(e,t){return function(i,r,n,o){let s=r.target,a=B.util.transformPoint({x:s.points[e].x-s.pathOffset.x,y:s.points[e].y-s.pathOffset.y},s.calcTransformMatrix()),l=t(i,r,n,o);s._setPositionDimensions({});let h=Z(s),c=(s.points[e].x-s.pathOffset.x)/h.x,u=(s.points[e].y-s.pathOffset.y)/h.y;return s.setPositionByOrigin(a,c+.5,u+.5),l}}q.arrMediaTypes=["rect","arc","polygon","image","text","line","path"],q.arrStyleSelectors=["default","selected"],"undefined"!=typeof document&&"undefined"!=typeof window&&(B.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(B.util.cancelAnimFrame(this.isRendering),this.isRendering=0),this.forEachObject((function(e){e.dispose&&e.dispose()})),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose&&this.backgroundImage.dispose(),this.backgroundImage=null,this.overlayImage&&this.overlayImage.dispose&&this.overlayImage.dispose(),this.overlayImage=null,this._iTextInstances=null,this.contextContainer=null,this.lowerCanvasEl.classList.remove("lower-canvas"),delete this._originalCanvasStyle,this.lowerCanvasEl.setAttribute("width",this.width),this.lowerCanvasEl.setAttribute("height",this.height),B.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},B.Object.prototype.transparentCorners=!1,B.Object.prototype.cornerSize=20,B.Object.prototype.touchCornerSize=100,B.Object.prototype.cornerColor="rgb(254,142,20)",B.Object.prototype.cornerStyle="circle",B.Object.prototype.strokeUniform=!0,B.Object.prototype.hasBorders=!1,B.ActiveSelection.prototype.onDeselect=function(){return this.getObjects().forEach((e=>{setTimeout(e.onDeselect,0)})),this.destroy(),!1},B.Canvas.prototype.containerClass="",B.Canvas.prototype.getPointer=function(e,t){if(this._absolutePointer&&!t)return this._absolutePointer;if(this._pointer&&t)return this._pointer;var i,r=this.upperCanvasEl,n=B.util.getPointer(e,r),o=r.getBoundingClientRect(),s=o.width||0,a=o.height||0;s&&a||("top"in o&&"bottom"in o&&(a=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(s=Math.abs(o.right-o.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,t||(n=this.restorePointerVpt(n));var l=this.getRetinaScaling();if(1!==l&&(n.x/=l,n.y/=l),0!==s&&0!==a){var h=window.getComputedStyle(r).objectFit,c=r.width,u=r.height,d=s,f=a;i={width:c/d,height:u/f};var g,_,p=c/u,m=d/f;return"contain"===h?p>m?(g=d,_=d/p,{x:n.x*i.width,y:(n.y-(f-_)/2)*i.width}):(g=f*p,_=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===h?p>m?{x:(c-i.height*d)/2+n.x*i.height,y:n.y*i.height}:{x:n.x*i.width,y:(u-i.width*f)/2+n.y*i.width}:{x:n.x*i.width,y:n.y*i.height}}return i={width:1,height:1},{x:n.x*i.width,y:n.y*i.height}});class te{constructor(e,t,i,r){let n,o;switch(this.mapMediaType_Style=new Map,this.mode="viewer",this.onSelectionChange=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,e.hasOwnProperty("getFabricCanvas")?this.fabricCanvas=e.getFabricCanvas():(this.fabricCanvas=new B.Canvas(e,r),this.fabricCanvas.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),this.fabricCanvas.lowerCanvasEl.className="",this.fabricCanvas.upperCanvasEl.className="",this.fabricCanvas.on("selection:created",(function(e){const t=e.selected,i=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!i.includes(t)&&i.push(t)}for(let e of i){const i=[];for(let r of t){const t=r.getDrawingItem();t._drawingLayer===e&&i.push(t)}setTimeout((()=>{e.onSelectionChange&&e.onSelectionChange(i,[])}),0)}})),this.fabricCanvas.on("before:selection:cleared",(function(e){const t=this.getActiveObjects(),i=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!i.includes(t)&&i.push(t)}for(let e of i){const i=[];for(let r of t){const t=r.getDrawingItem();t._drawingLayer===e&&i.push(t)}setTimeout((()=>{const t=[];for(let r of i)e.hasDrawingItem(r)&&t.push(r);t.length>0&&e.onSelectionChange&&e.onSelectionChange([],t)}),0)}})),this.fabricCanvas.on("selection:updated",(function(e){const t=e.selected,i=e.deselected,r=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!r.includes(t)&&r.push(t)}for(let e of i){const t=e.getDrawingItem()._drawingLayer;t&&!r.includes(t)&&r.push(t)}for(let e of r){const r=[],n=[];for(let i of t){const t=i.getDrawingItem();t._drawingLayer===e&&r.push(t)}for(let t of i){const i=t.getDrawingItem();i._drawingLayer===e&&n.push(i)}setTimeout((()=>{e.onSelectionChange&&e.onSelectionChange(r,n)}),0)}})),this.fabricCanvas.wrapperEl.style.position="absolute",e.getFabricCanvas=()=>this.fabricCanvas),this.id=t,this._mapDrawingStyles=i,t){case 1:n=i.get(1),o=i.get(5);break;case 2:n=i.get(2),o=i.get(6);break;case 3:n=i.get(3),o=i.get(7);break;default:n=i.get(4),o=i.get(8)}for(let e of q.arrMediaTypes)this.mapMediaType_Style.set(e,{default:n,selected:o})}getId(){return this.id}_getDrawingStyle(e,t){if("number"!=typeof e)throw new Error("Invalid style id.");const i=this._mapDrawingStyles.get(e);return i?t?JSON.parse(JSON.stringify(i)):i:null}setVisible(e){if(e){for(let e of this._arrFabricObject)e.visible=!0;this._visible=!0}else{for(let e of this._arrFabricObject)e.visible=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyleId(e){return e.styleId?e.styleId:this.mapMediaType_Style.get(e._mediaType)[e.styleSelector].styleId}_getItemCurrentStyle(e){if(e.styleId)return this._getDrawingStyle(e.styleId);return e._mapStyle.get(e.styleSelector)||null}_changeMediaTypeCurStyleInStyleSelector(e,t,i,r){let n;switch(e){case"rect":n=this.fabricCanvas.getObjects("rect");break;case"arc":n=this.fabricCanvas.getObjects("circle");break;case"polygon":n=this.fabricCanvas.getObjects("polygon");break;case"image":n=this.fabricCanvas.getObjects("image");break;case"text":n=this.fabricCanvas.getObjects("text");break;case"line":n=this.fabricCanvas.getObjects("line");break;case"path":n=this.fabricCanvas.getObjects("path")}for(let e of n){if(!this._arrFabricObject.includes(e))continue;const r=e.getDrawingItem();r.styleSelector===t&&this._changeItemStyle(r,i,!0)}r||this.fabricCanvas.renderAll()}_changeItemStyle(e,t,i){if(!e||!t)return;const r=e._getFabricObject();"number"==typeof e.styleId&&(t=this._getDrawingStyle(e.styleId)),r.strokeWidth=t.lineWidth,"fill"===t.paintMode?(r.fill=t.fillStyle,r.stroke=t.fillStyle):"stroke"===t.paintMode?(r.fill="transparent",r.stroke=t.strokeStyle):"strokeAndFill"===t.paintMode&&(r.fill=t.fillStyle,r.stroke=t.strokeStyle),r.fontFamily&&(r.fontFamily=t.fontFamily),r.fontSize&&(r.fontSize=t.fontSize),r.group||(r.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(e,t,i){if(!e||!t)return;const r=e.getChildItems();if("add"===i){if(r.includes(t))return;const i=t._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");t._zIndex=null}else{let i;if(t.styleId)i=this._getDrawingStyle(t.styleId);else{i=this.mapMediaType_Style.get(t._mediaType)[e.styleSelector];const r=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).selected,!0)},n=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).default,!0)};t.on("select",r),t.on("deselect",n),t._funcChangeStyleToSelected=r,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,i,!0)}e._fabricObject.addWithUpdate(t._getFabricObject())}else{if("remove"!==i)return;if(!r.includes(t))return;t._zIndex=null,t._drawingLayer=null,t._drawingLayerId=null,t.off("select",t._funcChangeStyleToSelected),t.off("deselect",t._funcChangeStyleToDefault),t._funcChangeStyleToSelected=null,t._funcChangeStyleToDefault=null,e._fabricObject.removeWithUpdate(t._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(e,t){let i=e._getFabricObject();const r=this.fabricCanvas.getObjects();let n,o;if(r.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===e._mediaType){n=e.getChildItems();for(let e of n)if(e._drawingLayer&&e._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(t&&"object"==typeof t&&!Array.isArray(t))for(let e in t)i.set(e,t[e]);if(n){for(let e of n){if(e.styleId)o=this._getDrawingStyle(e.styleId);else{const t=this.mapMediaType_Style.get(e._mediaType);for(let i of q.arrStyleSelectors)e._mapStyle.set(i,t[i]);o=t.default;const i=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected,!0)},r=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default,!0)};e.on("select",i),e.on("deselect",r),e._funcChangeStyleToSelected=i,e._funcChangeStyleToDefault=r}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,o,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{if(e.styleId)o=this._getDrawingStyle(e.styleId);else{const t=this.mapMediaType_Style.get(e._mediaType);for(let i of q.arrStyleSelectors)e._mapStyle.set(i,t[i]);o=t.default;const i=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected)},r=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default)};e.on("select",i),e.on("deselect",r),e._funcChangeStyleToSelected=i,e._funcChangeStyleToDefault=r}this._changeItemStyle(e,o)}e._zIndex=this.id,e._drawingLayer=this,e._drawingLayerId=this.id;const s=this._arrFabricObject.length;let a=r.length;if(s)a=r.indexOf(this._arrFabricObject[s-1])+1;else for(let t=0;t{for(let t of this._arrDrawingLayer)if(t.getId()===e)return!0;return!1};if(void 0===t){for(let e=100;;e++)if(!i(e)){t=e;break}}else if(i(t))throw new Error("Existed drawing layer id.");const r=new te(e,t,this._mapDrawingStyles,{enableRetinaScaling:!1});return r._manager=this,this._arrDrawingLayer.push(r),this._switchPointerEvent(),r}deleteDrwaingLayer(e){const t=this.getDrawingLayer(e);if(!t)return;const i=this._arrDrawingLayer;t.dispose(),i.splice(i.indexOf(t),1),this._switchPointerEvent()}clearDrawingLayers(){for(let e of this._arrDrawingLayer)e.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(e){for(let t of this._arrDrawingLayer)if(t.getId()===e)return t;return null}getDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const e=this._arrDrawingLayer[0].fabricCanvas.getActiveObjects(),t=[];for(let i of e)t.push(i.getDrawingItem());return t}setDimensions(e,t){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(e,t)}setObjectFit(e){for(let t of this._arrDrawingLayer)t&&t._setObjectFit(e)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(e){this._arrDrawingLayer.length&&(this._arrDrawingLayer[0].fabricCanvas.wrapperEl.style.display=e?"block":"none")}_switchPointerEvent(){if(!this._arrDrawingLayer.length)return;let e=!1;for(let t of this._arrDrawingLayer)"editor"===t.getMode()&&(e=!0);this._arrDrawingLayer[0].fabricCanvas.wrapperEl.style.pointerEvents=e?"":"none"}}class re{constructor(e){this._controlTarget=null,this._arrUsers=[],this._mapAction_UserArgs=new Map,this._mapProperty_UserValue=new Map,this._mapAction_Callbacks=new Map,this._controlTarget=e}setControlTarget(e){this._controlTarget=e}getControlTarget(){return this._controlTarget}register(e){this._arrUsers.includes(e)||this._arrUsers.push(e)}logout(e){const t=this._arrUsers.indexOf(e);-1!==t&&(this.clearUserDisiredAction({user:e}),this.clearUserDisiredValue({user:e}),this._arrUsers.splice(t,1))}getRegisteredUsers(){return this._arrUsers}ifUserExisted(e){return this._arrUsers.includes(e)}setDisiredValue(e,t,i,r){if(!this._arrUsers.includes(e))throw new Error("Unregistered user.");r&&(this._controlTarget[t]=i),this._mapProperty_UserValue.get(t)?this._mapProperty_UserValue.get(t).set(e,i):this._mapProperty_UserValue.set(t,new Map([[e,i]]))}clearUserDisiredValue(e){if(e&&(e.user||e.property)){if(e.property&&e.user){const t=this._mapProperty_UserValue.get(e.property);if(!t)return;t.delete(e.user)}else if(e.property)this._mapProperty_UserValue.delete(e.property);else if(e.user)for(let t of this._mapProperty_UserValue.values())t.delete(e.user)}else this._mapProperty_UserValue=new Map}getValue(e){if(!this._controlTarget)throw new Error("Control target is not set.");return this._controlTarget[e]}getPropertyDisiredValue(e){if(this._mapProperty_UserValue.get(e)){const t=[],i=this._mapProperty_UserValue.get(e);for(let e of i.values())t.push(e);return t}return null}setDisiredAction(e,t,i,r){if(!this._arrUsers.includes(e))throw new Error("Unregistered user.");return i||(i=[]),r?this._controlTarget[t](...i):(this._mapAction_UserArgs.get(t)?this._mapAction_UserArgs.get(t).set(e,i):this._mapAction_UserArgs.set(t,new Map([[e,i]])),this._render(t))}clearUserDisiredAction(e){if(e&&(e.user||e.actionName)){if(e.actionName&&e.user){const t=this._mapAction_UserArgs.get(e.actionName);if(!t)return;t.delete(e.user)}else if(e.actionName)this._mapAction_UserArgs.delete(e.actionName);else if(e.user)for(let t of this._mapAction_UserArgs.values())t.delete(e.user);this.render()}else this._mapAction_UserArgs=new Map}addCallback(e,t){const i=this._mapAction_Callbacks.get(e);i?i.push(t):this._mapAction_Callbacks.set(e,[t])}removeCallback(e,t){const i=this._mapAction_Callbacks.get(e);if(!i)return;const r=i.indexOf(t);-1!==r&&i.splice(r,1)}clearCallback(e){e?this._mapAction_Callbacks.delete(e):this._mapAction_Callbacks.clear()}_fireCallback(e){const t=this._mapAction_Callbacks.get(e);if(t)for(let e of t){if(!e)return;setTimeout(e.bind(this._controlTarget),0)}}_render(e){const t=this._mapAction_UserArgs.get(e);if(!t)throw new Error("Unrecorded action.");if(t.size===this._arrUsers.length){let i=[];for(let e of t.values())e.length>0&&(i=e);if(this._controlTarget[e]){const t=this._controlTarget[e](...i);return this._mapAction_UserArgs.delete(e),this._fireCallback(e),t}}}render(e){if(e)return this._render(e);for(let e of this._mapAction_UserArgs.keys())this._render(e)}}class ne{constructor(){this._maxCvsSideLength=void 0,this._defaultMaxCvsSideLength=null,this._predefinedResolutions=[{width:160,height:120},{width:320,height:240},{width:480,height:360},{width:640,height:480},{width:800,height:600},{width:960,height:720},{width:1280,height:720},{width:1920,height:1080},{width:2560,height:1440},{width:3840,height:2160}],this._mapCameraResolutions=new Map,this._bWebGLSupported=!0,this.extraBindings=[],this._singleFrameMode=!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia),this._cvsSingleFrameMode=null,this._cvsOriginalImage=null,this._imgWidth=0,this._imgHeight=0,this._singleFrameModeIpt=null,this._clickIptSingleFrameMode=()=>{if(this.singleFrameMode){if(!this._singleFrameModeIpt){const e=document.createElement("input");this._singleFrameModeIpt=e,e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.addEventListener("change",(()=>j(this,void 0,void 0,(function*(){const t=e.files[0];e.value="";const i=yield(e=>j(this,void 0,void 0,(function*(){let t=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(t=yield createImageBitmap(e),t)return t}catch(e){}var r;return t||(i=yield(r=e,new Promise(((e,t)=>{let i=URL.createObjectURL(r),n=new Image;n.dbrObjUrl=i,n.src=i,n.onload=()=>{e(n)},n.onerror=e=>{t(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}})))),i})))(t),r=i instanceof HTMLImageElement?i.naturalWidth:i.width,n=i instanceof HTMLImageElement?i.naturalHeight:i.height;this._imgWidth=r,this._imgHeight=n;const o=e=>{const t=Date.now();if(0===r||0===n)return null;const i=this._scanRegion,o=this.getFrameSize(r,n,i,this.maxCvsSideLength);if(!o)return null;let s,a;s=r!==o.sWidth||n!==o.sHeight,a=o.sWidth!==o.dWidth||o.sHeight!==o.dHeight;const l=(()=>!(!this._bWebGLSupported||a))(),h={data:null,region:i?JSON.parse(JSON.stringify(i)):null,sx:o.sx,sy:o.sy,width:o.dWidth,height:o.dHeight,colorMode:null,timeSpent:null,timeStamp:null,isCropped:s,toCanvas:this._toCanvas,_sWidth:o.sWidth,_sHeight:o.sHeight,_bUseWebGL:null};let c;try{c=this._getImageData(e,r,n,o,null,{targetColorMode:this.frameColorMode,bUseWebGL:l})}catch(t){if("WebGLError"!==t.name)throw t;c=this._getImageData(e,r,n,o,null,{targetColorMode:this.frameColorMode,bUseWebGL:!1})}if(!c)return null;const u=Date.now();return ne._onLog&&ne._onLog("DCE: _getVideoFrame(region?) END: "+u),h.data=c.data,h.colorMode=c.colorMode,h._bUseWebGL=c._bUseWebGL,h.timeSpent=u-t,h.timeStamp=u,h};(e=>{let t=this._cvsSingleFrameMode;if(!t){if(t=document.createElement("canvas"),t.style.pointerEvents="none",!this._video)throw new Error("'video' is null.");this._video.after(t),t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.left="0",t.style.top="0",t.style.objectFit="contain",this._cvsSingleFrameMode=t}t.width==r&&t.height==n||(t.width=r,t.height=n);const i=t.getContext("2d");i.clearRect(0,0,t.width,t.height),i.drawImage(e,0,0)})(i),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e);let s;this._updateDrawingLayersSize();try{s=o(i)}catch(e){throw e}const a=this.mapCameraEvents.get("singleFrameAcquired");for(let e of a)if(e)try{const t={data:new Uint8Array(s.data),region:JSON.parse(JSON.stringify(s.region)),sx:s.sx,sy:s.sy,width:s.width,height:s.height,colorMode:s.colorMode,timeSpent:s.timeSpent,timeStamp:s.timeStamp,isCropped:s.isCropped,toCanvas:s.toCanvas,_sWidth:s._sWidth,_sHeight:s._sHeight,_bUseWebGL:s._bUseWebGL};yield e.apply(this,[t])}catch(e){console.error(e)}})))),e.style.position="fixed",e.style.left="-1px",e.style.top="-1px",e.style.width="1px",e.style.height="1px",e.style.backgroundColor="transparent",e.style.color="transparent",document.body.appendChild(e)}this._singleFrameModeIpt.click()}},this.styleEls=[],this._frameColorMode=void 0,this._defaultFrameColorMode="RGBA",this.currentFSColorMode="rgba",this.ifReuseArrayBufferView=!1,this.maxVideoCvsLength=3,this._reusedCvs=null,this._reusedWebGLCvs=null,this._reusedWebGLCtx=null,this._reusedDataContainer=null,this._webGLTexture=null,this._webGLProgramInfo=null,this._webGLBuffers=null,this._recordedStates={},this._toCanvas=function(){const e=document.createElement("canvas");let t;if(e.width=this.width,e.height=this.height,"grey"===this.colorMode){t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;ej(this,void 0,void 0,(function*(){yield this.selectCamera(this._selCam.value),this._bOpen||this.stop()})),this._onResolutionSelChange=()=>j(this,void 0,void 0,(function*(){let e,t;if(this._selRsl&&-1!=this._selRsl.selectedIndex){let i=this._selRsl.options[this._selRsl.selectedIndex];e=i.getAttribute("data-width"),t=i.getAttribute("data-height")}yield this.setResolution(e,t),this._bOpen||this.stop()})),this._onCloseBtnClick=()=>{this.close(!0)},this._bOpen=!1,this.isCameraEnhancer=!0,this.isDisposed=!1,this.videoSrc=null,this.videoSettings={video:{width:{ideal:1280},height:{ideal:720},facingMode:{ideal:"environment"}}},this.iPlayRound=0,this.promisePlay=null,this._ifSaveLastUsedCamera=!1,this.ifSkipCameraInspection=!1,this._allCameras=[],this._currentCamera=null,this._videoTrack=null,this._lastDeviceId=void 0,this._vc_bPlayingVideoBeforeHide=!1,this._ev_documentHideEvent=()=>{"visible"===document.visibilityState?this._vc_bPlayingVideoBeforeHide&&("Firefox"==H.browser?this.play():this._video.play(),this._vc_bPlayingVideoBeforeHide=!1):this._video&&!this._video.paused&&(this._vc_bPlayingVideoBeforeHide=!0,this._video.pause())},this._divVideoContainer=null,this._video=null,this.videoFit="contain",this._cvsScanRegion=null,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=2,this._bShowScanRegionMask=!0,this._bShowScanRegionLaser=void 0,this._defaultBShowScanRegionLaser=!1,this._scanRegion=null,this._arrScanRegionOverlays=[],this._layerBaseCvs=null,this._cvsViewDecorator=null,this._decoratorType=[],this._decoratorArea=null,this._viewDecoratorInfo={rectangle:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},focus:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},crossline:{lineWidth:2,strokeStyle:"rgb(254,142,20)"},crosshair:{lineWidth:4,strokeStyle:"rgb(254,142,20)"}},this._croppingRegions=void 0,this._defaultCroppingRegions=[null],this.bIncreaseRegionIndexAuto=!0,this._croppingRegionIndex=0,this._loopInterval=void 0,this._defaultLoopInterval=0,this._maxNumberOfFramesInBuffer=void 0,this._defaultMaxNumberOfFramesInBuffer=1,this._frameQueue=[],this._bFetchingLoopStarted=!1,this._refreshInterval=void 0,this._defaultRefreshInterval=-1,this._updateLayersTimeout=0,this._updateLayers=()=>{this._resizeTimeoutId&&clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=setTimeout((()=>{if(!this.isDisposed){this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e)}}),this._updateLayersTimeout)},this.mapCameraEvents=new Map([["cameraOpen",[]],["cameraClose",[]],["cameraChange",[]],["resolutionChange",[]],["played",[]],["singleFrameAcquired",[]],["frameAddedToBuffer",[]]]),this._controler=null}static getVersion(){return this._version}static detectEnvironment(){return j(this,void 0,void 0,(function*(){return yield(async()=>({wasm:X,worker:Y,getUserMedia:z,camera:await K(),browser:H.browser,version:H.version,OS:H.OS}))()}))}static set engineResourcePath(e){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");ne._engineResourcePath=(e=>{if(null==e&&(e="./"),!N){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get engineResourcePath(){return this._engineResourcePath}static isStorageAvailable(e){let t;try{t=window[e];const i="__storage_test__";return t.setItem(i,i),t.removeItem(i),!0}catch(e){return e instanceof DOMException&&(22===e.code||1014===e.code||"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)&&t&&0!==t.length}}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"data"in e&&"region"in e&&"sx"in e&&"sy"in e&&"width"in e&&"height"in e&&"colorMode"in e&&"timeSpent"in e&&"timeStamp"in e&&"isCropped"in e&&"toCanvas"in e&&"_sWidth"in e&&"_sHeight"in e&&"_bUseWebGL"in e}set maxCvsSideLength(e){if(e<=0)throw new Error("Invalid value.");this._maxCvsSideLength=e}get maxCvsSideLength(){if(void 0!==this._maxCvsSideLength)return this._maxCvsSideLength;if(this._controler){const e=this._controler.getPropertyDisiredValue("maxCvsSideLength");if(e&&1===e.length)return e[0]}return this._defaultMaxCvsSideLength}static set defaultUIElementURL(e){ne._defaultUIElementURL=e}static get defaultUIElementURL(){var e;return null===(e=ne._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",ne.engineResourcePath)}getUIElement(){return this.UIElement}setUIElement(e){return j(this,void 0,void 0,(function*(){if(this._bOpen)throw new Error("It is not allowed to change the UIElement when the camera is open.");if("string"==typeof e||e instanceof String){if(!e.trim().startsWith("<")){let t=yield fetch(e);if(!t.ok)throw Error("setUIElement(elementOrUrl): Network Error: "+t.statusText);e=yield t.text()}if(!e.trim().startsWith("<"))throw Error("setUIElement(elementOrUrl): Can't get valid HTMLElement.");let t=document.createElement("div");t.innerHTML=e;for(let e=0;e100||e.regionTop>100||e.regionRight>100||e.regionBottom>100)))}set scanRegion(e){if(!this._checkValidRegion(e))throw new Error("Invalid region.");this._scanRegion=JSON.parse(JSON.stringify(e)),this._updateScanRegionCanvas(),this._updateScanAreaDiv();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e)}setScanRegion(e){this.scanRegion=e}getScanRegion(){return JSON.parse(JSON.stringify(this._scanRegion))}_calculateCvsSize(){if(!this._bOpen)return null;let e,t,i;if(this.singleFrameMode)e=this._imgWidth,t=this._imgHeight,i="contain";else{if(!this._video)return null;e=this._video.videoWidth,t=this._video.videoHeight,i=this.getVideoFit()}return{width:e,height:t,objectFit:i}}addScanRegionOverlayCanvas(){this._assertOpen();const e=document.createElement("canvas");if(this._updateScanRegionOverlay(e),!this._scanRegionOverlayContainer){const e=document.createElement("div");if(this._scanRegionOverlayContainer=e,e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e.style.overflow="hidden",e.style.pointerEvents="none",this._layerBaseCvs)this._layerBaseCvs.parentElement.after(e);else if(this._cvsScanRegion)this._cvsScanRegion.before(e);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(e);else{if(!this._video)throw new Error("'video' is null.");this._video.after(e)}this._recordedStates.overlayShow=!0}return this._scanRegionOverlayContainer.append(e),this._arrScanRegionOverlays.push(e),e}removeScanRegionOverlayCanvas(e){const t=this._arrScanRegionOverlays.indexOf(e);-1!==t&&(e.remove(),this._arrScanRegionOverlays.splice(t,1))}_updateScanRegionOverlay(e){if(!e)return;const t=this._calculateCvsSize();if(!t)return;const{width:i,height:r,objectFit:n}=t;if(i<=0||r<=0)return e.width=0,void(e.height=0);const o=this._getRegionInPixels(i,r,this._scanRegion),s=this.getFrameSize(i,r,this._scanRegion,this.maxCvsSideLength),a=s.dWidth,l=s.dHeight;e.width==a&&e.height==l||(e.width=a,e.height=l);const h=window.getComputedStyle(this._video),c=parseFloat(h.width),u=parseFloat(h.height),d=c/u,f=i/r;let g,_,p,m,v=1;"contain"===n?(dd?(v=u/r,g=o.regionLeft*v-(i*v-c)/2,_=o.regionTop*v):(v=c/i,g=o.regionLeft*v,_=o.regionTop*v-(r*v-u)/2),p=(o.regionRight-o.regionLeft)*v,m=(o.regionBottom-o.regionTop)*v):(g=0,_=0,p=0,m=0),e.style.position="absolute",e.style.left=g+"px",e.style.top=_+"px",e.style.width=p+"px",e.style.height=m+"px"}showScanRegionOverlays(){this._scanRegionOverlayContainer&&("none"==this._scanRegionOverlayContainer.style.display&&(this._scanRegionOverlayContainer.style.display=""),this._recordedStates.overlayShow=!0)}hideScanRegionOverlays(){this._scanRegionOverlayContainer&&(this._scanRegionOverlayContainer.style.display="none",this._recordedStates.overlayShow=!1)}setViewDecorator(e,t){if(!e)return void(this._cvsViewDecorator&&(this._cvsViewDecorator.remove(),this._cvsViewDecorator=null));this._assertOpen();let i=[];if("string"==typeof e?i.push(e):Array.isArray(e)&&(i=JSON.parse(JSON.stringify(e))),!this._cvsViewDecorator){if(this._cvsViewDecorator=document.createElement("canvas"),this._cvsViewDecorator.style.pointerEvents="none",this._cvsScanRegion)this._cvsScanRegion.after(this._cvsViewDecorator);else if(this._scanRegionOverlayContainer)this._scanRegionOverlayContainer.after(this._cvsViewDecorator);else if(this._layerBaseCvs)this._layerBaseCvs.parentElement.after(this._cvsViewDecorator);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(this._cvsViewDecorator);else{if(!this._video)throw new Error("'video' is null.");this._video.after(this._cvsViewDecorator)}this._recordedStates.decoratorShow=!0}this._decoratorArea=JSON.parse(JSON.stringify(t)),this._decoratorType.length=0;const r=["rectangle","focus"],n=["crossline","crosshair"];let o=!1,s=!1;for(let e of i)e=e.toLowerCase(),r.includes(e)&&!o&&(o=!0,this._decoratorType.push(e)),n.includes(e)&&!s&&(s=!0,!this._decoratorType.includes(e)&&this._decoratorType.push(e));this._updateViewDecorator()}getViewDecorator(){return{type:JSON.parse(JSON.stringify(this._decoratorType)),area:JSON.parse(JSON.stringify(this._decoratorArea)),canvas:this._cvsViewDecorator}}showViewDecorator(){this._cvsViewDecorator&&("none"==this._cvsViewDecorator.style.display&&(this._cvsViewDecorator.style.display=""),this._recordedStates.decoratorShow=!0)}hideViewDecorator(){this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none",this._recordedStates.decoratorShow=!1)}setViewDecoratorLineWidth(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("lineWidth"))throw new Error(`It is not allowed to change the property 'lineWidth' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].lineWidth=t,this._updateViewDecorator()}setViewDecoratorStrokeStyle(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("strokeStyle"))throw new Error(`It is not allowed to change the property 'strokeStyle' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].strokeStyle=t,this._updateViewDecorator()}setViewDecoratorFillStyle(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("fillStyle"))throw new Error(`It is not allowed to change the property 'fillStyle' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].fillStyle=t,this._updateViewDecorator()}setViewDecoratorMaskFillStyle(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("maskFillStyle"))throw new Error(`It is not allowed to change the property 'maskFillStyle' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].maskFillStyle=t,this._updateViewDecorator()}_updateViewDecorator(){if(!this._bOpen)return;if(!this._cvsViewDecorator||!this._decoratorArea)return;let e;if(this.singleFrameMode)e="contain";else{if(!this._video)return;e=this.getVideoFit()}const t=this._cvsViewDecorator;t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.left="0",t.style.top="0",t.style.objectFit=e;const i=this.getVisibleRegion(!0),r=i.regionRight-i.regionLeft,n=i.regionBottom-i.regionTop;if(t.width==r&&t.height==n||(t.width=r,t.height=n),r<=0||n<=0)return;const o=t.getContext("2d");o.clearRect(0,0,t.width,t.height);const s=this._decoratorArea.x/100*r,a=this._decoratorArea.y/100*n,l=this._decoratorArea.width/100*r,h=this._decoratorArea.height/100*n;for(let e of this._decoratorType){if("rectangle"===e){o.fillStyle=this._viewDecoratorInfo.rectangle.maskFillStyle,o.fillRect(0,0,t.width,t.height),o.clearRect(Math.round(s),Math.round(a),Math.round(l),Math.round(h)),o.fillStyle=this._viewDecoratorInfo.rectangle.fillStyle,o.fillRect(Math.round(s),Math.round(a),Math.round(l),Math.round(h)),o.lineWidth=this._viewDecoratorInfo.rectangle.lineWidth,o.strokeStyle=this._viewDecoratorInfo.rectangle.strokeStyle;const e=o.lineWidth/2;o.strokeRect(Math.round(s-e),Math.round(a-e),Math.round(l+o.lineWidth),Math.round(h+o.lineWidth))}if("focus"===e){o.fillStyle=this._viewDecoratorInfo.focus.maskFillStyle,o.fillRect(0,0,t.width,t.height),o.clearRect(Math.round(s),Math.round(a),Math.round(l),Math.round(h)),o.fillStyle=this._viewDecoratorInfo.focus.fillStyle,o.fillRect(Math.round(s),Math.round(a),Math.round(l),Math.round(h)),o.lineWidth=this._viewDecoratorInfo.focus.lineWidth,o.strokeStyle=this._viewDecoratorInfo.focus.strokeStyle;const e=o.lineWidth/2,i=[0,.25,.75,1],r=[0,.25,.75,1];o.beginPath();for(let e=0;e{const e=parseFloat(window.getComputedStyle(this._video).width),t=parseFloat(window.getComputedStyle(this._video).height);let o,s={regionBottom:r,regionRight:i,regionLeft:0,regionTop:0,regionMeasuredByPercentage:!1};return"cover"===n?e/tthis.maxNumberOfFramesInBuffer;)this._frameQueue.shift()}get maxNumberOfFramesInBuffer(){if(void 0!==this._maxNumberOfFramesInBuffer)return this._maxNumberOfFramesInBuffer;if(this._controler){const e=this._controler.getPropertyDisiredValue("maxNumberOfFramesInBuffer");if(e&&1===e.length)return e[0]}return this._defaultMaxNumberOfFramesInBuffer}get numberOfFramesInBuffer(){return this._frameQueue.length}set refreshInterval(e){this._refreshInterval=e}get refreshInterval(){if(void 0!==this._refreshInterval)return this._refreshInterval;if(this._controler){const e=this._controler.getPropertyDisiredValue("refreshInterval");if(e&&1===e.length)return e[0]}return this._defaultRefreshInterval}static createInstance(e){return j(this,void 0,void 0,(function*(){let t=new ne;("string"==typeof e||e instanceof String)&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return this._hasEngineResourceLoaded=!0,ne.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{ne.onWarning&&ne.onWarning({id:1,message:"Not using HTTP protocol, the SDK may not work correctly."})}),0):location&&"https:"!==location.protocol&&setTimeout((()=>{ne.onWarning&&ne.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)),t._drawingLayersManager=new ie,t}))}play(e,t,i,r){return j(this,void 0,void 0,(function*(){if(this._video&&this.videoSrc){yield new Promise(((e,t)=>{this._video.onloadedmetadata=()=>j(this,void 0,void 0,(function*(){this._video&&(this._video.onloadedmetadata=null,yield this._video.play(),e())})),"string"==typeof this.videoSrc||this.videoSrc instanceof String?this._video.src=this.videoSrc:this._video.srcObject=this.videoSrc,setTimeout((()=>t(new Error("Failed to play video. Timeout."))),4e3)}));const e={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};this.playCallbackInfo=JSON.parse(JSON.stringify(e));const t=this.mapCameraEvents.get("played");for(let i of t){if(!i)continue;const t=JSON.parse(JSON.stringify(e));setTimeout((()=>i.apply(this,[t])),0)}return this._recordedStates.videoPlaying=!0,e}if(this.singleFrameMode)return r&&r.notTriggerSingleFrameClick||this._clickIptSingleFrameMode(),this.playCallbackInfo={width:0,height:0,deviceId:null},JSON.parse(JSON.stringify(this.playCallbackInfo));if(!this._video)return this.playCallbackInfo=null,null;const n=++this.iPlayRound;let o=null,s=0,a=0;if(this._currentCamera&&(o=this._currentCamera.deviceId),this._video&&(s=this._video.videoWidth,a=this._video.videoHeight),this.promisePlay&&(yield this.promisePlay,nj(this,void 0,void 0,(function*(){var r;try{this._video&&this._video.srcObject&&this.stop(),ne._onLog&&ne._onLog("DCE: ======before video========");const n=()=>{if(!this._video)throw d&&d.getTracks().forEach((e=>{e.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null.")},l=this.getVideoSettings();let h;"boolean"==typeof l.video&&(l.video={});const c=["rear","back","rück","arrière","trasera","trás","traseira","posteriore","后面","後面","背面","后置","後置","背置","задней","الخلفية","후","arka","achterzijde","หลัง","baksidan","bagside","sau","bak","tylny","takakamera","belakang","אחורית","πίσω","spate","hátsó","zadní","darrere","zadná","задня","stražnja","belakang","बैक"],u=()=>{for(let e of this._allCameras){let t=e.label.toLowerCase();if(t&&c.some((e=>-1!=t.indexOf(e)))&&/\b0(\b)?/.test(t)){delete l.video.facingMode,l.video.deviceId={ideal:e.deviceId};break}}l.video.deviceId||-1==["Android","HarmonyOS"].indexOf(H.OS)||(delete l.video.facingMode,l.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})};if(e)delete l.video.facingMode,l.video.deviceId={exact:e};else if(l.video.deviceId);else if(this._lastDeviceId)delete l.video.facingMode,l.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&ne.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete l.video.facingMode,l.video.deviceId={exact:window.localStorage.getItem("dce_last_camera_id")};const w=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),T=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));w&&T&&(l.video.width=w,l.video.height=T)}else if(this.ifSkipCameraInspection);else if(l.video.facingMode){if("iPhone"!==H.OS&&"Mac"!==H.OS&&(yield this.getAllCameras(!0)),!this._video)return null;let x=l.video.facingMode;x instanceof Array&&x.length&&(x=x[0]),x=x.exact||x.ideal||x,"environment"===x&&(h=!!l.video.facingMode,u())}let d;t&&(l.video.width={ideal:t}),i&&(l.video.height={ideal:i}),ne._onLog&&ne._onLog("DCE: ======try getUserMedia========");let f,g=[0,500],_=null,p=null;function m(e){return j(this,void 0,void 0,(function*(){for(let t of g){n(),t&&(yield new Promise((e=>setTimeout(e,t)))),n();{const t=e.video.deviceId;p=t?t.exact||t.ideal||t:null}try{ne._onLog&&ne._onLog("DCE: ask "+JSON.stringify(e)),d=yield navigator.mediaDevices.getUserMedia(e),n();break}catch(e){_=e,ne._onLog&&ne._onLog("DCE: "+e.message||e)}}}))}if(yield m(l),d||(ne._onLog&&ne._onLog("DCE: ======try getUserMedia again========"),f=JSON.parse(JSON.stringify(l)),"object"==typeof f.video&&("iPhone"==H.OS?(t>=1280||i>=1280?f.video.width=1280:t>=640||i>=640?f.video.width=640:(t<640||i<640)&&(f.video.width=320),delete f.video.height):h&&!l.video.deviceId?(delete f.video.facingMode,this._allCameras.length&&(f.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):f.video=!0),ne._onLog&&ne._onLog("DCE: "+f),yield m(f)),d||(g=[1e3,2e3],yield m(l)),d||(yield m(f)),!d)throw _;const v=()=>{const e=d.getVideoTracks();let t,i;if(e.length&&(t=this._videoTrack=e[0]),this._video&&t){const e=t.getSettings();if(e)for(let r of this._allCameras)if(e.deviceId===r.deviceId){r._checked=!0,r.label=t.label,i=r;break}if(!i&&p)for(let e of this._allCameras)if(p==e.deviceId){t.label&&(e._checked=!0,e.label=t.label),i=e;break}}this._currentCamera=i};if(yield this.getAllCameras(!0),n(),h){v(),u();let E=l.video.deviceId;E&&(E=E.exact||E.ideal||E);let A=null===(r=this._currentCamera)||void 0===r?void 0:r.deviceId;!E||A&&E==A||(d.getTracks().forEach((e=>{e.stop()})),g=[0,500,1e3,2e3],yield m(l))}n();const y=()=>j(this,void 0,void 0,(function*(){ne._onLog&&ne._onLog("======play video========"),yield new Promise(((e,t)=>{n(),this._video.onloadedmetadata=()=>j(this,void 0,void 0,(function*(){n(),this._video.onloadedmetadata=null,yield this._video.play(),e()})),this._video.srcObject=d,setTimeout((()=>t(new Error("Failed to play video. Timeout."))),4e3)}))}));yield y(),n(),ne._onLog&&ne._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const S=this._video.videoWidth+"x"+this._video.videoHeight;this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",this._video.videoWidth),this._optGotRsl.setAttribute("data-height",this._video.videoHeight),this._optGotRsl.innerText=S,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),ne._onLog&&ne._onLog("DCE: got "+S),v(),n(),this._renderSelCameraInfo();const b={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};b.deviceId&&(this._lastDeviceId=b.deviceId,this.ifSaveLastUsedCamera&&ne.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),l.video.width&&l.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(l.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(l.video.height)))));const C=this.mapCameraEvents.get("played");for(let I of C){if(!I)continue;const O=JSON.parse(JSON.stringify(b));setTimeout((()=>I.apply(this,[O])),0)}if(o&&o!=b.deviceId){const R=this.mapCameraEvents.get("cameraChange");for(let D of R){if(!D)continue;const M=JSON.parse(JSON.stringify(b));setTimeout((()=>D.apply(this,[M])),0)}}if(s&&a&&(s!=b.width||a!=b.height)){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let P of this._arrScanRegionOverlays)P&&this._updateScanRegionOverlay(P);this._cvsOriginalImage||this._updateDrawingLayersSize();const L=this.mapCameraEvents.get("resolutionChange");for(let F of L){if(!F)continue;const k=JSON.parse(JSON.stringify(b));setTimeout((()=>F.apply(this,[k])),0)}}return this.promisePlay=null,b}catch(B){throw this.promisePlay=null,this._bgLoading&&(this._bgLoading.style.display="none"),"NotFoundError"===B.name&&(DOMException?B=new DOMException("No camera available, please use a device with an accessible camera.",B.name):(B=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),B}})))();const l=yield this.promisePlay;return this.playCallbackInfo=JSON.parse(JSON.stringify(l)),this._recordedStates.videoPlaying=!0,l}))}resume(){return j(this,void 0,void 0,(function*(){this._assertOpen(),yield this.play(),this.ifShowScanRegionLaser&&this.showScanRegionLaser()}))}pause(){this._assertOpen(),this._video&&(this._video.pause(),this._recordedStates.videoPlaying=!1),this.ifShowScanRegionLaser&&this.hideScanRegionLaser()}_bindUI(){if(!this.UIElement)throw new Error("Need to define `UIElement` before opening.");const e=[this.UIElement];for(let t=0;t','','',''].join(""),this._optGotRsl=this._optGotRsl||this._selRsl.options[0])):!this._optGotRsl&&t.classList.contains("dce-opt-gotResolution")?this._optGotRsl=t:!this._btnClose&&t.classList.contains("dce-btn-close")?this._btnClose=t:!this._selMinLtr&&t.classList.contains("dlr-sel-minletter")?(this._selMinLtr=t,this._selMinLtr.options.length||(this._selMinLtr.innerHTML=[this._optGotMinLtr?"":'','','','','','','','','','',''].join(""),this._optGotMinLtr=this._optGotMinLtr||this._selMinLtr.options[0])):!this._optGotMinLtr&&t.classList.contains("dlr-opt-gotMinLtr")&&(this._optGotMinLtr=t);if(this.extraBindings&&this.extraBindings.length)for(let i of this.extraBindings)try{i(t)}catch(e){}}if(!this._video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'");this.singleFrameMode?(this._video&&(this._video.addEventListener("click",this._clickIptSingleFrameMode),this._video.style.cursor="pointer",this._video.setAttribute("title","Take a photo")),this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none"),this._bgCamera&&(this._bgCamera.style.display="block")):(this._selCam&&(this._selCam.style.display="block",this._selCam.addEventListener("change",this._onCameraSelChange)),this._selRsl&&(this._selRsl.style.display="block",this._selRsl.addEventListener("change",this._onResolutionSelChange)),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._bgLoading&&(this._bgLoading.style.display="block")),this._btnClose&&this._btnClose.addEventListener("click",this._onCloseBtnClick),document.addEventListener("visibilitychange",this._ev_documentHideEvent),ResizeObserver?(this._resizeObserver||(this._resizeObserver=new ResizeObserver((e=>{for(let t of e)t.target===this._divVideoContainer&&this._updateLayers()}))),this._divVideoContainer&&this._resizeObserver.observe(this._divVideoContainer)):window.addEventListener("resize",this._updateLayers)}_unbindUI(){this.singleFrameMode?(this._video&&(this._video.removeEventListener("click",this._clickIptSingleFrameMode),this._video.style.cursor="",this._video.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._bgLoading&&(this._bgLoading.style.display="none"),this._selCam&&this._selCam.removeEventListener("change",this._onCameraSelChange),this._selRsl&&this._selRsl.removeEventListener("change",this._onResolutionSelChange),this._btnClose&&this._btnClose.removeEventListener("click",this._onCloseBtnClick),this.hideScanRegionLaser(),this.hideViewDecorator(),this.hideScanRegionOverlays(),this._drawingLayersManager.setVisible(!1),this._hideOriginalImageCvs(),this._video&&(this._video.onloadedmetadata=null,this._video.remove()),this._divVideoContainer=null,this._video=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._cvsScanRegion&&(this._cvsScanRegion.remove(),this._cvsScanRegion=null),this._singleFrameModeIpt&&(this._singleFrameModeIpt.remove(),this._singleFrameModeIpt=null),this._cvsSingleFrameMode&&(this._cvsSingleFrameMode.remove(),this._cvsSingleFrameMode=null),document.removeEventListener("visibilitychange",this._ev_documentHideEvent),ResizeObserver?this._resizeObserver&&this._resizeObserver.disconnect():window.removeEventListener("resize",this._updateLayers)}_assertOpen(){if(!this._bOpen)throw Error("The camera is not open.")}open(e){return j(this,void 0,void 0,(function*(){this.UIElement||(yield this.setUIElement(ne.defaultUIElementURL)),this._bindUI(),e&&this.appendAndShowUI();let t=yield this.play();this.bOpen=!0;const i=this.mapCameraEvents.get("cameraOpen");for(let e of i){if(!e)continue;const i=JSON.parse(JSON.stringify(t));setTimeout((()=>e.apply(this,[i])),0)}return t}))}close(e){if(!this._video)return;this.stop(),this._hideOriginalImage(!1),this._unbindUI(),e&&this.hideUI(),this.stopFetchingLoop(),this.bOpen=!1;const t=this.mapCameraEvents.get("cameraClose");for(let e of t){if(!e)continue;const t={width:0,height:0,deviceId:null};setTimeout((()=>e.apply(this,[t])),0)}}stop(){this._video&&this._video.srcObject&&(ne._onLog&&ne._onLog("DCE: ======stop video========"),this._video.srcObject.getTracks().forEach((e=>{e.stop()})),this._video.srcObject=null,this._videoTrack=null,this._currentCamera=null),this._video&&this.videoSrc&&(ne._onLog&&ne._onLog("DCE: ======stop existing video========"),this._video.pause(),this._video.currentTime=0),this._bgLoading&&(this._bgLoading.style.animationPlayState=""),this._frameQueue.length=0,this._reusedCvs&&this._reusedCvs.ctx2d&&this._reusedCvs.ctx2d.clearRect(0,0,this._reusedCvs.width,this._reusedCvs.height),this.forceLoseContext()}getAllCameras(e){return j(this,void 0,void 0,(function*(){let t=yield navigator.mediaDevices.enumerateDevices();if(!e&&t&&t.length&&!t[0].deviceId){let e=yield navigator.mediaDevices.getUserMedia({video:!0});t=yield navigator.mediaDevices.enumerateDevices(),e.getTracks().forEach((e=>{e.stop()})),e=null}const i=[],r=[];if(this._allCameras)for(let e of this._allCameras)e._checked&&r.push(e);for(let e=0;e{const i=this._mapCameraResolutions.get(e);if(!i||!i.length)return!1;for(let e of i)if(e[0]===t.width&&e[1]===t.height)return!0;return!1},r=(e,t,i)=>j(this,void 0,void 0,(function*(){const r={video:{deviceId:{exact:e},width:{ideal:t},height:{ideal:i}}};let n=null;try{n=yield navigator.mediaDevices.getUserMedia(r)}catch(e){return null}if(!n)return null;const o=n.getVideoTracks();let s=null;try{const e=o[0].getSettings();s={width:e.width,height:e.height}}catch(e){const t=document.createElement("video");t.srcObject=n,s={width:t.videoWidth,height:t.videoHeight},t.srcObject=null}return o.forEach((e=>{e.stop()})),s}));if(!this._bOpen){const n=this.videoSettings.video.deviceId;if(!n)return null;if(t=n.hasOwnProperty("exact")?this.videoSettings.video.deviceId.exact:n.hasOwnProperty("ideal")?this.videoSettings.video.deviceId.ideal:this.videoSettings.video.deviceId,!t)return null;let o=this._mapCameraResolutions.get(t);if(o&&!e)return this._mapCameraResolutions.get(t);this._mapCameraResolutions.set(t,[]),o=this._mapCameraResolutions.get(t);for(let e of this._predefinedResolutions){const n=yield r(t,e.width,e.height);n&&!i(t,n)&&o.push([n.width,n.height])}return o}if(this._currentCamera){t=this._currentCamera.deviceId;let r=this._mapCameraResolutions.get(t);if(r&&!e)return this._mapCameraResolutions.get(t);this._mapCameraResolutions.set(t,[]),r=this._mapCameraResolutions.get(t);const n=this.getConstraints();for(let e of this._predefinedResolutions){yield this._videoTrack.applyConstraints({width:{ideal:e.width},height:{ideal:e.height}});const n=this._videoTrack.getSettings(),o={width:n.width,height:n.height};i(t,o)||r.push([o.width,o.height])}return yield this._videoTrack.applyConstraints(n),r}return null}))}on(e,t){if(!this.mapCameraEvents.has(e))throw new Error(`Event '${e}' is not exists.`);const i=this.mapCameraEvents.get(e);i.includes(t)||i.push(t)}off(e,t){if(!this.mapCameraEvents.has(e))throw new Error(`Event '${e}' is not exists.`);const i=this.mapCameraEvents.get(e),r=i.indexOf(t);-1!==r&&i.splice(r,1)}offAll(e){if(e){if("string"==typeof e){const t=this.mapCameraEvents.get(e);t&&(t.length=0)}}else for(let e of this.mapCameraEvents.values())e&&(e.length=0)}getVideoSettings(){return JSON.parse(JSON.stringify(this.videoSettings))}updateVideoSettings(e){return this.videoSettings=JSON.parse(JSON.stringify(e)),this._lastDeviceId=null,this._bOpen?this.play():Promise.resolve()}isOpen(){return this._bOpen}getCapabilities(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCapabilities()' is unavailable in singleFrameMode.");return this._videoTrack&&this._videoTrack.getCapabilities?this._videoTrack.getCapabilities():{}}getCameraSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCameraSettings()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings():null}getConstraints(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getConstraints()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getConstraints():null}applyConstraints(e){return j(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'applyConstraints()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error('"_videoTrack" is null.');if(!this._videoTrack.applyConstraints)throw Error("Not supported.");return yield this._videoTrack.applyConstraints(e)}))}turnOnTorch(){return j(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOnTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return yield this._videoTrack.applyConstraints({advanced:[{torch:!0}]});throw Error("Not supported.")}))}turnOffTorch(){return j(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOffTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return yield this._videoTrack.applyConstraints({advanced:[{torch:!1}]});throw Error("Not supported.")}))}setColorTemperature(e){return j(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setColorTemperature()' is unavailable in singleFrameMode.");let t=this.getCapabilities().colorTemperature;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),yield this._videoTrack.applyConstraints({advanced:[{colorTemperature:e}]})}))}setExposureCompensation(e){return j(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setExposureCompensation()' is unavailable in singleFrameMode.");let t=this.getCapabilities().exposureCompensation;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),yield this._videoTrack.applyConstraints({advanced:[{exposureCompensation:e}]})}))}setZoom(e){return j(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setZoom()' is unavailable in singleFrameMode.");let t=this.getCapabilities().zoom;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),yield this._videoTrack.applyConstraints({advanced:[{zoom:e}]})}))}setFrameRate(e){return j(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFrameRate()' is unavailable in singleFrameMode.");let t=this.getCapabilities().frameRate;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),yield this._videoTrack.applyConstraints({width:{ideal:Math.max(this._video.videoWidth,this._video.videoHeight)},frameRate:e})}))}getFrameRate(){return this.getCameraSettings().frameRate}setFocus(e,t){return j(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFocus()' is unavailable in singleFrameMode.");const i=this.getCapabilities().focusMode,r=this.getCapabilities().focusDistance;if(!i||!i.includes(e)||!r)throw Error("Not supported.");return t?(tr.max&&(t=r.max),yield this._videoTrack.applyConstraints({advanced:[{focusMode:e,focusDistance:t}]})):yield this._videoTrack.applyConstraints({advanced:[{focusMode:e}]})}))}getFocus(){const e=this.getCameraSettings().focusMode;return"continuous"===e?{mode:e}:{mode:e,distance:this.getCameraSettings().focusDistance}}getFrameSize(e,t,i,r){if(!e||!t)return null;let n,o,s,a,l=e,h=t;const c={regionLeft:0,regionTop:0,regionRight:l,regionBottom:h,regionMeasuredByPercentage:!1};i?(i.regionMeasuredByPercentage?(c.regionLeft=i.regionLeft*l/100,c.regionTop=i.regionTop*h/100,c.regionRight=i.regionRight*l/100,c.regionBottom=i.regionBottom*h/100):(c.regionLeft=i.regionLeft,c.regionTop=i.regionTop,c.regionRight=i.regionRight,c.regionBottom=i.regionBottom),n=c.regionLeft,o=c.regionTop,l=Math.round(c.regionRight-c.regionLeft),h=Math.round(c.regionBottom-c.regionTop)):(n=0,o=0);const u=Math.max(l,h);if(r&&r>0&&u>r){const e=r/u;l>h?(s=r,a=Math.round(h*e)):(s=Math.round(l*e),a=r)}else s=l,a=h;return s<=0||a<=0?null:{sx:n,sy:o,sWidth:l,sHeight:h,dWidth:s,dHeight:a}}getFrame(){if(this.singleFrameMode)throw Error("'getFrame()' is unavailable in singleFrameMode.");if(this._assertOpen(),this.singleFrameMode)throw new Error("'getFrame()' is unavailable in singleFrameMode.");return this._getVideoFrame(this._scanRegion)}getImage(){const e=this.getFrame();return e.pixelFormat=e.colorMode,Object.assign(Object.assign({},e),{pixelFormat:e.colorMode})}_getVideoFrame(e,t){if(this.isDisposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getVideoFrame()' is unavailable in singleFrameMode.");const i=Date.now();ne._onLog&&ne._onLog("DCE: _getVideoFrame(region?) START: "+i);const r=this._video.videoWidth,n=this._video.videoHeight;if(0===r||0===n)return null;const o=this.getFrameSize(r,n,e,this.maxCvsSideLength);if(!o)return null;let s,a;s=r!==o.sWidth||n!==o.sHeight,a=o.sWidth!==o.dWidth||o.sHeight!==o.dHeight;const l=(()=>!(!this._bWebGLSupported||a))(),h={data:null,region:e?JSON.parse(JSON.stringify(e)):null,sx:o.sx,sy:o.sy,width:o.dWidth,height:o.dHeight,colorMode:null,timeSpent:null,timeStamp:null,isCropped:s,toCanvas:this._toCanvas,_sWidth:o.sWidth,_sHeight:o.sHeight,_bUseWebGL:null};let c;try{c=this._getImageData(this._video,r,n,o,t,{targetColorMode:this.frameColorMode,bUseWebGL:l})}catch(e){if("WebGLError"!==e.name)throw e;c=this._getImageData(this._video,r,n,o,t,{targetColorMode:this.frameColorMode,bUseWebGL:!1})}if(!c)return null;const u=Date.now();return ne._onLog&&ne._onLog("DCE: _getVideoFrame(region?) END: "+u),h.data=c.data,h.colorMode=c.colorMode,h._bUseWebGL=c._bUseWebGL,h.timeSpent=u-i,h.timeStamp=u,h}_getImageData(e,t,i,r,n,o){if(this.isDisposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(!t||!i)return null;ne._onLog&&ne._onLog("DCE: _getImageData() START: "+Date.now());const{sx:s,sy:a,sWidth:l,sHeight:h,dWidth:c,dHeight:u}=r;let d;if(d=o&&o.targetColorMode?o.targetColorMode.toLowerCase():"rgba",o&&o.bUseWebGL){this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas"));const r=this._reusedWebGLCvs;r.width==t&&r.height==i||(r.width=t,r.height=i,this._reusedWebGLCtx&&this._reusedWebGLCtx.viewport(0,0,t,i));const o=this._reusedWebGLCtx||r.getContext("webgl",{antialias:!1})||r.getContext("experimental-webgl",{antialias:!1});if(!o){this._reusedWebGLCtx=null,this._bWebGLSupported=!1;const e=new Error("WebGL error: unable to initialize WebGL. Your browser or machine may not support it.");throw e.name="WebGLError",e}if(o.enable(o.SCISSOR_TEST),o.scissor(s,a,c,u),!this._reusedWebGLCtx||d!==this.currentFSColorMode){this._reusedWebGLCtx=o;const e=e=>{const t=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,t),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,1,1,-1,1]),e.STATIC_DRAW);const i=e.createBuffer();return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,i),e.bufferData(e.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,0,2,3]),e.STATIC_DRAW),{position:t,indices:i}},t=e=>{const t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),t},i=(e,t,i)=>{const n=r(e,e.VERTEX_SHADER,t),o=r(e,e.FRAGMENT_SHADER,i),s=e.createProgram();return e.attachShader(s,n),e.attachShader(s,o),e.linkProgram(s),e.getProgramParameter(s,e.LINK_STATUS)?s:(alert("Unable to initialize the shader program: "+e.getProgramInfoLog(s)),null)},r=(e,t,i)=>{const r=e.createShader(t);return e.shaderSource(r,i),e.compileShader(r),e.getShaderParameter(r,e.COMPILE_STATUS)?r:(alert("An error occurred compiling the shaders: "+e.getShaderInfoLog(r)),e.deleteShader(r),null)},n="\n attribute mediump vec2 aVertexPosition;\n varying mediump vec2 vDirection;\n \n void main( void )\n {\n gl_Position = vec4(aVertexPosition, 1.0, 1.0) * 2.0;\n vDirection = aVertexPosition;\n }\n ";let s;s=["rgba","rbga","grba","gbra","brga","bgra"].includes(d)?d.slice(0,3):"rgb";const a=i(o,n,`\n precision mediump float;\n\n varying mediump vec2 vDirection;\n uniform sampler2D uSampler;\n uniform lowp float uColorFactor;\n \n void main(void)\n {\n vec4 sample = texture2D(uSampler, vec2(vDirection.x * 0.5 + 0.5, vDirection.y * 0.5 + 0.5));\n lowp float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${s} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `);this._webGLProgramInfo={program:a,attribLocations:{vertexPosition:o.getAttribLocation(a,"aVertexPosition")},uniformLocations:{uSampler:o.getUniformLocation(a,"uSampler"),uColorFactor:o.getUniformLocation(a,"uColorFactor")}},this._webGLBuffers=e(o),this._webGLTexture=t(o),this.currentFSColorMode=d}const l=(e,t,i)=>{const r=e.RGBA,n=e.RGBA,o=e.UNSIGNED_BYTE;e.bindTexture(e.TEXTURE_2D,t),e.texImage2D(e.TEXTURE_2D,0,r,n,o,i)},h=(e,t,i,r)=>{e.clearColor(0,0,0,1),e.clearDepth(1),e.enable(e.DEPTH_TEST),e.depthFunc(e.LEQUAL),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,i.indices),e.useProgram(t.program);{const r=2,n=e.FLOAT,o=!1,s=0,a=0;e.bindBuffer(e.ARRAY_BUFFER,i.position),e.vertexAttribPointer(t.attribLocations.vertexPosition,r,n,o,s,a),e.enableVertexAttribArray(t.attribLocations.vertexPosition)}e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,r),e.uniform1i(t.uniformLocations.uSampler,0),e.uniform1f(t.uniformLocations.uColorFactor,"grey"===d||"grey32"===d?1:0);const n=e.UNSIGNED_SHORT;e.drawElements(e.TRIANGLES,6,n,0)};let f;if(l(o,this._webGLTexture,e),h(o,this._webGLProgramInfo,this._webGLBuffers,this._webGLTexture),n){if(n.length=this.croppingRegions.length||this._croppingRegionIndex<0)throw new Error("The 'croppingRegionIndex' is out of bounds.");e=this.croppingRegions[this._croppingRegionIndex],this.bIncreaseRegionIndexAuto&&++this._croppingRegionIndex>=this.croppingRegions.length&&(this._croppingRegionIndex=0)}return e}_fetchingLoop(e){if(this.isDisposed)return;if(!this._bOpen||!this.isFetchingLoopStarted())return void this.stopFetchingLoop();const t=()=>{ne._onLog&&ne._onLog("DCE: start fetching a frame: "+Date.now());const e=this.getCurrentRegion();let t=this._getVideoFrame(e);if(!t)return void(ne._onLog&&ne._onLog("DCE: get a invalid frame, abandon it: "+Date.now()));for(;this._frameQueue&&this._frameQueue.length>=this.maxNumberOfFramesInBuffer;)this._frameQueue.shift();this._frameQueue.push(t),ne._onLog&&ne._onLog("DCE: finish fetching a frame: "+Date.now());const i=this.mapCameraEvents.get("frameAddedToBuffer");for(let e of i)e&&setTimeout(e.bind(this),0)},i=()=>{this.isDisposed||(this._frameLoopTimeoutId2&&clearTimeout(this._frameLoopTimeoutId2),this.refreshInterval<=0||(this._frameLoopTimeoutId2=setTimeout((()=>{this.isDisposed||(this._bOpen&&this.isFetchingLoopStarted()?(ne._onLog&&ne._onLog("DCE: second timeout executes: "+Date.now()),t(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};e&&(this._frameQueue.length0&&i()):this.refreshInterval>0?(t(),i()):0===this.refreshInterval?t():this.refreshInterval),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameLoopTimeoutId=setTimeout((()=>{this.isDisposed||this._fetchingLoop(!0)}),this.loopInterval)}startFetchingLoop(){if(this.isDisposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(this._assertOpen(),this.singleFrameMode)throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,this._recordedStates.fetchingLoopStart=!0,ne._onLog&&ne._onLog("start fetching loop: "+Date.now()),this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(ne._onLog&&ne._onLog("stop fetching loop: "+Date.now()),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameQueue.length=0,this._bFetchingLoopStarted=!1,this._recordedStates.fetchingLoopStart=!1)}getFrameFromBuffer(e){return this._frameQueue&&this._frameQueue.length?e?e0?i-1:r,$),actionName:"modifyPolygon",pointIndex:i}),e}),{})}_extendSet(e,t){if("vertices"===e){const e=this._fabricObject;e.points=t;const i=e.points.length-1;return e.controls=e.points.reduce((function(e,t,r){return e["p"+r]=new B.Control({positionHandler:Q,actionHandler:ee(r>0?r-1:i,$),actionName:"modifyPolygon",pointIndex:r}),e}),{}),e._setPositionDimensions({}),!0}}_extendGet(e){if("vertices"===e){const e=[],t=this._fabricObject;if(t.selectable)for(let i in t.oCoords)e.push({x:t.oCoords[i].x,y:t.oCoords[i].y});else for(let i in t.getCoords())e.push({x:t.getCoords()[i].x,y:t.getCoords()[i].y});return e}}},DT_Rect:class extends q{constructor(e,t,i,r,n){super(new B.Rect({left:e,top:t,width:i,height:r}),n)}},DT_Image:class extends q{constructor(e,t,i,r){super(new B.Image(e,{left:t,top:i}),r),this.image=e}_extendSet(e,t){if("image"===e){if(t instanceof HTMLImageElement)return this._fabricObject.setElement(t),this.image=t,!0;if(t instanceof HTMLCanvasElement){const e=new Image;return e.src=t.toDataURL(),this._fabricObject.setElement(e),this.image=t,!0}throw new Error("Unsupported value.")}}_extendGet(e){if("image"===e)return this.image}},DT_Text:class extends q{constructor(e,t,i,r){super(new B.IText(e,{left:t,top:i}),r),this._mediaType="text"}},DT_Line:class extends q{constructor(e,t,i){super(new B.Line([e.x,e.y,t.x,t.y]),i)}_extendSet(e,t){return"startPoint"===e?(this._fabricObject.set("x1",t.x),this._fabricObject.set("y1",t.y),!0):"endPoint"===e?(this._fabricObject.set("x2",t.x),this._fabricObject.set("y2",t.y),!0):void 0}_extendGet(e){return"startPoint"===e?{x:this._fabricObject.get("x1"),y:this._fabricObject.get("y1")}:"endPoint"===e?{x:this._fabricObject.get("x2"),y:this._fabricObject.get("y2")}:void 0}},DT_Group:class extends q{constructor(e){super(new B.Group(e.map((e=>e._getFabricObject()))));const t=this.mapEvents;this._fabricObject.onSelect=()=>{this.styleSelector="selected";const e=this.mapEvents.get("select");for(let t of e)t&&t.apply(this);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e.onSelect&&e.onSelect()}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)},this._fabricObject.onDeselect=()=>{this.styleSelector="default";const e=t.get("deselect");for(let t of e)t&&t.apply(this);const i=this._fabricObject._objects;for(let e of i)setTimeout((()=>{e.onDeselect&&e.onDeselect()}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)}}getChildItems(){return this._fabricObject._objects.map((e=>e.getDrawingItem()))}addChildItem(e){if(!e||!e.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,e,"add"):this._fabricObject.addWithUpdate(e._getFabricObject())}removeChildItem(e){e&&e.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,e,"remove"):this._fabricObject.removeWithUpdate(e._getFabricObject()))}}};class se extends M{constructor(){super(),this.bFilterRegionInJs=!0,this._onCameraSelChange=()=>{},this._onResolutionSelChange=()=>{},this._onCloseBtnClick=()=>{},this._onPlayed=null}static get version(){return this._version+`(DCE ${ne.getVersion()})`}static _fireHTTPSWarnning(){se.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{se.onWarning&&se.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}_fireResolutionWarning(){if(!this.singleFrameMode&&this.onWarning){const e=this.dce.getConstraints();e&&e.width<1280&&e.height<720&&setTimeout((()=>{this.onWarning&&this.onWarning({id:3,message:"Camera resolution too low, please use a higher resolution (720P or better)."})}),0)}}getUIElement(){return this.dce.getUIElement()}async setUIElement(e){await this.dce.setUIElement(e)}get singleFrameMode(){return this.dce.singleFrameMode}set singleFrameMode(e){this.dce.singleFrameMode=e,e&&(this.dce.ifShowScanRegionLaser=!1,(async()=>{let e=await this.getScanSettings();e.oneDTrustFrameCount=1,await this.updateScanSettings(e)})())}get onUnduplicatedRead(){return this.onUniqueRead}set onUnduplicatedRead(e){this.onUniqueRead=e}get video(){return this.dce&&this.dce.video}set videoSrc(e){this.dce&&(this.dce.videoSrc=e)}get videoSrc(){return this.dce&&this.dce.videoSrc}_assertOpen(){if(!this.dce.isOpen())throw Error("The scanner is not open.")}set regionMaskFillStyle(e){this.dce.setScanRegionMaskStyle({fillStyle:e})}get regionMaskFillStyle(){return this.dce.regionMaskFillStyle}set regionMaskStrokeStyle(e){this.dce.setScanRegionMaskStyle({strokeStyle:e})}get regionMaskStrokeStyle(){return this.dce.regionMaskStrokeStyle}set regionMaskLineWidth(e){this.dce.setScanRegionMaskStyle({lineWidth:e})}get regionMaskLineWidth(){return this.dce.regionMaskLineWidth}set region(e){this._region=e,this.dce&&(e?e instanceof Array||this.dce.setScanRegion(e):this.dce.setScanRegion(null)),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e,this.dce.frameColorMode=e?"rgba":"grey"}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}async createDCEInstance(){if(!this.dce){M._onLog&&M._onLog("createDCEInstance()");try{ResizeObserver}catch(e){"ReferenceError"===e.name&&window&&(window.ResizeObserver=void 0)}ne.defaultUIElementURL=null,this.dce=await ne.createInstance(),this.dce.refreshInterval=200,this.dce.frameColorMode="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this._drawingItemNamespace=oe,"iPhone"!==M.browserInfo.OS&&"Android"!==M.browserInfo.OS&&"HarmonyOS"!==M.browserInfo.OS&&this.dce.setResolution(1920,1080),this.dce.on("cameraChange",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("resolutionChange",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("cameraClose",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1})),this.dce.on("singleFrameAcquired",(async t=>{if(!t)return;if(!t.data)return;let i;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{data:r,sx:n,sy:o,width:s,height:a,colorMode:l,timeStamp:h,_sWidth:c,_sHeight:u}=t,d={timeStamp:h};if("grey"===l)i=await this._decodeBuffer_Uint8Array(r,s,a,s,e.EnumImagePixelFormat.IPF_GrayScaled,d);else if("rgba"===l)i=await this._decodeBuffer_Uint8Array(r,s,a,4*s,e.EnumImagePixelFormat.IPF_ABGR_8888,d);else{if("bgra"!==l)throw new Error(`Color mode '${l}' is not supported.`);i=await this._decodeBuffer_Uint8Array(r,s,a,4*s,e.EnumImagePixelFormat.IPF_ARGB_8888,d)}if(await this.clearMapDecodeRecord(),M.recalculateResultLocation(i,n,o,c,u,s,a),this._drawResults(i),this.onFrameRead&&this.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(i);this.onFrameRead(e)}if(this.onUniqueRead&&this.isOpen()&&!this._bPauseScan)for(let e of i)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e))}))}}set maxCvsSideLength(e){this._maxCvsSideLength=e,this.dce.maxCvsSideLength=e}get maxCvsSideLength(){return this._maxCvsSideLength}static async createInstance(e){let t=new se;t._instanceID=await se.createInstanceInWorker(!0),await t.createDCEInstance(),"string"==typeof e&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return await t.dce.setUIElement(se.defaultUIElementURL),t.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),se._fireHTTPSWarnning(),t.singleFrameMode||await t.updateRuntimeSettings("single"),t}async decodeCurrentFrame(e){this._assertOpen();let t=null;e&&e.region&&(t=e.region);const i=this.dce._getVideoFrame(t);return this._decode_DCEFrame(i)}static isRegionNormalPreset(e){return 0==e.regionLeft&&0==e.regionTop&&0==e.regionRight&&0==e.regionBottom&&0==e.regionMeasuredByPercentage}async updateRuntimeSettings(t){let i;if("string"==typeof t)if("speed"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region)}else if("balance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region),i.deblurLevel=3,i.expectedBarcodesCount=512,i.localizationModes=[2,16,0,0,0,0,0,0],i.timeout=1e5}else if("coverage"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region),i.deblurLevel=5,i.expectedBarcodesCount=512,i.scaleDownThreshold=1e5,i.localizationModes=[2,16,4,8,0,0,0,0],i.timeout=1e5}else if("single"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,se.isRegionNormalPreset(e.region)?i.region=null:i.region=e.region,i.expectedBarcodesCount=1,i.localizationModes=[16,2,0,0,0,0,0,0],i.barcodeZoneMinDistanceToImageBorders=0}else if("dense"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region),i.deblurLevel=7,i.scaleDownThreshold=1e5,i.localizationModes=[2,8,0,0,0,0,0,0],i.minResultConfidence=0,i.timeout=1e5}else if("distance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region),i.scaleDownThreshold=1e5,i.localizationModes=[2,8,0,0,0,0,0,0],i.timeout=1e5}else i=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(i=JSON.parse(JSON.stringify(t)),i.region instanceof Array){let e=t.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(i.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!M._bUseFullFeature){if(0!=(i.barcodeFormatIds&~(e.EnumBarcodeFormat.BF_ONED|e.EnumBarcodeFormat.BF_QR_CODE|e.EnumBarcodeFormat.BF_PDF417|e.EnumBarcodeFormat.BF_DATAMATRIX))||0!=i.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=i.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}{let e=i.region;if(this.bFilterRegionInJs?this.userDefinedRegion=JSON.parse(JSON.stringify(e)):this.userDefinedRegion=null,e instanceof Array)if(e.length){for(let t=0;t{let r=M._nextTaskID++;M._taskCallbackMap.set(r,(i=>{if(i.success){try{this._handleRetJsonString(i.updateReturn)}catch(e){t(e)}return e()}{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),M._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(i)}})})),"single"==t&&(await this.setModeArgument("BinarizationModes",0,"EnableFillBinaryVacancy","0"),await this.setModeArgument("LocalizationModes",0,"ScanDirection","2"),await this.setModeArgument("BinarizationModes",0,"BlockSizeX","71"),await this.setModeArgument("BinarizationModes",0,"BlockSizeY","71"))}_bindUI(){if(!this.getUIElement())throw new Error("Need to define `UIElement` before opening.");if(this.dce._bindUI(),!this.dce.video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'")}_unbindUI(){this.dce._unbindUI()}set onPlayed(e){this.dce.off("played",this._onPlayed),this._onPlayed=e,this.dce.on("played",this._onPlayed)}get onPlayed(){return this._onPlayed}async getAllCameras(){return this.dce.getAllCameras()}async getCurrentCamera(){return this.dce.getSelectedCamera()}async setCurrentCamera(e){const t=await this.dce.selectCamera(e);return this._fireResolutionWarning(),t}getResolution(){return this.dce.getResolution()}async setResolution(e,t){const i=await this.dce.setResolution(e,t);return this._fireResolutionWarning(),i}getVideoSettings(){return this.dce.getVideoSettings()}updateVideoSettings(e){return this.dce.updateVideoSettings(e)}isOpen(){return this.dce&&this.dce.isOpen()}setVideoFit(e){return this.dce&&this.dce.setVideoFit(e)}set ifShowScanRegionMask(e){this.dce&&(this.dce.ifShowScanRegionMask=e)}get ifShowScanRegionMask(){return this.dce&&this.dce.ifShowScanRegionMask}set ifSaveLastUsedCamera(e){this.dce&&(this.dce.ifSaveLastUsedCamera=e)}get ifSaveLastUsedCamera(){return this.dce&&this.dce.ifSaveLastUsedCamera}set ifSkipCameraInspection(e){this.dce&&(this.dce.ifSkipCameraInspection=e)}get ifSkipCameraInspection(){return this.dce&&this.dce.ifSkipCameraInspection}stop(){this._drawResults(null),this.dce.stop(),this.dce.ifShowScanRegionLaser=!1,this.dce.hideViewDecorator(),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}pause(){this.dce.pause()}async play(e,t,i){this.dce.ifShowScanRegionLaser=!0;const r=await this.dce.play(e,t,i);return this._fireResolutionWarning(),r}pauseScan(e){this._assertOpen(),e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce.ifShowScanRegionLaser=!1,this.dce.stopFetchingLoop()}resumeScan(){this._assertOpen(),this._bPauseScan=!1,this.dce.ifShowScanRegionLaser=!0}getCapabilities(){return this.dce.getCapabilities()}getCameraSettings(){return this.dce.getCameraSettings()}getConstraints(){return this.dce.getConstraints()}async applyConstraints(e){return this.dce.applyConstraints(e)}async turnOnTorch(){return this.dce.turnOnTorch()}async turnOffTorch(){return this.dce.turnOffTorch()}async setColorTemperature(e){return this.dce.setColorTemperature(e)}async setExposureCompensation(e){return this.dce.setExposureCompensation(e)}async setZoom(e){return this.dce.setZoom(e)}async setFrameRate(e){return this.dce.setFrameRate(e)}getFrameRate(){return this.dce.getFrameRate()}async setFocus(e,t){return this.dce.setFocus(e,t)}getFocus(){return this.dce.getFocus()}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),void this._drawResults(null);if(!this.isOpen())return this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce.video||this.dce.video.paused||this._bPauseScan)return M._onLog&&M._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));M._onLog&&M._onLog("======= once read ======="),M._onLog&&(this._timeStartDecode=Date.now());const t=this._getVideoFrame();if(!t)return this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{t._bUseWebGL||"grey"!==t.colorMode||(this.dce.frameColorMode="rgba");let i=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{data:r,sx:n,sy:o,width:s,height:a,colorMode:l,timeStamp:h,_sWidth:c,_sHeight:u}=t,d={timeStamp:h};if("grey"===l)i=await this._decodeBuffer_Uint8Array(r,s,a,s,e.EnumImagePixelFormat.IPF_GrayScaled,d);else if("rgba"===l)i=await this._decodeBuffer_Uint8Array(r,s,a,4*s,e.EnumImagePixelFormat.IPF_ABGR_8888,d);else{if("bgra"!==l)throw new Error(`Color mode '${l}' is not supported.`);i=await this._decodeBuffer_Uint8Array(r,s,a,4*s,e.EnumImagePixelFormat.IPF_ARGB_8888,d)}return M.recalculateResultLocation(i,n,o,c,u,s,a),i})().then((e=>{if(M._onLog&&M._onLog(e),this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost,i=this._indexCurrentDecodingFrame;const r=()=>{let r=0;if(this.region instanceof Array){let n=0,o=0;n=i+1>=this.region.length?0:i+1,o=n+1>=this.region.length?0:n+1,r=e[n]&&e[n].length&&t[o]&&t[o].length?Math.min(...e[n])-Math.max(...t[o]):0}else if(t&&t.length){let i=Math.min(...e),n=Math.max(...t);i&&n&&(r=i-n)}else r=0;return r>0?r:0};(()=>{if(this.region instanceof Array){for(e[i]&&e[i]instanceof Array||(e[i]=[]);e[i].length>=5;)e[i].shift();e[i].push(this._lastInnerDecodeDuration)}else{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)}})(),this._intervalGetVideoFrame=r()+this.intervalTime}if(this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead)t=!0;else if("unique"===this.bPlaySoundOnSuccessfulRead)for(let i of e)if(0==i.resultsType){t=!0;break}t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead)t=!0;else if("unique"===this.bVibrateOnSuccessfulRead)for(let i of e)if(0==i.resultsType){t=!0;break}if(t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onFrameRead){let t=this._cloneDecodeResults(e);for(let e of t)0!=e.resultsType&&1!=e.resultsType||this.onFrameRead(t)}if(this.onUniqueRead)for(let t of e)0==t.resultsType&&this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t));this._drawResults(e)}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce.stopFetchingLoop(),M._onLog&&M._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){let t=this.dce.isFetchingLoopStarted();if(this.dce.loopInterval=this._intervalGetVideoFrame,t||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dce.loopInterval=0,null;e=this.dce.getFrameFromBuffer();const i=e=>{if(!e)return;let t=e.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(t)};i(e)}else this.dce.stopFetchingLoop(),e=this.dce.getFrame();return e}async open(){this._bindUI();const e=await this.dce.open();return this._bPauseScan=!1,this.singleFrameMode||(this.dce&&(this.dce.ifShowScanRegionLaser=!0),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),this.keepAlive(),e}async openVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open();return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),this.keepAlive(),e}close(){this.dce.close(),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId)}async show(){this._bindUI();const e=await this.dce.open(!0);return this._bPauseScan=!1,this.singleFrameMode||(this.dce&&(this.dce.ifShowScanRegionLaser=!0),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),this.keepAlive(),e}async showVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open(!0);return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),this.keepAlive(),e}hide(){this.dce.close(!0),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId)}destroyContext(){this.close(),this.bDestroyed||super.destroyContext()}}var ae,le,he,ce,ue,de,fe,ge,_e,pe,me,ve,ye,Se,be,Ce,we,Te,xe,Ee,Ae,Ie,Oe,Re,De,Me,Le;e.EnumBarcodeColourMode=void 0,(ae=e.EnumBarcodeColourMode||(e.EnumBarcodeColourMode={}))[ae.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",ae[ae.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",ae[ae.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",ae[ae.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",ae[ae.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",ae[ae.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",ae[ae.BICM_SKIP=0]="BICM_SKIP",ae[ae.BICM_REV=2147483648]="BICM_REV",e.EnumBarcodeComplementMode=void 0,(le=e.EnumBarcodeComplementMode||(e.EnumBarcodeComplementMode={}))[le.BCM_AUTO=1]="BCM_AUTO",le[le.BCM_GENERAL=2]="BCM_GENERAL",le[le.BCM_SKIP=0]="BCM_SKIP",le[le.BCM_REV=2147483648]="BCM_REV",e.EnumBarcodeFormat_2=void 0,(he=e.EnumBarcodeFormat_2||(e.EnumBarcodeFormat_2={}))[he.BF2_NULL=0]="BF2_NULL",he[he.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",he[he.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",he[he.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",he[he.BF2_POSTNET=2097152]="BF2_POSTNET",he[he.BF2_PLANET=4194304]="BF2_PLANET",he[he.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",he[he.BF2_RM4SCC=16777216]="BF2_RM4SCC",he[he.BF2_DOTCODE=2]="BF2_DOTCODE",he[he.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",he[he.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",he[he.BF2_PHARMACODE=12]="BF2_PHARMACODE",e.EnumBinarizationMode=void 0,(ce=e.EnumBinarizationMode||(e.EnumBinarizationMode={}))[ce.BM_AUTO=1]="BM_AUTO",ce[ce.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",ce[ce.BM_SKIP=0]="BM_SKIP",ce[ce.BM_THRESHOLD=4]="BM_THRESHOLD",ce[ce.BM_REV=2147483648]="BM_REV",e.EnumClarityCalculationMethod=void 0,(ue=e.EnumClarityCalculationMethod||(e.EnumClarityCalculationMethod={}))[ue.ECCM_CONTRAST=1]="ECCM_CONTRAST",e.EnumClarityFilterMode=void 0,(de=e.EnumClarityFilterMode||(e.EnumClarityFilterMode={}))[de.CFM_GENERAL=1]="CFM_GENERAL",e.EnumColourClusteringMode=void 0,(fe=e.EnumColourClusteringMode||(e.EnumColourClusteringMode={}))[fe.CCM_AUTO=1]="CCM_AUTO",fe[fe.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",fe[fe.CCM_SKIP=0]="CCM_SKIP",fe[fe.CCM_REV=2147483648]="CCM_REV",e.EnumColourConversionMode=void 0,(ge=e.EnumColourConversionMode||(e.EnumColourConversionMode={}))[ge.CICM_GENERAL=1]="CICM_GENERAL",ge[ge.CICM_SKIP=0]="CICM_SKIP",ge[ge.CICM_REV=2147483648]="CICM_REV",e.EnumConflictMode=void 0,(_e=e.EnumConflictMode||(e.EnumConflictMode={}))[_e.CM_IGNORE=1]="CM_IGNORE",_e[_e.CM_OVERWRITE=2]="CM_OVERWRITE",e.EnumDeblurMode=void 0,(pe=e.EnumDeblurMode||(e.EnumDeblurMode={}))[pe.DM_SKIP=0]="DM_SKIP",pe[pe.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",pe[pe.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",pe[pe.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",pe[pe.DM_SMOOTHING=8]="DM_SMOOTHING",pe[pe.DM_MORPHING=16]="DM_MORPHING",pe[pe.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",pe[pe.DM_SHARPENING=64]="DM_SHARPENING",pe[pe.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",pe[pe.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",e.EnumDeformationResistingMode=void 0,(me=e.EnumDeformationResistingMode||(e.EnumDeformationResistingMode={}))[me.DRM_AUTO=1]="DRM_AUTO",me[me.DRM_GENERAL=2]="DRM_GENERAL",me[me.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",me[me.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",me[me.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",me[me.DRM_SKIP=0]="DRM_SKIP",me[me.DRM_REV=2147483648]="DRM_REV",e.EnumDPMCodeReadingMode=void 0,(ve=e.EnumDPMCodeReadingMode||(e.EnumDPMCodeReadingMode={}))[ve.DPMCRM_AUTO=1]="DPMCRM_AUTO",ve[ve.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",ve[ve.DPMCRM_SKIP=0]="DPMCRM_SKIP",ve[ve.DPMCRM_REV=2147483648]="DPMCRM_REV",e.EnumGrayscaleTransformationMode=void 0,(ye=e.EnumGrayscaleTransformationMode||(e.EnumGrayscaleTransformationMode={}))[ye.GTM_INVERTED=1]="GTM_INVERTED",ye[ye.GTM_ORIGINAL=2]="GTM_ORIGINAL",ye[ye.GTM_SKIP=0]="GTM_SKIP",ye[ye.GTM_REV=2147483648]="GTM_REV",e.EnumImagePreprocessingMode=void 0,(Se=e.EnumImagePreprocessingMode||(e.EnumImagePreprocessingMode={}))[Se.IPM_AUTO=1]="IPM_AUTO",Se[Se.IPM_GENERAL=2]="IPM_GENERAL",Se[Se.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",Se[Se.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",Se[Se.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",Se[Se.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",Se[Se.IPM_SKIP=0]="IPM_SKIP",Se[Se.IPM_REV=2147483648]="IPM_REV",e.EnumIntermediateResultSavingMode=void 0,(be=e.EnumIntermediateResultSavingMode||(e.EnumIntermediateResultSavingMode={}))[be.IRSM_MEMORY=1]="IRSM_MEMORY",be[be.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",be[be.IRSM_BOTH=4]="IRSM_BOTH",e.EnumIntermediateResultType=void 0,(Ce=e.EnumIntermediateResultType||(e.EnumIntermediateResultType={}))[Ce.IRT_NO_RESULT=0]="IRT_NO_RESULT",Ce[Ce.IRT_ORIGINAL_IMAGE=1]="IRT_ORIGINAL_IMAGE",Ce[Ce.IRT_COLOUR_CLUSTERED_IMAGE=2]="IRT_COLOUR_CLUSTERED_IMAGE",Ce[Ce.IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE=4]="IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE",Ce[Ce.IRT_TRANSFORMED_GRAYSCALE_IMAGE=8]="IRT_TRANSFORMED_GRAYSCALE_IMAGE",Ce[Ce.IRT_PREDETECTED_REGION=16]="IRT_PREDETECTED_REGION",Ce[Ce.IRT_PREPROCESSED_IMAGE=32]="IRT_PREPROCESSED_IMAGE",Ce[Ce.IRT_BINARIZED_IMAGE=64]="IRT_BINARIZED_IMAGE",Ce[Ce.IRT_TEXT_ZONE=128]="IRT_TEXT_ZONE",Ce[Ce.IRT_CONTOUR=256]="IRT_CONTOUR",Ce[Ce.IRT_LINE_SEGMENT=512]="IRT_LINE_SEGMENT",Ce[Ce.IRT_FORM=1024]="IRT_FORM",Ce[Ce.IRT_SEGMENTATION_BLOCK=2048]="IRT_SEGMENTATION_BLOCK",Ce[Ce.IRT_TYPED_BARCODE_ZONE=4096]="IRT_TYPED_BARCODE_ZONE",Ce[Ce.IRT_PREDETECTED_QUADRILATERAL=8192]="IRT_PREDETECTED_QUADRILATERAL",e.EnumLocalizationMode=void 0,(we=e.EnumLocalizationMode||(e.EnumLocalizationMode={}))[we.LM_SKIP=0]="LM_SKIP",we[we.LM_AUTO=1]="LM_AUTO",we[we.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",we[we.LM_LINES=8]="LM_LINES",we[we.LM_STATISTICS=4]="LM_STATISTICS",we[we.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",we[we.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",we[we.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",we[we.LM_CENTRE=128]="LM_CENTRE",we[we.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",we[we.LM_REV=2147483648]="LM_REV",e.EnumPDFReadingMode=void 0,(Te=e.EnumPDFReadingMode||(e.EnumPDFReadingMode={}))[Te.PDFRM_RASTER=1]="PDFRM_RASTER",Te[Te.PDFRM_AUTO=2]="PDFRM_AUTO",Te[Te.PDFRM_VECTOR=4]="PDFRM_VECTOR",Te[Te.PDFRM_REV=2147483648]="PDFRM_REV",e.EnumQRCodeErrorCorrectionLevel=void 0,(xe=e.EnumQRCodeErrorCorrectionLevel||(e.EnumQRCodeErrorCorrectionLevel={}))[xe.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",xe[xe.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",xe[xe.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",xe[xe.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q",e.EnumRegionPredetectionMode=void 0,(Ee=e.EnumRegionPredetectionMode||(e.EnumRegionPredetectionMode={}))[Ee.RPM_AUTO=1]="RPM_AUTO",Ee[Ee.RPM_GENERAL=2]="RPM_GENERAL",Ee[Ee.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",Ee[Ee.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",Ee[Ee.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",Ee[Ee.RPM_SKIP=0]="RPM_SKIP",Ee[Ee.RPM_REV=2147483648]="RPM_REV",e.EnumResultCoordinateType=void 0,(Ae=e.EnumResultCoordinateType||(e.EnumResultCoordinateType={}))[Ae.RCT_PIXEL=1]="RCT_PIXEL",Ae[Ae.RCT_PERCENTAGE=2]="RCT_PERCENTAGE",e.EnumResultType=void 0,(Ie=e.EnumResultType||(e.EnumResultType={}))[Ie.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",Ie[Ie.RT_RAW_TEXT=1]="RT_RAW_TEXT",Ie[Ie.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",Ie[Ie.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT",e.EnumScaleUpMode=void 0,(Oe=e.EnumScaleUpMode||(e.EnumScaleUpMode={}))[Oe.SUM_AUTO=1]="SUM_AUTO",Oe[Oe.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",Oe[Oe.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",Oe[Oe.SUM_SKIP=0]="SUM_SKIP",Oe[Oe.SUM_REV=2147483648]="SUM_REV",e.EnumTerminatePhase=void 0,(Re=e.EnumTerminatePhase||(e.EnumTerminatePhase={}))[Re.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",Re[Re.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",Re[Re.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",Re[Re.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",Re[Re.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",Re[Re.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED",e.EnumTextFilterMode=void 0,(De=e.EnumTextFilterMode||(e.EnumTextFilterMode={}))[De.TFM_AUTO=1]="TFM_AUTO",De[De.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",De[De.TFM_SKIP=0]="TFM_SKIP",De[De.TFM_REV=2147483648]="TFM_REV",e.EnumTextResultOrderMode=void 0,(Me=e.EnumTextResultOrderMode||(e.EnumTextResultOrderMode={}))[Me.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",Me[Me.TROM_POSITION=2]="TROM_POSITION",Me[Me.TROM_FORMAT=4]="TROM_FORMAT",Me[Me.TROM_SKIP=0]="TROM_SKIP",Me[Me.TROM_REV=2147483648]="TROM_REV",e.EnumTextureDetectionMode=void 0,(Le=e.EnumTextureDetectionMode||(e.EnumTextureDetectionMode={}))[Le.TDM_AUTO=1]="TDM_AUTO",Le[Le.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",Le[Le.TDM_SKIP=0]="TDM_SKIP",Le[Le.TDM_REV=2147483648]="TDM_REV",e.BarcodeReader=M,e.BarcodeScanner=se,Object.defineProperty(e,"__esModule",{value:!0})})); diff --git a/dist/dbr.mjs b/dist/dbr.mjs index 964f2a5..8b18e96 100644 --- a/dist/dbr.mjs +++ b/dist/dbr.mjs @@ -4,19 +4,18 @@ * @website http://www.dynamsoft.com * @copyright Copyright 2022, Dynamsoft Corporation * @author Dynamsoft - * @version 9.0.2 (js 20220505) + * @version 9.2.11 (js 20220727) * @fileoverview Dynamsoft JavaScript Library for Barcode Reader * More info on DBR JS: https://www.dynamsoft.com/barcode-reader/sdk-javascript/ */ -const e="undefined"==typeof self;let t;if(!e){const e={init:function(){this.browser=this.searchString(this.dataBrowser)||"unknownBrowser",this.version=this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion)||"unknownVersion",this.OS=this.searchString(this.dataOS)||"unknownOS","Linux"==this.OS&&-1!=navigator.userAgent.indexOf("Windows NT")&&(this.OS="HarmonyOS")},searchString:function(e){for(var t=0;t{let e=!1;if(o)try{(await navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e},s=(()=>{if(!e&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),a=" is not allowed to change after `createInstance` or `loadWasm` is called.",d=!e&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",l=!e&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",h=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let i=0;ie&&"object"==typeof e&&"function"==typeof e.then;var m=function(){this.init()};m.prototype={init:function(){var e=this||p;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var t=this||p;if(e=parseFloat(e),t.ctx||T(),void 0!==e&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,p.ctx.currentTime);for(var i=0;i=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,T()),e},codecs:function(e){return(this||p)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||p;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||p,t=null;try{t="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!t||"function"!=typeof t.canPlayType)return e;var i=t.canPlayType("audio/mpeg;").replace(/^no$/,""),n=e._navigator?e._navigator.userAgent:"",o=n.match(/OPR\/([0-6].)/g),r=o&&parseInt(o[0].split("/")[1],10)<33,s=-1!==n.indexOf("Safari")&&-1===n.indexOf("Chrome"),a=n.match(/Version\/(.*?) /),d=s&&a&&parseInt(a[1],10)<15;return e._codecs={mp3:!(r||!i&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!i,opus:!!t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(t.canPlayType('audio/wav; codecs="1"')||t.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!t.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!t.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/m4a;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(t.canPlayType("audio/x-m4b;")||t.canPlayType("audio/m4b;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(t.canPlayType("audio/x-mp4;")||t.canPlayType("audio/mp4;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(d||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(d||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!t.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(t.canPlayType("audio/x-flac;")||t.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||p;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var t=function(i){for(;e._html5AudioPool.length0?s._seek:i._sprite[e][0]/1e3),l=Math.max(0,(i._sprite[e][0]+i._sprite[e][1])/1e3-d),h=1e3*l/Math.abs(s._rate),c=i._sprite[e][0]/1e3,_=(i._sprite[e][0]+i._sprite[e][1])/1e3;s._sprite=e,s._ended=!1;var u=function(){s._paused=!1,s._seek=d,s._start=c,s._stop=_,s._loop=!(!s._loop&&!i._sprite[e][2])};if(!(d>=_)){var g=s._node;if(i._webAudio){var f=function(){i._playLock=!1,u(),i._refreshBuffer(s);var e=s._muted||i._muted?0:s._volume;g.gain.setValueAtTime(e,p.ctx.currentTime),s._playStart=p.ctx.currentTime,void 0===g.bufferSource.start?s._loop?g.bufferSource.noteGrainOn(0,d,86400):g.bufferSource.noteGrainOn(0,d,l):s._loop?g.bufferSource.start(0,d,86400):g.bufferSource.start(0,d,l),h!==1/0&&(i._endTimers[s._id]=setTimeout(i._ended.bind(i,s),h)),t||setTimeout((function(){i._emit("play",s._id),i._loadQueue()}),0)};"running"===p.state&&"interrupted"!==p.ctx.state?f():(i._playLock=!0,i.once("resume",f),i._clearTimer(s._id))}else{var m=function(){g.currentTime=d,g.muted=s._muted||i._muted||p._muted||g.muted,g.volume=s._volume*p.volume(),g.playbackRate=s._rate;try{var n=g.play();if(n&&"undefined"!=typeof Promise&&(n instanceof Promise||"function"==typeof n.then)?(i._playLock=!0,u(),n.then((function(){i._playLock=!1,g._unlocked=!0,t?i._loadQueue():i._emit("play",s._id)})).catch((function(){i._playLock=!1,i._emit("playerror",s._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),s._ended=!0,s._paused=!0}))):t||(i._playLock=!1,u(),i._emit("play",s._id)),g.playbackRate=s._rate,g.paused)return void i._emit("playerror",s._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||s._loop?i._endTimers[s._id]=setTimeout(i._ended.bind(i,s),h):(i._endTimers[s._id]=function(){i._ended(s),g.removeEventListener("ended",i._endTimers[s._id],!1)},g.addEventListener("ended",i._endTimers[s._id],!1))}catch(e){i._emit("playerror",s._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===g.src&&(g.src=i._src,g.load());var v=window&&window.ejecta||!g.readyState&&p._navigator.isCocoonJS;if(g.readyState>=3||v)m();else{i._playLock=!0,i._state="loading";var A=function(){i._state="loaded",m(),g.removeEventListener(p._canPlayEvent,A,!1)};g.addEventListener(p._canPlayEvent,A,!1),i._clearTimer(s._id)}}return s._id}i._ended(s)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var i=t._getSoundIds(e),n=0;n=0?t=parseInt(o[0],10):e=parseFloat(o[0])}else o.length>=2&&(e=parseFloat(o[0]),t=parseInt(o[1],10));if(!(void 0!==e&&e>=0&&e<=1))return(i=t?n._soundById(t):n._sounds[0])?i._volume:0;if("loaded"!==n._state||n._playLock)return n._queue.push({event:"volume",action:function(){n.volume.apply(n,o)}}),n;void 0===t&&(n._volume=e),t=n._getSoundIds(t);for(var a=0;a0?n/l:n),c=Date.now();e._fadeTo=i,e._interval=setInterval((function(){var o=(Date.now()-c)/n;c=Date.now(),a+=d*o,a=Math.round(100*a)/100,a=d<0?Math.max(i,a):Math.min(i,a),s._webAudio?e._volume=a:s.volume(a,e._id,!0),r&&(s._volume=a),(it&&a>=i)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,s.volume(i,e._id),s._emit("fade",e._id))}),h)},_stopFade:function(e){var t=this,i=t._soundById(e);return i&&i._interval&&(t._webAudio&&i._node.gain.cancelScheduledValues(p.ctx.currentTime),clearInterval(i._interval),i._interval=null,t.volume(i._fadeTo,e),i._fadeTo=null,t._emit("fade",e)),t},loop:function(){var e,t,i,n=this,o=arguments;if(0===o.length)return n._loop;if(1===o.length){if("boolean"!=typeof o[0])return!!(i=n._soundById(parseInt(o[0],10)))&&i._loop;e=o[0],n._loop=e}else 2===o.length&&(e=o[0],t=parseInt(o[1],10));for(var r=n._getSoundIds(t),s=0;s=0?t=parseInt(o[0],10):e=parseFloat(o[0])}else 2===o.length&&(e=parseFloat(o[0]),t=parseInt(o[1],10));if("number"!=typeof e)return(i=n._soundById(t))?i._rate:n._rate;if("loaded"!==n._state||n._playLock)return n._queue.push({event:"rate",action:function(){n.rate.apply(n,o)}}),n;void 0===t&&(n._rate=e),t=n._getSoundIds(t);for(var a=0;a=0?t=parseInt(n[0],10):i._sounds.length&&(t=i._sounds[0]._id,e=parseFloat(n[0]))}else 2===n.length&&(e=parseFloat(n[0]),t=parseInt(n[1],10));if(void 0===t)return 0;if("number"==typeof e&&("loaded"!==i._state||i._playLock))return i._queue.push({event:"seek",action:function(){i.seek.apply(i,n)}}),i;var s=i._soundById(t);if(s){if(!("number"==typeof e&&e>=0)){if(i._webAudio){var a=i.playing(t)?p.ctx.currentTime-s._playStart:0,d=s._rateSeek?s._rateSeek-s._seek:0;return s._seek+(d+a*Math.abs(s._rate))}return s._node.currentTime}var l=i.playing(t);l&&i.pause(t,!0),s._seek=e,s._ended=!1,i._clearTimer(t),i._webAudio||!s._node||isNaN(s._node.duration)||(s._node.currentTime=e);var h=function(){l&&i.play(t,!0),i._emit("seek",t)};if(l&&!i._webAudio){var c=function(){i._playLock?setTimeout(c,0):h()};setTimeout(c,0)}else h()}return i},playing:function(e){var t=this;if("number"==typeof e){var i=t._soundById(e);return!!i&&!i._paused}for(var n=0;n=0&&p._howls.splice(n,1);var o=!0;for(i=0;i=0){o=!1;break}return R&&o&&delete R[e._src],p.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,i,n){var o=this["_on"+e];return"function"==typeof t&&o.push(n?{id:i,fn:t,once:n}:{id:i,fn:t}),this},off:function(e,t,i){var n=this,o=n["_on"+e],r=0;if("number"==typeof t&&(i=t,t=null),t||i)for(r=0;r=0;r--)o[r].id&&o[r].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,i)}.bind(n,o[r].fn),0),o[r].once&&n.off(e,o[r].fn,o[r].id));return n._loadQueue(e),n},_loadQueue:function(e){var t=this;if(t._queue.length>0){var i=t._queue[0];i.event===e&&(t._queue.shift(),t._loadQueue()),e||i.action()}return t},_ended:function(e){var t=this,i=e._sprite;if(!t._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;n--){if(i<=t)return;e._sounds[n]._ended&&(e._webAudio&&e._sounds[n]._node&&e._sounds[n]._node.disconnect(0),e._sounds.splice(n,1),i--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],i=0;i=0;if(!e.bufferSource)return this;if(p._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))try{e.bufferSource.buffer=p._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(p._navigator&&p._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var A=function(e){this._parent=e,this.init()};A.prototype={init:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++p._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,i=p._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=void 0===p.ctx.createGain?p.ctx.createGainNode():p.ctx.createGain(),e._node.gain.setValueAtTime(i,p.ctx.currentTime),e._node.paused=!0,e._node.connect(p.masterGain)):p.noAudio||(e._node=p._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(p._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=t._src,e._node.preload=!0===t._preload?"auto":t._preload,e._node.volume=i*p.volume(),e._node.load()),e},reset:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++p._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,t=e._parent;t._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(t._sprite).length&&(t._sprite={__default:[0,1e3*t._duration]}),"loaded"!==t._state&&(t._state="loaded",t._emit("load"),t._loadQueue()),e._node.removeEventListener(p._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var R={},S=function(e){var t=e._src;if(R[t])return e._duration=R[t].duration,void E(e);if(/^data:[^;]+;base64,/.test(t)){for(var i=atob(t.split(",")[1]),n=new Uint8Array(i.length),o=0;o0?(R[t._src]=e,E(t,e)):i()};"undefined"!=typeof Promise&&1===p.ctx.decodeAudioData.length?p.ctx.decodeAudioData(e).then(n).catch(i):p.ctx.decodeAudioData(e,n,i)},E=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},T=function(){if(p.usingWebAudio){try{"undefined"!=typeof AudioContext?p.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?p.ctx=new webkitAudioContext:p.usingWebAudio=!1}catch(e){p.usingWebAudio=!1}p.ctx||(p.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(p._navigator&&p._navigator.platform),t=p._navigator&&p._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),i=t?parseInt(t[1],10):null;if(e&&i&&i<9){var n=/safari/.test(p._navigator&&p._navigator.userAgent.toLowerCase());p._navigator&&!n&&(p.usingWebAudio=!1)}p.usingWebAudio&&(p.masterGain=void 0===p.ctx.createGain?p.ctx.createGainNode():p.ctx.createGain(),p.masterGain.gain.setValueAtTime(p._muted?0:p._volume,p.ctx.currentTime),p.masterGain.connect(p.ctx.destination)),p._setup()}};!function(e,t,i,n){var o;e.prototype._pos=[0,0,0],e.prototype._orientation=[0,0,-1,0,1,0],e.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var i=t._howls.length-1;i>=0;i--)t._howls[i].stereo(e);return t},e.prototype.pos=function(e,i,n){var o=this;return o.ctx&&o.ctx.listener?(i="number"!=typeof i?o._pos[1]:i,n="number"!=typeof n?o._pos[2]:n,"number"!=typeof e?o._pos:(o._pos=[e,i,n],void 0!==o.ctx.listener.positionX?(o.ctx.listener.positionX.setTargetAtTime(o._pos[0],t.ctx.currentTime,.1),o.ctx.listener.positionY.setTargetAtTime(o._pos[1],t.ctx.currentTime,.1),o.ctx.listener.positionZ.setTargetAtTime(o._pos[2],t.ctx.currentTime,.1)):o.ctx.listener.setPosition(o._pos[0],o._pos[1],o._pos[2]),o)):o},e.prototype.orientation=function(e,i,n,o,r,s){var a=this;if(!a.ctx||!a.ctx.listener)return a;var d=a._orientation;return i="number"!=typeof i?d[1]:i,n="number"!=typeof n?d[2]:n,o="number"!=typeof o?d[3]:o,r="number"!=typeof r?d[4]:r,s="number"!=typeof s?d[5]:s,"number"!=typeof e?d:(a._orientation=[e,i,n,o,r,s],void 0!==a.ctx.listener.forwardX?(a.ctx.listener.forwardX.setTargetAtTime(e,t.ctx.currentTime,.1),a.ctx.listener.forwardY.setTargetAtTime(i,t.ctx.currentTime,.1),a.ctx.listener.forwardZ.setTargetAtTime(n,t.ctx.currentTime,.1),a.ctx.listener.upX.setTargetAtTime(o,t.ctx.currentTime,.1),a.ctx.listener.upY.setTargetAtTime(r,t.ctx.currentTime,.1),a.ctx.listener.upZ.setTargetAtTime(s,t.ctx.currentTime,.1)):a.ctx.listener.setOrientation(e,i,n,o,r,s),a)},i.prototype.init=(o=i.prototype.init,function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],o.call(this,e)}),i.prototype.stereo=function(e,i){var n=this;if(!n._webAudio)return n;if("loaded"!==n._state)return n._queue.push({event:"stereo",action:function(){n.stereo(e,i)}}),n;var o=void 0===t.ctx.createStereoPanner?"spatial":"stereo";if(void 0===i){if("number"!=typeof e)return n._stereo;n._stereo=e,n._pos=[e,0,0]}for(var s=n._getSoundIds(i),a=0;a{console.warn(`Sound '${e}' playback failure: ${t}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.barcodeFillStyle="rgba(254,180,32,0.3)",this.barcodeStrokeStyle="rgba(254,180,32,0.9)",this.barcodeLineWidth=1,this._dce=null,this.dceConfig={},this.imgSource=null,this._maxCvsSideLength="iPhone"==t.OS||"Android"==t.OS?2048:4096,this._tempSolutionStatus="closed"}static get version(){return this._version}static get license(){return this._license}static set license(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`license`"+a);i._license=t})(w,e)}static get productKeys(){return this._license}static set productKeys(e){w.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){w.license=e}static get organizationID(){return this._license}static set organizationID(e){w.license=e}static set sessionPassword(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`sessionPassword`"+a);i._sessionPassword=t})(w,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:i,worker:n,getUserMedia:o,camera:await r(),browser:t.browser,version:t.version,OS:t.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(t){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");w._engineResourcePath=(t=>{if(null==t&&(t="./"),!e){let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(t)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+a);i._licenseServer=h(t)})(w,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+a);i._deviceFriendlyName=t||""})(w,e)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(e){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");w.__bUseFullFeature=e}static isImageSource(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"getImage"in e}static isDSImage(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("width"in e&&("height"in e&&"pixelFormat"in e)))}static isCameraEnhancer(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("referenceConfigurationArray"in e&&("isOpen"in e&&("on"in e&&("off"in e&&("startFetchingLoop"in e&&("stopFetchingLoop"in e&&("getUIElement"in e&&("video"in e&&("isFetchingLoopStarted"in e&&("numberOfFramesInBuffer"in e&&("getFrameFromBuffer"in e&&("addScanRegionOverlayCanvas"in e&&("ifShowScanRegionLaser"in e&&("open"in e&&"close"in e))))))))))))))}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("region"in e&&("sx"in e&&("sy"in e&&("width"in e&&("height"in e&&("colorMode"in e&&("timeSpent"in e&&("timeStamp"in e&&("isCropped"in e&&("toCanvas"in e&&"_bUseWebGL"in e)))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(e){this._region=e,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var e;return null===(e=w._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",w.engineResourcePath)}static set defaultUIElementURL(e){w._defaultUIElementURL=e}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new v({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(e){this.bPlaySoundOnSuccessfulRead="never"!==e&&e}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(e){this.bVibrateOnSuccessfulRead="never"!==e&&e}set dce(e){this._dce=e}get dce(){return w.isCameraEnhancer(this._dce)?this._dce:null}set maxCvsSideLength(e){this._maxCvsSideLength=e,this.dceConfig.maxCvsSideLength=e}get maxCvsSideLength(){return this._maxCvsSideLength}updateDCEConfig(){if(!this.dce)return;w._onLog&&w._onLog("updateDCEConfig()"),this.dceConfig={bufferRefreshInterval:200,maxCvsSideLength:this._maxCvsSideLength};let e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);for(;-1!==e;)this.dce.referenceConfigurationArray.splice(e,1),e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);this.dce.referenceConfigurationArray.push(this.dceConfig),this.callbackCameraChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async e=>{let t=await this._decode_DCEFrame(e,{bCopyData:!1});await this.clearMapDecodeRecord();for(let e of t)delete e.bUnduplicated;if(this._drawResults(t),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan&&this.onImageRead(t),this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,e)},this.dce.on("cameraChange",this.callbackCameraChange),this.dce.on("resolutionChange",this.callbackResolutionChange),this.dce.on("cameraClose",this.callbackCameraClose),this.dce.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}releaseDCEConfig(){if(this.dce){if(w._onLog&&w._onLog("releaseDCEConfig()"),this.dce&&w.isCameraEnhancer(this.dce)){let e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);for(;-1!==e;)this.dce.referenceConfigurationArray.splice(e,1),e=this.dce.referenceConfigurationArray.indexOf(this.dceConfig);if(this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this.dce.stopFetchingLoop(),this.resultsOverlay){let e=this.dce._arrScanRegionOverlays.indexOf(this.resultsOverlay);for(;-1!==e;)this.dce._arrScanRegionOverlays.splice(e,1),e=this.dce._arrScanRegionOverlays.indexOf(this.resultsOverlay);this.resultsOverlay.remove(),this.resultsOverlay=null}}this.dce=null}}setImageSource(e){if(null==e)return this.imgSource=null,void this.releaseDCEConfig();if(w.isCameraEnhancer(e))this.dce=e,this.updateDCEConfig(),this.imgSource=null;else{if(!w.isImageSource(e))throw new Error("Invalid value.");this.releaseDCEConfig(),this.imgSource=e}}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:e,l:i,ls:n,sp:o,rmk:r}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,i,n=t._license||"",o=JSON.parse(JSON.stringify(t._licenseServer)),r=t._sessionPassword,s=0;if(n.startsWith("t")||n.startsWith("f"))s=0;else if(0===n.length||n.startsWith("P")||n.startsWith("L")||n.startsWith("Y")||n.startsWith("A"))s=1;else{s=2;const t=n.indexOf(":");if(-1!=t&&(n=n.substring(t+1)),n.startsWith("DLS2")){let t=n.substring(4);try{t=atob(t)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}const i=JSON.parse(t);if(n=i.handshakeCode?i.handshakeCode:i.organizationID?i.organizationID:"","number"==typeof n&&(n=JSON.stringify(n)),0===o.length){let e=[];i.mainServerURL&&(e[0]=i.mainServerURL),i.standbyServerURL&&(e[1]=i.standbyServerURL),o=h(e)}!r&&i.sessionPassword&&(r=i.sessionPassword),e=i.remark}("200001"===n||n.startsWith("200001-"))&&(o&&o.length||(n="")),n||(s=1)}if(s&&(globalThis.crypto||(i="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(i="Require https to use online key in this browser.")),i){if(1!==s)throw new Error(i);s=0,console.warn(i),t._lastErrorCode=-1,t._lastErrorString=i}return 1===s&&(n="",console.warn("Applying for a public trial license ...")),{lt:s,l:n,ls:o,sp:r,rmk:e}}throw new Error("Can't preprocess license again"+a)})(w);this._pLoad.task=async(s,a)=>{let d=w.engineResourcePath+w._workerName;w.engineResourcePath.startsWith(location.origin)||(d=await fetch(d).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),w._dbrWorker=new Worker(d),w._dbrWorker.onerror=e=>{let t=new Error(e.message);a(t)},w._dbrWorker.onmessage=async t=>{let i=t.data?t.data:t;switch(i.type){case"log":w._onLog&&w._onLog(i.message);break;case"load":{i.message&&(i.message=i.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,n=!1;1===e&&(n=!0),i.success?(w._dbrWorker.onerror=null,w._version=i.version+"(JS "+w._jsVersion+"."+w._jsEditVersion+")",w._onLog&&w._onLog("load dbr worker success"),i.message&&console.warn(i.message)):(t=new Error(i.message),t.stack=i.stack+"\n"+t.stack,n||111==i.ltsErrorCode&&-1!=i.message.toLowerCase().indexOf("trial license")&&(n=!0)),n&&w.showDialog(i.success?"warn":"error",i.message),i.success?s():a(t);break}case"task":{let e=i.id,t=i.body;try{w._taskCallbackMap.get(e)(t),w._taskCallbackMap.delete(e)}catch(t){throw w._taskCallbackMap.delete(e),t}break}default:w._onLog&&w._onLog(t)}},w._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:w.engineResourcePath,bUseFullFeature:w._bUseFullFeature,bd:w._bWasmDebug,v:w._jsVersion,brtk:!!e,bptk:1===e,l:i,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:t,fn:w.deviceFriendlyName,ls:n,sp:o,rmk:r})}}await this._pLoad}static async showDialog(e,t){if(!w._bNeverShowDialog)try{let i=await fetch(w.engineResourcePath+"dls.license.dialog.html");if(!i.ok)throw Error("Get license dialog fail. Network Error: "+i.statusText);let n=await i.text();if(!n.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let o=document.createElement("div");o.innerHTML=n;let r=[];for(let e=0;e{if(i==e.target){s.remove();for(let e of r)e.remove()}}));else if(!d&&i.classList.contains("dls-license-icon-close"))d=i,i.addEventListener("click",(()=>{s.remove();for(let e of r)e.remove()}));else if(!l&&i.classList.contains("dls-license-icon-error"))l=i,"error"!=e&&i.remove();else if(!h&&i.classList.contains("dls-license-icon-warn"))h=i,"warn"!=e&&i.remove();else if(!c&&i.classList.contains("dls-license-msg-content")){c=i;let e=t;for(;e;){let t=e.indexOf("["),n=e.indexOf("]",t),o=e.indexOf("(",n),r=e.indexOf(")",o);if(-1==t||-1==n||-1==o||-1==r){i.appendChild(new Text(e));break}t>0&&i.appendChild(new Text(e.substring(0,t)));let s=document.createElement("a"),a=e.substring(t+1,n);s.innerText=a;let d=e.substring(o+1,r);s.setAttribute("href",d),s.setAttribute("target","_blank"),i.appendChild(s),e=e.substring(r+1)}}document.body.appendChild(s)}catch(e){w._onLog&&w._onLog(e.message||e)}}static async createInstanceInWorker(e=!1){return await w.loadWasm(),await new Promise(((t,i)=>{let n=w._nextTaskID++;w._taskCallbackMap.set(n,(e=>{if(e.success)return t(e.instanceID);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),w._dbrWorker.postMessage({type:"createInstance",id:n,bScanner:e})}))}static async createInstance(){let e=new w;return e._instanceID=await w.createInstanceInWorker(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let i=w._nextTaskID++;w._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),w._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:i,instanceID:this._instanceID})}))}async decode(e){w._onLog&&w._onLog("decode(source: any)"),w._onLog&&(this._timeStartDecode=Date.now());{let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),e instanceof Blob?await this._decode_Blob(e,t):e instanceof ArrayBuffer?await this._decode_ArrayBuffer(e,t):e instanceof Uint8Array||e instanceof Uint8ClampedArray?await this._decode_Uint8Array(e,t):e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?await this._decode_Image(e,t):e instanceof HTMLCanvasElement?await this._decode_Canvas(e,t):e instanceof HTMLVideoElement?await this._decode_Video(e,t):"string"==typeof e?"data:image/"==e.substring(0,11)?await this._decode_Base64(e,t):await this._decode_Url(e,t):w.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):w.isDSImage(e)?(t.bCopyData=!0,await this._decode_DSImage(e,t)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(e,t)}async decodeUrl(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(e,t)}async _decodeBuffer_Uint8Array(e,t,i,n,o,r){return await new Promise(((s,a)=>{let d=w._nextTaskID++;w._taskCallbackMap.set(d,(e=>{if(e.success){let t,i=w._onLog?Date.now():0;w._onLog&&w._onLog("worker return result: "+i),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return a(e)}if(w._onLog){let e=Date.now();w._onLog("DBR time get result: "+i),w._onLog("Handle image cost: "+(this._timeEnterInnerDBR-this._timeStartDecode)),w._onLog("DBR worker decode image cost: "+(i-this._timeEnterInnerDBR)),w._onLog("DBR worker handle results: "+(e-i)),w._onLog("Total decode image cost: "+(e-this._timeStartDecode))}return s(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}})),this._timeEnterInnerDBR=Date.now(),w._onLog&&w._onLog("Send buffer to worker:"+this._timeEnterInnerDBR),w._dbrWorker.postMessage({type:"decodeBuffer",id:d,instanceID:this._instanceID,body:{buffer:e,width:t,height:i,stride:n,format:o,config:r}},[e.buffer]),w._onLog&&r&&r.timeStamp&&w._onLog("decode image delay: "+(this._timeEnterInnerDBR-r.timeStamp))}))}async _decodeBuffer_Blob(e,t,i,n,o,r){w._onLog&&w._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const s=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,i)=>{let n=new FileReader;n.readAsArrayBuffer(e),n.onload=()=>{t(n.result)},n.onerror=()=>{i(n.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(s),t,i,n,o,r)}async decodeBuffer(e,t,i,n,o,r){let s;return w._onLog&&w._onLog("decodeBuffer(buffer,width,height,stride,format)"),w._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?s=await this._decodeBuffer_Uint8Array(e,t,i,n,o,r):e instanceof ArrayBuffer?s=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,i,n,o,r):e instanceof Blob&&(s=await this._decodeBuffer_Blob(e,t,i,n,o,r)),s}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,i)=>{let n=w._nextTaskID++;w._taskCallbackMap.set(n,(e=>{if(e.success){let n;this._lastInnerDecodeDuration=e.duration;try{n=this._handleRetJsonString(e.decodeReturn)}catch(e){return i(e)}return t(n)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),w._dbrWorker.postMessage({type:"decodeFileInMemory",id:n,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let i=w._nextTaskID++;w._taskCallbackMap.set(i,(i=>{if(i.success){let t=JSON.parse(i.results);return null!=this.userDefinedRegion&&(t.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),e(t)}{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),w._dbrWorker.postMessage({type:"getRuntimeSettings",id:i,instanceID:this._instanceID})}))}async updateRuntimeSettings(e){let t;if("string"==typeof e)if("speed"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=3,t.expectedBarcodesCount=0,t.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=5,t.expectedBarcodesCount=512,t.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region}else t=JSON.parse(e);else{if("object"!=typeof e)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(t=JSON.parse(JSON.stringify(e)),t.region instanceof Array){let e=t.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(t.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!w._bUseFullFeature){if(0!=(t.barcodeFormatIds&~(g.BF_ONED|g.BF_QR_CODE|g.BF_PDF417|g.BF_DATAMATRIX))||0!=t.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=t.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let e=t.region;if(e instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(e)),(e.regionLeft||e.regionTop||e.regionRight||e.regionBottom||e.regionMeasuredByPercentage)&&(e.regionLeft||e.regionTop||100!=e.regionRight||100!=e.regionBottom||!e.regionMeasuredByPercentage)?this.region=e:this.region=null,t.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return await new Promise(((e,i)=>{let n=w._nextTaskID++;w._taskCallbackMap.set(n,(t=>{if(t.success){try{this._handleRetJsonString(t.updateReturn)}catch(e){i(e)}return e()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}})),w._dbrWorker.postMessage({type:"updateRuntimeSettings",id:n,instanceID:this._instanceID,body:{settings:JSON.stringify(t)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,await new Promise(((e,t)=>{let i=w._nextTaskID++;w._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),w._dbrWorker.postMessage({type:"resetRuntimeSettings",id:i,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!w._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((e,t)=>{let i=w._nextTaskID++;w._taskCallbackMap.set(i,(i=>{if(i.success)return e(i.results);{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),w._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:i,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!w._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof e)e=e;else{if("object"!=typeof e)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");e=JSON.stringify(e)}return await new Promise(((t,i)=>{let n=w._nextTaskID++;w._taskCallbackMap.set(n,(e=>{if(e.success){try{this._handleRetJsonString(e.initReturn)}catch(e){i(e)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),w._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:n,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){w._onLog&&w._onLog("_decode_Blob(blob: Blob)");let i=null,n=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(e)}catch(e){}i||(n=await function(e){return new Promise(((t,i)=>{let n=URL.createObjectURL(e),o=new Image;o.dbrObjUrl=n,o.src=n,o.onload=()=>{t(o)},o.onerror=e=>{i(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let o=await this._decode_Image(i||n,t);return i&&i.close(),o}async _decode_ArrayBuffer(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Uint8Array(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Image(e,t){w._onLog&&w._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),t=t||{};let i,n,o=e instanceof HTMLImageElement?e.naturalWidth:e.width,r=e instanceof HTMLImageElement?e.naturalHeight:e.height,s=Math.max(o,r);if(s>this._maxCvsSideLength){let e=this._maxCvsSideLength/s;i=Math.round(o*e),n=Math.round(r*e)}else i=o,n=r;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d"));return a.ctx2d.drawImage(e,0,0,o,r,0,0,i,n),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._decode_Canvas(a,t)}async _decode_Canvas(e,t){if(w._onLog&&w._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";if(0===e.width||0===e.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=e,this.oriCanvasData=null);let i=(e.ctx2d||e.getContext("2d")).getImageData(0,0,e.width,e.height).data;return await this._decodeBuffer_Uint8Array(i,e.width,e.height,4*e.width,c.IPF_ABGR_8888,t)}async _decode_Video(e,t){if(w._onLog&&w._onLog("_decode_Video(video)"),!(e instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";t=t||{};let i,n,o=e.videoWidth,r=e.videoHeight,s=Math.max(o,r);if(s>this._maxCvsSideLength){let e=this._maxCvsSideLength/s;i=Math.round(o*e),n=Math.round(r*e)}else i=o,n=r;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d"));return a.ctx2d.drawImage(e,0,0,o,r,0,0,i,n),await this._decode_Canvas(a,t)}async _decode_DCEFrame(e,t){if(w._onLog&&w._onLog("_decode_DCEFrame(dceFrame)"),!w.isDCEFrame(e))return null;let i;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,colorMode:e.colorMode,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{width:n,height:o,colorMode:r,timeStamp:s}=e;let a;a=t&&t.bCopyData?new Uint8Array(e.data):e.data;let d=null;if(t?(d=JSON.parse(JSON.stringify(t)),d.timeStamp=s):d={timeStamp:s},"grey"===r)i=await this._decodeBuffer_Uint8Array(a,n,o,n,c.IPF_GrayScaled,d);else if("rgba"===r)i=await this._decodeBuffer_Uint8Array(a,n,o,4*n,c.IPF_ABGR_8888,d);else{if("bgra"!==r)throw new Error(`Color mode '${r}' is not supported to decode.`);i=await this._decodeBuffer_Uint8Array(a,n,o,4*n,c.IPF_ARGB_8888,d)}return i}async _decode_DSImage(e,t){if(w._onLog&&w._onLog("_decode_DSImage(dsImage)"),!w.isDSImage(e))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,pixelFormat:e.pixelFormat.toLowerCase(),data:new Uint8Array(e.data),toCanvas:function(){const e=document.createElement("canvas");let t;switch(e.width=this.width,e.height=this.height,this.pixelFormat){case"grey":t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{let n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="blob",n.send(),n.onloadend=async()=>{t(n.response)},n.onerror=()=>{i(new Error("Network Error: "+n.statusText))}}));return await this._decode_Blob(i,t)}}async _decode_FilePath(e,t){throw w._onLog&&w._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static fixResultLocationWhenFilterRegionInJs(e,t,i,n,o,r,s,a){if(e&&t.length>0)for(let e of t){let t=e.localizationResult;2==t.resultCoordinateType&&(t.x1*=.01*s,t.x2*=.01*s,t.x3*=.01*s,t.x4*=.01*s,t.y1*=.01*a,t.y2*=.01*a,t.y3*=.01*a,t.y4*=.01*a);let d=s/o,l=a/r;t.x1=t.x1/d+i,t.x2=t.x2/d+i,t.x3=t.x3/d+i,t.x4=t.x4/d+i,t.y1=t.y1/l+n,t.y2=t.y2/l+n,t.y3=t.y3/l+n,t.y4=t.y4/l+n,2==t.resultCoordinateType&&(t.x1*=100/o,t.x2*=100/o,t.x3*=100/o,t.x4*=100/o,t.y1*=100/r,t.y2*=100/r,t.y3*=100/r,t.y4*=100/r)}}static BarcodeReaderException(e,t){let i,n=_.DBR_UNKNOWN;return"number"==typeof e?(n=e,i=new Error(t)):i=new Error(e),i.code=n,i}_handleRetJsonString(e){let t=_;if(e.textResults){for(let t=0;t{let i=t.indexOf(":");e[t.substring(0,i)]=t.substring(i+1)})),i.exception=e}}return e.decodeRecords?this.decodeRecords=e.decodeRecords:this.decodeRecords={},this._lastErrorCode=e.exception,this._lastErrorString=e.description,e.exception&&!w._setWarnnedEx.has(e.description)&&(w._setWarnnedEx.add(e.description),console.warn(e.description)),e.textResults}if(e.exception==t.DBR_SUCCESS)return e.data;throw w.BarcodeReaderException(e.exception,e.description)}async setModeArgument(e,t,i,n){return await new Promise(((o,r)=>{let s=w._nextTaskID++;w._taskCallbackMap.set(s,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return r(e)}return o()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,r(t)}})),w._dbrWorker.postMessage({type:"setModeArgument",id:s,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i,argumentValue:n}})}))}async getModeArgument(e,t,i){return await new Promise(((n,o)=>{let r=w._nextTaskID++;w._taskCallbackMap.set(r,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return o(e)}return n(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,o(t)}})),w._dbrWorker.postMessage({type:"getModeArgument",id:r,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i}})}))}async getIntermediateResults(){return await new Promise(((e,t)=>{let i=w._nextTaskID++;w._taskCallbackMap.set(i,(i=>{if(i.success)return e(i.results);{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),w._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let e=await this.getIntermediateResults(),t=[];for(let i of e)if(i.dataType==u.IMRDT_IMAGE)for(let e of i.results){const i=e.bytes;let n;switch(w._onLog&&w._onLog(" "+i.length+" "+i.byteLength+" "+e.width+" "+e.height+" "+e.stride+" "+e.format),e.format){case c.IPF_ABGR_8888:n=new Uint8ClampedArray(i);break;case c.IPF_RGB_888:{const e=i.length/3;n=new Uint8ClampedArray(4*e);for(let t=0;t{let i=w._nextTaskID++;w._taskCallbackMap.set(i,(i=>{if(i.success){let t=i.results;return t.intervalTime=this.intervalTime,t.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,t.soundOnSuccessfullRead=this.soundSource,t.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,t.vibrateDuration=this.vibrateDuration,e(t)}{let e=new Error(i.message);return e.stack+="\n"+i.stack,t(e)}})),w._dbrWorker.postMessage({type:"getScanSettings",id:i,instanceID:this._instanceID})}))}async updateScanSettings(e){if(!e)return;const t=JSON.parse(JSON.stringify(e));return t.hasOwnProperty("intervalTime")&&(this.intervalTime=t.intervalTime,delete t.intervalTime),t.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=t.whenToPlaySoundforSuccessfulRead,delete t.whenToPlaySoundforSuccessfulRead),t.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=t.soundOnSuccessfullRead,delete t.soundOnSuccessfullRead),t.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=t.whenToVibrateforSuccessfulRead,delete t.whenToVibrateforSuccessfulRead),t.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=t.vibrateDuration,delete t.vibrateDuration),await new Promise(((e,i)=>{let n=w._nextTaskID++;w._taskCallbackMap.set(n,(t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack+="\n"+t.stack,i(e)}})),w._dbrWorker.postMessage({type:"updateScanSettings",id:n,instanceID:this._instanceID,body:{settings:t}})}))}_cloneDecodeResults(e){if(e instanceof Array){let t=[];for(let i of e)t.push(this._cloneDecodeResults(i));return t}{let t=e;return JSON.parse(JSON.stringify(t,((e,t)=>"oriVideoCanvas"==e||"searchRegionCanvas"==e?void 0:t)))}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this.imgSource||this._bPauseScan)return w._onLog&&w._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));w._onLog&&w._onLog("======= once read ======="),w._onLog&&(this._timeStartDecode=Date.now());let e=null,t=null;if(this.dce)e=this._getVideoFrame();else if(this.imgSource&&(t=await this.imgSource.getImage(),!w.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let i=null;return e?i=await this._decode_DCEFrame(e,{bScanner:!0,bCopyData:!1}):t&&(i=await this._decode_DSImage(t,{bScanner:!0,bCopyData:!1})),i})().then((e=>{if(w._onLog&&w._onLog(e),this.dce){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost;this._indexCurrentDecodingFrame;const i=()=>{let i=0;if(t&&t.length){let n=Math.min(...e),o=Math.max(...t);n&&o&&(i=n-o)}else i=0;return i>0?i:0};(()=>{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=i()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this.imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead)t=!0;else if("unique"===this.bPlaySoundOnSuccessfulRead)for(let i of e)if(i.bUnduplicated){t=!0;break}t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead)t=!0;else if("unique"===this.bVibrateOnSuccessfulRead)for(let i of e)if(i.bUnduplicated){t=!0;break}if(t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onImageRead){let t=this._cloneDecodeResults(e);for(let e of t)delete e.bUnduplicated;this.onImageRead(t)}if(this.onUniqueRead)for(let t of e)t.bUnduplicated&&this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t));this._drawResults(e)}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce&&this.dce.stopFetchingLoop(),w._onLog&&w._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e=this.dce.isFetchingLoopStarted();if(this.dceConfig.loopInterval=this._intervalGetVideoFrame,e||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dceConfig.loopInterval=0,null;const t=this.dce.getFrameFromBuffer();return(e=>{if(!e)return;let t=e.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(t)})(t),t}_drawResults(e){if(!this.dce||this._bPauseScan)return;if(!this.resultsOverlay){if(!this.dce.isOpen())return;this.resultsOverlay=this.dce.addScanRegionOverlayCanvas()}const t=this.resultsOverlay.getContext("2d");if(t.clearRect(0,0,this.resultsOverlay.width,this.resultsOverlay.height),e){t.globalCompositeOperation="destination-over",t.fillStyle=this.barcodeFillStyle,t.strokeStyle=this.barcodeStrokeStyle,t.lineWidth=this.barcodeLineWidth;for(let i of e){let e=i.localizationResult;t.beginPath(),t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineTo(e.x3,e.y3),t.lineTo(e.x4,e.y4),t.fill(),t.beginPath(),t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineTo(e.x3,e.y3),t.lineTo(e.x4,e.y4),t.closePath(),t.stroke()}}}async startScanning(e){if(!this.dce&&!this.imgSource)throw new Error("'imageSource' is not set. call 'setImageSource()' before 'startScanning()'.");if("closed"!=this._tempSolutionStatus)return;if(this._tempSolutionStatus="opening","opening"!=this._tempSolutionStatus)return;let t=null;return this.dce&&!this.dce.isOpen()&&(this.dce.ifShowScanRegionLaser=!0,t=await this.dce.open(e)),"opening"==this._tempSolutionStatus?(this._bPauseScan=!1,this.dce&&this.dce.singleFrameMode||this._loopReadVideo(),this._tempSolutionStatus="opened",this.keepAlive(),t):void 0}stopScanning(e){this.dce&&(this._drawResults(null),this.dce.ifShowScanRegionLaser=!1,this.dce.close(e)),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._tempSolutionStatus="closed"}pauseScanning(){if(this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.ifShowScanRegionLaser=!1,this.dce.stopFetchingLoop()}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.ifShowScanRegionLaser=!0}}destroyContext(){if(w._onLog&&w._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,(this.dce||"opening"===this._tempSolutionStatus)&&this.stopScanning(),this.setImageSource(null);let e=w._nextTaskID++;w._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),w._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}} +const e="undefined"==typeof self;let t,i,r,n,s;if("undefined"!=typeof navigator&&(t=navigator,i=t.userAgent,r=t.platform,n=t.mediaDevices),!e){const e={init:function(){this.browser=this.searchString(this.dataBrowser)||"unknownBrowser",this.version=this.searchVersion(i)||this.searchVersion(t.appVersion)||0,this.OS=this.searchString(this.dataOS)||"unknownOS","Linux"==this.OS&&-1!=i.indexOf("Windows NT")&&(this.OS="HarmonyOS")},searchString:function(e){for(let t=0;t{let e=!1;if(l)try{(await n.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===s.browser&&s.version>66||"Safari"===s.browser&&s.version>13||"OPR"===s.browser&&s.version>43||"Edge"===s.browser&&s.version;const c=(()=>{if(!e&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),u=" is not allowed to change after `createInstance` or `loadWasm` is called.",d=!e&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",f=!e&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",g=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let i=0;ie&&"object"==typeof e&&"function"==typeof e.then;var S=function(){this.init()};S.prototype={init:function(){var e=this||b;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var t=this||b;if(e=parseFloat(e),t.ctx||E(),void 0!==e&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,b.ctx.currentTime);for(var i=0;i=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,E()),e},codecs:function(e){return(this||b)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||b;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||b,t=null;try{t="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!t||"function"!=typeof t.canPlayType)return e;var i=t.canPlayType("audio/mpeg;").replace(/^no$/,""),r=e._navigator?e._navigator.userAgent:"",n=r.match(/OPR\/([0-6].)/g),s=n&&parseInt(n[0].split("/")[1],10)<33,o=-1!==r.indexOf("Safari")&&-1===r.indexOf("Chrome"),a=r.match(/Version\/(.*?) /),l=o&&a&&parseInt(a[1],10)<15;return e._codecs={mp3:!(s||!i&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!i,opus:!!t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(t.canPlayType('audio/wav; codecs="1"')||t.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!t.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!t.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/m4a;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(t.canPlayType("audio/x-m4b;")||t.canPlayType("audio/m4b;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(t.canPlayType("audio/x-mp4;")||t.canPlayType("audio/mp4;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(l||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(l||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!t.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(t.canPlayType("audio/x-flac;")||t.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||b;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var t=function(i){for(;e._html5AudioPool.length0?o._seek:i._sprite[e][0]/1e3),h=Math.max(0,(i._sprite[e][0]+i._sprite[e][1])/1e3-l),c=1e3*h/Math.abs(o._rate),u=i._sprite[e][0]/1e3,d=(i._sprite[e][0]+i._sprite[e][1])/1e3;o._sprite=e,o._ended=!1;var f=function(){o._paused=!1,o._seek=l,o._start=u,o._stop=d,o._loop=!(!o._loop&&!i._sprite[e][2])};if(!(l>=d)){var g=o._node;if(i._webAudio){var _=function(){i._playLock=!1,f(),i._refreshBuffer(o);var e=o._muted||i._muted?0:o._volume;g.gain.setValueAtTime(e,b.ctx.currentTime),o._playStart=b.ctx.currentTime,void 0===g.bufferSource.start?o._loop?g.bufferSource.noteGrainOn(0,l,86400):g.bufferSource.noteGrainOn(0,l,h):o._loop?g.bufferSource.start(0,l,86400):g.bufferSource.start(0,l,h),c!==1/0&&(i._endTimers[o._id]=setTimeout(i._ended.bind(i,o),c)),t||setTimeout((function(){i._emit("play",o._id),i._loadQueue()}),0)};"running"===b.state&&"interrupted"!==b.ctx.state?_():(i._playLock=!0,i.once("resume",_),i._clearTimer(o._id))}else{var p=function(){g.currentTime=l,g.muted=o._muted||i._muted||b._muted||g.muted,g.volume=o._volume*b.volume(),g.playbackRate=o._rate;try{var r=g.play();if(r&&"undefined"!=typeof Promise&&(r instanceof Promise||"function"==typeof r.then)?(i._playLock=!0,f(),r.then((function(){i._playLock=!1,g._unlocked=!0,t?i._loadQueue():i._emit("play",o._id)})).catch((function(){i._playLock=!1,i._emit("playerror",o._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),o._ended=!0,o._paused=!0}))):t||(i._playLock=!1,f(),i._emit("play",o._id)),g.playbackRate=o._rate,g.paused)return void i._emit("playerror",o._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||o._loop?i._endTimers[o._id]=setTimeout(i._ended.bind(i,o),c):(i._endTimers[o._id]=function(){i._ended(o),g.removeEventListener("ended",i._endTimers[o._id],!1)},g.addEventListener("ended",i._endTimers[o._id],!1))}catch(e){i._emit("playerror",o._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===g.src&&(g.src=i._src,g.load());var m=window&&window.ejecta||!g.readyState&&b._navigator.isCocoonJS;if(g.readyState>=3||m)p();else{i._playLock=!0,i._state="loading";var v=function(){i._state="loaded",p(),g.removeEventListener(b._canPlayEvent,v,!1)};g.addEventListener(b._canPlayEvent,v,!1),i._clearTimer(o._id)}}return o._id}i._ended(o)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var i=t._getSoundIds(e),r=0;r=0?t=parseInt(n[0],10):e=parseFloat(n[0])}else n.length>=2&&(e=parseFloat(n[0]),t=parseInt(n[1],10));if(!(void 0!==e&&e>=0&&e<=1))return(i=t?r._soundById(t):r._sounds[0])?i._volume:0;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"volume",action:function(){r.volume.apply(r,n)}}),r;void 0===t&&(r._volume=e),t=r._getSoundIds(t);for(var a=0;a0?r/h:r),u=Date.now();e._fadeTo=i,e._interval=setInterval((function(){var n=(Date.now()-u)/r;u=Date.now(),a+=l*n,a=Math.round(100*a)/100,a=l<0?Math.max(i,a):Math.min(i,a),o._webAudio?e._volume=a:o.volume(a,e._id,!0),s&&(o._volume=a),(it&&a>=i)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,o.volume(i,e._id),o._emit("fade",e._id))}),c)},_stopFade:function(e){var t=this,i=t._soundById(e);return i&&i._interval&&(t._webAudio&&i._node.gain.cancelScheduledValues(b.ctx.currentTime),clearInterval(i._interval),i._interval=null,t.volume(i._fadeTo,e),i._fadeTo=null,t._emit("fade",e)),t},loop:function(){var e,t,i,r=this,n=arguments;if(0===n.length)return r._loop;if(1===n.length){if("boolean"!=typeof n[0])return!!(i=r._soundById(parseInt(n[0],10)))&&i._loop;e=n[0],r._loop=e}else 2===n.length&&(e=n[0],t=parseInt(n[1],10));for(var s=r._getSoundIds(t),o=0;o=0?t=parseInt(n[0],10):e=parseFloat(n[0])}else 2===n.length&&(e=parseFloat(n[0]),t=parseInt(n[1],10));if("number"!=typeof e)return(i=r._soundById(t))?i._rate:r._rate;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"rate",action:function(){r.rate.apply(r,n)}}),r;void 0===t&&(r._rate=e),t=r._getSoundIds(t);for(var a=0;a=0?t=parseInt(r[0],10):i._sounds.length&&(t=i._sounds[0]._id,e=parseFloat(r[0]))}else 2===r.length&&(e=parseFloat(r[0]),t=parseInt(r[1],10));if(void 0===t)return 0;if("number"==typeof e&&("loaded"!==i._state||i._playLock))return i._queue.push({event:"seek",action:function(){i.seek.apply(i,r)}}),i;var o=i._soundById(t);if(o){if(!("number"==typeof e&&e>=0)){if(i._webAudio){var a=i.playing(t)?b.ctx.currentTime-o._playStart:0,l=o._rateSeek?o._rateSeek-o._seek:0;return o._seek+(l+a*Math.abs(o._rate))}return o._node.currentTime}var h=i.playing(t);h&&i.pause(t,!0),o._seek=e,o._ended=!1,i._clearTimer(t),i._webAudio||!o._node||isNaN(o._node.duration)||(o._node.currentTime=e);var c=function(){h&&i.play(t,!0),i._emit("seek",t)};if(h&&!i._webAudio){var u=function(){i._playLock?setTimeout(u,0):c()};setTimeout(u,0)}else c()}return i},playing:function(e){var t=this;if("number"==typeof e){var i=t._soundById(e);return!!i&&!i._paused}for(var r=0;r=0&&b._howls.splice(r,1);var n=!0;for(i=0;i=0){n=!1;break}return T&&n&&delete T[e._src],b.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,i,r){var n=this["_on"+e];return"function"==typeof t&&n.push(r?{id:i,fn:t,once:r}:{id:i,fn:t}),this},off:function(e,t,i){var r=this,n=r["_on"+e],s=0;if("number"==typeof t&&(i=t,t=null),t||i)for(s=0;s=0;s--)n[s].id&&n[s].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,i)}.bind(r,n[s].fn),0),n[s].once&&r.off(e,n[s].fn,n[s].id));return r._loadQueue(e),r},_loadQueue:function(e){var t=this;if(t._queue.length>0){var i=t._queue[0];i.event===e&&(t._queue.shift(),t._loadQueue()),e||i.action()}return t},_ended:function(e){var t=this,i=e._sprite;if(!t._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;r--){if(i<=t)return;e._sounds[r]._ended&&(e._webAudio&&e._sounds[r]._node&&e._sounds[r]._node.disconnect(0),e._sounds.splice(r,1),i--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],i=0;i=0;if(!e.bufferSource)return this;if(b._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))try{e.bufferSource.buffer=b._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(b._navigator&&b._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var w=function(e){this._parent=e,this.init()};w.prototype={init:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++b._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,i=b._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=void 0===b.ctx.createGain?b.ctx.createGainNode():b.ctx.createGain(),e._node.gain.setValueAtTime(i,b.ctx.currentTime),e._node.paused=!0,e._node.connect(b.masterGain)):b.noAudio||(e._node=b._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(b._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=t._src,e._node.preload=!0===t._preload?"auto":t._preload,e._node.volume=i*b.volume(),e._node.load()),e},reset:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++b._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,t=e._parent;t._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(t._sprite).length&&(t._sprite={__default:[0,1e3*t._duration]}),"loaded"!==t._state&&(t._state="loaded",t._emit("load"),t._loadQueue()),e._node.removeEventListener(b._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var T={},x=function(e){var t=e._src;if(T[t])return e._duration=T[t].duration,void I(e);if(/^data:[^;]+;base64,/.test(t)){for(var i=atob(t.split(",")[1]),r=new Uint8Array(i.length),n=0;n0?(T[t._src]=e,I(t,e)):i()};"undefined"!=typeof Promise&&1===b.ctx.decodeAudioData.length?b.ctx.decodeAudioData(e).then(r).catch(i):b.ctx.decodeAudioData(e,r,i)},I=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},E=function(){if(b.usingWebAudio){try{"undefined"!=typeof AudioContext?b.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?b.ctx=new webkitAudioContext:b.usingWebAudio=!1}catch(e){b.usingWebAudio=!1}b.ctx||(b.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(b._navigator&&b._navigator.platform),t=b._navigator&&b._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),i=t?parseInt(t[1],10):null;if(e&&i&&i<9){var r=/safari/.test(b._navigator&&b._navigator.userAgent.toLowerCase());b._navigator&&!r&&(b.usingWebAudio=!1)}b.usingWebAudio&&(b.masterGain=void 0===b.ctx.createGain?b.ctx.createGainNode():b.ctx.createGain(),b.masterGain.gain.setValueAtTime(b._muted?0:b._volume,b.ctx.currentTime),b.masterGain.connect(b.ctx.destination)),b._setup()}};!function(e,t,i,r){var n;e.prototype._pos=[0,0,0],e.prototype._orientation=[0,0,-1,0,1,0],e.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var i=t._howls.length-1;i>=0;i--)t._howls[i].stereo(e);return t},e.prototype.pos=function(e,i,r){var n=this;return n.ctx&&n.ctx.listener?(i="number"!=typeof i?n._pos[1]:i,r="number"!=typeof r?n._pos[2]:r,"number"!=typeof e?n._pos:(n._pos=[e,i,r],void 0!==n.ctx.listener.positionX?(n.ctx.listener.positionX.setTargetAtTime(n._pos[0],t.ctx.currentTime,.1),n.ctx.listener.positionY.setTargetAtTime(n._pos[1],t.ctx.currentTime,.1),n.ctx.listener.positionZ.setTargetAtTime(n._pos[2],t.ctx.currentTime,.1)):n.ctx.listener.setPosition(n._pos[0],n._pos[1],n._pos[2]),n)):n},e.prototype.orientation=function(e,i,r,n,s,o){var a=this;if(!a.ctx||!a.ctx.listener)return a;var l=a._orientation;return i="number"!=typeof i?l[1]:i,r="number"!=typeof r?l[2]:r,n="number"!=typeof n?l[3]:n,s="number"!=typeof s?l[4]:s,o="number"!=typeof o?l[5]:o,"number"!=typeof e?l:(a._orientation=[e,i,r,n,s,o],void 0!==a.ctx.listener.forwardX?(a.ctx.listener.forwardX.setTargetAtTime(e,t.ctx.currentTime,.1),a.ctx.listener.forwardY.setTargetAtTime(i,t.ctx.currentTime,.1),a.ctx.listener.forwardZ.setTargetAtTime(r,t.ctx.currentTime,.1),a.ctx.listener.upX.setTargetAtTime(n,t.ctx.currentTime,.1),a.ctx.listener.upY.setTargetAtTime(s,t.ctx.currentTime,.1),a.ctx.listener.upZ.setTargetAtTime(o,t.ctx.currentTime,.1)):a.ctx.listener.setOrientation(e,i,r,n,s,o),a)},i.prototype.init=(n=i.prototype.init,function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],n.call(this,e)}),i.prototype.stereo=function(e,i){var r=this;if(!r._webAudio)return r;if("loaded"!==r._state)return r._queue.push({event:"stereo",action:function(){r.stereo(e,i)}}),r;var n=void 0===t.ctx.createStereoPanner?"spatial":"stereo";if(void 0===i){if("number"!=typeof e)return r._stereo;r._stereo=e,r._pos=[e,0,0]}for(var o=r._getSoundIds(i),a=0;a{console.warn(`Sound '${e}' playback failure: ${t}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.captureAndDecodeInParallel=!0,this.barcodeFillStyle="rgba(254,180,32,0.3)",this.barcodeStrokeStyle="rgba(254,180,32,0.9)",this.barcodeLineWidth=1,this._dce=null,this._imgSource=null,this._maxCvsSideLength=R,this._tempSolutionStatus="closed"}static get version(){return this._version}static get license(){return this._license}static set license(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`license`"+u);i._license=t})(D,e)}static get productKeys(){return this._license}static set productKeys(e){D.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){D.license=e}static get organizationID(){return this._license}static set organizationID(e){D.license=e}static set sessionPassword(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`sessionPassword`"+u);i._sessionPassword=t})(D,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:o,worker:a,getUserMedia:l,camera:await h(),browser:s.browser,version:s.version,OS:s.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(t){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");D._engineResourcePath=(t=>{if(null==t&&(t="./"),!e){let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(t)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+u);i._licenseServer=g(t)})(D,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+u);i._deviceFriendlyName=t||""})(D,e)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(e){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");D.__bUseFullFeature=e}static isImageSource(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"getImage"in e}static isDSImage(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("width"in e&&("height"in e&&"pixelFormat"in e)))}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("region"in e&&("sx"in e&&("sy"in e&&("width"in e&&("height"in e&&("colorMode"in e&&("timeSpent"in e&&("timeStamp"in e&&("isCropped"in e&&("toCanvas"in e&&("_sWidth"in e&&("_sHeight"in e&&"_bUseWebGL"in e)))))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(e){this._region=e,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var e;return null===(e=D._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",D.engineResourcePath)}static set defaultUIElementURL(e){D._defaultUIElementURL=e}static _fireHTTPSWarnning(){D.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{D.onWarning&&D.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new C({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(e){this.bPlaySoundOnSuccessfulRead="never"!==e&&e}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(e){this.bVibrateOnSuccessfulRead="never"!==e&&e}set dce(e){this._dce=e}get dce(){return!this._dce||this._dce.isDisposed?null:this._dce}set maxCvsSideLength(e){this._maxCvsSideLength=e,this._dceControler&&this._dceControler.setDisiredValue(this,"maxCvsSideLength",e)}get maxCvsSideLength(){return this._maxCvsSideLength}async _registerDCEControler(){if(!this.dce)return;D._onLog&&D._onLog("_registerDCEControler()");const e=this.dce;this._dceControler=e._createControler();const t=this._dceControler;t.register(this),t.setDisiredValue(this,"refreshInterval",200),t.setDisiredValue(this,"maxCvsSideLength",this._maxCvsSideLength);try{ResizeObserver}catch(e){"ReferenceError"===e.name&&window&&(window.ResizeObserver=void 0)}const i=e.getUIElement(),r=this.dce.constructor;if("@engineResourcePath/dce.ui.html"===r._defaultUIElementURL)try{i?i===t._innerSetUI&&(await e.setUIElement(`${r.engineResourcePath}dce.ui.html`),t._innerSetUI=e.getUIElement()):(await e.setUIElement(`${r.engineResourcePath}dbr.ui.html`),t._innerSetUI=e.getUIElement())}catch(t){await e.setUIElement(r.defaultUIElementURL)}else i||await e.setUIElement(r.defaultUIElementURL);this.callbackCameraChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async e=>{let t=await this._decode_DCEFrame(e,{bCopyData:!1});if(await this.clearMapDecodeRecord(),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(t);this.onImageRead(e)}if(this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e));const{sx:i,sy:r,width:n,height:s,_sWidth:o,_sHeight:a}=e;D.recalculateResultLocation(t,i,r,o,a,n,s),this._drawResults(t)},e.on("cameraChange",this.callbackCameraChange),e.on("resolutionChange",this.callbackResolutionChange),e.on("cameraClose",this.callbackCameraClose),e.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}_logoutDCEControler(){this.dce&&this._dceControler&&(D._onLog&&D._onLog("_logoutDCEControler()"),this._dceControler.logout(this),this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this._dceControler=null,this.dce=null)}async setImageSource(e,t){if(null==e)return this._imgSource=null,this._logoutDCEControler(),void(this._drawingItemNamespace=null);if(e&&e.isCameraEnhancer)this.dce=e,await this._registerDCEControler(),this._imgSource=null;else{if(!D.isImageSource(e))throw new Error("Invalid value.");this._logoutDCEControler(),this._imgSource=e}t&&t.resultsHighlightBaseShapes&&(this._drawingItemNamespace=t.resultsHighlightBaseShapes)}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:e,l:t,ls:i,sp:r,rmk:n}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,i,r=t._license||"",n=JSON.parse(JSON.stringify(t._licenseServer)),s=t._sessionPassword,o=0;if(r.startsWith("t")||r.startsWith("f"))o=0;else if(0===r.length||r.startsWith("P")||r.startsWith("L")||r.startsWith("Y")||r.startsWith("A"))o=1;else{o=2;const t=r.indexOf(":");if(-1!=t&&(r=r.substring(t+1)),r.startsWith("DLS2")){let t=r.substring(4);try{t=atob(t)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}const i=JSON.parse(t);if(r=i.handshakeCode?i.handshakeCode:i.organizationID?i.organizationID:"","number"==typeof r&&(r=JSON.stringify(r)),0===n.length){let e=[];i.mainServerURL&&(e[0]=i.mainServerURL),i.standbyServerURL&&(e[1]=i.standbyServerURL),n=g(e)}!s&&i.sessionPassword&&(s=i.sessionPassword),e=i.remark}("200001"===r||r.startsWith("200001-"))&&(n&&n.length||(r="")),r||(o=1)}if(o&&(globalThis.crypto||(i="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(i="Require https to use online key in this browser.")),i){if(1!==o)throw new Error(i);o=0,console.warn(i),t._lastErrorCode=-1,t._lastErrorString=i}return 1===o&&(r="",console.warn("Applying for a public trial license ...")),{lt:o,l:r,ls:n,sp:s,rmk:e}}throw new Error("Can't preprocess license again"+u)})(D);this._pLoad.task=async(o,a)=>{let l=D.engineResourcePath+D._workerName;D.engineResourcePath.startsWith(location.origin)||(l=await fetch(l).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),D._dbrWorker=new Worker(l),D._dbrWorker.onerror=e=>{let t=new Error(e.message);a(t)},D._dbrWorker.onmessage=async t=>{let i=t.data?t.data:t;switch(i.type){case"log":D._onLog&&D._onLog(i.message);break;case"load":{i.message&&(i.message=i.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,r=!1;1===e&&(r=!0),i.success?(D._dbrWorker.onerror=null,D._version=i.version+"(JS "+D._jsVersion+"."+D._jsEditVersion+")",D._onLog&&D._onLog("load dbr worker success"),i.message&&console.warn(i.message)):(t=new Error(i.message),t.stack=i.stack+"\n"+t.stack,r||111==i.ltsErrorCode&&-1!=i.message.toLowerCase().indexOf("trial license")&&(r=!0)),r&&D.showDialog(i.success?"warn":"error",i.message),i.success?o():a(t);break}case"task":{let e=i.id,t=i.body;try{D._taskCallbackMap.get(e)(t),D._taskCallbackMap.delete(e)}catch(t){throw D._taskCallbackMap.delete(e),t}break}default:D._onLog&&D._onLog(t)}},D._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:D.engineResourcePath,bUseFullFeature:D._bUseFullFeature,bd:D._bWasmDebug,v:D._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:s,fn:D.deviceFriendlyName,ls:i,sp:r,rmk:n})}}await this._pLoad}static async showDialog(e,t){await(async(e,t,i)=>{if(!e._bNeverShowDialog)try{let r=await fetch(e.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let n=await r.text();if(!n.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.innerHTML=n;let o=[];for(let e=0;e{if(e==t.target){a.remove();for(let e of o)e.remove()}}));else if(!h&&e.classList.contains("dls-license-icon-close"))h=e,e.addEventListener("click",(()=>{a.remove();for(let e of o)e.remove()}));else if(!c&&e.classList.contains("dls-license-icon-error"))c=e,"error"!=t&&e.remove();else if(!u&&e.classList.contains("dls-license-icon-warn"))u=e,"warn"!=t&&e.remove();else if(!d&&e.classList.contains("dls-license-msg-content")){d=e;let t=i;for(;t;){let i=t.indexOf("["),r=t.indexOf("]",i),n=t.indexOf("(",r),s=t.indexOf(")",n);if(-1==i||-1==r||-1==n||-1==s){e.appendChild(new Text(t));break}i>0&&e.appendChild(new Text(t.substring(0,i)));let o=document.createElement("a"),a=t.substring(i+1,r);o.innerText=a;let l=t.substring(n+1,s);o.setAttribute("href",l),o.setAttribute("target","_blank"),e.appendChild(o),t=t.substring(s+1)}}document.body.appendChild(a)}catch(t){e._onLog&&e._onLog(t.message||t)}})(this,e,t)}static async createInstanceInWorker(e=!1){return await D.loadWasm(),await new Promise(((t,i)=>{let r=D._nextTaskID++;D._taskCallbackMap.set(r,(e=>{if(e.success)return t(e.instanceID);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),D._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}static async createInstance(){let e=new D;return e._instanceID=await D.createInstanceInWorker(),D._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let i=D._nextTaskID++;D._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),D._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:i,instanceID:this._instanceID})}))}async decode(e){D._onLog&&D._onLog("decode(source: any)"),D._onLog&&(this._timeStartDecode=Date.now());{let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),e instanceof Blob?await this._decode_Blob(e,t):e instanceof ArrayBuffer?await this._decode_ArrayBuffer(e,t):e instanceof Uint8Array||e instanceof Uint8ClampedArray?await this._decode_Uint8Array(e,t):e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?await this._decode_Image(e,t):e instanceof HTMLCanvasElement?await this._decode_Canvas(e,t):e instanceof HTMLVideoElement?await this._decode_Video(e,t):"string"==typeof e?"data:image/"==e.substring(0,11)?await this._decode_Base64(e,t):await this._decode_Url(e,t):D.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):D.isDSImage(e)?(t.bCopyData=!0,await this._decode_DSImage(e,t)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(e,t)}async decodeUrl(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(e,t)}async _decodeBuffer_Uint8Array(e,t,i,r,n,s){return await new Promise(((o,a)=>{let l=D._nextTaskID++;D._taskCallbackMap.set(l,(e=>{if(e.success){let t,i=D._onLog?Date.now():0;D._onLog&&D._onLog("worker return result: "+i),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return a(e)}if(D._onLog){let e=Date.now();D._onLog("DBR time get result: "+i),D._onLog("Handle image cost: "+(this._timeEnterInnerDBR-this._timeStartDecode)),D._onLog("DBR worker decode image cost: "+(i-this._timeEnterInnerDBR)),D._onLog("DBR worker handle results: "+(e-i)),D._onLog("Total decode image cost: "+(e-this._timeStartDecode))}return o(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}})),this._timeEnterInnerDBR=Date.now(),D._onLog&&D._onLog("Send buffer to worker:"+this._timeEnterInnerDBR),D._dbrWorker.postMessage({type:"decodeBuffer",id:l,instanceID:this._instanceID,body:{buffer:e,width:t,height:i,stride:r,format:n,config:s}},[e.buffer]),D._onLog&&s&&s.timeStamp&&D._onLog("decode image delay: "+(this._timeEnterInnerDBR-s.timeStamp))}))}async _decodeBuffer_Blob(e,t,i,r,n,s){D._onLog&&D._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const o=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,i)=>{let r=new FileReader;r.readAsArrayBuffer(e),r.onload=()=>{t(r.result)},r.onerror=()=>{i(r.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(o),t,i,r,n,s)}async decodeBuffer(e,t,i,r,n,s){let o;return D._onLog&&D._onLog("decodeBuffer(buffer,width,height,stride,format)"),D._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?o=await this._decodeBuffer_Uint8Array(e,t,i,r,n,s):e instanceof ArrayBuffer?o=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,i,r,n,s):e instanceof Blob&&(o=await this._decodeBuffer_Blob(e,t,i,r,n,s)),o}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,i)=>{let r=D._nextTaskID++;D._taskCallbackMap.set(r,(e=>{if(e.success){let r;this._lastInnerDecodeDuration=e.duration;try{r=this._handleRetJsonString(e.decodeReturn)}catch(e){return i(e)}return t(r)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),D._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let i=D._nextTaskID++;D._taskCallbackMap.set(i,(i=>{if(i.success){let t=JSON.parse(i.results);return null!=this.userDefinedRegion&&(t.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),e(t)}{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),D._dbrWorker.postMessage({type:"getRuntimeSettings",id:i,instanceID:this._instanceID})}))}async updateRuntimeSettings(e){let t;if("string"==typeof e)if("speed"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=3,t.expectedBarcodesCount=0,t.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=5,t.expectedBarcodesCount=512,t.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region}else if("dense"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=9,t.expectedBarcodesCount=0,t.localizationModes=[2,8,0,0,0,0,0,0]}else if("distance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=3,t.expectedBarcodesCount=0,t.localizationModes=[2,8,0,0,0,0,0,0]}else t=JSON.parse(e);else{if("object"!=typeof e)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(t=JSON.parse(JSON.stringify(e)),t.region instanceof Array){let e=t.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(t.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!D._bUseFullFeature){if(0!=(t.barcodeFormatIds&~(v.BF_ONED|v.BF_QR_CODE|v.BF_PDF417|v.BF_DATAMATRIX))||0!=t.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=t.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let e=t.region;if(e instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(e)),(e.regionLeft||e.regionTop||e.regionRight||e.regionBottom||e.regionMeasuredByPercentage)&&(e.regionLeft||e.regionTop||100!=e.regionRight||100!=e.regionBottom||!e.regionMeasuredByPercentage)?this.region=e:this.region=null,t.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return await new Promise(((e,i)=>{let r=D._nextTaskID++;D._taskCallbackMap.set(r,(t=>{if(t.success){try{this._handleRetJsonString(t.updateReturn)}catch(e){i(e)}return e()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}})),D._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(t)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=R,await new Promise(((e,t)=>{let i=D._nextTaskID++;D._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),D._dbrWorker.postMessage({type:"resetRuntimeSettings",id:i,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!D._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((e,t)=>{let i=D._nextTaskID++;D._taskCallbackMap.set(i,(i=>{if(i.success)return e(i.results);{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),D._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:i,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!D._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof e)e=e;else{if("object"!=typeof e)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");e=JSON.stringify(e)}return await new Promise(((t,i)=>{let r=D._nextTaskID++;D._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.initReturn)}catch(e){i(e)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),D._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){D._onLog&&D._onLog("_decode_Blob(blob: Blob)");let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(e)}catch(e){}i||(r=await function(e){return new Promise(((t,i)=>{let r=URL.createObjectURL(e),n=new Image;n.dbrObjUrl=r,n.src=r,n.onload=()=>{t(n)},n.onerror=e=>{i(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let n=await this._decode_Image(i||r,t);return i&&i.close(),n}async _decode_ArrayBuffer(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Uint8Array(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Image(e,t){D._onLog&&D._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),t=t||{};let i,r,n=e instanceof HTMLImageElement?e.naturalWidth:e.width,s=e instanceof HTMLImageElement?e.naturalHeight:e.height,o=Math.max(n,s);if(o>this._maxCvsSideLength){let e=this._maxCvsSideLength/o;i=Math.round(n*e),r=Math.round(s*e)}else i=n,r=s;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d"));return a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._decode_Canvas(a,t)}async _decode_Canvas(e,t){if(D._onLog&&D._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";if(0===e.width||0===e.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=e,this.oriCanvasData=null);let i=(e.ctx2d||e.getContext("2d")).getImageData(0,0,e.width,e.height).data;return await this._decodeBuffer_Uint8Array(i,e.width,e.height,4*e.width,_.IPF_ABGR_8888,t)}async _decode_Video(e,t){if(D._onLog&&D._onLog("_decode_Video(video)"),!(e instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";t=t||{};let i,r,n=e.videoWidth,s=e.videoHeight,o=Math.max(n,s);if(o>this._maxCvsSideLength){let e=this._maxCvsSideLength/o;i=Math.round(n*e),r=Math.round(s*e)}else i=n,r=s;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d"));return a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r),await this._decode_Canvas(a,t)}async _decode_DCEFrame(e,t){if(D._onLog&&D._onLog("_decode_DCEFrame(dceFrame)"),!D.isDCEFrame(e))return[];let i=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,colorMode:e.colorMode,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{width:r,height:n,colorMode:s,timeStamp:o}=e;let a;a=t&&t.bCopyData?new Uint8Array(e.data):e.data;let l=null;if(t?(l=JSON.parse(JSON.stringify(t)),l.timeStamp=o):l={timeStamp:o},"grey"===s)i=await this._decodeBuffer_Uint8Array(a,r,n,r,_.IPF_GrayScaled,l);else if("rgba"===s)i=await this._decodeBuffer_Uint8Array(a,r,n,4*r,_.IPF_ABGR_8888,l);else{if("bgra"!==s)throw new Error(`Color mode '${s}' is not supported to decode.`);i=await this._decodeBuffer_Uint8Array(a,r,n,4*r,_.IPF_ARGB_8888,l)}return i}async _decode_DSImage(e,t){if(D._onLog&&D._onLog("_decode_DSImage(dsImage)"),!D.isDSImage(e))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,pixelFormat:e.pixelFormat.toLowerCase(),data:new Uint8Array(e.data),toCanvas:function(){const e=document.createElement("canvas");let t;switch(e.width=this.width,e.height=this.height,this.pixelFormat){case"grey":t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{let r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="blob",r.send(),r.onloadend=async()=>{t(r.response)},r.onerror=()=>{i(new Error("Network Error: "+r.statusText))}}));return await this._decode_Blob(i,t)}}async _decode_FilePath(e,t){throw D._onLog&&D._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static recalculateResultLocation(e,t,i,r,n,s,o){if(e.length>0)for(let a of e){let e=a.localizationResult;2==e.resultCoordinateType&&(e.x1*=.01*s,e.x2*=.01*s,e.x3*=.01*s,e.x4*=.01*s,e.y1*=.01*o,e.y2*=.01*o,e.y3*=.01*o,e.y4*=.01*o);let l=s/r,h=o/n;e.x1=e.x1/l+t,e.x2=e.x2/l+t,e.x3=e.x3/l+t,e.x4=e.x4/l+t,e.y1=e.y1/h+i,e.y2=e.y2/h+i,e.y3=e.y3/h+i,e.y4=e.y4/h+i,2==e.resultCoordinateType&&(e.x1*=100/r,e.x2*=100/r,e.x3*=100/r,e.x4*=100/r,e.y1*=100/n,e.y2*=100/n,e.y3*=100/n,e.y4*=100/n)}}static BarcodeReaderException(e,t){let i,r=p.DBR_UNKNOWN;return"number"==typeof e?(r=e,i=new Error(t)):i=new Error(e),i.code=r,i}_handleRetJsonString(e){let t=p;if(e.textResults){for(let t=0;t{let i=t.indexOf(":");e[t.substring(0,i)]=t.substring(i+1)})),i.exception=e}}return e.decodeRecords?this.decodeRecords=e.decodeRecords:this.decodeRecords={},this._lastErrorCode=e.exception,this._lastErrorString=e.description,e.exception&&!D._setWarnnedEx.has(e.description)&&(D._setWarnnedEx.add(e.description),console.warn(e.description)),e.textResults}if(e.exception==t.DBR_SUCCESS)return e.data;throw D.BarcodeReaderException(e.exception,e.description)}async setModeArgument(e,t,i,r){return await new Promise(((n,s)=>{let o=D._nextTaskID++;D._taskCallbackMap.set(o,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return s(e)}return n()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,s(t)}})),D._dbrWorker.postMessage({type:"setModeArgument",id:o,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i,argumentValue:r}})}))}async getModeArgument(e,t,i){return await new Promise(((r,n)=>{let s=D._nextTaskID++;D._taskCallbackMap.set(s,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return n(e)}return r(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),D._dbrWorker.postMessage({type:"getModeArgument",id:s,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i}})}))}async getIntermediateResults(){return await new Promise(((e,t)=>{let i=D._nextTaskID++;D._taskCallbackMap.set(i,(i=>{if(i.success)return e(i.results);{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),D._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let e=await this.getIntermediateResults(),t=[];for(let i of e)if(i.dataType==m.IMRDT_IMAGE)for(let e of i.results){const i=e.bytes;let r;switch(D._onLog&&D._onLog(" "+i.length+" "+i.byteLength+" "+e.width+" "+e.height+" "+e.stride+" "+e.format),e.format){case _.IPF_ABGR_8888:r=new Uint8ClampedArray(i);break;case _.IPF_RGB_888:{const e=i.length/3;r=new Uint8ClampedArray(4*e);for(let t=0;t{let i=D._nextTaskID++;D._taskCallbackMap.set(i,(i=>{if(i.success){let t=i.results;return t.intervalTime=this.intervalTime,t.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,t.soundOnSuccessfullRead=this.soundSource,t.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,t.vibrateDuration=this.vibrateDuration,t.captureAndDecodeInParallel=this.captureAndDecodeInParallel,e(t)}{let e=new Error(i.message);return e.stack+="\n"+i.stack,t(e)}})),D._dbrWorker.postMessage({type:"getScanSettings",id:i,instanceID:this._instanceID})}))}async updateScanSettings(e){if(!e)return;const t=JSON.parse(JSON.stringify(e));return t.hasOwnProperty("intervalTime")&&(this.intervalTime=Math.max(t.intervalTime,0),delete t.intervalTime),t.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=t.whenToPlaySoundforSuccessfulRead,delete t.whenToPlaySoundforSuccessfulRead),t.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=t.soundOnSuccessfullRead,delete t.soundOnSuccessfullRead),t.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=t.whenToVibrateforSuccessfulRead,delete t.whenToVibrateforSuccessfulRead),t.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=t.vibrateDuration,delete t.vibrateDuration),t.hasOwnProperty("captureAndDecodeInParallel")&&(this.captureAndDecodeInParallel=t.captureAndDecodeInParallel,delete t.captureAndDecodeInParallel),await new Promise(((e,i)=>{let r=D._nextTaskID++;D._taskCallbackMap.set(r,(t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack+="\n"+t.stack,i(e)}})),D._dbrWorker.postMessage({type:"updateScanSettings",id:r,instanceID:this._instanceID,body:{settings:t}})}))}_cloneDecodeResults(e){if(e instanceof Array){let t=[];for(let i of e)t.push(this._cloneDecodeResults(i));return t}{let t=e,i=JSON.parse(JSON.stringify(t,((e,t)=>"oriVideoCanvas"==e||"searchRegionCanvas"==e?void 0:t)));return i}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this._imgSource||this._bPauseScan)return D._onLog&&D._onLog("Scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));D._onLog&&D._onLog("======= once read ======="),D._onLog&&(this._timeStartDecode=Date.now());let e=null,t=null;if(this.dce)e=this._getVideoFrame();else if(this._imgSource&&(t=await this._imgSource.getImage(),!D.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let i=[];if(e){i=await this._decode_DCEFrame(e,{bScanner:!0,bCopyData:!1});let t=null;if(i&&i.length){const{sx:r,sy:n,width:s,height:o,_sWidth:a,_sHeight:l}=e;t=i.map((e=>({localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),D.recalculateResultLocation(t,r,n,a,l,s,o)}this._drawResults(t)}else t&&(i=await this._decode_DSImage(t,{bScanner:!0,bCopyData:!1}));return i})().then((e=>{if(D._onLog&&D._onLog(e),this.dce&&this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost;const i=()=>{let i=0;if(t&&t.length){let r=Math.min(...e),n=Math.max(...t);r&&n&&(i=r-n)}else i=0;return i>0?i:0};(()=>{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=i()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this._imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead)t=!0;else if("unique"===this.bPlaySoundOnSuccessfulRead)for(let i of e)if(0==i.resultsType){t=!0;break}t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead)t=!0;else if("unique"===this.bVibrateOnSuccessfulRead)for(let i of e)if(0==i.resultsType){t=!0;break}if(t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onImageRead){let t=this._cloneDecodeResults(e);for(let e of t)0!=e.resultsType&&1!=e.resultsType||this.onImageRead(t);this.onImageRead(t)}if(this.onUniqueRead)for(let t of e)0==t.resultsType&&this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t))}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),D._onLog&&D._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){if(this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",this._intervalGetVideoFrame),!this.dce.numberOfFramesInBuffer)return this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",0),null;e=this.dce.getFrameFromBuffer();const t=e=>{if(!e)return;let t=e.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(t)};t(e)}else this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),e=this.dce.getFrame();return e}_drawResults(e){if(!this.dce||this._bPauseScan||!this._drawingItemNamespace||!this._drawingItemNamespace.DT_Polygon)return;if(!this._dbrDrawingLayer){if(!this.dce.isOpen())return;this._dbrDrawingLayer=this.dce.getDrawingLayer(3)}const t=this._dbrDrawingLayer;if(t.clearDrawingItems(),e&&e.length)for(let i of e){const e=i.localizationResult,r=new this._drawingItemNamespace.DT_Polygon([{x:e.x1,y:e.y1},{x:e.x2,y:e.y2},{x:e.x3,y:e.y3},{x:e.x4,y:e.y4}]);t.addDrawingItem(r)}}async startScanning(e){if(!this.dce&&!this._imgSource)throw new Error("'imageSource' is not set. call 'setImageSource()' before 'startScanning()'.");if("closed"!=this._tempSolutionStatus)return;if(this._tempSolutionStatus="opening","opening"!=this._tempSolutionStatus)return;let t=null;return this.dce&&(this.dce.isOpen()?(e&&this.dce.appendAndShowUI(),t=JSON.parse(JSON.stringify(this.dce.playCallbackInfo))):t=await this.dce.open(e),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"close"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())),"opening"==this._tempSolutionStatus?(this._bPauseScan=!1,this.dce&&this.dce.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),0)),this._tempSolutionStatus="opened",this.keepAlive(),t):void 0}stopScanning(e){this.dce&&(this._drawResults(null),this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"close",e))),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._tempSolutionStatus="closed"}pauseScanning(e){if(e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"stopFetchingLoop"))}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.startFetchingLoop(),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(D._onLog&&D._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,(this.dce||"opening"===this._tempSolutionStatus)&&this.stopScanning(),this.setImageSource(null);let e=D._nextTaskID++;D._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),D._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}D._jsVersion="9.2.11",D._jsEditVersion="20220727",D._version=`loading...(JS ${D._jsVersion}.${D._jsEditVersion})`,D._license=d,D._sessionPassword=f,D.browserInfo=s,D._workerName=`dbr-${D._jsVersion}.browser.worker.js`,D._engineResourcePath=c,D._licenseServer=[],D._deviceFriendlyName="",D._isShowRelDecodeTimeInResults=!1,D._bWasmDebug=!1,D._bNeverShowDialog=!1,D.__bUseFullFeature=!0,D._nextTaskID=0,D._taskCallbackMap=new Map,D._pLoad=new class extends Promise{constructor(e){let t,i;super(((e,r)=>{t=e,i=r})),this._s="pending",this.resolve=e=>{this.isPending&&(y(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",i(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,y(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const i=await t;e===this._task&&this.resolve(i)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}},D._lastErrorCode=0,D._lastErrorString="",D._setWarnnedEx=new Set,D._defaultUIElementURL="@engineResourcePath/dbr.ui.html";var M={653:(e,t,i)=>{var r,n,s,o,a,l,h,c,u,d,f,g,_,p,m,v,y,S,b,C,w,T=T||{version:"5.2.1"};if(t.fabric=T,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?T.document=document:T.document=document.implementation.createHTMLDocument(""),T.window=window;else{var x=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;T.document=x.document,T.jsdomImplForWrapper=i(898).implForWrapper,T.nodeCanvas=i(245).Canvas,T.window=x,DOMParser=T.window.DOMParser}function A(e,t){var i=e.canvas,r=t.targetCanvas,n=r.getContext("2d");n.translate(0,r.height),n.scale(1,-1);var s=i.height-r.height;n.drawImage(i,0,s,r.width,r.height,0,0,r.width,r.height)}function O(e,t){var i=t.targetCanvas.getContext("2d"),r=t.destinationWidth,n=t.destinationHeight,s=r*n*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,o);var l=new ImageData(a,r,n);i.putImageData(l,0,0)}T.isTouchSupported="ontouchstart"in T.window||"ontouchstart"in T.document||T.window&&T.window.navigator&&T.window.navigator.maxTouchPoints>0,T.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,T.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],T.DPI=96,T.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",T.commaWsp="(?:\\s+,?\\s*|,\\s*)",T.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,T.reNonWord=/[ \n\.,;!\?\-]/,T.fontPaths={},T.iMatrix=[1,0,0,1,0,0],T.svgNS="http://www.w3.org/2000/svg",T.perfLimitSizeTotal=2097152,T.maxCacheSideLimit=4096,T.minCacheSideLimit=256,T.charWidthsCache={},T.textureSize=2048,T.disableStyleCopyPaste=!1,T.enableGLFiltering=!0,T.devicePixelRatio=T.window.devicePixelRatio||T.window.webkitDevicePixelRatio||T.window.mozDevicePixelRatio||1,T.browserShadowBlurConstant=1,T.arcToSegmentsCache={},T.boundsOfCurveCache={},T.cachesBoundsOfCurve=!0,T.forceGLPutImageData=!1,T.initFilterBackend=function(){return T.enableGLFiltering&&T.isWebglSupported&&T.isWebglSupported(T.textureSize)?(console.log("max texture size: "+T.maxTextureSize),new T.WebglFilterBackend({tileSize:T.textureSize})):T.Canvas2dFilterBackend?new T.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=T),function(){function e(e,t){if(this.__eventListeners[e]){var i=this.__eventListeners[e];t?i[i.indexOf(t)]=!1:T.util.array.fill(i,!1)}}function t(e,t){var i=function(){t.apply(this,arguments),this.off(e,i)}.bind(this);this.on(e,i)}T.Observable={fire:function(e,t){if(!this.__eventListeners)return this;var i=this.__eventListeners[e];if(!i)return this;for(var r=0,n=i.length;r-1||!!t&&this._objects.some((function(t){return"function"==typeof t.contains&&t.contains(e,!0)}))},complexity:function(){return this._objects.reduce((function(e,t){return e+(t.complexity?t.complexity():0)}),0)}},T.CommonMethods={_setOptions:function(e){for(var t in e)this.set(t,e[t])},_initGradient:function(e,t){!e||!e.colorStops||e instanceof T.Gradient||this.set(t,new T.Gradient(e))},_initPattern:function(e,t,i){!e||!e.source||e instanceof T.Pattern?i&&i():this.set(t,new T.Pattern(e,i))},_setObject:function(e){for(var t in e)this._set(t,e[t])},set:function(e,t){return"object"==typeof e?this._setObject(e):this._set(e,t),this},_set:function(e,t){this[e]=t},toggle:function(e){var t=this.get(e);return"boolean"==typeof t&&this.set(e,!t),this},get:function(e){return this[e]}},r=t,n=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,l=Math.PI/2,T.util={cos:function(e){if(0===e)return 1;switch(e<0&&(e=-e),e/l){case 1:case 3:return 0;case 2:return-1}return Math.cos(e)},sin:function(e){if(0===e)return 0;var t=1;switch(e<0&&(t=-1),e/l){case 1:return t;case 2:return 0;case 3:return-t}return Math.sin(e)},removeFromArray:function(e,t){var i=e.indexOf(t);return-1!==i&&e.splice(i,1),e},getRandomInt:function(e,t){return Math.floor(Math.random()*(t-e+1))+e},degreesToRadians:function(e){return e*a},radiansToDegrees:function(e){return e/a},rotatePoint:function(e,t,i){var r=new T.Point(e.x-t.x,e.y-t.y),n=T.util.rotateVector(r,i);return new T.Point(n.x,n.y).addEquals(t)},rotateVector:function(e,t){var i=T.util.sin(t),r=T.util.cos(t);return{x:e.x*r-e.y*i,y:e.x*i+e.y*r}},createVector:function(e,t){return new T.Point(t.x-e.x,t.y-e.y)},calcAngleBetweenVectors:function(e,t){return Math.acos((e.x*t.x+e.y*t.y)/(Math.hypot(e.x,e.y)*Math.hypot(t.x,t.y)))},getHatVector:function(e){return new T.Point(e.x,e.y).multiply(1/Math.hypot(e.x,e.y))},getBisector:function(e,t,i){var r=T.util.createVector(e,t),n=T.util.createVector(e,i),s=T.util.calcAngleBetweenVectors(r,n),o=s*(0===T.util.calcAngleBetweenVectors(T.util.rotateVector(r,s),n)?1:-1)/2;return{vector:T.util.getHatVector(T.util.rotateVector(r,o)),angle:s}},projectStrokeOnPoints:function(e,t,i){var r=[],n=t.strokeWidth/2,s=t.strokeUniform?new T.Point(1/t.scaleX,1/t.scaleY):new T.Point(1,1),o=function(e){var t=n/Math.hypot(e.x,e.y);return new T.Point(e.x*t*s.x,e.y*t*s.y)};return e.length<=1||e.forEach((function(a,l){var h,c,u=new T.Point(a.x,a.y);0===l?(c=e[l+1],h=i?o(T.util.createVector(c,u)).addEquals(u):e[e.length-1]):l===e.length-1?(h=e[l-1],c=i?o(T.util.createVector(h,u)).addEquals(u):e[0]):(h=e[l-1],c=e[l+1]);var d,f,g=T.util.getBisector(u,h,c),_=g.vector,p=g.angle;if("miter"===t.strokeLineJoin&&(d=-n/Math.sin(p/2),f=new T.Point(_.x*d*s.x,_.y*d*s.y),Math.hypot(f.x,f.y)/n<=t.strokeMiterLimit))return r.push(u.add(f)),void r.push(u.subtract(f));d=-n*Math.SQRT2,f=new T.Point(_.x*d*s.x,_.y*d*s.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(e,t,i){return i?new T.Point(t[0]*e.x+t[2]*e.y,t[1]*e.x+t[3]*e.y):new T.Point(t[0]*e.x+t[2]*e.y+t[4],t[1]*e.x+t[3]*e.y+t[5])},makeBoundingBoxFromPoints:function(e,t){if(t)for(var i=0;i0&&(t>r?t-=r:t=0,i>r?i-=r:i=0);var n,s=!0,o=e.getImageData(t,i,2*r||1,2*r||1),a=o.data.length;for(n=3;n=n?s-n:2*Math.PI-(n-s)}function s(e,t,i){for(var s=i[1],o=i[2],a=i[3],l=i[4],h=i[5],c=function(e,t,i,s,o,a,l){var h=Math.PI,c=l*h/180,u=T.util.sin(c),d=T.util.cos(c),f=0,g=0,_=-d*e*.5-u*t*.5,p=-d*t*.5+u*e*.5,m=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,S=_*_,b=m*v-m*y-v*S,C=0;if(b<0){var w=Math.sqrt(1-b/(m*v));i*=w,s*=w}else C=(o===a?-1:1)*Math.sqrt(b/(m*y+v*S));var x=C*i*p/s,A=-C*s*_/i,O=d*x-u*A+.5*e,I=u*x+d*A+.5*t,E=n(1,0,(_-x)/i,(p-A)/s),R=n((_-x)/i,(p-A)/s,(-_-x)/i,(-p-A)/s);0===a&&R>0?R-=2*h:1===a&&R<0&&(R+=2*h);for(var D=Math.ceil(Math.abs(R/h*2)),M=[],L=R/D,P=8/3*Math.sin(L/4)*Math.sin(L/4)/Math.sin(L/2),F=E+L,k=0;kC)for(var x=1,A=_.length;x2;for(t=t||0,h&&(a=e[2].xe[i-2].x?1:n.x===e[i-2].x?0:-1,l=n.y>e[i-2].y?1:n.y===e[i-2].y?0:-1),r.push(["L",n.x+a*t,n.y+l*t]),r},T.util.getPathSegmentsInfo=d,T.util.getBoundsOfCurve=function(t,i,r,n,s,o,a,l){var h;if(T.cachesBoundsOfCurve&&(h=e.call(arguments),T.boundsOfCurveCache[h]))return T.boundsOfCurveCache[h];var c,u,d,f,g,_,p,m,v=Math.sqrt,y=Math.min,S=Math.max,b=Math.abs,C=[],w=[[],[]];u=6*t-12*r+6*s,c=-3*t+9*r-9*s+3*a,d=3*r-3*t;for(var x=0;x<2;++x)if(x>0&&(u=6*i-12*n+6*o,c=-3*i+9*n-9*o+3*l,d=3*n-3*i),b(c)<1e-12){if(b(u)<1e-12)continue;0<(f=-d/u)&&f<1&&C.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(m=v(p)))/(2*c))&&g<1&&C.push(g),0<(_=(-u-m)/(2*c))&&_<1&&C.push(_));for(var A,O,I,E=C.length,R=E;E--;)A=(I=1-(f=C[E]))*I*I*t+3*I*I*f*r+3*I*f*f*s+f*f*f*a,w[0][E]=A,O=I*I*I*i+3*I*I*f*n+3*I*f*f*o+f*f*f*l,w[1][E]=O;w[0][R]=t,w[1][R]=i,w[0][R+1]=a,w[1][R+1]=l;var D=[{x:y.apply(null,w[0]),y:y.apply(null,w[1])},{x:S.apply(null,w[0]),y:S.apply(null,w[1])}];return T.cachesBoundsOfCurve&&(T.boundsOfCurveCache[h]=D),D},T.util.getPointOnPath=function(e,t,i){i||(i=d(e));for(var r=0;t-i[r].length>0&&r1e-4;)i=l(s),n=s,(r=o(h.x,h.y,i.x,i.y))+a>t?(s-=c,c/=2):(h=i,s+=c,a+=r);return i.angle=u(n),i}(s,t)}},T.util.transformPath=function(e,t,i){return i&&(t=T.util.multiplyTransformMatrices(t,[1,0,0,1,-i.x,-i.y])),e.map((function(e){for(var i=e.slice(0),r={},n=1;n=t}))}}}(),function(){function e(t,i,r){if(r)if(!T.isLikelyNode&&i instanceof Element)t=i;else if(i instanceof Array){t=[];for(var n=0,s=i.length;n57343)return e.charAt(t);if(55296<=i&&i<=56319){if(e.length<=t+1)throw"High surrogate without following low surrogate";var r=e.charCodeAt(t+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return e.charAt(t)+e.charAt(t+1)}if(0===t)throw"Low surrogate without preceding high surrogate";var n=e.charCodeAt(t-1);if(55296>n||n>56319)throw"Low surrogate without preceding high surrogate";return!1}T.util.string={camelize:function(e){return e.replace(/-+(.)?/g,(function(e,t){return t?t.toUpperCase():""}))},capitalize:function(e,t){return e.charAt(0).toUpperCase()+(t?e.slice(1):e.slice(1).toLowerCase())},escapeXml:function(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(t){var i,r=0,n=[];for(r=0;r-1?e.prototype[n]=function(e){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var n=t[e].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==e)return n}}(n):e.prototype[n]=t[n],i&&(t.toString!==Object.prototype.toString&&(e.prototype.toString=t.toString),t.valueOf!==Object.prototype.valueOf&&(e.prototype.valueOf=t.valueOf))};function n(){}function s(t){for(var i=null,r=this;r.constructor.superclass;){var n=r.constructor.superclass.prototype[t];if(r[t]!==n){i=n;break}r=r.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,e.call(arguments,1)):i.call(this):console.log("tried to callSuper "+t+", method not found in prototype chain",this)}T.util.createClass=function(){var i=null,o=e.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(n.prototype=i.prototype,a.prototype=new n,i.subclasses.push(a));for(var l=0,h=o.length;l-1||"touch"===e.pointerType},d="string"==typeof(u=T.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,_=function(e){return e},d?_=function(e,t){return e.style.opacity=t,e}:f&&(_=function(e,t){var i=e.style;return e.currentStyle&&!e.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(t=t>=.9999?"":"alpha(opacity="+100*t+")",i.filter=i.filter.replace(g,t)):i.filter+=" alpha(opacity="+100*t+")",e}),T.util.setStyle=function(e,t){var i=e.style;if(!i)return e;if("string"==typeof t)return e.style.cssText+=";"+t,t.indexOf("opacity")>-1?_(e,t.match(/opacity:\s*(\d?\.?\d*)/)[1]):e;for(var r in t)"opacity"===r?_(e,t[r]):i["float"===r||"cssFloat"===r?void 0===i.styleFloat?"cssFloat":"styleFloat":r]=t[r];return e},function(){var e,t,i,r,n=Array.prototype.slice,s=function(e){return n.call(e,0)};try{e=s(T.document.childNodes)instanceof Array}catch(e){}function o(e,t){var i=T.document.createElement(e);for(var r in t)"class"===r?i.className=t[r]:"for"===r?i.htmlFor=t[r]:i.setAttribute(r,t[r]);return i}function a(e){for(var t=0,i=0,r=T.document.documentElement,n=T.document.body||{scrollLeft:0,scrollTop:0};e&&(e.parentNode||e.host)&&((e=e.parentNode||e.host)===T.document?(t=n.scrollLeft||r.scrollLeft||0,i=n.scrollTop||r.scrollTop||0):(t+=e.scrollLeft||0,i+=e.scrollTop||0),1!==e.nodeType||"fixed"!==e.style.position););return{left:t,top:i}}e||(s=function(e){for(var t=new Array(e.length),i=e.length;i--;)t[i]=e[i];return t}),t=T.document.defaultView&&T.document.defaultView.getComputedStyle?function(e,t){var i=T.document.defaultView.getComputedStyle(e,null);return i?i[t]:void 0}:function(e,t){var i=e.style[t];return!i&&e.currentStyle&&(i=e.currentStyle[t]),i},i=T.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",T.util.makeElementUnselectable=function(e){return void 0!==e.onselectstart&&(e.onselectstart=T.util.falseFunction),r?e.style[r]="none":"string"==typeof e.unselectable&&(e.unselectable="on"),e},T.util.makeElementSelectable=function(e){return void 0!==e.onselectstart&&(e.onselectstart=null),r?e.style[r]="":"string"==typeof e.unselectable&&(e.unselectable=""),e},T.util.setImageSmoothing=function(e,t){e.imageSmoothingEnabled=e.imageSmoothingEnabled||e.webkitImageSmoothingEnabled||e.mozImageSmoothingEnabled||e.msImageSmoothingEnabled||e.oImageSmoothingEnabled,e.imageSmoothingEnabled=t},T.util.getById=function(e){return"string"==typeof e?T.document.getElementById(e):e},T.util.toArray=s,T.util.addClass=function(e,t){e&&-1===(" "+e.className+" ").indexOf(" "+t+" ")&&(e.className+=(e.className?" ":"")+t)},T.util.makeElement=o,T.util.wrapElement=function(e,t,i){return"string"==typeof t&&(t=o(t,i)),e.parentNode&&e.parentNode.replaceChild(t,e),t.appendChild(e),t},T.util.getScrollLeftTop=a,T.util.getElementOffset=function(e){var i,r,n=e&&e.ownerDocument,s={left:0,top:0},o={left:0,top:0},l={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!n)return o;for(var h in l)o[l[h]]+=parseInt(t(e,h),10)||0;return i=n.documentElement,void 0!==e.getBoundingClientRect&&(s=e.getBoundingClientRect()),r=a(e),{left:s.left+r.left-(i.clientLeft||0)+o.left,top:s.top+r.top-(i.clientTop||0)+o.top}},T.util.getNodeCanvas=function(e){var t=T.jsdomImplForWrapper(e);return t._canvas||t._image},T.util.cleanUpJsdomNode=function(e){if(T.isLikelyNode){var t=T.jsdomImplForWrapper(e);t&&(t._image=null,t._canvas=null,t._currentSrc=null,t._attributes=null,t._classList=null)}}}(),function(){function e(){}T.util.request=function(t,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",n=i.onComplete||function(){},s=new T.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(n(s),s.onreadystatechange=e)},"GET"===r&&(o=null,"string"==typeof i.parameters&&(t=function(e,t){return e+(/\?/.test(e)?"&":"?")+t}(t,i.parameters))),s.open(r,t,!0),"POST"!==r&&"PUT"!==r||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),T.log=console.log,T.warn=console.warn,function(){var e=T.util.object.extend,t=T.util.object.clone,i=[];function r(){return!1}function n(e,t,i,r){return-i*Math.cos(e/r*(Math.PI/2))+i+t}T.util.object.extend(i,{cancelAll:function(){var e=this.splice(0);return e.forEach((function(e){e.cancel()})),e},cancelByCanvas:function(e){if(!e)return[];var t=this.filter((function(t){return"object"==typeof t.target&&t.target.canvas===e}));return t.forEach((function(e){e.cancel()})),t},cancelByTarget:function(e){var t=this.findAnimationsByTarget(e);return t.forEach((function(e){e.cancel()})),t},findAnimationIndex:function(e){return this.indexOf(this.findAnimation(e))},findAnimation:function(e){return this.find((function(t){return t.cancel===e}))},findAnimationsByTarget:function(e){return e?this.filter((function(t){return t.target===e})):[]}});var s=T.window.requestAnimationFrame||T.window.webkitRequestAnimationFrame||T.window.mozRequestAnimationFrame||T.window.oRequestAnimationFrame||T.window.msRequestAnimationFrame||function(e){return T.window.setTimeout(e,1e3/60)},o=T.window.cancelAnimationFrame||T.window.clearTimeout;function a(){return s.apply(T.window,arguments)}T.util.animate=function(i){i||(i={});var s,o=!1,l=function(){var e=T.runningAnimations.indexOf(s);return e>-1&&T.runningAnimations.splice(e,1)[0]};return s=e(t(i),{cancel:function(){return o=!0,l()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),T.runningAnimations.push(s),a((function(e){var t,h=e||+new Date,c=i.duration||500,u=h+c,d=i.onChange||r,f=i.abort||r,g=i.onComplete||r,_=i.easing||n,p="startValue"in i&&i.startValue.length>0,m="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?m.map((function(e,t){return v[t]-m[t]})):v-m);i.onStart&&i.onStart(),function e(i){var r=(t=i||+new Date)>u?c:t-h,n=r/c,S=p?m.map((function(e,t){return _(r,m[t],y[t],c)})):_(r,m,y,c),b=p?Math.abs((S[0]-m[0])/y[0]):Math.abs((S-m)/y);if(s.currentValue=p?S.slice():S,s.completionRate=b,s.durationRate=n,!o){if(!f(S,b,n))return t>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void l()):(d(S,b,n),void a(e));l()}}(h)})),s.cancel},T.util.requestAnimFrame=a,T.util.cancelAnimFrame=function(){return o.apply(T.window,arguments)},T.runningAnimations=i}(),function(){function e(e,t,i){var r="rgba("+parseInt(e[0]+i*(t[0]-e[0]),10)+","+parseInt(e[1]+i*(t[1]-e[1]),10)+","+parseInt(e[2]+i*(t[2]-e[2]),10);return(r+=","+(e&&t?parseFloat(e[3]+i*(t[3]-e[3])):1))+")"}T.util.animateColor=function(t,i,r,n){var s=new T.Color(t).getSource(),o=new T.Color(i).getSource(),a=n.onComplete,l=n.onChange;return n=n||{},T.util.animate(T.util.object.extend(n,{duration:r||500,startValue:s,endValue:o,byValue:o,easing:function(t,i,r,s){return e(i,r,n.colorEasing?n.colorEasing(t,s):1-Math.cos(t/s*(Math.PI/2)))},onComplete:function(t,i,r){if(a)return a(e(o,o,0),i,r)},onChange:function(t,i,r){if(l){if(Array.isArray(t))return l(e(t,t,0),i,r);l(t,i,r)}}}))}}(),function(){function e(e,t,i,r){return e-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===e||"xlink:href"===e||"font"===e)return i;if("imageSmoothing"===e)return"optimizeQuality"===i;a=l?i.map(s):s(i,n)}}else i="";return!l&&isNaN(a)?i:a}function f(e){return new RegExp("^("+e.join("|")+")\\b","i")}function g(e,t){var i,r,n,s,o=[];for(n=0,s=t.length;n1;)l.shift(),h=t.util.multiplyTransformMatrices(h,l[0]);return h}}();var v=new RegExp("^\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*$");function y(e){if(!t.svgViewBoxElementsRegEx.test(e.nodeName))return{};var i,r,n,o,a,l,h=e.getAttribute("viewBox"),c=1,u=1,d=e.getAttribute("width"),f=e.getAttribute("height"),g=e.getAttribute("x")||0,_=e.getAttribute("y")||0,p=e.getAttribute("preserveAspectRatio")||"",m=!h||!(h=h.match(v)),y=!d||!f||"100%"===d||"100%"===f,S=m&&y,b={},C="",w=0,T=0;if(b.width=0,b.height=0,b.toBeParsed=S,m&&(g||_)&&e.parentNode&&"#document"!==e.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(_)+") ",a=(e.getAttribute("transform")||"")+C,e.setAttribute("transform",a),e.removeAttribute("x"),e.removeAttribute("y")),S)return b;if(m)return b.width=s(d),b.height=s(f),b;if(i=-parseFloat(h[1]),r=-parseFloat(h[2]),n=parseFloat(h[3]),o=parseFloat(h[4]),b.minX=i,b.minY=r,b.viewBoxWidth=n,b.viewBoxHeight=o,y?(b.width=n,b.height=o):(b.width=s(d),b.height=s(f),c=b.width/n,u=b.height/o),"none"!==(p=t.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),w=b.width-n*c,T=b.height-o*c,"Mid"===p.alignX&&(w/=2),"Mid"===p.alignY&&(T/=2),"Min"===p.alignX&&(w=0),"Min"===p.alignY&&(T=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===_)return b;if((g||_)&&"#document"!==e.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(_)+") "),a=C+" matrix("+c+" 0 0 "+u+" "+(i*c+w)+" "+(r*u+T)+") ","svg"===e.nodeName){for(l=e.ownerDocument.createElementNS(t.svgNS,"g");e.firstChild;)l.appendChild(e.firstChild);e.appendChild(l)}else(l=e).removeAttribute("x"),l.removeAttribute("y"),a=l.getAttribute("transform")+a;return l.setAttribute("transform",a),b}function S(e,t){var i="xlink:href",r=m(e,t.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&S(e,r),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(e){r&&!t.hasAttribute(e)&&r.hasAttribute(e)&&t.setAttribute(e,r.getAttribute(e))})),!t.children.length)for(var n=r.cloneNode(!0);n.firstChild;)t.appendChild(n.firstChild);t.removeAttribute(i)}t.parseSVGDocument=function(e,i,n,s){if(e){!function(e){for(var i=g(e,["use","svg:use"]),r=0;i.length&&re.x&&this.y>e.y},gte:function(e){return this.x>=e.x&&this.y>=e.y},lerp:function(e,t){return void 0===t&&(t=.5),t=Math.max(Math.min(1,t),0),new i(this.x+(e.x-this.x)*t,this.y+(e.y-this.y)*t)},distanceFrom:function(e){var t=this.x-e.x,i=this.y-e.y;return Math.sqrt(t*t+i*i)},midPointFrom:function(e){return this.lerp(e)},min:function(e){return new i(Math.min(this.x,e.x),Math.min(this.y,e.y))},max:function(e){return new i(Math.max(this.x,e.x),Math.max(this.y,e.y))},toString:function(){return this.x+","+this.y},setXY:function(e,t){return this.x=e,this.y=t,this},setX:function(e){return this.x=e,this},setY:function(e){return this.y=e,this},setFromPoint:function(e){return this.x=e.x,this.y=e.y,this},swap:function(e){var t=this.x,i=this.y;this.x=e.x,this.y=e.y,e.x=t,e.y=i},clone:function(){return new i(this.x,this.y)}})}(t),function(e){var t=e.fabric||(e.fabric={});function i(e){this.status=e,this.points=[]}t.Intersection?t.warn("fabric.Intersection is already defined"):(t.Intersection=i,t.Intersection.prototype={constructor:i,appendPoint:function(e){return this.points.push(e),this},appendPoints:function(e){return this.points=this.points.concat(e),this}},t.Intersection.intersectLineLine=function(e,r,n,s){var o,a=(s.x-n.x)*(e.y-n.y)-(s.y-n.y)*(e.x-n.x),l=(r.x-e.x)*(e.y-n.y)-(r.y-e.y)*(e.x-n.x),h=(s.y-n.y)*(r.x-e.x)-(s.x-n.x)*(r.y-e.y);if(0!==h){var c=a/h,u=l/h;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new t.Point(e.x+c*(r.x-e.x),e.y+c*(r.y-e.y))):o=new i}else o=new i(0===a||0===l?"Coincident":"Parallel");return o},t.Intersection.intersectLinePolygon=function(e,t,r){var n,s,o,a,l=new i,h=r.length;for(a=0;a0&&(l.status="Intersection"),l},t.Intersection.intersectPolygonPolygon=function(e,t){var r,n=new i,s=e.length;for(r=0;r0&&(n.status="Intersection"),n},t.Intersection.intersectPolygonRectangle=function(e,r,n){var s=r.min(n),o=r.max(n),a=new t.Point(o.x,s.y),l=new t.Point(s.x,o.y),h=i.intersectLinePolygon(s,a,e),c=i.intersectLinePolygon(a,o,e),u=i.intersectLinePolygon(o,l,e),d=i.intersectLinePolygon(l,s,e),f=new i;return f.appendPoints(h.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(t),function(e){var t=e.fabric||(e.fabric={});function i(e){e?this._tryParsingColor(e):this.setSource([0,0,0,1])}function r(e,t,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e}t.Color?t.warn("fabric.Color is already defined."):(t.Color=i,t.Color.prototype={_tryParsingColor:function(e){var t;e in i.colorNameMap&&(e=i.colorNameMap[e]),"transparent"===e&&(t=[255,255,255,0]),t||(t=i.sourceFromHex(e)),t||(t=i.sourceFromRgb(e)),t||(t=i.sourceFromHsl(e)),t||(t=[0,0,0,1]),t&&this.setSource(t)},_rgbToHsl:function(e,i,r){e/=255,i/=255,r/=255;var n,s,o,a=t.util.array.max([e,i,r]),l=t.util.array.min([e,i,r]);if(o=(a+l)/2,a===l)n=s=0;else{var h=a-l;switch(s=o>.5?h/(2-a-l):h/(a+l),a){case e:n=(i-r)/h+(i0)-(e<0)||+e};function f(e,t){var i=e.angle+u(Math.atan2(t.y,t.x))+360;return Math.round(i%360/45)}function g(e,i){var r=i.transform.target,n=r.canvas,s=t.util.object.clone(i);s.target=r,n&&n.fire("object:"+e,s),r.fire(e,i)}function _(e,t){var i=t.canvas,r=e[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function p(e){return e.originX===h&&e.originY===h}function m(e,t,i){var r=e.lockScalingX,n=e.lockScalingY;return!((!r||!n)&&(t||!r&&!n||!i)&&(!r||"x"!==t)&&(!n||"y"!==t))}function v(e,t,i,r){return{e,transform:t,pointer:{x:i,y:r}}}function y(e){return function(t,i,r,n){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),l=e(t,i,r,n);return s.setPositionByOrigin(a,i.originX,i.originY),l}}function S(e,t){return function(i,r,n,s){var o=t(i,r,n,s);return o&&g(e,v(i,r,n,s)),o}}function b(e,i,r,n,s){var o=e.target,a=o.controls[e.corner],l=o.canvas.getZoom(),h=o.padding/l,c=o.toLocalPoint(new t.Point(n,s),i,r);return c.x>=h&&(c.x-=h),c.x<=-h&&(c.x+=h),c.y>=h&&(c.y-=h),c.y<=h&&(c.y+=h),c.x-=a.offsetX,c.y-=a.offsetY,c}function C(e){return e.flipX!==e.flipY}function w(e,t,i,r,n){if(0!==e[t]){var s=n/e._getTransformedDimensions()[r]*e[i];e.set(i,s)}}function T(e,t,i,r){var n,h=t.target,c=h._getTransformedDimensions(0,h.skewY),d=b(t,t.originX,t.originY,i,r),f=Math.abs(2*d.x)-c.x,g=h.skewX;f<2?n=0:(n=u(Math.atan2(f/h.scaleX,c.y/h.scaleY)),t.originX===s&&t.originY===l&&(n=-n),t.originX===a&&t.originY===o&&(n=-n),C(h)&&(n=-n));var _=g!==n;if(_){var p=h._getTransformedDimensions().y;h.set("skewX",n),w(h,"skewY","scaleY","y",p)}return _}function x(e,t,i,r){var n,h=t.target,c=h._getTransformedDimensions(h.skewX,0),d=b(t,t.originX,t.originY,i,r),f=Math.abs(2*d.y)-c.y,g=h.skewY;f<2?n=0:(n=u(Math.atan2(f/h.scaleY,c.x/h.scaleX)),t.originX===s&&t.originY===l&&(n=-n),t.originX===a&&t.originY===o&&(n=-n),C(h)&&(n=-n));var _=g!==n;if(_){var p=h._getTransformedDimensions().x;h.set("skewY",n),w(h,"skewX","scaleX","x",p)}return _}function A(e,t,i,r,n){n=n||{};var s,o,a,l,h,u,f=t.target,g=f.lockScalingX,v=f.lockScalingY,y=n.by,S=_(e,f),C=m(f,y,S),w=t.gestureScale;if(C)return!1;if(w)o=t.scaleX*w,a=t.scaleY*w;else{if(s=b(t,t.originX,t.originY,i,r),h="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,t.signX||(t.signX=h),t.signY||(t.signY=u),f.lockScalingFlip&&(t.signX!==h||t.signY!==u))return!1;if(l=f._getTransformedDimensions(),S&&!y){var T=Math.abs(s.x)+Math.abs(s.y),x=t.original,A=T/(Math.abs(l.x*x.scaleX/f.scaleX)+Math.abs(l.y*x.scaleY/f.scaleY));o=x.scaleX*A,a=x.scaleY*A}else o=Math.abs(s.x*f.scaleX/l.x),a=Math.abs(s.y*f.scaleY/l.y);p(t)&&(o*=2,a*=2),t.signX!==h&&"y"!==y&&(t.originX=c[t.originX],o*=-1,t.signX=h),t.signY!==u&&"x"!==y&&(t.originY=c[t.originY],a*=-1,t.signY=u)}var O=f.scaleX,I=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),O!==f.scaleX||I!==f.scaleY}n.scaleCursorStyleHandler=function(e,t,r){var n=_(e,r),s="";if(0!==t.x&&0===t.y?s="x":0===t.x&&0!==t.y&&(s="y"),m(r,s,n))return"not-allowed";var o=f(r,t);return i[o]+"-resize"},n.skewCursorStyleHandler=function(e,t,i){var n="not-allowed";if(0!==t.x&&i.lockSkewingY)return n;if(0!==t.y&&i.lockSkewingX)return n;var s=f(i,t)%4;return r[s]+"-resize"},n.scaleSkewCursorStyleHandler=function(e,t,i){return e[i.canvas.altActionKey]?n.skewCursorStyleHandler(e,t,i):n.scaleCursorStyleHandler(e,t,i)},n.rotationWithSnapping=S("rotating",y((function(e,t,i,r){var n=t,s=n.target,o=s.translateToOriginPoint(s.getCenterPoint(),n.originX,n.originY);if(s.lockRotation)return!1;var a,l=Math.atan2(n.ey-o.y,n.ex-o.x),h=Math.atan2(r-o.y,i-o.x),c=u(h-l+n.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,_=Math.floor(c/d)*d;Math.abs(c-_)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),C(l)&&(n=n===s?a:s)),t.originX=n,S("skewing",y(T))(e,t,i,r))},n.skewHandlerY=function(e,t,i,r){var n,a=t.target,c=a.skewY,u=t.originX;return!a.lockSkewingY&&(0===c?n=b(t,h,h,i,r).y>0?o:l:(c>0&&(n=u===s?o:l),c<0&&(n=u===s?l:o),C(a)&&(n=n===o?l:o)),t.originY=n,S("skewing",y(x))(e,t,i,r))},n.dragHandler=function(e,t,i,r){var n=t.target,s=i-t.offsetX,o=r-t.offsetY,a=!n.get("lockMovementX")&&n.left!==s,l=!n.get("lockMovementY")&&n.top!==o;return a&&n.set("left",s),l&&n.set("top",o),(a||l)&&g("moving",v(e,t,i,r)),a||l},n.scaleOrSkewActionName=function(e,t,i){var r=e[i.canvas.altActionKey];return 0===t.x?r?"skewX":"scaleY":0===t.y?r?"skewY":"scaleX":void 0},n.rotationStyleHandler=function(e,t,i){return i.lockRotation?"not-allowed":t.cursorStyle},n.fireEvent=g,n.wrapWithFixedAnchor=y,n.wrapWithFireEvent=S,n.getLocalPoint=b,t.controlsUtils=n}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.degreesToRadians,r=t.controlsUtils;r.renderCircleControl=function(e,t,i,r,n){r=r||{};var s,o=this.sizeX||r.cornerSize||n.cornerSize,a=this.sizeY||r.cornerSize||n.cornerSize,l=void 0!==r.transparentCorners?r.transparentCorners:n.transparentCorners,h=l?"stroke":"fill",c=!l&&(r.cornerStrokeColor||n.cornerStrokeColor),u=t,d=i;e.save(),e.fillStyle=r.cornerColor||n.cornerColor,e.strokeStyle=r.cornerStrokeColor||n.cornerStrokeColor,o>a?(s=o,e.scale(1,a/o),d=i*o/a):a>o?(s=a,e.scale(o/a,1),u=t*a/o):s=o,e.lineWidth=1,e.beginPath(),e.arc(u,d,s/2,0,2*Math.PI,!1),e[h](),c&&e.stroke(),e.restore()},r.renderSquareControl=function(e,t,r,n,s){n=n||{};var o=this.sizeX||n.cornerSize||s.cornerSize,a=this.sizeY||n.cornerSize||s.cornerSize,l=void 0!==n.transparentCorners?n.transparentCorners:s.transparentCorners,h=l?"stroke":"fill",c=!l&&(n.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;e.save(),e.fillStyle=n.cornerColor||s.cornerColor,e.strokeStyle=n.cornerStrokeColor||s.cornerStrokeColor,e.lineWidth=1,e.translate(t,r),e.rotate(i(s.angle)),e[h+"Rect"](-u,-d,o,a),c&&e.strokeRect(-u,-d,o,a),e.restore()}}(t),function(e){var t=e.fabric||(e.fabric={});t.Control=function(e){for(var t in e)this[t]=e[t]},t.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(e,t){return t.cursorStyle},getActionName:function(e,t){return t.actionName},getVisibility:function(e,t){var i=e._controlsVisibility;return i&&void 0!==i[t]?i[t]:this.visible},setVisibility:function(e){this.visible=e},positionHandler:function(e,i){return t.util.transformPoint({x:this.x*e.x+this.offsetX,y:this.y*e.y+this.offsetY},i)},calcCornerCoords:function(e,i,r,n,s){var o,a,l,h,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-t.util.degreesToRadians(e),_=Math.PI/2-d-t.util.degreesToRadians(e);o=f*t.util.cos(g),a=f*t.util.sin(g),l=f*t.util.cos(_),h=f*t.util.sin(_)}else f=.7071067812*(c&&u?c:i),g=t.util.degreesToRadians(45-e),o=l=f*t.util.cos(g),a=h=f*t.util.sin(g);return{tl:{x:r-h,y:n-l},tr:{x:r+o,y:n-a},bl:{x:r-o,y:n+a},br:{x:r+h,y:n+l}}},render:function(e,i,r,n,s){"circle"===((n=n||{}).cornerStyle||s.cornerStyle)?t.controlsUtils.renderCircleControl.call(this,e,i,r,n,s):t.controlsUtils.renderSquareControl.call(this,e,i,r,n,s)}}}(t),function(){function e(e,t){var i,r,n,s,o=e.getAttribute("style"),a=e.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var l=o.split(/\s*;\s*/);for(""===l[l.length-1]&&l.pop(),s=l.length;s--;){var h=l[s].split(/\s*:\s*/),c=h[0].trim(),u=h[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(n=u)}}return i||(i=e.getAttribute("stop-color")||"rgb(0,0,0)"),n||(n=e.getAttribute("stop-opacity")),r=(i=new T.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*t,{offset:a,color:i.toRgb(),opacity:n}}var t=T.util.object.clone;T.Gradient=T.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(e){e||(e={}),e.coords||(e.coords={});var t,i=this;Object.keys(e).forEach((function(t){i[t]=e[t]})),this.id?this.id+="_"+T.Object.__uid++:this.id=T.Object.__uid++,t={x1:e.coords.x1||0,y1:e.coords.y1||0,x2:e.coords.x2||0,y2:e.coords.y2||0},"radial"===this.type&&(t.r1=e.coords.r1||0,t.r2=e.coords.r2||0),this.coords=t,this.colorStops=e.colorStops.slice()},addColorStop:function(e){for(var t in e){var i=new T.Color(e[t]);this.colorStops.push({offset:parseFloat(t),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(e){var t={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return T.util.populateWithProperties(this,t,e),t},toSVG:function(e,i){var r,n,s,o,a=t(this.coords,!0),l=(i=i||{},t(this.colorStops,!0)),h=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():T.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(l.sort((function(e,t){return e.offset-t.offset})),"objectBoundingBox"===g?(u/=e.width,d/=e.height):(u+=e.width/2,d+=e.height/2),"path"===e.type&&"percentage"!==this.gradientUnits&&(u-=e.pathOffset.x,d-=e.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+T.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(h)for((l=l.concat()).reverse(),r=0,n=l.length;r0){var p=_/Math.max(a.r1,a.r2);for(r=0,n=l.length;r\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(e){var t,i,r,n=T.util.object.clone(this.coords);if(this.type){for("linear"===this.type?t=e.createLinearGradient(n.x1,n.y1,n.x2,n.y2):"radial"===this.type&&(t=e.createRadialGradient(n.x1,n.y1,n.r1,n.x2,n.y2,n.r2)),i=0,r=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var o,a,l,h,c=t.getElementsByTagName("stop"),u="userSpaceOnUse"===t.getAttribute("gradientUnits")?"pixels":"percentage",d=t.getAttribute("gradientTransform")||"",f=[],g=0,_=0;for("linearGradient"===t.nodeName||"LINEARGRADIENT"===t.nodeName?(o="linear",a=function(e){return{x1:e.getAttribute("x1")||0,y1:e.getAttribute("y1")||0,x2:e.getAttribute("x2")||"100%",y2:e.getAttribute("y2")||0}}(t)):(o="radial",a=function(e){return{x1:e.getAttribute("fx")||e.getAttribute("cx")||"50%",y1:e.getAttribute("fy")||e.getAttribute("cy")||"50%",r1:0,x2:e.getAttribute("cx")||"50%",y2:e.getAttribute("cy")||"50%",r2:e.getAttribute("r")||"50%"}}(t)),l=c.length;l--;)f.push(e(c[l],s));return h=T.parseTransformAttribute(d),function(e,t,i,r){var n,s;Object.keys(t).forEach((function(e){"Infinity"===(n=t[e])?s=1:"-Infinity"===n?s=0:(s=parseFloat(t[e],10),"string"==typeof n&&/^(\d+\.\d+)%|(\d+)%$/.test(n)&&(s*=.01,"pixels"===r&&("x1"!==e&&"x2"!==e&&"r2"!==e||(s*=i.viewBoxWidth||i.width),"y1"!==e&&"y2"!==e||(s*=i.viewBoxHeight||i.height)))),t[e]=s}))}(0,a,n,u),"pixels"===u&&(g=-i.left,_=-i.top),new T.Gradient({id:t.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:h,offsetX:g,offsetY:_})}})}(),m=T.util.toFixed,T.Pattern=T.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(e,t){if(e||(e={}),this.id=T.Object.__uid++,this.setOptions(e),!e.source||e.source&&"string"!=typeof e.source)t&&t(this);else{var i=this;this.source=T.util.createImage(),T.util.loadImage(e.source,(function(e,r){i.source=e,t&&t(i,r)}),null,this.crossOrigin)}},toObject:function(e){var t,i,r=T.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?t=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(t=this.source.toDataURL()),i={type:"pattern",source:t,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:m(this.offsetX,r),offsetY:m(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},T.util.populateWithProperties(this,i,e),i},toSVG:function(e){var t="function"==typeof this.source?this.source():this.source,i=t.width/e.width,r=t.height/e.height,n=this.offsetX/e.width,s=this.offsetY/e.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(r=1,s&&(r+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,n&&(i+=Math.abs(n))),t.src?o=t.src:t.toDataURL&&(o=t.toDataURL()),'\n\n\n'},setOptions:function(e){for(var t in e)this[t]=e[t]},toLive:function(e){var t=this.source;if(!t)return"";if(void 0!==t.src){if(!t.complete)return"";if(0===t.naturalWidth||0===t.naturalHeight)return""}return e.createPattern(t,this.repeat)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.toFixed;t.Shadow?t.warn("fabric.Shadow is already defined."):(t.Shadow=t.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(e){for(var i in"string"==typeof e&&(e=this._parseShadow(e)),e)this[i]=e[i];this.id=t.Object.__uid++},_parseShadow:function(e){var i=e.trim(),r=t.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(t.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(r[1],10)||0,offsetY:parseFloat(r[2],10)||0,blur:parseFloat(r[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(e){var r=40,n=40,s=t.Object.NUM_FRACTION_DIGITS,o=t.util.rotateVector({x:this.offsetX,y:this.offsetY},t.util.degreesToRadians(-e.angle)),a=new t.Color(this.color);return e.width&&e.height&&(r=100*i((Math.abs(o.x)+this.blur)/e.width,s)+20,n=100*i((Math.abs(o.y)+this.blur)/e.height,s)+20),e.flipX&&(o.x*=-1),e.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var e={},i=t.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(t){this[t]!==i[t]&&(e[t]=this[t])}),this),e}}),t.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(t),function(){if(T.StaticCanvas)T.warn("fabric.StaticCanvas is already defined.");else{var e=T.util.object.extend,t=T.util.getElementOffset,i=T.util.removeFromArray,r=T.util.toFixed,n=T.util.transformPoint,s=T.util.invertTransform,o=T.util.getNodeCanvas,a=T.util.createCanvasElement,l=new Error("Could not initialize `canvas` element");T.StaticCanvas=T.util.createClass(T.CommonMethods,{initialize:function(e,t){t||(t={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(e,t)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:T.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(e,t){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(e),this._initOptions(t),this.interactive||this._initRetinaScaling(),t.overlayImage&&this.setOverlayImage(t.overlayImage,i),t.backgroundImage&&this.setBackgroundImage(t.backgroundImage,i),t.backgroundColor&&this.setBackgroundColor(t.backgroundColor,i),t.overlayColor&&this.setOverlayColor(t.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return T.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,T.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var e=T.devicePixelRatio;this.__initRetinaScaling(e,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(e,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(e,t,i){t.setAttribute("width",this.width*e),t.setAttribute("height",this.height*e),i.scale(e,e)},calcOffset:function(){return this._offset=t(this.lowerCanvasEl),this},setOverlayImage:function(e,t,i){return this.__setBgOverlayImage("overlayImage",e,t,i)},setBackgroundImage:function(e,t,i){return this.__setBgOverlayImage("backgroundImage",e,t,i)},setOverlayColor:function(e,t){return this.__setBgOverlayColor("overlayColor",e,t)},setBackgroundColor:function(e,t){return this.__setBgOverlayColor("backgroundColor",e,t)},__setBgOverlayImage:function(e,t,i,r){return"string"==typeof t?T.util.loadImage(t,(function(t,n){if(t){var s=new T.Image(t,r);this[e]=s,s.canvas=this}i&&i(t,n)}),this,r&&r.crossOrigin):(r&&t.setOptions(r),this[e]=t,t&&(t.canvas=this),i&&i(t,!1)),this},__setBgOverlayColor:function(e,t,i){return this[e]=t,this._initGradient(t,e),this._initPattern(t,e,i),this},_createCanvasElement:function(){var e=a();if(!e)throw l;if(e.style||(e.style={}),void 0===e.getContext)throw l;return e},_initOptions:function(e){var t=this.lowerCanvasEl;this._setOptions(e),this.width=this.width||parseInt(t.width,10)||0,this.height=this.height||parseInt(t.height,10)||0,this.lowerCanvasEl.style&&(t.width=this.width,t.height=this.height,t.style.width=this.width+"px",t.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(e){e&&e.getContext?this.lowerCanvasEl=e:this.lowerCanvasEl=T.util.getById(e)||this._createCanvasElement(),T.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(e,t){return this.setDimensions({width:e},t)},setHeight:function(e,t){return this.setDimensions({height:e},t)},setDimensions:function(e,t){var i;for(var r in t=t||{},e)i=e[r],t.cssOnly||(this._setBackstoreDimension(r,e[r]),i+="px",this.hasLostContext=!0),t.backstoreOnly||this._setCssDimension(r,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),t.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(e,t){return this.lowerCanvasEl[e]=t,this.upperCanvasEl&&(this.upperCanvasEl[e]=t),this.cacheCanvasEl&&(this.cacheCanvasEl[e]=t),this[e]=t,this},_setCssDimension:function(e,t){return this.lowerCanvasEl.style[e]=t,this.upperCanvasEl&&(this.upperCanvasEl.style[e]=t),this.wrapperEl&&(this.wrapperEl.style[e]=t),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(e){var t,i,r,n=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=e,i=0,r=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",t),this._setSVGObjects(i,t),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",t),i.push(""),i.join("")},_setSVGPreamble:function(e,t){t.suppressPreamble||e.push('\n','\n')},_setSVGHeader:function(e,t){var i,n=t.width||this.width,s=t.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=T.Object.NUM_FRACTION_DIGITS;t.viewBox?o='viewBox="'+t.viewBox.x+" "+t.viewBox.y+" "+t.viewBox.width+" "+t.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+r(-i[4]/i[0],a)+" "+r(-i[5]/i[3],a)+" "+r(this.width/i[0],a)+" "+r(this.height/i[3],a)+'" '),e.push("\n',"Created with Fabric.js ",T.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(t),"\n")},createSVGClipPathMarkup:function(e){var t=this.clipPath;return t?(t.clipPathId="CLIPPATH_"+T.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(e.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var e=this;return["background","overlay"].map((function(t){var i=e[t+"Color"];if(i&&i.toLive){var r=e[t+"Vpt"],n=e.viewportTransform,s={width:e.width/(r?n[0]:1),height:e.height/(r?n[3]:1)};return i.toSVG(s,{additionalTransform:r?T.util.matrixToSVG(n):""})}})).join("")},createSVGFontFacesMarkup:function(){var e,t,i,r,n,s,o,a,l="",h={},c=T.fontPaths,u=[];for(this._objects.forEach((function e(t){u.push(t),t._objects&&t._objects.forEach(e)})),o=0,a=u.length;o',"\n",l,"","\n"].join("")),l},_setSVGObjects:function(e,t){var i,r,n,s=this._objects;for(r=0,n=s.length;r\n")}else e.push('\n")},sendToBack:function(e){if(!e)return this;var t,r,n,s=this._activeObject;if(e===s&&"activeSelection"===e.type)for(t=(n=s._objects).length;t--;)r=n[t],i(this._objects,r),this._objects.unshift(r);else i(this._objects,e),this._objects.unshift(e);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(e){if(!e)return this;var t,r,n,s=this._activeObject;if(e===s&&"activeSelection"===e.type)for(n=s._objects,t=0;t0+h&&(o=s-1,i(this._objects,n),this._objects.splice(o,0,n)),h++;else 0!==(s=this._objects.indexOf(e))&&(o=this._findNewLowerIndex(e,s,t),i(this._objects,e),this._objects.splice(o,0,e));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(e,t,i){var r,n;if(i){for(r=t,n=t-1;n>=0;--n)if(e.intersectsWithObject(this._objects[n])||e.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(e)){r=n;break}}else r=t-1;return r},bringForward:function(e,t){if(!e)return this;var r,n,s,o,a,l=this._activeObject,h=0;if(e===l&&"activeSelection"===e.type)for(r=(a=l._objects).length;r--;)n=a[r],(s=this._objects.indexOf(n))"}}),e(T.StaticCanvas.prototype,T.Observable),e(T.StaticCanvas.prototype,T.Collection),e(T.StaticCanvas.prototype,T.DataURLExporter),e(T.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(e){var t=a();if(!t||!t.getContext)return null;var i=t.getContext("2d");return i&&"setLineDash"===e?void 0!==i.setLineDash:null}}),T.StaticCanvas.prototype.toJSON=T.StaticCanvas.prototype.toObject,T.isLikelyNode&&(T.StaticCanvas.prototype.createPNGStream=function(){var e=o(this.lowerCanvasEl);return e&&e.createPNGStream()},T.StaticCanvas.prototype.createJPEGStream=function(e){var t=o(this.lowerCanvasEl);return t&&t.createJPEGStream(e)})}}(),T.BaseBrush=T.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(e){e.strokeStyle=this.color,e.lineWidth=this.width,e.lineCap=this.strokeLineCap,e.miterLimit=this.strokeMiterLimit,e.lineJoin=this.strokeLineJoin,e.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(e){var t=this.canvas.viewportTransform;e.save(),e.transform(t[0],t[1],t[2],t[3],t[4],t[5])},_setShadow:function(){if(this.shadow){var e=this.canvas,t=this.shadow,i=e.contextTop,r=e.getZoom();e&&e._isRetinaScaling()&&(r*=T.devicePixelRatio),i.shadowColor=t.color,i.shadowBlur=t.blur*r,i.shadowOffsetX=t.offsetX*r,i.shadowOffsetY=t.offsetY*r}},needsFullRender:function(){return new T.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var e=this.canvas.contextTop;e.shadowColor="",e.shadowBlur=e.shadowOffsetX=e.shadowOffsetY=0},_isOutSideCanvas:function(e){return e.x<0||e.x>this.canvas.getWidth()||e.y<0||e.y>this.canvas.getHeight()}}),T.PencilBrush=T.util.createClass(T.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(e){this.canvas=e,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(e,t,i){var r=t.midPointFrom(i);return e.quadraticCurveTo(t.x,t.y,r.x,r.y),r},onMouseDown:function(e,t){this.canvas._isMainEvent(t.e)&&(this.drawStraightLine=t.e[this.straightLineKey],this._prepareForDrawing(e),this._captureDrawingPath(e),this._render())},onMouseMove:function(e,t){if(this.canvas._isMainEvent(t.e)&&(this.drawStraightLine=t.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(e))&&this._captureDrawingPath(e)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,r=i.length,n=this.canvas.contextTop;this._saveAndTransform(n),this.oldEnd&&(n.beginPath(),n.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(n,i[r-2],i[r-1],!0),n.stroke(),n.restore()}},onMouseUp:function(e){return!this.canvas._isMainEvent(e.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(e){var t=new T.Point(e.x,e.y);this._reset(),this._addPoint(t),this.canvas.contextTop.moveTo(t.x,t.y)},_addPoint:function(e){return!(this._points.length>1&&e.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(e),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(e){var t=new T.Point(e.x,e.y);return this._addPoint(t)},_render:function(e){var t,i,r=this._points[0],n=this._points[1];if(e=e||this.canvas.contextTop,this._saveAndTransform(e),e.beginPath(),2===this._points.length&&r.x===n.x&&r.y===n.y){var s=this.width/1e3;r=new T.Point(r.x,r.y),n=new T.Point(n.x,n.y),r.x-=s,n.x+=s}for(e.moveTo(r.x,r.y),t=1,i=this._points.length;t=n&&(o=e[i],a.push(o));return a.push(e[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var e=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(e))this.canvas.requestRenderAll();else{var t=this.createPath(e);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:t}),this.canvas.add(t),this.canvas.requestRenderAll(),t.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:t})}}}),T.CircleBrush=T.util.createClass(T.BaseBrush,{width:10,initialize:function(e){this.canvas=e,this.points=[]},drawDot:function(e){var t=this.addPoint(e),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,t),i.restore()},dot:function(e,t){e.fillStyle=t.fill,e.beginPath(),e.arc(t.x,t.y,t.radius,0,2*Math.PI,!1),e.closePath(),e.fill()},onMouseDown:function(e){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(e)},_render:function(){var e,t,i=this.canvas.contextTop,r=this.points;for(this._saveAndTransform(i),e=0,t=r.length;e0&&!this.preserveObjectStacking){t=[],i=[];for(var n=0,s=this._objects.length;n1&&(this._activeObject._objects=i),t.push.apply(t,i)}else t=this._objects;return t},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var e=this.contextContainer;return this.renderCanvas(e,this._chooseObjectsToRender()),this},renderTopLayer:function(e){e.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(e),this.contextTopDirty=!0),e.restore()},renderTop:function(){var e=this.contextTop;return this.clearContext(e),this.renderTopLayer(e),this.fire("after:render"),this},_normalizePointer:function(e,t){var i=e.calcTransformMatrix(),r=T.util.invertTransform(i),n=this.restorePointerVpt(t);return T.util.transformPoint(n,r)},isTargetTransparent:function(e,t,i){if(e.shouldCache()&&e._cacheCanvas&&e!==this._activeObject){var r=this._normalizePointer(e,{x:t,y:i}),n=Math.max(e.cacheTranslationX+r.x*e.zoomX,0),s=Math.max(e.cacheTranslationY+r.y*e.zoomY,0);return T.util.isTransparent(e._cacheContext,Math.round(n),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=e.selectionBackgroundColor,l=this.viewportTransform;return e.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(l[0],l[1],l[2],l[3],l[4],l[5]),e.render(o),o.restore(),e.selectionBackgroundColor=a,T.util.isTransparent(o,t,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(e){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(t){return!0===e[t]})):e[this.selectionKey]},_shouldClearSelection:function(e,t){var i=this.getActiveObjects(),r=this._activeObject;return!t||t&&r&&i.length>1&&-1===i.indexOf(t)&&r!==t&&!this._isSelectionKeyPressed(e)||t&&!t.evented||t&&!t.selectable&&r&&r!==t},_shouldCenterTransform:function(e,t,i){var r;if(e)return"scale"===t||"scaleX"===t||"scaleY"===t||"resizing"===t?r=this.centeredScaling||e.centeredScaling:"rotate"===t&&(r=this.centeredRotation||e.centeredRotation),r?!i:i},_getOriginFromCorner:function(e,t){var i={x:e.originX,y:e.originY};return"ml"===t||"tl"===t||"bl"===t?i.x="right":"mr"!==t&&"tr"!==t&&"br"!==t||(i.x="left"),"tl"===t||"mt"===t||"tr"===t?i.y="bottom":"bl"!==t&&"mb"!==t&&"br"!==t||(i.y="top"),i},_getActionFromCorner:function(e,t,i,r){if(!t||!e)return"drag";var n=r.controls[t];return n.getActionName(i,n,r)},_setupCurrentTransform:function(e,i,r){if(i){var n=this.getPointer(e),s=i.__corner,o=i.controls[s],a=r&&s?o.getActionHandler(e,i,o):T.controlsUtils.dragHandler,l=this._getActionFromCorner(r,s,e,i),h=this._getOriginFromCorner(i,s),c=e[this.centeredKey],u={target:i,action:l,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:n.x-i.left,offsetY:n.y-i.top,originX:h.x,originY:h.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:t(i.angle),width:i.width*i.scaleX,shiftKey:e.shiftKey,altKey:c,original:T.util.saveObjectTransform(i)};this._shouldCenterTransform(i,l,c)&&(u.originX="center",u.originY="center"),u.original.originX=h.x,u.original.originY=h.y,this._currentTransform=u,this._beforeTransform(e)}},setCursor:function(e){this.upperCanvasEl.style.cursor=e},_drawSelection:function(e){var t=this._groupSelector,i=new T.Point(t.ex,t.ey),r=T.util.transformPoint(i,this.viewportTransform),n=new T.Point(t.ex+t.left,t.ey+t.top),s=T.util.transformPoint(n,this.viewportTransform),o=Math.min(r.x,s.x),a=Math.min(r.y,s.y),l=Math.max(r.x,s.x),h=Math.max(r.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(e.fillStyle=this.selectionColor,e.fillRect(o,a,l-o,h-a)),this.selectionLineWidth&&this.selectionBorderColor&&(e.lineWidth=this.selectionLineWidth,e.strokeStyle=this.selectionBorderColor,o+=c,a+=c,l-=c,h-=c,T.Object.prototype._setLineDash.call(this,e,this.selectionDashArray),e.strokeRect(o,a,l-o,h-a))},findTarget:function(e,t){if(!this.skipTargetFind){var r,n,s=this.getPointer(e,!0),o=this._activeObject,a=this.getActiveObjects(),l=i(e),h=a.length>1&&!t||1===a.length;if(this.targets=[],h&&o._findTargetCorner(s,l))return o;if(a.length>1&&!t&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;r=o,n=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return e[this.altSelectionKey]&&c&&r&&c!==r&&(c=r,this.targets=n),c}},_checkTarget:function(e,t,i){if(t&&t.visible&&t.evented&&t.containsPoint(e)){if(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing)return!0;if(!this.isTargetTransparent(t,i.x,i.y))return!0}},_searchPossibleTargets:function(e,t){for(var i,r,n=e.length;n--;){var s=e[n],o=s.group?this._normalizePointer(s.group,t):t;if(this._checkTarget(o,s,t)){(i=e[n]).subTargetCheck&&i instanceof T.Group&&(r=this._searchPossibleTargets(i._objects,t))&&this.targets.push(r);break}}return i},restorePointerVpt:function(e){return T.util.transformPoint(e,T.util.invertTransform(this.viewportTransform))},getPointer:function(t,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var r,n=e(t),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,l=o.height||0;a&&l||("top"in o&&"bottom"in o&&(l=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,i||(n=this.restorePointerVpt(n));var h=this.getRetinaScaling();return 1!==h&&(n.x/=h,n.y/=h),r=0===a||0===l?{width:1,height:1}:{width:s.width/a,height:s.height/l},{x:n.x*r.width,y:n.y*r.height}},_createUpperCanvas:function(){var e=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),t=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),T.util.addClass(i,"upper-canvas "+e),this.wrapperEl.appendChild(i),this._copyCanvasStyle(t,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=T.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),T.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),T.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(e){var t=this.width||e.width,i=this.height||e.height;T.util.setStyle(e,{position:"absolute",width:t+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),e.width=t,e.height=i,T.util.makeElementUnselectable(e)},_copyCanvasStyle:function(e,t){t.style.cssText=e.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var e=this._activeObject;return e?"activeSelection"===e.type&&e._objects?e._objects.slice(0):[e]:[]},_onObjectRemoved:function(e){e===this._activeObject&&(this.fire("before:selection:cleared",{target:e}),this._discardActiveObject(),this.fire("selection:cleared",{target:e}),e.fire("deselected")),e===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",e)},_fireSelectionEvents:function(e,t){var i=!1,r=this.getActiveObjects(),n=[],s=[];e.forEach((function(e){-1===r.indexOf(e)&&(i=!0,e.fire("deselected",{e:t,target:e}),s.push(e))})),r.forEach((function(r){-1===e.indexOf(r)&&(i=!0,r.fire("selected",{e:t,target:r}),n.push(r))})),e.length>0&&r.length>0?i&&this.fire("selection:updated",{e:t,selected:n,deselected:s}):r.length>0?this.fire("selection:created",{e:t,selected:n}):e.length>0&&this.fire("selection:cleared",{e:t,deselected:s})},setActiveObject:function(e,t){var i=this.getActiveObjects();return this._setActiveObject(e,t),this._fireSelectionEvents(i,t),this},_setActiveObject:function(e,t){return this._activeObject!==e&&!!this._discardActiveObject(t,e)&&!e.onSelect({e:t})&&(this._activeObject=e,!0)},_discardActiveObject:function(e,t){var i=this._activeObject;if(i){if(i.onDeselect({e,object:t}))return!1;this._activeObject=null}return!0},discardActiveObject:function(e){var t=this.getActiveObjects(),i=this.getActiveObject();return t.length&&this.fire("before:selection:cleared",{target:i,e}),this._discardActiveObject(e),this._fireSelectionEvents(t,e),this},dispose:function(){var e=this.wrapperEl;return this.removeListeners(),e.removeChild(this.upperCanvasEl),e.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(e){T.util.cleanUpJsdomNode(this[e]),this[e]=void 0}.bind(this)),e.parentNode&&e.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,T.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(e){var t=this._activeObject;t&&t._renderControls(e)},_toObject:function(e,t,i){var r=this._realizeGroupTransformOnObject(e),n=this.callSuper("_toObject",e,t,i);return this._unwindGroupTransformOnObject(e,r),n},_realizeGroupTransformOnObject:function(e){if(e.group&&"activeSelection"===e.group.type&&this._activeObject===e.group){var t={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){t[i]=e[i]})),T.util.addTransformToObject(e,this._activeObject.calcOwnMatrix()),t}return null},_unwindGroupTransformOnObject:function(e,t){t&&e.set(t)},_setSVGObject:function(e,t,i){var r=this._realizeGroupTransformOnObject(t);this.callSuper("_setSVGObject",e,t,i),this._unwindGroupTransformOnObject(t,r)},setViewportTransform:function(e){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),T.StaticCanvas.prototype.setViewportTransform.call(this,e)}}),T.StaticCanvas)"prototype"!==r&&(T.Canvas[r]=T.StaticCanvas[r])}(),function(){var e=T.util.addListener,t=T.util.removeListener,i={passive:!1};function r(e,t){return e.button&&e.button===t-1}T.util.object.extend(T.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(e,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(e,t){var r=this.upperCanvasEl,n=this._getEventPrefix();e(T.window,"resize",this._onResize),e(r,n+"down",this._onMouseDown),e(r,n+"move",this._onMouseMove,i),e(r,n+"out",this._onMouseOut),e(r,n+"enter",this._onMouseEnter),e(r,"wheel",this._onMouseWheel),e(r,"contextmenu",this._onContextMenu),e(r,"dblclick",this._onDoubleClick),e(r,"dragover",this._onDragOver),e(r,"dragenter",this._onDragEnter),e(r,"dragleave",this._onDragLeave),e(r,"drop",this._onDrop),this.enablePointerEvents||e(r,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&t in eventjs&&(eventjs[t](r,"gesture",this._onGesture),eventjs[t](r,"drag",this._onDrag),eventjs[t](r,"orientation",this._onOrientationChange),eventjs[t](r,"shake",this._onShake),eventjs[t](r,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(t,"remove");var e=this._getEventPrefix();t(T.document,e+"up",this._onMouseUp),t(T.document,"touchend",this._onTouchEnd,i),t(T.document,e+"move",this._onMouseMove,i),t(T.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(e,t){this.__onTransformGesture&&this.__onTransformGesture(e,t)},_onDrag:function(e,t){this.__onDrag&&this.__onDrag(e,t)},_onMouseWheel:function(e){this.__onMouseWheel(e)},_onMouseOut:function(e){var t=this._hoveredTarget;this.fire("mouse:out",{target:t,e}),this._hoveredTarget=null,t&&t.fire("mouseout",{e});var i=this;this._hoveredTargets.forEach((function(r){i.fire("mouse:out",{target:t,e}),r&&t.fire("mouseout",{e})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(e){e.isEditing&&e.hiddenTextarea.focus()}))},_onMouseEnter:function(e){this._currentTransform||this.findTarget(e)||(this.fire("mouse:over",{target:null,e}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(e,t){this.__onOrientationChange&&this.__onOrientationChange(e,t)},_onShake:function(e,t){this.__onShake&&this.__onShake(e,t)},_onLongPress:function(e,t){this.__onLongPress&&this.__onLongPress(e,t)},_onDragOver:function(e){e.preventDefault();var t=this._simpleEventHandler("dragover",e);this._fireEnterLeaveEvents(t,e)},_onDrop:function(e){return this._simpleEventHandler("drop:before",e),this._simpleEventHandler("drop",e)},_onContextMenu:function(e){return this.stopContextMenu&&(e.stopPropagation(),e.preventDefault()),!1},_onDoubleClick:function(e){this._cacheTransformEventData(e),this._handleEvent(e,"dblclick"),this._resetTransformEventData(e)},getPointerId:function(e){var t=e.changedTouches;return t?t[0]&&t[0].identifier:this.enablePointerEvents?e.pointerId:-1},_isMainEvent:function(e){return!0===e.isPrimary||!1!==e.isPrimary&&("touchend"===e.type&&0===e.touches.length||!e.changedTouches||e.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(r){r.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(r)),this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();e(T.document,"touchend",this._onTouchEnd,i),e(T.document,"touchmove",this._onMouseMove,i),t(n,s+"down",this._onMouseDown)},_onMouseDown:function(r){this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();t(n,s+"move",this._onMouseMove,i),e(T.document,s+"up",this._onMouseUp),e(T.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(r){if(!(r.touches.length>0)){this.__onMouseUp(r),this._resetTransformEventData(),this.mainTouchId=null;var n=this._getEventPrefix();t(T.document,"touchend",this._onTouchEnd,i),t(T.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){e(s.upperCanvasEl,n+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(r){this.__onMouseUp(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(r)&&(t(T.document,s+"up",this._onMouseUp),t(T.document,s+"move",this._onMouseMove,i),e(n,s+"move",this._onMouseMove,i))},_onMouseMove:function(e){!this.allowTouchScrolling&&e.preventDefault&&e.preventDefault(),this.__onMouseMove(e)},_onResize:function(){this.calcOffset()},_shouldRender:function(e){var t=this._activeObject;return!!(!!t!=!!e||t&&e&&t!==e)||(t&&t.isEditing,!1)},__onMouseUp:function(e){var t,i=this._currentTransform,n=this._groupSelector,s=!1,o=!n||0===n.left&&0===n.top;if(this._cacheTransformEventData(e),t=this._target,this._handleEvent(e,"up:before"),r(e,3))this.fireRightClick&&this._handleEvent(e,"up",3,o);else{if(r(e,2))return this.fireMiddleClick&&this._handleEvent(e,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(e);else if(this._isMainEvent(e)){if(i&&(this._finalizeCurrentTransform(e),s=i.actionPerformed),!o){var a=t===this._activeObject;this._maybeGroupObjects(e),s||(s=this._shouldRender(t)||!a&&t===this._activeObject)}var l,h;if(t){if(l=t._findTargetCorner(this.getPointer(e,!0),T.util.isTouchEvent(e)),t.selectable&&t!==this._activeObject&&"up"===t.activeOn)this.setActiveObject(t,e),s=!0;else{var c=t.controls[l],u=c&&c.getMouseUpHandler(e,t,c);u&&u(e,i,(h=this.getPointer(e)).x,h.y)}t.isMoving=!1}if(i&&(i.target!==t||i.corner!==l)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(e,t,c);h=h||this.getPointer(e),f&&f(e,i,h.x,h.y)}this._setCursorFromEvent(e,t),this._handleEvent(e,"up",1,o),this._groupSelector=null,this._currentTransform=null,t&&(t.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(e,t){var i=this.findTarget(t),r=this.targets,n={e:t,target:i,subTargets:r};if(this.fire(e,n),i&&i.fire(e,n),!r)return i;for(var s=0;s1&&(t=new T.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(t,e))},_collectObjects:function(e){for(var t,i=[],r=this._groupSelector.ex,n=this._groupSelector.ey,s=r+this._groupSelector.left,o=n+this._groupSelector.top,a=new T.Point(v(r,s),v(n,o)),l=new T.Point(y(r,s),y(n,o)),h=!this.selectionFullyContained,c=r===s&&n===o,u=this._objects.length;u--&&!((t=this._objects[u])&&t.selectable&&t.visible&&(h&&t.intersectsWithRect(a,l,!0)||t.isContainedWithinRect(a,l,!0)||h&&t.containsPoint(a,null,!0)||h&&t.containsPoint(l,null,!0))&&(i.push(t),c)););return i.length>1&&(i=i.filter((function(t){return!t.onSelect({e})}))),i},_maybeGroupObjects:function(e){this.selection&&this._groupSelector&&this._groupSelectedObjects(e),this.setCursor(this.defaultCursor),this._groupSelector=null}}),T.util.object.extend(T.StaticCanvas.prototype,{toDataURL:function(e){e||(e={});var t=e.format||"png",i=e.quality||1,r=(e.multiplier||1)*(e.enableRetinaScaling?this.getRetinaScaling():1),n=this.toCanvasElement(r,e);return T.util.toDataURL(n,t,i)},toCanvasElement:function(e,t){e=e||1;var i=((t=t||{}).width||this.width)*e,r=(t.height||this.height)*e,n=this.getZoom(),s=this.width,o=this.height,a=n*e,l=this.viewportTransform,h=(l[4]-(t.left||0))*e,c=(l[5]-(t.top||0))*e,u=this.interactive,d=[a,0,0,a,h,c],f=this.enableRetinaScaling,g=T.util.createCanvasElement(),_=this.contextTop;return g.width=i,g.height=r,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=r,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=l,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=_,g}}),T.util.object.extend(T.StaticCanvas.prototype,{loadFromJSON:function(e,t,i){if(e){var r="string"==typeof e?JSON.parse(e):T.util.object.clone(e),n=this,s=r.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete r.clipPath,this._enlivenObjects(r.objects,(function(e){n.clear(),n._setBgOverlay(r,(function(){s?n._enlivenObjects([s],(function(i){n.clipPath=i[0],n.__setupCanvas.call(n,r,e,o,t)})):n.__setupCanvas.call(n,r,e,o,t)}))}),i),this}},__setupCanvas:function(e,t,i,r){var n=this;t.forEach((function(e,t){n.insertAt(e,t)})),this.renderOnAddRemove=i,delete e.objects,delete e.backgroundImage,delete e.overlayImage,delete e.background,delete e.overlay,this._setOptions(e),this.renderAll(),r&&r()},_setBgOverlay:function(e,t){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(e.backgroundImage||e.overlayImage||e.background||e.overlay){var r=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&t&&t()};this.__setBgOverlay("backgroundImage",e.backgroundImage,i,r),this.__setBgOverlay("overlayImage",e.overlayImage,i,r),this.__setBgOverlay("backgroundColor",e.background,i,r),this.__setBgOverlay("overlayColor",e.overlay,i,r)}else t&&t()},__setBgOverlay:function(e,t,i,r){var n=this;if(!t)return i[e]=!0,void(r&&r());"backgroundImage"===e||"overlayImage"===e?T.util.enlivenObjects([t],(function(t){n[e]=t[0],i[e]=!0,r&&r()})):this["set"+T.util.string.capitalize(e,!0)](t,(function(){i[e]=!0,r&&r()}))},_enlivenObjects:function(e,t,i){e&&0!==e.length?T.util.enlivenObjects(e,(function(e){t&&t(e)}),null,i):t&&t([])},_toDataURL:function(e,t){this.clone((function(i){t(i.toDataURL(e))}))},_toDataURLWithMultiplier:function(e,t,i){this.clone((function(r){i(r.toDataURLWithMultiplier(e,t))}))},clone:function(e,t){var i=JSON.stringify(this.toJSON(t));this.cloneWithoutData((function(t){t.loadFromJSON(i,(function(){e&&e(t)}))}))},cloneWithoutData:function(e){var t=T.util.createCanvasElement();t.width=this.width,t.height=this.height;var i=new T.Canvas(t);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),e&&e(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):e&&e(i)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend,r=t.util.object.clone,n=t.util.toFixed,s=t.util.string.capitalize,o=t.util.degreesToRadians,a=!t.isLikelyNode;t.Object||(t.Object=t.util.createClass(t.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(e){e&&this.setOptions(e)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=t.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(e){var i=t.perfLimitSizeTotal,r=e.width,n=e.height,s=t.maxCacheSideLimit,o=t.minCacheSideLimit;if(r<=s&&n<=s&&r*n<=i)return rc&&(e.zoomX/=r/c,e.width=c,e.capped=!0),n>u&&(e.zoomY/=n/u,e.height=u,e.capped=!0),e},_getCacheCanvasDimensions:function(){var e=this.getTotalObjectScaling(),t=this._getTransformedDimensions(0,0),i=t.x*e.scaleX/this.scaleX,r=t.y*e.scaleY/this.scaleY;return{width:i+2,height:r+2,zoomX:e.scaleX,zoomY:e.scaleY,x:i,y:r}},_updateCacheCanvas:function(){var e=this.canvas;if(this.noScaleCache&&e&&e._currentTransform){var i=e._currentTransform.target,r=e._currentTransform.action;if(this===i&&r.slice&&"scale"===r.slice(0,5))return!1}var n,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),l=t.minCacheSideLimit,h=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=h!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,_=f||g,p=0,m=0,v=!1;if(f){var y=this._cacheCanvas.width,S=this._cacheCanvas.height,b=h>y||c>S;v=b||(h<.9*y||c<.9*S)&&y>l&&S>l,b&&!a.capped&&(h>l||c>l)&&(p=.1*h,m=.1*c)}return this instanceof t.Text&&this.path&&(_=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,m+=this.getHeightOfLine(0)*this.zoomY),!!_&&(v?(o.width=Math.ceil(h+p),o.height=Math.ceil(c+m)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),n=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-n)+n,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=h,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(e){this._setOptions(e),this._initGradient(e.fill,"fill"),this._initGradient(e.stroke,"stroke"),this._initPattern(e.fill,"fill"),this._initPattern(e.stroke,"stroke")},transform:function(e){var t=this.group&&!this.group._transformDone||this.group&&this.canvas&&e===this.canvas.contextTop,i=this.calcTransformMatrix(!t);e.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(e){var i=t.Object.NUM_FRACTION_DIGITS,r={type:this.type,version:t.version,originX:this.originX,originY:this.originY,left:n(this.left,i),top:n(this.top,i),width:n(this.width,i),height:n(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:n(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:n(this.strokeMiterLimit,i),scaleX:n(this.scaleX,i),scaleY:n(this.scaleY,i),angle:n(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:n(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:n(this.skewX,i),skewY:n(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(r.clipPath=this.clipPath.toObject(e),r.clipPath.inverted=this.clipPath.inverted,r.clipPath.absolutePositioned=this.clipPath.absolutePositioned),t.util.populateWithProperties(this,r,e),this.includeDefaultValues||(r=this._removeDefaultValues(r)),r},toDatalessObject:function(e){return this.toObject(e)},_removeDefaultValues:function(e){var i=t.util.getKlass(e.type).prototype;return i.stateProperties.forEach((function(t){"left"!==t&&"top"!==t&&(e[t]===i[t]&&delete e[t],Array.isArray(e[t])&&Array.isArray(i[t])&&0===e[t].length&&0===i[t].length&&delete e[t])})),e},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var e=t.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(e.scaleX),scaleY:Math.abs(e.scaleY)}},getTotalObjectScaling:function(){var e=this.getObjectScaling(),t=e.scaleX,i=e.scaleY;if(this.canvas){var r=this.canvas.getZoom(),n=this.canvas.getRetinaScaling();t*=r*n,i*=r*n}return{scaleX:t,scaleY:i}},getObjectOpacity:function(){var e=this.opacity;return this.group&&(e*=this.group.getObjectOpacity()),e},_set:function(e,i){var r="scaleX"===e||"scaleY"===e,n=this[e]!==i,s=!1;return r&&(i=this._constrainScale(i)),"scaleX"===e&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===e&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==e||!i||i instanceof t.Shadow?"dirty"===e&&this.group&&this.group.set("dirty",i):i=new t.Shadow(i),this[e]=i,n&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(e)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(e)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:t.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(e){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(e.save(),this._setupCompositeOperation(e),this.drawSelectionBackground(e),this.transform(e),this._setOpacity(e),this._setShadow(e,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(e)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(e),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),e.restore())},renderCache:function(e){e=e||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,e.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(e,i){if(e.save(),i.inverted?e.globalCompositeOperation="destination-out":e.globalCompositeOperation="destination-in",i.absolutePositioned){var r=t.util.invertTransform(this.calcTransformMatrix());e.transform(r[0],r[1],r[2],r[3],r[4],r[5])}i.transform(e),e.scale(1/i.zoomX,1/i.zoomY),e.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),e.restore()},drawObject:function(e,t){var i=this.fill,r=this.stroke;t?(this.fill="black",this.stroke="",this._setClippingProperties(e)):this._renderBackground(e),this._render(e),this._drawClipPath(e,this.clipPath),this.fill=i,this.stroke=r},_drawClipPath:function(e,t){t&&(t.canvas=this.canvas,t.shouldCache(),t._transformDone=!0,t.renderCache({forClipping:!0}),this.drawClipPathOnCache(e,t))},drawCacheOnCanvas:function(e){e.scale(1/this.zoomX,1/this.zoomY),e.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(e){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!e&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!e){var t=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-t/2,-i/2,t,i)}return!0}return!1},_renderBackground:function(e){if(this.backgroundColor){var t=this._getNonTransformedDimensions();e.fillStyle=this.backgroundColor,e.fillRect(-t.x/2,-t.y/2,t.x,t.y),this._removeShadow(e)}},_setOpacity:function(e){this.group&&!this.group._transformDone?e.globalAlpha=this.getObjectOpacity():e.globalAlpha*=this.opacity},_setStrokeStyles:function(e,t){var i=t.stroke;i&&(e.lineWidth=t.strokeWidth,e.lineCap=t.strokeLineCap,e.lineDashOffset=t.strokeDashOffset,e.lineJoin=t.strokeLineJoin,e.miterLimit=t.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(e,i):(e.strokeStyle=i.toLive(e,this),this._applyPatternGradientTransform(e,i)):e.strokeStyle=t.stroke)},_setFillStyles:function(e,t){var i=t.fill;i&&(i.toLive?(e.fillStyle=i.toLive(e,this),this._applyPatternGradientTransform(e,t.fill)):e.fillStyle=i)},_setClippingProperties:function(e){e.globalAlpha=1,e.strokeStyle="transparent",e.fillStyle="#000000"},_setLineDash:function(e,t){t&&0!==t.length&&(1&t.length&&t.push.apply(t,t),e.setLineDash(t))},_renderControls:function(e,i){var r,n,s,a=this.getViewportTransform(),l=this.calcTransformMatrix();n=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,l=t.util.multiplyTransformMatrices(a,l),r=t.util.qrDecompose(l),e.save(),e.translate(r.translateX,r.translateY),e.lineWidth=1*this.borderScaleFactor,this.group||(e.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(r.angle-=180),e.rotate(o(this.group?r.angle:this.angle)),i.forActiveSelection||this.group?n&&this.drawBordersInGroup(e,r,i):n&&this.drawBorders(e,i),s&&this.drawControls(e,i),e.restore()},_setShadow:function(e){if(this.shadow){var i,r=this.shadow,n=this.canvas,s=n&&n.viewportTransform[0]||1,o=n&&n.viewportTransform[3]||1;i=r.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),n&&n._isRetinaScaling()&&(s*=t.devicePixelRatio,o*=t.devicePixelRatio),e.shadowColor=r.color,e.shadowBlur=r.blur*t.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,e.shadowOffsetX=r.offsetX*s*i.scaleX,e.shadowOffsetY=r.offsetY*o*i.scaleY}},_removeShadow:function(e){this.shadow&&(e.shadowColor="",e.shadowBlur=e.shadowOffsetX=e.shadowOffsetY=0)},_applyPatternGradientTransform:function(e,t){if(!t||!t.toLive)return{offsetX:0,offsetY:0};var i=t.gradientTransform||t.patternTransform,r=-this.width/2+t.offsetX||0,n=-this.height/2+t.offsetY||0;return"percentage"===t.gradientUnits?e.transform(this.width,0,0,this.height,r,n):e.transform(1,0,0,1,r,n),i&&e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:r,offsetY:n}},_renderPaintInOrder:function(e){"stroke"===this.paintFirst?(this._renderStroke(e),this._renderFill(e)):(this._renderFill(e),this._renderStroke(e))},_render:function(){},_renderFill:function(e){this.fill&&(e.save(),this._setFillStyles(e,this),"evenodd"===this.fillRule?e.fill("evenodd"):e.fill(),e.restore())},_renderStroke:function(e){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(e),e.save(),this.strokeUniform&&this.group){var t=this.getObjectScaling();e.scale(1/t.scaleX,1/t.scaleY)}else this.strokeUniform&&e.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(e,this.strokeDashArray),this._setStrokeStyles(e,this),e.stroke(),e.restore()}},_applyPatternForTransformedGradient:function(e,i){var r,n=this._limitCacheSize(this._getCacheCanvasDimensions()),s=t.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=n.x/this.scaleX/o,l=n.y/this.scaleY/o;s.width=a,s.height=l,(r=s.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,l),r.lineTo(0,l),r.closePath(),r.translate(a/2,l/2),r.scale(n.zoomX/this.scaleX/o,n.zoomY/this.scaleY/o),this._applyPatternGradientTransform(r,i),r.fillStyle=i.toLive(e),r.fill(),e.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),e.scale(o*this.scaleX/n.zoomX,o*this.scaleY/n.zoomY),e.strokeStyle=r.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var e=t.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",e.scaleX),this.set("scaleY",e.scaleY),this.angle=e.angle,this.skewX=e.skewX,this.skewY=0}},_removeTransformMatrix:function(e){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=t.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,e&&(this.scaleX*=e.scaleX,this.scaleY*=e.scaleY,this.cropX=e.cropX,this.cropY=e.cropY,i.x+=e.offsetLeft,i.y+=e.offsetTop,this.width=e.width,this.height=e.height),this.setPositionByOrigin(i,"center","center")},clone:function(e,i){var r=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(r,e):t.Object._fromObject("Object",r,e)},cloneAsImage:function(e,i){var r=this.toCanvasElement(i);return e&&e(new t.Image(r)),this},toCanvasElement:function(e){e||(e={});var i=t.util,r=i.saveObjectTransform(this),n=this.group,s=this.shadow,o=Math.abs,a=(e.multiplier||1)*(e.enableRetinaScaling?t.devicePixelRatio:1);delete this.group,e.withoutTransform&&i.resetObjectTransform(this),e.withoutShadow&&(this.shadow=null);var l,h,c,u,d=t.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,_={x:0,y:0};g&&(h=g.blur,l=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),_.x=2*Math.round(o(g.offsetX)+h)*o(l.scaleX),_.y=2*Math.round(o(g.offsetY)+h)*o(l.scaleY)),c=f.width+_.x,u=f.height+_.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new t.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===e.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new t.Point(p.width/2,p.height/2),"center","center");var m=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,e);return this.shadow=s,this.set("canvas",m),n&&(this.group=n),this.set(r).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(e){return e||(e={}),t.util.toDataURL(this.toCanvasElement(e),e.format||"png",e.quality||1)},isType:function(e){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===e},complexity:function(){return 1},toJSON:function(e){return this.toObject(e)},rotate:function(e){var t=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return t&&this._setOriginToCenter(),this.set("angle",e),t&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(e,i){i=i||this.canvas.getPointer(e);var r=new t.Point(i.x,i.y),n=this._getLeftTopCoords();return this.angle&&(r=t.util.rotatePoint(r,n,o(-this.angle))),{x:r.x-n.x,y:r.y-n.y}},_setupCompositeOperation:function(e){this.globalCompositeOperation&&(e.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){t.runningAnimations&&t.runningAnimations.cancelByTarget(this)}}),t.util.createAccessors&&t.util.createAccessors(t.Object),i(t.Object.prototype,t.Observable),t.Object.NUM_FRACTION_DIGITS=2,t.Object.ENLIVEN_PROPS=["clipPath"],t.Object._fromObject=function(e,i,n,s){var o=t[e];i=r(i,!0),t.util.enlivenPatterns([i.fill,i.stroke],(function(e){void 0!==e[0]&&(i.fill=e[0]),void 0!==e[1]&&(i.stroke=e[1]),t.util.enlivenObjectEnlivables(i,i,(function(){var e=s?new o(i[s],i):new o(i);n&&n(e)}))}))},t.Object.__uid=0)}(t),S=T.util.degreesToRadians,b={left:-.5,center:0,right:.5},C={top:-.5,center:0,bottom:.5},T.util.object.extend(T.Object.prototype,{translateToGivenOrigin:function(e,t,i,r,n){var s,o,a,l=e.x,h=e.y;return"string"==typeof t?t=b[t]:t-=.5,"string"==typeof r?r=b[r]:r-=.5,"string"==typeof i?i=C[i]:i-=.5,"string"==typeof n?n=C[n]:n-=.5,o=n-i,((s=r-t)||o)&&(a=this._getTransformedDimensions(),l=e.x+s*a.x,h=e.y+o*a.y),new T.Point(l,h)},translateToCenterPoint:function(e,t,i){var r=this.translateToGivenOrigin(e,t,i,"center","center");return this.angle?T.util.rotatePoint(r,e,S(this.angle)):r},translateToOriginPoint:function(e,t,i){var r=this.translateToGivenOrigin(e,"center","center",t,i);return this.angle?T.util.rotatePoint(r,e,S(this.angle)):r},getCenterPoint:function(){var e=new T.Point(this.left,this.top);return this.translateToCenterPoint(e,this.originX,this.originY)},getPointByOrigin:function(e,t){var i=this.getCenterPoint();return this.translateToOriginPoint(i,e,t)},toLocalPoint:function(e,t,i){var r,n,s=this.getCenterPoint();return r=void 0!==t&&void 0!==i?this.translateToGivenOrigin(s,"center","center",t,i):new T.Point(this.left,this.top),n=new T.Point(e.x,e.y),this.angle&&(n=T.util.rotatePoint(n,s,-S(this.angle))),n.subtractEquals(r)},setPositionByOrigin:function(e,t,i){var r=this.translateToCenterPoint(e,t,i),n=this.translateToOriginPoint(r,this.originX,this.originY);this.set("left",n.x),this.set("top",n.y)},adjustPosition:function(e){var t,i,r=S(this.angle),n=this.getScaledWidth(),s=T.util.cos(r)*n,o=T.util.sin(r)*n;t="string"==typeof this.originX?b[this.originX]:this.originX-.5,i="string"==typeof e?b[e]:e-.5,this.left+=s*(i-t),this.top+=o*(i-t),this.setCoords(),this.originX=e},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var e=this.getCenterPoint();this.originX="center",this.originY="center",this.left=e.x,this.top=e.y},_resetOrigin:function(){var e=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=e.x,this.top=e.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var e=T.util,t=e.degreesToRadians,i=e.multiplyTransformMatrices,r=e.transformPoint;e.object.extend(T.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(e,t){return t?e?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),e?this.aCoords:this.lineCoords)},getCoords:function(e,t){return i=this._getCoords(e,t),[new T.Point(i.tl.x,i.tl.y),new T.Point(i.tr.x,i.tr.y),new T.Point(i.br.x,i.br.y),new T.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(e,t,i,r){var n=this.getCoords(i,r);return"Intersection"===T.Intersection.intersectPolygonRectangle(n,e,t).status},intersectsWithObject:function(e,t,i){return"Intersection"===T.Intersection.intersectPolygonPolygon(this.getCoords(t,i),e.getCoords(t,i)).status||e.isContainedWithinObject(this,t,i)||this.isContainedWithinObject(e,t,i)},isContainedWithinObject:function(e,t,i){for(var r=this.getCoords(t,i),n=t?e.aCoords:e.lineCoords,s=0,o=e._getImageLines(n);s<4;s++)if(!e.containsPoint(r[s],o))return!1;return!0},isContainedWithinRect:function(e,t,i,r){var n=this.getBoundingRect(i,r);return n.left>=e.x&&n.left+n.width<=t.x&&n.top>=e.y&&n.top+n.height<=t.y},containsPoint:function(e,t,i,r){var n=this._getCoords(i,r),s=(t=t||this._getImageLines(n),this._findCrossPoints(e,t));return 0!==s&&s%2==1},isOnScreen:function(e){if(!this.canvas)return!1;var t=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,e).some((function(e){return e.x<=i.x&&e.x>=t.x&&e.y<=i.y&&e.y>=t.y}))||!!this.intersectsWithRect(t,i,!0,e)||this._containsCenterOfCanvas(t,i,e)},_containsCenterOfCanvas:function(e,t,i){var r={x:(e.x+t.x)/2,y:(e.y+t.y)/2};return!!this.containsPoint(r,null,!0,i)},isPartiallyOnScreen:function(e){if(!this.canvas)return!1;var t=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(t,i,!0,e)||this.getCoords(!0,e).every((function(e){return(e.x>=i.x||e.x<=t.x)&&(e.y>=i.y||e.y<=t.y)}))&&this._containsCenterOfCanvas(t,i,e)},_getImageLines:function(e){return{topline:{o:e.tl,d:e.tr},rightline:{o:e.tr,d:e.br},bottomline:{o:e.br,d:e.bl},leftline:{o:e.bl,d:e.tl}}},_findCrossPoints:function(e,t){var i,r,n,s=0;for(var o in t)if(!((n=t[o]).o.y=e.y&&n.d.y>=e.y||(n.o.x===n.d.x&&n.o.x>=e.x?r=n.o.x:(i=(n.d.y-n.o.y)/(n.d.x-n.o.x),r=-(e.y-0*e.x-(n.o.y-i*n.o.x))/(0-i)),r>=e.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(t,i){var r=this.getCoords(t,i);return e.makeBoundingBoxFromPoints(r)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(e){return Math.abs(e)\n')}},toSVG:function(e){return this._createBaseSVGMarkup(this._toSVG(e),{reviver:e})},toClipPathSVG:function(e){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(e),{reviver:e})},_createBaseClipPathSVGMarkup:function(e,t){var i=(t=t||{}).reviver,r=t.additionalTransform||"",n=[this.getSvgTransform(!0,r),this.getSvgCommons()].join(""),s=e.indexOf("COMMON_PARTS");return e[s]=n,i?i(e.join("")):e.join("")},_createBaseSVGMarkup:function(e,t){var i,r,n=(t=t||{}).noStyle,s=t.reviver,o=n?"":'style="'+this.getSvgStyles()+'" ',a=t.withShadow?'style="'+this.getSvgFilter()+'" ':"",l=this.clipPath,h=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=l&&l.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],_=e.indexOf("COMMON_PARTS"),p=t.additionalTransform;return l&&(l.clipPathId="CLIPPATH_"+T.Object.__uid++,r='\n'+l.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,h,n?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),e[_]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),l&&g.push(r),g.push(e.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var e=T.util.object.extend,t="stateProperties";function i(t,i,r){var n={};r.forEach((function(e){n[e]=t[e]})),e(t[i],n,!0)}function r(e,t,i){if(e===t)return!0;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(var n=0,s=e.length;n=0;l--)if(n=a[l],this.isControlVisible(n)&&(r=this._getImageLines(t?this.oCoords[n].touchCorner:this.oCoords[n].corner),0!==(i=this._findCrossPoints({x:s,y:o},r))&&i%2==1))return this.__corner=n,n;return!1},forEachControl:function(e){for(var t in this.controls)e(this.controls[t],t,this)},_setCornerCoords:function(){var e=this.oCoords;for(var t in e){var i=this.controls[t];e[t].corner=i.calcCornerCoords(this.angle,this.cornerSize,e[t].x,e[t].y,!1),e[t].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,e[t].x,e[t].y,!0)}},drawSelectionBackground:function(t){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;t.save();var i=this.getCenterPoint(),r=this._calculateCurrentDimensions(),n=this.canvas.viewportTransform;return t.translate(i.x,i.y),t.scale(1/n[0],1/n[3]),t.rotate(e(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-r.x/2,-r.y/2,r.x,r.y),t.restore(),this},drawBorders:function(e,t){t=t||{};var i=this._calculateCurrentDimensions(),r=this.borderScaleFactor,n=i.x+r,s=i.y+r,o=void 0!==t.hasControls?t.hasControls:this.hasControls,a=!1;return e.save(),e.strokeStyle=t.borderColor||this.borderColor,this._setLineDash(e,t.borderDashArray||this.borderDashArray),e.strokeRect(-n/2,-s/2,n,s),o&&(e.beginPath(),this.forEachControl((function(t,i,r){t.withConnection&&t.getVisibility(r,i)&&(a=!0,e.moveTo(t.x*n,t.y*s),e.lineTo(t.x*n+t.offsetX,t.y*s+t.offsetY))})),a&&e.stroke()),e.restore(),this},drawBordersInGroup:function(e,t,i){i=i||{};var r=T.util.sizeAfterTransform(this.width,this.height,t),n=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=r.x+n*(s?this.canvas.getZoom():t.scaleX)+o,l=r.y+n*(s?this.canvas.getZoom():t.scaleY)+o;return e.save(),this._setLineDash(e,i.borderDashArray||this.borderDashArray),e.strokeStyle=i.borderColor||this.borderColor,e.strokeRect(-a/2,-l/2,a,l),e.restore(),this},drawControls:function(e,t){t=t||{},e.save();var i,r,n=this.canvas.getRetinaScaling();return e.setTransform(n,0,0,n,0,0),e.strokeStyle=e.fillStyle=t.cornerColor||this.cornerColor,this.transparentCorners||(e.strokeStyle=t.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(e,t.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(n,s,o){r=o.oCoords[s],n.getVisibility(o,s)&&(i&&(r=T.util.transformPoint(r,i)),n.render(e,r.x,r.y,t,o))})),e.restore(),this},isControlVisible:function(e){return this.controls[e]&&this.controls[e].getVisibility(this,e)},setControlVisible:function(e,t){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[e]=t,this},setControlsVisibility:function(e){for(var t in e||(e={}),e)this.setControlVisible(t,e[t]);return this},onDeselect:function(){},onSelect:function(){}})}(),T.util.object.extend(T.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(e,t){var i=function(){},r=(t=t||{}).onComplete||i,n=t.onChange||i,s=this;return T.util.animate({target:this,startValue:e.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(t){e.set("left",t),s.requestRenderAll(),n()},onComplete:function(){e.setCoords(),r()}})},fxCenterObjectV:function(e,t){var i=function(){},r=(t=t||{}).onComplete||i,n=t.onChange||i,s=this;return T.util.animate({target:this,startValue:e.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(t){e.set("top",t),s.requestRenderAll(),n()},onComplete:function(){e.setCoords(),r()}})},fxRemove:function(e,t){var i=function(){},r=(t=t||{}).onComplete||i,n=t.onChange||i,s=this;return T.util.animate({target:this,startValue:e.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(t){e.set("opacity",t),s.requestRenderAll(),n()},onComplete:function(){s.remove(e),r()}})}}),T.util.object.extend(T.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var e,t,i=[],r=[];for(e in arguments[0])i.push(e);for(var n=0,s=i.length;n-1||n&&s.colorProperties.indexOf(n[1])>-1,a=n?this.get(n[0])[n[1]]:this.get(e);"from"in i||(i.from=a),o||(t=~t.indexOf("=")?a+parseFloat(t.replace("=","")):parseFloat(t));var l={target:this,startValue:i.from,endValue:t,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(e,t,r){return i.abort.call(s,e,t,r)},onChange:function(t,o,a){n?s[n[0]][n[1]]=t:s.set(e,t),r||i.onChange&&i.onChange(t,o,a)},onComplete:function(e,t,n){r||(s.setCoords(),i.onComplete&&i.onComplete(e,t,n))}};return o?T.util.animateColor(l.startValue,l.endValue,l.duration,l):T.util.animate(l)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend,r=t.util.object.clone,n={x1:1,x2:1,y1:1,y2:1};function s(e,t){var i=e.origin,r=e.axis1,n=e.axis2,s=e.dimension,o=t.nearest,a=t.center,l=t.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(r),this.get(n));case a:return Math.min(this.get(r),this.get(n))+.5*this.get(s);case l:return Math.max(this.get(r),this.get(n))}}}t.Line?t.warn("fabric.Line is already defined"):(t.Line=t.util.createClass(t.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:t.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(e,t){e||(e=[0,0,0,0]),this.callSuper("initialize",t),this.set("x1",e[0]),this.set("y1",e[1]),this.set("x2",e[2]),this.set("y2",e[3]),this._setWidthHeight(t)},_setWidthHeight:function(e){e||(e={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in e?e.left:this._getLeftToOriginX(),this.top="top"in e?e.top:this._getTopToOriginY()},_set:function(e,t){return this.callSuper("_set",e,t),void 0!==n[e]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(e){e.beginPath();var t=this.calcLinePoints();e.moveTo(t.x1,t.y1),e.lineTo(t.x2,t.y2),e.lineWidth=this.strokeWidth;var i=e.strokeStyle;e.strokeStyle=this.stroke||e.fillStyle,this.stroke&&this._renderStroke(e),e.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(e){return i(this.callSuper("toObject",e),this.calcLinePoints())},_getNonTransformedDimensions:function(){var e=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(e.y-=this.strokeWidth),0===this.height&&(e.x-=this.strokeWidth)),e},calcLinePoints:function(){var e=this.x1<=this.x2?-1:1,t=this.y1<=this.y2?-1:1,i=e*this.width*.5,r=t*this.height*.5;return{x1:i,x2:e*this.width*-.5,y1:r,y2:t*this.height*-.5}},_toSVG:function(){var e=this.calcLinePoints();return["\n']}}),t.Line.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),t.Line.fromElement=function(e,r,n){n=n||{};var s=t.parseAttributes(e,t.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];r(new t.Line(o,i(s,n)))},t.Line.fromObject=function(e,i){var n=r(e,!0);n.points=[e.x1,e.y1,e.x2,e.y2],t.Object._fromObject("Line",n,(function(e){delete e.points,i&&i(e)}),"points")})}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.degreesToRadians;t.Circle?t.warn("fabric.Circle is already defined."):(t.Circle=t.util.createClass(t.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:t.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(e,t){return this.callSuper("_set",e,t),"radius"===e&&this.setRadius(t),this},toObject:function(e){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(e))},_toSVG:function(){var e,r=(this.endAngle-this.startAngle)%360;if(0===r)e=["\n'];else{var n=i(this.startAngle),s=i(this.endAngle),o=this.radius;e=['180?"1":"0")+" 1"," "+t.util.cos(s)*o+" "+t.util.sin(s)*o,'" ',"COMMON_PARTS"," />\n"]}return e},_render:function(e){e.beginPath(),e.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(e)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(e){return this.radius=e,this.set("width",2*e).set("height",2*e)}}),t.Circle.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),t.Circle.fromElement=function(e,i){var r,n=t.parseAttributes(e,t.Circle.ATTRIBUTE_NAMES);if(!("radius"in(r=n)&&r.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");n.left=(n.left||0)-n.radius,n.top=(n.top||0)-n.radius,i(new t.Circle(n))},t.Circle.fromObject=function(e,i){t.Object._fromObject("Circle",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={});t.Triangle?t.warn("fabric.Triangle is already defined"):(t.Triangle=t.util.createClass(t.Object,{type:"triangle",width:100,height:100,_render:function(e){var t=this.width/2,i=this.height/2;e.beginPath(),e.moveTo(-t,i),e.lineTo(0,-i),e.lineTo(t,i),e.closePath(),this._renderPaintInOrder(e)},_toSVG:function(){var e=this.width/2,t=this.height/2;return["']}}),t.Triangle.fromObject=function(e,i){return t.Object._fromObject("Triangle",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={}),i=2*Math.PI;t.Ellipse?t.warn("fabric.Ellipse is already defined."):(t.Ellipse=t.util.createClass(t.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:t.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(e){this.callSuper("initialize",e),this.set("rx",e&&e.rx||0),this.set("ry",e&&e.ry||0)},_set:function(e,t){switch(this.callSuper("_set",e,t),e){case"rx":this.rx=t,this.set("width",2*t);break;case"ry":this.ry=t,this.set("height",2*t)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(e){return this.callSuper("toObject",["rx","ry"].concat(e))},_toSVG:function(){return["\n']},_render:function(e){e.beginPath(),e.save(),e.transform(1,0,0,this.ry/this.rx,0,0),e.arc(0,0,this.rx,0,i,!1),e.restore(),this._renderPaintInOrder(e)}}),t.Ellipse.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),t.Ellipse.fromElement=function(e,i){var r=t.parseAttributes(e,t.Ellipse.ATTRIBUTE_NAMES);r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,i(new t.Ellipse(r))},t.Ellipse.fromObject=function(e,i){t.Object._fromObject("Ellipse",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend;t.Rect?t.warn("fabric.Rect is already defined"):(t.Rect=t.util.createClass(t.Object,{stateProperties:t.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:t.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(e){this.callSuper("initialize",e),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(e){var t=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,r=this.width,n=this.height,s=-this.width/2,o=-this.height/2,a=0!==t||0!==i,l=.4477152502;e.beginPath(),e.moveTo(s+t,o),e.lineTo(s+r-t,o),a&&e.bezierCurveTo(s+r-l*t,o,s+r,o+l*i,s+r,o+i),e.lineTo(s+r,o+n-i),a&&e.bezierCurveTo(s+r,o+n-l*i,s+r-l*t,o+n,s+r-t,o+n),e.lineTo(s+t,o+n),a&&e.bezierCurveTo(s+l*t,o+n,s,o+n-l*i,s,o+n-i),e.lineTo(s,o+i),a&&e.bezierCurveTo(s,o+l*i,s+l*t,o,s+t,o),e.closePath(),this._renderPaintInOrder(e)},toObject:function(e){return this.callSuper("toObject",["rx","ry"].concat(e))},_toSVG:function(){return["\n']}}),t.Rect.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),t.Rect.fromElement=function(e,r,n){if(!e)return r(null);n=n||{};var s=t.parseAttributes(e,t.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new t.Rect(i(n?t.util.object.clone(n):{},s));o.visible=o.visible&&o.width>0&&o.height>0,r(o)},t.Rect.fromObject=function(e,i){return t.Object._fromObject("Rect",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend,r=t.util.array.min,n=t.util.array.max,s=t.util.toFixed,o=t.util.projectStrokeOnPoints;t.Polyline?t.warn("fabric.Polyline is already defined"):(t.Polyline=t.util.createClass(t.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:t.Object.prototype.cacheProperties.concat("points"),initialize:function(e,t){t=t||{},this.points=e||[],this.callSuper("initialize",t),this._setPositionDimensions(t)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(e){var t,i=this._calcDimensions(e),r=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-r,this.height=i.height-r,e.fromSVG||(t=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+r/2,y:i.top-this.strokeWidth/2+r/2},"left","top",this.originX,this.originY)),void 0===e.left&&(this.left=e.fromSVG?i.left:t.x),void 0===e.top&&(this.top=e.fromSVG?i.top:t.y),this.pathOffset={x:i.left+this.width/2+r/2,y:i.top+this.height/2+r/2}},_calcDimensions:function(){var e=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,t=r(e,"x")||0,i=r(e,"y")||0;return{left:t,top:i,width:(n(e,"x")||0)-t,height:(n(e,"y")||0)-i}},toObject:function(e){return i(this.callSuper("toObject",e),{points:this.points.concat()})},_toSVG:function(){for(var e=[],i=this.pathOffset.x,r=this.pathOffset.y,n=t.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(e){var t,i=this.points.length,r=this.pathOffset.x,n=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;e.beginPath(),e.moveTo(this.points[0].x-r,this.points[0].y-n);for(var s=0;s"},toObject:function(e){return n(this.callSuper("toObject",e),{path:this.path.map((function(e){return e.slice()}))})},toDatalessObject:function(e){var t=this.toObject(["sourcePath"].concat(e));return t.sourcePath&&delete t.path,t},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var e=t.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,e)+", "+o(-this.pathOffset.y,e)+")"},toClipPathSVG:function(e){var t=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:e,additionalTransform:t})},toSVG:function(e){var t=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:e,additionalTransform:t})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var e,n,s=[],o=[],a=0,l=0,h=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(e){var i=!!this.group;return this._restoreObjectsState(),t.util.resetObjectTransform(this),e&&(i&&t.util.removeTransformFromObject(e,this.group.calcTransformMatrix()),this._objects.push(e),e.group=this,e._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(e){return this._restoreObjectsState(),t.util.resetObjectTransform(this),this.remove(e),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(e){this.dirty=!0,e.group=this,e._set("canvas",this.canvas)},_onObjectRemoved:function(e){this.dirty=!0,delete e.group},_set:function(e,i){var r=this._objects.length;if(this.useSetOnGroup)for(;r--;)this._objects[r].setOnGroup(e,i);if("canvas"===e)for(;r--;)this._objects[r]._set(e,i);t.Object.prototype._set.call(this,e,i)},toObject:function(e){var i=this.includeDefaultValues,r=this._objects.filter((function(e){return!e.excludeFromExport})).map((function(t){var r=t.includeDefaultValues;t.includeDefaultValues=i;var n=t.toObject(e);return t.includeDefaultValues=r,n})),n=t.Object.prototype.toObject.call(this,e);return n.objects=r,n},toDatalessObject:function(e){var i,r=this.sourcePath;if(r)i=r;else{var n=this.includeDefaultValues;i=this._objects.map((function(t){var i=t.includeDefaultValues;t.includeDefaultValues=n;var r=t.toDatalessObject(e);return t.includeDefaultValues=i,r}))}var s=t.Object.prototype.toDatalessObject.call(this,e);return s.objects=i,s},render:function(e){this._transformDone=!0,this.callSuper("render",e),this._transformDone=!1},shouldCache:function(){var e=t.Object.prototype.shouldCache.call(this);if(e)for(var i=0,r=this._objects.length;i\n"],i=0,r=this._objects.length;i\n"),t},getSvgStyles:function(){var e=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",t=this.visible?"":" visibility: hidden;";return[e,this.getSvgFilter(),t].join("")},toClipPathSVG:function(e){for(var t=[],i=0,r=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(e,t,i){e.save(),e.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",e,t),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var r=0,n=this._objects.length;r\n','\t\n',"\n"),o=' clip-path="url(#imageCrop_'+l+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var h=this.fill;this.fill=null,e=["\t\n'],this.fill=h}return"fill"!==this.paintFirst?t.concat(e,i):t.concat(i,e)},getSrc:function(e){var t=e?this._element:this._originalElement;return t?t.toDataURL?t.toDataURL():this.srcFromAttribute?t.getAttribute("src"):t.src:this.src||""},setSrc:function(e,t,i){return T.util.loadImage(e,(function(e,r){this.setElement(e,i),this._setWidthHeight(),t&&t(this,r)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var e=this.resizeFilter,t=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),r=i.scaleX,n=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!e||r>t&&n>t)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=n);T.filterBackend||(T.filterBackend=T.initFilterBackend());var o=T.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,l=s.width,h=s.height;o.width=l,o.height=h,this._element=o,this._lastScaleX=e.scaleX=r,this._lastScaleY=e.scaleY=n,T.filterBackend.applyFilters([e],s,l,h,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(e){if(e=(e=e||this.filters||[]).filter((function(e){return e&&!e.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===e.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var t=this._originalElement,i=t.naturalWidth||t.width,r=t.naturalHeight||t.height;if(this._element===this._originalElement){var n=T.util.createCanvasElement();n.width=i,n.height=r,this._element=n,this._filteredEl=n}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,r),this._lastScaleX=1,this._lastScaleY=1;return T.filterBackend||(T.filterBackend=T.initFilterBackend()),T.filterBackend.applyFilters(e,this._originalElement,i,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(e){T.util.setImageSmoothing(e,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(e),this._renderPaintInOrder(e)},drawCacheOnCanvas:function(e){T.util.setImageSmoothing(e,this.imageSmoothing),T.Object.prototype.drawCacheOnCanvas.call(this,e)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(e){var t=this._element;if(t){var i=this._filterScalingX,r=this._filterScalingY,n=this.width,s=this.height,o=Math.min,a=Math.max,l=a(this.cropX,0),h=a(this.cropY,0),c=t.naturalWidth||t.width,u=t.naturalHeight||t.height,d=l*i,f=h*r,g=o(n*i,c-d),_=o(s*r,u-f),p=-n/2,m=-s/2,v=o(n,c/i-l),y=o(s,u/r-h);t&&e.drawImage(t,d,f,g,_,p,m,v,y)}},_needsResize:function(){var e=this.getTotalObjectScaling();return e.scaleX!==this._lastScaleX||e.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(e,t){this.setElement(T.util.getById(e),t),T.util.addClass(this.getElement(),T.Image.CSS_CANVAS)},_initConfig:function(e){e||(e={}),this.setOptions(e),this._setWidthHeight(e)},_initFilters:function(e,t){e&&e.length?T.util.enlivenObjects(e,(function(e){t&&t(e)}),"fabric.Image.filters"):t&&t()},_setWidthHeight:function(e){e||(e={});var t=this.getElement();this.width=e.width||t.naturalWidth||t.width||0,this.height=e.height||t.naturalHeight||t.height||0},parsePreserveAspectRatioAttribute:function(){var e,t=T.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,r=this._element.height,n=1,s=1,o=0,a=0,l=0,h=0,c=this.width,u=this.height,d={width:c,height:u};return!t||"none"===t.alignX&&"none"===t.alignY?(n=c/i,s=u/r):("meet"===t.meetOrSlice&&(e=(c-i*(n=s=T.util.findScaleToFit(this._element,d)))/2,"Min"===t.alignX&&(o=-e),"Max"===t.alignX&&(o=e),e=(u-r*s)/2,"Min"===t.alignY&&(a=-e),"Max"===t.alignY&&(a=e)),"slice"===t.meetOrSlice&&(e=i-c/(n=s=T.util.findScaleToCover(this._element,d)),"Mid"===t.alignX&&(l=e/2),"Max"===t.alignX&&(l=e),e=r-u/s,"Mid"===t.alignY&&(h=e/2),"Max"===t.alignY&&(h=e),i=c/n,r=u/s)),{width:i,height:r,scaleX:n,scaleY:s,offsetLeft:o,offsetTop:a,cropX:l,cropY:h}}}),T.Image.CSS_CANVAS="canvas-img",T.Image.prototype.getSvgSrc=T.Image.prototype.getSrc,T.Image.fromObject=function(e,t){var i=T.util.object.clone(e);T.util.loadImage(i.src,(function(e,r){r?t&&t(null,!0):T.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],T.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],T.util.enlivenObjectEnlivables(i,i,(function(){var r=new T.Image(e,i);t(r,!1)}))}))}))}),null,i.crossOrigin)},T.Image.fromURL=function(e,t,i){T.util.loadImage(e,(function(e,r){t&&t(new T.Image(e,i),r)}),null,i&&i.crossOrigin)},T.Image.ATTRIBUTE_NAMES=T.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),T.Image.fromElement=function(e,i,r){var n=T.parseAttributes(e,T.Image.ATTRIBUTE_NAMES);T.Image.fromURL(n["xlink:href"],i,t(r?T.util.object.clone(r):{},n))})}(t),T.util.object.extend(T.Object.prototype,{_getAngleValueForStraighten:function(){var e=this.angle%360;return e>0?90*Math.round((e-1)/90):90*Math.round(e/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(e){var t=function(){},i=(e=e||{}).onComplete||t,r=e.onChange||t,n=this;return T.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(e){n.rotate(e),r()},onComplete:function(){n.setCoords(),i()}})}}),T.util.object.extend(T.StaticCanvas.prototype,{straightenObject:function(e){return e.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(e){return e.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function e(e,t){var i="precision "+t+" float;\nvoid main(){}",r=e.createShader(e.FRAGMENT_SHADER);return e.shaderSource(r,i),e.compileShader(r),!!e.getShaderParameter(r,e.COMPILE_STATUS)}function t(e){e&&e.tileSize&&(this.tileSize=e.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}T.isWebglSupported=function(t){if(T.isLikelyNode)return!1;t=t||T.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),n=!1;if(r){T.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),n=T.maxTextureSize>=t;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(e(r,s[o])){T.webGlPrecision=s[o];break}}return this.isSupported=n,n},T.WebglFilterBackend=t,t.prototype={tileSize:2048,resources:{},setupGLContext:function(e,t){this.dispose(),this.createWebGLCanvas(e,t),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(e,t)},chooseFastestCopyGLTo2DMethod:function(e,t){var i,r=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(e){i=!1}var n="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(r&&i&&n&&s){var o=T.util.createCanvasElement(),a=new ArrayBuffer(e*t*4);if(T.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=O);var l,h,c={imageBuffer:a,destinationWidth:e,destinationHeight:t,targetCanvas:o};o.width=e,o.height=t,l=window.performance.now(),A.call(c,this.gl,c),h=window.performance.now()-l,l=window.performance.now(),O.call(c,this.gl,c),h>window.performance.now()-l?(this.imageBuffer=a,this.copyGLTo2D=O):this.copyGLTo2D=A}},createWebGLCanvas:function(e,t){var i=T.util.createCanvasElement();i.width=e,i.height=t;var r={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},n=i.getContext("webgl",r);n||(n=i.getContext("experimental-webgl",r)),n&&(n.clearColor(0,0,0,0),this.canvas=i,this.gl=n)},applyFilters:function(e,t,i,r,n,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,t));var l={originalWidth:t.width||t.originalWidth,originalHeight:t.height||t.originalHeight,sourceWidth:i,sourceHeight:r,destinationWidth:i,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,i,r,!o&&t),targetTexture:this.createTexture(a,i,r),originalTexture:o||this.createTexture(a,i,r,!o&&t),passes:e.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},h=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,h),e.forEach((function(e){e&&e.applyTo(l)})),function(e){var t=e.targetCanvas,i=t.width,r=t.height,n=e.destinationWidth,s=e.destinationHeight;i===n&&r===s||(t.width=n,t.height=s)}(l),this.copyGLTo2D(a,l),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(l.sourceTexture),a.deleteTexture(l.targetTexture),a.deleteFramebuffer(h),n.getContext("2d").setTransform(1,0,0,1,0,0),l},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(e,t,i,r){var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),r?e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r):e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,i,0,e.RGBA,e.UNSIGNED_BYTE,null),n},getCachedTexture:function(e,t){if(this.textureCache[e])return this.textureCache[e];var i=this.createTexture(this.gl,t.width,t.height,t);return this.textureCache[e]=i,i},evictCachesForKey:function(e){this.textureCache[e]&&(this.gl.deleteTexture(this.textureCache[e]),delete this.textureCache[e])},copyGLTo2D:A,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var e=this.gl,t={renderer:"",vendor:""};if(!e)return t;var i=e.getExtension("WEBGL_debug_renderer_info");if(i){var r=e.getParameter(i.UNMASKED_RENDERER_WEBGL),n=e.getParameter(i.UNMASKED_VENDOR_WEBGL);r&&(t.renderer=r.toLowerCase()),n&&(t.vendor=n.toLowerCase())}return this.gpuInfo=t,t}}}(),function(){var e=function(){};function t(){}T.Canvas2dFilterBackend=t,t.prototype={evictCachesForKey:e,dispose:e,clearWebGLCaches:e,resources:{},applyFilters:function(e,t,i,r,n){var s=n.getContext("2d");s.drawImage(t,0,0,i,r);var o={sourceWidth:i,sourceHeight:r,imageData:s.getImageData(0,0,i,r),originalEl:t,originalImageData:s.getImageData(0,0,i,r),canvasEl:n,ctx:s,filterBackend:this};return e.forEach((function(e){e.applyTo(o)})),o.imageData.width===i&&o.imageData.height===r||(n.width=o.imageData.width,n.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),T.Image=T.Image||{},T.Image.filters=T.Image.filters||{},T.Image.filters.BaseFilter=T.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(e){e&&this.setOptions(e)},setOptions:function(e){for(var t in e)this[t]=e[t]},createProgram:function(e,t,i){t=t||this.fragmentSource,i=i||this.vertexSource,"highp"!==T.webGlPrecision&&(t=t.replace(/precision highp float/g,"precision "+T.webGlPrecision+" float"));var r=e.createShader(e.VERTEX_SHADER);if(e.shaderSource(r,i),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+e.getShaderInfoLog(r));var n=e.createShader(e.FRAGMENT_SHADER);if(e.shaderSource(n,t),e.compileShader(n),!e.getShaderParameter(n,e.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+e.getShaderInfoLog(n));var s=e.createProgram();if(e.attachShader(s,r),e.attachShader(s,n),e.linkProgram(s),!e.getProgramParameter(s,e.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+e.getProgramInfoLog(s));var o=this.getAttributeLocations(e,s),a=this.getUniformLocations(e,s)||{};return a.uStepW=e.getUniformLocation(s,"uStepW"),a.uStepH=e.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(e,t){return{aPosition:e.getAttribLocation(t,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(e,t,i){var r=t.aPosition,n=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,n),e.enableVertexAttribArray(r),e.vertexAttribPointer(r,2,e.FLOAT,!1,0,0),e.bufferData(e.ARRAY_BUFFER,i,e.STATIC_DRAW)},_setupFrameBuffer:function(e){var t,i,r=e.context;e.passes>1?(t=e.destinationWidth,i=e.destinationHeight,e.sourceWidth===t&&e.sourceHeight===i||(r.deleteTexture(e.targetTexture),e.targetTexture=e.filterBackend.createTexture(r,t,i)),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e.targetTexture,0)):(r.bindFramebuffer(r.FRAMEBUFFER,null),r.finish())},_swapTextures:function(e){e.passes--,e.pass++;var t=e.targetTexture;e.targetTexture=e.sourceTexture,e.sourceTexture=t},isNeutralState:function(){var e=this.mainParameter,t=T.Image.filters[this.type].prototype;if(e){if(Array.isArray(t[e])){for(var i=t[e].length;i--;)if(this[e][i]!==t[e][i])return!1;return!0}return t[e]===this[e]}return!1},applyTo:function(e){e.webgl?(this._setupFrameBuffer(e),this.applyToWebGL(e),this._swapTextures(e)):this.applyTo2d(e)},retrieveShader:function(e){return e.programCache.hasOwnProperty(this.type)||(e.programCache[this.type]=this.createProgram(e.context)),e.programCache[this.type]},applyToWebGL:function(e){var t=e.context,i=this.retrieveShader(e);0===e.pass&&e.originalTexture?t.bindTexture(t.TEXTURE_2D,e.originalTexture):t.bindTexture(t.TEXTURE_2D,e.sourceTexture),t.useProgram(i.program),this.sendAttributeData(t,i.attributeLocations,e.aPosition),t.uniform1f(i.uniformLocations.uStepW,1/e.sourceWidth),t.uniform1f(i.uniformLocations.uStepH,1/e.sourceHeight),this.sendUniformData(t,i.uniformLocations),t.viewport(0,0,e.destinationWidth,e.destinationHeight),t.drawArrays(t.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(e,t,i){e.activeTexture(i),e.bindTexture(e.TEXTURE_2D,t),e.activeTexture(e.TEXTURE0)},unbindAdditionalTexture:function(e,t){e.activeTexture(t),e.bindTexture(e.TEXTURE_2D,null),e.activeTexture(e.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(e){this[this.mainParameter]=e},sendUniformData:function(){},createHelpLayer:function(e){if(!e.helpLayer){var t=document.createElement("canvas");t.width=e.sourceWidth,t.height=e.sourceHeight,e.helpLayer=t}},toObject:function(){var e={type:this.type},t=this.mainParameter;return t&&(e[t]=this[t]),e},toJSON:function(){return this.toObject()}}),T.Image.filters.BaseFilter.fromObject=function(e,t){var i=new T.Image.filters[e.type](e);return t&&t(i),i},function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.ColorMatrix=r(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(e){this.callSuper("initialize",e),this.matrix=this.matrix.slice(0)},applyTo2d:function(e){var t,i,r,n,s,o=e.imageData.data,a=o.length,l=this.matrix,h=this.colorsOnly;for(s=0;s=S||o<0||o>=y||(l=4*(a*y+o),h=p[f*m+d],t+=_[l]*h,i+=_[l+1]*h,r+=_[l+2]*h,w||(n+=_[l+3]*h));C[s]=t,C[s+1]=i,C[s+2]=r,C[s+3]=w?_[s+3]:n}e.imageData=b},getUniformLocations:function(e,t){return{uMatrix:e.getUniformLocation(t,"uMatrix"),uOpaque:e.getUniformLocation(t,"uOpaque"),uHalfSize:e.getUniformLocation(t,"uHalfSize"),uSize:e.getUniformLocation(t,"uSize")}},sendUniformData:function(e,t){e.uniform1fv(t.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),t.Image.filters.Convolute.fromObject=t.Image.filters.BaseFilter.fromObject}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.Grayscale=r(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(e){var t,i,r=e.imageData.data,n=r.length,s=this.mode;for(t=0;th[0]&&n>h[1]&&s>h[2]&&r 0.0) {\n"+this.fragmentSource[e]+"}\n}"},retrieveShader:function(e){var t,i=this.type+"_"+this.mode;return e.programCache.hasOwnProperty(i)||(t=this.buildSource(this.mode),e.programCache[i]=this.createProgram(e.context,t)),e.programCache[i]},applyTo2d:function(e){var i,r,n,s,o,a,l,h=e.imageData.data,c=h.length,u=1-this.alpha;i=(l=new t.Color(this.color).getSource())[0]*this.alpha,r=l[1]*this.alpha,n=l[2]*this.alpha;for(var d=0;d=e||t<=-e)return 0;if(t<1.1920929e-7&&t>-1.1920929e-7)return 1;var i=(t*=Math.PI)/e;return a(t)/t*a(i)/i}},applyTo2d:function(e){var t=e.imageData,i=this.scaleX,r=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/r;var n,s=t.width,a=t.height,l=o(s*i),h=o(a*r);"sliceHack"===this.resizeType?n=this.sliceByTwo(e,s,a,l,h):"hermite"===this.resizeType?n=this.hermiteFastResize(e,s,a,l,h):"bilinear"===this.resizeType?n=this.bilinearFiltering(e,s,a,l,h):"lanczos"===this.resizeType&&(n=this.lanczosResize(e,s,a,l,h)),e.imageData=n},sliceByTwo:function(e,i,n,s,o){var a,l,h=e.imageData,c=.5,u=!1,d=!1,f=i*c,g=n*c,_=t.filterBackend.resources,p=0,m=0,v=i,y=0;for(_.sliceByTwo||(_.sliceByTwo=document.createElement("canvas")),((a=_.sliceByTwo).width<1.5*i||a.height=t)){M=r(1e3*s(T-b.x)),S[M]||(S[M]={});for(var P=C.y-y;P<=C.y+y;P++)P<0||P>=o||(L=r(1e3*s(P-b.y)),S[M][L]||(S[M][L]=f(n(i(M*p,2)+i(L*m,2))/1e3)),(x=S[M][L])>0&&(O+=x,I+=x*c[A=4*(P*t+T)],E+=x*c[A+1],R+=x*c[A+2],D+=x*c[A+3]))}d[A=4*(w*a+l)]=I/O,d[A+1]=E/O,d[A+2]=R/O,d[A+3]=D/O}return++l1&&L<-1||(y=2*L*L*L-3*L*L+1)>0&&(x+=y*f[3+(M=4*(D+O*t))],b+=y,f[M+3]<255&&(y=y*f[M+3]/250),C+=y*f[M],w+=y*f[M+1],T+=y*f[M+2],S+=y)}_[v]=C/S,_[v+1]=w/S,_[v+2]=T/S,_[v+3]=x/b}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),t.Image.filters.Resize.fromObject=t.Image.filters.BaseFilter.fromObject}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.Contrast=r(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(e){if(0!==this.contrast){var t,i=e.imageData.data,r=i.length,n=Math.floor(255*this.contrast),s=259*(n+255)/(255*(259-n));for(t=0;t1&&(t=1/this.aspectRatio):this.aspectRatio<1&&(t=this.aspectRatio),e=t*this.blur*.12,this.horizontal?i[0]=e:i[1]=e,i}}),i.Blur.fromObject=t.Image.filters.BaseFilter.fromObject}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.Gamma=r(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(e){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,e)},applyTo2d:function(e){var t,i=e.imageData.data,r=this.gamma,n=i.length,s=1/r[0],o=1/r[1],a=1/r[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),t=0,n=256;t'},_getCacheCanvasDimensions:function(){var e=this.callSuper("_getCacheCanvasDimensions"),t=this.fontSize;return e.width+=t*e.zoomX,e.height+=t*e.zoomY,e},_render:function(e){var t=this.path;t&&!t.isNotVisible()&&t._render(e),this._setTextStyles(e),this._renderTextLinesBackground(e),this._renderTextDecoration(e,"underline"),this._renderText(e),this._renderTextDecoration(e,"overline"),this._renderTextDecoration(e,"linethrough")},_renderText:function(e){"stroke"===this.paintFirst?(this._renderTextStroke(e),this._renderTextFill(e)):(this._renderTextFill(e),this._renderTextStroke(e))},_setTextStyles:function(e,t,i){if(e.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":e.textBaseline="middle";break;case"ascender":e.textBaseline="top";break;case"descender":e.textBaseline="bottom"}e.font=this._getFontDeclaration(t,i)},calcTextWidth:function(){for(var e=this.getLineWidth(0),t=1,i=this._textLines.length;te&&(e=r)}return e},_renderTextLine:function(e,t,i,r,n,s){this._renderChars(e,t,i,r,n,s)},_renderTextLinesBackground:function(e){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var t,i,r,n,s,o,a,l=e.fillStyle,h=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,_=this._textLines.length;g<_;g++)if(t=this.getHeightOfLine(g),this.textBackgroundColor||this.styleHas("textBackgroundColor",g)){r=this._textLines[g],i=this._getLineLeftOffset(g),d=0,u=0,n=this.getValueOfPropertyAt(g,0,"textBackgroundColor");for(var p=0,m=r.length;p=0:ia?u%=a:u<0&&(u+=a),this._setGraphemeOnPath(u,s,o),u+=s.kernedWidth}return{width:l,numOfSpaces:0}},_setGraphemeOnPath:function(e,i,r){var n=e+i.kernedWidth/2,s=this.path,o=t.util.getPointOnPath(s.path,n,s.segmentsInfo);i.renderLeft=o.x-r.x,i.renderTop=o.y-r.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(e,t,i,r,n){var s,o=this.getCompleteStyleDeclaration(t,i),a=r?this.getCompleteStyleDeclaration(t,i-1):{},l=this._measureChar(e,o,r,a),h=l.kernedWidth,c=l.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),h+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:h,deltaY:o.deltaY};if(i>0&&!n){var d=this.__charBounds[t][i-1];u.left=d.left+d.width+l.kernedWidth-l.width}return u},getHeightOfLine:function(e){if(this.__lineHeights[e])return this.__lineHeights[e];for(var t=this._textLines[e],i=this.getHeightOfChar(e,0),r=1,n=t.length;r0){var O=v+s+u;"rtl"===this.direction&&(O=this.width-O-d),h&&m&&(e.fillStyle=m,e.fillRect(O,c+C*r+o,d,this.fontSize/15)),u=f.left,d=f.width,h=g,m=p,r=n,o=a}else d+=f.kernedWidth;O=v+s+u,"rtl"===this.direction&&(O=this.width-O-d),e.fillStyle=p,g&&p&&e.fillRect(O,c+C*r+o,d-b,this.fontSize/15),y+=i}else y+=i;this._removeShadow(e)}},_getFontDeclaration:function(e,i){var r=e||this,n=this.fontFamily,s=t.Text.genericFonts.indexOf(n.toLowerCase())>-1,o=void 0===n||n.indexOf("'")>-1||n.indexOf(",")>-1||n.indexOf('"')>-1||s?r.fontFamily:'"'+r.fontFamily+'"';return[t.isLikelyNode?r.fontWeight:r.fontStyle,t.isLikelyNode?r.fontStyle:r.fontWeight,i?this.CACHE_FONT_SIZE+"px":r.fontSize+"px",o].join(" ")},render:function(e){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",e)))},_splitTextIntoLines:function(e){for(var i=e.split(this._reNewline),r=new Array(i.length),n=["\n"],s=[],o=0;o-1&&(e.underline=!0),e.textDecoration.indexOf("line-through")>-1&&(e.linethrough=!0),e.textDecoration.indexOf("overline")>-1&&(e.overline=!0),delete e.textDecoration)}T.IText=T.util.createClass(T.Text,T.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(e,t){this.callSuper("initialize",e,t),this.initBehavior()},setSelectionStart:function(e){e=Math.max(e,0),this._updateAndFire("selectionStart",e)},setSelectionEnd:function(e){e=Math.min(e,this.text.length),this._updateAndFire("selectionEnd",e)},_updateAndFire:function(e,t){this[e]!==t&&(this._fireSelectionChanged(),this[e]=t),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(e){this.clearContextTop(),this.callSuper("render",e),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(e){this.callSuper("_render",e)},clearContextTop:function(e){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this.canvas.contextTop,i=this.canvas.viewportTransform;t.save(),t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(t),this._clearTextArea(t),e||t.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this._getCursorBoundaries(),t=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(e,t):this.renderSelection(e,t),t.restore()}},_clearTextArea:function(e){var t=this.width+4,i=this.height+4;e.clearRect(-t/2,-i/2,t,i)},_getCursorBoundaries:function(e){void 0===e&&(e=this.selectionStart);var t=this._getLeftOffset(),i=this._getTopOffset(),r=this._getCursorBoundariesOffsets(e);return{left:t,top:i,leftOffset:r.left,topOffset:r.top}},_getCursorBoundariesOffsets:function(e){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var t,i,r,n,s=0,o=0,a=this.get2DCursorLocation(e);r=a.charIndex,i=a.lineIndex;for(var l=0;l0?o:0)},"rtl"===this.direction&&(n.left*=-1),this.cursorOffsetCache=n,this.cursorOffsetCache},renderCursor:function(e,t){var i=this.get2DCursorLocation(),r=i.lineIndex,n=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(r,n,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,l=e.topOffset,h=this.getValueOfPropertyAt(r,n,"deltaY");l+=(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(e,t),t.fillStyle=this.cursorColor||this.getValueOfPropertyAt(r,n,"fill"),t.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,t.fillRect(e.left+e.leftOffset-a/2,l+e.top+h,a,s)},renderSelection:function(e,t){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,r=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,n=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(r),a=s.lineIndex,l=o.lineIndex,h=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=l;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),_=0,p=0;if(u===a&&(_=this.__charBounds[a][h].left),u>=a&&u1)&&(g/=this.lineHeight);var v=e.left+f+_,y=p-_,S=g,b=0;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",S=1,b=g):t.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),t.fillRect(v,e.top+e.topOffset+b,y,S),e.topOffset+=d}},getCurrentCharFontSize:function(){var e=this._getCurrentCharIndex();return this.getValueOfPropertyAt(e.l,e.c,"fontSize")},getCurrentCharColor:function(){var e=this._getCurrentCharIndex();return this.getValueOfPropertyAt(e.l,e.c,"fill")},_getCurrentCharIndex:function(){var e=this.get2DCursorLocation(this.selectionStart,!0),t=e.charIndex>0?e.charIndex-1:0;return{l:e.lineIndex,c:t}}}),T.IText.fromObject=function(t,i){if(e(t),t.styles)for(var r in t.styles)for(var n in t.styles[r])e(t.styles[r][n]);T.Object._fromObject("IText",t,i,"text")}}(),w=T.util.object.clone,T.util.object.extend(T.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var e=this;this.on("added",(function(){var t=e.canvas;t&&(t._hasITextHandlers||(t._hasITextHandlers=!0,e._initCanvasHandlers(t)),t._iTextInstances=t._iTextInstances||[],t._iTextInstances.push(e))}))},initRemovedHandler:function(){var e=this;this.on("removed",(function(){var t=e.canvas;t&&(t._iTextInstances=t._iTextInstances||[],T.util.removeFromArray(t._iTextInstances,e),0===t._iTextInstances.length&&(t._hasITextHandlers=!1,e._removeCanvasHandlers(t)))}))},_initCanvasHandlers:function(e){e._mouseUpITextHandler=function(){e._iTextInstances&&e._iTextInstances.forEach((function(e){e.__isMousedown=!1}))},e.on("mouse:up",e._mouseUpITextHandler)},_removeCanvasHandlers:function(e){e.off("mouse:up",e._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(e,t,i,r){var n;return n={isAborted:!1,abort:function(){this.isAborted=!0}},e.animate("_currentCursorOpacity",t,{duration:i,onComplete:function(){n.isAborted||e[r]()},onChange:function(){e.canvas&&e.selectionStart===e.selectionEnd&&e.renderCursorOrSelection()},abort:function(){return n.isAborted}}),n},_onTickComplete:function(){var e=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){e._currentTickCompleteState=e._animateCursor(e,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(e){var t=this,i=e?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){t._tick()}),i)},abortCursorAnimation:function(){var e=this._currentTickState||this._currentTickCompleteState,t=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,e&&t&&t.clearContext(t.contextTop||t.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(e){var t=0,i=e-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)t++,i--;for(;/\S/.test(this._text[i])&&i>-1;)t++,i--;return e-t},findWordBoundaryRight:function(e){var t=0,i=e;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)t++,i++;for(;/\S/.test(this._text[i])&&i-1;)t++,i--;return e-t},findLineBoundaryRight:function(e){for(var t=0,i=e;!/\n/.test(this._text[i])&&i0&&rthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=t):(this.selectionStart=t,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===r||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(e,t,i){var r=i.slice(0,e),n=T.util.string.graphemeSplit(r).length;if(e===t)return{selectionStart:n,selectionEnd:n};var s=i.slice(e,t);return{selectionStart:n,selectionEnd:n+T.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(e,t,i){var r=i.slice(0,e).join("").length;return e===t?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+i.slice(e,t).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var e=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=e.selectionStart,this.hiddenTextarea.selectionEnd=e.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var e=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=e.selectionEnd,this.inCompositionMode||(this.selectionStart=e.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var e=this._calcTextareaPosition();this.hiddenTextarea.style.left=e.left,this.hiddenTextarea.style.top=e.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var e=this.inCompositionMode?this.compositionStart:this.selectionStart,t=this._getCursorBoundaries(e),i=this.get2DCursorLocation(e),r=i.lineIndex,n=i.charIndex,s=this.getValueOfPropertyAt(r,n,"fontSize")*this.lineHeight,o=t.leftOffset,a=this.calcTransformMatrix(),l={x:t.left+o,y:t.top+t.topOffset+s},h=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/h,d=c.height/h,f=u-s,g=d-s,_=c.clientWidth/u,p=c.clientHeight/d;return l=T.util.transformPoint(l,a),(l=T.util.transformPoint(l,this.canvas.viewportTransform)).x*=_,l.y*=p,l.x<0&&(l.x=0),l.x>f&&(l.x=f),l.y<0&&(l.y=0),l.y>g&&(l.y=g),l.x+=this.canvas._offset.left,l.y+=this.canvas._offset.top,{left:l.x+"px",top:l.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var e=this._textBeforeEdit!==this.text,t=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,t&&(t.blur&&t.blur(),t.parentNode&&t.parentNode.removeChild(t)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),e&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),e&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var e in this.styles)this._textLines[e]||delete this.styles[e]},removeStyleFromTo:function(e,t){var i,r,n=this.get2DCursorLocation(e,!0),s=this.get2DCursorLocation(t,!0),o=n.lineIndex,a=n.charIndex,l=s.lineIndex,h=s.charIndex;if(o!==l){if(this.styles[o])for(i=a;i=h&&(r[c-d]=r[u],delete r[u])}},shiftLineStyles:function(e,t){var i=w(this.styles);for(var r in this.styles){var n=parseInt(r,10);n>e&&(this.styles[n+t]=i[n],i[n-t]||delete this.styles[n])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(e,t,i,r){var n,s={},o=!1,a=this._unwrappedTextLines[e].length===t;for(var l in i||(i=1),this.shiftLineStyles(e,i),this.styles[e]&&(n=this.styles[e][0===t?t:t-1]),this.styles[e]){var h=parseInt(l,10);h>=t&&(o=!0,s[h-t]=this.styles[e][l],a&&0===t||delete this.styles[e][l])}var c=!1;for(o&&!a&&(this.styles[e+i]=s,c=!0),c&&i--;i>0;)r&&r[i-1]?this.styles[e+i]={0:w(r[i-1])}:n?this.styles[e+i]={0:w(n)}:delete this.styles[e+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(e,t,i,r){this.styles||(this.styles={});var n=this.styles[e],s=n?w(n):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=t&&(n[a+i]=s[a],s[a-i]||delete n[a])}if(this._forceClearCache=!0,r)for(;i--;)Object.keys(r[i]).length&&(this.styles[e]||(this.styles[e]={}),this.styles[e][t+i]=w(r[i]));else if(n)for(var l=n[t?t-1:1];l&&i--;)this.styles[e][t+i]=w(l)},insertNewStyleBlock:function(e,t,i){for(var r=this.get2DCursorLocation(t,!0),n=[0],s=0,o=0;o0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,n[0],i),i=i&&i.slice(n[0]+1)),s&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+n[0],s),o=1;o0?this.insertCharStyleObject(r.lineIndex+o,0,n[o],i):i&&this.styles[r.lineIndex+o]&&i[0]&&(this.styles[r.lineIndex+o][0]=i[0]),i=i&&i.slice(n[o]+1);n[o]>0&&this.insertCharStyleObject(r.lineIndex+o,0,n[o],i)},setSelectionStartEndWithShift:function(e,t,i){i<=e?(t===e?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=e),this.selectionStart=i):i>e&&ie?this.selectionStart=e:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>e?this.selectionEnd=e:this.selectionEnd<0&&(this.selectionEnd=0)}}),T.util.object.extend(T.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(e){if(this.canvas){this.__newClickTime=+new Date;var t=e.pointer;this.isTripleClick(t)&&(this.fire("tripleclick",e),this._stopEvent(e.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=t,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(e){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===e.x&&this.__lastPointer.y===e.y},_stopEvent:function(e){e.preventDefault&&e.preventDefault(),e.stopPropagation&&e.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(e){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(e.e))},tripleClickHandler:function(e){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(e.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(e){!this.canvas||!this.editable||e.e.button&&1!==e.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(e.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(e){!this.canvas||!this.editable||e.e.button&&1!==e.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(e){if(this.__isMousedown=!1,!(!this.editable||this.group||e.transform&&e.transform.actionPerformed||e.e.button&&1!==e.e.button)){if(this.canvas){var t=this.canvas._activeObject;if(t&&t!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(e.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(e){var t=this.getSelectionStartFromPointer(e),i=this.selectionStart,r=this.selectionEnd;e.shiftKey?this.setSelectionStartEndWithShift(i,r,t):(this.selectionStart=t,this.selectionEnd=t),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(e){for(var t,i=this.getLocalPointer(e),r=0,n=0,s=0,o=0,a=0,l=0,h=this._textLines.length;l0&&(o+=this._textLines[l-1].length+this.missingNewlineOffset(l-1));n=this._getLineLeftOffset(a)*this.scaleX,t=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+n);for(var c=0,u=t.length;cs||o<0?0:1);return this.flipX&&(a=n-a),a>this._text.length&&(a=this._text.length),a}}),T.util.object.extend(T.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=T.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var e=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+e.top+"; left: "+e.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+e.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):T.document.body.appendChild(this.hiddenTextarea),T.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),T.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),T.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),T.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),T.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),T.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(T.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(e){if(this.isEditing){var t="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(e.keyCode in t)this[t[e.keyCode]](e);else{if(!(e.keyCode in this.ctrlKeysMapDown)||!e.ctrlKey&&!e.metaKey)return;this[this.ctrlKeysMapDown[e.keyCode]](e)}e.stopImmediatePropagation(),e.preventDefault(),e.keyCode>=33&&e.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(e){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:e.keyCode in this.ctrlKeysMapUp&&(e.ctrlKey||e.metaKey)&&(this[this.ctrlKeysMapUp[e.keyCode]](e),e.stopImmediatePropagation(),e.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(e){var t=this.fromPaste;if(this.fromPaste=!1,e&&e.stopPropagation(),this.isEditing){var i,r,n,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,l=this._text.length,h=a.length,c=h-l,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),_=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):h0&&(r+=(i=this.__charBounds[e][t-1]).left+i.width),r},getDownCursorOffset:function(e,t){var i=this._getSelectionForOffset(e,t),r=this.get2DCursorLocation(i),n=r.lineIndex;if(n===this._textLines.length-1||e.metaKey||34===e.keyCode)return this._text.length-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(s).length+a+1+this.missingNewlineOffset(n)},_getSelectionForOffset:function(e,t){return e.shiftKey&&this.selectionStart!==this.selectionEnd&&t?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(e,t){var i=this._getSelectionForOffset(e,t),r=this.get2DCursorLocation(i),n=r.lineIndex;if(0===n||e.metaKey||33===e.keyCode)return-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n-1,o),l=this._textLines[n].slice(0,s),h=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-l.length+(1-h)},_getIndexOnLine:function(e,t){for(var i,r,n=this._textLines[e],s=this._getLineLeftOffset(e),o=0,a=0,l=n.length;at){r=!0;var h=s-i,c=s,u=Math.abs(h-t);o=Math.abs(c-t)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",e)},moveCursorUp:function(e){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",e)},_moveCursorUpOrDown:function(e,t){var i=this["get"+e+"CursorOffset"](t,"right"===this._selectionDirection);t.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(e){var t="left"===this._selectionDirection?this.selectionStart+e:this.selectionEnd+e;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,t),0!==e},moveCursorWithoutShift:function(e){return e<0?(this.selectionStart+=e,this.selectionEnd=this.selectionStart):(this.selectionEnd+=e,this.selectionStart=this.selectionEnd),0!==e},moveCursorLeft:function(e){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",e)},_move:function(e,t,i){var r;if(e.altKey)r=this["findWordBoundary"+i](this[t]);else{if(!e.metaKey&&35!==e.keyCode&&36!==e.keyCode)return this[t]+="Left"===i?-1:1,!0;r=this["findLineBoundary"+i](this[t])}if(void 0!==typeof r&&this[t]!==r)return this[t]=r,!0},_moveLeft:function(e,t){return this._move(e,t,"Left")},_moveRight:function(e,t){return this._move(e,t,"Right")},moveCursorLeftWithoutShift:function(e){var t=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(t=this._moveLeft(e,"selectionStart")),this.selectionEnd=this.selectionStart,t},moveCursorLeftWithShift:function(e){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(e,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(e,"selectionStart")):void 0},moveCursorRight:function(e){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",e)},_moveCursorLeftOrRight:function(e,t){var i="moveCursor"+e+"With";this._currentCursorOpacity=1,t.shiftKey?i+="Shift":i+="outShift",this[i](t)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(e){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(e,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(e,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(e){var t=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(t=this._moveRight(e,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,t},removeChars:function(e,t){void 0===t&&(t=e+1),this.removeStyleFromTo(e,t),this._text.splice(e,t-e),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(e,t,i,r){void 0===r&&(r=i),r>i&&this.removeStyleFromTo(i,r);var n=T.util.string.graphemeSplit(e);this.insertNewStyleBlock(n,i,t),this._text=[].concat(this._text.slice(0,i),n,this._text.slice(r)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var e=T.util.toFixed,t=/ +/g;T.util.object.extend(T.Text.prototype,{_toSVG:function(){var e=this._getSVGLeftTopOffsets(),t=this._getSVGTextAndBg(e.textTop,e.textLeft);return this._wrapSVGTextAndBg(t)},toSVG:function(e){return this._createBaseSVGMarkup(this._toSVG(),{reviver:e,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(e){var t=this.getSvgTextDecoration(this);return[e.textBgRects.join(""),'\t\t",e.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(e,t){var i,r=[],n=[],s=e;this._setSVGBg(n);for(var o=0,a=this._textLines.length;o",T.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(e,t,i,r){var n,s,o,a,l,h=this.getHeightOfLine(t),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[t];r+=h*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,_=f.length-1;g<=_;g++)l=g===_||this.charSpacing,u+=f[g],o=this.__charBounds[t][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!l&&this._reSpaceAndTab.test(f[g])&&(l=!0),l||(n=n||this.getCompleteStyleDeclaration(t,g),s=this.getCompleteStyleDeclaration(t,g+1),l=this._hasStyleChangedForSvg(n,s)),l&&(a=this._getStyleDeclaration(t,g)||{},e.push(this._createTextCharSpan(u,a,i,r)),u="",n=s,i+=d,d=0)},_pushTextBgRect:function(t,i,r,n,s,o){var a=T.Object.NUM_FRACTION_DIGITS;t.push("\t\t\n')},_setSVGTextLineBg:function(e,t,i,r){for(var n,s,o=this._textLines[t],a=this.getHeightOfLine(t)/this.lineHeight,l=0,h=0,c=this.getValueOfPropertyAt(t,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(e){for(var t=0,i=0,r=0,n={},s=0;s0?(i=0,r++,t++):!this.splitByGrapheme&&this._reSpaceAndTab.test(e.graphemeText[r])&&s>0&&(i++,r++),n[s]={line:t,offset:i},r+=e.graphemeLines[s].length,i+=e.graphemeLines[s].length;return n},styleHas:function(e,i){if(this._styleMap&&!this.isWrapping){var r=this._styleMap[i];r&&(i=r.line)}return t.Text.prototype.styleHas.call(this,e,i)},isEmptyStyles:function(e){if(!this.styles)return!0;var t,i,r=0,n=!1,s=this._styleMap[e],o=this._styleMap[e+1];for(var a in s&&(e=s.line,r=s.offset),o&&(n=o.line===e,t=o.offset),i=void 0===e?this.styles:{line:this.styles[e]})for(var l in i[a])if(l>=r&&(!n||lr&&!p?(a.push(l),l=[],s=f,p=!0):s+=m,p||o||l.push(d),l=l.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>_&&(_=f);return v&&a.push(l),_+n>this.dynamicMinWidth&&(this.dynamicMinWidth=_-m+n),a},isEndOfWrapping:function(e){return!this._styleMap[e+1]||this._styleMap[e+1].line!==this._styleMap[e].line},missingNewlineOffset:function(e){return this.splitByGrapheme?this.isEndOfWrapping(e)?1:0:1},_splitTextIntoLines:function(e){for(var i=t.Text.prototype._splitTextIntoLines.call(this,e),r=this._wrapText(i.lines,this.width),n=new Array(r.length),s=0;s{},898:()=>{},245:()=>{}},L={};function P(e){var t=L[e];if(void 0!==t)return t.exports;var i=L[e]={exports:{}};return M[e](i,i.exports,P),i.exports}P.d=(e,t)=>{for(var i in t)P.o(t,i)&&!P.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},P.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var F={};(()=>{let e;P.d(F,{R:()=>e}),e="undefined"!=typeof document&&"undefined"!=typeof window?P(653).fabric:{version:"5.2.1"}})();var k=F.R; /*! * Dynamsoft JavaScript Library * @product Dynamsoft Camera Enhancer JS Edition * @website https://www.dynamsoft.com * @copyright Copyright 2022, Dynamsoft Corporation * @author Dynamsoft - * @version 2.3.2 (js 20220321) + * @version 3.0.0 (js 20220726) * @fileoverview Dynamsoft JavaScript Library for Camera Enhancer * More info on DCE JS: https://www.dynamsoft.com/camera-enhancer/docs/programming/javascript/?ver=latest - */ -function C(e,t,i,n){return new(i||(i=Promise))((function(o,r){function s(e){try{d(n.next(e))}catch(e){r(e)}}function a(e){try{d(n.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}d((n=n.apply(e,t||[])).next())}))}w._jsVersion="9.0.2",w._jsEditVersion="20220505",w._version=`loading...(JS ${w._jsVersion}.${w._jsEditVersion})`,w._license=d,w._sessionPassword=l,w.browserInfo=t,w._workerName=`dbr-${w._jsVersion}.browser.worker.js`,w._engineResourcePath=s,w._licenseServer=[],w._deviceFriendlyName="",w._isShowRelDecodeTimeInResults=!1,w._bWasmDebug=!1,w._bNeverShowDialog=!1,w.__bUseFullFeature=!0,w._nextTaskID=0,w._taskCallbackMap=new Map,w._pLoad=new class extends Promise{constructor(e){let t,i;super(((e,n)=>{t=e,i=n})),this._s="pending",this.resolve=e=>{this.isPending&&(f(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",i(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,f(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const i=await t;e===this._task&&this.resolve(i)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}},w._lastErrorCode=0,w._lastErrorString="",w._setWarnnedEx=new Set,w._defaultUIElementURL="@engineResourcePath/dbr.ui.html";const D="undefined"==typeof self;class b{constructor(){this._maxCvsSideLength=void 0,this._defaultMaxCvsSideLength=null,this.predefinedResolutions=[{width:160,height:120},{width:320,height:240},{width:480,height:360},{width:640,height:480},{width:800,height:600},{width:960,height:720},{width:1280,height:720},{width:1920,height:1080},{width:2560,height:1440},{width:3840,height:2160}],this.mapCameraResolutions=new Map,this._bWebGLSupported=!0,this._singleFrameMode=!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia),this._cvsSingleFrameMode=null,this._imgWidth=0,this._imgHeight=0,this._singleFrameModeIpt=null,this._clickIptSingleFrameMode=()=>{if(this.singleFrameMode){if(!this._singleFrameModeIpt){const e=document.createElement("input");this._singleFrameModeIpt=e,e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.addEventListener("change",(()=>C(this,void 0,void 0,(function*(){const t=e.files[0];e.value="";const i=yield(e=>C(this,void 0,void 0,(function*(){let t=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(t=yield createImageBitmap(e),t)return t}catch(t){}var n;return t||(i=yield(n=e,new Promise(((e,t)=>{let i=URL.createObjectURL(n),o=new Image;o.dbrObjUrl=i,o.src=i,o.onload=()=>{e(o)},o.onerror=e=>{t(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}})))),i})))(t),n=i instanceof HTMLImageElement?i.naturalWidth:i.width,o=i instanceof HTMLImageElement?i.naturalHeight:i.height;this._imgWidth=n,this._imgHeight=o,(e=>{if(!this._cvsSingleFrameMode){if(this._cvsSingleFrameMode=document.createElement("canvas"),this._cvsSingleFrameMode.className="cvs-single-frame-mode",this._cvsSingleFrameMode.addEventListener("click",this._clickIptSingleFrameMode),this._cvsSingleFrameMode.style.cursor="pointer",this._cvsSingleFrameMode.setAttribute("title","Take a photo"),!this._video)throw new Error("'video' is null.");this._video.after(this._cvsSingleFrameMode)}const t=this._cvsSingleFrameMode;t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.left="0",t.style.top="0",t.style.objectFit="contain",t.width==n&&t.height==o||(t.width=n,t.height=o);let i=t.getContext("2d");i.clearRect(0,0,t.width,t.height),i.drawImage(e,0,0)})(i),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e);const r=(e=>{const t=Date.now();if(0===n||0===o)return null;const i=this._scanRegion,r=this.getFrameSize(n,o,i,this.maxCvsSideLength);if(!r)return null;let s,a;s=n!==r.sWidth||o!==r.sHeight,a=r.sWidth!==r.dWidth||r.sHeight!==r.dHeight;const d=(()=>!(!this._bWebGLSupported||a))(),l={data:null,region:i?JSON.parse(JSON.stringify(i)):null,sx:r.sx,sy:r.sy,width:r.dWidth,height:r.dHeight,colorMode:null,timeSpent:null,timeStamp:null,isCropped:s,toCanvas:this.toCanvas,_bUseWebGL:null},h=this._getImageData(e,n,o,r,null,{targetColorMode:this.frameColorMode,bUseWebGL:d});if(!h)return null;const c=Date.now();return b._onLog&&b._onLog("DCE: _getVideoFrame(region?) END: "+c),l.data=h.data,l.colorMode=h.colorMode,l._bUseWebGL=h._bUseWebGL,l.timeSpent=c-t,l.timeStamp=c,l})(i),s=this.mapCameraEvents.get("singleFrameAcquired");for(let e of s)try{const t={data:new Uint8Array(r.data),region:JSON.parse(JSON.stringify(r.region)),sx:r.sx,sy:r.sy,width:r.width,height:r.height,colorMode:r.colorMode,timeSpent:r.timeSpent,timeStamp:r.timeStamp,isCropped:r.isCropped,toCanvas:r.toCanvas,_bUseWebGL:r._bUseWebGL};yield e(t)}catch(e){console.error(e)}})))),e.style.position="fixed",e.style.left="-1px",e.style.top="-1px",e.style.width="1px",e.style.height="1px",e.style.backgroundColor="transparent",e.style.color="transparent",document.body.appendChild(e)}this._singleFrameModeIpt.click()}},this.styleEls=[],this._frameColorMode=void 0,this._defaultFrameColorMode="RGBA",this.currentFSColorMode="rgba",this.ifReuseArrayBufferView=!1,this.maxVideoCvsLength=3,this.canvas=null,this.videoGlCvs=null,this.videoGl=null,this.glImgData=null,this.webglTexture=null,this.webglProgramInfo=null,this.webglBuffers=null,this.toCanvas=function(){const e=document.createElement("canvas");let t;if(e.width=this.width,e.height=this.height,"grey"===this.colorMode){t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;eC(this,void 0,void 0,(function*(){yield this.selectCamera(this._selCam.value),this._bOpen||this.stop()})),this._onResolutionSelChange=()=>C(this,void 0,void 0,(function*(){let e,t;if(this._selRsl&&-1!=this._selRsl.selectedIndex){let i=this._selRsl.options[this._selRsl.selectedIndex];e=i.getAttribute("data-width"),t=i.getAttribute("data-height")}yield this.setResolution(e,t),this._bOpen||this.stop()})),this._onCloseBtnClick=()=>{this.close(!0)},this._bOpen=!1,this.videoSrc=null,this.videoSettings={video:{width:{ideal:1280},height:{ideal:720},facingMode:{ideal:"environment"}}},this.iPlayRound=0,this.promisePlay=null,this._ifSaveLastUsedCamera=!1,this.ifSkipCameraInspection=!1,this._allCameras=[],this._currentCamera=null,this._videoTrack=null,this._lastDeviceId=void 0,this._vc_bPlayingVideoBeforeHide=!1,this._ev_documentHideEvent=()=>{"visible"===document.visibilityState?this._vc_bPlayingVideoBeforeHide&&("Firefox"==b.browserInfo.browser?this.play():this._video.play(),this._vc_bPlayingVideoBeforeHide=!1):this._video&&!this._video.paused&&(this._vc_bPlayingVideoBeforeHide=!0,this._video.pause())},this._video=null,this.videoFit="contain",this._cvsScanRegion=null,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=2,this._bShowScanRegionMask=!0,this._bShowScanRegionLaser=!1,this._scanRegion=null,this._arrScanRegionOverlays=[],this._cvsViewDecorator=null,this._decoratorType=[],this._decoratorArea=null,this._viewDecoratorInfo={rectangle:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},focus:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},crossline:{lineWidth:2,strokeStyle:"rgb(254,142,20)"},crosshair:{lineWidth:4,strokeStyle:"rgb(254,142,20)"}},this._croppingRegions=void 0,this._defaultCroppingRegions=[null],this.bIncreaseRegionIndexAuto=!0,this._croppingRegionIndex=0,this._loopInterval=void 0,this._defaultLoopInterval=0,this._maxNumberOfFramesInBuffer=void 0,this._defaultMaxNumberOfFramesInBuffer=1,this._frameQueue=[],this._bFetchingLoopStarted=!1,this._bStoppedByPause=!1,this._refreshInterval=void 0,this._defaultRefreshInterval=-1,this._updateCanvasTimeout=500,this.referenceConfigurationArray=[],this._onWindowResize=()=>{this._resizeTimeoutId&&clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=setTimeout((()=>{this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e)}),this._updateCanvasTimeout)},this.bDestroyed=!1,this.mapCameraEvents=new Map([["cameraOpen",[]],["cameraClose",[]],["cameraChange",[]],["resolutionChange",[]],["played",[]],["singleFrameAcquired",[]],["frameAddedToBuffer",[]]])}static getVersion(){return this._version}static detectEnvironment(){return C(this,void 0,void 0,(function*(){let e={wasm:"undefined"!=typeof WebAssembly&&("undefined"==typeof navigator||!(/Safari/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&/\(.+\s11_2_([2-6]).*\)/.test(navigator.userAgent))),worker:!("undefined"==typeof Worker),getUserMedia:!("undefined"==typeof navigator||!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia),camera:!1,browser:this.browserInfo.browser,version:this.browserInfo.version,OS:this.browserInfo.OS};if(e.getUserMedia)try{(yield navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e.camera=!0}catch(e){}return e}))}static set engineResourcePath(e){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");if(null==e&&(e="./"),D)b._engineResourcePath=e;else{let t=document.createElement("a");t.href=e,b._engineResourcePath=t.href}this._engineResourcePath.endsWith("/")||(b._engineResourcePath+="/")}static get engineResourcePath(){return this._engineResourcePath}static isStorageAvailable(e){let t;try{t=window[e];const i="__storage_test__";return t.setItem(i,i),t.removeItem(i),!0}catch(e){return e instanceof DOMException&&(22===e.code||1014===e.code||"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)&&t&&0!==t.length}}set maxCvsSideLength(e){if(e<=0)throw new Error("The 'maxCvsSideLength' should be greater than 0.");this._maxCvsSideLength=e}get maxCvsSideLength(){return void 0!==this._maxCvsSideLength?this._maxCvsSideLength:this.referenceConfigurationArray&&1===this.referenceConfigurationArray.length&&this.referenceConfigurationArray[0].hasOwnProperty("maxCvsSideLength")?this.referenceConfigurationArray[0].maxCvsSideLength:this._defaultMaxCvsSideLength}static set defaultUIElementURL(e){b._defaultUIElementURL=e}static get defaultUIElementURL(){var e;return null===(e=b._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",b.engineResourcePath)}getUIElement(){return this.UIElement}setUIElement(e){return C(this,void 0,void 0,(function*(){if(this._bOpen)throw new Error("It is not allowed to change the UIElement when the camera is open.");if("string"==typeof e||e instanceof String){if(!e.trim().startsWith("<")){let t=yield fetch(e);if(!t.ok)throw Error("setUIElement(elementOrUrl): Network Error: "+t.statusText);e=yield t.text()}if(!e.trim().startsWith("<"))throw Error("setUIElement(elementOrUrl): Can't get valid HTMLElement.");let t=document.createElement("div");t.innerHTML=e;for(let e=0;e','','',''].join(""),this._optGotRsl=this._optGotRsl||this._selRsl.options[0])):!this._optGotRsl&&t.classList.contains("dce-opt-gotResolution")?this._optGotRsl=t:!this._btnClose&&t.classList.contains("dce-btn-close")&&(this._btnClose=t);if(!this._video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'");this.singleFrameMode?(this._video&&(this._video.addEventListener("click",this._clickIptSingleFrameMode),this._video.style.cursor="pointer",this._video.setAttribute("title","Take a photo")),this._divScanArea&&(this._divScanArea.addEventListener("click",this._clickIptSingleFrameMode),this._divScanArea.style.cursor="pointer",this._divScanArea.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="")):this._bgLoading&&(this._bgLoading.style.display=""),this._selCam&&this._selCam.addEventListener("change",this._onCameraSelChange),this._selRsl&&this._selRsl.addEventListener("change",this._onResolutionSelChange),this._btnClose&&this._btnClose.addEventListener("click",this._onCloseBtnClick),document.addEventListener("visibilitychange",this._ev_documentHideEvent),window.addEventListener("resize",this._onWindowResize)}_unbindUI(){this.singleFrameMode?(this._video&&(this._video.removeEventListener("click",this._clickIptSingleFrameMode),this._video.style.cursor="",this._video.removeAttribute("title")),this._divScanArea&&(this._divScanArea.removeEventListener("click",this._clickIptSingleFrameMode),this._divScanArea.style.cursor="",this._divScanArea.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._bgLoading&&(this._bgLoading.style.display="none"),this._selCam&&this._selCam.removeEventListener("change",this._onCameraSelChange),this._selRsl&&this._selRsl.removeEventListener("change",this._onResolutionSelChange),this._btnClose&&this._btnClose.removeEventListener("click",this._onCloseBtnClick),this._cvsViewDecorator&&(this._cvsViewDecorator.removeEventListener("click",this._clickIptSingleFrameMode),this._cvsViewDecorator.style.cursor="",this._cvsViewDecorator.removeAttribute("title"));for(let e of this._arrScanRegionOverlays)e&&(e.removeEventListener("click",this._clickIptSingleFrameMode),e.style.cursor="",e.removeAttribute("title"));this.hideScanRegionLaser(),this.hideViewDecorator(),this.hideScanRegionOverlays(),this._video&&(this._video.onloadedmetadata=null,this._video.remove()),this._video=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._divScanArea=null,this._divScanLight=null,this._cvsScanRegion&&(this._cvsScanRegion.remove(),this._cvsScanRegion=null),this._singleFrameModeIpt&&(this._singleFrameModeIpt.remove(),this._singleFrameModeIpt=null),this._cvsSingleFrameMode&&(this._cvsSingleFrameMode.remove(),this._cvsSingleFrameMode=null),document.removeEventListener("visibilitychange",this._ev_documentHideEvent),window.removeEventListener("resize",this._onWindowResize)}set bOpen(e){if(this._bOpen=e,e){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e);this._bShowScanRegionMask?this.showScanRegionMask():this.hideScanRegionMask(),this._bShowScanRegionLaser?this.showScanRegionLaser():this.hideScanRegionLaser(),this.showViewDecorator(),this._cvsViewDecorator&&(this._cvsViewDecorator.addEventListener("click",this._clickIptSingleFrameMode),this._cvsViewDecorator.style.cursor="pointer",this._cvsViewDecorator.setAttribute("title","Take a photo")),this.showScanRegionOverlays();for(let e of this._arrScanRegionOverlays)e&&(e.addEventListener("click",this._clickIptSingleFrameMode),e.style.cursor="pointer",e.setAttribute("title","Take a photo"))}}_assertOpen(){if(!this._bOpen)throw Error("The camera is not open.")}set ifSaveLastUsedCamera(e){e?b.isStorageAvailable("localStorage")?this._ifSaveLastUsedCamera=!0:(this._ifSaveLastUsedCamera=!1,console.warn("Local storage is unavailable")):this._ifSaveLastUsedCamera=!1}get ifSaveLastUsedCamera(){return this._ifSaveLastUsedCamera}get video(){return this._video}setVideoFit(e){if(e=e.toLowerCase(),!["contain","cover"].includes(e))throw new Error(`It is not allowed to set '${e}'.`);if(this.videoFit=e,this._video&&(this._video.style.objectFit=e,!this.singleFrameMode)){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e)}}getVideoFit(){return this.videoFit}set ifShowScanRegionMask(e){this._bShowScanRegionMask=e,e?this.showScanRegionMask():this.hideScanRegionMask()}get ifShowScanRegionMask(){return this._bShowScanRegionMask}showScanRegionMask(){this._cvsScanRegion&&"none"==this._cvsScanRegion.style.display&&(this._cvsScanRegion.style.display="")}hideScanRegionMask(){this._cvsScanRegion&&(this._cvsScanRegion.style.display="none")}set ifShowScanRegionLaser(e){this._bShowScanRegionLaser=e,e?this.showScanRegionLaser():this.hideScanRegionLaser()}get ifShowScanRegionLaser(){return this._bShowScanRegionLaser}showScanRegionLaser(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="")}hideScanRegionLaser(){this._divScanLight&&(this._divScanLight.style.display="none")}_checkValidRegion(e){return!(null!==e&&(!e||!(e.hasOwnProperty("regionLeft")&&e.hasOwnProperty("regionTop")&&e.hasOwnProperty("regionRight")&&e.hasOwnProperty("regionBottom")&&e.hasOwnProperty("regionMeasuredByPercentage"))||e.regionLeft<0||e.regionTop<0||e.regionRight<0||e.regionBottom<0||e.regionMeasuredByPercentage&&(e.regionLeft>100||e.regionTop>100||e.regionRight>100||e.regionBottom>100)))}set scanRegion(e){if(!this._checkValidRegion(e))throw new Error("The region is invalid.");this._scanRegion=JSON.parse(JSON.stringify(e)),this._updateScanRegionCanvas(),this._updateScanAreaDiv();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e)}setScanRegion(e){this.scanRegion=e}getScanRegion(){return JSON.parse(JSON.stringify(this._scanRegion))}addScanRegionOverlayCanvas(){this._assertOpen();const e=document.createElement("canvas");if(e.className="cvs-scan-region-overlay-"+this._arrScanRegionOverlays.length,this.singleFrameMode&&(e.addEventListener("click",this._clickIptSingleFrameMode),e.style.cursor="pointer",e.setAttribute("title","Take a photo")),this._updateScanRegionOverlay(e),this._arrScanRegionOverlays.length>0){const t=this._arrScanRegionOverlays.length;this._arrScanRegionOverlays[t-1].after(e)}else if(this._cvsScanRegion)this._cvsScanRegion.before(e);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(e);else{if(!this._video)throw new Error("'video' is null.");this._video.after(e)}return this._arrScanRegionOverlays.push(e),e}_updateScanRegionOverlay(e){if(!e)return;let t,i,n;if(this.singleFrameMode)t=this._imgWidth,i=this._imgHeight,n="contain";else{if(!this._video)return;t=this._video.videoWidth,i=this._video.videoHeight,n=this.getVideoFit()}if(t<=0||i<=0)return e.width=0,void(e.height=0);const o=this._getRegionInPixels(t,i,this._scanRegion),r=this.getFrameSize(t,i,this._scanRegion,this.maxCvsSideLength).dWidth,s=this.getFrameSize(t,i,this._scanRegion,this.maxCvsSideLength).dHeight;e.width==r&&e.height==s||(e.width=r,e.height=s);const a=window.getComputedStyle(this._video),d=parseFloat(a.width),l=parseFloat(a.height),h=d/l,c=t/i;let _,u,g,f,m=1;if("contain"===n)h{const e=parseFloat(window.getComputedStyle(this._video).width),o=parseFloat(window.getComputedStyle(this._video).height);let r,s={regionBottom:i,regionRight:t,regionLeft:0,regionTop:0,regionMeasuredByPercentage:!1};return"cover"===n?e/othis.maxNumberOfFramesInBuffer;)this._frameQueue.shift()}get maxNumberOfFramesInBuffer(){return void 0!==this._maxNumberOfFramesInBuffer?this._maxNumberOfFramesInBuffer:this.referenceConfigurationArray&&1===this.referenceConfigurationArray.length&&this.referenceConfigurationArray[0].hasOwnProperty("maxNumberOfFramesInBuffer")?this.referenceConfigurationArray[0].maxNumberOfFramesInBuffer:this._defaultMaxNumberOfFramesInBuffer}get numberOfFramesInBuffer(){return this._frameQueue.length}set refreshInterval(e){this._refreshInterval=e}get refreshInterval(){return void 0!==this._refreshInterval?this._refreshInterval:this.referenceConfigurationArray&&1===this.referenceConfigurationArray.length&&this.referenceConfigurationArray[0].hasOwnProperty("refreshInterval")?this.referenceConfigurationArray[0].refreshInterval:this._defaultRefreshInterval}isContextDestroyed(){return this.bDestroyed}static createInstance(e){return C(this,void 0,void 0,(function*(){let t=new b;("string"==typeof e||e instanceof String)&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return yield t.setUIElement(b.defaultUIElementURL),this._hasEngineResourceLoaded=!0,t}))}play(e,t,i){return C(this,void 0,void 0,(function*(){if(this._video&&this.videoSrc){yield new Promise(((e,t)=>{this._video.onloadedmetadata=()=>C(this,void 0,void 0,(function*(){this._video&&(this._video.onloadedmetadata=null,yield this._video.play(),e())})),"string"==typeof this.videoSrc||this.videoSrc instanceof String?this._video.src=this.videoSrc:this._video.srcObject=this.videoSrc,setTimeout((()=>t(new Error("Failed to play video. Timeout."))),4e3)}));let e={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};const t=this.mapCameraEvents.get("played");for(let i of t){const t=JSON.parse(JSON.stringify(e));setTimeout((()=>i(t)),0)}return e}if(this.singleFrameMode)return this._clickIptSingleFrameMode(),{width:0,height:0,deviceId:null};if(!this._video)return null;const n=++this.iPlayRound;let o=null,r=0,s=0;return this._currentCamera&&(o=this._currentCamera.deviceId),this._video&&(r=this._video.videoWidth,s=this._video.videoHeight),this.promisePlay&&(yield this.promisePlay,nC(this,void 0,void 0,(function*(){var n;try{this._video&&this._video.srcObject&&this.stop(),b._onLog&&b._onLog("DCE: ======before video========");const a=()=>{if(!this._video)throw _&&_.getTracks().forEach((e=>{e.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null.")},d=this.getVideoSettings();let l;"boolean"==typeof d.video&&(d.video={});const h=["rear","back","rück","arrière","trasera","trás","traseira","posteriore","后面","後面","背面","后置","後置","背置","задней","الخلفية","후","arka","achterzijde","หลัง","baksidan","bagside","sau","bak","tylny","takakamera","belakang","אחורית","πίσω","spate","hátsó","zadní","darrere","zadná","задня","stražnja","belakang","बैक"],c=()=>{for(let e of this._allCameras){let t=e.label.toLowerCase();if(t&&h.some((e=>-1!=t.indexOf(e)))&&/\b0(\b)?/.test(t)){delete d.video.facingMode,d.video.deviceId={ideal:e.deviceId};break}}d.video.deviceId||-1==["Android","HarmonyOS"].indexOf(b.browserInfo.OS)||(delete d.video.facingMode,d.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})};if(e)delete d.video.facingMode,d.video.deviceId={exact:e};else if(d.video.deviceId);else if(this._lastDeviceId)delete d.video.facingMode,d.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&b.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete d.video.facingMode,d.video.deviceId={exact:window.localStorage.getItem("dce_last_camera_id")};const y=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),E=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));y&&E&&(d.video.width=y,d.video.height=E)}else if(this.ifSkipCameraInspection);else if(d.video.facingMode){if(yield this.getAllCameras(),!this._video)return null;let T=d.video.facingMode;T instanceof Array&&T.length&&(T=T[0]),T=T.exact||T.ideal||T,"environment"===T&&(l=!!d.video.facingMode,c())}let _;t&&(d.video.width={ideal:t}),i&&(d.video.height={ideal:i}),b._onLog&&b._onLog("DCE: ======try getUserMedia========");let u,g=[0,500],f=null,m=null;function p(e){return C(this,void 0,void 0,(function*(){for(let t of g){a(),t&&(yield new Promise((e=>setTimeout(e,t)))),a();{const t=e.video.deviceId;m=t?t.exact||t.ideal||t:null}try{b._onLog&&b._onLog("DCE: ask "+JSON.stringify(e)),_=yield navigator.mediaDevices.getUserMedia(e),a();break}catch(e){f=e,b._onLog&&b._onLog("DCE: "+e.message||e)}}}))}if(yield p(d),_||(b._onLog&&b._onLog("DCE: ======try getUserMedia again========"),u=JSON.parse(JSON.stringify(d)),"object"==typeof u.video&&("iPhone"==b.browserInfo.OS?(t>=1280||i>=1280?u.video.width=1280:t>=640||i>=640?u.video.width=640:(t<640||i<640)&&(u.video.width=320),delete u.video.height):l&&!d.video.deviceId?(delete u.video.facingMode,this._allCameras.length&&(u.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):u.video=!0),b._onLog&&b._onLog("DCE: "+u),yield p(u)),_||(g=[1e3,2e3],yield p(d)),_||(yield p(u)),!_)throw f;const v=()=>{const e=_.getVideoTracks();let t,i;if(e.length&&(t=this._videoTrack=e[0]),this._video&&t){const e=t.getSettings();if(e)for(let n of this._allCameras)if(e.deviceId===n.deviceId){n._checked=!0,n.label=t.label,i=n;break}if(!i&&m)for(let e of this._allCameras)if(m==e.deviceId){t.label&&(e._checked=!0,e.label=t.label),i=e;break}}this._currentCamera=i};if(yield this.getAllCameras(),a(),l){v(),c();let w=d.video.deviceId;w&&(w=w.exact||w.ideal||w);let D=null===(n=this._currentCamera)||void 0===n?void 0:n.deviceId;!w||D&&w==D||(_.getTracks().forEach((e=>{e.stop()})),g=[0,500,1e3,2e3],yield p(d))}a();const A=()=>C(this,void 0,void 0,(function*(){b._onLog&&b._onLog("======play video========"),yield new Promise(((e,t)=>{a(),this._video.onloadedmetadata=()=>C(this,void 0,void 0,(function*(){a(),this._video.onloadedmetadata=null,yield this._video.play(),e()})),this._video.srcObject=_,setTimeout((()=>t(new Error("Failed to play video. Timeout."))),4e3)}))}));yield A(),a(),b._onLog&&b._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const R=this._video.videoWidth+"x"+this._video.videoHeight;this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",this._video.videoWidth),this._optGotRsl.setAttribute("data-height",this._video.videoHeight),this._optGotRsl.innerText=R,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),b._onLog&&b._onLog("DCE: got "+R),v(),a(),this._renderSelCameraInfo();const S={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};S.deviceId&&(this._lastDeviceId=S.deviceId,this.ifSaveLastUsedCamera&&b.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),d.video.width&&d.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(d.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(d.video.height)))));const I=this.mapCameraEvents.get("played");for(let M of I){const L=JSON.parse(JSON.stringify(S));setTimeout((()=>M(L)),0)}if(o&&o!=S.deviceId){const O=this.mapCameraEvents.get("cameraChange");for(let F of O){const B=JSON.parse(JSON.stringify(S));setTimeout((()=>F(B)),0)}}if(r&&s&&(r!=S.width||s!=S.height)){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let P of this._arrScanRegionOverlays)P&&this._updateScanRegionOverlay(P);const N=this.mapCameraEvents.get("resolutionChange");for(let x of N){const V=JSON.parse(JSON.stringify(S));setTimeout((()=>x(V)),0)}}return this.promisePlay=null,S}catch(k){throw this.promisePlay=null,k}})))(),yield this.promisePlay)}))}resume(){return C(this,void 0,void 0,(function*(){this._assertOpen(),yield this.play(),this._bStoppedByPause&&(this._bStoppedByPause=!1,this.startFetchingLoop()),this._bShowScanRegionLaser&&this.showScanRegionLaser()}))}pause(){this._bOpen||console.warn("The camera is not open."),this._video&&this._video.pause(),this._bFetchingLoopStarted&&(this.stopFetchingLoop(),this._bStoppedByPause=!0),this._bShowScanRegionLaser&&this.hideScanRegionLaser()}close(e){if(!this._video)return;this.stop(),this._unbindUI(),e&&(this.UIElement.style.display="none"),this.stopFetchingLoop(),this.bOpen=!1;const t=this.mapCameraEvents.get("cameraClose");for(let e of t){const t={width:0,height:0,deviceId:null};setTimeout((()=>e(t)),0)}}open(e){return C(this,void 0,void 0,(function*(){this._bindUI(),e&&(this.UIElement.parentNode||(this.UIElement.style.position="fixed",this.UIElement.style.left="0",this.UIElement.style.top="0",document.body.append(this.UIElement)),"none"==this.UIElement.style.display&&(this.UIElement.style.display=""));let t=yield this.play();this.bOpen=!0;const i=this.mapCameraEvents.get("cameraOpen");for(let e of i){const i=JSON.parse(JSON.stringify(t));setTimeout((()=>e(i)),0)}return t}))}stop(){this._video&&this._video.srcObject&&(b._onLog&&b._onLog("DCE: ======stop video========"),this._video.srcObject.getTracks().forEach((e=>{e.stop()})),this._video.srcObject=null,this._videoTrack=null,this._currentCamera=null),this._video&&this.videoSrc&&(b._onLog&&b._onLog("DCE: ======stop existing video========"),this._video.pause(),this._video.currentTime=0),this._bgLoading&&(this._bgLoading.style.animationPlayState=""),this._frameQueue.length=0}getAllCameras(){return C(this,void 0,void 0,(function*(){let e=yield navigator.mediaDevices.enumerateDevices();if(!e[0].deviceId){let t=yield navigator.mediaDevices.getUserMedia({video:!0});e=yield navigator.mediaDevices.enumerateDevices(),t.getTracks().forEach((e=>{e.stop()})),t=null}const t=[],i=[];if(this._allCameras)for(let e of this._allCameras)e._checked&&i.push(e);for(let n=0;n{const i=this.mapCameraResolutions.get(e);if(!i||!i.length)return!1;for(let e of i)if(e[0]===t.width&&e[1]===t.height)return!0;return!1},n=(e,t,i)=>C(this,void 0,void 0,(function*(){const n={video:{deviceId:{exact:e},width:{ideal:t},height:{ideal:i}}};let o=null;try{o=yield navigator.mediaDevices.getUserMedia(n)}catch(n){return null}if(!o)return null;const r=o.getVideoTracks();let s=null;try{const e=r[0].getSettings();s={width:e.width,height:e.height}}catch(n){const e=document.createElement("video");e.srcObject=o,s={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return r.forEach((e=>{e.stop()})),s}));if(!this._bOpen){const o=this.videoSettings.video.deviceId;if(!o)return null;if(t=o.hasOwnProperty("exact")?this.videoSettings.video.deviceId.exact:o.hasOwnProperty("ideal")?this.videoSettings.video.deviceId.ideal:this.videoSettings.video.deviceId,!t)return null;let r=this.mapCameraResolutions.get(t);if(r&&!e)return this.mapCameraResolutions.get(t);this.mapCameraResolutions.set(t,[]),r=this.mapCameraResolutions.get(t);for(let e of this.predefinedResolutions){const o=yield n(t,e.width,e.height);o&&!i(t,o)&&r.push([o.width,o.height])}return r}if(this._currentCamera){t=this._currentCamera.deviceId;let n=this.mapCameraResolutions.get(t);if(n&&!e)return this.mapCameraResolutions.get(t);this.mapCameraResolutions.set(t,[]),n=this.mapCameraResolutions.get(t);const o=this.getConstraints();for(let e of this.predefinedResolutions){yield this._videoTrack.applyConstraints({width:{ideal:e.width},height:{ideal:e.height}});const o=this._videoTrack.getSettings(),r={width:o.width,height:o.height};i(t,r)||n.push([r.width,r.height])}return yield this._videoTrack.applyConstraints(o),n}return null}))}on(e,t){if(!this.mapCameraEvents.has(e))throw new Error(`Event '${e}' is not exists.`);const i=this.mapCameraEvents.get(e);i.includes(t)||i.push(t)}off(e,t){if(!this.mapCameraEvents.has(e))throw new Error(`Event '${e}' is not exists.`);const i=this.mapCameraEvents.get(e),n=i.indexOf(t);-1!==n&&i.splice(n,1)}getVideoSettings(){return JSON.parse(JSON.stringify(this.videoSettings))}updateVideoSettings(e){return this.videoSettings=JSON.parse(JSON.stringify(e)),this._lastDeviceId=null,this._bOpen?this.play():Promise.resolve()}isOpen(){return this._bOpen}getCapabilities(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOnTorch()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error('"_videoTrack" is null.');return this._videoTrack.getCapabilities?this._videoTrack.getCapabilities():{}}getCameraSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCameraSettings()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error('"_videoTrack" is null.');return this._videoTrack.getSettings()}getConstraints(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getConstraints()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error('"_videoTrack" is null.');return this._videoTrack.getConstraints()}applyConstraints(e){return C(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'applyConstraints()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error('"_videoTrack" is null.');if(!this._videoTrack.applyConstraints)throw Error("Not supported.");return yield this._videoTrack.applyConstraints(e)}))}turnOnTorch(){return C(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOnTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return yield this._videoTrack.applyConstraints({advanced:[{torch:!0}]});throw Error("Not supported.")}))}turnOffTorch(){return C(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOffTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return yield this._videoTrack.applyConstraints({advanced:[{torch:!1}]});throw Error("Not supported.")}))}setColorTemperature(e){return C(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setColorTemperature()' is unavailable in singleFrameMode.");let t=this.getCapabilities().colorTemperature;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),yield this._videoTrack.applyConstraints({advanced:[{colorTemperature:e}]})}))}setExposureCompensation(e){return C(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setExposureCompensation()' is unavailable in singleFrameMode.");let t=this.getCapabilities().exposureCompensation;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),yield this._videoTrack.applyConstraints({advanced:[{exposureCompensation:e}]})}))}setZoom(e){return C(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setZoom()' is unavailable in singleFrameMode.");let t=this.getCapabilities().zoom;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),yield this._videoTrack.applyConstraints({advanced:[{zoom:e}]})}))}setFrameRate(e){return C(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFrameRate()' is unavailable in singleFrameMode.");let t=this.getCapabilities().frameRate;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),yield this._videoTrack.applyConstraints({width:{ideal:Math.max(this._video.videoWidth,this._video.videoHeight)},frameRate:e})}))}getFrameRate(){return this.getCameraSettings().frameRate}setFocus(e,t){return C(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFocus()' is unavailable in singleFrameMode.");const i=this.getCapabilities().focusMode,n=this.getCapabilities().focusDistance;if(!i||!i.includes(e)||!n)throw Error("Not supported.");return t?(tn.max&&(t=n.max),yield this._videoTrack.applyConstraints({advanced:[{focusMode:e,focusDistance:t}]})):yield this._videoTrack.applyConstraints({advanced:[{focusMode:e}]})}))}getFocus(){const e=this.getCameraSettings().focusMode;return"continuous"===e?{mode:e}:{mode:e,distance:this.getCameraSettings().focusDistance}}getFrameSize(e,t,i,n){if(!e||!t)return null;let o,r,s,a,d=e,l=t;const h={regionLeft:0,regionTop:0,regionRight:d,regionBottom:l,regionMeasuredByPercentage:!1};i?(i.regionMeasuredByPercentage?(h.regionLeft=i.regionLeft*d/100,h.regionTop=i.regionTop*l/100,h.regionRight=i.regionRight*d/100,h.regionBottom=i.regionBottom*l/100):(h.regionLeft=i.regionLeft,h.regionTop=i.regionTop,h.regionRight=i.regionRight,h.regionBottom=i.regionBottom),o=h.regionLeft,r=h.regionTop,d=Math.round(h.regionRight-h.regionLeft),l=Math.round(h.regionBottom-h.regionTop)):(o=0,r=0);const c=Math.max(d,l);if(n&&n>0&&c>n){const e=n/c;d>l?(s=n,a=Math.round(l*e)):(s=Math.round(d*e),a=n)}else s=d,a=l;return s<=0||a<=0?null:{sx:o,sy:r,sWidth:d,sHeight:l,dWidth:s,dHeight:a}}getFrame(){if(this.singleFrameMode)throw Error("'getFrame()' is unavailable in singleFrameMode.");if(this._assertOpen(),this.singleFrameMode)throw new Error("'getFrame()' is unavailable in singleFrameMode.");return this._getVideoFrame(this._scanRegion)}_getVideoFrame(e,t){if(this.bDestroyed)throw Error("The 'CameraEnhancer' instance has been destroyed.");if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getVideoFrame()' is unavailable in singleFrameMode.");const i=Date.now();b._onLog&&b._onLog("DCE: _getVideoFrame(region?) START: "+i);const n=this._video.videoWidth,o=this._video.videoHeight;if(0===n||0===o)return null;const r=this.getFrameSize(n,o,e,this.maxCvsSideLength);if(!r)return null;let s,a;s=n!==r.sWidth||o!==r.sHeight,a=r.sWidth!==r.dWidth||r.sHeight!==r.dHeight;const d=(()=>!(!this._bWebGLSupported||a))(),l={data:null,region:e?JSON.parse(JSON.stringify(e)):null,sx:r.sx,sy:r.sy,width:r.dWidth,height:r.dHeight,colorMode:null,timeSpent:null,timeStamp:null,isCropped:s,toCanvas:this.toCanvas,_bUseWebGL:null},h=this._getImageData(this._video,n,o,r,t,{targetColorMode:this.frameColorMode,bUseWebGL:d});if(!h)return null;const c=Date.now();return b._onLog&&b._onLog("DCE: _getVideoFrame(region?) END: "+c),l.data=h.data,l.colorMode=h.colorMode,l._bUseWebGL=h._bUseWebGL,l.timeSpent=c-i,l.timeStamp=c,l}_getImageData(e,t,i,n,o,r){if(this.bDestroyed)throw Error("The 'CameraEnhancer' instance has been destroyed.");if(!t||!i)return null;b._onLog&&b._onLog("DCE: _getImageData() START: "+Date.now());const{sx:s,sy:a,sWidth:d,sHeight:l,dWidth:h,dHeight:c}=n;let _;if(_=r&&r.targetColorMode?r.targetColorMode.toLowerCase():"rgba",r&&r.bUseWebGL){this.videoGlCvs||(this.videoGlCvs=document.createElement("canvas"));const d=this.videoGlCvs;d.width==t&&d.height==i||(d.width=t,d.height=i,this.videoGl&&this.videoGl.viewport(0,0,t,i));const l=this.videoGl||d.getContext("webgl",{antialias:!1})||d.getContext("experimental-webgl",{antialias:!1});if(!l){this.videoGl=null,this._bWebGLSupported=!1;let s=null;return r?(s=JSON.parse(JSON.stringify(r)),s.bUseWebGL=!1):s={bUseWebGL:!1},this._getImageData(e,t,i,n,o,s)}if(l.enable(l.SCISSOR_TEST),l.scissor(s,a,h,c),!this.videoGl||_!==this.currentFSColorMode){this.videoGl=l;const e=e=>{const t=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,t),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,1,1,-1,1]),e.STATIC_DRAW);const i=e.createBuffer();return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,i),e.bufferData(e.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,0,2,3]),e.STATIC_DRAW),{position:t,indices:i}},t=e=>{const t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),t},i=(e,t,i)=>{const o=n(e,e.VERTEX_SHADER,t),r=n(e,e.FRAGMENT_SHADER,i),s=e.createProgram();return e.attachShader(s,o),e.attachShader(s,r),e.linkProgram(s),e.getProgramParameter(s,e.LINK_STATUS)?s:(alert("Unable to initialize the shader program: "+e.getProgramInfoLog(s)),null)},n=(e,t,i)=>{const n=e.createShader(t);return e.shaderSource(n,i),e.compileShader(n),e.getShaderParameter(n,e.COMPILE_STATUS)?n:(alert("An error occurred compiling the shaders: "+e.getShaderInfoLog(n)),e.deleteShader(n),null)},o="\n attribute mediump vec2 aVertexPosition;\n varying mediump vec2 vDirection;\n \n void main( void )\n {\n gl_Position = vec4(aVertexPosition, 1.0, 1.0) * 2.0;\n vDirection = aVertexPosition;\n }\n ";let r;r=["rgba","rbga","grba","gbra","brga","bgra"].includes(_)?_.slice(0,3):"rgb";const s=i(l,o,`\n precision mediump float;\n\n varying mediump vec2 vDirection;\n uniform sampler2D uSampler;\n uniform lowp float uColorFactor;\n \n void main(void)\n {\n vec4 sample = texture2D(uSampler, vec2(vDirection.x * 0.5 + 0.5, vDirection.y * 0.5 + 0.5));\n lowp float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${r} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `);this.webglProgramInfo={program:s,attribLocations:{vertexPosition:l.getAttribLocation(s,"aVertexPosition")},uniformLocations:{uSampler:l.getUniformLocation(s,"uSampler"),uColorFactor:l.getUniformLocation(s,"uColorFactor")}},this.webglBuffers=e(l),this.webglTexture=t(l),this.currentFSColorMode=_}const u=(e,t,i)=>{const n=e.RGBA,o=e.RGBA,r=e.UNSIGNED_BYTE;e.bindTexture(e.TEXTURE_2D,t),e.texImage2D(e.TEXTURE_2D,0,n,o,r,i)},g=(e,t,i,n)=>{e.clearColor(0,0,0,1),e.clearDepth(1),e.enable(e.DEPTH_TEST),e.depthFunc(e.LEQUAL),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,i.indices),e.useProgram(t.program);{const n=2,o=e.FLOAT,r=!1,s=0,a=0;e.bindBuffer(e.ARRAY_BUFFER,i.position),e.vertexAttribPointer(t.attribLocations.vertexPosition,n,o,r,s,a),e.enableVertexAttribArray(t.attribLocations.vertexPosition)}e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,n),e.uniform1i(t.uniformLocations.uSampler,0),e.uniform1f(t.uniformLocations.uColorFactor,"grey"===_||"grey32"===_?1:0);const o=e.UNSIGNED_SHORT;e.drawElements(e.TRIANGLES,6,o,0)};let f;if(u(l,this.webglTexture,e),g(l,this.webglProgramInfo,this.webglBuffers,this.webglTexture),o){if(o.length=this.croppingRegions.length||this._croppingRegionIndex<0)throw new Error("The 'croppingRegionIndex' is out of bounds.");e=this.croppingRegions[this._croppingRegionIndex],this.bIncreaseRegionIndexAuto&&++this._croppingRegionIndex>=this.croppingRegions.length&&(this._croppingRegionIndex=0)}return e}_fetchingLoop(e){if(this.bDestroyed)return void this.stopFetchingLoop();if(!this._bOpen||!this.isFetchingLoopStarted())return void this.stopFetchingLoop();if(this._video.paused)return b._onLog&&b._onLog("DCE: Video is paused. Ask in 1s."),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),void(this._frameLoopTimeoutId=setTimeout((()=>{this._fetchingLoop(!0)}),1e3));const t=()=>{b._onLog&&b._onLog("DCE: start fetching a frame: "+Date.now());const e=this.getCurrentRegion();let t=this._getVideoFrame(e);if(!t)return void(b._onLog&&b._onLog("DCE: get a invalid frame, abandon it: "+Date.now()));for(;this._frameQueue&&this._frameQueue.length>=this.maxNumberOfFramesInBuffer;)this._frameQueue.shift();this._frameQueue.push(t),b._onLog&&b._onLog("DCE: finish fetching a frame: "+Date.now());const i=this.mapCameraEvents.get("frameAddedToBuffer");for(let e of i)setTimeout(e,0)},i=()=>{this._frameLoopTimeoutId2&&clearTimeout(this._frameLoopTimeoutId2),this.refreshInterval<=0||(this._frameLoopTimeoutId2=setTimeout((()=>{this.bDestroyed?this.stopFetchingLoop():this._bOpen&&this.isFetchingLoopStarted()?this._video.paused?this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId):(b._onLog&&b._onLog("DCE: second timeout executes: "+Date.now()),t(),i()):this.stopFetchingLoop()}),this.refreshInterval))};e&&(this._frameQueue.length0&&i()):this.refreshInterval>0?(t(),i()):0===this.refreshInterval?t():this.refreshInterval),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameLoopTimeoutId=setTimeout((()=>{this._fetchingLoop(!0)}),this.loopInterval)}startFetchingLoop(){if(this.bDestroyed)throw Error("The DCE instance has been destroyed.");if(this._assertOpen(),this.singleFrameMode)throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");if(this._video.paused)throw Error("The video is paused.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,b._onLog&&b._onLog("start fetching loop: "+Date.now()),this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(b._onLog&&b._onLog("stop fetching loop: "+Date.now()),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameQueue.length=0,this._bFetchingLoopStarted=!1)}getFrameFromBuffer(e){return this._frameQueue&&this._frameQueue.length?e?e{if(!D&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),b._defaultUIElementURL="@engineResourcePath/dce.ui.html";class M extends w{constructor(){super(),this.bFilterRegionInJs=!0,this._onCameraSelChange=()=>{},this._onResolutionSelChange=()=>{},this._onCloseBtnClick=()=>{},this._onPlayed=null}static get version(){return this._version+`(DCE ${b.getVersion()})`}getUIElement(){return this.dce.getUIElement()}async setUIElement(e){await this.dce.setUIElement(e)}get singleFrameMode(){return this.dce.singleFrameMode}set singleFrameMode(e){this.dce.singleFrameMode=e,e&&(this.dce.ifShowScanRegionLaser=!1,(async()=>{let e=await this.getScanSettings();e.oneDTrustFrameCount=1,await this.updateScanSettings(e)})())}get onUnduplicatedRead(){return this.onUniqueRead}set onUnduplicatedRead(e){this.onUniqueRead=e}_assertOpen(){if(!this.dce.isOpen())throw Error("The scanner is not open.")}set regionMaskFillStyle(e){this.dce.setScanRegionMaskStyle({fillStyle:e})}get regionMaskFillStyle(){return this.dce.regionMaskFillStyle}set regionMaskStrokeStyle(e){this.dce.setScanRegionMaskStyle({strokeStyle:e})}get regionMaskStrokeStyle(){return this.dce.regionMaskStrokeStyle}set regionMaskLineWidth(e){this.dce.setScanRegionMaskStyle({lineWidth:e})}get regionMaskLineWidth(){return this.dce.regionMaskLineWidth}set region(e){this._region=e,this.dce&&(e?e instanceof Array||this.dce.setScanRegion(e):this.dce.setScanRegion(null)),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e,this.dce.frameColorMode=e?"rgba":"grey"}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}async createDCEInstance(){this.dce||(w._onLog&&w._onLog("createDCEInstance()"),b.defaultUIElementURL=null,this.dce=await b.createInstance(),this.dce.refreshInterval=200,this.dce.frameColorMode="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this.dce.on("cameraChange",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("resolutionChange",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("cameraClose",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1})),this.dce.on("singleFrameAcquired",(async e=>{if(!e)return;if(!e.data)return;let t;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,colorMode:e.colorMode,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{data:i,region:n,sx:o,sy:r,width:s,height:a,colorMode:d,timeStamp:l}=e,h={timeStamp:l};if("grey"===d)t=await this._decodeBuffer_Uint8Array(i,s,a,s,c.IPF_GrayScaled,h);else if("rgba"===d)t=await this._decodeBuffer_Uint8Array(i,s,a,4*s,c.IPF_ABGR_8888,h);else{if("bgra"!==d)throw new Error(`Color mode '${d}' is not supported.`);t=await this._decodeBuffer_Uint8Array(i,s,a,4*s,c.IPF_ARGB_8888,h)}await this.clearMapDecodeRecord();for(let e of t)delete e.bUnduplicated;if(this._drawResults(t),w.fixResultLocationWhenFilterRegionInJs(n,t,o,r,s,a,s,a),this.onFrameRead&&this.isOpen()&&!this._bPauseScan&&this.onFrameRead(t),this.onUniqueRead&&this.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,e)})))}set maxCvsSideLength(e){this._maxCvsSideLength=e,this.dce.maxCvsSideLength=e}get maxCvsSideLength(){return this._maxCvsSideLength}static async createInstance(e){let t=new M;await t.createDCEInstance(),t._instanceID=await M.createInstanceInWorker(!0),"string"==typeof e&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return await t.setUIElement(M.defaultUIElementURL),t.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),t.singleFrameMode||await t.updateRuntimeSettings("single"),t}async decodeCurrentFrame(e){this._assertOpen();let t=null;e&&e.region&&(t=e.region);const i=this.dce._getVideoFrame(t);return this._decode_DCEFrame(i)}static isRegionNormalPreset(e){return 0==e.regionLeft&&0==e.regionTop&&0==e.regionRight&&0==e.regionBottom&&0==e.regionMeasuredByPercentage}async updateRuntimeSettings(e){let t;if("string"==typeof e)if("speed"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region)}else if("balance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.deblurLevel=3,t.expectedBarcodesCount=512,t.localizationModes=[2,16,0,0,0,0,0,0],t.timeout=1e5}else if("coverage"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.deblurLevel=5,t.expectedBarcodesCount=512,t.scaleDownThreshold=1e5,t.localizationModes=[2,16,4,8,0,0,0,0],t.timeout=1e5}else if("single"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,M.isRegionNormalPreset(e.region)?t.region=null:t.region=e.region,t.expectedBarcodesCount=1,t.localizationModes=[16,2,0,0,0,0,0,0],t.barcodeZoneMinDistanceToImageBorders=0}else t=JSON.parse(e);else{if("object"!=typeof e)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(t=JSON.parse(JSON.stringify(e)),t.region instanceof Array){let i=e.region;[i.regionLeft,i.regionTop,i.regionLeft,i.regionBottom,i.regionMeasuredByPercentage].some((e=>void 0!==e))&&(t.region={regionLeft:i.regionLeft||0,regionTop:i.regionTop||0,regionRight:i.regionRight||0,regionBottom:i.regionBottom||0,regionMeasuredByPercentage:i.regionMeasuredByPercentage||0})}}if(!w._bUseFullFeature){if(0!=(t.barcodeFormatIds&~(g.BF_ONED|g.BF_QR_CODE|g.BF_PDF417|g.BF_DATAMATRIX))||0!=t.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=t.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}{let e=t.region;if(this.bFilterRegionInJs?this.userDefinedRegion=JSON.parse(JSON.stringify(e)):this.userDefinedRegion=null,e instanceof Array)if(e.length){for(let t=0;t{let n=w._nextTaskID++;w._taskCallbackMap.set(n,(t=>{if(t.success){try{this._handleRetJsonString(t.updateReturn)}catch(e){i(e)}return e()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}})),w._dbrWorker.postMessage({type:"updateRuntimeSettings",id:n,instanceID:this._instanceID,body:{settings:JSON.stringify(t)}})})),"single"==e&&(await this.setModeArgument("BinarizationModes",0,"EnableFillBinaryVacancy","0"),await this.setModeArgument("LocalizationModes",0,"ScanDirection","2"),await this.setModeArgument("BinarizationModes",0,"BlockSizeX","71"),await this.setModeArgument("BinarizationModes",0,"BlockSizeY","71"))}_bindUI(){if(!this.getUIElement())throw new Error("Need to define `UIElement` before opening.");if(this.dce._bindUI(),!this.dce.video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'")}_unbindUI(){this.dce._unbindUI()}set onPlayed(e){this.dce.off("played",this._onPlayed),this._onPlayed=e,this.dce.on("played",this._onPlayed)}get onPlayed(){return this._onPlayed}async getAllCameras(){return this.dce.getAllCameras()}async getCurrentCamera(){return this.dce.getSelectedCamera()}async setCurrentCamera(e){return this.dce.selectCamera(e)}getResolution(){return this.dce.getResolution()}async setResolution(e,t){return this.dce.setResolution(e,t)}getVideoSettings(){return this.dce.getVideoSettings()}updateVideoSettings(e){return this.dce.updateVideoSettings(e)}isOpen(){return this.dce&&this.dce.isOpen()}setVideoFit(e){return this.dce&&this.dce.setVideoFit(e)}set ifShowScanRegionMask(e){this.dce&&(this.dce.ifShowScanRegionMask=e)}get ifShowScanRegionMask(){return this.dce&&this.dce.ifShowScanRegionMask}stop(){this.dce.stop(),this.dce.hideScanRegionLaser(),this.dce.hideViewDecorator(),this.dce.hideScanRegionOverlays(),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}pause(){this._drawResults(null),this.dce.pause()}async play(e,t,i){this.dce.ifShowScanRegionLaser=!0;return await this.dce.play(e,t,i)}pauseScan(){this._assertOpen(),this._drawResults(null),this._bPauseScan=!0,this.dce.ifShowScanRegionLaser=!1}resumeScan(){this._assertOpen(),this._bPauseScan=!1,this.dce.ifShowScanRegionLaser=!0}getCapabilities(){return this.dce.getCapabilities()}getCameraSettings(){return this.dce.getCameraSettings()}getConstraints(){return this.dce.getConstraints()}async applyConstraints(e){return this.dce.applyConstraints(e)}async turnOnTorch(){return this.dce.turnOnTorch()}async turnOffTorch(){return this.dce.turnOffTorch()}async setColorTemperature(e){return this.dce.setColorTemperature(e)}async setExposureCompensation(e){return this.dce.setExposureCompensation(e)}async setZoom(e){return this.dce.setZoom(e)}async setFrameRate(e){return this.dce.setFrameRate(e)}getFrameRate(){return this.dce.getFrameRate()}async setFocus(e,t){return this.dce.setFocus(e,t)}getFocus(){return this.dce.getFocus()}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),void this._drawResults(null);if(!this.isOpen())return this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce.video||this.dce.video.paused||this._bPauseScan)return w._onLog&&w._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));w._onLog&&w._onLog("======= once read ======="),w._onLog&&(this._timeStartDecode=Date.now());const e=this._getVideoFrame();if(!e)return this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let t;e._bUseWebGL||"grey"!==e.colorMode||(this.dce.frameColorMode="rgba"),this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,colorMode:e.colorMode,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{data:i,region:n,sx:o,sy:r,width:s,height:a,colorMode:d,timeStamp:l}=e,h={timeStamp:l};if("grey"===d)t=await this._decodeBuffer_Uint8Array(i,s,a,s,c.IPF_GrayScaled,h);else if("rgba"===d)t=await this._decodeBuffer_Uint8Array(i,s,a,4*s,c.IPF_ABGR_8888,h);else{if("bgra"!==d)throw new Error(`Color mode '${d}' is not supported.`);t=await this._decodeBuffer_Uint8Array(i,s,a,4*s,c.IPF_ARGB_8888,h)}return this.dce&&this.dce.video&&!this.dce.video.paused&&this._drawResults(t),w.fixResultLocationWhenFilterRegionInJs(n,t,o,r,s,a,s,a),t})().then((e=>{w._onLog&&w._onLog(e);let t=this.array_decodeFrameTimeCost,i=this.array_getFrameTimeCost,n=this._indexCurrentDecodingFrame;if((()=>{if(this.region instanceof Array){for(t[n]&&t[n]instanceof Array||(t[n]=[]);t[n].length>=5;)t[n].shift();t[n].push(this._lastInnerDecodeDuration)}else{for(;t.length>=5;)t.shift();t.push(this._lastInnerDecodeDuration)}})(),this._intervalGetVideoFrame=(()=>{let e=0;if(this.region instanceof Array){let o=0,r=0;o=n+1>=this.region.length?0:n+1,r=o+1>=this.region.length?0:o+1,e=t[o]&&t[o].length&&i[r]&&i[r].length?Math.min(...t[o])-Math.max(...i[r]):0}else if(i&&i.length){let n=Math.min(...t),o=Math.max(...i);n&&o&&(e=n-o)}else e=0;return e>0?e:0})()+this.intervalTime,this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead)t=!0;else if("unique"===this.bPlaySoundOnSuccessfulRead)for(let i of e)if(i.bUnduplicated){t=!0;break}t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead)t=!0;else if("unique"===this.bVibrateOnSuccessfulRead)for(let i of e)if(i.bUnduplicated){t=!0;break}if(t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onFrameRead){let t=this._cloneDecodeResults(e);for(let e of t)delete e.bUnduplicated;this.onFrameRead(t)}if(this.onUniqueRead)for(let t of e)t.bUnduplicated&&this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t))}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce.stopFetchingLoop(),w._onLog&&w._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e=this.dce.isFetchingLoopStarted();if(this.dce.loopInterval=this._intervalGetVideoFrame,e||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dce.loopInterval=0,null;const t=this.dce.getFrameFromBuffer();return(e=>{if(!e)return;let t=e.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(t)})(t),t}async open(){this._bindUI();let e=await this.dce.open();return this._bPauseScan=!1,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.dce.ifShowScanRegionLaser=!0,this._loopReadVideo()),this.keepAlive(),e}async openVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open();return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideo()),this.keepAlive(),e}close(){this.dce.close(),this._bPauseScan=!0}async show(){this._bindUI();const e=await this.dce.open(!0);return this._bPauseScan=!1,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.dce.ifShowScanRegionLaser=!0,this._loopReadVideo()),this.keepAlive(),e}async showVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open(!0);return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideo()),this.keepAlive(),e}hide(){this.dce.close(!0),this._bPauseScan=!0}destroyContext(){this.close(),this.bDestroyed||super.destroyContext()}}var L,O,F,B,N,P,x,V,k,U,G,W,H,J,K,Y,Q,X,j,Z,q,z,$,ee,te,ie,ne;!function(e){e[e.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",e[e.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",e[e.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",e[e.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",e[e.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",e[e.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",e[e.BICM_SKIP=0]="BICM_SKIP",e[e.BICM_REV=2147483648]="BICM_REV"}(L||(L={})),function(e){e[e.BCM_AUTO=1]="BCM_AUTO",e[e.BCM_GENERAL=2]="BCM_GENERAL",e[e.BCM_SKIP=0]="BCM_SKIP",e[e.BCM_REV=2147483648]="BCM_REV"}(O||(O={})),function(e){e[e.BF2_NULL=0]="BF2_NULL",e[e.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",e[e.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",e[e.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",e[e.BF2_POSTNET=2097152]="BF2_POSTNET",e[e.BF2_PLANET=4194304]="BF2_PLANET",e[e.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",e[e.BF2_RM4SCC=16777216]="BF2_RM4SCC",e[e.BF2_DOTCODE=2]="BF2_DOTCODE",e[e.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",e[e.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",e[e.BF2_PHARMACODE=12]="BF2_PHARMACODE"}(F||(F={})),function(e){e[e.BM_AUTO=1]="BM_AUTO",e[e.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",e[e.BM_SKIP=0]="BM_SKIP",e[e.BM_THRESHOLD=4]="BM_THRESHOLD",e[e.BM_REV=2147483648]="BM_REV"}(B||(B={})),function(e){e[e.ECCM_CONTRAST=1]="ECCM_CONTRAST"}(N||(N={})),function(e){e[e.CFM_GENERAL=1]="CFM_GENERAL"}(P||(P={})),function(e){e[e.CCM_AUTO=1]="CCM_AUTO",e[e.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",e[e.CCM_SKIP=0]="CCM_SKIP",e[e.CCM_REV=2147483648]="CCM_REV"}(x||(x={})),function(e){e[e.CICM_GENERAL=1]="CICM_GENERAL",e[e.CICM_SKIP=0]="CICM_SKIP",e[e.CICM_REV=2147483648]="CICM_REV"}(V||(V={})),function(e){e[e.CM_IGNORE=1]="CM_IGNORE",e[e.CM_OVERWRITE=2]="CM_OVERWRITE"}(k||(k={})),function(e){e[e.DM_SKIP=0]="DM_SKIP",e[e.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",e[e.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",e[e.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",e[e.DM_SMOOTHING=8]="DM_SMOOTHING",e[e.DM_MORPHING=16]="DM_MORPHING",e[e.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",e[e.DM_SHARPENING=64]="DM_SHARPENING",e[e.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",e[e.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING"}(U||(U={})),function(e){e[e.DRM_AUTO=1]="DRM_AUTO",e[e.DRM_GENERAL=2]="DRM_GENERAL",e[e.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",e[e.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",e[e.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",e[e.DRM_SKIP=0]="DRM_SKIP",e[e.DRM_REV=2147483648]="DRM_REV"}(G||(G={})),function(e){e[e.DPMCRM_AUTO=1]="DPMCRM_AUTO",e[e.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",e[e.DPMCRM_SKIP=0]="DPMCRM_SKIP",e[e.DPMCRM_REV=2147483648]="DPMCRM_REV"}(W||(W={})),function(e){e[e.GTM_INVERTED=1]="GTM_INVERTED",e[e.GTM_ORIGINAL=2]="GTM_ORIGINAL",e[e.GTM_SKIP=0]="GTM_SKIP",e[e.GTM_REV=2147483648]="GTM_REV"}(H||(H={})),function(e){e[e.IPM_AUTO=1]="IPM_AUTO",e[e.IPM_GENERAL=2]="IPM_GENERAL",e[e.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",e[e.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",e[e.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",e[e.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",e[e.IPM_SKIP=0]="IPM_SKIP",e[e.IPM_REV=2147483648]="IPM_REV"}(J||(J={})),function(e){e[e.IRSM_MEMORY=1]="IRSM_MEMORY",e[e.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",e[e.IRSM_BOTH=4]="IRSM_BOTH"}(K||(K={})),function(e){e[e.IRT_NO_RESULT=0]="IRT_NO_RESULT",e[e.IRT_ORIGINAL_IMAGE=1]="IRT_ORIGINAL_IMAGE",e[e.IRT_COLOUR_CLUSTERED_IMAGE=2]="IRT_COLOUR_CLUSTERED_IMAGE",e[e.IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE=4]="IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE",e[e.IRT_TRANSFORMED_GRAYSCALE_IMAGE=8]="IRT_TRANSFORMED_GRAYSCALE_IMAGE",e[e.IRT_PREDETECTED_REGION=16]="IRT_PREDETECTED_REGION",e[e.IRT_PREPROCESSED_IMAGE=32]="IRT_PREPROCESSED_IMAGE",e[e.IRT_BINARIZED_IMAGE=64]="IRT_BINARIZED_IMAGE",e[e.IRT_TEXT_ZONE=128]="IRT_TEXT_ZONE",e[e.IRT_CONTOUR=256]="IRT_CONTOUR",e[e.IRT_LINE_SEGMENT=512]="IRT_LINE_SEGMENT",e[e.IRT_FORM=1024]="IRT_FORM",e[e.IRT_SEGMENTATION_BLOCK=2048]="IRT_SEGMENTATION_BLOCK",e[e.IRT_TYPED_BARCODE_ZONE=4096]="IRT_TYPED_BARCODE_ZONE",e[e.IRT_PREDETECTED_QUADRILATERAL=8192]="IRT_PREDETECTED_QUADRILATERAL"}(Y||(Y={})),function(e){e[e.LM_SKIP=0]="LM_SKIP",e[e.LM_AUTO=1]="LM_AUTO",e[e.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",e[e.LM_LINES=8]="LM_LINES",e[e.LM_STATISTICS=4]="LM_STATISTICS",e[e.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",e[e.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",e[e.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",e[e.LM_CENTRE=128]="LM_CENTRE",e[e.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",e[e.LM_REV=2147483648]="LM_REV"}(Q||(Q={})),function(e){e[e.PDFRM_RASTER=1]="PDFRM_RASTER",e[e.PDFRM_AUTO=2]="PDFRM_AUTO",e[e.PDFRM_VECTOR=4]="PDFRM_VECTOR",e[e.PDFRM_REV=2147483648]="PDFRM_REV"}(X||(X={})),function(e){e[e.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",e[e.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",e[e.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",e[e.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(j||(j={})),function(e){e[e.RPM_AUTO=1]="RPM_AUTO",e[e.RPM_GENERAL=2]="RPM_GENERAL",e[e.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",e[e.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",e[e.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",e[e.RPM_SKIP=0]="RPM_SKIP",e[e.RPM_REV=2147483648]="RPM_REV"}(Z||(Z={})),function(e){e[e.RCT_PIXEL=1]="RCT_PIXEL",e[e.RCT_PERCENTAGE=2]="RCT_PERCENTAGE"}(q||(q={})),function(e){e[e.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",e[e.RT_RAW_TEXT=1]="RT_RAW_TEXT",e[e.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",e[e.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT"}(z||(z={})),function(e){e[e.SUM_AUTO=1]="SUM_AUTO",e[e.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",e[e.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",e[e.SUM_SKIP=0]="SUM_SKIP",e[e.SUM_REV=2147483648]="SUM_REV"}($||($={})),function(e){e[e.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",e[e.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",e[e.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",e[e.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",e[e.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",e[e.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED"}(ee||(ee={})),function(e){e[e.TFM_AUTO=1]="TFM_AUTO",e[e.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",e[e.TFM_SKIP=0]="TFM_SKIP",e[e.TFM_REV=2147483648]="TFM_REV"}(te||(te={})),function(e){e[e.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",e[e.TROM_POSITION=2]="TROM_POSITION",e[e.TROM_FORMAT=4]="TROM_FORMAT",e[e.TROM_SKIP=0]="TROM_SKIP",e[e.TROM_REV=2147483648]="TROM_REV"}(ie||(ie={})),function(e){e[e.TDM_AUTO=1]="TDM_AUTO",e[e.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",e[e.TDM_SKIP=0]="TDM_SKIP",e[e.TDM_REV=2147483648]="TDM_REV"}(ne||(ne={}));export{w as BarcodeReader,M as BarcodeScanner,L as EnumBarcodeColourMode,O as EnumBarcodeComplementMode,g as EnumBarcodeFormat,F as EnumBarcodeFormat_2,B as EnumBinarizationMode,N as EnumClarityCalculationMethod,P as EnumClarityFilterMode,x as EnumColourClusteringMode,V as EnumColourConversionMode,k as EnumConflictMode,W as EnumDPMCodeReadingMode,U as EnumDeblurMode,G as EnumDeformationResistingMode,_ as EnumErrorCode,H as EnumGrayscaleTransformationMode,u as EnumIMResultDataType,c as EnumImagePixelFormat,J as EnumImagePreprocessingMode,K as EnumIntermediateResultSavingMode,Y as EnumIntermediateResultType,Q as EnumLocalizationMode,X as EnumPDFReadingMode,j as EnumQRCodeErrorCorrectionLevel,Z as EnumRegionPredetectionMode,q as EnumResultCoordinateType,z as EnumResultType,$ as EnumScaleUpMode,ee as EnumTerminatePhase,te as EnumTextFilterMode,ie as EnumTextResultOrderMode,ne as EnumTextureDetectionMode}; + */function B(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{l(r.next(e))}catch(e){s(e)}}function a(e){try{l(r.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))}const j="undefined"==typeof self;let N,V,U,G,W;if("undefined"!=typeof navigator&&(N=navigator,V=N.userAgent,U=N.platform,G=N.mediaDevices),!j){const e={init:function(){this.browser=this.searchString(this.dataBrowser)||"unknownBrowser",this.version=this.searchVersion(V)||this.searchVersion(N.appVersion)||0,this.OS=this.searchString(this.dataOS)||"unknownOS","Linux"==this.OS&&-1!=V.indexOf("Windows NT")&&(this.OS="HarmonyOS")},searchString:function(e){for(let t=0;t{let e=!1;if(Y)try{(await G.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===W.browser&&W.version>66||"Safari"===W.browser&&W.version>13||"OPR"===W.browser&&W.version>43||"Edge"===W.browser&&W.version;const K=(()=>{if(!j&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})();class J{constructor(e,t){this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapStyle=new Map,this.mapEvents=new Map([["select",[]],["deselect",[]]]),this.isDrawingItem=!0,this._setFabricObject(e),this._mediaType=e.type,this.styleSelector="default",this.styleId=t;for(let e of J.arrStyleSelectors)this._mapStyle.set(e,null)}get mediaType(){return this._mediaType}get drawingLayerId(){return this._drawingLayerId}_setFabricObject(e){this._fabricObject=e;const t=this.mapEvents;this._fabricObject.onSelect=()=>{this.styleSelector="selected";const e=this.mapEvents.get("select");for(let t of e)t&&t.apply(this)},this._fabricObject.onDeselect=()=>{this.styleSelector="default";const e=t.get("deselect");for(let t of e)t&&t.apply(this)},e.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}on(e,t,i){const r=this.mapEvents.get(e);r.includes(t)||r.push(t)}off(e,t){const i=this.mapEvents.get(e),r=i.indexOf(t);-1!==r&&i.splice(r,1)}_setEditable(e){const t=this._fabricObject;e?(t.selectable=!0,t.evented=!0,t.hasControls=!0):(t.selectable=!1,t.evented=!1,t.hasControls=!1)}_extendSet(e,t){return!1}_extendGet(e){}set(e,t){this._extendSet(e,t)||("x"===e?this._fabricObject.set("left",t):"y"===e?this._fabricObject.set("top",t):this._fabricObject.set(e,t)),["vertices","left","top","width","height","scaleX","scaleY","skewX","skewY","padding","angle","strokeWidth"].includes(e)&&this._fabricObject.setCoords()}get(e){let t=this._extendGet(e);return void 0===t&&(t="x"===e?this._fabricObject.get("left"):"y"===e?this._fabricObject.get("top"):this._fabricObject.get(e)),t}}function q(e,t,i){let r=i.points[this.pointIndex].x-i.pathOffset.x,n=i.points[this.pointIndex].y-i.pathOffset.y;return k.util.transformPoint({x:r,y:n},k.util.multiplyTransformMatrices(i.canvas.viewportTransform,i.calcTransformMatrix()))}function Q(e){let t=new k.Point(e.strokeUniform?1/e.scaleX:1,e.strokeUniform?1/e.scaleY:1).multiply(e.strokeWidth);return new k.Point(e.width+t.x,e.height+t.y)}function Z(e,t,i,r){let n=t.target,s=n.controls[n.__corner],o=n.toLocalPoint(new k.Point(i,r),"center","center"),a=Q(n),l=n._getTransformedDimensions(0,0),h={x:o.x*a.x/l.x+n.pathOffset.x,y:o.y*a.y/l.y+n.pathOffset.y};return n.points[s.pointIndex]=h,!0}function $(e,t){return function(i,r,n,s){let o=r.target,a=k.util.transformPoint({x:o.points[e].x-o.pathOffset.x,y:o.points[e].y-o.pathOffset.y},o.calcTransformMatrix()),l=t(i,r,n,s);o._setPositionDimensions({});let h=Q(o),c=(o.points[e].x-o.pathOffset.x)/h.x,u=(o.points[e].y-o.pathOffset.y)/h.y;return o.setPositionByOrigin(a,c+.5,u+.5),l}}J.arrMediaTypes=["rect","arc","polygon","image","text","line","path"],J.arrStyleSelectors=["default","selected"],"undefined"!=typeof document&&"undefined"!=typeof window&&(k.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(k.util.cancelAnimFrame(this.isRendering),this.isRendering=0),this.forEachObject((function(e){e.dispose&&e.dispose()})),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose&&this.backgroundImage.dispose(),this.backgroundImage=null,this.overlayImage&&this.overlayImage.dispose&&this.overlayImage.dispose(),this.overlayImage=null,this._iTextInstances=null,this.contextContainer=null,this.lowerCanvasEl.classList.remove("lower-canvas"),delete this._originalCanvasStyle,this.lowerCanvasEl.setAttribute("width",this.width),this.lowerCanvasEl.setAttribute("height",this.height),k.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},k.Object.prototype.transparentCorners=!1,k.Object.prototype.cornerSize=20,k.Object.prototype.touchCornerSize=100,k.Object.prototype.cornerColor="rgb(254,142,20)",k.Object.prototype.cornerStyle="circle",k.Object.prototype.strokeUniform=!0,k.Object.prototype.hasBorders=!1,k.ActiveSelection.prototype.onDeselect=function(){return this.getObjects().forEach((e=>{setTimeout(e.onDeselect,0)})),this.destroy(),!1},k.Canvas.prototype.containerClass="",k.Canvas.prototype.getPointer=function(e,t){if(this._absolutePointer&&!t)return this._absolutePointer;if(this._pointer&&t)return this._pointer;var i,r=this.upperCanvasEl,n=k.util.getPointer(e,r),s=r.getBoundingClientRect(),o=s.width||0,a=s.height||0;o&&a||("top"in s&&"bottom"in s&&(a=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(o=Math.abs(s.right-s.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,t||(n=this.restorePointerVpt(n));var l=this.getRetinaScaling();if(1!==l&&(n.x/=l,n.y/=l),0!==o&&0!==a){var h=window.getComputedStyle(r).objectFit,c=r.width,u=r.height,d=o,f=a;i={width:c/d,height:u/f};var g,_,p=c/u,m=d/f;return"contain"===h?p>m?(g=d,_=d/p,{x:n.x*i.width,y:(n.y-(f-_)/2)*i.width}):(g=f*p,_=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===h?p>m?{x:(c-i.height*d)/2+n.x*i.height,y:n.y*i.height}:{x:n.x*i.width,y:(u-i.width*f)/2+n.y*i.width}:{x:n.x*i.width,y:n.y*i.height}}return i={width:1,height:1},{x:n.x*i.width,y:n.y*i.height}});class ee{constructor(e,t,i,r){let n,s;switch(this.mapMediaType_Style=new Map,this.mode="viewer",this.onSelectionChange=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,e.hasOwnProperty("getFabricCanvas")?this.fabricCanvas=e.getFabricCanvas():(this.fabricCanvas=new k.Canvas(e,r),this.fabricCanvas.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),this.fabricCanvas.lowerCanvasEl.className="",this.fabricCanvas.upperCanvasEl.className="",this.fabricCanvas.on("selection:created",(function(e){const t=e.selected,i=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!i.includes(t)&&i.push(t)}for(let e of i){const i=[];for(let r of t){const t=r.getDrawingItem();t._drawingLayer===e&&i.push(t)}setTimeout((()=>{e.onSelectionChange&&e.onSelectionChange(i,[])}),0)}})),this.fabricCanvas.on("before:selection:cleared",(function(e){const t=this.getActiveObjects(),i=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!i.includes(t)&&i.push(t)}for(let e of i){const i=[];for(let r of t){const t=r.getDrawingItem();t._drawingLayer===e&&i.push(t)}setTimeout((()=>{const t=[];for(let r of i)e.hasDrawingItem(r)&&t.push(r);t.length>0&&e.onSelectionChange&&e.onSelectionChange([],t)}),0)}})),this.fabricCanvas.on("selection:updated",(function(e){const t=e.selected,i=e.deselected,r=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!r.includes(t)&&r.push(t)}for(let e of i){const t=e.getDrawingItem()._drawingLayer;t&&!r.includes(t)&&r.push(t)}for(let e of r){const r=[],n=[];for(let i of t){const t=i.getDrawingItem();t._drawingLayer===e&&r.push(t)}for(let t of i){const i=t.getDrawingItem();i._drawingLayer===e&&n.push(i)}setTimeout((()=>{e.onSelectionChange&&e.onSelectionChange(r,n)}),0)}})),this.fabricCanvas.wrapperEl.style.position="absolute",e.getFabricCanvas=()=>this.fabricCanvas),this.id=t,this._mapDrawingStyles=i,t){case 1:n=i.get(1),s=i.get(5);break;case 2:n=i.get(2),s=i.get(6);break;case 3:n=i.get(3),s=i.get(7);break;default:n=i.get(4),s=i.get(8)}for(let e of J.arrMediaTypes)this.mapMediaType_Style.set(e,{default:n,selected:s})}getId(){return this.id}_getDrawingStyle(e,t){if("number"!=typeof e)throw new Error("Invalid style id.");const i=this._mapDrawingStyles.get(e);return i?t?JSON.parse(JSON.stringify(i)):i:null}setVisible(e){if(e){for(let e of this._arrFabricObject)e.visible=!0;this._visible=!0}else{for(let e of this._arrFabricObject)e.visible=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyleId(e){return e.styleId?e.styleId:this.mapMediaType_Style.get(e._mediaType)[e.styleSelector].styleId}_getItemCurrentStyle(e){if(e.styleId)return this._getDrawingStyle(e.styleId);return e._mapStyle.get(e.styleSelector)||null}_changeMediaTypeCurStyleInStyleSelector(e,t,i,r){let n;switch(e){case"rect":n=this.fabricCanvas.getObjects("rect");break;case"arc":n=this.fabricCanvas.getObjects("circle");break;case"polygon":n=this.fabricCanvas.getObjects("polygon");break;case"image":n=this.fabricCanvas.getObjects("image");break;case"text":n=this.fabricCanvas.getObjects("text");break;case"line":n=this.fabricCanvas.getObjects("line");break;case"path":n=this.fabricCanvas.getObjects("path")}for(let e of n){if(!this._arrFabricObject.includes(e))continue;const r=e.getDrawingItem();r.styleSelector===t&&this._changeItemStyle(r,i,!0)}r||this.fabricCanvas.renderAll()}_changeItemStyle(e,t,i){if(!e||!t)return;const r=e._getFabricObject();"number"==typeof e.styleId&&(t=this._getDrawingStyle(e.styleId)),r.strokeWidth=t.lineWidth,"fill"===t.paintMode?(r.fill=t.fillStyle,r.stroke=t.fillStyle):"stroke"===t.paintMode?(r.fill="transparent",r.stroke=t.strokeStyle):"strokeAndFill"===t.paintMode&&(r.fill=t.fillStyle,r.stroke=t.strokeStyle),r.fontFamily&&(r.fontFamily=t.fontFamily),r.fontSize&&(r.fontSize=t.fontSize),r.group||(r.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(e,t,i){if(!e||!t)return;const r=e.getChildItems();if("add"===i){if(r.includes(t))return;const i=t._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");t._zIndex=null}else{let i;if(t.styleId)i=this._getDrawingStyle(t.styleId);else{i=this.mapMediaType_Style.get(t._mediaType)[e.styleSelector];const r=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).selected,!0)},n=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).default,!0)};t.on("select",r),t.on("deselect",n),t._funcChangeStyleToSelected=r,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,i,!0)}e._fabricObject.addWithUpdate(t._getFabricObject())}else{if("remove"!==i)return;if(!r.includes(t))return;t._zIndex=null,t._drawingLayer=null,t._drawingLayerId=null,t.off("select",t._funcChangeStyleToSelected),t.off("deselect",t._funcChangeStyleToDefault),t._funcChangeStyleToSelected=null,t._funcChangeStyleToDefault=null,e._fabricObject.removeWithUpdate(t._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(e,t){let i=e._getFabricObject();const r=this.fabricCanvas.getObjects();let n,s;if(r.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===e._mediaType){n=e.getChildItems();for(let e of n)if(e._drawingLayer&&e._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(t&&"object"==typeof t&&!Array.isArray(t))for(let e in t)i.set(e,t[e]);if(n){for(let e of n){if(e.styleId)s=this._getDrawingStyle(e.styleId);else{const t=this.mapMediaType_Style.get(e._mediaType);for(let i of J.arrStyleSelectors)e._mapStyle.set(i,t[i]);s=t.default;const i=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected,!0)},r=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default,!0)};e.on("select",i),e.on("deselect",r),e._funcChangeStyleToSelected=i,e._funcChangeStyleToDefault=r}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{if(e.styleId)s=this._getDrawingStyle(e.styleId);else{const t=this.mapMediaType_Style.get(e._mediaType);for(let i of J.arrStyleSelectors)e._mapStyle.set(i,t[i]);s=t.default;const i=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected)},r=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default)};e.on("select",i),e.on("deselect",r),e._funcChangeStyleToSelected=i,e._funcChangeStyleToDefault=r}this._changeItemStyle(e,s)}e._zIndex=this.id,e._drawingLayer=this,e._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=r.length;if(o)a=r.indexOf(this._arrFabricObject[o-1])+1;else for(let t=0;t{for(let t of this._arrDrawingLayer)if(t.getId()===e)return!0;return!1};if(void 0===t){for(let e=100;;e++)if(!i(e)){t=e;break}}else if(i(t))throw new Error("Existed drawing layer id.");const r=new ee(e,t,this._mapDrawingStyles,{enableRetinaScaling:!1});return r._manager=this,this._arrDrawingLayer.push(r),this._switchPointerEvent(),r}deleteDrwaingLayer(e){const t=this.getDrawingLayer(e);if(!t)return;const i=this._arrDrawingLayer;t.dispose(),i.splice(i.indexOf(t),1),this._switchPointerEvent()}clearDrawingLayers(){for(let e of this._arrDrawingLayer)e.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(e){for(let t of this._arrDrawingLayer)if(t.getId()===e)return t;return null}getDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const e=this._arrDrawingLayer[0].fabricCanvas.getActiveObjects(),t=[];for(let i of e)t.push(i.getDrawingItem());return t}setDimensions(e,t){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(e,t)}setObjectFit(e){for(let t of this._arrDrawingLayer)t&&t._setObjectFit(e)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(e){this._arrDrawingLayer.length&&(this._arrDrawingLayer[0].fabricCanvas.wrapperEl.style.display=e?"block":"none")}_switchPointerEvent(){if(!this._arrDrawingLayer.length)return;let e=!1;for(let t of this._arrDrawingLayer)"editor"===t.getMode()&&(e=!0);this._arrDrawingLayer[0].fabricCanvas.wrapperEl.style.pointerEvents=e?"":"none"}}class ie{constructor(e){this._controlTarget=null,this._arrUsers=[],this._mapAction_UserArgs=new Map,this._mapProperty_UserValue=new Map,this._mapAction_Callbacks=new Map,this._controlTarget=e}setControlTarget(e){this._controlTarget=e}getControlTarget(){return this._controlTarget}register(e){this._arrUsers.includes(e)||this._arrUsers.push(e)}logout(e){const t=this._arrUsers.indexOf(e);-1!==t&&(this.clearUserDisiredAction({user:e}),this.clearUserDisiredValue({user:e}),this._arrUsers.splice(t,1))}getRegisteredUsers(){return this._arrUsers}ifUserExisted(e){return this._arrUsers.includes(e)}setDisiredValue(e,t,i,r){if(!this._arrUsers.includes(e))throw new Error("Unregistered user.");r&&(this._controlTarget[t]=i),this._mapProperty_UserValue.get(t)?this._mapProperty_UserValue.get(t).set(e,i):this._mapProperty_UserValue.set(t,new Map([[e,i]]))}clearUserDisiredValue(e){if(e&&(e.user||e.property)){if(e.property&&e.user){const t=this._mapProperty_UserValue.get(e.property);if(!t)return;t.delete(e.user)}else if(e.property)this._mapProperty_UserValue.delete(e.property);else if(e.user)for(let t of this._mapProperty_UserValue.values())t.delete(e.user)}else this._mapProperty_UserValue=new Map}getValue(e){if(!this._controlTarget)throw new Error("Control target is not set.");return this._controlTarget[e]}getPropertyDisiredValue(e){if(this._mapProperty_UserValue.get(e)){const t=[],i=this._mapProperty_UserValue.get(e);for(let e of i.values())t.push(e);return t}return null}setDisiredAction(e,t,i,r){if(!this._arrUsers.includes(e))throw new Error("Unregistered user.");return i||(i=[]),r?this._controlTarget[t](...i):(this._mapAction_UserArgs.get(t)?this._mapAction_UserArgs.get(t).set(e,i):this._mapAction_UserArgs.set(t,new Map([[e,i]])),this._render(t))}clearUserDisiredAction(e){if(e&&(e.user||e.actionName)){if(e.actionName&&e.user){const t=this._mapAction_UserArgs.get(e.actionName);if(!t)return;t.delete(e.user)}else if(e.actionName)this._mapAction_UserArgs.delete(e.actionName);else if(e.user)for(let t of this._mapAction_UserArgs.values())t.delete(e.user);this.render()}else this._mapAction_UserArgs=new Map}addCallback(e,t){const i=this._mapAction_Callbacks.get(e);i?i.push(t):this._mapAction_Callbacks.set(e,[t])}removeCallback(e,t){const i=this._mapAction_Callbacks.get(e);if(!i)return;const r=i.indexOf(t);-1!==r&&i.splice(r,1)}clearCallback(e){e?this._mapAction_Callbacks.delete(e):this._mapAction_Callbacks.clear()}_fireCallback(e){const t=this._mapAction_Callbacks.get(e);if(t)for(let e of t){if(!e)return;setTimeout(e.bind(this._controlTarget),0)}}_render(e){const t=this._mapAction_UserArgs.get(e);if(!t)throw new Error("Unrecorded action.");if(t.size===this._arrUsers.length){let i=[];for(let e of t.values())e.length>0&&(i=e);if(this._controlTarget[e]){const t=this._controlTarget[e](...i);return this._mapAction_UserArgs.delete(e),this._fireCallback(e),t}}}render(e){if(e)return this._render(e);for(let e of this._mapAction_UserArgs.keys())this._render(e)}}class re{constructor(){this._maxCvsSideLength=void 0,this._defaultMaxCvsSideLength=null,this._predefinedResolutions=[{width:160,height:120},{width:320,height:240},{width:480,height:360},{width:640,height:480},{width:800,height:600},{width:960,height:720},{width:1280,height:720},{width:1920,height:1080},{width:2560,height:1440},{width:3840,height:2160}],this._mapCameraResolutions=new Map,this._bWebGLSupported=!0,this.extraBindings=[],this._singleFrameMode=!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia),this._cvsSingleFrameMode=null,this._cvsOriginalImage=null,this._imgWidth=0,this._imgHeight=0,this._singleFrameModeIpt=null,this._clickIptSingleFrameMode=()=>{if(this.singleFrameMode){if(!this._singleFrameModeIpt){const e=document.createElement("input");this._singleFrameModeIpt=e,e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.addEventListener("change",(()=>B(this,void 0,void 0,(function*(){const t=e.files[0];e.value="";const i=yield(e=>B(this,void 0,void 0,(function*(){let t=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(t=yield createImageBitmap(e),t)return t}catch(e){}var r;return t||(i=yield(r=e,new Promise(((e,t)=>{let i=URL.createObjectURL(r),n=new Image;n.dbrObjUrl=i,n.src=i,n.onload=()=>{e(n)},n.onerror=e=>{t(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}})))),i})))(t),r=i instanceof HTMLImageElement?i.naturalWidth:i.width,n=i instanceof HTMLImageElement?i.naturalHeight:i.height;this._imgWidth=r,this._imgHeight=n;const s=e=>{const t=Date.now();if(0===r||0===n)return null;const i=this._scanRegion,s=this.getFrameSize(r,n,i,this.maxCvsSideLength);if(!s)return null;let o,a;o=r!==s.sWidth||n!==s.sHeight,a=s.sWidth!==s.dWidth||s.sHeight!==s.dHeight;const l=(()=>!(!this._bWebGLSupported||a))(),h={data:null,region:i?JSON.parse(JSON.stringify(i)):null,sx:s.sx,sy:s.sy,width:s.dWidth,height:s.dHeight,colorMode:null,timeSpent:null,timeStamp:null,isCropped:o,toCanvas:this._toCanvas,_sWidth:s.sWidth,_sHeight:s.sHeight,_bUseWebGL:null};let c;try{c=this._getImageData(e,r,n,s,null,{targetColorMode:this.frameColorMode,bUseWebGL:l})}catch(t){if("WebGLError"!==t.name)throw t;c=this._getImageData(e,r,n,s,null,{targetColorMode:this.frameColorMode,bUseWebGL:!1})}if(!c)return null;const u=Date.now();return re._onLog&&re._onLog("DCE: _getVideoFrame(region?) END: "+u),h.data=c.data,h.colorMode=c.colorMode,h._bUseWebGL=c._bUseWebGL,h.timeSpent=u-t,h.timeStamp=u,h};(e=>{let t=this._cvsSingleFrameMode;if(!t){if(t=document.createElement("canvas"),t.style.pointerEvents="none",!this._video)throw new Error("'video' is null.");this._video.after(t),t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.left="0",t.style.top="0",t.style.objectFit="contain",this._cvsSingleFrameMode=t}t.width==r&&t.height==n||(t.width=r,t.height=n);const i=t.getContext("2d");i.clearRect(0,0,t.width,t.height),i.drawImage(e,0,0)})(i),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e);let o;this._updateDrawingLayersSize();try{o=s(i)}catch(e){throw e}const a=this.mapCameraEvents.get("singleFrameAcquired");for(let e of a)if(e)try{const t={data:new Uint8Array(o.data),region:JSON.parse(JSON.stringify(o.region)),sx:o.sx,sy:o.sy,width:o.width,height:o.height,colorMode:o.colorMode,timeSpent:o.timeSpent,timeStamp:o.timeStamp,isCropped:o.isCropped,toCanvas:o.toCanvas,_sWidth:o._sWidth,_sHeight:o._sHeight,_bUseWebGL:o._bUseWebGL};yield e.apply(this,[t])}catch(e){console.error(e)}})))),e.style.position="fixed",e.style.left="-1px",e.style.top="-1px",e.style.width="1px",e.style.height="1px",e.style.backgroundColor="transparent",e.style.color="transparent",document.body.appendChild(e)}this._singleFrameModeIpt.click()}},this.styleEls=[],this._frameColorMode=void 0,this._defaultFrameColorMode="RGBA",this.currentFSColorMode="rgba",this.ifReuseArrayBufferView=!1,this.maxVideoCvsLength=3,this._reusedCvs=null,this._reusedWebGLCvs=null,this._reusedWebGLCtx=null,this._reusedDataContainer=null,this._webGLTexture=null,this._webGLProgramInfo=null,this._webGLBuffers=null,this._recordedStates={},this._toCanvas=function(){const e=document.createElement("canvas");let t;if(e.width=this.width,e.height=this.height,"grey"===this.colorMode){t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;eB(this,void 0,void 0,(function*(){yield this.selectCamera(this._selCam.value),this._bOpen||this.stop()})),this._onResolutionSelChange=()=>B(this,void 0,void 0,(function*(){let e,t;if(this._selRsl&&-1!=this._selRsl.selectedIndex){let i=this._selRsl.options[this._selRsl.selectedIndex];e=i.getAttribute("data-width"),t=i.getAttribute("data-height")}yield this.setResolution(e,t),this._bOpen||this.stop()})),this._onCloseBtnClick=()=>{this.close(!0)},this._bOpen=!1,this.isCameraEnhancer=!0,this.isDisposed=!1,this.videoSrc=null,this.videoSettings={video:{width:{ideal:1280},height:{ideal:720},facingMode:{ideal:"environment"}}},this.iPlayRound=0,this.promisePlay=null,this._ifSaveLastUsedCamera=!1,this.ifSkipCameraInspection=!1,this._allCameras=[],this._currentCamera=null,this._videoTrack=null,this._lastDeviceId=void 0,this._vc_bPlayingVideoBeforeHide=!1,this._ev_documentHideEvent=()=>{"visible"===document.visibilityState?this._vc_bPlayingVideoBeforeHide&&("Firefox"==W.browser?this.play():this._video.play(),this._vc_bPlayingVideoBeforeHide=!1):this._video&&!this._video.paused&&(this._vc_bPlayingVideoBeforeHide=!0,this._video.pause())},this._divVideoContainer=null,this._video=null,this.videoFit="contain",this._cvsScanRegion=null,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=2,this._bShowScanRegionMask=!0,this._bShowScanRegionLaser=void 0,this._defaultBShowScanRegionLaser=!1,this._scanRegion=null,this._arrScanRegionOverlays=[],this._layerBaseCvs=null,this._cvsViewDecorator=null,this._decoratorType=[],this._decoratorArea=null,this._viewDecoratorInfo={rectangle:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},focus:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},crossline:{lineWidth:2,strokeStyle:"rgb(254,142,20)"},crosshair:{lineWidth:4,strokeStyle:"rgb(254,142,20)"}},this._croppingRegions=void 0,this._defaultCroppingRegions=[null],this.bIncreaseRegionIndexAuto=!0,this._croppingRegionIndex=0,this._loopInterval=void 0,this._defaultLoopInterval=0,this._maxNumberOfFramesInBuffer=void 0,this._defaultMaxNumberOfFramesInBuffer=1,this._frameQueue=[],this._bFetchingLoopStarted=!1,this._refreshInterval=void 0,this._defaultRefreshInterval=-1,this._updateLayersTimeout=0,this._updateLayers=()=>{this._resizeTimeoutId&&clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=setTimeout((()=>{if(!this.isDisposed){this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e)}}),this._updateLayersTimeout)},this.mapCameraEvents=new Map([["cameraOpen",[]],["cameraClose",[]],["cameraChange",[]],["resolutionChange",[]],["played",[]],["singleFrameAcquired",[]],["frameAddedToBuffer",[]]]),this._controler=null}static getVersion(){return this._version}static detectEnvironment(){return B(this,void 0,void 0,(function*(){return yield(async()=>({wasm:H,worker:X,getUserMedia:Y,camera:await z(),browser:W.browser,version:W.version,OS:W.OS}))()}))}static set engineResourcePath(e){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");re._engineResourcePath=(e=>{if(null==e&&(e="./"),!j){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get engineResourcePath(){return this._engineResourcePath}static isStorageAvailable(e){let t;try{t=window[e];const i="__storage_test__";return t.setItem(i,i),t.removeItem(i),!0}catch(e){return e instanceof DOMException&&(22===e.code||1014===e.code||"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)&&t&&0!==t.length}}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"data"in e&&"region"in e&&"sx"in e&&"sy"in e&&"width"in e&&"height"in e&&"colorMode"in e&&"timeSpent"in e&&"timeStamp"in e&&"isCropped"in e&&"toCanvas"in e&&"_sWidth"in e&&"_sHeight"in e&&"_bUseWebGL"in e}set maxCvsSideLength(e){if(e<=0)throw new Error("Invalid value.");this._maxCvsSideLength=e}get maxCvsSideLength(){if(void 0!==this._maxCvsSideLength)return this._maxCvsSideLength;if(this._controler){const e=this._controler.getPropertyDisiredValue("maxCvsSideLength");if(e&&1===e.length)return e[0]}return this._defaultMaxCvsSideLength}static set defaultUIElementURL(e){re._defaultUIElementURL=e}static get defaultUIElementURL(){var e;return null===(e=re._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",re.engineResourcePath)}getUIElement(){return this.UIElement}setUIElement(e){return B(this,void 0,void 0,(function*(){if(this._bOpen)throw new Error("It is not allowed to change the UIElement when the camera is open.");if("string"==typeof e||e instanceof String){if(!e.trim().startsWith("<")){let t=yield fetch(e);if(!t.ok)throw Error("setUIElement(elementOrUrl): Network Error: "+t.statusText);e=yield t.text()}if(!e.trim().startsWith("<"))throw Error("setUIElement(elementOrUrl): Can't get valid HTMLElement.");let t=document.createElement("div");t.innerHTML=e;for(let e=0;e100||e.regionTop>100||e.regionRight>100||e.regionBottom>100)))}set scanRegion(e){if(!this._checkValidRegion(e))throw new Error("Invalid region.");this._scanRegion=JSON.parse(JSON.stringify(e)),this._updateScanRegionCanvas(),this._updateScanAreaDiv();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e)}setScanRegion(e){this.scanRegion=e}getScanRegion(){return JSON.parse(JSON.stringify(this._scanRegion))}_calculateCvsSize(){if(!this._bOpen)return null;let e,t,i;if(this.singleFrameMode)e=this._imgWidth,t=this._imgHeight,i="contain";else{if(!this._video)return null;e=this._video.videoWidth,t=this._video.videoHeight,i=this.getVideoFit()}return{width:e,height:t,objectFit:i}}addScanRegionOverlayCanvas(){this._assertOpen();const e=document.createElement("canvas");if(this._updateScanRegionOverlay(e),!this._scanRegionOverlayContainer){const e=document.createElement("div");if(this._scanRegionOverlayContainer=e,e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e.style.overflow="hidden",e.style.pointerEvents="none",this._layerBaseCvs)this._layerBaseCvs.parentElement.after(e);else if(this._cvsScanRegion)this._cvsScanRegion.before(e);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(e);else{if(!this._video)throw new Error("'video' is null.");this._video.after(e)}this._recordedStates.overlayShow=!0}return this._scanRegionOverlayContainer.append(e),this._arrScanRegionOverlays.push(e),e}removeScanRegionOverlayCanvas(e){const t=this._arrScanRegionOverlays.indexOf(e);-1!==t&&(e.remove(),this._arrScanRegionOverlays.splice(t,1))}_updateScanRegionOverlay(e){if(!e)return;const t=this._calculateCvsSize();if(!t)return;const{width:i,height:r,objectFit:n}=t;if(i<=0||r<=0)return e.width=0,void(e.height=0);const s=this._getRegionInPixels(i,r,this._scanRegion),o=this.getFrameSize(i,r,this._scanRegion,this.maxCvsSideLength),a=o.dWidth,l=o.dHeight;e.width==a&&e.height==l||(e.width=a,e.height=l);const h=window.getComputedStyle(this._video),c=parseFloat(h.width),u=parseFloat(h.height),d=c/u,f=i/r;let g,_,p,m,v=1;"contain"===n?(dd?(v=u/r,g=s.regionLeft*v-(i*v-c)/2,_=s.regionTop*v):(v=c/i,g=s.regionLeft*v,_=s.regionTop*v-(r*v-u)/2),p=(s.regionRight-s.regionLeft)*v,m=(s.regionBottom-s.regionTop)*v):(g=0,_=0,p=0,m=0),e.style.position="absolute",e.style.left=g+"px",e.style.top=_+"px",e.style.width=p+"px",e.style.height=m+"px"}showScanRegionOverlays(){this._scanRegionOverlayContainer&&("none"==this._scanRegionOverlayContainer.style.display&&(this._scanRegionOverlayContainer.style.display=""),this._recordedStates.overlayShow=!0)}hideScanRegionOverlays(){this._scanRegionOverlayContainer&&(this._scanRegionOverlayContainer.style.display="none",this._recordedStates.overlayShow=!1)}setViewDecorator(e,t){if(!e)return void(this._cvsViewDecorator&&(this._cvsViewDecorator.remove(),this._cvsViewDecorator=null));this._assertOpen();let i=[];if("string"==typeof e?i.push(e):Array.isArray(e)&&(i=JSON.parse(JSON.stringify(e))),!this._cvsViewDecorator){if(this._cvsViewDecorator=document.createElement("canvas"),this._cvsViewDecorator.style.pointerEvents="none",this._cvsScanRegion)this._cvsScanRegion.after(this._cvsViewDecorator);else if(this._scanRegionOverlayContainer)this._scanRegionOverlayContainer.after(this._cvsViewDecorator);else if(this._layerBaseCvs)this._layerBaseCvs.parentElement.after(this._cvsViewDecorator);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(this._cvsViewDecorator);else{if(!this._video)throw new Error("'video' is null.");this._video.after(this._cvsViewDecorator)}this._recordedStates.decoratorShow=!0}this._decoratorArea=JSON.parse(JSON.stringify(t)),this._decoratorType.length=0;const r=["rectangle","focus"],n=["crossline","crosshair"];let s=!1,o=!1;for(let e of i)e=e.toLowerCase(),r.includes(e)&&!s&&(s=!0,this._decoratorType.push(e)),n.includes(e)&&!o&&(o=!0,!this._decoratorType.includes(e)&&this._decoratorType.push(e));this._updateViewDecorator()}getViewDecorator(){return{type:JSON.parse(JSON.stringify(this._decoratorType)),area:JSON.parse(JSON.stringify(this._decoratorArea)),canvas:this._cvsViewDecorator}}showViewDecorator(){this._cvsViewDecorator&&("none"==this._cvsViewDecorator.style.display&&(this._cvsViewDecorator.style.display=""),this._recordedStates.decoratorShow=!0)}hideViewDecorator(){this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none",this._recordedStates.decoratorShow=!1)}setViewDecoratorLineWidth(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("lineWidth"))throw new Error(`It is not allowed to change the property 'lineWidth' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].lineWidth=t,this._updateViewDecorator()}setViewDecoratorStrokeStyle(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("strokeStyle"))throw new Error(`It is not allowed to change the property 'strokeStyle' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].strokeStyle=t,this._updateViewDecorator()}setViewDecoratorFillStyle(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("fillStyle"))throw new Error(`It is not allowed to change the property 'fillStyle' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].fillStyle=t,this._updateViewDecorator()}setViewDecoratorMaskFillStyle(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("maskFillStyle"))throw new Error(`It is not allowed to change the property 'maskFillStyle' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].maskFillStyle=t,this._updateViewDecorator()}_updateViewDecorator(){if(!this._bOpen)return;if(!this._cvsViewDecorator||!this._decoratorArea)return;let e;if(this.singleFrameMode)e="contain";else{if(!this._video)return;e=this.getVideoFit()}const t=this._cvsViewDecorator;t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.left="0",t.style.top="0",t.style.objectFit=e;const i=this.getVisibleRegion(!0),r=i.regionRight-i.regionLeft,n=i.regionBottom-i.regionTop;if(t.width==r&&t.height==n||(t.width=r,t.height=n),r<=0||n<=0)return;const s=t.getContext("2d");s.clearRect(0,0,t.width,t.height);const o=this._decoratorArea.x/100*r,a=this._decoratorArea.y/100*n,l=this._decoratorArea.width/100*r,h=this._decoratorArea.height/100*n;for(let e of this._decoratorType){if("rectangle"===e){s.fillStyle=this._viewDecoratorInfo.rectangle.maskFillStyle,s.fillRect(0,0,t.width,t.height),s.clearRect(Math.round(o),Math.round(a),Math.round(l),Math.round(h)),s.fillStyle=this._viewDecoratorInfo.rectangle.fillStyle,s.fillRect(Math.round(o),Math.round(a),Math.round(l),Math.round(h)),s.lineWidth=this._viewDecoratorInfo.rectangle.lineWidth,s.strokeStyle=this._viewDecoratorInfo.rectangle.strokeStyle;const e=s.lineWidth/2;s.strokeRect(Math.round(o-e),Math.round(a-e),Math.round(l+s.lineWidth),Math.round(h+s.lineWidth))}if("focus"===e){s.fillStyle=this._viewDecoratorInfo.focus.maskFillStyle,s.fillRect(0,0,t.width,t.height),s.clearRect(Math.round(o),Math.round(a),Math.round(l),Math.round(h)),s.fillStyle=this._viewDecoratorInfo.focus.fillStyle,s.fillRect(Math.round(o),Math.round(a),Math.round(l),Math.round(h)),s.lineWidth=this._viewDecoratorInfo.focus.lineWidth,s.strokeStyle=this._viewDecoratorInfo.focus.strokeStyle;const e=s.lineWidth/2,i=[0,.25,.75,1],r=[0,.25,.75,1];s.beginPath();for(let e=0;e{const e=parseFloat(window.getComputedStyle(this._video).width),t=parseFloat(window.getComputedStyle(this._video).height);let s,o={regionBottom:r,regionRight:i,regionLeft:0,regionTop:0,regionMeasuredByPercentage:!1};return"cover"===n?e/tthis.maxNumberOfFramesInBuffer;)this._frameQueue.shift()}get maxNumberOfFramesInBuffer(){if(void 0!==this._maxNumberOfFramesInBuffer)return this._maxNumberOfFramesInBuffer;if(this._controler){const e=this._controler.getPropertyDisiredValue("maxNumberOfFramesInBuffer");if(e&&1===e.length)return e[0]}return this._defaultMaxNumberOfFramesInBuffer}get numberOfFramesInBuffer(){return this._frameQueue.length}set refreshInterval(e){this._refreshInterval=e}get refreshInterval(){if(void 0!==this._refreshInterval)return this._refreshInterval;if(this._controler){const e=this._controler.getPropertyDisiredValue("refreshInterval");if(e&&1===e.length)return e[0]}return this._defaultRefreshInterval}static createInstance(e){return B(this,void 0,void 0,(function*(){let t=new re;("string"==typeof e||e instanceof String)&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return this._hasEngineResourceLoaded=!0,re.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{re.onWarning&&re.onWarning({id:1,message:"Not using HTTP protocol, the SDK may not work correctly."})}),0):location&&"https:"!==location.protocol&&setTimeout((()=>{re.onWarning&&re.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)),t._drawingLayersManager=new te,t}))}play(e,t,i,r){return B(this,void 0,void 0,(function*(){if(this._video&&this.videoSrc){yield new Promise(((e,t)=>{this._video.onloadedmetadata=()=>B(this,void 0,void 0,(function*(){this._video&&(this._video.onloadedmetadata=null,yield this._video.play(),e())})),"string"==typeof this.videoSrc||this.videoSrc instanceof String?this._video.src=this.videoSrc:this._video.srcObject=this.videoSrc,setTimeout((()=>t(new Error("Failed to play video. Timeout."))),4e3)}));const e={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};this.playCallbackInfo=JSON.parse(JSON.stringify(e));const t=this.mapCameraEvents.get("played");for(let i of t){if(!i)continue;const t=JSON.parse(JSON.stringify(e));setTimeout((()=>i.apply(this,[t])),0)}return this._recordedStates.videoPlaying=!0,e}if(this.singleFrameMode)return r&&r.notTriggerSingleFrameClick||this._clickIptSingleFrameMode(),this.playCallbackInfo={width:0,height:0,deviceId:null},JSON.parse(JSON.stringify(this.playCallbackInfo));if(!this._video)return this.playCallbackInfo=null,null;const n=++this.iPlayRound;let s=null,o=0,a=0;if(this._currentCamera&&(s=this._currentCamera.deviceId),this._video&&(o=this._video.videoWidth,a=this._video.videoHeight),this.promisePlay&&(yield this.promisePlay,nB(this,void 0,void 0,(function*(){var r;try{this._video&&this._video.srcObject&&this.stop(),re._onLog&&re._onLog("DCE: ======before video========");const n=()=>{if(!this._video)throw d&&d.getTracks().forEach((e=>{e.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null.")},l=this.getVideoSettings();let h;"boolean"==typeof l.video&&(l.video={});const c=["rear","back","rück","arrière","trasera","trás","traseira","posteriore","后面","後面","背面","后置","後置","背置","задней","الخلفية","후","arka","achterzijde","หลัง","baksidan","bagside","sau","bak","tylny","takakamera","belakang","אחורית","πίσω","spate","hátsó","zadní","darrere","zadná","задня","stražnja","belakang","बैक"],u=()=>{for(let e of this._allCameras){let t=e.label.toLowerCase();if(t&&c.some((e=>-1!=t.indexOf(e)))&&/\b0(\b)?/.test(t)){delete l.video.facingMode,l.video.deviceId={ideal:e.deviceId};break}}l.video.deviceId||-1==["Android","HarmonyOS"].indexOf(W.OS)||(delete l.video.facingMode,l.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})};if(e)delete l.video.facingMode,l.video.deviceId={exact:e};else if(l.video.deviceId);else if(this._lastDeviceId)delete l.video.facingMode,l.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&re.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete l.video.facingMode,l.video.deviceId={exact:window.localStorage.getItem("dce_last_camera_id")};const w=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),T=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));w&&T&&(l.video.width=w,l.video.height=T)}else if(this.ifSkipCameraInspection);else if(l.video.facingMode){if("iPhone"!==W.OS&&"Mac"!==W.OS&&(yield this.getAllCameras(!0)),!this._video)return null;let x=l.video.facingMode;x instanceof Array&&x.length&&(x=x[0]),x=x.exact||x.ideal||x,"environment"===x&&(h=!!l.video.facingMode,u())}let d;t&&(l.video.width={ideal:t}),i&&(l.video.height={ideal:i}),re._onLog&&re._onLog("DCE: ======try getUserMedia========");let f,g=[0,500],_=null,p=null;function m(e){return B(this,void 0,void 0,(function*(){for(let t of g){n(),t&&(yield new Promise((e=>setTimeout(e,t)))),n();{const t=e.video.deviceId;p=t?t.exact||t.ideal||t:null}try{re._onLog&&re._onLog("DCE: ask "+JSON.stringify(e)),d=yield navigator.mediaDevices.getUserMedia(e),n();break}catch(e){_=e,re._onLog&&re._onLog("DCE: "+e.message||e)}}}))}if(yield m(l),d||(re._onLog&&re._onLog("DCE: ======try getUserMedia again========"),f=JSON.parse(JSON.stringify(l)),"object"==typeof f.video&&("iPhone"==W.OS?(t>=1280||i>=1280?f.video.width=1280:t>=640||i>=640?f.video.width=640:(t<640||i<640)&&(f.video.width=320),delete f.video.height):h&&!l.video.deviceId?(delete f.video.facingMode,this._allCameras.length&&(f.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):f.video=!0),re._onLog&&re._onLog("DCE: "+f),yield m(f)),d||(g=[1e3,2e3],yield m(l)),d||(yield m(f)),!d)throw _;const v=()=>{const e=d.getVideoTracks();let t,i;if(e.length&&(t=this._videoTrack=e[0]),this._video&&t){const e=t.getSettings();if(e)for(let r of this._allCameras)if(e.deviceId===r.deviceId){r._checked=!0,r.label=t.label,i=r;break}if(!i&&p)for(let e of this._allCameras)if(p==e.deviceId){t.label&&(e._checked=!0,e.label=t.label),i=e;break}}this._currentCamera=i};if(yield this.getAllCameras(!0),n(),h){v(),u();let A=l.video.deviceId;A&&(A=A.exact||A.ideal||A);let O=null===(r=this._currentCamera)||void 0===r?void 0:r.deviceId;!A||O&&A==O||(d.getTracks().forEach((e=>{e.stop()})),g=[0,500,1e3,2e3],yield m(l))}n();const y=()=>B(this,void 0,void 0,(function*(){re._onLog&&re._onLog("======play video========"),yield new Promise(((e,t)=>{n(),this._video.onloadedmetadata=()=>B(this,void 0,void 0,(function*(){n(),this._video.onloadedmetadata=null,yield this._video.play(),e()})),this._video.srcObject=d,setTimeout((()=>t(new Error("Failed to play video. Timeout."))),4e3)}))}));yield y(),n(),re._onLog&&re._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const S=this._video.videoWidth+"x"+this._video.videoHeight;this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",this._video.videoWidth),this._optGotRsl.setAttribute("data-height",this._video.videoHeight),this._optGotRsl.innerText=S,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),re._onLog&&re._onLog("DCE: got "+S),v(),n(),this._renderSelCameraInfo();const b={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};b.deviceId&&(this._lastDeviceId=b.deviceId,this.ifSaveLastUsedCamera&&re.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),l.video.width&&l.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(l.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(l.video.height)))));const C=this.mapCameraEvents.get("played");for(let I of C){if(!I)continue;const E=JSON.parse(JSON.stringify(b));setTimeout((()=>I.apply(this,[E])),0)}if(s&&s!=b.deviceId){const R=this.mapCameraEvents.get("cameraChange");for(let D of R){if(!D)continue;const M=JSON.parse(JSON.stringify(b));setTimeout((()=>D.apply(this,[M])),0)}}if(o&&a&&(o!=b.width||a!=b.height)){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let P of this._arrScanRegionOverlays)P&&this._updateScanRegionOverlay(P);this._cvsOriginalImage||this._updateDrawingLayersSize();const L=this.mapCameraEvents.get("resolutionChange");for(let F of L){if(!F)continue;const k=JSON.parse(JSON.stringify(b));setTimeout((()=>F.apply(this,[k])),0)}}return this.promisePlay=null,b}catch(j){throw this.promisePlay=null,this._bgLoading&&(this._bgLoading.style.display="none"),"NotFoundError"===j.name&&(DOMException?j=new DOMException("No camera available, please use a device with an accessible camera.",j.name):(j=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),j}})))();const l=yield this.promisePlay;return this.playCallbackInfo=JSON.parse(JSON.stringify(l)),this._recordedStates.videoPlaying=!0,l}))}resume(){return B(this,void 0,void 0,(function*(){this._assertOpen(),yield this.play(),this.ifShowScanRegionLaser&&this.showScanRegionLaser()}))}pause(){this._assertOpen(),this._video&&(this._video.pause(),this._recordedStates.videoPlaying=!1),this.ifShowScanRegionLaser&&this.hideScanRegionLaser()}_bindUI(){if(!this.UIElement)throw new Error("Need to define `UIElement` before opening.");const e=[this.UIElement];for(let t=0;t','','',''].join(""),this._optGotRsl=this._optGotRsl||this._selRsl.options[0])):!this._optGotRsl&&t.classList.contains("dce-opt-gotResolution")?this._optGotRsl=t:!this._btnClose&&t.classList.contains("dce-btn-close")?this._btnClose=t:!this._selMinLtr&&t.classList.contains("dlr-sel-minletter")?(this._selMinLtr=t,this._selMinLtr.options.length||(this._selMinLtr.innerHTML=[this._optGotMinLtr?"":'','','','','','','','','','',''].join(""),this._optGotMinLtr=this._optGotMinLtr||this._selMinLtr.options[0])):!this._optGotMinLtr&&t.classList.contains("dlr-opt-gotMinLtr")&&(this._optGotMinLtr=t);if(this.extraBindings&&this.extraBindings.length)for(let i of this.extraBindings)try{i(t)}catch(e){}}if(!this._video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'");this.singleFrameMode?(this._video&&(this._video.addEventListener("click",this._clickIptSingleFrameMode),this._video.style.cursor="pointer",this._video.setAttribute("title","Take a photo")),this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none"),this._bgCamera&&(this._bgCamera.style.display="block")):(this._selCam&&(this._selCam.style.display="block",this._selCam.addEventListener("change",this._onCameraSelChange)),this._selRsl&&(this._selRsl.style.display="block",this._selRsl.addEventListener("change",this._onResolutionSelChange)),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._bgLoading&&(this._bgLoading.style.display="block")),this._btnClose&&this._btnClose.addEventListener("click",this._onCloseBtnClick),document.addEventListener("visibilitychange",this._ev_documentHideEvent),ResizeObserver?(this._resizeObserver||(this._resizeObserver=new ResizeObserver((e=>{for(let t of e)t.target===this._divVideoContainer&&this._updateLayers()}))),this._divVideoContainer&&this._resizeObserver.observe(this._divVideoContainer)):window.addEventListener("resize",this._updateLayers)}_unbindUI(){this.singleFrameMode?(this._video&&(this._video.removeEventListener("click",this._clickIptSingleFrameMode),this._video.style.cursor="",this._video.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._bgLoading&&(this._bgLoading.style.display="none"),this._selCam&&this._selCam.removeEventListener("change",this._onCameraSelChange),this._selRsl&&this._selRsl.removeEventListener("change",this._onResolutionSelChange),this._btnClose&&this._btnClose.removeEventListener("click",this._onCloseBtnClick),this.hideScanRegionLaser(),this.hideViewDecorator(),this.hideScanRegionOverlays(),this._drawingLayersManager.setVisible(!1),this._hideOriginalImageCvs(),this._video&&(this._video.onloadedmetadata=null,this._video.remove()),this._divVideoContainer=null,this._video=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._cvsScanRegion&&(this._cvsScanRegion.remove(),this._cvsScanRegion=null),this._singleFrameModeIpt&&(this._singleFrameModeIpt.remove(),this._singleFrameModeIpt=null),this._cvsSingleFrameMode&&(this._cvsSingleFrameMode.remove(),this._cvsSingleFrameMode=null),document.removeEventListener("visibilitychange",this._ev_documentHideEvent),ResizeObserver?this._resizeObserver&&this._resizeObserver.disconnect():window.removeEventListener("resize",this._updateLayers)}_assertOpen(){if(!this._bOpen)throw Error("The camera is not open.")}open(e){return B(this,void 0,void 0,(function*(){this.UIElement||(yield this.setUIElement(re.defaultUIElementURL)),this._bindUI(),e&&this.appendAndShowUI();let t=yield this.play();this.bOpen=!0;const i=this.mapCameraEvents.get("cameraOpen");for(let e of i){if(!e)continue;const i=JSON.parse(JSON.stringify(t));setTimeout((()=>e.apply(this,[i])),0)}return t}))}close(e){if(!this._video)return;this.stop(),this._hideOriginalImage(!1),this._unbindUI(),e&&this.hideUI(),this.stopFetchingLoop(),this.bOpen=!1;const t=this.mapCameraEvents.get("cameraClose");for(let e of t){if(!e)continue;const t={width:0,height:0,deviceId:null};setTimeout((()=>e.apply(this,[t])),0)}}stop(){this._video&&this._video.srcObject&&(re._onLog&&re._onLog("DCE: ======stop video========"),this._video.srcObject.getTracks().forEach((e=>{e.stop()})),this._video.srcObject=null,this._videoTrack=null,this._currentCamera=null),this._video&&this.videoSrc&&(re._onLog&&re._onLog("DCE: ======stop existing video========"),this._video.pause(),this._video.currentTime=0),this._bgLoading&&(this._bgLoading.style.animationPlayState=""),this._frameQueue.length=0,this._reusedCvs&&this._reusedCvs.ctx2d&&this._reusedCvs.ctx2d.clearRect(0,0,this._reusedCvs.width,this._reusedCvs.height),this.forceLoseContext()}getAllCameras(e){return B(this,void 0,void 0,(function*(){let t=yield navigator.mediaDevices.enumerateDevices();if(!e&&t&&t.length&&!t[0].deviceId){let e=yield navigator.mediaDevices.getUserMedia({video:!0});t=yield navigator.mediaDevices.enumerateDevices(),e.getTracks().forEach((e=>{e.stop()})),e=null}const i=[],r=[];if(this._allCameras)for(let e of this._allCameras)e._checked&&r.push(e);for(let e=0;e{const i=this._mapCameraResolutions.get(e);if(!i||!i.length)return!1;for(let e of i)if(e[0]===t.width&&e[1]===t.height)return!0;return!1},r=(e,t,i)=>B(this,void 0,void 0,(function*(){const r={video:{deviceId:{exact:e},width:{ideal:t},height:{ideal:i}}};let n=null;try{n=yield navigator.mediaDevices.getUserMedia(r)}catch(e){return null}if(!n)return null;const s=n.getVideoTracks();let o=null;try{const e=s[0].getSettings();o={width:e.width,height:e.height}}catch(e){const t=document.createElement("video");t.srcObject=n,o={width:t.videoWidth,height:t.videoHeight},t.srcObject=null}return s.forEach((e=>{e.stop()})),o}));if(!this._bOpen){const n=this.videoSettings.video.deviceId;if(!n)return null;if(t=n.hasOwnProperty("exact")?this.videoSettings.video.deviceId.exact:n.hasOwnProperty("ideal")?this.videoSettings.video.deviceId.ideal:this.videoSettings.video.deviceId,!t)return null;let s=this._mapCameraResolutions.get(t);if(s&&!e)return this._mapCameraResolutions.get(t);this._mapCameraResolutions.set(t,[]),s=this._mapCameraResolutions.get(t);for(let e of this._predefinedResolutions){const n=yield r(t,e.width,e.height);n&&!i(t,n)&&s.push([n.width,n.height])}return s}if(this._currentCamera){t=this._currentCamera.deviceId;let r=this._mapCameraResolutions.get(t);if(r&&!e)return this._mapCameraResolutions.get(t);this._mapCameraResolutions.set(t,[]),r=this._mapCameraResolutions.get(t);const n=this.getConstraints();for(let e of this._predefinedResolutions){yield this._videoTrack.applyConstraints({width:{ideal:e.width},height:{ideal:e.height}});const n=this._videoTrack.getSettings(),s={width:n.width,height:n.height};i(t,s)||r.push([s.width,s.height])}return yield this._videoTrack.applyConstraints(n),r}return null}))}on(e,t){if(!this.mapCameraEvents.has(e))throw new Error(`Event '${e}' is not exists.`);const i=this.mapCameraEvents.get(e);i.includes(t)||i.push(t)}off(e,t){if(!this.mapCameraEvents.has(e))throw new Error(`Event '${e}' is not exists.`);const i=this.mapCameraEvents.get(e),r=i.indexOf(t);-1!==r&&i.splice(r,1)}offAll(e){if(e){if("string"==typeof e){const t=this.mapCameraEvents.get(e);t&&(t.length=0)}}else for(let e of this.mapCameraEvents.values())e&&(e.length=0)}getVideoSettings(){return JSON.parse(JSON.stringify(this.videoSettings))}updateVideoSettings(e){return this.videoSettings=JSON.parse(JSON.stringify(e)),this._lastDeviceId=null,this._bOpen?this.play():Promise.resolve()}isOpen(){return this._bOpen}getCapabilities(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCapabilities()' is unavailable in singleFrameMode.");return this._videoTrack&&this._videoTrack.getCapabilities?this._videoTrack.getCapabilities():{}}getCameraSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCameraSettings()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings():null}getConstraints(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getConstraints()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getConstraints():null}applyConstraints(e){return B(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'applyConstraints()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error('"_videoTrack" is null.');if(!this._videoTrack.applyConstraints)throw Error("Not supported.");return yield this._videoTrack.applyConstraints(e)}))}turnOnTorch(){return B(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOnTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return yield this._videoTrack.applyConstraints({advanced:[{torch:!0}]});throw Error("Not supported.")}))}turnOffTorch(){return B(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOffTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return yield this._videoTrack.applyConstraints({advanced:[{torch:!1}]});throw Error("Not supported.")}))}setColorTemperature(e){return B(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setColorTemperature()' is unavailable in singleFrameMode.");let t=this.getCapabilities().colorTemperature;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),yield this._videoTrack.applyConstraints({advanced:[{colorTemperature:e}]})}))}setExposureCompensation(e){return B(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setExposureCompensation()' is unavailable in singleFrameMode.");let t=this.getCapabilities().exposureCompensation;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),yield this._videoTrack.applyConstraints({advanced:[{exposureCompensation:e}]})}))}setZoom(e){return B(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setZoom()' is unavailable in singleFrameMode.");let t=this.getCapabilities().zoom;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),yield this._videoTrack.applyConstraints({advanced:[{zoom:e}]})}))}setFrameRate(e){return B(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFrameRate()' is unavailable in singleFrameMode.");let t=this.getCapabilities().frameRate;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),yield this._videoTrack.applyConstraints({width:{ideal:Math.max(this._video.videoWidth,this._video.videoHeight)},frameRate:e})}))}getFrameRate(){return this.getCameraSettings().frameRate}setFocus(e,t){return B(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFocus()' is unavailable in singleFrameMode.");const i=this.getCapabilities().focusMode,r=this.getCapabilities().focusDistance;if(!i||!i.includes(e)||!r)throw Error("Not supported.");return t?(tr.max&&(t=r.max),yield this._videoTrack.applyConstraints({advanced:[{focusMode:e,focusDistance:t}]})):yield this._videoTrack.applyConstraints({advanced:[{focusMode:e}]})}))}getFocus(){const e=this.getCameraSettings().focusMode;return"continuous"===e?{mode:e}:{mode:e,distance:this.getCameraSettings().focusDistance}}getFrameSize(e,t,i,r){if(!e||!t)return null;let n,s,o,a,l=e,h=t;const c={regionLeft:0,regionTop:0,regionRight:l,regionBottom:h,regionMeasuredByPercentage:!1};i?(i.regionMeasuredByPercentage?(c.regionLeft=i.regionLeft*l/100,c.regionTop=i.regionTop*h/100,c.regionRight=i.regionRight*l/100,c.regionBottom=i.regionBottom*h/100):(c.regionLeft=i.regionLeft,c.regionTop=i.regionTop,c.regionRight=i.regionRight,c.regionBottom=i.regionBottom),n=c.regionLeft,s=c.regionTop,l=Math.round(c.regionRight-c.regionLeft),h=Math.round(c.regionBottom-c.regionTop)):(n=0,s=0);const u=Math.max(l,h);if(r&&r>0&&u>r){const e=r/u;l>h?(o=r,a=Math.round(h*e)):(o=Math.round(l*e),a=r)}else o=l,a=h;return o<=0||a<=0?null:{sx:n,sy:s,sWidth:l,sHeight:h,dWidth:o,dHeight:a}}getFrame(){if(this.singleFrameMode)throw Error("'getFrame()' is unavailable in singleFrameMode.");if(this._assertOpen(),this.singleFrameMode)throw new Error("'getFrame()' is unavailable in singleFrameMode.");return this._getVideoFrame(this._scanRegion)}getImage(){const e=this.getFrame();return e.pixelFormat=e.colorMode,Object.assign(Object.assign({},e),{pixelFormat:e.colorMode})}_getVideoFrame(e,t){if(this.isDisposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getVideoFrame()' is unavailable in singleFrameMode.");const i=Date.now();re._onLog&&re._onLog("DCE: _getVideoFrame(region?) START: "+i);const r=this._video.videoWidth,n=this._video.videoHeight;if(0===r||0===n)return null;const s=this.getFrameSize(r,n,e,this.maxCvsSideLength);if(!s)return null;let o,a;o=r!==s.sWidth||n!==s.sHeight,a=s.sWidth!==s.dWidth||s.sHeight!==s.dHeight;const l=(()=>!(!this._bWebGLSupported||a))(),h={data:null,region:e?JSON.parse(JSON.stringify(e)):null,sx:s.sx,sy:s.sy,width:s.dWidth,height:s.dHeight,colorMode:null,timeSpent:null,timeStamp:null,isCropped:o,toCanvas:this._toCanvas,_sWidth:s.sWidth,_sHeight:s.sHeight,_bUseWebGL:null};let c;try{c=this._getImageData(this._video,r,n,s,t,{targetColorMode:this.frameColorMode,bUseWebGL:l})}catch(e){if("WebGLError"!==e.name)throw e;c=this._getImageData(this._video,r,n,s,t,{targetColorMode:this.frameColorMode,bUseWebGL:!1})}if(!c)return null;const u=Date.now();return re._onLog&&re._onLog("DCE: _getVideoFrame(region?) END: "+u),h.data=c.data,h.colorMode=c.colorMode,h._bUseWebGL=c._bUseWebGL,h.timeSpent=u-i,h.timeStamp=u,h}_getImageData(e,t,i,r,n,s){if(this.isDisposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(!t||!i)return null;re._onLog&&re._onLog("DCE: _getImageData() START: "+Date.now());const{sx:o,sy:a,sWidth:l,sHeight:h,dWidth:c,dHeight:u}=r;let d;if(d=s&&s.targetColorMode?s.targetColorMode.toLowerCase():"rgba",s&&s.bUseWebGL){this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas"));const r=this._reusedWebGLCvs;r.width==t&&r.height==i||(r.width=t,r.height=i,this._reusedWebGLCtx&&this._reusedWebGLCtx.viewport(0,0,t,i));const s=this._reusedWebGLCtx||r.getContext("webgl",{antialias:!1})||r.getContext("experimental-webgl",{antialias:!1});if(!s){this._reusedWebGLCtx=null,this._bWebGLSupported=!1;const e=new Error("WebGL error: unable to initialize WebGL. Your browser or machine may not support it.");throw e.name="WebGLError",e}if(s.enable(s.SCISSOR_TEST),s.scissor(o,a,c,u),!this._reusedWebGLCtx||d!==this.currentFSColorMode){this._reusedWebGLCtx=s;const e=e=>{const t=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,t),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,1,1,-1,1]),e.STATIC_DRAW);const i=e.createBuffer();return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,i),e.bufferData(e.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,0,2,3]),e.STATIC_DRAW),{position:t,indices:i}},t=e=>{const t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),t},i=(e,t,i)=>{const n=r(e,e.VERTEX_SHADER,t),s=r(e,e.FRAGMENT_SHADER,i),o=e.createProgram();return e.attachShader(o,n),e.attachShader(o,s),e.linkProgram(o),e.getProgramParameter(o,e.LINK_STATUS)?o:(alert("Unable to initialize the shader program: "+e.getProgramInfoLog(o)),null)},r=(e,t,i)=>{const r=e.createShader(t);return e.shaderSource(r,i),e.compileShader(r),e.getShaderParameter(r,e.COMPILE_STATUS)?r:(alert("An error occurred compiling the shaders: "+e.getShaderInfoLog(r)),e.deleteShader(r),null)},n="\n attribute mediump vec2 aVertexPosition;\n varying mediump vec2 vDirection;\n \n void main( void )\n {\n gl_Position = vec4(aVertexPosition, 1.0, 1.0) * 2.0;\n vDirection = aVertexPosition;\n }\n ";let o;o=["rgba","rbga","grba","gbra","brga","bgra"].includes(d)?d.slice(0,3):"rgb";const a=i(s,n,`\n precision mediump float;\n\n varying mediump vec2 vDirection;\n uniform sampler2D uSampler;\n uniform lowp float uColorFactor;\n \n void main(void)\n {\n vec4 sample = texture2D(uSampler, vec2(vDirection.x * 0.5 + 0.5, vDirection.y * 0.5 + 0.5));\n lowp float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `);this._webGLProgramInfo={program:a,attribLocations:{vertexPosition:s.getAttribLocation(a,"aVertexPosition")},uniformLocations:{uSampler:s.getUniformLocation(a,"uSampler"),uColorFactor:s.getUniformLocation(a,"uColorFactor")}},this._webGLBuffers=e(s),this._webGLTexture=t(s),this.currentFSColorMode=d}const l=(e,t,i)=>{const r=e.RGBA,n=e.RGBA,s=e.UNSIGNED_BYTE;e.bindTexture(e.TEXTURE_2D,t),e.texImage2D(e.TEXTURE_2D,0,r,n,s,i)},h=(e,t,i,r)=>{e.clearColor(0,0,0,1),e.clearDepth(1),e.enable(e.DEPTH_TEST),e.depthFunc(e.LEQUAL),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,i.indices),e.useProgram(t.program);{const r=2,n=e.FLOAT,s=!1,o=0,a=0;e.bindBuffer(e.ARRAY_BUFFER,i.position),e.vertexAttribPointer(t.attribLocations.vertexPosition,r,n,s,o,a),e.enableVertexAttribArray(t.attribLocations.vertexPosition)}e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,r),e.uniform1i(t.uniformLocations.uSampler,0),e.uniform1f(t.uniformLocations.uColorFactor,"grey"===d||"grey32"===d?1:0);const n=e.UNSIGNED_SHORT;e.drawElements(e.TRIANGLES,6,n,0)};let f;if(l(s,this._webGLTexture,e),h(s,this._webGLProgramInfo,this._webGLBuffers,this._webGLTexture),n){if(n.length=this.croppingRegions.length||this._croppingRegionIndex<0)throw new Error("The 'croppingRegionIndex' is out of bounds.");e=this.croppingRegions[this._croppingRegionIndex],this.bIncreaseRegionIndexAuto&&++this._croppingRegionIndex>=this.croppingRegions.length&&(this._croppingRegionIndex=0)}return e}_fetchingLoop(e){if(this.isDisposed)return;if(!this._bOpen||!this.isFetchingLoopStarted())return void this.stopFetchingLoop();const t=()=>{re._onLog&&re._onLog("DCE: start fetching a frame: "+Date.now());const e=this.getCurrentRegion();let t=this._getVideoFrame(e);if(!t)return void(re._onLog&&re._onLog("DCE: get a invalid frame, abandon it: "+Date.now()));for(;this._frameQueue&&this._frameQueue.length>=this.maxNumberOfFramesInBuffer;)this._frameQueue.shift();this._frameQueue.push(t),re._onLog&&re._onLog("DCE: finish fetching a frame: "+Date.now());const i=this.mapCameraEvents.get("frameAddedToBuffer");for(let e of i)e&&setTimeout(e.bind(this),0)},i=()=>{this.isDisposed||(this._frameLoopTimeoutId2&&clearTimeout(this._frameLoopTimeoutId2),this.refreshInterval<=0||(this._frameLoopTimeoutId2=setTimeout((()=>{this.isDisposed||(this._bOpen&&this.isFetchingLoopStarted()?(re._onLog&&re._onLog("DCE: second timeout executes: "+Date.now()),t(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};e&&(this._frameQueue.length0&&i()):this.refreshInterval>0?(t(),i()):0===this.refreshInterval?t():this.refreshInterval),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameLoopTimeoutId=setTimeout((()=>{this.isDisposed||this._fetchingLoop(!0)}),this.loopInterval)}startFetchingLoop(){if(this.isDisposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(this._assertOpen(),this.singleFrameMode)throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,this._recordedStates.fetchingLoopStart=!0,re._onLog&&re._onLog("start fetching loop: "+Date.now()),this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(re._onLog&&re._onLog("stop fetching loop: "+Date.now()),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameQueue.length=0,this._bFetchingLoopStarted=!1,this._recordedStates.fetchingLoopStart=!1)}getFrameFromBuffer(e){return this._frameQueue&&this._frameQueue.length?e?e0?i-1:r,Z),actionName:"modifyPolygon",pointIndex:i}),e}),{})}_extendSet(e,t){if("vertices"===e){const e=this._fabricObject;e.points=t;const i=e.points.length-1;return e.controls=e.points.reduce((function(e,t,r){return e["p"+r]=new k.Control({positionHandler:q,actionHandler:$(r>0?r-1:i,Z),actionName:"modifyPolygon",pointIndex:r}),e}),{}),e._setPositionDimensions({}),!0}}_extendGet(e){if("vertices"===e){const e=[],t=this._fabricObject;if(t.selectable)for(let i in t.oCoords)e.push({x:t.oCoords[i].x,y:t.oCoords[i].y});else for(let i in t.getCoords())e.push({x:t.getCoords()[i].x,y:t.getCoords()[i].y});return e}}},DT_Rect:class extends J{constructor(e,t,i,r,n){super(new k.Rect({left:e,top:t,width:i,height:r}),n)}},DT_Image:class extends J{constructor(e,t,i,r){super(new k.Image(e,{left:t,top:i}),r),this.image=e}_extendSet(e,t){if("image"===e){if(t instanceof HTMLImageElement)return this._fabricObject.setElement(t),this.image=t,!0;if(t instanceof HTMLCanvasElement){const e=new Image;return e.src=t.toDataURL(),this._fabricObject.setElement(e),this.image=t,!0}throw new Error("Unsupported value.")}}_extendGet(e){if("image"===e)return this.image}},DT_Text:class extends J{constructor(e,t,i,r){super(new k.IText(e,{left:t,top:i}),r),this._mediaType="text"}},DT_Line:class extends J{constructor(e,t,i){super(new k.Line([e.x,e.y,t.x,t.y]),i)}_extendSet(e,t){return"startPoint"===e?(this._fabricObject.set("x1",t.x),this._fabricObject.set("y1",t.y),!0):"endPoint"===e?(this._fabricObject.set("x2",t.x),this._fabricObject.set("y2",t.y),!0):void 0}_extendGet(e){return"startPoint"===e?{x:this._fabricObject.get("x1"),y:this._fabricObject.get("y1")}:"endPoint"===e?{x:this._fabricObject.get("x2"),y:this._fabricObject.get("y2")}:void 0}},DT_Group:class extends J{constructor(e){super(new k.Group(e.map((e=>e._getFabricObject()))));const t=this.mapEvents;this._fabricObject.onSelect=()=>{this.styleSelector="selected";const e=this.mapEvents.get("select");for(let t of e)t&&t.apply(this);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e.onSelect&&e.onSelect()}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)},this._fabricObject.onDeselect=()=>{this.styleSelector="default";const e=t.get("deselect");for(let t of e)t&&t.apply(this);const i=this._fabricObject._objects;for(let e of i)setTimeout((()=>{e.onDeselect&&e.onDeselect()}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)}}getChildItems(){return this._fabricObject._objects.map((e=>e.getDrawingItem()))}addChildItem(e){if(!e||!e.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,e,"add"):this._fabricObject.addWithUpdate(e._getFabricObject())}removeChildItem(e){e&&e.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,e,"remove"):this._fabricObject.removeWithUpdate(e._getFabricObject()))}}};class se extends D{constructor(){super(),this.bFilterRegionInJs=!0,this._onCameraSelChange=()=>{},this._onResolutionSelChange=()=>{},this._onCloseBtnClick=()=>{},this._onPlayed=null}static get version(){return this._version+`(DCE ${re.getVersion()})`}static _fireHTTPSWarnning(){se.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{se.onWarning&&se.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}_fireResolutionWarning(){if(!this.singleFrameMode&&this.onWarning){const e=this.dce.getConstraints();e&&e.width<1280&&e.height<720&&setTimeout((()=>{this.onWarning&&this.onWarning({id:3,message:"Camera resolution too low, please use a higher resolution (720P or better)."})}),0)}}getUIElement(){return this.dce.getUIElement()}async setUIElement(e){await this.dce.setUIElement(e)}get singleFrameMode(){return this.dce.singleFrameMode}set singleFrameMode(e){this.dce.singleFrameMode=e,e&&(this.dce.ifShowScanRegionLaser=!1,(async()=>{let e=await this.getScanSettings();e.oneDTrustFrameCount=1,await this.updateScanSettings(e)})())}get onUnduplicatedRead(){return this.onUniqueRead}set onUnduplicatedRead(e){this.onUniqueRead=e}get video(){return this.dce&&this.dce.video}set videoSrc(e){this.dce&&(this.dce.videoSrc=e)}get videoSrc(){return this.dce&&this.dce.videoSrc}_assertOpen(){if(!this.dce.isOpen())throw Error("The scanner is not open.")}set regionMaskFillStyle(e){this.dce.setScanRegionMaskStyle({fillStyle:e})}get regionMaskFillStyle(){return this.dce.regionMaskFillStyle}set regionMaskStrokeStyle(e){this.dce.setScanRegionMaskStyle({strokeStyle:e})}get regionMaskStrokeStyle(){return this.dce.regionMaskStrokeStyle}set regionMaskLineWidth(e){this.dce.setScanRegionMaskStyle({lineWidth:e})}get regionMaskLineWidth(){return this.dce.regionMaskLineWidth}set region(e){this._region=e,this.dce&&(e?e instanceof Array||this.dce.setScanRegion(e):this.dce.setScanRegion(null)),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e,this.dce.frameColorMode=e?"rgba":"grey"}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}async createDCEInstance(){if(!this.dce){D._onLog&&D._onLog("createDCEInstance()");try{ResizeObserver}catch(e){"ReferenceError"===e.name&&window&&(window.ResizeObserver=void 0)}re.defaultUIElementURL=null,this.dce=await re.createInstance(),this.dce.refreshInterval=200,this.dce.frameColorMode="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this._drawingItemNamespace=ne,"iPhone"!==D.browserInfo.OS&&"Android"!==D.browserInfo.OS&&"HarmonyOS"!==D.browserInfo.OS&&this.dce.setResolution(1920,1080),this.dce.on("cameraChange",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("resolutionChange",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("cameraClose",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1})),this.dce.on("singleFrameAcquired",(async e=>{if(!e)return;if(!e.data)return;let t;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,colorMode:e.colorMode,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{data:i,sx:r,sy:n,width:s,height:o,colorMode:a,timeStamp:l,_sWidth:h,_sHeight:c}=e,u={timeStamp:l};if("grey"===a)t=await this._decodeBuffer_Uint8Array(i,s,o,s,_.IPF_GrayScaled,u);else if("rgba"===a)t=await this._decodeBuffer_Uint8Array(i,s,o,4*s,_.IPF_ABGR_8888,u);else{if("bgra"!==a)throw new Error(`Color mode '${a}' is not supported.`);t=await this._decodeBuffer_Uint8Array(i,s,o,4*s,_.IPF_ARGB_8888,u)}if(await this.clearMapDecodeRecord(),D.recalculateResultLocation(t,r,n,h,c,s,o),this._drawResults(t),this.onFrameRead&&this.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(t);this.onFrameRead(e)}if(this.onUniqueRead&&this.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e))}))}}set maxCvsSideLength(e){this._maxCvsSideLength=e,this.dce.maxCvsSideLength=e}get maxCvsSideLength(){return this._maxCvsSideLength}static async createInstance(e){let t=new se;t._instanceID=await se.createInstanceInWorker(!0),await t.createDCEInstance(),"string"==typeof e&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return await t.dce.setUIElement(se.defaultUIElementURL),t.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),se._fireHTTPSWarnning(),t.singleFrameMode||await t.updateRuntimeSettings("single"),t}async decodeCurrentFrame(e){this._assertOpen();let t=null;e&&e.region&&(t=e.region);const i=this.dce._getVideoFrame(t);return this._decode_DCEFrame(i)}static isRegionNormalPreset(e){return 0==e.regionLeft&&0==e.regionTop&&0==e.regionRight&&0==e.regionBottom&&0==e.regionMeasuredByPercentage}async updateRuntimeSettings(e){let t;if("string"==typeof e)if("speed"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region)}else if("balance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.deblurLevel=3,t.expectedBarcodesCount=512,t.localizationModes=[2,16,0,0,0,0,0,0],t.timeout=1e5}else if("coverage"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.deblurLevel=5,t.expectedBarcodesCount=512,t.scaleDownThreshold=1e5,t.localizationModes=[2,16,4,8,0,0,0,0],t.timeout=1e5}else if("single"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,se.isRegionNormalPreset(e.region)?t.region=null:t.region=e.region,t.expectedBarcodesCount=1,t.localizationModes=[16,2,0,0,0,0,0,0],t.barcodeZoneMinDistanceToImageBorders=0}else if("dense"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.deblurLevel=7,t.scaleDownThreshold=1e5,t.localizationModes=[2,8,0,0,0,0,0,0],t.minResultConfidence=0,t.timeout=1e5}else if("distance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.scaleDownThreshold=1e5,t.localizationModes=[2,8,0,0,0,0,0,0],t.timeout=1e5}else t=JSON.parse(e);else{if("object"!=typeof e)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(t=JSON.parse(JSON.stringify(e)),t.region instanceof Array){let i=e.region;[i.regionLeft,i.regionTop,i.regionLeft,i.regionBottom,i.regionMeasuredByPercentage].some((e=>void 0!==e))&&(t.region={regionLeft:i.regionLeft||0,regionTop:i.regionTop||0,regionRight:i.regionRight||0,regionBottom:i.regionBottom||0,regionMeasuredByPercentage:i.regionMeasuredByPercentage||0})}}if(!D._bUseFullFeature){if(0!=(t.barcodeFormatIds&~(v.BF_ONED|v.BF_QR_CODE|v.BF_PDF417|v.BF_DATAMATRIX))||0!=t.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=t.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}{let e=t.region;if(this.bFilterRegionInJs?this.userDefinedRegion=JSON.parse(JSON.stringify(e)):this.userDefinedRegion=null,e instanceof Array)if(e.length){for(let t=0;t{let r=D._nextTaskID++;D._taskCallbackMap.set(r,(t=>{if(t.success){try{this._handleRetJsonString(t.updateReturn)}catch(e){i(e)}return e()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}})),D._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(t)}})})),"single"==e&&(await this.setModeArgument("BinarizationModes",0,"EnableFillBinaryVacancy","0"),await this.setModeArgument("LocalizationModes",0,"ScanDirection","2"),await this.setModeArgument("BinarizationModes",0,"BlockSizeX","71"),await this.setModeArgument("BinarizationModes",0,"BlockSizeY","71"))}_bindUI(){if(!this.getUIElement())throw new Error("Need to define `UIElement` before opening.");if(this.dce._bindUI(),!this.dce.video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'")}_unbindUI(){this.dce._unbindUI()}set onPlayed(e){this.dce.off("played",this._onPlayed),this._onPlayed=e,this.dce.on("played",this._onPlayed)}get onPlayed(){return this._onPlayed}async getAllCameras(){return this.dce.getAllCameras()}async getCurrentCamera(){return this.dce.getSelectedCamera()}async setCurrentCamera(e){const t=await this.dce.selectCamera(e);return this._fireResolutionWarning(),t}getResolution(){return this.dce.getResolution()}async setResolution(e,t){const i=await this.dce.setResolution(e,t);return this._fireResolutionWarning(),i}getVideoSettings(){return this.dce.getVideoSettings()}updateVideoSettings(e){return this.dce.updateVideoSettings(e)}isOpen(){return this.dce&&this.dce.isOpen()}setVideoFit(e){return this.dce&&this.dce.setVideoFit(e)}set ifShowScanRegionMask(e){this.dce&&(this.dce.ifShowScanRegionMask=e)}get ifShowScanRegionMask(){return this.dce&&this.dce.ifShowScanRegionMask}set ifSaveLastUsedCamera(e){this.dce&&(this.dce.ifSaveLastUsedCamera=e)}get ifSaveLastUsedCamera(){return this.dce&&this.dce.ifSaveLastUsedCamera}set ifSkipCameraInspection(e){this.dce&&(this.dce.ifSkipCameraInspection=e)}get ifSkipCameraInspection(){return this.dce&&this.dce.ifSkipCameraInspection}stop(){this._drawResults(null),this.dce.stop(),this.dce.ifShowScanRegionLaser=!1,this.dce.hideViewDecorator(),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}pause(){this.dce.pause()}async play(e,t,i){this.dce.ifShowScanRegionLaser=!0;const r=await this.dce.play(e,t,i);return this._fireResolutionWarning(),r}pauseScan(e){this._assertOpen(),e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce.ifShowScanRegionLaser=!1,this.dce.stopFetchingLoop()}resumeScan(){this._assertOpen(),this._bPauseScan=!1,this.dce.ifShowScanRegionLaser=!0}getCapabilities(){return this.dce.getCapabilities()}getCameraSettings(){return this.dce.getCameraSettings()}getConstraints(){return this.dce.getConstraints()}async applyConstraints(e){return this.dce.applyConstraints(e)}async turnOnTorch(){return this.dce.turnOnTorch()}async turnOffTorch(){return this.dce.turnOffTorch()}async setColorTemperature(e){return this.dce.setColorTemperature(e)}async setExposureCompensation(e){return this.dce.setExposureCompensation(e)}async setZoom(e){return this.dce.setZoom(e)}async setFrameRate(e){return this.dce.setFrameRate(e)}getFrameRate(){return this.dce.getFrameRate()}async setFocus(e,t){return this.dce.setFocus(e,t)}getFocus(){return this.dce.getFocus()}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),void this._drawResults(null);if(!this.isOpen())return this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce.video||this.dce.video.paused||this._bPauseScan)return D._onLog&&D._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));D._onLog&&D._onLog("======= once read ======="),D._onLog&&(this._timeStartDecode=Date.now());const e=this._getVideoFrame();if(!e)return this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{e._bUseWebGL||"grey"!==e.colorMode||(this.dce.frameColorMode="rgba");let t=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,colorMode:e.colorMode,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{data:i,sx:r,sy:n,width:s,height:o,colorMode:a,timeStamp:l,_sWidth:h,_sHeight:c}=e,u={timeStamp:l};if("grey"===a)t=await this._decodeBuffer_Uint8Array(i,s,o,s,_.IPF_GrayScaled,u);else if("rgba"===a)t=await this._decodeBuffer_Uint8Array(i,s,o,4*s,_.IPF_ABGR_8888,u);else{if("bgra"!==a)throw new Error(`Color mode '${a}' is not supported.`);t=await this._decodeBuffer_Uint8Array(i,s,o,4*s,_.IPF_ARGB_8888,u)}return D.recalculateResultLocation(t,r,n,h,c,s,o),t})().then((e=>{if(D._onLog&&D._onLog(e),this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost,i=this._indexCurrentDecodingFrame;const r=()=>{let r=0;if(this.region instanceof Array){let n=0,s=0;n=i+1>=this.region.length?0:i+1,s=n+1>=this.region.length?0:n+1,r=e[n]&&e[n].length&&t[s]&&t[s].length?Math.min(...e[n])-Math.max(...t[s]):0}else if(t&&t.length){let i=Math.min(...e),n=Math.max(...t);i&&n&&(r=i-n)}else r=0;return r>0?r:0};(()=>{if(this.region instanceof Array){for(e[i]&&e[i]instanceof Array||(e[i]=[]);e[i].length>=5;)e[i].shift();e[i].push(this._lastInnerDecodeDuration)}else{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)}})(),this._intervalGetVideoFrame=r()+this.intervalTime}if(this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead)t=!0;else if("unique"===this.bPlaySoundOnSuccessfulRead)for(let i of e)if(0==i.resultsType){t=!0;break}t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead)t=!0;else if("unique"===this.bVibrateOnSuccessfulRead)for(let i of e)if(0==i.resultsType){t=!0;break}if(t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onFrameRead){let t=this._cloneDecodeResults(e);for(let e of t)0!=e.resultsType&&1!=e.resultsType||this.onFrameRead(t)}if(this.onUniqueRead)for(let t of e)0==t.resultsType&&this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t));this._drawResults(e)}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce.stopFetchingLoop(),D._onLog&&D._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){let t=this.dce.isFetchingLoopStarted();if(this.dce.loopInterval=this._intervalGetVideoFrame,t||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dce.loopInterval=0,null;e=this.dce.getFrameFromBuffer();const i=e=>{if(!e)return;let t=e.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(t)};i(e)}else this.dce.stopFetchingLoop(),e=this.dce.getFrame();return e}async open(){this._bindUI();const e=await this.dce.open();return this._bPauseScan=!1,this.singleFrameMode||(this.dce&&(this.dce.ifShowScanRegionLaser=!0),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),this.keepAlive(),e}async openVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open();return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),this.keepAlive(),e}close(){this.dce.close(),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId)}async show(){this._bindUI();const e=await this.dce.open(!0);return this._bPauseScan=!1,this.singleFrameMode||(this.dce&&(this.dce.ifShowScanRegionLaser=!0),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),this.keepAlive(),e}async showVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open(!0);return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),this.keepAlive(),e}hide(){this.dce.close(!0),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId)}destroyContext(){this.close(),this.bDestroyed||super.destroyContext()}}var oe,ae,le,he,ce,ue,de,fe,ge,_e,pe,me,ve,ye,Se,be,Ce,we,Te,xe,Ae,Oe,Ie,Ee,Re,De,Me;!function(e){e[e.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",e[e.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",e[e.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",e[e.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",e[e.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",e[e.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",e[e.BICM_SKIP=0]="BICM_SKIP",e[e.BICM_REV=2147483648]="BICM_REV"}(oe||(oe={})),function(e){e[e.BCM_AUTO=1]="BCM_AUTO",e[e.BCM_GENERAL=2]="BCM_GENERAL",e[e.BCM_SKIP=0]="BCM_SKIP",e[e.BCM_REV=2147483648]="BCM_REV"}(ae||(ae={})),function(e){e[e.BF2_NULL=0]="BF2_NULL",e[e.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",e[e.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",e[e.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",e[e.BF2_POSTNET=2097152]="BF2_POSTNET",e[e.BF2_PLANET=4194304]="BF2_PLANET",e[e.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",e[e.BF2_RM4SCC=16777216]="BF2_RM4SCC",e[e.BF2_DOTCODE=2]="BF2_DOTCODE",e[e.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",e[e.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",e[e.BF2_PHARMACODE=12]="BF2_PHARMACODE"}(le||(le={})),function(e){e[e.BM_AUTO=1]="BM_AUTO",e[e.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",e[e.BM_SKIP=0]="BM_SKIP",e[e.BM_THRESHOLD=4]="BM_THRESHOLD",e[e.BM_REV=2147483648]="BM_REV"}(he||(he={})),function(e){e[e.ECCM_CONTRAST=1]="ECCM_CONTRAST"}(ce||(ce={})),function(e){e[e.CFM_GENERAL=1]="CFM_GENERAL"}(ue||(ue={})),function(e){e[e.CCM_AUTO=1]="CCM_AUTO",e[e.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",e[e.CCM_SKIP=0]="CCM_SKIP",e[e.CCM_REV=2147483648]="CCM_REV"}(de||(de={})),function(e){e[e.CICM_GENERAL=1]="CICM_GENERAL",e[e.CICM_SKIP=0]="CICM_SKIP",e[e.CICM_REV=2147483648]="CICM_REV"}(fe||(fe={})),function(e){e[e.CM_IGNORE=1]="CM_IGNORE",e[e.CM_OVERWRITE=2]="CM_OVERWRITE"}(ge||(ge={})),function(e){e[e.DM_SKIP=0]="DM_SKIP",e[e.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",e[e.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",e[e.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",e[e.DM_SMOOTHING=8]="DM_SMOOTHING",e[e.DM_MORPHING=16]="DM_MORPHING",e[e.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",e[e.DM_SHARPENING=64]="DM_SHARPENING",e[e.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",e[e.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING"}(_e||(_e={})),function(e){e[e.DRM_AUTO=1]="DRM_AUTO",e[e.DRM_GENERAL=2]="DRM_GENERAL",e[e.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",e[e.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",e[e.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",e[e.DRM_SKIP=0]="DRM_SKIP",e[e.DRM_REV=2147483648]="DRM_REV"}(pe||(pe={})),function(e){e[e.DPMCRM_AUTO=1]="DPMCRM_AUTO",e[e.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",e[e.DPMCRM_SKIP=0]="DPMCRM_SKIP",e[e.DPMCRM_REV=2147483648]="DPMCRM_REV"}(me||(me={})),function(e){e[e.GTM_INVERTED=1]="GTM_INVERTED",e[e.GTM_ORIGINAL=2]="GTM_ORIGINAL",e[e.GTM_SKIP=0]="GTM_SKIP",e[e.GTM_REV=2147483648]="GTM_REV"}(ve||(ve={})),function(e){e[e.IPM_AUTO=1]="IPM_AUTO",e[e.IPM_GENERAL=2]="IPM_GENERAL",e[e.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",e[e.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",e[e.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",e[e.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",e[e.IPM_SKIP=0]="IPM_SKIP",e[e.IPM_REV=2147483648]="IPM_REV"}(ye||(ye={})),function(e){e[e.IRSM_MEMORY=1]="IRSM_MEMORY",e[e.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",e[e.IRSM_BOTH=4]="IRSM_BOTH"}(Se||(Se={})),function(e){e[e.IRT_NO_RESULT=0]="IRT_NO_RESULT",e[e.IRT_ORIGINAL_IMAGE=1]="IRT_ORIGINAL_IMAGE",e[e.IRT_COLOUR_CLUSTERED_IMAGE=2]="IRT_COLOUR_CLUSTERED_IMAGE",e[e.IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE=4]="IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE",e[e.IRT_TRANSFORMED_GRAYSCALE_IMAGE=8]="IRT_TRANSFORMED_GRAYSCALE_IMAGE",e[e.IRT_PREDETECTED_REGION=16]="IRT_PREDETECTED_REGION",e[e.IRT_PREPROCESSED_IMAGE=32]="IRT_PREPROCESSED_IMAGE",e[e.IRT_BINARIZED_IMAGE=64]="IRT_BINARIZED_IMAGE",e[e.IRT_TEXT_ZONE=128]="IRT_TEXT_ZONE",e[e.IRT_CONTOUR=256]="IRT_CONTOUR",e[e.IRT_LINE_SEGMENT=512]="IRT_LINE_SEGMENT",e[e.IRT_FORM=1024]="IRT_FORM",e[e.IRT_SEGMENTATION_BLOCK=2048]="IRT_SEGMENTATION_BLOCK",e[e.IRT_TYPED_BARCODE_ZONE=4096]="IRT_TYPED_BARCODE_ZONE",e[e.IRT_PREDETECTED_QUADRILATERAL=8192]="IRT_PREDETECTED_QUADRILATERAL"}(be||(be={})),function(e){e[e.LM_SKIP=0]="LM_SKIP",e[e.LM_AUTO=1]="LM_AUTO",e[e.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",e[e.LM_LINES=8]="LM_LINES",e[e.LM_STATISTICS=4]="LM_STATISTICS",e[e.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",e[e.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",e[e.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",e[e.LM_CENTRE=128]="LM_CENTRE",e[e.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",e[e.LM_REV=2147483648]="LM_REV"}(Ce||(Ce={})),function(e){e[e.PDFRM_RASTER=1]="PDFRM_RASTER",e[e.PDFRM_AUTO=2]="PDFRM_AUTO",e[e.PDFRM_VECTOR=4]="PDFRM_VECTOR",e[e.PDFRM_REV=2147483648]="PDFRM_REV"}(we||(we={})),function(e){e[e.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",e[e.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",e[e.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",e[e.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(Te||(Te={})),function(e){e[e.RPM_AUTO=1]="RPM_AUTO",e[e.RPM_GENERAL=2]="RPM_GENERAL",e[e.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",e[e.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",e[e.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",e[e.RPM_SKIP=0]="RPM_SKIP",e[e.RPM_REV=2147483648]="RPM_REV"}(xe||(xe={})),function(e){e[e.RCT_PIXEL=1]="RCT_PIXEL",e[e.RCT_PERCENTAGE=2]="RCT_PERCENTAGE"}(Ae||(Ae={})),function(e){e[e.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",e[e.RT_RAW_TEXT=1]="RT_RAW_TEXT",e[e.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",e[e.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT"}(Oe||(Oe={})),function(e){e[e.SUM_AUTO=1]="SUM_AUTO",e[e.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",e[e.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",e[e.SUM_SKIP=0]="SUM_SKIP",e[e.SUM_REV=2147483648]="SUM_REV"}(Ie||(Ie={})),function(e){e[e.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",e[e.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",e[e.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",e[e.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",e[e.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",e[e.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED"}(Ee||(Ee={})),function(e){e[e.TFM_AUTO=1]="TFM_AUTO",e[e.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",e[e.TFM_SKIP=0]="TFM_SKIP",e[e.TFM_REV=2147483648]="TFM_REV"}(Re||(Re={})),function(e){e[e.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",e[e.TROM_POSITION=2]="TROM_POSITION",e[e.TROM_FORMAT=4]="TROM_FORMAT",e[e.TROM_SKIP=0]="TROM_SKIP",e[e.TROM_REV=2147483648]="TROM_REV"}(De||(De={})),function(e){e[e.TDM_AUTO=1]="TDM_AUTO",e[e.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",e[e.TDM_SKIP=0]="TDM_SKIP",e[e.TDM_REV=2147483648]="TDM_REV"}(Me||(Me={}));export{D as BarcodeReader,se as BarcodeScanner,oe as EnumBarcodeColourMode,ae as EnumBarcodeComplementMode,v as EnumBarcodeFormat,le as EnumBarcodeFormat_2,he as EnumBinarizationMode,ce as EnumClarityCalculationMethod,ue as EnumClarityFilterMode,de as EnumColourClusteringMode,fe as EnumColourConversionMode,ge as EnumConflictMode,me as EnumDPMCodeReadingMode,_e as EnumDeblurMode,pe as EnumDeformationResistingMode,p as EnumErrorCode,ve as EnumGrayscaleTransformationMode,m as EnumIMResultDataType,_ as EnumImagePixelFormat,ye as EnumImagePreprocessingMode,Se as EnumIntermediateResultSavingMode,be as EnumIntermediateResultType,Ce as EnumLocalizationMode,we as EnumPDFReadingMode,Te as EnumQRCodeErrorCorrectionLevel,xe as EnumRegionPredetectionMode,Ae as EnumResultCoordinateType,Oe as EnumResultType,Ie as EnumScaleUpMode,Ee as EnumTerminatePhase,Re as EnumTextFilterMode,De as EnumTextResultOrderMode,Me as EnumTextureDetectionMode}; diff --git a/dist/dbr.pure.esm.js b/dist/dbr.pure.esm.js new file mode 100644 index 0000000..fad60b8 --- /dev/null +++ b/dist/dbr.pure.esm.js @@ -0,0 +1,21 @@ +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft Barcode Reader JS Edition + * @website http://www.dynamsoft.com + * @copyright Copyright 2022, Dynamsoft Corporation + * @author Dynamsoft + * @version 9.2.11 (js 20220727) + * @fileoverview Dynamsoft JavaScript Library for Barcode Reader + * More info on DBR JS: https://www.dynamsoft.com/barcode-reader/sdk-javascript/ + */ +import{Howl as t}from"dm-howler";const e="undefined"==typeof self;let i,r,n,s,o;if("undefined"!=typeof navigator&&(i=navigator,r=i.userAgent,n=i.platform,s=i.mediaDevices),!e){const t={init:function(){this.browser=this.searchString(this.dataBrowser)||"unknownBrowser",this.version=this.searchVersion(r)||this.searchVersion(i.appVersion)||0,this.OS=this.searchString(this.dataOS)||"unknownOS","Linux"==this.OS&&-1!=r.indexOf("Windows NT")&&(this.OS="HarmonyOS")},searchString:function(t){for(let e=0;e{let t=!1;if(l)try{(await s.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===o.browser&&o.version>66||"Safari"===o.browser&&o.version>13||"OPR"===o.browser&&o.version>43||"Edge"===o.browser&&o.version;const u=(()=>{if(!e&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),d=" is not allowed to change after `createInstance` or `loadWasm` is called.",f=!e&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",g=!e&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",_=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let i=0;it&&"object"==typeof t&&"function"==typeof t.then;const C="iPhone"==o.OS||"Android"==o.OS||"HarmonyOS"==o.OS?2048:4096;class b{constructor(){this._instanceID=void 0,this._ifSaveOriginalImageInACanvas=!1,this.oriCanvas=null,this.oriCanvasData=null,this.canvas=null,this.bFilterRegionInJs=!1,this._region=null,this._timeStartDecode=null,this._timeEnterInnerDBR=null,this._timeGetMessage=null,this.decodeRecords={},this.bDestroyed=!1,this._lastErrorCode=0,this._lastErrorString="",this._lastInnerDecodeDuration=0,this.intervalTime=0,this._intervalGetVideoFrame=0,this.array_getFrameTimeCost=[],this.array_decodeFrameTimeCost=[],this._indexCurrentDecodingFrame=0,this._bPauseScan=!1,this._intervalDetectVideoPause=1e3,this._soundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",this.beepSound=new t({src:["data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV"],onplayerror:(t,e)=>{console.warn(`Sound '${t}' playback failure: ${e}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.captureAndDecodeInParallel=!0,this.barcodeFillStyle="rgba(254,180,32,0.3)",this.barcodeStrokeStyle="rgba(254,180,32,0.9)",this.barcodeLineWidth=1,this._dce=null,this._imgSource=null,this._maxCvsSideLength=C,this._tempSolutionStatus="closed"}static get version(){return this._version}static get license(){return this._license}static set license(t){((t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`license`"+d);i._license=e})(b,t)}static get productKeys(){return this._license}static set productKeys(t){b.license=t}static get handshakeCode(){return this._license}static set handshakeCode(t){b.license=t}static get organizationID(){return this._license}static set organizationID(t){b.license=t}static set sessionPassword(t){((t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`sessionPassword`"+d);i._sessionPassword=e})(b,t)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:a,worker:h,getUserMedia:l,camera:await c(),browser:o.browser,version:o.version,OS:o.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(t){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");b._engineResourcePath=(t=>{if(null==t&&(t="./"),!e){let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(t)}static get licenseServer(){return this._licenseServer}static set licenseServer(t){((t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+d);i._licenseServer=_(e)})(b,t)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(t){((t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+d);i._deviceFriendlyName=e||""})(b,t)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(t){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");b.__bUseFullFeature=t}static isImageSource(t){return!(!t||"object"!=typeof t||Array.isArray(t))&&"getImage"in t}static isDSImage(t){return!(!t||"object"!=typeof t||Array.isArray(t))&&("data"in t&&("width"in t&&("height"in t&&"pixelFormat"in t)))}static isDCEFrame(t){return!(!t||"object"!=typeof t||Array.isArray(t))&&("data"in t&&("region"in t&&("sx"in t&&("sy"in t&&("width"in t&&("height"in t&&("colorMode"in t&&("timeSpent"in t&&("timeStamp"in t&&("isCropped"in t&&("toCanvas"in t&&("_sWidth"in t&&("_sHeight"in t&&"_bUseWebGL"in t)))))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(t){this._ifSaveOriginalImageInACanvas=t}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(t){this._region=t,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var t;return null===(t=b._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",b.engineResourcePath)}static set defaultUIElementURL(t){b._defaultUIElementURL=t}static _fireHTTPSWarnning(){b.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{b.onWarning&&b.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new t({src:[this._soundSource],onplayerror:(t,e)=>{console.warn(`Sound '${t}' playback failure: ${e}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(t){this.bPlaySoundOnSuccessfulRead="never"!==t&&t}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(t){this.bVibrateOnSuccessfulRead="never"!==t&&t}set dce(t){this._dce=t}get dce(){return!this._dce||this._dce.isDisposed?null:this._dce}set maxCvsSideLength(t){this._maxCvsSideLength=t,this._dceControler&&this._dceControler.setDisiredValue(this,"maxCvsSideLength",t)}get maxCvsSideLength(){return this._maxCvsSideLength}async _registerDCEControler(){if(!this.dce)return;b._onLog&&b._onLog("_registerDCEControler()");const t=this.dce;this._dceControler=t._createControler();const e=this._dceControler;e.register(this),e.setDisiredValue(this,"refreshInterval",200),e.setDisiredValue(this,"maxCvsSideLength",this._maxCvsSideLength);try{ResizeObserver}catch(t){"ReferenceError"===t.name&&window&&(window.ResizeObserver=void 0)}const i=t.getUIElement(),r=this.dce.constructor;if("@engineResourcePath/dce.ui.html"===r._defaultUIElementURL)try{i?i===e._innerSetUI&&(await t.setUIElement(`${r.engineResourcePath}dce.ui.html`),e._innerSetUI=t.getUIElement()):(await t.setUIElement(`${r.engineResourcePath}dbr.ui.html`),e._innerSetUI=t.getUIElement())}catch(e){await t.setUIElement(r.defaultUIElementURL)}else i||await t.setUIElement(r.defaultUIElementURL);this.callbackCameraChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async t=>{let e=await this._decode_DCEFrame(t,{bCopyData:!1});if(await this.clearMapDecodeRecord(),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan){let t=this._cloneDecodeResults(e);this.onImageRead(t)}if(this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let t of e)this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t));const{sx:i,sy:r,width:n,height:s,_sWidth:o,_sHeight:a}=t;b.recalculateResultLocation(e,i,r,o,a,n,s),this._drawResults(e)},t.on("cameraChange",this.callbackCameraChange),t.on("resolutionChange",this.callbackResolutionChange),t.on("cameraClose",this.callbackCameraClose),t.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}_logoutDCEControler(){this.dce&&this._dceControler&&(b._onLog&&b._onLog("_logoutDCEControler()"),this._dceControler.logout(this),this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this._dceControler=null,this.dce=null)}async setImageSource(t,e){if(null==t)return this._imgSource=null,this._logoutDCEControler(),void(this._drawingItemNamespace=null);if(t&&t.isCameraEnhancer)this.dce=t,await this._registerDCEControler(),this._imgSource=null;else{if(!b.isImageSource(t))throw new Error("Invalid value.");this._logoutDCEControler(),this._imgSource=t}e&&e.resultsHighlightBaseShapes&&(this._drawingItemNamespace=e.resultsHighlightBaseShapes)}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:t,l:e,ls:i,sp:r,rmk:n}=(t=>{const e=t;if(e._pLoad.isEmpty){let t,i,r=e._license||"",n=JSON.parse(JSON.stringify(e._licenseServer)),s=e._sessionPassword,o=0;if(r.startsWith("t")||r.startsWith("f"))o=0;else if(0===r.length||r.startsWith("P")||r.startsWith("L")||r.startsWith("Y")||r.startsWith("A"))o=1;else{o=2;const e=r.indexOf(":");if(-1!=e&&(r=r.substring(e+1)),r.startsWith("DLS2")){let e=r.substring(4);try{e=atob(e)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}const i=JSON.parse(e);if(r=i.handshakeCode?i.handshakeCode:i.organizationID?i.organizationID:"","number"==typeof r&&(r=JSON.stringify(r)),0===n.length){let t=[];i.mainServerURL&&(t[0]=i.mainServerURL),i.standbyServerURL&&(t[1]=i.standbyServerURL),n=_(t)}!s&&i.sessionPassword&&(s=i.sessionPassword),t=i.remark}("200001"===r||r.startsWith("200001-"))&&(n&&n.length||(r="")),r||(o=1)}if(o&&(globalThis.crypto||(i="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(i="Require https to use online key in this browser.")),i){if(1!==o)throw new Error(i);o=0,console.warn(i),e._lastErrorCode=-1,e._lastErrorString=i}return 1===o&&(r="",console.warn("Applying for a public trial license ...")),{lt:o,l:r,ls:n,sp:s,rmk:t}}throw new Error("Can't preprocess license again"+d)})(b);this._pLoad.task=async(s,a)=>{let h=b.engineResourcePath+b._workerName;b.engineResourcePath.startsWith(location.origin)||(h=await fetch(h).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),b._dbrWorker=new Worker(h),b._dbrWorker.onerror=t=>{let e=new Error(t.message);a(e)},b._dbrWorker.onmessage=async e=>{let i=e.data?e.data:e;switch(i.type){case"log":b._onLog&&b._onLog(i.message);break;case"load":{i.message&&(i.message=i.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let e,r=!1;1===t&&(r=!0),i.success?(b._dbrWorker.onerror=null,b._version=i.version+"(JS "+b._jsVersion+"."+b._jsEditVersion+")",b._onLog&&b._onLog("load dbr worker success"),i.message&&console.warn(i.message)):(e=new Error(i.message),e.stack=i.stack+"\n"+e.stack,r||111==i.ltsErrorCode&&-1!=i.message.toLowerCase().indexOf("trial license")&&(r=!0)),r&&b.showDialog(i.success?"warn":"error",i.message),i.success?s():a(e);break}case"task":{let t=i.id,e=i.body;try{b._taskCallbackMap.get(t)(e),b._taskCallbackMap.delete(t)}catch(e){throw b._taskCallbackMap.delete(t),e}break}default:b._onLog&&b._onLog(e)}},b._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:b.engineResourcePath,bUseFullFeature:b._bUseFullFeature,bd:b._bWasmDebug,v:b._jsVersion,brtk:!!t,bptk:1===t,l:e,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:o,fn:b.deviceFriendlyName,ls:i,sp:r,rmk:n})}}await this._pLoad}static async showDialog(t,e){await(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let r=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let n=await r.text();if(!n.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.innerHTML=n;let o=[];for(let t=0;t{if(t==e.target){a.remove();for(let t of o)t.remove()}}));else if(!l&&t.classList.contains("dls-license-icon-close"))l=t,t.addEventListener("click",(()=>{a.remove();for(let t of o)t.remove()}));else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-icon-warn"))u=t,"warn"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-msg-content")){d=t;let e=i;for(;e;){let i=e.indexOf("["),r=e.indexOf("]",i),n=e.indexOf("(",r),s=e.indexOf(")",n);if(-1==i||-1==r||-1==n||-1==s){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let o=document.createElement("a"),a=e.substring(i+1,r);o.innerText=a;let h=e.substring(n+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(s+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})(this,t,e)}static async createInstanceInWorker(t=!1){return await b.loadWasm(),await new Promise(((e,i)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(t=>{if(t.success)return e(t.instanceID);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}})),b._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:t})}))}static async createInstance(){let t=new b;return t._instanceID=await b.createInstanceInWorker(),b._fireHTTPSWarnning(),t}async clearMapDecodeRecord(){return await new Promise(((t,e)=>{let i=b._nextTaskID++;b._taskCallbackMap.set(i,(i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}})),b._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:i,instanceID:this._instanceID})}))}async decode(t){b._onLog&&b._onLog("decode(source: any)"),b._onLog&&(this._timeStartDecode=Date.now());{let e={};return!this.region||this.region instanceof Array||(e.region=JSON.parse(JSON.stringify(this.region))),t instanceof Blob?await this._decode_Blob(t,e):t instanceof ArrayBuffer?await this._decode_ArrayBuffer(t,e):t instanceof Uint8Array||t instanceof Uint8ClampedArray?await this._decode_Uint8Array(t,e):t instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap?await this._decode_Image(t,e):t instanceof HTMLCanvasElement?await this._decode_Canvas(t,e):t instanceof HTMLVideoElement?await this._decode_Video(t,e):"string"==typeof t?"data:image/"==t.substring(0,11)?await this._decode_Base64(t,e):await this._decode_Url(t,e):b.isDCEFrame(t)?(e.bCopyData=!0,await this._decode_DCEFrame(t,e)):b.isDSImage(t)?(e.bCopyData=!0,await this._decode_DSImage(t,e)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(t){let e={};return!this.region||this.region instanceof Array||(e.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(t,e)}async decodeUrl(t){let e={};return!this.region||this.region instanceof Array||(e.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(t,e)}async _decodeBuffer_Uint8Array(t,e,i,r,n,s){return await new Promise(((o,a)=>{let h=b._nextTaskID++;b._taskCallbackMap.set(h,(t=>{if(t.success){let e,i=b._onLog?Date.now():0;b._onLog&&b._onLog("worker return result: "+i),this._lastInnerDecodeDuration=t.duration;try{e=this._handleRetJsonString(t.decodeReturn)}catch(t){return a(t)}if(b._onLog){let t=Date.now();b._onLog("DBR time get result: "+i),b._onLog("Handle image cost: "+(this._timeEnterInnerDBR-this._timeStartDecode)),b._onLog("DBR worker decode image cost: "+(i-this._timeEnterInnerDBR)),b._onLog("DBR worker handle results: "+(t-i)),b._onLog("Total decode image cost: "+(t-this._timeStartDecode))}return o(e)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,a(e)}})),this._timeEnterInnerDBR=Date.now(),b._onLog&&b._onLog("Send buffer to worker:"+this._timeEnterInnerDBR),b._dbrWorker.postMessage({type:"decodeBuffer",id:h,instanceID:this._instanceID,body:{buffer:t,width:e,height:i,stride:r,format:n,config:s}},[t.buffer]),b._onLog&&s&&s.timeStamp&&b._onLog("decode image delay: "+(this._timeEnterInnerDBR-s.timeStamp))}))}async _decodeBuffer_Blob(t,e,i,r,n,s){b._onLog&&b._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const o=t.arrayBuffer?await t.arrayBuffer():await new Promise(((e,i)=>{let r=new FileReader;r.readAsArrayBuffer(t),r.onload=()=>{e(r.result)},r.onerror=()=>{i(r.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(o),e,i,r,n,s)}async decodeBuffer(t,e,i,r,n,s){let o;return b._onLog&&b._onLog("decodeBuffer(buffer,width,height,stride,format)"),b._onLog&&(this._timeStartDecode=Date.now()),t instanceof Uint8Array||t instanceof Uint8ClampedArray?o=await this._decodeBuffer_Uint8Array(t,e,i,r,n,s):t instanceof ArrayBuffer?o=await this._decodeBuffer_Uint8Array(new Uint8Array(t),e,i,r,n,s):t instanceof Blob&&(o=await this._decodeBuffer_Blob(t,e,i,r,n,s)),o}async _decodeFileInMemory_Uint8Array(t){return await new Promise(((e,i)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(t=>{if(t.success){let r;this._lastInnerDecodeDuration=t.duration;try{r=this._handleRetJsonString(t.decodeReturn)}catch(t){return i(t)}return e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}})),b._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:t}})}))}async getRuntimeSettings(){return await new Promise(((t,e)=>{let i=b._nextTaskID++;b._taskCallbackMap.set(i,(i=>{if(i.success){let e=JSON.parse(i.results);return null!=this.userDefinedRegion&&(e.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),t(e)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}})),b._dbrWorker.postMessage({type:"getRuntimeSettings",id:i,instanceID:this._instanceID})}))}async updateRuntimeSettings(t){let e;if("string"==typeof t)if("speed"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,e.region=t.region,e.deblurLevel=3,e.expectedBarcodesCount=0,e.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,e.region=t.region,e.deblurLevel=5,e.expectedBarcodesCount=512,e.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,e.region=t.region}else if("dense"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,e.region=t.region,e.deblurLevel=9,e.expectedBarcodesCount=0,e.localizationModes=[2,8,0,0,0,0,0,0]}else if("distance"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,e.region=t.region,e.deblurLevel=3,e.expectedBarcodesCount=0,e.localizationModes=[2,8,0,0,0,0,0,0]}else e=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(e=JSON.parse(JSON.stringify(t)),e.region instanceof Array){let t=e.region;[t.regionLeft,t.regionTop,t.regionLeft,t.regionBottom,t.regionMeasuredByPercentage].some((t=>void 0!==t))&&(e.region={regionLeft:t.regionLeft||0,regionTop:t.regionTop||0,regionRight:t.regionRight||0,regionBottom:t.regionBottom||0,regionMeasuredByPercentage:t.regionMeasuredByPercentage||0})}}if(!b._bUseFullFeature){if(0!=(e.barcodeFormatIds&~(y.BF_ONED|y.BF_QR_CODE|y.BF_PDF417|y.BF_DATAMATRIX))||0!=e.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=e.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let t=e.region;if(t instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(t)),(t.regionLeft||t.regionTop||t.regionRight||t.regionBottom||t.regionMeasuredByPercentage)&&(t.regionLeft||t.regionTop||100!=t.regionRight||100!=t.regionBottom||!t.regionMeasuredByPercentage)?this.region=t:this.region=null,e.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return await new Promise(((t,i)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.updateReturn)}catch(t){i(t)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),b._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(e)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=C,await new Promise(((t,e)=>{let i=b._nextTaskID++;b._taskCallbackMap.set(i,(i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}})),b._dbrWorker.postMessage({type:"resetRuntimeSettings",id:i,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!b._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((t,e)=>{let i=b._nextTaskID++;b._taskCallbackMap.set(i,(i=>{if(i.success)return t(i.results);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}})),b._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:i,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(t){if(!b._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof t)t=t;else{if("object"!=typeof t)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");t=JSON.stringify(t)}return await new Promise(((e,i)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(t=>{if(t.success){try{this._handleRetJsonString(t.initReturn)}catch(t){i(t)}return e()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}})),b._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:t}})}))}async _decode_Blob(t,e){b._onLog&&b._onLog("_decode_Blob(blob: Blob)");let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(r=await function(t){return new Promise(((e,i)=>{let r=URL.createObjectURL(t),n=new Image;n.dbrObjUrl=r,n.src=r,n.onload=()=>{e(n)},n.onerror=t=>{i(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))}(t));let n=await this._decode_Image(i||r,e);return i&&i.close(),n}async _decode_ArrayBuffer(t,e){return await this._decode_Blob(new Blob([t]),e)}async _decode_Uint8Array(t,e){return await this._decode_Blob(new Blob([t]),e)}async _decode_Image(t,e){b._onLog&&b._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),e=e||{};let i,r,n=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(n,s);if(o>this._maxCvsSideLength){let t=this._maxCvsSideLength/o;i=Math.round(n*t),r=Math.round(s*t)}else i=n,r=s;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d"));return a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._decode_Canvas(a,e)}async _decode_Canvas(t,e){if(b._onLog&&b._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if(0===t.width||0===t.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=t,this.oriCanvasData=null);let i=(t.ctx2d||t.getContext("2d")).getImageData(0,0,t.width,t.height).data;return await this._decodeBuffer_Uint8Array(i,t.width,t.height,4*t.width,p.IPF_ABGR_8888,e)}async _decode_Video(t,e){if(b._onLog&&b._onLog("_decode_Video(video)"),!(t instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";e=e||{};let i,r,n=t.videoWidth,s=t.videoHeight,o=Math.max(n,s);if(o>this._maxCvsSideLength){let t=this._maxCvsSideLength/o;i=Math.round(n*t),r=Math.round(s*t)}else i=n,r=s;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d"));return a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),await this._decode_Canvas(a,e)}async _decode_DCEFrame(t,e){if(b._onLog&&b._onLog("_decode_DCEFrame(dceFrame)"),!b.isDCEFrame(t))return[];let i=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{width:r,height:n,colorMode:s,timeStamp:o}=t;let a;a=e&&e.bCopyData?new Uint8Array(t.data):t.data;let h=null;if(e?(h=JSON.parse(JSON.stringify(e)),h.timeStamp=o):h={timeStamp:o},"grey"===s)i=await this._decodeBuffer_Uint8Array(a,r,n,r,p.IPF_GrayScaled,h);else if("rgba"===s)i=await this._decodeBuffer_Uint8Array(a,r,n,4*r,p.IPF_ABGR_8888,h);else{if("bgra"!==s)throw new Error(`Color mode '${s}' is not supported to decode.`);i=await this._decodeBuffer_Uint8Array(a,r,n,4*r,p.IPF_ARGB_8888,h)}return i}async _decode_DSImage(t,e){if(b._onLog&&b._onLog("_decode_DSImage(dsImage)"),!b.isDSImage(t))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat.toLowerCase(),data:new Uint8Array(t.data),toCanvas:function(){const t=document.createElement("canvas");let e;switch(t.width=this.width,t.height=this.height,this.pixelFormat){case"grey":e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{let r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="blob",r.send(),r.onloadend=async()=>{e(r.response)},r.onerror=()=>{i(new Error("Network Error: "+r.statusText))}}));return await this._decode_Blob(i,e)}}async _decode_FilePath(t,e){throw b._onLog&&b._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static recalculateResultLocation(t,e,i,r,n,s,o){if(t.length>0)for(let a of t){let t=a.localizationResult;2==t.resultCoordinateType&&(t.x1*=.01*s,t.x2*=.01*s,t.x3*=.01*s,t.x4*=.01*s,t.y1*=.01*o,t.y2*=.01*o,t.y3*=.01*o,t.y4*=.01*o);let h=s/r,l=o/n;t.x1=t.x1/h+e,t.x2=t.x2/h+e,t.x3=t.x3/h+e,t.x4=t.x4/h+e,t.y1=t.y1/l+i,t.y2=t.y2/l+i,t.y3=t.y3/l+i,t.y4=t.y4/l+i,2==t.resultCoordinateType&&(t.x1*=100/r,t.x2*=100/r,t.x3*=100/r,t.x4*=100/r,t.y1*=100/n,t.y2*=100/n,t.y3*=100/n,t.y4*=100/n)}}static BarcodeReaderException(t,e){let i,r=m.DBR_UNKNOWN;return"number"==typeof t?(r=t,i=new Error(e)):i=new Error(t),i.code=r,i}_handleRetJsonString(t){let e=m;if(t.textResults){for(let e=0;e{let i=e.indexOf(":");t[e.substring(0,i)]=e.substring(i+1)})),i.exception=t}}return t.decodeRecords?this.decodeRecords=t.decodeRecords:this.decodeRecords={},this._lastErrorCode=t.exception,this._lastErrorString=t.description,t.exception&&!b._setWarnnedEx.has(t.description)&&(b._setWarnnedEx.add(t.description),console.warn(t.description)),t.textResults}if(t.exception==e.DBR_SUCCESS)return t.data;throw b.BarcodeReaderException(t.exception,t.description)}async setModeArgument(t,e,i,r){return await new Promise(((n,s)=>{let o=b._nextTaskID++;b._taskCallbackMap.set(o,(t=>{if(t.success){try{this._handleRetJsonString(t.setReturn)}catch(t){return s(t)}return n()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,s(e)}})),b._dbrWorker.postMessage({type:"setModeArgument",id:o,instanceID:this._instanceID,body:{modeName:t,index:e,argumentName:i,argumentValue:r}})}))}async getModeArgument(t,e,i){return await new Promise(((r,n)=>{let s=b._nextTaskID++;b._taskCallbackMap.set(s,(t=>{if(t.success){let e;try{e=this._handleRetJsonString(t.getReturn)}catch(t){return n(t)}return r(e)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}})),b._dbrWorker.postMessage({type:"getModeArgument",id:s,instanceID:this._instanceID,body:{modeName:t,index:e,argumentName:i}})}))}async getIntermediateResults(){return await new Promise(((t,e)=>{let i=b._nextTaskID++;b._taskCallbackMap.set(i,(i=>{if(i.success)return t(i.results);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}})),b._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let t=await this.getIntermediateResults(),e=[];for(let i of t)if(i.dataType==v.IMRDT_IMAGE)for(let t of i.results){const i=t.bytes;let r;switch(b._onLog&&b._onLog(" "+i.length+" "+i.byteLength+" "+t.width+" "+t.height+" "+t.stride+" "+t.format),t.format){case p.IPF_ABGR_8888:r=new Uint8ClampedArray(i);break;case p.IPF_RGB_888:{const t=i.length/3;r=new Uint8ClampedArray(4*t);for(let e=0;e{let i=b._nextTaskID++;b._taskCallbackMap.set(i,(i=>{if(i.success){let e=i.results;return e.intervalTime=this.intervalTime,e.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,e.soundOnSuccessfullRead=this.soundSource,e.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,e.vibrateDuration=this.vibrateDuration,e.captureAndDecodeInParallel=this.captureAndDecodeInParallel,t(e)}{let t=new Error(i.message);return t.stack+="\n"+i.stack,e(t)}})),b._dbrWorker.postMessage({type:"getScanSettings",id:i,instanceID:this._instanceID})}))}async updateScanSettings(t){if(!t)return;const e=JSON.parse(JSON.stringify(t));return e.hasOwnProperty("intervalTime")&&(this.intervalTime=Math.max(e.intervalTime,0),delete e.intervalTime),e.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=e.whenToPlaySoundforSuccessfulRead,delete e.whenToPlaySoundforSuccessfulRead),e.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=e.soundOnSuccessfullRead,delete e.soundOnSuccessfullRead),e.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=e.whenToVibrateforSuccessfulRead,delete e.whenToVibrateforSuccessfulRead),e.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=e.vibrateDuration,delete e.vibrateDuration),e.hasOwnProperty("captureAndDecodeInParallel")&&(this.captureAndDecodeInParallel=e.captureAndDecodeInParallel,delete e.captureAndDecodeInParallel),await new Promise(((t,i)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack+="\n"+e.stack,i(t)}})),b._dbrWorker.postMessage({type:"updateScanSettings",id:r,instanceID:this._instanceID,body:{settings:e}})}))}_cloneDecodeResults(t){if(t instanceof Array){let e=[];for(let i of t)e.push(this._cloneDecodeResults(i));return e}{let e=t,i=JSON.parse(JSON.stringify(e,((t,e)=>"oriVideoCanvas"==t||"searchRegionCanvas"==t?void 0:e)));return i}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this._imgSource||this._bPauseScan)return b._onLog&&b._onLog("Scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));b._onLog&&b._onLog("======= once read ======="),b._onLog&&(this._timeStartDecode=Date.now());let t=null,e=null;if(this.dce)t=this._getVideoFrame();else if(this._imgSource&&(e=await this._imgSource.getImage(),!b.isDSImage(e)))throw new Error("Invalid DSImage.");if(!t&&!e)return this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let i=[];if(t){i=await this._decode_DCEFrame(t,{bScanner:!0,bCopyData:!1});let e=null;if(i&&i.length){const{sx:r,sy:n,width:s,height:o,_sWidth:a,_sHeight:h}=t;e=i.map((t=>({localizationResult:JSON.parse(JSON.stringify(t.localizationResult))}))),b.recalculateResultLocation(e,r,n,a,h,s,o)}this._drawResults(e)}else e&&(i=await this._decode_DSImage(e,{bScanner:!0,bCopyData:!1}));return i})().then((t=>{if(b._onLog&&b._onLog(t),this.dce&&this.captureAndDecodeInParallel){let t=this.array_decodeFrameTimeCost,e=this.array_getFrameTimeCost;const i=()=>{let i=0;if(e&&e.length){let r=Math.min(...t),n=Math.max(...e);r&&n&&(i=r-n)}else i=0;return i>0?i:0};(()=>{for(;t.length>=5;)t.shift();t.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=i()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this._imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&t.length){let e=!1;if(!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead)e=!0;else if("unique"===this.bPlaySoundOnSuccessfulRead)for(let i of t)if(0==i.resultsType){e=!0;break}e&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&t.length){let e=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead)e=!0;else if("unique"===this.bVibrateOnSuccessfulRead)for(let i of t)if(0==i.resultsType){e=!0;break}if(e)try{navigator.vibrate(this.vibrateDuration)}catch(t){console.warn("Vibration not allowed. User interaction required: "+(t.message||t))}}if(this.onImageRead){let e=this._cloneDecodeResults(t);for(let t of e)0!=t.resultsType&&1!=t.resultsType||this.onImageRead(e);this.onImageRead(e)}if(this.onUniqueRead)for(let e of t)0==e.resultsType&&this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e))}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((t=>{this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),b._onLog&&b._onLog(t.message||t),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==t.message||console.warn(t.message)}))}_getVideoFrame(){if(!this.dce)return null;let t;if(this.captureAndDecodeInParallel){if(this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",this._intervalGetVideoFrame),!this.dce.numberOfFramesInBuffer)return this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",0),null;t=this.dce.getFrameFromBuffer();const e=t=>{if(!t)return;let e=t.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(e)};e(t)}else this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),t=this.dce.getFrame();return t}_drawResults(t){if(!this.dce||this._bPauseScan||!this._drawingItemNamespace||!this._drawingItemNamespace.DT_Polygon)return;if(!this._dbrDrawingLayer){if(!this.dce.isOpen())return;this._dbrDrawingLayer=this.dce.getDrawingLayer(3)}const e=this._dbrDrawingLayer;if(e.clearDrawingItems(),t&&t.length)for(let i of t){const t=i.localizationResult,r=new this._drawingItemNamespace.DT_Polygon([{x:t.x1,y:t.y1},{x:t.x2,y:t.y2},{x:t.x3,y:t.y3},{x:t.x4,y:t.y4}]);e.addDrawingItem(r)}}async startScanning(t){if(!this.dce&&!this._imgSource)throw new Error("'imageSource' is not set. call 'setImageSource()' before 'startScanning()'.");if("closed"!=this._tempSolutionStatus)return;if(this._tempSolutionStatus="opening","opening"!=this._tempSolutionStatus)return;let e=null;return this.dce&&(this.dce.isOpen()?(t&&this.dce.appendAndShowUI(),e=JSON.parse(JSON.stringify(this.dce.playCallbackInfo))):e=await this.dce.open(t),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"close"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())),"opening"==this._tempSolutionStatus?(this._bPauseScan=!1,this.dce&&this.dce.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),0)),this._tempSolutionStatus="opened",this.keepAlive(),e):void 0}stopScanning(t){this.dce&&(this._drawResults(null),this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"close",t))),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._tempSolutionStatus="closed"}pauseScanning(t){if(t&&t.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"stopFetchingLoop"))}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.startFetchingLoop(),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(b._onLog&&b._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,(this.dce||"opening"===this._tempSolutionStatus)&&this.stopScanning(),this.setImageSource(null);let t=b._nextTaskID++;b._taskCallbackMap.set(t,(t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}})),b._dbrWorker.postMessage({type:"destroyContext",id:t,instanceID:this._instanceID})}}b._jsVersion="9.2.11",b._jsEditVersion="20220727",b._version=`loading...(JS ${b._jsVersion}.${b._jsEditVersion})`,b._license=f,b._sessionPassword=g,b.browserInfo=o,b._workerName=`dbr-${b._jsVersion}.browser.worker.js`,b._engineResourcePath=u,b._licenseServer=[],b._deviceFriendlyName="",b._isShowRelDecodeTimeInResults=!1,b._bWasmDebug=!1,b._bNeverShowDialog=!1,b.__bUseFullFeature=!0,b._nextTaskID=0,b._taskCallbackMap=new Map,b._pLoad=new class extends Promise{constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(S(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,S(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}},b._lastErrorCode=0,b._lastErrorString="",b._setWarnnedEx=new Set,b._defaultUIElementURL="@engineResourcePath/dbr.ui.html";var w={653:(t,e,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,_,p,m,v,y,S,C,b,w,T=T||{version:"5.2.1"};if(e.fabric=T,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?T.document=document:T.document=document.implementation.createHTMLDocument(""),T.window=window;else{var x=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;T.document=x.document,T.jsdomImplForWrapper=i(898).implForWrapper,T.nodeCanvas=i(245).Canvas,T.window=x,DOMParser=T.window.DOMParser}function O(t,e){var i=t.canvas,r=e.targetCanvas,n=r.getContext("2d");n.translate(0,r.height),n.scale(1,-1);var s=i.height-r.height;n.drawImage(i,0,s,r.width,r.height,0,0,r.width,r.height)}function E(t,e){var i=e.targetCanvas.getContext("2d"),r=e.destinationWidth,n=e.destinationHeight,s=r*n*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,r,n,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,r,n);i.putImageData(h,0,0)}T.isTouchSupported="ontouchstart"in T.window||"ontouchstart"in T.document||T.window&&T.window.navigator&&T.window.navigator.maxTouchPoints>0,T.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,T.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],T.DPI=96,T.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",T.commaWsp="(?:\\s+,?\\s*|,\\s*)",T.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,T.reNonWord=/[ \n\.,;!\?\-]/,T.fontPaths={},T.iMatrix=[1,0,0,1,0,0],T.svgNS="http://www.w3.org/2000/svg",T.perfLimitSizeTotal=2097152,T.maxCacheSideLimit=4096,T.minCacheSideLimit=256,T.charWidthsCache={},T.textureSize=2048,T.disableStyleCopyPaste=!1,T.enableGLFiltering=!0,T.devicePixelRatio=T.window.devicePixelRatio||T.window.webkitDevicePixelRatio||T.window.mozDevicePixelRatio||1,T.browserShadowBlurConstant=1,T.arcToSegmentsCache={},T.boundsOfCurveCache={},T.cachesBoundsOfCurve=!0,T.forceGLPutImageData=!1,T.initFilterBackend=function(){return T.enableGLFiltering&&T.isWebglSupported&&T.isWebglSupported(T.textureSize)?(console.log("max texture size: "+T.maxTextureSize),new T.WebglFilterBackend({tileSize:T.textureSize})):T.Canvas2dFilterBackend?new T.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=T),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:T.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}T.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var r=0,n=i.length;r-1||!!e&&this._objects.some((function(e){return"function"==typeof e.contains&&e.contains(t,!0)}))},complexity:function(){return this._objects.reduce((function(t,e){return t+(e.complexity?e.complexity():0)}),0)}},T.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof T.Gradient||this.set(e,new T.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof T.Pattern?i&&i():this.set(e,new T.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},r=e,n=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,T.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/h){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*a},radiansToDegrees:function(t){return t/a},rotatePoint:function(t,e,i){var r=new T.Point(t.x-e.x,t.y-e.y),n=T.util.rotateVector(r,i);return new T.Point(n.x,n.y).addEquals(e)},rotateVector:function(t,e){var i=T.util.sin(e),r=T.util.cos(e);return{x:t.x*r-t.y*i,y:t.x*i+t.y*r}},createVector:function(t,e){return new T.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new T.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var r=T.util.createVector(t,e),n=T.util.createVector(t,i),s=T.util.calcAngleBetweenVectors(r,n),o=s*(0===T.util.calcAngleBetweenVectors(T.util.rotateVector(r,s),n)?1:-1)/2;return{vector:T.util.getHatVector(T.util.rotateVector(r,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var r=[],n=e.strokeWidth/2,s=e.strokeUniform?new T.Point(1/e.scaleX,1/e.scaleY):new T.Point(1,1),o=function(t){var e=n/Math.hypot(t.x,t.y);return new T.Point(t.x*e*s.x,t.y*e*s.y)};return t.length<=1||t.forEach((function(a,h){var l,c,u=new T.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(T.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(T.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=T.util.getBisector(u,l,c),_=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-n/Math.sin(p/2),f=new T.Point(_.x*d*s.x,_.y*d*s.y),Math.hypot(f.x,f.y)/n<=e.strokeMiterLimit))return r.push(u.add(f)),void r.push(u.subtract(f));d=-n*Math.SQRT2,f=new T.Point(_.x*d*s.x,_.y*d*s.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(t,e,i){return i?new T.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new T.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>r?e-=r:e=0,i>r?i-=r:i=0);var n,s=!0,o=t.getImageData(e,i,2*r||1,2*r||1),a=o.data.length;for(n=3;n=n?s-n:2*Math.PI-(n-s)}function s(t,e,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=T.util.sin(c),d=T.util.cos(c),f=0,g=0,_=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,m=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,S=_*_,C=m*v-m*y-v*S,b=0;if(C<0){var w=Math.sqrt(1-C/(m*v));i*=w,s*=w}else b=(o===a?-1:1)*Math.sqrt(C/(m*y+v*S));var x=b*i*p/s,O=-b*s*_/i,E=d*x-u*O+.5*t,I=u*x+d*O+.5*e,R=n(1,0,(_-x)/i,(p-O)/s),A=n((_-x)/i,(p-O)/s,(-_-x)/i,(-p-O)/s);0===a&&A>0?A-=2*l:1===a&&A<0&&(A+=2*l);for(var D=Math.ceil(Math.abs(A/l*2)),M=[],L=A/D,P=8/3*Math.sin(L/4)*Math.sin(L/4)/Math.sin(L/2),F=R+L,k=0;kb)for(var x=1,O=_.length;x2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:n.x===t[i-2].x?0:-1,h=n.y>t[i-2].y?1:n.y===t[i-2].y?0:-1),r.push(["L",n.x+a*e,n.y+h*e]),r},T.util.getPathSegmentsInfo=d,T.util.getBoundsOfCurve=function(e,i,r,n,s,o,a,h){var l;if(T.cachesBoundsOfCurve&&(l=t.call(arguments),T.boundsOfCurveCache[l]))return T.boundsOfCurveCache[l];var c,u,d,f,g,_,p,m,v=Math.sqrt,y=Math.min,S=Math.max,C=Math.abs,b=[],w=[[],[]];u=6*e-12*r+6*s,c=-3*e+9*r-9*s+3*a,d=3*r-3*e;for(var x=0;x<2;++x)if(x>0&&(u=6*i-12*n+6*o,c=-3*i+9*n-9*o+3*h,d=3*n-3*i),C(c)<1e-12){if(C(u)<1e-12)continue;0<(f=-d/u)&&f<1&&b.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(m=v(p)))/(2*c))&&g<1&&b.push(g),0<(_=(-u-m)/(2*c))&&_<1&&b.push(_));for(var O,E,I,R=b.length,A=R;R--;)O=(I=1-(f=b[R]))*I*I*e+3*I*I*f*r+3*I*f*f*s+f*f*f*a,w[0][R]=O,E=I*I*I*i+3*I*I*f*n+3*I*f*f*o+f*f*f*h,w[1][R]=E;w[0][A]=e,w[1][A]=i,w[0][A+1]=a,w[1][A+1]=h;var D=[{x:y.apply(null,w[0]),y:y.apply(null,w[1])},{x:S.apply(null,w[0]),y:S.apply(null,w[1])}];return T.cachesBoundsOfCurve&&(T.boundsOfCurveCache[l]=D),D},T.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var r=0;e-i[r].length>0&&r1e-4;)i=h(s),n=s,(r=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=r);return i.angle=u(n),i}(s,e)}},T.util.transformPath=function(t,e,i){return i&&(e=T.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map((function(t){for(var i=t.slice(0),r={},n=1;n=e}))}}}(),function(){function t(e,i,r){if(r)if(!T.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var n=0,s=i.length;n57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var r=t.charCodeAt(e+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var n=t.charCodeAt(e-1);if(55296>n||n>56319)throw"Low surrogate without preceding high surrogate";return!1}T.util.string={camelize:function(t){return t.replace(/-+(.)?/g,(function(t,e){return e?e.toUpperCase():""}))},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,r=0,n=[];for(r=0;r-1?t.prototype[n]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var n=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return n}}(n):t.prototype[n]=e[n],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function n(){}function s(e){for(var i=null,r=this;r.constructor.superclass;){var n=r.constructor.superclass.prototype[e];if(r[e]!==n){i=n;break}r=r.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}T.util.createClass=function(){var i=null,o=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(n.prototype=i.prototype,a.prototype=new n,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===t.pointerType},d="string"==typeof(u=T.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,_=function(t){return t},d?_=function(t,e){return t.style.opacity=e,t}:f&&(_=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),T.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?_(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var r in e)"opacity"===r?_(t,e[r]):i["float"===r||"cssFloat"===r?void 0===i.styleFloat?"cssFloat":"styleFloat":r]=e[r];return t},function(){var t,e,i,r,n=Array.prototype.slice,s=function(t){return n.call(t,0)};try{t=s(T.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=T.document.createElement(t);for(var r in e)"class"===r?i.className=e[r]:"for"===r?i.htmlFor=e[r]:i.setAttribute(r,e[r]);return i}function a(t){for(var e=0,i=0,r=T.document.documentElement,n=T.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===T.document?(e=n.scrollLeft||r.scrollLeft||0,i=n.scrollTop||r.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(s=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=T.document.defaultView&&T.document.defaultView.getComputedStyle?function(t,e){var i=T.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=T.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",T.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=T.util.falseFunction),r?t.style[r]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},T.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),r?t.style[r]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},T.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},T.util.getById=function(t){return"string"==typeof t?T.document.getElementById(t):t},T.util.toArray=s,T.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},T.util.makeElement=o,T.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=o(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},T.util.getScrollLeftTop=a,T.util.getElementOffset=function(t){var i,r,n=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!n)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=n.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),r=a(t),{left:s.left+r.left-(i.clientLeft||0)+o.left,top:s.top+r.top-(i.clientTop||0)+o.top}},T.util.getNodeCanvas=function(t){var e=T.jsdomImplForWrapper(t);return e._canvas||e._image},T.util.cleanUpJsdomNode=function(t){if(T.isLikelyNode){var e=T.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}T.util.request=function(e,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",n=i.onComplete||function(){},s=new T.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(n(s),s.onreadystatechange=t)},"GET"===r&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(r,e,!0),"POST"!==r&&"PUT"!==r||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),T.log=console.log,T.warn=console.warn,function(){var t=T.util.object.extend,e=T.util.object.clone,i=[];function r(){return!1}function n(t,e,i,r){return-i*Math.cos(t/r*(Math.PI/2))+i+e}T.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach((function(t){t.cancel()})),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter((function(e){return"object"==typeof e.target&&e.target.canvas===t}));return e.forEach((function(t){t.cancel()})),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach((function(t){t.cancel()})),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find((function(e){return e.cancel===t}))},findAnimationsByTarget:function(t){return t?this.filter((function(e){return e.target===t})):[]}});var s=T.window.requestAnimationFrame||T.window.webkitRequestAnimationFrame||T.window.mozRequestAnimationFrame||T.window.oRequestAnimationFrame||T.window.msRequestAnimationFrame||function(t){return T.window.setTimeout(t,1e3/60)},o=T.window.cancelAnimationFrame||T.window.clearTimeout;function a(){return s.apply(T.window,arguments)}T.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=T.runningAnimations.indexOf(s);return t>-1&&T.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),T.runningAnimations.push(s),a((function(t){var e,l=t||+new Date,c=i.duration||500,u=l+c,d=i.onChange||r,f=i.abort||r,g=i.onComplete||r,_=i.easing||n,p="startValue"in i&&i.startValue.length>0,m="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?m.map((function(t,e){return v[e]-m[e]})):v-m);i.onStart&&i.onStart(),function t(i){var r=(e=i||+new Date)>u?c:e-l,n=r/c,S=p?m.map((function(t,e){return _(r,m[e],y[e],c)})):_(r,m,y,c),C=p?Math.abs((S[0]-m[0])/y[0]):Math.abs((S-m)/y);if(s.currentValue=p?S.slice():S,s.completionRate=C,s.durationRate=n,!o){if(!f(S,C,n))return e>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(S,C,n),void a(t));h()}}(l)})),s.cancel},T.util.requestAnimFrame=a,T.util.cancelAnimFrame=function(){return o.apply(T.window,arguments)},T.runningAnimations=i}(),function(){function t(t,e,i){var r="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(r+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}T.util.animateColor=function(e,i,r,n){var s=new T.Color(e).getSource(),o=new T.Color(i).getSource(),a=n.onComplete,h=n.onChange;return n=n||{},T.util.animate(T.util.object.extend(n,{duration:r||500,startValue:s,endValue:o,byValue:o,easing:function(e,i,r,s){return t(i,r,n.colorEasing?n.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,r){if(a)return a(t(o,o,0),i,r)},onChange:function(e,i,r){if(h){if(Array.isArray(e))return h(t(e,e,0),i,r);h(e,i,r)}}}))}}(),function(){function t(t,e,i,r){return t-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===t||"xlink:href"===t||"font"===t)return i;if("imageSmoothing"===t)return"optimizeQuality"===i;a=h?i.map(s):s(i,n)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,r,n,s,o=[];for(n=0,s=e.length;n1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,r,n,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,_=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",m=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,S=m&&y,C={},b="",w=0,T=0;if(C.width=0,C.height=0,C.toBeParsed=S,m&&(g||_)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(b=" translate("+s(g)+" "+s(_)+") ",a=(t.getAttribute("transform")||"")+b,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),S)return C;if(m)return C.width=s(d),C.height=s(f),C;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),n=parseFloat(l[3]),o=parseFloat(l[4]),C.minX=i,C.minY=r,C.viewBoxWidth=n,C.viewBoxHeight=o,y?(C.width=n,C.height=o):(C.width=s(d),C.height=s(f),c=C.width/n,u=C.height/o),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),w=C.width-n*c,T=C.height-o*c,"Mid"===p.alignX&&(w/=2),"Mid"===p.alignY&&(T/=2),"Min"===p.alignX&&(w=0),"Min"===p.alignY&&(T=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===_)return C;if((g||_)&&"#document"!==t.parentNode.nodeName&&(b=" translate("+s(g)+" "+s(_)+") "),a=b+" matrix("+c+" 0 0 "+u+" "+(i*c+w)+" "+(r*u+T)+") ","svg"===t.nodeName){for(h=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)h.appendChild(t.firstChild);t.appendChild(h)}else(h=t).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),C}function S(t,e){var i="xlink:href",r=m(t,e.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&S(t,r),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(t){r&&!e.hasAttribute(t)&&r.hasAttribute(t)&&e.setAttribute(t,r.getAttribute(t))})),!e.children.length)for(var n=r.cloneNode(!0);n.firstChild;)e.appendChild(n.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,n,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),r=0;i.length&&rt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,r,n,s){var o,a=(s.x-n.x)*(t.y-n.y)-(s.y-n.y)*(t.x-n.x),h=(r.x-t.x)*(t.y-n.y)-(r.y-t.y)*(t.x-n.x),l=(s.y-n.y)*(r.x-t.x)-(s.x-n.x)*(r.y-t.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new e.Point(t.x+c*(r.x-t.x),t.y+c*(r.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,r){var n,s,o,a,h=new i,l=r.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var r,n=new i,s=t.length;for(r=0;r0&&(n.status="Intersection"),n},e.Intersection.intersectPolygonRectangle=function(t,r,n){var s=r.min(n),o=r.max(n),a=new e.Point(o.x,s.y),h=new e.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,s,t),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function r(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,r){t/=255,i/=255,r/=255;var n,s,o,a=e.util.array.max([t,i,r]),h=e.util.array.min([t,i,r]);if(o=(a+h)/2,a===h)n=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:n=(i-r)/l+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+u(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var r=i.transform.target,n=r.canvas,s=e.util.object.clone(i);s.target=r,n&&n.fire("object:"+t,s),r.fire(t,i)}function _(t,e){var i=e.canvas,r=t[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function p(t){return t.originX===l&&t.originY===l}function m(t,e,i){var r=t.lockScalingX,n=t.lockScalingY;return!((!r||!n)&&(e||!r&&!n||!i)&&(!r||"x"!==e)&&(!n||"y"!==e))}function v(t,e,i,r){return{e:t,transform:e,pointer:{x:i,y:r}}}function y(t){return function(e,i,r,n){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,r,n);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function S(t,e){return function(i,r,n,s){var o=e(i,r,n,s);return o&&g(t,v(i,r,n,s)),o}}function C(t,i,r,n,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(n,s),i,r);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function b(t){return t.flipX!==t.flipY}function w(t,e,i,r,n){if(0!==t[e]){var s=n/t._getTransformedDimensions()[r]*t[i];t.set(i,s)}}function T(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=C(e,e.originX,e.originY,i,r),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?n=0:(n=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(n=-n),e.originX===a&&e.originY===o&&(n=-n),b(l)&&(n=-n));var _=g!==n;if(_){var p=l._getTransformedDimensions().y;l.set("skewX",n),w(l,"skewY","scaleY","y",p)}return _}function x(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=C(e,e.originX,e.originY,i,r),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?n=0:(n=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(n=-n),e.originX===a&&e.originY===o&&(n=-n),b(l)&&(n=-n));var _=g!==n;if(_){var p=l._getTransformedDimensions().x;l.set("skewY",n),w(l,"skewX","scaleX","x",p)}return _}function O(t,e,i,r,n){n=n||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=n.by,S=_(t,f),b=m(f,y,S),w=e.gestureScale;if(b)return!1;if(w)o=e.scaleX*w,a=e.scaleY*w;else{if(s=C(e,e.originX,e.originY,i,r),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,e.signX||(e.signX=l),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==l||e.signY!==u))return!1;if(h=f._getTransformedDimensions(),S&&!y){var T=Math.abs(s.x)+Math.abs(s.y),x=e.original,O=T/(Math.abs(h.x*x.scaleX/f.scaleX)+Math.abs(h.y*x.scaleY/f.scaleY));o=x.scaleX*O,a=x.scaleY*O}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var E=f.scaleX,I=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),E!==f.scaleX||I!==f.scaleY}n.scaleCursorStyleHandler=function(t,e,r){var n=_(t,r),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),m(r,s,n))return"not-allowed";var o=f(r,e);return i[o]+"-resize"},n.skewCursorStyleHandler=function(t,e,i){var n="not-allowed";if(0!==e.x&&i.lockSkewingY)return n;if(0!==e.y&&i.lockSkewingX)return n;var s=f(i,e)%4;return r[s]+"-resize"},n.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?n.skewCursorStyleHandler(t,e,i):n.scaleCursorStyleHandler(t,e,i)},n.rotationWithSnapping=S("rotating",y((function(t,e,i,r){var n=e,s=n.target,o=s.translateToOriginPoint(s.getCenterPoint(),n.originX,n.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(n.ey-o.y,n.ex-o.x),l=Math.atan2(r-o.y,i-o.x),c=u(l-h+n.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,_=Math.floor(c/d)*d;Math.abs(c-_)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),b(h)&&(n=n===s?a:s)),e.originX=n,S("skewing",y(T))(t,e,i,r))},n.skewHandlerY=function(t,e,i,r){var n,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?n=C(e,l,l,i,r).y>0?o:h:(c>0&&(n=u===s?o:h),c<0&&(n=u===s?h:o),b(a)&&(n=n===o?h:o)),e.originY=n,S("skewing",y(x))(t,e,i,r))},n.dragHandler=function(t,e,i,r){var n=e.target,s=i-e.offsetX,o=r-e.offsetY,a=!n.get("lockMovementX")&&n.left!==s,h=!n.get("lockMovementY")&&n.top!==o;return a&&n.set("left",s),h&&n.set("top",o),(a||h)&&g("moving",v(t,e,i,r)),a||h},n.scaleOrSkewActionName=function(t,e,i){var r=t[i.canvas.altActionKey];return 0===e.x?r?"skewX":"scaleY":0===e.y?r?"skewY":"scaleX":void 0},n.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},n.fireEvent=g,n.wrapWithFixedAnchor=y,n.wrapWithFireEvent=S,n.getLocalPoint=C,e.controlsUtils=n}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,r=e.controlsUtils;r.renderCircleControl=function(t,e,i,r,n){r=r||{};var s,o=this.sizeX||r.cornerSize||n.cornerSize,a=this.sizeY||r.cornerSize||n.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:n.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||n.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=r.cornerColor||n.cornerColor,t.strokeStyle=r.cornerStrokeColor||n.cornerStrokeColor,o>a?(s=o,t.scale(1,a/o),d=i*o/a):a>o?(s=a,t.scale(o/a,1),u=e*a/o):s=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},r.renderSquareControl=function(t,e,r,n,s){n=n||{};var o=this.sizeX||n.cornerSize||s.cornerSize,a=this.sizeY||n.cornerSize||s.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=n.cornerColor||s.cornerColor,t.strokeStyle=n.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,r),t.rotate(i(s.angle)),t[l+"Rect"](-u,-d,o,a),c&&t.strokeRect(-u,-d,o,a),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,r,n,s){var o,a,h,l,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-e.util.degreesToRadians(t),_=Math.PI/2-d-e.util.degreesToRadians(t);o=f*e.util.cos(g),a=f*e.util.sin(g),h=f*e.util.cos(_),l=f*e.util.sin(_)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),o=h=f*e.util.cos(g),a=l=f*e.util.sin(g);return{tl:{x:r-l,y:n-h},tr:{x:r+o,y:n-a},bl:{x:r-o,y:n+a},br:{x:r+l,y:n+h}}},render:function(t,i,r,n,s){"circle"===((n=n||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,r,n,s):e.controlsUtils.renderSquareControl.call(this,t,i,r,n,s)}}}(e),function(){function t(t,e){var i,r,n,s,o=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(n=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),n||(n=t.getAttribute("stop-opacity")),r=(i=new T.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*e,{offset:a,color:i.toRgb(),opacity:n}}var e=T.util.object.clone;T.Gradient=T.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach((function(e){i[e]=t[e]})),this.id?this.id+="_"+T.Object.__uid++:this.id=T.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new T.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return T.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var r,n,s,o,a=e(this.coords,!0),h=(i=i||{},e(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():T.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort((function(t,e){return t.offset-e.offset})),"objectBoundingBox"===g?(u/=t.width,d/=t.height):(u+=t.width/2,d+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(u-=t.pathOffset.x,d-=t.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+T.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),r=0,n=h.length;r0){var p=_/Math.max(a.r1,a.r2);for(r=0,n=h.length;r\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,r,n=T.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(n.x1,n.y1,n.x2,n.y2):"radial"===this.type&&(e=t.createRadialGradient(n.x1,n.y1,n.r1,n.x2,n.y2,n.r2)),i=0,r=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var o,a,h,l,c=e.getElementsByTagName("stop"),u="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",d=e.getAttribute("gradientTransform")||"",f=[],g=0,_=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(o="linear",a=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(o="radial",a=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),h=c.length;h--;)f.push(t(c[h],s));return l=T.parseTransformAttribute(d),function(t,e,i,r){var n,s;Object.keys(e).forEach((function(t){"Infinity"===(n=e[t])?s=1:"-Infinity"===n?s=0:(s=parseFloat(e[t],10),"string"==typeof n&&/^(\d+\.\d+)%|(\d+)%$/.test(n)&&(s*=.01,"pixels"===r&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s}))}(0,a,n,u),"pixels"===u&&(g=-i.left,_=-i.top),new T.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:_})}})}(),m=T.util.toFixed,T.Pattern=T.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=T.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=T.util.createImage(),T.util.loadImage(t.source,(function(t,r){i.source=t,e&&e(i,r)}),null,this.crossOrigin)}},toObject:function(t){var e,i,r=T.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:m(this.offsetX,r),offsetY:m(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},T.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,r=e.height/t.height,n=this.offsetX/t.width,s=this.offsetY/t.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(r=1,s&&(r+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,n&&(i+=Math.abs(n))),e.src?o=e.src:e.toDataURL&&(o=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),r=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(r[1],10)||0,offsetY:parseFloat(r[2],10)||0,blur:parseFloat(r[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var r=40,n=40,s=e.Object.NUM_FRACTION_DIGITS,o=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),a=new e.Color(this.color);return t.width&&t.height&&(r=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,n=100*i((Math.abs(o.y)+this.blur)/t.height,s)+20),t.flipX&&(o.x*=-1),t.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(e){this[e]!==i[e]&&(t[e]=this[e])}),this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(T.StaticCanvas)T.warn("fabric.StaticCanvas is already defined.");else{var t=T.util.object.extend,e=T.util.getElementOffset,i=T.util.removeFromArray,r=T.util.toFixed,n=T.util.transformPoint,s=T.util.invertTransform,o=T.util.getNodeCanvas,a=T.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");T.StaticCanvas=T.util.createClass(T.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:T.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return T.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,T.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=T.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,r){return"string"==typeof e?T.util.loadImage(e,(function(e,n){if(e){var s=new T.Image(e,r);this[t]=s,s.canvas=this}i&&i(e,n)}),this,r&&r.crossOrigin):(r&&e.setOptions(r),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=a();if(!t)throw h;if(t.style||(t.style={}),void 0===t.getContext)throw h;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=T.util.getById(t)||this._createCanvasElement(),T.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var r in e=e||{},t)i=t[r],e.cssOnly||(this._setBackstoreDimension(r,t[r]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(r,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,r,n=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,r=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,n=e.width||this.width,s=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=T.Object.NUM_FRACTION_DIGITS;e.viewBox?o='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+r(-i[4]/i[0],a)+" "+r(-i[5]/i[3],a)+" "+r(this.width/i[0],a)+" "+r(this.height/i[3],a)+'" '),t.push("\n',"Created with Fabric.js ",T.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+T.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map((function(e){var i=t[e+"Color"];if(i&&i.toLive){var r=t[e+"Vpt"],n=t.viewportTransform,s={width:t.width/(r?n[0]:1),height:t.height/(r?n[3]:1)};return i.toSVG(s,{additionalTransform:r?T.util.matrixToSVG(n):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,r,n,s,o,a,h="",l={},c=T.fontPaths,u=[];for(this._objects.forEach((function t(e){u.push(e),e._objects&&e._objects.forEach(t)})),o=0,a=u.length;o',"\n",h,"","\n"].join("")),h},_setSVGObjects:function(t,e){var i,r,n,s=this._objects;for(r=0,n=s.length;r\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,r,n,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(n=s._objects).length;e--;)r=n[e],i(this._objects,r),this._objects.unshift(r);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,r,n,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(n=s._objects,e=0;e0+l&&(o=s-1,i(this._objects,n),this._objects.splice(o,0,n)),l++;else 0!==(s=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var r,n;if(i){for(r=e,n=e-1;n>=0;--n)if(t.intersectsWithObject(this._objects[n])||t.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(t)){r=n;break}}else r=e-1;return r},bringForward:function(t,e){if(!t)return this;var r,n,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(r=(a=h._objects).length;r--;)n=a[r],(s=this._objects.indexOf(n))"}}),t(T.StaticCanvas.prototype,T.Observable),t(T.StaticCanvas.prototype,T.Collection),t(T.StaticCanvas.prototype,T.DataURLExporter),t(T.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=a();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),T.StaticCanvas.prototype.toJSON=T.StaticCanvas.prototype.toObject,T.isLikelyNode&&(T.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},T.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),T.BaseBrush=T.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,r=t.getZoom();t&&t._isRetinaScaling()&&(r*=T.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*r,i.shadowOffsetX=e.offsetX*r,i.shadowOffsetY=e.offsetY*r}},needsFullRender:function(){return new T.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),T.PencilBrush=T.util.createClass(T.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var r=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,r.x,r.y),r},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,r=i.length,n=this.canvas.contextTop;this._saveAndTransform(n),this.oldEnd&&(n.beginPath(),n.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(n,i[r-2],i[r-1],!0),n.stroke(),n.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new T.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new T.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,r=this._points[0],n=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&r.x===n.x&&r.y===n.y){var s=this.width/1e3;r=new T.Point(r.x,r.y),n=new T.Point(n.x,n.y),r.x-=s,n.x+=s}for(t.moveTo(r.x,r.y),e=1,i=this._points.length;e=n&&(o=t[i],a.push(o));return a.push(t[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),T.CircleBrush=T.util.createClass(T.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,r=this.points;for(this._saveAndTransform(i),t=0,e=r.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var n=0,s=this._objects.length;n1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),r=T.util.invertTransform(i),n=this.restorePointerVpt(e);return T.util.transformPoint(n,r)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var r=this._normalizePointer(t,{x:e,y:i}),n=Math.max(t.cacheTranslationX+r.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+r.y*t.zoomY,0);return T.util.isTransparent(t._cacheContext,Math.round(n),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=t.selectionBackgroundColor,h=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),t.render(o),o.restore(),t.selectionBackgroundColor=a,T.util.isTransparent(o,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(e){return!0===t[e]})):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),r=this._activeObject;return!e||e&&r&&i.length>1&&-1===i.indexOf(e)&&r!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&r&&r!==e},_shouldCenterTransform:function(t,e,i){var r;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?r=this.centeredScaling||t.centeredScaling:"rotate"===e&&(r=this.centeredRotation||t.centeredRotation),r?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,r){if(!e||!t)return"drag";var n=r.controls[e];return n.getActionName(i,n,r)},_setupCurrentTransform:function(t,i,r){if(i){var n=this.getPointer(t),s=i.__corner,o=i.controls[s],a=r&&s?o.getActionHandler(t,i,o):T.controlsUtils.dragHandler,h=this._getActionFromCorner(r,s,t,i),l=this._getOriginFromCorner(i,s),c=t[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:n.x-i.left,offsetY:n.y-i.top,originX:l.x,originY:l.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:T.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new T.Point(e.ex,e.ey),r=T.util.transformPoint(i,this.viewportTransform),n=new T.Point(e.ex+e.left,e.ey+e.top),s=T.util.transformPoint(n,this.viewportTransform),o=Math.min(r.x,s.x),a=Math.min(r.y,s.y),h=Math.max(r.x,s.x),l=Math.max(r.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,T.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var r,n,s=this.getPointer(t,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(t),l=a.length>1&&!e||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!e&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;r=o,n=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&r&&c!==r&&(c=r,this.targets=n),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,r,n=t.length;n--;){var s=t[n],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,s,e)){(i=t[n]).subTargetCheck&&i instanceof T.Group&&(r=this._searchPossibleTargets(i._objects,e))&&this.targets.push(r);break}}return i},restorePointerVpt:function(t){return T.util.transformPoint(t,T.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var r,n=t(e),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,i||(n=this.restorePointerVpt(n));var l=this.getRetinaScaling();return 1!==l&&(n.x/=l,n.y/=l),r=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:n.x*r.width,y:n.y*r.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),T.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=T.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),T.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),T.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;T.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,T.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,r=this.getActiveObjects(),n=[],s=[];t.forEach((function(t){-1===r.indexOf(t)&&(i=!0,t.fire("deselected",{e,target:t}),s.push(t))})),r.forEach((function(r){-1===t.indexOf(r)&&(i=!0,r.fire("selected",{e,target:r}),n.push(r))})),t.length>0&&r.length>0?i&&this.fire("selection:updated",{e,selected:n,deselected:s}):r.length>0?this.fire("selection:created",{e,selected:n}):t.length>0&&this.fire("selection:cleared",{e,deselected:s})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){T.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,T.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(t),n=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,r),n},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){e[i]=t[i]})),T.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,r)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),T.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),T.StaticCanvas)"prototype"!==r&&(T.Canvas[r]=T.StaticCanvas[r])}(),function(){var t=T.util.addListener,e=T.util.removeListener,i={passive:!1};function r(t,e){return t.button&&t.button===e-1}T.util.object.extend(T.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var r=this.upperCanvasEl,n=this._getEventPrefix();t(T.window,"resize",this._onResize),t(r,n+"down",this._onMouseDown),t(r,n+"move",this._onMouseMove,i),t(r,n+"out",this._onMouseOut),t(r,n+"enter",this._onMouseEnter),t(r,"wheel",this._onMouseWheel),t(r,"contextmenu",this._onContextMenu),t(r,"dblclick",this._onDoubleClick),t(r,"dragover",this._onDragOver),t(r,"dragenter",this._onDragEnter),t(r,"dragleave",this._onDragLeave),t(r,"drop",this._onDrop),this.enablePointerEvents||t(r,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](r,"gesture",this._onGesture),eventjs[e](r,"drag",this._onDrag),eventjs[e](r,"orientation",this._onOrientationChange),eventjs[e](r,"shake",this._onShake),eventjs[e](r,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(T.document,t+"up",this._onMouseUp),e(T.document,"touchend",this._onTouchEnd,i),e(T.document,t+"move",this._onMouseMove,i),e(T.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach((function(r){i.fire("mouse:out",{target:e,e:t}),r&&e.fire("mouseout",{e:t})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(t){t.isEditing&&t.hiddenTextarea.focus()}))},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(r){r.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(r)),this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();t(T.document,"touchend",this._onTouchEnd,i),t(T.document,"touchmove",this._onMouseMove,i),e(n,s+"down",this._onMouseDown)},_onMouseDown:function(r){this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();e(n,s+"move",this._onMouseMove,i),t(T.document,s+"up",this._onMouseUp),t(T.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(r){if(!(r.touches.length>0)){this.__onMouseUp(r),this._resetTransformEventData(),this.mainTouchId=null;var n=this._getEventPrefix();e(T.document,"touchend",this._onTouchEnd,i),e(T.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){t(s.upperCanvasEl,n+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(r){this.__onMouseUp(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(r)&&(e(T.document,s+"up",this._onMouseUp),e(T.document,s+"move",this._onMouseMove,i),t(n,s+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,n=this._groupSelector,s=!1,o=!n||0===n.left&&0===n.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),r(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(r(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!a&&e===this._activeObject)}var h,l;if(e){if(h=e._findTargetCorner(this.getPointer(t,!0),T.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),s=!0;else{var c=e.controls[h],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(l=this.getPointer(t)).x,l.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);l=l||this.getPointer(t),f&&f(t,i,l.x,l.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,o),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),r=this.targets,n={e,target:i,subTargets:r};if(this.fire(t,n),i&&i.fire(t,n),!r)return i;for(var s=0;s1&&(e=new T.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],r=this._groupSelector.ex,n=this._groupSelector.ey,s=r+this._groupSelector.left,o=n+this._groupSelector.top,a=new T.Point(v(r,s),v(n,o)),h=new T.Point(y(r,s),y(n,o)),l=!this.selectionFullyContained,c=r===s&&n===o,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(l&&e.intersectsWithRect(a,h,!0)||e.isContainedWithinRect(a,h,!0)||l&&e.containsPoint(a,null,!0)||l&&e.containsPoint(h,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter((function(e){return!e.onSelect({e:t})}))),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),T.util.object.extend(T.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,r=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),n=this.toCanvasElement(r,t);return T.util.toDataURL(n,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,r=(e.height||this.height)*t,n=this.getZoom(),s=this.width,o=this.height,a=n*t,h=this.viewportTransform,l=(h[4]-(e.left||0))*t,c=(h[5]-(e.top||0))*t,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=T.util.createCanvasElement(),_=this.contextTop;return g.width=i,g.height=r,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=r,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=_,g}}),T.util.object.extend(T.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var r="string"==typeof t?JSON.parse(t):T.util.object.clone(t),n=this,s=r.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete r.clipPath,this._enlivenObjects(r.objects,(function(t){n.clear(),n._setBgOverlay(r,(function(){s?n._enlivenObjects([s],(function(i){n.clipPath=i[0],n.__setupCanvas.call(n,r,t,o,e)})):n.__setupCanvas.call(n,r,t,o,e)}))}),i),this}},__setupCanvas:function(t,e,i,r){var n=this;e.forEach((function(t,e){n.insertAt(t,e)})),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),r&&r()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var r=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,r),this.__setBgOverlay("overlayImage",t.overlayImage,i,r),this.__setBgOverlay("backgroundColor",t.background,i,r),this.__setBgOverlay("overlayColor",t.overlay,i,r)}else e&&e()},__setBgOverlay:function(t,e,i,r){var n=this;if(!e)return i[t]=!0,void(r&&r());"backgroundImage"===t||"overlayImage"===t?T.util.enlivenObjects([e],(function(e){n[t]=e[0],i[t]=!0,r&&r()})):this["set"+T.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,r&&r()}))},_enlivenObjects:function(t,e,i){t&&0!==t.length?T.util.enlivenObjects(t,(function(t){e&&e(t)}),null,i):e&&e([])},_toDataURL:function(t,e){this.clone((function(i){e(i.toDataURL(t))}))},_toDataURLWithMultiplier:function(t,e,i){this.clone((function(r){i(r.toDataURLWithMultiplier(t,e))}))},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData((function(e){e.loadFromJSON(i,(function(){t&&t(e)}))}))},cloneWithoutData:function(t){var e=T.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new T.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),t&&t(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,n=e.util.toFixed,s=e.util.string.capitalize,o=e.util.degreesToRadians,a=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,r=t.width,n=t.height,s=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(r<=s&&n<=s&&r*n<=i)return rc&&(t.zoomX/=r/c,t.width=c,t.capped=!0),n>u&&(t.zoomY/=n/u,t.height=u,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,r=e.y*t.scaleY/this.scaleY;return{width:i+2,height:r+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:r}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,r=t._currentTransform.action;if(this===i&&r.slice&&"scale"===r.slice(0,5))return!1}var n,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=e.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,_=f||g,p=0,m=0,v=!1;if(f){var y=this._cacheCanvas.width,S=this._cacheCanvas.height,C=l>y||c>S;v=C||(l<.9*y||c<.9*S)&&y>h&&S>h,C&&!a.capped&&(l>h||c>h)&&(p=.1*l,m=.1*c)}return this instanceof e.Text&&this.path&&(_=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,m+=this.getHeightOfLine(0)*this.zoomY),!!_&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+m)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),n=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-n)+n,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,r={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:n(this.left,i),top:n(this.top,i),width:n(this.width,i),height:n(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:n(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:n(this.strokeMiterLimit,i),scaleX:n(this.scaleX,i),scaleY:n(this.scaleY,i),angle:n(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:n(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:n(this.skewX,i),skewY:n(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(r.clipPath=this.clipPath.toObject(t),r.clipPath.inverted=this.clipPath.inverted,r.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,r,t),this.includeDefaultValues||(r=this._removeDefaultValues(r)),r},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach((function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])})),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var r=this.canvas.getZoom(),n=this.canvas.getRetinaScaling();e*=r*n,i*=r*n}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var r="scaleX"===t||"scaleY"===t,n=this[t]!==i,s=!1;return r&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,n&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var r=e.util.invertTransform(this.calcTransformMatrix());t.transform(r[0],r[1],r[2],r[3],r[4],r[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,r=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=r},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var r,n,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();n=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),r=e.util.qrDecompose(h),t.save(),t.translate(r.translateX,r.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(r.angle-=180),t.rotate(o(this.group?r.angle:this.angle)),i.forActiveSelection||this.group?n&&this.drawBordersInGroup(t,r,i):n&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,r=this.shadow,n=this.canvas,s=n&&n.viewportTransform[0]||1,o=n&&n.viewportTransform[3]||1;i=r.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),n&&n._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=r.color,t.shadowBlur=r.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=r.offsetX*s*i.scaleX,t.shadowOffsetY=r.offsetY*o*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,r=-this.width/2+e.offsetX||0,n=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,r,n):t.transform(1,0,0,1,r,n),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:r,offsetY:n}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var r,n=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=n.x/this.scaleX/o,h=n.y/this.scaleY/o;s.width=a,s.height=h,(r=s.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,h),r.lineTo(0,h),r.closePath(),r.translate(a/2,h/2),r.scale(n.zoomX/this.scaleX/o,n.zoomY/this.scaleY/o),this._applyPatternGradientTransform(r,i),r.fillStyle=i.toLive(t),r.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/n.zoomX,o*this.scaleY/n.zoomY),t.strokeStyle=r.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var r=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(r,t):e.Object._fromObject("Object",r,t)},cloneAsImage:function(t,i){var r=this.toCanvasElement(i);return t&&t(new e.Image(r)),this},toCanvasElement:function(t){t||(t={});var i=e.util,r=i.saveObjectTransform(this),n=this.group,s=this.shadow,o=Math.abs,a=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var h,l,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,_={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),_.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),_.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+_.x,u=f.height+_.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var m=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",m),n&&(this.group=n),this.set(r).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var r=new e.Point(i.x,i.y),n=this._getLeftTopCoords();return this.angle&&(r=e.util.rotatePoint(r,n,o(-this.angle))),{x:r.x-n.x,y:r.y-n.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,n,s){var o=e[t];i=r(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],(function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,(function(){var t=s?new o(i[s],i):new o(i);n&&n(t)}))}))},e.Object.__uid=0)}(e),S=T.util.degreesToRadians,C={left:-.5,center:0,right:.5},b={top:-.5,center:0,bottom:.5},T.util.object.extend(T.Object.prototype,{translateToGivenOrigin:function(t,e,i,r,n){var s,o,a,h=t.x,l=t.y;return"string"==typeof e?e=C[e]:e-=.5,"string"==typeof r?r=C[r]:r-=.5,"string"==typeof i?i=b[i]:i-=.5,"string"==typeof n?n=b[n]:n-=.5,o=n-i,((s=r-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+s*a.x,l=t.y+o*a.y),new T.Point(h,l)},translateToCenterPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?T.util.rotatePoint(r,t,S(this.angle)):r},translateToOriginPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?T.util.rotatePoint(r,t,S(this.angle)):r},getCenterPoint:function(){var t=new T.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var r,n,s=this.getCenterPoint();return r=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new T.Point(this.left,this.top),n=new T.Point(t.x,t.y),this.angle&&(n=T.util.rotatePoint(n,s,-S(this.angle))),n.subtractEquals(r)},setPositionByOrigin:function(t,e,i){var r=this.translateToCenterPoint(t,e,i),n=this.translateToOriginPoint(r,this.originX,this.originY);this.set("left",n.x),this.set("top",n.y)},adjustPosition:function(t){var e,i,r=S(this.angle),n=this.getScaledWidth(),s=T.util.cos(r)*n,o=T.util.sin(r)*n;e="string"==typeof this.originX?C[this.originX]:this.originX-.5,i="string"==typeof t?C[t]:t-.5,this.left+=s*(i-e),this.top+=o*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=T.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,r=t.transformPoint;t.object.extend(T.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new T.Point(i.tl.x,i.tl.y),new T.Point(i.tr.x,i.tr.y),new T.Point(i.br.x,i.br.y),new T.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,r){var n=this.getCoords(i,r);return"Intersection"===T.Intersection.intersectPolygonRectangle(n,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===T.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var r=this.getCoords(e,i),n=e?t.aCoords:t.lineCoords,s=0,o=t._getImageLines(n);s<4;s++)if(!t.containsPoint(r[s],o))return!1;return!0},isContainedWithinRect:function(t,e,i,r){var n=this.getBoundingRect(i,r);return n.left>=t.x&&n.left+n.width<=e.x&&n.top>=t.y&&n.top+n.height<=e.y},containsPoint:function(t,e,i,r){var n=this._getCoords(i,r),s=(e=e||this._getImageLines(n),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some((function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y}))||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var r={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(r,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every((function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)}))&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,r,n,s=0;for(var o in e)if(!((n=e[o]).o.y=t.y&&n.d.y>=t.y||(n.o.x===n.d.x&&n.o.x>=t.x?r=n.o.x:(i=(n.d.y-n.o.y)/(n.d.x-n.o.x),r=-(t.y-0*t.x-(n.o.y-i*n.o.x))/(0-i)),r>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var r=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(r)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,r=e.additionalTransform||"",n=[this.getSvgTransform(!0,r),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=n,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,r,n=(e=e||{}).noStyle,s=e.reviver,o=n?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],_=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+T.Object.__uid++,r='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,n?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[_]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(r),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=T.util.object.extend,e="stateProperties";function i(e,i,r){var n={};r.forEach((function(t){n[t]=e[t]})),t(e[i],n,!0)}function r(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var n=0,s=t.length;n=0;h--)if(n=a[h],this.isControlVisible(n)&&(r=this._getImageLines(e?this.oCoords[n].touchCorner:this.oCoords[n].corner),0!==(i=this._findCrossPoints({x:s,y:o},r))&&i%2==1))return this.__corner=n,n;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),r=this._calculateCurrentDimensions(),n=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/n[0],1/n[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-r.x/2,-r.y/2,r.x,r.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),r=this.borderScaleFactor,n=i.x+r,s=i.y+r,o=void 0!==e.hasControls?e.hasControls:this.hasControls,a=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-n/2,-s/2,n,s),o&&(t.beginPath(),this.forEachControl((function(e,i,r){e.withConnection&&e.getVisibility(r,i)&&(a=!0,t.moveTo(e.x*n,e.y*s),t.lineTo(e.x*n+e.offsetX,e.y*s+e.offsetY))})),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var r=T.util.sizeAfterTransform(this.width,this.height,e),n=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=r.x+n*(s?this.canvas.getZoom():e.scaleX)+o,h=r.y+n*(s?this.canvas.getZoom():e.scaleY)+o;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-h/2,a,h),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,r,n=this.canvas.getRetinaScaling();return t.setTransform(n,0,0,n,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(n,s,o){r=o.oCoords[s],n.getVisibility(o,s)&&(i&&(r=T.util.transformPoint(r,i)),n.render(t,r.x,r.y,e,o))})),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),T.util.object.extend(T.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),n()},onComplete:function(){t.setCoords(),r()}})},fxCenterObjectV:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),n()},onComplete:function(){t.setCoords(),r()}})},fxRemove:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),n()},onComplete:function(){s.remove(t),r()}})}}),T.util.object.extend(T.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],r=[];for(t in arguments[0])i.push(t);for(var n=0,s=i.length;n-1||n&&s.colorProperties.indexOf(n[1])>-1,a=n?this.get(n[0])[n[1]]:this.get(t);"from"in i||(i.from=a),o||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var h={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,r){return i.abort.call(s,t,e,r)},onChange:function(e,o,a){n?s[n[0]][n[1]]=e:s.set(t,e),r||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,n){r||(s.setCoords(),i.onComplete&&i.onComplete(t,e,n))}};return o?T.util.animateColor(h.startValue,h.endValue,h.duration,h):T.util.animate(h)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,n={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,r=t.axis1,n=t.axis2,s=t.dimension,o=e.nearest,a=e.center,h=e.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(r),this.get(n));case a:return Math.min(this.get(r),this.get(n))+.5*this.get(s);case h:return Math.max(this.get(r),this.get(n))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==n[t]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,r=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:r,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,r,n){n=n||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];r(new e.Line(o,i(s,n)))},e.Line.fromObject=function(t,i){var n=r(t,!0);n.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",n,(function(t){delete t.points,i&&i(t)}),"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,r=(this.endAngle-this.startAngle)%360;if(0===r)t=["\n'];else{var n=i(this.startAngle),s=i(this.endAngle),o=this.radius;t=['180?"1":"0")+" 1"," "+e.util.cos(s)*o+" "+e.util.sin(s)*o,'" ',"COMMON_PARTS"," />\n"]}return t},_render:function(t){t.beginPath(),t.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(t)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(t){return this.radius=t,this.set("width",2*t).set("height",2*t)}}),e.Circle.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),e.Circle.fromElement=function(t,i){var r,n=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(r=n)&&r.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");n.left=(n.left||0)-n.radius,n.top=(n.top||0)-n.radius,i(new e.Circle(n))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var r=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,i(new e.Ellipse(r))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,r=this.width,n=this.height,s=-this.width/2,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(s+e,o),t.lineTo(s+r-e,o),a&&t.bezierCurveTo(s+r-h*e,o,s+r,o+h*i,s+r,o+i),t.lineTo(s+r,o+n-i),a&&t.bezierCurveTo(s+r,o+n-h*i,s+r-h*e,o+n,s+r-e,o+n),t.lineTo(s+e,o+n),a&&t.bezierCurveTo(s+h*e,o+n,s,o+n-h*i,s,o+n-i),t.lineTo(s,o+i),a&&t.bezierCurveTo(s,o+h*i,s+h*e,o,s+e,o),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,r,n){if(!t)return r(null);n=n||{};var s=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new e.Rect(i(n?e.util.object.clone(n):{},s));o.visible=o.visible&&o.width>0&&o.height>0,r(o)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.array.min,n=e.util.array.max,s=e.util.toFixed,o=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),r=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-r,this.height=i.height-r,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+r/2,y:i.top-this.strokeWidth/2+r/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+r/2,y:i.top+this.height/2+r/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=r(t,"x")||0,i=r(t,"y")||0;return{left:e,top:i,width:(n(t,"x")||0)-e,height:(n(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,r=this.pathOffset.y,n=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,r=this.pathOffset.x,n=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-r,this.points[0].y-n);for(var s=0;s"},toObject:function(t){return n(this.callSuper("toObject",t),{path:this.path.map((function(t){return t.slice()}))})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,t)+", "+o(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,n,s=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var r=this._objects.length;if(this.useSetOnGroup)for(;r--;)this._objects[r].setOnGroup(t,i);if("canvas"===t)for(;r--;)this._objects[r]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,r=this._objects.filter((function(t){return!t.excludeFromExport})).map((function(e){var r=e.includeDefaultValues;e.includeDefaultValues=i;var n=e.toObject(t);return e.includeDefaultValues=r,n})),n=e.Object.prototype.toObject.call(this,t);return n.objects=r,n},toDatalessObject:function(t){var i,r=this.sourcePath;if(r)i=r;else{var n=this.includeDefaultValues;i=this._objects.map((function(e){var i=e.includeDefaultValues;e.includeDefaultValues=n;var r=e.toDatalessObject(t);return e.includeDefaultValues=i,r}))}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,r=this._objects.length;i\n"],i=0,r=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,r=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var r=0,n=this._objects.length;r\n','\t\n',"\n"),o=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var l=this.fill;this.fill=null,t=["\t\n'],this.fill=l}return"fill"!==this.paintFirst?e.concat(t,i):e.concat(i,t)},getSrc:function(t){var e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src"):e.src:this.src||""},setSrc:function(t,e,i){return T.util.loadImage(t,(function(t,r){this.setElement(t,i),this._setWidthHeight(),e&&e(this,r)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),r=i.scaleX,n=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||r>e&&n>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=n);T.filterBackend||(T.filterBackend=T.initFilterBackend());var o=T.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=r,this._lastScaleY=t.scaleY=n,T.filterBackend.applyFilters([t],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter((function(t){return t&&!t.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,r=e.naturalHeight||e.height;if(this._element===this._originalElement){var n=T.util.createCanvasElement();n.width=i,n.height=r,this._element=n,this._filteredEl=n}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,r),this._lastScaleX=1,this._lastScaleY=1;return T.filterBackend||(T.filterBackend=T.initFilterBackend()),T.filterBackend.applyFilters(t,this._originalElement,i,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){T.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){T.util.setImageSmoothing(t,this.imageSmoothing),T.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,r=this._filterScalingY,n=this.width,s=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=h*i,f=l*r,g=o(n*i,c-d),_=o(s*r,u-f),p=-n/2,m=-s/2,v=o(n,c/i-h),y=o(s,u/r-l);e&&t.drawImage(e,d,f,g,_,p,m,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(T.util.getById(t),e),T.util.addClass(this.getElement(),T.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?T.util.enlivenObjects(t,(function(t){e&&e(t)}),"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=T.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,r=this._element.height,n=1,s=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!e||"none"===e.alignX&&"none"===e.alignY?(n=c/i,s=u/r):("meet"===e.meetOrSlice&&(t=(c-i*(n=s=T.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-r*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(n=s=T.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=r-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/n,r=u/s)),{width:i,height:r,scaleX:n,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),T.Image.CSS_CANVAS="canvas-img",T.Image.prototype.getSvgSrc=T.Image.prototype.getSrc,T.Image.fromObject=function(t,e){var i=T.util.object.clone(t);T.util.loadImage(i.src,(function(t,r){r?e&&e(null,!0):T.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],T.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],T.util.enlivenObjectEnlivables(i,i,(function(){var r=new T.Image(t,i);e(r,!1)}))}))}))}),null,i.crossOrigin)},T.Image.fromURL=function(t,e,i){T.util.loadImage(t,(function(t,r){e&&e(new T.Image(t,i),r)}),null,i&&i.crossOrigin)},T.Image.ATTRIBUTE_NAMES=T.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),T.Image.fromElement=function(t,i,r){var n=T.parseAttributes(t,T.Image.ATTRIBUTE_NAMES);T.Image.fromURL(n["xlink:href"],i,e(r?T.util.object.clone(r):{},n))})}(e),T.util.object.extend(T.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,r=t.onChange||e,n=this;return T.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){n.rotate(t),r()},onComplete:function(){n.setCoords(),i()}})}}),T.util.object.extend(T.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",r=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(r,i),t.compileShader(r),!!t.getShaderParameter(r,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}T.isWebglSupported=function(e){if(T.isLikelyNode)return!1;e=e||T.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),n=!1;if(r){T.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),n=T.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(r,s[o])){T.webGlPrecision=s[o];break}}return this.isSupported=n,n},T.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,r=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var n="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(r&&i&&n&&s){var o=T.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(T.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=E);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),O.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),E.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=E):this.copyGLTo2D=O}},createWebGLCanvas:function(t,e){var i=T.util.createCanvasElement();i.width=t,i.height=e;var r={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},n=i.getContext("webgl",r);n||(n=i.getContext("experimental-webgl",r)),n&&(n.clearColor(0,0,0,0),this.canvas=i,this.gl=n)},applyFilters:function(t,e,i,r,n,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,e));var h={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:r,destinationWidth:i,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,i,r,!o&&e),targetTexture:this.createTexture(a,i,r),originalTexture:o||this.createTexture(a,i,r,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach((function(t){t&&t.applyTo(h)})),function(t){var e=t.targetCanvas,i=e.width,r=e.height,n=t.destinationWidth,s=t.destinationHeight;i===n&&r===s||(e.width=n,e.height=s)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),n.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,r){var n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),r?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),n},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:O,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var r=t.getParameter(i.UNMASKED_RENDERER_WEBGL),n=t.getParameter(i.UNMASKED_VENDOR_WEBGL);r&&(e.renderer=r.toLowerCase()),n&&(e.vendor=n.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}T.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,r,n){var s=n.getContext("2d");s.drawImage(e,0,0,i,r);var o={sourceWidth:i,sourceHeight:r,imageData:s.getImageData(0,0,i,r),originalEl:e,originalImageData:s.getImageData(0,0,i,r),canvasEl:n,ctx:s,filterBackend:this};return t.forEach((function(t){t.applyTo(o)})),o.imageData.width===i&&o.imageData.height===r||(n.width=o.imageData.width,n.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),T.Image=T.Image||{},T.Image.filters=T.Image.filters||{},T.Image.filters.BaseFilter=T.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==T.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+T.webGlPrecision+" float"));var r=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var n=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(n,e),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var s=t.createProgram();if(t.attachShader(s,r),t.attachShader(s,n),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var o=this.getAttributeLocations(t,s),a=this.getUniformLocations(t,s)||{};return a.uStepW=t.getUniformLocation(s,"uStepW"),a.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var r=e.aPosition,n=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(r),t.vertexAttribPointer(r,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,r=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(r.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(r,e,i)),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,t.targetTexture,0)):(r.bindFramebuffer(r.FRAMEBUFFER,null),r.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=T.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),T.Image.filters.BaseFilter.fromObject=function(t,e){var i=new T.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.ColorMatrix=r(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,r,n,s,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=S||o<0||o>=y||(h=4*(a*y+o),l=p[f*m+d],e+=_[h]*l,i+=_[h+1]*l,r+=_[h+2]*l,w||(n+=_[h+3]*l));b[s]=e,b[s+1]=i,b[s+2]=r,b[s+3]=w?_[s+3]:n}t.imageData=C},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Grayscale=r(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,r=t.imageData.data,n=r.length,s=this.mode;for(e=0;el[0]&&n>l[1]&&s>l[2]&&r 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,r,n,s,o,a,h,l=t.imageData.data,c=l.length,u=1-this.alpha;i=(h=new e.Color(this.color).getSource())[0]*this.alpha,r=h[1]*this.alpha,n=h[2]*this.alpha;for(var d=0;d=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return a(e)/e*a(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,r=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/r;var n,s=e.width,a=e.height,h=o(s*i),l=o(a*r);"sliceHack"===this.resizeType?n=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?n=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?n=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(n=this.lanczosResize(t,s,a,h,l)),t.imageData=n},sliceByTwo:function(t,i,n,s,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=n*c,_=e.filterBackend.resources,p=0,m=0,v=i,y=0;for(_.sliceByTwo||(_.sliceByTwo=document.createElement("canvas")),((a=_.sliceByTwo).width<1.5*i||a.height=e)){M=r(1e3*s(T-C.x)),S[M]||(S[M]={});for(var P=b.y-y;P<=b.y+y;P++)P<0||P>=o||(L=r(1e3*s(P-C.y)),S[M][L]||(S[M][L]=f(n(i(M*p,2)+i(L*m,2))/1e3)),(x=S[M][L])>0&&(E+=x,I+=x*c[O=4*(P*e+T)],R+=x*c[O+1],A+=x*c[O+2],D+=x*c[O+3]))}d[O=4*(w*a+h)]=I/E,d[O+1]=R/E,d[O+2]=A/E,d[O+3]=D/E}return++h1&&L<-1||(y=2*L*L*L-3*L*L+1)>0&&(x+=y*f[3+(M=4*(D+E*e))],C+=y,f[M+3]<255&&(y=y*f[M+3]/250),b+=y*f[M],w+=y*f[M+1],T+=y*f[M+2],S+=y)}_[v]=b/S,_[v+1]=w/S,_[v+2]=T/S,_[v+3]=x/C}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Contrast=r(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,r=i.length,n=Math.floor(255*this.contrast),s=259*(n+255)/(255*(259-n));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Gamma=r(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,r=this.gamma,n=i.length,s=1/r[0],o=1/r[1],a=1/r[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,n=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=r)}return t},_renderTextLine:function(t,e,i,r,n,s){this._renderChars(t,e,i,r,n,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,r,n,s,o,a,h=t.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,_=this._textLines.length;g<_;g++)if(e=this.getHeightOfLine(g),this.textBackgroundColor||this.styleHas("textBackgroundColor",g)){r=this._textLines[g],i=this._getLineLeftOffset(g),d=0,u=0,n=this.getValueOfPropertyAt(g,0,"textBackgroundColor");for(var p=0,m=r.length;p=0:ia?u%=a:u<0&&(u+=a),this._setGraphemeOnPath(u,s,o),u+=s.kernedWidth}return{width:h,numOfSpaces:0}},_setGraphemeOnPath:function(t,i,r){var n=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,n,s.segmentsInfo);i.renderLeft=o.x-r.x,i.renderTop=o.y-r.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,r,n){var s,o=this.getCompleteStyleDeclaration(e,i),a=r?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,r,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!n){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),r=1,n=e.length;r0){var E=v+s+u;"rtl"===this.direction&&(E=this.width-E-d),l&&m&&(t.fillStyle=m,t.fillRect(E,c+b*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,m=p,r=n,o=a}else d+=f.kernedWidth;E=v+s+u,"rtl"===this.direction&&(E=this.width-E-d),t.fillStyle=p,g&&p&&t.fillRect(E,c+b*r+o,d-C,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var r=t||this,n=this.fontFamily,s=e.Text.genericFonts.indexOf(n.toLowerCase())>-1,o=void 0===n||n.indexOf("'")>-1||n.indexOf(",")>-1||n.indexOf('"')>-1||s?r.fontFamily:'"'+r.fontFamily+'"';return[e.isLikelyNode?r.fontWeight:r.fontStyle,e.isLikelyNode?r.fontStyle:r.fontWeight,i?this.CACHE_FONT_SIZE+"px":r.fontSize+"px",o].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),r=new Array(i.length),n=["\n"],s=[],o=0;o-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}T.IText=T.util.createClass(T.Text,T.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),r=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:r.left,topOffset:r.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,r,n,s=0,o=0,a=this.get2DCursorLocation(t);r=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(n.left*=-1),this.cursorOffsetCache=n,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),r=i.lineIndex,n=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(r,n,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(r,n,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(r,n,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-a/2,h+t.top+l,a,s)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,r=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,n=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(r),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),_=0,p=0;if(u===a&&(_=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=t.left+f+_,y=p-_,S=g,C=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",S=1,C=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+C,y,S),t.topOffset+=d}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),T.IText.fromObject=function(e,i){if(t(e),e.styles)for(var r in e.styles)for(var n in e.styles[r])t(e.styles[r][n]);T.Object._fromObject("IText",e,i,"text")}}(),w=T.util.object.clone,T.util.object.extend(T.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",(function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))}))},initRemovedHandler:function(){var t=this;this.on("removed",(function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],T.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))}))},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach((function(t){t.__isMousedown=!1}))},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,r){var n;return n={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){n.isAborted||t[r]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return n.isAborted}}),n},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){e._tick()}),i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&rthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===r||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var r=i.slice(0,t),n=T.util.string.graphemeSplit(r).length;if(t===e)return{selectionStart:n,selectionEnd:n};var s=i.slice(t,e);return{selectionStart:n,selectionEnd:n+T.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var r=i.slice(0,t).join("").length;return t===e?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),r=i.lineIndex,n=i.charIndex,s=this.getValueOfPropertyAt(r,n,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,_=c.clientWidth/u,p=c.clientHeight/d;return h=T.util.transformPoint(h,a),(h=T.util.transformPoint(h,this.canvas.viewportTransform)).x*=_,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,r,n=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),o=n.lineIndex,a=n.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(r[c-d]=r[u],delete r[u])}},shiftLineStyles:function(t,e){var i=w(this.styles);for(var r in this.styles){var n=parseInt(r,10);n>t&&(this.styles[n+e]=i[n],i[n-e]||delete this.styles[n])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,r){var n,s={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(n=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,s[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)r&&r[i-1]?this.styles[t+i]={0:w(r[i-1])}:n?this.styles[t+i]={0:w(n)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,r){this.styles||(this.styles={});var n=this.styles[t],s=n?w(n):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(n[a+i]=s[a],s[a-i]||delete n[a])}if(this._forceClearCache=!0,r)for(;i--;)Object.keys(r[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=w(r[i]));else if(n)for(var h=n[e?e-1:1];h&&i--;)this.styles[t][e+i]=w(h)},insertNewStyleBlock:function(t,e,i){for(var r=this.get2DCursorLocation(e,!0),n=[0],s=0,o=0;o0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,n[0],i),i=i&&i.slice(n[0]+1)),s&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+n[0],s),o=1;o0?this.insertCharStyleObject(r.lineIndex+o,0,n[o],i):i&&this.styles[r.lineIndex+o]&&i[0]&&(this.styles[r.lineIndex+o][0]=i[0]),i=i&&i.slice(n[o]+1);n[o]>0&&this.insertCharStyleObject(r.lineIndex+o,0,n[o],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),T.util.object.extend(T.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,r=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,r,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),r=0,n=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));n=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+n);for(var c=0,u=e.length;cs||o<0?0:1);return this.flipX&&(a=n-a),a>this._text.length&&(a=this._text.length),a}}),T.util.object.extend(T.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=T.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):T.document.body.appendChild(this.hiddenTextarea),T.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),T.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),T.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),T.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),T.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),T.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(T.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,r,n,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),_=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(r+=(i=this.__charBounds[t][e-1]).left+i.width),r},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),n=r.lineIndex;if(n===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(s).length+a+1+this.missingNewlineOffset(n)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),n=r.lineIndex;if(0===n||t.metaKey||33===t.keyCode)return-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n-1,o),h=this._textLines[n].slice(0,s),l=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,r,n=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=n.length;ae){r=!0;var l=s-i,c=s,u=Math.abs(l-e);o=Math.abs(c-e)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)},moveCursorUp:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)},_moveCursorUpOrDown:function(t,e){var i=this["get"+t+"CursorOffset"](e,"right"===this._selectionDirection);e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(t){var e="left"===this._selectionDirection?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t},moveCursorWithoutShift:function(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t},moveCursorLeft:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)},_move:function(t,e,i){var r;if(t.altKey)r=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;r=this["findLineBoundary"+i](this[e])}if(void 0!==typeof r&&this[e]!==r)return this[e]=r,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,r){void 0===r&&(r=i),r>i&&this.removeStyleFromTo(i,r);var n=T.util.string.graphemeSplit(t);this.insertNewStyleBlock(n,i,e),this._text=[].concat(this._text.slice(0,i),n,this._text.slice(r)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=T.util.toFixed,e=/ +/g;T.util.object.extend(T.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,r=[],n=[],s=t;this._setSVGBg(n);for(var o=0,a=this._textLines.length;o",T.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,r){var n,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];r+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,_=f.length-1;g<=_;g++)h=g===_||this.charSpacing,u+=f[g],o=this.__charBounds[e][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(n=n||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(n,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,r)),u="",n=s,i+=d,d=0)},_pushTextBgRect:function(e,i,r,n,s,o){var a=T.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,r){for(var n,s,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,r=0,n={},s=0;s0?(i=0,r++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[r])&&s>0&&(i++,r++),n[s]={line:e,offset:i},r+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return n},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var r=this._styleMap[i];r&&(i=r.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,r=0,n=!1,s=this._styleMap[t],o=this._styleMap[t+1];for(var a in s&&(t=s.line,r=s.offset),o&&(n=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=r&&(!n||hr&&!p?(a.push(h),h=[],s=f,p=!0):s+=m,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>_&&(_=f);return v&&a.push(h),_+n>this.dynamicMinWidth&&(this.dynamicMinWidth=_-m+n),a},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),r=this._wrapText(i.lines,this.width),n=new Array(r.length),s=0;s{},898:()=>{},245:()=>{}},T={};function x(t){var e=T[t];if(void 0!==e)return e.exports;var i=T[t]={exports:{}};return w[t](i,i.exports,x),i.exports}x.d=(t,e)=>{for(var i in e)x.o(e,i)&&!x.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},x.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var O={};(()=>{let t;x.d(O,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?x(653).fabric:{version:"5.2.1"}})();var E=O.R; +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft Camera Enhancer JS Edition + * @website https://www.dynamsoft.com + * @copyright Copyright 2022, Dynamsoft Corporation + * @author Dynamsoft + * @version 3.0.0 (js 20220726) + * @fileoverview Dynamsoft JavaScript Library for Camera Enhancer + * More info on DCE JS: https://www.dynamsoft.com/camera-enhancer/docs/programming/javascript/?ver=latest + */function I(t,e,i,r){return new(i||(i=Promise))((function(n,s){function o(t){try{h(r.next(t))}catch(t){s(t)}}function a(t){try{h(r.throw(t))}catch(t){s(t)}}function h(t){var e;t.done?n(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,a)}h((r=r.apply(t,e||[])).next())}))}const R="undefined"==typeof self;let A,D,M,L,P;if("undefined"!=typeof navigator&&(A=navigator,D=A.userAgent,M=A.platform,L=A.mediaDevices),!R){const t={init:function(){this.browser=this.searchString(this.dataBrowser)||"unknownBrowser",this.version=this.searchVersion(D)||this.searchVersion(A.appVersion)||0,this.OS=this.searchString(this.dataOS)||"unknownOS","Linux"==this.OS&&-1!=D.indexOf("Windows NT")&&(this.OS="HarmonyOS")},searchString:function(t){for(let e=0;e{let t=!1;if(B)try{(await L.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===P.browser&&P.version>66||"Safari"===P.browser&&P.version>13||"OPR"===P.browser&&P.version>43||"Edge"===P.browser&&P.version;const N=(()=>{if(!R&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})();class V{constructor(t,e){this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapStyle=new Map,this.mapEvents=new Map([["select",[]],["deselect",[]]]),this.isDrawingItem=!0,this._setFabricObject(t),this._mediaType=t.type,this.styleSelector="default",this.styleId=e;for(let t of V.arrStyleSelectors)this._mapStyle.set(t,null)}get mediaType(){return this._mediaType}get drawingLayerId(){return this._drawingLayerId}_setFabricObject(t){this._fabricObject=t;const e=this.mapEvents;this._fabricObject.onSelect=()=>{this.styleSelector="selected";const t=this.mapEvents.get("select");for(let e of t)e&&e.apply(this)},this._fabricObject.onDeselect=()=>{this.styleSelector="default";const t=e.get("deselect");for(let e of t)e&&e.apply(this)},t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}on(t,e,i){const r=this.mapEvents.get(t);r.includes(e)||r.push(e)}off(t,e){const i=this.mapEvents.get(t),r=i.indexOf(e);-1!==r&&i.splice(r,1)}_setEditable(t){const e=this._fabricObject;t?(e.selectable=!0,e.evented=!0,e.hasControls=!0):(e.selectable=!1,e.evented=!1,e.hasControls=!1)}_extendSet(t,e){return!1}_extendGet(t){}set(t,e){this._extendSet(t,e)||("x"===t?this._fabricObject.set("left",e):"y"===t?this._fabricObject.set("top",e):this._fabricObject.set(t,e)),["vertices","left","top","width","height","scaleX","scaleY","skewX","skewY","padding","angle","strokeWidth"].includes(t)&&this._fabricObject.setCoords()}get(t){let e=this._extendGet(t);return void 0===e&&(e="x"===t?this._fabricObject.get("left"):"y"===t?this._fabricObject.get("top"):this._fabricObject.get(t)),e}}function U(t,e,i){let r=i.points[this.pointIndex].x-i.pathOffset.x,n=i.points[this.pointIndex].y-i.pathOffset.y;return E.util.transformPoint({x:r,y:n},E.util.multiplyTransformMatrices(i.canvas.viewportTransform,i.calcTransformMatrix()))}function G(t){let e=new E.Point(t.strokeUniform?1/t.scaleX:1,t.strokeUniform?1/t.scaleY:1).multiply(t.strokeWidth);return new E.Point(t.width+e.x,t.height+e.y)}function W(t,e,i,r){let n=e.target,s=n.controls[n.__corner],o=n.toLocalPoint(new E.Point(i,r),"center","center"),a=G(n),h=n._getTransformedDimensions(0,0),l={x:o.x*a.x/h.x+n.pathOffset.x,y:o.y*a.y/h.y+n.pathOffset.y};return n.points[s.pointIndex]=l,!0}function H(t,e){return function(i,r,n,s){let o=r.target,a=E.util.transformPoint({x:o.points[t].x-o.pathOffset.x,y:o.points[t].y-o.pathOffset.y},o.calcTransformMatrix()),h=e(i,r,n,s);o._setPositionDimensions({});let l=G(o),c=(o.points[t].x-o.pathOffset.x)/l.x,u=(o.points[t].y-o.pathOffset.y)/l.y;return o.setPositionByOrigin(a,c+.5,u+.5),h}}V.arrMediaTypes=["rect","arc","polygon","image","text","line","path"],V.arrStyleSelectors=["default","selected"],"undefined"!=typeof document&&"undefined"!=typeof window&&(E.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(E.util.cancelAnimFrame(this.isRendering),this.isRendering=0),this.forEachObject((function(t){t.dispose&&t.dispose()})),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose&&this.backgroundImage.dispose(),this.backgroundImage=null,this.overlayImage&&this.overlayImage.dispose&&this.overlayImage.dispose(),this.overlayImage=null,this._iTextInstances=null,this.contextContainer=null,this.lowerCanvasEl.classList.remove("lower-canvas"),delete this._originalCanvasStyle,this.lowerCanvasEl.setAttribute("width",this.width),this.lowerCanvasEl.setAttribute("height",this.height),E.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},E.Object.prototype.transparentCorners=!1,E.Object.prototype.cornerSize=20,E.Object.prototype.touchCornerSize=100,E.Object.prototype.cornerColor="rgb(254,142,20)",E.Object.prototype.cornerStyle="circle",E.Object.prototype.strokeUniform=!0,E.Object.prototype.hasBorders=!1,E.ActiveSelection.prototype.onDeselect=function(){return this.getObjects().forEach((t=>{setTimeout(t.onDeselect,0)})),this.destroy(),!1},E.Canvas.prototype.containerClass="",E.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i,r=this.upperCanvasEl,n=E.util.getPointer(t,r),s=r.getBoundingClientRect(),o=s.width||0,a=s.height||0;o&&a||("top"in s&&"bottom"in s&&(a=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(o=Math.abs(s.right-s.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,e||(n=this.restorePointerVpt(n));var h=this.getRetinaScaling();if(1!==h&&(n.x/=h,n.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(r).objectFit,c=r.width,u=r.height,d=o,f=a;i={width:c/d,height:u/f};var g,_,p=c/u,m=d/f;return"contain"===l?p>m?(g=d,_=d/p,{x:n.x*i.width,y:(n.y-(f-_)/2)*i.width}):(g=f*p,_=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===l?p>m?{x:(c-i.height*d)/2+n.x*i.height,y:n.y*i.height}:{x:n.x*i.width,y:(u-i.width*f)/2+n.y*i.width}:{x:n.x*i.width,y:n.y*i.height}}return i={width:1,height:1},{x:n.x*i.width,y:n.y*i.height}});class Y{constructor(t,e,i,r){let n,s;switch(this.mapMediaType_Style=new Map,this.mode="viewer",this.onSelectionChange=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas")?this.fabricCanvas=t.getFabricCanvas():(this.fabricCanvas=new E.Canvas(t,r),this.fabricCanvas.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),this.fabricCanvas.lowerCanvasEl.className="",this.fabricCanvas.upperCanvasEl.className="",this.fabricCanvas.on("selection:created",(function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{t.onSelectionChange&&t.onSelectionChange(i,[])}),0)}})),this.fabricCanvas.on("before:selection:cleared",(function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{const e=[];for(let r of i)t.hasDrawingItem(r)&&e.push(r);e.length>0&&t.onSelectionChange&&t.onSelectionChange([],e)}),0)}})),this.fabricCanvas.on("selection:updated",(function(t){const e=t.selected,i=t.deselected,r=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of r){const r=[],n=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&r.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&n.push(i)}setTimeout((()=>{t.onSelectionChange&&t.onSelectionChange(r,n)}),0)}})),this.fabricCanvas.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas),this.id=e,this._mapDrawingStyles=i,e){case 1:n=i.get(1),s=i.get(5);break;case 2:n=i.get(2),s=i.get(6);break;case 3:n=i.get(3),s=i.get(7);break;default:n=i.get(4),s=i.get(8)}for(let t of V.arrMediaTypes)this.mapMediaType_Style.set(t,{default:n,selected:s})}getId(){return this.id}_getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=this._mapDrawingStyles.get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyleId(t){return t.styleId?t.styleId:this.mapMediaType_Style.get(t._mediaType)[t.styleSelector].styleId}_getItemCurrentStyle(t){if(t.styleId)return this._getDrawingStyle(t.styleId);return t._mapStyle.get(t.styleSelector)||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,r){let n;switch(t){case"rect":n=this.fabricCanvas.getObjects("rect");break;case"arc":n=this.fabricCanvas.getObjects("circle");break;case"polygon":n=this.fabricCanvas.getObjects("polygon");break;case"image":n=this.fabricCanvas.getObjects("image");break;case"text":n=this.fabricCanvas.getObjects("text");break;case"line":n=this.fabricCanvas.getObjects("line");break;case"path":n=this.fabricCanvas.getObjects("path")}for(let t of n){if(!this._arrFabricObject.includes(t))continue;const r=t.getDrawingItem();r.styleSelector===e&&this._changeItemStyle(r,i,!0)}r||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const r=t._getFabricObject();"number"==typeof t.styleId&&(e=this._getDrawingStyle(t.styleId)),r.strokeWidth=e.lineWidth,"fill"===e.paintMode?(r.fill=e.fillStyle,r.stroke=e.fillStyle):"stroke"===e.paintMode?(r.fill="transparent",r.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(r.fill=e.fillStyle,r.stroke=e.strokeStyle),r.fontFamily&&(r.fontFamily=e.fontFamily),r.fontSize&&(r.fontSize=e.fontSize),r.group||(r.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const r=t.getChildItems();if("add"===i){if(r.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=this._getDrawingStyle(e.styleId);else{i=this.mapMediaType_Style.get(e._mediaType)[t.styleSelector];const r=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected,!0)},n=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default,!0)};e.on("select",r),e.on("deselect",n),e._funcChangeStyleToSelected=r,e._funcChangeStyleToDefault=n}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!r.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e.off("select",e._funcChangeStyleToSelected),e.off("deselect",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){let i=t._getFabricObject();const r=this.fabricCanvas.getObjects();let n,s;if(r.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){n=t.getChildItems();for(let t of n)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(n){for(let t of n){if(t.styleId)s=this._getDrawingStyle(t.styleId);else{const e=this.mapMediaType_Style.get(t._mediaType);for(let i of V.arrStyleSelectors)t._mapStyle.set(i,e[i]);s=e.default;const i=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).selected,!0)},r=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).default,!0)};t.on("select",i),t.on("deselect",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{if(t.styleId)s=this._getDrawingStyle(t.styleId);else{const e=this.mapMediaType_Style.get(t._mediaType);for(let i of V.arrStyleSelectors)t._mapStyle.set(i,e[i]);s=e.default;const i=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).selected)},r=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).default)};t.on("select",i),t.on("deselect",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=r.length;if(o)a=r.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;e{for(let e of this._arrDrawingLayer)if(e.getId()===t)return!0;return!1};if(void 0===e){for(let t=100;;t++)if(!i(t)){e=t;break}}else if(i(e))throw new Error("Existed drawing layer id.");const r=new Y(t,e,this._mapDrawingStyles,{enableRetinaScaling:!1});return r._manager=this,this._arrDrawingLayer.push(r),this._switchPointerEvent(),r}deleteDrwaingLayer(t){const e=this.getDrawingLayer(t);if(!e)return;const i=this._arrDrawingLayer;e.dispose(),i.splice(i.indexOf(e),1),this._switchPointerEvent()}clearDrawingLayers(){for(let t of this._arrDrawingLayer)t.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(t){for(let e of this._arrDrawingLayer)if(e.getId()===t)return e;return null}getDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._arrDrawingLayer[0].fabricCanvas.getActiveObjects(),e=[];for(let i of t)e.push(i.getDrawingItem());return e}setDimensions(t,e){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(t,e)}setObjectFit(t){for(let e of this._arrDrawingLayer)e&&e._setObjectFit(t)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(t){this._arrDrawingLayer.length&&(this._arrDrawingLayer[0].fabricCanvas.wrapperEl.style.display=t?"block":"none")}_switchPointerEvent(){if(!this._arrDrawingLayer.length)return;let t=!1;for(let e of this._arrDrawingLayer)"editor"===e.getMode()&&(t=!0);this._arrDrawingLayer[0].fabricCanvas.wrapperEl.style.pointerEvents=t?"":"none"}}class z{constructor(t){this._controlTarget=null,this._arrUsers=[],this._mapAction_UserArgs=new Map,this._mapProperty_UserValue=new Map,this._mapAction_Callbacks=new Map,this._controlTarget=t}setControlTarget(t){this._controlTarget=t}getControlTarget(){return this._controlTarget}register(t){this._arrUsers.includes(t)||this._arrUsers.push(t)}logout(t){const e=this._arrUsers.indexOf(t);-1!==e&&(this.clearUserDisiredAction({user:t}),this.clearUserDisiredValue({user:t}),this._arrUsers.splice(e,1))}getRegisteredUsers(){return this._arrUsers}ifUserExisted(t){return this._arrUsers.includes(t)}setDisiredValue(t,e,i,r){if(!this._arrUsers.includes(t))throw new Error("Unregistered user.");r&&(this._controlTarget[e]=i),this._mapProperty_UserValue.get(e)?this._mapProperty_UserValue.get(e).set(t,i):this._mapProperty_UserValue.set(e,new Map([[t,i]]))}clearUserDisiredValue(t){if(t&&(t.user||t.property)){if(t.property&&t.user){const e=this._mapProperty_UserValue.get(t.property);if(!e)return;e.delete(t.user)}else if(t.property)this._mapProperty_UserValue.delete(t.property);else if(t.user)for(let e of this._mapProperty_UserValue.values())e.delete(t.user)}else this._mapProperty_UserValue=new Map}getValue(t){if(!this._controlTarget)throw new Error("Control target is not set.");return this._controlTarget[t]}getPropertyDisiredValue(t){if(this._mapProperty_UserValue.get(t)){const e=[],i=this._mapProperty_UserValue.get(t);for(let t of i.values())e.push(t);return e}return null}setDisiredAction(t,e,i,r){if(!this._arrUsers.includes(t))throw new Error("Unregistered user.");return i||(i=[]),r?this._controlTarget[e](...i):(this._mapAction_UserArgs.get(e)?this._mapAction_UserArgs.get(e).set(t,i):this._mapAction_UserArgs.set(e,new Map([[t,i]])),this._render(e))}clearUserDisiredAction(t){if(t&&(t.user||t.actionName)){if(t.actionName&&t.user){const e=this._mapAction_UserArgs.get(t.actionName);if(!e)return;e.delete(t.user)}else if(t.actionName)this._mapAction_UserArgs.delete(t.actionName);else if(t.user)for(let e of this._mapAction_UserArgs.values())e.delete(t.user);this.render()}else this._mapAction_UserArgs=new Map}addCallback(t,e){const i=this._mapAction_Callbacks.get(t);i?i.push(e):this._mapAction_Callbacks.set(t,[e])}removeCallback(t,e){const i=this._mapAction_Callbacks.get(t);if(!i)return;const r=i.indexOf(e);-1!==r&&i.splice(r,1)}clearCallback(t){t?this._mapAction_Callbacks.delete(t):this._mapAction_Callbacks.clear()}_fireCallback(t){const e=this._mapAction_Callbacks.get(t);if(e)for(let t of e){if(!t)return;setTimeout(t.bind(this._controlTarget),0)}}_render(t){const e=this._mapAction_UserArgs.get(t);if(!e)throw new Error("Unrecorded action.");if(e.size===this._arrUsers.length){let i=[];for(let t of e.values())t.length>0&&(i=t);if(this._controlTarget[t]){const e=this._controlTarget[t](...i);return this._mapAction_UserArgs.delete(t),this._fireCallback(t),e}}}render(t){if(t)return this._render(t);for(let t of this._mapAction_UserArgs.keys())this._render(t)}}class K{constructor(){this._maxCvsSideLength=void 0,this._defaultMaxCvsSideLength=null,this._predefinedResolutions=[{width:160,height:120},{width:320,height:240},{width:480,height:360},{width:640,height:480},{width:800,height:600},{width:960,height:720},{width:1280,height:720},{width:1920,height:1080},{width:2560,height:1440},{width:3840,height:2160}],this._mapCameraResolutions=new Map,this._bWebGLSupported=!0,this.extraBindings=[],this._singleFrameMode=!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia),this._cvsSingleFrameMode=null,this._cvsOriginalImage=null,this._imgWidth=0,this._imgHeight=0,this._singleFrameModeIpt=null,this._clickIptSingleFrameMode=()=>{if(this.singleFrameMode){if(!this._singleFrameModeIpt){const t=document.createElement("input");this._singleFrameModeIpt=t,t.setAttribute("type","file"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),t.setAttribute("capture",""),t.addEventListener("change",(()=>I(this,void 0,void 0,(function*(){const e=t.files[0];t.value="";const i=yield(t=>I(this,void 0,void 0,(function*(){let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=yield createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=yield(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.dbrObjUrl=i,n.src=i,n.onload=()=>{t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})))(e),r=i instanceof HTMLImageElement?i.naturalWidth:i.width,n=i instanceof HTMLImageElement?i.naturalHeight:i.height;this._imgWidth=r,this._imgHeight=n;const s=t=>{const e=Date.now();if(0===r||0===n)return null;const i=this._scanRegion,s=this.getFrameSize(r,n,i,this.maxCvsSideLength);if(!s)return null;let o,a;o=r!==s.sWidth||n!==s.sHeight,a=s.sWidth!==s.dWidth||s.sHeight!==s.dHeight;const h=(()=>!(!this._bWebGLSupported||a))(),l={data:null,region:i?JSON.parse(JSON.stringify(i)):null,sx:s.sx,sy:s.sy,width:s.dWidth,height:s.dHeight,colorMode:null,timeSpent:null,timeStamp:null,isCropped:o,toCanvas:this._toCanvas,_sWidth:s.sWidth,_sHeight:s.sHeight,_bUseWebGL:null};let c;try{c=this._getImageData(t,r,n,s,null,{targetColorMode:this.frameColorMode,bUseWebGL:h})}catch(e){if("WebGLError"!==e.name)throw e;c=this._getImageData(t,r,n,s,null,{targetColorMode:this.frameColorMode,bUseWebGL:!1})}if(!c)return null;const u=Date.now();return K._onLog&&K._onLog("DCE: _getVideoFrame(region?) END: "+u),l.data=c.data,l.colorMode=c.colorMode,l._bUseWebGL=c._bUseWebGL,l.timeSpent=u-e,l.timeStamp=u,l};(t=>{let e=this._cvsSingleFrameMode;if(!e){if(e=document.createElement("canvas"),e.style.pointerEvents="none",!this._video)throw new Error("'video' is null.");this._video.after(e),e.style.position="absolute",e.style.width="100%",e.style.height="100%",e.style.left="0",e.style.top="0",e.style.objectFit="contain",this._cvsSingleFrameMode=e}e.width==r&&e.height==n||(e.width=r,e.height=n);const i=e.getContext("2d");i.clearRect(0,0,e.width,e.height),i.drawImage(t,0,0)})(i),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let t of this._arrScanRegionOverlays)t&&this._updateScanRegionOverlay(t);let o;this._updateDrawingLayersSize();try{o=s(i)}catch(t){throw t}const a=this.mapCameraEvents.get("singleFrameAcquired");for(let t of a)if(t)try{const e={data:new Uint8Array(o.data),region:JSON.parse(JSON.stringify(o.region)),sx:o.sx,sy:o.sy,width:o.width,height:o.height,colorMode:o.colorMode,timeSpent:o.timeSpent,timeStamp:o.timeStamp,isCropped:o.isCropped,toCanvas:o.toCanvas,_sWidth:o._sWidth,_sHeight:o._sHeight,_bUseWebGL:o._bUseWebGL};yield t.apply(this,[e])}catch(t){console.error(t)}})))),t.style.position="fixed",t.style.left="-1px",t.style.top="-1px",t.style.width="1px",t.style.height="1px",t.style.backgroundColor="transparent",t.style.color="transparent",document.body.appendChild(t)}this._singleFrameModeIpt.click()}},this.styleEls=[],this._frameColorMode=void 0,this._defaultFrameColorMode="RGBA",this.currentFSColorMode="rgba",this.ifReuseArrayBufferView=!1,this.maxVideoCvsLength=3,this._reusedCvs=null,this._reusedWebGLCvs=null,this._reusedWebGLCtx=null,this._reusedDataContainer=null,this._webGLTexture=null,this._webGLProgramInfo=null,this._webGLBuffers=null,this._recordedStates={},this._toCanvas=function(){const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,"grey"===this.colorMode){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;tI(this,void 0,void 0,(function*(){yield this.selectCamera(this._selCam.value),this._bOpen||this.stop()})),this._onResolutionSelChange=()=>I(this,void 0,void 0,(function*(){let t,e;if(this._selRsl&&-1!=this._selRsl.selectedIndex){let i=this._selRsl.options[this._selRsl.selectedIndex];t=i.getAttribute("data-width"),e=i.getAttribute("data-height")}yield this.setResolution(t,e),this._bOpen||this.stop()})),this._onCloseBtnClick=()=>{this.close(!0)},this._bOpen=!1,this.isCameraEnhancer=!0,this.isDisposed=!1,this.videoSrc=null,this.videoSettings={video:{width:{ideal:1280},height:{ideal:720},facingMode:{ideal:"environment"}}},this.iPlayRound=0,this.promisePlay=null,this._ifSaveLastUsedCamera=!1,this.ifSkipCameraInspection=!1,this._allCameras=[],this._currentCamera=null,this._videoTrack=null,this._lastDeviceId=void 0,this._vc_bPlayingVideoBeforeHide=!1,this._ev_documentHideEvent=()=>{"visible"===document.visibilityState?this._vc_bPlayingVideoBeforeHide&&("Firefox"==P.browser?this.play():this._video.play(),this._vc_bPlayingVideoBeforeHide=!1):this._video&&!this._video.paused&&(this._vc_bPlayingVideoBeforeHide=!0,this._video.pause())},this._divVideoContainer=null,this._video=null,this.videoFit="contain",this._cvsScanRegion=null,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=2,this._bShowScanRegionMask=!0,this._bShowScanRegionLaser=void 0,this._defaultBShowScanRegionLaser=!1,this._scanRegion=null,this._arrScanRegionOverlays=[],this._layerBaseCvs=null,this._cvsViewDecorator=null,this._decoratorType=[],this._decoratorArea=null,this._viewDecoratorInfo={rectangle:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},focus:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},crossline:{lineWidth:2,strokeStyle:"rgb(254,142,20)"},crosshair:{lineWidth:4,strokeStyle:"rgb(254,142,20)"}},this._croppingRegions=void 0,this._defaultCroppingRegions=[null],this.bIncreaseRegionIndexAuto=!0,this._croppingRegionIndex=0,this._loopInterval=void 0,this._defaultLoopInterval=0,this._maxNumberOfFramesInBuffer=void 0,this._defaultMaxNumberOfFramesInBuffer=1,this._frameQueue=[],this._bFetchingLoopStarted=!1,this._refreshInterval=void 0,this._defaultRefreshInterval=-1,this._updateLayersTimeout=0,this._updateLayers=()=>{this._resizeTimeoutId&&clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=setTimeout((()=>{if(!this.isDisposed){this._updateScanAreaDiv(),this._updateViewDecorator();for(let t of this._arrScanRegionOverlays)t&&this._updateScanRegionOverlay(t)}}),this._updateLayersTimeout)},this.mapCameraEvents=new Map([["cameraOpen",[]],["cameraClose",[]],["cameraChange",[]],["resolutionChange",[]],["played",[]],["singleFrameAcquired",[]],["frameAddedToBuffer",[]]]),this._controler=null}static getVersion(){return this._version}static detectEnvironment(){return I(this,void 0,void 0,(function*(){return yield(async()=>({wasm:F,worker:k,getUserMedia:B,camera:await j(),browser:P.browser,version:P.version,OS:P.OS}))()}))}static set engineResourcePath(t){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");K._engineResourcePath=(t=>{if(null==t&&(t="./"),!R){let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(t)}static get engineResourcePath(){return this._engineResourcePath}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static isDCEFrame(t){return!(!t||"object"!=typeof t||Array.isArray(t))&&"data"in t&&"region"in t&&"sx"in t&&"sy"in t&&"width"in t&&"height"in t&&"colorMode"in t&&"timeSpent"in t&&"timeStamp"in t&&"isCropped"in t&&"toCanvas"in t&&"_sWidth"in t&&"_sHeight"in t&&"_bUseWebGL"in t}set maxCvsSideLength(t){if(t<=0)throw new Error("Invalid value.");this._maxCvsSideLength=t}get maxCvsSideLength(){if(void 0!==this._maxCvsSideLength)return this._maxCvsSideLength;if(this._controler){const t=this._controler.getPropertyDisiredValue("maxCvsSideLength");if(t&&1===t.length)return t[0]}return this._defaultMaxCvsSideLength}static set defaultUIElementURL(t){K._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=K._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",K.engineResourcePath)}getUIElement(){return this.UIElement}setUIElement(t){return I(this,void 0,void 0,(function*(){if(this._bOpen)throw new Error("It is not allowed to change the UIElement when the camera is open.");if("string"==typeof t||t instanceof String){if(!t.trim().startsWith("<")){let e=yield fetch(t);if(!e.ok)throw Error("setUIElement(elementOrUrl): Network Error: "+e.statusText);t=yield e.text()}if(!t.trim().startsWith("<"))throw Error("setUIElement(elementOrUrl): Can't get valid HTMLElement.");let e=document.createElement("div");e.innerHTML=t;for(let t=0;t100||t.regionTop>100||t.regionRight>100||t.regionBottom>100)))}set scanRegion(t){if(!this._checkValidRegion(t))throw new Error("Invalid region.");this._scanRegion=JSON.parse(JSON.stringify(t)),this._updateScanRegionCanvas(),this._updateScanAreaDiv();for(let t of this._arrScanRegionOverlays)t&&this._updateScanRegionOverlay(t)}setScanRegion(t){this.scanRegion=t}getScanRegion(){return JSON.parse(JSON.stringify(this._scanRegion))}_calculateCvsSize(){if(!this._bOpen)return null;let t,e,i;if(this.singleFrameMode)t=this._imgWidth,e=this._imgHeight,i="contain";else{if(!this._video)return null;t=this._video.videoWidth,e=this._video.videoHeight,i=this.getVideoFit()}return{width:t,height:e,objectFit:i}}addScanRegionOverlayCanvas(){this._assertOpen();const t=document.createElement("canvas");if(this._updateScanRegionOverlay(t),!this._scanRegionOverlayContainer){const t=document.createElement("div");if(this._scanRegionOverlayContainer=t,t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.overflow="hidden",t.style.pointerEvents="none",this._layerBaseCvs)this._layerBaseCvs.parentElement.after(t);else if(this._cvsScanRegion)this._cvsScanRegion.before(t);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(t);else{if(!this._video)throw new Error("'video' is null.");this._video.after(t)}this._recordedStates.overlayShow=!0}return this._scanRegionOverlayContainer.append(t),this._arrScanRegionOverlays.push(t),t}removeScanRegionOverlayCanvas(t){const e=this._arrScanRegionOverlays.indexOf(t);-1!==e&&(t.remove(),this._arrScanRegionOverlays.splice(e,1))}_updateScanRegionOverlay(t){if(!t)return;const e=this._calculateCvsSize();if(!e)return;const{width:i,height:r,objectFit:n}=e;if(i<=0||r<=0)return t.width=0,void(t.height=0);const s=this._getRegionInPixels(i,r,this._scanRegion),o=this.getFrameSize(i,r,this._scanRegion,this.maxCvsSideLength),a=o.dWidth,h=o.dHeight;t.width==a&&t.height==h||(t.width=a,t.height=h);const l=window.getComputedStyle(this._video),c=parseFloat(l.width),u=parseFloat(l.height),d=c/u,f=i/r;let g,_,p,m,v=1;"contain"===n?(dd?(v=u/r,g=s.regionLeft*v-(i*v-c)/2,_=s.regionTop*v):(v=c/i,g=s.regionLeft*v,_=s.regionTop*v-(r*v-u)/2),p=(s.regionRight-s.regionLeft)*v,m=(s.regionBottom-s.regionTop)*v):(g=0,_=0,p=0,m=0),t.style.position="absolute",t.style.left=g+"px",t.style.top=_+"px",t.style.width=p+"px",t.style.height=m+"px"}showScanRegionOverlays(){this._scanRegionOverlayContainer&&("none"==this._scanRegionOverlayContainer.style.display&&(this._scanRegionOverlayContainer.style.display=""),this._recordedStates.overlayShow=!0)}hideScanRegionOverlays(){this._scanRegionOverlayContainer&&(this._scanRegionOverlayContainer.style.display="none",this._recordedStates.overlayShow=!1)}setViewDecorator(t,e){if(!t)return void(this._cvsViewDecorator&&(this._cvsViewDecorator.remove(),this._cvsViewDecorator=null));this._assertOpen();let i=[];if("string"==typeof t?i.push(t):Array.isArray(t)&&(i=JSON.parse(JSON.stringify(t))),!this._cvsViewDecorator){if(this._cvsViewDecorator=document.createElement("canvas"),this._cvsViewDecorator.style.pointerEvents="none",this._cvsScanRegion)this._cvsScanRegion.after(this._cvsViewDecorator);else if(this._scanRegionOverlayContainer)this._scanRegionOverlayContainer.after(this._cvsViewDecorator);else if(this._layerBaseCvs)this._layerBaseCvs.parentElement.after(this._cvsViewDecorator);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(this._cvsViewDecorator);else{if(!this._video)throw new Error("'video' is null.");this._video.after(this._cvsViewDecorator)}this._recordedStates.decoratorShow=!0}this._decoratorArea=JSON.parse(JSON.stringify(e)),this._decoratorType.length=0;const r=["rectangle","focus"],n=["crossline","crosshair"];let s=!1,o=!1;for(let t of i)t=t.toLowerCase(),r.includes(t)&&!s&&(s=!0,this._decoratorType.push(t)),n.includes(t)&&!o&&(o=!0,!this._decoratorType.includes(t)&&this._decoratorType.push(t));this._updateViewDecorator()}getViewDecorator(){return{type:JSON.parse(JSON.stringify(this._decoratorType)),area:JSON.parse(JSON.stringify(this._decoratorArea)),canvas:this._cvsViewDecorator}}showViewDecorator(){this._cvsViewDecorator&&("none"==this._cvsViewDecorator.style.display&&(this._cvsViewDecorator.style.display=""),this._recordedStates.decoratorShow=!0)}hideViewDecorator(){this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none",this._recordedStates.decoratorShow=!1)}setViewDecoratorLineWidth(t,e){if("string"!=typeof t)throw new Error("The 'type' should be a string.");if(t=t.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(t))throw new Error(`The type of '${t}' doesn't exist.`);if(!this._viewDecoratorInfo[t].hasOwnProperty("lineWidth"))throw new Error(`It is not allowed to change the property 'lineWidth' when the decorator type is '${t}'.`);this._viewDecoratorInfo[t].lineWidth=e,this._updateViewDecorator()}setViewDecoratorStrokeStyle(t,e){if("string"!=typeof t)throw new Error("The 'type' should be a string.");if(t=t.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(t))throw new Error(`The type of '${t}' doesn't exist.`);if(!this._viewDecoratorInfo[t].hasOwnProperty("strokeStyle"))throw new Error(`It is not allowed to change the property 'strokeStyle' when the decorator type is '${t}'.`);this._viewDecoratorInfo[t].strokeStyle=e,this._updateViewDecorator()}setViewDecoratorFillStyle(t,e){if("string"!=typeof t)throw new Error("The 'type' should be a string.");if(t=t.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(t))throw new Error(`The type of '${t}' doesn't exist.`);if(!this._viewDecoratorInfo[t].hasOwnProperty("fillStyle"))throw new Error(`It is not allowed to change the property 'fillStyle' when the decorator type is '${t}'.`);this._viewDecoratorInfo[t].fillStyle=e,this._updateViewDecorator()}setViewDecoratorMaskFillStyle(t,e){if("string"!=typeof t)throw new Error("The 'type' should be a string.");if(t=t.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(t))throw new Error(`The type of '${t}' doesn't exist.`);if(!this._viewDecoratorInfo[t].hasOwnProperty("maskFillStyle"))throw new Error(`It is not allowed to change the property 'maskFillStyle' when the decorator type is '${t}'.`);this._viewDecoratorInfo[t].maskFillStyle=e,this._updateViewDecorator()}_updateViewDecorator(){if(!this._bOpen)return;if(!this._cvsViewDecorator||!this._decoratorArea)return;let t;if(this.singleFrameMode)t="contain";else{if(!this._video)return;t=this.getVideoFit()}const e=this._cvsViewDecorator;e.style.position="absolute",e.style.width="100%",e.style.height="100%",e.style.left="0",e.style.top="0",e.style.objectFit=t;const i=this.getVisibleRegion(!0),r=i.regionRight-i.regionLeft,n=i.regionBottom-i.regionTop;if(e.width==r&&e.height==n||(e.width=r,e.height=n),r<=0||n<=0)return;const s=e.getContext("2d");s.clearRect(0,0,e.width,e.height);const o=this._decoratorArea.x/100*r,a=this._decoratorArea.y/100*n,h=this._decoratorArea.width/100*r,l=this._decoratorArea.height/100*n;for(let t of this._decoratorType){if("rectangle"===t){s.fillStyle=this._viewDecoratorInfo.rectangle.maskFillStyle,s.fillRect(0,0,e.width,e.height),s.clearRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.fillStyle=this._viewDecoratorInfo.rectangle.fillStyle,s.fillRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.lineWidth=this._viewDecoratorInfo.rectangle.lineWidth,s.strokeStyle=this._viewDecoratorInfo.rectangle.strokeStyle;const t=s.lineWidth/2;s.strokeRect(Math.round(o-t),Math.round(a-t),Math.round(h+s.lineWidth),Math.round(l+s.lineWidth))}if("focus"===t){s.fillStyle=this._viewDecoratorInfo.focus.maskFillStyle,s.fillRect(0,0,e.width,e.height),s.clearRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.fillStyle=this._viewDecoratorInfo.focus.fillStyle,s.fillRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.lineWidth=this._viewDecoratorInfo.focus.lineWidth,s.strokeStyle=this._viewDecoratorInfo.focus.strokeStyle;const t=s.lineWidth/2,i=[0,.25,.75,1],r=[0,.25,.75,1];s.beginPath();for(let t=0;t{const t=parseFloat(window.getComputedStyle(this._video).width),e=parseFloat(window.getComputedStyle(this._video).height);let s,o={regionBottom:r,regionRight:i,regionLeft:0,regionTop:0,regionMeasuredByPercentage:!1};return"cover"===n?t/ethis.maxNumberOfFramesInBuffer;)this._frameQueue.shift()}get maxNumberOfFramesInBuffer(){if(void 0!==this._maxNumberOfFramesInBuffer)return this._maxNumberOfFramesInBuffer;if(this._controler){const t=this._controler.getPropertyDisiredValue("maxNumberOfFramesInBuffer");if(t&&1===t.length)return t[0]}return this._defaultMaxNumberOfFramesInBuffer}get numberOfFramesInBuffer(){return this._frameQueue.length}set refreshInterval(t){this._refreshInterval=t}get refreshInterval(){if(void 0!==this._refreshInterval)return this._refreshInterval;if(this._controler){const t=this._controler.getPropertyDisiredValue("refreshInterval");if(t&&1===t.length)return t[0]}return this._defaultRefreshInterval}static createInstance(t){return I(this,void 0,void 0,(function*(){let e=new K;("string"==typeof t||t instanceof String)&&(t=JSON.parse(t));for(let i in t)e[i]=t[i];return this._hasEngineResourceLoaded=!0,K.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{K.onWarning&&K.onWarning({id:1,message:"Not using HTTP protocol, the SDK may not work correctly."})}),0):location&&"https:"!==location.protocol&&setTimeout((()=>{K.onWarning&&K.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)),e._drawingLayersManager=new X,e}))}play(t,e,i,r){return I(this,void 0,void 0,(function*(){if(this._video&&this.videoSrc){yield new Promise(((t,e)=>{this._video.onloadedmetadata=()=>I(this,void 0,void 0,(function*(){this._video&&(this._video.onloadedmetadata=null,yield this._video.play(),t())})),"string"==typeof this.videoSrc||this.videoSrc instanceof String?this._video.src=this.videoSrc:this._video.srcObject=this.videoSrc,setTimeout((()=>e(new Error("Failed to play video. Timeout."))),4e3)}));const t={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};this.playCallbackInfo=JSON.parse(JSON.stringify(t));const e=this.mapCameraEvents.get("played");for(let i of e){if(!i)continue;const e=JSON.parse(JSON.stringify(t));setTimeout((()=>i.apply(this,[e])),0)}return this._recordedStates.videoPlaying=!0,t}if(this.singleFrameMode)return r&&r.notTriggerSingleFrameClick||this._clickIptSingleFrameMode(),this.playCallbackInfo={width:0,height:0,deviceId:null},JSON.parse(JSON.stringify(this.playCallbackInfo));if(!this._video)return this.playCallbackInfo=null,null;const n=++this.iPlayRound;let s=null,o=0,a=0;if(this._currentCamera&&(s=this._currentCamera.deviceId),this._video&&(o=this._video.videoWidth,a=this._video.videoHeight),this.promisePlay&&(yield this.promisePlay,nI(this,void 0,void 0,(function*(){var r;try{this._video&&this._video.srcObject&&this.stop(),K._onLog&&K._onLog("DCE: ======before video========");const n=()=>{if(!this._video)throw d&&d.getTracks().forEach((t=>{t.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null.")},h=this.getVideoSettings();let l;"boolean"==typeof h.video&&(h.video={});const c=["rear","back","rück","arrière","trasera","trás","traseira","posteriore","后面","後面","背面","后置","後置","背置","задней","الخلفية","후","arka","achterzijde","หลัง","baksidan","bagside","sau","bak","tylny","takakamera","belakang","אחורית","πίσω","spate","hátsó","zadní","darrere","zadná","задня","stražnja","belakang","बैक"],u=()=>{for(let t of this._allCameras){let e=t.label.toLowerCase();if(e&&c.some((t=>-1!=e.indexOf(t)))&&/\b0(\b)?/.test(e)){delete h.video.facingMode,h.video.deviceId={ideal:t.deviceId};break}}h.video.deviceId||-1==["Android","HarmonyOS"].indexOf(P.OS)||(delete h.video.facingMode,h.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})};if(t)delete h.video.facingMode,h.video.deviceId={exact:t};else if(h.video.deviceId);else if(this._lastDeviceId)delete h.video.facingMode,h.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&K.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete h.video.facingMode,h.video.deviceId={exact:window.localStorage.getItem("dce_last_camera_id")};const w=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),T=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));w&&T&&(h.video.width=w,h.video.height=T)}else if(this.ifSkipCameraInspection);else if(h.video.facingMode){if("iPhone"!==P.OS&&"Mac"!==P.OS&&(yield this.getAllCameras(!0)),!this._video)return null;let x=h.video.facingMode;x instanceof Array&&x.length&&(x=x[0]),x=x.exact||x.ideal||x,"environment"===x&&(l=!!h.video.facingMode,u())}let d;e&&(h.video.width={ideal:e}),i&&(h.video.height={ideal:i}),K._onLog&&K._onLog("DCE: ======try getUserMedia========");let f,g=[0,500],_=null,p=null;function m(t){return I(this,void 0,void 0,(function*(){for(let e of g){n(),e&&(yield new Promise((t=>setTimeout(t,e)))),n();{const e=t.video.deviceId;p=e?e.exact||e.ideal||e:null}try{K._onLog&&K._onLog("DCE: ask "+JSON.stringify(t)),d=yield navigator.mediaDevices.getUserMedia(t),n();break}catch(t){_=t,K._onLog&&K._onLog("DCE: "+t.message||t)}}}))}if(yield m(h),d||(K._onLog&&K._onLog("DCE: ======try getUserMedia again========"),f=JSON.parse(JSON.stringify(h)),"object"==typeof f.video&&("iPhone"==P.OS?(e>=1280||i>=1280?f.video.width=1280:e>=640||i>=640?f.video.width=640:(e<640||i<640)&&(f.video.width=320),delete f.video.height):l&&!h.video.deviceId?(delete f.video.facingMode,this._allCameras.length&&(f.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):f.video=!0),K._onLog&&K._onLog("DCE: "+f),yield m(f)),d||(g=[1e3,2e3],yield m(h)),d||(yield m(f)),!d)throw _;const v=()=>{const t=d.getVideoTracks();let e,i;if(t.length&&(e=this._videoTrack=t[0]),this._video&&e){const t=e.getSettings();if(t)for(let r of this._allCameras)if(t.deviceId===r.deviceId){r._checked=!0,r.label=e.label,i=r;break}if(!i&&p)for(let t of this._allCameras)if(p==t.deviceId){e.label&&(t._checked=!0,t.label=e.label),i=t;break}}this._currentCamera=i};if(yield this.getAllCameras(!0),n(),l){v(),u();let O=h.video.deviceId;O&&(O=O.exact||O.ideal||O);let E=null===(r=this._currentCamera)||void 0===r?void 0:r.deviceId;!O||E&&O==E||(d.getTracks().forEach((t=>{t.stop()})),g=[0,500,1e3,2e3],yield m(h))}n();const y=()=>I(this,void 0,void 0,(function*(){K._onLog&&K._onLog("======play video========"),yield new Promise(((t,e)=>{n(),this._video.onloadedmetadata=()=>I(this,void 0,void 0,(function*(){n(),this._video.onloadedmetadata=null,yield this._video.play(),t()})),this._video.srcObject=d,setTimeout((()=>e(new Error("Failed to play video. Timeout."))),4e3)}))}));yield y(),n(),K._onLog&&K._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const S=this._video.videoWidth+"x"+this._video.videoHeight;this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",this._video.videoWidth),this._optGotRsl.setAttribute("data-height",this._video.videoHeight),this._optGotRsl.innerText=S,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),K._onLog&&K._onLog("DCE: got "+S),v(),n(),this._renderSelCameraInfo();const C={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};C.deviceId&&(this._lastDeviceId=C.deviceId,this.ifSaveLastUsedCamera&&K.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),h.video.width&&h.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(h.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(h.video.height)))));const b=this.mapCameraEvents.get("played");for(let R of b){if(!R)continue;const A=JSON.parse(JSON.stringify(C));setTimeout((()=>R.apply(this,[A])),0)}if(s&&s!=C.deviceId){const D=this.mapCameraEvents.get("cameraChange");for(let M of D){if(!M)continue;const L=JSON.parse(JSON.stringify(C));setTimeout((()=>M.apply(this,[L])),0)}}if(o&&a&&(o!=C.width||a!=C.height)){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let k of this._arrScanRegionOverlays)k&&this._updateScanRegionOverlay(k);this._cvsOriginalImage||this._updateDrawingLayersSize();const F=this.mapCameraEvents.get("resolutionChange");for(let B of F){if(!B)continue;const j=JSON.parse(JSON.stringify(C));setTimeout((()=>B.apply(this,[j])),0)}}return this.promisePlay=null,C}catch(N){throw this.promisePlay=null,this._bgLoading&&(this._bgLoading.style.display="none"),"NotFoundError"===N.name&&(DOMException?N=new DOMException("No camera available, please use a device with an accessible camera.",N.name):(N=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),N}})))();const h=yield this.promisePlay;return this.playCallbackInfo=JSON.parse(JSON.stringify(h)),this._recordedStates.videoPlaying=!0,h}))}resume(){return I(this,void 0,void 0,(function*(){this._assertOpen(),yield this.play(),this.ifShowScanRegionLaser&&this.showScanRegionLaser()}))}pause(){this._assertOpen(),this._video&&(this._video.pause(),this._recordedStates.videoPlaying=!1),this.ifShowScanRegionLaser&&this.hideScanRegionLaser()}_bindUI(){if(!this.UIElement)throw new Error("Need to define `UIElement` before opening.");const t=[this.UIElement];for(let e=0;e','','',''].join(""),this._optGotRsl=this._optGotRsl||this._selRsl.options[0])):!this._optGotRsl&&e.classList.contains("dce-opt-gotResolution")?this._optGotRsl=e:!this._btnClose&&e.classList.contains("dce-btn-close")?this._btnClose=e:!this._selMinLtr&&e.classList.contains("dlr-sel-minletter")?(this._selMinLtr=e,this._selMinLtr.options.length||(this._selMinLtr.innerHTML=[this._optGotMinLtr?"":'','','','','','','','','','',''].join(""),this._optGotMinLtr=this._optGotMinLtr||this._selMinLtr.options[0])):!this._optGotMinLtr&&e.classList.contains("dlr-opt-gotMinLtr")&&(this._optGotMinLtr=e);if(this.extraBindings&&this.extraBindings.length)for(let i of this.extraBindings)try{i(e)}catch(t){}}if(!this._video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'");this.singleFrameMode?(this._video&&(this._video.addEventListener("click",this._clickIptSingleFrameMode),this._video.style.cursor="pointer",this._video.setAttribute("title","Take a photo")),this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none"),this._bgCamera&&(this._bgCamera.style.display="block")):(this._selCam&&(this._selCam.style.display="block",this._selCam.addEventListener("change",this._onCameraSelChange)),this._selRsl&&(this._selRsl.style.display="block",this._selRsl.addEventListener("change",this._onResolutionSelChange)),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._bgLoading&&(this._bgLoading.style.display="block")),this._btnClose&&this._btnClose.addEventListener("click",this._onCloseBtnClick),document.addEventListener("visibilitychange",this._ev_documentHideEvent),ResizeObserver?(this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{for(let e of t)e.target===this._divVideoContainer&&this._updateLayers()}))),this._divVideoContainer&&this._resizeObserver.observe(this._divVideoContainer)):window.addEventListener("resize",this._updateLayers)}_unbindUI(){this.singleFrameMode?(this._video&&(this._video.removeEventListener("click",this._clickIptSingleFrameMode),this._video.style.cursor="",this._video.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._bgLoading&&(this._bgLoading.style.display="none"),this._selCam&&this._selCam.removeEventListener("change",this._onCameraSelChange),this._selRsl&&this._selRsl.removeEventListener("change",this._onResolutionSelChange),this._btnClose&&this._btnClose.removeEventListener("click",this._onCloseBtnClick),this.hideScanRegionLaser(),this.hideViewDecorator(),this.hideScanRegionOverlays(),this._drawingLayersManager.setVisible(!1),this._hideOriginalImageCvs(),this._video&&(this._video.onloadedmetadata=null,this._video.remove()),this._divVideoContainer=null,this._video=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._cvsScanRegion&&(this._cvsScanRegion.remove(),this._cvsScanRegion=null),this._singleFrameModeIpt&&(this._singleFrameModeIpt.remove(),this._singleFrameModeIpt=null),this._cvsSingleFrameMode&&(this._cvsSingleFrameMode.remove(),this._cvsSingleFrameMode=null),document.removeEventListener("visibilitychange",this._ev_documentHideEvent),ResizeObserver?this._resizeObserver&&this._resizeObserver.disconnect():window.removeEventListener("resize",this._updateLayers)}_assertOpen(){if(!this._bOpen)throw Error("The camera is not open.")}open(t){return I(this,void 0,void 0,(function*(){this.UIElement||(yield this.setUIElement(K.defaultUIElementURL)),this._bindUI(),t&&this.appendAndShowUI();let e=yield this.play();this.bOpen=!0;const i=this.mapCameraEvents.get("cameraOpen");for(let t of i){if(!t)continue;const i=JSON.parse(JSON.stringify(e));setTimeout((()=>t.apply(this,[i])),0)}return e}))}close(t){if(!this._video)return;this.stop(),this._hideOriginalImage(!1),this._unbindUI(),t&&this.hideUI(),this.stopFetchingLoop(),this.bOpen=!1;const e=this.mapCameraEvents.get("cameraClose");for(let t of e){if(!t)continue;const e={width:0,height:0,deviceId:null};setTimeout((()=>t.apply(this,[e])),0)}}stop(){this._video&&this._video.srcObject&&(K._onLog&&K._onLog("DCE: ======stop video========"),this._video.srcObject.getTracks().forEach((t=>{t.stop()})),this._video.srcObject=null,this._videoTrack=null,this._currentCamera=null),this._video&&this.videoSrc&&(K._onLog&&K._onLog("DCE: ======stop existing video========"),this._video.pause(),this._video.currentTime=0),this._bgLoading&&(this._bgLoading.style.animationPlayState=""),this._frameQueue.length=0,this._reusedCvs&&this._reusedCvs.ctx2d&&this._reusedCvs.ctx2d.clearRect(0,0,this._reusedCvs.width,this._reusedCvs.height),this.forceLoseContext()}getAllCameras(t){return I(this,void 0,void 0,(function*(){let e=yield navigator.mediaDevices.enumerateDevices();if(!t&&e&&e.length&&!e[0].deviceId){let t=yield navigator.mediaDevices.getUserMedia({video:!0});e=yield navigator.mediaDevices.enumerateDevices(),t.getTracks().forEach((t=>{t.stop()})),t=null}const i=[],r=[];if(this._allCameras)for(let t of this._allCameras)t._checked&&r.push(t);for(let t=0;t{const i=this._mapCameraResolutions.get(t);if(!i||!i.length)return!1;for(let t of i)if(t[0]===e.width&&t[1]===e.height)return!0;return!1},r=(t,e,i)=>I(this,void 0,void 0,(function*(){const r={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let n=null;try{n=yield navigator.mediaDevices.getUserMedia(r)}catch(t){return null}if(!n)return null;const s=n.getVideoTracks();let o=null;try{const t=s[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=n,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach((t=>{t.stop()})),o}));if(!this._bOpen){const n=this.videoSettings.video.deviceId;if(!n)return null;if(e=n.hasOwnProperty("exact")?this.videoSettings.video.deviceId.exact:n.hasOwnProperty("ideal")?this.videoSettings.video.deviceId.ideal:this.videoSettings.video.deviceId,!e)return null;let s=this._mapCameraResolutions.get(e);if(s&&!t)return this._mapCameraResolutions.get(e);this._mapCameraResolutions.set(e,[]),s=this._mapCameraResolutions.get(e);for(let t of this._predefinedResolutions){const n=yield r(e,t.width,t.height);n&&!i(e,n)&&s.push([n.width,n.height])}return s}if(this._currentCamera){e=this._currentCamera.deviceId;let r=this._mapCameraResolutions.get(e);if(r&&!t)return this._mapCameraResolutions.get(e);this._mapCameraResolutions.set(e,[]),r=this._mapCameraResolutions.get(e);const n=this.getConstraints();for(let t of this._predefinedResolutions){yield this._videoTrack.applyConstraints({width:{ideal:t.width},height:{ideal:t.height}});const n=this._videoTrack.getSettings(),s={width:n.width,height:n.height};i(e,s)||r.push([s.width,s.height])}return yield this._videoTrack.applyConstraints(n),r}return null}))}on(t,e){if(!this.mapCameraEvents.has(t))throw new Error(`Event '${t}' is not exists.`);const i=this.mapCameraEvents.get(t);i.includes(e)||i.push(e)}off(t,e){if(!this.mapCameraEvents.has(t))throw new Error(`Event '${t}' is not exists.`);const i=this.mapCameraEvents.get(t),r=i.indexOf(e);-1!==r&&i.splice(r,1)}offAll(t){if(t){if("string"==typeof t){const e=this.mapCameraEvents.get(t);e&&(e.length=0)}}else for(let t of this.mapCameraEvents.values())t&&(t.length=0)}getVideoSettings(){return JSON.parse(JSON.stringify(this.videoSettings))}updateVideoSettings(t){return this.videoSettings=JSON.parse(JSON.stringify(t)),this._lastDeviceId=null,this._bOpen?this.play():Promise.resolve()}isOpen(){return this._bOpen}getCapabilities(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCapabilities()' is unavailable in singleFrameMode.");return this._videoTrack&&this._videoTrack.getCapabilities?this._videoTrack.getCapabilities():{}}getCameraSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCameraSettings()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings():null}getConstraints(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getConstraints()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getConstraints():null}applyConstraints(t){return I(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'applyConstraints()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error('"_videoTrack" is null.');if(!this._videoTrack.applyConstraints)throw Error("Not supported.");return yield this._videoTrack.applyConstraints(t)}))}turnOnTorch(){return I(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOnTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return yield this._videoTrack.applyConstraints({advanced:[{torch:!0}]});throw Error("Not supported.")}))}turnOffTorch(){return I(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOffTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return yield this._videoTrack.applyConstraints({advanced:[{torch:!1}]});throw Error("Not supported.")}))}setColorTemperature(t){return I(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setColorTemperature()' is unavailable in singleFrameMode.");let e=this.getCapabilities().colorTemperature;if(!e)throw Error("Not supported.");return te.max&&(t=e.max),yield this._videoTrack.applyConstraints({advanced:[{colorTemperature:t}]})}))}setExposureCompensation(t){return I(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setExposureCompensation()' is unavailable in singleFrameMode.");let e=this.getCapabilities().exposureCompensation;if(!e)throw Error("Not supported.");return te.max&&(t=e.max),yield this._videoTrack.applyConstraints({advanced:[{exposureCompensation:t}]})}))}setZoom(t){return I(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setZoom()' is unavailable in singleFrameMode.");let e=this.getCapabilities().zoom;if(!e)throw Error("Not supported.");return te.max&&(t=e.max),yield this._videoTrack.applyConstraints({advanced:[{zoom:t}]})}))}setFrameRate(t){return I(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFrameRate()' is unavailable in singleFrameMode.");let e=this.getCapabilities().frameRate;if(!e)throw Error("Not supported.");return te.max&&(t=e.max),yield this._videoTrack.applyConstraints({width:{ideal:Math.max(this._video.videoWidth,this._video.videoHeight)},frameRate:t})}))}getFrameRate(){return this.getCameraSettings().frameRate}setFocus(t,e){return I(this,void 0,void 0,(function*(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFocus()' is unavailable in singleFrameMode.");const i=this.getCapabilities().focusMode,r=this.getCapabilities().focusDistance;if(!i||!i.includes(t)||!r)throw Error("Not supported.");return e?(er.max&&(e=r.max),yield this._videoTrack.applyConstraints({advanced:[{focusMode:t,focusDistance:e}]})):yield this._videoTrack.applyConstraints({advanced:[{focusMode:t}]})}))}getFocus(){const t=this.getCameraSettings().focusMode;return"continuous"===t?{mode:t}:{mode:t,distance:this.getCameraSettings().focusDistance}}getFrameSize(t,e,i,r){if(!t||!e)return null;let n,s,o,a,h=t,l=e;const c={regionLeft:0,regionTop:0,regionRight:h,regionBottom:l,regionMeasuredByPercentage:!1};i?(i.regionMeasuredByPercentage?(c.regionLeft=i.regionLeft*h/100,c.regionTop=i.regionTop*l/100,c.regionRight=i.regionRight*h/100,c.regionBottom=i.regionBottom*l/100):(c.regionLeft=i.regionLeft,c.regionTop=i.regionTop,c.regionRight=i.regionRight,c.regionBottom=i.regionBottom),n=c.regionLeft,s=c.regionTop,h=Math.round(c.regionRight-c.regionLeft),l=Math.round(c.regionBottom-c.regionTop)):(n=0,s=0);const u=Math.max(h,l);if(r&&r>0&&u>r){const t=r/u;h>l?(o=r,a=Math.round(l*t)):(o=Math.round(h*t),a=r)}else o=h,a=l;return o<=0||a<=0?null:{sx:n,sy:s,sWidth:h,sHeight:l,dWidth:o,dHeight:a}}getFrame(){if(this.singleFrameMode)throw Error("'getFrame()' is unavailable in singleFrameMode.");if(this._assertOpen(),this.singleFrameMode)throw new Error("'getFrame()' is unavailable in singleFrameMode.");return this._getVideoFrame(this._scanRegion)}getImage(){const t=this.getFrame();return t.pixelFormat=t.colorMode,Object.assign(Object.assign({},t),{pixelFormat:t.colorMode})}_getVideoFrame(t,e){if(this.isDisposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getVideoFrame()' is unavailable in singleFrameMode.");const i=Date.now();K._onLog&&K._onLog("DCE: _getVideoFrame(region?) START: "+i);const r=this._video.videoWidth,n=this._video.videoHeight;if(0===r||0===n)return null;const s=this.getFrameSize(r,n,t,this.maxCvsSideLength);if(!s)return null;let o,a;o=r!==s.sWidth||n!==s.sHeight,a=s.sWidth!==s.dWidth||s.sHeight!==s.dHeight;const h=(()=>!(!this._bWebGLSupported||a))(),l={data:null,region:t?JSON.parse(JSON.stringify(t)):null,sx:s.sx,sy:s.sy,width:s.dWidth,height:s.dHeight,colorMode:null,timeSpent:null,timeStamp:null,isCropped:o,toCanvas:this._toCanvas,_sWidth:s.sWidth,_sHeight:s.sHeight,_bUseWebGL:null};let c;try{c=this._getImageData(this._video,r,n,s,e,{targetColorMode:this.frameColorMode,bUseWebGL:h})}catch(t){if("WebGLError"!==t.name)throw t;c=this._getImageData(this._video,r,n,s,e,{targetColorMode:this.frameColorMode,bUseWebGL:!1})}if(!c)return null;const u=Date.now();return K._onLog&&K._onLog("DCE: _getVideoFrame(region?) END: "+u),l.data=c.data,l.colorMode=c.colorMode,l._bUseWebGL=c._bUseWebGL,l.timeSpent=u-i,l.timeStamp=u,l}_getImageData(t,e,i,r,n,s){if(this.isDisposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(!e||!i)return null;K._onLog&&K._onLog("DCE: _getImageData() START: "+Date.now());const{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u}=r;let d;if(d=s&&s.targetColorMode?s.targetColorMode.toLowerCase():"rgba",s&&s.bUseWebGL){this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas"));const r=this._reusedWebGLCvs;r.width==e&&r.height==i||(r.width=e,r.height=i,this._reusedWebGLCtx&&this._reusedWebGLCtx.viewport(0,0,e,i));const s=this._reusedWebGLCtx||r.getContext("webgl",{antialias:!1})||r.getContext("experimental-webgl",{antialias:!1});if(!s){this._reusedWebGLCtx=null,this._bWebGLSupported=!1;const t=new Error("WebGL error: unable to initialize WebGL. Your browser or machine may not support it.");throw t.name="WebGLError",t}if(s.enable(s.SCISSOR_TEST),s.scissor(o,a,c,u),!this._reusedWebGLCtx||d!==this.currentFSColorMode){this._reusedWebGLCtx=s;const t=t=>{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,1,1,-1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,i),t.bufferData(t.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,0,2,3]),t.STATIC_DRAW),{position:e,indices:i}},e=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},i=(t,e,i)=>{const n=r(t,t.VERTEX_SHADER,e),s=r(t,t.FRAGMENT_SHADER,i),o=t.createProgram();return t.attachShader(o,n),t.attachShader(o,s),t.linkProgram(o),t.getProgramParameter(o,t.LINK_STATUS)?o:(alert("Unable to initialize the shader program: "+t.getProgramInfoLog(o)),null)},r=(t,e,i)=>{const r=t.createShader(e);return t.shaderSource(r,i),t.compileShader(r),t.getShaderParameter(r,t.COMPILE_STATUS)?r:(alert("An error occurred compiling the shaders: "+t.getShaderInfoLog(r)),t.deleteShader(r),null)},n="\n attribute mediump vec2 aVertexPosition;\n varying mediump vec2 vDirection;\n \n void main( void )\n {\n gl_Position = vec4(aVertexPosition, 1.0, 1.0) * 2.0;\n vDirection = aVertexPosition;\n }\n ";let o;o=["rgba","rbga","grba","gbra","brga","bgra"].includes(d)?d.slice(0,3):"rgb";const a=i(s,n,`\n precision mediump float;\n\n varying mediump vec2 vDirection;\n uniform sampler2D uSampler;\n uniform lowp float uColorFactor;\n \n void main(void)\n {\n vec4 sample = texture2D(uSampler, vec2(vDirection.x * 0.5 + 0.5, vDirection.y * 0.5 + 0.5));\n lowp float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `);this._webGLProgramInfo={program:a,attribLocations:{vertexPosition:s.getAttribLocation(a,"aVertexPosition")},uniformLocations:{uSampler:s.getUniformLocation(a,"uSampler"),uColorFactor:s.getUniformLocation(a,"uColorFactor")}},this._webGLBuffers=t(s),this._webGLTexture=e(s),this.currentFSColorMode=d}const h=(t,e,i)=>{const r=t.RGBA,n=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,r,n,s,i)},l=(t,e,i,r)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,i.indices),t.useProgram(e.program);{const r=2,n=t.FLOAT,s=!1,o=0,a=0;t.bindBuffer(t.ARRAY_BUFFER,i.position),t.vertexAttribPointer(e.attribLocations.vertexPosition,r,n,s,o,a),t.enableVertexAttribArray(e.attribLocations.vertexPosition)}t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,r),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,"grey"===d||"grey32"===d?1:0);const n=t.UNSIGNED_SHORT;t.drawElements(t.TRIANGLES,6,n,0)};let f;if(h(s,this._webGLTexture,t),l(s,this._webGLProgramInfo,this._webGLBuffers,this._webGLTexture),n){if(n.length=this.croppingRegions.length||this._croppingRegionIndex<0)throw new Error("The 'croppingRegionIndex' is out of bounds.");t=this.croppingRegions[this._croppingRegionIndex],this.bIncreaseRegionIndexAuto&&++this._croppingRegionIndex>=this.croppingRegions.length&&(this._croppingRegionIndex=0)}return t}_fetchingLoop(t){if(this.isDisposed)return;if(!this._bOpen||!this.isFetchingLoopStarted())return void this.stopFetchingLoop();const e=()=>{K._onLog&&K._onLog("DCE: start fetching a frame: "+Date.now());const t=this.getCurrentRegion();let e=this._getVideoFrame(t);if(!e)return void(K._onLog&&K._onLog("DCE: get a invalid frame, abandon it: "+Date.now()));for(;this._frameQueue&&this._frameQueue.length>=this.maxNumberOfFramesInBuffer;)this._frameQueue.shift();this._frameQueue.push(e),K._onLog&&K._onLog("DCE: finish fetching a frame: "+Date.now());const i=this.mapCameraEvents.get("frameAddedToBuffer");for(let t of i)t&&setTimeout(t.bind(this),0)},i=()=>{this.isDisposed||(this._frameLoopTimeoutId2&&clearTimeout(this._frameLoopTimeoutId2),this.refreshInterval<=0||(this._frameLoopTimeoutId2=setTimeout((()=>{this.isDisposed||(this._bOpen&&this.isFetchingLoopStarted()?(K._onLog&&K._onLog("DCE: second timeout executes: "+Date.now()),e(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};t&&(this._frameQueue.length0&&i()):this.refreshInterval>0?(e(),i()):0===this.refreshInterval?e():this.refreshInterval),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameLoopTimeoutId=setTimeout((()=>{this.isDisposed||this._fetchingLoop(!0)}),this.loopInterval)}startFetchingLoop(){if(this.isDisposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(this._assertOpen(),this.singleFrameMode)throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,this._recordedStates.fetchingLoopStart=!0,K._onLog&&K._onLog("start fetching loop: "+Date.now()),this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(K._onLog&&K._onLog("stop fetching loop: "+Date.now()),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameQueue.length=0,this._bFetchingLoopStarted=!1,this._recordedStates.fetchingLoopStart=!1)}getFrameFromBuffer(t){return this._frameQueue&&this._frameQueue.length?t?t0?i-1:r,W),actionName:"modifyPolygon",pointIndex:i}),t}),{})}_extendSet(t,e){if("vertices"===t){const t=this._fabricObject;t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,r){return t["p"+r]=new E.Control({positionHandler:U,actionHandler:H(r>0?r-1:i,W),actionName:"modifyPolygon",pointIndex:r}),t}),{}),t._setPositionDimensions({}),!0}}_extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i in e.getCoords())t.push({x:e.getCoords()[i].x,y:e.getCoords()[i].y});return t}}},DT_Rect:class extends V{constructor(t,e,i,r,n){super(new E.Rect({left:t,top:e,width:i,height:r}),n)}},DT_Image:class extends V{constructor(t,e,i,r){super(new E.Image(t,{left:e,top:i}),r),this.image=t}_extendSet(t,e){if("image"===t){if(e instanceof HTMLImageElement)return this._fabricObject.setElement(e),this.image=e,!0;if(e instanceof HTMLCanvasElement){const t=new Image;return t.src=e.toDataURL(),this._fabricObject.setElement(t),this.image=e,!0}throw new Error("Unsupported value.")}}_extendGet(t){if("image"===t)return this.image}},DT_Text:class extends V{constructor(t,e,i,r){super(new E.IText(t,{left:e,top:i}),r),this._mediaType="text"}},DT_Line:class extends V{constructor(t,e,i){super(new E.Line([t.x,t.y,e.x,e.y]),i)}_extendSet(t,e){return"startPoint"===t?(this._fabricObject.set("x1",e.x),this._fabricObject.set("y1",e.y),!0):"endPoint"===t?(this._fabricObject.set("x2",e.x),this._fabricObject.set("y2",e.y),!0):void 0}_extendGet(t){return"startPoint"===t?{x:this._fabricObject.get("x1"),y:this._fabricObject.get("y1")}:"endPoint"===t?{x:this._fabricObject.get("x2"),y:this._fabricObject.get("y2")}:void 0}},DT_Group:class extends V{constructor(t){super(new E.Group(t.map((t=>t._getFabricObject()))));const e=this.mapEvents;this._fabricObject.onSelect=()=>{this.styleSelector="selected";const t=this.mapEvents.get("select");for(let e of t)e&&e.apply(this);const e=this._fabricObject._objects;for(let t of e)setTimeout((()=>{t.onSelect&&t.onSelect()}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)},this._fabricObject.onDeselect=()=>{this.styleSelector="default";const t=e.get("deselect");for(let e of t)e&&e.apply(this);const i=this._fabricObject._objects;for(let t of i)setTimeout((()=>{t.onDeselect&&t.onDeselect()}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)}}getChildItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}addChildItem(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}}};class q extends b{constructor(){super(),this.bFilterRegionInJs=!0,this._onCameraSelChange=()=>{},this._onResolutionSelChange=()=>{},this._onCloseBtnClick=()=>{},this._onPlayed=null}static get version(){return this._version+`(DCE ${K.getVersion()})`}static _fireHTTPSWarnning(){q.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{q.onWarning&&q.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}_fireResolutionWarning(){if(!this.singleFrameMode&&this.onWarning){const t=this.dce.getConstraints();t&&t.width<1280&&t.height<720&&setTimeout((()=>{this.onWarning&&this.onWarning({id:3,message:"Camera resolution too low, please use a higher resolution (720P or better)."})}),0)}}getUIElement(){return this.dce.getUIElement()}async setUIElement(t){await this.dce.setUIElement(t)}get singleFrameMode(){return this.dce.singleFrameMode}set singleFrameMode(t){this.dce.singleFrameMode=t,t&&(this.dce.ifShowScanRegionLaser=!1,(async()=>{let t=await this.getScanSettings();t.oneDTrustFrameCount=1,await this.updateScanSettings(t)})())}get onUnduplicatedRead(){return this.onUniqueRead}set onUnduplicatedRead(t){this.onUniqueRead=t}get video(){return this.dce&&this.dce.video}set videoSrc(t){this.dce&&(this.dce.videoSrc=t)}get videoSrc(){return this.dce&&this.dce.videoSrc}_assertOpen(){if(!this.dce.isOpen())throw Error("The scanner is not open.")}set regionMaskFillStyle(t){this.dce.setScanRegionMaskStyle({fillStyle:t})}get regionMaskFillStyle(){return this.dce.regionMaskFillStyle}set regionMaskStrokeStyle(t){this.dce.setScanRegionMaskStyle({strokeStyle:t})}get regionMaskStrokeStyle(){return this.dce.regionMaskStrokeStyle}set regionMaskLineWidth(t){this.dce.setScanRegionMaskStyle({lineWidth:t})}get regionMaskLineWidth(){return this.dce.regionMaskLineWidth}set region(t){this._region=t,this.dce&&(t?t instanceof Array||this.dce.setScanRegion(t):this.dce.setScanRegion(null)),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}set ifSaveOriginalImageInACanvas(t){this._ifSaveOriginalImageInACanvas=t,this.dce.frameColorMode=t?"rgba":"grey"}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}async createDCEInstance(){if(!this.dce){b._onLog&&b._onLog("createDCEInstance()");try{ResizeObserver}catch(t){"ReferenceError"===t.name&&window&&(window.ResizeObserver=void 0)}K.defaultUIElementURL=null,this.dce=await K.createInstance(),this.dce.refreshInterval=200,this.dce.frameColorMode="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this._drawingItemNamespace=J,"iPhone"!==b.browserInfo.OS&&"Android"!==b.browserInfo.OS&&"HarmonyOS"!==b.browserInfo.OS&&this.dce.setResolution(1920,1080),this.dce.on("cameraChange",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("resolutionChange",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("cameraClose",(()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1})),this.dce.on("singleFrameAcquired",(async t=>{if(!t)return;if(!t.data)return;let e;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{data:i,sx:r,sy:n,width:s,height:o,colorMode:a,timeStamp:h,_sWidth:l,_sHeight:c}=t,u={timeStamp:h};if("grey"===a)e=await this._decodeBuffer_Uint8Array(i,s,o,s,p.IPF_GrayScaled,u);else if("rgba"===a)e=await this._decodeBuffer_Uint8Array(i,s,o,4*s,p.IPF_ABGR_8888,u);else{if("bgra"!==a)throw new Error(`Color mode '${a}' is not supported.`);e=await this._decodeBuffer_Uint8Array(i,s,o,4*s,p.IPF_ARGB_8888,u)}if(await this.clearMapDecodeRecord(),b.recalculateResultLocation(e,r,n,l,c,s,o),this._drawResults(e),this.onFrameRead&&this.isOpen()&&!this._bPauseScan){let t=this._cloneDecodeResults(e);this.onFrameRead(t)}if(this.onUniqueRead&&this.isOpen()&&!this._bPauseScan)for(let t of e)this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t))}))}}set maxCvsSideLength(t){this._maxCvsSideLength=t,this.dce.maxCvsSideLength=t}get maxCvsSideLength(){return this._maxCvsSideLength}static async createInstance(t){let e=new q;e._instanceID=await q.createInstanceInWorker(!0),await e.createDCEInstance(),"string"==typeof t&&(t=JSON.parse(t));for(let i in t)e[i]=t[i];return await e.dce.setUIElement(q.defaultUIElementURL),e.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),q._fireHTTPSWarnning(),e.singleFrameMode||await e.updateRuntimeSettings("single"),e}async decodeCurrentFrame(t){this._assertOpen();let e=null;t&&t.region&&(e=t.region);const i=this.dce._getVideoFrame(e);return this._decode_DCEFrame(i)}static isRegionNormalPreset(t){return 0==t.regionLeft&&0==t.regionTop&&0==t.regionRight&&0==t.regionBottom&&0==t.regionMeasuredByPercentage}async updateRuntimeSettings(t){let e;if("string"==typeof t)if("speed"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,t.region&&(e.region=t.region)}else if("balance"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,t.region&&(e.region=t.region),e.deblurLevel=3,e.expectedBarcodesCount=512,e.localizationModes=[2,16,0,0,0,0,0,0],e.timeout=1e5}else if("coverage"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,t.region&&(e.region=t.region),e.deblurLevel=5,e.expectedBarcodesCount=512,e.scaleDownThreshold=1e5,e.localizationModes=[2,16,4,8,0,0,0,0],e.timeout=1e5}else if("single"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,q.isRegionNormalPreset(t.region)?e.region=null:e.region=t.region,e.expectedBarcodesCount=1,e.localizationModes=[16,2,0,0,0,0,0,0],e.barcodeZoneMinDistanceToImageBorders=0}else if("dense"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,t.region&&(e.region=t.region),e.deblurLevel=7,e.scaleDownThreshold=1e5,e.localizationModes=[2,8,0,0,0,0,0,0],e.minResultConfidence=0,e.timeout=1e5}else if("distance"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,t.region&&(e.region=t.region),e.scaleDownThreshold=1e5,e.localizationModes=[2,8,0,0,0,0,0,0],e.timeout=1e5}else e=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(e=JSON.parse(JSON.stringify(t)),e.region instanceof Array){let i=t.region;[i.regionLeft,i.regionTop,i.regionLeft,i.regionBottom,i.regionMeasuredByPercentage].some((t=>void 0!==t))&&(e.region={regionLeft:i.regionLeft||0,regionTop:i.regionTop||0,regionRight:i.regionRight||0,regionBottom:i.regionBottom||0,regionMeasuredByPercentage:i.regionMeasuredByPercentage||0})}}if(!b._bUseFullFeature){if(0!=(e.barcodeFormatIds&~(y.BF_ONED|y.BF_QR_CODE|y.BF_PDF417|y.BF_DATAMATRIX))||0!=e.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=e.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}{let t=e.region;if(this.bFilterRegionInJs?this.userDefinedRegion=JSON.parse(JSON.stringify(t)):this.userDefinedRegion=null,t instanceof Array)if(t.length){for(let e=0;e{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.updateReturn)}catch(t){i(t)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),b._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(e)}})})),"single"==t&&(await this.setModeArgument("BinarizationModes",0,"EnableFillBinaryVacancy","0"),await this.setModeArgument("LocalizationModes",0,"ScanDirection","2"),await this.setModeArgument("BinarizationModes",0,"BlockSizeX","71"),await this.setModeArgument("BinarizationModes",0,"BlockSizeY","71"))}_bindUI(){if(!this.getUIElement())throw new Error("Need to define `UIElement` before opening.");if(this.dce._bindUI(),!this.dce.video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'")}_unbindUI(){this.dce._unbindUI()}set onPlayed(t){this.dce.off("played",this._onPlayed),this._onPlayed=t,this.dce.on("played",this._onPlayed)}get onPlayed(){return this._onPlayed}async getAllCameras(){return this.dce.getAllCameras()}async getCurrentCamera(){return this.dce.getSelectedCamera()}async setCurrentCamera(t){const e=await this.dce.selectCamera(t);return this._fireResolutionWarning(),e}getResolution(){return this.dce.getResolution()}async setResolution(t,e){const i=await this.dce.setResolution(t,e);return this._fireResolutionWarning(),i}getVideoSettings(){return this.dce.getVideoSettings()}updateVideoSettings(t){return this.dce.updateVideoSettings(t)}isOpen(){return this.dce&&this.dce.isOpen()}setVideoFit(t){return this.dce&&this.dce.setVideoFit(t)}set ifShowScanRegionMask(t){this.dce&&(this.dce.ifShowScanRegionMask=t)}get ifShowScanRegionMask(){return this.dce&&this.dce.ifShowScanRegionMask}set ifSaveLastUsedCamera(t){this.dce&&(this.dce.ifSaveLastUsedCamera=t)}get ifSaveLastUsedCamera(){return this.dce&&this.dce.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){this.dce&&(this.dce.ifSkipCameraInspection=t)}get ifSkipCameraInspection(){return this.dce&&this.dce.ifSkipCameraInspection}stop(){this._drawResults(null),this.dce.stop(),this.dce.ifShowScanRegionLaser=!1,this.dce.hideViewDecorator(),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}pause(){this.dce.pause()}async play(t,e,i){this.dce.ifShowScanRegionLaser=!0;const r=await this.dce.play(t,e,i);return this._fireResolutionWarning(),r}pauseScan(t){this._assertOpen(),t&&t.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce.ifShowScanRegionLaser=!1,this.dce.stopFetchingLoop()}resumeScan(){this._assertOpen(),this._bPauseScan=!1,this.dce.ifShowScanRegionLaser=!0}getCapabilities(){return this.dce.getCapabilities()}getCameraSettings(){return this.dce.getCameraSettings()}getConstraints(){return this.dce.getConstraints()}async applyConstraints(t){return this.dce.applyConstraints(t)}async turnOnTorch(){return this.dce.turnOnTorch()}async turnOffTorch(){return this.dce.turnOffTorch()}async setColorTemperature(t){return this.dce.setColorTemperature(t)}async setExposureCompensation(t){return this.dce.setExposureCompensation(t)}async setZoom(t){return this.dce.setZoom(t)}async setFrameRate(t){return this.dce.setFrameRate(t)}getFrameRate(){return this.dce.getFrameRate()}async setFocus(t,e){return this.dce.setFocus(t,e)}getFocus(){return this.dce.getFocus()}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),void this._drawResults(null);if(!this.isOpen())return this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce.video||this.dce.video.paused||this._bPauseScan)return b._onLog&&b._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));b._onLog&&b._onLog("======= once read ======="),b._onLog&&(this._timeStartDecode=Date.now());const t=this._getVideoFrame();if(!t)return this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{t._bUseWebGL||"grey"!==t.colorMode||(this.dce.frameColorMode="rgba");let e=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{data:i,sx:r,sy:n,width:s,height:o,colorMode:a,timeStamp:h,_sWidth:l,_sHeight:c}=t,u={timeStamp:h};if("grey"===a)e=await this._decodeBuffer_Uint8Array(i,s,o,s,p.IPF_GrayScaled,u);else if("rgba"===a)e=await this._decodeBuffer_Uint8Array(i,s,o,4*s,p.IPF_ABGR_8888,u);else{if("bgra"!==a)throw new Error(`Color mode '${a}' is not supported.`);e=await this._decodeBuffer_Uint8Array(i,s,o,4*s,p.IPF_ARGB_8888,u)}return b.recalculateResultLocation(e,r,n,l,c,s,o),e})().then((t=>{if(b._onLog&&b._onLog(t),this.captureAndDecodeInParallel){let t=this.array_decodeFrameTimeCost,e=this.array_getFrameTimeCost,i=this._indexCurrentDecodingFrame;const r=()=>{let r=0;if(this.region instanceof Array){let n=0,s=0;n=i+1>=this.region.length?0:i+1,s=n+1>=this.region.length?0:n+1,r=t[n]&&t[n].length&&e[s]&&e[s].length?Math.min(...t[n])-Math.max(...e[s]):0}else if(e&&e.length){let i=Math.min(...t),n=Math.max(...e);i&&n&&(r=i-n)}else r=0;return r>0?r:0};(()=>{if(this.region instanceof Array){for(t[i]&&t[i]instanceof Array||(t[i]=[]);t[i].length>=5;)t[i].shift();t[i].push(this._lastInnerDecodeDuration)}else{for(;t.length>=5;)t.shift();t.push(this._lastInnerDecodeDuration)}})(),this._intervalGetVideoFrame=r()+this.intervalTime}if(this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&t.length){let e=!1;if(!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead)e=!0;else if("unique"===this.bPlaySoundOnSuccessfulRead)for(let i of t)if(0==i.resultsType){e=!0;break}e&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&t.length){let e=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead)e=!0;else if("unique"===this.bVibrateOnSuccessfulRead)for(let i of t)if(0==i.resultsType){e=!0;break}if(e)try{navigator.vibrate(this.vibrateDuration)}catch(t){console.warn("Vibration not allowed. User interaction required: "+(t.message||t))}}if(this.onFrameRead){let e=this._cloneDecodeResults(t);for(let t of e)0!=t.resultsType&&1!=t.resultsType||this.onFrameRead(e)}if(this.onUniqueRead)for(let e of t)0==e.resultsType&&this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e));this._drawResults(t)}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((t=>{this.dce.stopFetchingLoop(),b._onLog&&b._onLog(t.message||t),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==t.message||console.warn(t.message)}))}_getVideoFrame(){if(!this.dce)return null;let t;if(this.captureAndDecodeInParallel){let e=this.dce.isFetchingLoopStarted();if(this.dce.loopInterval=this._intervalGetVideoFrame,e||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dce.loopInterval=0,null;t=this.dce.getFrameFromBuffer();const i=t=>{if(!t)return;let e=t.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(e)};i(t)}else this.dce.stopFetchingLoop(),t=this.dce.getFrame();return t}async open(){this._bindUI();const t=await this.dce.open();return this._bPauseScan=!1,this.singleFrameMode||(this.dce&&(this.dce.ifShowScanRegionLaser=!0),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),this.keepAlive(),t}async openVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const t=await this.dce.open();return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),this.keepAlive(),t}close(){this.dce.close(),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId)}async show(){this._bindUI();const t=await this.dce.open(!0);return this._bPauseScan=!1,this.singleFrameMode||(this.dce&&(this.dce.ifShowScanRegionLaser=!0),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),this.keepAlive(),t}async showVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const t=await this.dce.open(!0);return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),this.keepAlive(),t}hide(){this.dce.close(!0),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId)}destroyContext(){this.close(),this.bDestroyed||super.destroyContext()}}var Q,Z,$,tt,et,it,rt,nt,st,ot,at,ht,lt,ct,ut,dt,ft,gt,_t,pt,mt,vt,yt,St,Ct,bt,wt;!function(t){t[t.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",t[t.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",t[t.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",t[t.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",t[t.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",t[t.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",t[t.BICM_SKIP=0]="BICM_SKIP",t[t.BICM_REV=2147483648]="BICM_REV"}(Q||(Q={})),function(t){t[t.BCM_AUTO=1]="BCM_AUTO",t[t.BCM_GENERAL=2]="BCM_GENERAL",t[t.BCM_SKIP=0]="BCM_SKIP",t[t.BCM_REV=2147483648]="BCM_REV"}(Z||(Z={})),function(t){t[t.BF2_NULL=0]="BF2_NULL",t[t.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",t[t.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",t[t.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",t[t.BF2_POSTNET=2097152]="BF2_POSTNET",t[t.BF2_PLANET=4194304]="BF2_PLANET",t[t.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",t[t.BF2_RM4SCC=16777216]="BF2_RM4SCC",t[t.BF2_DOTCODE=2]="BF2_DOTCODE",t[t.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",t[t.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",t[t.BF2_PHARMACODE=12]="BF2_PHARMACODE"}($||($={})),function(t){t[t.BM_AUTO=1]="BM_AUTO",t[t.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",t[t.BM_SKIP=0]="BM_SKIP",t[t.BM_THRESHOLD=4]="BM_THRESHOLD",t[t.BM_REV=2147483648]="BM_REV"}(tt||(tt={})),function(t){t[t.ECCM_CONTRAST=1]="ECCM_CONTRAST"}(et||(et={})),function(t){t[t.CFM_GENERAL=1]="CFM_GENERAL"}(it||(it={})),function(t){t[t.CCM_AUTO=1]="CCM_AUTO",t[t.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",t[t.CCM_SKIP=0]="CCM_SKIP",t[t.CCM_REV=2147483648]="CCM_REV"}(rt||(rt={})),function(t){t[t.CICM_GENERAL=1]="CICM_GENERAL",t[t.CICM_SKIP=0]="CICM_SKIP",t[t.CICM_REV=2147483648]="CICM_REV"}(nt||(nt={})),function(t){t[t.CM_IGNORE=1]="CM_IGNORE",t[t.CM_OVERWRITE=2]="CM_OVERWRITE"}(st||(st={})),function(t){t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING"}(ot||(ot={})),function(t){t[t.DRM_AUTO=1]="DRM_AUTO",t[t.DRM_GENERAL=2]="DRM_GENERAL",t[t.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",t[t.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",t[t.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",t[t.DRM_SKIP=0]="DRM_SKIP",t[t.DRM_REV=2147483648]="DRM_REV"}(at||(at={})),function(t){t[t.DPMCRM_AUTO=1]="DPMCRM_AUTO",t[t.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",t[t.DPMCRM_SKIP=0]="DPMCRM_SKIP",t[t.DPMCRM_REV=2147483648]="DPMCRM_REV"}(ht||(ht={})),function(t){t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_REV=2147483648]="GTM_REV"}(lt||(lt={})),function(t){t[t.IPM_AUTO=1]="IPM_AUTO",t[t.IPM_GENERAL=2]="IPM_GENERAL",t[t.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",t[t.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",t[t.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",t[t.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",t[t.IPM_SKIP=0]="IPM_SKIP",t[t.IPM_REV=2147483648]="IPM_REV"}(ct||(ct={})),function(t){t[t.IRSM_MEMORY=1]="IRSM_MEMORY",t[t.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",t[t.IRSM_BOTH=4]="IRSM_BOTH"}(ut||(ut={})),function(t){t[t.IRT_NO_RESULT=0]="IRT_NO_RESULT",t[t.IRT_ORIGINAL_IMAGE=1]="IRT_ORIGINAL_IMAGE",t[t.IRT_COLOUR_CLUSTERED_IMAGE=2]="IRT_COLOUR_CLUSTERED_IMAGE",t[t.IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE=4]="IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE",t[t.IRT_TRANSFORMED_GRAYSCALE_IMAGE=8]="IRT_TRANSFORMED_GRAYSCALE_IMAGE",t[t.IRT_PREDETECTED_REGION=16]="IRT_PREDETECTED_REGION",t[t.IRT_PREPROCESSED_IMAGE=32]="IRT_PREPROCESSED_IMAGE",t[t.IRT_BINARIZED_IMAGE=64]="IRT_BINARIZED_IMAGE",t[t.IRT_TEXT_ZONE=128]="IRT_TEXT_ZONE",t[t.IRT_CONTOUR=256]="IRT_CONTOUR",t[t.IRT_LINE_SEGMENT=512]="IRT_LINE_SEGMENT",t[t.IRT_FORM=1024]="IRT_FORM",t[t.IRT_SEGMENTATION_BLOCK=2048]="IRT_SEGMENTATION_BLOCK",t[t.IRT_TYPED_BARCODE_ZONE=4096]="IRT_TYPED_BARCODE_ZONE",t[t.IRT_PREDETECTED_QUADRILATERAL=8192]="IRT_PREDETECTED_QUADRILATERAL"}(dt||(dt={})),function(t){t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=2147483648]="LM_REV"}(ft||(ft={})),function(t){t[t.PDFRM_RASTER=1]="PDFRM_RASTER",t[t.PDFRM_AUTO=2]="PDFRM_AUTO",t[t.PDFRM_VECTOR=4]="PDFRM_VECTOR",t[t.PDFRM_REV=2147483648]="PDFRM_REV"}(gt||(gt={})),function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(_t||(_t={})),function(t){t[t.RPM_AUTO=1]="RPM_AUTO",t[t.RPM_GENERAL=2]="RPM_GENERAL",t[t.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",t[t.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",t[t.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",t[t.RPM_SKIP=0]="RPM_SKIP",t[t.RPM_REV=2147483648]="RPM_REV"}(pt||(pt={})),function(t){t[t.RCT_PIXEL=1]="RCT_PIXEL",t[t.RCT_PERCENTAGE=2]="RCT_PERCENTAGE"}(mt||(mt={})),function(t){t[t.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",t[t.RT_RAW_TEXT=1]="RT_RAW_TEXT",t[t.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",t[t.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT"}(vt||(vt={})),function(t){t[t.SUM_AUTO=1]="SUM_AUTO",t[t.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",t[t.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",t[t.SUM_SKIP=0]="SUM_SKIP",t[t.SUM_REV=2147483648]="SUM_REV"}(yt||(yt={})),function(t){t[t.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",t[t.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",t[t.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",t[t.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",t[t.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",t[t.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED"}(St||(St={})),function(t){t[t.TFM_AUTO=1]="TFM_AUTO",t[t.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",t[t.TFM_SKIP=0]="TFM_SKIP",t[t.TFM_REV=2147483648]="TFM_REV"}(Ct||(Ct={})),function(t){t[t.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",t[t.TROM_POSITION=2]="TROM_POSITION",t[t.TROM_FORMAT=4]="TROM_FORMAT",t[t.TROM_SKIP=0]="TROM_SKIP",t[t.TROM_REV=2147483648]="TROM_REV"}(bt||(bt={})),function(t){t[t.TDM_AUTO=1]="TDM_AUTO",t[t.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",t[t.TDM_SKIP=0]="TDM_SKIP",t[t.TDM_REV=2147483648]="TDM_REV"}(wt||(wt={}));export{b as BarcodeReader,q as BarcodeScanner,Q as EnumBarcodeColourMode,Z as EnumBarcodeComplementMode,y as EnumBarcodeFormat,$ as EnumBarcodeFormat_2,tt as EnumBinarizationMode,et as EnumClarityCalculationMethod,it as EnumClarityFilterMode,rt as EnumColourClusteringMode,nt as EnumColourConversionMode,st as EnumConflictMode,ht as EnumDPMCodeReadingMode,ot as EnumDeblurMode,at as EnumDeformationResistingMode,m as EnumErrorCode,lt as EnumGrayscaleTransformationMode,v as EnumIMResultDataType,p as EnumImagePixelFormat,ct as EnumImagePreprocessingMode,ut as EnumIntermediateResultSavingMode,dt as EnumIntermediateResultType,ft as EnumLocalizationMode,gt as EnumPDFReadingMode,_t as EnumQRCodeErrorCorrectionLevel,pt as EnumRegionPredetectionMode,mt as EnumResultCoordinateType,vt as EnumResultType,yt as EnumScaleUpMode,St as EnumTerminatePhase,Ct as EnumTextFilterMode,bt as EnumTextResultOrderMode,wt as EnumTextureDetectionMode}; diff --git a/dist/dbr.pure.js b/dist/dbr.pure.js new file mode 100644 index 0000000..9c706e5 --- /dev/null +++ b/dist/dbr.pure.js @@ -0,0 +1,11 @@ +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft Barcode Reader JS Edition + * @website http://www.dynamsoft.com + * @copyright Copyright 2022, Dynamsoft Corporation + * @author Dynamsoft + * @version 9.2.11 (js 20220727) + * @fileoverview Dynamsoft JavaScript Library for Barcode Reader + * More info on DBR JS: https://www.dynamsoft.com/barcode-reader/sdk-javascript/ + */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).Dynamsoft=e.Dynamsoft||{},e.Dynamsoft.DBR={}))}(this,(function(e){"use strict";var t=function(){this.init()};t.prototype={init:function(){var e=this||n;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var t=this||n;if(e=parseFloat(e),t.ctx||u(),void 0!==e&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,n.ctx.currentTime);for(var r=0;r=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,u()),e},codecs:function(e){return(this||n)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||n;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||n,t=null;try{t="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!t||"function"!=typeof t.canPlayType)return e;var r=t.canPlayType("audio/mpeg;").replace(/^no$/,""),o=e._navigator?e._navigator.userAgent:"",i=o.match(/OPR\/([0-6].)/g),a=i&&parseInt(i[0].split("/")[1],10)<33,s=-1!==o.indexOf("Safari")&&-1===o.indexOf("Chrome"),_=o.match(/Version\/(.*?) /),d=s&&_&&parseInt(_[1],10)<15;return e._codecs={mp3:!(a||!r&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!r,opus:!!t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(t.canPlayType('audio/wav; codecs="1"')||t.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!t.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!t.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/m4a;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(t.canPlayType("audio/x-m4b;")||t.canPlayType("audio/m4b;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(t.canPlayType("audio/x-mp4;")||t.canPlayType("audio/mp4;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(d||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(d||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!t.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(t.canPlayType("audio/x-flac;")||t.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||n;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var t=function(n){for(;e._html5AudioPool.length0?s._seek:r._sprite[e][0]/1e3),u=Math.max(0,(r._sprite[e][0]+r._sprite[e][1])/1e3-d),c=1e3*u/Math.abs(s._rate),l=r._sprite[e][0]/1e3,h=(r._sprite[e][0]+r._sprite[e][1])/1e3;s._sprite=e,s._ended=!1;var A=function(){s._paused=!1,s._seek=d,s._start=l,s._stop=h,s._loop=!(!s._loop&&!r._sprite[e][2])};if(!(d>=h)){var m=s._node;if(r._webAudio){var f=function(){r._playLock=!1,A(),r._refreshBuffer(s);var e=s._muted||r._muted?0:s._volume;m.gain.setValueAtTime(e,n.ctx.currentTime),s._playStart=n.ctx.currentTime,void 0===m.bufferSource.start?s._loop?m.bufferSource.noteGrainOn(0,d,86400):m.bufferSource.noteGrainOn(0,d,u):s._loop?m.bufferSource.start(0,d,86400):m.bufferSource.start(0,d,u),c!==1/0&&(r._endTimers[s._id]=setTimeout(r._ended.bind(r,s),c)),t||setTimeout((function(){r._emit("play",s._id),r._loadQueue()}),0)};"running"===n.state&&"interrupted"!==n.ctx.state?f():(r._playLock=!0,r.once("resume",f),r._clearTimer(s._id))}else{var g=function(){m.currentTime=d,m.muted=s._muted||r._muted||n._muted||m.muted,m.volume=s._volume*n.volume(),m.playbackRate=s._rate;try{var o=m.play();if(o&&"undefined"!=typeof Promise&&(o instanceof Promise||"function"==typeof o.then)?(r._playLock=!0,A(),o.then((function(){r._playLock=!1,m._unlocked=!0,t?r._loadQueue():r._emit("play",s._id)})).catch((function(){r._playLock=!1,r._emit("playerror",s._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),s._ended=!0,s._paused=!0}))):t||(r._playLock=!1,A(),r._emit("play",s._id)),m.playbackRate=s._rate,m.paused)return void r._emit("playerror",s._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||s._loop?r._endTimers[s._id]=setTimeout(r._ended.bind(r,s),c):(r._endTimers[s._id]=function(){r._ended(s),m.removeEventListener("ended",r._endTimers[s._id],!1)},m.addEventListener("ended",r._endTimers[s._id],!1))}catch(e){r._emit("playerror",s._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===m.src&&(m.src=r._src,m.load());var p=window&&window.ejecta||!m.readyState&&n._navigator.isCocoonJS;if(m.readyState>=3||p)g();else{r._playLock=!0,r._state="loading";var E=function(){r._state="loaded",g(),m.removeEventListener(n._canPlayEvent,E,!1)};m.addEventListener(n._canPlayEvent,E,!1),r._clearTimer(s._id)}}return s._id}r._ended(s)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var n=t._getSoundIds(e),r=0;r=0?t=parseInt(i[0],10):e=parseFloat(i[0])}else i.length>=2&&(e=parseFloat(i[0]),t=parseInt(i[1],10));if(!(void 0!==e&&e>=0&&e<=1))return(r=t?o._soundById(t):o._sounds[0])?r._volume:0;if("loaded"!==o._state||o._playLock)return o._queue.push({event:"volume",action:function(){o.volume.apply(o,i)}}),o;void 0===t&&(o._volume=e),t=o._getSoundIds(t);for(var _=0;_0?r/d:r),c=Date.now();e._fadeTo=n,e._interval=setInterval((function(){var o=(Date.now()-c)/r;c=Date.now(),s+=_*o,s=Math.round(100*s)/100,s=_<0?Math.max(n,s):Math.min(n,s),a._webAudio?e._volume=s:a.volume(s,e._id,!0),i&&(a._volume=s),(nt&&s>=n)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,a.volume(n,e._id),a._emit("fade",e._id))}),u)},_stopFade:function(e){var t=this,r=t._soundById(e);return r&&r._interval&&(t._webAudio&&r._node.gain.cancelScheduledValues(n.ctx.currentTime),clearInterval(r._interval),r._interval=null,t.volume(r._fadeTo,e),r._fadeTo=null,t._emit("fade",e)),t},loop:function(){var e,t,n,r=this,o=arguments;if(0===o.length)return r._loop;if(1===o.length){if("boolean"!=typeof o[0])return!!(n=r._soundById(parseInt(o[0],10)))&&n._loop;e=o[0],r._loop=e}else 2===o.length&&(e=o[0],t=parseInt(o[1],10));for(var i=r._getSoundIds(t),a=0;a=0?t=parseInt(i[0],10):e=parseFloat(i[0])}else 2===i.length&&(e=parseFloat(i[0]),t=parseInt(i[1],10));if("number"!=typeof e)return(r=o._soundById(t))?r._rate:o._rate;if("loaded"!==o._state||o._playLock)return o._queue.push({event:"rate",action:function(){o.rate.apply(o,i)}}),o;void 0===t&&(o._rate=e),t=o._getSoundIds(t);for(var _=0;_=0?t=parseInt(o[0],10):r._sounds.length&&(t=r._sounds[0]._id,e=parseFloat(o[0]))}else 2===o.length&&(e=parseFloat(o[0]),t=parseInt(o[1],10));if(void 0===t)return 0;if("number"==typeof e&&("loaded"!==r._state||r._playLock))return r._queue.push({event:"seek",action:function(){r.seek.apply(r,o)}}),r;var s=r._soundById(t);if(s){if(!("number"==typeof e&&e>=0)){if(r._webAudio){var _=r.playing(t)?n.ctx.currentTime-s._playStart:0,d=s._rateSeek?s._rateSeek-s._seek:0;return s._seek+(d+_*Math.abs(s._rate))}return s._node.currentTime}var u=r.playing(t);u&&r.pause(t,!0),s._seek=e,s._ended=!1,r._clearTimer(t),r._webAudio||!s._node||isNaN(s._node.duration)||(s._node.currentTime=e);var c=function(){u&&r.play(t,!0),r._emit("seek",t)};if(u&&!r._webAudio){var l=function(){r._playLock?setTimeout(l,0):c()};setTimeout(l,0)}else c()}return r},playing:function(e){var t=this;if("number"==typeof e){var n=t._soundById(e);return!!n&&!n._paused}for(var r=0;r=0&&n._howls.splice(o,1);var a=!0;for(r=0;r=0){a=!1;break}return i&&a&&delete i[e._src],n.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,n,r){var o=this["_on"+e];return"function"==typeof t&&o.push(r?{id:n,fn:t,once:r}:{id:n,fn:t}),this},off:function(e,t,n){var r=this,o=r["_on"+e],i=0;if("number"==typeof t&&(n=t,t=null),t||n)for(i=0;i=0;i--)o[i].id&&o[i].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,n)}.bind(r,o[i].fn),0),o[i].once&&r.off(e,o[i].fn,o[i].id));return r._loadQueue(e),r},_loadQueue:function(e){var t=this;if(t._queue.length>0){var n=t._queue[0];n.event===e&&(t._queue.shift(),t._loadQueue()),e||n.action()}return t},_ended:function(e){var t=this,r=e._sprite;if(!t._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;r--){if(n<=t)return;e._sounds[r]._ended&&(e._webAudio&&e._sounds[r]._node&&e._sounds[r]._node.disconnect(0),e._sounds.splice(r,1),n--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],n=0;n=0;if(!e.bufferSource)return this;if(n._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))try{e.bufferSource.buffer=n._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(n._navigator&&n._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var o=function(e){this._parent=e,this.init()};o.prototype={init:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++n._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,r=n._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=void 0===n.ctx.createGain?n.ctx.createGainNode():n.ctx.createGain(),e._node.gain.setValueAtTime(r,n.ctx.currentTime),e._node.paused=!0,e._node.connect(n.masterGain)):n.noAudio||(e._node=n._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(n._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=t._src,e._node.preload=!0===t._preload?"auto":t._preload,e._node.volume=r*n.volume(),e._node.load()),e},reset:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++n._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,t=e._parent;t._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(t._sprite).length&&(t._sprite={__default:[0,1e3*t._duration]}),"loaded"!==t._state&&(t._state="loaded",t._emit("load"),t._loadQueue()),e._node.removeEventListener(n._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var i={},a=function(e){var t=e._src;if(i[t])return e._duration=i[t].duration,void d(e);if(/^data:[^;]+;base64,/.test(t)){for(var n=atob(t.split(",")[1]),r=new Uint8Array(n.length),o=0;o0?(i[t._src]=e,d(t,e)):r()};"undefined"!=typeof Promise&&1===n.ctx.decodeAudioData.length?n.ctx.decodeAudioData(e).then(o).catch(r):n.ctx.decodeAudioData(e,o,r)},d=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},u=function(){if(n.usingWebAudio){try{"undefined"!=typeof AudioContext?n.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?n.ctx=new webkitAudioContext:n.usingWebAudio=!1}catch(e){n.usingWebAudio=!1}n.ctx||(n.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(n._navigator&&n._navigator.platform),t=n._navigator&&n._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),r=t?parseInt(t[1],10):null;if(e&&r&&r<9){var o=/safari/.test(n._navigator&&n._navigator.userAgent.toLowerCase());n._navigator&&!o&&(n.usingWebAudio=!1)}n.usingWebAudio&&(n.masterGain=void 0===n.ctx.createGain?n.ctx.createGainNode():n.ctx.createGain(),n.masterGain.gain.setValueAtTime(n._muted?0:n._volume,n.ctx.currentTime),n.masterGain.connect(n.ctx.destination)),n._setup()}};!function(e,t,n,r){var o;e.prototype._pos=[0,0,0],e.prototype._orientation=[0,0,-1,0,1,0],e.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var n=t._howls.length-1;n>=0;n--)t._howls[n].stereo(e);return t},e.prototype.pos=function(e,n,r){var o=this;return o.ctx&&o.ctx.listener?(n="number"!=typeof n?o._pos[1]:n,r="number"!=typeof r?o._pos[2]:r,"number"!=typeof e?o._pos:(o._pos=[e,n,r],void 0!==o.ctx.listener.positionX?(o.ctx.listener.positionX.setTargetAtTime(o._pos[0],t.ctx.currentTime,.1),o.ctx.listener.positionY.setTargetAtTime(o._pos[1],t.ctx.currentTime,.1),o.ctx.listener.positionZ.setTargetAtTime(o._pos[2],t.ctx.currentTime,.1)):o.ctx.listener.setPosition(o._pos[0],o._pos[1],o._pos[2]),o)):o},e.prototype.orientation=function(e,n,r,o,i,a){var s=this;if(!s.ctx||!s.ctx.listener)return s;var _=s._orientation;return n="number"!=typeof n?_[1]:n,r="number"!=typeof r?_[2]:r,o="number"!=typeof o?_[3]:o,i="number"!=typeof i?_[4]:i,a="number"!=typeof a?_[5]:a,"number"!=typeof e?_:(s._orientation=[e,n,r,o,i,a],void 0!==s.ctx.listener.forwardX?(s.ctx.listener.forwardX.setTargetAtTime(e,t.ctx.currentTime,.1),s.ctx.listener.forwardY.setTargetAtTime(n,t.ctx.currentTime,.1),s.ctx.listener.forwardZ.setTargetAtTime(r,t.ctx.currentTime,.1),s.ctx.listener.upX.setTargetAtTime(o,t.ctx.currentTime,.1),s.ctx.listener.upY.setTargetAtTime(i,t.ctx.currentTime,.1),s.ctx.listener.upZ.setTargetAtTime(a,t.ctx.currentTime,.1)):s.ctx.listener.setOrientation(e,n,r,o,i,a),s)},n.prototype.init=(o=n.prototype.init,function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],o.call(this,e)}),n.prototype.stereo=function(e,n){var r=this;if(!r._webAudio)return r;if("loaded"!==r._state)return r._queue.push({event:"stereo",action:function(){r.stereo(e,n)}}),r;var o=void 0===t.ctx.createStereoPanner?"spatial":"stereo";if(void 0===n){if("number"!=typeof e)return r._stereo;r._stereo=e,r._pos=[e,0,0]}for(var a=r._getSoundIds(n),s=0;s{let e=!1;if(E)try{(await m.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===f.browser&&f.version>66||"Safari"===f.browser&&f.version>13||"OPR"===f.browser&&f.version>43||"Edge"===f.browser&&f.version;const I=(()=>{if(!c&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),T=" is not allowed to change after `createInstance` or `loadWasm` is called.",D=!c&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",S=!c&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",C=e=>{if(null==e)e=[];else{e=e instanceof Array?[...e]:[e];for(let t=0;te&&"object"==typeof e&&"function"==typeof e.then;const w="iPhone"==f.OS||"Android"==f.OS||"HarmonyOS"==f.OS?2048:4096;class b{constructor(){this._instanceID=void 0,this._ifSaveOriginalImageInACanvas=!1,this.oriCanvas=null,this.oriCanvasData=null,this.canvas=null,this.bFilterRegionInJs=!1,this._region=null,this._timeStartDecode=null,this._timeEnterInnerDBR=null,this._timeGetMessage=null,this.decodeRecords={},this.bDestroyed=!1,this._lastErrorCode=0,this._lastErrorString="",this._lastInnerDecodeDuration=0,this.intervalTime=0,this._intervalGetVideoFrame=0,this.array_getFrameTimeCost=[],this.array_decodeFrameTimeCost=[],this._indexCurrentDecodingFrame=0,this._bPauseScan=!1,this._intervalDetectVideoPause=1e3,this._soundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",this.beepSound=new r({src:["data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV"],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.captureAndDecodeInParallel=!0,this.barcodeFillStyle="rgba(254,180,32,0.3)",this.barcodeStrokeStyle="rgba(254,180,32,0.9)",this.barcodeLineWidth=1,this._dce=null,this._imgSource=null,this._maxCvsSideLength=w,this._tempSolutionStatus="closed"}static get version(){return this._version}static get license(){return this._license}static set license(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`license`"+T);n._license=t})(b,e)}static get productKeys(){return this._license}static set productKeys(e){b.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){b.license=e}static get organizationID(){return this._license}static set organizationID(e){b.license=e}static set sessionPassword(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`sessionPassword`"+T);n._sessionPassword=t})(b,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:g,worker:p,getUserMedia:E,camera:await R(),browser:f.browser,version:f.version,OS:f.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(e){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");b._engineResourcePath=(e=>{if(null==e&&(e="./"),!c){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`licenseServer`"+T);n._licenseServer=C(t)})(b,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+T);n._deviceFriendlyName=t||""})(b,e)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(e){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");b.__bUseFullFeature=e}static isImageSource(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"getImage"in e}static isDSImage(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("width"in e&&("height"in e&&"pixelFormat"in e)))}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("region"in e&&("sx"in e&&("sy"in e&&("width"in e&&("height"in e&&("colorMode"in e&&("timeSpent"in e&&("timeStamp"in e&&("isCropped"in e&&("toCanvas"in e&&("_sWidth"in e&&("_sHeight"in e&&"_bUseWebGL"in e)))))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(e){this._region=e,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var e;return null===(e=b._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",b.engineResourcePath)}static set defaultUIElementURL(e){b._defaultUIElementURL=e}static _fireHTTPSWarnning(){b.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{b.onWarning&&b.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new r({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(e){this.bPlaySoundOnSuccessfulRead="never"!==e&&e}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(e){this.bVibrateOnSuccessfulRead="never"!==e&&e}set dce(e){this._dce=e}get dce(){return!this._dce||this._dce.isDisposed?null:this._dce}set maxCvsSideLength(e){this._maxCvsSideLength=e,this._dceControler&&this._dceControler.setDisiredValue(this,"maxCvsSideLength",e)}get maxCvsSideLength(){return this._maxCvsSideLength}async _registerDCEControler(){if(!this.dce)return;b._onLog&&b._onLog("_registerDCEControler()");const e=this.dce;this._dceControler=e._createControler();const t=this._dceControler;t.register(this),t.setDisiredValue(this,"refreshInterval",200),t.setDisiredValue(this,"maxCvsSideLength",this._maxCvsSideLength);try{ResizeObserver}catch(e){"ReferenceError"===e.name&&window&&(window.ResizeObserver=void 0)}const n=e.getUIElement(),r=this.dce.constructor;if("@engineResourcePath/dce.ui.html"===r._defaultUIElementURL)try{n?n===t._innerSetUI&&(await e.setUIElement(`${r.engineResourcePath}dce.ui.html`),t._innerSetUI=e.getUIElement()):(await e.setUIElement(`${r.engineResourcePath}dbr.ui.html`),t._innerSetUI=e.getUIElement())}catch(t){await e.setUIElement(r.defaultUIElementURL)}else n||await e.setUIElement(r.defaultUIElementURL);this.callbackCameraChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async e=>{let t=await this._decode_DCEFrame(e,{bCopyData:!1});if(await this.clearMapDecodeRecord(),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(t);this.onImageRead(e)}if(this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e));const{sx:n,sy:r,width:o,height:i,_sWidth:a,_sHeight:s}=e;b.recalculateResultLocation(t,n,r,a,s,o,i),this._drawResults(t)},e.on("cameraChange",this.callbackCameraChange),e.on("resolutionChange",this.callbackResolutionChange),e.on("cameraClose",this.callbackCameraClose),e.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}_logoutDCEControler(){this.dce&&this._dceControler&&(b._onLog&&b._onLog("_logoutDCEControler()"),this._dceControler.logout(this),this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this._dceControler=null,this.dce=null)}async setImageSource(e,t){if(null==e)return this._imgSource=null,this._logoutDCEControler(),void(this._drawingItemNamespace=null);if(e&&e.isCameraEnhancer)this.dce=e,await this._registerDCEControler(),this._imgSource=null;else{if(!b.isImageSource(e))throw new Error("Invalid value.");this._logoutDCEControler(),this._imgSource=e}t&&t.resultsHighlightBaseShapes&&(this._drawingItemNamespace=t.resultsHighlightBaseShapes)}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:e,l:t,ls:n,sp:r,rmk:o}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,n,r=t._license||"",o=JSON.parse(JSON.stringify(t._licenseServer)),i=t._sessionPassword,a=0;if(r.startsWith("t")||r.startsWith("f"))a=0;else if(0===r.length||r.startsWith("P")||r.startsWith("L")||r.startsWith("Y")||r.startsWith("A"))a=1;else{a=2;const t=r.indexOf(":");if(-1!=t&&(r=r.substring(t+1)),r.startsWith("DLS2")){let t=r.substring(4);try{t=atob(t)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}const n=JSON.parse(t);if(r=n.handshakeCode?n.handshakeCode:n.organizationID?n.organizationID:"","number"==typeof r&&(r=JSON.stringify(r)),0===o.length){let e=[];n.mainServerURL&&(e[0]=n.mainServerURL),n.standbyServerURL&&(e[1]=n.standbyServerURL),o=C(e)}!i&&n.sessionPassword&&(i=n.sessionPassword),e=n.remark}("200001"===r||r.startsWith("200001-"))&&(o&&o.length||(r="")),r||(a=1)}if(a&&(globalThis.crypto||(n="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(n="Require https to use online key in this browser.")),n){if(1!==a)throw new Error(n);a=0,console.warn(n),t._lastErrorCode=-1,t._lastErrorString=n}return 1===a&&(r="",console.warn("Applying for a public trial license ...")),{lt:a,l:r,ls:o,sp:i,rmk:e}}throw new Error("Can't preprocess license again"+T)})(b);this._pLoad.task=async(i,a)=>{let s=b.engineResourcePath+b._workerName;b.engineResourcePath.startsWith(location.origin)||(s=await fetch(s).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),b._dbrWorker=new Worker(s),b._dbrWorker.onerror=e=>{let t=new Error(e.message);a(t)},b._dbrWorker.onmessage=async t=>{let n=t.data?t.data:t;switch(n.type){case"log":b._onLog&&b._onLog(n.message);break;case"load":{n.message&&(n.message=n.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,r=!1;1===e&&(r=!0),n.success?(b._dbrWorker.onerror=null,b._version=n.version+"(JS "+b._jsVersion+"."+b._jsEditVersion+")",b._onLog&&b._onLog("load dbr worker success"),n.message&&console.warn(n.message)):(t=new Error(n.message),t.stack=n.stack+"\n"+t.stack,r||111==n.ltsErrorCode&&-1!=n.message.toLowerCase().indexOf("trial license")&&(r=!0)),r&&b.showDialog(n.success?"warn":"error",n.message),n.success?i():a(t);break}case"task":{let e=n.id,t=n.body;try{b._taskCallbackMap.get(e)(t),b._taskCallbackMap.delete(e)}catch(t){throw b._taskCallbackMap.delete(e),t}break}default:b._onLog&&b._onLog(t)}},b._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:b.engineResourcePath,bUseFullFeature:b._bUseFullFeature,bd:b._bWasmDebug,v:b._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:f,fn:b.deviceFriendlyName,ls:n,sp:r,rmk:o})}}await this._pLoad}static async showDialog(e,t){await(async(e,t,n)=>{if(!e._bNeverShowDialog)try{let r=await fetch(e.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let o=await r.text();if(!o.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let i=document.createElement("div");i.innerHTML=o;let a=[];for(let e=0;e{if(e==t.target){s.remove();for(let e of a)e.remove()}}));else if(!d&&e.classList.contains("dls-license-icon-close"))d=e,e.addEventListener("click",(()=>{s.remove();for(let e of a)e.remove()}));else if(!u&&e.classList.contains("dls-license-icon-error"))u=e,"error"!=t&&e.remove();else if(!c&&e.classList.contains("dls-license-icon-warn"))c=e,"warn"!=t&&e.remove();else if(!l&&e.classList.contains("dls-license-msg-content")){l=e;let t=n;for(;t;){let n=t.indexOf("["),r=t.indexOf("]",n),o=t.indexOf("(",r),i=t.indexOf(")",o);if(-1==n||-1==r||-1==o||-1==i){e.appendChild(new Text(t));break}n>0&&e.appendChild(new Text(t.substring(0,n)));let a=document.createElement("a"),s=t.substring(n+1,r);a.innerText=s;let _=t.substring(o+1,i);a.setAttribute("href",_),a.setAttribute("target","_blank"),e.appendChild(a),t=t.substring(i+1)}}document.body.appendChild(s)}catch(t){e._onLog&&e._onLog(t.message||t)}})(this,e,t)}static async createInstanceInWorker(e=!1){return await b.loadWasm(),await new Promise(((t,n)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(e=>{if(e.success)return t(e.instanceID);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),b._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}static async createInstance(){let e=new b;return e._instanceID=await b.createInstanceInWorker(),b._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),b._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:n,instanceID:this._instanceID})}))}async decode(e){b._onLog&&b._onLog("decode(source: any)"),b._onLog&&(this._timeStartDecode=Date.now());{let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),e instanceof Blob?await this._decode_Blob(e,t):e instanceof ArrayBuffer?await this._decode_ArrayBuffer(e,t):e instanceof Uint8Array||e instanceof Uint8ClampedArray?await this._decode_Uint8Array(e,t):e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?await this._decode_Image(e,t):e instanceof HTMLCanvasElement?await this._decode_Canvas(e,t):e instanceof HTMLVideoElement?await this._decode_Video(e,t):"string"==typeof e?"data:image/"==e.substring(0,11)?await this._decode_Base64(e,t):await this._decode_Url(e,t):b.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):b.isDSImage(e)?(t.bCopyData=!0,await this._decode_DSImage(e,t)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(e,t)}async decodeUrl(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(e,t)}async _decodeBuffer_Uint8Array(e,t,n,r,o,i){return await new Promise(((a,s)=>{let _=b._nextTaskID++;b._taskCallbackMap.set(_,(e=>{if(e.success){let t,n=b._onLog?Date.now():0;b._onLog&&b._onLog("worker return result: "+n),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return s(e)}if(b._onLog){let e=Date.now();b._onLog("DBR time get result: "+n),b._onLog("Handle image cost: "+(this._timeEnterInnerDBR-this._timeStartDecode)),b._onLog("DBR worker decode image cost: "+(n-this._timeEnterInnerDBR)),b._onLog("DBR worker handle results: "+(e-n)),b._onLog("Total decode image cost: "+(e-this._timeStartDecode))}return a(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,s(t)}})),this._timeEnterInnerDBR=Date.now(),b._onLog&&b._onLog("Send buffer to worker:"+this._timeEnterInnerDBR),b._dbrWorker.postMessage({type:"decodeBuffer",id:_,instanceID:this._instanceID,body:{buffer:e,width:t,height:n,stride:r,format:o,config:i}},[e.buffer]),b._onLog&&i&&i.timeStamp&&b._onLog("decode image delay: "+(this._timeEnterInnerDBR-i.timeStamp))}))}async _decodeBuffer_Blob(e,t,n,r,o,i){b._onLog&&b._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const a=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,n)=>{let r=new FileReader;r.readAsArrayBuffer(e),r.onload=()=>{t(r.result)},r.onerror=()=>{n(r.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(a),t,n,r,o,i)}async decodeBuffer(e,t,n,r,o,i){let a;return b._onLog&&b._onLog("decodeBuffer(buffer,width,height,stride,format)"),b._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?a=await this._decodeBuffer_Uint8Array(e,t,n,r,o,i):e instanceof ArrayBuffer?a=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,n,r,o,i):e instanceof Blob&&(a=await this._decodeBuffer_Blob(e,t,n,r,o,i)),a}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,n)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(e=>{if(e.success){let r;this._lastInnerDecodeDuration=e.duration;try{r=this._handleRetJsonString(e.decodeReturn)}catch(e){return n(e)}return t(r)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),b._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success){let t=JSON.parse(n.results);return null!=this.userDefinedRegion&&(t.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),e(t)}{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),b._dbrWorker.postMessage({type:"getRuntimeSettings",id:n,instanceID:this._instanceID})}))}async updateRuntimeSettings(t){let n;if("string"==typeof t)if("speed"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,n.region=e.region,n.deblurLevel=3,n.expectedBarcodesCount=0,n.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,n.region=e.region,n.deblurLevel=5,n.expectedBarcodesCount=512,n.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,n.region=e.region}else if("dense"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,n.region=e.region,n.deblurLevel=9,n.expectedBarcodesCount=0,n.localizationModes=[2,8,0,0,0,0,0,0]}else if("distance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,n.region=e.region,n.deblurLevel=3,n.expectedBarcodesCount=0,n.localizationModes=[2,8,0,0,0,0,0,0]}else n=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(n=JSON.parse(JSON.stringify(t)),n.region instanceof Array){let e=n.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(n.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!b._bUseFullFeature){if(0!=(n.barcodeFormatIds&~(e.EnumBarcodeFormat.BF_ONED|e.EnumBarcodeFormat.BF_QR_CODE|e.EnumBarcodeFormat.BF_PDF417|e.EnumBarcodeFormat.BF_DATAMATRIX))||0!=n.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=n.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let e=n.region;if(e instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(e)),(e.regionLeft||e.regionTop||e.regionRight||e.regionBottom||e.regionMeasuredByPercentage)&&(e.regionLeft||e.regionTop||100!=e.regionRight||100!=e.regionBottom||!e.regionMeasuredByPercentage)?this.region=e:this.region=null,n.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return await new Promise(((e,t)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(n=>{if(n.success){try{this._handleRetJsonString(n.updateReturn)}catch(e){t(e)}return e()}{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),b._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(n)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=w,await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),b._dbrWorker.postMessage({type:"resetRuntimeSettings",id:n,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!b._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success)return e(n.results);{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),b._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:n,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!b._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof e)e=e;else{if("object"!=typeof e)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");e=JSON.stringify(e)}return await new Promise(((t,n)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.initReturn)}catch(e){n(e)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),b._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){b._onLog&&b._onLog("_decode_Blob(blob: Blob)");let n=null,r=null;if("undefined"!=typeof createImageBitmap)try{n=await createImageBitmap(e)}catch(e){}n||(r=await function(e){return new Promise(((t,n)=>{let r=URL.createObjectURL(e),o=new Image;o.dbrObjUrl=r,o.src=r,o.onload=()=>{t(o)},o.onerror=e=>{n(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let o=await this._decode_Image(n||r,t);return n&&n.close(),o}async _decode_ArrayBuffer(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Uint8Array(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Image(e,t){b._onLog&&b._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),t=t||{};let n,r,o=e instanceof HTMLImageElement?e.naturalWidth:e.width,i=e instanceof HTMLImageElement?e.naturalHeight:e.height,a=Math.max(o,i);if(a>this._maxCvsSideLength){let e=this._maxCvsSideLength/a;n=Math.round(o*e),r=Math.round(i*e)}else n=o,r=i;this.canvas||(this.canvas=document.createElement("canvas"));const s=this.canvas;s.width===n&&s.height===r||(s.width=n,s.height=r),s.ctx2d||(s.ctx2d=s.getContext("2d"));return s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._decode_Canvas(s,t)}async _decode_Canvas(t,n){if(b._onLog&&b._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if(0===t.width||0===t.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=t,this.oriCanvasData=null);let r=(t.ctx2d||t.getContext("2d")).getImageData(0,0,t.width,t.height).data;return await this._decodeBuffer_Uint8Array(r,t.width,t.height,4*t.width,e.EnumImagePixelFormat.IPF_ABGR_8888,n)}async _decode_Video(e,t){if(b._onLog&&b._onLog("_decode_Video(video)"),!(e instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";t=t||{};let n,r,o=e.videoWidth,i=e.videoHeight,a=Math.max(o,i);if(a>this._maxCvsSideLength){let e=this._maxCvsSideLength/a;n=Math.round(o*e),r=Math.round(i*e)}else n=o,r=i;this.canvas||(this.canvas=document.createElement("canvas"));const s=this.canvas;s.width===n&&s.height===r||(s.width=n,s.height=r),s.ctx2d||(s.ctx2d=s.getContext("2d"));return s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r),await this._decode_Canvas(s,t)}async _decode_DCEFrame(t,n){if(b._onLog&&b._onLog("_decode_DCEFrame(dceFrame)"),!b.isDCEFrame(t))return[];let r=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{width:o,height:i,colorMode:a,timeStamp:s}=t;let _;_=n&&n.bCopyData?new Uint8Array(t.data):t.data;let d=null;if(n?(d=JSON.parse(JSON.stringify(n)),d.timeStamp=s):d={timeStamp:s},"grey"===a)r=await this._decodeBuffer_Uint8Array(_,o,i,o,e.EnumImagePixelFormat.IPF_GrayScaled,d);else if("rgba"===a)r=await this._decodeBuffer_Uint8Array(_,o,i,4*o,e.EnumImagePixelFormat.IPF_ABGR_8888,d);else{if("bgra"!==a)throw new Error(`Color mode '${a}' is not supported to decode.`);r=await this._decodeBuffer_Uint8Array(_,o,i,4*o,e.EnumImagePixelFormat.IPF_ARGB_8888,d)}return r}async _decode_DSImage(t,n){if(b._onLog&&b._onLog("_decode_DSImage(dsImage)"),!b.isDSImage(t))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat.toLowerCase(),data:new Uint8Array(t.data),toCanvas:function(){const e=document.createElement("canvas");let t;switch(e.width=this.width,e.height=this.height,this.pixelFormat){case"grey":t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{let r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="blob",r.send(),r.onloadend=async()=>{t(r.response)},r.onerror=()=>{n(new Error("Network Error: "+r.statusText))}}));return await this._decode_Blob(n,t)}}async _decode_FilePath(e,t){throw b._onLog&&b._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static recalculateResultLocation(e,t,n,r,o,i,a){if(e.length>0)for(let s of e){let e=s.localizationResult;2==e.resultCoordinateType&&(e.x1*=.01*i,e.x2*=.01*i,e.x3*=.01*i,e.x4*=.01*i,e.y1*=.01*a,e.y2*=.01*a,e.y3*=.01*a,e.y4*=.01*a);let _=i/r,d=a/o;e.x1=e.x1/_+t,e.x2=e.x2/_+t,e.x3=e.x3/_+t,e.x4=e.x4/_+t,e.y1=e.y1/d+n,e.y2=e.y2/d+n,e.y3=e.y3/d+n,e.y4=e.y4/d+n,2==e.resultCoordinateType&&(e.x1*=100/r,e.x2*=100/r,e.x3*=100/r,e.x4*=100/r,e.y1*=100/o,e.y2*=100/o,e.y3*=100/o,e.y4*=100/o)}}static BarcodeReaderException(t,n){let r,o=e.EnumErrorCode.DBR_UNKNOWN;return"number"==typeof t?(o=t,r=new Error(n)):r=new Error(t),r.code=o,r}_handleRetJsonString(t){let n=e.EnumErrorCode;if(t.textResults){for(let e=0;e{let n=t.indexOf(":");e[t.substring(0,n)]=t.substring(n+1)})),n.exception=e}}return t.decodeRecords?this.decodeRecords=t.decodeRecords:this.decodeRecords={},this._lastErrorCode=t.exception,this._lastErrorString=t.description,t.exception&&!b._setWarnnedEx.has(t.description)&&(b._setWarnnedEx.add(t.description),console.warn(t.description)),t.textResults}if(t.exception==n.DBR_SUCCESS)return t.data;throw b.BarcodeReaderException(t.exception,t.description)}async setModeArgument(e,t,n,r){return await new Promise(((o,i)=>{let a=b._nextTaskID++;b._taskCallbackMap.set(a,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return i(e)}return o()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),b._dbrWorker.postMessage({type:"setModeArgument",id:a,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:n,argumentValue:r}})}))}async getModeArgument(e,t,n){return await new Promise(((r,o)=>{let i=b._nextTaskID++;b._taskCallbackMap.set(i,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return o(e)}return r(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,o(t)}})),b._dbrWorker.postMessage({type:"getModeArgument",id:i,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:n}})}))}async getIntermediateResults(){return await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success)return e(n.results);{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),b._dbrWorker.postMessage({type:"getIntermediateResults",id:n,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let t=await this.getIntermediateResults(),n=[];for(let r of t)if(r.dataType==e.EnumIMResultDataType.IMRDT_IMAGE)for(let t of r.results){const r=t.bytes;let o;switch(b._onLog&&b._onLog(" "+r.length+" "+r.byteLength+" "+t.width+" "+t.height+" "+t.stride+" "+t.format),t.format){case e.EnumImagePixelFormat.IPF_ABGR_8888:o=new Uint8ClampedArray(r);break;case e.EnumImagePixelFormat.IPF_RGB_888:{const e=r.length/3;o=new Uint8ClampedArray(4*e);for(let t=0;t{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success){let t=n.results;return t.intervalTime=this.intervalTime,t.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,t.soundOnSuccessfullRead=this.soundSource,t.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,t.vibrateDuration=this.vibrateDuration,t.captureAndDecodeInParallel=this.captureAndDecodeInParallel,e(t)}{let e=new Error(n.message);return e.stack+="\n"+n.stack,t(e)}})),b._dbrWorker.postMessage({type:"getScanSettings",id:n,instanceID:this._instanceID})}))}async updateScanSettings(e){if(!e)return;const t=JSON.parse(JSON.stringify(e));return t.hasOwnProperty("intervalTime")&&(this.intervalTime=Math.max(t.intervalTime,0),delete t.intervalTime),t.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=t.whenToPlaySoundforSuccessfulRead,delete t.whenToPlaySoundforSuccessfulRead),t.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=t.soundOnSuccessfullRead,delete t.soundOnSuccessfullRead),t.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=t.whenToVibrateforSuccessfulRead,delete t.whenToVibrateforSuccessfulRead),t.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=t.vibrateDuration,delete t.vibrateDuration),t.hasOwnProperty("captureAndDecodeInParallel")&&(this.captureAndDecodeInParallel=t.captureAndDecodeInParallel,delete t.captureAndDecodeInParallel),await new Promise(((e,n)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack+="\n"+t.stack,n(e)}})),b._dbrWorker.postMessage({type:"updateScanSettings",id:r,instanceID:this._instanceID,body:{settings:t}})}))}_cloneDecodeResults(e){if(e instanceof Array){let t=[];for(let n of e)t.push(this._cloneDecodeResults(n));return t}{let t=e;return JSON.parse(JSON.stringify(t,((e,t)=>"oriVideoCanvas"==e||"searchRegionCanvas"==e?void 0:t)))}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this._imgSource||this._bPauseScan)return b._onLog&&b._onLog("Scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));b._onLog&&b._onLog("======= once read ======="),b._onLog&&(this._timeStartDecode=Date.now());let e=null,t=null;if(this.dce)e=this._getVideoFrame();else if(this._imgSource&&(t=await this._imgSource.getImage(),!b.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let n=[];if(e){n=await this._decode_DCEFrame(e,{bScanner:!0,bCopyData:!1});let t=null;if(n&&n.length){const{sx:r,sy:o,width:i,height:a,_sWidth:s,_sHeight:_}=e;t=n.map((e=>({localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),b.recalculateResultLocation(t,r,o,s,_,i,a)}this._drawResults(t)}else t&&(n=await this._decode_DSImage(t,{bScanner:!0,bCopyData:!1}));return n})().then((e=>{if(b._onLog&&b._onLog(e),this.dce&&this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost;const n=()=>{let n=0;if(t&&t.length){let r=Math.min(...e),o=Math.max(...t);r&&o&&(n=r-o)}else n=0;return n>0?n:0};(()=>{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=n()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this._imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead)t=!0;else if("unique"===this.bPlaySoundOnSuccessfulRead)for(let n of e)if(0==n.resultsType){t=!0;break}t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead)t=!0;else if("unique"===this.bVibrateOnSuccessfulRead)for(let n of e)if(0==n.resultsType){t=!0;break}if(t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onImageRead){let t=this._cloneDecodeResults(e);for(let e of t)0!=e.resultsType&&1!=e.resultsType||this.onImageRead(t);this.onImageRead(t)}if(this.onUniqueRead)for(let t of e)0==t.resultsType&&this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t))}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),b._onLog&&b._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){if(this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",this._intervalGetVideoFrame),!this.dce.numberOfFramesInBuffer)return this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",0),null;e=this.dce.getFrameFromBuffer();const t=e=>{if(!e)return;let t=e.timeSpent,n=this.array_getFrameTimeCost;for(;n.length>=5;)n.shift();n.push(t)};t(e)}else this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),e=this.dce.getFrame();return e}_drawResults(e){if(!this.dce||this._bPauseScan||!this._drawingItemNamespace||!this._drawingItemNamespace.DT_Polygon)return;if(!this._dbrDrawingLayer){if(!this.dce.isOpen())return;this._dbrDrawingLayer=this.dce.getDrawingLayer(3)}const t=this._dbrDrawingLayer;if(t.clearDrawingItems(),e&&e.length)for(let n of e){const e=n.localizationResult,r=new this._drawingItemNamespace.DT_Polygon([{x:e.x1,y:e.y1},{x:e.x2,y:e.y2},{x:e.x3,y:e.y3},{x:e.x4,y:e.y4}]);t.addDrawingItem(r)}}async startScanning(e){if(!this.dce&&!this._imgSource)throw new Error("'imageSource' is not set. call 'setImageSource()' before 'startScanning()'.");if("closed"!=this._tempSolutionStatus)return;if(this._tempSolutionStatus="opening","opening"!=this._tempSolutionStatus)return;let t=null;return this.dce&&(this.dce.isOpen()?(e&&this.dce.appendAndShowUI(),t=JSON.parse(JSON.stringify(this.dce.playCallbackInfo))):t=await this.dce.open(e),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"close"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())),"opening"==this._tempSolutionStatus?(this._bPauseScan=!1,this.dce&&this.dce.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),0)),this._tempSolutionStatus="opened",this.keepAlive(),t):void 0}stopScanning(e){this.dce&&(this._drawResults(null),this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"close",e))),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._tempSolutionStatus="closed"}pauseScanning(e){if(e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"stopFetchingLoop"))}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.startFetchingLoop(),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(b._onLog&&b._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,(this.dce||"opening"===this._tempSolutionStatus)&&this.stopScanning(),this.setImageSource(null);let e=b._nextTaskID++;b._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),b._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}var B,N,P,F,V,x,k,U,G,H,K,W,Y,Q,J,X,Z,j,q,$,z,ee,te,ne,re,oe,ie;b._jsVersion="9.2.11",b._jsEditVersion="20220727",b._version=`loading...(JS ${b._jsVersion}.${b._jsEditVersion})`,b._license=D,b._sessionPassword=S,b.browserInfo=f,b._workerName=`dbr-${b._jsVersion}.browser.worker.js`,b._engineResourcePath=I,b._licenseServer=[],b._deviceFriendlyName="",b._isShowRelDecodeTimeInResults=!1,b._bWasmDebug=!1,b._bNeverShowDialog=!1,b.__bUseFullFeature=!0,b._nextTaskID=0,b._taskCallbackMap=new Map,b._pLoad=new class extends Promise{constructor(e){let t,n;super(((e,r)=>{t=e,n=r})),this._s="pending",this.resolve=e=>{this.isPending&&(L(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",n(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,L(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const n=await t;e===this._task&&this.resolve(n)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}},b._lastErrorCode=0,b._lastErrorString="",b._setWarnnedEx=new Set,b._defaultUIElementURL="@engineResourcePath/dbr.ui.html",e.EnumBarcodeColourMode=void 0,(B=e.EnumBarcodeColourMode||(e.EnumBarcodeColourMode={}))[B.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",B[B.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",B[B.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",B[B.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",B[B.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",B[B.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",B[B.BICM_SKIP=0]="BICM_SKIP",B[B.BICM_REV=2147483648]="BICM_REV",e.EnumBarcodeComplementMode=void 0,(N=e.EnumBarcodeComplementMode||(e.EnumBarcodeComplementMode={}))[N.BCM_AUTO=1]="BCM_AUTO",N[N.BCM_GENERAL=2]="BCM_GENERAL",N[N.BCM_SKIP=0]="BCM_SKIP",N[N.BCM_REV=2147483648]="BCM_REV",e.EnumBarcodeFormat_2=void 0,(P=e.EnumBarcodeFormat_2||(e.EnumBarcodeFormat_2={}))[P.BF2_NULL=0]="BF2_NULL",P[P.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",P[P.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",P[P.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",P[P.BF2_POSTNET=2097152]="BF2_POSTNET",P[P.BF2_PLANET=4194304]="BF2_PLANET",P[P.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",P[P.BF2_RM4SCC=16777216]="BF2_RM4SCC",P[P.BF2_DOTCODE=2]="BF2_DOTCODE",P[P.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",P[P.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",P[P.BF2_PHARMACODE=12]="BF2_PHARMACODE",e.EnumBinarizationMode=void 0,(F=e.EnumBinarizationMode||(e.EnumBinarizationMode={}))[F.BM_AUTO=1]="BM_AUTO",F[F.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",F[F.BM_SKIP=0]="BM_SKIP",F[F.BM_THRESHOLD=4]="BM_THRESHOLD",F[F.BM_REV=2147483648]="BM_REV",e.EnumClarityCalculationMethod=void 0,(V=e.EnumClarityCalculationMethod||(e.EnumClarityCalculationMethod={}))[V.ECCM_CONTRAST=1]="ECCM_CONTRAST",e.EnumClarityFilterMode=void 0,(x=e.EnumClarityFilterMode||(e.EnumClarityFilterMode={}))[x.CFM_GENERAL=1]="CFM_GENERAL",e.EnumColourClusteringMode=void 0,(k=e.EnumColourClusteringMode||(e.EnumColourClusteringMode={}))[k.CCM_AUTO=1]="CCM_AUTO",k[k.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",k[k.CCM_SKIP=0]="CCM_SKIP",k[k.CCM_REV=2147483648]="CCM_REV",e.EnumColourConversionMode=void 0,(U=e.EnumColourConversionMode||(e.EnumColourConversionMode={}))[U.CICM_GENERAL=1]="CICM_GENERAL",U[U.CICM_SKIP=0]="CICM_SKIP",U[U.CICM_REV=2147483648]="CICM_REV",e.EnumConflictMode=void 0,(G=e.EnumConflictMode||(e.EnumConflictMode={}))[G.CM_IGNORE=1]="CM_IGNORE",G[G.CM_OVERWRITE=2]="CM_OVERWRITE",e.EnumDeblurMode=void 0,(H=e.EnumDeblurMode||(e.EnumDeblurMode={}))[H.DM_SKIP=0]="DM_SKIP",H[H.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",H[H.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",H[H.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",H[H.DM_SMOOTHING=8]="DM_SMOOTHING",H[H.DM_MORPHING=16]="DM_MORPHING",H[H.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",H[H.DM_SHARPENING=64]="DM_SHARPENING",H[H.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",H[H.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",e.EnumDeformationResistingMode=void 0,(K=e.EnumDeformationResistingMode||(e.EnumDeformationResistingMode={}))[K.DRM_AUTO=1]="DRM_AUTO",K[K.DRM_GENERAL=2]="DRM_GENERAL",K[K.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",K[K.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",K[K.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",K[K.DRM_SKIP=0]="DRM_SKIP",K[K.DRM_REV=2147483648]="DRM_REV",e.EnumDPMCodeReadingMode=void 0,(W=e.EnumDPMCodeReadingMode||(e.EnumDPMCodeReadingMode={}))[W.DPMCRM_AUTO=1]="DPMCRM_AUTO",W[W.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",W[W.DPMCRM_SKIP=0]="DPMCRM_SKIP",W[W.DPMCRM_REV=2147483648]="DPMCRM_REV",e.EnumGrayscaleTransformationMode=void 0,(Y=e.EnumGrayscaleTransformationMode||(e.EnumGrayscaleTransformationMode={}))[Y.GTM_INVERTED=1]="GTM_INVERTED",Y[Y.GTM_ORIGINAL=2]="GTM_ORIGINAL",Y[Y.GTM_SKIP=0]="GTM_SKIP",Y[Y.GTM_REV=2147483648]="GTM_REV",e.EnumImagePreprocessingMode=void 0,(Q=e.EnumImagePreprocessingMode||(e.EnumImagePreprocessingMode={}))[Q.IPM_AUTO=1]="IPM_AUTO",Q[Q.IPM_GENERAL=2]="IPM_GENERAL",Q[Q.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",Q[Q.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",Q[Q.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",Q[Q.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",Q[Q.IPM_SKIP=0]="IPM_SKIP",Q[Q.IPM_REV=2147483648]="IPM_REV",e.EnumIntermediateResultSavingMode=void 0,(J=e.EnumIntermediateResultSavingMode||(e.EnumIntermediateResultSavingMode={}))[J.IRSM_MEMORY=1]="IRSM_MEMORY",J[J.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",J[J.IRSM_BOTH=4]="IRSM_BOTH",e.EnumIntermediateResultType=void 0,(X=e.EnumIntermediateResultType||(e.EnumIntermediateResultType={}))[X.IRT_NO_RESULT=0]="IRT_NO_RESULT",X[X.IRT_ORIGINAL_IMAGE=1]="IRT_ORIGINAL_IMAGE",X[X.IRT_COLOUR_CLUSTERED_IMAGE=2]="IRT_COLOUR_CLUSTERED_IMAGE",X[X.IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE=4]="IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE",X[X.IRT_TRANSFORMED_GRAYSCALE_IMAGE=8]="IRT_TRANSFORMED_GRAYSCALE_IMAGE",X[X.IRT_PREDETECTED_REGION=16]="IRT_PREDETECTED_REGION",X[X.IRT_PREPROCESSED_IMAGE=32]="IRT_PREPROCESSED_IMAGE",X[X.IRT_BINARIZED_IMAGE=64]="IRT_BINARIZED_IMAGE",X[X.IRT_TEXT_ZONE=128]="IRT_TEXT_ZONE",X[X.IRT_CONTOUR=256]="IRT_CONTOUR",X[X.IRT_LINE_SEGMENT=512]="IRT_LINE_SEGMENT",X[X.IRT_FORM=1024]="IRT_FORM",X[X.IRT_SEGMENTATION_BLOCK=2048]="IRT_SEGMENTATION_BLOCK",X[X.IRT_TYPED_BARCODE_ZONE=4096]="IRT_TYPED_BARCODE_ZONE",X[X.IRT_PREDETECTED_QUADRILATERAL=8192]="IRT_PREDETECTED_QUADRILATERAL",e.EnumLocalizationMode=void 0,(Z=e.EnumLocalizationMode||(e.EnumLocalizationMode={}))[Z.LM_SKIP=0]="LM_SKIP",Z[Z.LM_AUTO=1]="LM_AUTO",Z[Z.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",Z[Z.LM_LINES=8]="LM_LINES",Z[Z.LM_STATISTICS=4]="LM_STATISTICS",Z[Z.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",Z[Z.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",Z[Z.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",Z[Z.LM_CENTRE=128]="LM_CENTRE",Z[Z.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",Z[Z.LM_REV=2147483648]="LM_REV",e.EnumPDFReadingMode=void 0,(j=e.EnumPDFReadingMode||(e.EnumPDFReadingMode={}))[j.PDFRM_RASTER=1]="PDFRM_RASTER",j[j.PDFRM_AUTO=2]="PDFRM_AUTO",j[j.PDFRM_VECTOR=4]="PDFRM_VECTOR",j[j.PDFRM_REV=2147483648]="PDFRM_REV",e.EnumQRCodeErrorCorrectionLevel=void 0,(q=e.EnumQRCodeErrorCorrectionLevel||(e.EnumQRCodeErrorCorrectionLevel={}))[q.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",q[q.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",q[q.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",q[q.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q",e.EnumRegionPredetectionMode=void 0,($=e.EnumRegionPredetectionMode||(e.EnumRegionPredetectionMode={}))[$.RPM_AUTO=1]="RPM_AUTO",$[$.RPM_GENERAL=2]="RPM_GENERAL",$[$.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",$[$.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",$[$.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",$[$.RPM_SKIP=0]="RPM_SKIP",$[$.RPM_REV=2147483648]="RPM_REV",e.EnumResultCoordinateType=void 0,(z=e.EnumResultCoordinateType||(e.EnumResultCoordinateType={}))[z.RCT_PIXEL=1]="RCT_PIXEL",z[z.RCT_PERCENTAGE=2]="RCT_PERCENTAGE",e.EnumResultType=void 0,(ee=e.EnumResultType||(e.EnumResultType={}))[ee.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",ee[ee.RT_RAW_TEXT=1]="RT_RAW_TEXT",ee[ee.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",ee[ee.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT",e.EnumScaleUpMode=void 0,(te=e.EnumScaleUpMode||(e.EnumScaleUpMode={}))[te.SUM_AUTO=1]="SUM_AUTO",te[te.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",te[te.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",te[te.SUM_SKIP=0]="SUM_SKIP",te[te.SUM_REV=2147483648]="SUM_REV",e.EnumTerminatePhase=void 0,(ne=e.EnumTerminatePhase||(e.EnumTerminatePhase={}))[ne.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",ne[ne.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",ne[ne.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",ne[ne.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",ne[ne.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",ne[ne.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED",e.EnumTextFilterMode=void 0,(re=e.EnumTextFilterMode||(e.EnumTextFilterMode={}))[re.TFM_AUTO=1]="TFM_AUTO",re[re.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",re[re.TFM_SKIP=0]="TFM_SKIP",re[re.TFM_REV=2147483648]="TFM_REV",e.EnumTextResultOrderMode=void 0,(oe=e.EnumTextResultOrderMode||(e.EnumTextResultOrderMode={}))[oe.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",oe[oe.TROM_POSITION=2]="TROM_POSITION",oe[oe.TROM_FORMAT=4]="TROM_FORMAT",oe[oe.TROM_SKIP=0]="TROM_SKIP",oe[oe.TROM_REV=2147483648]="TROM_REV",e.EnumTextureDetectionMode=void 0,(ie=e.EnumTextureDetectionMode||(e.EnumTextureDetectionMode={}))[ie.TDM_AUTO=1]="TDM_AUTO",ie[ie.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",ie[ie.TDM_SKIP=0]="TDM_SKIP",ie[ie.TDM_REV=2147483648]="TDM_REV",e.BarcodeReader=b,Object.defineProperty(e,"__esModule",{value:!0})})); diff --git a/dist/dbr.pure.mjs b/dist/dbr.pure.mjs new file mode 100644 index 0000000..73a145a --- /dev/null +++ b/dist/dbr.pure.mjs @@ -0,0 +1,11 @@ +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft Barcode Reader JS Edition + * @website http://www.dynamsoft.com + * @copyright Copyright 2022, Dynamsoft Corporation + * @author Dynamsoft + * @version 9.2.11 (js 20220727) + * @fileoverview Dynamsoft JavaScript Library for Barcode Reader + * More info on DBR JS: https://www.dynamsoft.com/barcode-reader/sdk-javascript/ + */ +var e=function(){this.init()};e.prototype={init:function(){var e=this||t;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var n=this||t;if(e=parseFloat(e),n.ctx||d(),void 0!==e&&e>=0&&e<=1){if(n._volume=e,n._muted)return n;n.usingWebAudio&&n.masterGain.gain.setValueAtTime(e,t.ctx.currentTime);for(var r=0;r=0;n--)e._howls[n].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,d()),e},codecs:function(e){return(this||t)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||t;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||t,n=null;try{n="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!n||"function"!=typeof n.canPlayType)return e;var r=n.canPlayType("audio/mpeg;").replace(/^no$/,""),o=e._navigator?e._navigator.userAgent:"",i=o.match(/OPR\/([0-6].)/g),a=i&&parseInt(i[0].split("/")[1],10)<33,s=-1!==o.indexOf("Safari")&&-1===o.indexOf("Chrome"),_=o.match(/Version\/(.*?) /),d=s&&_&&parseInt(_[1],10)<15;return e._codecs={mp3:!(a||!r&&!n.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!r,opus:!!n.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!n.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!n.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(n.canPlayType('audio/wav; codecs="1"')||n.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!n.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!n.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(n.canPlayType("audio/x-m4a;")||n.canPlayType("audio/m4a;")||n.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(n.canPlayType("audio/x-m4b;")||n.canPlayType("audio/m4b;")||n.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(n.canPlayType("audio/x-mp4;")||n.canPlayType("audio/mp4;")||n.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(d||!n.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(d||!n.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!n.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(n.canPlayType("audio/x-flac;")||n.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||t;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var n=function(t){for(;e._html5AudioPool.length0?s._seek:r._sprite[e][0]/1e3),c=Math.max(0,(r._sprite[e][0]+r._sprite[e][1])/1e3-d),u=1e3*c/Math.abs(s._rate),l=r._sprite[e][0]/1e3,h=(r._sprite[e][0]+r._sprite[e][1])/1e3;s._sprite=e,s._ended=!1;var A=function(){s._paused=!1,s._seek=d,s._start=l,s._stop=h,s._loop=!(!s._loop&&!r._sprite[e][2])};if(!(d>=h)){var f=s._node;if(r._webAudio){var g=function(){r._playLock=!1,A(),r._refreshBuffer(s);var e=s._muted||r._muted?0:s._volume;f.gain.setValueAtTime(e,t.ctx.currentTime),s._playStart=t.ctx.currentTime,void 0===f.bufferSource.start?s._loop?f.bufferSource.noteGrainOn(0,d,86400):f.bufferSource.noteGrainOn(0,d,c):s._loop?f.bufferSource.start(0,d,86400):f.bufferSource.start(0,d,c),u!==1/0&&(r._endTimers[s._id]=setTimeout(r._ended.bind(r,s),u)),n||setTimeout((function(){r._emit("play",s._id),r._loadQueue()}),0)};"running"===t.state&&"interrupted"!==t.ctx.state?g():(r._playLock=!0,r.once("resume",g),r._clearTimer(s._id))}else{var p=function(){f.currentTime=d,f.muted=s._muted||r._muted||t._muted||f.muted,f.volume=s._volume*t.volume(),f.playbackRate=s._rate;try{var o=f.play();if(o&&"undefined"!=typeof Promise&&(o instanceof Promise||"function"==typeof o.then)?(r._playLock=!0,A(),o.then((function(){r._playLock=!1,f._unlocked=!0,n?r._loadQueue():r._emit("play",s._id)})).catch((function(){r._playLock=!1,r._emit("playerror",s._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),s._ended=!0,s._paused=!0}))):n||(r._playLock=!1,A(),r._emit("play",s._id)),f.playbackRate=s._rate,f.paused)return void r._emit("playerror",s._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||s._loop?r._endTimers[s._id]=setTimeout(r._ended.bind(r,s),u):(r._endTimers[s._id]=function(){r._ended(s),f.removeEventListener("ended",r._endTimers[s._id],!1)},f.addEventListener("ended",r._endTimers[s._id],!1))}catch(e){r._emit("playerror",s._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===f.src&&(f.src=r._src,f.load());var m=window&&window.ejecta||!f.readyState&&t._navigator.isCocoonJS;if(f.readyState>=3||m)p();else{r._playLock=!0,r._state="loading";var R=function(){r._state="loaded",p(),f.removeEventListener(t._canPlayEvent,R,!1)};f.addEventListener(t._canPlayEvent,R,!1),r._clearTimer(s._id)}}return s._id}r._ended(s)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var n=t._getSoundIds(e),r=0;r=0?n=parseInt(i[0],10):e=parseFloat(i[0])}else i.length>=2&&(e=parseFloat(i[0]),n=parseInt(i[1],10));if(!(void 0!==e&&e>=0&&e<=1))return(r=n?o._soundById(n):o._sounds[0])?r._volume:0;if("loaded"!==o._state||o._playLock)return o._queue.push({event:"volume",action:function(){o.volume.apply(o,i)}}),o;void 0===n&&(o._volume=e),n=o._getSoundIds(n);for(var _=0;_0?r/d:r),u=Date.now();e._fadeTo=n,e._interval=setInterval((function(){var o=(Date.now()-u)/r;u=Date.now(),s+=_*o,s=Math.round(100*s)/100,s=_<0?Math.max(n,s):Math.min(n,s),a._webAudio?e._volume=s:a.volume(s,e._id,!0),i&&(a._volume=s),(nt&&s>=n)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,a.volume(n,e._id),a._emit("fade",e._id))}),c)},_stopFade:function(e){var n=this,r=n._soundById(e);return r&&r._interval&&(n._webAudio&&r._node.gain.cancelScheduledValues(t.ctx.currentTime),clearInterval(r._interval),r._interval=null,n.volume(r._fadeTo,e),r._fadeTo=null,n._emit("fade",e)),n},loop:function(){var e,t,n,r=this,o=arguments;if(0===o.length)return r._loop;if(1===o.length){if("boolean"!=typeof o[0])return!!(n=r._soundById(parseInt(o[0],10)))&&n._loop;e=o[0],r._loop=e}else 2===o.length&&(e=o[0],t=parseInt(o[1],10));for(var i=r._getSoundIds(t),a=0;a=0?n=parseInt(i[0],10):e=parseFloat(i[0])}else 2===i.length&&(e=parseFloat(i[0]),n=parseInt(i[1],10));if("number"!=typeof e)return(r=o._soundById(n))?r._rate:o._rate;if("loaded"!==o._state||o._playLock)return o._queue.push({event:"rate",action:function(){o.rate.apply(o,i)}}),o;void 0===n&&(o._rate=e),n=o._getSoundIds(n);for(var _=0;_=0?n=parseInt(o[0],10):r._sounds.length&&(n=r._sounds[0]._id,e=parseFloat(o[0]))}else 2===o.length&&(e=parseFloat(o[0]),n=parseInt(o[1],10));if(void 0===n)return 0;if("number"==typeof e&&("loaded"!==r._state||r._playLock))return r._queue.push({event:"seek",action:function(){r.seek.apply(r,o)}}),r;var s=r._soundById(n);if(s){if(!("number"==typeof e&&e>=0)){if(r._webAudio){var _=r.playing(n)?t.ctx.currentTime-s._playStart:0,d=s._rateSeek?s._rateSeek-s._seek:0;return s._seek+(d+_*Math.abs(s._rate))}return s._node.currentTime}var c=r.playing(n);c&&r.pause(n,!0),s._seek=e,s._ended=!1,r._clearTimer(n),r._webAudio||!s._node||isNaN(s._node.duration)||(s._node.currentTime=e);var u=function(){c&&r.play(n,!0),r._emit("seek",n)};if(c&&!r._webAudio){var l=function(){r._playLock?setTimeout(l,0):u()};setTimeout(l,0)}else u()}return r},playing:function(e){var t=this;if("number"==typeof e){var n=t._soundById(e);return!!n&&!n._paused}for(var r=0;r=0&&t._howls.splice(i,1);var a=!0;for(r=0;r=0){a=!1;break}return o&&a&&delete o[e._src],t.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,n,r){var o=this["_on"+e];return"function"==typeof t&&o.push(r?{id:n,fn:t,once:r}:{id:n,fn:t}),this},off:function(e,t,n){var r=this,o=r["_on"+e],i=0;if("number"==typeof t&&(n=t,t=null),t||n)for(i=0;i=0;i--)o[i].id&&o[i].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,n)}.bind(r,o[i].fn),0),o[i].once&&r.off(e,o[i].fn,o[i].id));return r._loadQueue(e),r},_loadQueue:function(e){var t=this;if(t._queue.length>0){var n=t._queue[0];n.event===e&&(t._queue.shift(),t._loadQueue()),e||n.action()}return t},_ended:function(e){var n=this,r=e._sprite;if(!n._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;r--){if(n<=t)return;e._sounds[r]._ended&&(e._webAudio&&e._sounds[r]._node&&e._sounds[r]._node.disconnect(0),e._sounds.splice(r,1),n--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],n=0;n=0;if(!e.bufferSource)return this;if(t._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),n))try{e.bufferSource.buffer=t._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(t._navigator&&t._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var r=function(e){this._parent=e,this.init()};r.prototype={init:function(){var e=this,n=e._parent;return e._muted=n._muted,e._loop=n._loop,e._volume=n._volume,e._rate=n._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++t._counter,n._sounds.push(e),e.create(),e},create:function(){var e=this,n=e._parent,r=t._muted||e._muted||e._parent._muted?0:e._volume;return n._webAudio?(e._node=void 0===t.ctx.createGain?t.ctx.createGainNode():t.ctx.createGain(),e._node.gain.setValueAtTime(r,t.ctx.currentTime),e._node.paused=!0,e._node.connect(t.masterGain)):t.noAudio||(e._node=t._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(t._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=n._src,e._node.preload=!0===n._preload?"auto":n._preload,e._node.volume=r*t.volume(),e._node.load()),e},reset:function(){var e=this,n=e._parent;return e._muted=n._muted,e._loop=n._loop,e._volume=n._volume,e._rate=n._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++t._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,n=e._parent;n._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(n._sprite).length&&(n._sprite={__default:[0,1e3*n._duration]}),"loaded"!==n._state&&(n._state="loaded",n._emit("load"),n._loadQueue()),e._node.removeEventListener(t._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var o={},i=function(e){var t=e._src;if(o[t])return e._duration=o[t].duration,void _(e);if(/^data:[^;]+;base64,/.test(t)){for(var n=atob(t.split(",")[1]),r=new Uint8Array(n.length),i=0;i0?(o[n._src]=e,_(n,e)):r()};"undefined"!=typeof Promise&&1===t.ctx.decodeAudioData.length?t.ctx.decodeAudioData(e).then(i).catch(r):t.ctx.decodeAudioData(e,i,r)},_=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},d=function(){if(t.usingWebAudio){try{"undefined"!=typeof AudioContext?t.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?t.ctx=new webkitAudioContext:t.usingWebAudio=!1}catch(e){t.usingWebAudio=!1}t.ctx||(t.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(t._navigator&&t._navigator.platform),n=t._navigator&&t._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),r=n?parseInt(n[1],10):null;if(e&&r&&r<9){var o=/safari/.test(t._navigator&&t._navigator.userAgent.toLowerCase());t._navigator&&!o&&(t.usingWebAudio=!1)}t.usingWebAudio&&(t.masterGain=void 0===t.ctx.createGain?t.ctx.createGainNode():t.ctx.createGain(),t.masterGain.gain.setValueAtTime(t._muted?0:t._volume,t.ctx.currentTime),t.masterGain.connect(t.ctx.destination)),t._setup()}};!function(e,t,n,r){var o;e.prototype._pos=[0,0,0],e.prototype._orientation=[0,0,-1,0,1,0],e.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var n=t._howls.length-1;n>=0;n--)t._howls[n].stereo(e);return t},e.prototype.pos=function(e,n,r){var o=this;return o.ctx&&o.ctx.listener?(n="number"!=typeof n?o._pos[1]:n,r="number"!=typeof r?o._pos[2]:r,"number"!=typeof e?o._pos:(o._pos=[e,n,r],void 0!==o.ctx.listener.positionX?(o.ctx.listener.positionX.setTargetAtTime(o._pos[0],t.ctx.currentTime,.1),o.ctx.listener.positionY.setTargetAtTime(o._pos[1],t.ctx.currentTime,.1),o.ctx.listener.positionZ.setTargetAtTime(o._pos[2],t.ctx.currentTime,.1)):o.ctx.listener.setPosition(o._pos[0],o._pos[1],o._pos[2]),o)):o},e.prototype.orientation=function(e,n,r,o,i,a){var s=this;if(!s.ctx||!s.ctx.listener)return s;var _=s._orientation;return n="number"!=typeof n?_[1]:n,r="number"!=typeof r?_[2]:r,o="number"!=typeof o?_[3]:o,i="number"!=typeof i?_[4]:i,a="number"!=typeof a?_[5]:a,"number"!=typeof e?_:(s._orientation=[e,n,r,o,i,a],void 0!==s.ctx.listener.forwardX?(s.ctx.listener.forwardX.setTargetAtTime(e,t.ctx.currentTime,.1),s.ctx.listener.forwardY.setTargetAtTime(n,t.ctx.currentTime,.1),s.ctx.listener.forwardZ.setTargetAtTime(r,t.ctx.currentTime,.1),s.ctx.listener.upX.setTargetAtTime(o,t.ctx.currentTime,.1),s.ctx.listener.upY.setTargetAtTime(i,t.ctx.currentTime,.1),s.ctx.listener.upZ.setTargetAtTime(a,t.ctx.currentTime,.1)):s.ctx.listener.setOrientation(e,n,r,o,i,a),s)},n.prototype.init=(o=n.prototype.init,function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],o.call(this,e)}),n.prototype.stereo=function(e,n){var r=this;if(!r._webAudio)return r;if("loaded"!==r._state)return r._queue.push({event:"stereo",action:function(){r.stereo(e,n)}}),r;var o=void 0===t.ctx.createStereoPanner?"spatial":"stereo";if(void 0===n){if("number"!=typeof e)return r._stereo;r._stereo=e,r._pos=[e,0,0]}for(var a=r._getSoundIds(n),s=0;s{let e=!1;if(m)try{(await A.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===f.browser&&f.version>66||"Safari"===f.browser&&f.version>13||"OPR"===f.browser&&f.version>43||"Edge"===f.browser&&f.version;const I=(()=>{if(!c&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),E=" is not allowed to change after `createInstance` or `loadWasm` is called.",T=!c&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",D=!c&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",S=e=>{if(null==e)e=[];else{e=e instanceof Array?[...e]:[e];for(let t=0;te&&"object"==typeof e&&"function"==typeof e.then;const v="iPhone"==f.OS||"Android"==f.OS||"HarmonyOS"==f.OS?2048:4096;class w{constructor(){this._instanceID=void 0,this._ifSaveOriginalImageInACanvas=!1,this.oriCanvas=null,this.oriCanvasData=null,this.canvas=null,this.bFilterRegionInJs=!1,this._region=null,this._timeStartDecode=null,this._timeEnterInnerDBR=null,this._timeGetMessage=null,this.decodeRecords={},this.bDestroyed=!1,this._lastErrorCode=0,this._lastErrorString="",this._lastInnerDecodeDuration=0,this.intervalTime=0,this._intervalGetVideoFrame=0,this.array_getFrameTimeCost=[],this.array_decodeFrameTimeCost=[],this._indexCurrentDecodingFrame=0,this._bPauseScan=!1,this._intervalDetectVideoPause=1e3,this._soundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",this.beepSound=new n({src:["data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV"],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.captureAndDecodeInParallel=!0,this.barcodeFillStyle="rgba(254,180,32,0.3)",this.barcodeStrokeStyle="rgba(254,180,32,0.9)",this.barcodeLineWidth=1,this._dce=null,this._imgSource=null,this._maxCvsSideLength=v,this._tempSolutionStatus="closed"}static get version(){return this._version}static get license(){return this._license}static set license(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`license`"+E);n._license=t})(w,e)}static get productKeys(){return this._license}static set productKeys(e){w.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){w.license=e}static get organizationID(){return this._license}static set organizationID(e){w.license=e}static set sessionPassword(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`sessionPassword`"+E);n._sessionPassword=t})(w,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:g,worker:p,getUserMedia:m,camera:await R(),browser:f.browser,version:f.version,OS:f.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(e){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");w._engineResourcePath=(e=>{if(null==e&&(e="./"),!c){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`licenseServer`"+E);n._licenseServer=S(t)})(w,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+E);n._deviceFriendlyName=t||""})(w,e)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(e){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");w.__bUseFullFeature=e}static isImageSource(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"getImage"in e}static isDSImage(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("width"in e&&("height"in e&&"pixelFormat"in e)))}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("region"in e&&("sx"in e&&("sy"in e&&("width"in e&&("height"in e&&("colorMode"in e&&("timeSpent"in e&&("timeStamp"in e&&("isCropped"in e&&("toCanvas"in e&&("_sWidth"in e&&("_sHeight"in e&&"_bUseWebGL"in e)))))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(e){this._region=e,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var e;return null===(e=w._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",w.engineResourcePath)}static set defaultUIElementURL(e){w._defaultUIElementURL=e}static _fireHTTPSWarnning(){w.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{w.onWarning&&w.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new n({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(e){this.bPlaySoundOnSuccessfulRead="never"!==e&&e}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(e){this.bVibrateOnSuccessfulRead="never"!==e&&e}set dce(e){this._dce=e}get dce(){return!this._dce||this._dce.isDisposed?null:this._dce}set maxCvsSideLength(e){this._maxCvsSideLength=e,this._dceControler&&this._dceControler.setDisiredValue(this,"maxCvsSideLength",e)}get maxCvsSideLength(){return this._maxCvsSideLength}async _registerDCEControler(){if(!this.dce)return;w._onLog&&w._onLog("_registerDCEControler()");const e=this.dce;this._dceControler=e._createControler();const t=this._dceControler;t.register(this),t.setDisiredValue(this,"refreshInterval",200),t.setDisiredValue(this,"maxCvsSideLength",this._maxCvsSideLength);try{ResizeObserver}catch(e){"ReferenceError"===e.name&&window&&(window.ResizeObserver=void 0)}const n=e.getUIElement(),r=this.dce.constructor;if("@engineResourcePath/dce.ui.html"===r._defaultUIElementURL)try{n?n===t._innerSetUI&&(await e.setUIElement(`${r.engineResourcePath}dce.ui.html`),t._innerSetUI=e.getUIElement()):(await e.setUIElement(`${r.engineResourcePath}dbr.ui.html`),t._innerSetUI=e.getUIElement())}catch(t){await e.setUIElement(r.defaultUIElementURL)}else n||await e.setUIElement(r.defaultUIElementURL);this.callbackCameraChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async e=>{let t=await this._decode_DCEFrame(e,{bCopyData:!1});if(await this.clearMapDecodeRecord(),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(t);this.onImageRead(e)}if(this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e));const{sx:n,sy:r,width:o,height:i,_sWidth:a,_sHeight:s}=e;w.recalculateResultLocation(t,n,r,a,s,o,i),this._drawResults(t)},e.on("cameraChange",this.callbackCameraChange),e.on("resolutionChange",this.callbackResolutionChange),e.on("cameraClose",this.callbackCameraClose),e.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}_logoutDCEControler(){this.dce&&this._dceControler&&(w._onLog&&w._onLog("_logoutDCEControler()"),this._dceControler.logout(this),this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this._dceControler=null,this.dce=null)}async setImageSource(e,t){if(null==e)return this._imgSource=null,this._logoutDCEControler(),void(this._drawingItemNamespace=null);if(e&&e.isCameraEnhancer)this.dce=e,await this._registerDCEControler(),this._imgSource=null;else{if(!w.isImageSource(e))throw new Error("Invalid value.");this._logoutDCEControler(),this._imgSource=e}t&&t.resultsHighlightBaseShapes&&(this._drawingItemNamespace=t.resultsHighlightBaseShapes)}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:e,l:t,ls:n,sp:r,rmk:o}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,n,r=t._license||"",o=JSON.parse(JSON.stringify(t._licenseServer)),i=t._sessionPassword,a=0;if(r.startsWith("t")||r.startsWith("f"))a=0;else if(0===r.length||r.startsWith("P")||r.startsWith("L")||r.startsWith("Y")||r.startsWith("A"))a=1;else{a=2;const t=r.indexOf(":");if(-1!=t&&(r=r.substring(t+1)),r.startsWith("DLS2")){let t=r.substring(4);try{t=atob(t)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}const n=JSON.parse(t);if(r=n.handshakeCode?n.handshakeCode:n.organizationID?n.organizationID:"","number"==typeof r&&(r=JSON.stringify(r)),0===o.length){let e=[];n.mainServerURL&&(e[0]=n.mainServerURL),n.standbyServerURL&&(e[1]=n.standbyServerURL),o=S(e)}!i&&n.sessionPassword&&(i=n.sessionPassword),e=n.remark}("200001"===r||r.startsWith("200001-"))&&(o&&o.length||(r="")),r||(a=1)}if(a&&(globalThis.crypto||(n="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(n="Require https to use online key in this browser.")),n){if(1!==a)throw new Error(n);a=0,console.warn(n),t._lastErrorCode=-1,t._lastErrorString=n}return 1===a&&(r="",console.warn("Applying for a public trial license ...")),{lt:a,l:r,ls:o,sp:i,rmk:e}}throw new Error("Can't preprocess license again"+E)})(w);this._pLoad.task=async(i,a)=>{let s=w.engineResourcePath+w._workerName;w.engineResourcePath.startsWith(location.origin)||(s=await fetch(s).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),w._dbrWorker=new Worker(s),w._dbrWorker.onerror=e=>{let t=new Error(e.message);a(t)},w._dbrWorker.onmessage=async t=>{let n=t.data?t.data:t;switch(n.type){case"log":w._onLog&&w._onLog(n.message);break;case"load":{n.message&&(n.message=n.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,r=!1;1===e&&(r=!0),n.success?(w._dbrWorker.onerror=null,w._version=n.version+"(JS "+w._jsVersion+"."+w._jsEditVersion+")",w._onLog&&w._onLog("load dbr worker success"),n.message&&console.warn(n.message)):(t=new Error(n.message),t.stack=n.stack+"\n"+t.stack,r||111==n.ltsErrorCode&&-1!=n.message.toLowerCase().indexOf("trial license")&&(r=!0)),r&&w.showDialog(n.success?"warn":"error",n.message),n.success?i():a(t);break}case"task":{let e=n.id,t=n.body;try{w._taskCallbackMap.get(e)(t),w._taskCallbackMap.delete(e)}catch(t){throw w._taskCallbackMap.delete(e),t}break}default:w._onLog&&w._onLog(t)}},w._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:w.engineResourcePath,bUseFullFeature:w._bUseFullFeature,bd:w._bWasmDebug,v:w._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:f,fn:w.deviceFriendlyName,ls:n,sp:r,rmk:o})}}await this._pLoad}static async showDialog(e,t){await(async(e,t,n)=>{if(!e._bNeverShowDialog)try{let r=await fetch(e.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let o=await r.text();if(!o.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let i=document.createElement("div");i.innerHTML=o;let a=[];for(let e=0;e{if(e==t.target){s.remove();for(let e of a)e.remove()}}));else if(!d&&e.classList.contains("dls-license-icon-close"))d=e,e.addEventListener("click",(()=>{s.remove();for(let e of a)e.remove()}));else if(!c&&e.classList.contains("dls-license-icon-error"))c=e,"error"!=t&&e.remove();else if(!u&&e.classList.contains("dls-license-icon-warn"))u=e,"warn"!=t&&e.remove();else if(!l&&e.classList.contains("dls-license-msg-content")){l=e;let t=n;for(;t;){let n=t.indexOf("["),r=t.indexOf("]",n),o=t.indexOf("(",r),i=t.indexOf(")",o);if(-1==n||-1==r||-1==o||-1==i){e.appendChild(new Text(t));break}n>0&&e.appendChild(new Text(t.substring(0,n)));let a=document.createElement("a"),s=t.substring(n+1,r);a.innerText=s;let _=t.substring(o+1,i);a.setAttribute("href",_),a.setAttribute("target","_blank"),e.appendChild(a),t=t.substring(i+1)}}document.body.appendChild(s)}catch(t){e._onLog&&e._onLog(t.message||t)}})(this,e,t)}static async createInstanceInWorker(e=!1){return await w.loadWasm(),await new Promise(((t,n)=>{let r=w._nextTaskID++;w._taskCallbackMap.set(r,(e=>{if(e.success)return t(e.instanceID);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),w._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}static async createInstance(){let e=new w;return e._instanceID=await w.createInstanceInWorker(),w._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let n=w._nextTaskID++;w._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),w._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:n,instanceID:this._instanceID})}))}async decode(e){w._onLog&&w._onLog("decode(source: any)"),w._onLog&&(this._timeStartDecode=Date.now());{let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),e instanceof Blob?await this._decode_Blob(e,t):e instanceof ArrayBuffer?await this._decode_ArrayBuffer(e,t):e instanceof Uint8Array||e instanceof Uint8ClampedArray?await this._decode_Uint8Array(e,t):e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?await this._decode_Image(e,t):e instanceof HTMLCanvasElement?await this._decode_Canvas(e,t):e instanceof HTMLVideoElement?await this._decode_Video(e,t):"string"==typeof e?"data:image/"==e.substring(0,11)?await this._decode_Base64(e,t):await this._decode_Url(e,t):w.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):w.isDSImage(e)?(t.bCopyData=!0,await this._decode_DSImage(e,t)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(e,t)}async decodeUrl(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(e,t)}async _decodeBuffer_Uint8Array(e,t,n,r,o,i){return await new Promise(((a,s)=>{let _=w._nextTaskID++;w._taskCallbackMap.set(_,(e=>{if(e.success){let t,n=w._onLog?Date.now():0;w._onLog&&w._onLog("worker return result: "+n),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return s(e)}if(w._onLog){let e=Date.now();w._onLog("DBR time get result: "+n),w._onLog("Handle image cost: "+(this._timeEnterInnerDBR-this._timeStartDecode)),w._onLog("DBR worker decode image cost: "+(n-this._timeEnterInnerDBR)),w._onLog("DBR worker handle results: "+(e-n)),w._onLog("Total decode image cost: "+(e-this._timeStartDecode))}return a(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,s(t)}})),this._timeEnterInnerDBR=Date.now(),w._onLog&&w._onLog("Send buffer to worker:"+this._timeEnterInnerDBR),w._dbrWorker.postMessage({type:"decodeBuffer",id:_,instanceID:this._instanceID,body:{buffer:e,width:t,height:n,stride:r,format:o,config:i}},[e.buffer]),w._onLog&&i&&i.timeStamp&&w._onLog("decode image delay: "+(this._timeEnterInnerDBR-i.timeStamp))}))}async _decodeBuffer_Blob(e,t,n,r,o,i){w._onLog&&w._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const a=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,n)=>{let r=new FileReader;r.readAsArrayBuffer(e),r.onload=()=>{t(r.result)},r.onerror=()=>{n(r.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(a),t,n,r,o,i)}async decodeBuffer(e,t,n,r,o,i){let a;return w._onLog&&w._onLog("decodeBuffer(buffer,width,height,stride,format)"),w._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?a=await this._decodeBuffer_Uint8Array(e,t,n,r,o,i):e instanceof ArrayBuffer?a=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,n,r,o,i):e instanceof Blob&&(a=await this._decodeBuffer_Blob(e,t,n,r,o,i)),a}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,n)=>{let r=w._nextTaskID++;w._taskCallbackMap.set(r,(e=>{if(e.success){let r;this._lastInnerDecodeDuration=e.duration;try{r=this._handleRetJsonString(e.decodeReturn)}catch(e){return n(e)}return t(r)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),w._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let n=w._nextTaskID++;w._taskCallbackMap.set(n,(n=>{if(n.success){let t=JSON.parse(n.results);return null!=this.userDefinedRegion&&(t.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),e(t)}{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),w._dbrWorker.postMessage({type:"getRuntimeSettings",id:n,instanceID:this._instanceID})}))}async updateRuntimeSettings(e){let t;if("string"==typeof e)if("speed"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=3,t.expectedBarcodesCount=0,t.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=5,t.expectedBarcodesCount=512,t.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region}else if("dense"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=9,t.expectedBarcodesCount=0,t.localizationModes=[2,8,0,0,0,0,0,0]}else if("distance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=3,t.expectedBarcodesCount=0,t.localizationModes=[2,8,0,0,0,0,0,0]}else t=JSON.parse(e);else{if("object"!=typeof e)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(t=JSON.parse(JSON.stringify(e)),t.region instanceof Array){let e=t.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(t.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!w._bUseFullFeature){if(0!=(t.barcodeFormatIds&~(L.BF_ONED|L.BF_QR_CODE|L.BF_PDF417|L.BF_DATAMATRIX))||0!=t.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=t.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let e=t.region;if(e instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(e)),(e.regionLeft||e.regionTop||e.regionRight||e.regionBottom||e.regionMeasuredByPercentage)&&(e.regionLeft||e.regionTop||100!=e.regionRight||100!=e.regionBottom||!e.regionMeasuredByPercentage)?this.region=e:this.region=null,t.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return await new Promise(((e,n)=>{let r=w._nextTaskID++;w._taskCallbackMap.set(r,(t=>{if(t.success){try{this._handleRetJsonString(t.updateReturn)}catch(e){n(e)}return e()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}})),w._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(t)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=v,await new Promise(((e,t)=>{let n=w._nextTaskID++;w._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),w._dbrWorker.postMessage({type:"resetRuntimeSettings",id:n,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!w._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((e,t)=>{let n=w._nextTaskID++;w._taskCallbackMap.set(n,(n=>{if(n.success)return e(n.results);{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),w._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:n,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!w._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof e)e=e;else{if("object"!=typeof e)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");e=JSON.stringify(e)}return await new Promise(((t,n)=>{let r=w._nextTaskID++;w._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.initReturn)}catch(e){n(e)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),w._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){w._onLog&&w._onLog("_decode_Blob(blob: Blob)");let n=null,r=null;if("undefined"!=typeof createImageBitmap)try{n=await createImageBitmap(e)}catch(e){}n||(r=await function(e){return new Promise(((t,n)=>{let r=URL.createObjectURL(e),o=new Image;o.dbrObjUrl=r,o.src=r,o.onload=()=>{t(o)},o.onerror=e=>{n(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let o=await this._decode_Image(n||r,t);return n&&n.close(),o}async _decode_ArrayBuffer(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Uint8Array(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Image(e,t){w._onLog&&w._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),t=t||{};let n,r,o=e instanceof HTMLImageElement?e.naturalWidth:e.width,i=e instanceof HTMLImageElement?e.naturalHeight:e.height,a=Math.max(o,i);if(a>this._maxCvsSideLength){let e=this._maxCvsSideLength/a;n=Math.round(o*e),r=Math.round(i*e)}else n=o,r=i;this.canvas||(this.canvas=document.createElement("canvas"));const s=this.canvas;s.width===n&&s.height===r||(s.width=n,s.height=r),s.ctx2d||(s.ctx2d=s.getContext("2d"));return s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._decode_Canvas(s,t)}async _decode_Canvas(e,t){if(w._onLog&&w._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";if(0===e.width||0===e.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=e,this.oriCanvasData=null);let n=(e.ctx2d||e.getContext("2d")).getImageData(0,0,e.width,e.height).data;return await this._decodeBuffer_Uint8Array(n,e.width,e.height,4*e.width,C.IPF_ABGR_8888,t)}async _decode_Video(e,t){if(w._onLog&&w._onLog("_decode_Video(video)"),!(e instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";t=t||{};let n,r,o=e.videoWidth,i=e.videoHeight,a=Math.max(o,i);if(a>this._maxCvsSideLength){let e=this._maxCvsSideLength/a;n=Math.round(o*e),r=Math.round(i*e)}else n=o,r=i;this.canvas||(this.canvas=document.createElement("canvas"));const s=this.canvas;s.width===n&&s.height===r||(s.width=n,s.height=r),s.ctx2d||(s.ctx2d=s.getContext("2d"));return s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r),await this._decode_Canvas(s,t)}async _decode_DCEFrame(e,t){if(w._onLog&&w._onLog("_decode_DCEFrame(dceFrame)"),!w.isDCEFrame(e))return[];let n=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,colorMode:e.colorMode,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{width:r,height:o,colorMode:i,timeStamp:a}=e;let s;s=t&&t.bCopyData?new Uint8Array(e.data):e.data;let _=null;if(t?(_=JSON.parse(JSON.stringify(t)),_.timeStamp=a):_={timeStamp:a},"grey"===i)n=await this._decodeBuffer_Uint8Array(s,r,o,r,C.IPF_GrayScaled,_);else if("rgba"===i)n=await this._decodeBuffer_Uint8Array(s,r,o,4*r,C.IPF_ABGR_8888,_);else{if("bgra"!==i)throw new Error(`Color mode '${i}' is not supported to decode.`);n=await this._decodeBuffer_Uint8Array(s,r,o,4*r,C.IPF_ARGB_8888,_)}return n}async _decode_DSImage(e,t){if(w._onLog&&w._onLog("_decode_DSImage(dsImage)"),!w.isDSImage(e))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,pixelFormat:e.pixelFormat.toLowerCase(),data:new Uint8Array(e.data),toCanvas:function(){const e=document.createElement("canvas");let t;switch(e.width=this.width,e.height=this.height,this.pixelFormat){case"grey":t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{let r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="blob",r.send(),r.onloadend=async()=>{t(r.response)},r.onerror=()=>{n(new Error("Network Error: "+r.statusText))}}));return await this._decode_Blob(n,t)}}async _decode_FilePath(e,t){throw w._onLog&&w._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static recalculateResultLocation(e,t,n,r,o,i,a){if(e.length>0)for(let s of e){let e=s.localizationResult;2==e.resultCoordinateType&&(e.x1*=.01*i,e.x2*=.01*i,e.x3*=.01*i,e.x4*=.01*i,e.y1*=.01*a,e.y2*=.01*a,e.y3*=.01*a,e.y4*=.01*a);let _=i/r,d=a/o;e.x1=e.x1/_+t,e.x2=e.x2/_+t,e.x3=e.x3/_+t,e.x4=e.x4/_+t,e.y1=e.y1/d+n,e.y2=e.y2/d+n,e.y3=e.y3/d+n,e.y4=e.y4/d+n,2==e.resultCoordinateType&&(e.x1*=100/r,e.x2*=100/r,e.x3*=100/r,e.x4*=100/r,e.y1*=100/o,e.y2*=100/o,e.y3*=100/o,e.y4*=100/o)}}static BarcodeReaderException(e,t){let n,r=y.DBR_UNKNOWN;return"number"==typeof e?(r=e,n=new Error(t)):n=new Error(e),n.code=r,n}_handleRetJsonString(e){let t=y;if(e.textResults){for(let t=0;t{let n=t.indexOf(":");e[t.substring(0,n)]=t.substring(n+1)})),n.exception=e}}return e.decodeRecords?this.decodeRecords=e.decodeRecords:this.decodeRecords={},this._lastErrorCode=e.exception,this._lastErrorString=e.description,e.exception&&!w._setWarnnedEx.has(e.description)&&(w._setWarnnedEx.add(e.description),console.warn(e.description)),e.textResults}if(e.exception==t.DBR_SUCCESS)return e.data;throw w.BarcodeReaderException(e.exception,e.description)}async setModeArgument(e,t,n,r){return await new Promise(((o,i)=>{let a=w._nextTaskID++;w._taskCallbackMap.set(a,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return i(e)}return o()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),w._dbrWorker.postMessage({type:"setModeArgument",id:a,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:n,argumentValue:r}})}))}async getModeArgument(e,t,n){return await new Promise(((r,o)=>{let i=w._nextTaskID++;w._taskCallbackMap.set(i,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return o(e)}return r(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,o(t)}})),w._dbrWorker.postMessage({type:"getModeArgument",id:i,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:n}})}))}async getIntermediateResults(){return await new Promise(((e,t)=>{let n=w._nextTaskID++;w._taskCallbackMap.set(n,(n=>{if(n.success)return e(n.results);{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),w._dbrWorker.postMessage({type:"getIntermediateResults",id:n,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let e=await this.getIntermediateResults(),t=[];for(let n of e)if(n.dataType==O.IMRDT_IMAGE)for(let e of n.results){const n=e.bytes;let r;switch(w._onLog&&w._onLog(" "+n.length+" "+n.byteLength+" "+e.width+" "+e.height+" "+e.stride+" "+e.format),e.format){case C.IPF_ABGR_8888:r=new Uint8ClampedArray(n);break;case C.IPF_RGB_888:{const e=n.length/3;r=new Uint8ClampedArray(4*e);for(let t=0;t{let n=w._nextTaskID++;w._taskCallbackMap.set(n,(n=>{if(n.success){let t=n.results;return t.intervalTime=this.intervalTime,t.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,t.soundOnSuccessfullRead=this.soundSource,t.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,t.vibrateDuration=this.vibrateDuration,t.captureAndDecodeInParallel=this.captureAndDecodeInParallel,e(t)}{let e=new Error(n.message);return e.stack+="\n"+n.stack,t(e)}})),w._dbrWorker.postMessage({type:"getScanSettings",id:n,instanceID:this._instanceID})}))}async updateScanSettings(e){if(!e)return;const t=JSON.parse(JSON.stringify(e));return t.hasOwnProperty("intervalTime")&&(this.intervalTime=Math.max(t.intervalTime,0),delete t.intervalTime),t.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=t.whenToPlaySoundforSuccessfulRead,delete t.whenToPlaySoundforSuccessfulRead),t.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=t.soundOnSuccessfullRead,delete t.soundOnSuccessfullRead),t.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=t.whenToVibrateforSuccessfulRead,delete t.whenToVibrateforSuccessfulRead),t.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=t.vibrateDuration,delete t.vibrateDuration),t.hasOwnProperty("captureAndDecodeInParallel")&&(this.captureAndDecodeInParallel=t.captureAndDecodeInParallel,delete t.captureAndDecodeInParallel),await new Promise(((e,n)=>{let r=w._nextTaskID++;w._taskCallbackMap.set(r,(t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack+="\n"+t.stack,n(e)}})),w._dbrWorker.postMessage({type:"updateScanSettings",id:r,instanceID:this._instanceID,body:{settings:t}})}))}_cloneDecodeResults(e){if(e instanceof Array){let t=[];for(let n of e)t.push(this._cloneDecodeResults(n));return t}{let t=e;return JSON.parse(JSON.stringify(t,((e,t)=>"oriVideoCanvas"==e||"searchRegionCanvas"==e?void 0:t)))}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this._imgSource||this._bPauseScan)return w._onLog&&w._onLog("Scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));w._onLog&&w._onLog("======= once read ======="),w._onLog&&(this._timeStartDecode=Date.now());let e=null,t=null;if(this.dce)e=this._getVideoFrame();else if(this._imgSource&&(t=await this._imgSource.getImage(),!w.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let n=[];if(e){n=await this._decode_DCEFrame(e,{bScanner:!0,bCopyData:!1});let t=null;if(n&&n.length){const{sx:r,sy:o,width:i,height:a,_sWidth:s,_sHeight:_}=e;t=n.map((e=>({localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),w.recalculateResultLocation(t,r,o,s,_,i,a)}this._drawResults(t)}else t&&(n=await this._decode_DSImage(t,{bScanner:!0,bCopyData:!1}));return n})().then((e=>{if(w._onLog&&w._onLog(e),this.dce&&this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost;const n=()=>{let n=0;if(t&&t.length){let r=Math.min(...e),o=Math.max(...t);r&&o&&(n=r-o)}else n=0;return n>0?n:0};(()=>{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=n()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this._imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead)t=!0;else if("unique"===this.bPlaySoundOnSuccessfulRead)for(let n of e)if(0==n.resultsType){t=!0;break}t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead)t=!0;else if("unique"===this.bVibrateOnSuccessfulRead)for(let n of e)if(0==n.resultsType){t=!0;break}if(t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onImageRead){let t=this._cloneDecodeResults(e);for(let e of t)0!=e.resultsType&&1!=e.resultsType||this.onImageRead(t);this.onImageRead(t)}if(this.onUniqueRead)for(let t of e)0==t.resultsType&&this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t))}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),w._onLog&&w._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){if(this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",this._intervalGetVideoFrame),!this.dce.numberOfFramesInBuffer)return this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",0),null;e=this.dce.getFrameFromBuffer();const t=e=>{if(!e)return;let t=e.timeSpent,n=this.array_getFrameTimeCost;for(;n.length>=5;)n.shift();n.push(t)};t(e)}else this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),e=this.dce.getFrame();return e}_drawResults(e){if(!this.dce||this._bPauseScan||!this._drawingItemNamespace||!this._drawingItemNamespace.DT_Polygon)return;if(!this._dbrDrawingLayer){if(!this.dce.isOpen())return;this._dbrDrawingLayer=this.dce.getDrawingLayer(3)}const t=this._dbrDrawingLayer;if(t.clearDrawingItems(),e&&e.length)for(let n of e){const e=n.localizationResult,r=new this._drawingItemNamespace.DT_Polygon([{x:e.x1,y:e.y1},{x:e.x2,y:e.y2},{x:e.x3,y:e.y3},{x:e.x4,y:e.y4}]);t.addDrawingItem(r)}}async startScanning(e){if(!this.dce&&!this._imgSource)throw new Error("'imageSource' is not set. call 'setImageSource()' before 'startScanning()'.");if("closed"!=this._tempSolutionStatus)return;if(this._tempSolutionStatus="opening","opening"!=this._tempSolutionStatus)return;let t=null;return this.dce&&(this.dce.isOpen()?(e&&this.dce.appendAndShowUI(),t=JSON.parse(JSON.stringify(this.dce.playCallbackInfo))):t=await this.dce.open(e),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"close"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())),"opening"==this._tempSolutionStatus?(this._bPauseScan=!1,this.dce&&this.dce.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),0)),this._tempSolutionStatus="opened",this.keepAlive(),t):void 0}stopScanning(e){this.dce&&(this._drawResults(null),this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"close",e))),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._tempSolutionStatus="closed"}pauseScanning(e){if(e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"stopFetchingLoop"))}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.startFetchingLoop(),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(w._onLog&&w._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,(this.dce||"opening"===this._tempSolutionStatus)&&this.stopScanning(),this.setImageSource(null);let e=w._nextTaskID++;w._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),w._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}var b,N,B,P,F,V,x,k,U,G,H,K,W,Y,Q,J,X,Z,j,q,$,z,ee,te,ne,re,oe;w._jsVersion="9.2.11",w._jsEditVersion="20220727",w._version=`loading...(JS ${w._jsVersion}.${w._jsEditVersion})`,w._license=T,w._sessionPassword=D,w.browserInfo=f,w._workerName=`dbr-${w._jsVersion}.browser.worker.js`,w._engineResourcePath=I,w._licenseServer=[],w._deviceFriendlyName="",w._isShowRelDecodeTimeInResults=!1,w._bWasmDebug=!1,w._bNeverShowDialog=!1,w.__bUseFullFeature=!0,w._nextTaskID=0,w._taskCallbackMap=new Map,w._pLoad=new class extends Promise{constructor(e){let t,n;super(((e,r)=>{t=e,n=r})),this._s="pending",this.resolve=e=>{this.isPending&&(M(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",n(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,M(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const n=await t;e===this._task&&this.resolve(n)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}},w._lastErrorCode=0,w._lastErrorString="",w._setWarnnedEx=new Set,w._defaultUIElementURL="@engineResourcePath/dbr.ui.html",function(e){e[e.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",e[e.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",e[e.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",e[e.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",e[e.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",e[e.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",e[e.BICM_SKIP=0]="BICM_SKIP",e[e.BICM_REV=2147483648]="BICM_REV"}(b||(b={})),function(e){e[e.BCM_AUTO=1]="BCM_AUTO",e[e.BCM_GENERAL=2]="BCM_GENERAL",e[e.BCM_SKIP=0]="BCM_SKIP",e[e.BCM_REV=2147483648]="BCM_REV"}(N||(N={})),function(e){e[e.BF2_NULL=0]="BF2_NULL",e[e.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",e[e.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",e[e.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",e[e.BF2_POSTNET=2097152]="BF2_POSTNET",e[e.BF2_PLANET=4194304]="BF2_PLANET",e[e.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",e[e.BF2_RM4SCC=16777216]="BF2_RM4SCC",e[e.BF2_DOTCODE=2]="BF2_DOTCODE",e[e.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",e[e.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",e[e.BF2_PHARMACODE=12]="BF2_PHARMACODE"}(B||(B={})),function(e){e[e.BM_AUTO=1]="BM_AUTO",e[e.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",e[e.BM_SKIP=0]="BM_SKIP",e[e.BM_THRESHOLD=4]="BM_THRESHOLD",e[e.BM_REV=2147483648]="BM_REV"}(P||(P={})),function(e){e[e.ECCM_CONTRAST=1]="ECCM_CONTRAST"}(F||(F={})),function(e){e[e.CFM_GENERAL=1]="CFM_GENERAL"}(V||(V={})),function(e){e[e.CCM_AUTO=1]="CCM_AUTO",e[e.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",e[e.CCM_SKIP=0]="CCM_SKIP",e[e.CCM_REV=2147483648]="CCM_REV"}(x||(x={})),function(e){e[e.CICM_GENERAL=1]="CICM_GENERAL",e[e.CICM_SKIP=0]="CICM_SKIP",e[e.CICM_REV=2147483648]="CICM_REV"}(k||(k={})),function(e){e[e.CM_IGNORE=1]="CM_IGNORE",e[e.CM_OVERWRITE=2]="CM_OVERWRITE"}(U||(U={})),function(e){e[e.DM_SKIP=0]="DM_SKIP",e[e.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",e[e.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",e[e.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",e[e.DM_SMOOTHING=8]="DM_SMOOTHING",e[e.DM_MORPHING=16]="DM_MORPHING",e[e.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",e[e.DM_SHARPENING=64]="DM_SHARPENING",e[e.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",e[e.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING"}(G||(G={})),function(e){e[e.DRM_AUTO=1]="DRM_AUTO",e[e.DRM_GENERAL=2]="DRM_GENERAL",e[e.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",e[e.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",e[e.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",e[e.DRM_SKIP=0]="DRM_SKIP",e[e.DRM_REV=2147483648]="DRM_REV"}(H||(H={})),function(e){e[e.DPMCRM_AUTO=1]="DPMCRM_AUTO",e[e.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",e[e.DPMCRM_SKIP=0]="DPMCRM_SKIP",e[e.DPMCRM_REV=2147483648]="DPMCRM_REV"}(K||(K={})),function(e){e[e.GTM_INVERTED=1]="GTM_INVERTED",e[e.GTM_ORIGINAL=2]="GTM_ORIGINAL",e[e.GTM_SKIP=0]="GTM_SKIP",e[e.GTM_REV=2147483648]="GTM_REV"}(W||(W={})),function(e){e[e.IPM_AUTO=1]="IPM_AUTO",e[e.IPM_GENERAL=2]="IPM_GENERAL",e[e.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",e[e.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",e[e.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",e[e.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",e[e.IPM_SKIP=0]="IPM_SKIP",e[e.IPM_REV=2147483648]="IPM_REV"}(Y||(Y={})),function(e){e[e.IRSM_MEMORY=1]="IRSM_MEMORY",e[e.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",e[e.IRSM_BOTH=4]="IRSM_BOTH"}(Q||(Q={})),function(e){e[e.IRT_NO_RESULT=0]="IRT_NO_RESULT",e[e.IRT_ORIGINAL_IMAGE=1]="IRT_ORIGINAL_IMAGE",e[e.IRT_COLOUR_CLUSTERED_IMAGE=2]="IRT_COLOUR_CLUSTERED_IMAGE",e[e.IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE=4]="IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE",e[e.IRT_TRANSFORMED_GRAYSCALE_IMAGE=8]="IRT_TRANSFORMED_GRAYSCALE_IMAGE",e[e.IRT_PREDETECTED_REGION=16]="IRT_PREDETECTED_REGION",e[e.IRT_PREPROCESSED_IMAGE=32]="IRT_PREPROCESSED_IMAGE",e[e.IRT_BINARIZED_IMAGE=64]="IRT_BINARIZED_IMAGE",e[e.IRT_TEXT_ZONE=128]="IRT_TEXT_ZONE",e[e.IRT_CONTOUR=256]="IRT_CONTOUR",e[e.IRT_LINE_SEGMENT=512]="IRT_LINE_SEGMENT",e[e.IRT_FORM=1024]="IRT_FORM",e[e.IRT_SEGMENTATION_BLOCK=2048]="IRT_SEGMENTATION_BLOCK",e[e.IRT_TYPED_BARCODE_ZONE=4096]="IRT_TYPED_BARCODE_ZONE",e[e.IRT_PREDETECTED_QUADRILATERAL=8192]="IRT_PREDETECTED_QUADRILATERAL"}(J||(J={})),function(e){e[e.LM_SKIP=0]="LM_SKIP",e[e.LM_AUTO=1]="LM_AUTO",e[e.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",e[e.LM_LINES=8]="LM_LINES",e[e.LM_STATISTICS=4]="LM_STATISTICS",e[e.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",e[e.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",e[e.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",e[e.LM_CENTRE=128]="LM_CENTRE",e[e.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",e[e.LM_REV=2147483648]="LM_REV"}(X||(X={})),function(e){e[e.PDFRM_RASTER=1]="PDFRM_RASTER",e[e.PDFRM_AUTO=2]="PDFRM_AUTO",e[e.PDFRM_VECTOR=4]="PDFRM_VECTOR",e[e.PDFRM_REV=2147483648]="PDFRM_REV"}(Z||(Z={})),function(e){e[e.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",e[e.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",e[e.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",e[e.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(j||(j={})),function(e){e[e.RPM_AUTO=1]="RPM_AUTO",e[e.RPM_GENERAL=2]="RPM_GENERAL",e[e.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",e[e.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",e[e.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",e[e.RPM_SKIP=0]="RPM_SKIP",e[e.RPM_REV=2147483648]="RPM_REV"}(q||(q={})),function(e){e[e.RCT_PIXEL=1]="RCT_PIXEL",e[e.RCT_PERCENTAGE=2]="RCT_PERCENTAGE"}($||($={})),function(e){e[e.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",e[e.RT_RAW_TEXT=1]="RT_RAW_TEXT",e[e.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",e[e.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT"}(z||(z={})),function(e){e[e.SUM_AUTO=1]="SUM_AUTO",e[e.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",e[e.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",e[e.SUM_SKIP=0]="SUM_SKIP",e[e.SUM_REV=2147483648]="SUM_REV"}(ee||(ee={})),function(e){e[e.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",e[e.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",e[e.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",e[e.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",e[e.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",e[e.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED"}(te||(te={})),function(e){e[e.TFM_AUTO=1]="TFM_AUTO",e[e.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",e[e.TFM_SKIP=0]="TFM_SKIP",e[e.TFM_REV=2147483648]="TFM_REV"}(ne||(ne={})),function(e){e[e.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",e[e.TROM_POSITION=2]="TROM_POSITION",e[e.TROM_FORMAT=4]="TROM_FORMAT",e[e.TROM_SKIP=0]="TROM_SKIP",e[e.TROM_REV=2147483648]="TROM_REV"}(re||(re={})),function(e){e[e.TDM_AUTO=1]="TDM_AUTO",e[e.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",e[e.TDM_SKIP=0]="TDM_SKIP",e[e.TDM_REV=2147483648]="TDM_REV"}(oe||(oe={}));export{w as BarcodeReader,b as EnumBarcodeColourMode,N as EnumBarcodeComplementMode,L as EnumBarcodeFormat,B as EnumBarcodeFormat_2,P as EnumBinarizationMode,F as EnumClarityCalculationMethod,V as EnumClarityFilterMode,x as EnumColourClusteringMode,k as EnumColourConversionMode,U as EnumConflictMode,K as EnumDPMCodeReadingMode,G as EnumDeblurMode,H as EnumDeformationResistingMode,y as EnumErrorCode,W as EnumGrayscaleTransformationMode,O as EnumIMResultDataType,C as EnumImagePixelFormat,Y as EnumImagePreprocessingMode,Q as EnumIntermediateResultSavingMode,J as EnumIntermediateResultType,X as EnumLocalizationMode,Z as EnumPDFReadingMode,j as EnumQRCodeErrorCorrectionLevel,q as EnumRegionPredetectionMode,$ as EnumResultCoordinateType,z as EnumResultType,ee as EnumScaleUpMode,te as EnumTerminatePhase,ne as EnumTextFilterMode,re as EnumTextResultOrderMode,oe as EnumTextureDetectionMode}; diff --git a/dist/dbr.ui.html b/dist/dbr.ui.html index 1ec381c..2b478f2 100644 --- a/dist/dbr.ui.html +++ b/dist/dbr.ui.html @@ -10,7 +10,7 @@
-
+
@@ -23,7 +23,7 @@ -
+
- x + x
diff --git a/dist/types/class/barcodereader.d.ts b/dist/types/class/barcodereader.d.ts index 81b2c51..86866ee 100644 --- a/dist/types/class/barcodereader.d.ts +++ b/dist/types/class/barcodereader.d.ts @@ -10,20 +10,7 @@ import { ImageSource } from '../interface/imagesource'; import { DSImage } from '../interface/dsimage'; import { ScanSettings } from '../interface/scanSettings'; import { ScannerPlayCallbackInfo } from '../interface/scannerplaycallbackinfo'; -/** - * The `BarcodeReader` class is used for image decoding - * Comparing to `BarcodeScanner`, the default decoding settings are more accurate but slower. - * ```js - * let pReader = null; - * (async()=>{ - * let reader = await (pReader = pReader || Dynamsoft.DBR.BarcodeReader.createInstance()); - * let results = await reader.decode(imageSource); - * for(let result of results){ - * console.log(result.barcodeText); - * } - * })(); - * ``` - */ +import { Warning } from '../interface/warning'; export default class BarcodeReader { private static _jsVersion; private static _jsEditVersion; @@ -41,7 +28,7 @@ export default class BarcodeReader { * ``` * For convenience, you can set `license` in `script` tag instead. * ```html - * + * * ``` */ static set license(license: string); @@ -96,7 +83,7 @@ export default class BarcodeReader { * If the auto-explored engine location is incorrect, you can manually specify the engine location. * The property needs to be set before [[loadWasm]]. * ```js - * Dynamsoft.DBR.BarcodeReader.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.0.2/dist/"; + * Dynamsoft.DBR.BarcodeReader.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.2.11/dist/"; * await Dynamsoft.DBR.BarcodeReader.loadWasm(); * ``` */ @@ -116,8 +103,6 @@ export default class BarcodeReader { /** @ignore */ static _isShowRelDecodeTimeInResults: boolean; /** @ignore */ - _canvasMaxWH: number; - /** @ignore */ static _onLog: any; /** @ignore */ static _bWasmDebug: boolean; @@ -162,8 +147,6 @@ export default class BarcodeReader { /** @ignore */ static isDSImage(value: any): boolean; /** @ignore */ - static isCameraEnhancer(value: any): boolean; - /** @ignore */ static isDCEFrame(value: any): boolean; /** @ignore */ _instanceID: number; @@ -246,7 +229,7 @@ export default class BarcodeReader { * The url of the default scanner UI. * Can only be changed before `createInstance`. * ```js - * Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.0.2/dist/dbr.ui.html"; + * Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.2.11/dist/dbr.ui.html"; * let pScanner = null; * (async()=>{ * let scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); @@ -255,6 +238,8 @@ export default class BarcodeReader { * ``` */ static set defaultUIElementURL(value: string); + static onWarning: (warning: Warning) => void; + protected static _fireHTTPSWarnning(): void; /** @ignore */ intervalTime: number; /** @ignore */ @@ -266,7 +251,7 @@ export default class BarcodeReader { protected array_decodeFrameTimeCost: any[]; /** @ignore */ protected _indexCurrentDecodingFrame: number; - protected resultsOverlay: HTMLCanvasElement; + protected _dbrDrawingLayer: any; protected _bPauseScan: boolean; protected _intervalDetectVideoPause: number; /** @ignore */ @@ -342,6 +327,7 @@ export default class BarcodeReader { * @ignore */ private set whenToVibrateforSuccessfulRead(value); + protected captureAndDecodeInParallel: boolean; /** * Set the style used when filling in located barcode. * @category UI @@ -360,8 +346,9 @@ export default class BarcodeReader { private _dce; protected set dce(value: CameraEnhancer); protected get dce(): CameraEnhancer; - private dceConfig; - private imgSource; + protected _drawingItemNamespace: any; + private _dceControler; + private _imgSource; private callbackCameraChange?; private callbackResolutionChange?; private callbackCameraClose?; @@ -370,9 +357,9 @@ export default class BarcodeReader { /** @ignore */ set maxCvsSideLength(value: number); get maxCvsSideLength(): number; - private updateDCEConfig; - private releaseDCEConfig; - setImageSource(imgSource: ImageSource | CameraEnhancer): void; + private _registerDCEControler; + private _logoutDCEControler; + setImageSource(imgSource: ImageSource | CameraEnhancer, options?: any): Promise; /** * Before most operations, `loadWasm` needs to be excuted firstly. * Most time, you do not need excute `loadWasm` manually. Because when you excute [[createInstance]], `loadWasm` will be excuted implicitly. @@ -588,7 +575,9 @@ export default class BarcodeReader { private _decode_Url; private _decode_FilePath; /** @ignore */ - static fixResultLocationWhenFilterRegionInJs(region: any, results: TextResult[], sx: number, sy: number, sWidth: number, sHeight: number, dWidth: number, dHeight: number): void; + static recalculateResultLocation(results: Array<{ + localizationResult: any; + }>, sx: number, sy: number, sWidth: number, sHeight: number, dWidth: number, dHeight: number): void; /** @ignore */ static BarcodeReaderException(ag0: any, ag1: any): BarcodeReaderException; protected _handleRetJsonString(objRet: any): any; @@ -684,7 +673,9 @@ export default class BarcodeReader { * @ignore */ protected _getVideoFrame(): DCEFrame; - protected _drawResults(results: TextResult[]): void; + protected _drawResults(results: Array<{ + localizationResult: any; + }>): void; private _tempSolutionStatus; /** * Bind UI, open the camera, start recognizing. @@ -707,7 +698,7 @@ export default class BarcodeReader { * Pause the recognizing process. * @category Pause and Resume */ - pauseScanning(): void; + pauseScanning(options?: any): void; /** * Resume the recognizing process. * @category Pause and Resume diff --git a/dist/types/class/barcodescanner.d.ts b/dist/types/class/barcodescanner.d.ts index c8fc0ee..1c1eb25 100644 --- a/dist/types/class/barcodescanner.d.ts +++ b/dist/types/class/barcodescanner.d.ts @@ -5,6 +5,7 @@ import BarcodeReader from './barcodereader'; import { RuntimeSettings } from '../interface/runtimesettings'; import { Region } from '../interface/region'; import { DCEFrame } from 'dynamsoft-camera-enhancer'; +import { Warning } from '../interface/warning'; /** * The `BarcodeScanner` class is used for video decoding. * ```js @@ -21,6 +22,10 @@ export default class BarcodeScanner extends BarcodeReader { * Get the current version. */ static get version(): string; + static onWarning: (warning: Warning) => void; + protected static _fireHTTPSWarnning(): void; + onWarning: (warning: Warning) => void; + private _fireResolutionWarning; /** @ignore */ /** * Get HTML element containing the `BarcodeScanner` instance. @@ -87,6 +92,9 @@ export default class BarcodeScanner extends BarcodeReader { onFrameRead?: (results: TextResult[]) => void; get onUnduplicatedRead(): (txt: string, result: TextResult) => void; set onUnduplicatedRead(value: (txt: string, result: TextResult) => void); + get video(): HTMLVideoElement; + set videoSrc(source: string | MediaStream | MediaSource | Blob); + get videoSrc(): string | MediaStream | MediaSource | Blob; private _assertOpen; /** * Set the style used when filling the mask beyond the region. @@ -264,6 +272,10 @@ export default class BarcodeScanner extends BarcodeReader { */ set ifShowScanRegionMask(value: boolean); get ifShowScanRegionMask(): boolean; + set ifSaveLastUsedCamera(value: boolean); + get ifSaveLastUsedCamera(): boolean; + set ifSkipCameraInspection(value: boolean); + get ifSkipCameraInspection(): boolean; /** * Stop the video, and release the camera. * ```js @@ -304,7 +316,7 @@ export default class BarcodeScanner extends BarcodeReader { * ``` * @category Play and Pause */ - pauseScan(): void; + pauseScan(options?: any): void; /** * Resume the decoding process. * ```js @@ -470,7 +482,7 @@ export default class BarcodeScanner extends BarcodeReader { * @fires [[onPlayed]],[[onUniqueRead]],[[onFrameRead]] * @category Open and Close */ - open(): Promise; + open(): Promise; /** * Bind UI, open the camera, but not decode. * ```js @@ -482,7 +494,7 @@ export default class BarcodeScanner extends BarcodeReader { * @fires [[onPlayed]],[[onUniqueRead]],[[onFrameRead]] * @category Open and Close */ - openVideo(): Promise; + openVideo(): Promise; /** * Stop decoding, release camera, unbind UI. * ```js @@ -499,7 +511,7 @@ export default class BarcodeScanner extends BarcodeReader { /** * Bind UI, open the camera, start decoding, and remove the UIElement `display` style if the original style is `display:none;`. * ```js - * await scanner.setUIElement("https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.0.2/dist/dbr.ui.html"); + * await scanner.setUIElement("https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.2.11/dist/dbr.ui.html"); * scanner.onUniqueRead = (txt, result) => { alert(txt); console.log(result); }; * await scanner.show(); * // await scanner.hide(); @@ -507,7 +519,7 @@ export default class BarcodeScanner extends BarcodeReader { * @fires [[onPlayed]],[[onUniqueRead]],[[onFrameRead]] * @category Open and Close */ - show(): Promise; + show(): Promise; /** * Bind UI, open the camera, but not decode, and remove the UIElement `display` style if the original style is `display:none;`. * ```js @@ -518,7 +530,7 @@ export default class BarcodeScanner extends BarcodeReader { * @fires [[onPlayed]],[[onUniqueRead]],[[onFrameRead]] * @category Open and Close */ - showVideo(): Promise; + showVideo(): Promise; /** * Stop decoding, release camera, unbind UI, and set the Element as `display:none;`. * ```js diff --git a/dist/types/dbr.d.ts b/dist/types/dbr.d.ts index 8ca23a0..1b6b735 100644 --- a/dist/types/dbr.d.ts +++ b/dist/types/dbr.d.ts @@ -32,5 +32,10 @@ import { EnumTextFilterMode } from "./enum/enumtextfiltermode"; import { EnumTextResultOrderMode } from "./enum/enumtextresultordermode"; import { EnumTextureDetectionMode } from "./enum/enumtexturedetectionmode"; import { TextResult } from "./interface/textresult"; -export { BarcodeReader, BarcodeScanner, EnumBarcodeColourMode, EnumBarcodeComplementMode, EnumBarcodeFormat, EnumBarcodeFormat_2, EnumBinarizationMode, EnumClarityCalculationMethod, EnumClarityFilterMode, EnumColourClusteringMode, EnumColourConversionMode, EnumConflictMode, EnumDeblurMode, EnumDeformationResistingMode, EnumDPMCodeReadingMode, EnumErrorCode, EnumGrayscaleTransformationMode, EnumImagePixelFormat, EnumImagePreprocessingMode, EnumIMResultDataType, EnumIntermediateResultSavingMode, EnumIntermediateResultType, EnumLocalizationMode, EnumPDFReadingMode, EnumQRCodeErrorCorrectionLevel, EnumRegionPredetectionMode, EnumResultCoordinateType, EnumResultType, EnumScaleUpMode, EnumTerminatePhase, EnumTextFilterMode, EnumTextResultOrderMode, EnumTextureDetectionMode, TextResult, }; +import { RuntimeSettings } from "./interface/runtimesettings"; +import { ScanSettings } from "./interface/scanSettings"; +import { Region } from "./interface/region"; +import { ImageSource } from "./interface/imagesource"; +import { DSImage } from "./interface/dsimage"; +export { BarcodeReader, BarcodeScanner, EnumBarcodeColourMode, EnumBarcodeComplementMode, EnumBarcodeFormat, EnumBarcodeFormat_2, EnumBinarizationMode, EnumClarityCalculationMethod, EnumClarityFilterMode, EnumColourClusteringMode, EnumColourConversionMode, EnumConflictMode, EnumDeblurMode, EnumDeformationResistingMode, EnumDPMCodeReadingMode, EnumErrorCode, EnumGrayscaleTransformationMode, EnumImagePixelFormat, EnumImagePreprocessingMode, EnumIMResultDataType, EnumIntermediateResultSavingMode, EnumIntermediateResultType, EnumLocalizationMode, EnumPDFReadingMode, EnumQRCodeErrorCorrectionLevel, EnumRegionPredetectionMode, EnumResultCoordinateType, EnumResultType, EnumScaleUpMode, EnumTerminatePhase, EnumTextFilterMode, EnumTextResultOrderMode, EnumTextureDetectionMode, TextResult, RuntimeSettings, ScanSettings, Region, ImageSource, DSImage }; //# sourceMappingURL=dbr.d.ts.map \ No newline at end of file diff --git a/dist/types/interface/scanSettings.d.ts b/dist/types/interface/scanSettings.d.ts index 13586c0..3b91104 100644 --- a/dist/types/interface/scanSettings.d.ts +++ b/dist/types/interface/scanSettings.d.ts @@ -49,5 +49,6 @@ export interface ScanSettings { * @see [[whenToVibrateforSuccessfulRead]] */ vibrateDuration?: number; + captureAndDecodeInParallel?: boolean; } //# sourceMappingURL=scanSettings.d.ts.map \ No newline at end of file diff --git a/dist/types/interface/warning.d.ts b/dist/types/interface/warning.d.ts new file mode 100644 index 0000000..020ae27 --- /dev/null +++ b/dist/types/interface/warning.d.ts @@ -0,0 +1,5 @@ +export interface Warning { + id: number; + message: string; +} +//# sourceMappingURL=warning.d.ts.map \ No newline at end of file diff --git a/legal.txt b/legal.txt index 1ddb66c..60eb5c2 100644 --- a/legal.txt +++ b/legal.txt @@ -962,186 +962,4 @@ Code generated by the Protocol Buffer compiler is owned by the owner of the input file used when generating it. This code is not standalone and requires a support library to be linked with it. This support library is itself covered by the above license. -=================================================================================== - - -================================== SOFTWARES USED IN SAMPLES ===================================== - - -Webpack - -Copyright JS Foundation and other contributors - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - -Angular - -The MIT License - -Copyright (c) 2010-2019 Google LLC. http://angular.io/license - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - - - -React - -MIT License - -Copyright (c) Facebook, Inc. and its affiliates. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - - -Vue - -The MIT License (MIT) - -Copyright (c) 2013-present, Yuxi (Evan) You - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - - - -RequireJS - -Copyright jQuery Foundation and other contributors, https://jquery.org/ - -This software consists of voluntary contributions made by many -individuals. For exact contribution history, see the revision history -available at https://github.com/requirejs/requirejs - -The following license applies to all parts of this software except as -documented below: - -==== - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -==== - -Copyright and related rights for sample code are waived via CC0. Sample -code is defined as all source code displayed within the prose of the -documentation. - -CC0: http://creativecommons.org/publicdomain/zero/1.0/ - -==== - -Files located in the node_modules directory, and certain utilities used -to build or test the software in the test and dist directories, are -externally maintained libraries used by this software which have their own -licenses; we recommend you read them, as their terms may differ from the -terms above. - - - -eruda - -The MIT License (MIT) - -Copyright (c) 2016-present liriliri - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - +=================================================================================== \ No newline at end of file diff --git a/package.json b/package.json index 44fa832..439bd58 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dynamsoft-javascript-barcode", - "version": "9.0.2", + "version": "9.2.11", "description": "Dynamsoft Barcode Reader JS is a recognition SDK which enables you to embed barcode reading functionality in your web, desktop, and mobile applications. With a few lines of JavaScript code, you can develop a robust application to scan a linear barcode, QR Code, DaraMatrix, PDF417, and Aztec Code.", "files": [ "/dist", @@ -9,11 +9,11 @@ "/samples.url" ], "homepage": "https://www.dynamsoft.com/barcode-reader/sdk-javascript", - "main": "./dist/dbr.browser.pure.js", - "module": "./dist/dbr.browser.pure.esm.js", + "main": "./dist/dbr.pure.js", + "module": "./dist/dbr.pure.esm.js", "exports": { - "import": "./dist/dbr.browser.pure.esm.js", - "require": "./dist/dbr.browser.pure.js" + "import": "./dist/dbr.pure.esm.js", + "require": "./dist/dbr.pure.js" }, "sideEffects": false, "types": "./dist/types/dbr.d.ts", @@ -21,7 +21,7 @@ "name": "Dynamsoft", "url": "https://www.dynamsoft.com" }, - "license": "SEE LICENSE IN LICENSE.txt", + "license": "SEE LICENSE IN LICENSE", "repository": { "type": "git", "url": "https://github.com/dynamsoft/barcode-reader-javascript.git" @@ -52,18 +52,16 @@ "test": "node ./samples/node/helloworld.js" }, "devDependencies": { - "@babel/core": "7.15.8", - "@babel/preset-env": "7.15.8", "@rollup/plugin-node-resolve": "13.0.5", "@rollup/plugin-replace": "3.0.0", "@rollup/plugin-typescript": "8.3.0", "@types/node": "16.11.2", "@types/node-fetch": "2.6.1", "@types/node-localstorage": "1.3.0", - "detect-browser-node-ssr": "^1.0.1", - "dlsjs": "http://npm.dynamsoftwebtwain.com/dlsjs/-/dlsjs-1.0.17.tgz", - "dm-browser-info": "http://npm.dynamsoftwebtwain.com/dm-browser-info/-/dm-browser-info-1.0.3.tgz", - "dm-curscript-path": "http://npm.dynamsoftwebtwain.com/dm-curscript-path/-/dm-curscript-path-1.0.2.tgz", + "detect-browser-node-ssr": "^2.0.0", + "dlsjs": "http://npm.dynamsoftwebtwain.com/dlsjs/-/dlsjs-1.0.22.tgz", + "dm-browser-info": "http://npm.dynamsoftwebtwain.com/dm-browser-info/-/dm-browser-info-1.0.5.tgz", + "dm-curscript-path": "http://npm.dynamsoftwebtwain.com/dm-curscript-path/-/dm-curscript-path-1.0.3.tgz", "fs-extra": "8.1.0", "mutable-promise": "1.1.13", "rollup": "2.58.0", @@ -87,6 +85,6 @@ }, "dependencies": { "dm-howler": "^2.2.4", - "dynamsoft-camera-enhancer": "2.3.2" + "dynamsoft-camera-enhancer": "^3.0.0" } } diff --git a/samples.url b/samples.url new file mode 100644 index 0000000..119e8f1 --- /dev/null +++ b/samples.url @@ -0,0 +1,2 @@ +[InternetShortcut] +URL=https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.2.11 \ No newline at end of file