diff --git a/API_Reference_BarcodeScanner.url b/API_Reference_BarcodeScanner.url new file mode 100644 index 0000000..1d92f1d --- /dev/null +++ b/API_Reference_BarcodeScanner.url @@ -0,0 +1,2 @@ +[InternetShortcut] +URL=https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/barcode-scanner.html \ No newline at end of file diff --git a/API Reference.url b/API_Reference_Foundational.url similarity index 100% rename from API Reference.url rename to API_Reference_Foundational.url diff --git a/LICENSE b/LICENSE index e734929..8b9bf8f 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright © 2003–2024 Dynamsoft. All Rights Reserved. +Copyright © 2003–2025 Dynamsoft. All Rights Reserved. The use of this software is governed by the Dynamsoft Terms and Conditions. URL=https://www.dynamsoft.com/barcode-reader/license-agreement/#javascript \ No newline at end of file diff --git a/README.html b/README.html new file mode 100644 index 0000000..6093825 --- /dev/null +++ b/README.html @@ -0,0 +1,420 @@ + + + Dynamsoft Barcode Reader for Your Website - User Guide + + + + + + +
+

Barcode Scanner JavaScript Edition - User Guide

+ +

This user guide provides a step-by-step walkthrough of a "Hello World" web application using the BarcodeScanner JavaScript Edition.

+

The BarcodeScanner class offers the following features:

+ +

We recommend using this guide as a reference when creating your own application. If you are looking for a fully customizable barcode decoding library, you are welcome to use the Foundational APIs. Before starting, ensure the basic requirements are met.

+ + +
+

[!TIP]
+ Please refer to system requirements for more details.

+
+

License

+

Trial License

+ +

When getting started with Barcode Scanner, we recommend getting your own 30-day trial license

+ +
+

[!IMPORTANT]
+ The trial license can be renewed via the customer portal twice, each time for another 15 days, giving you a total of 60 days to develop your own application using the solution. Please contact the Dynamsoft Support Team if you need more time for a full evaluation.

+
+

Full License

+

If you are fully satisfied with the solution and would like to move forward with a full license, please contact the Dynamsoft Sales Team.

+

Quick Start: Hello World Example

+
<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8" />
+    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+    <title>Dynamsoft Barcode Scanner - Hello World</title>
+    <script src="https://cdn.jsdelivr.net/npm/dynamsoft-barcode-reader-bundle@10.5.3000/dist/dbr.bundle.js"></script>
+  </head>
+
+  <body>
+    <h1 style="font-size: large">Dynamsoft Barcode Scanner</h1>
+
+    <script>
+      // Initialize the Dynamsoft Barcode Scanner
+      const barcodeScanner = new Dynamsoft.BarcodeScanner({
+        // Please don't forget to replace YOUR_LICENSE_KEY_HERE
+        license: "YOUR_LICENSE_KEY_HERE",
+      });
+      (async () => {
+        // Launch the scanner and wait for the result
+        const result = await barcodeScanner.launch();
+        alert(result.barcodeResults[0].text);
+      })();
+    </script>
+  </body>
+</html>
+
+

+ + Code in Github + +   + + Run via JSFiddle + +   + + Run in Dynamsoft + +

+

Step 1: Setting up the HTML and Including the Barcode Scanner

+

As outlined earlier, this guide will help you create a simple Hello World barcode scanning application using vanilla JavaScript. The full sample code is also available in the GitHub repository.

+

The first step before writing the code is to include the SDK in your application. You can simply include the SDK by using the precompiled script.

+
<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8" />
+    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+    <title>Dynamsoft Barcode Scanner - Hello World</title>
+    <script src="https://cdn.jsdelivr.net/npm/dynamsoft-barcode-reader-bundle@10.5.3000/dist/dbr.bundle.js"></script>
+  </head>
+
+  <body>
+    <h1 style="font-size: large">Dynamsoft Barcode Scanner</h1>
+  </body>
+
+</html>
+
+

In this example, we include the precompiled Barcode Scanner SDK script via public CDN in the header.

+
+
+
Use a public CDN
+

The simplest way to include the SDK is to use either the jsDelivr or UNPKG CDN.

+ +
  <script src="https://cdn.jsdelivr.net/npm/dynamsoft-barcode-reader-bundle@10.5.3000/dist/dbr.bundle.js"></script>
+
+ +
  <script src="https://unpkg.com/dynamsoft-barcode-reader-bundle@10.5.3000/dist/dbr.bundle.js"></script>
+
+

When using a framework such as React, Vue or Angular, we recommend adding the package as a dependency using a package manager such as npm or yarn:

+
  npm i dynamsoft-barcode-reader-bundle@10.5.3000
+  # or
+  yarn add dynamsoft-barcode-reader-bundle@10.5.3000
+
+

As for package managers like npm or yarn, you likely need to specify the location of the engine files as a link to a CDN. Please see the BarcodeScannerConfig API for a code snippet on how to set the engineResourcePaths.

+
+
+
Host the SDK yourself
+

Alternatively, you may choose to download the SDK and host the files on your own server or preferred CDN. This approach provides better control over versioning and availability.

+ +
  npm i dynamsoft-barcode-reader-bundle@10.5.3000
+
+

The resources are located at the path node_modules/<pkg>, without @<version>. You can copy it elsewhere and add @<version> tag. One more thing to do is to specify the engineResourcePaths so that the SDK can correctly locate the resources.

+
+

[!IMPORTANT]
+ Since "nodemodules" is reserved for Node.js dependencies, and in our case the package is used only as static resources, we recommend either renaming the "nodemodules" folder or moving the "dynamsoft-" packages to a dedicated folder for static resources in your project to facilitate self-hosting.

+
+

You can typically include SDK like this:

+
<script src="path/to/dynamsoft-barcode-reader-bundle@10.5.3000/dist/dbr.bundle.js"></script>
+
+
+
+

Barcode Scanner comes with a Ready-to-Use UI. When the Barcode Scanner launches, it creates a container which it populates with the Ready-to-Use UI.

+

Step 2: Initializing the Barcode Scanner

+
// Initialize the Dynamsoft Barcode Scanner
+const Barcodescanner = new Dynamsoft.BarcodeScanner({
+  // Please don't forget to replace YOUR_LICENSE_KEY_HERE
+  license: "YOUR_LICENSE_KEY_HERE", 
+});
+
+

This is the simplest way to initialize the Barcode Scanner. The configuration object must include a valid license key. Without it, the scanner will fail to launch and display an error. For help obtaining a license, see the licensing section.

+
+

[!TIP]
+ By default, the BarcodeScanner scans a single barcode at a time. However, it also supports a MULTI_UNIQUE scanning mode, which continuously scans and accumulates unique results in real time. You can enable this mode by modifying the BarcodeScannerConfig as follows:

+
+
// Initialize the Dynamsoft Barcode Scanner in MULTI_UNIQUE mode
+const barcodescanner = new Dynamsoft.BarcodeScanner({
+  license: "YOUR_LICENSE_KEY_HERE",
+  scanMode: Dynamsoft.EnumScanMode.SM_MULTI_UNIQUE,
+  showResultView: true,
+});
+
+

Step 3: Launching the Barcode Scanner

+
(async () => {
+  // Launch the scanner and wait for the result
+  const result = await barcodescanner.launch();
+  alert(result.barcodeResults[0].text);
+})();
+
+

Now that the Barcode Scanner has been initialized and configured, it is ready to be launched! Upon launch, the Barcode Scanner presents the main BarcodeScannerView UI in its container on the page, and is ready to start scanning. By default, we use the SINGLE scanning mode, which means only one decoding result will be included in the final result. In the code above, we directly alerted the successfully decoded barcode text on the page.

+
+

[!NOTE]
+ In the Hello World sample, after a successfully decoding process, the scanner closes and the user is met with an empty page. In order to open the scanner again, the user must refresh the page. You may choose to implement a more user-friendly behavior in a production environment, such as presenting the user with an option to re-open the Barcode Scanner upon closing it.

+
+

Next Steps

+

Now that you've implemented the basic functionality, here are some recommended next steps to further explore the capabilities of the Barcode Scanner

+
    +
  1. Learn how to Customize the Barcode Scanner
  2. +
  3. Check out the Official Samples and Demo
  4. +
  5. Learn about the APIs of BarcodeScanner
  6. +
+
+ + \ No newline at end of file diff --git a/README.md b/README.md index d9c886d..ec9c411 100644 --- a/README.md +++ b/README.md @@ -1,735 +1,245 @@ -# Barcode Reader for Your Website - User Guide - -[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-barcode-reader.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-barcode-reader.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-barcode-reader.svg) - -![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) - -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 the DBR-JS SDK into your website. - -Table of Contents - -- [Barcode Reader for Your Website - User Guide](#barcode-reader-for-your-website---user-guide) - - [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [About the code](#about-the-code) - - [Run the example](#run-the-example) - - [Preparing the SDK](#preparing-the-sdk) - - [Step 1: Include the SDK](#step-1-include-the-sdk) - - [Option 1: Use a public CDN](#option-1-use-a-public-cdn) - - [Option 2: Host the SDK yourself (optional)](#option-2-host-the-sdk-yourself-optional) - - [Step 2: Prepare the SDK](#step-2-prepare-the-sdk) - - [1. Specify the license](#1-specify-the-license) - - [2. \[Optional\] Specify the location of the "engine" files](#2-optional-specify-the-location-of-the-engine-files) - - [Using the SDK](#using-the-sdk) - - [Step 1: Preload the module](#step-1-preload-the-module) - - [Step 2: Create a CaptureVisionRouter object](#step-2-create-a-capturevisionrouter-object) - - [Step 3: Connect an image source](#step-3-connect-an-image-source) - - [Step 4: Register a result receiver](#step-4-register-a-result-receiver) - - [Step 5: Start process video frames](#step-5-start-process-video-frames) - - [Customizing the process](#customizing-the-process) - - [1. Adjust the preset template settings](#1-adjust-the-preset-template-settings) - - [1.1. Change barcode settings](#11-change-barcode-settings) - - [1.2. Retrieve the original image](#12-retrieve-the-original-image) - - [1.3. Change reading frequency to save power](#13-change-reading-frequency-to-save-power) - - [1.4. Specify a scan region](#14-specify-a-scan-region) - - [2. Edit the preset templates directly](#2-edit-the-preset-templates-directly) - - [3. \[Important\] Filter the results](#3-important-filter-the-results) - - [Method 1: Verify results across multiple frames](#method-1-verify-results-across-multiple-frames) - - [Method 2: Eliminate redundant results detected within a short time frame](#method-2-eliminate-redundant-results-detected-within-a-short-time-frame) - - [4. Add feedback](#4-add-feedback) - - [Customizing the UI](#customizing-the-ui) - - [Documentation](#documentation) - - [API Reference](#api-reference) - - [How to Upgrade](#how-to-upgrade) - - [Release Notes](#release-notes) +# Barcode Scanner JavaScript Edition - User Guide + +- [Barcode Scanner JavaScript Edition - User Guide](#barcode-scanner-javascript-edition---user-guide) + - [License](#license) + - [Trial License](#trial-license) + - [Full License](#full-license) + - [Quick Start: Hello World Example](#quick-start-hello-world-example) + - [Step 1: Setting up the HTML and Including the Barcode Scanner](#step-1-setting-up-the-html-and-including-the-barcode-scanner) + - [Step 2: Initializing the Barcode Scanner](#step-2-initializing-the-barcode-scanner) + - [Step 3: Launching the Barcode Scanner](#step-3-launching-the-barcode-scanner) - [Next Steps](#next-steps) -**Popular Examples** +This user guide provides a step-by-step walkthrough of a "Hello World" web application using the `BarcodeScanner` JavaScript Edition. -- Hello World - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.31/hello-world/hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/hello-world.html?ver=10.4.31&utm_source=github) -- Angular App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.31/hello-world/angular) -- React App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.31/hello-world/react) -- Vue App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.31/hello-world/vue) -- PWA App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.31/hello-world/pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/pwa/helloworld-pwa.html?ver=10.4.31&utm_source=github) -- WebView in Android and iOS - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.4.31/hello-world/webview) -- Read Driver Licenses - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.31/use-case/read-a-drivers-license/index.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/use-case/read-a-drivers-license/index.html?ver=10.4.31&utm_source=github) -- Fill A Form - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.31/use-case/fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/use-case/fill-a-form-with-barcode-reading.html?ver=10.4.31&utm_source=github) -- Show result information on the video - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.31/use-case/show-result-texts-on-the-video.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/use-case/show-result-texts-on-the-video.html?ver=10.4.31&utm_source=github) -- Debug Camera and Collect Video Frame - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.31/others/debug) +The `BarcodeScanner` class offers the following features: -You can also: +- High-level APIs that deliver core functionality with a single line of code. -- Try the Official Demo - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) \| [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=10.4.31&utm_source=github) -- Try Online Examples - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.4.31/) +- Pre-built UI components for fast and easy integration. -## Hello World - Simplest Implementation +- Intuitive configuration objects that streamline both algorithm and UI setup. -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. +We recommend using this guide as a reference when creating your own application. If you are looking for a fully customizable barcode decoding library, you are welcome to use the [Foundational APIs](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/index.html). Before starting, ensure the **basic requirements** are met. -**Basic Requirements** - - Internet connection - - A supported browser - - Camera access + + +- Internet connection +- A supported browser +- Camera access + +> [!TIP] +> Please refer to [system requirements](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/faq/system-requirement.html) for more details. + +## License + +### Trial License -The complete code of the "Hello World" example is shown below + + +When getting started with Barcode Scanner, we recommend [getting your own 30-day trial license](https://www.dynamsoft.com/customer/license/trialLicense/?product=dbr&utm_source=github&package=js) + + + +> [!IMPORTANT] +> The trial license can be renewed via the [customer portal](https://www.dynamsoft.com/customer/license/trialLicense/?product=dbr&utm_source=github&package=js) twice, each time for another 15 days, giving you a total of 60 days to develop your own application using the solution. Please contact the [Dynamsoft Support Team](https://www.dynamsoft.com/company/contact/) if you need more time for a full evaluation. + +### Full License + +If you are fully satisfied with the solution and would like to move forward with a full license, please contact the [Dynamsoft Sales Team](https://www.dynamsoft.com/company/contact/). + +## Quick Start: Hello World Example ```html - - -
- - - - + + + + + Dynamsoft Barcode Scanner - Hello World + + + + +

Dynamsoft Barcode Scanner

+ + + ``` - -

- + Code in Github   - + Run via JSFiddle   - + Run in Dynamsoft

-> Don't want to deal with too many details? We also have an **out-of-the-box** version: -> -> [Easy Barcode Scanner >>](https://github.com/Dynamsoft/easy-barcode-scanner) available for your reference. -> ```js -> // Scan instantly with a single function! -> let txt = await EasyBarcodeScanner.scan(); -> ``` - ------ - -#### About the code +### Step 1: Setting up the HTML and Including the Barcode Scanner -- `Dynamsoft.License.LicenseManager.initLicense()`: This method initializes the license for using the SDK in the application. Note that the string "**DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9**" used in this example points to an online license that requires a network connection to work. Read more on [Specify the license](#specify-the-license). +As outlined earlier, this guide will help you create a simple Hello World barcode scanning application using vanilla JavaScript. The full sample code is also available in the [GitHub repository](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.5.30). -- `Dynamsoft.Core.CoreModule.loadWasm(["dbr"])`: This is an optional code. Used to load wasm resources in advance, reducing latency between video playing and barcode decoding. +The first step before writing the code is to include the SDK in your application. You can simply include the SDK by using the precompiled script. -- `Dynamsoft.CVR.CaptureVisionRouter.createInstance()`: This method creates a `CaptureVisionRouter` object `cvRouter` which controls the entire process in three steps: - - **Retrieve Images from the Image Source** - - `cvRouter` connects to the image source through the [ImageSourceAdapter](https://www.dynamsoft.com/capture-vision/docs/core/architecture/input.html#image-source-adapter?lang=js) interface with the method `setInput()`. - ```js - cvRouter.setInput(cameraEnhancer); - ``` - > The image source in our case is a [CameraEnhancer](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/user-guide/index.html) object created with `Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView)` - - **Coordinate Image-Processing Tasks** - - The coordination happens behind the scenes. `cvRouter` starts the process by specifying a preset template "ReadSingleBarcode" in the method `startCapturing()`. - ```js - cvRouter.startCapturing("ReadSingleBarcode"); - ``` - - **Dispatch Results to Listening Objects** - - The processing results are returned through the [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs/core/architecture/output.html#captured-result-receiver?lang=js) interface. The `CapturedResultReceiver` object is registered to `cvRouter` via the method `addResultReceiver()`. For more information, please check out [Register a result receiver](#register-a-result-receiver). - ```js - cvRouter.addResultReceiver({/*The-CapturedResultReceiver-Object"*/}); - ``` - - Also note that reading from video is extremely fast and there could be many duplicate results. We can use a [filter](#filter-the-results-important) with result deduplication enabled to filter out the duplicate results. The object is registered to `cvRouter` via the method `addResultFilter()`. - ```js - cvRouter.addResultFilter(filter); - ``` - -> Read more on [Capture Vision Router](https://www.dynamsoft.com/capture-vision/docs/core/architecture/#capture-vision-router). - -### Run the example - -You can run the example deployed to [the Dynamsoft Demo Server](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/hello-world.html?ver=10.4.31&utm_source=github) or test it with [JSFiddle code editor](https://jsfiddle.net/DynamsoftTeam/csm2f9wb/). - -You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text show up under the video and the barcode location will be highlighted in the video feed. - -Alternatively, you can test locally by copying and pasting the code shown above into a local file (e.g. "hello-world.html") and opening it in your browser. +```html + + + + + + Dynamsoft Barcode Scanner - Hello World + + + + +

Dynamsoft Barcode Scanner

+ -> *Secure Contexts*: -> -> If you open the web page as `http://` , our SDK may not work correctly because the [MediaDevices: getUserMedia()](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) and other methods only work in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS, `localhost`, `127.0.0.1`, `file://`), in some or all supporting browsers. -> -> Regarding configuring https on your server, these guides for [nginx](https://nginx.org/en/docs/http/configuring_https_servers.html) / [IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) / [tomcat](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) / [nodejs](https://nodejs.org/docs/v0.4.1/api/tls.html) might help. -> -> If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/company/contact/?ver=10.4.31&utm_source=github&product=dbr&package=js). + +``` -## Preparing the SDK +In this example, we include the precompiled Barcode Scanner SDK script via public CDN in the header. -### Step 1: Include the SDK +
-#### Option 1: Use a public CDN +
+
Use a public CDN
-The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. +The simplest way to include the SDK is to use either the [**jsDelivr**](https://jsdelivr.com/) or [**UNPKG**](https://unpkg.com/) CDN. - jsDelivr ```html - + ``` - UNPKG ```html - - ``` - -- In some rare cases (such as some restricted areas), you might not be able to access the CDN. If this happens, you can use the following files for the test. - - ```html - + ``` - However, please **DO NOT** use `download2.dynamsoft.com` resources in a production application as they are for temporary testing purposes only. Instead, you can try hosting the SDK yourself. - -- In frameworks like React, Vue and Angular, you may want to add the package as a dependency. +When using a framework such as **React**, **Vue** or **Angular**, we recommend adding the package as a dependency using a package manager such as **npm** or **yarn**: ```sh - npm i dynamsoft-barcode-reader-bundle@10.4.3100 -E + npm i dynamsoft-barcode-reader-bundle@10.5.3000 # or - yarn add dynamsoft-barcode-reader-bundle@10.4.3100 -E + yarn add dynamsoft-barcode-reader-bundle@10.5.3000 ``` - NOTE that in frameworks, you need to [specify the engineResourcePaths](#specify-the-location-of-the-engine-files-optional). +As for package managers like **npm** or **yarn**, you likely need to specify the location of the engine files as a link to a CDN. Please see the [BarcodeScannerConfig API](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/barcode-scanner.html#barcodescannerconfig) for a code snippet on how to set the `engineResourcePaths`. +
-#### Option 2: Host the SDK yourself (optional) +
+
Host the SDK yourself
-Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. +Alternatively, you may choose to download the SDK and host the files on your own server or preferred CDN. This approach provides better control over versioning and availability. - From the website - [Download Dynamsoft Barcode Reader JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?ver=10.4.31&utm_source=github&product=dbr&package=js) + [Download Dynamsoft Barcode Reader JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?ver=10.5.30&utm_source=github&product=dbr&package=js) - The resources are located at path `dynamsoft/distributables/@`. + The resources are located at path `dynamsoft/distributables/`. - From npm ```sh - npm i dynamsoft-barcode-reader-bundle@10.4.3100 -E - # Compared with using CDN, you need to set up more resources. - npm i dynamsoft-capture-vision-std@1.4.21 -E - npm i dynamsoft-image-processing@2.4.31 -E + npm i dynamsoft-barcode-reader-bundle@10.5.3000 ``` - The resources are located at the path `node_modules/`, without `@`. You must copy "dynamsoft-xxx" packages elsewhere and add `@`. The `` can be obtained from `package.json` of each package. Another thing to do is to [specify the engineResourcePaths](#2-optional-specify-the-location-of-the-engine-files) so that the SDK can correctly locate the resources. + The resources are located at the path `node_modules/`, without `@`. You can copy it elsewhere and add `@` tag. One more thing to do is to [specify the engineResourcePaths](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/barcode-scanner.html#barcodescannerconfig) so that the SDK can correctly locate the resources. + + > [!IMPORTANT] > Since "node_modules" is reserved for Node.js dependencies, and in our case the package is used only as static resources, we recommend either renaming the "node_modules" folder or moving the "dynamsoft-" packages to a dedicated folder for static resources in your project to facilitate self-hosting. You can typically include SDK like this: ```html - -``` - -*Note*: - -* Certain legacy web application servers may lack support for the `application/wasm` mimetype for .wasm files. To address this, you have two options: - 1. Upgrade your web application server to one that supports the `application/wasm` mimetype. - 2. Manually define the mimetype on your server. You can refer to the guides for [apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) / [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) / [nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types). - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ``` - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Step 2: Prepare the SDK - -Before using the SDK, you need to configure a few things. - -#### 1. Specify the license - -To enable the SDK's functionality, you must provide a valid license. Utilize the API function initLicense to set your license key. - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); -``` - -As previously stated, the key "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" serves as a test license valid for 24 hours, applicable to any newly authorized browser. To test the SDK further, you can request a 30-day free trial license via the Request a Trial License link. - -> Upon registering a Dynamsoft account and obtaining the SDK package from the official website, Dynamsoft will automatically create a 30-day free trial license and embed the corresponding license key into all the provided SDK samples. - -#### 2. [Optional] Specify the location of the "engine" files - -This is usually only required with frameworks like Angular, React or Vue. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). - -```ts -// in framework -import { CoreModule } from "dynamsoft-barcode-reader-bundle"; -CoreModule.engineResourcePaths.rootDirectory = "https://cdn.jsdelivr.net/npm/"; + ``` -```js -// in pure js -Dynamsoft.Core.CoreModule.engineResourcePaths.rootDirectory = "https://cdn.jsdelivr.net/npm/"; -``` -These code uses the jsDelivr CDN as an example, feel free to change it to your own location. +
-## Using the SDK +
-### Step 1: Preload the module +Barcode Scanner comes with a **Ready-to-Use UI**. When the Barcode Scanner launches, it creates a container which it populates with the **Ready-to-Use UI**. -The image processing logic is encapsulated within .wasm library files, and these files may require some time for downloading. To enhance the speed, we advise utilizing the following method to preload the libraries. +### Step 2: Initializing the Barcode Scanner ```js -// Preload the .wasm files -await Dynamsoft.Core.CoreModule.loadWasm(["dbr"]); -``` - -### Step 2: Create a CaptureVisionRouter object - -To use the SDK, we first create a `CaptureVisionRouter` object. - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -let cvRouter = null; -try { - cvRouter = await Dynamsoft.CVR.CaptureVisionRouter.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -*Tip*: - -When creating a `CaptureVisionRouter` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pCvRouter` in the following code: - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -let pCvRouter = null; // The helper variable which is a promise of cvRouter -let cvRouter = null; - -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - cvRouter = await (pCvRouter = pCvRouter || Dynamsoft.CVR.CaptureVisionRouter.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -### Step 3: Connect an image source - -The `CaptureVisionRouter` object, denoted as `cvRouter`, is responsible for handling images provided by an image source. In our scenario, we aim to detect barcodes directly from a live video stream. To facilitate this, we initialize a `CameraEnhancer` object, identified as `cameraEnhancer`, which is specifically designed to capture image frames from the video feed and subsequently forward them to `cvRouter`. - -To enable video streaming on the webpage, we create a `CameraView` object referred to as `cameraView`, which is then passed to `cameraEnhancer`, and its content is displayed on the webpage. - -```html -
-``` - -```javascript -let cameraView = await Dynamsoft.DCE.CameraView.createInstance(); -let cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView); -document.querySelector("#camera-view-container").append(cameraView.getUIElement()); -cvRouter.setInput(cameraEnhancer); -``` - -### Step 4: Register a result receiver - -Once the image processing is complete, the results are sent to all the registered `CapturedResultReceiver` objects. Each `CapturedResultReceiver` object may encompass one or multiple callback functions associated with various result types. This time we use `onCapturedResultReceived`: - - -```javascript -const resultsContainer = document.querySelector("#results"); -const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver(); -resultReceiver.onCapturedResultReceived = (result) => { - if (result.barcodeResultItems?.length) { - resultsContainer.textContent = ''; - for (let item of result.barcodeResultItems) { - // In this example, the barcode results are displayed on the page below the video. - resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`; - } - } -}; -cvRouter.addResultReceiver(resultReceiver); -``` - -You can also write code like this. It is the same. - -```javascript -const resultsContainer = document.querySelector("#results"); -cvRouter.addResultReceiver({ onCapturedResultReceived: (result) => { - if (result.barcodeResultItems?.length) { - resultsContainer.textContent = ''; - for (let item of result.barcodeResultItems) { - // In this example, the barcode results are displayed on the page below the video. - resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`; - } - } -}}); -``` - -Check out [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/captured-result-receiver.html) for more information. - -### Step 5: Start process video frames - -With the setup now complete, we can proceed to process the images in two straightforward steps: - -1. Initiate the image source to commence image acquisition. In our scenario, we invoke the `open()` method on `cameraEnhancer` to initiate video streaming and simultaneously initiate the collection of images. These collected images will be dispatched to `cvRouter` as per its request. -2. Define a preset template to commence image processing. In our case, we utilize the "ReadSingleBarcode" template, specifically tailored for processing images containing a single barcode. - -```javascript -await cameraEnhancer.open(); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -*Note*: - -* `cvRouter` is engineered to consistently request images from the image source. -* Various preset templates are at your disposal for barcode reading: - -| Template Name | Function Description | -| ------------------------------ | -------------------------------------------------------------- | -| **ReadBarcodes_Default** | Scans multiple barcodes by default setting. | -| **ReadSingleBarcode** | Quickly scans a single barcode. | -| **ReadBarcodes_SpeedFirst** | Prioritizes speed in scanning multiple barcodes. | -| **ReadBarcodes_ReadRateFirst** | Maximizes the number of barcodes read. | -| **ReadBarcodes_Balance** | Balances speed and quantity in reading multiple barcodes. | -| **ReadDenseBarcodes** | Specialized in reading barcodes with high information density. | -| **ReadDistantBarcodes** | Capable of reading barcodes from extended distances. | - -Read more on the [preset CaptureVisionTemplates](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/preset-templates.html). - -## Customizing the process - -### 1. Adjust the preset template settings - -When making adjustments to some basic tasks, we often only need to modify [SimplifiedCaptureVisionSettings](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/interfaces/simplified-capture-vision-settings.html). - -#### 1.1. Change barcode settings - -The preset templates can be updated to meet different requirements. For example, the following code limits the barcode format to QR code. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.barcodeSettings.barcodeFormatIds = - Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -For a list of adjustable barcode settings, check out [SimplifiedBarcodeReaderSettings](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/interfaces/simplified-barcode-reader-settings.html). - -#### 1.2. Retrieve the original image - -Additionally, we have the option to modify the template to retrieve the original image containing the barcode. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.capturedResultItemTypes |= - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -Limit the barcode format to QR code, and retrieve the original image containing the barcode, at the same time. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.capturedResultItemTypes = - Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE | - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -Please be aware that it is necessary to update the `CapturedResultReceiver` object to obtain the original image. For instance: - -```javascript -const EnumCRIT = Dynamsoft.Core.EnumCapturedResultItemType; -resultReceiver.onCapturedResultReceived = (result) => { - if (result.barcodeResultItems?.length) { - // Use a filter to get the image on which barcodes are found. - let image = result.items.filter( - item => item.type === EnumCRIT.CRIT_ORIGINAL_IMAGE - )[0].imageData; - } -}; -``` - -#### 1.3. Change reading frequency to save power - -The SDK is initially configured to process images sequentially without any breaks. Although this setup maximizes performance, it can lead to elevated power consumption, potentially causing the device to overheat. In many cases, it's possible to reduce the reading speed while still satisfying business requirements. The following code snippet illustrates how to adjust the SDK to process an image every 500 milliseconds: - -> Please bear in mind that in the following code, if an image's processing time is shorter than 500 milliseconds, the SDK will wait for the full 500 milliseconds before proceeding to process the next image. Conversely, if an image's processing time exceeds 500 milliseconds, the subsequent image will be processed immediately upon completion. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.minImageCaptureInterval = 500; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -#### 1.4. Specify a scan region - -We can specify a scan region to allow the SDK to process only part of the image, improving processing speed. The code snippet below demonstrates how to do this using the `cameraEnhancer` image source. - -```javascript -cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView); -// In this example, we set the scan region to cover the central 25% of the image. -cameraEnhancer.setScanRegion({ - x: 25, - y: 25, - width: 50, - height: 50, - isMeasuredInPercentage: true, +// Initialize the Dynamsoft Barcode Scanner +const Barcodescanner = new Dynamsoft.BarcodeScanner({ + // Please don't forget to replace YOUR_LICENSE_KEY_HERE + license: "YOUR_LICENSE_KEY_HERE", }); ``` -*Note*: - -1. By configuring the region at the image source, images are cropped before processing, removing the need to adjust any further processing settings. -2. `cameraEnhancer` enhances interactivity by overlaying a mask on the video, clearly marking the scanning region. - -*See Also*: - -[CameraEnhancer::setScanRegion](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/acquisition.html#setscanregion) - - - - - - -### 2. Edit the preset templates directly - -The preset templates have many more settings that can be customized to suit your use case best. If you [download the SDK from Dynamsoft website](https://www.dynamsoft.com/barcode-reader/downloads/1000003-confirmation/), you can find the templates under - -* "/dynamsoft-barcode-reader-js-10.4.3100/dynamsoft/templates/" - -Upon completing the template editing, you can invoke the `initSettings` method and provide it with the template path as an argument. - -```javascript -await cvRouter.initSettings("PATH-TO-THE-FILE"); // E.g. "https://your-website/ReadSingleBarcode.json") -await cvRouter.startCapturing("ReadSingleBarcode"); // Make sure the name matches one of the CaptureVisionTemplates in the template JSON file. -``` - -### 3. [Important] Filter the results - -When processing video frames, the same barcode is often detected multiple times. To improve the user experience, we can use the [MultiFrameResultCrossFilter](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/utility/multi-frame-result-cross-filter.html) object. This object provides two methods for handling duplicate detections, which can be used independently or together, depending on what best suits your application needs: - -#### Method 1: Verify results across multiple frames - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultCrossVerification("barcode", true); -await cvRouter.addResultFilter(filter); -``` - -*Note*: - -* `enableResultCrossVerification` was designed to cross-validate the outcomes across various frames in a video streaming scenario, enhancing the reliability of the final results. This validation is particularly crucial for barcodes with limited error correction capabilities, such as 1D codes. - -#### Method 2: Eliminate redundant results detected within a short time frame - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultDeduplication("barcode", true); -await cvRouter.addResultFilter(filter); -``` - -*Note*: - -* `enableResultDeduplication` was designed to prevent high usage in video streaming scenarios, addressing the repetitive processing of the same code within a short period of time. +This is the **simplest** way to initialize the Barcode Scanner. The configuration object must include a valid **license** key. Without it, the scanner will fail to launch and display an error. For help obtaining a license, see the [licensing](#license) section. -Initially, the filter is set to forget a result 3 seconds after it is first received. During this time frame, if an identical result appears, it is ignored. - -> It's important to know that in version 9.x or earlier, the occurrence of an identical result would reset the timer, thus reinitiating the 3-second count at that point. However, in version 10.2.10 and later, an identical result no longer resets the timer but is instead disregarded, and the duration count continues uninterrupted. - -Under certain circumstances, this duration can be extended with the method `setDuplicateForgetTime()`. - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.setDuplicateForgetTime(5000); // Extend the duration to 5 seconds. -await cvRouter.addResultFilter(filter); -``` - -You can also enable both options at the same time: +> [!TIP] +> By default, the `BarcodeScanner` scans a single barcode at a time. However, it also supports a `MULTI_UNIQUE` scanning mode, which continuously scans and accumulates unique results in real time. You can enable this mode by modifying the [`BarcodeScannerConfig`](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/barcode-scanner.html#barcodescannerconfig) as follows: ```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultCrossVerification("barcode", true); -filter.enableResultDeduplication("barcode", true); -filter.setDuplicateForgetTime(5000); -await cvRouter.addResultFilter(filter); +// Initialize the Dynamsoft Barcode Scanner in MULTI_UNIQUE mode +const barcodescanner = new Dynamsoft.BarcodeScanner({ + license: "YOUR_LICENSE_KEY_HERE", + scanMode: Dynamsoft.EnumScanMode.SM_MULTI_UNIQUE, + showResultView: true, +}); ``` -### 4. Add feedback - -When a barcode is detected within the video stream, its position is immediately displayed within the video. Furthermore, utilizing the "Dynamsoft Camera Enhancer" SDK, we can introduce feedback mechanisms, such as emitting a "beep" sound or triggering a "vibration". - -The following code snippet adds a "beep" sound for when a barcode is found: +### Step 3: Launching the Barcode Scanner ```js -const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver(); -resultReceiver.onDecodedBarcodesReceived = (result) => { - if (result.barcodeResultItems.length > 0) { - Dynamsoft.DCE.Feedback.beep(); - } -}; -cvRouter.addResultReceiver(resultReceiver); +(async () => { + // Launch the scanner and wait for the result + const result = await barcodescanner.launch(); + alert(result.barcodeResults[0].text); +})(); ``` -## Customizing the UI - -```javascript -// Create a CameraView instance with default settings -let cameraView = await Dynamsoft.DCE.CameraView.createInstance(); -// Create a CameraView instance with a specified HTML file path, typically a local or remote URL -let cameraView1 = await Dynamsoft.DCE.CameraView.createInstance('@engineResourcePath/dce.mobile-native.ui.html'); -// Create a CameraView instance within a specified DOM element -let cameraView2 = await Dynamsoft.DCE.CameraView.createInstance(document.getElementById('my-ui')); -// Create a CameraView instance using a custom UI file path -let cameraView3 = await Dynamsoft.DCE.CameraView.createInstance('url/to/my/ui.html'); - -// Get the UI element associated with the cameraView instance -let uiElement = cameraView.getUIElement(); -// Remove the camera selection dropdown from the CameraView's UI element -uiElement.shadowRoot.querySelector('.dce-sel-camera').remove(); -// Remove the resolution selection dropdown from the CameraView's UI element -uiElement.shadowRoot.querySelector('.dce-sel-resolution').remove(); -``` - -The UI is part of the auxiliary SDK "Dynamsoft Camera Enhancer", read more on how to [customize the UI](https://www.dynamsoft.com/barcode-reader/docs/core/programming/features/ui-customization-js.html?lang=js). - -## Documentation - -### API Reference - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=10.4.3100](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=10.4.3100). - - - -### How to Upgrade - -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/docs/web/programming/javascript/upgrade-guide/index.html?ver=10.4.3100&utm_source=github). - -### Release Notes +Now that the Barcode Scanner has been initialized and configured, it is ready to be launched! Upon launch, the Barcode Scanner presents the main **`BarcodeScannerView`** UI in its container on the page, and is ready to start scanning. By default, we use the `SINGLE` scanning mode, which means only one decoding result will be included in the final result. In the code above, we directly alerted the successfully decoded barcode text on the page. -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/index.html](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/index.html?ver=10.4.31&utm_source=github). +> [!NOTE] +> In the Hello World sample, after a successfully decoding process, the scanner closes and the user is met with an empty page. In order to open the scanner again, the user must refresh the page. You may choose to implement a more user-friendly behavior in a production environment, such as presenting the user with an option to re-open the Barcode Scanner upon closing it. ## Next Steps -Now that you have got the SDK integrated, you can choose to move forward in the following directions +Now that you've implemented the basic functionality, here are some recommended next steps to further explore the capabilities of the Barcode Scanner -1. Learn how to [Use in Framework](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-in-framework.html) -2. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=10.4.31) -3. Learn about the [APIs of the SDK](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/index.html?ver=10.4.3100) +1. Learn how to [Customize the Barcode Scanner](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/barcode-scanner-customization.html) +2. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=10.5.30) +3. Learn about the [APIs of BarcodeScanner](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/barcode-scanner.html?ver=10.5.3000) diff --git a/dist/DBR-PresetTemplates.json b/dist/DBR-PresetTemplates.json new file mode 100644 index 0000000..8bc3616 --- /dev/null +++ b/dist/DBR-PresetTemplates.json @@ -0,0 +1,628 @@ +{ + "CaptureVisionTemplates": [ + { + "Name": "ReadBarcodes_Default", + "ImageROIProcessingNameArray": [ + "roi-read-barcodes" + ], + "Timeout": 10000 + }, + { + "Name": "ReadBarcodes_SpeedFirst", + "ImageROIProcessingNameArray": [ + "roi-read-barcodes-speed-first" + ], + "Timeout": 10000 + }, + { + "Name": "ReadBarcodes_ReadRateFirst", + "ImageROIProcessingNameArray": [ + "roi-read-barcodes-read-rate" + ], + "Timeout": 100000 + }, + { + "Name": "ReadSingleBarcode", + "ImageROIProcessingNameArray": [ + "roi-read-single-barcode" + ], + "Timeout": 10000 + }, + { + "Name": "ReadBarcodes_Balance", + "ImageROIProcessingNameArray": [ + "roi-read-barcodes-balance" + ], + "Timeout": 100000 + }, + { + "Name": "ReadDenseBarcodes", + "ImageROIProcessingNameArray": [ + "roi-read-barcodes-dense" + ], + "Timeout": 10000 + }, + { + "Name": "ReadDistantBarcodes", + "ImageROIProcessingNameArray": [ + "roi-read-barcodes-distant" + ], + "Timeout": 10000 + } + ], + "TargetROIDefOptions": [ + { + "Name": "roi-read-barcodes", + "TaskSettingNameArray": [ + "task-read-barcodes" + ] + }, + { + "Name": "roi-read-barcodes-speed-first", + "TaskSettingNameArray": [ + "task-read-barcodes-speed-first" + ] + }, + { + "Name": "roi-read-barcodes-read-rate", + "TaskSettingNameArray": [ + "task-read-barcodes-read-rate" + ] + }, + { + "Name": "roi-read-single-barcode", + "TaskSettingNameArray": [ + "task-read-single-barcode" + ] + }, + { + "Name": "roi-read-barcodes-balance", + "TaskSettingNameArray": [ + "task-read-barcodes-balance" + ] + }, + { + "Name": "roi-read-barcodes-dense", + "TaskSettingNameArray": [ + "task-read-barcodes-dense" + ] + }, + { + "Name": "roi-read-barcodes-distant", + "TaskSettingNameArray": [ + "task-read-barcodes-distant" + ] + } + ], + "BarcodeFormatSpecificationOptions": [ + { + "Name": "bfs1", + "BarcodeFormatIds": [ + "BF_PDF417", + "BF_QR_CODE", + "BF_DATAMATRIX", + "BF_AZTEC", + "BF_MICRO_QR", + "BF_MICRO_PDF417", + "BF_DOTCODE" + ], + "MirrorMode": "MM_BOTH" + }, + { + "Name": "bfs2", + "BarcodeFormatIds": [ + "BF_ALL" + ], + "MirrorMode": "MM_NORMAL" + }, + { + "Name": "bfs1-speed-first", + "BaseBarcodeFormatSpecification": "bfs1" + }, + { + "Name": "bfs2-speed-first", + "BaseBarcodeFormatSpecification": "bfs2" + }, + { + "Name": "bfs1-read-rate-first", + "BaseBarcodeFormatSpecification": "bfs1" + }, + { + "Name": "bfs2-read-rate-first", + "BaseBarcodeFormatSpecification": "bfs2" + }, + { + "Name": "bfs1-single-barcode", + "BaseBarcodeFormatSpecification": "bfs1" + }, + { + "Name": "bfs2-single-barcode", + "BaseBarcodeFormatSpecification": "bfs2" + }, + { + "Name": "bfs1-balance", + "BaseBarcodeFormatSpecification": "bfs1" + }, + { + "Name": "bfs2-balance", + "BaseBarcodeFormatSpecification": "bfs2" + }, + { + "Name": "bfs1-dense", + "BaseBarcodeFormatSpecification": "bfs1" + }, + { + "Name": "bfs2-dense", + "BaseBarcodeFormatSpecification": "bfs2" + }, + { + "Name": "bfs1-distant", + "BaseBarcodeFormatSpecification": "bfs1" + }, + { + "Name": "bfs2-distant", + "BaseBarcodeFormatSpecification": "bfs2" + } + ], + "BarcodeReaderTaskSettingOptions": [ + { + "Name": "task-read-barcodes", + "ExpectedBarcodesCount": 0, + "LocalizationModes": [ + { + "Mode": "LM_CONNECTED_BLOCKS" + }, + { + "Mode": "LM_LINES" + } + ], + "DeblurModes": [ + { + "Mode": "DM_BASED_ON_LOC_BIN" + }, + { + "Mode": "DM_THRESHOLD_BINARIZATION" + } + ], + "BarcodeFormatSpecificationNameArray": [ + "bfs1", + "bfs2" + ], + "SectionImageParameterArray": [ + { + "Section": "ST_REGION_PREDETECTION", + "ImageParameterName": "ip-read-barcodes" + }, + { + "Section": "ST_BARCODE_LOCALIZATION", + "ImageParameterName": "ip-read-barcodes" + }, + { + "Section": "ST_BARCODE_DECODING", + "ImageParameterName": "ip-read-barcodes" + } + ] + }, + { + "Name": "task-read-barcodes-speed-first", + "ExpectedBarcodesCount": 0, + "LocalizationModes": [ + { + "Mode": "LM_SCAN_DIRECTLY", + "ScanDirection": 2 + }, + { + "Mode": "LM_CONNECTED_BLOCKS" + } + ], + "DeblurModes": [ + { + "Mode": "DM_BASED_ON_LOC_BIN" + }, + { + "Mode": "DM_THRESHOLD_BINARIZATION" + }, + { + "Mode": "DM_DEEP_ANALYSIS" + } + ], + "BarcodeFormatSpecificationNameArray": [ + "bfs1-speed-first", + "bfs2-speed-first" + ], + "SectionImageParameterArray": [ + { + "Section": "ST_REGION_PREDETECTION", + "ImageParameterName": "ip-read-barcodes-speed-first" + }, + { + "Section": "ST_BARCODE_LOCALIZATION", + "ImageParameterName": "ip-read-barcodes-speed-first" + }, + { + "Section": "ST_BARCODE_DECODING", + "ImageParameterName": "ip-read-barcodes-speed-first" + } + ] + }, + { + "Name": "task-read-barcodes-read-rate", + "ExpectedBarcodesCount": 999, + "LocalizationModes": [ + { + "Mode": "LM_CONNECTED_BLOCKS" + }, + { + "Mode": "LM_LINES" + }, + { + "Mode": "LM_STATISTICS" + } + ], + "DeblurModes": [ + { + "Mode": "DM_BASED_ON_LOC_BIN" + }, + { + "Mode": "DM_THRESHOLD_BINARIZATION" + }, + { + "Mode": "DM_DIRECT_BINARIZATION" + }, + { + "Mode": "DM_SMOOTHING" + } + ], + "BarcodeFormatSpecificationNameArray": [ + "bfs1-read-rate-first", + "bfs2-read-rate-first" + ], + "SectionImageParameterArray": [ + { + "Section": "ST_REGION_PREDETECTION", + "ImageParameterName": "ip-read-barcodes-read-rate" + }, + { + "Section": "ST_BARCODE_LOCALIZATION", + "ImageParameterName": "ip-read-barcodes-read-rate" + }, + { + "Section": "ST_BARCODE_DECODING", + "ImageParameterName": "ip-read-barcodes-read-rate" + } + ] + }, + { + "Name": "task-read-single-barcode", + "ExpectedBarcodesCount": 1, + "LocalizationModes": [ + { + "Mode": "LM_SCAN_DIRECTLY", + "ScanDirection": 2 + }, + { + "Mode": "LM_CONNECTED_BLOCKS" + } + ], + "DeblurModes": [ + { + "Mode": "DM_BASED_ON_LOC_BIN" + }, + { + "Mode": "DM_THRESHOLD_BINARIZATION" + }, + { + "Mode": "DM_DEEP_ANALYSIS" + } + ], + "BarcodeFormatSpecificationNameArray": [ + "bfs1-single-barcode", + "bfs2-single-barcode" + ], + "SectionImageParameterArray": [ + { + "Section": "ST_REGION_PREDETECTION", + "ImageParameterName": "ip-read-single-barcode" + }, + { + "Section": "ST_BARCODE_LOCALIZATION", + "ImageParameterName": "ip-read-single-barcode" + }, + { + "Section": "ST_BARCODE_DECODING", + "ImageParameterName": "ip-read-single-barcode" + } + ] + }, + { + "Name": "task-read-barcodes-balance", + "ExpectedBarcodesCount": 999, + "LocalizationModes": [ + { + "Mode": "LM_CONNECTED_BLOCKS" + }, + { + "Mode": "LM_SCAN_DIRECTLY" + } + ], + "DeblurModes": [ + { + "Mode": "DM_BASED_ON_LOC_BIN" + }, + { + "Mode": "DM_THRESHOLD_BINARIZATION" + }, + { + "Mode": "DM_DIRECT_BINARIZATION" + } + ], + "BarcodeFormatSpecificationNameArray": [ + "bfs1-balance", + "bfs2-balance" + ], + "SectionImageParameterArray": [ + { + "Section": "ST_REGION_PREDETECTION", + "ImageParameterName": "ip-read-barcodes-balance" + }, + { + "Section": "ST_BARCODE_LOCALIZATION", + "ImageParameterName": "ip-read-barcodes-balance" + }, + { + "Section": "ST_BARCODE_DECODING", + "ImageParameterName": "ip-read-barcodes-balance" + } + ] + }, + { + "Name": "task-read-barcodes-dense", + "ExpectedBarcodesCount": 0, + "LocalizationModes": [ + { + "Mode": "LM_CONNECTED_BLOCKS" + }, + { + "Mode": "LM_LINES" + } + ], + "DeblurModes": [ + { + "Mode": "DM_BASED_ON_LOC_BIN" + }, + { + "Mode": "DM_THRESHOLD_BINARIZATION" + }, + { + "Mode": "DM_DIRECT_BINARIZATION" + }, + { + "Mode": "DM_SMOOTHING" + }, + { + "Mode": "DM_GRAY_EQUALIZATION" + } + ], + "BarcodeFormatSpecificationNameArray": [ + "bfs1-dense", + "bfs2-dense" + ], + "SectionImageParameterArray": [ + { + "Section": "ST_REGION_PREDETECTION", + "ImageParameterName": "ip-read-barcodes-dense" + }, + { + "Section": "ST_BARCODE_LOCALIZATION", + "ImageParameterName": "ip-read-barcodes-dense" + }, + { + "Section": "ST_BARCODE_DECODING", + "ImageParameterName": "ip-read-barcodes-dense" + } + ] + }, + { + "Name": "task-read-barcodes-distant", + "ExpectedBarcodesCount": 0, + "LocalizationModes": [ + { + "Mode": "LM_CONNECTED_BLOCKS" + }, + { + "Mode": "LM_LINES" + } + ], + "DeblurModes": [ + { + "Mode": "DM_BASED_ON_LOC_BIN" + }, + { + "Mode": "DM_THRESHOLD_BINARIZATION" + }, + { + "Mode": "DM_DIRECT_BINARIZATION" + } + ], + "BarcodeFormatSpecificationNameArray": [ + "bfs1-distant", + "bfs2-distant" + ], + "SectionImageParameterArray": [ + { + "Section": "ST_REGION_PREDETECTION", + "ImageParameterName": "ip-read-barcodes-distant" + }, + { + "Section": "ST_BARCODE_LOCALIZATION", + "ImageParameterName": "ip-read-barcodes-distant" + }, + { + "Section": "ST_BARCODE_DECODING", + "ImageParameterName": "ip-read-barcodes-distant" + } + ] + } + ], + "ImageParameterOptions": [ + { + "Name": "ip-read-barcodes", + "TextDetectionMode": { + "Mode": "TTDM_LINE", + "Direction": "UNKNOWN", + "Sensitivity": 3 + }, + "IfEraseTextZone": 1, + "BinarizationModes": [ + { + "Mode": "BM_LOCAL_BLOCK", + "BlockSizeX": 71, + "BlockSizeY": 71, + "EnableFillBinaryVacancy": 0 + } + ], + "GrayscaleTransformationModes": [ + { + "Mode": "GTM_ORIGINAL" + } + ] + }, + { + "Name": "ip-read-barcodes-speed-first", + "TextDetectionMode": { + "Mode": "TTDM_LINE", + "Direction": "UNKNOWN", + "Sensitivity": 3 + }, + "IfEraseTextZone": 1, + "BinarizationModes": [ + { + "Mode": "BM_LOCAL_BLOCK", + "BlockSizeX": 27, + "BlockSizeY": 27, + "EnableFillBinaryVacancy": 1 + } + ], + "GrayscaleTransformationModes": [ + { + "Mode": "GTM_ORIGINAL" + } + ], + "ScaleDownThreshold": 2300 + }, + { + "Name": "ip-read-barcodes-read-rate", + "TextDetectionMode": { + "Mode": "TTDM_LINE", + "Direction": "UNKNOWN", + "Sensitivity": 3 + }, + "IfEraseTextZone": 1, + "BinarizationModes": [ + { + "Mode": "BM_LOCAL_BLOCK", + "BlockSizeX": 0, + "BlockSizeY": 0, + "EnableFillBinaryVacancy": 1 + } + ], + "GrayscaleTransformationModes": [ + { + "Mode": "GTM_ORIGINAL" + } + ], + "ScaleDownThreshold": 100000 + }, + { + "Name": "ip-read-single-barcode", + "TextDetectionMode": { + "Mode": "TTDM_LINE", + "Direction": "UNKNOWN", + "Sensitivity": 3 + }, + "IfEraseTextZone": 1, + "BinarizationModes": [ + { + "Mode": "BM_LOCAL_BLOCK", + "BlockSizeX": 27, + "BlockSizeY": 27, + "EnableFillBinaryVacancy": 0 + } + ], + "GrayscaleTransformationModes": [ + { + "Mode": "GTM_ORIGINAL" + } + ], + "ScaleDownThreshold": 2300 + }, + { + "Name": "ip-read-barcodes-balance", + "TextDetectionMode": { + "Mode": "TTDM_LINE", + "Direction": "UNKNOWN", + "Sensitivity": 3 + }, + "IfEraseTextZone": 1, + "BinarizationModes": [ + { + "Mode": "BM_LOCAL_BLOCK", + "BlockSizeX": 0, + "BlockSizeY": 0, + "EnableFillBinaryVacancy": 1 + } + ], + "GrayscaleTransformationModes": [ + { + "Mode": "GTM_ORIGINAL" + } + ] + }, + { + "Name": "ip-read-barcodes-dense", + "TextDetectionMode": { + "Mode": "TTDM_LINE", + "Direction": "UNKNOWN", + "Sensitivity": 3 + }, + "IfEraseTextZone": 1, + "BinarizationModes": [ + { + "Mode": "BM_LOCAL_BLOCK", + "BlockSizeX": 0, + "BlockSizeY": 0, + "EnableFillBinaryVacancy": 1 + } + ], + "GrayscaleTransformationModes": [ + { + "Mode": "GTM_ORIGINAL" + } + ], + "ScaleDownThreshold": 100000 + }, + { + "Name": "ip-read-barcodes-distant", + "TextDetectionMode": { + "Mode": "TTDM_LINE", + "Direction": "UNKNOWN", + "Sensitivity": 3 + }, + "IfEraseTextZone": 1, + "BinarizationModes": [ + { + "Mode": "BM_LOCAL_BLOCK", + "BlockSizeX": 0, + "BlockSizeY": 0, + "EnableFillBinaryVacancy": 1 + } + ], + "GrayscaleTransformationModes": [ + { + "Mode": "GTM_ORIGINAL" + } + ], + "ScaleDownThreshold": 2300 + } + ] +} \ No newline at end of file diff --git a/dist/barcode-scanner.ui.xml b/dist/barcode-scanner.ui.xml new file mode 100644 index 0000000..b245f3a --- /dev/null +++ b/dist/barcode-scanner.ui.xml @@ -0,0 +1,140 @@ + \ No newline at end of file diff --git a/dist/dbr.bundle.d.ts b/dist/dbr.bundle.d.ts index 1c54afb..728cdf1 100644 --- a/dist/dbr.bundle.d.ts +++ b/dist/dbr.bundle.d.ts @@ -1,12 +1,99 @@ +import { EngineResourcePaths, DSImageData } from 'dynamsoft-core'; import * as dynamsoftCore from 'dynamsoft-core'; export { dynamsoftCore as Core }; -import * as dynamsoftLicense from 'dynamsoft-license'; -export { dynamsoftLicense as License }; +import { CapturedResult } from 'dynamsoft-capture-vision-router'; import * as dynamsoftCaptureVisionRouter from 'dynamsoft-capture-vision-router'; export { dynamsoftCaptureVisionRouter as CVR }; -import * as dynamsoftCameraEnhancer from 'dynamsoft-camera-enhancer'; -export { dynamsoftCameraEnhancer as DCE }; +import { EnumBarcodeFormat, BarcodeResultItem } from 'dynamsoft-barcode-reader'; import * as dynamsoftBarcodeReader from 'dynamsoft-barcode-reader'; export { dynamsoftBarcodeReader as DBR }; +import * as dynamsoftLicense from 'dynamsoft-license'; +export { dynamsoftLicense as License }; +import * as dynamsoftCameraEnhancer from 'dynamsoft-camera-enhancer'; +export { dynamsoftCameraEnhancer as DCE }; import * as dynamsoftUtility from 'dynamsoft-utility'; export { dynamsoftUtility as Utility }; + +declare enum EnumScanMode { + SM_SINGLE = 0, + SM_MULTI_UNIQUE = 1 +} +declare enum EnumOptimizationMode { + OM_NONE = 0, + OM_SPEED = 1, + OM_COVERAGE = 2, + OM_BALANCE = 3, + OM_DPM = 4, + OM_DENSE = 5 +} +declare enum EnumResultStatus { + RS_SUCCESS = 0, + RS_CANCELLED = 1, + RS_FAILED = 2 +} + +interface BarcodeScannerConfig { + license?: string; + scanMode?: EnumScanMode; + templateFilePath?: string; + utilizedTemplateNames?: UtilizedTemplateNames; + engineResourcePaths?: EngineResourcePaths; + barcodeFormats?: Array | EnumBarcodeFormat; + duplicateForgetTime?: number; + container?: HTMLElement | string | undefined; + onUniqueBarcodeScanned?: (result: BarcodeResultItem) => void | Promise; + showResultView?: boolean; + showUploadImageButton?: boolean; + removePoweredByMessage?: boolean; + scannerViewConfig?: ScannerViewConfig; + resultViewConfig?: ResultViewConfig; + uiPath?: string; +} +interface ScannerViewConfig { + container?: HTMLElement | string | undefined; + showCloseButton?: boolean; +} +interface BarcodeResultViewToolbarButtonsConfig { + clear?: ToolbarButtonConfig; + done?: ToolbarButtonConfig; +} +interface ResultViewConfig { + container?: HTMLElement | string | undefined; + toolbarButtonsConfig?: BarcodeResultViewToolbarButtonsConfig; +} + +type ResultStatus = { + code: EnumResultStatus; + message: string; +}; +interface ToolbarButtonConfig { + label?: string; + className?: string; + isHidden?: boolean; +} +interface BarcodeScanResult { + status: ResultStatus; + barcodeResults: Array; + originalImageResult?: DSImageData; + barcodeImage?: DSImageData; +} +interface UtilizedTemplateNames { + single?: string; + multi_unique?: string; + image?: string; +} + +declare class BarcodeScanner { + #private; + private _cameraEnhancer; + private _cameraView; + private _cvRouter; + config: BarcodeScannerConfig; + constructor(config?: BarcodeScannerConfig); + launch(): Promise; + decode(imageOrFile: Blob | string | DSImageData | HTMLImageElement | HTMLVideoElement | HTMLCanvasElement, templateName?: string): Promise; + dispose(): void; +} + +export { BarcodeScanner, EnumOptimizationMode, EnumResultStatus, EnumScanMode }; +export type { BarcodeResultViewToolbarButtonsConfig, BarcodeScanResult, BarcodeScannerConfig, ResultStatus, ResultViewConfig, ScannerViewConfig, ToolbarButtonConfig, UtilizedTemplateNames }; diff --git a/dist/dbr.bundle.esm.d.ts b/dist/dbr.bundle.esm.d.ts index bbfbd47..8708fdd 100644 --- a/dist/dbr.bundle.esm.d.ts +++ b/dist/dbr.bundle.esm.d.ts @@ -1,6 +1,93 @@ +import { EngineResourcePaths, DSImageData } from 'dynamsoft-core'; export * from 'dynamsoft-core'; -export * from 'dynamsoft-license'; +import { CapturedResult } from 'dynamsoft-capture-vision-router'; export * from 'dynamsoft-capture-vision-router'; -export * from 'dynamsoft-camera-enhancer'; +import { EnumBarcodeFormat, BarcodeResultItem } from 'dynamsoft-barcode-reader'; export * from 'dynamsoft-barcode-reader'; +export * from 'dynamsoft-license'; +export * from 'dynamsoft-camera-enhancer'; export * from 'dynamsoft-utility'; + +declare enum EnumScanMode { + SM_SINGLE = 0, + SM_MULTI_UNIQUE = 1 +} +declare enum EnumOptimizationMode { + OM_NONE = 0, + OM_SPEED = 1, + OM_COVERAGE = 2, + OM_BALANCE = 3, + OM_DPM = 4, + OM_DENSE = 5 +} +declare enum EnumResultStatus { + RS_SUCCESS = 0, + RS_CANCELLED = 1, + RS_FAILED = 2 +} + +interface BarcodeScannerConfig { + license?: string; + scanMode?: EnumScanMode; + templateFilePath?: string; + utilizedTemplateNames?: UtilizedTemplateNames; + engineResourcePaths?: EngineResourcePaths; + barcodeFormats?: Array | EnumBarcodeFormat; + duplicateForgetTime?: number; + container?: HTMLElement | string | undefined; + onUniqueBarcodeScanned?: (result: BarcodeResultItem) => void | Promise; + showResultView?: boolean; + showUploadImageButton?: boolean; + removePoweredByMessage?: boolean; + scannerViewConfig?: ScannerViewConfig; + resultViewConfig?: ResultViewConfig; + uiPath?: string; +} +interface ScannerViewConfig { + container?: HTMLElement | string | undefined; + showCloseButton?: boolean; +} +interface BarcodeResultViewToolbarButtonsConfig { + clear?: ToolbarButtonConfig; + done?: ToolbarButtonConfig; +} +interface ResultViewConfig { + container?: HTMLElement | string | undefined; + toolbarButtonsConfig?: BarcodeResultViewToolbarButtonsConfig; +} + +type ResultStatus = { + code: EnumResultStatus; + message: string; +}; +interface ToolbarButtonConfig { + label?: string; + className?: string; + isHidden?: boolean; +} +interface BarcodeScanResult { + status: ResultStatus; + barcodeResults: Array; + originalImageResult?: DSImageData; + barcodeImage?: DSImageData; +} +interface UtilizedTemplateNames { + single?: string; + multi_unique?: string; + image?: string; +} + +declare class BarcodeScanner { + #private; + private _cameraEnhancer; + private _cameraView; + private _cvRouter; + config: BarcodeScannerConfig; + constructor(config?: BarcodeScannerConfig); + launch(): Promise; + decode(imageOrFile: Blob | string | DSImageData | HTMLImageElement | HTMLVideoElement | HTMLCanvasElement, templateName?: string): Promise; + dispose(): void; +} + +export { BarcodeScanner, EnumOptimizationMode, EnumResultStatus, EnumScanMode }; +export type { BarcodeResultViewToolbarButtonsConfig, BarcodeScanResult, BarcodeScannerConfig, ResultStatus, ResultViewConfig, ScannerViewConfig, ToolbarButtonConfig, UtilizedTemplateNames }; diff --git a/dist/dbr.bundle.js b/dist/dbr.bundle.js index 9005013..57d6d03 100644 --- a/dist/dbr.bundle.js +++ b/dist/dbr.bundle.js @@ -4,8 +4,8 @@ * @website http://www.dynamsoft.com * @copyright Copyright 2025, Dynamsoft Corporation * @author Dynamsoft -* @version 10.4.3100 +* @version 10.5.3000 * @fileoverview Dynamsoft JavaScript Library for Barcode Reader * More info on dbr JS: https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/ */ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).Dynamsoft=t.Dynamsoft||{})}(this,(function(t){"use strict";const e=t=>t&&"object"==typeof t&&"function"==typeof t.then,i=(async()=>{})().constructor;let r=class extends i{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 r;this._task=t,e(t)?r=t:"function"==typeof t&&(r=new i(t)),r&&(async()=>{try{const e=await r;t===this._task&&this.resolve(e)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let i,r;super(((t,e)=>{i=t,r=e})),this._s="pending",this.resolve=t=>{this.isPending&&(e(t)?this.task=t:(this._s="fulfilled",i(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",r(t))},this.task=t}};function n(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function s(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}var o,a,h;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(o||(o={})),function(t){t[t.CCUT_AUTO=0]="CCUT_AUTO",t[t.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",t[t.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",t[t.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",t[t.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",t[t.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(a||(a={})),function(t){t[t.IPF_BINARY=0]="IPF_BINARY",t[t.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",t[t.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",t[t.IPF_NV21=3]="IPF_NV21",t[t.IPF_RGB_565=4]="IPF_RGB_565",t[t.IPF_RGB_555=5]="IPF_RGB_555",t[t.IPF_RGB_888=6]="IPF_RGB_888",t[t.IPF_ARGB_8888=7]="IPF_ARGB_8888",t[t.IPF_RGB_161616=8]="IPF_RGB_161616",t[t.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",t[t.IPF_ABGR_8888=10]="IPF_ABGR_8888",t[t.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",t[t.IPF_BGR_888=12]="IPF_BGR_888",t[t.IPF_BINARY_8=13]="IPF_BINARY_8",t[t.IPF_NV12=14]="IPF_NV12",t[t.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(h||(h={}));const l="undefined"==typeof self,c="function"==typeof importScripts,u=(()=>{if(!c){if(!l&&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=t=>{if(null==t&&(t="./"),l||c);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},f=t=>Object.prototype.toString.call(t),g=t=>Array.isArray?Array.isArray(t):"[object Array]"===f(t),m=t=>"[object Boolean]"===f(t),p=t=>"number"==typeof t&&!Number.isNaN(t),_=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),v=t=>!(!_(t)||!p(t.width)||t.width<=0||!p(t.height)||t.height<=0||!p(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!C(t.tag)),y=t=>!!v(t)&&t.bytes instanceof Uint8Array,w=t=>!(!_(t)||!p(t.left)||t.left<0||!p(t.top)||t.top<0||!p(t.right)||t.right<0||!p(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom||!m(t.isMeasuredInPercentage)),C=t=>null===t||!!_(t)&&!!p(t.imageId)&&"type"in t,E=t=>!(!_(t)||!T(t.startPoint)||!T(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),T=t=>!!_(t)&&!!p(t.x)&&!!p(t.y),S=t=>!!_(t)&&!!g(t.points)&&0!=t.points.length&&!t.points.some((t=>!T(t))),b=t=>!!_(t)&&!!g(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some((t=>!T(t))),I=t=>!(!_(t)||!p(t.x)||!p(t.y)||!p(t.width)||t.width<0||!p(t.height)||t.height<0||"isMeasuredInPercentage"in t&&!m(t.isMeasuredInPercentage)),x=async(t,e)=>await new Promise(((i,r)=>{let n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType=e,n.send(),n.onloadend=async()=>{n.status<200||n.status>=300?r(new Error(t+" "+n.status)):i(n.response)},n.onerror=()=>{r(new Error("Network Error: "+n.statusText))}})),O=(t,e)=>{let i=t.split("."),r=e.split(".");for(let t=0;t{const e={},i={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcpd:"dynamsoft-code-parser",dlrData:"dynamsoft-label-recognizer-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer"};for(let r in t){if("rootDirectory"===r)continue;let n=r,s=t[n],o=s&&"object"==typeof s&&s.path?s.path:s,a=t.rootDirectory;if(a&&!a.endsWith("/")&&(a+="/"),"object"==typeof s&&s.isInternal)a&&(o=t[n].version?`${a}${i[n]}@${t[n].version}/dist/${"ddv"===n?"engine":""}`:`${a}${i[n]}/dist/${"ddv"===n?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof o&&(o=o.replace(i,a||"")),"object"==typeof o&&"dwt"===n){const r=t[n].resourcesPath,s=t[n].serviceInstallerLocation;e[n]={resourcesPath:r.replace(i,a||""),serviceInstallerLocation:s.replace(i,a||"")};continue}}e[n]=d(o)}return e},R=async(t,e,i)=>await new Promise((async(r,n)=>{try{const n=e.split(".");let s=n[n.length-1];const o=await L(`image/${s}`,t);n.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return r(a)}catch(t){return n()}})),D=t=>{y(t)&&(t=M(t));const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d",{willReadFrequently:!0}).putImageData(t,0,0),e},L=async(t,e)=>{y(e)&&(e=M(e));const i=D(e);return new Promise(((e,r)=>{i.toBlob((t=>e(t)),t)}))},M=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===h.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let r=0;r=n)break;e[o]=e[o+1]=e[o+2]=(128&r)/128*255,e[o+3]=255,r<<=1}}}else if(Number(t.format)===h.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let r=0;r=n)break;e[o]=e[o+1]=e[o+2]=128&r?0:255,e[o+3]=255,r<<=1}}}return new ImageData(e,t.width,t.height)};var F,P,k,B,N,j,U,V;let G,W,Y,H,X,z=class t{get _isFetchingStarted(){return n(this,N,"f")}constructor(){F.add(this),P.set(this,[]),k.set(this,1),B.set(this,o.BOPM_BLOCK),N.set(this,!1),j.set(this,void 0),U.set(this,a.CCUT_AUTO)}setErrorListener(t){}addImageToBuffer(t){var e;if(!y(t))throw new TypeError("Invalid 'image'.");if((null===(e=t.tag)||void 0===e?void 0:e.hasOwnProperty("imageId"))&&"number"==typeof t.tag.imageId&&this.hasImage(t.tag.imageId))throw new Error("Existed imageId.");if(n(this,P,"f").length>=n(this,k,"f"))switch(n(this,B,"f")){case o.BOPM_BLOCK:break;case o.BOPM_UPDATE:if(n(this,P,"f").push(t),_(n(this,j,"f"))&&p(n(this,j,"f").imageId)&&1==n(this,j,"f").keepInBuffer)for(;n(this,P,"f").length>n(this,k,"f");){const t=n(this,P,"f").findIndex((t=>{var e;return(null===(e=t.tag)||void 0===e?void 0:e.imageId)!==n(this,j,"f").imageId}));n(this,P,"f").splice(t,1)}else n(this,P,"f").splice(0,n(this,P,"f").length-n(this,k,"f"))}else n(this,P,"f").push(t)}getImage(){if(0===n(this,P,"f").length)return null;let e;if(n(this,j,"f")&&p(n(this,j,"f").imageId)){const t=n(this,F,"m",V).call(this,n(this,j,"f").imageId);if(t<0)throw new Error(`Image with id ${n(this,j,"f").imageId} doesn't exist.`);e=n(this,P,"f").slice(t,t+1)[0]}else e=n(this,P,"f").pop();if([h.IPF_RGB_565,h.IPF_RGB_555,h.IPF_RGB_888,h.IPF_ARGB_8888,h.IPF_RGB_161616,h.IPF_ARGB_16161616,h.IPF_ABGR_8888,h.IPF_ABGR_16161616,h.IPF_BGR_888].includes(e.format)){if(n(this,U,"f")===a.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t0!==t.length&&t.every((t=>p(t))))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&!m(e))throw new TypeError("Invalid 'keepInBuffer'.");s(this,j,{imageId:t,keepInBuffer:e},"f")}_resetNextReturnedImage(){s(this,j,null,"f")}hasImage(t){return n(this,F,"m",V).call(this,t)>=0}startFetching(){s(this,N,!0,"f")}stopFetching(){s(this,N,!1,"f")}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(s(this,k,t,"f");n(this,P,"f")&&n(this,P,"f").length>t;)n(this,P,"f").shift()}getMaxImageCount(){return n(this,k,"f")}getImageCount(){return n(this,P,"f").length}clearBuffer(){n(this,P,"f").length=0}isBufferEmpty(){return 0===n(this,P,"f").length}setBufferOverflowProtectionMode(t){s(this,B,t,"f")}getBufferOverflowProtectionMode(){return n(this,B,"f")}setColourChannelUsageType(t){s(this,U,t,"f")}getColourChannelUsageType(){return n(this,U,"f")}};P=new WeakMap,k=new WeakMap,B=new WeakMap,N=new WeakMap,j=new WeakMap,U=new WeakMap,F=new WeakSet,V=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return n(this,P,"f").findIndex((e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t}))},"undefined"!=typeof navigator&&(G=navigator,W=G.userAgent,Y=G.platform,H=G.mediaDevices),function(){if(!l){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:G.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Y,search:"Win"},Mac:{str:Y},Linux:{str:Y}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||W,o=n.search||e,a=n.verStr||W,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||W,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=W.indexOf("Windows NT")&&(n="HarmonyOS"),X={browser:i,version:r,OS:n}}l&&(X={browser:"ssr",version:0,OS:"ssr"})}();const Z="undefined"!=typeof WebAssembly&&W&&!(/Safari/.test(W)&&!/Chrome/.test(W)&&/\(.+\s11_2_([2-6]).*\)/.test(W)),q=!("undefined"==typeof Worker),K=!(!H||!H.getUserMedia),J=async()=>{let t=!1;if(K)try{(await H.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===X.browser&&X.version>66||"Safari"===X.browser&&X.version>13||"OPR"===X.browser&&X.version>43||"Edge"===X.browser&&X.version;const Q={},$=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push(Q[t]=Q[t]||new r);await Promise.all(i)},tt=async(t,e)=>{let i,n="string"==typeof t?[t]:t,s=[];for(let t of n){let n;s.push(n=Q[t]=Q[t]||new r(i=i||e())),n.isEmpty&&(n.task=i=i||e())}await Promise.all(s)};let et,it=0;const rt=()=>it++,nt={};let st;const ot=t=>{st=t,et&&et.postMessage({type:"setBLog",body:{value:!!t}})};let at=!1;const ht=t=>{at=t,et&&et.postMessage({type:"setBDebug",body:{value:!!t}})},lt={},ct={},ut={dip:{wasm:!0}},dt={std:{version:"1.4.21",path:d(u+"../../dynamsoft-capture-vision-std@1.4.21/dist/"),isInternal:!0},core:{version:"3.4.31",path:u,isInternal:!0}},ft=async t=>{let e;t instanceof Array||(t=t?[t]:[]);let i=Q.core;e=!i||i.isEmpty;let n=new Map;const s=t=>{if("std"==(t=t.toLowerCase())||"core"==t)return;if(!ut[t])throw Error("The '"+t+"' module cannot be found.");let e=ut[t].deps;if(null==e?void 0:e.length)for(let t of e)s(t);let i=Q[t];n.has(t)||n.set(t,!i||i.isEmpty)};for(let e of t)s(e);let o=[];e&&o.push("core"),o.push(...n.keys());const a=[...n.entries()].filter((t=>!t[1])).map((t=>t[0]));await tt(o,(async()=>{const t=[...n.entries()].filter((t=>t[1])).map((t=>t[0]));await $(a);const i=A(dt),s={};for(let e of t)s[e]=ut[e];const o={engineResourcePaths:i,autoResources:s,names:t};let h=new r;if(e){o.needLoadCore=!0;let t=i.core+gt._workerName;t.startsWith(location.origin)||(t=await fetch(t).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),et=new Worker(t),et.onerror=t=>{let e=new Error(t.message);h.reject(e)},et.addEventListener("message",(t=>{let e=t.data?t.data:t,i=e.type,r=e.id,n=e.body;switch(i){case"log":st&&st(e.message);break;case"task":try{nt[r](n),delete nt[r]}catch(t){throw delete nt[r],t}break;case"event":try{nt[r](n)}catch(t){throw t}break;default:console.log(t)}})),o.bLog=!!st,o.bd=at,o.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await $("core");let l=it++;nt[l]=t=>{if(t.success)Object.assign(lt,t.versions),"{}"!==JSON.stringify(t.versions)&&(gt._versions=t.versions),h.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),h.reject(e)}},et.postMessage({type:"loadWasm",body:o,id:l}),await h}))};class gt{static get engineResourcePaths(){return dt}static set engineResourcePaths(t){Object.assign(dt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return st}static set _onLog(t){ot(t)}static get _bDebug(){return at}static set _bDebug(t){ht(t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!Q[t]&&Q[t].isFulfilled}static async loadWasm(t){return await ft(t)}static async detectEnvironment(){return await(async()=>({wasm:Z,worker:q,getUserMedia:K,camera:await J(),browser:X.browser,version:X.version,OS:X.OS}))()}static async getModuleVersion(){return await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success)return t(i.versions);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"getModuleVersion",id:i})}))}static getVersion(){return`3.4.31(Worker: ${lt.core&<.core.worker||"Not Loaded"}, Wasm: ${lt.core&<.core.wasm||"Not Loaded"})`}static enableLogging(){z._onLog=console.log,gt._onLog=console.log}static disableLogging(){z._onLog=null,gt._onLog=null}static async cfd(t){return await new Promise(((e,i)=>{let r=rt();nt[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cfd",id:r,body:{count:t}})}))}}var mt,pt,_t,vt,yt,wt,Ct,Et,Tt;gt._bSupportDce4Module=-1,gt._bSupportIRTModule=-1,gt._versions=null,gt._workerName="core.worker.js",gt.browserInfo=X,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_NORMALIZED_IMAGE=16]="CRIT_NORMALIZED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT"}(mt||(mt={})),function(t){t[t.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",t[t.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",t[t.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",t[t.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(pt||(pt={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_RESERVED_INFO_NOT_MATCH=-10040]="EC_RESERVED_INFO_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_REQUEST_FAILED=-10044]="EC_REQUEST_FAILED",t[t.EC_LICENSE_INIT_FAILED=-10045]="EC_LICENSE_INIT_FAILED",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_LICENSE_CONTENT_INVALID=-10052]="EC_LICENSE_CONTENT_INVALID",t[t.EC_LICENSE_KEY_INVALID=-10053]="EC_LICENSE_KEY_INVALID",t[t.EC_LICENSE_DEVICE_RUNS_OUT=-10054]="EC_LICENSE_DEVICE_RUNS_OUT",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_HANDSHAKE_CODE_INVALID=-20001]="EC_HANDSHAKE_CODE_INVALID",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_LICENSE_INIT_SEQUENCE_FAILED=-20009]="EC_LICENSE_INIT_SEQUENCE_FAILED",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_FAILED_TO_REACH_DLS=-20200]="EC_FAILED_TO_REACH_DLS",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_QR_LICENSE_INVALID=-30016]="EC_QR_LICENSE_INVALID",t[t.EC_1D_LICENSE_INVALID=-30017]="EC_1D_LICENSE_INVALID",t[t.EC_PDF417_LICENSE_INVALID=-30019]="EC_PDF417_LICENSE_INVALID",t[t.EC_DATAMATRIX_LICENSE_INVALID=-30020]="EC_DATAMATRIX_LICENSE_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_AZTEC_LICENSE_INVALID=-30041]="EC_AZTEC_LICENSE_INVALID",t[t.EC_PATCHCODE_LICENSE_INVALID=-30046]="EC_PATCHCODE_LICENSE_INVALID",t[t.EC_POSTALCODE_LICENSE_INVALID=-30047]="EC_POSTALCODE_LICENSE_INVALID",t[t.EC_DPM_LICENSE_INVALID=-30048]="EC_DPM_LICENSE_INVALID",t[t.EC_FRAME_DECODING_THREAD_EXISTS=-30049]="EC_FRAME_DECODING_THREAD_EXISTS",t[t.EC_STOP_DECODING_THREAD_FAILED=-30050]="EC_STOP_DECODING_THREAD_FAILED",t[t.EC_MAXICODE_LICENSE_INVALID=-30057]="EC_MAXICODE_LICENSE_INVALID",t[t.EC_GS1_DATABAR_LICENSE_INVALID=-30058]="EC_GS1_DATABAR_LICENSE_INVALID",t[t.EC_GS1_COMPOSITE_LICENSE_INVALID=-30059]="EC_GS1_COMPOSITE_LICENSE_INVALID",t[t.EC_DOTCODE_LICENSE_INVALID=-30061]="EC_DOTCODE_LICENSE_INVALID",t[t.EC_PHARMACODE_LICENSE_INVALID=-30062]="EC_PHARMACODE_LICENSE_INVALID",t[t.EC_CHARACTER_MODEL_FILE_NOT_FOUND=-40100]="EC_CHARACTER_MODEL_FILE_NOT_FOUND",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_ZA_DL_LICENSE_INVALID=-90006]="EC_ZA_DL_LICENSE_INVALID",t[t.EC_AAMVA_DL_ID_LICENSE_INVALID=-90007]="EC_AAMVA_DL_ID_LICENSE_INVALID",t[t.EC_AADHAAR_LICENSE_INVALID=-90008]="EC_AADHAAR_LICENSE_INVALID",t[t.EC_MRTD_LICENSE_INVALID=-90009]="EC_MRTD_LICENSE_INVALID",t[t.EC_VIN_LICENSE_INVALID=-90010]="EC_VIN_LICENSE_INVALID",t[t.EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID=-90011]="EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID",t[t.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",t[t.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",t[t.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",t[t.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",t[t.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(_t||(_t={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV"}(vt||(vt={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV"}(yt||(yt={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(wt||(wt={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(Ct||(Ct={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(Et||(Et={})),function(t){t[t.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",t[t.CVS_PASSED=1]="CVS_PASSED",t[t.CVS_FAILED=2]="CVS_FAILED"}(Tt||(Tt={}));const St={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_DOWN_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_UP_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_NORMALIZED_IMAGES:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var bt,It;!function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_NORMALIZED_IMAGE=6]="ROET_NORMALIZED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI"}(bt||(bt={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_NORMALIZATION=7]="ST_DOCUMENT_NORMALIZATION"}(It||(It={}));var xt=Object.freeze({__proto__:null,CoreModule:gt,get EnumBufferOverflowProtectionMode(){return o},get EnumCapturedResultItemType(){return mt},get EnumColourChannelUsageType(){return a},get EnumCornerType(){return pt},get EnumCrossVerificationStatus(){return Tt},get EnumErrorCode(){return _t},get EnumGrayscaleEnhancementMode(){return vt},get EnumGrayscaleTransformationMode(){return yt},get EnumImagePixelFormat(){return h},get EnumImageTagType(){return wt},EnumIntermediateResultUnitType:St,get EnumPDFReadingMode(){return Ct},get EnumRasterDataSource(){return Et},get EnumRegionObjectElementType(){return bt},get EnumSectionType(){return It},ImageSourceAdapter:z,_getNorImageData:M,_saveToFile:R,_toBlob:L,_toCanvas:D,_toImage:(t,e)=>{y(e)&&(e=M(e));const i=D(e);let r=new Image,n=i.toDataURL(t);return r.src=n,r},get bDebug(){return at},checkIsLink:t=>/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t),compareVersion:O,doOrWaitAsyncDependency:tt,getNextTaskID:rt,handleEngineResourcePaths:A,innerVersions:lt,isArc:t=>!(!_(t)||!p(t.x)||!p(t.y)||!p(t.radius)||t.radius<0||!p(t.startAngle)||!p(t.endAngle)),isContour:t=>!!_(t)&&!!g(t.points)&&0!=t.points.length&&!t.points.some((t=>!T(t))),isDSImageData:y,isDSRect:w,isImageTag:C,isLineSegment:E,isObject:_,isOriginalDsImageData:t=>!(!v(t)||!p(t.bytes.length)&&!p(t.bytes.ptr)),isPoint:T,isPolygon:S,isQuad:b,isRect:I,loadWasm:ft,mapAsyncDependency:Q,mapPackageRegister:ct,mapTaskCallBack:nt,get onLog(){return st},requestResource:x,setBDebug:ht,setOnLog:ot,waitAsyncDependency:$,get worker(){return et},workerAutoResources:ut});let Ot="./";if(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))}Ot=t.substring(0,t.lastIndexOf("/")+1)}function At(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Rt(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}gt.engineResourcePaths={rootDirectory:(t=>{null==t&&(t="./");let e=document.createElement("a");return e.href=t,(t=e.href).endsWith("/")||(t+="/"),t})(Ot+"../../")},"function"==typeof SuppressedError&&SuppressedError;const Dt=t=>t&&"object"==typeof t&&"function"==typeof t.then,Lt=(async()=>{})().constructor;class Mt extends Lt{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,Dt(t)?e=t:"function"==typeof t&&(e=new Lt(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}constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(Dt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class Ft{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success)return t(i.count);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})}))}async setMaxBufferedItems(t){return await new Promise(((e,i)=>{let r=rt();nt[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_setMaxBufferedItems",id:r,instanceID:this._cvr._instanceID,body:{count:t}})}))}async getBufferedCharacterItemSet(){return await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success)return t(i.itemSet);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})}))}}var Pt={onTaskResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onColourImageUnitReceived:!1,onScaledDownColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledUpBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesReceived:!1};const kt=t=>{for(let e in t._irrRegistryState)t._irrRegistryState[e]=!1;for(let e of t._intermediateResultReceiverSet)if(e.isDce||e.isFilter)t._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let i in e)t._irrRegistryState[i]||(t._irrRegistryState[i]=!!e[i])};class Bt{constructor(t){this._irrRegistryState=Pt,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),kt(this);let e=-1,i={};if(!t.isDce&&!t.isFilter){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach(((t,e)=>{i[e]=t})),t._observedTaskMap.clear()}return await new Promise(((t,r)=>{let n=rt();nt[n]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,r(t)}},et.postMessage({type:"cvr_setIrrRegistry",id:n,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})}))}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),kt(this),await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})}))}getOriginalImage(){return this._cvr._dsImage}}const Nt="undefined"==typeof self,jt="function"==typeof importScripts,Ut=(()=>{if(!jt){if(!Nt&&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"./"}})(),Vt=t=>{if(null==t&&(t="./"),Nt||jt);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var Gt;gt.engineResourcePaths.cvr={version:"2.4.33",path:Ut,isInternal:!0},ut.cvr={js:!0,wasm:!0,deps:["license","dip"]},ct.cvr={};const Wt="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&O(gt.engineResourcePaths.std.version,Wt)<0&&(gt.engineResourcePaths.std={version:Wt,path:Vt(Ut+`../../dynamsoft-capture-vision-std@${Wt}/dist/`),isInternal:!0});const Yt="2.4.31";(!gt.engineResourcePaths.dip||"string"!=typeof gt.engineResourcePaths.dip&&O(gt.engineResourcePaths.dip.version,Yt)<0)&&(gt.engineResourcePaths.dip={version:Yt,path:Vt(Ut+`../../dynamsoft-image-processing@${Yt}/dist/`),isInternal:!0});class Ht{static getVersion(){return this._version}}Ht._version=`2.4.33(Worker: ${null===(Gt=lt.cvr)||void 0===Gt?void 0:Gt.worker}, Wasm: loading...`;const Xt={barcodeResultItems:{type:mt.CRIT_BARCODE,reveiver:"onDecodedBarcodesReceived",isNeedFilter:!0},textLineResultItems:{type:mt.CRIT_TEXT_LINE,reveiver:"onRecognizedTextLinesReceived",isNeedFilter:!0},detectedQuadResultItems:{type:mt.CRIT_DETECTED_QUAD,reveiver:"onDetectedQuadsReceived",isNeedFilter:!1},normalizedImageResultItems:{type:mt.CRIT_NORMALIZED_IMAGE,reveiver:"onNormalizedImagesReceived",isNeedFilter:!1},parsedResultItems:{type:mt.CRIT_PARSED_RESULT,reveiver:"onParsedResultsReceived",isNeedFilter:!1}};var zt,Zt,qt,Kt,Jt,Qt,$t,te,ee,ie,re,ne,se;function oe(t,e){if(t&&t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;oe(t.referencedItem,e)}}function ae(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}!function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(zt||(zt={}));const he={onTaskResultsReceived:()=>{},isFilter:!0};class le{constructor(){this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(gt.browserInfo.OS)?2048:4096,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,Zt.set(this,null),qt.set(this,null),Kt.set(this,null),Jt.set(this,null),Qt.set(this,null),$t.set(this,new Set),te.set(this,new Set),ee.set(this,new Set),ie.set(this,0),re.set(this,!1),ne.set(this,!1),se.set(this,!1),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return At(this,se,"f")}static async createInstance(){if(!ct.license)throw Error("Module `license` is not existed.");await ct.license.dynamsoft(),await ft(["cvr"]);const t=new le,e=new Mt;let i=rt();return nt[i]=async i=>{var r;if(i.success)t._instanceID=i.instanceID,t._currentSettings=JSON.parse(JSON.parse(i.outputSettings).data),Ht._version=`2.4.33(Worker: ${null===(r=lt.cvr)||void 0===r?void 0:r.worker}, Wasm: ${i.version})`,Rt(t,ne,!0,"f"),Rt(t,Jt,t.getIntermediateResultManager(),"f"),Rt(t,ne,!1,"f"),e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},et.postMessage({type:"cvr_createInstance",id:i}),e}async _singleFrameModeCallback(t){for(let e of At(this,$t,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:t});const e={bytes:new Uint8Array(t.bytes),width:t.width,height:t.height,stride:t.stride,format:t.format,tag:t.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(e,this._templateName);i.originalImageTag=t.tag;const r={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of At(this,$t,"f"))if(t.isDce)t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1});else{for(let e in Xt){const n=e,s=Xt[n];t[s.reveiver]&&i[n]&&t[s.reveiver](Object.assign(Object.assign({},r),{[n]:i[n]}))}t.onCapturedResultReceived&&t.onCapturedResultReceived(i)}}setInput(t){if(ae(this),t){if(Rt(this,Zt,t,"f"),t.isCameraEnhancer){At(this,Jt,"f")&&(At(this,Zt,"f")._intermediateResultReceiver.isDce=!0,At(this,Jt,"f").addResultReceiver(At(this,Zt,"f")._intermediateResultReceiver));const t=At(this,Zt,"f").getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,At(this,$t,"f").add(e)}}}else Rt(this,Zt,null,"f")}getInput(){return At(this,Zt,"f")}addImageSourceStateListener(t){if(ae(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&At(this,te,"f").add(t)}removeImageSourceStateListener(t){return ae(this),At(this,te,"f").delete(t)}addResultReceiver(t){if(ae(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(At(this,$t,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){ae(this),At(this,$t,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onParsedResultsReceived:!1};for(let e of At(this,$t,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onDetectedQuadsReceived=!!e.onDetectedQuadsReceived,t.onNormalizedImagesReceived=!!e.onNormalizedImagesReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new Mt;let i=rt();return nt[i]=async t=>{if(t.success)e.resolve();else{let i=new Error(t.message);i.stack=t.stack+"\n"+i.stack,e.reject()}},et.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(ae(this),!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");At(this,ee,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){ae(this),At(this,ee,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(At(this,Jt,"f").removeResultReceiver(he),0===At(this,ee,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[mt.CRIT_BARCODE]:!1,[mt.CRIT_TEXT_LINE]:!1,[mt.CRIT_DETECTED_QUAD]:!1,[mt.CRIT_NORMALIZED_IMAGE]:!1},e={[mt.CRIT_BARCODE]:!1,[mt.CRIT_TEXT_LINE]:!1,[mt.CRIT_DETECTED_QUAD]:!1,[mt.CRIT_NORMALIZED_IMAGE]:!1};return await ce(this,t),void await ue(this,e)}for(let t of At(this,ee,"f")){if(this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(mt.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(mt.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(mt.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(mt.CRIT_NORMALIZED_IMAGE),t.isLatestOverlappingEnabled(mt.CRIT_BARCODE)){[...At(this,Jt,"f")._intermediateResultReceiverSet.values()].find((t=>t.isFilter))||At(this,Jt,"f").addResultReceiver(he)}await ce(this,t.verificationEnabled),await ue(this,t.duplicateFilterEnabled),await de(this,t.duplicateForgetTime)}}async startCapturing(t){var e,i;if(ae(this),!this._isPauseScan)return;if(!At(this,Zt,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");t||(t=le._defaultTemplate);const r=await this.containsTask(t);await ft(r);for(let t of At(this,ee,"f"))await this.addResultFilter(t);if(r.includes("dlr")&&!(null===(e=ct.dlr)||void 0===e?void 0:e.bLoadConfusableCharsData)){const t=A(gt.engineResourcePaths);await(null===(i=ct.dlr)||void 0===i?void 0:i.loadRecognitionData("ConfusableChars",t.dlr))}if(At(this,Zt,"f").isCameraEnhancer&&(r.includes("ddn")?At(this,Zt,"f").setPixelFormat(h.IPF_ABGR_8888):At(this,Zt,"f").setPixelFormat(h.IPF_GRAYSCALED)),void 0!==At(this,Zt,"f").singleFrameMode&&"disabled"!==At(this,Zt,"f").singleFrameMode)return this._templateName=t,void At(this,Zt,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind);return At(this,Zt,"f").getColourChannelUsageType()===a.CCUT_AUTO&&At(this,Zt,"f").setColourChannelUsageType(r.includes("ddn")?a.CCUT_FULL_CHANNEL:a.CCUT_Y_CHANNEL_ONLY),At(this,Kt,"f")&&At(this,Kt,"f").isPending?At(this,Kt,"f"):(Rt(this,Kt,new Mt(((e,i)=>{if(this.disposed)return;let r=rt();nt[r]=async r=>{if(At(this,Kt,"f")&&!At(this,Kt,"f").isFulfilled){if(!r.success){let t=new Error(r.message);return t.stack=r.stack+"\n"+t.stack,i(t)}this._isPauseScan=!1,this._isOutputOriginalImage=r.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((async()=>{-1!==this._minImageCaptureInterval&&At(this,Zt,"f").startFetching(),this._loopReadVideo(t),e()}),0)}},et.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:t}})})),"f"),await At(this,Kt,"f"))}stopCapturing(){ae(this),At(this,Zt,"f")&&(At(this,Zt,"f").isCameraEnhancer&&void 0!==At(this,Zt,"f").singleFrameMode&&"disabled"!==At(this,Zt,"f").singleFrameMode?At(this,Zt,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(!async function(t){let e=rt();const i=new Mt;nt[e]=async t=>{if(t.success)return i.resolve();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i.reject(e)}},et.postMessage({type:"cvr_clearVerifyList",id:e,instanceID:t._instanceID})}(this),At(this,Zt,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,Rt(this,Kt,null,"f"),At(this,Zt,"f").setColourChannelUsageType(a.CCUT_AUTO)))}async containsTask(t){return ae(this),await new Promise(((e,i)=>{let r=rt();nt[r]=async t=>{if(t.success)return e(JSON.parse(t.tasks));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_containsTask",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async _loopReadVideo(t){if(this.disposed||this._isPauseScan)return;if(Rt(this,re,!0,"f"),At(this,Zt,"f").isBufferEmpty())if(At(this,Zt,"f").hasNextImageToFetch())for(let t of At(this,te,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(zt.ISS_BUFFER_EMPTY);else if(!At(this,Zt,"f").hasNextImageToFetch())for(let t of At(this,te,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(zt.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||At(this,Zt,"f").isBufferEmpty())try{At(this,Zt,"f").isBufferEmpty()&&le._onLog&&le._onLog("buffer is empty so fetch image"),le._onLog&&le._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=At(this,Zt,"f").fetchImage(),le._onLog&&le._onLog(`DCE: finish fetching a frame: ${Date.now()}`),At(this,Zt,"f").setImageFetchInterval(this._averageTime)}catch(e){return void this._reRunCurrnetFunc(t)}else if(At(this,Zt,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=At(this,Zt,"f").getImage(),this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(t);if(!this._dsImage)return void this._reRunCurrnetFunc(t);for(let t of At(this,$t,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const e=Date.now();this._captureDsimage(this._dsImage,t).then((async i=>{if(le._onLog&&le._onLog("no js handle time: "+(Date.now()-e)),this._isPauseScan)return void this._reRunCurrnetFunc(t);i.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;const r={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of At(this,$t,"f"))if(t.isDce){const e=Date.now();if(t.onCapturedResultReceived(i,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify}),le._onLog){const t=Date.now()-e;t>10&&le._onLog(`draw result time: ${t}`)}}else{for(let e in Xt){const n=e,s=Xt[n];t[s.reveiver],t[s.reveiver]&&i[n]&&t[s.reveiver](Object.assign(Object.assign({},r),{[n]:i[n].filter((t=>!s.isNeedFilter||!t.isFilter))})),i[n]&&(i[n]=i[n].filter((t=>!s.isNeedFilter||!t.isFilter)))}t.onCapturedResultReceived&&(i.items=i.items.filter((t=>[mt.CRIT_DETECTED_QUAD,mt.CRIT_NORMALIZED_IMAGE].includes(t.type)||!t.isFilter)),t.onCapturedResultReceived(i))}const n=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-e),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,le._onLog&&(le._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),le._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),le._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),le._onLog(`averageTime: ${this._averageTime}`))),le._onLog){const t=Date.now()-n;t>10&&le._onLog(`fetch image calculate time: ${t}`)}le._onLog&&le._onLog(`time finish decode: ${Date.now()}`),le._onLog&&le._onLog("main time: "+(Date.now()-e)),le._onLog&&le._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,0))})).catch((e=>{At(this,Zt,"f").stopFetching(),e.errorCode&&0===e.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{At(this,Zt,"f").startFetching(),this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,1e3))),"platform error"!==e.message&&setTimeout((()=>{throw e}),0)}))}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),0)}async capture(t,e){var i,r;ae(this),e||(e=le._defaultTemplate);const n=await this.containsTask(e);if(await ft(n),n.includes("dlr")&&!(null===(i=ct.dlr)||void 0===i?void 0:i.bLoadConfusableCharsData)){const t=A(gt.engineResourcePaths);await(null===(r=ct.dlr)||void 0===r?void 0:r.loadRecognitionData("ConfusableChars",t.dlr))}let s;if(Rt(this,re,!1,"f"),y(t))s=await this._captureDsimage(t,e);else if("string"==typeof t)s="data:image/"==t.substring(0,11)?await this._captureBase64(t,e):await this._captureUrl(t,e);else if(t instanceof Blob)s=await this._captureBlob(t,e);else if(t instanceof HTMLImageElement)s=await this._captureImage(t,e);else if(t instanceof HTMLCanvasElement)s=await this._captureCanvas(t,e);else{if(!(t instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");s=await this._captureVideo(t,e)}return s}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await x(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),r=i.length,n=new Uint8Array(r);for(;r--;)n[r]=i.charCodeAt(r);return await this._captureBlob(new Blob([n]),e)}async _captureBlob(t,e){let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(r=await async function(t){return await new Promise(((e,i)=>{let r=URL.createObjectURL(t),n=new Image;n.src=r,n.onload=()=>{URL.revokeObjectURL(n.dbrObjUrl),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._captureImage(i||r,e);return i&&i.close(),n}async _captureImage(t,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);o>this.maxImageSideLength?(Rt(this,ie,this.maxImageSideLength/o,"f"),i=Math.round(n*At(this,ie,"f")),r=Math.round(s*At(this,ie,"f"))):(i=n,r=s),At(this,qt,"f")||Rt(this,qt,document.createElement("canvas"),"f");const a=At(this,qt,"f");a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),r={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(r,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,r,n=t.videoWidth,s=t.videoHeight,o=Math.max(n,s);o>this.maxImageSideLength?(Rt(this,ie,this.maxImageSideLength/o,"f"),i=Math.round(n*At(this,ie,"f")),r=Math.round(s*At(this,ie,"f"))):(i=n,r=s),At(this,qt,"f")||Rt(this,qt,document.createElement("canvas"),"f");const a=At(this,qt,"f");a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),await this._captureCanvas(a,e)}async _captureInWorker(t,e){const{bytes:i,width:r,height:n,stride:s,format:o}=t;let a=rt();const h=new Mt;return nt[a]=async e=>{var i,r;if(!e.success){let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h.reject(t)}{const n=Date.now();le._onLog&&(le._onLog(`get result time from worker: ${n}`),le._onLog("worker to main time consume: "+(n-e.workerReturnMsgTime)));try{const n=e.captureResult;if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,h.reject(t)}t.bytes=e.bytes;for(let e of n.items)0!==At(this,ie,"f")&&oe(e,At(this,ie,"f")),e.type===mt.CRIT_ORIGINAL_IMAGE?e.imageData=t:e.type===mt.CRIT_NORMALIZED_IMAGE?null===(i=ct.ddn)||void 0===i||i.handleNormalizedImageResultItem(e):e.type===mt.CRIT_PARSED_RESULT&&(null===(r=ct.dcp)||void 0===r||r.handleParsedResultItem(e));if(At(this,re,"f"))for(let t of At(this,ee,"f"))t.onDecodedBarcodesReceived(n),t.onRecognizedTextLinesReceived(n),t.onDetectedQuadsReceived(n),t.onNormalizedImagesReceived(n);for(let t in Xt){const e=t,i=n.items.filter((t=>t.type===Xt[e].type));i.length&&(n[t]=i)}if(!this._isPauseScan||!At(this,re,"f")){const e=n.intermediateResult;if(e){let i=0;for(let r of At(this,Jt,"f")._intermediateResultReceiverSet){i++;for(let n of e){if("onTaskResultsReceived"===n.info.callbackName){for(let e of n.intermediateResultUnits)e.originalImageTag=t.tag?t.tag:null;r[n.info.callbackName]&&r[n.info.callbackName]({intermediateResultUnits:n.intermediateResultUnits},n.info)}else r[n.info.callbackName]&&r[n.info.callbackName](n.result,n.info);i===At(this,Jt,"f")._intermediateResultReceiverSet.size&&delete n.info.callbackName}}}}return n&&n.hasOwnProperty("intermediateResult")&&delete n.intermediateResult,Rt(this,ie,0,"f"),h.resolve(n)}catch(t){return h.reject(t)}}},le._onLog&&le._onLog(`send buffer to worker: ${Date.now()}`),et.postMessage({type:"cvr_capture",id:a,instanceID:this._instanceID,body:{bytes:i,width:r,height:n,stride:s,format:o,templateName:e||"",isScanner:At(this,re,"f")}},[i.buffer]),h}async initSettings(t){return ae(this),t&&["string","object"].includes(typeof t)?("string"==typeof t?t.trimStart().startsWith("{")||(t=await x(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise(((e,i)=>{let r=rt();nt[r]=async r=>{if(r.success){const n=JSON.parse(r.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Init Settings Failed.");return t.errorCode=n.errorCode,i(t)}const s=JSON.parse(t);this._currentSettings=s;let o=[],a=s.CaptureVisionTemplates;for(let t=0;t{let r=rt();nt[r]=async t=>{if(t.success){const r=JSON.parse(t.response);if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,i(t)}return e(JSON.parse(r.data))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_outputSettings",id:r,instanceID:this._instanceID,body:{templateName:t||"*"}})}))}async outputSettingsToFile(t,e,i){const r=await this.outputSettings(t),n=new Blob([JSON.stringify(r,null,2,(function(t,e){return e instanceof Array?JSON.stringify(e):e}),2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(n),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout((()=>{URL.revokeObjectURL(t.href)}),500)},t.click()}return n}async getTemplateNames(){return ae(this),await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success){const r=JSON.parse(i.response);if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,e(t)}return t(JSON.parse(r.data))}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})}))}async getSimplifiedSettings(t){ae(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const e=await this.containsTask(t);return await ft(e),await new Promise(((e,i)=>{let r=rt();nt[r]=async t=>{if(t.success){const r=JSON.parse(t.response);if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,i(t)}const n=JSON.parse(r.data,((t,e)=>"barcodeFormatIds"===t?BigInt(e):e));return n.minImageCaptureInterval=this._minImageCaptureInterval,e(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_getSimplifiedSettings",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async updateSettings(t,e){ae(this);const i=await this.containsTask(t);return await ft(i),await new Promise(((i,r)=>{let n=rt();nt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Update Settings Failed.");return t.errorCode=n.errorCode,r(t)}return this._currentSettings=await this.outputSettings("*"),i(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},et.postMessage({type:"cvr_updateSettings",id:n,instanceID:this._instanceID,body:{settings:e,templateName:t}})}))}async resetSettings(){return ae(this),await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success){const r=JSON.parse(i.response);if(0!==r.errorCode){let t=new Error(r.errorString?r.errorString:"Reset Settings Failed.");return t.errorCode=r.errorCode,e(t)}return this._currentSettings=await this.outputSettings("*"),t(r)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})}))}getBufferedItemsManager(){return At(this,Qt,"f")||Rt(this,Qt,new Ft(this),"f"),At(this,Qt,"f")}getIntermediateResultManager(){if(ae(this),!At(this,ne,"f")&&0!==gt.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return At(this,Jt,"f")||Rt(this,Jt,new Bt(this),"f"),At(this,Jt,"f")}async parseRequiredResources(t){return ae(this),await new Promise(((e,i)=>{let r=rt();nt[r]=async t=>{if(t.success)return e(JSON.parse(t.resources));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_parseRequiredResources",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async dispose(){ae(this),At(this,Kt,"f")&&this.stopCapturing(),Rt(this,Zt,null,"f"),At(this,$t,"f").clear(),At(this,te,"f").clear(),At(this,ee,"f").clear(),At(this,Jt,"f")._intermediateResultReceiverSet.clear(),Rt(this,se,!0,"f");let t=rt();nt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},et.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:At(this,Zt,"f"),promiseStartScan:At(this,Kt,"f"),intermediateResultManager:At(this,Jt,"f"),bufferdItemsManager:At(this,Qt,"f"),resultReceiverSet:At(this,$t,"f"),isaStateListenerSet:At(this,te,"f"),resultFilterSet:At(this,ee,"f"),compressRate:At(this,ie,"f"),canvas:At(this,qt,"f"),isScanner:At(this,re,"f"),innerUseTag:At(this,ne,"f"),isDestroyed:At(this,se,"f")}}async _getWasmFilterState(){return await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})}))}}async function ce(t,e){return ae(t),await new Promise(((i,r)=>{let n=rt();nt[n]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},et.postMessage({type:"cvr_enableResultCrossVerification",id:n,instanceID:t._instanceID,body:{verificationEnabled:e}})}))}async function ue(t,e){return ae(t),await new Promise(((i,r)=>{let n=rt();nt[n]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},et.postMessage({type:"cvr_enableResultDeduplication",id:n,instanceID:t._instanceID,body:{duplicateFilterEnabled:e}})}))}async function de(t,e){return ae(t),await new Promise(((i,r)=>{let n=rt();nt[n]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},et.postMessage({type:"cvr_setDuplicateForgetTime",id:n,instanceID:t._instanceID,body:{duplicateForgetTime:e}})}))}Zt=new WeakMap,qt=new WeakMap,Kt=new WeakMap,Jt=new WeakMap,Qt=new WeakMap,$t=new WeakMap,te=new WeakMap,ee=new WeakMap,ie=new WeakMap,re=new WeakMap,ne=new WeakMap,se=new WeakMap,le._defaultTemplate="Default";var fe;!function(t){t.PT_DEFAULT="Default",t.PT_READ_BARCODES="ReadBarcodes_Default",t.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",t.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",t.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",t.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",t.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",t.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",t.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",t.PT_READ_SINGLE_BARCODE="ReadBarcodes_Balanced",t.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",t.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",t.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",t.PT_RECOGNIZE_LETTERS="RecognizeLetters",t.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",t.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",t.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters"}(fe||(fe={}));var ge=Object.freeze({__proto__:null,CaptureVisionRouter:le,CaptureVisionRouterModule:Ht,CapturedResultReceiver:class{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}},get EnumImageSourceState(){return zt},get EnumPresetTemplate(){return fe},IntermediateResultReceiver:class{constructor(){this._observedResultUnitTypes=St.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledDownColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}}});const me="undefined"==typeof self,pe=me?{}:self,_e="function"==typeof importScripts,ve=(()=>{if(!_e){if(!me&&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"./"}})(),ye=t=>t&&"object"==typeof t&&"function"==typeof t.then,we=(async()=>{})().constructor;let Ce=class extends we{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,ye(t)?e=t:"function"==typeof t&&(e=new we(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}constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(ye(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Ee=" is not allowed to change after `createInstance` or `loadWasm` is called.",Te=!me&&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"))||"",Se=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Ee);i._license=e}};!me&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const be=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{e=be(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Ee);i._licenseServer=e}},xe=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Ee);i._deviceFriendlyName=e}};let Oe,Ae,Re,De,Le;"undefined"!=typeof navigator&&(Oe=navigator,Ae=Oe.userAgent,Re=Oe.platform,De=Oe.mediaDevices),function(){if(!me){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Oe.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Re,search:"Win"},Mac:{str:Re},Linux:{str:Re}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||Ae,o=n.search||e,a=n.verStr||Ae,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||Ae,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=Ae.indexOf("Windows NT")&&(n="HarmonyOS"),Le={browser:i,version:r,OS:n}}me&&(Le={browser:"ssr",version:0,OS:"ssr"})}(),De&&De.getUserMedia,"Chrome"===Le.browser&&Le.version>66||"Safari"===Le.browser&&Le.version>13||"OPR"===Le.browser&&Le.version>43||"Edge"===Le.browser&&Le.version;const Me=()=>(ft("license"),tt("dynamsoft_inited",(async()=>{let{lt:t,l:e,ls:i,sp:r,rmk:n,cv:s}=((t,e=!1)=>{const i=t;if(i._pLoad.isEmpty){let r,n,s,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(n=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=be(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),r=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(pe.crypto||(s="Please upgrade your browser to support online key."),pe.crypto.subtle||(s="Require https to use online key in this browser."))),s)throw new Error(s);return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:r,cv:n}}throw new Error("Can't preprocess license again"+Ee)})(Pe),o=new Ce;Pe._pLoad.task=o,(async()=>{try{await Pe._pLoad}catch(t){}})();let a=rt();nt[a]=e=>{if(e.message&&Pe._onAuthMessage){let t=Pe._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,r=!1;if(1===t&&(r=!0),e.success?(st&&st("init license success"),e.message&&console.warn(e.message),gt._bSupportIRTModule=e.bSupportIRTModule,gt._bSupportDce4Module=e.bSupportDce4Module,Pe.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):o.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),r||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(r=!0)),r){const t=A(gt.engineResourcePaths);(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)}})({_bNeverShowDialog:Pe._bNeverShowDialog,engineResourcePath:t.license,_onLog:st},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await $("core"),et.postMessage({type:"license_dynamsoft",body:{v:"3.4.31",brtk:!!t,bptk:1===t,l:e,os:Le,fn:Pe.deviceFriendlyName,ls:i,sp:r,rmk:n,cv:s},id:a}),Pe.bCallInitLicense=!0,await o})));let Fe;ct.license={},ct.license.dynamsoft=Me,ct.license.getAR=async()=>{{let t=Q.dynamsoft_inited;t&&t.isRejected&&await t}return et?new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success){delete i.success;{let t=Pe.license;t&&(t.startsWith("t")||t.startsWith("f"))&&(i.pk=t)}if(Object.keys(i).length){if(i.lem){let t=Error(i.lem);t.ltsErrorCode=i.lec,delete i.lem,delete i.lec,i.ae=t}t(i)}else t(null)}else{let t=Error(i.message);i.stack&&(t.stack=i.stack),e(t)}},et.postMessage({type:"license_getAR",id:i})})):null};let Pe=class t{static setLicenseServer(e){Ie(t,e)}static get license(){return this._license}static set license(e){Se(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Ie(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){xe(t,e)}static initLicense(e,i){if(Se(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return Me()}static setDeviceFriendlyName(e){xe(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await tt("dynamsoft_uuid",(async()=>{await ft();let t=new Ce,e=rt();nt[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},et.postMessage({type:"license_getDeviceUUID",id:e}),Fe=await t})),Fe))()}};Pe._pLoad=new Ce,Pe.bPassValidation=!1,Pe.bCallInitLicense=!1,Pe._license=Te,Pe._licenseServer=[],Pe._deviceFriendlyName="",gt.engineResourcePaths.license={version:"3.4.31",path:ve,isInternal:!0},ut.license={wasm:!0,js:!0},ct.license.LicenseManager=Pe;const ke="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&O(gt.engineResourcePaths.std.version,ke)<0&&(gt.engineResourcePaths.std={version:ke,path:(t=>{if(null==t&&(t="./"),me||_e);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(ve+`../../dynamsoft-capture-vision-std@${ke}/dist/`),isInternal:!0});var Be=Object.freeze({__proto__:null,LicenseManager:Pe,LicenseModule:class{static getVersion(){return`3.4.31(Worker: ${lt.license&<.license.worker||"Not Loaded"}, Wasm: ${lt.license&<.license.wasm||"Not Loaded"})`}}});const Ne="undefined"==typeof self,je="function"==typeof importScripts,Ue=(()=>{if(!je){if(!Ne&&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"./"}})();gt.engineResourcePaths.dce={version:"4.1.1",path:Ue,isInternal:!0},ut.dce={wasm:!1,js:!1},ct.dce={};let Ve,Ge,We,Ye,He;function Xe(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function ze(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(Ve=navigator,Ge=Ve.userAgent,We=Ve.platform,Ye=Ve.mediaDevices),function(){if(!Ne){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Ve.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:We,search:"Win"},Mac:{str:We},Linux:{str:We}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||Ge,o=n.search||e,a=n.verStr||Ge,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||Ge,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=Ge.indexOf("Windows NT")&&(n="HarmonyOS"),He={browser:i,version:r,OS:n}}Ne&&(He={browser:"ssr",version:0,OS:"ssr"})}();const Ze="undefined"!=typeof WebAssembly&&Ge&&!(/Safari/.test(Ge)&&!/Chrome/.test(Ge)&&/\(.+\s11_2_([2-6]).*\)/.test(Ge)),qe=!("undefined"==typeof Worker),Ke=!(!Ye||!Ye.getUserMedia),Je=async()=>{let t=!1;if(Ke)try{(await Ye.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===He.browser&&He.version>66||"Safari"===He.browser&&He.version>13||"OPR"===He.browser&&He.version>43||"Edge"===He.browser&&He.version;var Qe={653:(t,e,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,m,p,_,v,y,w,C,E,T,S=S||{version:"5.2.1"};if(e.fabric=S,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?S.document=document:S.document=document.implementation.createHTMLDocument(""),S.window=window;else{var b=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;S.document=b.document,S.jsdomImplForWrapper=i(898).implForWrapper,S.nodeCanvas=i(245).Canvas,S.window=b,DOMParser=S.window.DOMParser}function I(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 x(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)}S.isTouchSupported="ontouchstart"in S.window||"ontouchstart"in S.document||S.window&&S.window.navigator&&S.window.navigator.maxTouchPoints>0,S.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,S.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"],S.DPI=96,S.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",S.commaWsp="(?:\\s+,?\\s*|,\\s*)",S.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,S.reNonWord=/[ \n\.,;!\?\-]/,S.fontPaths={},S.iMatrix=[1,0,0,1,0,0],S.svgNS="http://www.w3.org/2000/svg",S.perfLimitSizeTotal=2097152,S.maxCacheSideLimit=4096,S.minCacheSideLimit=256,S.charWidthsCache={},S.textureSize=2048,S.disableStyleCopyPaste=!1,S.enableGLFiltering=!0,S.devicePixelRatio=S.window.devicePixelRatio||S.window.webkitDevicePixelRatio||S.window.mozDevicePixelRatio||1,S.browserShadowBlurConstant=1,S.arcToSegmentsCache={},S.boundsOfCurveCache={},S.cachesBoundsOfCurve=!0,S.forceGLPutImageData=!1,S.initFilterBackend=function(){return S.enableGLFiltering&&S.isWebglSupported&&S.isWebglSupported(S.textureSize)?(console.log("max texture size: "+S.maxTextureSize),new S.WebglFilterBackend({tileSize:S.textureSize})):S.Canvas2dFilterBackend?new S.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=S),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:S.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)}S.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)}},S.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof S.Gradient||this.set(e,new S.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof S.Pattern?i&&i():this.set(e,new S.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,S.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 S.Point(t.x-e.x,t.y-e.y),n=S.util.rotateVector(r,i);return new S.Point(n.x,n.y).addEquals(e)},rotateVector:function(t,e){var i=S.util.sin(e),r=S.util.cos(e);return{x:t.x*r-t.y*i,y:t.x*i+t.y*r}},createVector:function(t,e){return new S.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 S.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var r=S.util.createVector(t,e),n=S.util.createVector(t,i),s=S.util.calcAngleBetweenVectors(r,n),o=s*(0===S.util.calcAngleBetweenVectors(S.util.rotateVector(r,s),n)?1:-1)/2;return{vector:S.util.getHatVector(S.util.rotateVector(r,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var r=[],n=e.strokeWidth/2,s=e.strokeUniform?new S.Point(1/e.scaleX,1/e.scaleY):new S.Point(1,1),o=function(t){var e=n/Math.hypot(t.x,t.y);return new S.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 S.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(S.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(S.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=S.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-n/Math.sin(p/2),f=new S.Point(m.x*d*s.x,m.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 S.Point(m.x*d*s.x,m.y*d*s.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(t,e,i){return i?new S.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new S.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=S.util.sin(c),d=S.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,C=_*v-_*y-v*w,E=0;if(C<0){var T=Math.sqrt(1-C/(_*v));i*=T,s*=T}else E=(o===a?-1:1)*Math.sqrt(C/(_*y+v*w));var b=E*i*p/s,I=-E*s*m/i,x=d*b-u*I+.5*t,O=u*b+d*I+.5*e,A=n(1,0,(m-b)/i,(p-I)/s),R=n((m-b)/i,(p-I)/s,(-m-b)/i,(-p-I)/s);0===a&&R>0?R-=2*l:1===a&&R<0&&(R+=2*l);for(var D=Math.ceil(Math.abs(R/l*2)),L=[],M=R/D,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=A+M,k=0;kE)for(var b=1,I=m.length;b2;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},S.util.getPathSegmentsInfo=d,S.util.getBoundsOfCurve=function(e,i,r,n,s,o,a,h){var l;if(S.cachesBoundsOfCurve&&(l=t.call(arguments),S.boundsOfCurveCache[l]))return S.boundsOfCurveCache[l];var c,u,d,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,C=Math.abs,E=[],T=[[],[]];u=6*e-12*r+6*s,c=-3*e+9*r-9*s+3*a,d=3*r-3*e;for(var b=0;b<2;++b)if(b>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&&E.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&E.push(g),0<(m=(-u-_)/(2*c))&&m<1&&E.push(m));for(var I,x,O,A=E.length,R=A;A--;)I=(O=1-(f=E[A]))*O*O*e+3*O*O*f*r+3*O*f*f*s+f*f*f*a,T[0][A]=I,x=O*O*O*i+3*O*O*f*n+3*O*f*f*o+f*f*f*h,T[1][A]=x;T[0][R]=e,T[1][R]=i,T[0][R+1]=a,T[1][R+1]=h;var D=[{x:y.apply(null,T[0]),y:y.apply(null,T[1])},{x:w.apply(null,T[0]),y:w.apply(null,T[1])}];return S.cachesBoundsOfCurve&&(S.boundsOfCurveCache[l]=D),D},S.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)}},S.util.transformPath=function(t,e,i){return i&&(e=S.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(!S.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}S.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)}S.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=S.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=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}),S.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?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var r in e)"opacity"===r?m(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(S.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=S.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=S.document.documentElement,n=S.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===S.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=S.document.defaultView&&S.document.defaultView.getComputedStyle?function(t,e){var i=S.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=S.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",S.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=S.util.falseFunction),r?t.style[r]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},S.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),r?t.style[r]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},S.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},S.util.getById=function(t){return"string"==typeof t?S.document.getElementById(t):t},S.util.toArray=s,S.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},S.util.makeElement=o,S.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},S.util.getScrollLeftTop=a,S.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}},S.util.getNodeCanvas=function(t){var e=S.jsdomImplForWrapper(t);return e._canvas||e._image},S.util.cleanUpJsdomNode=function(t){if(S.isLikelyNode){var e=S.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}S.util.request=function(e,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",n=i.onComplete||function(){},s=new S.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}}(),S.log=console.log,S.warn=console.warn,function(){var t=S.util.object.extend,e=S.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}S.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=S.window.requestAnimationFrame||S.window.webkitRequestAnimationFrame||S.window.mozRequestAnimationFrame||S.window.oRequestAnimationFrame||S.window.msRequestAnimationFrame||function(t){return S.window.setTimeout(t,1e3/60)},o=S.window.cancelAnimationFrame||S.window.clearTimeout;function a(){return s.apply(S.window,arguments)}S.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=S.runningAnimations.indexOf(s);return t>-1&&S.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}),S.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,m=i.easing||n,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map((function(t,e){return v[e]-_[e]})):v-_);i.onStart&&i.onStart(),function t(i){var r=(e=i||+new Date)>u?c:e-l,n=r/c,w=p?_.map((function(t,e){return m(r,_[e],y[e],c)})):m(r,_,y,c),C=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=C,s.durationRate=n,!o){if(!f(w,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(w,C,n),void a(t));h()}}(l)})),s.cancel},S.util.requestAnimFrame=a,S.util.cancelAnimFrame=function(){return o.apply(S.window,arguments)},S.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))+")"}S.util.animateColor=function(e,i,r,n){var s=new S.Color(e).getSource(),o=new S.Color(i).getSource(),a=n.onComplete,h=n.onChange;return n=n||{},S.util.animate(S.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,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,C={},E="",T=0,S=0;if(C.width=0,C.height=0,C.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+E,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return C;if(_)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),T=C.width-n*c,S=C.height-o*c,"Mid"===p.alignX&&(T/=2),"Mid"===p.alignY&&(S/=2),"Min"===p.alignX&&(T=0),"Min"===p.alignY&&(S=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===m)return C;if((g||m)&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") "),a=E+" matrix("+c+" 0 0 "+u+" "+(i*c+T)+" "+(r*u+S)+") ","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 w(t,e){var i="xlink:href",r=_(t,e.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&w(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 m(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 _(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 w(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 E(t){return t.flipX!==t.flipY}function T(t,e,i,r,n){if(0!==t[e]){var s=n/t._getTransformedDimensions()[r]*t[i];t.set(i,s)}}function S(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),E(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",n),T(l,"skewY","scaleY","y",p)}return m}function b(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),E(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",n),T(l,"skewX","scaleX","x",p)}return m}function I(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,w=m(t,f),E=_(f,y,w),T=e.gestureScale;if(E)return!1;if(T)o=e.scaleX*T,a=e.scaleY*T;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(),w&&!y){var S=Math.abs(s.x)+Math.abs(s.y),b=e.original,I=S/(Math.abs(h.x*b.scaleX/f.scaleX)+Math.abs(h.y*b.scaleY/f.scaleY));o=b.scaleX*I,a=b.scaleY*I}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 x=f.scaleX,O=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)),x!==f.scaleX||O!==f.scaleY}n.scaleCursorStyleHandler=function(t,e,r){var n=m(t,r),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(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=w("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,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),E(h)&&(n=n===s?a:s)),e.originX=n,w("skewing",y(S))(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),E(a)&&(n=n===o?h:o)),e.originY=n,w("skewing",y(b))(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=w,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),m=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(m),l=f*e.util.sin(m)}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 S.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*e,{offset:a,color:i.toRgb(),opacity:n}}var e=S.util.object.clone;S.Gradient=S.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+="_"+S.Object.__uid++:this.id=S.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 S.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 S.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():S.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+" ":"")+S.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=m/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=S.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,m=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=S.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,m=-i.top),new S.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:m})}})}(),_=S.util.toFixed,S.Pattern=S.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=S.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=S.util.createImage(),S.util.loadImage(t.source,(function(t,r){i.source=t,e&&e(i,r)}),null,this.crossOrigin)}},toObject:function(t){var e,i,r=S.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:_(this.offsetX,r),offsetY:_(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},S.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(S.StaticCanvas)S.warn("fabric.StaticCanvas is already defined.");else{var t=S.util.object.extend,e=S.util.getElementOffset,i=S.util.removeFromArray,r=S.util.toFixed,n=S.util.transformPoint,s=S.util.invertTransform,o=S.util.getNodeCanvas,a=S.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");S.StaticCanvas=S.util.createClass(S.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:S.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 S.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,S.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=S.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?S.util.loadImage(e,(function(e,n){if(e){var s=new S.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=S.util.getById(t)||this._createCanvasElement(),S.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=S.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 ",S.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+S.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?S.util.matrixToSVG(n):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,r,n,s,o,a,h="",l={},c=S.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(S.StaticCanvas.prototype,S.Observable),t(S.StaticCanvas.prototype,S.Collection),t(S.StaticCanvas.prototype,S.DataURLExporter),t(S.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}}),S.StaticCanvas.prototype.toJSON=S.StaticCanvas.prototype.toObject,S.isLikelyNode&&(S.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},S.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),S.BaseBrush=S.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*=S.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*r,i.shadowOffsetX=e.offsetX*r,i.shadowOffsetY=e.offsetY*r}},needsFullRender:function(){return new S.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()}}),S.PencilBrush=S.util.createClass(S.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 S.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 S.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 S.Point(r.x,r.y),n=new S.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})}}}),S.CircleBrush=S.util.createClass(S.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=S.util.invertTransform(i),n=this.restorePointerVpt(e);return S.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 S.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,S.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):S.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:S.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 S.Point(e.ex,e.ey),r=S.util.transformPoint(i,this.viewportTransform),n=new S.Point(e.ex+e.left,e.ey+e.top),s=S.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,S.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 S.Group&&(r=this._searchPossibleTargets(i._objects,e))&&this.targets.push(r);break}}return i},restorePointerVpt:function(t){return S.util.transformPoint(t,S.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),S.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=S.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),S.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),S.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;S.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,S.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:e,target:t}),s.push(t))})),r.forEach((function(r){-1===t.indexOf(r)&&(i=!0,r.fire("selected",{e:e,target:r}),n.push(r))})),t.length>0&&r.length>0?i&&this.fire("selection:updated",{e:e,selected:n,deselected:s}):r.length>0?this.fire("selection:created",{e:e,selected:n}):t.length>0&&this.fire("selection:cleared",{e: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: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){S.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,S.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]})),S.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(),S.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),S.StaticCanvas)"prototype"!==r&&(S.Canvas[r]=S.StaticCanvas[r])}(),function(){var t=S.util.addListener,e=S.util.removeListener,i={passive:!1};function r(t,e){return t.button&&t.button===e-1}S.util.object.extend(S.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(S.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(S.document,t+"up",this._onMouseUp),e(S.document,"touchend",this._onTouchEnd,i),e(S.document,t+"move",this._onMouseMove,i),e(S.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(S.document,"touchend",this._onTouchEnd,i),t(S.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(S.document,s+"up",this._onMouseUp),t(S.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(S.document,"touchend",this._onTouchEnd,i),e(S.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(S.document,s+"up",this._onMouseUp),e(S.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),S.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: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 S.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 S.Point(v(r,s),v(n,o)),h=new S.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}}),S.util.object.extend(S.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 S.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=S.util.createCanvasElement(),m=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=m,g}}),S.util.object.extend(S.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var r="string"==typeof t?JSON.parse(t):S.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?S.util.enlivenObjects([e],(function(e){n[t]=e[0],i[t]=!0,r&&r()})):this["set"+S.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,r&&r()}))},_enlivenObjects:function(t,e,i){t&&0!==t.length?S.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=S.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new S.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,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,C=l>y||c>w;v=C||(l<.9*y||c<.9*w)&&y>h&&w>h,C&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(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,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.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 _=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",_),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),w=S.util.degreesToRadians,C={left:-.5,center:0,right:.5},E={top:-.5,center:0,bottom:.5},S.util.object.extend(S.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=E[i]:i-=.5,"string"==typeof n?n=E[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 S.Point(h,l)},translateToCenterPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?S.util.rotatePoint(r,t,w(this.angle)):r},translateToOriginPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?S.util.rotatePoint(r,t,w(this.angle)):r},getCenterPoint:function(){var t=new S.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 S.Point(this.left,this.top),n=new S.Point(t.x,t.y),this.angle&&(n=S.util.rotatePoint(n,s,-w(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=w(this.angle),n=this.getScaledWidth(),s=S.util.cos(r)*n,o=S.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=S.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,r=t.transformPoint;t.object.extend(S.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 S.Point(i.tl.x,i.tl.y),new S.Point(i.tr.x,i.tr.y),new S.Point(i.br.x,i.br.y),new S.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,r){var n=this.getCoords(i,r);return"Intersection"===S.Intersection.intersectPolygonRectangle(n,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===S.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=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+S.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[m]=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=S.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=S.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=S.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(){}})}(),S.util.object.extend(S.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return S.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 S.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 S.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()}})}}),S.util.object.extend(S.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?S.util.animateColor(h.startValue,h.endValue,h.duration,h):S.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 S.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);S.filterBackend||(S.filterBackend=S.initFilterBackend());var o=S.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,S.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=S.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 S.filterBackend||(S.filterBackend=S.initFilterBackend()),S.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){S.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){S.util.setImageSmoothing(t,this.imageSmoothing),S.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),m=o(s*r,u-f),p=-n/2,_=-s/2,v=o(n,c/i-h),y=o(s,u/r-l);e&&t.drawImage(e,d,f,g,m,p,_,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(S.util.getById(t),e),S.util.addClass(this.getElement(),S.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?S.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=S.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=S.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=S.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}}}),S.Image.CSS_CANVAS="canvas-img",S.Image.prototype.getSvgSrc=S.Image.prototype.getSrc,S.Image.fromObject=function(t,e){var i=S.util.object.clone(t);S.util.loadImage(i.src,(function(t,r){r?e&&e(null,!0):S.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],S.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],S.util.enlivenObjectEnlivables(i,i,(function(){var r=new S.Image(t,i);e(r,!1)}))}))}))}),null,i.crossOrigin)},S.Image.fromURL=function(t,e,i){S.util.loadImage(t,(function(t,r){e&&e(new S.Image(t,i),r)}),null,i&&i.crossOrigin)},S.Image.ATTRIBUTE_NAMES=S.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),S.Image.fromElement=function(t,i,r){var n=S.parseAttributes(t,S.Image.ATTRIBUTE_NAMES);S.Image.fromURL(n["xlink:href"],i,e(r?S.util.object.clone(r):{},n))})}(e),S.util.object.extend(S.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 S.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()}})}}),S.util.object.extend(S.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()}S.isWebglSupported=function(e){if(S.isLikelyNode)return!1;e=e||S.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),n=!1;if(r){S.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),n=S.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(r,s[o])){S.webGlPrecision=s[o];break}}return this.isSupported=n,n},S.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=S.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(S.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=S.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:I,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(){}S.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}}}(),S.Image=S.Image||{},S.Image.filters=S.Image.filters||{},S.Image.filters.BaseFilter=S.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"!==S.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+S.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=S.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()}}),S.Image.filters.BaseFilter.fromObject=function(t,e){var i=new S.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=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,r+=m[h+2]*l,T||(n+=m[h+3]*l));E[s]=e,E[s+1]=i,E[s+2]=r,E[s+3]=T?m[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,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){L=r(1e3*s(S-C.x)),w[L]||(w[L]={});for(var F=E.y-y;F<=E.y+y;F++)F<0||F>=o||(M=r(1e3*s(F-C.y)),w[L][M]||(w[L][M]=f(n(i(L*p,2)+i(M*_,2))/1e3)),(b=w[L][M])>0&&(x+=b,O+=b*c[I=4*(F*e+S)],A+=b*c[I+1],R+=b*c[I+2],D+=b*c[I+3]))}d[I=4*(T*a+h)]=O/x,d[I+1]=A/x,d[I+2]=R/x,d[I+3]=D/x}return++h1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(b+=y*f[3+(L=4*(D+x*e))],C+=y,f[L+3]<255&&(y=y*f[L+3]/250),E+=y*f[L],T+=y*f[L+1],S+=y*f[L+2],w+=y)}m[v]=E/w,m[v+1]=T/w,m[v+2]=S/w,m[v+3]=b/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,m=this._textLines.length;g=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 x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+E*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,r=n,o=a}else d+=f.kernedWidth;x=v+s+u,"rtl"===this.direction&&(x=this.width-x-d),t.fillStyle=p,g&&p&&t.fillRect(x,c+E*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)}S.IText=S.util.createClass(S.Text,S.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),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,C=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,C=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+C,y,w),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}}}),S.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]);S.Object._fromObject("IText",e,i,"text")}}(),T=S.util.object.clone,S.util.object.extend(S.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||[],S.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=S.util.string.graphemeSplit(r).length;if(t===e)return{selectionStart:n,selectionEnd:n};var s=i.slice(t,e);return{selectionStart:n,selectionEnd:n+S.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,m=c.clientWidth/u,p=c.clientHeight/d;return h=S.util.transformPoint(h,a),(h=S.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,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=T(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:T(r[i-1])}:n?this.styles[t+i]={0:T(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?T(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]=T(r[i]));else if(n)for(var h=n[e?e-1:1];h&&i--;)this.styles[t][e+i]=T(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)}}),S.util.object.extend(S.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}}),S.util.object.extend(S.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=S.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):S.document.body.appendChild(this.hiddenTextarea),S.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),S.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),S.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),S.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),S.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),S.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),S.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),S.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),S.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(S.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),m=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=S.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=S.util.toFixed,e=/ +/g;S.util.object.extend(S.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",S.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,m=f.length-1;g<=m;g++)h=g===m||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=S.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+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+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:()=>{}},$e={};function ti(t){var e=$e[t];if(void 0!==e)return e.exports;var i=$e[t]={exports:{}};return Qe[t](i,i.exports,ti),i.exports}ti.d=(t,e)=>{for(var i in e)ti.o(e,i)&&!ti.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},ti.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var ei={};(()=>{let t;ti.d(ei,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?ti(653).fabric:{version:"5.2.1"}})();var ii,ri,ni,si,oi=ei.R;!function(t){t[t.DIMT_RECTANGLE=1]="DIMT_RECTANGLE",t[t.DIMT_QUADRILATERAL=2]="DIMT_QUADRILATERAL",t[t.DIMT_TEXT=4]="DIMT_TEXT",t[t.DIMT_ARC=8]="DIMT_ARC",t[t.DIMT_IMAGE=16]="DIMT_IMAGE",t[t.DIMT_POLYGON=32]="DIMT_POLYGON",t[t.DIMT_LINE=64]="DIMT_LINE",t[t.DIMT_GROUP=128]="DIMT_GROUP"}(ii||(ii={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(ri||(ri={})),function(t){t[t.EF_ENHANCED_FOCUS=4]="EF_ENHANCED_FOCUS",t[t.EF_AUTO_ZOOM=16]="EF_AUTO_ZOOM",t[t.EF_TAP_TO_FOCUS=64]="EF_TAP_TO_FOCUS"}(ni||(ni={})),function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(si||(si={}));const ai=t=>"number"==typeof t&&!Number.isNaN(t),hi=t=>"string"==typeof t;var li,ci,ui,di,fi,gi,mi,pi,_i,vi,yi;!function(t){t[t.ARC=0]="ARC",t[t.IMAGE=1]="IMAGE",t[t.LINE=2]="LINE",t[t.POLYGON=3]="POLYGON",t[t.QUAD=4]="QUAD",t[t.RECT=5]="RECT",t[t.TEXT=6]="TEXT",t[t.GROUP=7]="GROUP"}(fi||(fi={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(gi||(gi={}));class wi{get mediaType(){return new Map([["rect",ii.DIMT_RECTANGLE],["quad",ii.DIMT_QUADRILATERAL],["text",ii.DIMT_TEXT],["arc",ii.DIMT_ARC],["image",ii.DIMT_IMAGE],["polygon",ii.DIMT_POLYGON],["line",ii.DIMT_LINE],["group",ii.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(Xe(this,ci,"f")){case ri.DIS_DEFAULT:return"default";case ri.DIS_SELECTED:return"selected"}}set drawingStyleId(t){this.styleId=t}get drawingStyleId(){return this.styleId}set coordinateBase(t){if(!["view","image"].includes(t))throw new Error("Invalid 'coordinateBase'.");this._drawingLayer&&("image"===Xe(this,ui,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===Xe(this,ui,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),ze(this,ui,t,"f")}get coordinateBase(){return Xe(this,ui,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(li.add(this),ci.set(this,void 0),ui.set(this,"image"),this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapState_StyleId=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,null!=e&&!ai(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(ri.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",(()=>{this.setState(ri.DIS_SELECTED)})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(ri.DIS_SELECTED):this.setState(ri.DIS_DEFAULT),"textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}setState(t){ze(this,ci,t,"f")}getState(){return Xe(this,ci,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),r=this.mapEvent_Callbacks.get(i);if(!r)throw new Error(`Event '${t}' does not exist.`);let n=r.get(e);n||(n=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const r={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,n,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,n=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)u0?i-1:r,Si),actionName:"modifyPolygon",pointIndex:i}),t}),{}),ze(this,pi,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,r){return t["p"+r]=new oi.Control({positionHandler:Ei,actionHandler:bi(r>0?r-1:i,Si),actionName:"modifyPolygon",pointIndex:r}),t}),{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let r=i.x-e.pathOffset.x,n=i.y-e.pathOffset.y;const s=oi.util.transformPoint({x:r,y:n},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){Xe(this,pi,"f")&&this.setPolygon(Xe(this,pi,"f"))}setPolygon(t){if(!S(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else ze(this,pi,JSON.parse(JSON.stringify(t)),"f")}getPolygon(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Xe(this,pi,"f")?JSON.parse(JSON.stringify(Xe(this,pi,"f"))):null}}pi=new WeakMap;_i=new WeakMap,vi=new WeakMap;const xi=t=>{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let r=0;ri&&(i=n.length)}if(-1===i)break;for(let r=0;r=t[r].length-1)continue;let n=" ".repeat(i+2-t[r][e].length);t[r][e]=t[r][e].concat(n)}}})(e),(t=>{let e="";for(let i=0;i({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else ze(this,Ri,JSON.parse(JSON.stringify(t)),"f")}getQuad(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Xe(this,Ri,"f")?JSON.parse(JSON.stringify(Xe(this,Ri,"f"))):null}}Ri=new WeakMap;class Li extends wi{constructor(t){super(new oi.Group(t.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.setState(ri.DIS_SELECTED);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.setState(ri.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}setChildDrawingItems(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()))}}const Mi=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),Fi=t=>!!hi(t)&&""!==t,Pi=t=>!(!Mi(t)||"id"in t&&!ai(t.id)||"lineWidth"in t&&!ai(t.lineWidth)||"fillStyle"in t&&!Fi(t.fillStyle)||"strokeStyle"in t&&!Fi(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!Fi(t.fontFamily)||"fontSize"in t&&!ai(t.fontSize));class ki{static convert(t,e,i){const r={x:0,y:0,width:e,height:i};if(!t)return r;if(I(t))t.isMeasuredInPercentage?(r.x=t.x/100*e,r.y=t.y/100*i,r.width=t.width/100*e,r.height=t.height/100*i):(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height);else{if(!w(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?(r.x=t.left/100*e,r.y=t.top/100*i,r.width=(t.right-t.left)/100*e,r.height=(t.bottom-t.top)/100*i):(r.x=t.left,r.y=t.top,r.width=t.right-t.left,r.height=t.bottom-t.top)}return r.x=Math.round(r.x),r.y=Math.round(r.y),r.width=Math.round(r.width),r.height=Math.round(r.height),r}}var Bi,Ni;class ji{constructor(){Bi.set(this,new Map),Ni.set(this,!1)}get disposed(){return Xe(this,Ni,"f")}on(t,e){t=t.toLowerCase();const i=Xe(this,Bi,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else Xe(this,Bi,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=Xe(this,Bi,"f").get(t);if(!i)return;const r=i.indexOf(e);-1!==r&&i.splice(r,1)}offAll(t){t=t.toLowerCase();const e=Xe(this,Bi,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const r=Xe(this,Bi,"f").get(t);if(r&&r.length){i=Object.assign({async:!1,copy:!0},i);for(let n of r){if(!n)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let o=!1;if(i.async)setTimeout((()=>{this.disposed||r.includes(n)&&n.apply(i.target,s)}),0);else try{o=n.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){ze(this,Ni,!0,"f")}}function Ui(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function Vi(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function Gi(t,e,i,r){let n=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(r[1]-e[1])+e[0]*(t[1]-r[1])+r[0]*(e[1]-t[1]);return!((n^s)>=0&&0!==n&&0!==s||(n=i[0]*(t[1]-r[1])+r[0]*(i[1]-t[1])+t[0]*(r[1]-i[1]),s=i[0]*(e[1]-r[1])+r[0]*(i[1]-e[1])+e[0]*(r[1]-i[1]),(n^s)>=0&&0!==n&&0!==s))}Bi=new WeakMap,Ni=new WeakMap;const Wi=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const r=document.createElement("div");if(r.insertAdjacentHTML("beforeend",i),1===r.childElementCount&&r.firstChild instanceof HTMLTemplateElement)return r.firstChild.content;const n=new DocumentFragment;for(let t of r.children)n.append(t);return n};var Yi,Hi,Xi,zi,Zi,qi,Ki,Ji,Qi,$i,tr,er,ir,rr,nr,sr,or,ar,hr,lr,cr,ur,dr,fr,gr,mr,pr,_r,vr,yr,wr,Cr,Er,Tr;class Sr{static createDrawingStyle(t){if(!Pi(t))throw new Error("Invalid style definition.");let e,i=Sr.USER_START_STYLE_ID;for(;Xe(Sr,Yi,"f",Hi).has(i);)i++;e=i;const r=JSON.parse(JSON.stringify(t));r.id=e;for(let t in Xe(Sr,Yi,"f",Xi))r.hasOwnProperty(t)||(r[t]=Xe(Sr,Yi,"f",Xi)[t]);return Xe(Sr,Yi,"f",Hi).set(e,r),r.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=Xe(Sr,Yi,"f",Hi).get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}static getDrawingStyle(t){return this._getDrawingStyle(t,!0)}static getAllDrawingStyles(){return JSON.parse(JSON.stringify(Array.from(Xe(Sr,Yi,"f",Hi).values())))}static _updateDrawingStyle(t,e){if(!Pi(e))throw new Error("Invalid style definition.");const i=Xe(Sr,Yi,"f",Hi).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}Yi=Sr,Sr.STYLE_BLUE_STROKE=1,Sr.STYLE_GREEN_STROKE=2,Sr.STYLE_ORANGE_STROKE=3,Sr.STYLE_YELLOW_STROKE=4,Sr.STYLE_BLUE_STROKE_FILL=5,Sr.STYLE_GREEN_STROKE_FILL=6,Sr.STYLE_ORANGE_STROKE_FILL=7,Sr.STYLE_YELLOW_STROKE_FILL=8,Sr.STYLE_BLUE_STROKE_TRANSPARENT=9,Sr.STYLE_GREEN_STROKE_TRANSPARENT=10,Sr.STYLE_ORANGE_STROKE_TRANSPARENT=11,Sr.USER_START_STYLE_ID=1024,Hi={value:new Map([[Sr.STYLE_BLUE_STROKE,{id:Sr.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_GREEN_STROKE,{id:Sr.STYLE_GREEN_STROKE,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_ORANGE_STROKE,{id:Sr.STYLE_ORANGE_STROKE,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_YELLOW_STROKE,{id:Sr.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_BLUE_STROKE_FILL,{id:Sr.STYLE_BLUE_STROKE_FILL,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_GREEN_STROKE_FILL,{id:Sr.STYLE_GREEN_STROKE_FILL,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_ORANGE_STROKE_FILL,{id:Sr.STYLE_ORANGE_STROKE_FILL,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_YELLOW_STROKE_FILL,{id:Sr.STYLE_YELLOW_STROKE_FILL,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_BLUE_STROKE_TRANSPARENT,{id:Sr.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_GREEN_STROKE_TRANSPARENT,{id:Sr.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_ORANGE_STROKE_TRANSPARENT,{id:Sr.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},Xi={value:{lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}},"undefined"!=typeof document&&"undefined"!=typeof window&&(oi.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(oi.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),oi.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},oi.Object.prototype.transparentCorners=!1,oi.Object.prototype.cornerSize=20,oi.Object.prototype.touchCornerSize=100,oi.Object.prototype.cornerColor="rgb(254,142,20)",oi.Object.prototype.cornerStyle="circle",oi.Object.prototype.strokeUniform=!0,oi.Object.prototype.hasBorders=!1,oi.Canvas.prototype.containerClass="",oi.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=oi.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,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:n.x*i.width,y:(n.y-(f-m)/2)*i.width}):(g=f*p,m=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===l?p>_?{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}},oi.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,r=this._getEventPrefix();oi.util.addListener(oi.document,"touchend",this._onTouchEnd,{passive:!1}),oi.util.addListener(oi.document,"touchmove",this._onMouseMove,{passive:!1}),oi.util.removeListener(i,r+"down",this._onMouseDown)},oi.Textbox.prototype._wrapLine=function(t,e,i,r){const n=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!n||!n.length);var o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?oi.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,m=0,p=0,_=!0,v=this._getWidthOfCharSpacing();r=r||0,0===c.length&&c.push([]),i-=r;for(var y=0;yi&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),h});class br{get width(){return this.fabricCanvas.width}get height(){return this.fabricCanvas.height}set _allowMultiSelect(t){this.fabricCanvas.selection=t,this.fabricCanvas.renderAll()}get _allowMultiSelect(){return this.fabricCanvas.selection}constructor(t,e,i){if(this.mapType_StateAndStyleId=new Map,this.mode="viewer",this.onSelectionChanged=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas"))this.fabricCanvas=t.getFabricCanvas();else{let e=this.fabricCanvas=new oi.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.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.onSelectionChanged&&t.onSelectionChanged(i,[])}),0)}})),e.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.onSelectionChanged&&t.onSelectionChanged([],e)}),0)}})),e.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.onSelectionChanged&&t.onSelectionChanged(r,n)}),0)}})),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let r,n;switch(this.id=e,e){case br.DDN_LAYER_ID:r=Sr.getDrawingStyle(Sr.STYLE_BLUE_STROKE),n=Sr.getDrawingStyle(Sr.STYLE_BLUE_STROKE_FILL);break;case br.DBR_LAYER_ID:r=Sr.getDrawingStyle(Sr.STYLE_ORANGE_STROKE),n=Sr.getDrawingStyle(Sr.STYLE_ORANGE_STROKE_FILL);break;case br.DLR_LAYER_ID:r=Sr.getDrawingStyle(Sr.STYLE_GREEN_STROKE),n=Sr.getDrawingStyle(Sr.STYLE_GREEN_STROKE_FILL);break;default:r=Sr.getDrawingStyle(Sr.STYLE_YELLOW_STROKE),n=Sr.getDrawingStyle(Sr.STYLE_YELLOW_STROKE_FILL)}for(let t of wi.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:r.id,selected:n.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return Sr.getDrawingStyle(t.styleId);return Sr.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,r){const n=this.getDrawingItems((e=>e._mediaType===t));for(let t of n)t.styleSelector===e&&this._changeItemStyle(t,i,!0);r||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const r=t._getFabricObject();"number"==typeof t.styleId&&(e=Sr.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.getChildDrawingItems();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=Sr.getDrawingStyle(e.styleId);else{const r=this.mapType_StateAndStyleId.get(e._mediaType);i=Sr.getDrawingStyle(r[t.styleSelector]);const n=()=>{this._changeItemStyle(e,Sr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,Sr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",n),e._on("deselected",s),e._funcChangeStyleToSelected=n,e._funcChangeStyleToDefault=s}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("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof wi))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}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.getChildDrawingItems();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){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of wi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Sr.getDrawingStyle(t.styleId);else{s=Sr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Sr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},r=()=>{this._changeItemStyle(t,Sr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",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{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of wi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Sr.getDrawingStyle(t.styleId);else{s=Sr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Sr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},r=()=>{this._changeItemStyle(t,Sr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",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;et.toLowerCase())):e=wi.arrMediaTypes,i?i.forEach((t=>t.toLowerCase())):i=wi.arrStyleSelectors;const r=Sr.getDrawingStyle(t);if(!r)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let n;for(let s of e)if(n=this.mapType_StateAndStyleId.get(s),n)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,r,!0),n[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const r=[];i&ii.DIMT_RECTANGLE&&r.push("rect"),i&ii.DIMT_QUADRILATERAL&&r.push("quad"),i&ii.DIMT_TEXT&&r.push("text"),i&ii.DIMT_ARC&&r.push("arc"),i&ii.DIMT_IMAGE&&r.push("image"),i&ii.DIMT_POLYGON&&r.push("polygon"),i&ii.DIMT_LINE&&r.push("line");const n=[];e&ri.DIS_DEFAULT&&n.push("default"),e&ri.DIS_SELECTED&&n.push("selected"),this._setDefaultStyle(t,r.length?r:null,n.length?n:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}br.DDN_LAYER_ID=1,br.DBR_LAYER_ID=2,br.DLR_LAYER_ID=3,br.USER_DEFINED_LAYER_BASE_ID=100,br.TIP_LAYER_ID=999;class Ir{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new br(t,e,{enableRetinaScaling:!1});return i._manager=this,this._arrDrawingLayer.push(i),this._switchPointerEvent(),i}deleteDrawingLayer(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}getAllDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._getFabricCanvas().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){if(!this._arrDrawingLayer.length)return;this._getFabricCanvas().wrapperEl.style.display=t?"block":"none"}_getFabricCanvas(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0].fabricCanvas:null}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class xr extends Oi{constructor(t,e,i,r,n){super(t,{x:e,y:i,width:r,height:0},n),zi.set(this,void 0),Zi.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&ze(this,Zi,setTimeout((()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()}),Xe(this,zi,"f")),"f")}getDuration(){return Xe(this,zi,"f")}}zi=new WeakMap,Zi=new WeakMap;class Or{constructor(){qi.add(this),Ki.set(this,void 0),Ji.set(this,void 0),Qi.set(this,void 0),$i.set(this,!0),this._drawingLayerManager=new Ir}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const r=document.createElement("canvas");return r.width==t&&r.height==e||(r.width=t,r.height=e),r.style.objectFit=i,r}_createDrawingLayer(t,e,i,r){if(!this._layerBaseCvs){let n;try{n=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==n?void 0:n.width)||1280),i||(i=(null==n?void 0:n.height)||720),r||(r=(null==n?void 0:n.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,r)}const n=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(n,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",n.parentElement),s}createDrawingLayer(){let t;for(let e=br.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==br.TIP_LAYER_ID){t=e;break}return this._createDrawingLayer(t)}deleteDrawingLayer(t){var e;this._drawingLayerManager.deleteDrawingLayer(t),this._drawingLayerManager.getAllDrawingLayers().length||(null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null)}deleteUserDefinedDrawingLayer(t){if("number"!=typeof t)throw new TypeError("Invalid id.");if(tt.getId()>=0&&t.getId()!==br.TIP_LAYER_ID))}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(Mi(e=t)&&T(e.topLeftPoint)&&ai(e.width))||e.width<=0||!ai(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;ze(this,Ki,JSON.parse(JSON.stringify(t)),"f"),Xe(this,Ki,"f").coordinateBase||(Xe(this,Ki,"f").coordinateBase="view"),ze(this,Qi,t.duration,"f"),Xe(this,qi,"m",rr).call(this)}getTipConfig(){return Xe(this,Ki,"f")?Xe(this,Ki,"f"):null}setTipVisible(t){if("boolean"!=typeof t)throw new TypeError("Invalid value.");this._tip&&(this._tip.set("visible",t),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll()),ze(this,$i,t,"f")}isTipVisible(){return Xe(this,$i,"f")}updateTipMessage(t){if(!Xe(this,Ki,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=Sr.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(br.TIP_LAYER_ID)||this._createDrawingLayer(br.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=Xe(this,qi,"m",tr).call(this,t,Xe(this,Ki,"f").topLeftPoint.x,Xe(this,Ki,"f").topLeftPoint.y,Xe(this,Ki,"f").width,Xe(this,Ki,"f").coordinateBase,this._tipStyleId),Xe(this,qi,"m",er).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",Xe(this,$i,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),Xe(this,Ji,"f")&&clearTimeout(Xe(this,Ji,"f")),Xe(this,Qi,"f")>=0&&ze(this,Ji,setTimeout((()=>{Xe(this,qi,"m",ir).call(this)}),Xe(this,Qi,"f")),"f")}}Ki=new WeakMap,Ji=new WeakMap,Qi=new WeakMap,$i=new WeakMap,qi=new WeakSet,tr=function(t,e,i,r,n,s){const o=new xr(t,e,i,r,s);return o.coordinateBase=n,o},er=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},ir=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},rr=function(){if(!this._tip)return;const t=Xe(this,Ki,"f");this._tip.coordinateBase=t.coordinateBase,this._tip.setTextRect({x:t.topLeftPoint.x,y:t.topLeftPoint.y,width:t.width,height:0}),this._tip.set("width",this._tip.get("width")),this._tip._drawingLayer&&this._tip._drawingLayer.renderAll()};class Ar extends HTMLElement{constructor(){super(),nr.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),ze(this,nr,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const r=document.createElement("slot");r.setAttribute("name","content"),e.append(r);const n=document.createElement("slot");n.setAttribute("name","drawing-layer"),e.append(n);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return Xe(this,nr,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach((t=>t.remove()))}}nr=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",Ar);class Rr extends Or{static get engineResourcePath(){return A(gt.engineResourcePaths).dce}static set defaultUIElementURL(t){Rr._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=Rr._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",Rr.engineResourcePath)}static async createInstance(t){const e=new Rr;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",Rr.engineResourcePath)),await e.setUIElement(t||Rr.defaultUIElementURL),e}static _transformCoordinates(t,e,i,r,n,s,o){const a=s/r,h=o/n;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==Xe(this,gr,"f")){if(ze(this,gr,t,"f"),Xe(this,sr,"m",_r).call(this))ze(this,lr,null,"f"),this._videoContainer=null,this._innerComponent.removeElement("content"),this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block");else if(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none"),!Xe(this,lr,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(He.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),ze(this,lr,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}Xe(this,sr,"m",_r).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading())}}get _singleFrameMode(){return Xe(this,gr,"f")}get disposed(){return Xe(this,pr,"f")}constructor(){super(),sr.add(this),or.set(this,void 0),ar.set(this,void 0),hr.set(this,void 0),this.containerClassName="dce-video-container",lr.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,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,cr.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,ur.set(this,!1),dr.set(this,!1),fr.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{Xe(this,sr,"m",Er).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout((()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&Xe(this,sr,"m",Cr).call(this))}),this._updateLayersTimeout)},this._windowResizeListener=()=>{Rr._onLog&&Rr._onLog("window resize event triggered."),Xe(this,fr,"f").width===document.documentElement.clientWidth&&Xe(this,fr,"f").height===document.documentElement.clientHeight||(Xe(this,fr,"f").width=document.documentElement.clientWidth,Xe(this,fr,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},gr.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!Xe(this,sr,"m",_r).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i},i=(t,e,i,r)=>{t.width==i&&t.height==r||(t.width=i,t.height=r);const n=t.getContext("2d");n.clearRect(0,0,t.width,t.height),n.drawImage(e,0,0)},r=await t(e),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,r,n,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout((()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)}),0)})),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},mr.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,r,n,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(r=o.cropRegion)||void 0===r?void 0:r.top)||0,c=(null===(n=o.cropRegion)||void 0===n?void 0:n.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,r,n,s,o,a,h=[],l)=>{e.forEach((t=>Rr._transformCoordinates(t,i,r,n,s,o,a)));const c=new Di({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},l);for(let t of h)c.addNote(t);t.addDrawingItems([c]),Xe(this,mr,"f").push(c)};let m,p;for(let t of a)switch(t.type){case mt.CRIT_ORIGINAL_IMAGE:break;case mt.CRIT_BARCODE:m=this.getDrawingLayer(br.DBR_LAYER_ID),p=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==e?void 0:e.isBarcodeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,Sr.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case mt.CRIT_TEXT_LINE:m=this.getDrawingLayer(br.DLR_LAYER_ID),p=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,Sr.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case mt.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(br.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.crossVerificationStatus===Tt.CVS_PASSED?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Sr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case mt.CRIT_NORMALIZED_IMAGE:m=this.getDrawingLayer(br.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.crossVerificationStatus===Tt.CVS_PASSED?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Sr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case mt.CRIT_PARSED_RESULT:break;default:throw new Error("Illegal item type.")}}},pr.set(this,!1),this.eventHandler=new ji,this.eventHandler.on("content:updated",(()=>{Xe(this,or,"f")&&clearTimeout(Xe(this,or,"f")),ze(this,or,setTimeout((()=>{if(this.disposed)return;let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(t),this.updateConvertedRegion(t)}),0),"f")})),this.eventHandler.on("videoEl:resized",(()=>{Xe(this,ar,"f")&&clearTimeout(Xe(this,ar,"f")),ze(this,ar,setTimeout((()=>{this.disposed||this._updateVideoContainer()}),0),"f")}))}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Wi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let r=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!r)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=document.createElement("dce-component"),r.appendChild(this._innerComponent),Xe(this,sr,"m",_r).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(He.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),ze(this,lr,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._selRsl&&(this._hideDefaultSelection||Xe(this,sr,"m",_r).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||Xe(this,sr,"m",_r).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||Xe(this,sr,"m",Er).call(this),Xe(this,sr,"m",_r).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),Xe(this,sr,"m",_r).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading()),window.ResizeObserver){this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{var e;Rr._onLog&&Rr._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()})));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}Xe(this,fr,"f").width=document.documentElement.clientWidth,Xe(this,fr,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,r;Xe(this,sr,"m",_r).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),Xe(this,sr,"m",Er).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,ze(this,lr,null,"f"),null===(r=this._videoContainer)||void 0===r||r.remove(),this._videoContainer=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._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let r of e){const e=document.createElement("option");e.value=r.deviceId,e.innerText=r.label,this._selCam.append(e),r.deviceId&&t&&t.deviceId==r.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),r=Math.min(t.width,t.height);e=r<=1080?r+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return Xe(this,lr,"f")}isVideoLoaded(){return!(!Xe(this,lr,"f")||!this.cameraEnhancer)&&this.cameraEnhancer.isOpen()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!Xe(this,lr,"f"))return;if(Xe(this,lr,"f").style.objectFit=t,Xe(this,sr,"m",_r).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Xe(this,sr,"m",Tr).call(this,e,this.getConvertedRegion()),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,r;let n,s,o;if(Xe(this,sr,"m",_r).call(this)?(n=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(r=this._cvsSingleFrameMode)||void 0===r?void 0:r.height,o="contain"):(n=null===(t=Xe(this,lr,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=Xe(this,lr,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!n||!s)throw new Error("Invalid content dimensions.");return{width:n,height:s,objectFit:o}}updateConvertedRegion(t){const e=ki.convert(this.scanRegion,t.width,t.height);ze(this,cr,e,"f"),Xe(this,hr,"f")&&clearTimeout(Xe(this,hr,"f")),ze(this,hr,setTimeout((()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Xe(this,sr,"m",vr).call(this,t,e),Xe(this,sr,"m",Tr).call(this,t,e)}),0),"f")}getConvertedRegion(){return Xe(this,cr,"f")}setScanRegion(t){if(null!=t&&!w(t)&&!I(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=Xe(this,lr,"f").videoWidth,i=Xe(this,lr,"f").videoHeight,r=this.getVideoFit(),{width:n,height:s}=this._innerComponent.getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===r&&(n/s1){const t=Xe(this,lr,"f").videoWidth,e=Xe(this,lr,"f").videoHeight,{width:r,height:n}=this._innerComponent.getBoundingClientRect(),s=t/e;if(r/nt.remove())),Xe(this,mr,"f").length=0}dispose(){this._unbindUI(),ze(this,pr,!0,"f")}}function Dr(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Lr(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}or=new WeakMap,ar=new WeakMap,hr=new WeakMap,lr=new WeakMap,cr=new WeakMap,ur=new WeakMap,dr=new WeakMap,fr=new WeakMap,gr=new WeakMap,mr=new WeakMap,pr=new WeakMap,sr=new WeakSet,_r=function(){return"disabled"!==this._singleFrameMode},vr=function(t,e){!e||0===e.x&&0===e.y&&e.width===t.width&&e.height===t.height?this.clearScanRegionMask():this.setScanRegionMask(e.x,e.y,e.width,e.height)},yr=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},wr=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},Cr=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},Er=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Tr=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:r,objectFit:n}=t;e||(e={x:0,y:0,width:i,height:r});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/r;let l,c,u,d,f=1;if("contain"===n)a66||"Safari"===Nr.browser&&Nr.version>13||"OPR"===Nr.browser&&Nr.version>43||"Edge"===Nr.browser&&Nr.version,"function"==typeof SuppressedError&&SuppressedError;class Vr{static multiply(t,e){const i=[];for(let r=0;r<3;r++){const n=e.slice(3*r,3*r+3);for(let e=0;e<3;e++){const r=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return Vr.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),r=Math.sin(e);return Vr.multiply(t,[i,-r,0,r,i,0,0,0,1])}static scale(t,e,i){return Vr.multiply(t,[e,0,0,0,i,0,0,0,1])}}var Gr,Wr,Yr,Hr,Xr,zr,Zr,qr,Kr,Jr,Qr,$r,tn,en,rn,nn,sn,on,an,hn,ln,cn,un,dn,fn,gn,mn,pn,_n,vn,yn,wn,Cn,En,Tn,Sn,bn,In,xn,On,An,Rn,Dn,Ln,Mn,Fn,Pn,kn,Bn,Nn;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(Gr||(Gr={}));class jn{static get version(){return"1.1.3"}static get webGLSupported(){return void 0===jn._webGLSupported&&(jn._webGLSupported=!!document.createElement("canvas").getContext("webgl")),jn._webGLSupported}get disposed(){return jr(this,Zr,"f")}constructor(){Wr.set(this,Gr.RGBA),Yr.set(this,null),Hr.set(this,null),Xr.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,zr.set(this,null),Zr.set(this,!1)}drawImage(t,e,i,r,n,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!r)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if((null==s?void 0:s.bUseWebGL)&&!jn.webGLSupported)throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;jn._onLog&&(o=Date.now(),jn._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;n&&(n.sx&&(a=Math.round(n.sx)),n.sy&&(h=Math.round(n.sy)),n.sWidth&&(l=Math.round(n.sWidth)),n.sHeight&&(c=Math.round(n.sHeight)),n.dx&&(u=Math.round(n.dx)),n.dy&&(d=Math.round(n.dy)),n.dWidth&&(f=Math.round(n.dWidth)),n.dHeight&&(g=Math.round(n.dHeight)));let m,p=Gr.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!jn.webGLSupported||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){jn._onLog&&jn._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=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},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},n=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},s="\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\n\nuniform mat3 u_matrix;\nuniform mat3 u_textureMatrix;\n\nvarying vec2 v_texCoord;\nvoid main(void) {\ngl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\nv_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n}";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_image;\nuniform float uColorFactor;\n\nvoid main() {\nvec4 sample = texture2D(u_image, v_texCoord);\nfloat grey = 0.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\ngl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n}`,h=r(t,[n(t,t.VERTEX_SHADER,s),n(t,t.FRAGMENT_SHADER,a)]);Ur(this,Hr,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),Ur(this,Xr,e(t),"f"),Ur(this,Yr,i(t),"f"),Ur(this,Wr,p,"f")}const n=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(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)},v=(t,e,s,o)=>{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),n(t,s.positions,e.attribLocations.vertexPosition),n(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[Gr.GREY,Gr.GREY32].includes(p)?1:0);let m,_,v=Vr.translate(Vr.identity(),-1,-1);v=Vr.scale(v,2,2),v=Vr.scale(v,1/t.canvas.width,1/t.canvas.height),m=Vr.translate(v,u,d),m=Vr.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=Vr.translate(Vr.identity(),a/i,h/r),_=Vr.scale(_,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,jr(this,Yr,"f"),e),v(t,jr(this,Hr,"f"),jr(this,Xr,"f"),jr(this,Yr,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){jn._onLog&&jn._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return jn._onLog&&jn._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===Gr.GREY?Gr.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return jn._onLog&&jn._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,r,n,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let r,n=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(n=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),r=new Uint8Array(i.buffer,0,4*o*a)):(r=new Uint8Array(4*o*a),e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,r))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(n,s,o,a),r=new Uint8Array(e.data.buffer),null==i||i.set(r)}return r}transformPixelFormat(t,e,i,r){let n,s;if(jn._onLog&&(n=Date.now(),jn._onLog("transformPixelFormat(), START: "+n)),e===i)return jn._onLog&&jn._onLog("transformPixelFormat() end. Costs: "+(Date.now()-n)),r?new Uint8Array(t):t;const o=[Gr.RGBA,Gr.RBGA,Gr.GRBA,Gr.GBRA,Gr.BRGA,Gr.BGRA];if(o.includes(e))if(i===Gr.GREY){s=new Uint8Array(t.length/4);for(let e=0;eh||e.sy+e.sHeight>l)throw new Error("Invalid position.");null===(r=jn._onLog)||void 0===r||r.call(jn,"getImageData(), START: "+(c=Date.now()));const d=Math.round(e.sx),f=Math.round(e.sy),g=Math.round(e.sWidth),m=Math.round(e.sHeight),p=Math.round(e.dWidth),_=Math.round(e.dHeight);let v,y=(null==i?void 0:i.pixelFormat)||Gr.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(Gr.GREY===y&&w.length{this.disposed||r.includes(n)&&n.apply(i.target,s)}),0);else try{o=n.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){Lr(this,Kr,!0,"f")}}qr=new WeakMap,Kr=new WeakMap;const Vn=(t,e,i,r)=>{if(!i)return t;let n=e+Math.round((t-e)/i)*i;return r&&(n=Math.min(n,r)),n};class Gn{static get version(){return"2.0.18"}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 findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find((t=>e.includes(t.label.toLowerCase())));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],r=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],n=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!n.length)return null;const s=n.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const o=n.find((t=>{const e=t.label.toLowerCase();return r.some((t=>e.includes(t)))}));return o?o.deviceId:n[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(Nr.OS))return Gn.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(Nr.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise((async(r,n)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),r(t)},l=t=>{s&&clearTimeout(s),o(),n(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise((t=>{g=t})),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise((t=>{setTimeout(t,1e3)})),!a){i&&(s=setTimeout((()=>{o(),n(new Error("Failed to play video. Timeout."))}),i)),await m;try{await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a)try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}}))}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let r;try{r=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==r||r.getTracks().forEach((t=>{t.stop()}))}return{ok:!0}}get state(){if(!Dr(this,un,"f"))return"closed";if("pending"===Dr(this,un,"f"))return"opening";if("fulfilled"===Dr(this,un,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Gn.isStorageAvailable("localStorage")?Lr(this,an,!0,"f"):(Lr(this,an,!1,"f"),console.warn("Local storage is unavailable")):Lr(this,an,!1,"f")}get ifSaveLastUsedCamera(){return Dr(this,an,"f")}get isVideoPlaying(){return!(!Dr(this,$r,"f")||Dr(this,$r,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,r;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=Dr(this,_n,"f"))||void 0===e||e.removeEventListener("click",Dr(this,pn,"f")),null===(i=Dr(this,_n,"f"))||void 0===i||i.removeEventListener("touchend",Dr(this,pn,"f")),null===(r=Dr(this,_n,"f"))||void 0===r||r.removeEventListener("touchmove",Dr(this,mn,"f")),Lr(this,_n,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(Nr.OS)?(t.addEventListener("touchend",Dr(this,pn,"f")),t.addEventListener("touchmove",Dr(this,mn,"f"))):t.addEventListener("click",Dr(this,pn,"f")))}get tapFocusEventBoundEl(){return Dr(this,_n,"f")}get disposed(){return Dr(this,In,"f")}constructor(t){var e,i;Qr.add(this),$r.set(this,null),tn.set(this,void 0),en.set(this,(()=>{"opened"===this.state&&Dr(this,Cn,"f").fire("resumed",null,{target:this,async:!1})})),rn.set(this,(()=>{Dr(this,Cn,"f").fire("paused",null,{target:this,async:!1})})),nn.set(this,void 0),sn.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],on.set(this,void 0),an.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,hn.set(this,void 0),ln.set(this,!0),cn.set(this,void 0),un.set(this,void 0),dn.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},fn.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,r;const n=window.getComputedStyle(Dr(this,$r,"f")).objectFit,s=this.getResolution(),o=Dr(this,$r,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=Dr(this,$r,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===n)d>u?(f=l/s.width,i=(t-a)/f,r=(e-h-(c-l/d)/2)/f):(f=c/s.height,r=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==n)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,r=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,r=(e-h+(l/d-c)/2)/f)}return{x:i,y:r}},gn.set(this,!1),mn.set(this,(()=>{Lr(this,gn,!0,"f")})),pn.set(this,(async t=>{var e;if(Dr(this,gn,"f"))return void Lr(this,gn,!1,"f");if(!Dr(this,fn,"f"))return;if(!this.isVideoPlaying)return;if(!Dr(this,tn,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,r;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,r=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,r=t.changedTouches[0].clientY}const n=this.getResolution(),s=2*Math.round(Math.min(n.width,n.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,r)}catch(t){}if(o.x<0||o.x>n.width||o.y<0||o.y>n.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;Gn._onLog&&(c=Date.now());try{await Dr(this,Qr,"m",kn).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Gn._onLog)throw Gn._onLog(t),t}Gn._onLog&&Gn._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout((()=>{var t;Gn._onLog&&Gn._onLog("Back to continuous focus."),null===(t=Dr(this,tn,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime),Dr(this,Cn,"f").fire("tapfocus",null,{target:this,async:!1})})),_n.set(this,null),vn.set(this,1),yn.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!Dr(this,$r,"f"))return;const t=Dr(this,vn,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)Dr(this,$r,"f").style.transform="";else{const e=window.getComputedStyle(Dr(this,$r,"f")).objectFit,i=Dr(this,$r,"f").videoWidth,r=Dr(this,$r,"f").videoHeight,{width:n,height:s}=Dr(this,$r,"f").getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=n/s,a=i/r;let h=1;"contain"===e?h=oo?s/(i/t):n/(r/t));const l=h*(1-1/t)*(i/2-Dr(this,yn,"f").x),c=h*(1-1/t)*(r/2-Dr(this,yn,"f").y);Dr(this,$r,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},wn.set(this,(function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===Gr.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(Gn._onLog&&Gn._onLog("document visible. video paused: "+(null===(t=Dr(this,$r,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){Gn._onLog&&Gn._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){Gn._onLog&&Gn._onLog("document visible. 1st resume video failed, try open instead.")}e||await Dr(this,Qr,"m",Dn).call(this)}if(await new Promise((t=>setTimeout(t,300))),!this.isVideoPlaying){Gn._onLog&&Gn._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){Gn._onLog&&Gn._onLog("document visible. 2rd resume video failed, try open instead.")}e||await Dr(this,Qr,"m",Dn).call(this)}}}else"hidden"===document.visibilityState&&(Gn._onLog&&Gn._onLog("document hidden. video paused: "+(null===(e=Dr(this,$r,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())})),In.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout((()=>{Gn.onWarning&&Gn.onWarning("The browser is too old or the page is loaded from an insecure origin.")}),0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),Lr(this,Cn,new Un,"f"),this.imageDataGetter=new jn,document.addEventListener("visibilitychange",Dr(this,bn,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",Dr(this,en,"f")),t.addEventListener("pause",Dr(this,rn,"f")),Lr(this,$r,t,"f")}getVideoEl(){return Dr(this,$r,"f")}releaseVideoEl(){var t,e;null===(t=Dr(this,$r,"f"))||void 0===t||t.removeEventListener("play",Dr(this,en,"f")),null===(e=Dr(this,$r,"f"))||void 0===e||e.removeEventListener("pause",Dr(this,rn,"f")),Lr(this,$r,null,"f")}isVideoLoaded(){return!!Dr(this,$r,"f")&&4==Dr(this,$r,"f").readyState}async open(){if(Dr(this,cn,"f")&&!Dr(this,ln,"f")){if("pending"===Dr(this,un,"f"))return Dr(this,cn,"f");if("fulfilled"===Dr(this,un,"f"))return}Dr(this,Cn,"f").fire("before:open",null,{target:this}),await Dr(this,Qr,"m",Dn).call(this),Dr(this,Cn,"f").fire("played",null,{target:this,async:!1}),Dr(this,Cn,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;Dr(this,Cn,"f").fire("before:close",null,{target:this});const t=Dr(this,cn,"f");if(Dr(this,Qr,"m",Mn).call(this),t&&"pending"===Dr(this,un,"f")){try{await t}catch(t){}if(!1===Dr(this,ln,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}Lr(this,cn,null,"f"),Lr(this,un,null,"f"),Dr(this,Cn,"f").fire("closed",null,{target:this,async:!1})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");Dr(this,$r,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await Dr(this,$r,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof Dr(this,nn,"f").video&&(Dr(this,nn,"f").video={}),delete Dr(this,nn,"f").video.facingMode,Dr(this,nn,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&Dr(this,ln,"f"))){Dr(this,Cn,"f").fire("before:camera:change",[],{target:this,async:!1}),await Dr(this,Qr,"m",Ln).call(this);try{this.resetSoftwareScale()}catch(t){}return Dr(this,sn,"f")}}async switchToFrontCamera(t){if("object"!=typeof Dr(this,nn,"f").video&&(Dr(this,nn,"f").video={}),(null==t?void 0:t.resolution)&&(Dr(this,nn,"f").video.width={ideal:t.resolution.width},Dr(this,nn,"f").video.height={ideal:t.resolution.height}),delete Dr(this,nn,"f").video.deviceId,Dr(this,nn,"f").video.facingMode={exact:"user"},Lr(this,on,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&Dr(this,ln,"f"))){Dr(this,Cn,"f").fire("before:camera:change",[],{target:this,async:!1}),Dr(this,Qr,"m",Ln).call(this);try{this.resetSoftwareScale()}catch(t){}return Dr(this,sn,"f")}}getCamera(){var t;if(Dr(this,sn,"f"))return Dr(this,sn,"f");{let e=(null===(t=Dr(this,nn,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}else r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));const n=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind));return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof Dr(this,nn,"f").video&&(Dr(this,nn,"f").video={}),i?(Dr(this,nn,"f").video.width={exact:t},Dr(this,nn,"f").video.height={exact:e}):(Dr(this,nn,"f").video.width={ideal:t},Dr(this,nn,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&Dr(this,ln,"f"))return null;Dr(this,Cn,"f").fire("before:resolution:change",[],{target:this,async:!1}),await Dr(this,Qr,"m",Ln).call(this);try{this.resetSoftwareScale()}catch(t){}const r=this.getResolution();return{width:r.width,height:r.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&Dr(this,$r,"f"))return{width:Dr(this,$r,"f").videoWidth,height:Dr(this,$r,"f").videoHeight};if(Dr(this,tn,"f")){const t=Dr(this,tn,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:Dr(this,$r,"f").videoWidth,height:Dr(this,$r,"f").videoHeight};{const t={width:0,height:0};let e=Dr(this,nn,"f").video.width||0,i=Dr(this,nn,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,r,n,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=Dr(this,Tn,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){d=null===(u=Dr(this,sn,"f"))||void 0===u?void 0:u.deviceId;let e=Dr(this,Tn,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],Dr(this,Tn,"f").set(d,e),Lr(this,dn,!0,"f");try{for(let t of this.detectedResolutions){await Dr(this,tn,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),Dr(this,Qr,"m",On).call(this);const i=Dr(this,tn,"f").getSettings(),r={width:i.width,height:i.height};f(d,r)||e.push({width:r.width,height:r.height})}}catch(t){throw Dr(this,Qr,"m",Mn).call(this),Lr(this,dn,!1,"f"),t}try{await Dr(this,Qr,"m",Dn).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{Lr(this,dn,!1,"f")}return e}{const e=async(t,e,i)=>{const r={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let n=null;try{n=await 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};let i=(null===(s=null===(n=null===(r=Dr(this,nn,"f"))||void 0===r?void 0:r.video)||void 0===n?void 0:n.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=Dr(this,nn,"f"))||void 0===o?void 0:o.video)||void 0===a?void 0:a.deviceId)||void 0===h?void 0:h.ideal)||(null===(c=null===(l=Dr(this,nn,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=Dr(this,Tn,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],Dr(this,Tn,"f").set(i,u);for(let t of this.detectedResolutions){const r=await e(i,t.width,t.height);r&&!f(i,r)&&u.push({width:r.width,height:r.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");Lr(this,nn,JSON.parse(JSON.stringify(t)),"f"),Lr(this,on,null,"f"),e&&Dr(this,Qr,"m",Ln).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(Dr(this,nn,"f")))}resetMediaStreamConstraints(){Lr(this,nn,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!Dr(this,tn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Dr(this,tn,"f").getCapabilities?Dr(this,tn,"f").getCapabilities():{}}getCameraSettings(){if(!Dr(this,tn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Dr(this,tn,"f").getSettings()}async turnOnTorch(){if(!Dr(this,tn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Dr(this,tn,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!Dr(this,tn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Dr(this,tn,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Dr(this,tn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Vn(t,r.min,r.step,r.max)),await Dr(this,tn,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Dr(this,tn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Vn(t,r.min,r.step,r.max)),await Dr(this,tn,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Dr(this,tn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!r)throw Error("Not supported.");e&&(tr.max&&(t=r.max));const n=this.getResolution();return await Dr(this,tn,"f").applyConstraints({width:{ideal:Math.max(n.width,n.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!Dr(this,tn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),r=null==i?void 0:i.focusMode,n=null==i?void 0:i.focusDistance;if(!r)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!r.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!n)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(in.max&&(i=n.max),i=Vn(i,n.min,n.step,n.max)),this._focusParameters.focusArea=null,await Dr(this,tn,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,r=t.area.height;if(!i||!r){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),r||(r=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:r},await Dr(this,Qr,"m",kn).call(this,e,i,r)}}}else this._focusParameters.focusArea=null,await Dr(this,tn,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async enableTapToFocus(){Lr(this,fn,!0,"f")}disableTapToFocus(){Lr(this,fn,!1,"f")}isTapToFocusEnabled(){return Dr(this,fn,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"!==this.state)throw new Error("Video is not playing.");t.centerPoint?Dr(this,Qr,"m",Bn).call(this,t.centerPoint):this.resetScaleCenter();try{if(Dr(this,Qr,"m",Nn).call(this,Dr(this,yn,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*Dr(this,vn,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!Dr(this,tn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Vn(t,r.min,r.step,r.max)),await Dr(this,tn,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&Dr(this,Qr,"m",Bn).call(this,e),Lr(this,vn,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return Dr(this,vn,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();Lr(this,yn,{x:t.width/2,y:t.height/2},"f")}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(Dr(this,dn,"f"))return null;const e=Date.now();Gn._onLog&&Gn._onLog("getFrameData() START: "+e);const i=Dr(this,$r,"f").videoWidth,r=Dr(this,$r,"f").videoHeight;let n={sx:0,sy:0,sWidth:i,sHeight:r,dWidth:i,dHeight:r};(null==t?void 0:t.position)&&(n=JSON.parse(JSON.stringify(t.position)));let s=Gr.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=Dr(this,vn,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=Dr(this,yn,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,n=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))n=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.scaleCenter.y)/100*r}if(isNaN(e)||isNaN(n))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(n)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==r)return null;1!==o&&(n.sWidth=Math.round(n.sWidth/o),n.sHeight=Math.round(n.sHeight/o),n.sx=Math.round((1-1/o)*a.x+n.sx/o),n.sy=Math.round((1-1/o)*a.y+n.sy/o));const l=this.imageDataGetter.getImageData(Dr(this,$r,"f"),n,{pixelFormat:s,bufferContainer:h});if(!l)return null;const c=Date.now();return Gn._onLog&&Gn._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:Dr(this,wn,"f")}}on(t,e){if(!Dr(this,En,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);Dr(this,Cn,"f").on(t,e)}off(t,e){Dr(this,Cn,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),Dr(this,Cn,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",Dr(this,bn,"f")),Lr(this,In,!0,"f")}}var Wn,Yn,Hn,Xn,zn,Zn,qn,Kn,Jn,Qn,$n,ts,es,is,rs,ns,ss,os,as,hs,ls,cs,us,ds,fs,gs,ms,ps,_s,vs,ys,ws,Cs,Es,Ts;$r=new WeakMap,tn=new WeakMap,en=new WeakMap,rn=new WeakMap,nn=new WeakMap,sn=new WeakMap,on=new WeakMap,an=new WeakMap,hn=new WeakMap,ln=new WeakMap,cn=new WeakMap,un=new WeakMap,dn=new WeakMap,fn=new WeakMap,gn=new WeakMap,mn=new WeakMap,pn=new WeakMap,_n=new WeakMap,vn=new WeakMap,yn=new WeakMap,wn=new WeakMap,Cn=new WeakMap,En=new WeakMap,Tn=new WeakMap,Sn=new WeakMap,bn=new WeakMap,In=new WeakMap,Qr=new WeakSet,xn=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(Dr(this,on,"f"))delete t.video.facingMode,t.video.deviceId={exact:Dr(this,on,"f")};else if(this.ifSaveLastUsedCamera&&Gn.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(Nr.OS)?(await this._getCameras(!1),Dr(this,Qr,"m",On).call(this),e=Gn.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(Nr.OS)||(await this._getCameras(!1),Dr(this,Qr,"m",On).call(this),e=Gn.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const r=await e(i);r&&(delete t.video.facingMode,t.video.deviceId={exact:r})}return t},On=function(){if(Dr(this,ln,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},An=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;try{Gn._onLog&&Gn._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const n=async t=>{for(let n of e){n&&(await new Promise((t=>setTimeout(t,n))),Dr(this,Qr,"m",On).call(this));try{Gn._onLog&&Gn._onLog("ask "+JSON.stringify(t)),r=await navigator.mediaDevices.getUserMedia(t),Dr(this,Qr,"m",On).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Gn._onLog&&Gn._onLog(t.message||t)}}};if(await n(t),r||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await n(t)),!r&&t.video.facingMode&&(delete t.video.facingMode,await n(t)),r||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await n(t))),!r)throw i;return r}catch(t){throw null==r||r.getTracks().forEach((t=>{t.stop()})),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},Rn=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach((t=>{t.stop()})),this._mediaStream=null),Lr(this,tn,null,"f")},Dn=async function(){Lr(this,ln,!1,"f");const t=Lr(this,hn,Symbol(),"f");if(Dr(this,cn,"f")&&"pending"===Dr(this,un,"f")){try{await Dr(this,cn,"f")}catch(t){}Dr(this,Qr,"m",On).call(this)}if(t!==Dr(this,hn,"f"))return;const e=Lr(this,cn,(async()=>{Lr(this,un,"pending","f");try{if(this.videoSrc){if(!Dr(this,$r,"f"))throw new Error("'videoEl' should be set.");await Gn.playVideo(Dr(this,$r,"f"),this.videoSrc,this.cameraOpenTimeout),Dr(this,Qr,"m",On).call(this)}else{let t=await Dr(this,Qr,"m",xn).call(this);Dr(this,Qr,"m",Rn).call(this);let e=await Dr(this,Qr,"m",An).call(this,t);await this._getCameras(!1),Dr(this,Qr,"m",On).call(this);const i=()=>{const t=e.getVideoTracks();let i,r;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,r=e;break}}return r},r=Dr(this,nn,"f");if("object"==typeof r.video){let n=r.video.facingMode;if(n instanceof Array&&n.length&&(n=n[0]),"object"==typeof n&&(n=n.exact||n.ideal),!(Dr(this,on,"f")||this.ifSaveLastUsedCamera&&Gn.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||r.video.deviceId)){const r=i(),s=Gn.findBestCamera(this._arrCameras,n,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==r?void 0:r.deviceId)&&(e.getTracks().forEach((t=>{t.stop()})),t.video.deviceId={exact:s},e=await Dr(this,Qr,"m",An).call(this,t),Dr(this,Qr,"m",On).call(this))}}const n=i();(null==n?void 0:n.deviceId)&&(Lr(this,on,n&&n.deviceId,"f"),this.ifSaveLastUsedCamera&&Gn.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",Dr(this,on,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),Dr(this,$r,"f")&&(await Gn.playVideo(Dr(this,$r,"f"),e,this.cameraOpenTimeout),Dr(this,Qr,"m",On).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&Lr(this,tn,s[0],"f"),Lr(this,sn,n,"f")}}catch(t){throw Dr(this,Qr,"m",Mn).call(this),Lr(this,un,null,"f"),t}Lr(this,un,"fulfilled","f")})(),"f");return e},Ln=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=Dr(this,sn,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await Dr(this,Qr,"m",Dn).call(this);const r=this.getResolution();e&&e!==Dr(this,sn,"f").deviceId&&Dr(this,Cn,"f").fire("camera:changed",[Dr(this,sn,"f").deviceId,e],{target:this,async:!1}),i.width==r.width&&i.height==r.height||Dr(this,Cn,"f").fire("resolution:changed",[{width:r.width,height:r.height},{width:i.width,height:i.height}],{target:this,async:!1}),Dr(this,Cn,"f").fire("played",null,{target:this,async:!1})},Mn=function(){Dr(this,Qr,"m",Rn).call(this),Lr(this,sn,null,"f"),Dr(this,$r,"f")&&(Dr(this,$r,"f").srcObject=null,this.videoSrc&&(Dr(this,$r,"f").pause(),Dr(this,$r,"f").currentTime=0)),Lr(this,ln,!0,"f");try{this.resetSoftwareScale()}catch(t){}},Fn=async function t(e,i){const r=t=>{if(!Dr(this,tn,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){Dr(this,tn,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let n;i=Vn(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await Dr(this,tn,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),r(e),n=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise((t=>{setTimeout(t,n)})),r(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h),a>l.width&&(a=l.width),h>l.height&&(h=l.height),s<0?s=0:s+a>l.width&&(s=l.width-a),o<0?o=0:o+h>l.height&&(o=l.height-h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(Dr(this,$r,"f"),{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:Gr.RGBA,bufferContainer:d}))return Dr(this,Qr,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await Dr(this,Qr,"m",t).call(this,e,o,a,n,s,c,u)}else{let h=await Dr(this,Qr,"m",Fn).call(this,e,c);if(a>h)return await Dr(this,Qr,"m",t).call(this,e,o,a,n,s,c,h);if(a==h)return await Dr(this,Qr,"m",t).call(this,e,o,a,c,h);let u=await Dr(this,Qr,"m",Fn).call(this,e,l);if(u>a&&ao.width||h<0||h>o.height)throw new Error("Invalid 'centerPoint'.");let l=0;if(e.endsWith("px"))l=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");l=parseFloat(e)/100*o.width}if(isNaN(l)||l<0)throw new Error("Invalid 'width'.");let c=0;if(i.endsWith("px"))c=parseFloat(i);else{if(!i.endsWith("%"))throw new Error("Invalid 'height'.");c=parseFloat(i)/100*o.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==Dr(this,vn,"f")){const t=Dr(this,vn,"f"),e=Dr(this,yn,"f");l/=t,c/=t,a=(1-1/t)*e.x+a/t,h=(1-1/t)*e.y+h/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const u={focusL:a,focusT:h,focusW:l,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let r=Vn(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=Vn(Math.sqrt((e||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Vn(Math.sqrt(r*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await Dr(this,Qr,"m",Fn).call(this,t,s),a=await Dr(this,Qr,"m",Fn).call(this,t,n),h=await Dr(this,Qr,"m",Fn).call(this,t,r);if(a>h&&ho&&a>o){let e=await Dr(this,Qr,"m",Fn).call(this,t,i);const n=await Dr(this,Qr,"m",Pn).call(this,t,r,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,n}if(a==h&&hh){const e=await Dr(this,Qr,"m",Pn).call(this,t,r,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,r,n)},Bn=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,r=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))r=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(r))throw new Error("Invalid scale center.");Lr(this,yn,{x:i,y:r},"f")},Nn=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},Gn.browserInfo=Nr,Gn.onWarning=null===(Jr=null===window||void 0===window?void 0:window.console)||void 0===Jr?void 0:Jr.warn;class Ss{constructor(t){Wn.add(this),Yn.set(this,void 0),Hn.set(this,0),Xn.set(this,void 0),zn.set(this,0),Zn.set(this,!1),ze(this,Yn,t,"f")}startCharging(){Xe(this,Zn,"f")||(Ss._onLog&&Ss._onLog("start charging."),Xe(this,Wn,"m",Kn).call(this),ze(this,Zn,!0,"f"))}stopCharging(){Xe(this,Xn,"f")&&clearTimeout(Xe(this,Xn,"f")),Xe(this,Zn,"f")&&(Ss._onLog&&Ss._onLog("stop charging."),ze(this,Hn,Date.now()-Xe(this,zn,"f"),"f"),ze(this,Zn,!1,"f"))}}Yn=new WeakMap,Hn=new WeakMap,Xn=new WeakMap,zn=new WeakMap,Zn=new WeakMap,Wn=new WeakSet,qn=function(){gt.cfd(1),Ss._onLog&&Ss._onLog("charge 1.")},Kn=function t(){0==Xe(this,Hn,"f")&&Xe(this,Wn,"m",qn).call(this),ze(this,zn,Date.now(),"f"),Xe(this,Xn,"f")&&clearTimeout(Xe(this,Xn,"f")),ze(this,Xn,setTimeout((()=>{ze(this,Hn,0,"f"),Xe(this,Wn,"m",t).call(this)}),Xe(this,Yn,"f")-Xe(this,Hn,"f")),"f")};class bs{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-Xe(this,Jn,"f",ts)<100)){if(ze(this,Jn,e,"f",ts),Xe(this,Jn,"f",Qn).size&&(t=Xe(this,Jn,"f",Qn).values().next().value,this.beepSoundSource==t.src?(Xe(this,Jn,"f",Qn).delete(t),t.play()):t=null),!t)if(Xe(this,Jn,"f",$n).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout((()=>{Xe(this,Jn,"f",$n).delete(t)}),2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",(()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,Xe(this,Jn,"f",$n).delete(t),Xe(this,Jn,"f",Qn).add(t)}))}else Xe(this,Jn,"f",es)||(ze(this,Jn,!0,"f",es),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&Xe(this,Jn,"f",$n).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(bs.vibrateDuration)}}}Jn=bs,Qn={value:new Set},$n={value:new Set},ts={value:0},es={value:!1},bs.allowBeep=!0,bs.beepSoundSource="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",bs.allowVibrate=!0,bs.vibrateDuration=300;const Is=new Map([[Gr.GREY,h.IPF_GRAYSCALED],[Gr.RGBA,h.IPF_ABGR_8888]]),xs="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};class Os extends z{static set _onLog(t){ze(Os,rs,t,"f",ns),Gn._onLog=t,Ss._onLog=t}static get _onLog(){return Xe(Os,rs,"f",ns)}static async detectEnvironment(){return await(async()=>({wasm:Ze,worker:qe,getUserMedia:Ke,camera:await Je(),browser:He.browser,version:He.version,OS:He.OS}))()}static async testCameraAccess(){const t=await Gn.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(t){var e,i;if(t&&!(t instanceof Rr))throw new TypeError("Invalid view.");if(null===(e=ct.license)||void 0===e?void 0:e.LicenseManager){if(!(null===(i=ct.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await gt.loadWasm(["license"]),await ct.license.dynamsoft()}const r=new Os(t);return Os.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{Os.onWarning&&Os.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{Os.onWarning&&Os.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),r}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");ze(this,as,t,"f")}get singleFrameMode(){return Xe(this,as,"f")}get _isFetchingStarted(){return Xe(this,fs,"f")}get disposed(){return Xe(this,vs,"f")}constructor(t){if(super(),is.add(this),ss.set(this,"closed"),os.set(this,void 0),this.isTorchOn=void 0,as.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},hs.set(this,((t,e,i,r)=>{const n=Date.now(),s={sx:r.x,sy:r.y,sWidth:r.width,sHeight:r.height,dWidth:r.width,dHeight:r.height},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const a=this.cameraManager.imageDataGetter.getImageData(t,s,{pixelFormat:this.getPixelFormat()===h.IPF_GRAYSCALED?Gr.GREY:Gr.RGBA});let l=null;if(a){const t=Date.now();let o;o=a.pixelFormat===Gr.GREY?a.width:4*a.width;let h=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(h=!1),l={bytes:a.data,width:a.width,height:a.height,stride:o,format:Is.get(a.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:wt.ITT_FILE_IMAGE,isCropped:h,cropRegion:{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:a.width,currentHeight:a.height,timeSpent:t-n,timeStamp:t},toCanvas:Xe(this,ls,"f"),isDCEFrame:!0}}return l})),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():ki.convert(Xe(this,us,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height});const i=Xe(this,hs,"f").call(this,t,t.width,t.height,e);Xe(this,os,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},ls.set(this,(function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.format===h.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(He.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",(()=>{Xe(this,_s,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("camera:changed",(()=>{this.clearBuffer()})),this._on("before:resolution:change",(()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("resolution:changed",(()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})})),this._on("paused",(()=>{Xe(this,_s,"f").stopCharging();const t=this.cameraView;t&&t.disposed})),this._on("resumed",(()=>{const t=this.cameraView;t&&t.disposed})),this._on("tapfocus",(()=>{Xe(this,ms,"f").tapToFocus&&Xe(this,_s,"f").startCharging()})),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,r,n,s;if(Xe(this,is,"m",ys).call(this)||!this.isOpen()||this.isPaused())return;const o=t.intermediateResultUnits;Os._onLog&&(Os._onLog("intermediateResultUnits:"),Os._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===St.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===St.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(Os._onLog&&(Os._onLog("hasLocalizedBarcodes:"),Os._onLog(h)),Xe(this,ms,"f").autoZoom||Xe(this,ms,"f").enhancedFocus)if(a)Xe(this,ps,"f").autoZoomInFrameArray.length=0,Xe(this,ps,"f").autoZoomOutFrameCount=0,Xe(this,ps,"f").frameArrayInIdealZoom.length=0,Xe(this,ps,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),Xe(this,ms,"f").autoZoom&&Xe(this,_s,"f").startCharging()},a=async t=>{await this.setFocus(t),Xe(this,ms,"f").enhancedFocus&&Xe(this,_s,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(r=h.cropRegion)||void 0===r?void 0:r.top)||0,u=(null===(n=h.cropRegion)||void 0===n?void 0:n.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,r,n;{const t=this.video.videoWidth*(1-Xe(this,ps,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+Xe(this,ps,"f").autoZoomDetectionArea)/2,i=e,r=t,s=this.video.videoHeight*(1-Xe(this,ps,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+Xe(this,ps,"f").autoZoomDetectionArea)/2;n=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:r,y:a}]}Os._onLog&&(Os._onLog("detectionArea:"),Os._onLog(n));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let r=!1;const n=t.length;if(n<=2)return!1;for(let s=0;s0!=Vi(a.y-i)>0&&Vi(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(r=!r)}return r}(e,t.x,t.y)},r=(t,e)=>!!(Gi([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||Gi([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||Gi([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||Gi([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(r([e[0].x,e[0].y,e[1].x,e[1].y],t)||r([e[1].x,e[1].y,e[2].x,e[2].y],t)||r([e[2].x,e[2].y,e[3].x,e[3].y],t)||r([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of o)if(e.unitType===St.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach((t=>{Rr._transformCoordinates(t,l,c,u,d,f,g)})),t(n,e)&&s.push(i)}if(Os._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=Sr.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===St.IRUT_LOCALIZED_BARCODES)for(let r of i.localizedBarcodes){if(!r)continue;const i=r.location.points,n=new Ii({points:i},e);t.addDrawingItems([n])}}}if(Os._onLog&&(Os._onLog("intersectedResults:"),Os._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter((t=>t.possibleFormats==xs.BF_QR_CODE||t.possibleFormats==xs.BF_DATAMATRIX));if(t.length||(t=s.filter((t=>t.possibleFormats==xs.BF_ONED)),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,r=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(r-g/2)*(r-g/2)};a=t[0];let i=e(a);if(1!=t.length)for(let r=1;r1.1*a.confidence||t[r].confidence>.9*a.confidence&&ni&&s>i&&o>i&&h>i&&m.result.moduleSize{})),Xe(this,ps,"f").autoZoomInFrameArray.filter((t=>!0===t)).length>=Xe(this,ps,"f").autoZoomInFrameLimit[1]){Xe(this,ps,"f").autoZoomInFrameArray.length=0;const i=[(.5-r)/(.5-n),(.5-r)/(.5-s),(.5-r)/(.5-o),(.5-r)/(.5-h)].filter((t=>t>0)),a=Math.min(...i,Xe(this,ps,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/Xe(this,ps,"f").autoZoomInMaxTimes),Xe(this,ps,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max(Xe(this,ps,"f").minValue,u),u=Math.min(Xe(this,ps,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(Xe(this,ps,"f").autoZoomInFrameArray.length=0,Xe(this,ps,"f").frameArrayInIdealZoom.push(!0),Xe(this,ps,"f").frameArrayInIdealZoom.splice(0,Xe(this,ps,"f").frameArrayInIdealZoom.length-Xe(this,ps,"f").frameLimitInIdealZoom[0]),Xe(this,ps,"f").frameArrayInIdealZoom.filter((t=>!0===t)).length>=Xe(this,ps,"f").frameLimitInIdealZoom[1]&&(Xe(this,ps,"f").frameArrayInIdealZoom.length=0,Xe(this,ms,"f").enhancedFocus)){const e=m.points;try{await a({mode:"manual",area:{centerPoint:{x:(e[0].x+e[2].x)/2+"px",y:(e[0].y+e[2].y)/2+"px"},width:e[2].x-e[0].x+"px",height:e[2].y-e[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}if(!Xe(this,ms,"f").autoZoom&&Xe(this,ms,"f").enhancedFocus&&(Xe(this,ps,"f").autoFocusFrameArray.push(!0),Xe(this,ps,"f").autoFocusFrameArray.splice(0,Xe(this,ps,"f").autoFocusFrameArray.length-Xe(this,ps,"f").autoFocusFrameLimit[0]),Xe(this,ps,"f").autoFocusFrameArray.filter((t=>!0===t)).length>=Xe(this,ps,"f").autoFocusFrameLimit[1])){Xe(this,ps,"f").autoFocusFrameArray.length=0;try{const t=m.points;await a({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(Xe(this,ms,"f").autoZoom){if(Xe(this,ps,"f").autoZoomInFrameArray.push(!1),Xe(this,ps,"f").autoZoomInFrameArray.splice(0,Xe(this,ps,"f").autoZoomInFrameArray.length-Xe(this,ps,"f").autoZoomInFrameLimit[0]),Xe(this,ps,"f").autoZoomOutFrameCount++,Xe(this,ps,"f").frameArrayInIdealZoom.push(!1),Xe(this,ps,"f").frameArrayInIdealZoom.splice(0,Xe(this,ps,"f").frameArrayInIdealZoom.length-Xe(this,ps,"f").frameLimitInIdealZoom[0]),Xe(this,ps,"f").autoZoomOutFrameCount>=Xe(this,ps,"f").autoZoomOutFrameLimit){Xe(this,ps,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let r=i-Math.max((i-1)*Xe(this,ps,"f").autoZoomOutStepRate,Xe(this,ps,"f").autoZoomOutMinStep);r=Math.max(Xe(this,ps,"f").minValue,r),r=Math.min(Xe(this,ps,"f").maxValue,r);try{await e({factor:r})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}Xe(this,ms,"f").enhancedFocus&&a({mode:"continuous"}).catch((()=>{}))}!Xe(this,ms,"f").autoZoom&&Xe(this,ms,"f").enhancedFocus&&(Xe(this,ps,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch((()=>{})))}}},ze(this,_s,new Ss(1e4),"f")}setCameraView(t){if(!(t instanceof Rr))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),Xe(this,is,"m",ys).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;Xe(this,is,"m",ys).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return Xe(this,is,"m",ys).call(this)?Xe(this,ss,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){const t=this.cameraView;if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");t&&(t._singleFrameMode=this.singleFrameMode,Xe(this,is,"m",ys).call(this)?t._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(t.getVideoElement()),t._startLoading()));let e={width:0,height:0,deviceId:""};if(Xe(this,is,"m",ys).call(this));else{try{await this.cameraManager.open()}catch(e){throw t&&t._stopLoading(),"NotFoundError"===e.name?new Error(`No camera devices were detected. Please ensure a camera is connected and recognized by your system. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):"NotAllowedError"===e.name?new Error(`Camera access is blocked. Please check your browser settings or grant permission to use the camera. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):e}let i,r=t.getUIElement();if(r=r.shadowRoot||r,i=r.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=r.elTorchAuto=r.querySelector(".dce-mn-torch-auto"),e=r.elTorchOn=r.querySelector(".dce-mn-torch-on"),n=r.elTorchOff=r.querySelector(".dce-mn-torch-off");t&&(e.style.display=null==this.isTorchOn?"":"none"),e&&(e.style.display=1==this.isTorchOn?"":"none"),n&&(n.style.display=0==this.isTorchOn?"":"none");let s=r.elBeepOn=r.querySelector(".dce-mn-beep-on"),o=r.elBeepOff=r.querySelector(".dce-mn-beep-off");s&&(s.style.display=bs.allowBeep?"":"none"),o&&(o.style.display=bs.allowBeep?"none":"");let a=r.elVibrateOn=r.querySelector(".dce-mn-vibrate-on"),h=r.elVibrateOff=r.querySelector(".dce-mn-vibrate-off");a&&(a.style.display=bs.allowVibrate?"":"none"),h&&(h.style.display=bs.allowVibrate?"none":""),r.elResolutionBox=r.querySelector(".dce-mn-resolution-box");let l,c=r.elZoom=r.querySelector(".dce-mn-zoom");c&&(c.style.display="none",l=r.elZoomSpan=c.querySelector("span"));let u=r.elToast=r.querySelector(".dce-mn-toast"),d=r.elCameraClose=r.querySelector(".dce-mn-camera-close"),f=r.elTakePhoto=r.querySelector(".dce-mn-take-photo"),g=r.elCameraSwitch=r.querySelector(".dce-mn-camera-switch"),m=r.elCameraAndResolutionSettings=r.querySelector(".dce-mn-camera-and-resolution-settings");m&&(m.style.display="none");const p=r.dceMnFs={},_=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",_);const v=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",v);const y=()=>{this.turnAutoTorch()};null==n||n.addEventListener("pointerdown",y);const w=()=>{bs.allowBeep=!bs.allowBeep,s&&(s.style.display=bs.allowBeep?"":"none"),o&&(o.style.display=bs.allowBeep?"none":"")};for(let t of[o,s])null==t||t.addEventListener("pointerdown",w);const C=()=>{bs.allowVibrate=!bs.allowVibrate,a&&(a.style.display=bs.allowVibrate?"":"none"),h&&(h.style.display=bs.allowVibrate?"none":"")};for(let t of[h,a])null==t||t.addEventListener("pointerdown",C);const E=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),r=parseInt(e.getAttribute("data-height")),n=await this.setResolution({width:i,height:r});{let e=Math.max(n.width,n.height),i=Math.min(n.width,n.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&b(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?m&&(m.style.display=m.style.display?"":"none"):m&&""===m.style.display&&(m.style.display="none"))};r.addEventListener("click",E);let T=null;p.funcInfoZoomChange=(t,e=3e3)=>{c&&l&&(l.textContent=t.toFixed(1),c.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout((()=>{c.style.display="none",T=null}),e))};let S=null,b=p.funcShowToast=(t,e=3e3)=>{u&&(u.textContent=t,u.style.display="",null!=S&&(clearTimeout(S),S=null),S=setTimeout((()=>{u.style.display="none",S=null}),e))};const I=()=>{this.close()};null==d||d.addEventListener("click",I);const x=()=>{};null==f||f.addEventListener("pointerdown",x);const O=()=>{var t,e;let i,r=this.getVideoSettings(),n=r.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),o=null==s?void 0:s.indexOf("front");-1===o&&(o=null==s?void 0:s.indexOf("前"));let a=null==s?void 0:s.indexOf("back");-1===a&&(a=null==s?void 0:s.indexOf("后")),"number"==typeof o&&-1!==o?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i&&(i="user"===((null==n?void 0:n.ideal)||(null==n?void 0:n.exact)||n)),r.video.facingMode={ideal:i?"environment":"user"},delete r.video.deviceId,this.updateVideoSettings(r)};null==g||g.addEventListener("pointerdown",O);let A=-1/0,R=1;const D=t=>{let e=Date.now();e-A>1e3&&(R=this.getZoomSettings().factor),R-=t.deltaY/200,R>20&&(R=20),R<1&&(R=1),this.setZoom({factor:R}),A=e};i.addEventListener("wheel",D);const L=new Map;let M=!1;const F=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],r=t.touches[1],n=L.get(i.identifier),s=L.get(r.identifier);if(!n||!s)break;let o=Math.pow(Math.pow(n.x-s.x,2)+Math.pow(n.y-s.y,2),.5),a=Math.pow(Math.pow(i.clientX-r.clientX,2)+Math.pow(i.clientY-r.clientY,2),.5),h=Date.now();if(M||h-A<100)return;h-A>1e3&&(R=this.getZoomSettings().factor),R*=a/o,R>20&&(R=20),R<1&&(R=1);let l=!1;"safari"==(null===(e=null==He?void 0:He.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/o>1&&R<2?(R=2,l=!0):a/o<1&&R<2&&(R=1,l=!0)),M=!0,l&&b("zooming..."),await this.setZoom({factor:R}),l&&(u.textContent=""),M=!1,A=Date.now();break}L.clear();for(let e of t.touches)L.set(e.identifier,{x:e.clientX,y:e.clientY})};r.addEventListener("touchstart",F),r.addEventListener("touchmove",F),r.addEventListener("touchend",F),r.addEventListener("touchcancel",F),p.unbind=()=>{null==t||t.removeEventListener("pointerdown",_),null==e||e.removeEventListener("pointerdown",v),null==n||n.removeEventListener("pointerdown",y);for(let t of[o,s])null==t||t.removeEventListener("pointerdown",w);for(let t of[h,a])null==t||t.removeEventListener("pointerdown",C);r.removeEventListener("click",E),null==d||d.removeEventListener("click",I),null==f||f.removeEventListener("pointerdown",x),null==g||g.removeEventListener("pointerdown",O),i.removeEventListener("wheel",D),r.removeEventListener("touchstart",F),r.removeEventListener("touchmove",F),r.removeEventListener("touchend",F),r.removeEventListener("touchcancel",F),delete r.dceMnFs,i.style.display="none"},i.style.display="",t&&null==this.isTorchOn&&setTimeout((()=>{this.turnAutoTorch(1e3)}),0)}this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const n=this.getResolution();e.width=n.width,e.height=n.height,e.deviceId=this.getSelectedCamera().deviceId}return ze(this,ss,"open","f"),t&&(t._innerComponent.style.display="",Xe(this,is,"m",ys).call(this)||(t._stopLoading(),t._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),t._renderResolutionInfo({width:e.width,height:e.height}),t.eventHandler.fire("content:updated",null,{async:!1}),t.eventHandler.fire("videoEl:resized",null,{async:!1}))),Xe(this,os,"f").fire("opened",null,{target:this,async:!1}),e}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),Xe(this,is,"m",ys).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}ze(this,ss,"closed","f"),Xe(this,_s,"f").stopCharging(),e&&(e._innerComponent.style.display="none",Xe(this,is,"m",ys).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),Xe(this,os,"f").fire("closed",null,{target:this,async:!1})}pause(){if(Xe(this,is,"m",ys).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!Xe(this,is,"m",ys).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(Xe(this,is,"m",ys).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){if(!t)throw new Error("Invalid value.");let e;e="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(e),this.isTorchOn=!1;const i=this.getResolution(),r=this.cameraView;return r&&!r.disposed&&(r._stopLoading(),r._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),r._renderResolutionInfo({width:i.width,height:i.height})),{width:i.width,height:i.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Xe(this,os,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Xe(this,os,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._on(r,e)}off(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._off(r,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(Xe(this,is,"m",ys).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(Xe(this,is,"m",ys).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){if(null!=this._taskid4AutoTorch){if(!(t{var t,n,s;if(this.disposed||e||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++r>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let o;try{o=this.fetchImage()}catch(t){}if(!o||!o.width||!o.height)return;let a=0;if(h.IPF_GRAYSCALED===o.format){for(let t=0;t=this.maxDarkCount4AutoTroch){null===(t=Os._onLog)||void 0===t||t.call(Os,`darkCount ${i}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(n=null==t?void 0:t.dceMnFs)||void 0===n||n.funcShowToast("Torch Auto On")}catch(t){console.warn(t),e=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,null===(s=null==i?void 0:i.dceMnFs)||void 0===s||s.funcShowToast("Torch Not Supported")}}}else i=0};this._taskid4AutoTorch=setInterval(n,t),this.isTorchOn=void 0,n();let s=this.cameraView.getUIElement();s=s.shadowRoot||s,s.elTorchAuto&&(s.elTorchAuto.style.display=""),s.elTorchOn&&(s.elTorchOn.style.display="none"),s.elTorchOff&&(s.elTorchOff.style.display="none")}async setColorTemperature(t){if(Xe(this,is,"m",ys).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(Xe(this,is,"m",ys).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,r;if(Xe(this,is,"m",ys).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(r=null==e?void 0:e.dceMnFs)||void 0===r||r.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(Xe(this,is,"m",ys).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(Xe(this,is,"m",ys).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(Xe(this,is,"m",ys).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){Xe(this,ps,"f").minValue=t.min,Xe(this,ps,"f").maxValue=t.max}getAutoZoomRange(){return{min:Xe(this,ps,"f").minValue,max:Xe(this,ps,"f").maxValue}}async enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=ct.license)||void 0===e?void 0:e.LicenseManager)||void 0===i?void 0:i.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==gt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&ni.EF_ENHANCED_FOCUS&&(Xe(this,ms,"f").enhancedFocus=!0),t&ni.EF_AUTO_ZOOM&&(Xe(this,ms,"f").autoZoom=!0),t&ni.EF_TAP_TO_FOCUS&&(Xe(this,ms,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&ni.EF_ENHANCED_FOCUS&&(Xe(this,ms,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch((()=>{}))),t&ni.EF_AUTO_ZOOM&&(Xe(this,ms,"f").autoZoom=!1,this.resetZoom().catch((()=>{}))),t&ni.EF_TAP_TO_FOCUS&&(Xe(this,ms,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),Xe(this,is,"m",Cs).call(this)&&Xe(this,is,"m",ws).call(this)||Xe(this,_s,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!w(t)&&!I(t))throw TypeError("Invalid 'region'.");ze(this,us,t?JSON.parse(JSON.stringify(t)):null,"f"),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(Xe(this,us,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");ze(this,cs,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||Xe(this,is,"m",ys).call(this))}startFetching(){if(Xe(this,is,"m",ys).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");Xe(this,fs,"f")||(ze(this,fs,!0,"f"),Xe(this,is,"m",Es).call(this))}stopFetching(){Xe(this,fs,"f")&&(Os._onLog&&Os._onLog("DCE: stop fetching loop: "+Date.now()),Xe(this,gs,"f")&&clearTimeout(Xe(this,gs,"f")),ze(this,fs,!1,"f"))}fetchImage(){if(Xe(this,is,"m",ys).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(4!==this.video.readyState)throw new Error("The video is not loaded.");const t=this.getResolution();if(!(null==t?void 0:t.width)||!(null==t?void 0:t.height))throw new Error("The video is not loaded.");let e;if(e=ki.convert(Xe(this,us,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height}),e.x>t.width||e.y>t.height)throw new Error("Invalid scan region.");e.x+e.width>t.width&&(e.width=t.width-e.x),e.y+e.height>t.height&&(e.height=t.height-e.y);const i={sx:e.x,sy:e.y,sWidth:e.width,sHeight:e.height,dWidth:e.width,dHeight:e.height},r=Math.max(i.dWidth,i.dHeight);if(this.canvasSizeLimit&&r>this.canvasSizeLimit){const t=this.canvasSizeLimit/r;i.dWidth>i.dHeight?(i.dWidth=this.canvasSizeLimit,i.dHeight=Math.round(i.dHeight*t)):(i.dWidth=Math.round(i.dWidth*t),i.dHeight=this.canvasSizeLimit)}const n=this.cameraManager.getFrameData({position:i,pixelFormat:this.getPixelFormat()===h.IPF_GRAYSCALED?Gr.GREY:Gr.RGBA});if(!n)return null;let s;s=n.pixelFormat===Gr.GREY?n.width:4*n.width;let o=!0;return 0===i.sx&&0===i.sy&&i.sWidth===t.width&&i.sHeight===t.height&&(o=!1),{bytes:n.data,width:n.width,height:n.height,stride:s,format:Is.get(n.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:wt.ITT_VIDEO_FRAME,isCropped:o,cropRegion:{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height,isMeasuredInPercentage:!1},originalWidth:t.width,originalHeight:t.height,currentWidth:n.width,currentHeight:n.height,timeSpent:n.timeSpent,timeStamp:n.timeStamp},toCanvas:Xe(this,ls,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,Xe(this,fs,"f")&&(Xe(this,gs,"f")&&clearTimeout(Xe(this,gs,"f")),ze(this,gs,setTimeout((()=>{this.disposed||Xe(this,is,"m",Es).call(this)}),t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){ze(this,ds,t,"f")}getPixelFormat(){return Xe(this,ds,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(Xe(this,is,"m",ys).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",(()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",(()=>{t&&this.open(),e.remove()}),{once:!0})})),e.addEventListener("change",(async()=>{const i=e.files[0],r=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(i),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=ki.convert(Xe(this,us,"f"),n,s);o||(o={x:0,y:0,width:n,height:s});const a=Xe(this,hs,"f").call(this,r,n,s,o);t&&t(a)})),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=Xe(this,is,"m",Ts).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=Xe(this,is,"m",Ts).call(this,t);return{x:e.clientX,y:e.clientY}}convertToScanRegionCoordinates(t){if(!Xe(this,us,"f"))return JSON.parse(JSON.stringify(t));let e,i,r=Xe(this,us,"f").left||Xe(this,us,"f").x||0,n=Xe(this,us,"f").top||Xe(this,us,"f").y||0;if(!Xe(this,us,"f").isMeasuredInPercentage)return{x:t.x-r,y:t.y-n};if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!Xe(this,is,"m",ys).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Xe(this,is,"m",ys).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(Xe(this,is,"m",ys).call(this)){const t=this.cameraView._innerComponent.getElement("content");e=t.width,i=t.height}else{const t=this.getVideoEl();e=t.videoWidth,i=t.videoHeight}return{x:t.x-Math.round(r*e/100),y:t.y-Math.round(n*i/100)}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),ze(this,vs,!0,"f")}}var As,Rs,Ds,Ls,Ms,Fs,Ps,ks;rs=Os,ss=new WeakMap,os=new WeakMap,as=new WeakMap,hs=new WeakMap,ls=new WeakMap,cs=new WeakMap,us=new WeakMap,ds=new WeakMap,fs=new WeakMap,gs=new WeakMap,ms=new WeakMap,ps=new WeakMap,_s=new WeakMap,vs=new WeakMap,is=new WeakSet,ys=function(){return"disabled"!==this.singleFrameMode},ws=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},Cs=function(){for(let t in Xe(this,ms,"f"))if(1==Xe(this,ms,"f")[t])return!0;return!1},Es=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!Xe(this,fs,"f"))return Xe(this,gs,"f")&&clearTimeout(Xe(this,gs,"f")),void ze(this,gs,setTimeout((()=>{this.disposed||Xe(this,is,"m",t).call(this)}),this.fetchInterval),"f");const e=()=>{var t;let e;Os._onLog&&Os._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{e=this.fetchImage()}catch(e){const i=e.message||e;if("The video is not loaded."===i)return;if(null===(t=Xe(this,cs,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout((()=>{var t;null===(t=Xe(this,cs,"f"))||void 0===t||t.onErrorReceived(_t.EC_IMAGE_READ_FAILED,i)}),0);console.warn(e)}e?(this.addImageToBuffer(e),Os._onLog&&Os._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),Xe(this,os,"f").fire("frameAddedToBuffer",null,{async:!1})):Os._onLog&&Os._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case o.BOPM_BLOCK:break;case o.BOPM_UPDATE:e()}else e();Xe(this,gs,"f")&&clearTimeout(Xe(this,gs,"f")),ze(this,gs,setTimeout((()=>{this.disposed||Xe(this,is,"m",t).call(this)}),this.fetchInterval),"f")},Ts=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!Xe(this,is,"m",ys).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Xe(this,is,"m",ys).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,r=e.top,n=i+window.scrollX,s=r+window.scrollY,{width:o,height:a}=this.cameraView._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(Xe(this,is,"m",ys).call(this)){const t=this.cameraView._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=this.cameraView.getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)u{var e;if(!this.isUseMagnifier)return;if(Xe(this,Ls,"f")||ze(this,Ls,new Bs,"f"),!Xe(this,Ls,"f").magnifierCanvas)return;document.body.contains(Xe(this,Ls,"f").magnifierCanvas)||(Xe(this,Ls,"f").magnifierCanvas.style.position="fixed",Xe(this,Ls,"f").magnifierCanvas.style.boxSizing="content-box",Xe(this,Ls,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(Xe(this,Ls,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void Xe(this,Fs,"f").call(this);const r=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!r)return;const n=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*n,o=[{image:i,width:i.width,height:i.height},{image:r,width:r.width,height:r.height}];Xe(this,Ls,"f").update(s,t.pointer,n,o);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(Xe(this,Ls,"f").magnifierCanvas.style.left="auto",Xe(this,Ls,"f").magnifierCanvas.style.top="0",Xe(this,Ls,"f").magnifierCanvas.style.right="0"):(Xe(this,Ls,"f").magnifierCanvas.style.left="0",Xe(this,Ls,"f").magnifierCanvas.style.top="0",Xe(this,Ls,"f").magnifierCanvas.style.right="auto")}Xe(this,Ls,"f").show()})),Fs.set(this,(()=>{Xe(this,Ls,"f")&&Xe(this,Ls,"f").hide()})),Ps.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Wi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=document.createElement("dce-component"),e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let r=this._innerComponent.getElement("content");r||(r=document.createElement("canvas"),r.style.objectFit="contain",this._innerComponent.setElement("content",r)),r.width===e&&r.height===i||(r.width=e,r.height=i);const n=r.getContext("2d");n.clearRect(0,0,r.width,r.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),n.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&n.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(y(t)){ze(this,Ds,t,"f");const{width:e,height:i,bytes:r,format:n}=Object.assign({},t);let s;if(n===h.IPF_GRAYSCALED){s=new Uint8ClampedArray(e*i*4);for(let t=0;t({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const r=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new oi.Control({positionHandler:Ei,actionHandler:bi(i>0?i-1:r,Si),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let r=t.x-i.pathOffset.x,n=t.y-i.pathOffset.y;const s=oi.util.transformPoint({x:r,y:n},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){Xe(this,Ai,"f")&&this.setLine(Xe(this,Ai,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!E(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else ze(this,Ai,JSON.parse(JSON.stringify(t)),"f")}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return Xe(this,Ai,"f")?JSON.parse(JSON.stringify(Xe(this,Ai,"f"))):null}},QuadDrawingItem:Di,RectDrawingItem:Ci,TextDrawingItem:Oi});const Us="undefined"==typeof self,Vs="function"==typeof importScripts,Gs=(()=>{if(!Vs){if(!Us&&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"./"}})(),Ws=t=>{if(null==t&&(t="./"),Us||Vs);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};gt.engineResourcePaths.dbr={version:"10.4.31",path:Gs,isInternal:!0},ut.dbr={js:!1,wasm:!0,deps:["license","dip"]},ct.dbr={};const Ys="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&O(gt.engineResourcePaths.std.version,Ys)<0&&(gt.engineResourcePaths.std={version:Ys,path:Ws(Gs+`../../dynamsoft-capture-vision-std@${Ys}/dist/`),isInternal:!0});const Hs="2.4.31";(!gt.engineResourcePaths.dip||"string"!=typeof gt.engineResourcePaths.dip&&O(gt.engineResourcePaths.dip.version,Hs)<0)&&(gt.engineResourcePaths.dip={version:Hs,path:Ws(Gs+`../../dynamsoft-image-processing@${Hs}/dist/`),isInternal:!0});const Xs={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)};var zs,Zs,qs,Ks;!function(t){t[t.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",t[t.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",t[t.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(zs||(zs={})),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"}(Zs||(Zs={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",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",t[t.LM_SKIP=0]="LM_SKIP"}(qs||(qs={})),function(t){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",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP"}(Ks||(Ks={}));var Js=Object.freeze({__proto__:null,BarcodeReaderModule:class{static getVersion(){const t=lt.dbr&<.dbr.wasm;return`10.4.31(Worker: ${lt.dbr&<.dbr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}},EnumBarcodeFormat:Xs,get EnumDeblurMode(){return Ks},get EnumExtendedBarcodeResultType(){return zs},get EnumLocalizationMode(){return qs},get EnumQRCodeErrorCorrectionLevel(){return Zs}});const Qs=async t=>{let e;await new Promise(((i,r)=>{e=new Image,e.onload=()=>i(e),e.onerror=r,e.src=URL.createObjectURL(t)}));const i=document.createElement("canvas"),r=i.getContext("2d");return i.width=e.width,i.height=e.height,r.drawImage(e,0,0),{bytes:Uint8Array.from(r.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:10}};const $s="undefined"==typeof self,to="function"==typeof importScripts,eo=(()=>{if(!to){if(!$s&&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"./"}})(),io=t=>{if(null==t&&(t="./"),$s||to);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};gt.engineResourcePaths.utility={version:"1.4.32",path:eo,isInternal:!0},ut.utility={js:!0,wasm:!0};const ro="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&O(gt.engineResourcePaths.std.version,ro)<0&&(gt.engineResourcePaths.std={version:ro,path:io(eo+`../../dynamsoft-capture-vision-std@${ro}/dist/`),isInternal:!0});const no="2.4.31";(!gt.engineResourcePaths.dip||"string"!=typeof gt.engineResourcePaths.dip&&O(gt.engineResourcePaths.dip.version,no)<0)&&(gt.engineResourcePaths.dip={version:no,path:io(eo+`../../dynamsoft-image-processing@${no}/dist/`),isInternal:!0});function so(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}var oo,ao,ho,lo,co;function uo(t,e){let i=!0;for(let o=0;o1)return Math.sqrt((h-o)**2+(l-a)**2);{const t=n+u*(o-n),e=s+u*(a-s);return Math.sqrt((h-t)**2+(l-e)**2)}}function mo(t){const e=[];for(let i=0;i=0&&h<=1&&l>=0&&l<=1?{x:t.x+l*n,y:t.y+l*s}:null}function vo(t){let e=0;for(let i=0;i0}function wo(t,e){for(let i=0;i<4;i++)if(!yo(t.points[i],t.points[(i+1)%4],e))return!1;return!0}"function"==typeof SuppressedError&&SuppressedError;function Co(t,e,i,r){const n=t.points,s=e.points;let o=8*i;o=Math.max(o,5);const a=mo(n)[3],h=mo(n)[1],l=mo(s)[3],c=mo(s)[1];let u,d=0;if(u=Math.max(Math.abs(go(a,e.points[0])),Math.abs(go(a,e.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(go(h,e.points[1])),Math.abs(go(h,e.points[2]))),u>d&&(d=u),u=Math.max(Math.abs(go(l,t.points[0])),Math.abs(go(l,t.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(go(c,t.points[1])),Math.abs(go(c,t.points[2]))),u>d&&(d=u),d>o)return!1;const f=po(mo(n)[0]),g=po(mo(n)[2]),m=po(mo(s)[0]),p=po(mo(s)[2]),_=fo(f,p),v=fo(m,g),y=_>v,w=Math.min(_,v),C=fo(f,g),E=fo(m,p);let T=12*i;return T=Math.max(T,5),T=Math.min(T,C),T=Math.min(T,E),!!(w{e.x+=t,e.y+=i})),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,r=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-r.area)>.4*i.area)return!1;let n=new Array(4).fill(0),s=new Array(4).fill(0),o=0,a=0;for(let t=0;t<4;++t)n[t]=Math.round(100*(r.points[t].x-i.points[t].x))/100,o+=n[t],s[t]=Math.round(100*(r.points[t].y-i.points[t].y))/100,a+=s[t];o/=4,a/=4;for(let t=0;t<4;++t){if(Math.abs(n[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1;if(Math.abs(s[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1}return e.x=o,e.y=a,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(wo(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(wo(this.location,e))return!0}else{for(let e=0;e<4;e++)if(wo(t,this.location.points[e]))return!0;if(wo(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const r=[this.location.points[0],this.location.points[3]],n=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],s=0===t||3===t?r:n;if(Math.abs(go(s,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const r=t.location.points[i],n=this.location.points[i];if(!(Math.abs(n.x+e.x-r.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const r=Object.assign({},t.location);for(let t=0;t<4;t++)r.points[t].x-=e.x,r.points[t].y-=e.y;if(!this.isLocationOverlap(r,t.location.area))return!1;if(i){const t=.75;return function(t,e){const i=[];for(let r=0;r<4;r++)for(let n=0;n<4;n++){const s=_o(t[r],t[(r+1)%4],e[n],e[(n+1)%4]);s&&i.push(s)}return t.forEach((t=>{uo(e,t)&&i.push(t)})),e.forEach((e=>{uo(t,e)&&i.push(e)})),vo(function(t){if(t.length<=1)return t;t.sort(((t,e)=>t.x-e.x||t.y-e.y));const e=t.shift();return t.sort(((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x))),[e,...t]}(i))}([...this.location.points],r.points)>this.locationArea*t}return!0}}const To={BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096)},So={barcode:2,text_line:4,detected_quad:8,normalized_image:16},bo=t=>Object.values(So).includes(t)||So.hasOwnProperty(t),Io=(t,e)=>"string"==typeof t?e[So[t]]:e[t],xo=(t,e,i)=>{"string"==typeof t?e[So[t]]=i:e[t]=i},Oo=(t,e,i)=>{const r=[8,16].includes(i);if(!r&&t.isResultCrossVerificationEnabled(i))for(let t=0;t{let h=rt();nt[h]=async e=>{if(e.success)return s&&this.saveToFile(e.image,"test.png",s),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},et.postMessage({type:"utility_drawOnImage",id:h,body:{dsImage:o,drawingItem:e instanceof Array?e:[e],color:r,thickness:n,type:i}})}))}},MultiFrameResultCrossFilter:class{constructor(){this.verificationEnabled={[mt.CRIT_BARCODE]:!1,[mt.CRIT_TEXT_LINE]:!0,[mt.CRIT_DETECTED_QUAD]:!0,[mt.CRIT_NORMALIZED_IMAGE]:!1},this.duplicateFilterEnabled={[mt.CRIT_BARCODE]:!1,[mt.CRIT_TEXT_LINE]:!1,[mt.CRIT_DETECTED_QUAD]:!1,[mt.CRIT_NORMALIZED_IMAGE]:!1},this.duplicateForgetTime={[mt.CRIT_BARCODE]:3e3,[mt.CRIT_TEXT_LINE]:3e3,[mt.CRIT_DETECTED_QUAD]:3e3,[mt.CRIT_NORMALIZED_IMAGE]:3e3},this.latestOverlappingEnabled={[mt.CRIT_BARCODE]:!1,[mt.CRIT_TEXT_LINE]:!1,[mt.CRIT_DETECTED_QUAD]:!1,[mt.CRIT_NORMALIZED_IMAGE]:!1},this.maxOverlappingFrames={[mt.CRIT_BARCODE]:5,[mt.CRIT_TEXT_LINE]:5,[mt.CRIT_DETECTED_QUAD]:5,[mt.CRIT_NORMALIZED_IMAGE]:5},this.overlapSet=[],this.stabilityCount=0,this.crossVerificationFrames=5,oo.set(this,new Map),ao.set(this,new Map),ho.set(this,new Map),lo.set(this,new Map),co.set(this,new Map)}_dynamsoft(){so(this,oo,"f").forEach(((t,e)=>{xo(e,this.verificationEnabled,t)})),so(this,ao,"f").forEach(((t,e)=>{xo(e,this.duplicateFilterEnabled,t)})),so(this,ho,"f").forEach(((t,e)=>{xo(e,this.duplicateForgetTime,t)})),so(this,lo,"f").forEach(((t,e)=>{xo(e,this.latestOverlappingEnabled,t)})),so(this,co,"f").forEach(((t,e)=>{xo(e,this.maxOverlappingFrames,t)}))}enableResultCrossVerification(t,e){bo(t)&&so(this,oo,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!bo(t)&&Io(t,this.verificationEnabled)}enableResultDeduplication(t,e){bo(t)&&(e&&this.enableLatestOverlapping(t,!1),so(this,ao,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!bo(t)&&Io(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){bo(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),so(this,ho,"f").set(t,e))}getDuplicateForgetTime(t){return bo(t)?Io(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){bo(t)&&so(this,co,"f").set(t,e)}getMaxOverlappingFrames(t){return bo(t)?Io(t,this.maxOverlappingFrames):-1}enableLatestOverlapping(t,e){bo(t)&&(e&&this.enableResultDeduplication(t,!1),so(this,lo,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!bo(t)&&Io(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[mt.CRIT_BARCODE,mt.CRIT_TEXT_LINE,mt.CRIT_DETECTED_QUAD,mt.CRIT_NORMALIZED_IMAGE];for(let i=0;i{if(1!==t.type){const e=(BigInt(t.format)&BigInt(To.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(To.BF_GS1_DATABAR))!=BigInt(0);return new Eo(h,e?1:2,e,t)}})).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(l).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t)).length;n>p&&(p=n,m=r,g.x=i.x,g.y=i.y)}}if(0===p){for(let e=0;e-1!=t)).length}let i=this.overlapSet.length<=3?p>=1:p>=2;if(!i&&s&&u>0){let t=0;for(let e=0;e=1:t>=3}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach(((t,e)=>{if(1!==t.type){const i=Object.assign({},t),r=(BigInt(t.format)&BigInt(To.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(To.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0)))}f.sort(((t,e)=>e-t)).forEach(((e,i)=>{t.items.splice(e,1)})),d.forEach((e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))}))}}onDecodedBarcodesReceived(t){this.latestOverlappingFilter(t),Oo(this,t.items,mt.CRIT_BARCODE)}onRecognizedTextLinesReceived(t){Oo(this,t.items,mt.CRIT_TEXT_LINE)}onDetectedQuadsReceived(t){Oo(this,t.items,mt.CRIT_DETECTED_QUAD)}onNormalizedImagesReceived(t){Oo(this,t.items,mt.CRIT_NORMALIZED_IMAGE)}},UtilityModule:class{static getVersion(){return`1.4.32(Worker: ${lt.utility&<.utility.worker||"Not Loaded"}, Wasm: ${lt.utility&<.utility.wasm||"Not Loaded"})`}}});le._defaultTemplate="ReadSingleBarcode",t.CVR=ge,t.Core=xt,t.DBR=Js,t.DCE=js,t.License=Be,t.Utility=Ao})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).Dynamsoft=t.Dynamsoft||{})}(this,(function(t){"use strict";const e=t=>t&&"object"==typeof t&&"function"==typeof t.then,i=(async()=>{})().constructor;let n=class extends i{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 n;this._task=t,e(t)?n=t:"function"==typeof t&&(n=new i(t)),n&&(async()=>{try{const e=await n;t===this._task&&this.resolve(e)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let i,n;super(((t,e)=>{i=t,n=e})),this._s="pending",this.resolve=t=>{this.isPending&&(e(t)?this.task=t:(this._s="fulfilled",i(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",n(t))},this.task=t}};function r(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function s(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}var o,a,h;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(o||(o={})),function(t){t[t.CCUT_AUTO=0]="CCUT_AUTO",t[t.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",t[t.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",t[t.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",t[t.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",t[t.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(a||(a={})),function(t){t[t.IPF_BINARY=0]="IPF_BINARY",t[t.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",t[t.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",t[t.IPF_NV21=3]="IPF_NV21",t[t.IPF_RGB_565=4]="IPF_RGB_565",t[t.IPF_RGB_555=5]="IPF_RGB_555",t[t.IPF_RGB_888=6]="IPF_RGB_888",t[t.IPF_ARGB_8888=7]="IPF_ARGB_8888",t[t.IPF_RGB_161616=8]="IPF_RGB_161616",t[t.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",t[t.IPF_ABGR_8888=10]="IPF_ABGR_8888",t[t.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",t[t.IPF_BGR_888=12]="IPF_BGR_888",t[t.IPF_BINARY_8=13]="IPF_BINARY_8",t[t.IPF_NV12=14]="IPF_NV12",t[t.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(h||(h={}));const l="undefined"==typeof self,c="function"==typeof importScripts,u=(()=>{if(!c){if(!l&&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=t=>{if(null==t&&(t="./"),l||c);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},f=t=>Object.prototype.toString.call(t),g=t=>Array.isArray?Array.isArray(t):"[object Array]"===f(t),m=t=>"[object Boolean]"===f(t),p=t=>"number"==typeof t&&!Number.isNaN(t),_=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),v=t=>!(!_(t)||!p(t.width)||t.width<=0||!p(t.height)||t.height<=0||!p(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!C(t.tag)),y=t=>!!v(t)&&t.bytes instanceof Uint8Array,w=t=>!(!_(t)||!p(t.left)||t.left<0||!p(t.top)||t.top<0||!p(t.right)||t.right<0||!p(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom||!m(t.isMeasuredInPercentage)),C=t=>null===t||!!_(t)&&!!p(t.imageId)&&"type"in t,E=t=>!(!_(t)||!S(t.startPoint)||!S(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),S=t=>!!_(t)&&!!p(t.x)&&!!p(t.y),T=t=>!!_(t)&&!!g(t.points)&&0!=t.points.length&&!t.points.some((t=>!S(t))),b=t=>!!_(t)&&!!g(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some((t=>!S(t))),I=t=>!(!_(t)||!p(t.x)||!p(t.y)||!p(t.width)||t.width<0||!p(t.height)||t.height<0||"isMeasuredInPercentage"in t&&!m(t.isMeasuredInPercentage)),x=async(t,e)=>await new Promise(((i,n)=>{let r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType=e,r.send(),r.onloadend=async()=>{r.status<200||r.status>=300?n(new Error(t+" "+r.status)):i(r.response)},r.onerror=()=>{n(new Error("Network Error: "+r.statusText))}})),O=(t,e)=>{let i=t.split("."),n=e.split(".");for(let t=0;t{const e={},i={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcpd:"dynamsoft-code-parser",dlrData:"dynamsoft-label-recognizer-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer"};for(let n in t){if("rootDirectory"===n)continue;let r=n,s=t[r],o=s&&"object"==typeof s&&s.path?s.path:s,a=t.rootDirectory;if(a&&!a.endsWith("/")&&(a+="/"),"object"==typeof s&&s.isInternal)a&&(o=t[r].version?`${a}${i[r]}@${t[r].version}/dist/${"ddv"===r?"engine":""}`:`${a}${i[r]}/dist/${"ddv"===r?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof o&&(o=o.replace(i,a||"")),"object"==typeof o&&"dwt"===r){const n=t[r].resourcesPath,s=t[r].serviceInstallerLocation;e[r]={resourcesPath:n.replace(i,a||""),serviceInstallerLocation:s.replace(i,a||"")};continue}}e[r]=d(o)}return e},R=async(t,e,i)=>await new Promise((async(n,r)=>{try{const r=e.split(".");let s=r[r.length-1];const o=await L(`image/${s}`,t);r.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return n(a)}catch(t){return r()}})),D=t=>{y(t)&&(t=M(t));const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d",{willReadFrequently:!0}).putImageData(t,0,0),e},L=async(t,e)=>{y(e)&&(e=M(e));const i=D(e);return new Promise(((e,n)=>{i.toBlob((t=>e(t)),t)}))},M=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===h.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n=r)break;e[o]=e[o+1]=e[o+2]=(128&n)/128*255,e[o+3]=255,n<<=1}}}else if(Number(t.format)===h.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n=r)break;e[o]=e[o+1]=e[o+2]=128&n?0:255,e[o+3]=255,n<<=1}}}return new ImageData(e,t.width,t.height)};var F,P,k,B,N,j,U,V;let G,W,Y,H,X,z=class t{get _isFetchingStarted(){return r(this,N,"f")}constructor(){F.add(this),P.set(this,[]),k.set(this,1),B.set(this,o.BOPM_BLOCK),N.set(this,!1),j.set(this,void 0),U.set(this,a.CCUT_AUTO)}setErrorListener(t){}addImageToBuffer(t){var e;if(!y(t))throw new TypeError("Invalid 'image'.");if((null===(e=t.tag)||void 0===e?void 0:e.hasOwnProperty("imageId"))&&"number"==typeof t.tag.imageId&&this.hasImage(t.tag.imageId))throw new Error("Existed imageId.");if(r(this,P,"f").length>=r(this,k,"f"))switch(r(this,B,"f")){case o.BOPM_BLOCK:break;case o.BOPM_UPDATE:if(r(this,P,"f").push(t),_(r(this,j,"f"))&&p(r(this,j,"f").imageId)&&1==r(this,j,"f").keepInBuffer)for(;r(this,P,"f").length>r(this,k,"f");){const t=r(this,P,"f").findIndex((t=>{var e;return(null===(e=t.tag)||void 0===e?void 0:e.imageId)!==r(this,j,"f").imageId}));r(this,P,"f").splice(t,1)}else r(this,P,"f").splice(0,r(this,P,"f").length-r(this,k,"f"))}else r(this,P,"f").push(t)}getImage(){if(0===r(this,P,"f").length)return null;let e;if(r(this,j,"f")&&p(r(this,j,"f").imageId)){const t=r(this,F,"m",V).call(this,r(this,j,"f").imageId);if(t<0)throw new Error(`Image with id ${r(this,j,"f").imageId} doesn't exist.`);e=r(this,P,"f").slice(t,t+1)[0]}else e=r(this,P,"f").pop();if([h.IPF_RGB_565,h.IPF_RGB_555,h.IPF_RGB_888,h.IPF_ARGB_8888,h.IPF_RGB_161616,h.IPF_ARGB_16161616,h.IPF_ABGR_8888,h.IPF_ABGR_16161616,h.IPF_BGR_888].includes(e.format)){if(r(this,U,"f")===a.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t0!==t.length&&t.every((t=>p(t))))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&!m(e))throw new TypeError("Invalid 'keepInBuffer'.");s(this,j,{imageId:t,keepInBuffer:e},"f")}_resetNextReturnedImage(){s(this,j,null,"f")}hasImage(t){return r(this,F,"m",V).call(this,t)>=0}startFetching(){s(this,N,!0,"f")}stopFetching(){s(this,N,!1,"f")}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(s(this,k,t,"f");r(this,P,"f")&&r(this,P,"f").length>t;)r(this,P,"f").shift()}getMaxImageCount(){return r(this,k,"f")}getImageCount(){return r(this,P,"f").length}clearBuffer(){r(this,P,"f").length=0}isBufferEmpty(){return 0===r(this,P,"f").length}setBufferOverflowProtectionMode(t){s(this,B,t,"f")}getBufferOverflowProtectionMode(){return r(this,B,"f")}setColourChannelUsageType(t){s(this,U,t,"f")}getColourChannelUsageType(){return r(this,U,"f")}};P=new WeakMap,k=new WeakMap,B=new WeakMap,N=new WeakMap,j=new WeakMap,U=new WeakMap,F=new WeakSet,V=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return r(this,P,"f").findIndex((e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t}))},"undefined"!=typeof navigator&&(G=navigator,W=G.userAgent,Y=G.platform,H=G.mediaDevices),function(){if(!l){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:G.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Y,search:"Win"},Mac:{str:Y},Linux:{str:Y}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||W,o=r.search||e,a=r.verStr||W,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||W,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=W.indexOf("Windows NT")&&(r="HarmonyOS"),X={browser:i,version:n,OS:r}}l&&(X={browser:"ssr",version:0,OS:"ssr"})}();const q="undefined"!=typeof WebAssembly&&W&&!(/Safari/.test(W)&&!/Chrome/.test(W)&&/\(.+\s11_2_([2-6]).*\)/.test(W)),Z=!("undefined"==typeof Worker),K=!(!H||!H.getUserMedia),J=async()=>{let t=!1;if(K)try{(await H.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===X.browser&&X.version>66||"Safari"===X.browser&&X.version>13||"OPR"===X.browser&&X.version>43||"Edge"===X.browser&&X.version;const Q={},$=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push(Q[t]=Q[t]||new n);await Promise.all(i)},tt=async(t,e)=>{let i,r="string"==typeof t?[t]:t,s=[];for(let t of r){let r;s.push(r=Q[t]=Q[t]||new n(i=i||e())),r.isEmpty&&(r.task=i=i||e())}await Promise.all(s)};let et,it=0;const nt=()=>it++,rt={};let st;const ot=t=>{st=t,et&&et.postMessage({type:"setBLog",body:{value:!!t}})};let at=!1;const ht=t=>{at=t,et&&et.postMessage({type:"setBDebug",body:{value:!!t}})},lt={},ct={},ut={dip:{wasm:!0}},dt={std:{version:"1.4.21",path:d(u+"../../dynamsoft-capture-vision-std@1.4.21/dist/"),isInternal:!0},core:{version:"3.4.31",path:u,isInternal:!0}},ft=async t=>{let e;t instanceof Array||(t=t?[t]:[]);let i=Q.core;e=!i||i.isEmpty;let r=new Map;const s=t=>{if("std"==(t=t.toLowerCase())||"core"==t)return;if(!ut[t])throw Error("The '"+t+"' module cannot be found.");let e=ut[t].deps;if(null==e?void 0:e.length)for(let t of e)s(t);let i=Q[t];r.has(t)||r.set(t,!i||i.isEmpty)};for(let e of t)s(e);let o=[];e&&o.push("core"),o.push(...r.keys());const a=[...r.entries()].filter((t=>!t[1])).map((t=>t[0]));await tt(o,(async()=>{const t=[...r.entries()].filter((t=>t[1])).map((t=>t[0]));await $(a);const i=A(dt),s={};for(let e of t)s[e]=ut[e];const o={engineResourcePaths:i,autoResources:s,names:t};let h=new n;if(e){o.needLoadCore=!0;let t=i.core+gt._workerName;t.startsWith(location.origin)||(t=await fetch(t).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),et=new Worker(t),et.onerror=t=>{let e=new Error(t.message);h.reject(e)},et.addEventListener("message",(t=>{let e=t.data?t.data:t,i=e.type,n=e.id,r=e.body;switch(i){case"log":st&&st(e.message);break;case"task":try{rt[n](r),delete rt[n]}catch(t){throw delete rt[n],t}break;case"event":try{rt[n](r)}catch(t){throw t}break;default:console.log(t)}})),o.bLog=!!st,o.bd=at,o.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await $("core");let l=it++;rt[l]=t=>{if(t.success)Object.assign(lt,t.versions),"{}"!==JSON.stringify(t.versions)&&(gt._versions=t.versions),h.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),h.reject(e)}},et.postMessage({type:"loadWasm",body:o,id:l}),await h}))};class gt{static get engineResourcePaths(){return dt}static set engineResourcePaths(t){Object.assign(dt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return st}static set _onLog(t){ot(t)}static get _bDebug(){return at}static set _bDebug(t){ht(t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!Q[t]&&Q[t].isFulfilled}static async loadWasm(t){return await ft(t)}static async detectEnvironment(){return await(async()=>({wasm:q,worker:Z,getUserMedia:K,camera:await J(),browser:X.browser,version:X.version,OS:X.OS}))()}static async getModuleVersion(){return await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success)return t(i.versions);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"getModuleVersion",id:i})}))}static getVersion(){return`3.4.31(Worker: ${lt.core&<.core.worker||"Not Loaded"}, Wasm: ${lt.core&<.core.wasm||"Not Loaded"})`}static enableLogging(){z._onLog=console.log,gt._onLog=console.log}static disableLogging(){z._onLog=null,gt._onLog=null}static async cfd(t){return await new Promise(((e,i)=>{let n=nt();rt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cfd",id:n,body:{count:t}})}))}}var mt,pt,_t,vt,yt,wt,Ct,Et,St;gt._bSupportDce4Module=-1,gt._bSupportIRTModule=-1,gt._versions=null,gt._workerName="core.worker.js",gt.browserInfo=X,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_NORMALIZED_IMAGE=16]="CRIT_NORMALIZED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT"}(mt||(mt={})),function(t){t[t.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",t[t.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",t[t.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",t[t.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(pt||(pt={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_RESERVED_INFO_NOT_MATCH=-10040]="EC_RESERVED_INFO_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_REQUEST_FAILED=-10044]="EC_REQUEST_FAILED",t[t.EC_LICENSE_INIT_FAILED=-10045]="EC_LICENSE_INIT_FAILED",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_LICENSE_CONTENT_INVALID=-10052]="EC_LICENSE_CONTENT_INVALID",t[t.EC_LICENSE_KEY_INVALID=-10053]="EC_LICENSE_KEY_INVALID",t[t.EC_LICENSE_DEVICE_RUNS_OUT=-10054]="EC_LICENSE_DEVICE_RUNS_OUT",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_HANDSHAKE_CODE_INVALID=-20001]="EC_HANDSHAKE_CODE_INVALID",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_LICENSE_INIT_SEQUENCE_FAILED=-20009]="EC_LICENSE_INIT_SEQUENCE_FAILED",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_FAILED_TO_REACH_DLS=-20200]="EC_FAILED_TO_REACH_DLS",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_QR_LICENSE_INVALID=-30016]="EC_QR_LICENSE_INVALID",t[t.EC_1D_LICENSE_INVALID=-30017]="EC_1D_LICENSE_INVALID",t[t.EC_PDF417_LICENSE_INVALID=-30019]="EC_PDF417_LICENSE_INVALID",t[t.EC_DATAMATRIX_LICENSE_INVALID=-30020]="EC_DATAMATRIX_LICENSE_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_AZTEC_LICENSE_INVALID=-30041]="EC_AZTEC_LICENSE_INVALID",t[t.EC_PATCHCODE_LICENSE_INVALID=-30046]="EC_PATCHCODE_LICENSE_INVALID",t[t.EC_POSTALCODE_LICENSE_INVALID=-30047]="EC_POSTALCODE_LICENSE_INVALID",t[t.EC_DPM_LICENSE_INVALID=-30048]="EC_DPM_LICENSE_INVALID",t[t.EC_FRAME_DECODING_THREAD_EXISTS=-30049]="EC_FRAME_DECODING_THREAD_EXISTS",t[t.EC_STOP_DECODING_THREAD_FAILED=-30050]="EC_STOP_DECODING_THREAD_FAILED",t[t.EC_MAXICODE_LICENSE_INVALID=-30057]="EC_MAXICODE_LICENSE_INVALID",t[t.EC_GS1_DATABAR_LICENSE_INVALID=-30058]="EC_GS1_DATABAR_LICENSE_INVALID",t[t.EC_GS1_COMPOSITE_LICENSE_INVALID=-30059]="EC_GS1_COMPOSITE_LICENSE_INVALID",t[t.EC_DOTCODE_LICENSE_INVALID=-30061]="EC_DOTCODE_LICENSE_INVALID",t[t.EC_PHARMACODE_LICENSE_INVALID=-30062]="EC_PHARMACODE_LICENSE_INVALID",t[t.EC_CHARACTER_MODEL_FILE_NOT_FOUND=-40100]="EC_CHARACTER_MODEL_FILE_NOT_FOUND",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_ZA_DL_LICENSE_INVALID=-90006]="EC_ZA_DL_LICENSE_INVALID",t[t.EC_AAMVA_DL_ID_LICENSE_INVALID=-90007]="EC_AAMVA_DL_ID_LICENSE_INVALID",t[t.EC_AADHAAR_LICENSE_INVALID=-90008]="EC_AADHAAR_LICENSE_INVALID",t[t.EC_MRTD_LICENSE_INVALID=-90009]="EC_MRTD_LICENSE_INVALID",t[t.EC_VIN_LICENSE_INVALID=-90010]="EC_VIN_LICENSE_INVALID",t[t.EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID=-90011]="EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID",t[t.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",t[t.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",t[t.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",t[t.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",t[t.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(_t||(_t={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV"}(vt||(vt={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV"}(yt||(yt={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(wt||(wt={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(Ct||(Ct={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(Et||(Et={})),function(t){t[t.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",t[t.CVS_PASSED=1]="CVS_PASSED",t[t.CVS_FAILED=2]="CVS_FAILED"}(St||(St={}));const Tt={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_DOWN_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_UP_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_NORMALIZED_IMAGES:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var bt,It;!function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_NORMALIZED_IMAGE=6]="ROET_NORMALIZED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI"}(bt||(bt={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_NORMALIZATION=7]="ST_DOCUMENT_NORMALIZATION"}(It||(It={}));var xt=Object.freeze({__proto__:null,CoreModule:gt,get EnumBufferOverflowProtectionMode(){return o},get EnumCapturedResultItemType(){return mt},get EnumColourChannelUsageType(){return a},get EnumCornerType(){return pt},get EnumCrossVerificationStatus(){return St},get EnumErrorCode(){return _t},get EnumGrayscaleEnhancementMode(){return vt},get EnumGrayscaleTransformationMode(){return yt},get EnumImagePixelFormat(){return h},get EnumImageTagType(){return wt},EnumIntermediateResultUnitType:Tt,get EnumPDFReadingMode(){return Ct},get EnumRasterDataSource(){return Et},get EnumRegionObjectElementType(){return bt},get EnumSectionType(){return It},ImageSourceAdapter:z,_getNorImageData:M,_saveToFile:R,_toBlob:L,_toCanvas:D,_toImage:(t,e)=>{y(e)&&(e=M(e));const i=D(e);let n=new Image,r=i.toDataURL(t);return n.src=r,n},get bDebug(){return at},checkIsLink:t=>/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t),compareVersion:O,doOrWaitAsyncDependency:tt,getNextTaskID:nt,handleEngineResourcePaths:A,innerVersions:lt,isArc:t=>!(!_(t)||!p(t.x)||!p(t.y)||!p(t.radius)||t.radius<0||!p(t.startAngle)||!p(t.endAngle)),isContour:t=>!!_(t)&&!!g(t.points)&&0!=t.points.length&&!t.points.some((t=>!S(t))),isDSImageData:y,isDSRect:w,isImageTag:C,isLineSegment:E,isObject:_,isOriginalDsImageData:t=>!(!v(t)||!p(t.bytes.length)&&!p(t.bytes.ptr)),isPoint:S,isPolygon:T,isQuad:b,isRect:I,loadWasm:ft,mapAsyncDependency:Q,mapPackageRegister:ct,mapTaskCallBack:rt,get onLog(){return st},requestResource:x,setBDebug:ht,setOnLog:ot,waitAsyncDependency:$,get worker(){return et},workerAutoResources:ut});let Ot="./";if(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))}Ot=t.substring(0,t.lastIndexOf("/")+1)}function At(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Rt(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}gt.engineResourcePaths={rootDirectory:(t=>{null==t&&(t="./");let e=document.createElement("a");return e.href=t,(t=e.href).endsWith("/")||(t+="/"),t})(Ot+"../../")},"function"==typeof SuppressedError&&SuppressedError;const Dt="undefined"==typeof self,Lt="function"==typeof importScripts,Mt=(()=>{if(!Lt){if(!Dt&&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"./"}})(),Ft=t=>{if(null==t&&(t="./"),Dt||Lt);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var Pt,kt,Bt;t.EnumScanMode=void 0,(Pt=t.EnumScanMode||(t.EnumScanMode={}))[Pt.SM_SINGLE=0]="SM_SINGLE",Pt[Pt.SM_MULTI_UNIQUE=1]="SM_MULTI_UNIQUE",t.EnumOptimizationMode=void 0,(kt=t.EnumOptimizationMode||(t.EnumOptimizationMode={}))[kt.OM_NONE=0]="OM_NONE",kt[kt.OM_SPEED=1]="OM_SPEED",kt[kt.OM_COVERAGE=2]="OM_COVERAGE",kt[kt.OM_BALANCE=3]="OM_BALANCE",kt[kt.OM_DPM=4]="OM_DPM",kt[kt.OM_DENSE=5]="OM_DENSE",t.EnumResultStatus=void 0,(Bt=t.EnumResultStatus||(t.EnumResultStatus={}))[Bt.RS_SUCCESS=0]="RS_SUCCESS",Bt[Bt.RS_CANCELLED=1]="RS_CANCELLED",Bt[Bt.RS_FAILED=2]="RS_FAILED";var Nt={license:"",scanMode:t.EnumScanMode.SM_SINGLE,templateFilePath:void 0,utilizedTemplateNames:{single:"ReadSingleBarcode",multi_unique:"ReadBarcodes_SpeedFirst",image:"ReadBarcodes_ReadRateFirst"},engineResourcePaths:{rootDirectory:Mt},barcodeFormats:void 0,duplicateForgetTime:3e3,container:void 0,onUniqueBarcodeScanned:void 0,showResultView:!1,showUploadImageButton:!1,removePoweredByMessage:!1,uiPath:Mt,scannerViewConfig:{container:void 0,showCloseButton:!1},resultViewConfig:{container:void 0,toolbarButtonsConfig:{clear:{label:"Clear",className:"btn-clear",isHidden:!1},done:{label:"Done",className:"btn-done",isHidden:!1}}}};const jt=t=>t&&"object"==typeof t&&"function"==typeof t.then,Ut=(async()=>{})().constructor;let Vt=class extends Ut{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,jt(t)?e=t:"function"==typeof t&&(e=new Ut(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}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(jt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};function Gt(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Wt(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const Yt=t=>t&&"object"==typeof t&&"function"==typeof t.then,Ht=(async()=>{})().constructor;class Xt extends Ht{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,Yt(t)?e=t:"function"==typeof t&&(e=new Ht(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}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(Yt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class zt{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success)return t(i.count);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})}))}async setMaxBufferedItems(t){return await new Promise(((e,i)=>{let n=nt();rt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_setMaxBufferedItems",id:n,instanceID:this._cvr._instanceID,body:{count:t}})}))}async getBufferedCharacterItemSet(){return await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success)return t(i.itemSet);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})}))}}var qt={onTaskResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onColourImageUnitReceived:!1,onScaledDownColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledUpBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesReceived:!1};const Zt=t=>{for(let e in t._irrRegistryState)t._irrRegistryState[e]=!1;for(let e of t._intermediateResultReceiverSet)if(e.isDce||e.isFilter)t._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let i in e)t._irrRegistryState[i]||(t._irrRegistryState[i]=!!e[i])};class Kt{constructor(t){this._irrRegistryState=qt,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),Zt(this);let e=-1,i={};if(!t.isDce&&!t.isFilter){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach(((t,e)=>{i[e]=t})),t._observedTaskMap.clear()}return await new Promise(((t,n)=>{let r=nt();rt[r]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},et.postMessage({type:"cvr_setIrrRegistry",id:r,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})}))}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),Zt(this),await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})}))}getOriginalImage(){return this._cvr._dsImage}}const Jt="undefined"==typeof self,Qt="function"==typeof importScripts,$t=(()=>{if(!Qt){if(!Jt&&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"./"}})(),te=t=>{if(null==t&&(t="./"),Jt||Qt);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var ee;gt.engineResourcePaths.cvr={version:"2.4.33",path:$t,isInternal:!0},ut.cvr={js:!0,wasm:!0,deps:["license","dip"]},ct.cvr={};const ie="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&O(gt.engineResourcePaths.std.version,ie)<0&&(gt.engineResourcePaths.std={version:ie,path:te($t+`../../dynamsoft-capture-vision-std@${ie}/dist/`),isInternal:!0});const ne="2.4.31";(!gt.engineResourcePaths.dip||"string"!=typeof gt.engineResourcePaths.dip&&O(gt.engineResourcePaths.dip.version,ne)<0)&&(gt.engineResourcePaths.dip={version:ne,path:te($t+`../../dynamsoft-image-processing@${ne}/dist/`),isInternal:!0});class re{static getVersion(){return this._version}}re._version=`2.4.33(Worker: ${null===(ee=lt.cvr)||void 0===ee?void 0:ee.worker}, Wasm: loading...`;const se={barcodeResultItems:{type:mt.CRIT_BARCODE,reveiver:"onDecodedBarcodesReceived",isNeedFilter:!0},textLineResultItems:{type:mt.CRIT_TEXT_LINE,reveiver:"onRecognizedTextLinesReceived",isNeedFilter:!0},detectedQuadResultItems:{type:mt.CRIT_DETECTED_QUAD,reveiver:"onDetectedQuadsReceived",isNeedFilter:!1},normalizedImageResultItems:{type:mt.CRIT_NORMALIZED_IMAGE,reveiver:"onNormalizedImagesReceived",isNeedFilter:!1},parsedResultItems:{type:mt.CRIT_PARSED_RESULT,reveiver:"onParsedResultsReceived",isNeedFilter:!1}};var oe,ae,he,le,ce,ue,de,fe,ge,me,pe,_e,ve;function ye(t,e){if(t&&t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;ye(t.referencedItem,e)}}function we(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}!function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(oe||(oe={}));const Ce={onTaskResultsReceived:()=>{},isFilter:!0};class Ee{constructor(){this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(gt.browserInfo.OS)?2048:4096,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,ae.set(this,null),he.set(this,null),le.set(this,null),ce.set(this,null),ue.set(this,null),de.set(this,new Set),fe.set(this,new Set),ge.set(this,new Set),me.set(this,0),pe.set(this,!1),_e.set(this,!1),ve.set(this,!1),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return Gt(this,ve,"f")}static async createInstance(){if(!ct.license)throw Error("Module `license` is not existed.");await ct.license.dynamsoft(),await ft(["cvr"]);const t=new Ee,e=new Xt;let i=nt();return rt[i]=async i=>{var n;if(i.success)t._instanceID=i.instanceID,t._currentSettings=JSON.parse(JSON.parse(i.outputSettings).data),re._version=`2.4.33(Worker: ${null===(n=lt.cvr)||void 0===n?void 0:n.worker}, Wasm: ${i.version})`,Wt(t,_e,!0,"f"),Wt(t,ce,t.getIntermediateResultManager(),"f"),Wt(t,_e,!1,"f"),e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},et.postMessage({type:"cvr_createInstance",id:i}),e}async _singleFrameModeCallback(t){for(let e of Gt(this,de,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:t});const e={bytes:new Uint8Array(t.bytes),width:t.width,height:t.height,stride:t.stride,format:t.format,tag:t.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(e,this._templateName);i.originalImageTag=t.tag;const n={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of Gt(this,de,"f"))if(t.isDce)t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1});else{for(let e in se){const r=e,s=se[r];t[s.reveiver]&&i[r]&&t[s.reveiver](Object.assign(Object.assign({},n),{[r]:i[r]}))}t.onCapturedResultReceived&&t.onCapturedResultReceived(i)}}setInput(t){if(we(this),t){if(Wt(this,ae,t,"f"),t.isCameraEnhancer){Gt(this,ce,"f")&&(Gt(this,ae,"f")._intermediateResultReceiver.isDce=!0,Gt(this,ce,"f").addResultReceiver(Gt(this,ae,"f")._intermediateResultReceiver));const t=Gt(this,ae,"f").getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,Gt(this,de,"f").add(e)}}}else Wt(this,ae,null,"f")}getInput(){return Gt(this,ae,"f")}addImageSourceStateListener(t){if(we(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&Gt(this,fe,"f").add(t)}removeImageSourceStateListener(t){return we(this),Gt(this,fe,"f").delete(t)}addResultReceiver(t){if(we(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(Gt(this,de,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){we(this),Gt(this,de,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onParsedResultsReceived:!1};for(let e of Gt(this,de,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onDetectedQuadsReceived=!!e.onDetectedQuadsReceived,t.onNormalizedImagesReceived=!!e.onNormalizedImagesReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new Xt;let i=nt();return rt[i]=async t=>{if(t.success)e.resolve();else{let i=new Error(t.message);i.stack=t.stack+"\n"+i.stack,e.reject()}},et.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(we(this),!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");Gt(this,ge,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){we(this),Gt(this,ge,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(Gt(this,ce,"f").removeResultReceiver(Ce),0===Gt(this,ge,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[mt.CRIT_BARCODE]:!1,[mt.CRIT_TEXT_LINE]:!1,[mt.CRIT_DETECTED_QUAD]:!1,[mt.CRIT_NORMALIZED_IMAGE]:!1},e={[mt.CRIT_BARCODE]:!1,[mt.CRIT_TEXT_LINE]:!1,[mt.CRIT_DETECTED_QUAD]:!1,[mt.CRIT_NORMALIZED_IMAGE]:!1};return await Se(this,t),void await Te(this,e)}for(let t of Gt(this,ge,"f")){if(this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(mt.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(mt.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(mt.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(mt.CRIT_NORMALIZED_IMAGE),t.isLatestOverlappingEnabled(mt.CRIT_BARCODE)){[...Gt(this,ce,"f")._intermediateResultReceiverSet.values()].find((t=>t.isFilter))||Gt(this,ce,"f").addResultReceiver(Ce)}await Se(this,t.verificationEnabled),await Te(this,t.duplicateFilterEnabled),await be(this,t.duplicateForgetTime)}}async startCapturing(t){var e,i;if(we(this),!this._isPauseScan)return;if(!Gt(this,ae,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");t||(t=Ee._defaultTemplate);const n=await this.containsTask(t);await ft(n);for(let t of Gt(this,ge,"f"))await this.addResultFilter(t);if(n.includes("dlr")&&!(null===(e=ct.dlr)||void 0===e?void 0:e.bLoadConfusableCharsData)){const t=A(gt.engineResourcePaths);await(null===(i=ct.dlr)||void 0===i?void 0:i.loadRecognitionData("ConfusableChars",t.dlr))}if(Gt(this,ae,"f").isCameraEnhancer&&(n.includes("ddn")?Gt(this,ae,"f").setPixelFormat(h.IPF_ABGR_8888):Gt(this,ae,"f").setPixelFormat(h.IPF_GRAYSCALED)),void 0!==Gt(this,ae,"f").singleFrameMode&&"disabled"!==Gt(this,ae,"f").singleFrameMode)return this._templateName=t,void Gt(this,ae,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind);return Gt(this,ae,"f").getColourChannelUsageType()===a.CCUT_AUTO&&Gt(this,ae,"f").setColourChannelUsageType(n.includes("ddn")?a.CCUT_FULL_CHANNEL:a.CCUT_Y_CHANNEL_ONLY),Gt(this,le,"f")&&Gt(this,le,"f").isPending?Gt(this,le,"f"):(Wt(this,le,new Xt(((e,i)=>{if(this.disposed)return;let n=nt();rt[n]=async n=>{if(Gt(this,le,"f")&&!Gt(this,le,"f").isFulfilled){if(!n.success){let t=new Error(n.message);return t.stack=n.stack+"\n"+t.stack,i(t)}this._isPauseScan=!1,this._isOutputOriginalImage=n.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((async()=>{-1!==this._minImageCaptureInterval&&Gt(this,ae,"f").startFetching(),this._loopReadVideo(t),e()}),0)}},et.postMessage({type:"cvr_startCapturing",id:n,instanceID:this._instanceID,body:{templateName:t}})})),"f"),await Gt(this,le,"f"))}stopCapturing(){we(this),Gt(this,ae,"f")&&(Gt(this,ae,"f").isCameraEnhancer&&void 0!==Gt(this,ae,"f").singleFrameMode&&"disabled"!==Gt(this,ae,"f").singleFrameMode?Gt(this,ae,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(!async function(t){let e=nt();const i=new Xt;rt[e]=async t=>{if(t.success)return i.resolve();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i.reject(e)}},et.postMessage({type:"cvr_clearVerifyList",id:e,instanceID:t._instanceID})}(this),Gt(this,ae,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,Wt(this,le,null,"f"),Gt(this,ae,"f").setColourChannelUsageType(a.CCUT_AUTO)))}async containsTask(t){return we(this),await new Promise(((e,i)=>{let n=nt();rt[n]=async t=>{if(t.success)return e(JSON.parse(t.tasks));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_containsTask",id:n,instanceID:this._instanceID,body:{templateName:t}})}))}async _loopReadVideo(t){if(this.disposed||this._isPauseScan)return;if(Wt(this,pe,!0,"f"),Gt(this,ae,"f").isBufferEmpty())if(Gt(this,ae,"f").hasNextImageToFetch())for(let t of Gt(this,fe,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(oe.ISS_BUFFER_EMPTY);else if(!Gt(this,ae,"f").hasNextImageToFetch())for(let t of Gt(this,fe,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(oe.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||Gt(this,ae,"f").isBufferEmpty())try{Gt(this,ae,"f").isBufferEmpty()&&Ee._onLog&&Ee._onLog("buffer is empty so fetch image"),Ee._onLog&&Ee._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=Gt(this,ae,"f").fetchImage(),Ee._onLog&&Ee._onLog(`DCE: finish fetching a frame: ${Date.now()}`),Gt(this,ae,"f").setImageFetchInterval(this._averageTime)}catch(e){return void this._reRunCurrnetFunc(t)}else if(Gt(this,ae,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=Gt(this,ae,"f").getImage(),this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(t);if(!this._dsImage)return void this._reRunCurrnetFunc(t);for(let t of Gt(this,de,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const e=Date.now();this._captureDsimage(this._dsImage,t).then((async i=>{if(Ee._onLog&&Ee._onLog("no js handle time: "+(Date.now()-e)),this._isPauseScan)return void this._reRunCurrnetFunc(t);i.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;const n={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of Gt(this,de,"f"))if(t.isDce){const e=Date.now();if(t.onCapturedResultReceived(i,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify}),Ee._onLog){const t=Date.now()-e;t>10&&Ee._onLog(`draw result time: ${t}`)}}else{for(let e in se){const r=e,s=se[r];t[s.reveiver],t[s.reveiver]&&i[r]&&t[s.reveiver](Object.assign(Object.assign({},n),{[r]:i[r].filter((t=>!s.isNeedFilter||!t.isFilter))})),i[r]&&(i[r]=i[r].filter((t=>!s.isNeedFilter||!t.isFilter)))}t.onCapturedResultReceived&&(i.items=i.items.filter((t=>[mt.CRIT_DETECTED_QUAD,mt.CRIT_NORMALIZED_IMAGE].includes(t.type)||!t.isFilter)),t.onCapturedResultReceived(i))}const r=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-e),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,Ee._onLog&&(Ee._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),Ee._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),Ee._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),Ee._onLog(`averageTime: ${this._averageTime}`))),Ee._onLog){const t=Date.now()-r;t>10&&Ee._onLog(`fetch image calculate time: ${t}`)}Ee._onLog&&Ee._onLog(`time finish decode: ${Date.now()}`),Ee._onLog&&Ee._onLog("main time: "+(Date.now()-e)),Ee._onLog&&Ee._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,0))})).catch((e=>{Gt(this,ae,"f").stopFetching(),e.errorCode&&0===e.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{Gt(this,ae,"f").startFetching(),this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,1e3))),"platform error"!==e.message&&setTimeout((()=>{throw e}),0)}))}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),0)}async capture(t,e){var i,n;we(this),e||(e=Ee._defaultTemplate);const r=await this.containsTask(e);if(await ft(r),r.includes("dlr")&&!(null===(i=ct.dlr)||void 0===i?void 0:i.bLoadConfusableCharsData)){const t=A(gt.engineResourcePaths);await(null===(n=ct.dlr)||void 0===n?void 0:n.loadRecognitionData("ConfusableChars",t.dlr))}let s;if(Wt(this,pe,!1,"f"),y(t))s=await this._captureDsimage(t,e);else if("string"==typeof t)s="data:image/"==t.substring(0,11)?await this._captureBase64(t,e):await this._captureUrl(t,e);else if(t instanceof Blob)s=await this._captureBlob(t,e);else if(t instanceof HTMLImageElement)s=await this._captureImage(t,e);else if(t instanceof HTMLCanvasElement)s=await this._captureCanvas(t,e);else{if(!(t instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");s=await this._captureVideo(t,e)}return s}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await x(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),n=i.length,r=new Uint8Array(n);for(;n--;)r[n]=i.charCodeAt(n);return await this._captureBlob(new Blob([r]),e)}async _captureBlob(t,e){let i=null,n=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(n=await async function(t){return await new Promise(((e,i)=>{let n=URL.createObjectURL(t),r=new Image;r.src=n,r.onload=()=>{URL.revokeObjectURL(r.dbrObjUrl),e(r)},r.onerror=t=>{i(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))}(t));let r=await this._captureImage(i||n,e);return i&&i.close(),r}async _captureImage(t,e){let i,n,r=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(r,s);o>this.maxImageSideLength?(Wt(this,me,this.maxImageSideLength/o,"f"),i=Math.round(r*Gt(this,me,"f")),n=Math.round(s*Gt(this,me,"f"))):(i=r,n=s),Gt(this,he,"f")||Wt(this,he,document.createElement("canvas"),"f");const a=Gt(this,he,"f");a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),n={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(n,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,n,r=t.videoWidth,s=t.videoHeight,o=Math.max(r,s);o>this.maxImageSideLength?(Wt(this,me,this.maxImageSideLength/o,"f"),i=Math.round(r*Gt(this,me,"f")),n=Math.round(s*Gt(this,me,"f"))):(i=r,n=s),Gt(this,he,"f")||Wt(this,he,document.createElement("canvas"),"f");const a=Gt(this,he,"f");a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),await this._captureCanvas(a,e)}async _captureInWorker(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=t;let a=nt();const h=new Xt;return rt[a]=async e=>{var i,n;if(!e.success){let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h.reject(t)}{const r=Date.now();Ee._onLog&&(Ee._onLog(`get result time from worker: ${r}`),Ee._onLog("worker to main time consume: "+(r-e.workerReturnMsgTime)));try{const r=e.captureResult;if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,h.reject(t)}t.bytes=e.bytes;for(let e of r.items)0!==Gt(this,me,"f")&&ye(e,Gt(this,me,"f")),e.type===mt.CRIT_ORIGINAL_IMAGE?e.imageData=t:e.type===mt.CRIT_NORMALIZED_IMAGE?null===(i=ct.ddn)||void 0===i||i.handleNormalizedImageResultItem(e):e.type===mt.CRIT_PARSED_RESULT&&(null===(n=ct.dcp)||void 0===n||n.handleParsedResultItem(e));if(Gt(this,pe,"f"))for(let t of Gt(this,ge,"f"))t.onDecodedBarcodesReceived(r),t.onRecognizedTextLinesReceived(r),t.onDetectedQuadsReceived(r),t.onNormalizedImagesReceived(r);for(let t in se){const e=t,i=r.items.filter((t=>t.type===se[e].type));i.length&&(r[t]=i)}if(!this._isPauseScan||!Gt(this,pe,"f")){const e=r.intermediateResult;if(e){let i=0;for(let n of Gt(this,ce,"f")._intermediateResultReceiverSet){i++;for(let r of e){if("onTaskResultsReceived"===r.info.callbackName){for(let e of r.intermediateResultUnits)e.originalImageTag=t.tag?t.tag:null;n[r.info.callbackName]&&n[r.info.callbackName]({intermediateResultUnits:r.intermediateResultUnits},r.info)}else n[r.info.callbackName]&&n[r.info.callbackName](r.result,r.info);i===Gt(this,ce,"f")._intermediateResultReceiverSet.size&&delete r.info.callbackName}}}}return r&&r.hasOwnProperty("intermediateResult")&&delete r.intermediateResult,Wt(this,me,0,"f"),h.resolve(r)}catch(t){return h.reject(t)}}},Ee._onLog&&Ee._onLog(`send buffer to worker: ${Date.now()}`),et.postMessage({type:"cvr_capture",id:a,instanceID:this._instanceID,body:{bytes:i,width:n,height:r,stride:s,format:o,templateName:e||"",isScanner:Gt(this,pe,"f")}},[i.buffer]),h}async initSettings(t){return we(this),t&&["string","object"].includes(typeof t)?("string"==typeof t?t.trimStart().startsWith("{")||(t=await x(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise(((e,i)=>{let n=nt();rt[n]=async n=>{if(n.success){const r=JSON.parse(n.response);if(0!==r.errorCode){let t=new Error(r.errorString?r.errorString:"Init Settings Failed.");return t.errorCode=r.errorCode,i(t)}const s=JSON.parse(t);this._currentSettings=s;let o=[],a=s.CaptureVisionTemplates;for(let t=0;t{let n=nt();rt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,i(t)}return e(JSON.parse(n.data))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_outputSettings",id:n,instanceID:this._instanceID,body:{templateName:t||"*"}})}))}async outputSettingsToFile(t,e,i){const n=await this.outputSettings(t),r=new Blob([JSON.stringify(n,null,2,(function(t,e){return e instanceof Array?JSON.stringify(e):e}),2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(r),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout((()=>{URL.revokeObjectURL(t.href)}),500)},t.click()}return r}async getTemplateNames(){return we(this),await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,e(t)}return t(JSON.parse(n.data))}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})}))}async getSimplifiedSettings(t){we(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const e=await this.containsTask(t);return await ft(e),await new Promise(((e,i)=>{let n=nt();rt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,i(t)}const r=JSON.parse(n.data,((t,e)=>"barcodeFormatIds"===t?BigInt(e):e));return r.minImageCaptureInterval=this._minImageCaptureInterval,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_getSimplifiedSettings",id:n,instanceID:this._instanceID,body:{templateName:t}})}))}async updateSettings(t,e){we(this);const i=await this.containsTask(t);return await ft(i),await new Promise(((i,n)=>{let r=nt();rt[r]=async t=>{if(t.success){const r=JSON.parse(t.response);if(e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==r.errorCode){let t=new Error(r.errorString?r.errorString:"Update Settings Failed.");return t.errorCode=r.errorCode,n(t)}return this._currentSettings=await this.outputSettings("*"),i(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},et.postMessage({type:"cvr_updateSettings",id:r,instanceID:this._instanceID,body:{settings:e,templateName:t}})}))}async resetSettings(){return we(this),await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Reset Settings Failed.");return t.errorCode=n.errorCode,e(t)}return this._currentSettings=await this.outputSettings("*"),t(n)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})}))}getBufferedItemsManager(){return Gt(this,ue,"f")||Wt(this,ue,new zt(this),"f"),Gt(this,ue,"f")}getIntermediateResultManager(){if(we(this),!Gt(this,_e,"f")&&0!==gt.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return Gt(this,ce,"f")||Wt(this,ce,new Kt(this),"f"),Gt(this,ce,"f")}async parseRequiredResources(t){return we(this),await new Promise(((e,i)=>{let n=nt();rt[n]=async t=>{if(t.success)return e(JSON.parse(t.resources));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_parseRequiredResources",id:n,instanceID:this._instanceID,body:{templateName:t}})}))}async dispose(){we(this),Gt(this,le,"f")&&this.stopCapturing(),Wt(this,ae,null,"f"),Gt(this,de,"f").clear(),Gt(this,fe,"f").clear(),Gt(this,ge,"f").clear(),Gt(this,ce,"f")._intermediateResultReceiverSet.clear(),Wt(this,ve,!0,"f");let t=nt();rt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},et.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:Gt(this,ae,"f"),promiseStartScan:Gt(this,le,"f"),intermediateResultManager:Gt(this,ce,"f"),bufferdItemsManager:Gt(this,ue,"f"),resultReceiverSet:Gt(this,de,"f"),isaStateListenerSet:Gt(this,fe,"f"),resultFilterSet:Gt(this,ge,"f"),compressRate:Gt(this,me,"f"),canvas:Gt(this,he,"f"),isScanner:Gt(this,pe,"f"),innerUseTag:Gt(this,_e,"f"),isDestroyed:Gt(this,ve,"f")}}async _getWasmFilterState(){return await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})}))}}async function Se(t,e){return we(t),await new Promise(((i,n)=>{let r=nt();rt[r]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},et.postMessage({type:"cvr_enableResultCrossVerification",id:r,instanceID:t._instanceID,body:{verificationEnabled:e}})}))}async function Te(t,e){return we(t),await new Promise(((i,n)=>{let r=nt();rt[r]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},et.postMessage({type:"cvr_enableResultDeduplication",id:r,instanceID:t._instanceID,body:{duplicateFilterEnabled:e}})}))}async function be(t,e){return we(t),await new Promise(((i,n)=>{let r=nt();rt[r]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},et.postMessage({type:"cvr_setDuplicateForgetTime",id:r,instanceID:t._instanceID,body:{duplicateForgetTime:e}})}))}ae=new WeakMap,he=new WeakMap,le=new WeakMap,ce=new WeakMap,ue=new WeakMap,de=new WeakMap,fe=new WeakMap,ge=new WeakMap,me=new WeakMap,pe=new WeakMap,_e=new WeakMap,ve=new WeakMap,Ee._defaultTemplate="Default";class Ie{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}}var xe;!function(t){t.PT_DEFAULT="Default",t.PT_READ_BARCODES="ReadBarcodes_Default",t.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",t.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",t.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",t.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",t.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",t.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",t.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",t.PT_READ_SINGLE_BARCODE="ReadBarcodes_Balanced",t.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",t.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",t.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",t.PT_RECOGNIZE_LETTERS="RecognizeLetters",t.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",t.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",t.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters"}(xe||(xe={}));var Oe=Object.freeze({__proto__:null,CaptureVisionRouter:Ee,CaptureVisionRouterModule:re,CapturedResultReceiver:Ie,get EnumImageSourceState(){return oe},get EnumPresetTemplate(){return xe},IntermediateResultReceiver:class{constructor(){this._observedResultUnitTypes=Tt.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledDownColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}}});const Ae="undefined"==typeof self,Re="function"==typeof importScripts,De=(()=>{if(!Re){if(!Ae&&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"./"}})();gt.engineResourcePaths.dce={version:"4.1.1",path:De,isInternal:!0},ut.dce={wasm:!1,js:!1},ct.dce={};let Le,Me,Fe,Pe,ke;function Be(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Ne(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(Le=navigator,Me=Le.userAgent,Fe=Le.platform,Pe=Le.mediaDevices),function(){if(!Ae){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Le.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Fe,search:"Win"},Mac:{str:Fe},Linux:{str:Fe}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||Me,o=r.search||e,a=r.verStr||Me,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Me,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=Me.indexOf("Windows NT")&&(r="HarmonyOS"),ke={browser:i,version:n,OS:r}}Ae&&(ke={browser:"ssr",version:0,OS:"ssr"})}();const je="undefined"!=typeof WebAssembly&&Me&&!(/Safari/.test(Me)&&!/Chrome/.test(Me)&&/\(.+\s11_2_([2-6]).*\)/.test(Me)),Ue=!("undefined"==typeof Worker),Ve=!(!Pe||!Pe.getUserMedia),Ge=async()=>{let t=!1;if(Ve)try{(await Pe.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===ke.browser&&ke.version>66||"Safari"===ke.browser&&ke.version>13||"OPR"===ke.browser&&ke.version>43||"Edge"===ke.browser&&ke.version;var We={653:(t,e,i)=>{var n,r,s,o,a,h,l,c,u,d,f,g,m,p,_,v,y,w,C,E,S,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 b=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=b.document,T.jsdomImplForWrapper=i(898).implForWrapper,T.nodeCanvas=i(245).Canvas,T.window=b,DOMParser=T.window.DOMParser}function I(t,e){var i=t.canvas,n=e.targetCanvas,r=n.getContext("2d");r.translate(0,n.height),r.scale(1,-1);var s=i.height-n.height;r.drawImage(i,0,s,n.width,n.height,0,0,n.width,n.height)}function x(t,e){var i=e.targetCanvas.getContext("2d"),n=e.destinationWidth,r=e.destinationHeight,s=n*r*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,n,r);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 n=0,r=i.length;n-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]}},n=e,r=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 n=new T.Point(t.x-e.x,t.y-e.y),r=T.util.rotateVector(n,i);return new T.Point(r.x,r.y).addEquals(e)},rotateVector:function(t,e){var i=T.util.sin(e),n=T.util.cos(e);return{x:t.x*n-t.y*i,y:t.x*i+t.y*n}},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 n=T.util.createVector(t,e),r=T.util.createVector(t,i),s=T.util.calcAngleBetweenVectors(n,r),o=s*(0===T.util.calcAngleBetweenVectors(T.util.rotateVector(n,s),r)?1:-1)/2;return{vector:T.util.getHatVector(T.util.rotateVector(n,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var n=[],r=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=r/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),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-r/Math.sin(p/2),f=new T.Point(m.x*d*s.x,m.y*d*s.y),Math.hypot(f.x,f.y)/r<=e.strokeMiterLimit))return n.push(u.add(f)),void n.push(u.subtract(f));d=-r*Math.SQRT2,f=new T.Point(m.x*d*s.x,m.y*d*s.y),n.push(u.add(f)),n.push(u.subtract(f))})),n},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>n?e-=n:e=0,i>n?i-=n:i=0);var r,s=!0,o=t.getImageData(e,i,2*n||1,2*n||1),a=o.data.length;for(r=3;r=r?s-r:2*Math.PI-(r-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,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,C=_*v-_*y-v*w,E=0;if(C<0){var S=Math.sqrt(1-C/(_*v));i*=S,s*=S}else E=(o===a?-1:1)*Math.sqrt(C/(_*y+v*w));var b=E*i*p/s,I=-E*s*m/i,x=d*b-u*I+.5*t,O=u*b+d*I+.5*e,A=r(1,0,(m-b)/i,(p-I)/s),R=r((m-b)/i,(p-I)/s,(-m-b)/i,(-p-I)/s);0===a&&R>0?R-=2*l:1===a&&R<0&&(R+=2*l);for(var D=Math.ceil(Math.abs(R/l*2)),L=[],M=R/D,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=A+M,k=0;kE)for(var b=1,I=m.length;b2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:r.x===t[i-2].x?0:-1,h=r.y>t[i-2].y?1:r.y===t[i-2].y?0:-1),n.push(["L",r.x+a*e,r.y+h*e]),n},T.util.getPathSegmentsInfo=d,T.util.getBoundsOfCurve=function(e,i,n,r,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,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,C=Math.abs,E=[],S=[[],[]];u=6*e-12*n+6*s,c=-3*e+9*n-9*s+3*a,d=3*n-3*e;for(var b=0;b<2;++b)if(b>0&&(u=6*i-12*r+6*o,c=-3*i+9*r-9*o+3*h,d=3*r-3*i),C(c)<1e-12){if(C(u)<1e-12)continue;0<(f=-d/u)&&f<1&&E.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&E.push(g),0<(m=(-u-_)/(2*c))&&m<1&&E.push(m));for(var I,x,O,A=E.length,R=A;A--;)I=(O=1-(f=E[A]))*O*O*e+3*O*O*f*n+3*O*f*f*s+f*f*f*a,S[0][A]=I,x=O*O*O*i+3*O*O*f*r+3*O*f*f*o+f*f*f*h,S[1][A]=x;S[0][R]=e,S[1][R]=i,S[0][R+1]=a,S[1][R+1]=h;var D=[{x:y.apply(null,S[0]),y:y.apply(null,S[1])},{x:w.apply(null,S[0]),y:w.apply(null,S[1])}];return T.cachesBoundsOfCurve&&(T.boundsOfCurveCache[l]=D),D},T.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var n=0;e-i[n].length>0&&n1e-4;)i=h(s),r=s,(n=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=n);return i.angle=u(r),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),n={},r=1;r=e}))}}}(),function(){function t(e,i,n){if(n)if(!T.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var r=0,s=i.length;r57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var n=t.charCodeAt(e+1);if(56320>n||n>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 r=t.charCodeAt(e-1);if(55296>r||r>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,n=0,r=[];for(n=0;n-1?t.prototype[r]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=n;var r=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return r}}(r):t.prototype[r]=e[r],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function r(){}function s(e){for(var i=null,n=this;n.constructor.superclass;){var r=n.constructor.superclass.prototype[e];if(n[e]!==r){i=r;break}n=n.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&&(r.prototype=i.prototype,a.prototype=new r,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*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=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?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var n in e)"opacity"===n?m(t,e[n]):i["float"===n||"cssFloat"===n?void 0===i.styleFloat?"cssFloat":"styleFloat":n]=e[n];return t},function(){var t,e,i,n,r=Array.prototype.slice,s=function(t){return r.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 n in e)"class"===n?i.className=e[n]:"for"===n?i.htmlFor=e[n]:i.setAttribute(n,e[n]);return i}function a(t){for(var e=0,i=0,n=T.document.documentElement,r=T.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===T.document?(e=r.scrollLeft||n.scrollLeft||0,i=r.scrollTop||n.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,n="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),n?t.style[n]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},T.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),n?t.style[n]="":"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,n,r=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!r)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=r.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),n=a(t),{left:s.left+n.left-(i.clientLeft||0)+o.left,top:s.top+n.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 n=i.method?i.method.toUpperCase():"GET",r=i.onComplete||function(){},s=new T.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(r(s),s.onreadystatechange=t)},"GET"===n&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(n,e,!0),"POST"!==n&&"PUT"!==n||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 n(){return!1}function r(t,e,i,n){return-i*Math.cos(t/n*(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||n,f=i.abort||n,g=i.onComplete||n,m=i.easing||r,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map((function(t,e){return v[e]-_[e]})):v-_);i.onStart&&i.onStart(),function t(i){var n=(e=i||+new Date)>u?c:e-l,r=n/c,w=p?_.map((function(t,e){return m(n,_[e],y[e],c)})):m(n,_,y,c),C=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=C,s.durationRate=r,!o){if(!f(w,C,r))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(w,C,r),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 n="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(n+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}T.util.animateColor=function(e,i,n,r){var s=new T.Color(e).getSource(),o=new T.Color(i).getSource(),a=r.onComplete,h=r.onChange;return r=r||{},T.util.animate(T.util.object.extend(r,{duration:n||500,startValue:s,endValue:o,byValue:o,easing:function(e,i,n,s){return t(i,n,r.colorEasing?r.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,n){if(a)return a(t(o,o,0),i,n)},onChange:function(e,i,n){if(h){if(Array.isArray(e))return h(t(e,e,0),i,n);h(e,i,n)}}}))}}(),function(){function t(t,e,i,n){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,r)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,n,r,s,o=[];for(r=0,s=e.length;r1;)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,n,r,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,C={},E="",S=0,T=0;if(C.width=0,C.height=0,C.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+E,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return C;if(_)return C.width=s(d),C.height=s(f),C;if(i=-parseFloat(l[1]),n=-parseFloat(l[2]),r=parseFloat(l[3]),o=parseFloat(l[4]),C.minX=i,C.minY=n,C.viewBoxWidth=r,C.viewBoxHeight=o,y?(C.width=r,C.height=o):(C.width=s(d),C.height=s(f),c=C.width/r,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),S=C.width-r*c,T=C.height-o*c,"Mid"===p.alignX&&(S/=2),"Mid"===p.alignY&&(T/=2),"Min"===p.alignX&&(S=0),"Min"===p.alignY&&(T=0)),1===c&&1===u&&0===i&&0===n&&0===g&&0===m)return C;if((g||m)&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") "),a=E+" matrix("+c+" 0 0 "+u+" "+(i*c+S)+" "+(n*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 w(t,e){var i="xlink:href",n=_(t,e.getAttribute(i).slice(1));if(n&&n.getAttribute(i)&&w(t,n),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(t){n&&!e.hasAttribute(t)&&n.hasAttribute(t)&&e.setAttribute(t,n.getAttribute(t))})),!e.children.length)for(var r=n.cloneNode(!0);r.firstChild;)e.appendChild(r.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,r,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),n=0;i.length&&nt.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,n,r,s){var o,a=(s.x-r.x)*(t.y-r.y)-(s.y-r.y)*(t.x-r.x),h=(n.x-t.x)*(t.y-r.y)-(n.y-t.y)*(t.x-r.x),l=(s.y-r.y)*(n.x-t.x)-(s.x-r.x)*(n.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*(n.x-t.x),t.y+c*(n.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,n){var r,s,o,a,h=new i,l=n.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var n,r=new i,s=t.length;for(n=0;n0&&(r.status="Intersection"),r},e.Intersection.intersectPolygonRectangle=function(t,n,r){var s=n.min(r),o=n.max(r),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 n(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,n){t/=255,i/=255,n/=255;var r,s,o,a=e.util.array.max([t,i,n]),h=e.util.array.min([t,i,n]);if(o=(a+h)/2,a===h)r=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:r=(i-n)/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 n=i.transform.target,r=n.canvas,s=e.util.object.clone(i);s.target=n,r&&r.fire("object:"+t,s),n.fire(t,i)}function m(t,e){var i=e.canvas,n=t[i.uniScaleKey];return i.uniformScaling&&!n||!i.uniformScaling&&n}function p(t){return t.originX===l&&t.originY===l}function _(t,e,i){var n=t.lockScalingX,r=t.lockScalingY;return!((!n||!r)&&(e||!n&&!r||!i)&&(!n||"x"!==e)&&(!r||"y"!==e))}function v(t,e,i,n){return{e:t,transform:e,pointer:{x:i,y:n}}}function y(t){return function(e,i,n,r){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,n,r);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function w(t,e){return function(i,n,r,s){var o=e(i,n,r,s);return o&&g(t,v(i,n,r,s)),o}}function C(t,i,n,r,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(r,s),i,n);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 E(t){return t.flipX!==t.flipY}function S(t,e,i,n,r){if(0!==t[e]){var s=r/t._getTransformedDimensions()[n]*t[i];t.set(i,s)}}function T(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=C(e,e.originX,e.originY,i,n),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?r=0:(r=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),E(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",r),S(l,"skewY","scaleY","y",p)}return m}function b(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=C(e,e.originX,e.originY,i,n),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?r=0:(r=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),E(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",r),S(l,"skewX","scaleX","x",p)}return m}function I(t,e,i,n,r){r=r||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=r.by,w=m(t,f),E=_(f,y,w),S=e.gestureScale;if(E)return!1;if(S)o=e.scaleX*S,a=e.scaleY*S;else{if(s=C(e,e.originX,e.originY,i,n),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(),w&&!y){var T=Math.abs(s.x)+Math.abs(s.y),b=e.original,I=T/(Math.abs(h.x*b.scaleX/f.scaleX)+Math.abs(h.y*b.scaleY/f.scaleY));o=b.scaleX*I,a=b.scaleY*I}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 x=f.scaleX,O=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)),x!==f.scaleX||O!==f.scaleY}r.scaleCursorStyleHandler=function(t,e,n){var r=m(t,n),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(n,s,r))return"not-allowed";var o=f(n,e);return i[o]+"-resize"},r.skewCursorStyleHandler=function(t,e,i){var r="not-allowed";if(0!==e.x&&i.lockSkewingY)return r;if(0!==e.y&&i.lockSkewingX)return r;var s=f(i,e)%4;return n[s]+"-resize"},r.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?r.skewCursorStyleHandler(t,e,i):r.scaleCursorStyleHandler(t,e,i)},r.rotationWithSnapping=w("rotating",y((function(t,e,i,n){var r=e,s=r.target,o=s.translateToOriginPoint(s.getCenterPoint(),r.originX,r.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(r.ey-o.y,r.ex-o.x),l=Math.atan2(n-o.y,i-o.x),c=u(l-h+r.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(r=u===o?s:a),c<0&&(r=u===o?a:s),E(h)&&(r=r===s?a:s)),e.originX=r,w("skewing",y(T))(t,e,i,n))},r.skewHandlerY=function(t,e,i,n){var r,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?r=C(e,l,l,i,n).y>0?o:h:(c>0&&(r=u===s?o:h),c<0&&(r=u===s?h:o),E(a)&&(r=r===o?h:o)),e.originY=r,w("skewing",y(b))(t,e,i,n))},r.dragHandler=function(t,e,i,n){var r=e.target,s=i-e.offsetX,o=n-e.offsetY,a=!r.get("lockMovementX")&&r.left!==s,h=!r.get("lockMovementY")&&r.top!==o;return a&&r.set("left",s),h&&r.set("top",o),(a||h)&&g("moving",v(t,e,i,n)),a||h},r.scaleOrSkewActionName=function(t,e,i){var n=t[i.canvas.altActionKey];return 0===e.x?n?"skewX":"scaleY":0===e.y?n?"skewY":"scaleX":void 0},r.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},r.fireEvent=g,r.wrapWithFixedAnchor=y,r.wrapWithFireEvent=w,r.getLocalPoint=C,e.controlsUtils=r}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,n=e.controlsUtils;n.renderCircleControl=function(t,e,i,n,r){n=n||{};var s,o=this.sizeX||n.cornerSize||r.cornerSize,a=this.sizeY||n.cornerSize||r.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:r.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||r.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=n.cornerColor||r.cornerColor,t.strokeStyle=n.cornerStrokeColor||r.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()},n.renderSquareControl=function(t,e,n,r,s){r=r||{};var o=this.sizeX||r.cornerSize||s.cornerSize,a=this.sizeY||r.cornerSize||s.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=r.cornerColor||s.cornerColor,t.strokeStyle=r.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,n),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,n,r,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),m=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(m),l=f*e.util.sin(m)}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:n-l,y:r-h},tr:{x:n+o,y:r-a},bl:{x:n-o,y:r+a},br:{x:n+l,y:r+h}}},render:function(t,i,n,r,s){"circle"===((r=r||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,n,r,s):e.controlsUtils.renderSquareControl.call(this,t,i,n,r,s)}}}(e),function(){function t(t,e){var i,n,r,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&&(r=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),r||(r=t.getAttribute("stop-opacity")),n=(i=new T.Color(i)).getAlpha(),r=isNaN(parseFloat(r))?1:parseFloat(r),r*=n*e,{offset:a,color:i.toRgb(),opacity:r}}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 n,r,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(),n=0,r=h.length;n0){var p=m/Math.max(a.r1,a.r2);for(n=0,r=h.length;n\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,n,r=T.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(r.x1,r.y1,r.x2,r.y2):"radial"===this.type&&(e=t.createRadialGradient(r.x1,r.y1,r.r1,r.x2,r.y2,r.r2)),i=0,n=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,m=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,n){var r,s;Object.keys(e).forEach((function(t){"Infinity"===(r=e[t])?s=1:"-Infinity"===r?s=0:(s=parseFloat(e[t],10),"string"==typeof r&&/^(\d+\.\d+)%|(\d+)%$/.test(r)&&(s*=.01,"pixels"===n&&("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,r,u),"pixels"===u&&(g=-i.left,m=-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,n){i.source=t,e&&e(i,n)}),null,this.crossOrigin)}},toObject:function(t){var e,i,n=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:_(this.offsetX,n),offsetY:_(this.offsetY,n),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,n=e.height/t.height,r=this.offsetX/t.width,s=this.offsetY/t.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(n=1,s&&(n+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,r&&(i+=Math.abs(r))),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(),n=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(n[1],10)||0,offsetY:parseFloat(n[2],10)||0,blur:parseFloat(n[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var n=40,r=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&&(n=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,r=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,n=T.util.toFixed,r=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,n){return"string"==typeof e?T.util.loadImage(e,(function(e,r){if(e){var s=new T.Image(e,n);this[t]=s,s.canvas=this}i&&i(e,r)}),this,n&&n.crossOrigin):(n&&e.setOptions(n),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 n in e=e||{},t)i=t[n],e.cssOnly||(this._setBackstoreDimension(n,t[n]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(n,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,n,r=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,n=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,r=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="'+n(-i[4]/i[0],a)+" "+n(-i[5]/i[3],a)+" "+n(this.width/i[0],a)+" "+n(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 n=t[e+"Vpt"],r=t.viewportTransform,s={width:t.width/(n?r[0]:1),height:t.height/(n?r[3]:1)};return i.toSVG(s,{additionalTransform:n?T.util.matrixToSVG(r):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,n,r,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,n,r,s=this._objects;for(n=0,r=s.length;n\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(r=s._objects).length;e--;)n=r[e],i(this._objects,n),this._objects.unshift(n);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(r=s._objects,e=0;e0+l&&(o=s-1,i(this._objects,r),this._objects.splice(o,0,r)),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 n,r;if(i){for(n=e,r=e-1;r>=0;--r)if(t.intersectsWithObject(this._objects[r])||t.isContainedWithinObject(this._objects[r])||this._objects[r].isContainedWithinObject(t)){n=r;break}}else n=e-1;return n},bringForward:function(t,e){if(!t)return this;var n,r,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(n=(a=h._objects).length;n--;)r=a[n],(s=this._objects.indexOf(r))"}}),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,n=t.getZoom();t&&t._isRetinaScaling()&&(n*=T.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*n,i.shadowOffsetX=e.offsetX*n,i.shadowOffsetY=e.offsetY*n}},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 n=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,n.x,n.y),n},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,n=i.length,r=this.canvas.contextTop;this._saveAndTransform(r),this.oldEnd&&(r.beginPath(),r.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(r,i[n-2],i[n-1],!0),r.stroke(),r.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,n=this._points[0],r=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&n.x===r.x&&n.y===r.y){var s=this.width/1e3;n=new T.Point(n.x,n.y),r=new T.Point(r.x,r.y),n.x-=s,r.x+=s}for(t.moveTo(n.x,n.y),e=1,i=this._points.length;e=r&&(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,n=this.points;for(this._saveAndTransform(i),t=0,e=n.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var r=0,s=this._objects.length;r1&&(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(),n=T.util.invertTransform(i),r=this.restorePointerVpt(e);return T.util.transformPoint(r,n)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var n=this._normalizePointer(t,{x:e,y:i}),r=Math.max(t.cacheTranslationX+n.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+n.y*t.zoomY,0);return T.util.isTransparent(t._cacheContext,Math.round(r),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(),n=this._activeObject;return!e||e&&n&&i.length>1&&-1===i.indexOf(e)&&n!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&n&&n!==e},_shouldCenterTransform:function(t,e,i){var n;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?n=this.centeredScaling||t.centeredScaling:"rotate"===e&&(n=this.centeredRotation||t.centeredRotation),n?!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,n){if(!e||!t)return"drag";var r=n.controls[e];return r.getActionName(i,r,n)},_setupCurrentTransform:function(t,i,n){if(i){var r=this.getPointer(t),s=i.__corner,o=i.controls[s],a=n&&s?o.getActionHandler(t,i,o):T.controlsUtils.dragHandler,h=this._getActionFromCorner(n,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:r.x-i.left,offsetY:r.y-i.top,originX:l.x,originY:l.y,ex:r.x,ey:r.y,lastX:r.x,lastY:r.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),n=T.util.transformPoint(i,this.viewportTransform),r=new T.Point(e.ex+e.left,e.ey+e.top),s=T.util.transformPoint(r,this.viewportTransform),o=Math.min(n.x,s.x),a=Math.min(n.y,s.y),h=Math.max(n.x,s.x),l=Math.max(n.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 n,r,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;n=o,r=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&n&&c!==n&&(c=n,this.targets=r),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,n,r=t.length;r--;){var s=t[r],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,s,e)){(i=t[r]).subTargetCheck&&i instanceof T.Group&&(n=this._searchPossibleTargets(i._objects,e))&&this.targets.push(n);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 n,r=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(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,i||(r=this.restorePointerVpt(r));var l=this.getRetinaScaling();return 1!==l&&(r.x/=l,r.y/=l),n=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:r.x*n.width,y:r.y*n.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,n=this.getActiveObjects(),r=[],s=[];t.forEach((function(t){-1===n.indexOf(t)&&(i=!0,t.fire("deselected",{e:e,target:t}),s.push(t))})),n.forEach((function(n){-1===t.indexOf(n)&&(i=!0,n.fire("selected",{e:e,target:n}),r.push(n))})),t.length>0&&n.length>0?i&&this.fire("selection:updated",{e:e,selected:r,deselected:s}):n.length>0?this.fire("selection:created",{e:e,selected:r}):t.length>0&&this.fire("selection:cleared",{e: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: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 n=this._realizeGroupTransformOnObject(t),r=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,n),r},_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 n=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,n)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),T.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),T.StaticCanvas)"prototype"!==n&&(T.Canvas[n]=T.StaticCanvas[n])}(),function(){var t=T.util.addListener,e=T.util.removeListener,i={passive:!1};function n(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 n=this.upperCanvasEl,r=this._getEventPrefix();t(T.window,"resize",this._onResize),t(n,r+"down",this._onMouseDown),t(n,r+"move",this._onMouseMove,i),t(n,r+"out",this._onMouseOut),t(n,r+"enter",this._onMouseEnter),t(n,"wheel",this._onMouseWheel),t(n,"contextmenu",this._onContextMenu),t(n,"dblclick",this._onDoubleClick),t(n,"dragover",this._onDragOver),t(n,"dragenter",this._onDragEnter),t(n,"dragleave",this._onDragLeave),t(n,"drop",this._onDrop),this.enablePointerEvents||t(n,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](n,"gesture",this._onGesture),eventjs[e](n,"drag",this._onDrag),eventjs[e](n,"orientation",this._onOrientationChange),eventjs[e](n,"shake",this._onShake),eventjs[e](n,"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(n){i.fire("mouse:out",{target:e,e:t}),n&&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(n){n.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(n)),this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();t(T.document,"touchend",this._onTouchEnd,i),t(T.document,"touchmove",this._onMouseMove,i),e(r,s+"down",this._onMouseDown)},_onMouseDown:function(n){this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();e(r,s+"move",this._onMouseMove,i),t(T.document,s+"up",this._onMouseUp),t(T.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(n){if(!(n.touches.length>0)){this.__onMouseUp(n),this._resetTransformEventData(),this.mainTouchId=null;var r=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,r+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(n){this.__onMouseUp(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(n)&&(e(T.document,s+"up",this._onMouseUp),e(T.document,s+"move",this._onMouseMove,i),t(r,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,r=this._groupSelector,s=!1,o=!r||0===r.left&&0===r.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),n(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(n(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),n=this.targets,r={e:e,target:i,subTargets:n};if(this.fire(t,r),i&&i.fire(t,r),!n)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=[],n=this._groupSelector.ex,r=this._groupSelector.ey,s=n+this._groupSelector.left,o=r+this._groupSelector.top,a=new T.Point(v(n,s),v(r,o)),h=new T.Point(y(n,s),y(r,o)),l=!this.selectionFullyContained,c=n===s&&r===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,n=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),r=this.toCanvasElement(n,t);return T.util.toDataURL(r,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,n=(e.height||this.height)*t,r=this.getZoom(),s=this.width,o=this.height,a=r*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(),m=this.contextTop;return g.width=i,g.height=n,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=n,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=m,g}}),T.util.object.extend(T.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var n="string"==typeof t?JSON.parse(t):T.util.object.clone(t),r=this,s=n.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete n.clipPath,this._enlivenObjects(n.objects,(function(t){r.clear(),r._setBgOverlay(n,(function(){s?r._enlivenObjects([s],(function(i){r.clipPath=i[0],r.__setupCanvas.call(r,n,t,o,e)})):r.__setupCanvas.call(r,n,t,o,e)}))}),i),this}},__setupCanvas:function(t,e,i,n){var r=this;e.forEach((function(t,e){r.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(),n&&n()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var n=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,n),this.__setBgOverlay("overlayImage",t.overlayImage,i,n),this.__setBgOverlay("backgroundColor",t.background,i,n),this.__setBgOverlay("overlayColor",t.overlay,i,n)}else e&&e()},__setBgOverlay:function(t,e,i,n){var r=this;if(!e)return i[t]=!0,void(n&&n());"backgroundImage"===t||"overlayImage"===t?T.util.enlivenObjects([e],(function(e){r[t]=e[0],i[t]=!0,n&&n()})):this["set"+T.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,n&&n()}))},_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(n){i(n.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,n=e.util.object.clone,r=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,n=t.width,r=t.height,s=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(n<=s&&r<=s&&n*r<=i)return nc&&(t.zoomX/=n/c,t.width=c,t.capped=!0),r>u&&(t.zoomY/=r/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,n=e.y*t.scaleY/this.scaleY;return{width:i+2,height:n+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:n}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,n=t._currentTransform.action;if(this===i&&n.slice&&"scale"===n.slice(0,5))return!1}var r,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,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,C=l>y||c>w;v=C||(l<.9*y||c<.9*w)&&y>h&&w>h,C&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),r=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-r)+r,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,n={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:r(this.left,i),top:r(this.top,i),width:r(this.width,i),height:r(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:r(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:r(this.strokeMiterLimit,i),scaleX:r(this.scaleX,i),scaleY:r(this.scaleY,i),angle:r(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:r(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:r(this.skewX,i),skewY:r(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(n.clipPath=this.clipPath.toObject(t),n.clipPath.inverted=this.clipPath.inverted,n.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,n,t),this.includeDefaultValues||(n=this._removeDefaultValues(n)),n},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 n=this.canvas.getZoom(),r=this.canvas.getRetinaScaling();e*=n*r,i*=n*r}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var n="scaleX"===t||"scaleY"===t,r=this[t]!==i,s=!1;return n&&(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,r&&(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 n=e.util.invertTransform(this.calcTransformMatrix());t.transform(n[0],n[1],n[2],n[3],n[4],n[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,n=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=n},_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 n,r,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();r=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),n=e.util.qrDecompose(h),t.save(),t.translate(n.translateX,n.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(n.angle-=180),t.rotate(o(this.group?n.angle:this.angle)),i.forActiveSelection||this.group?r&&this.drawBordersInGroup(t,n,i):r&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,n=this.shadow,r=this.canvas,s=r&&r.viewportTransform[0]||1,o=r&&r.viewportTransform[3]||1;i=n.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),r&&r._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=n.color,t.shadowBlur=n.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=n.offsetX*s*i.scaleX,t.shadowOffsetY=n.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,n=-this.width/2+e.offsetX||0,r=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,n,r):t.transform(1,0,0,1,n,r),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:n,offsetY:r}},_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 n,r=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=r.x/this.scaleX/o,h=r.y/this.scaleY/o;s.width=a,s.height=h,(n=s.getContext("2d")).beginPath(),n.moveTo(0,0),n.lineTo(a,0),n.lineTo(a,h),n.lineTo(0,h),n.closePath(),n.translate(a/2,h/2),n.scale(r.zoomX/this.scaleX/o,r.zoomY/this.scaleY/o),this._applyPatternGradientTransform(n,i),n.fillStyle=i.toLive(t),n.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/r.zoomX,o*this.scaleY/r.zoomY),t.strokeStyle=n.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 n=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(n,t):e.Object._fromObject("Object",n,t)},cloneAsImage:function(t,i){var n=this.toCanvasElement(i);return t&&t(new e.Image(n)),this},toCanvasElement:function(t){t||(t={});var i=e.util,n=i.saveObjectTransform(this),r=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,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.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 _=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",_),r&&(this.group=r),this.set(n).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 n=new e.Point(i.x,i.y),r=this._getLeftTopCoords();return this.angle&&(n=e.util.rotatePoint(n,r,o(-this.angle))),{x:n.x-r.x,y:n.y-r.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,r,s){var o=e[t];i=n(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);r&&r(t)}))}))},e.Object.__uid=0)}(e),w=T.util.degreesToRadians,C={left:-.5,center:0,right:.5},E={top:-.5,center:0,bottom:.5},T.util.object.extend(T.Object.prototype,{translateToGivenOrigin:function(t,e,i,n,r){var s,o,a,h=t.x,l=t.y;return"string"==typeof e?e=C[e]:e-=.5,"string"==typeof n?n=C[n]:n-=.5,"string"==typeof i?i=E[i]:i-=.5,"string"==typeof r?r=E[r]:r-=.5,o=r-i,((s=n-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 n=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?T.util.rotatePoint(n,t,w(this.angle)):n},translateToOriginPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?T.util.rotatePoint(n,t,w(this.angle)):n},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 n,r,s=this.getCenterPoint();return n=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new T.Point(this.left,this.top),r=new T.Point(t.x,t.y),this.angle&&(r=T.util.rotatePoint(r,s,-w(this.angle))),r.subtractEquals(n)},setPositionByOrigin:function(t,e,i){var n=this.translateToCenterPoint(t,e,i),r=this.translateToOriginPoint(n,this.originX,this.originY);this.set("left",r.x),this.set("top",r.y)},adjustPosition:function(t){var e,i,n=w(this.angle),r=this.getScaledWidth(),s=T.util.cos(n)*r,o=T.util.sin(n)*r;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,n=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,n){var r=this.getCoords(i,n);return"Intersection"===T.Intersection.intersectPolygonRectangle(r,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 n=this.getCoords(e,i),r=e?t.aCoords:t.lineCoords,s=0,o=t._getImageLines(r);s<4;s++)if(!t.containsPoint(n[s],o))return!1;return!0},isContainedWithinRect:function(t,e,i,n){var r=this.getBoundingRect(i,n);return r.left>=t.x&&r.left+r.width<=e.x&&r.top>=t.y&&r.top+r.height<=e.y},containsPoint:function(t,e,i,n){var r=this._getCoords(i,n),s=(e=e||this._getImageLines(r),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 n={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(n,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,n,r,s=0;for(var o in e)if(!((r=e[o]).o.y=t.y&&r.d.y>=t.y||(r.o.x===r.d.x&&r.o.x>=t.x?n=r.o.x:(i=(r.d.y-r.o.y)/(r.d.x-r.o.x),n=-(t.y-0*t.x-(r.o.y-i*r.o.x))/(0-i)),n>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var n=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(n)},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,n=e.additionalTransform||"",r=[this.getSvgTransform(!0,n),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=r,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,n,r=(e=e||{}).noStyle,s=e.reviver,o=r?"":'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=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+T.Object.__uid++,n='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,r?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=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(n),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,n){var r={};n.forEach((function(t){r[t]=e[t]})),t(e[i],r,!0)}function n(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var r=0,s=t.length;r=0;h--)if(r=a[h],this.isControlVisible(r)&&(n=this._getImageLines(e?this.oCoords[r].touchCorner:this.oCoords[r].corner),0!==(i=this._findCrossPoints({x:s,y:o},n))&&i%2==1))return this.__corner=r,r;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(),n=this._calculateCurrentDimensions(),r=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/r[0],1/r[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-n.x/2,-n.y/2,n.x,n.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),n=this.borderScaleFactor,r=i.x+n,s=i.y+n,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(-r/2,-s/2,r,s),o&&(t.beginPath(),this.forEachControl((function(e,i,n){e.withConnection&&e.getVisibility(n,i)&&(a=!0,t.moveTo(e.x*r,e.y*s),t.lineTo(e.x*r+e.offsetX,e.y*s+e.offsetY))})),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var n=T.util.sizeAfterTransform(this.width,this.height,e),r=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=n.x+r*(s?this.canvas.getZoom():e.scaleX)+o,h=n.y+r*(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,n,r=this.canvas.getRetinaScaling();return t.setTransform(r,0,0,r,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(r,s,o){n=o.oCoords[s],r.getVisibility(o,s)&&(i&&(n=T.util.transformPoint(n,i)),r.render(t,n.x,n.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(){},n=(e=e||{}).onComplete||i,r=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(),r()},onComplete:function(){t.setCoords(),n()}})},fxCenterObjectV:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=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(),r()},onComplete:function(){t.setCoords(),n()}})},fxRemove:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=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(),r()},onComplete:function(){s.remove(t),n()}})}}),T.util.object.extend(T.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],n=[];for(t in arguments[0])i.push(t);for(var r=0,s=i.length;r-1||r&&s.colorProperties.indexOf(r[1])>-1,a=r?this.get(r[0])[r[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,n){return i.abort.call(s,t,e,n)},onChange:function(e,o,a){r?s[r[0]][r[1]]=e:s.set(t,e),n||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,r){n||(s.setCoords(),i.onComplete&&i.onComplete(t,e,r))}};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,n=e.util.object.clone,r={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,n=t.axis1,r=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(n),this.get(r));case a:return Math.min(this.get(n),this.get(r))+.5*this.get(s);case h:return Math.max(this.get(n),this.get(r))}}}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!==r[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,n=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:n,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,n,r){r=r||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];n(new e.Line(o,i(s,r)))},e.Line.fromObject=function(t,i){var r=n(t,!0);r.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",r,(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,n=(this.endAngle-this.startAngle)%360;if(0===n)t=["\n'];else{var r=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 n,r=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(n=r)&&n.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");r.left=(r.left||0)-r.radius,r.top=(r.top||0)-r.radius,i(new e.Circle(r))},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 n=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);n.left=(n.left||0)-n.rx,n.top=(n.top||0)-n.ry,i(new e.Ellipse(n))},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,n=this.width,r=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+n-e,o),a&&t.bezierCurveTo(s+n-h*e,o,s+n,o+h*i,s+n,o+i),t.lineTo(s+n,o+r-i),a&&t.bezierCurveTo(s+n,o+r-h*i,s+n-h*e,o+r,s+n-e,o+r),t.lineTo(s+e,o+r),a&&t.bezierCurveTo(s+h*e,o+r,s,o+r-h*i,s,o+r-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,n,r){if(!t)return n(null);r=r||{};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(r?e.util.object.clone(r):{},s));o.visible=o.visible&&o.width>0&&o.height>0,n(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,n=e.util.array.min,r=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),n=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-n,this.height=i.height-n,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+n/2,y:i.top-this.strokeWidth/2+n/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+n/2,y:i.top+this.height/2+n/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=n(t,"x")||0,i=n(t,"y")||0;return{left:e,top:i,width:(r(t,"x")||0)-e,height:(r(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,n=this.pathOffset.y,r=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,n=this.pathOffset.x,r=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-n,this.points[0].y-r);for(var s=0;s"},toObject:function(t){return r(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,r,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 n=this._objects.length;if(this.useSetOnGroup)for(;n--;)this._objects[n].setOnGroup(t,i);if("canvas"===t)for(;n--;)this._objects[n]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,n=this._objects.filter((function(t){return!t.excludeFromExport})).map((function(e){var n=e.includeDefaultValues;e.includeDefaultValues=i;var r=e.toObject(t);return e.includeDefaultValues=n,r})),r=e.Object.prototype.toObject.call(this,t);return r.objects=n,r},toDatalessObject:function(t){var i,n=this.sourcePath;if(n)i=n;else{var r=this.includeDefaultValues;i=this._objects.map((function(e){var i=e.includeDefaultValues;e.includeDefaultValues=r;var n=e.toDatalessObject(t);return e.includeDefaultValues=i,n}))}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,n=this._objects.length;i\n"],i=0,n=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,n=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 n=0,r=this._objects.length;n\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,n){this.setElement(t,i),this._setWidthHeight(),e&&e(this,n)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),n=i.scaleX,r=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||n>e&&r>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=n,void(this._lastScaleY=r);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=n,this._lastScaleY=t.scaleY=r,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,n=e.naturalHeight||e.height;if(this._element===this._originalElement){var r=T.util.createCanvasElement();r.width=i,r.height=n,this._element=r,this._filteredEl=r}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,n),this._lastScaleX=1,this._lastScaleY=1;return T.filterBackend||(T.filterBackend=T.initFilterBackend()),T.filterBackend.applyFilters(t,this._originalElement,i,n,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,n=this._filterScalingY,r=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*n,g=o(r*i,c-d),m=o(s*n,u-f),p=-r/2,_=-s/2,v=o(r,c/i-h),y=o(s,u/n-l);e&&t.drawImage(e,d,f,g,m,p,_,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,n=this._element.height,r=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?(r=c/i,s=u/n):("meet"===e.meetOrSlice&&(t=(c-i*(r=s=T.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-n*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(r=s=T.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=n-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/r,n=u/s)),{width:i,height:n,scaleX:r,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,n){n?e&&e(null,!0):T.Image.prototype._initFilters.call(i,i.filters,(function(n){i.filters=n||[],T.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(n){i.resizeFilter=n[0],T.util.enlivenObjectEnlivables(i,i,(function(){var n=new T.Image(t,i);e(n,!1)}))}))}))}),null,i.crossOrigin)},T.Image.fromURL=function(t,e,i){T.util.loadImage(t,(function(t,n){e&&e(new T.Image(t,i),n)}),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,n){var r=T.parseAttributes(t,T.Image.ATTRIBUTE_NAMES);T.Image.fromURL(r["xlink:href"],i,e(n?T.util.object.clone(n):{},r))})}(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,n=t.onChange||e,r=this;return T.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){r.rotate(t),n()},onComplete:function(){r.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(){}",n=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(n,i),t.compileShader(n),!!t.getShaderParameter(n,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"),n=i.getContext("webgl")||i.getContext("experimental-webgl"),r=!1;if(n){T.maxTextureSize=n.getParameter(n.MAX_TEXTURE_SIZE),r=T.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(n,s[o])){T.webGlPrecision=s[o];break}}return this.isSupported=r,r},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,n=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var r="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(n&&i&&r&&s){var o=T.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(T.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=T.util.createCanvasElement();i.width=t,i.height=e;var n={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},r=i.getContext("webgl",n);r||(r=i.getContext("experimental-webgl",n)),r&&(r.clearColor(0,0,0,0),this.canvas=i,this.gl=r)},applyFilters:function(t,e,i,n,r,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:n,destinationWidth:i,destinationHeight:n,context:a,sourceTexture:this.createTexture(a,i,n,!o&&e),targetTexture:this.createTexture(a,i,n),originalTexture:o||this.createTexture(a,i,n,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:r},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,n=e.height,r=t.destinationWidth,s=t.destinationHeight;i===r&&n===s||(e.width=r,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),r.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,n){var r=t.createTexture();return t.bindTexture(t.TEXTURE_2D,r),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),n?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,n):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),r},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:I,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 n=t.getParameter(i.UNMASKED_RENDERER_WEBGL),r=t.getParameter(i.UNMASKED_VENDOR_WEBGL);n&&(e.renderer=n.toLowerCase()),r&&(e.vendor=r.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,n,r){var s=r.getContext("2d");s.drawImage(e,0,0,i,n);var o={sourceWidth:i,sourceHeight:n,imageData:s.getImageData(0,0,i,n),originalEl:e,originalImageData:s.getImageData(0,0,i,n),canvasEl:r,ctx:s,filterBackend:this};return t.forEach((function(t){t.applyTo(o)})),o.imageData.width===i&&o.imageData.height===n||(r.width=o.imageData.width,r.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 n=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var r=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var s=t.createProgram();if(t.attachShader(s,n),t.attachShader(s,r),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 n=e.aPosition,r=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,r),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,n=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(n.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(n,e,i)),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t.targetTexture,0)):(n.bindFramebuffer(n.FRAMEBUFFER,null),n.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,n=e.util.createClass;i.ColorMatrix=n(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,n,r,s,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,n+=m[h+2]*l,S||(r+=m[h+3]*l));E[s]=e,E[s+1]=i,E[s+2]=n,E[s+3]=S?m[s+3]:r}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,n=e.util.createClass;i.Grayscale=n(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,n=t.imageData.data,r=n.length,s=this.mode;for(e=0;el[0]&&r>l[1]&&s>l[2]&&n 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,n,r,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,n=h[1]*this.alpha,r=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,n=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/n;var r,s=e.width,a=e.height,h=o(s*i),l=o(a*n);"sliceHack"===this.resizeType?r=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?r=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?r=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(r=this.lanczosResize(t,s,a,h,l)),t.imageData=r},sliceByTwo:function(t,i,r,s,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=r*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){L=n(1e3*s(T-C.x)),w[L]||(w[L]={});for(var F=E.y-y;F<=E.y+y;F++)F<0||F>=o||(M=n(1e3*s(F-C.y)),w[L][M]||(w[L][M]=f(r(i(L*p,2)+i(M*_,2))/1e3)),(b=w[L][M])>0&&(x+=b,O+=b*c[I=4*(F*e+T)],A+=b*c[I+1],R+=b*c[I+2],D+=b*c[I+3]))}d[I=4*(S*a+h)]=O/x,d[I+1]=A/x,d[I+2]=R/x,d[I+3]=D/x}return++h1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(b+=y*f[3+(L=4*(D+x*e))],C+=y,f[L+3]<255&&(y=y*f[L+3]/250),E+=y*f[L],S+=y*f[L+1],T+=y*f[L+2],w+=y)}m[v]=E/w,m[v+1]=S/w,m[v+2]=T/w,m[v+3]=b/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,n=e.util.createClass;i.Contrast=n(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,n=i.length,r=Math.floor(255*this.contrast),s=259*(r+255)/(255*(259-r));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,n=e.util.createClass;i.Gamma=n(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,n=this.gamma,r=i.length,s=1/n[0],o=1/n[1],a=1/n[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,r=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=n)}return t},_renderTextLine:function(t,e,i,n,r,s){this._renderChars(t,e,i,n,r,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,n,r,s,o,a,h=t.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,m=this._textLines.length;g=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,n){var r=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,r,s.segmentsInfo);i.renderLeft=o.x-n.x,i.renderTop=o.y-n.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,n,r){var s,o=this.getCompleteStyleDeclaration(e,i),a=n?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,n,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&&!r){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),n=1,r=e.length;n0){var x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+E*n+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,n=r,o=a}else d+=f.kernedWidth;x=v+s+u,"rtl"===this.direction&&(x=this.width-x-d),t.fillStyle=p,g&&p&&t.fillRect(x,c+E*n+o,d-C,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var n=t||this,r=this.fontFamily,s=e.Text.genericFonts.indexOf(r.toLowerCase())>-1,o=void 0===r||r.indexOf("'")>-1||r.indexOf(",")>-1||r.indexOf('"')>-1||s?n.fontFamily:'"'+n.fontFamily+'"';return[e.isLikelyNode?n.fontWeight:n.fontStyle,e.isLikelyNode?n.fontStyle:n.fontWeight,i?this.CACHE_FONT_SIZE+"px":n.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),n=new Array(i.length),r=["\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(),n=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:n.left,topOffset:n.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,n,r,s=0,o=0,a=this.get2DCursorLocation(t);n=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(r.left*=-1),this.cursorOffsetCache=r,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),n=i.lineIndex,r=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(n,r,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(n,r,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(n)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(n,r,"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,n=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,r=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(n),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),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,C=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,C=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+C,y,w),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 n in e.styles)for(var r in e.styles[n])t(e.styles[n][r]);T.Object._fromObject("IText",e,i,"text")}}(),S=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,n){var r;return r={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){r.isAborted||t[n]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return r.isAborted}}),r},_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&&nthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(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 n=i.slice(0,t),r=T.util.string.graphemeSplit(n).length;if(t===e)return{selectionStart:r,selectionEnd:r};var s=i.slice(t,e);return{selectionStart:r,selectionEnd:r+T.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var n=i.slice(0,t).join("").length;return t===e?{selectionStart:n,selectionEnd:n}:{selectionStart:n,selectionEnd:n+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),n=i.lineIndex,r=i.charIndex,s=this.getValueOfPropertyAt(n,r,"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,m=c.clientWidth/u,p=c.clientHeight/d;return h=T.util.transformPoint(h,a),(h=T.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,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,n,r=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),o=r.lineIndex,a=r.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(n[c-d]=n[u],delete n[u])}},shiftLineStyles:function(t,e){var i=S(this.styles);for(var n in this.styles){var r=parseInt(n,10);r>t&&(this.styles[r+e]=i[r],i[r-e]||delete this.styles[r])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,n){var r,s={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(r=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;)n&&n[i-1]?this.styles[t+i]={0:S(n[i-1])}:r?this.styles[t+i]={0:S(r)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,n){this.styles||(this.styles={});var r=this.styles[t],s=r?S(r):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(r[a+i]=s[a],s[a-i]||delete r[a])}if(this._forceClearCache=!0,n)for(;i--;)Object.keys(n[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=S(n[i]));else if(r)for(var h=r[e?e-1:1];h&&i--;)this.styles[t][e+i]=S(h)},insertNewStyleBlock:function(t,e,i){for(var n=this.get2DCursorLocation(e,!0),r=[0],s=0,o=0;o0&&(this.insertCharStyleObject(n.lineIndex,n.charIndex,r[0],i),i=i&&i.slice(r[0]+1)),s&&this.insertNewlineStyleObject(n.lineIndex,n.charIndex+r[0],s),o=1;o0?this.insertCharStyleObject(n.lineIndex+o,0,r[o],i):i&&this.styles[n.lineIndex+o]&&i[0]&&(this.styles[n.lineIndex+o][0]=i[0]),i=i&&i.slice(r[o]+1);r[o]>0&&this.insertCharStyleObject(n.lineIndex+o,0,r[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,n=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,n,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),n=0,r=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));r=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+r);for(var c=0,u=e.length;cs||o<0?0:1);return this.flipX&&(a=r-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,n,r,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),m=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(n+=(i=this.__charBounds[t][e-1]).left+i.width),n},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(r===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=n.charIndex,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r+1,o);return this._textLines[r].slice(s).length+a+1+this.missingNewlineOffset(r)},_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),n=this.get2DCursorLocation(i),r=n.lineIndex;if(0===r||t.metaKey||33===t.keyCode)return-i;var s=n.charIndex,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r-1,o),h=this._textLines[r].slice(0,s),l=this.missingNewlineOffset(r-1);return-this._textLines[r-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,n,r=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=r.length;ae){n=!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 n;if(t.altKey)n=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;n=this["findLineBoundary"+i](this[e])}if(void 0!==typeof n&&this[e]!==n)return this[e]=n,!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,n){void 0===n&&(n=i),n>i&&this.removeStyleFromTo(i,n);var r=T.util.string.graphemeSplit(t);this.insertNewStyleBlock(r,i,e),this._text=[].concat(this._text.slice(0,i),r,this._text.slice(n)),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,n=[],r=[],s=t;this._setSVGBg(r);for(var o=0,a=this._textLines.length;o",T.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,n){var r,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];n+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)h=g===m||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||(r=r||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(r,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,n)),u="",r=s,i+=d,d=0)},_pushTextBgRect:function(e,i,n,r,s,o){var a=T.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,n){for(var r,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,n=0,r={},s=0;s0?(i=0,n++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[n])&&s>0&&(i++,n++),r[s]={line:e,offset:i},n+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return r},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var n=this._styleMap[i];n&&(i=n.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,n=0,r=!1,s=this._styleMap[t],o=this._styleMap[t+1];for(var a in s&&(t=s.line,n=s.offset),o&&(r=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=n&&(!r||hn&&!p?(a.push(h),h=[],s=f,p=!0):s+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+r>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+r),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),n=this._wrapText(i.lines,this.width),r=new Array(n.length),s=0;s{},898:()=>{},245:()=>{}},Ye={};function He(t){var e=Ye[t];if(void 0!==e)return e.exports;var i=Ye[t]={exports:{}};return We[t](i,i.exports,He),i.exports}He.d=(t,e)=>{for(var i in e)He.o(e,i)&&!He.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},He.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Xe={};(()=>{let t;He.d(Xe,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?He(653).fabric:{version:"5.2.1"}})();var ze,qe,Ze,Ke,Je=Xe.R;!function(t){t[t.DIMT_RECTANGLE=1]="DIMT_RECTANGLE",t[t.DIMT_QUADRILATERAL=2]="DIMT_QUADRILATERAL",t[t.DIMT_TEXT=4]="DIMT_TEXT",t[t.DIMT_ARC=8]="DIMT_ARC",t[t.DIMT_IMAGE=16]="DIMT_IMAGE",t[t.DIMT_POLYGON=32]="DIMT_POLYGON",t[t.DIMT_LINE=64]="DIMT_LINE",t[t.DIMT_GROUP=128]="DIMT_GROUP"}(ze||(ze={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(qe||(qe={})),function(t){t[t.EF_ENHANCED_FOCUS=4]="EF_ENHANCED_FOCUS",t[t.EF_AUTO_ZOOM=16]="EF_AUTO_ZOOM",t[t.EF_TAP_TO_FOCUS=64]="EF_TAP_TO_FOCUS"}(Ze||(Ze={})),function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(Ke||(Ke={}));const Qe=t=>"number"==typeof t&&!Number.isNaN(t),$e=t=>"string"==typeof t;var ti,ei,ii,ni,ri,si,oi,ai,hi,li,ci;!function(t){t[t.ARC=0]="ARC",t[t.IMAGE=1]="IMAGE",t[t.LINE=2]="LINE",t[t.POLYGON=3]="POLYGON",t[t.QUAD=4]="QUAD",t[t.RECT=5]="RECT",t[t.TEXT=6]="TEXT",t[t.GROUP=7]="GROUP"}(ri||(ri={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(si||(si={}));class ui{get mediaType(){return new Map([["rect",ze.DIMT_RECTANGLE],["quad",ze.DIMT_QUADRILATERAL],["text",ze.DIMT_TEXT],["arc",ze.DIMT_ARC],["image",ze.DIMT_IMAGE],["polygon",ze.DIMT_POLYGON],["line",ze.DIMT_LINE],["group",ze.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(Be(this,ei,"f")){case qe.DIS_DEFAULT:return"default";case qe.DIS_SELECTED:return"selected"}}set drawingStyleId(t){this.styleId=t}get drawingStyleId(){return this.styleId}set coordinateBase(t){if(!["view","image"].includes(t))throw new Error("Invalid 'coordinateBase'.");this._drawingLayer&&("image"===Be(this,ii,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===Be(this,ii,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),Ne(this,ii,t,"f")}get coordinateBase(){return Be(this,ii,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(ti.add(this),ei.set(this,void 0),ii.set(this,"image"),this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapState_StyleId=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,null!=e&&!Qe(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(qe.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",(()=>{this.setState(qe.DIS_SELECTED)})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(qe.DIS_SELECTED):this.setState(qe.DIS_DEFAULT),"textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}setState(t){Ne(this,ei,t,"f")}getState(){return Be(this,ei,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),n=this.mapEvent_Callbacks.get(i);if(!n)throw new Error(`Event '${t}' does not exist.`);let r=n.get(e);r||(r=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const n={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,r,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,r=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)u0?i-1:n,mi),actionName:"modifyPolygon",pointIndex:i}),t}),{}),Ne(this,ai,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,n){return t["p"+n]=new Je.Control({positionHandler:fi,actionHandler:pi(n>0?n-1:i,mi),actionName:"modifyPolygon",pointIndex:n}),t}),{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let n=i.x-e.pathOffset.x,r=i.y-e.pathOffset.y;const s=Je.util.transformPoint({x:n,y:r},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){Be(this,ai,"f")&&this.setPolygon(Be(this,ai,"f"))}setPolygon(t){if(!T(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Ne(this,ai,JSON.parse(JSON.stringify(t)),"f")}getPolygon(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Be(this,ai,"f")?JSON.parse(JSON.stringify(Be(this,ai,"f"))):null}}ai=new WeakMap;hi=new WeakMap,li=new WeakMap;const vi=t=>{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let n=0;ni&&(i=r.length)}if(-1===i)break;for(let n=0;n=t[n].length-1)continue;let r=" ".repeat(i+2-t[n][e].length);t[n][e]=t[n][e].concat(r)}}})(e),(t=>{let e="";for(let i=0;i({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Ne(this,Ci,JSON.parse(JSON.stringify(t)),"f")}getQuad(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Be(this,Ci,"f")?JSON.parse(JSON.stringify(Be(this,Ci,"f"))):null}}Ci=new WeakMap;class Si extends ui{constructor(t){super(new Je.Group(t.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.setState(qe.DIS_SELECTED);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.setState(qe.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}setChildDrawingItems(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()))}}const Ti=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),bi=t=>!!$e(t)&&""!==t,Ii=t=>!(!Ti(t)||"id"in t&&!Qe(t.id)||"lineWidth"in t&&!Qe(t.lineWidth)||"fillStyle"in t&&!bi(t.fillStyle)||"strokeStyle"in t&&!bi(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!bi(t.fontFamily)||"fontSize"in t&&!Qe(t.fontSize));class xi{static convert(t,e,i){const n={x:0,y:0,width:e,height:i};if(!t)return n;if(I(t))t.isMeasuredInPercentage?(n.x=t.x/100*e,n.y=t.y/100*i,n.width=t.width/100*e,n.height=t.height/100*i):(n.x=t.x,n.y=t.y,n.width=t.width,n.height=t.height);else{if(!w(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?(n.x=t.left/100*e,n.y=t.top/100*i,n.width=(t.right-t.left)/100*e,n.height=(t.bottom-t.top)/100*i):(n.x=t.left,n.y=t.top,n.width=t.right-t.left,n.height=t.bottom-t.top)}return n.x=Math.round(n.x),n.y=Math.round(n.y),n.width=Math.round(n.width),n.height=Math.round(n.height),n}}var Oi,Ai;class Ri{constructor(){Oi.set(this,new Map),Ai.set(this,!1)}get disposed(){return Be(this,Ai,"f")}on(t,e){t=t.toLowerCase();const i=Be(this,Oi,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else Be(this,Oi,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=Be(this,Oi,"f").get(t);if(!i)return;const n=i.indexOf(e);-1!==n&&i.splice(n,1)}offAll(t){t=t.toLowerCase();const e=Be(this,Oi,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const n=Be(this,Oi,"f").get(t);if(n&&n.length){i=Object.assign({async:!1,copy:!0},i);for(let r of n){if(!r)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let o=!1;if(i.async)setTimeout((()=>{this.disposed||n.includes(r)&&r.apply(i.target,s)}),0);else try{o=r.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){Ne(this,Ai,!0,"f")}}function Di(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function Li(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function Mi(t,e,i,n){let r=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(n[1]-e[1])+e[0]*(t[1]-n[1])+n[0]*(e[1]-t[1]);return!((r^s)>=0&&0!==r&&0!==s||(r=i[0]*(t[1]-n[1])+n[0]*(i[1]-t[1])+t[0]*(n[1]-i[1]),s=i[0]*(e[1]-n[1])+n[0]*(i[1]-e[1])+e[0]*(n[1]-i[1]),(r^s)>=0&&0!==r&&0!==s))}Oi=new WeakMap,Ai=new WeakMap;const Fi=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const n=document.createElement("div");if(n.insertAdjacentHTML("beforeend",i),1===n.childElementCount&&n.firstChild instanceof HTMLTemplateElement)return n.firstChild.content;const r=new DocumentFragment;for(let t of n.children)r.append(t);return r};var Pi,ki,Bi,Ni,ji,Ui,Vi,Gi,Wi,Yi,Hi,Xi,zi,qi,Zi,Ki,Ji,Qi,$i,tn,en,nn,rn,sn,on,an,hn,ln,cn,un,dn,fn,gn,mn;class pn{static createDrawingStyle(t){if(!Ii(t))throw new Error("Invalid style definition.");let e,i=pn.USER_START_STYLE_ID;for(;Be(pn,Pi,"f",ki).has(i);)i++;e=i;const n=JSON.parse(JSON.stringify(t));n.id=e;for(let t in Be(pn,Pi,"f",Bi))n.hasOwnProperty(t)||(n[t]=Be(pn,Pi,"f",Bi)[t]);return Be(pn,Pi,"f",ki).set(e,n),n.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=Be(pn,Pi,"f",ki).get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}static getDrawingStyle(t){return this._getDrawingStyle(t,!0)}static getAllDrawingStyles(){return JSON.parse(JSON.stringify(Array.from(Be(pn,Pi,"f",ki).values())))}static _updateDrawingStyle(t,e){if(!Ii(e))throw new Error("Invalid style definition.");const i=Be(pn,Pi,"f",ki).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}Pi=pn,pn.STYLE_BLUE_STROKE=1,pn.STYLE_GREEN_STROKE=2,pn.STYLE_ORANGE_STROKE=3,pn.STYLE_YELLOW_STROKE=4,pn.STYLE_BLUE_STROKE_FILL=5,pn.STYLE_GREEN_STROKE_FILL=6,pn.STYLE_ORANGE_STROKE_FILL=7,pn.STYLE_YELLOW_STROKE_FILL=8,pn.STYLE_BLUE_STROKE_TRANSPARENT=9,pn.STYLE_GREEN_STROKE_TRANSPARENT=10,pn.STYLE_ORANGE_STROKE_TRANSPARENT=11,pn.USER_START_STYLE_ID=1024,ki={value:new Map([[pn.STYLE_BLUE_STROKE,{id:pn.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[pn.STYLE_GREEN_STROKE,{id:pn.STYLE_GREEN_STROKE,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[pn.STYLE_ORANGE_STROKE,{id:pn.STYLE_ORANGE_STROKE,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[pn.STYLE_YELLOW_STROKE,{id:pn.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[pn.STYLE_BLUE_STROKE_FILL,{id:pn.STYLE_BLUE_STROKE_FILL,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[pn.STYLE_GREEN_STROKE_FILL,{id:pn.STYLE_GREEN_STROKE_FILL,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[pn.STYLE_ORANGE_STROKE_FILL,{id:pn.STYLE_ORANGE_STROKE_FILL,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[pn.STYLE_YELLOW_STROKE_FILL,{id:pn.STYLE_YELLOW_STROKE_FILL,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[pn.STYLE_BLUE_STROKE_TRANSPARENT,{id:pn.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[pn.STYLE_GREEN_STROKE_TRANSPARENT,{id:pn.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[pn.STYLE_ORANGE_STROKE_TRANSPARENT,{id:pn.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},Bi={value:{lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}},"undefined"!=typeof document&&"undefined"!=typeof window&&(Je.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(Je.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),Je.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},Je.Object.prototype.transparentCorners=!1,Je.Object.prototype.cornerSize=20,Je.Object.prototype.touchCornerSize=100,Je.Object.prototype.cornerColor="rgb(254,142,20)",Je.Object.prototype.cornerStyle="circle",Je.Object.prototype.strokeUniform=!0,Je.Object.prototype.hasBorders=!1,Je.Canvas.prototype.containerClass="",Je.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i,n=this.upperCanvasEl,r=Je.util.getPointer(t,n),s=n.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(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,e||(r=this.restorePointerVpt(r));var h=this.getRetinaScaling();if(1!==h&&(r.x/=h,r.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(n).objectFit,c=n.width,u=n.height,d=o,f=a;i={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:r.x*i.width,y:(r.y-(f-m)/2)*i.width}):(g=f*p,m=f,{x:(r.x-(d-g)/2)*i.height,y:r.y*i.height}):"cover"===l?p>_?{x:(c-i.height*d)/2+r.x*i.height,y:r.y*i.height}:{x:r.x*i.width,y:(u-i.width*f)/2+r.y*i.width}:{x:r.x*i.width,y:r.y*i.height}}return i={width:1,height:1},{x:r.x*i.width,y:r.y*i.height}},Je.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,n=this._getEventPrefix();Je.util.addListener(Je.document,"touchend",this._onTouchEnd,{passive:!1}),Je.util.addListener(Je.document,"touchmove",this._onMouseMove,{passive:!1}),Je.util.removeListener(i,n+"down",this._onMouseDown)},Je.Textbox.prototype._wrapLine=function(t,e,i,n){const r=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!r||!r.length);var o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?Je.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,m=0,p=0,_=!0,v=this._getWidthOfCharSpacing();n=n||0,0===c.length&&c.push([]),i-=n;for(var y=0;yi&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+n),h});class _n{get width(){return this.fabricCanvas.width}get height(){return this.fabricCanvas.height}set _allowMultiSelect(t){this.fabricCanvas.selection=t,this.fabricCanvas.renderAll()}get _allowMultiSelect(){return this.fabricCanvas.selection}constructor(t,e,i){if(this.mapType_StateAndStyleId=new Map,this.mode="viewer",this.onSelectionChanged=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas"))this.fabricCanvas=t.getFabricCanvas();else{let e=this.fabricCanvas=new Je.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.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 n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])}),0)}})),e.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 n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{const e=[];for(let n of i)t.hasDrawingItem(n)&&e.push(n);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)}),0)}})),e.on("selection:updated",(function(t){const e=t.selected,i=t.deselected,n=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of n){const n=[],r=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&n.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&r.push(i)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(n,r)}),0)}})),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let n,r;switch(this.id=e,e){case _n.DDN_LAYER_ID:n=pn.getDrawingStyle(pn.STYLE_BLUE_STROKE),r=pn.getDrawingStyle(pn.STYLE_BLUE_STROKE_FILL);break;case _n.DBR_LAYER_ID:n=pn.getDrawingStyle(pn.STYLE_ORANGE_STROKE),r=pn.getDrawingStyle(pn.STYLE_ORANGE_STROKE_FILL);break;case _n.DLR_LAYER_ID:n=pn.getDrawingStyle(pn.STYLE_GREEN_STROKE),r=pn.getDrawingStyle(pn.STYLE_GREEN_STROKE_FILL);break;default:n=pn.getDrawingStyle(pn.STYLE_YELLOW_STROKE),r=pn.getDrawingStyle(pn.STYLE_YELLOW_STROKE_FILL)}for(let t of ui.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:n.id,selected:r.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return pn.getDrawingStyle(t.styleId);return pn.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,n){const r=this.getDrawingItems((e=>e._mediaType===t));for(let t of r)t.styleSelector===e&&this._changeItemStyle(t,i,!0);n||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const n=t._getFabricObject();"number"==typeof t.styleId&&(e=pn.getDrawingStyle(t.styleId)),n.strokeWidth=e.lineWidth,"fill"===e.paintMode?(n.fill=e.fillStyle,n.stroke=e.fillStyle):"stroke"===e.paintMode?(n.fill="transparent",n.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(n.fill=e.fillStyle,n.stroke=e.strokeStyle),n.fontFamily&&(n.fontFamily=e.fontFamily),n.fontSize&&(n.fontSize=e.fontSize),n.group||(n.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const n=t.getChildDrawingItems();if("add"===i){if(n.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=pn.getDrawingStyle(e.styleId);else{const n=this.mapType_StateAndStyleId.get(e._mediaType);i=pn.getDrawingStyle(n[t.styleSelector]);const r=()=>{this._changeItemStyle(e,pn.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,pn.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",r),e._on("deselected",s),e._funcChangeStyleToSelected=r,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!n.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof ui))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const n=this.fabricCanvas.getObjects();let r,s;if(n.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){r=t.getChildDrawingItems();for(let t of r)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(r){for(let t of r){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of ui.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=pn.getDrawingStyle(t.styleId);else{s=pn.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,pn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},n=()=>{this._changeItemStyle(t,pn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of ui.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=pn.getDrawingStyle(t.styleId);else{s=pn.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,pn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},n=()=>{this._changeItemStyle(t,pn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=n.length;if(o)a=n.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;et.toLowerCase())):e=ui.arrMediaTypes,i?i.forEach((t=>t.toLowerCase())):i=ui.arrStyleSelectors;const n=pn.getDrawingStyle(t);if(!n)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let r;for(let s of e)if(r=this.mapType_StateAndStyleId.get(s),r)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,n,!0),r[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const n=[];i&ze.DIMT_RECTANGLE&&n.push("rect"),i&ze.DIMT_QUADRILATERAL&&n.push("quad"),i&ze.DIMT_TEXT&&n.push("text"),i&ze.DIMT_ARC&&n.push("arc"),i&ze.DIMT_IMAGE&&n.push("image"),i&ze.DIMT_POLYGON&&n.push("polygon"),i&ze.DIMT_LINE&&n.push("line");const r=[];e&qe.DIS_DEFAULT&&r.push("default"),e&qe.DIS_SELECTED&&r.push("selected"),this._setDefaultStyle(t,n.length?n:null,r.length?r:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}_n.DDN_LAYER_ID=1,_n.DBR_LAYER_ID=2,_n.DLR_LAYER_ID=3,_n.USER_DEFINED_LAYER_BASE_ID=100,_n.TIP_LAYER_ID=999;class vn{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new _n(t,e,{enableRetinaScaling:!1});return i._manager=this,this._arrDrawingLayer.push(i),this._switchPointerEvent(),i}deleteDrawingLayer(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}getAllDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._getFabricCanvas().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){if(!this._arrDrawingLayer.length)return;this._getFabricCanvas().wrapperEl.style.display=t?"block":"none"}_getFabricCanvas(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0].fabricCanvas:null}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class yn extends yi{constructor(t,e,i,n,r){super(t,{x:e,y:i,width:n,height:0},r),Ni.set(this,void 0),ji.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&Ne(this,ji,setTimeout((()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()}),Be(this,Ni,"f")),"f")}getDuration(){return Be(this,Ni,"f")}}Ni=new WeakMap,ji=new WeakMap;class wn{constructor(){Ui.add(this),Vi.set(this,void 0),Gi.set(this,void 0),Wi.set(this,void 0),Yi.set(this,!0),this._drawingLayerManager=new vn}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const n=document.createElement("canvas");return n.width==t&&n.height==e||(n.width=t,n.height=e),n.style.objectFit=i,n}_createDrawingLayer(t,e,i,n){if(!this._layerBaseCvs){let r;try{r=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==r?void 0:r.width)||1280),i||(i=(null==r?void 0:r.height)||720),n||(n=(null==r?void 0:r.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,n)}const r=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(r,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",r.parentElement),s}createDrawingLayer(){let t;for(let e=_n.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==_n.TIP_LAYER_ID){t=e;break}return this._createDrawingLayer(t)}deleteDrawingLayer(t){var e;this._drawingLayerManager.deleteDrawingLayer(t),this._drawingLayerManager.getAllDrawingLayers().length||(null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null)}deleteUserDefinedDrawingLayer(t){if("number"!=typeof t)throw new TypeError("Invalid id.");if(t<_n.USER_DEFINED_LAYER_BASE_ID)throw new Error(`The drawing layer with id ${t} is not defined by users.`);this.deleteDrawingLayer(t)}_clearDrawingLayers(){const t=this.getAllDrawingLayers();for(let e of t)this.deleteDrawingLayer(e.getId())}clearUserDefinedDrawingLayers(){const t=this.getAllDrawingLayers();for(let e of t){const t=e.getId();t<_n.USER_DEFINED_LAYER_BASE_ID||this.deleteUserDefinedDrawingLayer(t)}}getDrawingLayer(t){if(t==_n.TIP_LAYER_ID)return null;return this._drawingLayerManager.getDrawingLayer(t)||([_n.DDN_LAYER_ID,_n.DBR_LAYER_ID,_n.DLR_LAYER_ID].includes(t)?this._createDrawingLayer(t):null)}getAllDrawingLayers(){return this._drawingLayerManager.getAllDrawingLayers().filter((t=>t.getId()>=0&&t.getId()!==_n.TIP_LAYER_ID))}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(Ti(e=t)&&S(e.topLeftPoint)&&Qe(e.width))||e.width<=0||!Qe(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;Ne(this,Vi,JSON.parse(JSON.stringify(t)),"f"),Be(this,Vi,"f").coordinateBase||(Be(this,Vi,"f").coordinateBase="view"),Ne(this,Wi,t.duration,"f"),Be(this,Ui,"m",qi).call(this)}getTipConfig(){return Be(this,Vi,"f")?Be(this,Vi,"f"):null}setTipVisible(t){if("boolean"!=typeof t)throw new TypeError("Invalid value.");this._tip&&(this._tip.set("visible",t),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll()),Ne(this,Yi,t,"f")}isTipVisible(){return Be(this,Yi,"f")}updateTipMessage(t){if(!Be(this,Vi,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=pn.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(_n.TIP_LAYER_ID)||this._createDrawingLayer(_n.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=Be(this,Ui,"m",Hi).call(this,t,Be(this,Vi,"f").topLeftPoint.x,Be(this,Vi,"f").topLeftPoint.y,Be(this,Vi,"f").width,Be(this,Vi,"f").coordinateBase,this._tipStyleId),Be(this,Ui,"m",Xi).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",Be(this,Yi,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),Be(this,Gi,"f")&&clearTimeout(Be(this,Gi,"f")),Be(this,Wi,"f")>=0&&Ne(this,Gi,setTimeout((()=>{Be(this,Ui,"m",zi).call(this)}),Be(this,Wi,"f")),"f")}}Vi=new WeakMap,Gi=new WeakMap,Wi=new WeakMap,Yi=new WeakMap,Ui=new WeakSet,Hi=function(t,e,i,n,r,s){const o=new yn(t,e,i,n,s);return o.coordinateBase=r,o},Xi=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},zi=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},qi=function(){if(!this._tip)return;const t=Be(this,Vi,"f");this._tip.coordinateBase=t.coordinateBase,this._tip.setTextRect({x:t.topLeftPoint.x,y:t.topLeftPoint.y,width:t.width,height:0}),this._tip.set("width",this._tip.get("width")),this._tip._drawingLayer&&this._tip._drawingLayer.renderAll()};class Cn extends HTMLElement{constructor(){super(),Zi.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),Ne(this,Zi,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const n=document.createElement("slot");n.setAttribute("name","content"),e.append(n);const r=document.createElement("slot");r.setAttribute("name","drawing-layer"),e.append(r);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return Be(this,Zi,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach((t=>t.remove()))}}Zi=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",Cn);class En extends wn{static get engineResourcePath(){return A(gt.engineResourcePaths).dce}static set defaultUIElementURL(t){En._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=En._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",En.engineResourcePath)}static async createInstance(t){const e=new En;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",En.engineResourcePath)),await e.setUIElement(t||En.defaultUIElementURL),e}static _transformCoordinates(t,e,i,n,r,s,o){const a=s/n,h=o/r;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==Be(this,on,"f")){if(Ne(this,on,t,"f"),Be(this,Ki,"m",ln).call(this))Ne(this,tn,null,"f"),this._videoContainer=null,this._innerComponent.removeElement("content"),this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block");else if(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none"),!Be(this,tn,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(ke.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Ne(this,tn,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}Be(this,Ki,"m",ln).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading())}}get _singleFrameMode(){return Be(this,on,"f")}get disposed(){return Be(this,hn,"f")}constructor(){super(),Ki.add(this),Ji.set(this,void 0),Qi.set(this,void 0),$i.set(this,void 0),this.containerClassName="dce-video-container",tn.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,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,en.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,nn.set(this,!1),rn.set(this,!1),sn.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{Be(this,Ki,"m",gn).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout((()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&Be(this,Ki,"m",fn).call(this))}),this._updateLayersTimeout)},this._windowResizeListener=()=>{En._onLog&&En._onLog("window resize event triggered."),Be(this,sn,"f").width===document.documentElement.clientWidth&&Be(this,sn,"f").height===document.documentElement.clientHeight||(Be(this,sn,"f").width=document.documentElement.clientWidth,Be(this,sn,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},on.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!Be(this,Ki,"m",ln).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise(((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i},i=(t,e,i,n)=>{t.width==i&&t.height==n||(t.width=i,t.height=n);const r=t.getContext("2d");r.clearRect(0,0,t.width,t.height),r.drawImage(e,0,0)},n=await t(e),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,n,r,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout((()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)}),0)})),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},an.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,n,r,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(n=o.cropRegion)||void 0===n?void 0:n.top)||0,c=(null===(r=o.cropRegion)||void 0===r?void 0:r.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,n,r,s,o,a,h=[],l)=>{e.forEach((t=>En._transformCoordinates(t,i,n,r,s,o,a)));const c=new Ei({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},l);for(let t of h)c.addNote(t);t.addDrawingItems([c]),Be(this,an,"f").push(c)};let m,p;for(let t of a)switch(t.type){case mt.CRIT_ORIGINAL_IMAGE:break;case mt.CRIT_BARCODE:m=this.getDrawingLayer(_n.DBR_LAYER_ID),p=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==e?void 0:e.isBarcodeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,pn.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case mt.CRIT_TEXT_LINE:m=this.getDrawingLayer(_n.DLR_LAYER_ID),p=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,pn.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case mt.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(_n.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.crossVerificationStatus===St.CVS_PASSED?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],pn.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case mt.CRIT_NORMALIZED_IMAGE:m=this.getDrawingLayer(_n.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.crossVerificationStatus===St.CVS_PASSED?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],pn.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case mt.CRIT_PARSED_RESULT:break;default:throw new Error("Illegal item type.")}}},hn.set(this,!1),this.eventHandler=new Ri,this.eventHandler.on("content:updated",(()=>{Be(this,Ji,"f")&&clearTimeout(Be(this,Ji,"f")),Ne(this,Ji,setTimeout((()=>{if(this.disposed)return;let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(t),this.updateConvertedRegion(t)}),0),"f")})),this.eventHandler.on("videoEl:resized",(()=>{Be(this,Qi,"f")&&clearTimeout(Be(this,Qi,"f")),Ne(this,Qi,setTimeout((()=>{this.disposed||this._updateVideoContainer()}),0),"f")}))}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Fi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let n=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!n)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=document.createElement("dce-component"),n.appendChild(this._innerComponent),Be(this,Ki,"m",ln).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(ke.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Ne(this,tn,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._selRsl&&(this._hideDefaultSelection||Be(this,Ki,"m",ln).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||Be(this,Ki,"m",ln).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||Be(this,Ki,"m",gn).call(this),Be(this,Ki,"m",ln).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),Be(this,Ki,"m",ln).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading()),window.ResizeObserver){this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{var e;En._onLog&&En._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()})));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}Be(this,sn,"f").width=document.documentElement.clientWidth,Be(this,sn,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,n;Be(this,Ki,"m",ln).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),Be(this,Ki,"m",gn).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,Ne(this,tn,null,"f"),null===(n=this._videoContainer)||void 0===n||n.remove(),this._videoContainer=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._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let n of e){const e=document.createElement("option");e.value=n.deviceId,e.innerText=n.label,this._selCam.append(e),n.deviceId&&t&&t.deviceId==n.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),n=Math.min(t.width,t.height);e=n<=1080?n+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return Be(this,tn,"f")}isVideoLoaded(){return!(!Be(this,tn,"f")||!this.cameraEnhancer)&&this.cameraEnhancer.isOpen()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!Be(this,tn,"f"))return;if(Be(this,tn,"f").style.objectFit=t,Be(this,Ki,"m",ln).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Be(this,Ki,"m",mn).call(this,e,this.getConvertedRegion()),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,n;let r,s,o;if(Be(this,Ki,"m",ln).call(this)?(r=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(n=this._cvsSingleFrameMode)||void 0===n?void 0:n.height,o="contain"):(r=null===(t=Be(this,tn,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=Be(this,tn,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!r||!s)throw new Error("Invalid content dimensions.");return{width:r,height:s,objectFit:o}}updateConvertedRegion(t){const e=xi.convert(this.scanRegion,t.width,t.height);Ne(this,en,e,"f"),Be(this,$i,"f")&&clearTimeout(Be(this,$i,"f")),Ne(this,$i,setTimeout((()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Be(this,Ki,"m",cn).call(this,t,e),Be(this,Ki,"m",mn).call(this,t,e)}),0),"f")}getConvertedRegion(){return Be(this,en,"f")}setScanRegion(t){if(null!=t&&!w(t)&&!I(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=Be(this,tn,"f").videoWidth,i=Be(this,tn,"f").videoHeight,n=this.getVideoFit(),{width:r,height:s}=this._innerComponent.getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===n&&(r/s1){const t=Be(this,tn,"f").videoWidth,e=Be(this,tn,"f").videoHeight,{width:n,height:r}=this._innerComponent.getBoundingClientRect(),s=t/e;if(n/rt.remove())),Be(this,an,"f").length=0}dispose(){this._unbindUI(),Ne(this,hn,!0,"f")}}function Sn(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Tn(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}Ji=new WeakMap,Qi=new WeakMap,$i=new WeakMap,tn=new WeakMap,en=new WeakMap,nn=new WeakMap,rn=new WeakMap,sn=new WeakMap,on=new WeakMap,an=new WeakMap,hn=new WeakMap,Ki=new WeakSet,ln=function(){return"disabled"!==this._singleFrameMode},cn=function(t,e){!e||0===e.x&&0===e.y&&e.width===t.width&&e.height===t.height?this.clearScanRegionMask():this.setScanRegionMask(e.x,e.y,e.width,e.height)},un=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},dn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},fn=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},gn=function(){this._divScanLight&&(this._divScanLight.style.display="none")},mn=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:n,objectFit:r}=t;e||(e={x:0,y:0,width:i,height:n});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/n;let l,c,u,d,f=1;if("contain"===r)a66||"Safari"===Rn.browser&&Rn.version>13||"OPR"===Rn.browser&&Rn.version>43||"Edge"===Rn.browser&&Rn.version,"function"==typeof SuppressedError&&SuppressedError;class Mn{static multiply(t,e){const i=[];for(let n=0;n<3;n++){const r=e.slice(3*n,3*n+3);for(let e=0;e<3;e++){const n=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*r[i]),0);i.push(n)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return Mn.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),n=Math.sin(e);return Mn.multiply(t,[i,-n,0,n,i,0,0,0,1])}static scale(t,e,i){return Mn.multiply(t,[e,0,0,0,i,0,0,0,1])}}var Fn,Pn,kn,Bn,Nn,jn,Un,Vn,Gn,Wn,Yn,Hn,Xn,zn,qn,Zn,Kn,Jn,Qn,$n,tr,er,ir,nr,rr,sr,or,ar,hr,lr,cr,ur,dr,fr,gr,mr,pr,_r,vr,yr,wr,Cr,Er,Sr,Tr,br,Ir,xr,Or,Ar;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(Fn||(Fn={}));class Rr{static get version(){return"1.1.3"}static get webGLSupported(){return void 0===Rr._webGLSupported&&(Rr._webGLSupported=!!document.createElement("canvas").getContext("webgl")),Rr._webGLSupported}get disposed(){return Dn(this,Un,"f")}constructor(){Pn.set(this,Fn.RGBA),kn.set(this,null),Bn.set(this,null),Nn.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,jn.set(this,null),Un.set(this,!1)}drawImage(t,e,i,n,r,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!n)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if((null==s?void 0:s.bUseWebGL)&&!Rr.webGLSupported)throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;Rr._onLog&&(o=Date.now(),Rr._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=n,u=0,d=0,f=i,g=n;r&&(r.sx&&(a=Math.round(r.sx)),r.sy&&(h=Math.round(r.sy)),r.sWidth&&(l=Math.round(r.sWidth)),r.sHeight&&(c=Math.round(r.sHeight)),r.dx&&(u=Math.round(r.dx)),r.dy&&(d=Math.round(r.dy)),r.dWidth&&(f=Math.round(r.dWidth)),r.dHeight&&(g=Math.round(r.dHeight)));let m,p=Fn.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!Rr.webGLSupported||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){Rr._onLog&&Rr._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=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},n=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},r=(t,e,i)=>{const n=t.createShader(e);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(n)}.`);throw e.name="WebGLError",e}return n},s="\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\n\nuniform mat3 u_matrix;\nuniform mat3 u_textureMatrix;\n\nvarying vec2 v_texCoord;\nvoid main(void) {\ngl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\nv_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n}";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_image;\nuniform float uColorFactor;\n\nvoid main() {\nvec4 sample = texture2D(u_image, v_texCoord);\nfloat grey = 0.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\ngl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n}`,h=n(t,[r(t,t.VERTEX_SHADER,s),r(t,t.FRAGMENT_SHADER,a)]);Ln(this,Bn,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),Ln(this,Nn,e(t),"f"),Ln(this,kn,i(t),"f"),Ln(this,Pn,p,"f")}const r=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const n=t.RGBA,r=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,n,r,s,i)},v=(t,e,s,o)=>{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),r(t,s.positions,e.attribLocations.vertexPosition),r(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[Fn.GREY,Fn.GREY32].includes(p)?1:0);let m,_,v=Mn.translate(Mn.identity(),-1,-1);v=Mn.scale(v,2,2),v=Mn.scale(v,1/t.canvas.width,1/t.canvas.height),m=Mn.translate(v,u,d),m=Mn.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=Mn.translate(Mn.identity(),a/i,h/n),_=Mn.scale(_,l/i,c/n),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,Dn(this,kn,"f"),e),v(t,Dn(this,Bn,"f"),Dn(this,Nn,"f"),Dn(this,kn,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){Rr._onLog&&Rr._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return Rr._onLog&&Rr._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===Fn.GREY?Fn.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return Rr._onLog&&Rr._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,n,r,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let n,r=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(r=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),n=new Uint8Array(i.buffer,0,4*o*a)):(n=new Uint8Array(4*o*a),e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,n))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(r,s,o,a),n=new Uint8Array(e.data.buffer),null==i||i.set(n)}return n}transformPixelFormat(t,e,i,n){let r,s;if(Rr._onLog&&(r=Date.now(),Rr._onLog("transformPixelFormat(), START: "+r)),e===i)return Rr._onLog&&Rr._onLog("transformPixelFormat() end. Costs: "+(Date.now()-r)),n?new Uint8Array(t):t;const o=[Fn.RGBA,Fn.RBGA,Fn.GRBA,Fn.GBRA,Fn.BRGA,Fn.BGRA];if(o.includes(e))if(i===Fn.GREY){s=new Uint8Array(t.length/4);for(let e=0;eh||e.sy+e.sHeight>l)throw new Error("Invalid position.");null===(n=Rr._onLog)||void 0===n||n.call(Rr,"getImageData(), START: "+(c=Date.now()));const d=Math.round(e.sx),f=Math.round(e.sy),g=Math.round(e.sWidth),m=Math.round(e.sHeight),p=Math.round(e.dWidth),_=Math.round(e.dHeight);let v,y=(null==i?void 0:i.pixelFormat)||Fn.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(Fn.GREY===y&&w.length{this.disposed||n.includes(r)&&r.apply(i.target,s)}),0);else try{o=r.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){Tn(this,Gn,!0,"f")}}Vn=new WeakMap,Gn=new WeakMap;const Lr=(t,e,i,n)=>{if(!i)return t;let r=e+Math.round((t-e)/i)*i;return n&&(r=Math.min(r,n)),r};class Mr{static get version(){return"2.0.18"}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 findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find((t=>e.includes(t.label.toLowerCase())));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],n=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],r=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!r.length)return null;const s=r.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const o=r.find((t=>{const e=t.label.toLowerCase();return n.some((t=>e.includes(t)))}));return o?o.deviceId:r[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(Rn.OS))return Mr.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(Rn.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise((async(n,r)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),n(t)},l=t=>{s&&clearTimeout(s),o(),r(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise((t=>{g=t})),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise((t=>{setTimeout(t,1e3)})),!a){i&&(s=setTimeout((()=>{o(),r(new Error("Failed to play video. Timeout."))}),i)),await m;try{await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a)try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}}))}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let n;try{n=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==n||n.getTracks().forEach((t=>{t.stop()}))}return{ok:!0}}get state(){if(!Sn(this,ir,"f"))return"closed";if("pending"===Sn(this,ir,"f"))return"opening";if("fulfilled"===Sn(this,ir,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Mr.isStorageAvailable("localStorage")?Tn(this,Qn,!0,"f"):(Tn(this,Qn,!1,"f"),console.warn("Local storage is unavailable")):Tn(this,Qn,!1,"f")}get ifSaveLastUsedCamera(){return Sn(this,Qn,"f")}get isVideoPlaying(){return!(!Sn(this,Hn,"f")||Sn(this,Hn,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,n;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=Sn(this,hr,"f"))||void 0===e||e.removeEventListener("click",Sn(this,ar,"f")),null===(i=Sn(this,hr,"f"))||void 0===i||i.removeEventListener("touchend",Sn(this,ar,"f")),null===(n=Sn(this,hr,"f"))||void 0===n||n.removeEventListener("touchmove",Sn(this,or,"f")),Tn(this,hr,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(Rn.OS)?(t.addEventListener("touchend",Sn(this,ar,"f")),t.addEventListener("touchmove",Sn(this,or,"f"))):t.addEventListener("click",Sn(this,ar,"f")))}get tapFocusEventBoundEl(){return Sn(this,hr,"f")}get disposed(){return Sn(this,_r,"f")}constructor(t){var e,i;Yn.add(this),Hn.set(this,null),Xn.set(this,void 0),zn.set(this,(()=>{"opened"===this.state&&Sn(this,dr,"f").fire("resumed",null,{target:this,async:!1})})),qn.set(this,(()=>{Sn(this,dr,"f").fire("paused",null,{target:this,async:!1})})),Zn.set(this,void 0),Kn.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],Jn.set(this,void 0),Qn.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,$n.set(this,void 0),tr.set(this,!0),er.set(this,void 0),ir.set(this,void 0),nr.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},rr.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,n;const r=window.getComputedStyle(Sn(this,Hn,"f")).objectFit,s=this.getResolution(),o=Sn(this,Hn,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=Sn(this,Hn,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===r)d>u?(f=l/s.width,i=(t-a)/f,n=(e-h-(c-l/d)/2)/f):(f=c/s.height,n=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==r)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,n=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,n=(e-h+(l/d-c)/2)/f)}return{x:i,y:n}},sr.set(this,!1),or.set(this,(()=>{Tn(this,sr,!0,"f")})),ar.set(this,(async t=>{var e;if(Sn(this,sr,"f"))return void Tn(this,sr,!1,"f");if(!Sn(this,rr,"f"))return;if(!this.isVideoPlaying)return;if(!Sn(this,Xn,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,n=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,n=t.changedTouches[0].clientY}const r=this.getResolution(),s=2*Math.round(Math.min(r.width,r.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,n)}catch(t){}if(o.x<0||o.x>r.width||o.y<0||o.y>r.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;Mr._onLog&&(c=Date.now());try{await Sn(this,Yn,"m",xr).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Mr._onLog)throw Mr._onLog(t),t}Mr._onLog&&Mr._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout((()=>{var t;Mr._onLog&&Mr._onLog("Back to continuous focus."),null===(t=Sn(this,Xn,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime),Sn(this,dr,"f").fire("tapfocus",null,{target:this,async:!1})})),hr.set(this,null),lr.set(this,1),cr.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!Sn(this,Hn,"f"))return;const t=Sn(this,lr,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)Sn(this,Hn,"f").style.transform="";else{const e=window.getComputedStyle(Sn(this,Hn,"f")).objectFit,i=Sn(this,Hn,"f").videoWidth,n=Sn(this,Hn,"f").videoHeight,{width:r,height:s}=Sn(this,Hn,"f").getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=r/s,a=i/n;let h=1;"contain"===e?h=oo?s/(i/t):r/(n/t));const l=h*(1-1/t)*(i/2-Sn(this,cr,"f").x),c=h*(1-1/t)*(n/2-Sn(this,cr,"f").y);Sn(this,Hn,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},ur.set(this,(function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===Fn.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(Mr._onLog&&Mr._onLog("document visible. video paused: "+(null===(t=Sn(this,Hn,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){Mr._onLog&&Mr._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){Mr._onLog&&Mr._onLog("document visible. 1st resume video failed, try open instead.")}e||await Sn(this,Yn,"m",Er).call(this)}if(await new Promise((t=>setTimeout(t,300))),!this.isVideoPlaying){Mr._onLog&&Mr._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){Mr._onLog&&Mr._onLog("document visible. 2rd resume video failed, try open instead.")}e||await Sn(this,Yn,"m",Er).call(this)}}}else"hidden"===document.visibilityState&&(Mr._onLog&&Mr._onLog("document hidden. video paused: "+(null===(e=Sn(this,Hn,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())})),_r.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout((()=>{Mr.onWarning&&Mr.onWarning("The browser is too old or the page is loaded from an insecure origin.")}),0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),Tn(this,dr,new Dr,"f"),this.imageDataGetter=new Rr,document.addEventListener("visibilitychange",Sn(this,pr,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",Sn(this,zn,"f")),t.addEventListener("pause",Sn(this,qn,"f")),Tn(this,Hn,t,"f")}getVideoEl(){return Sn(this,Hn,"f")}releaseVideoEl(){var t,e;null===(t=Sn(this,Hn,"f"))||void 0===t||t.removeEventListener("play",Sn(this,zn,"f")),null===(e=Sn(this,Hn,"f"))||void 0===e||e.removeEventListener("pause",Sn(this,qn,"f")),Tn(this,Hn,null,"f")}isVideoLoaded(){return!!Sn(this,Hn,"f")&&4==Sn(this,Hn,"f").readyState}async open(){if(Sn(this,er,"f")&&!Sn(this,tr,"f")){if("pending"===Sn(this,ir,"f"))return Sn(this,er,"f");if("fulfilled"===Sn(this,ir,"f"))return}Sn(this,dr,"f").fire("before:open",null,{target:this}),await Sn(this,Yn,"m",Er).call(this),Sn(this,dr,"f").fire("played",null,{target:this,async:!1}),Sn(this,dr,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;Sn(this,dr,"f").fire("before:close",null,{target:this});const t=Sn(this,er,"f");if(Sn(this,Yn,"m",Tr).call(this),t&&"pending"===Sn(this,ir,"f")){try{await t}catch(t){}if(!1===Sn(this,tr,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}Tn(this,er,null,"f"),Tn(this,ir,null,"f"),Sn(this,dr,"f").fire("closed",null,{target:this,async:!1})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");Sn(this,Hn,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await Sn(this,Hn,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof Sn(this,Zn,"f").video&&(Sn(this,Zn,"f").video={}),delete Sn(this,Zn,"f").video.facingMode,Sn(this,Zn,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&Sn(this,tr,"f"))){Sn(this,dr,"f").fire("before:camera:change",[],{target:this,async:!1}),await Sn(this,Yn,"m",Sr).call(this);try{this.resetSoftwareScale()}catch(t){}return Sn(this,Kn,"f")}}async switchToFrontCamera(t){if("object"!=typeof Sn(this,Zn,"f").video&&(Sn(this,Zn,"f").video={}),(null==t?void 0:t.resolution)&&(Sn(this,Zn,"f").video.width={ideal:t.resolution.width},Sn(this,Zn,"f").video.height={ideal:t.resolution.height}),delete Sn(this,Zn,"f").video.deviceId,Sn(this,Zn,"f").video.facingMode={exact:"user"},Tn(this,Jn,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&Sn(this,tr,"f"))){Sn(this,dr,"f").fire("before:camera:change",[],{target:this,async:!1}),Sn(this,Yn,"m",Sr).call(this);try{this.resetSoftwareScale()}catch(t){}return Sn(this,Kn,"f")}}getCamera(){var t;if(Sn(this,Kn,"f"))return Sn(this,Kn,"f");{let e=(null===(t=Sn(this,Zn,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});n=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}else n=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));const r=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind));return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof Sn(this,Zn,"f").video&&(Sn(this,Zn,"f").video={}),i?(Sn(this,Zn,"f").video.width={exact:t},Sn(this,Zn,"f").video.height={exact:e}):(Sn(this,Zn,"f").video.width={ideal:t},Sn(this,Zn,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&Sn(this,tr,"f"))return null;Sn(this,dr,"f").fire("before:resolution:change",[],{target:this,async:!1}),await Sn(this,Yn,"m",Sr).call(this);try{this.resetSoftwareScale()}catch(t){}const n=this.getResolution();return{width:n.width,height:n.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&Sn(this,Hn,"f"))return{width:Sn(this,Hn,"f").videoWidth,height:Sn(this,Hn,"f").videoHeight};if(Sn(this,Xn,"f")){const t=Sn(this,Xn,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:Sn(this,Hn,"f").videoWidth,height:Sn(this,Hn,"f").videoHeight};{const t={width:0,height:0};let e=Sn(this,Zn,"f").video.width||0,i=Sn(this,Zn,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,n,r,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=Sn(this,gr,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){d=null===(u=Sn(this,Kn,"f"))||void 0===u?void 0:u.deviceId;let e=Sn(this,gr,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],Sn(this,gr,"f").set(d,e),Tn(this,nr,!0,"f");try{for(let t of this.detectedResolutions){await Sn(this,Xn,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),Sn(this,Yn,"m",yr).call(this);const i=Sn(this,Xn,"f").getSettings(),n={width:i.width,height:i.height};f(d,n)||e.push({width:n.width,height:n.height})}}catch(t){throw Sn(this,Yn,"m",Tr).call(this),Tn(this,nr,!1,"f"),t}try{await Sn(this,Yn,"m",Er).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{Tn(this,nr,!1,"f")}return e}{const e=async(t,e,i)=>{const n={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let r=null;try{r=await navigator.mediaDevices.getUserMedia(n)}catch(t){return null}if(!r)return null;const s=r.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=r,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach((t=>{t.stop()})),o};let i=(null===(s=null===(r=null===(n=Sn(this,Zn,"f"))||void 0===n?void 0:n.video)||void 0===r?void 0:r.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=Sn(this,Zn,"f"))||void 0===o?void 0:o.video)||void 0===a?void 0:a.deviceId)||void 0===h?void 0:h.ideal)||(null===(c=null===(l=Sn(this,Zn,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=Sn(this,gr,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],Sn(this,gr,"f").set(i,u);for(let t of this.detectedResolutions){const n=await e(i,t.width,t.height);n&&!f(i,n)&&u.push({width:n.width,height:n.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");Tn(this,Zn,JSON.parse(JSON.stringify(t)),"f"),Tn(this,Jn,null,"f"),e&&Sn(this,Yn,"m",Sr).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(Sn(this,Zn,"f")))}resetMediaStreamConstraints(){Tn(this,Zn,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!Sn(this,Xn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Sn(this,Xn,"f").getCapabilities?Sn(this,Xn,"f").getCapabilities():{}}getCameraSettings(){if(!Sn(this,Xn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Sn(this,Xn,"f").getSettings()}async turnOnTorch(){if(!Sn(this,Xn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Sn(this,Xn,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!Sn(this,Xn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Sn(this,Xn,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Sn(this,Xn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Lr(t,n.min,n.step,n.max)),await Sn(this,Xn,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Sn(this,Xn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Lr(t,n.min,n.step,n.max)),await Sn(this,Xn,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Sn(this,Xn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!n)throw Error("Not supported.");e&&(tn.max&&(t=n.max));const r=this.getResolution();return await Sn(this,Xn,"f").applyConstraints({width:{ideal:Math.max(r.width,r.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!Sn(this,Xn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),n=null==i?void 0:i.focusMode,r=null==i?void 0:i.focusDistance;if(!n)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!n.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!r)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(ir.max&&(i=r.max),i=Lr(i,r.min,r.step,r.max)),this._focusParameters.focusArea=null,await Sn(this,Xn,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,n=t.area.height;if(!i||!n){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),n||(n=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:n},await Sn(this,Yn,"m",xr).call(this,e,i,n)}}}else this._focusParameters.focusArea=null,await Sn(this,Xn,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async enableTapToFocus(){Tn(this,rr,!0,"f")}disableTapToFocus(){Tn(this,rr,!1,"f")}isTapToFocusEnabled(){return Sn(this,rr,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"!==this.state)throw new Error("Video is not playing.");t.centerPoint?Sn(this,Yn,"m",Or).call(this,t.centerPoint):this.resetScaleCenter();try{if(Sn(this,Yn,"m",Ar).call(this,Sn(this,cr,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*Sn(this,lr,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!Sn(this,Xn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Lr(t,n.min,n.step,n.max)),await Sn(this,Xn,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&Sn(this,Yn,"m",Or).call(this,e),Tn(this,lr,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return Sn(this,lr,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();Tn(this,cr,{x:t.width/2,y:t.height/2},"f")}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(Sn(this,nr,"f"))return null;const e=Date.now();Mr._onLog&&Mr._onLog("getFrameData() START: "+e);const i=Sn(this,Hn,"f").videoWidth,n=Sn(this,Hn,"f").videoHeight;let r={sx:0,sy:0,sWidth:i,sHeight:n,dWidth:i,dHeight:n};(null==t?void 0:t.position)&&(r=JSON.parse(JSON.stringify(t.position)));let s=Fn.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=Sn(this,lr,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=Sn(this,cr,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,r=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))r=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.scaleCenter.y)/100*n}if(isNaN(e)||isNaN(r))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(r)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==n)return null;1!==o&&(r.sWidth=Math.round(r.sWidth/o),r.sHeight=Math.round(r.sHeight/o),r.sx=Math.round((1-1/o)*a.x+r.sx/o),r.sy=Math.round((1-1/o)*a.y+r.sy/o));const l=this.imageDataGetter.getImageData(Sn(this,Hn,"f"),r,{pixelFormat:s,bufferContainer:h});if(!l)return null;const c=Date.now();return Mr._onLog&&Mr._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:Sn(this,ur,"f")}}on(t,e){if(!Sn(this,fr,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);Sn(this,dr,"f").on(t,e)}off(t,e){Sn(this,dr,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),Sn(this,dr,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",Sn(this,pr,"f")),Tn(this,_r,!0,"f")}}var Fr,Pr,kr,Br,Nr,jr,Ur,Vr,Gr,Wr,Yr,Hr,Xr,zr,qr,Zr,Kr,Jr,Qr,$r,ts,es,is,ns,rs,ss,os,as,hs,ls,cs,us,ds,fs,gs;Hn=new WeakMap,Xn=new WeakMap,zn=new WeakMap,qn=new WeakMap,Zn=new WeakMap,Kn=new WeakMap,Jn=new WeakMap,Qn=new WeakMap,$n=new WeakMap,tr=new WeakMap,er=new WeakMap,ir=new WeakMap,nr=new WeakMap,rr=new WeakMap,sr=new WeakMap,or=new WeakMap,ar=new WeakMap,hr=new WeakMap,lr=new WeakMap,cr=new WeakMap,ur=new WeakMap,dr=new WeakMap,fr=new WeakMap,gr=new WeakMap,mr=new WeakMap,pr=new WeakMap,_r=new WeakMap,Yn=new WeakSet,vr=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(Sn(this,Jn,"f"))delete t.video.facingMode,t.video.deviceId={exact:Sn(this,Jn,"f")};else if(this.ifSaveLastUsedCamera&&Mr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(Rn.OS)?(await this._getCameras(!1),Sn(this,Yn,"m",yr).call(this),e=Mr.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(Rn.OS)||(await this._getCameras(!1),Sn(this,Yn,"m",yr).call(this),e=Mr.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const n=await e(i);n&&(delete t.video.facingMode,t.video.deviceId={exact:n})}return t},yr=function(){if(Sn(this,tr,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},wr=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;try{Mr._onLog&&Mr._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const r=async t=>{for(let r of e){r&&(await new Promise((t=>setTimeout(t,r))),Sn(this,Yn,"m",yr).call(this));try{Mr._onLog&&Mr._onLog("ask "+JSON.stringify(t)),n=await navigator.mediaDevices.getUserMedia(t),Sn(this,Yn,"m",yr).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Mr._onLog&&Mr._onLog(t.message||t)}}};if(await r(t),n||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await r(t)),!n&&t.video.facingMode&&(delete t.video.facingMode,await r(t)),n||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await r(t))),!n)throw i;return n}catch(t){throw null==n||n.getTracks().forEach((t=>{t.stop()})),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},Cr=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach((t=>{t.stop()})),this._mediaStream=null),Tn(this,Xn,null,"f")},Er=async function(){Tn(this,tr,!1,"f");const t=Tn(this,$n,Symbol(),"f");if(Sn(this,er,"f")&&"pending"===Sn(this,ir,"f")){try{await Sn(this,er,"f")}catch(t){}Sn(this,Yn,"m",yr).call(this)}if(t!==Sn(this,$n,"f"))return;const e=Tn(this,er,(async()=>{Tn(this,ir,"pending","f");try{if(this.videoSrc){if(!Sn(this,Hn,"f"))throw new Error("'videoEl' should be set.");await Mr.playVideo(Sn(this,Hn,"f"),this.videoSrc,this.cameraOpenTimeout),Sn(this,Yn,"m",yr).call(this)}else{let t=await Sn(this,Yn,"m",vr).call(this);Sn(this,Yn,"m",Cr).call(this);let e=await Sn(this,Yn,"m",wr).call(this,t);await this._getCameras(!1),Sn(this,Yn,"m",yr).call(this);const i=()=>{const t=e.getVideoTracks();let i,n;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,n=e;break}}return n},n=Sn(this,Zn,"f");if("object"==typeof n.video){let r=n.video.facingMode;if(r instanceof Array&&r.length&&(r=r[0]),"object"==typeof r&&(r=r.exact||r.ideal),!(Sn(this,Jn,"f")||this.ifSaveLastUsedCamera&&Mr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||n.video.deviceId)){const n=i(),s=Mr.findBestCamera(this._arrCameras,r,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==n?void 0:n.deviceId)&&(e.getTracks().forEach((t=>{t.stop()})),t.video.deviceId={exact:s},e=await Sn(this,Yn,"m",wr).call(this,t),Sn(this,Yn,"m",yr).call(this))}}const r=i();(null==r?void 0:r.deviceId)&&(Tn(this,Jn,r&&r.deviceId,"f"),this.ifSaveLastUsedCamera&&Mr.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",Sn(this,Jn,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),Sn(this,Hn,"f")&&(await Mr.playVideo(Sn(this,Hn,"f"),e,this.cameraOpenTimeout),Sn(this,Yn,"m",yr).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&Tn(this,Xn,s[0],"f"),Tn(this,Kn,r,"f")}}catch(t){throw Sn(this,Yn,"m",Tr).call(this),Tn(this,ir,null,"f"),t}Tn(this,ir,"fulfilled","f")})(),"f");return e},Sr=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=Sn(this,Kn,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await Sn(this,Yn,"m",Er).call(this);const n=this.getResolution();e&&e!==Sn(this,Kn,"f").deviceId&&Sn(this,dr,"f").fire("camera:changed",[Sn(this,Kn,"f").deviceId,e],{target:this,async:!1}),i.width==n.width&&i.height==n.height||Sn(this,dr,"f").fire("resolution:changed",[{width:n.width,height:n.height},{width:i.width,height:i.height}],{target:this,async:!1}),Sn(this,dr,"f").fire("played",null,{target:this,async:!1})},Tr=function(){Sn(this,Yn,"m",Cr).call(this),Tn(this,Kn,null,"f"),Sn(this,Hn,"f")&&(Sn(this,Hn,"f").srcObject=null,this.videoSrc&&(Sn(this,Hn,"f").pause(),Sn(this,Hn,"f").currentTime=0)),Tn(this,tr,!0,"f");try{this.resetSoftwareScale()}catch(t){}},br=async function t(e,i){const n=t=>{if(!Sn(this,Xn,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){Sn(this,Xn,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;i=Lr(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await Sn(this,Xn,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),n(e),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise((t=>{setTimeout(t,r)})),n(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h),a>l.width&&(a=l.width),h>l.height&&(h=l.height),s<0?s=0:s+a>l.width&&(s=l.width-a),o<0?o=0:o+h>l.height&&(o=l.height-h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(Sn(this,Hn,"f"),{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:Fn.RGBA,bufferContainer:d}))return Sn(this,Yn,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await Sn(this,Yn,"m",t).call(this,e,o,a,r,s,c,u)}else{let h=await Sn(this,Yn,"m",br).call(this,e,c);if(a>h)return await Sn(this,Yn,"m",t).call(this,e,o,a,r,s,c,h);if(a==h)return await Sn(this,Yn,"m",t).call(this,e,o,a,c,h);let u=await Sn(this,Yn,"m",br).call(this,e,l);if(u>a&&ao.width||h<0||h>o.height)throw new Error("Invalid 'centerPoint'.");let l=0;if(e.endsWith("px"))l=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");l=parseFloat(e)/100*o.width}if(isNaN(l)||l<0)throw new Error("Invalid 'width'.");let c=0;if(i.endsWith("px"))c=parseFloat(i);else{if(!i.endsWith("%"))throw new Error("Invalid 'height'.");c=parseFloat(i)/100*o.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==Sn(this,lr,"f")){const t=Sn(this,lr,"f"),e=Sn(this,cr,"f");l/=t,c/=t,a=(1-1/t)*e.x+a/t,h=(1-1/t)*e.y+h/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const u={focusL:a,focusT:h,focusW:l,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let n=Lr(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=Lr(Math.sqrt((e||this._focusParameters.fds.step)*n),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Lr(Math.sqrt(n*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await Sn(this,Yn,"m",br).call(this,t,s),a=await Sn(this,Yn,"m",br).call(this,t,r),h=await Sn(this,Yn,"m",br).call(this,t,n);if(a>h&&ho&&a>o){let e=await Sn(this,Yn,"m",br).call(this,t,i);const r=await Sn(this,Yn,"m",Ir).call(this,t,n,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,r}if(a==h&&hh){const e=await Sn(this,Yn,"m",Ir).call(this,t,n,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,n,r)},Or=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,n=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))n=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(n))throw new Error("Invalid scale center.");Tn(this,cr,{x:i,y:n},"f")},Ar=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},Mr.browserInfo=Rn,Mr.onWarning=null===(Wn=null===window||void 0===window?void 0:window.console)||void 0===Wn?void 0:Wn.warn;class ms{constructor(t){Fr.add(this),Pr.set(this,void 0),kr.set(this,0),Br.set(this,void 0),Nr.set(this,0),jr.set(this,!1),Ne(this,Pr,t,"f")}startCharging(){Be(this,jr,"f")||(ms._onLog&&ms._onLog("start charging."),Be(this,Fr,"m",Vr).call(this),Ne(this,jr,!0,"f"))}stopCharging(){Be(this,Br,"f")&&clearTimeout(Be(this,Br,"f")),Be(this,jr,"f")&&(ms._onLog&&ms._onLog("stop charging."),Ne(this,kr,Date.now()-Be(this,Nr,"f"),"f"),Ne(this,jr,!1,"f"))}}Pr=new WeakMap,kr=new WeakMap,Br=new WeakMap,Nr=new WeakMap,jr=new WeakMap,Fr=new WeakSet,Ur=function(){gt.cfd(1),ms._onLog&&ms._onLog("charge 1.")},Vr=function t(){0==Be(this,kr,"f")&&Be(this,Fr,"m",Ur).call(this),Ne(this,Nr,Date.now(),"f"),Be(this,Br,"f")&&clearTimeout(Be(this,Br,"f")),Ne(this,Br,setTimeout((()=>{Ne(this,kr,0,"f"),Be(this,Fr,"m",t).call(this)}),Be(this,Pr,"f")-Be(this,kr,"f")),"f")};class ps{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-Be(this,Gr,"f",Hr)<100)){if(Ne(this,Gr,e,"f",Hr),Be(this,Gr,"f",Wr).size&&(t=Be(this,Gr,"f",Wr).values().next().value,this.beepSoundSource==t.src?(Be(this,Gr,"f",Wr).delete(t),t.play()):t=null),!t)if(Be(this,Gr,"f",Yr).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout((()=>{Be(this,Gr,"f",Yr).delete(t)}),2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",(()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,Be(this,Gr,"f",Yr).delete(t),Be(this,Gr,"f",Wr).add(t)}))}else Be(this,Gr,"f",Xr)||(Ne(this,Gr,!0,"f",Xr),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&Be(this,Gr,"f",Yr).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(ps.vibrateDuration)}}}Gr=ps,Wr={value:new Set},Yr={value:new Set},Hr={value:0},Xr={value:!1},ps.allowBeep=!0,ps.beepSoundSource="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",ps.allowVibrate=!0,ps.vibrateDuration=300;const _s=new Map([[Fn.GREY,h.IPF_GRAYSCALED],[Fn.RGBA,h.IPF_ABGR_8888]]),vs="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};class ys extends z{static set _onLog(t){Ne(ys,qr,t,"f",Zr),Mr._onLog=t,ms._onLog=t}static get _onLog(){return Be(ys,qr,"f",Zr)}static async detectEnvironment(){return await(async()=>({wasm:je,worker:Ue,getUserMedia:Ve,camera:await Ge(),browser:ke.browser,version:ke.version,OS:ke.OS}))()}static async testCameraAccess(){const t=await Mr.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(t){var e,i;if(t&&!(t instanceof En))throw new TypeError("Invalid view.");if(null===(e=ct.license)||void 0===e?void 0:e.LicenseManager){if(!(null===(i=ct.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await gt.loadWasm(["license"]),await ct.license.dynamsoft()}const n=new ys(t);return ys.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{ys.onWarning&&ys.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{ys.onWarning&&ys.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),n}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");Ne(this,Qr,t,"f")}get singleFrameMode(){return Be(this,Qr,"f")}get _isFetchingStarted(){return Be(this,rs,"f")}get disposed(){return Be(this,ls,"f")}constructor(t){if(super(),zr.add(this),Kr.set(this,"closed"),Jr.set(this,void 0),this.isTorchOn=void 0,Qr.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},$r.set(this,((t,e,i,n)=>{const r=Date.now(),s={sx:n.x,sy:n.y,sWidth:n.width,sHeight:n.height,dWidth:n.width,dHeight:n.height},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const a=this.cameraManager.imageDataGetter.getImageData(t,s,{pixelFormat:this.getPixelFormat()===h.IPF_GRAYSCALED?Fn.GREY:Fn.RGBA});let l=null;if(a){const t=Date.now();let o;o=a.pixelFormat===Fn.GREY?a.width:4*a.width;let h=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(h=!1),l={bytes:a.data,width:a.width,height:a.height,stride:o,format:_s.get(a.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:wt.ITT_FILE_IMAGE,isCropped:h,cropRegion:{left:n.x,top:n.y,right:n.x+n.width,bottom:n.y+n.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:a.width,currentHeight:a.height,timeSpent:t-r,timeStamp:t},toCanvas:Be(this,ts,"f"),isDCEFrame:!0}}return l})),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():xi.convert(Be(this,is,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height});const i=Be(this,$r,"f").call(this,t,t.width,t.height,e);Be(this,Jr,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},ts.set(this,(function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.format===h.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(ke.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",(()=>{Be(this,hs,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("camera:changed",(()=>{this.clearBuffer()})),this._on("before:resolution:change",(()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("resolution:changed",(()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})})),this._on("paused",(()=>{Be(this,hs,"f").stopCharging();const t=this.cameraView;t&&t.disposed})),this._on("resumed",(()=>{const t=this.cameraView;t&&t.disposed})),this._on("tapfocus",(()=>{Be(this,os,"f").tapToFocus&&Be(this,hs,"f").startCharging()})),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,n,r,s;if(Be(this,zr,"m",cs).call(this)||!this.isOpen()||this.isPaused())return;const o=t.intermediateResultUnits;ys._onLog&&(ys._onLog("intermediateResultUnits:"),ys._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===Tt.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===Tt.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(ys._onLog&&(ys._onLog("hasLocalizedBarcodes:"),ys._onLog(h)),Be(this,os,"f").autoZoom||Be(this,os,"f").enhancedFocus)if(a)Be(this,as,"f").autoZoomInFrameArray.length=0,Be(this,as,"f").autoZoomOutFrameCount=0,Be(this,as,"f").frameArrayInIdealZoom.length=0,Be(this,as,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),Be(this,os,"f").autoZoom&&Be(this,hs,"f").startCharging()},a=async t=>{await this.setFocus(t),Be(this,os,"f").enhancedFocus&&Be(this,hs,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(n=h.cropRegion)||void 0===n?void 0:n.top)||0,u=(null===(r=h.cropRegion)||void 0===r?void 0:r.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,n,r;{const t=this.video.videoWidth*(1-Be(this,as,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+Be(this,as,"f").autoZoomDetectionArea)/2,i=e,n=t,s=this.video.videoHeight*(1-Be(this,as,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+Be(this,as,"f").autoZoomDetectionArea)/2;r=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:n,y:a}]}ys._onLog&&(ys._onLog("detectionArea:"),ys._onLog(r));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let n=!1;const r=t.length;if(r<=2)return!1;for(let s=0;s0!=Li(a.y-i)>0&&Li(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(n=!n)}return n}(e,t.x,t.y)},n=(t,e)=>!!(Mi([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||Mi([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||Mi([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||Mi([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(n([e[0].x,e[0].y,e[1].x,e[1].y],t)||n([e[1].x,e[1].y,e[2].x,e[2].y],t)||n([e[2].x,e[2].y,e[3].x,e[3].y],t)||n([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of o)if(e.unitType===Tt.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach((t=>{En._transformCoordinates(t,l,c,u,d,f,g)})),t(r,e)&&s.push(i)}if(ys._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=pn.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===Tt.IRUT_LOCALIZED_BARCODES)for(let n of i.localizedBarcodes){if(!n)continue;const i=n.location.points,r=new _i({points:i},e);t.addDrawingItems([r])}}}if(ys._onLog&&(ys._onLog("intersectedResults:"),ys._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter((t=>t.possibleFormats==vs.BF_QR_CODE||t.possibleFormats==vs.BF_DATAMATRIX));if(t.length||(t=s.filter((t=>t.possibleFormats==vs.BF_ONED)),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,n=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(n-g/2)*(n-g/2)};a=t[0];let i=e(a);if(1!=t.length)for(let n=1;n1.1*a.confidence||t[n].confidence>.9*a.confidence&&ri&&s>i&&o>i&&h>i&&m.result.moduleSize{})),Be(this,as,"f").autoZoomInFrameArray.filter((t=>!0===t)).length>=Be(this,as,"f").autoZoomInFrameLimit[1]){Be(this,as,"f").autoZoomInFrameArray.length=0;const i=[(.5-n)/(.5-r),(.5-n)/(.5-s),(.5-n)/(.5-o),(.5-n)/(.5-h)].filter((t=>t>0)),a=Math.min(...i,Be(this,as,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/Be(this,as,"f").autoZoomInMaxTimes),Be(this,as,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max(Be(this,as,"f").minValue,u),u=Math.min(Be(this,as,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(Be(this,as,"f").autoZoomInFrameArray.length=0,Be(this,as,"f").frameArrayInIdealZoom.push(!0),Be(this,as,"f").frameArrayInIdealZoom.splice(0,Be(this,as,"f").frameArrayInIdealZoom.length-Be(this,as,"f").frameLimitInIdealZoom[0]),Be(this,as,"f").frameArrayInIdealZoom.filter((t=>!0===t)).length>=Be(this,as,"f").frameLimitInIdealZoom[1]&&(Be(this,as,"f").frameArrayInIdealZoom.length=0,Be(this,os,"f").enhancedFocus)){const e=m.points;try{await a({mode:"manual",area:{centerPoint:{x:(e[0].x+e[2].x)/2+"px",y:(e[0].y+e[2].y)/2+"px"},width:e[2].x-e[0].x+"px",height:e[2].y-e[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}if(!Be(this,os,"f").autoZoom&&Be(this,os,"f").enhancedFocus&&(Be(this,as,"f").autoFocusFrameArray.push(!0),Be(this,as,"f").autoFocusFrameArray.splice(0,Be(this,as,"f").autoFocusFrameArray.length-Be(this,as,"f").autoFocusFrameLimit[0]),Be(this,as,"f").autoFocusFrameArray.filter((t=>!0===t)).length>=Be(this,as,"f").autoFocusFrameLimit[1])){Be(this,as,"f").autoFocusFrameArray.length=0;try{const t=m.points;await a({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(Be(this,os,"f").autoZoom){if(Be(this,as,"f").autoZoomInFrameArray.push(!1),Be(this,as,"f").autoZoomInFrameArray.splice(0,Be(this,as,"f").autoZoomInFrameArray.length-Be(this,as,"f").autoZoomInFrameLimit[0]),Be(this,as,"f").autoZoomOutFrameCount++,Be(this,as,"f").frameArrayInIdealZoom.push(!1),Be(this,as,"f").frameArrayInIdealZoom.splice(0,Be(this,as,"f").frameArrayInIdealZoom.length-Be(this,as,"f").frameLimitInIdealZoom[0]),Be(this,as,"f").autoZoomOutFrameCount>=Be(this,as,"f").autoZoomOutFrameLimit){Be(this,as,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let n=i-Math.max((i-1)*Be(this,as,"f").autoZoomOutStepRate,Be(this,as,"f").autoZoomOutMinStep);n=Math.max(Be(this,as,"f").minValue,n),n=Math.min(Be(this,as,"f").maxValue,n);try{await e({factor:n})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}Be(this,os,"f").enhancedFocus&&a({mode:"continuous"}).catch((()=>{}))}!Be(this,os,"f").autoZoom&&Be(this,os,"f").enhancedFocus&&(Be(this,as,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch((()=>{})))}}},Ne(this,hs,new ms(1e4),"f")}setCameraView(t){if(!(t instanceof En))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),Be(this,zr,"m",cs).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;Be(this,zr,"m",cs).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return Be(this,zr,"m",cs).call(this)?Be(this,Kr,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){const t=this.cameraView;if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");t&&(t._singleFrameMode=this.singleFrameMode,Be(this,zr,"m",cs).call(this)?t._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(t.getVideoElement()),t._startLoading()));let e={width:0,height:0,deviceId:""};if(Be(this,zr,"m",cs).call(this));else{try{await this.cameraManager.open()}catch(e){throw t&&t._stopLoading(),"NotFoundError"===e.name?new Error(`No camera devices were detected. Please ensure a camera is connected and recognized by your system. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):"NotAllowedError"===e.name?new Error(`Camera access is blocked. Please check your browser settings or grant permission to use the camera. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):e}let i,n=t.getUIElement();if(n=n.shadowRoot||n,i=n.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=n.elTorchAuto=n.querySelector(".dce-mn-torch-auto"),e=n.elTorchOn=n.querySelector(".dce-mn-torch-on"),r=n.elTorchOff=n.querySelector(".dce-mn-torch-off");t&&(e.style.display=null==this.isTorchOn?"":"none"),e&&(e.style.display=1==this.isTorchOn?"":"none"),r&&(r.style.display=0==this.isTorchOn?"":"none");let s=n.elBeepOn=n.querySelector(".dce-mn-beep-on"),o=n.elBeepOff=n.querySelector(".dce-mn-beep-off");s&&(s.style.display=ps.allowBeep?"":"none"),o&&(o.style.display=ps.allowBeep?"none":"");let a=n.elVibrateOn=n.querySelector(".dce-mn-vibrate-on"),h=n.elVibrateOff=n.querySelector(".dce-mn-vibrate-off");a&&(a.style.display=ps.allowVibrate?"":"none"),h&&(h.style.display=ps.allowVibrate?"none":""),n.elResolutionBox=n.querySelector(".dce-mn-resolution-box");let l,c=n.elZoom=n.querySelector(".dce-mn-zoom");c&&(c.style.display="none",l=n.elZoomSpan=c.querySelector("span"));let u=n.elToast=n.querySelector(".dce-mn-toast"),d=n.elCameraClose=n.querySelector(".dce-mn-camera-close"),f=n.elTakePhoto=n.querySelector(".dce-mn-take-photo"),g=n.elCameraSwitch=n.querySelector(".dce-mn-camera-switch"),m=n.elCameraAndResolutionSettings=n.querySelector(".dce-mn-camera-and-resolution-settings");m&&(m.style.display="none");const p=n.dceMnFs={},_=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",_);const v=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",v);const y=()=>{this.turnAutoTorch()};null==r||r.addEventListener("pointerdown",y);const w=()=>{ps.allowBeep=!ps.allowBeep,s&&(s.style.display=ps.allowBeep?"":"none"),o&&(o.style.display=ps.allowBeep?"none":"")};for(let t of[o,s])null==t||t.addEventListener("pointerdown",w);const C=()=>{ps.allowVibrate=!ps.allowVibrate,a&&(a.style.display=ps.allowVibrate?"":"none"),h&&(h.style.display=ps.allowVibrate?"none":"")};for(let t of[h,a])null==t||t.addEventListener("pointerdown",C);const E=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),n=parseInt(e.getAttribute("data-height")),r=await this.setResolution({width:i,height:n});{let e=Math.max(r.width,r.height),i=Math.min(r.width,r.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&b(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?m&&(m.style.display=m.style.display?"":"none"):m&&""===m.style.display&&(m.style.display="none"))};n.addEventListener("click",E);let S=null;p.funcInfoZoomChange=(t,e=3e3)=>{c&&l&&(l.textContent=t.toFixed(1),c.style.display="",null!=S&&(clearTimeout(S),S=null),S=setTimeout((()=>{c.style.display="none",S=null}),e))};let T=null,b=p.funcShowToast=(t,e=3e3)=>{u&&(u.textContent=t,u.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout((()=>{u.style.display="none",T=null}),e))};const I=()=>{this.close()};null==d||d.addEventListener("click",I);const x=()=>{};null==f||f.addEventListener("pointerdown",x);const O=()=>{var t,e;let i,n=this.getVideoSettings(),r=n.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),o=null==s?void 0:s.indexOf("front");-1===o&&(o=null==s?void 0:s.indexOf("前"));let a=null==s?void 0:s.indexOf("back");-1===a&&(a=null==s?void 0:s.indexOf("后")),"number"==typeof o&&-1!==o?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i&&(i="user"===((null==r?void 0:r.ideal)||(null==r?void 0:r.exact)||r)),n.video.facingMode={ideal:i?"environment":"user"},delete n.video.deviceId,this.updateVideoSettings(n)};null==g||g.addEventListener("pointerdown",O);let A=-1/0,R=1;const D=t=>{let e=Date.now();e-A>1e3&&(R=this.getZoomSettings().factor),R-=t.deltaY/200,R>20&&(R=20),R<1&&(R=1),this.setZoom({factor:R}),A=e};i.addEventListener("wheel",D);const L=new Map;let M=!1;const F=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],n=t.touches[1],r=L.get(i.identifier),s=L.get(n.identifier);if(!r||!s)break;let o=Math.pow(Math.pow(r.x-s.x,2)+Math.pow(r.y-s.y,2),.5),a=Math.pow(Math.pow(i.clientX-n.clientX,2)+Math.pow(i.clientY-n.clientY,2),.5),h=Date.now();if(M||h-A<100)return;h-A>1e3&&(R=this.getZoomSettings().factor),R*=a/o,R>20&&(R=20),R<1&&(R=1);let l=!1;"safari"==(null===(e=null==ke?void 0:ke.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/o>1&&R<2?(R=2,l=!0):a/o<1&&R<2&&(R=1,l=!0)),M=!0,l&&b("zooming..."),await this.setZoom({factor:R}),l&&(u.textContent=""),M=!1,A=Date.now();break}L.clear();for(let e of t.touches)L.set(e.identifier,{x:e.clientX,y:e.clientY})};n.addEventListener("touchstart",F),n.addEventListener("touchmove",F),n.addEventListener("touchend",F),n.addEventListener("touchcancel",F),p.unbind=()=>{null==t||t.removeEventListener("pointerdown",_),null==e||e.removeEventListener("pointerdown",v),null==r||r.removeEventListener("pointerdown",y);for(let t of[o,s])null==t||t.removeEventListener("pointerdown",w);for(let t of[h,a])null==t||t.removeEventListener("pointerdown",C);n.removeEventListener("click",E),null==d||d.removeEventListener("click",I),null==f||f.removeEventListener("pointerdown",x),null==g||g.removeEventListener("pointerdown",O),i.removeEventListener("wheel",D),n.removeEventListener("touchstart",F),n.removeEventListener("touchmove",F),n.removeEventListener("touchend",F),n.removeEventListener("touchcancel",F),delete n.dceMnFs,i.style.display="none"},i.style.display="",t&&null==this.isTorchOn&&setTimeout((()=>{this.turnAutoTorch(1e3)}),0)}this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const r=this.getResolution();e.width=r.width,e.height=r.height,e.deviceId=this.getSelectedCamera().deviceId}return Ne(this,Kr,"open","f"),t&&(t._innerComponent.style.display="",Be(this,zr,"m",cs).call(this)||(t._stopLoading(),t._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),t._renderResolutionInfo({width:e.width,height:e.height}),t.eventHandler.fire("content:updated",null,{async:!1}),t.eventHandler.fire("videoEl:resized",null,{async:!1}))),Be(this,Jr,"f").fire("opened",null,{target:this,async:!1}),e}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),Be(this,zr,"m",cs).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}Ne(this,Kr,"closed","f"),Be(this,hs,"f").stopCharging(),e&&(e._innerComponent.style.display="none",Be(this,zr,"m",cs).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),Be(this,Jr,"f").fire("closed",null,{target:this,async:!1})}pause(){if(Be(this,zr,"m",cs).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!Be(this,zr,"m",cs).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(Be(this,zr,"m",cs).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){if(!t)throw new Error("Invalid value.");let e;e="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(e),this.isTorchOn=!1;const i=this.getResolution(),n=this.cameraView;return n&&!n.disposed&&(n._stopLoading(),n._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),n._renderResolutionInfo({width:i.width,height:i.height})),{width:i.width,height:i.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Be(this,Jr,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Be(this,Jr,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._on(n,e)}off(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._off(n,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(Be(this,zr,"m",cs).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(Be(this,zr,"m",cs).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){if(null!=this._taskid4AutoTorch){if(!(t{var t,r,s;if(this.disposed||e||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++n>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let o;try{o=this.fetchImage()}catch(t){}if(!o||!o.width||!o.height)return;let a=0;if(h.IPF_GRAYSCALED===o.format){for(let t=0;t=this.maxDarkCount4AutoTroch){null===(t=ys._onLog)||void 0===t||t.call(ys,`darkCount ${i}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(r=null==t?void 0:t.dceMnFs)||void 0===r||r.funcShowToast("Torch Auto On")}catch(t){console.warn(t),e=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,null===(s=null==i?void 0:i.dceMnFs)||void 0===s||s.funcShowToast("Torch Not Supported")}}}else i=0};this._taskid4AutoTorch=setInterval(r,t),this.isTorchOn=void 0,r();let s=this.cameraView.getUIElement();s=s.shadowRoot||s,s.elTorchAuto&&(s.elTorchAuto.style.display=""),s.elTorchOn&&(s.elTorchOn.style.display="none"),s.elTorchOff&&(s.elTorchOff.style.display="none")}async setColorTemperature(t){if(Be(this,zr,"m",cs).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(Be(this,zr,"m",cs).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,n;if(Be(this,zr,"m",cs).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(n=null==e?void 0:e.dceMnFs)||void 0===n||n.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(Be(this,zr,"m",cs).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(Be(this,zr,"m",cs).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(Be(this,zr,"m",cs).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){Be(this,as,"f").minValue=t.min,Be(this,as,"f").maxValue=t.max}getAutoZoomRange(){return{min:Be(this,as,"f").minValue,max:Be(this,as,"f").maxValue}}async enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=ct.license)||void 0===e?void 0:e.LicenseManager)||void 0===i?void 0:i.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==gt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&Ze.EF_ENHANCED_FOCUS&&(Be(this,os,"f").enhancedFocus=!0),t&Ze.EF_AUTO_ZOOM&&(Be(this,os,"f").autoZoom=!0),t&Ze.EF_TAP_TO_FOCUS&&(Be(this,os,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&Ze.EF_ENHANCED_FOCUS&&(Be(this,os,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch((()=>{}))),t&Ze.EF_AUTO_ZOOM&&(Be(this,os,"f").autoZoom=!1,this.resetZoom().catch((()=>{}))),t&Ze.EF_TAP_TO_FOCUS&&(Be(this,os,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),Be(this,zr,"m",ds).call(this)&&Be(this,zr,"m",us).call(this)||Be(this,hs,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!w(t)&&!I(t))throw TypeError("Invalid 'region'.");Ne(this,is,t?JSON.parse(JSON.stringify(t)):null,"f"),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(Be(this,is,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");Ne(this,es,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||Be(this,zr,"m",cs).call(this))}startFetching(){if(Be(this,zr,"m",cs).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");Be(this,rs,"f")||(Ne(this,rs,!0,"f"),Be(this,zr,"m",fs).call(this))}stopFetching(){Be(this,rs,"f")&&(ys._onLog&&ys._onLog("DCE: stop fetching loop: "+Date.now()),Be(this,ss,"f")&&clearTimeout(Be(this,ss,"f")),Ne(this,rs,!1,"f"))}fetchImage(){if(Be(this,zr,"m",cs).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(4!==this.video.readyState)throw new Error("The video is not loaded.");const t=this.getResolution();if(!(null==t?void 0:t.width)||!(null==t?void 0:t.height))throw new Error("The video is not loaded.");let e;if(e=xi.convert(Be(this,is,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height}),e.x>t.width||e.y>t.height)throw new Error("Invalid scan region.");e.x+e.width>t.width&&(e.width=t.width-e.x),e.y+e.height>t.height&&(e.height=t.height-e.y);const i={sx:e.x,sy:e.y,sWidth:e.width,sHeight:e.height,dWidth:e.width,dHeight:e.height},n=Math.max(i.dWidth,i.dHeight);if(this.canvasSizeLimit&&n>this.canvasSizeLimit){const t=this.canvasSizeLimit/n;i.dWidth>i.dHeight?(i.dWidth=this.canvasSizeLimit,i.dHeight=Math.round(i.dHeight*t)):(i.dWidth=Math.round(i.dWidth*t),i.dHeight=this.canvasSizeLimit)}const r=this.cameraManager.getFrameData({position:i,pixelFormat:this.getPixelFormat()===h.IPF_GRAYSCALED?Fn.GREY:Fn.RGBA});if(!r)return null;let s;s=r.pixelFormat===Fn.GREY?r.width:4*r.width;let o=!0;return 0===i.sx&&0===i.sy&&i.sWidth===t.width&&i.sHeight===t.height&&(o=!1),{bytes:r.data,width:r.width,height:r.height,stride:s,format:_s.get(r.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:wt.ITT_VIDEO_FRAME,isCropped:o,cropRegion:{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height,isMeasuredInPercentage:!1},originalWidth:t.width,originalHeight:t.height,currentWidth:r.width,currentHeight:r.height,timeSpent:r.timeSpent,timeStamp:r.timeStamp},toCanvas:Be(this,ts,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,Be(this,rs,"f")&&(Be(this,ss,"f")&&clearTimeout(Be(this,ss,"f")),Ne(this,ss,setTimeout((()=>{this.disposed||Be(this,zr,"m",fs).call(this)}),t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){Ne(this,ns,t,"f")}getPixelFormat(){return Be(this,ns,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(Be(this,zr,"m",cs).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",(()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",(()=>{t&&this.open(),e.remove()}),{once:!0})})),e.addEventListener("change",(async()=>{const i=e.files[0],n=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise(((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(i),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let o=xi.convert(Be(this,is,"f"),r,s);o||(o={x:0,y:0,width:r,height:s});const a=Be(this,$r,"f").call(this,n,r,s,o);t&&t(a)})),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=Be(this,zr,"m",gs).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=Be(this,zr,"m",gs).call(this,t);return{x:e.clientX,y:e.clientY}}convertToScanRegionCoordinates(t){if(!Be(this,is,"f"))return JSON.parse(JSON.stringify(t));let e,i,n=Be(this,is,"f").left||Be(this,is,"f").x||0,r=Be(this,is,"f").top||Be(this,is,"f").y||0;if(!Be(this,is,"f").isMeasuredInPercentage)return{x:t.x-n,y:t.y-r};if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!Be(this,zr,"m",cs).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Be(this,zr,"m",cs).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(Be(this,zr,"m",cs).call(this)){const t=this.cameraView._innerComponent.getElement("content");e=t.width,i=t.height}else{const t=this.getVideoEl();e=t.videoWidth,i=t.videoHeight}return{x:t.x-Math.round(n*e/100),y:t.y-Math.round(r*i/100)}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),Ne(this,ls,!0,"f")}}var ws,Cs,Es,Ss,Ts,bs,Is,xs;qr=ys,Kr=new WeakMap,Jr=new WeakMap,Qr=new WeakMap,$r=new WeakMap,ts=new WeakMap,es=new WeakMap,is=new WeakMap,ns=new WeakMap,rs=new WeakMap,ss=new WeakMap,os=new WeakMap,as=new WeakMap,hs=new WeakMap,ls=new WeakMap,zr=new WeakSet,cs=function(){return"disabled"!==this.singleFrameMode},us=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},ds=function(){for(let t in Be(this,os,"f"))if(1==Be(this,os,"f")[t])return!0;return!1},fs=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!Be(this,rs,"f"))return Be(this,ss,"f")&&clearTimeout(Be(this,ss,"f")),void Ne(this,ss,setTimeout((()=>{this.disposed||Be(this,zr,"m",t).call(this)}),this.fetchInterval),"f");const e=()=>{var t;let e;ys._onLog&&ys._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{e=this.fetchImage()}catch(e){const i=e.message||e;if("The video is not loaded."===i)return;if(null===(t=Be(this,es,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout((()=>{var t;null===(t=Be(this,es,"f"))||void 0===t||t.onErrorReceived(_t.EC_IMAGE_READ_FAILED,i)}),0);console.warn(e)}e?(this.addImageToBuffer(e),ys._onLog&&ys._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),Be(this,Jr,"f").fire("frameAddedToBuffer",null,{async:!1})):ys._onLog&&ys._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case o.BOPM_BLOCK:break;case o.BOPM_UPDATE:e()}else e();Be(this,ss,"f")&&clearTimeout(Be(this,ss,"f")),Ne(this,ss,setTimeout((()=>{this.disposed||Be(this,zr,"m",t).call(this)}),this.fetchInterval),"f")},gs=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!Be(this,zr,"m",cs).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Be(this,zr,"m",cs).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,n=e.top,r=i+window.scrollX,s=n+window.scrollY,{width:o,height:a}=this.cameraView._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(Be(this,zr,"m",cs).call(this)){const t=this.cameraView._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=this.cameraView.getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)u{var e;if(!this.isUseMagnifier)return;if(Be(this,Ss,"f")||Ne(this,Ss,new Os,"f"),!Be(this,Ss,"f").magnifierCanvas)return;document.body.contains(Be(this,Ss,"f").magnifierCanvas)||(Be(this,Ss,"f").magnifierCanvas.style.position="fixed",Be(this,Ss,"f").magnifierCanvas.style.boxSizing="content-box",Be(this,Ss,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(Be(this,Ss,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void Be(this,bs,"f").call(this);const n=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!n)return;const r=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*r,o=[{image:i,width:i.width,height:i.height},{image:n,width:n.width,height:n.height}];Be(this,Ss,"f").update(s,t.pointer,r,o);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(Be(this,Ss,"f").magnifierCanvas.style.left="auto",Be(this,Ss,"f").magnifierCanvas.style.top="0",Be(this,Ss,"f").magnifierCanvas.style.right="0"):(Be(this,Ss,"f").magnifierCanvas.style.left="0",Be(this,Ss,"f").magnifierCanvas.style.top="0",Be(this,Ss,"f").magnifierCanvas.style.right="auto")}Be(this,Ss,"f").show()})),bs.set(this,(()=>{Be(this,Ss,"f")&&Be(this,Ss,"f").hide()})),Is.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Fi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=document.createElement("dce-component"),e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let n=this._innerComponent.getElement("content");n||(n=document.createElement("canvas"),n.style.objectFit="contain",this._innerComponent.setElement("content",n)),n.width===e&&n.height===i||(n.width=e,n.height=i);const r=n.getContext("2d");r.clearRect(0,0,n.width,n.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),r.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&r.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(y(t)){Ne(this,Es,t,"f");const{width:e,height:i,bytes:n,format:r}=Object.assign({},t);let s;if(r===h.IPF_GRAYSCALED){s=new Uint8ClampedArray(e*i*4);for(let t=0;t({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const n=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new Je.Control({positionHandler:fi,actionHandler:pi(i>0?i-1:n,mi),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let n=t.x-i.pathOffset.x,r=t.y-i.pathOffset.y;const s=Je.util.transformPoint({x:n,y:r},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){Be(this,wi,"f")&&this.setLine(Be(this,wi,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!E(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else Ne(this,wi,JSON.parse(JSON.stringify(t)),"f")}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return Be(this,wi,"f")?JSON.parse(JSON.stringify(Be(this,wi,"f"))):null}},QuadDrawingItem:Ei,RectDrawingItem:di,TextDrawingItem:yi});const Ds="undefined"==typeof self,Ls=Ds?{}:self,Ms="function"==typeof importScripts,Fs=(()=>{if(!Ms){if(!Ds&&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"./"}})(),Ps=t=>t&&"object"==typeof t&&"function"==typeof t.then,ks=(async()=>{})().constructor;let Bs=class extends ks{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,Ps(t)?e=t:"function"==typeof t&&(e=new ks(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}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(Ps(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Ns=" is not allowed to change after `createInstance` or `loadWasm` is called.",js=!Ds&&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"))||"",Us=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Ns);i._license=e}};!Ds&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Vs=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{e=Vs(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Ns);i._licenseServer=e}},Ws=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Ns);i._deviceFriendlyName=e}};let Ys,Hs,Xs,zs,qs;"undefined"!=typeof navigator&&(Ys=navigator,Hs=Ys.userAgent,Xs=Ys.platform,zs=Ys.mediaDevices),function(){if(!Ds){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Ys.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Xs,search:"Win"},Mac:{str:Xs},Linux:{str:Xs}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||Hs,o=r.search||e,a=r.verStr||Hs,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Hs,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=Hs.indexOf("Windows NT")&&(r="HarmonyOS"),qs={browser:i,version:n,OS:r}}Ds&&(qs={browser:"ssr",version:0,OS:"ssr"})}(),zs&&zs.getUserMedia,"Chrome"===qs.browser&&qs.version>66||"Safari"===qs.browser&&qs.version>13||"OPR"===qs.browser&&qs.version>43||"Edge"===qs.browser&&qs.version;const Zs=()=>(ft("license"),tt("dynamsoft_inited",(async()=>{let{lt:t,l:e,ls:i,sp:n,rmk:r,cv:s}=((t,e=!1)=>{const i=t;if(i._pLoad.isEmpty){let n,r,s,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(r=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=Vs(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),n=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(Ls.crypto||(s="Please upgrade your browser to support online key."),Ls.crypto.subtle||(s="Require https to use online key in this browser."))),s)throw new Error(s);return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:n,cv:r}}throw new Error("Can't preprocess license again"+Ns)})(Js),o=new Bs;Js._pLoad.task=o,(async()=>{try{await Js._pLoad}catch(t){}})();let a=nt();rt[a]=e=>{if(e.message&&Js._onAuthMessage){let t=Js._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,n=!1;if(1===t&&(n=!0),e.success?(st&&st("init license success"),e.message&&console.warn(e.message),gt._bSupportIRTModule=e.bSupportIRTModule,gt._bSupportDce4Module=e.bSupportDce4Module,Js.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):o.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),n||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(n=!0)),n){const t=A(gt.engineResourcePaths);(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let n=await fetch(t.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 s=document.createElement("div");s.innerHTML=r;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("["),n=e.indexOf("]",i),r=e.indexOf("(",n),s=e.indexOf(")",r);if(-1==i||-1==n||-1==r||-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,n);o.innerText=a;let h=e.substring(r+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)}})({_bNeverShowDialog:Js._bNeverShowDialog,engineResourcePath:t.license,_onLog:st},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await $("core"),et.postMessage({type:"license_dynamsoft",body:{v:"3.4.31",brtk:!!t,bptk:1===t,l:e,os:qs,fn:Js.deviceFriendlyName,ls:i,sp:n,rmk:r,cv:s},id:a}),Js.bCallInitLicense=!0,await o})));let Ks;ct.license={},ct.license.dynamsoft=Zs,ct.license.getAR=async()=>{{let t=Q.dynamsoft_inited;t&&t.isRejected&&await t}return et?new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success){delete i.success;{let t=Js.license;t&&(t.startsWith("t")||t.startsWith("f"))&&(i.pk=t)}if(Object.keys(i).length){if(i.lem){let t=Error(i.lem);t.ltsErrorCode=i.lec,delete i.lem,delete i.lec,i.ae=t}t(i)}else t(null)}else{let t=Error(i.message);i.stack&&(t.stack=i.stack),e(t)}},et.postMessage({type:"license_getAR",id:i})})):null};let Js=class t{static setLicenseServer(e){Gs(t,e)}static get license(){return this._license}static set license(e){Us(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Gs(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){Ws(t,e)}static initLicense(e,i){if(Us(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return Zs()}static setDeviceFriendlyName(e){Ws(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await tt("dynamsoft_uuid",(async()=>{await ft();let t=new Bs,e=nt();rt[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},et.postMessage({type:"license_getDeviceUUID",id:e}),Ks=await t})),Ks))()}};Js._pLoad=new Bs,Js.bPassValidation=!1,Js.bCallInitLicense=!1,Js._license=js,Js._licenseServer=[],Js._deviceFriendlyName="",gt.engineResourcePaths.license={version:"3.4.31",path:Fs,isInternal:!0},ut.license={wasm:!0,js:!0},ct.license.LicenseManager=Js;const Qs="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&O(gt.engineResourcePaths.std.version,Qs)<0&&(gt.engineResourcePaths.std={version:Qs,path:(t=>{if(null==t&&(t="./"),Ds||Ms);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(Fs+`../../dynamsoft-capture-vision-std@${Qs}/dist/`),isInternal:!0});var $s=Object.freeze({__proto__:null,LicenseManager:Js,LicenseModule:class{static getVersion(){return`3.4.31(Worker: ${lt.license&<.license.worker||"Not Loaded"}, Wasm: ${lt.license&<.license.wasm||"Not Loaded"})`}}});const to=()=>window.matchMedia("(orientation: landscape)").matches;function eo(t,e){for(const n in e)"Object"===(i=e[n],Object.prototype.toString.call(i).slice(8,-1))&&n in t?eo(t[n],e[n]):t[n]=e[n];var i;return t}const io=async t=>{let e;await new Promise(((i,n)=>{e=new Image,e.onload=()=>i(e),e.onerror=n,e.src=URL.createObjectURL(t)}));const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=e.width,i.height=e.height,n.drawImage(e,0,0),{bytes:Uint8Array.from(n.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:10}};const no="undefined"==typeof self,ro="function"==typeof importScripts,so=(()=>{if(!ro){if(!no&&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"./"}})(),oo=t=>{if(null==t&&(t="./"),no||ro);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};gt.engineResourcePaths.utility={version:"1.4.32",path:so,isInternal:!0},ut.utility={js:!0,wasm:!0};const ao="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&O(gt.engineResourcePaths.std.version,ao)<0&&(gt.engineResourcePaths.std={version:ao,path:oo(so+`../../dynamsoft-capture-vision-std@${ao}/dist/`),isInternal:!0});const ho="2.4.31";(!gt.engineResourcePaths.dip||"string"!=typeof gt.engineResourcePaths.dip&&O(gt.engineResourcePaths.dip.version,ho)<0)&&(gt.engineResourcePaths.dip={version:ho,path:oo(so+`../../dynamsoft-image-processing@${ho}/dist/`),isInternal:!0});function lo(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}var co,uo,fo,go,mo;function po(t,e){let i=!0;for(let o=0;o1)return Math.sqrt((h-o)**2+(l-a)**2);{const t=r+u*(o-r),e=s+u*(a-s);return Math.sqrt((h-t)**2+(l-e)**2)}}function yo(t){const e=[];for(let i=0;i=0&&h<=1&&l>=0&&l<=1?{x:t.x+l*r,y:t.y+l*s}:null}function Eo(t){let e=0;for(let i=0;i0}function To(t,e){for(let i=0;i<4;i++)if(!So(t.points[i],t.points[(i+1)%4],e))return!1;return!0}"function"==typeof SuppressedError&&SuppressedError;function bo(t,e,i,n){const r=t.points,s=e.points;let o=8*i;o=Math.max(o,5);const a=yo(r)[3],h=yo(r)[1],l=yo(s)[3],c=yo(s)[1];let u,d=0;if(u=Math.max(Math.abs(vo(a,e.points[0])),Math.abs(vo(a,e.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(vo(h,e.points[1])),Math.abs(vo(h,e.points[2]))),u>d&&(d=u),u=Math.max(Math.abs(vo(l,t.points[0])),Math.abs(vo(l,t.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(vo(c,t.points[1])),Math.abs(vo(c,t.points[2]))),u>d&&(d=u),d>o)return!1;const f=wo(yo(r)[0]),g=wo(yo(r)[2]),m=wo(yo(s)[0]),p=wo(yo(s)[2]),_=_o(f,p),v=_o(m,g),y=_>v,w=Math.min(_,v),C=_o(f,g),E=_o(m,p);let S=12*i;return S=Math.max(S,5),S=Math.min(S,C),S=Math.min(S,E),!!(w{e.x+=t,e.y+=i})),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,n=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-n.area)>.4*i.area)return!1;let r=new Array(4).fill(0),s=new Array(4).fill(0),o=0,a=0;for(let t=0;t<4;++t)r[t]=Math.round(100*(n.points[t].x-i.points[t].x))/100,o+=r[t],s[t]=Math.round(100*(n.points[t].y-i.points[t].y))/100,a+=s[t];o/=4,a/=4;for(let t=0;t<4;++t){if(Math.abs(r[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1;if(Math.abs(s[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1}return e.x=o,e.y=a,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(To(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(To(this.location,e))return!0}else{for(let e=0;e<4;e++)if(To(t,this.location.points[e]))return!0;if(To(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const n=[this.location.points[0],this.location.points[3]],r=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],s=0===t||3===t?n:r;if(Math.abs(vo(s,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const n=t.location.points[i],r=this.location.points[i];if(!(Math.abs(r.x+e.x-n.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const n=Object.assign({},t.location);for(let t=0;t<4;t++)n.points[t].x-=e.x,n.points[t].y-=e.y;if(!this.isLocationOverlap(n,t.location.area))return!1;if(i){const t=.75;return function(t,e){const i=[];for(let n=0;n<4;n++)for(let r=0;r<4;r++){const s=Co(t[n],t[(n+1)%4],e[r],e[(r+1)%4]);s&&i.push(s)}return t.forEach((t=>{po(e,t)&&i.push(t)})),e.forEach((e=>{po(t,e)&&i.push(e)})),Eo(function(t){if(t.length<=1)return t;t.sort(((t,e)=>t.x-e.x||t.y-e.y));const e=t.shift();return t.sort(((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x))),[e,...t]}(i))}([...this.location.points],n.points)>this.locationArea*t}return!0}}const xo={BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096)},Oo={barcode:2,text_line:4,detected_quad:8,normalized_image:16},Ao=t=>Object.values(Oo).includes(t)||Oo.hasOwnProperty(t),Ro=(t,e)=>"string"==typeof t?e[Oo[t]]:e[t],Do=(t,e,i)=>{"string"==typeof t?e[Oo[t]]=i:e[t]=i},Lo=(t,e,i)=>{const n=[8,16].includes(i);if(!n&&t.isResultCrossVerificationEnabled(i))for(let t=0;t{Do(e,this.verificationEnabled,t)})),lo(this,uo,"f").forEach(((t,e)=>{Do(e,this.duplicateFilterEnabled,t)})),lo(this,fo,"f").forEach(((t,e)=>{Do(e,this.duplicateForgetTime,t)})),lo(this,go,"f").forEach(((t,e)=>{Do(e,this.latestOverlappingEnabled,t)})),lo(this,mo,"f").forEach(((t,e)=>{Do(e,this.maxOverlappingFrames,t)}))}enableResultCrossVerification(t,e){Ao(t)&&lo(this,co,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!Ao(t)&&Ro(t,this.verificationEnabled)}enableResultDeduplication(t,e){Ao(t)&&(e&&this.enableLatestOverlapping(t,!1),lo(this,uo,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!Ao(t)&&Ro(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){Ao(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),lo(this,fo,"f").set(t,e))}getDuplicateForgetTime(t){return Ao(t)?Ro(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){Ao(t)&&lo(this,mo,"f").set(t,e)}getMaxOverlappingFrames(t){return Ao(t)?Ro(t,this.maxOverlappingFrames):-1}enableLatestOverlapping(t,e){Ao(t)&&(e&&this.enableResultDeduplication(t,!1),lo(this,go,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!Ao(t)&&Ro(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[mt.CRIT_BARCODE,mt.CRIT_TEXT_LINE,mt.CRIT_DETECTED_QUAD,mt.CRIT_NORMALIZED_IMAGE];for(let i=0;i{if(1!==t.type){const e=(BigInt(t.format)&BigInt(xo.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(xo.BF_GS1_DATABAR))!=BigInt(0);return new Io(h,e?1:2,e,t)}})).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(l).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t)).length;r>p&&(p=r,m=n,g.x=i.x,g.y=i.y)}}if(0===p){for(let e=0;e-1!=t)).length}let i=this.overlapSet.length<=3?p>=1:p>=2;if(!i&&s&&u>0){let t=0;for(let e=0;e=1:t>=3}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach(((t,e)=>{if(1!==t.type){const i=Object.assign({},t),n=(BigInt(t.format)&BigInt(xo.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(xo.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0)))}f.sort(((t,e)=>e-t)).forEach(((e,i)=>{t.items.splice(e,1)})),d.forEach((e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))}))}}onDecodedBarcodesReceived(t){this.latestOverlappingFilter(t),Lo(this,t.items,mt.CRIT_BARCODE)}onRecognizedTextLinesReceived(t){Lo(this,t.items,mt.CRIT_TEXT_LINE)}onDetectedQuadsReceived(t){Lo(this,t.items,mt.CRIT_DETECTED_QUAD)}onNormalizedImagesReceived(t){Lo(this,t.items,mt.CRIT_NORMALIZED_IMAGE)}}co=new WeakMap,uo=new WeakMap,fo=new WeakMap,go=new WeakMap,mo=new WeakMap;var Fo,Po,ko,Bo,No,jo,Uo,Vo,Go,Wo,Yo,Ho,Xo,zo,qo,Zo,Ko,Jo,Qo,$o,ta,ea=Object.freeze({__proto__:null,ImageManager:class{async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const n=M(t);return R(n,e,i)}async drawOnImage(t,e,i,n=4294901760,r=1,s){let o;if(t instanceof Blob)o=await io(t);else if("string"==typeof t){let e=await x(t,"blob");o=await io(e)}return await new Promise(((t,a)=>{let h=nt();rt[h]=async e=>{if(e.success)return s&&this.saveToFile(e.image,"test.png",s),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},et.postMessage({type:"utility_drawOnImage",id:h,body:{dsImage:o,drawingItem:e instanceof Array?e:[e],color:n,thickness:r,type:i}})}))}},MultiFrameResultCrossFilter:Mo,UtilityModule:class{static getVersion(){return`1.4.32(Worker: ${lt.utility&<.utility.worker||"Not Loaded"}, Wasm: ${lt.utility&<.utility.wasm||"Not Loaded"})`}}});class ia{constructor(e){if(Fo.add(this),Bo.set(this,void 0),No.set(this,{status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success."},barcodeResults:[]}),jo.set(this,!1),Uo.set(this,void 0),Vo.set(this,void 0),this.config=Nt,e&&"object"!=typeof e||Array.isArray(e))throw"Invalid config.";eo(this.config,e)}async launch(){if(At(this,jo,"f"))throw new Error("The BarcodeScanner instance has been destroyed.");if(At(ia,Po,"f",ko)&&!At(ia,Po,"f",ko).isFulfilled)throw new Error("Cannot call `launch()` while a previous task is still running.");return Rt(ia,Po,new Vt,"f",ko),await At(this,Fo,"m",Go).call(this),At(ia,Po,"f",ko)}async decode(t,e="ReadBarcodes_Default"){return Rt(this,Vo,e,"f"),await At(this,Fo,"m",Wo).call(this,!0),this._cvRouter.capture(t,e)}dispose(){Rt(this,jo,!0,"f"),At(ia,Po,"f",ko)&&At(ia,Po,"f",ko).isPending&&At(ia,Po,"f",ko).resolve(At(this,No,"f")),this._cameraEnhancer?.dispose(),this._cameraView?.dispose(),this._cvRouter?.dispose(),this._cameraEnhancer=null,this._cameraView=null,this._cvRouter=null,window.removeEventListener("resize",At(this,Bo,"f")),document.querySelector(".scanner-view-container")?.remove(),document.querySelector(".result-view-container")?.remove(),document.querySelector(".barcode-scanner-container")?.remove(),document.querySelector(".loading-page")?.remove()}}Po=ia,Bo=new WeakMap,No=new WeakMap,jo=new WeakMap,Uo=new WeakMap,Vo=new WeakMap,Fo=new WeakSet,Go=async function(){try{await At(this,Fo,"m",Wo).call(this);try{await this._cameraEnhancer.open()}catch(t){At(this,Fo,"m",ta).call(this);document.querySelector(".no-camera-view").style.display="flex"}await this._cvRouter.startCapturing(At(this,Vo,"f"))}catch(e){At(this,No,"f").status={code:t.EnumResultStatus.RS_FAILED,message:e.message||e},At(ia,Po,"f",ko).reject(new Error(At(this,No,"f").status.message)),this.dispose()}finally{const t=document.querySelector(".loading-page");t&&(t.style.display="none")}},Wo=async function(e=!1){gt.engineResourcePaths=this.config.engineResourcePaths,e||(this._cameraView=await En.createInstance(),this.config.scanMode===t.EnumScanMode.SM_SINGLE&&(this._cameraView._capturedResultReceiver.onCapturedResultReceived=()=>{}),await At(this,Fo,"m",Ho).call(this)),await Js.initLicense(this.config.license||"",{executeNow:!0}),this._cvRouter=this._cvRouter||await Ee.createInstance(),await At(this,Fo,"m",Yo).call(this,e),e||(this._cameraEnhancer=await ys.createInstance(this._cameraView),this._cvRouter.setInput(this._cameraEnhancer),At(this,Fo,"m",Xo).call(this),await At(this,Fo,"m",zo).call(this))},Yo=async function(e=!1){e||(this.config.scanMode===t.EnumScanMode.SM_SINGLE?Rt(this,Vo,this.config.utilizedTemplateNames.single,"f"):this.config.scanMode===t.EnumScanMode.SM_MULTI_UNIQUE&&Rt(this,Vo,this.config.utilizedTemplateNames.multi_unique,"f")),this.config.templateFilePath&&await this._cvRouter.initSettings(this.config.templateFilePath);const i=await this._cvRouter.getSimplifiedSettings(At(this,Vo,"f"));e||this.config.scanMode!==t.EnumScanMode.SM_SINGLE||(i.capturedResultItemTypes=mt.CRIT_ORIGINAL_IMAGE|mt.CRIT_BARCODE);let n=this.config.barcodeFormats;if(n){Array.isArray(n)||(n=[n]),i.barcodeSettings.barcodeFormatIds=BigInt(0);for(let t=0;t{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const n=document.createElement("div");if(n.insertAdjacentHTML("beforeend",i),1===n.childElementCount&&n.firstChild instanceof HTMLTemplateElement)return n.firstChild.content;const r=new DocumentFragment;for(let t of n.children)r.append(t);return r})(i);n.querySelectorAll("style").forEach((t=>{document.head.appendChild(t.cloneNode(!0))})),Rt(this,Uo,n.querySelector(".result-item"),"f");const r=n.querySelector(".btn-clear");if(r&&(r.addEventListener("click",(()=>{At(this,No,"f").barcodeResults=[],At(this,Fo,"m",Qo).call(this)})),this.config?.resultViewConfig?.toolbarButtonsConfig?.clear)){const t=this.config.resultViewConfig.toolbarButtonsConfig.clear;r.style.display=t.isHidden?"none":"flex",r.className=t.className?t.className:"btn-clear",r.innerText=t.label?t.label:"Clear",t.isHidden&&(n.querySelector(".toolbar-btns").style.justifyContent="center")}const s=n.querySelector(".btn-done");if(s&&(s.addEventListener("click",(()=>{const t=document.querySelector(".loading-page");t&&"none"===getComputedStyle(t).display&&this.dispose()})),this.config?.resultViewConfig?.toolbarButtonsConfig?.done)){const t=this.config.resultViewConfig.toolbarButtonsConfig.done;s.style.display=t.isHidden?"none":"flex",s.className=t.className?t.className:"btn-done",s.innerText=t.label?t.label:"Done",t.isHidden&&(n.querySelector(".toolbar-btns").style.justifyContent="center")}const o=this.config?.scannerViewConfig?.showCloseButton;if(o){const e=n.querySelector(".btn-close");e&&(e.style.display="",e.addEventListener("click",(()=>{At(this,No,"f").barcodeResults=[],At(this,No,"f").status={code:t.EnumResultStatus.RS_CANCELLED,message:"Cancelled."},this.dispose()})))}this.config.showUploadImageButton&&At(this,Fo,"m",ta).call(this,n.querySelector(".btn-upload-image"));const a=this._cameraView.getUIElement();a.shadowRoot.querySelector(".dce-sel-camera").remove(),a.shadowRoot.querySelector(".dce-sel-resolution").remove(),this._cameraView.setVideoFit("cover");const h=n.querySelector(".barcode-scanner-container");h.style.display=to()?"flex":"";const l=this.config.showResultView&&this.config.scanMode!==t.EnumScanMode.SM_SINGLE;let c;if(this.config.container?(h.style.position="relative",c=this.config.container):c=document.body,"string"==typeof c&&(c=document.querySelector(c),null===c))throw new Error("Failed to get the container");let u=this.config.scannerViewConfig.container;if("string"==typeof u&&(u=document.querySelector(u),null===u))throw new Error("Failed to get the container of the scanner view.");let d=this.config.resultViewConfig.container;if("string"==typeof d&&(d=document.querySelector(d),null===d))throw new Error("Failed to get the container of the result view.");const f=n.querySelector(".scanner-view-container"),g=n.querySelector(".result-view-container"),m=n.querySelector(".loading-page");f.append(m),u&&(f.append(a),u.append(f)),d&&d.append(g),u||d?u&&!d?(this.config.container||(g.style.position="absolute"),d=g,c.append(g)):!u&&d&&(this.config.container||(f.style.position="absolute"),u=f,f.append(a),c.append(f)):(u=f,d=g,l&&(Object.assign(f.style,{width:to()?"50%":"100%",height:to()?"100%":"50%"}),Object.assign(g.style,{width:to()?"50%":"100%",height:to()?"100%":"50%"})),f.append(a),c.append(h)),document.querySelector(".result-view-container").style.display=l?"":"none",this.config.removePoweredByMessage&&(a.shadowRoot.querySelector(".dce-msg-poweredby").style.display="none",document.querySelector(".no-result-svg").style.display="none"),Rt(this,Bo,(()=>{Object.assign(h.style,{display:to()?"flex":""}),!l||this.config.scannerViewConfig.container||this.config.resultViewConfig.container||(Object.assign(u.style,{width:to()?"50%":"100%",height:to()?"100%":"50%"}),Object.assign(d.style,{width:to()?"50%":"100%",height:to()?"100%":"50%"}))}),"f"),window.addEventListener("resize",At(this,Bo,"f")),this._cameraView._createDrawingLayer(2)},Xo=function(){const e=new Ie;let i=0;e.onCapturedResultReceived=async e=>{e.barcodeResultItems&&(this.config.scanMode===t.EnumScanMode.SM_SINGLE?2==++i&&At(this,Fo,"m",qo).call(this,e):At(this,Fo,"m",Zo).call(this,e))},this._cvRouter.addResultReceiver(e)},zo=async function(){const t=new Mo;t.enableResultCrossVerification(2,!0),t.enableResultDeduplication(2,!0),t.setDuplicateForgetTime(2,this.config.duplicateForgetTime),t.onDecodedBarcodesReceived=()=>{},await this._cvRouter.addResultFilter(t)},qo=function(e){const i=this._cameraView.getUIElement().shadowRoot;let n=new Promise((t=>{if(e.barcodeResultItems.length>1){At(this,Fo,"m",Jo).call(this);for(let n of e.barcodeResultItems){let e=0,r=0;for(let t=0;t<4;++t){let i=n.location.points[t];e+=i.x,r+=i.y}let s=this._cameraEnhancer.convertToClientCoordinates({x:e/4,y:r/4}),o=document.createElement("div");o.className="single-barcode-result-option",Object.assign(o.style,{position:"fixed",width:"32px",height:"32px",border:"#fff solid 4px","box-sizing":"border-box","border-radius":"16px",background:"#080",cursor:"pointer",transform:"translate(-50%, -50%)"}),o.style.left=s.x+"px",o.style.top=s.y+"px",o.addEventListener("click",(()=>{t(n)})),i.append(o)}}else t(e.barcodeResultItems[0])}));n.then((i=>{const n=e.items.filter((t=>t.type===mt.CRIT_ORIGINAL_IMAGE))[0].imageData,r={status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success."},originalImageResult:n,barcodeImage:(()=>{const t=D(n),e=i.location.points,r=Math.min(...e.map((t=>t.x))),s=Math.min(...e.map((t=>t.y))),o=Math.max(...e.map((t=>t.x))),a=Math.max(...e.map((t=>t.y))),l=o-r,c=a-s,u=document.createElement("canvas");u.width=l,u.height=c;const d=u.getContext("2d");d.beginPath(),d.moveTo(e[0].x-r,e[0].y-s);for(let t=1;tt.id===`${i.formatString}_${i.text}`));-1===t?(i.count=1,At(this,No,"f").barcodeResults.unshift(i),At(this,Fo,"m",Qo).call(this,i)):(At(this,No,"f").barcodeResults[t].count++,At(this,Fo,"m",$o).call(this,t)),this.config.onUniqueBarcodeScanned&&this.config.onUniqueBarcodeScanned(i)}},Ko=function(t){const e=At(this,Uo,"f").cloneNode(!0);e.querySelector(".format-string").innerText=t.formatString;e.querySelector(".text-string").innerText=t.text.replace(/\n|\r/g,""),e.id=`${t.formatString}_${t.text}`;return e.querySelector(".delete-icon").addEventListener("click",(()=>{const e=[...document.querySelectorAll(".main-list .result-item")],i=e.findIndex((e=>e.id===`${t.formatString}_${t.text}`));At(this,No,"f").barcodeResults.splice(i,1),e[i].remove()})),e},Jo=function(){const t=this._cameraView.getUIElement().shadowRoot;if(t.querySelector(".single-mode-mask"))return;const e=document.createElement("div");e.className="single-mode-mask",Object.assign(e.style,{width:"100%",height:"100%",position:"absolute",top:"0",left:"0",right:"0",bottom:"0","background-color":"#4C4C4C",opacity:"0.5"}),t.append(e),this._cameraEnhancer.pause(),this._cvRouter.stopCapturing()},Qo=function(e){const i=document.querySelector(".no-result-svg");if(!(this.config.showResultView&&this.config.scanMode!==t.EnumScanMode.SM_SINGLE))return;const n=document.querySelector(".main-list");if(!e)return n.textContent="",void(i.style.display="");i.style.display="none";const r=At(this,Fo,"m",Ko).call(this,e);n.insertBefore(r,document.querySelector(".result-item"))},$o=function(t){const e=document.querySelectorAll(".main-list .result-item"),i=e[t].querySelector(".result-count");let n=parseInt(i.textContent.replace("x",""));e[t].querySelector(".result-count").textContent="x"+ ++n},ta=function(e){e||(e=document.querySelector(".btn-upload-image")),e&&(e.style.display="",e.addEventListener("change",(async e=>{const i=e.target.files,n={status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success."},barcodeResults:[]};for(let e of i)try{const t=await this.decode(e,this.config.utilizedTemplateNames.image);t.barcodeResultItems&&n.barcodeResults.push(...t.barcodeResultItems)}catch(e){n.status={code:t.EnumResultStatus.RS_FAILED,message:e.message||e},At(ia,Po,"f",ko).reject(n.status.message),this.dispose()}At(ia,Po,"f",ko).resolve(n),this.dispose()})))},ko={value:null};const na="undefined"==typeof self,ra="function"==typeof importScripts,sa=(()=>{if(!ra){if(!na&&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"./"}})(),oa=t=>{if(null==t&&(t="./"),na||ra);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};gt.engineResourcePaths.dbr={version:"10.4.31",path:sa,isInternal:!0},ut.dbr={js:!1,wasm:!0,deps:["license","dip"]},ct.dbr={};const aa="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&O(gt.engineResourcePaths.std.version,aa)<0&&(gt.engineResourcePaths.std={version:aa,path:oa(sa+`../../dynamsoft-capture-vision-std@${aa}/dist/`),isInternal:!0});const ha="2.4.31";(!gt.engineResourcePaths.dip||"string"!=typeof gt.engineResourcePaths.dip&&O(gt.engineResourcePaths.dip.version,ha)<0)&&(gt.engineResourcePaths.dip={version:ha,path:oa(sa+`../../dynamsoft-image-processing@${ha}/dist/`),isInternal:!0});const la={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)};var ca,ua,da,fa;!function(t){t[t.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",t[t.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",t[t.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(ca||(ca={})),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"}(ua||(ua={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",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",t[t.LM_SKIP=0]="LM_SKIP"}(da||(da={})),function(t){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",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP"}(fa||(fa={}));var ga=Object.freeze({__proto__:null,BarcodeReaderModule:class{static getVersion(){const t=lt.dbr&<.dbr.wasm;return`10.4.31(Worker: ${lt.dbr&<.dbr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}},EnumBarcodeFormat:la,get EnumDeblurMode(){return fa},get EnumExtendedBarcodeResultType(){return ca},get EnumLocalizationMode(){return da},get EnumQRCodeErrorCorrectionLevel(){return ua}});Ee._defaultTemplate="ReadSingleBarcode",t.BarcodeScanner=ia,t.CVR=Oe,t.Core=xt,t.DBR=ga,t.DCE=Rs,t.License=$s,t.Utility=ea})); diff --git a/dist/dbr.bundle.mjs b/dist/dbr.bundle.mjs index 43a1ab1..531689d 100644 --- a/dist/dbr.bundle.mjs +++ b/dist/dbr.bundle.mjs @@ -4,8 +4,8 @@ * @website http://www.dynamsoft.com * @copyright Copyright 2025, Dynamsoft Corporation * @author Dynamsoft -* @version 10.4.3100 +* @version 10.5.3000 * @fileoverview Dynamsoft JavaScript Library for Barcode Reader * More info on dbr JS: https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/ */ -const t=t=>t&&"object"==typeof t&&"function"==typeof t.then,e=(async()=>{})().constructor;let i=class extends 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(i){let r;this._task=i,t(i)?r=i:"function"==typeof i&&(r=new e(i)),r&&(async()=>{try{const t=await r;i===this._task&&this.resolve(t)}catch(t){i===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}constructor(e){let i,r;super(((t,e)=>{i=t,r=e})),this._s="pending",this.resolve=e=>{this.isPending&&(t(e)?this.task=e:(this._s="fulfilled",i(e)))},this.reject=t=>{this.isPending&&(this._s="rejected",r(t))},this.task=e}};function r(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function n(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}var s,o,a;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(s||(s={})),function(t){t[t.CCUT_AUTO=0]="CCUT_AUTO",t[t.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",t[t.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",t[t.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",t[t.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",t[t.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(o||(o={})),function(t){t[t.IPF_BINARY=0]="IPF_BINARY",t[t.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",t[t.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",t[t.IPF_NV21=3]="IPF_NV21",t[t.IPF_RGB_565=4]="IPF_RGB_565",t[t.IPF_RGB_555=5]="IPF_RGB_555",t[t.IPF_RGB_888=6]="IPF_RGB_888",t[t.IPF_ARGB_8888=7]="IPF_ARGB_8888",t[t.IPF_RGB_161616=8]="IPF_RGB_161616",t[t.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",t[t.IPF_ABGR_8888=10]="IPF_ABGR_8888",t[t.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",t[t.IPF_BGR_888=12]="IPF_BGR_888",t[t.IPF_BINARY_8=13]="IPF_BINARY_8",t[t.IPF_NV12=14]="IPF_NV12",t[t.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(a||(a={}));const h="undefined"==typeof self,l="function"==typeof importScripts,c=(()=>{if(!l){if(!h&&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"./"}})(),u=t=>{if(null==t&&(t="./"),h||l);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},d=t=>Object.prototype.toString.call(t),f=t=>Array.isArray?Array.isArray(t):"[object Array]"===d(t),g=t=>"[object Boolean]"===d(t),m=t=>"number"==typeof t&&!Number.isNaN(t),p=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),_=t=>!(!p(t)||!m(t.x)||!m(t.y)||!m(t.radius)||t.radius<0||!m(t.startAngle)||!m(t.endAngle)),v=t=>!!p(t)&&!!f(t.points)&&0!=t.points.length&&!t.points.some((t=>!b(t))),y=t=>!(!p(t)||!m(t.width)||t.width<=0||!m(t.height)||t.height<=0||!m(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!T(t.tag)),w=t=>!(!y(t)||!m(t.bytes.length)&&!m(t.bytes.ptr)),C=t=>!!y(t)&&t.bytes instanceof Uint8Array,E=t=>!(!p(t)||!m(t.left)||t.left<0||!m(t.top)||t.top<0||!m(t.right)||t.right<0||!m(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom||!g(t.isMeasuredInPercentage)),T=t=>null===t||!!p(t)&&!!m(t.imageId)&&"type"in t,S=t=>!(!p(t)||!b(t.startPoint)||!b(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),b=t=>!!p(t)&&!!m(t.x)&&!!m(t.y),I=t=>!!p(t)&&!!f(t.points)&&0!=t.points.length&&!t.points.some((t=>!b(t))),x=t=>!!p(t)&&!!f(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some((t=>!b(t))),A=t=>!(!p(t)||!m(t.x)||!m(t.y)||!m(t.width)||t.width<0||!m(t.height)||t.height<0||"isMeasuredInPercentage"in t&&!g(t.isMeasuredInPercentage)),O=async(t,e)=>await new Promise(((i,r)=>{let n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType=e,n.send(),n.onloadend=async()=>{n.status<200||n.status>=300?r(new Error(t+" "+n.status)):i(n.response)},n.onerror=()=>{r(new Error("Network Error: "+n.statusText))}})),R=t=>/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t),D=(t,e)=>{let i=t.split("."),r=e.split(".");for(let t=0;t{const e={},i={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcpd:"dynamsoft-code-parser",dlrData:"dynamsoft-label-recognizer-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer"};for(let r in t){if("rootDirectory"===r)continue;let n=r,s=t[n],o=s&&"object"==typeof s&&s.path?s.path:s,a=t.rootDirectory;if(a&&!a.endsWith("/")&&(a+="/"),"object"==typeof s&&s.isInternal)a&&(o=t[n].version?`${a}${i[n]}@${t[n].version}/dist/${"ddv"===n?"engine":""}`:`${a}${i[n]}/dist/${"ddv"===n?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof o&&(o=o.replace(i,a||"")),"object"==typeof o&&"dwt"===n){const r=t[n].resourcesPath,s=t[n].serviceInstallerLocation;e[n]={resourcesPath:r.replace(i,a||""),serviceInstallerLocation:s.replace(i,a||"")};continue}}e[n]=u(o)}return e},M=async(t,e,i)=>await new Promise((async(r,n)=>{try{const n=e.split(".");let s=n[n.length-1];const o=await k(`image/${s}`,t);n.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return r(a)}catch(t){return n()}})),F=t=>{C(t)&&(t=B(t));const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d",{willReadFrequently:!0}).putImageData(t,0,0),e},P=(t,e)=>{C(e)&&(e=B(e));const i=F(e);let r=new Image,n=i.toDataURL(t);return r.src=n,r},k=async(t,e)=>{C(e)&&(e=B(e));const i=F(e);return new Promise(((e,r)=>{i.toBlob((t=>e(t)),t)}))},B=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===a.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let r=0;r=n)break;e[o]=e[o+1]=e[o+2]=(128&r)/128*255,e[o+3]=255,r<<=1}}}else if(Number(t.format)===a.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let r=0;r=n)break;e[o]=e[o+1]=e[o+2]=128&r?0:255,e[o+3]=255,r<<=1}}}return new ImageData(e,t.width,t.height)};var N,j,U,V,G,W,Y,H;let X,z,Z,q,K,J=class t{get _isFetchingStarted(){return r(this,G,"f")}constructor(){N.add(this),j.set(this,[]),U.set(this,1),V.set(this,s.BOPM_BLOCK),G.set(this,!1),W.set(this,void 0),Y.set(this,o.CCUT_AUTO)}setErrorListener(t){}addImageToBuffer(t){var e;if(!C(t))throw new TypeError("Invalid 'image'.");if((null===(e=t.tag)||void 0===e?void 0:e.hasOwnProperty("imageId"))&&"number"==typeof t.tag.imageId&&this.hasImage(t.tag.imageId))throw new Error("Existed imageId.");if(r(this,j,"f").length>=r(this,U,"f"))switch(r(this,V,"f")){case s.BOPM_BLOCK:break;case s.BOPM_UPDATE:if(r(this,j,"f").push(t),p(r(this,W,"f"))&&m(r(this,W,"f").imageId)&&1==r(this,W,"f").keepInBuffer)for(;r(this,j,"f").length>r(this,U,"f");){const t=r(this,j,"f").findIndex((t=>{var e;return(null===(e=t.tag)||void 0===e?void 0:e.imageId)!==r(this,W,"f").imageId}));r(this,j,"f").splice(t,1)}else r(this,j,"f").splice(0,r(this,j,"f").length-r(this,U,"f"))}else r(this,j,"f").push(t)}getImage(){if(0===r(this,j,"f").length)return null;let e;if(r(this,W,"f")&&m(r(this,W,"f").imageId)){const t=r(this,N,"m",H).call(this,r(this,W,"f").imageId);if(t<0)throw new Error(`Image with id ${r(this,W,"f").imageId} doesn't exist.`);e=r(this,j,"f").slice(t,t+1)[0]}else e=r(this,j,"f").pop();if([a.IPF_RGB_565,a.IPF_RGB_555,a.IPF_RGB_888,a.IPF_ARGB_8888,a.IPF_RGB_161616,a.IPF_ARGB_16161616,a.IPF_ABGR_8888,a.IPF_ABGR_16161616,a.IPF_BGR_888].includes(e.format)){if(r(this,Y,"f")===o.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t0!==t.length&&t.every((t=>m(t))))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&!g(e))throw new TypeError("Invalid 'keepInBuffer'.");n(this,W,{imageId:t,keepInBuffer:e},"f")}_resetNextReturnedImage(){n(this,W,null,"f")}hasImage(t){return r(this,N,"m",H).call(this,t)>=0}startFetching(){n(this,G,!0,"f")}stopFetching(){n(this,G,!1,"f")}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(n(this,U,t,"f");r(this,j,"f")&&r(this,j,"f").length>t;)r(this,j,"f").shift()}getMaxImageCount(){return r(this,U,"f")}getImageCount(){return r(this,j,"f").length}clearBuffer(){r(this,j,"f").length=0}isBufferEmpty(){return 0===r(this,j,"f").length}setBufferOverflowProtectionMode(t){n(this,V,t,"f")}getBufferOverflowProtectionMode(){return r(this,V,"f")}setColourChannelUsageType(t){n(this,Y,t,"f")}getColourChannelUsageType(){return r(this,Y,"f")}};j=new WeakMap,U=new WeakMap,V=new WeakMap,G=new WeakMap,W=new WeakMap,Y=new WeakMap,N=new WeakSet,H=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return r(this,j,"f").findIndex((e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t}))},"undefined"!=typeof navigator&&(X=navigator,z=X.userAgent,Z=X.platform,q=X.mediaDevices),function(){if(!h){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:X.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Z,search:"Win"},Mac:{str:Z},Linux:{str:Z}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||z,o=n.search||e,a=n.verStr||z,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||z,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=z.indexOf("Windows NT")&&(n="HarmonyOS"),K={browser:i,version:r,OS:n}}h&&(K={browser:"ssr",version:0,OS:"ssr"})}();const Q="undefined"!=typeof WebAssembly&&z&&!(/Safari/.test(z)&&!/Chrome/.test(z)&&/\(.+\s11_2_([2-6]).*\)/.test(z)),$=!("undefined"==typeof Worker),tt=!(!q||!q.getUserMedia),et=async()=>{let t=!1;if(tt)try{(await q.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===K.browser&&K.version>66||"Safari"===K.browser&&K.version>13||"OPR"===K.browser&&K.version>43||"Edge"===K.browser&&K.version;const it={},rt=async t=>{let e="string"==typeof t?[t]:t,r=[];for(let t of e)r.push(it[t]=it[t]||new i);await Promise.all(r)},nt=async(t,e)=>{let r,n="string"==typeof t?[t]:t,s=[];for(let t of n){let n;s.push(n=it[t]=it[t]||new i(r=r||e())),n.isEmpty&&(n.task=r=r||e())}await Promise.all(s)};let st,ot=0;const at=()=>ot++,ht={};let lt;const ct=t=>{lt=t,st&&st.postMessage({type:"setBLog",body:{value:!!t}})};let ut=!1;const dt=t=>{ut=t,st&&st.postMessage({type:"setBDebug",body:{value:!!t}})},ft={},gt={},mt={dip:{wasm:!0}},pt={std:{version:"1.4.21",path:u(c+"../../dynamsoft-capture-vision-std@1.4.21/dist/"),isInternal:!0},core:{version:"3.4.31",path:c,isInternal:!0}},_t=async t=>{let e;t instanceof Array||(t=t?[t]:[]);let r=it.core;e=!r||r.isEmpty;let n=new Map;const s=t=>{if("std"==(t=t.toLowerCase())||"core"==t)return;if(!mt[t])throw Error("The '"+t+"' module cannot be found.");let e=mt[t].deps;if(null==e?void 0:e.length)for(let t of e)s(t);let i=it[t];n.has(t)||n.set(t,!i||i.isEmpty)};for(let e of t)s(e);let o=[];e&&o.push("core"),o.push(...n.keys());const a=[...n.entries()].filter((t=>!t[1])).map((t=>t[0]));await nt(o,(async()=>{const t=[...n.entries()].filter((t=>t[1])).map((t=>t[0]));await rt(a);const r=L(pt),s={};for(let e of t)s[e]=mt[e];const o={engineResourcePaths:r,autoResources:s,names:t};let h=new i;if(e){o.needLoadCore=!0;let t=r.core+vt._workerName;t.startsWith(location.origin)||(t=await fetch(t).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),st=new Worker(t),st.onerror=t=>{let e=new Error(t.message);h.reject(e)},st.addEventListener("message",(t=>{let e=t.data?t.data:t,i=e.type,r=e.id,n=e.body;switch(i){case"log":lt&<(e.message);break;case"task":try{ht[r](n),delete ht[r]}catch(t){throw delete ht[r],t}break;case"event":try{ht[r](n)}catch(t){throw t}break;default:console.log(t)}})),o.bLog=!!lt,o.bd=ut,o.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await rt("core");let l=ot++;ht[l]=t=>{if(t.success)Object.assign(ft,t.versions),"{}"!==JSON.stringify(t.versions)&&(vt._versions=t.versions),h.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),h.reject(e)}},st.postMessage({type:"loadWasm",body:o,id:l}),await h}))};class vt{static get engineResourcePaths(){return pt}static set engineResourcePaths(t){Object.assign(pt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return lt}static set _onLog(t){ct(t)}static get _bDebug(){return ut}static set _bDebug(t){dt(t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!it[t]&&it[t].isFulfilled}static async loadWasm(t){return await _t(t)}static async detectEnvironment(){return await(async()=>({wasm:Q,worker:$,getUserMedia:tt,camera:await et(),browser:K.browser,version:K.version,OS:K.OS}))()}static async getModuleVersion(){return await new Promise(((t,e)=>{let i=at();ht[i]=async i=>{if(i.success)return t(i.versions);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"getModuleVersion",id:i})}))}static getVersion(){return`3.4.31(Worker: ${ft.core&&ft.core.worker||"Not Loaded"}, Wasm: ${ft.core&&ft.core.wasm||"Not Loaded"})`}static enableLogging(){J._onLog=console.log,vt._onLog=console.log}static disableLogging(){J._onLog=null,vt._onLog=null}static async cfd(t){return await new Promise(((e,i)=>{let r=at();ht[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cfd",id:r,body:{count:t}})}))}}var yt,wt,Ct,Et,Tt,St,bt,It,xt;vt._bSupportDce4Module=-1,vt._bSupportIRTModule=-1,vt._versions=null,vt._workerName="core.worker.js",vt.browserInfo=K,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_NORMALIZED_IMAGE=16]="CRIT_NORMALIZED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT"}(yt||(yt={})),function(t){t[t.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",t[t.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",t[t.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",t[t.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(wt||(wt={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_RESERVED_INFO_NOT_MATCH=-10040]="EC_RESERVED_INFO_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_REQUEST_FAILED=-10044]="EC_REQUEST_FAILED",t[t.EC_LICENSE_INIT_FAILED=-10045]="EC_LICENSE_INIT_FAILED",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_LICENSE_CONTENT_INVALID=-10052]="EC_LICENSE_CONTENT_INVALID",t[t.EC_LICENSE_KEY_INVALID=-10053]="EC_LICENSE_KEY_INVALID",t[t.EC_LICENSE_DEVICE_RUNS_OUT=-10054]="EC_LICENSE_DEVICE_RUNS_OUT",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_HANDSHAKE_CODE_INVALID=-20001]="EC_HANDSHAKE_CODE_INVALID",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_LICENSE_INIT_SEQUENCE_FAILED=-20009]="EC_LICENSE_INIT_SEQUENCE_FAILED",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_FAILED_TO_REACH_DLS=-20200]="EC_FAILED_TO_REACH_DLS",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_QR_LICENSE_INVALID=-30016]="EC_QR_LICENSE_INVALID",t[t.EC_1D_LICENSE_INVALID=-30017]="EC_1D_LICENSE_INVALID",t[t.EC_PDF417_LICENSE_INVALID=-30019]="EC_PDF417_LICENSE_INVALID",t[t.EC_DATAMATRIX_LICENSE_INVALID=-30020]="EC_DATAMATRIX_LICENSE_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_AZTEC_LICENSE_INVALID=-30041]="EC_AZTEC_LICENSE_INVALID",t[t.EC_PATCHCODE_LICENSE_INVALID=-30046]="EC_PATCHCODE_LICENSE_INVALID",t[t.EC_POSTALCODE_LICENSE_INVALID=-30047]="EC_POSTALCODE_LICENSE_INVALID",t[t.EC_DPM_LICENSE_INVALID=-30048]="EC_DPM_LICENSE_INVALID",t[t.EC_FRAME_DECODING_THREAD_EXISTS=-30049]="EC_FRAME_DECODING_THREAD_EXISTS",t[t.EC_STOP_DECODING_THREAD_FAILED=-30050]="EC_STOP_DECODING_THREAD_FAILED",t[t.EC_MAXICODE_LICENSE_INVALID=-30057]="EC_MAXICODE_LICENSE_INVALID",t[t.EC_GS1_DATABAR_LICENSE_INVALID=-30058]="EC_GS1_DATABAR_LICENSE_INVALID",t[t.EC_GS1_COMPOSITE_LICENSE_INVALID=-30059]="EC_GS1_COMPOSITE_LICENSE_INVALID",t[t.EC_DOTCODE_LICENSE_INVALID=-30061]="EC_DOTCODE_LICENSE_INVALID",t[t.EC_PHARMACODE_LICENSE_INVALID=-30062]="EC_PHARMACODE_LICENSE_INVALID",t[t.EC_CHARACTER_MODEL_FILE_NOT_FOUND=-40100]="EC_CHARACTER_MODEL_FILE_NOT_FOUND",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_ZA_DL_LICENSE_INVALID=-90006]="EC_ZA_DL_LICENSE_INVALID",t[t.EC_AAMVA_DL_ID_LICENSE_INVALID=-90007]="EC_AAMVA_DL_ID_LICENSE_INVALID",t[t.EC_AADHAAR_LICENSE_INVALID=-90008]="EC_AADHAAR_LICENSE_INVALID",t[t.EC_MRTD_LICENSE_INVALID=-90009]="EC_MRTD_LICENSE_INVALID",t[t.EC_VIN_LICENSE_INVALID=-90010]="EC_VIN_LICENSE_INVALID",t[t.EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID=-90011]="EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID",t[t.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",t[t.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",t[t.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",t[t.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",t[t.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(Ct||(Ct={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV"}(Et||(Et={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV"}(Tt||(Tt={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(St||(St={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(bt||(bt={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(It||(It={})),function(t){t[t.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",t[t.CVS_PASSED=1]="CVS_PASSED",t[t.CVS_FAILED=2]="CVS_FAILED"}(xt||(xt={}));const At={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_DOWN_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_UP_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_NORMALIZED_IMAGES:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var Ot,Rt;!function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_NORMALIZED_IMAGE=6]="ROET_NORMALIZED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI"}(Ot||(Ot={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_NORMALIZATION=7]="ST_DOCUMENT_NORMALIZATION"}(Rt||(Rt={}));let Dt="./";if(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))}Dt=t.substring(0,t.lastIndexOf("/")+1)}function Lt(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Mt(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}vt.engineResourcePaths={rootDirectory:(t=>{null==t&&(t="./");let e=document.createElement("a");return e.href=t,(t=e.href).endsWith("/")||(t+="/"),t})(Dt+"../../")},"function"==typeof SuppressedError&&SuppressedError;const Ft=t=>t&&"object"==typeof t&&"function"==typeof t.then,Pt=(async()=>{})().constructor;class kt extends Pt{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,Ft(t)?e=t:"function"==typeof t&&(e=new Pt(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}constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(Ft(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class Bt{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise(((t,e)=>{let i=at();ht[i]=async i=>{if(i.success)return t(i.count);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})}))}async setMaxBufferedItems(t){return await new Promise(((e,i)=>{let r=at();ht[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_setMaxBufferedItems",id:r,instanceID:this._cvr._instanceID,body:{count:t}})}))}async getBufferedCharacterItemSet(){return await new Promise(((t,e)=>{let i=at();ht[i]=async i=>{if(i.success)return t(i.itemSet);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})}))}}var Nt={onTaskResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onColourImageUnitReceived:!1,onScaledDownColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledUpBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesReceived:!1};const jt=t=>{for(let e in t._irrRegistryState)t._irrRegistryState[e]=!1;for(let e of t._intermediateResultReceiverSet)if(e.isDce||e.isFilter)t._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let i in e)t._irrRegistryState[i]||(t._irrRegistryState[i]=!!e[i])};class Ut{constructor(t){this._irrRegistryState=Nt,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),jt(this);let e=-1,i={};if(!t.isDce&&!t.isFilter){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach(((t,e)=>{i[e]=t})),t._observedTaskMap.clear()}return await new Promise(((t,r)=>{let n=at();ht[n]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,r(t)}},st.postMessage({type:"cvr_setIrrRegistry",id:n,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})}))}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),jt(this),await new Promise(((t,e)=>{let i=at();ht[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})}))}getOriginalImage(){return this._cvr._dsImage}}const Vt="undefined"==typeof self,Gt="function"==typeof importScripts,Wt=(()=>{if(!Gt){if(!Vt&&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"./"}})(),Yt=t=>{if(null==t&&(t="./"),Vt||Gt);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var Ht;vt.engineResourcePaths.cvr={version:"2.4.33",path:Wt,isInternal:!0},mt.cvr={js:!0,wasm:!0,deps:["license","dip"]},gt.cvr={};const Xt="1.4.21";"string"!=typeof vt.engineResourcePaths.std&&D(vt.engineResourcePaths.std.version,Xt)<0&&(vt.engineResourcePaths.std={version:Xt,path:Yt(Wt+`../../dynamsoft-capture-vision-std@${Xt}/dist/`),isInternal:!0});const zt="2.4.31";(!vt.engineResourcePaths.dip||"string"!=typeof vt.engineResourcePaths.dip&&D(vt.engineResourcePaths.dip.version,zt)<0)&&(vt.engineResourcePaths.dip={version:zt,path:Yt(Wt+`../../dynamsoft-image-processing@${zt}/dist/`),isInternal:!0});class Zt{static getVersion(){return this._version}}Zt._version=`2.4.33(Worker: ${null===(Ht=ft.cvr)||void 0===Ht?void 0:Ht.worker}, Wasm: loading...`;const qt={barcodeResultItems:{type:yt.CRIT_BARCODE,reveiver:"onDecodedBarcodesReceived",isNeedFilter:!0},textLineResultItems:{type:yt.CRIT_TEXT_LINE,reveiver:"onRecognizedTextLinesReceived",isNeedFilter:!0},detectedQuadResultItems:{type:yt.CRIT_DETECTED_QUAD,reveiver:"onDetectedQuadsReceived",isNeedFilter:!1},normalizedImageResultItems:{type:yt.CRIT_NORMALIZED_IMAGE,reveiver:"onNormalizedImagesReceived",isNeedFilter:!1},parsedResultItems:{type:yt.CRIT_PARSED_RESULT,reveiver:"onParsedResultsReceived",isNeedFilter:!1}};var Kt,Jt,Qt,$t,te,ee,ie,re,ne,se,oe,ae,he;function le(t,e){if(t&&t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;le(t.referencedItem,e)}}function ce(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}!function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(Kt||(Kt={}));const ue={onTaskResultsReceived:()=>{},isFilter:!0};class de{constructor(){this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(vt.browserInfo.OS)?2048:4096,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,Jt.set(this,null),Qt.set(this,null),$t.set(this,null),te.set(this,null),ee.set(this,null),ie.set(this,new Set),re.set(this,new Set),ne.set(this,new Set),se.set(this,0),oe.set(this,!1),ae.set(this,!1),he.set(this,!1),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return Lt(this,he,"f")}static async createInstance(){if(!gt.license)throw Error("Module `license` is not existed.");await gt.license.dynamsoft(),await _t(["cvr"]);const t=new de,e=new kt;let i=at();return ht[i]=async i=>{var r;if(i.success)t._instanceID=i.instanceID,t._currentSettings=JSON.parse(JSON.parse(i.outputSettings).data),Zt._version=`2.4.33(Worker: ${null===(r=ft.cvr)||void 0===r?void 0:r.worker}, Wasm: ${i.version})`,Mt(t,ae,!0,"f"),Mt(t,te,t.getIntermediateResultManager(),"f"),Mt(t,ae,!1,"f"),e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},st.postMessage({type:"cvr_createInstance",id:i}),e}async _singleFrameModeCallback(t){for(let e of Lt(this,ie,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:t});const e={bytes:new Uint8Array(t.bytes),width:t.width,height:t.height,stride:t.stride,format:t.format,tag:t.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(e,this._templateName);i.originalImageTag=t.tag;const r={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of Lt(this,ie,"f"))if(t.isDce)t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1});else{for(let e in qt){const n=e,s=qt[n];t[s.reveiver]&&i[n]&&t[s.reveiver](Object.assign(Object.assign({},r),{[n]:i[n]}))}t.onCapturedResultReceived&&t.onCapturedResultReceived(i)}}setInput(t){if(ce(this),t){if(Mt(this,Jt,t,"f"),t.isCameraEnhancer){Lt(this,te,"f")&&(Lt(this,Jt,"f")._intermediateResultReceiver.isDce=!0,Lt(this,te,"f").addResultReceiver(Lt(this,Jt,"f")._intermediateResultReceiver));const t=Lt(this,Jt,"f").getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,Lt(this,ie,"f").add(e)}}}else Mt(this,Jt,null,"f")}getInput(){return Lt(this,Jt,"f")}addImageSourceStateListener(t){if(ce(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&Lt(this,re,"f").add(t)}removeImageSourceStateListener(t){return ce(this),Lt(this,re,"f").delete(t)}addResultReceiver(t){if(ce(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(Lt(this,ie,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){ce(this),Lt(this,ie,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onParsedResultsReceived:!1};for(let e of Lt(this,ie,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onDetectedQuadsReceived=!!e.onDetectedQuadsReceived,t.onNormalizedImagesReceived=!!e.onNormalizedImagesReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new kt;let i=at();return ht[i]=async t=>{if(t.success)e.resolve();else{let i=new Error(t.message);i.stack=t.stack+"\n"+i.stack,e.reject()}},st.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(ce(this),!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");Lt(this,ne,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){ce(this),Lt(this,ne,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(Lt(this,te,"f").removeResultReceiver(ue),0===Lt(this,ne,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[yt.CRIT_BARCODE]:!1,[yt.CRIT_TEXT_LINE]:!1,[yt.CRIT_DETECTED_QUAD]:!1,[yt.CRIT_NORMALIZED_IMAGE]:!1},e={[yt.CRIT_BARCODE]:!1,[yt.CRIT_TEXT_LINE]:!1,[yt.CRIT_DETECTED_QUAD]:!1,[yt.CRIT_NORMALIZED_IMAGE]:!1};return await fe(this,t),void await ge(this,e)}for(let t of Lt(this,ne,"f")){if(this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(yt.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(yt.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(yt.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(yt.CRIT_NORMALIZED_IMAGE),t.isLatestOverlappingEnabled(yt.CRIT_BARCODE)){[...Lt(this,te,"f")._intermediateResultReceiverSet.values()].find((t=>t.isFilter))||Lt(this,te,"f").addResultReceiver(ue)}await fe(this,t.verificationEnabled),await ge(this,t.duplicateFilterEnabled),await me(this,t.duplicateForgetTime)}}async startCapturing(t){var e,i;if(ce(this),!this._isPauseScan)return;if(!Lt(this,Jt,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");t||(t=de._defaultTemplate);const r=await this.containsTask(t);await _t(r);for(let t of Lt(this,ne,"f"))await this.addResultFilter(t);if(r.includes("dlr")&&!(null===(e=gt.dlr)||void 0===e?void 0:e.bLoadConfusableCharsData)){const t=L(vt.engineResourcePaths);await(null===(i=gt.dlr)||void 0===i?void 0:i.loadRecognitionData("ConfusableChars",t.dlr))}if(Lt(this,Jt,"f").isCameraEnhancer&&(r.includes("ddn")?Lt(this,Jt,"f").setPixelFormat(a.IPF_ABGR_8888):Lt(this,Jt,"f").setPixelFormat(a.IPF_GRAYSCALED)),void 0!==Lt(this,Jt,"f").singleFrameMode&&"disabled"!==Lt(this,Jt,"f").singleFrameMode)return this._templateName=t,void Lt(this,Jt,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind);return Lt(this,Jt,"f").getColourChannelUsageType()===o.CCUT_AUTO&&Lt(this,Jt,"f").setColourChannelUsageType(r.includes("ddn")?o.CCUT_FULL_CHANNEL:o.CCUT_Y_CHANNEL_ONLY),Lt(this,$t,"f")&&Lt(this,$t,"f").isPending?Lt(this,$t,"f"):(Mt(this,$t,new kt(((e,i)=>{if(this.disposed)return;let r=at();ht[r]=async r=>{if(Lt(this,$t,"f")&&!Lt(this,$t,"f").isFulfilled){if(!r.success){let t=new Error(r.message);return t.stack=r.stack+"\n"+t.stack,i(t)}this._isPauseScan=!1,this._isOutputOriginalImage=r.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((async()=>{-1!==this._minImageCaptureInterval&&Lt(this,Jt,"f").startFetching(),this._loopReadVideo(t),e()}),0)}},st.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:t}})})),"f"),await Lt(this,$t,"f"))}stopCapturing(){ce(this),Lt(this,Jt,"f")&&(Lt(this,Jt,"f").isCameraEnhancer&&void 0!==Lt(this,Jt,"f").singleFrameMode&&"disabled"!==Lt(this,Jt,"f").singleFrameMode?Lt(this,Jt,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(!async function(t){let e=at();const i=new kt;ht[e]=async t=>{if(t.success)return i.resolve();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i.reject(e)}},st.postMessage({type:"cvr_clearVerifyList",id:e,instanceID:t._instanceID})}(this),Lt(this,Jt,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,Mt(this,$t,null,"f"),Lt(this,Jt,"f").setColourChannelUsageType(o.CCUT_AUTO)))}async containsTask(t){return ce(this),await new Promise(((e,i)=>{let r=at();ht[r]=async t=>{if(t.success)return e(JSON.parse(t.tasks));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_containsTask",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async _loopReadVideo(t){if(this.disposed||this._isPauseScan)return;if(Mt(this,oe,!0,"f"),Lt(this,Jt,"f").isBufferEmpty())if(Lt(this,Jt,"f").hasNextImageToFetch())for(let t of Lt(this,re,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(Kt.ISS_BUFFER_EMPTY);else if(!Lt(this,Jt,"f").hasNextImageToFetch())for(let t of Lt(this,re,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(Kt.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||Lt(this,Jt,"f").isBufferEmpty())try{Lt(this,Jt,"f").isBufferEmpty()&&de._onLog&&de._onLog("buffer is empty so fetch image"),de._onLog&&de._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=Lt(this,Jt,"f").fetchImage(),de._onLog&&de._onLog(`DCE: finish fetching a frame: ${Date.now()}`),Lt(this,Jt,"f").setImageFetchInterval(this._averageTime)}catch(e){return void this._reRunCurrnetFunc(t)}else if(Lt(this,Jt,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=Lt(this,Jt,"f").getImage(),this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(t);if(!this._dsImage)return void this._reRunCurrnetFunc(t);for(let t of Lt(this,ie,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const e=Date.now();this._captureDsimage(this._dsImage,t).then((async i=>{if(de._onLog&&de._onLog("no js handle time: "+(Date.now()-e)),this._isPauseScan)return void this._reRunCurrnetFunc(t);i.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;const r={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of Lt(this,ie,"f"))if(t.isDce){const e=Date.now();if(t.onCapturedResultReceived(i,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify}),de._onLog){const t=Date.now()-e;t>10&&de._onLog(`draw result time: ${t}`)}}else{for(let e in qt){const n=e,s=qt[n];t[s.reveiver],t[s.reveiver]&&i[n]&&t[s.reveiver](Object.assign(Object.assign({},r),{[n]:i[n].filter((t=>!s.isNeedFilter||!t.isFilter))})),i[n]&&(i[n]=i[n].filter((t=>!s.isNeedFilter||!t.isFilter)))}t.onCapturedResultReceived&&(i.items=i.items.filter((t=>[yt.CRIT_DETECTED_QUAD,yt.CRIT_NORMALIZED_IMAGE].includes(t.type)||!t.isFilter)),t.onCapturedResultReceived(i))}const n=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-e),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,de._onLog&&(de._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),de._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),de._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),de._onLog(`averageTime: ${this._averageTime}`))),de._onLog){const t=Date.now()-n;t>10&&de._onLog(`fetch image calculate time: ${t}`)}de._onLog&&de._onLog(`time finish decode: ${Date.now()}`),de._onLog&&de._onLog("main time: "+(Date.now()-e)),de._onLog&&de._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,0))})).catch((e=>{Lt(this,Jt,"f").stopFetching(),e.errorCode&&0===e.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{Lt(this,Jt,"f").startFetching(),this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,1e3))),"platform error"!==e.message&&setTimeout((()=>{throw e}),0)}))}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),0)}async capture(t,e){var i,r;ce(this),e||(e=de._defaultTemplate);const n=await this.containsTask(e);if(await _t(n),n.includes("dlr")&&!(null===(i=gt.dlr)||void 0===i?void 0:i.bLoadConfusableCharsData)){const t=L(vt.engineResourcePaths);await(null===(r=gt.dlr)||void 0===r?void 0:r.loadRecognitionData("ConfusableChars",t.dlr))}let s;if(Mt(this,oe,!1,"f"),C(t))s=await this._captureDsimage(t,e);else if("string"==typeof t)s="data:image/"==t.substring(0,11)?await this._captureBase64(t,e):await this._captureUrl(t,e);else if(t instanceof Blob)s=await this._captureBlob(t,e);else if(t instanceof HTMLImageElement)s=await this._captureImage(t,e);else if(t instanceof HTMLCanvasElement)s=await this._captureCanvas(t,e);else{if(!(t instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");s=await this._captureVideo(t,e)}return s}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await O(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),r=i.length,n=new Uint8Array(r);for(;r--;)n[r]=i.charCodeAt(r);return await this._captureBlob(new Blob([n]),e)}async _captureBlob(t,e){let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(r=await async function(t){return await new Promise(((e,i)=>{let r=URL.createObjectURL(t),n=new Image;n.src=r,n.onload=()=>{URL.revokeObjectURL(n.dbrObjUrl),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._captureImage(i||r,e);return i&&i.close(),n}async _captureImage(t,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);o>this.maxImageSideLength?(Mt(this,se,this.maxImageSideLength/o,"f"),i=Math.round(n*Lt(this,se,"f")),r=Math.round(s*Lt(this,se,"f"))):(i=n,r=s),Lt(this,Qt,"f")||Mt(this,Qt,document.createElement("canvas"),"f");const a=Lt(this,Qt,"f");a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),r={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(r,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,r,n=t.videoWidth,s=t.videoHeight,o=Math.max(n,s);o>this.maxImageSideLength?(Mt(this,se,this.maxImageSideLength/o,"f"),i=Math.round(n*Lt(this,se,"f")),r=Math.round(s*Lt(this,se,"f"))):(i=n,r=s),Lt(this,Qt,"f")||Mt(this,Qt,document.createElement("canvas"),"f");const a=Lt(this,Qt,"f");a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),await this._captureCanvas(a,e)}async _captureInWorker(t,e){const{bytes:i,width:r,height:n,stride:s,format:o}=t;let a=at();const h=new kt;return ht[a]=async e=>{var i,r;if(!e.success){let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h.reject(t)}{const n=Date.now();de._onLog&&(de._onLog(`get result time from worker: ${n}`),de._onLog("worker to main time consume: "+(n-e.workerReturnMsgTime)));try{const n=e.captureResult;if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,h.reject(t)}t.bytes=e.bytes;for(let e of n.items)0!==Lt(this,se,"f")&&le(e,Lt(this,se,"f")),e.type===yt.CRIT_ORIGINAL_IMAGE?e.imageData=t:e.type===yt.CRIT_NORMALIZED_IMAGE?null===(i=gt.ddn)||void 0===i||i.handleNormalizedImageResultItem(e):e.type===yt.CRIT_PARSED_RESULT&&(null===(r=gt.dcp)||void 0===r||r.handleParsedResultItem(e));if(Lt(this,oe,"f"))for(let t of Lt(this,ne,"f"))t.onDecodedBarcodesReceived(n),t.onRecognizedTextLinesReceived(n),t.onDetectedQuadsReceived(n),t.onNormalizedImagesReceived(n);for(let t in qt){const e=t,i=n.items.filter((t=>t.type===qt[e].type));i.length&&(n[t]=i)}if(!this._isPauseScan||!Lt(this,oe,"f")){const e=n.intermediateResult;if(e){let i=0;for(let r of Lt(this,te,"f")._intermediateResultReceiverSet){i++;for(let n of e){if("onTaskResultsReceived"===n.info.callbackName){for(let e of n.intermediateResultUnits)e.originalImageTag=t.tag?t.tag:null;r[n.info.callbackName]&&r[n.info.callbackName]({intermediateResultUnits:n.intermediateResultUnits},n.info)}else r[n.info.callbackName]&&r[n.info.callbackName](n.result,n.info);i===Lt(this,te,"f")._intermediateResultReceiverSet.size&&delete n.info.callbackName}}}}return n&&n.hasOwnProperty("intermediateResult")&&delete n.intermediateResult,Mt(this,se,0,"f"),h.resolve(n)}catch(t){return h.reject(t)}}},de._onLog&&de._onLog(`send buffer to worker: ${Date.now()}`),st.postMessage({type:"cvr_capture",id:a,instanceID:this._instanceID,body:{bytes:i,width:r,height:n,stride:s,format:o,templateName:e||"",isScanner:Lt(this,oe,"f")}},[i.buffer]),h}async initSettings(t){return ce(this),t&&["string","object"].includes(typeof t)?("string"==typeof t?t.trimStart().startsWith("{")||(t=await O(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise(((e,i)=>{let r=at();ht[r]=async r=>{if(r.success){const n=JSON.parse(r.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Init Settings Failed.");return t.errorCode=n.errorCode,i(t)}const s=JSON.parse(t);this._currentSettings=s;let o=[],a=s.CaptureVisionTemplates;for(let t=0;t{let r=at();ht[r]=async t=>{if(t.success){const r=JSON.parse(t.response);if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,i(t)}return e(JSON.parse(r.data))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_outputSettings",id:r,instanceID:this._instanceID,body:{templateName:t||"*"}})}))}async outputSettingsToFile(t,e,i){const r=await this.outputSettings(t),n=new Blob([JSON.stringify(r,null,2,(function(t,e){return e instanceof Array?JSON.stringify(e):e}),2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(n),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout((()=>{URL.revokeObjectURL(t.href)}),500)},t.click()}return n}async getTemplateNames(){return ce(this),await new Promise(((t,e)=>{let i=at();ht[i]=async i=>{if(i.success){const r=JSON.parse(i.response);if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,e(t)}return t(JSON.parse(r.data))}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})}))}async getSimplifiedSettings(t){ce(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const e=await this.containsTask(t);return await _t(e),await new Promise(((e,i)=>{let r=at();ht[r]=async t=>{if(t.success){const r=JSON.parse(t.response);if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,i(t)}const n=JSON.parse(r.data,((t,e)=>"barcodeFormatIds"===t?BigInt(e):e));return n.minImageCaptureInterval=this._minImageCaptureInterval,e(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_getSimplifiedSettings",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async updateSettings(t,e){ce(this);const i=await this.containsTask(t);return await _t(i),await new Promise(((i,r)=>{let n=at();ht[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Update Settings Failed.");return t.errorCode=n.errorCode,r(t)}return this._currentSettings=await this.outputSettings("*"),i(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},st.postMessage({type:"cvr_updateSettings",id:n,instanceID:this._instanceID,body:{settings:e,templateName:t}})}))}async resetSettings(){return ce(this),await new Promise(((t,e)=>{let i=at();ht[i]=async i=>{if(i.success){const r=JSON.parse(i.response);if(0!==r.errorCode){let t=new Error(r.errorString?r.errorString:"Reset Settings Failed.");return t.errorCode=r.errorCode,e(t)}return this._currentSettings=await this.outputSettings("*"),t(r)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})}))}getBufferedItemsManager(){return Lt(this,ee,"f")||Mt(this,ee,new Bt(this),"f"),Lt(this,ee,"f")}getIntermediateResultManager(){if(ce(this),!Lt(this,ae,"f")&&0!==vt.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return Lt(this,te,"f")||Mt(this,te,new Ut(this),"f"),Lt(this,te,"f")}async parseRequiredResources(t){return ce(this),await new Promise(((e,i)=>{let r=at();ht[r]=async t=>{if(t.success)return e(JSON.parse(t.resources));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_parseRequiredResources",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async dispose(){ce(this),Lt(this,$t,"f")&&this.stopCapturing(),Mt(this,Jt,null,"f"),Lt(this,ie,"f").clear(),Lt(this,re,"f").clear(),Lt(this,ne,"f").clear(),Lt(this,te,"f")._intermediateResultReceiverSet.clear(),Mt(this,he,!0,"f");let t=at();ht[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},st.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:Lt(this,Jt,"f"),promiseStartScan:Lt(this,$t,"f"),intermediateResultManager:Lt(this,te,"f"),bufferdItemsManager:Lt(this,ee,"f"),resultReceiverSet:Lt(this,ie,"f"),isaStateListenerSet:Lt(this,re,"f"),resultFilterSet:Lt(this,ne,"f"),compressRate:Lt(this,se,"f"),canvas:Lt(this,Qt,"f"),isScanner:Lt(this,oe,"f"),innerUseTag:Lt(this,ae,"f"),isDestroyed:Lt(this,he,"f")}}async _getWasmFilterState(){return await new Promise(((t,e)=>{let i=at();ht[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})}))}}async function fe(t,e){return ce(t),await new Promise(((i,r)=>{let n=at();ht[n]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},st.postMessage({type:"cvr_enableResultCrossVerification",id:n,instanceID:t._instanceID,body:{verificationEnabled:e}})}))}async function ge(t,e){return ce(t),await new Promise(((i,r)=>{let n=at();ht[n]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},st.postMessage({type:"cvr_enableResultDeduplication",id:n,instanceID:t._instanceID,body:{duplicateFilterEnabled:e}})}))}async function me(t,e){return ce(t),await new Promise(((i,r)=>{let n=at();ht[n]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},st.postMessage({type:"cvr_setDuplicateForgetTime",id:n,instanceID:t._instanceID,body:{duplicateForgetTime:e}})}))}Jt=new WeakMap,Qt=new WeakMap,$t=new WeakMap,te=new WeakMap,ee=new WeakMap,ie=new WeakMap,re=new WeakMap,ne=new WeakMap,se=new WeakMap,oe=new WeakMap,ae=new WeakMap,he=new WeakMap,de._defaultTemplate="Default";class pe{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}}class _e{constructor(){this._observedResultUnitTypes=At.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledDownColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}}var ve;!function(t){t.PT_DEFAULT="Default",t.PT_READ_BARCODES="ReadBarcodes_Default",t.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",t.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",t.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",t.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",t.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",t.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",t.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",t.PT_READ_SINGLE_BARCODE="ReadBarcodes_Balanced",t.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",t.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",t.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",t.PT_RECOGNIZE_LETTERS="RecognizeLetters",t.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",t.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",t.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters"}(ve||(ve={}));const ye="undefined"==typeof self,we=ye?{}:self,Ce="function"==typeof importScripts,Ee=(()=>{if(!Ce){if(!ye&&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"./"}})(),Te=t=>t&&"object"==typeof t&&"function"==typeof t.then,Se=(async()=>{})().constructor;let be=class extends Se{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,Te(t)?e=t:"function"==typeof t&&(e=new Se(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}constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(Te(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Ie=" is not allowed to change after `createInstance` or `loadWasm` is called.",xe=!ye&&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"))||"",Ae=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Ie);i._license=e}};!ye&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Oe=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{e=Oe(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Ie);i._licenseServer=e}},De=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Ie);i._deviceFriendlyName=e}};let Le,Me,Fe,Pe,ke;"undefined"!=typeof navigator&&(Le=navigator,Me=Le.userAgent,Fe=Le.platform,Pe=Le.mediaDevices),function(){if(!ye){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Le.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Fe,search:"Win"},Mac:{str:Fe},Linux:{str:Fe}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||Me,o=n.search||e,a=n.verStr||Me,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||Me,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=Me.indexOf("Windows NT")&&(n="HarmonyOS"),ke={browser:i,version:r,OS:n}}ye&&(ke={browser:"ssr",version:0,OS:"ssr"})}(),Pe&&Pe.getUserMedia,"Chrome"===ke.browser&&ke.version>66||"Safari"===ke.browser&&ke.version>13||"OPR"===ke.browser&&ke.version>43||"Edge"===ke.browser&&ke.version;const Be=()=>(_t("license"),nt("dynamsoft_inited",(async()=>{let{lt:t,l:e,ls:i,sp:r,rmk:n,cv:s}=((t,e=!1)=>{const i=je;if(i._pLoad.isEmpty){let r,n,s,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(n=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=Oe(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),r=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(we.crypto||(s="Please upgrade your browser to support online key."),we.crypto.subtle||(s="Require https to use online key in this browser."))),s)throw new Error(s);return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:r,cv:n}}throw new Error("Can't preprocess license again"+Ie)})(),o=new be;je._pLoad.task=o,(async()=>{try{await je._pLoad}catch(t){}})();let a=at();ht[a]=e=>{if(e.message&&je._onAuthMessage){let t=je._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,r=!1;if(1===t&&(r=!0),e.success?(lt&<("init license success"),e.message&&console.warn(e.message),vt._bSupportIRTModule=e.bSupportIRTModule,vt._bSupportDce4Module=e.bSupportDce4Module,je.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):o.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),r||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(r=!0)),r){const t=L(vt.engineResourcePaths);(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)}})({_bNeverShowDialog:je._bNeverShowDialog,engineResourcePath:t.license,_onLog:lt},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await rt("core"),st.postMessage({type:"license_dynamsoft",body:{v:"3.4.31",brtk:!!t,bptk:1===t,l:e,os:ke,fn:je.deviceFriendlyName,ls:i,sp:r,rmk:n,cv:s},id:a}),je.bCallInitLicense=!0,await o})));let Ne;gt.license={},gt.license.dynamsoft=Be,gt.license.getAR=async()=>{{let t=it.dynamsoft_inited;t&&t.isRejected&&await t}return st?new Promise(((t,e)=>{let i=at();ht[i]=async i=>{if(i.success){delete i.success;{let t=je.license;t&&(t.startsWith("t")||t.startsWith("f"))&&(i.pk=t)}if(Object.keys(i).length){if(i.lem){let t=Error(i.lem);t.ltsErrorCode=i.lec,delete i.lem,delete i.lec,i.ae=t}t(i)}else t(null)}else{let t=Error(i.message);i.stack&&(t.stack=i.stack),e(t)}},st.postMessage({type:"license_getAR",id:i})})):null};let je=class t{static setLicenseServer(e){Re(t,e)}static get license(){return this._license}static set license(e){Ae(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Re(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){De(t,e)}static initLicense(e,i){if(Ae(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return Be()}static setDeviceFriendlyName(e){De(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await nt("dynamsoft_uuid",(async()=>{await _t();let t=new be,e=at();ht[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},st.postMessage({type:"license_getDeviceUUID",id:e}),Ne=await t})),Ne))()}};je._pLoad=new be,je.bPassValidation=!1,je.bCallInitLicense=!1,je._license=xe,je._licenseServer=[],je._deviceFriendlyName="",vt.engineResourcePaths.license={version:"3.4.31",path:Ee,isInternal:!0},mt.license={wasm:!0,js:!0},gt.license.LicenseManager=je;const Ue="1.4.21";"string"!=typeof vt.engineResourcePaths.std&&D(vt.engineResourcePaths.std.version,Ue)<0&&(vt.engineResourcePaths.std={version:Ue,path:(t=>{if(null==t&&(t="./"),ye||Ce);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(Ee+`../../dynamsoft-capture-vision-std@${Ue}/dist/`),isInternal:!0});let Ve=class{static getVersion(){return`3.4.31(Worker: ${ft.license&&ft.license.worker||"Not Loaded"}, Wasm: ${ft.license&&ft.license.wasm||"Not Loaded"})`}};const Ge="undefined"==typeof self,We="function"==typeof importScripts,Ye=(()=>{if(!We){if(!Ge&&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"./"}})();vt.engineResourcePaths.dce={version:"4.1.1",path:Ye,isInternal:!0},mt.dce={wasm:!1,js:!1},gt.dce={};let He,Xe,ze,Ze,qe,Ke=class{static getVersion(){return"4.1.1"}};function Je(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Qe(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(He=navigator,Xe=He.userAgent,ze=He.platform,Ze=He.mediaDevices),function(){if(!Ge){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:He.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:ze,search:"Win"},Mac:{str:ze},Linux:{str:ze}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||Xe,o=n.search||e,a=n.verStr||Xe,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||Xe,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=Xe.indexOf("Windows NT")&&(n="HarmonyOS"),qe={browser:i,version:r,OS:n}}Ge&&(qe={browser:"ssr",version:0,OS:"ssr"})}();const $e="undefined"!=typeof WebAssembly&&Xe&&!(/Safari/.test(Xe)&&!/Chrome/.test(Xe)&&/\(.+\s11_2_([2-6]).*\)/.test(Xe)),ti=!("undefined"==typeof Worker),ei=!(!Ze||!Ze.getUserMedia),ii=async()=>{let t=!1;if(ei)try{(await Ze.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===qe.browser&&qe.version>66||"Safari"===qe.browser&&qe.version>13||"OPR"===qe.browser&&qe.version>43||"Edge"===qe.browser&&qe.version;var ri={653:(t,e,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,m,p,_,v,y,w,C,E,T,S=S||{version:"5.2.1"};if(e.fabric=S,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?S.document=document:S.document=document.implementation.createHTMLDocument(""),S.window=window;else{var b=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;S.document=b.document,S.jsdomImplForWrapper=i(898).implForWrapper,S.nodeCanvas=i(245).Canvas,S.window=b,DOMParser=S.window.DOMParser}function I(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 x(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)}S.isTouchSupported="ontouchstart"in S.window||"ontouchstart"in S.document||S.window&&S.window.navigator&&S.window.navigator.maxTouchPoints>0,S.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,S.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"],S.DPI=96,S.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",S.commaWsp="(?:\\s+,?\\s*|,\\s*)",S.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,S.reNonWord=/[ \n\.,;!\?\-]/,S.fontPaths={},S.iMatrix=[1,0,0,1,0,0],S.svgNS="http://www.w3.org/2000/svg",S.perfLimitSizeTotal=2097152,S.maxCacheSideLimit=4096,S.minCacheSideLimit=256,S.charWidthsCache={},S.textureSize=2048,S.disableStyleCopyPaste=!1,S.enableGLFiltering=!0,S.devicePixelRatio=S.window.devicePixelRatio||S.window.webkitDevicePixelRatio||S.window.mozDevicePixelRatio||1,S.browserShadowBlurConstant=1,S.arcToSegmentsCache={},S.boundsOfCurveCache={},S.cachesBoundsOfCurve=!0,S.forceGLPutImageData=!1,S.initFilterBackend=function(){return S.enableGLFiltering&&S.isWebglSupported&&S.isWebglSupported(S.textureSize)?(console.log("max texture size: "+S.maxTextureSize),new S.WebglFilterBackend({tileSize:S.textureSize})):S.Canvas2dFilterBackend?new S.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=S),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:S.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)}S.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)}},S.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof S.Gradient||this.set(e,new S.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof S.Pattern?i&&i():this.set(e,new S.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,S.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 S.Point(t.x-e.x,t.y-e.y),n=S.util.rotateVector(r,i);return new S.Point(n.x,n.y).addEquals(e)},rotateVector:function(t,e){var i=S.util.sin(e),r=S.util.cos(e);return{x:t.x*r-t.y*i,y:t.x*i+t.y*r}},createVector:function(t,e){return new S.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 S.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var r=S.util.createVector(t,e),n=S.util.createVector(t,i),s=S.util.calcAngleBetweenVectors(r,n),o=s*(0===S.util.calcAngleBetweenVectors(S.util.rotateVector(r,s),n)?1:-1)/2;return{vector:S.util.getHatVector(S.util.rotateVector(r,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var r=[],n=e.strokeWidth/2,s=e.strokeUniform?new S.Point(1/e.scaleX,1/e.scaleY):new S.Point(1,1),o=function(t){var e=n/Math.hypot(t.x,t.y);return new S.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 S.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(S.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(S.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=S.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-n/Math.sin(p/2),f=new S.Point(m.x*d*s.x,m.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 S.Point(m.x*d*s.x,m.y*d*s.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(t,e,i){return i?new S.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new S.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=S.util.sin(c),d=S.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,C=_*v-_*y-v*w,E=0;if(C<0){var T=Math.sqrt(1-C/(_*v));i*=T,s*=T}else E=(o===a?-1:1)*Math.sqrt(C/(_*y+v*w));var b=E*i*p/s,I=-E*s*m/i,x=d*b-u*I+.5*t,A=u*b+d*I+.5*e,O=n(1,0,(m-b)/i,(p-I)/s),R=n((m-b)/i,(p-I)/s,(-m-b)/i,(-p-I)/s);0===a&&R>0?R-=2*l:1===a&&R<0&&(R+=2*l);for(var D=Math.ceil(Math.abs(R/l*2)),L=[],M=R/D,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=O+M,k=0;kE)for(var b=1,I=m.length;b2;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},S.util.getPathSegmentsInfo=d,S.util.getBoundsOfCurve=function(e,i,r,n,s,o,a,h){var l;if(S.cachesBoundsOfCurve&&(l=t.call(arguments),S.boundsOfCurveCache[l]))return S.boundsOfCurveCache[l];var c,u,d,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,C=Math.abs,E=[],T=[[],[]];u=6*e-12*r+6*s,c=-3*e+9*r-9*s+3*a,d=3*r-3*e;for(var b=0;b<2;++b)if(b>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&&E.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&E.push(g),0<(m=(-u-_)/(2*c))&&m<1&&E.push(m));for(var I,x,A,O=E.length,R=O;O--;)I=(A=1-(f=E[O]))*A*A*e+3*A*A*f*r+3*A*f*f*s+f*f*f*a,T[0][O]=I,x=A*A*A*i+3*A*A*f*n+3*A*f*f*o+f*f*f*h,T[1][O]=x;T[0][R]=e,T[1][R]=i,T[0][R+1]=a,T[1][R+1]=h;var D=[{x:y.apply(null,T[0]),y:y.apply(null,T[1])},{x:w.apply(null,T[0]),y:w.apply(null,T[1])}];return S.cachesBoundsOfCurve&&(S.boundsOfCurveCache[l]=D),D},S.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)}},S.util.transformPath=function(t,e,i){return i&&(e=S.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(!S.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}S.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)}S.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=S.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=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}),S.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?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var r in e)"opacity"===r?m(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(S.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=S.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=S.document.documentElement,n=S.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===S.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=S.document.defaultView&&S.document.defaultView.getComputedStyle?function(t,e){var i=S.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=S.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",S.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=S.util.falseFunction),r?t.style[r]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},S.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),r?t.style[r]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},S.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},S.util.getById=function(t){return"string"==typeof t?S.document.getElementById(t):t},S.util.toArray=s,S.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},S.util.makeElement=o,S.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},S.util.getScrollLeftTop=a,S.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}},S.util.getNodeCanvas=function(t){var e=S.jsdomImplForWrapper(t);return e._canvas||e._image},S.util.cleanUpJsdomNode=function(t){if(S.isLikelyNode){var e=S.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}S.util.request=function(e,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",n=i.onComplete||function(){},s=new S.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}}(),S.log=console.log,S.warn=console.warn,function(){var t=S.util.object.extend,e=S.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}S.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=S.window.requestAnimationFrame||S.window.webkitRequestAnimationFrame||S.window.mozRequestAnimationFrame||S.window.oRequestAnimationFrame||S.window.msRequestAnimationFrame||function(t){return S.window.setTimeout(t,1e3/60)},o=S.window.cancelAnimationFrame||S.window.clearTimeout;function a(){return s.apply(S.window,arguments)}S.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=S.runningAnimations.indexOf(s);return t>-1&&S.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}),S.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,m=i.easing||n,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map((function(t,e){return v[e]-_[e]})):v-_);i.onStart&&i.onStart(),function t(i){var r=(e=i||+new Date)>u?c:e-l,n=r/c,w=p?_.map((function(t,e){return m(r,_[e],y[e],c)})):m(r,_,y,c),C=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=C,s.durationRate=n,!o){if(!f(w,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(w,C,n),void a(t));h()}}(l)})),s.cancel},S.util.requestAnimFrame=a,S.util.cancelAnimFrame=function(){return o.apply(S.window,arguments)},S.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))+")"}S.util.animateColor=function(e,i,r,n){var s=new S.Color(e).getSource(),o=new S.Color(i).getSource(),a=n.onComplete,h=n.onChange;return n=n||{},S.util.animate(S.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,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,C={},E="",T=0,S=0;if(C.width=0,C.height=0,C.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+E,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return C;if(_)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),T=C.width-n*c,S=C.height-o*c,"Mid"===p.alignX&&(T/=2),"Mid"===p.alignY&&(S/=2),"Min"===p.alignX&&(T=0),"Min"===p.alignY&&(S=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===m)return C;if((g||m)&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") "),a=E+" matrix("+c+" 0 0 "+u+" "+(i*c+T)+" "+(r*u+S)+") ","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 w(t,e){var i="xlink:href",r=_(t,e.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&w(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 m(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 _(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 w(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 E(t){return t.flipX!==t.flipY}function T(t,e,i,r,n){if(0!==t[e]){var s=n/t._getTransformedDimensions()[r]*t[i];t.set(i,s)}}function S(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),E(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",n),T(l,"skewY","scaleY","y",p)}return m}function b(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),E(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",n),T(l,"skewX","scaleX","x",p)}return m}function I(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,w=m(t,f),E=_(f,y,w),T=e.gestureScale;if(E)return!1;if(T)o=e.scaleX*T,a=e.scaleY*T;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(),w&&!y){var S=Math.abs(s.x)+Math.abs(s.y),b=e.original,I=S/(Math.abs(h.x*b.scaleX/f.scaleX)+Math.abs(h.y*b.scaleY/f.scaleY));o=b.scaleX*I,a=b.scaleY*I}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 x=f.scaleX,A=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)),x!==f.scaleX||A!==f.scaleY}n.scaleCursorStyleHandler=function(t,e,r){var n=m(t,r),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(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=w("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,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),E(h)&&(n=n===s?a:s)),e.originX=n,w("skewing",y(S))(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),E(a)&&(n=n===o?h:o)),e.originY=n,w("skewing",y(b))(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=w,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),m=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(m),l=f*e.util.sin(m)}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 S.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*e,{offset:a,color:i.toRgb(),opacity:n}}var e=S.util.object.clone;S.Gradient=S.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+="_"+S.Object.__uid++:this.id=S.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 S.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 S.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():S.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+" ":"")+S.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=m/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=S.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,m=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=S.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,m=-i.top),new S.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:m})}})}(),_=S.util.toFixed,S.Pattern=S.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=S.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=S.util.createImage(),S.util.loadImage(t.source,(function(t,r){i.source=t,e&&e(i,r)}),null,this.crossOrigin)}},toObject:function(t){var e,i,r=S.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:_(this.offsetX,r),offsetY:_(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},S.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(S.StaticCanvas)S.warn("fabric.StaticCanvas is already defined.");else{var t=S.util.object.extend,e=S.util.getElementOffset,i=S.util.removeFromArray,r=S.util.toFixed,n=S.util.transformPoint,s=S.util.invertTransform,o=S.util.getNodeCanvas,a=S.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");S.StaticCanvas=S.util.createClass(S.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:S.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 S.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,S.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=S.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?S.util.loadImage(e,(function(e,n){if(e){var s=new S.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=S.util.getById(t)||this._createCanvasElement(),S.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=S.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 ",S.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+S.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?S.util.matrixToSVG(n):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,r,n,s,o,a,h="",l={},c=S.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(S.StaticCanvas.prototype,S.Observable),t(S.StaticCanvas.prototype,S.Collection),t(S.StaticCanvas.prototype,S.DataURLExporter),t(S.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}}),S.StaticCanvas.prototype.toJSON=S.StaticCanvas.prototype.toObject,S.isLikelyNode&&(S.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},S.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),S.BaseBrush=S.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*=S.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*r,i.shadowOffsetX=e.offsetX*r,i.shadowOffsetY=e.offsetY*r}},needsFullRender:function(){return new S.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()}}),S.PencilBrush=S.util.createClass(S.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 S.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 S.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 S.Point(r.x,r.y),n=new S.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})}}}),S.CircleBrush=S.util.createClass(S.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=S.util.invertTransform(i),n=this.restorePointerVpt(e);return S.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 S.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,S.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):S.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:S.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 S.Point(e.ex,e.ey),r=S.util.transformPoint(i,this.viewportTransform),n=new S.Point(e.ex+e.left,e.ey+e.top),s=S.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,S.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 S.Group&&(r=this._searchPossibleTargets(i._objects,e))&&this.targets.push(r);break}}return i},restorePointerVpt:function(t){return S.util.transformPoint(t,S.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),S.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=S.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),S.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),S.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;S.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,S.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){S.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,S.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]})),S.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(),S.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),S.StaticCanvas)"prototype"!==r&&(S.Canvas[r]=S.StaticCanvas[r])}(),function(){var t=S.util.addListener,e=S.util.removeListener,i={passive:!1};function r(t,e){return t.button&&t.button===e-1}S.util.object.extend(S.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(S.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(S.document,t+"up",this._onMouseUp),e(S.document,"touchend",this._onTouchEnd,i),e(S.document,t+"move",this._onMouseMove,i),e(S.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(S.document,"touchend",this._onTouchEnd,i),t(S.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(S.document,s+"up",this._onMouseUp),t(S.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(S.document,"touchend",this._onTouchEnd,i),e(S.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(S.document,s+"up",this._onMouseUp),e(S.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),S.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 S.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 S.Point(v(r,s),v(n,o)),h=new S.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}}),S.util.object.extend(S.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 S.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=S.util.createCanvasElement(),m=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=m,g}}),S.util.object.extend(S.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var r="string"==typeof t?JSON.parse(t):S.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?S.util.enlivenObjects([e],(function(e){n[t]=e[0],i[t]=!0,r&&r()})):this["set"+S.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,r&&r()}))},_enlivenObjects:function(t,e,i){t&&0!==t.length?S.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=S.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new S.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,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,C=l>y||c>w;v=C||(l<.9*y||c<.9*w)&&y>h&&w>h,C&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(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,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.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 _=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",_),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),w=S.util.degreesToRadians,C={left:-.5,center:0,right:.5},E={top:-.5,center:0,bottom:.5},S.util.object.extend(S.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=E[i]:i-=.5,"string"==typeof n?n=E[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 S.Point(h,l)},translateToCenterPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?S.util.rotatePoint(r,t,w(this.angle)):r},translateToOriginPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?S.util.rotatePoint(r,t,w(this.angle)):r},getCenterPoint:function(){var t=new S.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 S.Point(this.left,this.top),n=new S.Point(t.x,t.y),this.angle&&(n=S.util.rotatePoint(n,s,-w(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=w(this.angle),n=this.getScaledWidth(),s=S.util.cos(r)*n,o=S.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=S.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,r=t.transformPoint;t.object.extend(S.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 S.Point(i.tl.x,i.tl.y),new S.Point(i.tr.x,i.tr.y),new S.Point(i.br.x,i.br.y),new S.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,r){var n=this.getCoords(i,r);return"Intersection"===S.Intersection.intersectPolygonRectangle(n,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===S.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=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+S.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[m]=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=S.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=S.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=S.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(){}})}(),S.util.object.extend(S.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return S.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 S.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 S.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()}})}}),S.util.object.extend(S.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?S.util.animateColor(h.startValue,h.endValue,h.duration,h):S.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 S.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);S.filterBackend||(S.filterBackend=S.initFilterBackend());var o=S.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,S.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=S.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 S.filterBackend||(S.filterBackend=S.initFilterBackend()),S.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){S.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){S.util.setImageSmoothing(t,this.imageSmoothing),S.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),m=o(s*r,u-f),p=-n/2,_=-s/2,v=o(n,c/i-h),y=o(s,u/r-l);e&&t.drawImage(e,d,f,g,m,p,_,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(S.util.getById(t),e),S.util.addClass(this.getElement(),S.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?S.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=S.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=S.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=S.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}}}),S.Image.CSS_CANVAS="canvas-img",S.Image.prototype.getSvgSrc=S.Image.prototype.getSrc,S.Image.fromObject=function(t,e){var i=S.util.object.clone(t);S.util.loadImage(i.src,(function(t,r){r?e&&e(null,!0):S.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],S.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],S.util.enlivenObjectEnlivables(i,i,(function(){var r=new S.Image(t,i);e(r,!1)}))}))}))}),null,i.crossOrigin)},S.Image.fromURL=function(t,e,i){S.util.loadImage(t,(function(t,r){e&&e(new S.Image(t,i),r)}),null,i&&i.crossOrigin)},S.Image.ATTRIBUTE_NAMES=S.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),S.Image.fromElement=function(t,i,r){var n=S.parseAttributes(t,S.Image.ATTRIBUTE_NAMES);S.Image.fromURL(n["xlink:href"],i,e(r?S.util.object.clone(r):{},n))})}(e),S.util.object.extend(S.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 S.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()}})}}),S.util.object.extend(S.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()}S.isWebglSupported=function(e){if(S.isLikelyNode)return!1;e=e||S.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),n=!1;if(r){S.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),n=S.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(r,s[o])){S.webGlPrecision=s[o];break}}return this.isSupported=n,n},S.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=S.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(S.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=S.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:I,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(){}S.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}}}(),S.Image=S.Image||{},S.Image.filters=S.Image.filters||{},S.Image.filters.BaseFilter=S.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"!==S.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+S.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=S.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()}}),S.Image.filters.BaseFilter.fromObject=function(t,e){var i=new S.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=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,r+=m[h+2]*l,T||(n+=m[h+3]*l));E[s]=e,E[s+1]=i,E[s+2]=r,E[s+3]=T?m[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,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){L=r(1e3*s(S-C.x)),w[L]||(w[L]={});for(var F=E.y-y;F<=E.y+y;F++)F<0||F>=o||(M=r(1e3*s(F-C.y)),w[L][M]||(w[L][M]=f(n(i(L*p,2)+i(M*_,2))/1e3)),(b=w[L][M])>0&&(x+=b,A+=b*c[I=4*(F*e+S)],O+=b*c[I+1],R+=b*c[I+2],D+=b*c[I+3]))}d[I=4*(T*a+h)]=A/x,d[I+1]=O/x,d[I+2]=R/x,d[I+3]=D/x}return++h1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(b+=y*f[3+(L=4*(D+x*e))],C+=y,f[L+3]<255&&(y=y*f[L+3]/250),E+=y*f[L],T+=y*f[L+1],S+=y*f[L+2],w+=y)}m[v]=E/w,m[v+1]=T/w,m[v+2]=S/w,m[v+3]=b/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,m=this._textLines.length;g=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 x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+E*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,r=n,o=a}else d+=f.kernedWidth;x=v+s+u,"rtl"===this.direction&&(x=this.width-x-d),t.fillStyle=p,g&&p&&t.fillRect(x,c+E*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)}S.IText=S.util.createClass(S.Text,S.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),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,C=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,C=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+C,y,w),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}}}),S.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]);S.Object._fromObject("IText",e,i,"text")}}(),T=S.util.object.clone,S.util.object.extend(S.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||[],S.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=S.util.string.graphemeSplit(r).length;if(t===e)return{selectionStart:n,selectionEnd:n};var s=i.slice(t,e);return{selectionStart:n,selectionEnd:n+S.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,m=c.clientWidth/u,p=c.clientHeight/d;return h=S.util.transformPoint(h,a),(h=S.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,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=T(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:T(r[i-1])}:n?this.styles[t+i]={0:T(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?T(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]=T(r[i]));else if(n)for(var h=n[e?e-1:1];h&&i--;)this.styles[t][e+i]=T(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)}}),S.util.object.extend(S.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}}),S.util.object.extend(S.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=S.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):S.document.body.appendChild(this.hiddenTextarea),S.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),S.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),S.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),S.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),S.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),S.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),S.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),S.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),S.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(S.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),m=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=S.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=S.util.toFixed,e=/ +/g;S.util.object.extend(S.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",S.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,m=f.length-1;g<=m;g++)h=g===m||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=S.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+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+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:()=>{}},ni={};function si(t){var e=ni[t];if(void 0!==e)return e.exports;var i=ni[t]={exports:{}};return ri[t](i,i.exports,si),i.exports}si.d=(t,e)=>{for(var i in e)si.o(e,i)&&!si.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},si.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var oi={};(()=>{let t;si.d(oi,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?si(653).fabric:{version:"5.2.1"}})();var ai,hi,li,ci,ui=oi.R;!function(t){t[t.DIMT_RECTANGLE=1]="DIMT_RECTANGLE",t[t.DIMT_QUADRILATERAL=2]="DIMT_QUADRILATERAL",t[t.DIMT_TEXT=4]="DIMT_TEXT",t[t.DIMT_ARC=8]="DIMT_ARC",t[t.DIMT_IMAGE=16]="DIMT_IMAGE",t[t.DIMT_POLYGON=32]="DIMT_POLYGON",t[t.DIMT_LINE=64]="DIMT_LINE",t[t.DIMT_GROUP=128]="DIMT_GROUP"}(ai||(ai={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(hi||(hi={})),function(t){t[t.EF_ENHANCED_FOCUS=4]="EF_ENHANCED_FOCUS",t[t.EF_AUTO_ZOOM=16]="EF_AUTO_ZOOM",t[t.EF_TAP_TO_FOCUS=64]="EF_TAP_TO_FOCUS"}(li||(li={})),function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(ci||(ci={}));const di=t=>"number"==typeof t&&!Number.isNaN(t),fi=t=>"string"==typeof t;var gi,mi,pi,_i,vi,yi,wi,Ci,Ei,Ti,Si;!function(t){t[t.ARC=0]="ARC",t[t.IMAGE=1]="IMAGE",t[t.LINE=2]="LINE",t[t.POLYGON=3]="POLYGON",t[t.QUAD=4]="QUAD",t[t.RECT=5]="RECT",t[t.TEXT=6]="TEXT",t[t.GROUP=7]="GROUP"}(vi||(vi={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(yi||(yi={}));class bi{get mediaType(){return new Map([["rect",ai.DIMT_RECTANGLE],["quad",ai.DIMT_QUADRILATERAL],["text",ai.DIMT_TEXT],["arc",ai.DIMT_ARC],["image",ai.DIMT_IMAGE],["polygon",ai.DIMT_POLYGON],["line",ai.DIMT_LINE],["group",ai.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(Je(this,mi,"f")){case hi.DIS_DEFAULT:return"default";case hi.DIS_SELECTED:return"selected"}}set drawingStyleId(t){this.styleId=t}get drawingStyleId(){return this.styleId}set coordinateBase(t){if(!["view","image"].includes(t))throw new Error("Invalid 'coordinateBase'.");this._drawingLayer&&("image"===Je(this,pi,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===Je(this,pi,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),Qe(this,pi,t,"f")}get coordinateBase(){return Je(this,pi,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(gi.add(this),mi.set(this,void 0),pi.set(this,"image"),this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapState_StyleId=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,null!=e&&!di(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(hi.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",(()=>{this.setState(hi.DIS_SELECTED)})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(hi.DIS_SELECTED):this.setState(hi.DIS_DEFAULT),"textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}setState(t){Qe(this,mi,t,"f")}getState(){return Je(this,mi,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),r=this.mapEvent_Callbacks.get(i);if(!r)throw new Error(`Event '${t}' does not exist.`);let n=r.get(e);n||(n=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const r={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,n,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,n=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)u0?i-1:r,Oi),actionName:"modifyPolygon",pointIndex:i}),t}),{}),Qe(this,Ci,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,r){return t["p"+r]=new ui.Control({positionHandler:xi,actionHandler:Ri(r>0?r-1:i,Oi),actionName:"modifyPolygon",pointIndex:r}),t}),{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let r=i.x-e.pathOffset.x,n=i.y-e.pathOffset.y;const s=ui.util.transformPoint({x:r,y:n},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){Je(this,Ci,"f")&&this.setPolygon(Je(this,Ci,"f"))}setPolygon(t){if(!I(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Qe(this,Ci,JSON.parse(JSON.stringify(t)),"f")}getPolygon(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Je(this,Ci,"f")?JSON.parse(JSON.stringify(Je(this,Ci,"f"))):null}}Ci=new WeakMap;class Li extends bi{set maintainAspectRatio(t){t&&this.set("scaleY",this.get("scaleX"))}get maintainAspectRatio(){return Je(this,Ti,"f")}constructor(t,e,i,r){if(super(null,r),Ei.set(this,void 0),Ti.set(this,void 0),!A(e))throw new TypeError("Invalid 'rect'.");if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)this._setFabricObject(new ui.Image(t,{left:e.x,top:e.y}));else{if(!C(t))throw new TypeError("Invalid 'image'.");{const i=document.createElement("canvas");let r;if(i.width=t.width,i.height=t.height,t.format===a.IPF_GRAYSCALED){r=new Uint8ClampedArray(t.width*t.height*4);for(let e=0;e{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let r=0;ri&&(i=n.length)}if(-1===i)break;for(let r=0;r=t[r].length-1)continue;let n=" ".repeat(i+2-t[r][e].length);t[r][e]=t[r][e].concat(n)}}})(e),(t=>{let e="";for(let i=0;i({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const r=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new ui.Control({positionHandler:xi,actionHandler:Ri(i>0?i-1:r,Oi),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let r=t.x-i.pathOffset.x,n=t.y-i.pathOffset.y;const s=ui.util.transformPoint({x:r,y:n},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){Je(this,Pi,"f")&&this.setLine(Je(this,Pi,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!S(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else Qe(this,Pi,JSON.parse(JSON.stringify(t)),"f")}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return Je(this,Pi,"f")?JSON.parse(JSON.stringify(Je(this,Pi,"f"))):null}}Pi=new WeakMap;class Ni extends Di{constructor(t,e){if(super({points:null==t?void 0:t.points},e),ki.set(this,void 0),!x(t))throw new TypeError("Invalid 'quad'.");Qe(this,ki,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="quad"}setPosition(t){this.setQuad(t)}getPosition(){return this.getQuad()}updatePosition(){Je(this,ki,"f")&&this.setQuad(Je(this,ki,"f"))}setPolygon(){}getPolygon(){return null}setQuad(t){if(!x(t))throw new TypeError("Invalid 'quad'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Qe(this,ki,JSON.parse(JSON.stringify(t)),"f")}getQuad(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Je(this,ki,"f")?JSON.parse(JSON.stringify(Je(this,ki,"f"))):null}}ki=new WeakMap;class ji extends bi{constructor(t){super(new ui.Group(t.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.setState(hi.DIS_SELECTED);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.setState(hi.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}setChildDrawingItems(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()))}}const Ui=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),Vi=t=>!!fi(t)&&""!==t,Gi=t=>!(!Ui(t)||"id"in t&&!di(t.id)||"lineWidth"in t&&!di(t.lineWidth)||"fillStyle"in t&&!Vi(t.fillStyle)||"strokeStyle"in t&&!Vi(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!Vi(t.fontFamily)||"fontSize"in t&&!di(t.fontSize));class Wi{static convert(t,e,i){const r={x:0,y:0,width:e,height:i};if(!t)return r;if(A(t))t.isMeasuredInPercentage?(r.x=t.x/100*e,r.y=t.y/100*i,r.width=t.width/100*e,r.height=t.height/100*i):(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height);else{if(!E(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?(r.x=t.left/100*e,r.y=t.top/100*i,r.width=(t.right-t.left)/100*e,r.height=(t.bottom-t.top)/100*i):(r.x=t.left,r.y=t.top,r.width=t.right-t.left,r.height=t.bottom-t.top)}return r.x=Math.round(r.x),r.y=Math.round(r.y),r.width=Math.round(r.width),r.height=Math.round(r.height),r}}var Yi,Hi;class Xi{constructor(){Yi.set(this,new Map),Hi.set(this,!1)}get disposed(){return Je(this,Hi,"f")}on(t,e){t=t.toLowerCase();const i=Je(this,Yi,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else Je(this,Yi,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=Je(this,Yi,"f").get(t);if(!i)return;const r=i.indexOf(e);-1!==r&&i.splice(r,1)}offAll(t){t=t.toLowerCase();const e=Je(this,Yi,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const r=Je(this,Yi,"f").get(t);if(r&&r.length){i=Object.assign({async:!1,copy:!0},i);for(let n of r){if(!n)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let o=!1;if(i.async)setTimeout((()=>{this.disposed||r.includes(n)&&n.apply(i.target,s)}),0);else try{o=n.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){Qe(this,Hi,!0,"f")}}function zi(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function Zi(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function qi(t,e,i,r){let n=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(r[1]-e[1])+e[0]*(t[1]-r[1])+r[0]*(e[1]-t[1]);return!((n^s)>=0&&0!==n&&0!==s||(n=i[0]*(t[1]-r[1])+r[0]*(i[1]-t[1])+t[0]*(r[1]-i[1]),s=i[0]*(e[1]-r[1])+r[0]*(i[1]-e[1])+e[0]*(r[1]-i[1]),(n^s)>=0&&0!==n&&0!==s))}Yi=new WeakMap,Hi=new WeakMap;const Ki=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const r=document.createElement("div");if(r.insertAdjacentHTML("beforeend",i),1===r.childElementCount&&r.firstChild instanceof HTMLTemplateElement)return r.firstChild.content;const n=new DocumentFragment;for(let t of r.children)n.append(t);return n};var Ji,Qi,$i,tr,er,ir,rr,nr,sr,or,ar,hr,lr,cr,ur,dr,fr,gr,mr,pr,_r,vr,yr,wr,Cr,Er,Tr,Sr,br,Ir,xr,Ar,Or,Rr;class Dr{static createDrawingStyle(t){if(!Gi(t))throw new Error("Invalid style definition.");let e,i=Dr.USER_START_STYLE_ID;for(;Je(Dr,Ji,"f",Qi).has(i);)i++;e=i;const r=JSON.parse(JSON.stringify(t));r.id=e;for(let t in Je(Dr,Ji,"f",$i))r.hasOwnProperty(t)||(r[t]=Je(Dr,Ji,"f",$i)[t]);return Je(Dr,Ji,"f",Qi).set(e,r),r.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=Je(Dr,Ji,"f",Qi).get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}static getDrawingStyle(t){return this._getDrawingStyle(t,!0)}static getAllDrawingStyles(){return JSON.parse(JSON.stringify(Array.from(Je(Dr,Ji,"f",Qi).values())))}static _updateDrawingStyle(t,e){if(!Gi(e))throw new Error("Invalid style definition.");const i=Je(Dr,Ji,"f",Qi).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}Ji=Dr,Dr.STYLE_BLUE_STROKE=1,Dr.STYLE_GREEN_STROKE=2,Dr.STYLE_ORANGE_STROKE=3,Dr.STYLE_YELLOW_STROKE=4,Dr.STYLE_BLUE_STROKE_FILL=5,Dr.STYLE_GREEN_STROKE_FILL=6,Dr.STYLE_ORANGE_STROKE_FILL=7,Dr.STYLE_YELLOW_STROKE_FILL=8,Dr.STYLE_BLUE_STROKE_TRANSPARENT=9,Dr.STYLE_GREEN_STROKE_TRANSPARENT=10,Dr.STYLE_ORANGE_STROKE_TRANSPARENT=11,Dr.USER_START_STYLE_ID=1024,Qi={value:new Map([[Dr.STYLE_BLUE_STROKE,{id:Dr.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Dr.STYLE_GREEN_STROKE,{id:Dr.STYLE_GREEN_STROKE,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dr.STYLE_ORANGE_STROKE,{id:Dr.STYLE_ORANGE_STROKE,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dr.STYLE_YELLOW_STROKE,{id:Dr.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Dr.STYLE_BLUE_STROKE_FILL,{id:Dr.STYLE_BLUE_STROKE_FILL,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dr.STYLE_GREEN_STROKE_FILL,{id:Dr.STYLE_GREEN_STROKE_FILL,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dr.STYLE_ORANGE_STROKE_FILL,{id:Dr.STYLE_ORANGE_STROKE_FILL,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dr.STYLE_YELLOW_STROKE_FILL,{id:Dr.STYLE_YELLOW_STROKE_FILL,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dr.STYLE_BLUE_STROKE_TRANSPARENT,{id:Dr.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dr.STYLE_GREEN_STROKE_TRANSPARENT,{id:Dr.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dr.STYLE_ORANGE_STROKE_TRANSPARENT,{id:Dr.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},$i={value:{lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}},"undefined"!=typeof document&&"undefined"!=typeof window&&(ui.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(ui.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),ui.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},ui.Object.prototype.transparentCorners=!1,ui.Object.prototype.cornerSize=20,ui.Object.prototype.touchCornerSize=100,ui.Object.prototype.cornerColor="rgb(254,142,20)",ui.Object.prototype.cornerStyle="circle",ui.Object.prototype.strokeUniform=!0,ui.Object.prototype.hasBorders=!1,ui.Canvas.prototype.containerClass="",ui.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=ui.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,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:n.x*i.width,y:(n.y-(f-m)/2)*i.width}):(g=f*p,m=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===l?p>_?{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}},ui.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,r=this._getEventPrefix();ui.util.addListener(ui.document,"touchend",this._onTouchEnd,{passive:!1}),ui.util.addListener(ui.document,"touchmove",this._onMouseMove,{passive:!1}),ui.util.removeListener(i,r+"down",this._onMouseDown)},ui.Textbox.prototype._wrapLine=function(t,e,i,r){const n=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!n||!n.length);var o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?ui.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,m=0,p=0,_=!0,v=this._getWidthOfCharSpacing();r=r||0,0===c.length&&c.push([]),i-=r;for(var y=0;yi&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),h});class Lr{get width(){return this.fabricCanvas.width}get height(){return this.fabricCanvas.height}set _allowMultiSelect(t){this.fabricCanvas.selection=t,this.fabricCanvas.renderAll()}get _allowMultiSelect(){return this.fabricCanvas.selection}constructor(t,e,i){if(this.mapType_StateAndStyleId=new Map,this.mode="viewer",this.onSelectionChanged=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas"))this.fabricCanvas=t.getFabricCanvas();else{let e=this.fabricCanvas=new ui.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.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.onSelectionChanged&&t.onSelectionChanged(i,[])}),0)}})),e.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.onSelectionChanged&&t.onSelectionChanged([],e)}),0)}})),e.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.onSelectionChanged&&t.onSelectionChanged(r,n)}),0)}})),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let r,n;switch(this.id=e,e){case Lr.DDN_LAYER_ID:r=Dr.getDrawingStyle(Dr.STYLE_BLUE_STROKE),n=Dr.getDrawingStyle(Dr.STYLE_BLUE_STROKE_FILL);break;case Lr.DBR_LAYER_ID:r=Dr.getDrawingStyle(Dr.STYLE_ORANGE_STROKE),n=Dr.getDrawingStyle(Dr.STYLE_ORANGE_STROKE_FILL);break;case Lr.DLR_LAYER_ID:r=Dr.getDrawingStyle(Dr.STYLE_GREEN_STROKE),n=Dr.getDrawingStyle(Dr.STYLE_GREEN_STROKE_FILL);break;default:r=Dr.getDrawingStyle(Dr.STYLE_YELLOW_STROKE),n=Dr.getDrawingStyle(Dr.STYLE_YELLOW_STROKE_FILL)}for(let t of bi.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:r.id,selected:n.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return Dr.getDrawingStyle(t.styleId);return Dr.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,r){const n=this.getDrawingItems((e=>e._mediaType===t));for(let t of n)t.styleSelector===e&&this._changeItemStyle(t,i,!0);r||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const r=t._getFabricObject();"number"==typeof t.styleId&&(e=Dr.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.getChildDrawingItems();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=Dr.getDrawingStyle(e.styleId);else{const r=this.mapType_StateAndStyleId.get(e._mediaType);i=Dr.getDrawingStyle(r[t.styleSelector]);const n=()=>{this._changeItemStyle(e,Dr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,Dr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",n),e._on("deselected",s),e._funcChangeStyleToSelected=n,e._funcChangeStyleToDefault=s}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("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof bi))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}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.getChildDrawingItems();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){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of bi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Dr.getDrawingStyle(t.styleId);else{s=Dr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Dr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},r=()=>{this._changeItemStyle(t,Dr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",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{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of bi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Dr.getDrawingStyle(t.styleId);else{s=Dr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Dr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},r=()=>{this._changeItemStyle(t,Dr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",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;et.toLowerCase())):e=bi.arrMediaTypes,i?i.forEach((t=>t.toLowerCase())):i=bi.arrStyleSelectors;const r=Dr.getDrawingStyle(t);if(!r)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let n;for(let s of e)if(n=this.mapType_StateAndStyleId.get(s),n)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,r,!0),n[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const r=[];i&ai.DIMT_RECTANGLE&&r.push("rect"),i&ai.DIMT_QUADRILATERAL&&r.push("quad"),i&ai.DIMT_TEXT&&r.push("text"),i&ai.DIMT_ARC&&r.push("arc"),i&ai.DIMT_IMAGE&&r.push("image"),i&ai.DIMT_POLYGON&&r.push("polygon"),i&ai.DIMT_LINE&&r.push("line");const n=[];e&hi.DIS_DEFAULT&&n.push("default"),e&hi.DIS_SELECTED&&n.push("selected"),this._setDefaultStyle(t,r.length?r:null,n.length?n:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}Lr.DDN_LAYER_ID=1,Lr.DBR_LAYER_ID=2,Lr.DLR_LAYER_ID=3,Lr.USER_DEFINED_LAYER_BASE_ID=100,Lr.TIP_LAYER_ID=999;class Mr{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new Lr(t,e,{enableRetinaScaling:!1});return i._manager=this,this._arrDrawingLayer.push(i),this._switchPointerEvent(),i}deleteDrawingLayer(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}getAllDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._getFabricCanvas().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){if(!this._arrDrawingLayer.length)return;this._getFabricCanvas().wrapperEl.style.display=t?"block":"none"}_getFabricCanvas(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0].fabricCanvas:null}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class Fr extends Fi{constructor(t,e,i,r,n){super(t,{x:e,y:i,width:r,height:0},n),tr.set(this,void 0),er.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&Qe(this,er,setTimeout((()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()}),Je(this,tr,"f")),"f")}getDuration(){return Je(this,tr,"f")}}tr=new WeakMap,er=new WeakMap;class Pr{constructor(){ir.add(this),rr.set(this,void 0),nr.set(this,void 0),sr.set(this,void 0),or.set(this,!0),this._drawingLayerManager=new Mr}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const r=document.createElement("canvas");return r.width==t&&r.height==e||(r.width=t,r.height=e),r.style.objectFit=i,r}_createDrawingLayer(t,e,i,r){if(!this._layerBaseCvs){let n;try{n=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==n?void 0:n.width)||1280),i||(i=(null==n?void 0:n.height)||720),r||(r=(null==n?void 0:n.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,r)}const n=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(n,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",n.parentElement),s}createDrawingLayer(){let t;for(let e=Lr.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==Lr.TIP_LAYER_ID){t=e;break}return this._createDrawingLayer(t)}deleteDrawingLayer(t){var e;this._drawingLayerManager.deleteDrawingLayer(t),this._drawingLayerManager.getAllDrawingLayers().length||(null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null)}deleteUserDefinedDrawingLayer(t){if("number"!=typeof t)throw new TypeError("Invalid id.");if(tt.getId()>=0&&t.getId()!==Lr.TIP_LAYER_ID))}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(Ui(e=t)&&b(e.topLeftPoint)&&di(e.width))||e.width<=0||!di(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;Qe(this,rr,JSON.parse(JSON.stringify(t)),"f"),Je(this,rr,"f").coordinateBase||(Je(this,rr,"f").coordinateBase="view"),Qe(this,sr,t.duration,"f"),Je(this,ir,"m",cr).call(this)}getTipConfig(){return Je(this,rr,"f")?Je(this,rr,"f"):null}setTipVisible(t){if("boolean"!=typeof t)throw new TypeError("Invalid value.");this._tip&&(this._tip.set("visible",t),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll()),Qe(this,or,t,"f")}isTipVisible(){return Je(this,or,"f")}updateTipMessage(t){if(!Je(this,rr,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=Dr.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(Lr.TIP_LAYER_ID)||this._createDrawingLayer(Lr.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=Je(this,ir,"m",ar).call(this,t,Je(this,rr,"f").topLeftPoint.x,Je(this,rr,"f").topLeftPoint.y,Je(this,rr,"f").width,Je(this,rr,"f").coordinateBase,this._tipStyleId),Je(this,ir,"m",hr).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",Je(this,or,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),Je(this,nr,"f")&&clearTimeout(Je(this,nr,"f")),Je(this,sr,"f")>=0&&Qe(this,nr,setTimeout((()=>{Je(this,ir,"m",lr).call(this)}),Je(this,sr,"f")),"f")}}rr=new WeakMap,nr=new WeakMap,sr=new WeakMap,or=new WeakMap,ir=new WeakSet,ar=function(t,e,i,r,n,s){const o=new Fr(t,e,i,r,s);return o.coordinateBase=n,o},hr=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},lr=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},cr=function(){if(!this._tip)return;const t=Je(this,rr,"f");this._tip.coordinateBase=t.coordinateBase,this._tip.setTextRect({x:t.topLeftPoint.x,y:t.topLeftPoint.y,width:t.width,height:0}),this._tip.set("width",this._tip.get("width")),this._tip._drawingLayer&&this._tip._drawingLayer.renderAll()};class kr extends HTMLElement{constructor(){super(),ur.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),Qe(this,ur,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const r=document.createElement("slot");r.setAttribute("name","content"),e.append(r);const n=document.createElement("slot");n.setAttribute("name","drawing-layer"),e.append(n);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return Je(this,ur,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach((t=>t.remove()))}}ur=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",kr);class Br extends Pr{static get engineResourcePath(){return L(vt.engineResourcePaths).dce}static set defaultUIElementURL(t){Br._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=Br._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",Br.engineResourcePath)}static async createInstance(t){const e=new Br;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",Br.engineResourcePath)),await e.setUIElement(t||Br.defaultUIElementURL),e}static _transformCoordinates(t,e,i,r,n,s,o){const a=s/r,h=o/n;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==Je(this,Cr,"f")){if(Qe(this,Cr,t,"f"),Je(this,dr,"m",Sr).call(this))Qe(this,pr,null,"f"),this._videoContainer=null,this._innerComponent.removeElement("content"),this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block");else if(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none"),!Je(this,pr,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(qe.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Qe(this,pr,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}Je(this,dr,"m",Sr).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading())}}get _singleFrameMode(){return Je(this,Cr,"f")}get disposed(){return Je(this,Tr,"f")}constructor(){super(),dr.add(this),fr.set(this,void 0),gr.set(this,void 0),mr.set(this,void 0),this.containerClassName="dce-video-container",pr.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,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,_r.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,vr.set(this,!1),yr.set(this,!1),wr.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{Je(this,dr,"m",Or).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout((()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&Je(this,dr,"m",Ar).call(this))}),this._updateLayersTimeout)},this._windowResizeListener=()=>{Br._onLog&&Br._onLog("window resize event triggered."),Je(this,wr,"f").width===document.documentElement.clientWidth&&Je(this,wr,"f").height===document.documentElement.clientHeight||(Je(this,wr,"f").width=document.documentElement.clientWidth,Je(this,wr,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},Cr.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!Je(this,dr,"m",Sr).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i},i=(t,e,i,r)=>{t.width==i&&t.height==r||(t.width=i,t.height=r);const n=t.getContext("2d");n.clearRect(0,0,t.width,t.height),n.drawImage(e,0,0)},r=await t(e),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,r,n,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout((()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)}),0)})),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},Er.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,r,n,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(r=o.cropRegion)||void 0===r?void 0:r.top)||0,c=(null===(n=o.cropRegion)||void 0===n?void 0:n.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,r,n,s,o,a,h=[],l)=>{e.forEach((t=>Br._transformCoordinates(t,i,r,n,s,o,a)));const c=new Ni({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},l);for(let t of h)c.addNote(t);t.addDrawingItems([c]),Je(this,Er,"f").push(c)};let m,p;for(let t of a)switch(t.type){case yt.CRIT_ORIGINAL_IMAGE:break;case yt.CRIT_BARCODE:m=this.getDrawingLayer(Lr.DBR_LAYER_ID),p=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==e?void 0:e.isBarcodeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,Dr.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case yt.CRIT_TEXT_LINE:m=this.getDrawingLayer(Lr.DLR_LAYER_ID),p=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,Dr.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case yt.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(Lr.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.crossVerificationStatus===xt.CVS_PASSED?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Dr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case yt.CRIT_NORMALIZED_IMAGE:m=this.getDrawingLayer(Lr.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.crossVerificationStatus===xt.CVS_PASSED?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Dr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case yt.CRIT_PARSED_RESULT:break;default:throw new Error("Illegal item type.")}}},Tr.set(this,!1),this.eventHandler=new Xi,this.eventHandler.on("content:updated",(()=>{Je(this,fr,"f")&&clearTimeout(Je(this,fr,"f")),Qe(this,fr,setTimeout((()=>{if(this.disposed)return;let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(t),this.updateConvertedRegion(t)}),0),"f")})),this.eventHandler.on("videoEl:resized",(()=>{Je(this,gr,"f")&&clearTimeout(Je(this,gr,"f")),Qe(this,gr,setTimeout((()=>{this.disposed||this._updateVideoContainer()}),0),"f")}))}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Ki(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let r=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!r)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=document.createElement("dce-component"),r.appendChild(this._innerComponent),Je(this,dr,"m",Sr).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(qe.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Qe(this,pr,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._selRsl&&(this._hideDefaultSelection||Je(this,dr,"m",Sr).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||Je(this,dr,"m",Sr).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||Je(this,dr,"m",Or).call(this),Je(this,dr,"m",Sr).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),Je(this,dr,"m",Sr).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading()),window.ResizeObserver){this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{var e;Br._onLog&&Br._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()})));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}Je(this,wr,"f").width=document.documentElement.clientWidth,Je(this,wr,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,r;Je(this,dr,"m",Sr).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),Je(this,dr,"m",Or).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,Qe(this,pr,null,"f"),null===(r=this._videoContainer)||void 0===r||r.remove(),this._videoContainer=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._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let r of e){const e=document.createElement("option");e.value=r.deviceId,e.innerText=r.label,this._selCam.append(e),r.deviceId&&t&&t.deviceId==r.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),r=Math.min(t.width,t.height);e=r<=1080?r+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return Je(this,pr,"f")}isVideoLoaded(){return!(!Je(this,pr,"f")||!this.cameraEnhancer)&&this.cameraEnhancer.isOpen()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!Je(this,pr,"f"))return;if(Je(this,pr,"f").style.objectFit=t,Je(this,dr,"m",Sr).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Je(this,dr,"m",Rr).call(this,e,this.getConvertedRegion()),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,r;let n,s,o;if(Je(this,dr,"m",Sr).call(this)?(n=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(r=this._cvsSingleFrameMode)||void 0===r?void 0:r.height,o="contain"):(n=null===(t=Je(this,pr,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=Je(this,pr,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!n||!s)throw new Error("Invalid content dimensions.");return{width:n,height:s,objectFit:o}}updateConvertedRegion(t){const e=Wi.convert(this.scanRegion,t.width,t.height);Qe(this,_r,e,"f"),Je(this,mr,"f")&&clearTimeout(Je(this,mr,"f")),Qe(this,mr,setTimeout((()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Je(this,dr,"m",br).call(this,t,e),Je(this,dr,"m",Rr).call(this,t,e)}),0),"f")}getConvertedRegion(){return Je(this,_r,"f")}setScanRegion(t){if(null!=t&&!E(t)&&!A(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=Je(this,pr,"f").videoWidth,i=Je(this,pr,"f").videoHeight,r=this.getVideoFit(),{width:n,height:s}=this._innerComponent.getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===r&&(n/s1){const t=Je(this,pr,"f").videoWidth,e=Je(this,pr,"f").videoHeight,{width:r,height:n}=this._innerComponent.getBoundingClientRect(),s=t/e;if(r/nt.remove())),Je(this,Er,"f").length=0}dispose(){this._unbindUI(),Qe(this,Tr,!0,"f")}}function Nr(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function jr(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}fr=new WeakMap,gr=new WeakMap,mr=new WeakMap,pr=new WeakMap,_r=new WeakMap,vr=new WeakMap,yr=new WeakMap,wr=new WeakMap,Cr=new WeakMap,Er=new WeakMap,Tr=new WeakMap,dr=new WeakSet,Sr=function(){return"disabled"!==this._singleFrameMode},br=function(t,e){!e||0===e.x&&0===e.y&&e.width===t.width&&e.height===t.height?this.clearScanRegionMask():this.setScanRegionMask(e.x,e.y,e.width,e.height)},Ir=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},xr=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},Ar=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},Or=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Rr=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:r,objectFit:n}=t;e||(e={x:0,y:0,width:i,height:r});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/r;let l,c,u,d,f=1;if("contain"===n)a66||"Safari"===Hr.browser&&Hr.version>13||"OPR"===Hr.browser&&Hr.version>43||"Edge"===Hr.browser&&Hr.version,"function"==typeof SuppressedError&&SuppressedError;class Zr{static multiply(t,e){const i=[];for(let r=0;r<3;r++){const n=e.slice(3*r,3*r+3);for(let e=0;e<3;e++){const r=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return Zr.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),r=Math.sin(e);return Zr.multiply(t,[i,-r,0,r,i,0,0,0,1])}static scale(t,e,i){return Zr.multiply(t,[e,0,0,0,i,0,0,0,1])}}var qr,Kr,Jr,Qr,$r,tn,en,rn,nn,sn,on,an,hn,ln,cn,un,dn,fn,gn,mn,pn,_n,vn,yn,wn,Cn,En,Tn,Sn,bn,In,xn,An,On,Rn,Dn,Ln,Mn,Fn,Pn,kn,Bn,Nn,jn,Un,Vn,Gn,Wn,Yn,Hn;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(qr||(qr={}));class Xn{static get version(){return"1.1.3"}static get webGLSupported(){return void 0===Xn._webGLSupported&&(Xn._webGLSupported=!!document.createElement("canvas").getContext("webgl")),Xn._webGLSupported}get disposed(){return Xr(this,en,"f")}constructor(){Kr.set(this,qr.RGBA),Jr.set(this,null),Qr.set(this,null),$r.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,tn.set(this,null),en.set(this,!1)}drawImage(t,e,i,r,n,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!r)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if((null==s?void 0:s.bUseWebGL)&&!Xn.webGLSupported)throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;Xn._onLog&&(o=Date.now(),Xn._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;n&&(n.sx&&(a=Math.round(n.sx)),n.sy&&(h=Math.round(n.sy)),n.sWidth&&(l=Math.round(n.sWidth)),n.sHeight&&(c=Math.round(n.sHeight)),n.dx&&(u=Math.round(n.dx)),n.dy&&(d=Math.round(n.dy)),n.dWidth&&(f=Math.round(n.dWidth)),n.dHeight&&(g=Math.round(n.dHeight)));let m,p=qr.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!Xn.webGLSupported||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){Xn._onLog&&Xn._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=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},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},n=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},s="\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\n\nuniform mat3 u_matrix;\nuniform mat3 u_textureMatrix;\n\nvarying vec2 v_texCoord;\nvoid main(void) {\ngl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\nv_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n}";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_image;\nuniform float uColorFactor;\n\nvoid main() {\nvec4 sample = texture2D(u_image, v_texCoord);\nfloat grey = 0.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\ngl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n}`,h=r(t,[n(t,t.VERTEX_SHADER,s),n(t,t.FRAGMENT_SHADER,a)]);zr(this,Qr,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),zr(this,$r,e(t),"f"),zr(this,Jr,i(t),"f"),zr(this,Kr,p,"f")}const n=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(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)},v=(t,e,s,o)=>{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),n(t,s.positions,e.attribLocations.vertexPosition),n(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[qr.GREY,qr.GREY32].includes(p)?1:0);let m,_,v=Zr.translate(Zr.identity(),-1,-1);v=Zr.scale(v,2,2),v=Zr.scale(v,1/t.canvas.width,1/t.canvas.height),m=Zr.translate(v,u,d),m=Zr.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=Zr.translate(Zr.identity(),a/i,h/r),_=Zr.scale(_,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,Xr(this,Jr,"f"),e),v(t,Xr(this,Qr,"f"),Xr(this,$r,"f"),Xr(this,Jr,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){Xn._onLog&&Xn._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return Xn._onLog&&Xn._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===qr.GREY?qr.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return Xn._onLog&&Xn._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,r,n,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let r,n=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(n=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),r=new Uint8Array(i.buffer,0,4*o*a)):(r=new Uint8Array(4*o*a),e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,r))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(n,s,o,a),r=new Uint8Array(e.data.buffer),null==i||i.set(r)}return r}transformPixelFormat(t,e,i,r){let n,s;if(Xn._onLog&&(n=Date.now(),Xn._onLog("transformPixelFormat(), START: "+n)),e===i)return Xn._onLog&&Xn._onLog("transformPixelFormat() end. Costs: "+(Date.now()-n)),r?new Uint8Array(t):t;const o=[qr.RGBA,qr.RBGA,qr.GRBA,qr.GBRA,qr.BRGA,qr.BGRA];if(o.includes(e))if(i===qr.GREY){s=new Uint8Array(t.length/4);for(let e=0;eh||e.sy+e.sHeight>l)throw new Error("Invalid position.");null===(r=Xn._onLog)||void 0===r||r.call(Xn,"getImageData(), START: "+(c=Date.now()));const d=Math.round(e.sx),f=Math.round(e.sy),g=Math.round(e.sWidth),m=Math.round(e.sHeight),p=Math.round(e.dWidth),_=Math.round(e.dHeight);let v,y=(null==i?void 0:i.pixelFormat)||qr.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(qr.GREY===y&&w.length{this.disposed||r.includes(n)&&n.apply(i.target,s)}),0);else try{o=n.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){jr(this,nn,!0,"f")}}rn=new WeakMap,nn=new WeakMap;const Zn=(t,e,i,r)=>{if(!i)return t;let n=e+Math.round((t-e)/i)*i;return r&&(n=Math.min(n,r)),n};class qn{static get version(){return"2.0.18"}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 findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find((t=>e.includes(t.label.toLowerCase())));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],r=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],n=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!n.length)return null;const s=n.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const o=n.find((t=>{const e=t.label.toLowerCase();return r.some((t=>e.includes(t)))}));return o?o.deviceId:n[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(Hr.OS))return qn.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(Hr.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise((async(r,n)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),r(t)},l=t=>{s&&clearTimeout(s),o(),n(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise((t=>{g=t})),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise((t=>{setTimeout(t,1e3)})),!a){i&&(s=setTimeout((()=>{o(),n(new Error("Failed to play video. Timeout."))}),i)),await m;try{await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a)try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}}))}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let r;try{r=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==r||r.getTracks().forEach((t=>{t.stop()}))}return{ok:!0}}get state(){if(!Nr(this,vn,"f"))return"closed";if("pending"===Nr(this,vn,"f"))return"opening";if("fulfilled"===Nr(this,vn,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?qn.isStorageAvailable("localStorage")?jr(this,gn,!0,"f"):(jr(this,gn,!1,"f"),console.warn("Local storage is unavailable")):jr(this,gn,!1,"f")}get ifSaveLastUsedCamera(){return Nr(this,gn,"f")}get isVideoPlaying(){return!(!Nr(this,an,"f")||Nr(this,an,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,r;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=Nr(this,Sn,"f"))||void 0===e||e.removeEventListener("click",Nr(this,Tn,"f")),null===(i=Nr(this,Sn,"f"))||void 0===i||i.removeEventListener("touchend",Nr(this,Tn,"f")),null===(r=Nr(this,Sn,"f"))||void 0===r||r.removeEventListener("touchmove",Nr(this,En,"f")),jr(this,Sn,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(Hr.OS)?(t.addEventListener("touchend",Nr(this,Tn,"f")),t.addEventListener("touchmove",Nr(this,En,"f"))):t.addEventListener("click",Nr(this,Tn,"f")))}get tapFocusEventBoundEl(){return Nr(this,Sn,"f")}get disposed(){return Nr(this,Mn,"f")}constructor(t){var e,i;on.add(this),an.set(this,null),hn.set(this,void 0),ln.set(this,(()=>{"opened"===this.state&&Nr(this,An,"f").fire("resumed",null,{target:this,async:!1})})),cn.set(this,(()=>{Nr(this,An,"f").fire("paused",null,{target:this,async:!1})})),un.set(this,void 0),dn.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],fn.set(this,void 0),gn.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,mn.set(this,void 0),pn.set(this,!0),_n.set(this,void 0),vn.set(this,void 0),yn.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},wn.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,r;const n=window.getComputedStyle(Nr(this,an,"f")).objectFit,s=this.getResolution(),o=Nr(this,an,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=Nr(this,an,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===n)d>u?(f=l/s.width,i=(t-a)/f,r=(e-h-(c-l/d)/2)/f):(f=c/s.height,r=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==n)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,r=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,r=(e-h+(l/d-c)/2)/f)}return{x:i,y:r}},Cn.set(this,!1),En.set(this,(()=>{jr(this,Cn,!0,"f")})),Tn.set(this,(async t=>{var e;if(Nr(this,Cn,"f"))return void jr(this,Cn,!1,"f");if(!Nr(this,wn,"f"))return;if(!this.isVideoPlaying)return;if(!Nr(this,hn,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,r;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,r=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,r=t.changedTouches[0].clientY}const n=this.getResolution(),s=2*Math.round(Math.min(n.width,n.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,r)}catch(t){}if(o.x<0||o.x>n.width||o.y<0||o.y>n.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;qn._onLog&&(c=Date.now());try{await Nr(this,on,"m",Wn).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(qn._onLog)throw qn._onLog(t),t}qn._onLog&&qn._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout((()=>{var t;qn._onLog&&qn._onLog("Back to continuous focus."),null===(t=Nr(this,hn,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime),Nr(this,An,"f").fire("tapfocus",null,{target:this,async:!1})})),Sn.set(this,null),bn.set(this,1),In.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!Nr(this,an,"f"))return;const t=Nr(this,bn,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)Nr(this,an,"f").style.transform="";else{const e=window.getComputedStyle(Nr(this,an,"f")).objectFit,i=Nr(this,an,"f").videoWidth,r=Nr(this,an,"f").videoHeight,{width:n,height:s}=Nr(this,an,"f").getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=n/s,a=i/r;let h=1;"contain"===e?h=oo?s/(i/t):n/(r/t));const l=h*(1-1/t)*(i/2-Nr(this,In,"f").x),c=h*(1-1/t)*(r/2-Nr(this,In,"f").y);Nr(this,an,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},xn.set(this,(function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===qr.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(qn._onLog&&qn._onLog("document visible. video paused: "+(null===(t=Nr(this,an,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){qn._onLog&&qn._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){qn._onLog&&qn._onLog("document visible. 1st resume video failed, try open instead.")}e||await Nr(this,on,"m",Nn).call(this)}if(await new Promise((t=>setTimeout(t,300))),!this.isVideoPlaying){qn._onLog&&qn._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){qn._onLog&&qn._onLog("document visible. 2rd resume video failed, try open instead.")}e||await Nr(this,on,"m",Nn).call(this)}}}else"hidden"===document.visibilityState&&(qn._onLog&&qn._onLog("document hidden. video paused: "+(null===(e=Nr(this,an,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())})),Mn.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout((()=>{qn.onWarning&&qn.onWarning("The browser is too old or the page is loaded from an insecure origin.")}),0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),jr(this,An,new zn,"f"),this.imageDataGetter=new Xn,document.addEventListener("visibilitychange",Nr(this,Ln,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",Nr(this,ln,"f")),t.addEventListener("pause",Nr(this,cn,"f")),jr(this,an,t,"f")}getVideoEl(){return Nr(this,an,"f")}releaseVideoEl(){var t,e;null===(t=Nr(this,an,"f"))||void 0===t||t.removeEventListener("play",Nr(this,ln,"f")),null===(e=Nr(this,an,"f"))||void 0===e||e.removeEventListener("pause",Nr(this,cn,"f")),jr(this,an,null,"f")}isVideoLoaded(){return!!Nr(this,an,"f")&&4==Nr(this,an,"f").readyState}async open(){if(Nr(this,_n,"f")&&!Nr(this,pn,"f")){if("pending"===Nr(this,vn,"f"))return Nr(this,_n,"f");if("fulfilled"===Nr(this,vn,"f"))return}Nr(this,An,"f").fire("before:open",null,{target:this}),await Nr(this,on,"m",Nn).call(this),Nr(this,An,"f").fire("played",null,{target:this,async:!1}),Nr(this,An,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;Nr(this,An,"f").fire("before:close",null,{target:this});const t=Nr(this,_n,"f");if(Nr(this,on,"m",Un).call(this),t&&"pending"===Nr(this,vn,"f")){try{await t}catch(t){}if(!1===Nr(this,pn,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}jr(this,_n,null,"f"),jr(this,vn,null,"f"),Nr(this,An,"f").fire("closed",null,{target:this,async:!1})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");Nr(this,an,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await Nr(this,an,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof Nr(this,un,"f").video&&(Nr(this,un,"f").video={}),delete Nr(this,un,"f").video.facingMode,Nr(this,un,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&Nr(this,pn,"f"))){Nr(this,An,"f").fire("before:camera:change",[],{target:this,async:!1}),await Nr(this,on,"m",jn).call(this);try{this.resetSoftwareScale()}catch(t){}return Nr(this,dn,"f")}}async switchToFrontCamera(t){if("object"!=typeof Nr(this,un,"f").video&&(Nr(this,un,"f").video={}),(null==t?void 0:t.resolution)&&(Nr(this,un,"f").video.width={ideal:t.resolution.width},Nr(this,un,"f").video.height={ideal:t.resolution.height}),delete Nr(this,un,"f").video.deviceId,Nr(this,un,"f").video.facingMode={exact:"user"},jr(this,fn,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&Nr(this,pn,"f"))){Nr(this,An,"f").fire("before:camera:change",[],{target:this,async:!1}),Nr(this,on,"m",jn).call(this);try{this.resetSoftwareScale()}catch(t){}return Nr(this,dn,"f")}}getCamera(){var t;if(Nr(this,dn,"f"))return Nr(this,dn,"f");{let e=(null===(t=Nr(this,un,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}else r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));const n=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind));return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof Nr(this,un,"f").video&&(Nr(this,un,"f").video={}),i?(Nr(this,un,"f").video.width={exact:t},Nr(this,un,"f").video.height={exact:e}):(Nr(this,un,"f").video.width={ideal:t},Nr(this,un,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&Nr(this,pn,"f"))return null;Nr(this,An,"f").fire("before:resolution:change",[],{target:this,async:!1}),await Nr(this,on,"m",jn).call(this);try{this.resetSoftwareScale()}catch(t){}const r=this.getResolution();return{width:r.width,height:r.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&Nr(this,an,"f"))return{width:Nr(this,an,"f").videoWidth,height:Nr(this,an,"f").videoHeight};if(Nr(this,hn,"f")){const t=Nr(this,hn,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:Nr(this,an,"f").videoWidth,height:Nr(this,an,"f").videoHeight};{const t={width:0,height:0};let e=Nr(this,un,"f").video.width||0,i=Nr(this,un,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,r,n,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=Nr(this,Rn,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){d=null===(u=Nr(this,dn,"f"))||void 0===u?void 0:u.deviceId;let e=Nr(this,Rn,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],Nr(this,Rn,"f").set(d,e),jr(this,yn,!0,"f");try{for(let t of this.detectedResolutions){await Nr(this,hn,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),Nr(this,on,"m",Pn).call(this);const i=Nr(this,hn,"f").getSettings(),r={width:i.width,height:i.height};f(d,r)||e.push({width:r.width,height:r.height})}}catch(t){throw Nr(this,on,"m",Un).call(this),jr(this,yn,!1,"f"),t}try{await Nr(this,on,"m",Nn).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{jr(this,yn,!1,"f")}return e}{const e=async(t,e,i)=>{const r={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let n=null;try{n=await 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};let i=(null===(s=null===(n=null===(r=Nr(this,un,"f"))||void 0===r?void 0:r.video)||void 0===n?void 0:n.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=Nr(this,un,"f"))||void 0===o?void 0:o.video)||void 0===a?void 0:a.deviceId)||void 0===h?void 0:h.ideal)||(null===(c=null===(l=Nr(this,un,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=Nr(this,Rn,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],Nr(this,Rn,"f").set(i,u);for(let t of this.detectedResolutions){const r=await e(i,t.width,t.height);r&&!f(i,r)&&u.push({width:r.width,height:r.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");jr(this,un,JSON.parse(JSON.stringify(t)),"f"),jr(this,fn,null,"f"),e&&Nr(this,on,"m",jn).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(Nr(this,un,"f")))}resetMediaStreamConstraints(){jr(this,un,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!Nr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Nr(this,hn,"f").getCapabilities?Nr(this,hn,"f").getCapabilities():{}}getCameraSettings(){if(!Nr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Nr(this,hn,"f").getSettings()}async turnOnTorch(){if(!Nr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Nr(this,hn,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!Nr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Nr(this,hn,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Nr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Zn(t,r.min,r.step,r.max)),await Nr(this,hn,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Nr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Zn(t,r.min,r.step,r.max)),await Nr(this,hn,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Nr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!r)throw Error("Not supported.");e&&(tr.max&&(t=r.max));const n=this.getResolution();return await Nr(this,hn,"f").applyConstraints({width:{ideal:Math.max(n.width,n.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!Nr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),r=null==i?void 0:i.focusMode,n=null==i?void 0:i.focusDistance;if(!r)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!r.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!n)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(in.max&&(i=n.max),i=Zn(i,n.min,n.step,n.max)),this._focusParameters.focusArea=null,await Nr(this,hn,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,r=t.area.height;if(!i||!r){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),r||(r=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:r},await Nr(this,on,"m",Wn).call(this,e,i,r)}}}else this._focusParameters.focusArea=null,await Nr(this,hn,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async enableTapToFocus(){jr(this,wn,!0,"f")}disableTapToFocus(){jr(this,wn,!1,"f")}isTapToFocusEnabled(){return Nr(this,wn,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"!==this.state)throw new Error("Video is not playing.");t.centerPoint?Nr(this,on,"m",Yn).call(this,t.centerPoint):this.resetScaleCenter();try{if(Nr(this,on,"m",Hn).call(this,Nr(this,In,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*Nr(this,bn,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!Nr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Zn(t,r.min,r.step,r.max)),await Nr(this,hn,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&Nr(this,on,"m",Yn).call(this,e),jr(this,bn,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return Nr(this,bn,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();jr(this,In,{x:t.width/2,y:t.height/2},"f")}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(Nr(this,yn,"f"))return null;const e=Date.now();qn._onLog&&qn._onLog("getFrameData() START: "+e);const i=Nr(this,an,"f").videoWidth,r=Nr(this,an,"f").videoHeight;let n={sx:0,sy:0,sWidth:i,sHeight:r,dWidth:i,dHeight:r};(null==t?void 0:t.position)&&(n=JSON.parse(JSON.stringify(t.position)));let s=qr.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=Nr(this,bn,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=Nr(this,In,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,n=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))n=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.scaleCenter.y)/100*r}if(isNaN(e)||isNaN(n))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(n)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==r)return null;1!==o&&(n.sWidth=Math.round(n.sWidth/o),n.sHeight=Math.round(n.sHeight/o),n.sx=Math.round((1-1/o)*a.x+n.sx/o),n.sy=Math.round((1-1/o)*a.y+n.sy/o));const l=this.imageDataGetter.getImageData(Nr(this,an,"f"),n,{pixelFormat:s,bufferContainer:h});if(!l)return null;const c=Date.now();return qn._onLog&&qn._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:Nr(this,xn,"f")}}on(t,e){if(!Nr(this,On,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);Nr(this,An,"f").on(t,e)}off(t,e){Nr(this,An,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),Nr(this,An,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",Nr(this,Ln,"f")),jr(this,Mn,!0,"f")}}var Kn,Jn,Qn,$n,ts,es,is,rs,ns,ss,os,as,hs,ls,cs,us,ds,fs,gs,ms,ps,_s,vs,ys,ws,Cs,Es,Ts,Ss,bs,Is,xs,As,Os,Rs;an=new WeakMap,hn=new WeakMap,ln=new WeakMap,cn=new WeakMap,un=new WeakMap,dn=new WeakMap,fn=new WeakMap,gn=new WeakMap,mn=new WeakMap,pn=new WeakMap,_n=new WeakMap,vn=new WeakMap,yn=new WeakMap,wn=new WeakMap,Cn=new WeakMap,En=new WeakMap,Tn=new WeakMap,Sn=new WeakMap,bn=new WeakMap,In=new WeakMap,xn=new WeakMap,An=new WeakMap,On=new WeakMap,Rn=new WeakMap,Dn=new WeakMap,Ln=new WeakMap,Mn=new WeakMap,on=new WeakSet,Fn=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(Nr(this,fn,"f"))delete t.video.facingMode,t.video.deviceId={exact:Nr(this,fn,"f")};else if(this.ifSaveLastUsedCamera&&qn.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(Hr.OS)?(await this._getCameras(!1),Nr(this,on,"m",Pn).call(this),e=qn.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(Hr.OS)||(await this._getCameras(!1),Nr(this,on,"m",Pn).call(this),e=qn.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const r=await e(i);r&&(delete t.video.facingMode,t.video.deviceId={exact:r})}return t},Pn=function(){if(Nr(this,pn,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},kn=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;try{qn._onLog&&qn._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const n=async t=>{for(let n of e){n&&(await new Promise((t=>setTimeout(t,n))),Nr(this,on,"m",Pn).call(this));try{qn._onLog&&qn._onLog("ask "+JSON.stringify(t)),r=await navigator.mediaDevices.getUserMedia(t),Nr(this,on,"m",Pn).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,qn._onLog&&qn._onLog(t.message||t)}}};if(await n(t),r||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await n(t)),!r&&t.video.facingMode&&(delete t.video.facingMode,await n(t)),r||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await n(t))),!r)throw i;return r}catch(t){throw null==r||r.getTracks().forEach((t=>{t.stop()})),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},Bn=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach((t=>{t.stop()})),this._mediaStream=null),jr(this,hn,null,"f")},Nn=async function(){jr(this,pn,!1,"f");const t=jr(this,mn,Symbol(),"f");if(Nr(this,_n,"f")&&"pending"===Nr(this,vn,"f")){try{await Nr(this,_n,"f")}catch(t){}Nr(this,on,"m",Pn).call(this)}if(t!==Nr(this,mn,"f"))return;const e=jr(this,_n,(async()=>{jr(this,vn,"pending","f");try{if(this.videoSrc){if(!Nr(this,an,"f"))throw new Error("'videoEl' should be set.");await qn.playVideo(Nr(this,an,"f"),this.videoSrc,this.cameraOpenTimeout),Nr(this,on,"m",Pn).call(this)}else{let t=await Nr(this,on,"m",Fn).call(this);Nr(this,on,"m",Bn).call(this);let e=await Nr(this,on,"m",kn).call(this,t);await this._getCameras(!1),Nr(this,on,"m",Pn).call(this);const i=()=>{const t=e.getVideoTracks();let i,r;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,r=e;break}}return r},r=Nr(this,un,"f");if("object"==typeof r.video){let n=r.video.facingMode;if(n instanceof Array&&n.length&&(n=n[0]),"object"==typeof n&&(n=n.exact||n.ideal),!(Nr(this,fn,"f")||this.ifSaveLastUsedCamera&&qn.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||r.video.deviceId)){const r=i(),s=qn.findBestCamera(this._arrCameras,n,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==r?void 0:r.deviceId)&&(e.getTracks().forEach((t=>{t.stop()})),t.video.deviceId={exact:s},e=await Nr(this,on,"m",kn).call(this,t),Nr(this,on,"m",Pn).call(this))}}const n=i();(null==n?void 0:n.deviceId)&&(jr(this,fn,n&&n.deviceId,"f"),this.ifSaveLastUsedCamera&&qn.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",Nr(this,fn,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),Nr(this,an,"f")&&(await qn.playVideo(Nr(this,an,"f"),e,this.cameraOpenTimeout),Nr(this,on,"m",Pn).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&jr(this,hn,s[0],"f"),jr(this,dn,n,"f")}}catch(t){throw Nr(this,on,"m",Un).call(this),jr(this,vn,null,"f"),t}jr(this,vn,"fulfilled","f")})(),"f");return e},jn=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=Nr(this,dn,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await Nr(this,on,"m",Nn).call(this);const r=this.getResolution();e&&e!==Nr(this,dn,"f").deviceId&&Nr(this,An,"f").fire("camera:changed",[Nr(this,dn,"f").deviceId,e],{target:this,async:!1}),i.width==r.width&&i.height==r.height||Nr(this,An,"f").fire("resolution:changed",[{width:r.width,height:r.height},{width:i.width,height:i.height}],{target:this,async:!1}),Nr(this,An,"f").fire("played",null,{target:this,async:!1})},Un=function(){Nr(this,on,"m",Bn).call(this),jr(this,dn,null,"f"),Nr(this,an,"f")&&(Nr(this,an,"f").srcObject=null,this.videoSrc&&(Nr(this,an,"f").pause(),Nr(this,an,"f").currentTime=0)),jr(this,pn,!0,"f");try{this.resetSoftwareScale()}catch(t){}},Vn=async function t(e,i){const r=t=>{if(!Nr(this,hn,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){Nr(this,hn,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let n;i=Zn(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await Nr(this,hn,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),r(e),n=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise((t=>{setTimeout(t,n)})),r(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h),a>l.width&&(a=l.width),h>l.height&&(h=l.height),s<0?s=0:s+a>l.width&&(s=l.width-a),o<0?o=0:o+h>l.height&&(o=l.height-h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(Nr(this,an,"f"),{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:qr.RGBA,bufferContainer:d}))return Nr(this,on,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await Nr(this,on,"m",t).call(this,e,o,a,n,s,c,u)}else{let h=await Nr(this,on,"m",Vn).call(this,e,c);if(a>h)return await Nr(this,on,"m",t).call(this,e,o,a,n,s,c,h);if(a==h)return await Nr(this,on,"m",t).call(this,e,o,a,c,h);let u=await Nr(this,on,"m",Vn).call(this,e,l);if(u>a&&ao.width||h<0||h>o.height)throw new Error("Invalid 'centerPoint'.");let l=0;if(e.endsWith("px"))l=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");l=parseFloat(e)/100*o.width}if(isNaN(l)||l<0)throw new Error("Invalid 'width'.");let c=0;if(i.endsWith("px"))c=parseFloat(i);else{if(!i.endsWith("%"))throw new Error("Invalid 'height'.");c=parseFloat(i)/100*o.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==Nr(this,bn,"f")){const t=Nr(this,bn,"f"),e=Nr(this,In,"f");l/=t,c/=t,a=(1-1/t)*e.x+a/t,h=(1-1/t)*e.y+h/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const u={focusL:a,focusT:h,focusW:l,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let r=Zn(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=Zn(Math.sqrt((e||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Zn(Math.sqrt(r*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await Nr(this,on,"m",Vn).call(this,t,s),a=await Nr(this,on,"m",Vn).call(this,t,n),h=await Nr(this,on,"m",Vn).call(this,t,r);if(a>h&&ho&&a>o){let e=await Nr(this,on,"m",Vn).call(this,t,i);const n=await Nr(this,on,"m",Gn).call(this,t,r,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,n}if(a==h&&hh){const e=await Nr(this,on,"m",Gn).call(this,t,r,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,r,n)},Yn=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,r=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))r=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(r))throw new Error("Invalid scale center.");jr(this,In,{x:i,y:r},"f")},Hn=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},qn.browserInfo=Hr,qn.onWarning=null===(sn=null===window||void 0===window?void 0:window.console)||void 0===sn?void 0:sn.warn;class Ds{constructor(t){Kn.add(this),Jn.set(this,void 0),Qn.set(this,0),$n.set(this,void 0),ts.set(this,0),es.set(this,!1),Qe(this,Jn,t,"f")}startCharging(){Je(this,es,"f")||(Ds._onLog&&Ds._onLog("start charging."),Je(this,Kn,"m",rs).call(this),Qe(this,es,!0,"f"))}stopCharging(){Je(this,$n,"f")&&clearTimeout(Je(this,$n,"f")),Je(this,es,"f")&&(Ds._onLog&&Ds._onLog("stop charging."),Qe(this,Qn,Date.now()-Je(this,ts,"f"),"f"),Qe(this,es,!1,"f"))}}Jn=new WeakMap,Qn=new WeakMap,$n=new WeakMap,ts=new WeakMap,es=new WeakMap,Kn=new WeakSet,is=function(){vt.cfd(1),Ds._onLog&&Ds._onLog("charge 1.")},rs=function t(){0==Je(this,Qn,"f")&&Je(this,Kn,"m",is).call(this),Qe(this,ts,Date.now(),"f"),Je(this,$n,"f")&&clearTimeout(Je(this,$n,"f")),Qe(this,$n,setTimeout((()=>{Qe(this,Qn,0,"f"),Je(this,Kn,"m",t).call(this)}),Je(this,Jn,"f")-Je(this,Qn,"f")),"f")};class Ls{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-Je(this,ns,"f",as)<100)){if(Qe(this,ns,e,"f",as),Je(this,ns,"f",ss).size&&(t=Je(this,ns,"f",ss).values().next().value,this.beepSoundSource==t.src?(Je(this,ns,"f",ss).delete(t),t.play()):t=null),!t)if(Je(this,ns,"f",os).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout((()=>{Je(this,ns,"f",os).delete(t)}),2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",(()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,Je(this,ns,"f",os).delete(t),Je(this,ns,"f",ss).add(t)}))}else Je(this,ns,"f",hs)||(Qe(this,ns,!0,"f",hs),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&Je(this,ns,"f",os).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(Ls.vibrateDuration)}}}ns=Ls,ss={value:new Set},os={value:new Set},as={value:0},hs={value:!1},Ls.allowBeep=!0,Ls.beepSoundSource="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",Ls.allowVibrate=!0,Ls.vibrateDuration=300;const Ms=new Map([[qr.GREY,a.IPF_GRAYSCALED],[qr.RGBA,a.IPF_ABGR_8888]]),Fs="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};class Ps extends J{static set _onLog(t){Qe(Ps,cs,t,"f",us),qn._onLog=t,Ds._onLog=t}static get _onLog(){return Je(Ps,cs,"f",us)}static async detectEnvironment(){return await(async()=>({wasm:$e,worker:ti,getUserMedia:ei,camera:await ii(),browser:qe.browser,version:qe.version,OS:qe.OS}))()}static async testCameraAccess(){const t=await qn.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(t){var e,i;if(t&&!(t instanceof Br))throw new TypeError("Invalid view.");if(null===(e=gt.license)||void 0===e?void 0:e.LicenseManager){if(!(null===(i=gt.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await vt.loadWasm(["license"]),await gt.license.dynamsoft()}const r=new Ps(t);return Ps.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{Ps.onWarning&&Ps.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{Ps.onWarning&&Ps.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),r}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");Qe(this,gs,t,"f")}get singleFrameMode(){return Je(this,gs,"f")}get _isFetchingStarted(){return Je(this,ws,"f")}get disposed(){return Je(this,bs,"f")}constructor(t){if(super(),ls.add(this),ds.set(this,"closed"),fs.set(this,void 0),this.isTorchOn=void 0,gs.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},ms.set(this,((t,e,i,r)=>{const n=Date.now(),s={sx:r.x,sy:r.y,sWidth:r.width,sHeight:r.height,dWidth:r.width,dHeight:r.height},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const h=this.cameraManager.imageDataGetter.getImageData(t,s,{pixelFormat:this.getPixelFormat()===a.IPF_GRAYSCALED?qr.GREY:qr.RGBA});let l=null;if(h){const t=Date.now();let o;o=h.pixelFormat===qr.GREY?h.width:4*h.width;let a=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(a=!1),l={bytes:h.data,width:h.width,height:h.height,stride:o,format:Ms.get(h.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:St.ITT_FILE_IMAGE,isCropped:a,cropRegion:{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:h.width,currentHeight:h.height,timeSpent:t-n,timeStamp:t},toCanvas:Je(this,ps,"f"),isDCEFrame:!0}}return l})),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():Wi.convert(Je(this,vs,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height});const i=Je(this,ms,"f").call(this,t,t.width,t.height,e);Je(this,fs,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},ps.set(this,(function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.format===a.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(qe.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",(()=>{Je(this,Ss,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("camera:changed",(()=>{this.clearBuffer()})),this._on("before:resolution:change",(()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("resolution:changed",(()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})})),this._on("paused",(()=>{Je(this,Ss,"f").stopCharging();const t=this.cameraView;t&&t.disposed})),this._on("resumed",(()=>{const t=this.cameraView;t&&t.disposed})),this._on("tapfocus",(()=>{Je(this,Es,"f").tapToFocus&&Je(this,Ss,"f").startCharging()})),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,r,n,s;if(Je(this,ls,"m",Is).call(this)||!this.isOpen()||this.isPaused())return;const o=t.intermediateResultUnits;Ps._onLog&&(Ps._onLog("intermediateResultUnits:"),Ps._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===At.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===At.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(Ps._onLog&&(Ps._onLog("hasLocalizedBarcodes:"),Ps._onLog(h)),Je(this,Es,"f").autoZoom||Je(this,Es,"f").enhancedFocus)if(a)Je(this,Ts,"f").autoZoomInFrameArray.length=0,Je(this,Ts,"f").autoZoomOutFrameCount=0,Je(this,Ts,"f").frameArrayInIdealZoom.length=0,Je(this,Ts,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),Je(this,Es,"f").autoZoom&&Je(this,Ss,"f").startCharging()},a=async t=>{await this.setFocus(t),Je(this,Es,"f").enhancedFocus&&Je(this,Ss,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(r=h.cropRegion)||void 0===r?void 0:r.top)||0,u=(null===(n=h.cropRegion)||void 0===n?void 0:n.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,r,n;{const t=this.video.videoWidth*(1-Je(this,Ts,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+Je(this,Ts,"f").autoZoomDetectionArea)/2,i=e,r=t,s=this.video.videoHeight*(1-Je(this,Ts,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+Je(this,Ts,"f").autoZoomDetectionArea)/2;n=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:r,y:a}]}Ps._onLog&&(Ps._onLog("detectionArea:"),Ps._onLog(n));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let r=!1;const n=t.length;if(n<=2)return!1;for(let s=0;s0!=Zi(a.y-i)>0&&Zi(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(r=!r)}return r}(e,t.x,t.y)},r=(t,e)=>!!(qi([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||qi([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||qi([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||qi([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(r([e[0].x,e[0].y,e[1].x,e[1].y],t)||r([e[1].x,e[1].y,e[2].x,e[2].y],t)||r([e[2].x,e[2].y,e[3].x,e[3].y],t)||r([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of o)if(e.unitType===At.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach((t=>{Br._transformCoordinates(t,l,c,u,d,f,g)})),t(n,e)&&s.push(i)}if(Ps._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=Dr.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===At.IRUT_LOCALIZED_BARCODES)for(let r of i.localizedBarcodes){if(!r)continue;const i=r.location.points,n=new Di({points:i},e);t.addDrawingItems([n])}}}if(Ps._onLog&&(Ps._onLog("intersectedResults:"),Ps._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter((t=>t.possibleFormats==Fs.BF_QR_CODE||t.possibleFormats==Fs.BF_DATAMATRIX));if(t.length||(t=s.filter((t=>t.possibleFormats==Fs.BF_ONED)),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,r=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(r-g/2)*(r-g/2)};a=t[0];let i=e(a);if(1!=t.length)for(let r=1;r1.1*a.confidence||t[r].confidence>.9*a.confidence&&ni&&s>i&&o>i&&h>i&&m.result.moduleSize{})),Je(this,Ts,"f").autoZoomInFrameArray.filter((t=>!0===t)).length>=Je(this,Ts,"f").autoZoomInFrameLimit[1]){Je(this,Ts,"f").autoZoomInFrameArray.length=0;const i=[(.5-r)/(.5-n),(.5-r)/(.5-s),(.5-r)/(.5-o),(.5-r)/(.5-h)].filter((t=>t>0)),a=Math.min(...i,Je(this,Ts,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/Je(this,Ts,"f").autoZoomInMaxTimes),Je(this,Ts,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max(Je(this,Ts,"f").minValue,u),u=Math.min(Je(this,Ts,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(Je(this,Ts,"f").autoZoomInFrameArray.length=0,Je(this,Ts,"f").frameArrayInIdealZoom.push(!0),Je(this,Ts,"f").frameArrayInIdealZoom.splice(0,Je(this,Ts,"f").frameArrayInIdealZoom.length-Je(this,Ts,"f").frameLimitInIdealZoom[0]),Je(this,Ts,"f").frameArrayInIdealZoom.filter((t=>!0===t)).length>=Je(this,Ts,"f").frameLimitInIdealZoom[1]&&(Je(this,Ts,"f").frameArrayInIdealZoom.length=0,Je(this,Es,"f").enhancedFocus)){const e=m.points;try{await a({mode:"manual",area:{centerPoint:{x:(e[0].x+e[2].x)/2+"px",y:(e[0].y+e[2].y)/2+"px"},width:e[2].x-e[0].x+"px",height:e[2].y-e[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}if(!Je(this,Es,"f").autoZoom&&Je(this,Es,"f").enhancedFocus&&(Je(this,Ts,"f").autoFocusFrameArray.push(!0),Je(this,Ts,"f").autoFocusFrameArray.splice(0,Je(this,Ts,"f").autoFocusFrameArray.length-Je(this,Ts,"f").autoFocusFrameLimit[0]),Je(this,Ts,"f").autoFocusFrameArray.filter((t=>!0===t)).length>=Je(this,Ts,"f").autoFocusFrameLimit[1])){Je(this,Ts,"f").autoFocusFrameArray.length=0;try{const t=m.points;await a({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(Je(this,Es,"f").autoZoom){if(Je(this,Ts,"f").autoZoomInFrameArray.push(!1),Je(this,Ts,"f").autoZoomInFrameArray.splice(0,Je(this,Ts,"f").autoZoomInFrameArray.length-Je(this,Ts,"f").autoZoomInFrameLimit[0]),Je(this,Ts,"f").autoZoomOutFrameCount++,Je(this,Ts,"f").frameArrayInIdealZoom.push(!1),Je(this,Ts,"f").frameArrayInIdealZoom.splice(0,Je(this,Ts,"f").frameArrayInIdealZoom.length-Je(this,Ts,"f").frameLimitInIdealZoom[0]),Je(this,Ts,"f").autoZoomOutFrameCount>=Je(this,Ts,"f").autoZoomOutFrameLimit){Je(this,Ts,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let r=i-Math.max((i-1)*Je(this,Ts,"f").autoZoomOutStepRate,Je(this,Ts,"f").autoZoomOutMinStep);r=Math.max(Je(this,Ts,"f").minValue,r),r=Math.min(Je(this,Ts,"f").maxValue,r);try{await e({factor:r})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}Je(this,Es,"f").enhancedFocus&&a({mode:"continuous"}).catch((()=>{}))}!Je(this,Es,"f").autoZoom&&Je(this,Es,"f").enhancedFocus&&(Je(this,Ts,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch((()=>{})))}}},Qe(this,Ss,new Ds(1e4),"f")}setCameraView(t){if(!(t instanceof Br))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),Je(this,ls,"m",Is).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;Je(this,ls,"m",Is).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return Je(this,ls,"m",Is).call(this)?Je(this,ds,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){const t=this.cameraView;if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");t&&(t._singleFrameMode=this.singleFrameMode,Je(this,ls,"m",Is).call(this)?t._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(t.getVideoElement()),t._startLoading()));let e={width:0,height:0,deviceId:""};if(Je(this,ls,"m",Is).call(this));else{try{await this.cameraManager.open()}catch(e){throw t&&t._stopLoading(),"NotFoundError"===e.name?new Error(`No camera devices were detected. Please ensure a camera is connected and recognized by your system. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):"NotAllowedError"===e.name?new Error(`Camera access is blocked. Please check your browser settings or grant permission to use the camera. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):e}let i,r=t.getUIElement();if(r=r.shadowRoot||r,i=r.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=r.elTorchAuto=r.querySelector(".dce-mn-torch-auto"),e=r.elTorchOn=r.querySelector(".dce-mn-torch-on"),n=r.elTorchOff=r.querySelector(".dce-mn-torch-off");t&&(e.style.display=null==this.isTorchOn?"":"none"),e&&(e.style.display=1==this.isTorchOn?"":"none"),n&&(n.style.display=0==this.isTorchOn?"":"none");let s=r.elBeepOn=r.querySelector(".dce-mn-beep-on"),o=r.elBeepOff=r.querySelector(".dce-mn-beep-off");s&&(s.style.display=Ls.allowBeep?"":"none"),o&&(o.style.display=Ls.allowBeep?"none":"");let a=r.elVibrateOn=r.querySelector(".dce-mn-vibrate-on"),h=r.elVibrateOff=r.querySelector(".dce-mn-vibrate-off");a&&(a.style.display=Ls.allowVibrate?"":"none"),h&&(h.style.display=Ls.allowVibrate?"none":""),r.elResolutionBox=r.querySelector(".dce-mn-resolution-box");let l,c=r.elZoom=r.querySelector(".dce-mn-zoom");c&&(c.style.display="none",l=r.elZoomSpan=c.querySelector("span"));let u=r.elToast=r.querySelector(".dce-mn-toast"),d=r.elCameraClose=r.querySelector(".dce-mn-camera-close"),f=r.elTakePhoto=r.querySelector(".dce-mn-take-photo"),g=r.elCameraSwitch=r.querySelector(".dce-mn-camera-switch"),m=r.elCameraAndResolutionSettings=r.querySelector(".dce-mn-camera-and-resolution-settings");m&&(m.style.display="none");const p=r.dceMnFs={},_=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",_);const v=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",v);const y=()=>{this.turnAutoTorch()};null==n||n.addEventListener("pointerdown",y);const w=()=>{Ls.allowBeep=!Ls.allowBeep,s&&(s.style.display=Ls.allowBeep?"":"none"),o&&(o.style.display=Ls.allowBeep?"none":"")};for(let t of[o,s])null==t||t.addEventListener("pointerdown",w);const C=()=>{Ls.allowVibrate=!Ls.allowVibrate,a&&(a.style.display=Ls.allowVibrate?"":"none"),h&&(h.style.display=Ls.allowVibrate?"none":"")};for(let t of[h,a])null==t||t.addEventListener("pointerdown",C);const E=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),r=parseInt(e.getAttribute("data-height")),n=await this.setResolution({width:i,height:r});{let e=Math.max(n.width,n.height),i=Math.min(n.width,n.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&b(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?m&&(m.style.display=m.style.display?"":"none"):m&&""===m.style.display&&(m.style.display="none"))};r.addEventListener("click",E);let T=null;p.funcInfoZoomChange=(t,e=3e3)=>{c&&l&&(l.textContent=t.toFixed(1),c.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout((()=>{c.style.display="none",T=null}),e))};let S=null,b=p.funcShowToast=(t,e=3e3)=>{u&&(u.textContent=t,u.style.display="",null!=S&&(clearTimeout(S),S=null),S=setTimeout((()=>{u.style.display="none",S=null}),e))};const I=()=>{this.close()};null==d||d.addEventListener("click",I);const x=()=>{};null==f||f.addEventListener("pointerdown",x);const A=()=>{var t,e;let i,r=this.getVideoSettings(),n=r.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),o=null==s?void 0:s.indexOf("front");-1===o&&(o=null==s?void 0:s.indexOf("前"));let a=null==s?void 0:s.indexOf("back");-1===a&&(a=null==s?void 0:s.indexOf("后")),"number"==typeof o&&-1!==o?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i&&(i="user"===((null==n?void 0:n.ideal)||(null==n?void 0:n.exact)||n)),r.video.facingMode={ideal:i?"environment":"user"},delete r.video.deviceId,this.updateVideoSettings(r)};null==g||g.addEventListener("pointerdown",A);let O=-1/0,R=1;const D=t=>{let e=Date.now();e-O>1e3&&(R=this.getZoomSettings().factor),R-=t.deltaY/200,R>20&&(R=20),R<1&&(R=1),this.setZoom({factor:R}),O=e};i.addEventListener("wheel",D);const L=new Map;let M=!1;const F=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],r=t.touches[1],n=L.get(i.identifier),s=L.get(r.identifier);if(!n||!s)break;let o=Math.pow(Math.pow(n.x-s.x,2)+Math.pow(n.y-s.y,2),.5),a=Math.pow(Math.pow(i.clientX-r.clientX,2)+Math.pow(i.clientY-r.clientY,2),.5),h=Date.now();if(M||h-O<100)return;h-O>1e3&&(R=this.getZoomSettings().factor),R*=a/o,R>20&&(R=20),R<1&&(R=1);let l=!1;"safari"==(null===(e=null==qe?void 0:qe.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/o>1&&R<2?(R=2,l=!0):a/o<1&&R<2&&(R=1,l=!0)),M=!0,l&&b("zooming..."),await this.setZoom({factor:R}),l&&(u.textContent=""),M=!1,O=Date.now();break}L.clear();for(let e of t.touches)L.set(e.identifier,{x:e.clientX,y:e.clientY})};r.addEventListener("touchstart",F),r.addEventListener("touchmove",F),r.addEventListener("touchend",F),r.addEventListener("touchcancel",F),p.unbind=()=>{null==t||t.removeEventListener("pointerdown",_),null==e||e.removeEventListener("pointerdown",v),null==n||n.removeEventListener("pointerdown",y);for(let t of[o,s])null==t||t.removeEventListener("pointerdown",w);for(let t of[h,a])null==t||t.removeEventListener("pointerdown",C);r.removeEventListener("click",E),null==d||d.removeEventListener("click",I),null==f||f.removeEventListener("pointerdown",x),null==g||g.removeEventListener("pointerdown",A),i.removeEventListener("wheel",D),r.removeEventListener("touchstart",F),r.removeEventListener("touchmove",F),r.removeEventListener("touchend",F),r.removeEventListener("touchcancel",F),delete r.dceMnFs,i.style.display="none"},i.style.display="",t&&null==this.isTorchOn&&setTimeout((()=>{this.turnAutoTorch(1e3)}),0)}this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const n=this.getResolution();e.width=n.width,e.height=n.height,e.deviceId=this.getSelectedCamera().deviceId}return Qe(this,ds,"open","f"),t&&(t._innerComponent.style.display="",Je(this,ls,"m",Is).call(this)||(t._stopLoading(),t._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),t._renderResolutionInfo({width:e.width,height:e.height}),t.eventHandler.fire("content:updated",null,{async:!1}),t.eventHandler.fire("videoEl:resized",null,{async:!1}))),Je(this,fs,"f").fire("opened",null,{target:this,async:!1}),e}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),Je(this,ls,"m",Is).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}Qe(this,ds,"closed","f"),Je(this,Ss,"f").stopCharging(),e&&(e._innerComponent.style.display="none",Je(this,ls,"m",Is).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),Je(this,fs,"f").fire("closed",null,{target:this,async:!1})}pause(){if(Je(this,ls,"m",Is).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!Je(this,ls,"m",Is).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(Je(this,ls,"m",Is).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){if(!t)throw new Error("Invalid value.");let e;e="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(e),this.isTorchOn=!1;const i=this.getResolution(),r=this.cameraView;return r&&!r.disposed&&(r._stopLoading(),r._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),r._renderResolutionInfo({width:i.width,height:i.height})),{width:i.width,height:i.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Je(this,fs,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Je(this,fs,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._on(r,e)}off(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._off(r,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(Je(this,ls,"m",Is).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(Je(this,ls,"m",Is).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){if(null!=this._taskid4AutoTorch){if(!(t{var t,n,s;if(this.disposed||e||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++r>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let o;try{o=this.fetchImage()}catch(t){}if(!o||!o.width||!o.height)return;let h=0;if(a.IPF_GRAYSCALED===o.format){for(let t=0;t=this.maxDarkCount4AutoTroch){null===(t=Ps._onLog)||void 0===t||t.call(Ps,`darkCount ${i}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(n=null==t?void 0:t.dceMnFs)||void 0===n||n.funcShowToast("Torch Auto On")}catch(t){console.warn(t),e=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,null===(s=null==i?void 0:i.dceMnFs)||void 0===s||s.funcShowToast("Torch Not Supported")}}}else i=0};this._taskid4AutoTorch=setInterval(n,t),this.isTorchOn=void 0,n();let s=this.cameraView.getUIElement();s=s.shadowRoot||s,s.elTorchAuto&&(s.elTorchAuto.style.display=""),s.elTorchOn&&(s.elTorchOn.style.display="none"),s.elTorchOff&&(s.elTorchOff.style.display="none")}async setColorTemperature(t){if(Je(this,ls,"m",Is).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(Je(this,ls,"m",Is).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,r;if(Je(this,ls,"m",Is).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(r=null==e?void 0:e.dceMnFs)||void 0===r||r.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(Je(this,ls,"m",Is).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(Je(this,ls,"m",Is).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(Je(this,ls,"m",Is).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){Je(this,Ts,"f").minValue=t.min,Je(this,Ts,"f").maxValue=t.max}getAutoZoomRange(){return{min:Je(this,Ts,"f").minValue,max:Je(this,Ts,"f").maxValue}}async enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=gt.license)||void 0===e?void 0:e.LicenseManager)||void 0===i?void 0:i.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==vt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&li.EF_ENHANCED_FOCUS&&(Je(this,Es,"f").enhancedFocus=!0),t&li.EF_AUTO_ZOOM&&(Je(this,Es,"f").autoZoom=!0),t&li.EF_TAP_TO_FOCUS&&(Je(this,Es,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&li.EF_ENHANCED_FOCUS&&(Je(this,Es,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch((()=>{}))),t&li.EF_AUTO_ZOOM&&(Je(this,Es,"f").autoZoom=!1,this.resetZoom().catch((()=>{}))),t&li.EF_TAP_TO_FOCUS&&(Je(this,Es,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),Je(this,ls,"m",As).call(this)&&Je(this,ls,"m",xs).call(this)||Je(this,Ss,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!E(t)&&!A(t))throw TypeError("Invalid 'region'.");Qe(this,vs,t?JSON.parse(JSON.stringify(t)):null,"f"),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(Je(this,vs,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");Qe(this,_s,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||Je(this,ls,"m",Is).call(this))}startFetching(){if(Je(this,ls,"m",Is).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");Je(this,ws,"f")||(Qe(this,ws,!0,"f"),Je(this,ls,"m",Os).call(this))}stopFetching(){Je(this,ws,"f")&&(Ps._onLog&&Ps._onLog("DCE: stop fetching loop: "+Date.now()),Je(this,Cs,"f")&&clearTimeout(Je(this,Cs,"f")),Qe(this,ws,!1,"f"))}fetchImage(){if(Je(this,ls,"m",Is).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(4!==this.video.readyState)throw new Error("The video is not loaded.");const t=this.getResolution();if(!(null==t?void 0:t.width)||!(null==t?void 0:t.height))throw new Error("The video is not loaded.");let e;if(e=Wi.convert(Je(this,vs,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height}),e.x>t.width||e.y>t.height)throw new Error("Invalid scan region.");e.x+e.width>t.width&&(e.width=t.width-e.x),e.y+e.height>t.height&&(e.height=t.height-e.y);const i={sx:e.x,sy:e.y,sWidth:e.width,sHeight:e.height,dWidth:e.width,dHeight:e.height},r=Math.max(i.dWidth,i.dHeight);if(this.canvasSizeLimit&&r>this.canvasSizeLimit){const t=this.canvasSizeLimit/r;i.dWidth>i.dHeight?(i.dWidth=this.canvasSizeLimit,i.dHeight=Math.round(i.dHeight*t)):(i.dWidth=Math.round(i.dWidth*t),i.dHeight=this.canvasSizeLimit)}const n=this.cameraManager.getFrameData({position:i,pixelFormat:this.getPixelFormat()===a.IPF_GRAYSCALED?qr.GREY:qr.RGBA});if(!n)return null;let s;s=n.pixelFormat===qr.GREY?n.width:4*n.width;let o=!0;return 0===i.sx&&0===i.sy&&i.sWidth===t.width&&i.sHeight===t.height&&(o=!1),{bytes:n.data,width:n.width,height:n.height,stride:s,format:Ms.get(n.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:St.ITT_VIDEO_FRAME,isCropped:o,cropRegion:{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height,isMeasuredInPercentage:!1},originalWidth:t.width,originalHeight:t.height,currentWidth:n.width,currentHeight:n.height,timeSpent:n.timeSpent,timeStamp:n.timeStamp},toCanvas:Je(this,ps,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,Je(this,ws,"f")&&(Je(this,Cs,"f")&&clearTimeout(Je(this,Cs,"f")),Qe(this,Cs,setTimeout((()=>{this.disposed||Je(this,ls,"m",Os).call(this)}),t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){Qe(this,ys,t,"f")}getPixelFormat(){return Je(this,ys,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(Je(this,ls,"m",Is).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",(()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",(()=>{t&&this.open(),e.remove()}),{once:!0})})),e.addEventListener("change",(async()=>{const i=e.files[0],r=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(i),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=Wi.convert(Je(this,vs,"f"),n,s);o||(o={x:0,y:0,width:n,height:s});const a=Je(this,ms,"f").call(this,r,n,s,o);t&&t(a)})),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=Je(this,ls,"m",Rs).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=Je(this,ls,"m",Rs).call(this,t);return{x:e.clientX,y:e.clientY}}convertToScanRegionCoordinates(t){if(!Je(this,vs,"f"))return JSON.parse(JSON.stringify(t));let e,i,r=Je(this,vs,"f").left||Je(this,vs,"f").x||0,n=Je(this,vs,"f").top||Je(this,vs,"f").y||0;if(!Je(this,vs,"f").isMeasuredInPercentage)return{x:t.x-r,y:t.y-n};if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!Je(this,ls,"m",Is).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Je(this,ls,"m",Is).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(Je(this,ls,"m",Is).call(this)){const t=this.cameraView._innerComponent.getElement("content");e=t.width,i=t.height}else{const t=this.getVideoEl();e=t.videoWidth,i=t.videoHeight}return{x:t.x-Math.round(r*e/100),y:t.y-Math.round(n*i/100)}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),Qe(this,bs,!0,"f")}}var ks,Bs,Ns,js,Us,Vs,Gs,Ws;cs=Ps,ds=new WeakMap,fs=new WeakMap,gs=new WeakMap,ms=new WeakMap,ps=new WeakMap,_s=new WeakMap,vs=new WeakMap,ys=new WeakMap,ws=new WeakMap,Cs=new WeakMap,Es=new WeakMap,Ts=new WeakMap,Ss=new WeakMap,bs=new WeakMap,ls=new WeakSet,Is=function(){return"disabled"!==this.singleFrameMode},xs=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},As=function(){for(let t in Je(this,Es,"f"))if(1==Je(this,Es,"f")[t])return!0;return!1},Os=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!Je(this,ws,"f"))return Je(this,Cs,"f")&&clearTimeout(Je(this,Cs,"f")),void Qe(this,Cs,setTimeout((()=>{this.disposed||Je(this,ls,"m",t).call(this)}),this.fetchInterval),"f");const e=()=>{var t;let e;Ps._onLog&&Ps._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{e=this.fetchImage()}catch(e){const i=e.message||e;if("The video is not loaded."===i)return;if(null===(t=Je(this,_s,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout((()=>{var t;null===(t=Je(this,_s,"f"))||void 0===t||t.onErrorReceived(Ct.EC_IMAGE_READ_FAILED,i)}),0);console.warn(e)}e?(this.addImageToBuffer(e),Ps._onLog&&Ps._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),Je(this,fs,"f").fire("frameAddedToBuffer",null,{async:!1})):Ps._onLog&&Ps._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case s.BOPM_BLOCK:break;case s.BOPM_UPDATE:e()}else e();Je(this,Cs,"f")&&clearTimeout(Je(this,Cs,"f")),Qe(this,Cs,setTimeout((()=>{this.disposed||Je(this,ls,"m",t).call(this)}),this.fetchInterval),"f")},Rs=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!Je(this,ls,"m",Is).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Je(this,ls,"m",Is).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,r=e.top,n=i+window.scrollX,s=r+window.scrollY,{width:o,height:a}=this.cameraView._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(Je(this,ls,"m",Is).call(this)){const t=this.cameraView._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=this.cameraView.getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)u{var e;if(!this.isUseMagnifier)return;if(Je(this,js,"f")||Qe(this,js,new Ys,"f"),!Je(this,js,"f").magnifierCanvas)return;document.body.contains(Je(this,js,"f").magnifierCanvas)||(Je(this,js,"f").magnifierCanvas.style.position="fixed",Je(this,js,"f").magnifierCanvas.style.boxSizing="content-box",Je(this,js,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(Je(this,js,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void Je(this,Vs,"f").call(this);const r=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!r)return;const n=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*n,o=[{image:i,width:i.width,height:i.height},{image:r,width:r.width,height:r.height}];Je(this,js,"f").update(s,t.pointer,n,o);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(Je(this,js,"f").magnifierCanvas.style.left="auto",Je(this,js,"f").magnifierCanvas.style.top="0",Je(this,js,"f").magnifierCanvas.style.right="0"):(Je(this,js,"f").magnifierCanvas.style.left="0",Je(this,js,"f").magnifierCanvas.style.top="0",Je(this,js,"f").magnifierCanvas.style.right="auto")}Je(this,js,"f").show()})),Vs.set(this,(()=>{Je(this,js,"f")&&Je(this,js,"f").hide()})),Gs.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Ki(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=document.createElement("dce-component"),e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let r=this._innerComponent.getElement("content");r||(r=document.createElement("canvas"),r.style.objectFit="contain",this._innerComponent.setElement("content",r)),r.width===e&&r.height===i||(r.width=e,r.height=i);const n=r.getContext("2d");n.clearRect(0,0,r.width,r.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),n.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&n.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(C(t)){Qe(this,Ns,t,"f");const{width:e,height:i,bytes:r,format:n}=Object.assign({},t);let s;if(n===a.IPF_GRAYSCALED){s=new Uint8ClampedArray(e*i*4);for(let t=0;t{if(!zs){if(!Xs&&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"./"}})(),qs=t=>{if(null==t&&(t="./"),Xs||zs);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};vt.engineResourcePaths.dbr={version:"10.4.31",path:Zs,isInternal:!0},mt.dbr={js:!1,wasm:!0,deps:["license","dip"]},gt.dbr={};const Ks="1.4.21";"string"!=typeof vt.engineResourcePaths.std&&D(vt.engineResourcePaths.std.version,Ks)<0&&(vt.engineResourcePaths.std={version:Ks,path:qs(Zs+`../../dynamsoft-capture-vision-std@${Ks}/dist/`),isInternal:!0});const Js="2.4.31";(!vt.engineResourcePaths.dip||"string"!=typeof vt.engineResourcePaths.dip&&D(vt.engineResourcePaths.dip.version,Js)<0)&&(vt.engineResourcePaths.dip={version:Js,path:qs(Zs+`../../dynamsoft-image-processing@${Js}/dist/`),isInternal:!0});let Qs=class{static getVersion(){const t=ft.dbr&&ft.dbr.wasm;return`10.4.31(Worker: ${ft.dbr&&ft.dbr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}};const $s={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)};var to,eo,io,ro;!function(t){t[t.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",t[t.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",t[t.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(to||(to={})),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"}(eo||(eo={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",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",t[t.LM_SKIP=0]="LM_SKIP"}(io||(io={})),function(t){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",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP"}(ro||(ro={}));const no=async t=>{let e;await new Promise(((i,r)=>{e=new Image,e.onload=()=>i(e),e.onerror=r,e.src=URL.createObjectURL(t)}));const i=document.createElement("canvas"),r=i.getContext("2d");return i.width=e.width,i.height=e.height,r.drawImage(e,0,0),{bytes:Uint8Array.from(r.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:10}};class so{async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const r=B(t);return M(r,e,i)}async drawOnImage(t,e,i,r=4294901760,n=1,s){let o;if(t instanceof Blob)o=await no(t);else if("string"==typeof t){let e=await O(t,"blob");o=await no(e)}return await new Promise(((t,a)=>{let h=at();ht[h]=async e=>{if(e.success)return s&&this.saveToFile(e.image,"test.png",s),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},st.postMessage({type:"utility_drawOnImage",id:h,body:{dsImage:o,drawingItem:e instanceof Array?e:[e],color:r,thickness:n,type:i}})}))}}const oo="undefined"==typeof self,ao="function"==typeof importScripts,ho=(()=>{if(!ao){if(!oo&&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"./"}})(),lo=t=>{if(null==t&&(t="./"),oo||ao);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};vt.engineResourcePaths.utility={version:"1.4.32",path:ho,isInternal:!0},mt.utility={js:!0,wasm:!0};const co="1.4.21";"string"!=typeof vt.engineResourcePaths.std&&D(vt.engineResourcePaths.std.version,co)<0&&(vt.engineResourcePaths.std={version:co,path:lo(ho+`../../dynamsoft-capture-vision-std@${co}/dist/`),isInternal:!0});const uo="2.4.31";(!vt.engineResourcePaths.dip||"string"!=typeof vt.engineResourcePaths.dip&&D(vt.engineResourcePaths.dip.version,uo)<0)&&(vt.engineResourcePaths.dip={version:uo,path:lo(ho+`../../dynamsoft-image-processing@${uo}/dist/`),isInternal:!0});class fo{static getVersion(){return`1.4.32(Worker: ${ft.utility&&ft.utility.worker||"Not Loaded"}, Wasm: ${ft.utility&&ft.utility.wasm||"Not Loaded"})`}}function go(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}var mo,po,_o,vo,yo;function wo(t,e){let i=!0;for(let o=0;o1)return Math.sqrt((h-o)**2+(l-a)**2);{const t=n+u*(o-n),e=s+u*(a-s);return Math.sqrt((h-t)**2+(l-e)**2)}}function To(t){const e=[];for(let i=0;i=0&&h<=1&&l>=0&&l<=1?{x:t.x+l*n,y:t.y+l*s}:null}function Io(t){let e=0;for(let i=0;i0}function Ao(t,e){for(let i=0;i<4;i++)if(!xo(t.points[i],t.points[(i+1)%4],e))return!1;return!0}"function"==typeof SuppressedError&&SuppressedError;function Oo(t,e,i,r){const n=t.points,s=e.points;let o=8*i;o=Math.max(o,5);const a=To(n)[3],h=To(n)[1],l=To(s)[3],c=To(s)[1];let u,d=0;if(u=Math.max(Math.abs(Eo(a,e.points[0])),Math.abs(Eo(a,e.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Eo(h,e.points[1])),Math.abs(Eo(h,e.points[2]))),u>d&&(d=u),u=Math.max(Math.abs(Eo(l,t.points[0])),Math.abs(Eo(l,t.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Eo(c,t.points[1])),Math.abs(Eo(c,t.points[2]))),u>d&&(d=u),d>o)return!1;const f=So(To(n)[0]),g=So(To(n)[2]),m=So(To(s)[0]),p=So(To(s)[2]),_=Co(f,p),v=Co(m,g),y=_>v,w=Math.min(_,v),C=Co(f,g),E=Co(m,p);let T=12*i;return T=Math.max(T,5),T=Math.min(T,C),T=Math.min(T,E),!!(w{e.x+=t,e.y+=i})),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,r=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-r.area)>.4*i.area)return!1;let n=new Array(4).fill(0),s=new Array(4).fill(0),o=0,a=0;for(let t=0;t<4;++t)n[t]=Math.round(100*(r.points[t].x-i.points[t].x))/100,o+=n[t],s[t]=Math.round(100*(r.points[t].y-i.points[t].y))/100,a+=s[t];o/=4,a/=4;for(let t=0;t<4;++t){if(Math.abs(n[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1;if(Math.abs(s[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1}return e.x=o,e.y=a,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(Ao(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(Ao(this.location,e))return!0}else{for(let e=0;e<4;e++)if(Ao(t,this.location.points[e]))return!0;if(Ao(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const r=[this.location.points[0],this.location.points[3]],n=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],s=0===t||3===t?r:n;if(Math.abs(Eo(s,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const r=t.location.points[i],n=this.location.points[i];if(!(Math.abs(n.x+e.x-r.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const r=Object.assign({},t.location);for(let t=0;t<4;t++)r.points[t].x-=e.x,r.points[t].y-=e.y;if(!this.isLocationOverlap(r,t.location.area))return!1;if(i){const t=.75;return function(t,e){const i=[];for(let r=0;r<4;r++)for(let n=0;n<4;n++){const s=bo(t[r],t[(r+1)%4],e[n],e[(n+1)%4]);s&&i.push(s)}return t.forEach((t=>{wo(e,t)&&i.push(t)})),e.forEach((e=>{wo(t,e)&&i.push(e)})),Io(function(t){if(t.length<=1)return t;t.sort(((t,e)=>t.x-e.x||t.y-e.y));const e=t.shift();return t.sort(((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x))),[e,...t]}(i))}([...this.location.points],r.points)>this.locationArea*t}return!0}}const Do={BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096)},Lo={barcode:2,text_line:4,detected_quad:8,normalized_image:16},Mo=t=>Object.values(Lo).includes(t)||Lo.hasOwnProperty(t),Fo=(t,e)=>"string"==typeof t?e[Lo[t]]:e[t],Po=(t,e,i)=>{"string"==typeof t?e[Lo[t]]=i:e[t]=i},ko=(t,e,i)=>{const r=[8,16].includes(i);if(!r&&t.isResultCrossVerificationEnabled(i))for(let t=0;t{Po(e,this.verificationEnabled,t)})),go(this,po,"f").forEach(((t,e)=>{Po(e,this.duplicateFilterEnabled,t)})),go(this,_o,"f").forEach(((t,e)=>{Po(e,this.duplicateForgetTime,t)})),go(this,vo,"f").forEach(((t,e)=>{Po(e,this.latestOverlappingEnabled,t)})),go(this,yo,"f").forEach(((t,e)=>{Po(e,this.maxOverlappingFrames,t)}))}enableResultCrossVerification(t,e){Mo(t)&&go(this,mo,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!Mo(t)&&Fo(t,this.verificationEnabled)}enableResultDeduplication(t,e){Mo(t)&&(e&&this.enableLatestOverlapping(t,!1),go(this,po,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!Mo(t)&&Fo(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){Mo(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),go(this,_o,"f").set(t,e))}getDuplicateForgetTime(t){return Mo(t)?Fo(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){Mo(t)&&go(this,yo,"f").set(t,e)}getMaxOverlappingFrames(t){return Mo(t)?Fo(t,this.maxOverlappingFrames):-1}enableLatestOverlapping(t,e){Mo(t)&&(e&&this.enableResultDeduplication(t,!1),go(this,vo,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!Mo(t)&&Fo(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[yt.CRIT_BARCODE,yt.CRIT_TEXT_LINE,yt.CRIT_DETECTED_QUAD,yt.CRIT_NORMALIZED_IMAGE];for(let i=0;i{if(1!==t.type){const e=(BigInt(t.format)&BigInt(Do.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Do.BF_GS1_DATABAR))!=BigInt(0);return new Ro(h,e?1:2,e,t)}})).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(l).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t)).length;n>p&&(p=n,m=r,g.x=i.x,g.y=i.y)}}if(0===p){for(let e=0;e-1!=t)).length}let i=this.overlapSet.length<=3?p>=1:p>=2;if(!i&&s&&u>0){let t=0;for(let e=0;e=1:t>=3}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach(((t,e)=>{if(1!==t.type){const i=Object.assign({},t),r=(BigInt(t.format)&BigInt(Do.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Do.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0)))}f.sort(((t,e)=>e-t)).forEach(((e,i)=>{t.items.splice(e,1)})),d.forEach((e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))}))}}onDecodedBarcodesReceived(t){this.latestOverlappingFilter(t),ko(this,t.items,yt.CRIT_BARCODE)}onRecognizedTextLinesReceived(t){ko(this,t.items,yt.CRIT_TEXT_LINE)}onDetectedQuadsReceived(t){ko(this,t.items,yt.CRIT_DETECTED_QUAD)}onNormalizedImagesReceived(t){ko(this,t.items,yt.CRIT_NORMALIZED_IMAGE)}}mo=new WeakMap,po=new WeakMap,_o=new WeakMap,vo=new WeakMap,yo=new WeakMap,de._defaultTemplate="ReadSingleBarcode";export{Qs as BarcodeReaderModule,Ps as CameraEnhancer,Ke as CameraEnhancerModule,Br as CameraView,de as CaptureVisionRouter,Zt as CaptureVisionRouterModule,pe as CapturedResultReceiver,vt as CoreModule,bi as DrawingItem,Dr as DrawingStyleManager,$s as EnumBarcodeFormat,s as EnumBufferOverflowProtectionMode,yt as EnumCapturedResultItemType,o as EnumColourChannelUsageType,wt as EnumCornerType,xt as EnumCrossVerificationStatus,ro as EnumDeblurMode,ai as EnumDrawingItemMediaType,hi as EnumDrawingItemState,li as EnumEnhancedFeatures,Ct as EnumErrorCode,to as EnumExtendedBarcodeResultType,Et as EnumGrayscaleEnhancementMode,Tt as EnumGrayscaleTransformationMode,a as EnumImagePixelFormat,Kt as EnumImageSourceState,St as EnumImageTagType,At as EnumIntermediateResultUnitType,io as EnumLocalizationMode,bt as EnumPDFReadingMode,ve as EnumPresetTemplate,eo as EnumQRCodeErrorCorrectionLevel,It as EnumRasterDataSource,Ot as EnumRegionObjectElementType,Rt as EnumSectionType,Ls as Feedback,ji as GroupDrawingItem,Li as ImageDrawingItem,Hs as ImageEditorView,so as ImageManager,J as ImageSourceAdapter,_e as IntermediateResultReceiver,je as LicenseManager,Ve as LicenseModule,Bi as LineDrawingItem,Bo as MultiFrameResultCrossFilter,Ni as QuadDrawingItem,Ii as RectDrawingItem,Fi as TextDrawingItem,fo as UtilityModule,B as _getNorImageData,M as _saveToFile,k as _toBlob,F as _toCanvas,P as _toImage,ut as bDebug,R as checkIsLink,D as compareVersion,nt as doOrWaitAsyncDependency,at as getNextTaskID,L as handleEngineResourcePaths,ft as innerVersions,_ as isArc,v as isContour,C as isDSImageData,E as isDSRect,T as isImageTag,S as isLineSegment,p as isObject,w as isOriginalDsImageData,b as isPoint,I as isPolygon,x as isQuad,A as isRect,_t as loadWasm,it as mapAsyncDependency,gt as mapPackageRegister,ht as mapTaskCallBack,lt as onLog,O as requestResource,dt as setBDebug,ct as setOnLog,rt as waitAsyncDependency,st as worker,mt as workerAutoResources}; +const t=t=>t&&"object"==typeof t&&"function"==typeof t.then,e=(async()=>{})().constructor;let i=class extends 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(i){let n;this._task=i,t(i)?n=i:"function"==typeof i&&(n=new e(i)),n&&(async()=>{try{const t=await n;i===this._task&&this.resolve(t)}catch(t){i===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}constructor(e){let i,n;super(((t,e)=>{i=t,n=e})),this._s="pending",this.resolve=e=>{this.isPending&&(t(e)?this.task=e:(this._s="fulfilled",i(e)))},this.reject=t=>{this.isPending&&(this._s="rejected",n(t))},this.task=e}};function n(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function r(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}var s,o,a;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(s||(s={})),function(t){t[t.CCUT_AUTO=0]="CCUT_AUTO",t[t.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",t[t.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",t[t.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",t[t.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",t[t.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(o||(o={})),function(t){t[t.IPF_BINARY=0]="IPF_BINARY",t[t.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",t[t.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",t[t.IPF_NV21=3]="IPF_NV21",t[t.IPF_RGB_565=4]="IPF_RGB_565",t[t.IPF_RGB_555=5]="IPF_RGB_555",t[t.IPF_RGB_888=6]="IPF_RGB_888",t[t.IPF_ARGB_8888=7]="IPF_ARGB_8888",t[t.IPF_RGB_161616=8]="IPF_RGB_161616",t[t.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",t[t.IPF_ABGR_8888=10]="IPF_ABGR_8888",t[t.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",t[t.IPF_BGR_888=12]="IPF_BGR_888",t[t.IPF_BINARY_8=13]="IPF_BINARY_8",t[t.IPF_NV12=14]="IPF_NV12",t[t.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(a||(a={}));const h="undefined"==typeof self,l="function"==typeof importScripts,c=(()=>{if(!l){if(!h&&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"./"}})(),u=t=>{if(null==t&&(t="./"),h||l);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},d=t=>Object.prototype.toString.call(t),f=t=>Array.isArray?Array.isArray(t):"[object Array]"===d(t),g=t=>"[object Boolean]"===d(t),m=t=>"number"==typeof t&&!Number.isNaN(t),p=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),_=t=>!(!p(t)||!m(t.x)||!m(t.y)||!m(t.radius)||t.radius<0||!m(t.startAngle)||!m(t.endAngle)),v=t=>!!p(t)&&!!f(t.points)&&0!=t.points.length&&!t.points.some((t=>!b(t))),y=t=>!(!p(t)||!m(t.width)||t.width<=0||!m(t.height)||t.height<=0||!m(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!S(t.tag)),w=t=>!(!y(t)||!m(t.bytes.length)&&!m(t.bytes.ptr)),C=t=>!!y(t)&&t.bytes instanceof Uint8Array,E=t=>!(!p(t)||!m(t.left)||t.left<0||!m(t.top)||t.top<0||!m(t.right)||t.right<0||!m(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom||!g(t.isMeasuredInPercentage)),S=t=>null===t||!!p(t)&&!!m(t.imageId)&&"type"in t,T=t=>!(!p(t)||!b(t.startPoint)||!b(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),b=t=>!!p(t)&&!!m(t.x)&&!!m(t.y),I=t=>!!p(t)&&!!f(t.points)&&0!=t.points.length&&!t.points.some((t=>!b(t))),x=t=>!!p(t)&&!!f(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some((t=>!b(t))),O=t=>!(!p(t)||!m(t.x)||!m(t.y)||!m(t.width)||t.width<0||!m(t.height)||t.height<0||"isMeasuredInPercentage"in t&&!g(t.isMeasuredInPercentage)),A=async(t,e)=>await new Promise(((i,n)=>{let r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType=e,r.send(),r.onloadend=async()=>{r.status<200||r.status>=300?n(new Error(t+" "+r.status)):i(r.response)},r.onerror=()=>{n(new Error("Network Error: "+r.statusText))}})),R=t=>/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t),D=(t,e)=>{let i=t.split("."),n=e.split(".");for(let t=0;t{const e={},i={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcpd:"dynamsoft-code-parser",dlrData:"dynamsoft-label-recognizer-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer"};for(let n in t){if("rootDirectory"===n)continue;let r=n,s=t[r],o=s&&"object"==typeof s&&s.path?s.path:s,a=t.rootDirectory;if(a&&!a.endsWith("/")&&(a+="/"),"object"==typeof s&&s.isInternal)a&&(o=t[r].version?`${a}${i[r]}@${t[r].version}/dist/${"ddv"===r?"engine":""}`:`${a}${i[r]}/dist/${"ddv"===r?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof o&&(o=o.replace(i,a||"")),"object"==typeof o&&"dwt"===r){const n=t[r].resourcesPath,s=t[r].serviceInstallerLocation;e[r]={resourcesPath:n.replace(i,a||""),serviceInstallerLocation:s.replace(i,a||"")};continue}}e[r]=u(o)}return e},M=async(t,e,i)=>await new Promise((async(n,r)=>{try{const r=e.split(".");let s=r[r.length-1];const o=await k(`image/${s}`,t);r.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return n(a)}catch(t){return r()}})),F=t=>{C(t)&&(t=B(t));const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d",{willReadFrequently:!0}).putImageData(t,0,0),e},P=(t,e)=>{C(e)&&(e=B(e));const i=F(e);let n=new Image,r=i.toDataURL(t);return n.src=r,n},k=async(t,e)=>{C(e)&&(e=B(e));const i=F(e);return new Promise(((e,n)=>{i.toBlob((t=>e(t)),t)}))},B=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===a.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n=r)break;e[o]=e[o+1]=e[o+2]=(128&n)/128*255,e[o+3]=255,n<<=1}}}else if(Number(t.format)===a.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n=r)break;e[o]=e[o+1]=e[o+2]=128&n?0:255,e[o+3]=255,n<<=1}}}return new ImageData(e,t.width,t.height)};var N,j,U,V,G,W,Y,H;let X,z,q,Z,K,J=class t{get _isFetchingStarted(){return n(this,G,"f")}constructor(){N.add(this),j.set(this,[]),U.set(this,1),V.set(this,s.BOPM_BLOCK),G.set(this,!1),W.set(this,void 0),Y.set(this,o.CCUT_AUTO)}setErrorListener(t){}addImageToBuffer(t){var e;if(!C(t))throw new TypeError("Invalid 'image'.");if((null===(e=t.tag)||void 0===e?void 0:e.hasOwnProperty("imageId"))&&"number"==typeof t.tag.imageId&&this.hasImage(t.tag.imageId))throw new Error("Existed imageId.");if(n(this,j,"f").length>=n(this,U,"f"))switch(n(this,V,"f")){case s.BOPM_BLOCK:break;case s.BOPM_UPDATE:if(n(this,j,"f").push(t),p(n(this,W,"f"))&&m(n(this,W,"f").imageId)&&1==n(this,W,"f").keepInBuffer)for(;n(this,j,"f").length>n(this,U,"f");){const t=n(this,j,"f").findIndex((t=>{var e;return(null===(e=t.tag)||void 0===e?void 0:e.imageId)!==n(this,W,"f").imageId}));n(this,j,"f").splice(t,1)}else n(this,j,"f").splice(0,n(this,j,"f").length-n(this,U,"f"))}else n(this,j,"f").push(t)}getImage(){if(0===n(this,j,"f").length)return null;let e;if(n(this,W,"f")&&m(n(this,W,"f").imageId)){const t=n(this,N,"m",H).call(this,n(this,W,"f").imageId);if(t<0)throw new Error(`Image with id ${n(this,W,"f").imageId} doesn't exist.`);e=n(this,j,"f").slice(t,t+1)[0]}else e=n(this,j,"f").pop();if([a.IPF_RGB_565,a.IPF_RGB_555,a.IPF_RGB_888,a.IPF_ARGB_8888,a.IPF_RGB_161616,a.IPF_ARGB_16161616,a.IPF_ABGR_8888,a.IPF_ABGR_16161616,a.IPF_BGR_888].includes(e.format)){if(n(this,Y,"f")===o.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t0!==t.length&&t.every((t=>m(t))))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&!g(e))throw new TypeError("Invalid 'keepInBuffer'.");r(this,W,{imageId:t,keepInBuffer:e},"f")}_resetNextReturnedImage(){r(this,W,null,"f")}hasImage(t){return n(this,N,"m",H).call(this,t)>=0}startFetching(){r(this,G,!0,"f")}stopFetching(){r(this,G,!1,"f")}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(r(this,U,t,"f");n(this,j,"f")&&n(this,j,"f").length>t;)n(this,j,"f").shift()}getMaxImageCount(){return n(this,U,"f")}getImageCount(){return n(this,j,"f").length}clearBuffer(){n(this,j,"f").length=0}isBufferEmpty(){return 0===n(this,j,"f").length}setBufferOverflowProtectionMode(t){r(this,V,t,"f")}getBufferOverflowProtectionMode(){return n(this,V,"f")}setColourChannelUsageType(t){r(this,Y,t,"f")}getColourChannelUsageType(){return n(this,Y,"f")}};j=new WeakMap,U=new WeakMap,V=new WeakMap,G=new WeakMap,W=new WeakMap,Y=new WeakMap,N=new WeakSet,H=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return n(this,j,"f").findIndex((e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t}))},"undefined"!=typeof navigator&&(X=navigator,z=X.userAgent,q=X.platform,Z=X.mediaDevices),function(){if(!h){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:X.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:q,search:"Win"},Mac:{str:q},Linux:{str:q}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||z,o=r.search||e,a=r.verStr||z,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||z,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=z.indexOf("Windows NT")&&(r="HarmonyOS"),K={browser:i,version:n,OS:r}}h&&(K={browser:"ssr",version:0,OS:"ssr"})}();const Q="undefined"!=typeof WebAssembly&&z&&!(/Safari/.test(z)&&!/Chrome/.test(z)&&/\(.+\s11_2_([2-6]).*\)/.test(z)),$=!("undefined"==typeof Worker),tt=!(!Z||!Z.getUserMedia),et=async()=>{let t=!1;if(tt)try{(await Z.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===K.browser&&K.version>66||"Safari"===K.browser&&K.version>13||"OPR"===K.browser&&K.version>43||"Edge"===K.browser&&K.version;const it={},nt=async t=>{let e="string"==typeof t?[t]:t,n=[];for(let t of e)n.push(it[t]=it[t]||new i);await Promise.all(n)},rt=async(t,e)=>{let n,r="string"==typeof t?[t]:t,s=[];for(let t of r){let r;s.push(r=it[t]=it[t]||new i(n=n||e())),r.isEmpty&&(r.task=n=n||e())}await Promise.all(s)};let st,ot=0;const at=()=>ot++,ht={};let lt;const ct=t=>{lt=t,st&&st.postMessage({type:"setBLog",body:{value:!!t}})};let ut=!1;const dt=t=>{ut=t,st&&st.postMessage({type:"setBDebug",body:{value:!!t}})},ft={},gt={},mt={dip:{wasm:!0}},pt={std:{version:"1.4.21",path:u(c+"../../dynamsoft-capture-vision-std@1.4.21/dist/"),isInternal:!0},core:{version:"3.4.31",path:c,isInternal:!0}},_t=async t=>{let e;t instanceof Array||(t=t?[t]:[]);let n=it.core;e=!n||n.isEmpty;let r=new Map;const s=t=>{if("std"==(t=t.toLowerCase())||"core"==t)return;if(!mt[t])throw Error("The '"+t+"' module cannot be found.");let e=mt[t].deps;if(null==e?void 0:e.length)for(let t of e)s(t);let i=it[t];r.has(t)||r.set(t,!i||i.isEmpty)};for(let e of t)s(e);let o=[];e&&o.push("core"),o.push(...r.keys());const a=[...r.entries()].filter((t=>!t[1])).map((t=>t[0]));await rt(o,(async()=>{const t=[...r.entries()].filter((t=>t[1])).map((t=>t[0]));await nt(a);const n=L(pt),s={};for(let e of t)s[e]=mt[e];const o={engineResourcePaths:n,autoResources:s,names:t};let h=new i;if(e){o.needLoadCore=!0;let t=n.core+vt._workerName;t.startsWith(location.origin)||(t=await fetch(t).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),st=new Worker(t),st.onerror=t=>{let e=new Error(t.message);h.reject(e)},st.addEventListener("message",(t=>{let e=t.data?t.data:t,i=e.type,n=e.id,r=e.body;switch(i){case"log":lt&<(e.message);break;case"task":try{ht[n](r),delete ht[n]}catch(t){throw delete ht[n],t}break;case"event":try{ht[n](r)}catch(t){throw t}break;default:console.log(t)}})),o.bLog=!!lt,o.bd=ut,o.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await nt("core");let l=ot++;ht[l]=t=>{if(t.success)Object.assign(ft,t.versions),"{}"!==JSON.stringify(t.versions)&&(vt._versions=t.versions),h.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),h.reject(e)}},st.postMessage({type:"loadWasm",body:o,id:l}),await h}))};class vt{static get engineResourcePaths(){return pt}static set engineResourcePaths(t){Object.assign(pt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return lt}static set _onLog(t){ct(t)}static get _bDebug(){return ut}static set _bDebug(t){dt(t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!it[t]&&it[t].isFulfilled}static async loadWasm(t){return await _t(t)}static async detectEnvironment(){return await(async()=>({wasm:Q,worker:$,getUserMedia:tt,camera:await et(),browser:K.browser,version:K.version,OS:K.OS}))()}static async getModuleVersion(){return await new Promise(((t,e)=>{let i=at();ht[i]=async i=>{if(i.success)return t(i.versions);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"getModuleVersion",id:i})}))}static getVersion(){return`3.4.31(Worker: ${ft.core&&ft.core.worker||"Not Loaded"}, Wasm: ${ft.core&&ft.core.wasm||"Not Loaded"})`}static enableLogging(){J._onLog=console.log,vt._onLog=console.log}static disableLogging(){J._onLog=null,vt._onLog=null}static async cfd(t){return await new Promise(((e,i)=>{let n=at();ht[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cfd",id:n,body:{count:t}})}))}}var yt,wt,Ct,Et,St,Tt,bt,It,xt;vt._bSupportDce4Module=-1,vt._bSupportIRTModule=-1,vt._versions=null,vt._workerName="core.worker.js",vt.browserInfo=K,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_NORMALIZED_IMAGE=16]="CRIT_NORMALIZED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT"}(yt||(yt={})),function(t){t[t.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",t[t.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",t[t.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",t[t.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(wt||(wt={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_RESERVED_INFO_NOT_MATCH=-10040]="EC_RESERVED_INFO_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_REQUEST_FAILED=-10044]="EC_REQUEST_FAILED",t[t.EC_LICENSE_INIT_FAILED=-10045]="EC_LICENSE_INIT_FAILED",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_LICENSE_CONTENT_INVALID=-10052]="EC_LICENSE_CONTENT_INVALID",t[t.EC_LICENSE_KEY_INVALID=-10053]="EC_LICENSE_KEY_INVALID",t[t.EC_LICENSE_DEVICE_RUNS_OUT=-10054]="EC_LICENSE_DEVICE_RUNS_OUT",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_HANDSHAKE_CODE_INVALID=-20001]="EC_HANDSHAKE_CODE_INVALID",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_LICENSE_INIT_SEQUENCE_FAILED=-20009]="EC_LICENSE_INIT_SEQUENCE_FAILED",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_FAILED_TO_REACH_DLS=-20200]="EC_FAILED_TO_REACH_DLS",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_QR_LICENSE_INVALID=-30016]="EC_QR_LICENSE_INVALID",t[t.EC_1D_LICENSE_INVALID=-30017]="EC_1D_LICENSE_INVALID",t[t.EC_PDF417_LICENSE_INVALID=-30019]="EC_PDF417_LICENSE_INVALID",t[t.EC_DATAMATRIX_LICENSE_INVALID=-30020]="EC_DATAMATRIX_LICENSE_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_AZTEC_LICENSE_INVALID=-30041]="EC_AZTEC_LICENSE_INVALID",t[t.EC_PATCHCODE_LICENSE_INVALID=-30046]="EC_PATCHCODE_LICENSE_INVALID",t[t.EC_POSTALCODE_LICENSE_INVALID=-30047]="EC_POSTALCODE_LICENSE_INVALID",t[t.EC_DPM_LICENSE_INVALID=-30048]="EC_DPM_LICENSE_INVALID",t[t.EC_FRAME_DECODING_THREAD_EXISTS=-30049]="EC_FRAME_DECODING_THREAD_EXISTS",t[t.EC_STOP_DECODING_THREAD_FAILED=-30050]="EC_STOP_DECODING_THREAD_FAILED",t[t.EC_MAXICODE_LICENSE_INVALID=-30057]="EC_MAXICODE_LICENSE_INVALID",t[t.EC_GS1_DATABAR_LICENSE_INVALID=-30058]="EC_GS1_DATABAR_LICENSE_INVALID",t[t.EC_GS1_COMPOSITE_LICENSE_INVALID=-30059]="EC_GS1_COMPOSITE_LICENSE_INVALID",t[t.EC_DOTCODE_LICENSE_INVALID=-30061]="EC_DOTCODE_LICENSE_INVALID",t[t.EC_PHARMACODE_LICENSE_INVALID=-30062]="EC_PHARMACODE_LICENSE_INVALID",t[t.EC_CHARACTER_MODEL_FILE_NOT_FOUND=-40100]="EC_CHARACTER_MODEL_FILE_NOT_FOUND",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_ZA_DL_LICENSE_INVALID=-90006]="EC_ZA_DL_LICENSE_INVALID",t[t.EC_AAMVA_DL_ID_LICENSE_INVALID=-90007]="EC_AAMVA_DL_ID_LICENSE_INVALID",t[t.EC_AADHAAR_LICENSE_INVALID=-90008]="EC_AADHAAR_LICENSE_INVALID",t[t.EC_MRTD_LICENSE_INVALID=-90009]="EC_MRTD_LICENSE_INVALID",t[t.EC_VIN_LICENSE_INVALID=-90010]="EC_VIN_LICENSE_INVALID",t[t.EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID=-90011]="EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID",t[t.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",t[t.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",t[t.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",t[t.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",t[t.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(Ct||(Ct={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV"}(Et||(Et={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV"}(St||(St={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(Tt||(Tt={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(bt||(bt={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(It||(It={})),function(t){t[t.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",t[t.CVS_PASSED=1]="CVS_PASSED",t[t.CVS_FAILED=2]="CVS_FAILED"}(xt||(xt={}));const Ot={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_DOWN_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_UP_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_NORMALIZED_IMAGES:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var At,Rt;!function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_NORMALIZED_IMAGE=6]="ROET_NORMALIZED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI"}(At||(At={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_NORMALIZATION=7]="ST_DOCUMENT_NORMALIZATION"}(Rt||(Rt={}));let Dt="./";if(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))}Dt=t.substring(0,t.lastIndexOf("/")+1)}function Lt(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Mt(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}vt.engineResourcePaths={rootDirectory:(t=>{null==t&&(t="./");let e=document.createElement("a");return e.href=t,(t=e.href).endsWith("/")||(t+="/"),t})(Dt+"../../")},"function"==typeof SuppressedError&&SuppressedError;const Ft="undefined"==typeof self,Pt="function"==typeof importScripts,kt=(()=>{if(!Pt){if(!Ft&&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"./"}})(),Bt=t=>{if(null==t&&(t="./"),Ft||Pt);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var Nt,jt,Ut;!function(t){t[t.SM_SINGLE=0]="SM_SINGLE",t[t.SM_MULTI_UNIQUE=1]="SM_MULTI_UNIQUE"}(Nt||(Nt={})),function(t){t[t.OM_NONE=0]="OM_NONE",t[t.OM_SPEED=1]="OM_SPEED",t[t.OM_COVERAGE=2]="OM_COVERAGE",t[t.OM_BALANCE=3]="OM_BALANCE",t[t.OM_DPM=4]="OM_DPM",t[t.OM_DENSE=5]="OM_DENSE"}(jt||(jt={})),function(t){t[t.RS_SUCCESS=0]="RS_SUCCESS",t[t.RS_CANCELLED=1]="RS_CANCELLED",t[t.RS_FAILED=2]="RS_FAILED"}(Ut||(Ut={}));var Vt={license:"",scanMode:Nt.SM_SINGLE,templateFilePath:void 0,utilizedTemplateNames:{single:"ReadSingleBarcode",multi_unique:"ReadBarcodes_SpeedFirst",image:"ReadBarcodes_ReadRateFirst"},engineResourcePaths:{rootDirectory:kt},barcodeFormats:void 0,duplicateForgetTime:3e3,container:void 0,onUniqueBarcodeScanned:void 0,showResultView:!1,showUploadImageButton:!1,removePoweredByMessage:!1,uiPath:kt,scannerViewConfig:{container:void 0,showCloseButton:!1},resultViewConfig:{container:void 0,toolbarButtonsConfig:{clear:{label:"Clear",className:"btn-clear",isHidden:!1},done:{label:"Done",className:"btn-done",isHidden:!1}}}};const Gt=t=>t&&"object"==typeof t&&"function"==typeof t.then,Wt=(async()=>{})().constructor;let Yt=class extends Wt{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,Gt(t)?e=t:"function"==typeof t&&(e=new Wt(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}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(Gt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};function Ht(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Xt(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const zt=t=>t&&"object"==typeof t&&"function"==typeof t.then,qt=(async()=>{})().constructor;class Zt extends qt{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,zt(t)?e=t:"function"==typeof t&&(e=new qt(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}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(zt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class Kt{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise(((t,e)=>{let i=at();ht[i]=async i=>{if(i.success)return t(i.count);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})}))}async setMaxBufferedItems(t){return await new Promise(((e,i)=>{let n=at();ht[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_setMaxBufferedItems",id:n,instanceID:this._cvr._instanceID,body:{count:t}})}))}async getBufferedCharacterItemSet(){return await new Promise(((t,e)=>{let i=at();ht[i]=async i=>{if(i.success)return t(i.itemSet);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})}))}}var Jt={onTaskResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onColourImageUnitReceived:!1,onScaledDownColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledUpBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesReceived:!1};const Qt=t=>{for(let e in t._irrRegistryState)t._irrRegistryState[e]=!1;for(let e of t._intermediateResultReceiverSet)if(e.isDce||e.isFilter)t._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let i in e)t._irrRegistryState[i]||(t._irrRegistryState[i]=!!e[i])};class $t{constructor(t){this._irrRegistryState=Jt,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),Qt(this);let e=-1,i={};if(!t.isDce&&!t.isFilter){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach(((t,e)=>{i[e]=t})),t._observedTaskMap.clear()}return await new Promise(((t,n)=>{let r=at();ht[r]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},st.postMessage({type:"cvr_setIrrRegistry",id:r,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})}))}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),Qt(this),await new Promise(((t,e)=>{let i=at();ht[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})}))}getOriginalImage(){return this._cvr._dsImage}}const te="undefined"==typeof self,ee="function"==typeof importScripts,ie=(()=>{if(!ee){if(!te&&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"./"}})(),ne=t=>{if(null==t&&(t="./"),te||ee);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var re;vt.engineResourcePaths.cvr={version:"2.4.33",path:ie,isInternal:!0},mt.cvr={js:!0,wasm:!0,deps:["license","dip"]},gt.cvr={};const se="1.4.21";"string"!=typeof vt.engineResourcePaths.std&&D(vt.engineResourcePaths.std.version,se)<0&&(vt.engineResourcePaths.std={version:se,path:ne(ie+`../../dynamsoft-capture-vision-std@${se}/dist/`),isInternal:!0});const oe="2.4.31";(!vt.engineResourcePaths.dip||"string"!=typeof vt.engineResourcePaths.dip&&D(vt.engineResourcePaths.dip.version,oe)<0)&&(vt.engineResourcePaths.dip={version:oe,path:ne(ie+`../../dynamsoft-image-processing@${oe}/dist/`),isInternal:!0});class ae{static getVersion(){return this._version}}ae._version=`2.4.33(Worker: ${null===(re=ft.cvr)||void 0===re?void 0:re.worker}, Wasm: loading...`;const he={barcodeResultItems:{type:yt.CRIT_BARCODE,reveiver:"onDecodedBarcodesReceived",isNeedFilter:!0},textLineResultItems:{type:yt.CRIT_TEXT_LINE,reveiver:"onRecognizedTextLinesReceived",isNeedFilter:!0},detectedQuadResultItems:{type:yt.CRIT_DETECTED_QUAD,reveiver:"onDetectedQuadsReceived",isNeedFilter:!1},normalizedImageResultItems:{type:yt.CRIT_NORMALIZED_IMAGE,reveiver:"onNormalizedImagesReceived",isNeedFilter:!1},parsedResultItems:{type:yt.CRIT_PARSED_RESULT,reveiver:"onParsedResultsReceived",isNeedFilter:!1}};var le,ce,ue,de,fe,ge,me,pe,_e,ve,ye,we,Ce;function Ee(t,e){if(t&&t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;Ee(t.referencedItem,e)}}function Se(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}!function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(le||(le={}));const Te={onTaskResultsReceived:()=>{},isFilter:!0};class be{constructor(){this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(vt.browserInfo.OS)?2048:4096,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,ce.set(this,null),ue.set(this,null),de.set(this,null),fe.set(this,null),ge.set(this,null),me.set(this,new Set),pe.set(this,new Set),_e.set(this,new Set),ve.set(this,0),ye.set(this,!1),we.set(this,!1),Ce.set(this,!1),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return Ht(this,Ce,"f")}static async createInstance(){if(!gt.license)throw Error("Module `license` is not existed.");await gt.license.dynamsoft(),await _t(["cvr"]);const t=new be,e=new Zt;let i=at();return ht[i]=async i=>{var n;if(i.success)t._instanceID=i.instanceID,t._currentSettings=JSON.parse(JSON.parse(i.outputSettings).data),ae._version=`2.4.33(Worker: ${null===(n=ft.cvr)||void 0===n?void 0:n.worker}, Wasm: ${i.version})`,Xt(t,we,!0,"f"),Xt(t,fe,t.getIntermediateResultManager(),"f"),Xt(t,we,!1,"f"),e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},st.postMessage({type:"cvr_createInstance",id:i}),e}async _singleFrameModeCallback(t){for(let e of Ht(this,me,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:t});const e={bytes:new Uint8Array(t.bytes),width:t.width,height:t.height,stride:t.stride,format:t.format,tag:t.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(e,this._templateName);i.originalImageTag=t.tag;const n={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of Ht(this,me,"f"))if(t.isDce)t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1});else{for(let e in he){const r=e,s=he[r];t[s.reveiver]&&i[r]&&t[s.reveiver](Object.assign(Object.assign({},n),{[r]:i[r]}))}t.onCapturedResultReceived&&t.onCapturedResultReceived(i)}}setInput(t){if(Se(this),t){if(Xt(this,ce,t,"f"),t.isCameraEnhancer){Ht(this,fe,"f")&&(Ht(this,ce,"f")._intermediateResultReceiver.isDce=!0,Ht(this,fe,"f").addResultReceiver(Ht(this,ce,"f")._intermediateResultReceiver));const t=Ht(this,ce,"f").getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,Ht(this,me,"f").add(e)}}}else Xt(this,ce,null,"f")}getInput(){return Ht(this,ce,"f")}addImageSourceStateListener(t){if(Se(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&Ht(this,pe,"f").add(t)}removeImageSourceStateListener(t){return Se(this),Ht(this,pe,"f").delete(t)}addResultReceiver(t){if(Se(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(Ht(this,me,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){Se(this),Ht(this,me,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onParsedResultsReceived:!1};for(let e of Ht(this,me,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onDetectedQuadsReceived=!!e.onDetectedQuadsReceived,t.onNormalizedImagesReceived=!!e.onNormalizedImagesReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new Zt;let i=at();return ht[i]=async t=>{if(t.success)e.resolve();else{let i=new Error(t.message);i.stack=t.stack+"\n"+i.stack,e.reject()}},st.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(Se(this),!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");Ht(this,_e,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){Se(this),Ht(this,_e,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(Ht(this,fe,"f").removeResultReceiver(Te),0===Ht(this,_e,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[yt.CRIT_BARCODE]:!1,[yt.CRIT_TEXT_LINE]:!1,[yt.CRIT_DETECTED_QUAD]:!1,[yt.CRIT_NORMALIZED_IMAGE]:!1},e={[yt.CRIT_BARCODE]:!1,[yt.CRIT_TEXT_LINE]:!1,[yt.CRIT_DETECTED_QUAD]:!1,[yt.CRIT_NORMALIZED_IMAGE]:!1};return await Ie(this,t),void await xe(this,e)}for(let t of Ht(this,_e,"f")){if(this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(yt.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(yt.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(yt.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(yt.CRIT_NORMALIZED_IMAGE),t.isLatestOverlappingEnabled(yt.CRIT_BARCODE)){[...Ht(this,fe,"f")._intermediateResultReceiverSet.values()].find((t=>t.isFilter))||Ht(this,fe,"f").addResultReceiver(Te)}await Ie(this,t.verificationEnabled),await xe(this,t.duplicateFilterEnabled),await Oe(this,t.duplicateForgetTime)}}async startCapturing(t){var e,i;if(Se(this),!this._isPauseScan)return;if(!Ht(this,ce,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");t||(t=be._defaultTemplate);const n=await this.containsTask(t);await _t(n);for(let t of Ht(this,_e,"f"))await this.addResultFilter(t);if(n.includes("dlr")&&!(null===(e=gt.dlr)||void 0===e?void 0:e.bLoadConfusableCharsData)){const t=L(vt.engineResourcePaths);await(null===(i=gt.dlr)||void 0===i?void 0:i.loadRecognitionData("ConfusableChars",t.dlr))}if(Ht(this,ce,"f").isCameraEnhancer&&(n.includes("ddn")?Ht(this,ce,"f").setPixelFormat(a.IPF_ABGR_8888):Ht(this,ce,"f").setPixelFormat(a.IPF_GRAYSCALED)),void 0!==Ht(this,ce,"f").singleFrameMode&&"disabled"!==Ht(this,ce,"f").singleFrameMode)return this._templateName=t,void Ht(this,ce,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind);return Ht(this,ce,"f").getColourChannelUsageType()===o.CCUT_AUTO&&Ht(this,ce,"f").setColourChannelUsageType(n.includes("ddn")?o.CCUT_FULL_CHANNEL:o.CCUT_Y_CHANNEL_ONLY),Ht(this,de,"f")&&Ht(this,de,"f").isPending?Ht(this,de,"f"):(Xt(this,de,new Zt(((e,i)=>{if(this.disposed)return;let n=at();ht[n]=async n=>{if(Ht(this,de,"f")&&!Ht(this,de,"f").isFulfilled){if(!n.success){let t=new Error(n.message);return t.stack=n.stack+"\n"+t.stack,i(t)}this._isPauseScan=!1,this._isOutputOriginalImage=n.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((async()=>{-1!==this._minImageCaptureInterval&&Ht(this,ce,"f").startFetching(),this._loopReadVideo(t),e()}),0)}},st.postMessage({type:"cvr_startCapturing",id:n,instanceID:this._instanceID,body:{templateName:t}})})),"f"),await Ht(this,de,"f"))}stopCapturing(){Se(this),Ht(this,ce,"f")&&(Ht(this,ce,"f").isCameraEnhancer&&void 0!==Ht(this,ce,"f").singleFrameMode&&"disabled"!==Ht(this,ce,"f").singleFrameMode?Ht(this,ce,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(!async function(t){let e=at();const i=new Zt;ht[e]=async t=>{if(t.success)return i.resolve();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i.reject(e)}},st.postMessage({type:"cvr_clearVerifyList",id:e,instanceID:t._instanceID})}(this),Ht(this,ce,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,Xt(this,de,null,"f"),Ht(this,ce,"f").setColourChannelUsageType(o.CCUT_AUTO)))}async containsTask(t){return Se(this),await new Promise(((e,i)=>{let n=at();ht[n]=async t=>{if(t.success)return e(JSON.parse(t.tasks));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_containsTask",id:n,instanceID:this._instanceID,body:{templateName:t}})}))}async _loopReadVideo(t){if(this.disposed||this._isPauseScan)return;if(Xt(this,ye,!0,"f"),Ht(this,ce,"f").isBufferEmpty())if(Ht(this,ce,"f").hasNextImageToFetch())for(let t of Ht(this,pe,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(le.ISS_BUFFER_EMPTY);else if(!Ht(this,ce,"f").hasNextImageToFetch())for(let t of Ht(this,pe,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(le.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||Ht(this,ce,"f").isBufferEmpty())try{Ht(this,ce,"f").isBufferEmpty()&&be._onLog&&be._onLog("buffer is empty so fetch image"),be._onLog&&be._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=Ht(this,ce,"f").fetchImage(),be._onLog&&be._onLog(`DCE: finish fetching a frame: ${Date.now()}`),Ht(this,ce,"f").setImageFetchInterval(this._averageTime)}catch(e){return void this._reRunCurrnetFunc(t)}else if(Ht(this,ce,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=Ht(this,ce,"f").getImage(),this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(t);if(!this._dsImage)return void this._reRunCurrnetFunc(t);for(let t of Ht(this,me,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const e=Date.now();this._captureDsimage(this._dsImage,t).then((async i=>{if(be._onLog&&be._onLog("no js handle time: "+(Date.now()-e)),this._isPauseScan)return void this._reRunCurrnetFunc(t);i.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;const n={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of Ht(this,me,"f"))if(t.isDce){const e=Date.now();if(t.onCapturedResultReceived(i,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify}),be._onLog){const t=Date.now()-e;t>10&&be._onLog(`draw result time: ${t}`)}}else{for(let e in he){const r=e,s=he[r];t[s.reveiver],t[s.reveiver]&&i[r]&&t[s.reveiver](Object.assign(Object.assign({},n),{[r]:i[r].filter((t=>!s.isNeedFilter||!t.isFilter))})),i[r]&&(i[r]=i[r].filter((t=>!s.isNeedFilter||!t.isFilter)))}t.onCapturedResultReceived&&(i.items=i.items.filter((t=>[yt.CRIT_DETECTED_QUAD,yt.CRIT_NORMALIZED_IMAGE].includes(t.type)||!t.isFilter)),t.onCapturedResultReceived(i))}const r=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-e),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,be._onLog&&(be._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),be._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),be._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),be._onLog(`averageTime: ${this._averageTime}`))),be._onLog){const t=Date.now()-r;t>10&&be._onLog(`fetch image calculate time: ${t}`)}be._onLog&&be._onLog(`time finish decode: ${Date.now()}`),be._onLog&&be._onLog("main time: "+(Date.now()-e)),be._onLog&&be._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,0))})).catch((e=>{Ht(this,ce,"f").stopFetching(),e.errorCode&&0===e.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{Ht(this,ce,"f").startFetching(),this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,1e3))),"platform error"!==e.message&&setTimeout((()=>{throw e}),0)}))}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),0)}async capture(t,e){var i,n;Se(this),e||(e=be._defaultTemplate);const r=await this.containsTask(e);if(await _t(r),r.includes("dlr")&&!(null===(i=gt.dlr)||void 0===i?void 0:i.bLoadConfusableCharsData)){const t=L(vt.engineResourcePaths);await(null===(n=gt.dlr)||void 0===n?void 0:n.loadRecognitionData("ConfusableChars",t.dlr))}let s;if(Xt(this,ye,!1,"f"),C(t))s=await this._captureDsimage(t,e);else if("string"==typeof t)s="data:image/"==t.substring(0,11)?await this._captureBase64(t,e):await this._captureUrl(t,e);else if(t instanceof Blob)s=await this._captureBlob(t,e);else if(t instanceof HTMLImageElement)s=await this._captureImage(t,e);else if(t instanceof HTMLCanvasElement)s=await this._captureCanvas(t,e);else{if(!(t instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");s=await this._captureVideo(t,e)}return s}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await A(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),n=i.length,r=new Uint8Array(n);for(;n--;)r[n]=i.charCodeAt(n);return await this._captureBlob(new Blob([r]),e)}async _captureBlob(t,e){let i=null,n=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(n=await async function(t){return await new Promise(((e,i)=>{let n=URL.createObjectURL(t),r=new Image;r.src=n,r.onload=()=>{URL.revokeObjectURL(r.dbrObjUrl),e(r)},r.onerror=t=>{i(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))}(t));let r=await this._captureImage(i||n,e);return i&&i.close(),r}async _captureImage(t,e){let i,n,r=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(r,s);o>this.maxImageSideLength?(Xt(this,ve,this.maxImageSideLength/o,"f"),i=Math.round(r*Ht(this,ve,"f")),n=Math.round(s*Ht(this,ve,"f"))):(i=r,n=s),Ht(this,ue,"f")||Xt(this,ue,document.createElement("canvas"),"f");const a=Ht(this,ue,"f");a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),n={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(n,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,n,r=t.videoWidth,s=t.videoHeight,o=Math.max(r,s);o>this.maxImageSideLength?(Xt(this,ve,this.maxImageSideLength/o,"f"),i=Math.round(r*Ht(this,ve,"f")),n=Math.round(s*Ht(this,ve,"f"))):(i=r,n=s),Ht(this,ue,"f")||Xt(this,ue,document.createElement("canvas"),"f");const a=Ht(this,ue,"f");a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),await this._captureCanvas(a,e)}async _captureInWorker(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=t;let a=at();const h=new Zt;return ht[a]=async e=>{var i,n;if(!e.success){let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h.reject(t)}{const r=Date.now();be._onLog&&(be._onLog(`get result time from worker: ${r}`),be._onLog("worker to main time consume: "+(r-e.workerReturnMsgTime)));try{const r=e.captureResult;if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,h.reject(t)}t.bytes=e.bytes;for(let e of r.items)0!==Ht(this,ve,"f")&&Ee(e,Ht(this,ve,"f")),e.type===yt.CRIT_ORIGINAL_IMAGE?e.imageData=t:e.type===yt.CRIT_NORMALIZED_IMAGE?null===(i=gt.ddn)||void 0===i||i.handleNormalizedImageResultItem(e):e.type===yt.CRIT_PARSED_RESULT&&(null===(n=gt.dcp)||void 0===n||n.handleParsedResultItem(e));if(Ht(this,ye,"f"))for(let t of Ht(this,_e,"f"))t.onDecodedBarcodesReceived(r),t.onRecognizedTextLinesReceived(r),t.onDetectedQuadsReceived(r),t.onNormalizedImagesReceived(r);for(let t in he){const e=t,i=r.items.filter((t=>t.type===he[e].type));i.length&&(r[t]=i)}if(!this._isPauseScan||!Ht(this,ye,"f")){const e=r.intermediateResult;if(e){let i=0;for(let n of Ht(this,fe,"f")._intermediateResultReceiverSet){i++;for(let r of e){if("onTaskResultsReceived"===r.info.callbackName){for(let e of r.intermediateResultUnits)e.originalImageTag=t.tag?t.tag:null;n[r.info.callbackName]&&n[r.info.callbackName]({intermediateResultUnits:r.intermediateResultUnits},r.info)}else n[r.info.callbackName]&&n[r.info.callbackName](r.result,r.info);i===Ht(this,fe,"f")._intermediateResultReceiverSet.size&&delete r.info.callbackName}}}}return r&&r.hasOwnProperty("intermediateResult")&&delete r.intermediateResult,Xt(this,ve,0,"f"),h.resolve(r)}catch(t){return h.reject(t)}}},be._onLog&&be._onLog(`send buffer to worker: ${Date.now()}`),st.postMessage({type:"cvr_capture",id:a,instanceID:this._instanceID,body:{bytes:i,width:n,height:r,stride:s,format:o,templateName:e||"",isScanner:Ht(this,ye,"f")}},[i.buffer]),h}async initSettings(t){return Se(this),t&&["string","object"].includes(typeof t)?("string"==typeof t?t.trimStart().startsWith("{")||(t=await A(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise(((e,i)=>{let n=at();ht[n]=async n=>{if(n.success){const r=JSON.parse(n.response);if(0!==r.errorCode){let t=new Error(r.errorString?r.errorString:"Init Settings Failed.");return t.errorCode=r.errorCode,i(t)}const s=JSON.parse(t);this._currentSettings=s;let o=[],a=s.CaptureVisionTemplates;for(let t=0;t{let n=at();ht[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,i(t)}return e(JSON.parse(n.data))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_outputSettings",id:n,instanceID:this._instanceID,body:{templateName:t||"*"}})}))}async outputSettingsToFile(t,e,i){const n=await this.outputSettings(t),r=new Blob([JSON.stringify(n,null,2,(function(t,e){return e instanceof Array?JSON.stringify(e):e}),2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(r),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout((()=>{URL.revokeObjectURL(t.href)}),500)},t.click()}return r}async getTemplateNames(){return Se(this),await new Promise(((t,e)=>{let i=at();ht[i]=async i=>{if(i.success){const n=JSON.parse(i.response);if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,e(t)}return t(JSON.parse(n.data))}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})}))}async getSimplifiedSettings(t){Se(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const e=await this.containsTask(t);return await _t(e),await new Promise(((e,i)=>{let n=at();ht[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,i(t)}const r=JSON.parse(n.data,((t,e)=>"barcodeFormatIds"===t?BigInt(e):e));return r.minImageCaptureInterval=this._minImageCaptureInterval,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_getSimplifiedSettings",id:n,instanceID:this._instanceID,body:{templateName:t}})}))}async updateSettings(t,e){Se(this);const i=await this.containsTask(t);return await _t(i),await new Promise(((i,n)=>{let r=at();ht[r]=async t=>{if(t.success){const r=JSON.parse(t.response);if(e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==r.errorCode){let t=new Error(r.errorString?r.errorString:"Update Settings Failed.");return t.errorCode=r.errorCode,n(t)}return this._currentSettings=await this.outputSettings("*"),i(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},st.postMessage({type:"cvr_updateSettings",id:r,instanceID:this._instanceID,body:{settings:e,templateName:t}})}))}async resetSettings(){return Se(this),await new Promise(((t,e)=>{let i=at();ht[i]=async i=>{if(i.success){const n=JSON.parse(i.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Reset Settings Failed.");return t.errorCode=n.errorCode,e(t)}return this._currentSettings=await this.outputSettings("*"),t(n)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})}))}getBufferedItemsManager(){return Ht(this,ge,"f")||Xt(this,ge,new Kt(this),"f"),Ht(this,ge,"f")}getIntermediateResultManager(){if(Se(this),!Ht(this,we,"f")&&0!==vt.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return Ht(this,fe,"f")||Xt(this,fe,new $t(this),"f"),Ht(this,fe,"f")}async parseRequiredResources(t){return Se(this),await new Promise(((e,i)=>{let n=at();ht[n]=async t=>{if(t.success)return e(JSON.parse(t.resources));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_parseRequiredResources",id:n,instanceID:this._instanceID,body:{templateName:t}})}))}async dispose(){Se(this),Ht(this,de,"f")&&this.stopCapturing(),Xt(this,ce,null,"f"),Ht(this,me,"f").clear(),Ht(this,pe,"f").clear(),Ht(this,_e,"f").clear(),Ht(this,fe,"f")._intermediateResultReceiverSet.clear(),Xt(this,Ce,!0,"f");let t=at();ht[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},st.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:Ht(this,ce,"f"),promiseStartScan:Ht(this,de,"f"),intermediateResultManager:Ht(this,fe,"f"),bufferdItemsManager:Ht(this,ge,"f"),resultReceiverSet:Ht(this,me,"f"),isaStateListenerSet:Ht(this,pe,"f"),resultFilterSet:Ht(this,_e,"f"),compressRate:Ht(this,ve,"f"),canvas:Ht(this,ue,"f"),isScanner:Ht(this,ye,"f"),innerUseTag:Ht(this,we,"f"),isDestroyed:Ht(this,Ce,"f")}}async _getWasmFilterState(){return await new Promise(((t,e)=>{let i=at();ht[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})}))}}async function Ie(t,e){return Se(t),await new Promise(((i,n)=>{let r=at();ht[r]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},st.postMessage({type:"cvr_enableResultCrossVerification",id:r,instanceID:t._instanceID,body:{verificationEnabled:e}})}))}async function xe(t,e){return Se(t),await new Promise(((i,n)=>{let r=at();ht[r]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},st.postMessage({type:"cvr_enableResultDeduplication",id:r,instanceID:t._instanceID,body:{duplicateFilterEnabled:e}})}))}async function Oe(t,e){return Se(t),await new Promise(((i,n)=>{let r=at();ht[r]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},st.postMessage({type:"cvr_setDuplicateForgetTime",id:r,instanceID:t._instanceID,body:{duplicateForgetTime:e}})}))}ce=new WeakMap,ue=new WeakMap,de=new WeakMap,fe=new WeakMap,ge=new WeakMap,me=new WeakMap,pe=new WeakMap,_e=new WeakMap,ve=new WeakMap,ye=new WeakMap,we=new WeakMap,Ce=new WeakMap,be._defaultTemplate="Default";class Ae{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}}class Re{constructor(){this._observedResultUnitTypes=Ot.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledDownColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}}var De;!function(t){t.PT_DEFAULT="Default",t.PT_READ_BARCODES="ReadBarcodes_Default",t.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",t.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",t.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",t.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",t.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",t.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",t.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",t.PT_READ_SINGLE_BARCODE="ReadBarcodes_Balanced",t.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",t.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",t.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",t.PT_RECOGNIZE_LETTERS="RecognizeLetters",t.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",t.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",t.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters"}(De||(De={}));const Le="undefined"==typeof self,Me="function"==typeof importScripts,Fe=(()=>{if(!Me){if(!Le&&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"./"}})();vt.engineResourcePaths.dce={version:"4.1.1",path:Fe,isInternal:!0},mt.dce={wasm:!1,js:!1},gt.dce={};let Pe,ke,Be,Ne,je,Ue=class{static getVersion(){return"4.1.1"}};function Ve(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Ge(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(Pe=navigator,ke=Pe.userAgent,Be=Pe.platform,Ne=Pe.mediaDevices),function(){if(!Le){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Pe.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Be,search:"Win"},Mac:{str:Be},Linux:{str:Be}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||ke,o=r.search||e,a=r.verStr||ke,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||ke,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=ke.indexOf("Windows NT")&&(r="HarmonyOS"),je={browser:i,version:n,OS:r}}Le&&(je={browser:"ssr",version:0,OS:"ssr"})}();const We="undefined"!=typeof WebAssembly&&ke&&!(/Safari/.test(ke)&&!/Chrome/.test(ke)&&/\(.+\s11_2_([2-6]).*\)/.test(ke)),Ye=!("undefined"==typeof Worker),He=!(!Ne||!Ne.getUserMedia),Xe=async()=>{let t=!1;if(He)try{(await Ne.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===je.browser&&je.version>66||"Safari"===je.browser&&je.version>13||"OPR"===je.browser&&je.version>43||"Edge"===je.browser&&je.version;var ze={653:(t,e,i)=>{var n,r,s,o,a,h,l,c,u,d,f,g,m,p,_,v,y,w,C,E,S,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 b=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=b.document,T.jsdomImplForWrapper=i(898).implForWrapper,T.nodeCanvas=i(245).Canvas,T.window=b,DOMParser=T.window.DOMParser}function I(t,e){var i=t.canvas,n=e.targetCanvas,r=n.getContext("2d");r.translate(0,n.height),r.scale(1,-1);var s=i.height-n.height;r.drawImage(i,0,s,n.width,n.height,0,0,n.width,n.height)}function x(t,e){var i=e.targetCanvas.getContext("2d"),n=e.destinationWidth,r=e.destinationHeight,s=n*r*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,n,r);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 n=0,r=i.length;n-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]}},n=e,r=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 n=new T.Point(t.x-e.x,t.y-e.y),r=T.util.rotateVector(n,i);return new T.Point(r.x,r.y).addEquals(e)},rotateVector:function(t,e){var i=T.util.sin(e),n=T.util.cos(e);return{x:t.x*n-t.y*i,y:t.x*i+t.y*n}},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 n=T.util.createVector(t,e),r=T.util.createVector(t,i),s=T.util.calcAngleBetweenVectors(n,r),o=s*(0===T.util.calcAngleBetweenVectors(T.util.rotateVector(n,s),r)?1:-1)/2;return{vector:T.util.getHatVector(T.util.rotateVector(n,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var n=[],r=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=r/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),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-r/Math.sin(p/2),f=new T.Point(m.x*d*s.x,m.y*d*s.y),Math.hypot(f.x,f.y)/r<=e.strokeMiterLimit))return n.push(u.add(f)),void n.push(u.subtract(f));d=-r*Math.SQRT2,f=new T.Point(m.x*d*s.x,m.y*d*s.y),n.push(u.add(f)),n.push(u.subtract(f))})),n},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>n?e-=n:e=0,i>n?i-=n:i=0);var r,s=!0,o=t.getImageData(e,i,2*n||1,2*n||1),a=o.data.length;for(r=3;r=r?s-r:2*Math.PI-(r-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,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,C=_*v-_*y-v*w,E=0;if(C<0){var S=Math.sqrt(1-C/(_*v));i*=S,s*=S}else E=(o===a?-1:1)*Math.sqrt(C/(_*y+v*w));var b=E*i*p/s,I=-E*s*m/i,x=d*b-u*I+.5*t,O=u*b+d*I+.5*e,A=r(1,0,(m-b)/i,(p-I)/s),R=r((m-b)/i,(p-I)/s,(-m-b)/i,(-p-I)/s);0===a&&R>0?R-=2*l:1===a&&R<0&&(R+=2*l);for(var D=Math.ceil(Math.abs(R/l*2)),L=[],M=R/D,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=A+M,k=0;kE)for(var b=1,I=m.length;b2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:r.x===t[i-2].x?0:-1,h=r.y>t[i-2].y?1:r.y===t[i-2].y?0:-1),n.push(["L",r.x+a*e,r.y+h*e]),n},T.util.getPathSegmentsInfo=d,T.util.getBoundsOfCurve=function(e,i,n,r,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,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,C=Math.abs,E=[],S=[[],[]];u=6*e-12*n+6*s,c=-3*e+9*n-9*s+3*a,d=3*n-3*e;for(var b=0;b<2;++b)if(b>0&&(u=6*i-12*r+6*o,c=-3*i+9*r-9*o+3*h,d=3*r-3*i),C(c)<1e-12){if(C(u)<1e-12)continue;0<(f=-d/u)&&f<1&&E.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&E.push(g),0<(m=(-u-_)/(2*c))&&m<1&&E.push(m));for(var I,x,O,A=E.length,R=A;A--;)I=(O=1-(f=E[A]))*O*O*e+3*O*O*f*n+3*O*f*f*s+f*f*f*a,S[0][A]=I,x=O*O*O*i+3*O*O*f*r+3*O*f*f*o+f*f*f*h,S[1][A]=x;S[0][R]=e,S[1][R]=i,S[0][R+1]=a,S[1][R+1]=h;var D=[{x:y.apply(null,S[0]),y:y.apply(null,S[1])},{x:w.apply(null,S[0]),y:w.apply(null,S[1])}];return T.cachesBoundsOfCurve&&(T.boundsOfCurveCache[l]=D),D},T.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var n=0;e-i[n].length>0&&n1e-4;)i=h(s),r=s,(n=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=n);return i.angle=u(r),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),n={},r=1;r=e}))}}}(),function(){function t(e,i,n){if(n)if(!T.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var r=0,s=i.length;r57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var n=t.charCodeAt(e+1);if(56320>n||n>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 r=t.charCodeAt(e-1);if(55296>r||r>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,n=0,r=[];for(n=0;n-1?t.prototype[r]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=n;var r=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return r}}(r):t.prototype[r]=e[r],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function r(){}function s(e){for(var i=null,n=this;n.constructor.superclass;){var r=n.constructor.superclass.prototype[e];if(n[e]!==r){i=r;break}n=n.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&&(r.prototype=i.prototype,a.prototype=new r,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*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=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?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var n in e)"opacity"===n?m(t,e[n]):i["float"===n||"cssFloat"===n?void 0===i.styleFloat?"cssFloat":"styleFloat":n]=e[n];return t},function(){var t,e,i,n,r=Array.prototype.slice,s=function(t){return r.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 n in e)"class"===n?i.className=e[n]:"for"===n?i.htmlFor=e[n]:i.setAttribute(n,e[n]);return i}function a(t){for(var e=0,i=0,n=T.document.documentElement,r=T.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===T.document?(e=r.scrollLeft||n.scrollLeft||0,i=r.scrollTop||n.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,n="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),n?t.style[n]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},T.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),n?t.style[n]="":"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,n,r=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!r)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=r.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),n=a(t),{left:s.left+n.left-(i.clientLeft||0)+o.left,top:s.top+n.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 n=i.method?i.method.toUpperCase():"GET",r=i.onComplete||function(){},s=new T.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(r(s),s.onreadystatechange=t)},"GET"===n&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(n,e,!0),"POST"!==n&&"PUT"!==n||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 n(){return!1}function r(t,e,i,n){return-i*Math.cos(t/n*(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||n,f=i.abort||n,g=i.onComplete||n,m=i.easing||r,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map((function(t,e){return v[e]-_[e]})):v-_);i.onStart&&i.onStart(),function t(i){var n=(e=i||+new Date)>u?c:e-l,r=n/c,w=p?_.map((function(t,e){return m(n,_[e],y[e],c)})):m(n,_,y,c),C=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=C,s.durationRate=r,!o){if(!f(w,C,r))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(w,C,r),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 n="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(n+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}T.util.animateColor=function(e,i,n,r){var s=new T.Color(e).getSource(),o=new T.Color(i).getSource(),a=r.onComplete,h=r.onChange;return r=r||{},T.util.animate(T.util.object.extend(r,{duration:n||500,startValue:s,endValue:o,byValue:o,easing:function(e,i,n,s){return t(i,n,r.colorEasing?r.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,n){if(a)return a(t(o,o,0),i,n)},onChange:function(e,i,n){if(h){if(Array.isArray(e))return h(t(e,e,0),i,n);h(e,i,n)}}}))}}(),function(){function t(t,e,i,n){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,r)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,n,r,s,o=[];for(r=0,s=e.length;r1;)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,n,r,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,C={},E="",S=0,T=0;if(C.width=0,C.height=0,C.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+E,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return C;if(_)return C.width=s(d),C.height=s(f),C;if(i=-parseFloat(l[1]),n=-parseFloat(l[2]),r=parseFloat(l[3]),o=parseFloat(l[4]),C.minX=i,C.minY=n,C.viewBoxWidth=r,C.viewBoxHeight=o,y?(C.width=r,C.height=o):(C.width=s(d),C.height=s(f),c=C.width/r,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),S=C.width-r*c,T=C.height-o*c,"Mid"===p.alignX&&(S/=2),"Mid"===p.alignY&&(T/=2),"Min"===p.alignX&&(S=0),"Min"===p.alignY&&(T=0)),1===c&&1===u&&0===i&&0===n&&0===g&&0===m)return C;if((g||m)&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") "),a=E+" matrix("+c+" 0 0 "+u+" "+(i*c+S)+" "+(n*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 w(t,e){var i="xlink:href",n=_(t,e.getAttribute(i).slice(1));if(n&&n.getAttribute(i)&&w(t,n),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(t){n&&!e.hasAttribute(t)&&n.hasAttribute(t)&&e.setAttribute(t,n.getAttribute(t))})),!e.children.length)for(var r=n.cloneNode(!0);r.firstChild;)e.appendChild(r.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,r,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),n=0;i.length&&nt.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,n,r,s){var o,a=(s.x-r.x)*(t.y-r.y)-(s.y-r.y)*(t.x-r.x),h=(n.x-t.x)*(t.y-r.y)-(n.y-t.y)*(t.x-r.x),l=(s.y-r.y)*(n.x-t.x)-(s.x-r.x)*(n.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*(n.x-t.x),t.y+c*(n.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,n){var r,s,o,a,h=new i,l=n.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var n,r=new i,s=t.length;for(n=0;n0&&(r.status="Intersection"),r},e.Intersection.intersectPolygonRectangle=function(t,n,r){var s=n.min(r),o=n.max(r),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 n(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,n){t/=255,i/=255,n/=255;var r,s,o,a=e.util.array.max([t,i,n]),h=e.util.array.min([t,i,n]);if(o=(a+h)/2,a===h)r=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:r=(i-n)/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 n=i.transform.target,r=n.canvas,s=e.util.object.clone(i);s.target=n,r&&r.fire("object:"+t,s),n.fire(t,i)}function m(t,e){var i=e.canvas,n=t[i.uniScaleKey];return i.uniformScaling&&!n||!i.uniformScaling&&n}function p(t){return t.originX===l&&t.originY===l}function _(t,e,i){var n=t.lockScalingX,r=t.lockScalingY;return!((!n||!r)&&(e||!n&&!r||!i)&&(!n||"x"!==e)&&(!r||"y"!==e))}function v(t,e,i,n){return{e:t,transform:e,pointer:{x:i,y:n}}}function y(t){return function(e,i,n,r){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,n,r);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function w(t,e){return function(i,n,r,s){var o=e(i,n,r,s);return o&&g(t,v(i,n,r,s)),o}}function C(t,i,n,r,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(r,s),i,n);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 E(t){return t.flipX!==t.flipY}function S(t,e,i,n,r){if(0!==t[e]){var s=r/t._getTransformedDimensions()[n]*t[i];t.set(i,s)}}function T(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=C(e,e.originX,e.originY,i,n),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?r=0:(r=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),E(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",r),S(l,"skewY","scaleY","y",p)}return m}function b(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=C(e,e.originX,e.originY,i,n),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?r=0:(r=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),E(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",r),S(l,"skewX","scaleX","x",p)}return m}function I(t,e,i,n,r){r=r||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=r.by,w=m(t,f),E=_(f,y,w),S=e.gestureScale;if(E)return!1;if(S)o=e.scaleX*S,a=e.scaleY*S;else{if(s=C(e,e.originX,e.originY,i,n),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(),w&&!y){var T=Math.abs(s.x)+Math.abs(s.y),b=e.original,I=T/(Math.abs(h.x*b.scaleX/f.scaleX)+Math.abs(h.y*b.scaleY/f.scaleY));o=b.scaleX*I,a=b.scaleY*I}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 x=f.scaleX,O=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)),x!==f.scaleX||O!==f.scaleY}r.scaleCursorStyleHandler=function(t,e,n){var r=m(t,n),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(n,s,r))return"not-allowed";var o=f(n,e);return i[o]+"-resize"},r.skewCursorStyleHandler=function(t,e,i){var r="not-allowed";if(0!==e.x&&i.lockSkewingY)return r;if(0!==e.y&&i.lockSkewingX)return r;var s=f(i,e)%4;return n[s]+"-resize"},r.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?r.skewCursorStyleHandler(t,e,i):r.scaleCursorStyleHandler(t,e,i)},r.rotationWithSnapping=w("rotating",y((function(t,e,i,n){var r=e,s=r.target,o=s.translateToOriginPoint(s.getCenterPoint(),r.originX,r.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(r.ey-o.y,r.ex-o.x),l=Math.atan2(n-o.y,i-o.x),c=u(l-h+r.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(r=u===o?s:a),c<0&&(r=u===o?a:s),E(h)&&(r=r===s?a:s)),e.originX=r,w("skewing",y(T))(t,e,i,n))},r.skewHandlerY=function(t,e,i,n){var r,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?r=C(e,l,l,i,n).y>0?o:h:(c>0&&(r=u===s?o:h),c<0&&(r=u===s?h:o),E(a)&&(r=r===o?h:o)),e.originY=r,w("skewing",y(b))(t,e,i,n))},r.dragHandler=function(t,e,i,n){var r=e.target,s=i-e.offsetX,o=n-e.offsetY,a=!r.get("lockMovementX")&&r.left!==s,h=!r.get("lockMovementY")&&r.top!==o;return a&&r.set("left",s),h&&r.set("top",o),(a||h)&&g("moving",v(t,e,i,n)),a||h},r.scaleOrSkewActionName=function(t,e,i){var n=t[i.canvas.altActionKey];return 0===e.x?n?"skewX":"scaleY":0===e.y?n?"skewY":"scaleX":void 0},r.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},r.fireEvent=g,r.wrapWithFixedAnchor=y,r.wrapWithFireEvent=w,r.getLocalPoint=C,e.controlsUtils=r}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,n=e.controlsUtils;n.renderCircleControl=function(t,e,i,n,r){n=n||{};var s,o=this.sizeX||n.cornerSize||r.cornerSize,a=this.sizeY||n.cornerSize||r.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:r.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||r.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=n.cornerColor||r.cornerColor,t.strokeStyle=n.cornerStrokeColor||r.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()},n.renderSquareControl=function(t,e,n,r,s){r=r||{};var o=this.sizeX||r.cornerSize||s.cornerSize,a=this.sizeY||r.cornerSize||s.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=r.cornerColor||s.cornerColor,t.strokeStyle=r.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,n),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,n,r,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),m=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(m),l=f*e.util.sin(m)}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:n-l,y:r-h},tr:{x:n+o,y:r-a},bl:{x:n-o,y:r+a},br:{x:n+l,y:r+h}}},render:function(t,i,n,r,s){"circle"===((r=r||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,n,r,s):e.controlsUtils.renderSquareControl.call(this,t,i,n,r,s)}}}(e),function(){function t(t,e){var i,n,r,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&&(r=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),r||(r=t.getAttribute("stop-opacity")),n=(i=new T.Color(i)).getAlpha(),r=isNaN(parseFloat(r))?1:parseFloat(r),r*=n*e,{offset:a,color:i.toRgb(),opacity:r}}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 n,r,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(),n=0,r=h.length;n0){var p=m/Math.max(a.r1,a.r2);for(n=0,r=h.length;n\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,n,r=T.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(r.x1,r.y1,r.x2,r.y2):"radial"===this.type&&(e=t.createRadialGradient(r.x1,r.y1,r.r1,r.x2,r.y2,r.r2)),i=0,n=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,m=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,n){var r,s;Object.keys(e).forEach((function(t){"Infinity"===(r=e[t])?s=1:"-Infinity"===r?s=0:(s=parseFloat(e[t],10),"string"==typeof r&&/^(\d+\.\d+)%|(\d+)%$/.test(r)&&(s*=.01,"pixels"===n&&("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,r,u),"pixels"===u&&(g=-i.left,m=-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,n){i.source=t,e&&e(i,n)}),null,this.crossOrigin)}},toObject:function(t){var e,i,n=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:_(this.offsetX,n),offsetY:_(this.offsetY,n),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,n=e.height/t.height,r=this.offsetX/t.width,s=this.offsetY/t.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(n=1,s&&(n+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,r&&(i+=Math.abs(r))),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(),n=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(n[1],10)||0,offsetY:parseFloat(n[2],10)||0,blur:parseFloat(n[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var n=40,r=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&&(n=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,r=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,n=T.util.toFixed,r=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,n){return"string"==typeof e?T.util.loadImage(e,(function(e,r){if(e){var s=new T.Image(e,n);this[t]=s,s.canvas=this}i&&i(e,r)}),this,n&&n.crossOrigin):(n&&e.setOptions(n),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 n in e=e||{},t)i=t[n],e.cssOnly||(this._setBackstoreDimension(n,t[n]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(n,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,n,r=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,n=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,r=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="'+n(-i[4]/i[0],a)+" "+n(-i[5]/i[3],a)+" "+n(this.width/i[0],a)+" "+n(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 n=t[e+"Vpt"],r=t.viewportTransform,s={width:t.width/(n?r[0]:1),height:t.height/(n?r[3]:1)};return i.toSVG(s,{additionalTransform:n?T.util.matrixToSVG(r):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,n,r,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,n,r,s=this._objects;for(n=0,r=s.length;n\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(r=s._objects).length;e--;)n=r[e],i(this._objects,n),this._objects.unshift(n);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(r=s._objects,e=0;e0+l&&(o=s-1,i(this._objects,r),this._objects.splice(o,0,r)),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 n,r;if(i){for(n=e,r=e-1;r>=0;--r)if(t.intersectsWithObject(this._objects[r])||t.isContainedWithinObject(this._objects[r])||this._objects[r].isContainedWithinObject(t)){n=r;break}}else n=e-1;return n},bringForward:function(t,e){if(!t)return this;var n,r,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(n=(a=h._objects).length;n--;)r=a[n],(s=this._objects.indexOf(r))"}}),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,n=t.getZoom();t&&t._isRetinaScaling()&&(n*=T.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*n,i.shadowOffsetX=e.offsetX*n,i.shadowOffsetY=e.offsetY*n}},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 n=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,n.x,n.y),n},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,n=i.length,r=this.canvas.contextTop;this._saveAndTransform(r),this.oldEnd&&(r.beginPath(),r.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(r,i[n-2],i[n-1],!0),r.stroke(),r.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,n=this._points[0],r=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&n.x===r.x&&n.y===r.y){var s=this.width/1e3;n=new T.Point(n.x,n.y),r=new T.Point(r.x,r.y),n.x-=s,r.x+=s}for(t.moveTo(n.x,n.y),e=1,i=this._points.length;e=r&&(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,n=this.points;for(this._saveAndTransform(i),t=0,e=n.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var r=0,s=this._objects.length;r1&&(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(),n=T.util.invertTransform(i),r=this.restorePointerVpt(e);return T.util.transformPoint(r,n)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var n=this._normalizePointer(t,{x:e,y:i}),r=Math.max(t.cacheTranslationX+n.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+n.y*t.zoomY,0);return T.util.isTransparent(t._cacheContext,Math.round(r),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(),n=this._activeObject;return!e||e&&n&&i.length>1&&-1===i.indexOf(e)&&n!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&n&&n!==e},_shouldCenterTransform:function(t,e,i){var n;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?n=this.centeredScaling||t.centeredScaling:"rotate"===e&&(n=this.centeredRotation||t.centeredRotation),n?!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,n){if(!e||!t)return"drag";var r=n.controls[e];return r.getActionName(i,r,n)},_setupCurrentTransform:function(t,i,n){if(i){var r=this.getPointer(t),s=i.__corner,o=i.controls[s],a=n&&s?o.getActionHandler(t,i,o):T.controlsUtils.dragHandler,h=this._getActionFromCorner(n,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:r.x-i.left,offsetY:r.y-i.top,originX:l.x,originY:l.y,ex:r.x,ey:r.y,lastX:r.x,lastY:r.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),n=T.util.transformPoint(i,this.viewportTransform),r=new T.Point(e.ex+e.left,e.ey+e.top),s=T.util.transformPoint(r,this.viewportTransform),o=Math.min(n.x,s.x),a=Math.min(n.y,s.y),h=Math.max(n.x,s.x),l=Math.max(n.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 n,r,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;n=o,r=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&n&&c!==n&&(c=n,this.targets=r),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,n,r=t.length;r--;){var s=t[r],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,s,e)){(i=t[r]).subTargetCheck&&i instanceof T.Group&&(n=this._searchPossibleTargets(i._objects,e))&&this.targets.push(n);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 n,r=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(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,i||(r=this.restorePointerVpt(r));var l=this.getRetinaScaling();return 1!==l&&(r.x/=l,r.y/=l),n=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:r.x*n.width,y:r.y*n.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,n=this.getActiveObjects(),r=[],s=[];t.forEach((function(t){-1===n.indexOf(t)&&(i=!0,t.fire("deselected",{e,target:t}),s.push(t))})),n.forEach((function(n){-1===t.indexOf(n)&&(i=!0,n.fire("selected",{e,target:n}),r.push(n))})),t.length>0&&n.length>0?i&&this.fire("selection:updated",{e,selected:r,deselected:s}):n.length>0?this.fire("selection:created",{e,selected:r}):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 n=this._realizeGroupTransformOnObject(t),r=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,n),r},_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 n=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,n)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),T.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),T.StaticCanvas)"prototype"!==n&&(T.Canvas[n]=T.StaticCanvas[n])}(),function(){var t=T.util.addListener,e=T.util.removeListener,i={passive:!1};function n(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 n=this.upperCanvasEl,r=this._getEventPrefix();t(T.window,"resize",this._onResize),t(n,r+"down",this._onMouseDown),t(n,r+"move",this._onMouseMove,i),t(n,r+"out",this._onMouseOut),t(n,r+"enter",this._onMouseEnter),t(n,"wheel",this._onMouseWheel),t(n,"contextmenu",this._onContextMenu),t(n,"dblclick",this._onDoubleClick),t(n,"dragover",this._onDragOver),t(n,"dragenter",this._onDragEnter),t(n,"dragleave",this._onDragLeave),t(n,"drop",this._onDrop),this.enablePointerEvents||t(n,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](n,"gesture",this._onGesture),eventjs[e](n,"drag",this._onDrag),eventjs[e](n,"orientation",this._onOrientationChange),eventjs[e](n,"shake",this._onShake),eventjs[e](n,"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(n){i.fire("mouse:out",{target:e,e:t}),n&&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(n){n.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(n)),this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();t(T.document,"touchend",this._onTouchEnd,i),t(T.document,"touchmove",this._onMouseMove,i),e(r,s+"down",this._onMouseDown)},_onMouseDown:function(n){this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();e(r,s+"move",this._onMouseMove,i),t(T.document,s+"up",this._onMouseUp),t(T.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(n){if(!(n.touches.length>0)){this.__onMouseUp(n),this._resetTransformEventData(),this.mainTouchId=null;var r=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,r+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(n){this.__onMouseUp(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(n)&&(e(T.document,s+"up",this._onMouseUp),e(T.document,s+"move",this._onMouseMove,i),t(r,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,r=this._groupSelector,s=!1,o=!r||0===r.left&&0===r.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),n(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(n(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),n=this.targets,r={e,target:i,subTargets:n};if(this.fire(t,r),i&&i.fire(t,r),!n)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=[],n=this._groupSelector.ex,r=this._groupSelector.ey,s=n+this._groupSelector.left,o=r+this._groupSelector.top,a=new T.Point(v(n,s),v(r,o)),h=new T.Point(y(n,s),y(r,o)),l=!this.selectionFullyContained,c=n===s&&r===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,n=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),r=this.toCanvasElement(n,t);return T.util.toDataURL(r,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,n=(e.height||this.height)*t,r=this.getZoom(),s=this.width,o=this.height,a=r*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(),m=this.contextTop;return g.width=i,g.height=n,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=n,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=m,g}}),T.util.object.extend(T.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var n="string"==typeof t?JSON.parse(t):T.util.object.clone(t),r=this,s=n.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete n.clipPath,this._enlivenObjects(n.objects,(function(t){r.clear(),r._setBgOverlay(n,(function(){s?r._enlivenObjects([s],(function(i){r.clipPath=i[0],r.__setupCanvas.call(r,n,t,o,e)})):r.__setupCanvas.call(r,n,t,o,e)}))}),i),this}},__setupCanvas:function(t,e,i,n){var r=this;e.forEach((function(t,e){r.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(),n&&n()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var n=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,n),this.__setBgOverlay("overlayImage",t.overlayImage,i,n),this.__setBgOverlay("backgroundColor",t.background,i,n),this.__setBgOverlay("overlayColor",t.overlay,i,n)}else e&&e()},__setBgOverlay:function(t,e,i,n){var r=this;if(!e)return i[t]=!0,void(n&&n());"backgroundImage"===t||"overlayImage"===t?T.util.enlivenObjects([e],(function(e){r[t]=e[0],i[t]=!0,n&&n()})):this["set"+T.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,n&&n()}))},_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(n){i(n.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,n=e.util.object.clone,r=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,n=t.width,r=t.height,s=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(n<=s&&r<=s&&n*r<=i)return nc&&(t.zoomX/=n/c,t.width=c,t.capped=!0),r>u&&(t.zoomY/=r/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,n=e.y*t.scaleY/this.scaleY;return{width:i+2,height:n+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:n}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,n=t._currentTransform.action;if(this===i&&n.slice&&"scale"===n.slice(0,5))return!1}var r,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,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,C=l>y||c>w;v=C||(l<.9*y||c<.9*w)&&y>h&&w>h,C&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),r=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-r)+r,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,n={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:r(this.left,i),top:r(this.top,i),width:r(this.width,i),height:r(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:r(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:r(this.strokeMiterLimit,i),scaleX:r(this.scaleX,i),scaleY:r(this.scaleY,i),angle:r(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:r(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:r(this.skewX,i),skewY:r(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(n.clipPath=this.clipPath.toObject(t),n.clipPath.inverted=this.clipPath.inverted,n.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,n,t),this.includeDefaultValues||(n=this._removeDefaultValues(n)),n},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 n=this.canvas.getZoom(),r=this.canvas.getRetinaScaling();e*=n*r,i*=n*r}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var n="scaleX"===t||"scaleY"===t,r=this[t]!==i,s=!1;return n&&(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,r&&(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 n=e.util.invertTransform(this.calcTransformMatrix());t.transform(n[0],n[1],n[2],n[3],n[4],n[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,n=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=n},_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 n,r,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();r=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),n=e.util.qrDecompose(h),t.save(),t.translate(n.translateX,n.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(n.angle-=180),t.rotate(o(this.group?n.angle:this.angle)),i.forActiveSelection||this.group?r&&this.drawBordersInGroup(t,n,i):r&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,n=this.shadow,r=this.canvas,s=r&&r.viewportTransform[0]||1,o=r&&r.viewportTransform[3]||1;i=n.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),r&&r._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=n.color,t.shadowBlur=n.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=n.offsetX*s*i.scaleX,t.shadowOffsetY=n.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,n=-this.width/2+e.offsetX||0,r=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,n,r):t.transform(1,0,0,1,n,r),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:n,offsetY:r}},_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 n,r=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=r.x/this.scaleX/o,h=r.y/this.scaleY/o;s.width=a,s.height=h,(n=s.getContext("2d")).beginPath(),n.moveTo(0,0),n.lineTo(a,0),n.lineTo(a,h),n.lineTo(0,h),n.closePath(),n.translate(a/2,h/2),n.scale(r.zoomX/this.scaleX/o,r.zoomY/this.scaleY/o),this._applyPatternGradientTransform(n,i),n.fillStyle=i.toLive(t),n.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/r.zoomX,o*this.scaleY/r.zoomY),t.strokeStyle=n.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 n=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(n,t):e.Object._fromObject("Object",n,t)},cloneAsImage:function(t,i){var n=this.toCanvasElement(i);return t&&t(new e.Image(n)),this},toCanvasElement:function(t){t||(t={});var i=e.util,n=i.saveObjectTransform(this),r=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,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.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 _=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",_),r&&(this.group=r),this.set(n).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 n=new e.Point(i.x,i.y),r=this._getLeftTopCoords();return this.angle&&(n=e.util.rotatePoint(n,r,o(-this.angle))),{x:n.x-r.x,y:n.y-r.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,r,s){var o=e[t];i=n(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);r&&r(t)}))}))},e.Object.__uid=0)}(e),w=T.util.degreesToRadians,C={left:-.5,center:0,right:.5},E={top:-.5,center:0,bottom:.5},T.util.object.extend(T.Object.prototype,{translateToGivenOrigin:function(t,e,i,n,r){var s,o,a,h=t.x,l=t.y;return"string"==typeof e?e=C[e]:e-=.5,"string"==typeof n?n=C[n]:n-=.5,"string"==typeof i?i=E[i]:i-=.5,"string"==typeof r?r=E[r]:r-=.5,o=r-i,((s=n-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 n=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?T.util.rotatePoint(n,t,w(this.angle)):n},translateToOriginPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?T.util.rotatePoint(n,t,w(this.angle)):n},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 n,r,s=this.getCenterPoint();return n=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new T.Point(this.left,this.top),r=new T.Point(t.x,t.y),this.angle&&(r=T.util.rotatePoint(r,s,-w(this.angle))),r.subtractEquals(n)},setPositionByOrigin:function(t,e,i){var n=this.translateToCenterPoint(t,e,i),r=this.translateToOriginPoint(n,this.originX,this.originY);this.set("left",r.x),this.set("top",r.y)},adjustPosition:function(t){var e,i,n=w(this.angle),r=this.getScaledWidth(),s=T.util.cos(n)*r,o=T.util.sin(n)*r;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,n=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,n){var r=this.getCoords(i,n);return"Intersection"===T.Intersection.intersectPolygonRectangle(r,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 n=this.getCoords(e,i),r=e?t.aCoords:t.lineCoords,s=0,o=t._getImageLines(r);s<4;s++)if(!t.containsPoint(n[s],o))return!1;return!0},isContainedWithinRect:function(t,e,i,n){var r=this.getBoundingRect(i,n);return r.left>=t.x&&r.left+r.width<=e.x&&r.top>=t.y&&r.top+r.height<=e.y},containsPoint:function(t,e,i,n){var r=this._getCoords(i,n),s=(e=e||this._getImageLines(r),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 n={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(n,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,n,r,s=0;for(var o in e)if(!((r=e[o]).o.y=t.y&&r.d.y>=t.y||(r.o.x===r.d.x&&r.o.x>=t.x?n=r.o.x:(i=(r.d.y-r.o.y)/(r.d.x-r.o.x),n=-(t.y-0*t.x-(r.o.y-i*r.o.x))/(0-i)),n>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var n=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(n)},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,n=e.additionalTransform||"",r=[this.getSvgTransform(!0,n),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=r,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,n,r=(e=e||{}).noStyle,s=e.reviver,o=r?"":'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=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+T.Object.__uid++,n='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,r?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=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(n),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,n){var r={};n.forEach((function(t){r[t]=e[t]})),t(e[i],r,!0)}function n(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var r=0,s=t.length;r=0;h--)if(r=a[h],this.isControlVisible(r)&&(n=this._getImageLines(e?this.oCoords[r].touchCorner:this.oCoords[r].corner),0!==(i=this._findCrossPoints({x:s,y:o},n))&&i%2==1))return this.__corner=r,r;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(),n=this._calculateCurrentDimensions(),r=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/r[0],1/r[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-n.x/2,-n.y/2,n.x,n.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),n=this.borderScaleFactor,r=i.x+n,s=i.y+n,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(-r/2,-s/2,r,s),o&&(t.beginPath(),this.forEachControl((function(e,i,n){e.withConnection&&e.getVisibility(n,i)&&(a=!0,t.moveTo(e.x*r,e.y*s),t.lineTo(e.x*r+e.offsetX,e.y*s+e.offsetY))})),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var n=T.util.sizeAfterTransform(this.width,this.height,e),r=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=n.x+r*(s?this.canvas.getZoom():e.scaleX)+o,h=n.y+r*(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,n,r=this.canvas.getRetinaScaling();return t.setTransform(r,0,0,r,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(r,s,o){n=o.oCoords[s],r.getVisibility(o,s)&&(i&&(n=T.util.transformPoint(n,i)),r.render(t,n.x,n.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(){},n=(e=e||{}).onComplete||i,r=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(),r()},onComplete:function(){t.setCoords(),n()}})},fxCenterObjectV:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=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(),r()},onComplete:function(){t.setCoords(),n()}})},fxRemove:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=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(),r()},onComplete:function(){s.remove(t),n()}})}}),T.util.object.extend(T.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],n=[];for(t in arguments[0])i.push(t);for(var r=0,s=i.length;r-1||r&&s.colorProperties.indexOf(r[1])>-1,a=r?this.get(r[0])[r[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,n){return i.abort.call(s,t,e,n)},onChange:function(e,o,a){r?s[r[0]][r[1]]=e:s.set(t,e),n||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,r){n||(s.setCoords(),i.onComplete&&i.onComplete(t,e,r))}};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,n=e.util.object.clone,r={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,n=t.axis1,r=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(n),this.get(r));case a:return Math.min(this.get(n),this.get(r))+.5*this.get(s);case h:return Math.max(this.get(n),this.get(r))}}}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!==r[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,n=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:n,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,n,r){r=r||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];n(new e.Line(o,i(s,r)))},e.Line.fromObject=function(t,i){var r=n(t,!0);r.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",r,(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,n=(this.endAngle-this.startAngle)%360;if(0===n)t=["\n'];else{var r=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 n,r=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(n=r)&&n.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");r.left=(r.left||0)-r.radius,r.top=(r.top||0)-r.radius,i(new e.Circle(r))},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 n=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);n.left=(n.left||0)-n.rx,n.top=(n.top||0)-n.ry,i(new e.Ellipse(n))},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,n=this.width,r=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+n-e,o),a&&t.bezierCurveTo(s+n-h*e,o,s+n,o+h*i,s+n,o+i),t.lineTo(s+n,o+r-i),a&&t.bezierCurveTo(s+n,o+r-h*i,s+n-h*e,o+r,s+n-e,o+r),t.lineTo(s+e,o+r),a&&t.bezierCurveTo(s+h*e,o+r,s,o+r-h*i,s,o+r-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,n,r){if(!t)return n(null);r=r||{};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(r?e.util.object.clone(r):{},s));o.visible=o.visible&&o.width>0&&o.height>0,n(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,n=e.util.array.min,r=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),n=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-n,this.height=i.height-n,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+n/2,y:i.top-this.strokeWidth/2+n/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+n/2,y:i.top+this.height/2+n/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=n(t,"x")||0,i=n(t,"y")||0;return{left:e,top:i,width:(r(t,"x")||0)-e,height:(r(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,n=this.pathOffset.y,r=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,n=this.pathOffset.x,r=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-n,this.points[0].y-r);for(var s=0;s"},toObject:function(t){return r(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,r,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 n=this._objects.length;if(this.useSetOnGroup)for(;n--;)this._objects[n].setOnGroup(t,i);if("canvas"===t)for(;n--;)this._objects[n]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,n=this._objects.filter((function(t){return!t.excludeFromExport})).map((function(e){var n=e.includeDefaultValues;e.includeDefaultValues=i;var r=e.toObject(t);return e.includeDefaultValues=n,r})),r=e.Object.prototype.toObject.call(this,t);return r.objects=n,r},toDatalessObject:function(t){var i,n=this.sourcePath;if(n)i=n;else{var r=this.includeDefaultValues;i=this._objects.map((function(e){var i=e.includeDefaultValues;e.includeDefaultValues=r;var n=e.toDatalessObject(t);return e.includeDefaultValues=i,n}))}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,n=this._objects.length;i\n"],i=0,n=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,n=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 n=0,r=this._objects.length;n\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,n){this.setElement(t,i),this._setWidthHeight(),e&&e(this,n)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),n=i.scaleX,r=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||n>e&&r>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=n,void(this._lastScaleY=r);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=n,this._lastScaleY=t.scaleY=r,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,n=e.naturalHeight||e.height;if(this._element===this._originalElement){var r=T.util.createCanvasElement();r.width=i,r.height=n,this._element=r,this._filteredEl=r}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,n),this._lastScaleX=1,this._lastScaleY=1;return T.filterBackend||(T.filterBackend=T.initFilterBackend()),T.filterBackend.applyFilters(t,this._originalElement,i,n,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,n=this._filterScalingY,r=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*n,g=o(r*i,c-d),m=o(s*n,u-f),p=-r/2,_=-s/2,v=o(r,c/i-h),y=o(s,u/n-l);e&&t.drawImage(e,d,f,g,m,p,_,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,n=this._element.height,r=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?(r=c/i,s=u/n):("meet"===e.meetOrSlice&&(t=(c-i*(r=s=T.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-n*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(r=s=T.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=n-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/r,n=u/s)),{width:i,height:n,scaleX:r,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,n){n?e&&e(null,!0):T.Image.prototype._initFilters.call(i,i.filters,(function(n){i.filters=n||[],T.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(n){i.resizeFilter=n[0],T.util.enlivenObjectEnlivables(i,i,(function(){var n=new T.Image(t,i);e(n,!1)}))}))}))}),null,i.crossOrigin)},T.Image.fromURL=function(t,e,i){T.util.loadImage(t,(function(t,n){e&&e(new T.Image(t,i),n)}),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,n){var r=T.parseAttributes(t,T.Image.ATTRIBUTE_NAMES);T.Image.fromURL(r["xlink:href"],i,e(n?T.util.object.clone(n):{},r))})}(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,n=t.onChange||e,r=this;return T.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){r.rotate(t),n()},onComplete:function(){r.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(){}",n=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(n,i),t.compileShader(n),!!t.getShaderParameter(n,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"),n=i.getContext("webgl")||i.getContext("experimental-webgl"),r=!1;if(n){T.maxTextureSize=n.getParameter(n.MAX_TEXTURE_SIZE),r=T.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(n,s[o])){T.webGlPrecision=s[o];break}}return this.isSupported=r,r},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,n=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var r="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(n&&i&&r&&s){var o=T.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(T.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=T.util.createCanvasElement();i.width=t,i.height=e;var n={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},r=i.getContext("webgl",n);r||(r=i.getContext("experimental-webgl",n)),r&&(r.clearColor(0,0,0,0),this.canvas=i,this.gl=r)},applyFilters:function(t,e,i,n,r,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:n,destinationWidth:i,destinationHeight:n,context:a,sourceTexture:this.createTexture(a,i,n,!o&&e),targetTexture:this.createTexture(a,i,n),originalTexture:o||this.createTexture(a,i,n,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:r},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,n=e.height,r=t.destinationWidth,s=t.destinationHeight;i===r&&n===s||(e.width=r,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),r.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,n){var r=t.createTexture();return t.bindTexture(t.TEXTURE_2D,r),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),n?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,n):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),r},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:I,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 n=t.getParameter(i.UNMASKED_RENDERER_WEBGL),r=t.getParameter(i.UNMASKED_VENDOR_WEBGL);n&&(e.renderer=n.toLowerCase()),r&&(e.vendor=r.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,n,r){var s=r.getContext("2d");s.drawImage(e,0,0,i,n);var o={sourceWidth:i,sourceHeight:n,imageData:s.getImageData(0,0,i,n),originalEl:e,originalImageData:s.getImageData(0,0,i,n),canvasEl:r,ctx:s,filterBackend:this};return t.forEach((function(t){t.applyTo(o)})),o.imageData.width===i&&o.imageData.height===n||(r.width=o.imageData.width,r.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 n=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var r=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var s=t.createProgram();if(t.attachShader(s,n),t.attachShader(s,r),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 n=e.aPosition,r=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,r),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,n=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(n.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(n,e,i)),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t.targetTexture,0)):(n.bindFramebuffer(n.FRAMEBUFFER,null),n.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,n=e.util.createClass;i.ColorMatrix=n(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,n,r,s,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,n+=m[h+2]*l,S||(r+=m[h+3]*l));E[s]=e,E[s+1]=i,E[s+2]=n,E[s+3]=S?m[s+3]:r}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,n=e.util.createClass;i.Grayscale=n(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,n=t.imageData.data,r=n.length,s=this.mode;for(e=0;el[0]&&r>l[1]&&s>l[2]&&n 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,n,r,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,n=h[1]*this.alpha,r=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,n=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/n;var r,s=e.width,a=e.height,h=o(s*i),l=o(a*n);"sliceHack"===this.resizeType?r=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?r=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?r=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(r=this.lanczosResize(t,s,a,h,l)),t.imageData=r},sliceByTwo:function(t,i,r,s,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=r*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){L=n(1e3*s(T-C.x)),w[L]||(w[L]={});for(var F=E.y-y;F<=E.y+y;F++)F<0||F>=o||(M=n(1e3*s(F-C.y)),w[L][M]||(w[L][M]=f(r(i(L*p,2)+i(M*_,2))/1e3)),(b=w[L][M])>0&&(x+=b,O+=b*c[I=4*(F*e+T)],A+=b*c[I+1],R+=b*c[I+2],D+=b*c[I+3]))}d[I=4*(S*a+h)]=O/x,d[I+1]=A/x,d[I+2]=R/x,d[I+3]=D/x}return++h1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(b+=y*f[3+(L=4*(D+x*e))],C+=y,f[L+3]<255&&(y=y*f[L+3]/250),E+=y*f[L],S+=y*f[L+1],T+=y*f[L+2],w+=y)}m[v]=E/w,m[v+1]=S/w,m[v+2]=T/w,m[v+3]=b/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,n=e.util.createClass;i.Contrast=n(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,n=i.length,r=Math.floor(255*this.contrast),s=259*(r+255)/(255*(259-r));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,n=e.util.createClass;i.Gamma=n(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,n=this.gamma,r=i.length,s=1/n[0],o=1/n[1],a=1/n[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,r=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=n)}return t},_renderTextLine:function(t,e,i,n,r,s){this._renderChars(t,e,i,n,r,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,n,r,s,o,a,h=t.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,m=this._textLines.length;g=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,n){var r=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,r,s.segmentsInfo);i.renderLeft=o.x-n.x,i.renderTop=o.y-n.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,n,r){var s,o=this.getCompleteStyleDeclaration(e,i),a=n?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,n,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&&!r){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),n=1,r=e.length;n0){var x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+E*n+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,n=r,o=a}else d+=f.kernedWidth;x=v+s+u,"rtl"===this.direction&&(x=this.width-x-d),t.fillStyle=p,g&&p&&t.fillRect(x,c+E*n+o,d-C,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var n=t||this,r=this.fontFamily,s=e.Text.genericFonts.indexOf(r.toLowerCase())>-1,o=void 0===r||r.indexOf("'")>-1||r.indexOf(",")>-1||r.indexOf('"')>-1||s?n.fontFamily:'"'+n.fontFamily+'"';return[e.isLikelyNode?n.fontWeight:n.fontStyle,e.isLikelyNode?n.fontStyle:n.fontWeight,i?this.CACHE_FONT_SIZE+"px":n.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),n=new Array(i.length),r=["\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(),n=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:n.left,topOffset:n.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,n,r,s=0,o=0,a=this.get2DCursorLocation(t);n=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(r.left*=-1),this.cursorOffsetCache=r,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),n=i.lineIndex,r=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(n,r,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(n,r,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(n)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(n,r,"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,n=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,r=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(n),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),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,C=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,C=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+C,y,w),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 n in e.styles)for(var r in e.styles[n])t(e.styles[n][r]);T.Object._fromObject("IText",e,i,"text")}}(),S=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,n){var r;return r={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){r.isAborted||t[n]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return r.isAborted}}),r},_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&&nthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(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 n=i.slice(0,t),r=T.util.string.graphemeSplit(n).length;if(t===e)return{selectionStart:r,selectionEnd:r};var s=i.slice(t,e);return{selectionStart:r,selectionEnd:r+T.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var n=i.slice(0,t).join("").length;return t===e?{selectionStart:n,selectionEnd:n}:{selectionStart:n,selectionEnd:n+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),n=i.lineIndex,r=i.charIndex,s=this.getValueOfPropertyAt(n,r,"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,m=c.clientWidth/u,p=c.clientHeight/d;return h=T.util.transformPoint(h,a),(h=T.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,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,n,r=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),o=r.lineIndex,a=r.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(n[c-d]=n[u],delete n[u])}},shiftLineStyles:function(t,e){var i=S(this.styles);for(var n in this.styles){var r=parseInt(n,10);r>t&&(this.styles[r+e]=i[r],i[r-e]||delete this.styles[r])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,n){var r,s={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(r=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;)n&&n[i-1]?this.styles[t+i]={0:S(n[i-1])}:r?this.styles[t+i]={0:S(r)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,n){this.styles||(this.styles={});var r=this.styles[t],s=r?S(r):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(r[a+i]=s[a],s[a-i]||delete r[a])}if(this._forceClearCache=!0,n)for(;i--;)Object.keys(n[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=S(n[i]));else if(r)for(var h=r[e?e-1:1];h&&i--;)this.styles[t][e+i]=S(h)},insertNewStyleBlock:function(t,e,i){for(var n=this.get2DCursorLocation(e,!0),r=[0],s=0,o=0;o0&&(this.insertCharStyleObject(n.lineIndex,n.charIndex,r[0],i),i=i&&i.slice(r[0]+1)),s&&this.insertNewlineStyleObject(n.lineIndex,n.charIndex+r[0],s),o=1;o0?this.insertCharStyleObject(n.lineIndex+o,0,r[o],i):i&&this.styles[n.lineIndex+o]&&i[0]&&(this.styles[n.lineIndex+o][0]=i[0]),i=i&&i.slice(r[o]+1);r[o]>0&&this.insertCharStyleObject(n.lineIndex+o,0,r[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,n=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,n,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),n=0,r=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));r=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+r);for(var c=0,u=e.length;cs||o<0?0:1);return this.flipX&&(a=r-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,n,r,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),m=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(n+=(i=this.__charBounds[t][e-1]).left+i.width),n},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(r===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=n.charIndex,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r+1,o);return this._textLines[r].slice(s).length+a+1+this.missingNewlineOffset(r)},_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),n=this.get2DCursorLocation(i),r=n.lineIndex;if(0===r||t.metaKey||33===t.keyCode)return-i;var s=n.charIndex,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r-1,o),h=this._textLines[r].slice(0,s),l=this.missingNewlineOffset(r-1);return-this._textLines[r-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,n,r=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=r.length;ae){n=!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 n;if(t.altKey)n=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;n=this["findLineBoundary"+i](this[e])}if(void 0!==typeof n&&this[e]!==n)return this[e]=n,!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,n){void 0===n&&(n=i),n>i&&this.removeStyleFromTo(i,n);var r=T.util.string.graphemeSplit(t);this.insertNewStyleBlock(r,i,e),this._text=[].concat(this._text.slice(0,i),r,this._text.slice(n)),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,n=[],r=[],s=t;this._setSVGBg(r);for(var o=0,a=this._textLines.length;o",T.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,n){var r,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];n+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)h=g===m||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||(r=r||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(r,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,n)),u="",r=s,i+=d,d=0)},_pushTextBgRect:function(e,i,n,r,s,o){var a=T.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,n){for(var r,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,n=0,r={},s=0;s0?(i=0,n++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[n])&&s>0&&(i++,n++),r[s]={line:e,offset:i},n+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return r},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var n=this._styleMap[i];n&&(i=n.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,n=0,r=!1,s=this._styleMap[t],o=this._styleMap[t+1];for(var a in s&&(t=s.line,n=s.offset),o&&(r=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=n&&(!r||hn&&!p?(a.push(h),h=[],s=f,p=!0):s+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+r>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+r),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),n=this._wrapText(i.lines,this.width),r=new Array(n.length),s=0;s{},898:()=>{},245:()=>{}},qe={};function Ze(t){var e=qe[t];if(void 0!==e)return e.exports;var i=qe[t]={exports:{}};return ze[t](i,i.exports,Ze),i.exports}Ze.d=(t,e)=>{for(var i in e)Ze.o(e,i)&&!Ze.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},Ze.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Ke={};(()=>{let t;Ze.d(Ke,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?Ze(653).fabric:{version:"5.2.1"}})();var Je,Qe,$e,ti,ei=Ke.R;!function(t){t[t.DIMT_RECTANGLE=1]="DIMT_RECTANGLE",t[t.DIMT_QUADRILATERAL=2]="DIMT_QUADRILATERAL",t[t.DIMT_TEXT=4]="DIMT_TEXT",t[t.DIMT_ARC=8]="DIMT_ARC",t[t.DIMT_IMAGE=16]="DIMT_IMAGE",t[t.DIMT_POLYGON=32]="DIMT_POLYGON",t[t.DIMT_LINE=64]="DIMT_LINE",t[t.DIMT_GROUP=128]="DIMT_GROUP"}(Je||(Je={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(Qe||(Qe={})),function(t){t[t.EF_ENHANCED_FOCUS=4]="EF_ENHANCED_FOCUS",t[t.EF_AUTO_ZOOM=16]="EF_AUTO_ZOOM",t[t.EF_TAP_TO_FOCUS=64]="EF_TAP_TO_FOCUS"}($e||($e={})),function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(ti||(ti={}));const ii=t=>"number"==typeof t&&!Number.isNaN(t),ni=t=>"string"==typeof t;var ri,si,oi,ai,hi,li,ci,ui,di,fi,gi;!function(t){t[t.ARC=0]="ARC",t[t.IMAGE=1]="IMAGE",t[t.LINE=2]="LINE",t[t.POLYGON=3]="POLYGON",t[t.QUAD=4]="QUAD",t[t.RECT=5]="RECT",t[t.TEXT=6]="TEXT",t[t.GROUP=7]="GROUP"}(hi||(hi={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(li||(li={}));class mi{get mediaType(){return new Map([["rect",Je.DIMT_RECTANGLE],["quad",Je.DIMT_QUADRILATERAL],["text",Je.DIMT_TEXT],["arc",Je.DIMT_ARC],["image",Je.DIMT_IMAGE],["polygon",Je.DIMT_POLYGON],["line",Je.DIMT_LINE],["group",Je.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(Ve(this,si,"f")){case Qe.DIS_DEFAULT:return"default";case Qe.DIS_SELECTED:return"selected"}}set drawingStyleId(t){this.styleId=t}get drawingStyleId(){return this.styleId}set coordinateBase(t){if(!["view","image"].includes(t))throw new Error("Invalid 'coordinateBase'.");this._drawingLayer&&("image"===Ve(this,oi,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===Ve(this,oi,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),Ge(this,oi,t,"f")}get coordinateBase(){return Ve(this,oi,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(ri.add(this),si.set(this,void 0),oi.set(this,"image"),this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapState_StyleId=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,null!=e&&!ii(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(Qe.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",(()=>{this.setState(Qe.DIS_SELECTED)})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(Qe.DIS_SELECTED):this.setState(Qe.DIS_DEFAULT),"textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}setState(t){Ge(this,si,t,"f")}getState(){return Ve(this,si,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),n=this.mapEvent_Callbacks.get(i);if(!n)throw new Error(`Event '${t}' does not exist.`);let r=n.get(e);r||(r=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const n={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,r,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,r=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)u0?i-1:n,yi),actionName:"modifyPolygon",pointIndex:i}),t}),{}),Ge(this,ui,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,n){return t["p"+n]=new ei.Control({positionHandler:_i,actionHandler:wi(n>0?n-1:i,yi),actionName:"modifyPolygon",pointIndex:n}),t}),{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let n=i.x-e.pathOffset.x,r=i.y-e.pathOffset.y;const s=ei.util.transformPoint({x:n,y:r},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){Ve(this,ui,"f")&&this.setPolygon(Ve(this,ui,"f"))}setPolygon(t){if(!I(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Ge(this,ui,JSON.parse(JSON.stringify(t)),"f")}getPolygon(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Ve(this,ui,"f")?JSON.parse(JSON.stringify(Ve(this,ui,"f"))):null}}ui=new WeakMap;class Ei extends mi{set maintainAspectRatio(t){t&&this.set("scaleY",this.get("scaleX"))}get maintainAspectRatio(){return Ve(this,fi,"f")}constructor(t,e,i,n){if(super(null,n),di.set(this,void 0),fi.set(this,void 0),!O(e))throw new TypeError("Invalid 'rect'.");if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)this._setFabricObject(new ei.Image(t,{left:e.x,top:e.y}));else{if(!C(t))throw new TypeError("Invalid 'image'.");{const i=document.createElement("canvas");let n;if(i.width=t.width,i.height=t.height,t.format===a.IPF_GRAYSCALED){n=new Uint8ClampedArray(t.width*t.height*4);for(let e=0;e{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let n=0;ni&&(i=r.length)}if(-1===i)break;for(let n=0;n=t[n].length-1)continue;let r=" ".repeat(i+2-t[n][e].length);t[n][e]=t[n][e].concat(r)}}})(e),(t=>{let e="";for(let i=0;i({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const n=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new ei.Control({positionHandler:_i,actionHandler:wi(i>0?i-1:n,yi),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let n=t.x-i.pathOffset.x,r=t.y-i.pathOffset.y;const s=ei.util.transformPoint({x:n,y:r},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){Ve(this,bi,"f")&&this.setLine(Ve(this,bi,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!T(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else Ge(this,bi,JSON.parse(JSON.stringify(t)),"f")}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return Ve(this,bi,"f")?JSON.parse(JSON.stringify(Ve(this,bi,"f"))):null}}bi=new WeakMap;class Oi extends Ci{constructor(t,e){if(super({points:null==t?void 0:t.points},e),Ii.set(this,void 0),!x(t))throw new TypeError("Invalid 'quad'.");Ge(this,Ii,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="quad"}setPosition(t){this.setQuad(t)}getPosition(){return this.getQuad()}updatePosition(){Ve(this,Ii,"f")&&this.setQuad(Ve(this,Ii,"f"))}setPolygon(){}getPolygon(){return null}setQuad(t){if(!x(t))throw new TypeError("Invalid 'quad'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Ge(this,Ii,JSON.parse(JSON.stringify(t)),"f")}getQuad(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Ve(this,Ii,"f")?JSON.parse(JSON.stringify(Ve(this,Ii,"f"))):null}}Ii=new WeakMap;class Ai extends mi{constructor(t){super(new ei.Group(t.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.setState(Qe.DIS_SELECTED);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.setState(Qe.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}setChildDrawingItems(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()))}}const Ri=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),Di=t=>!!ni(t)&&""!==t,Li=t=>!(!Ri(t)||"id"in t&&!ii(t.id)||"lineWidth"in t&&!ii(t.lineWidth)||"fillStyle"in t&&!Di(t.fillStyle)||"strokeStyle"in t&&!Di(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!Di(t.fontFamily)||"fontSize"in t&&!ii(t.fontSize));class Mi{static convert(t,e,i){const n={x:0,y:0,width:e,height:i};if(!t)return n;if(O(t))t.isMeasuredInPercentage?(n.x=t.x/100*e,n.y=t.y/100*i,n.width=t.width/100*e,n.height=t.height/100*i):(n.x=t.x,n.y=t.y,n.width=t.width,n.height=t.height);else{if(!E(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?(n.x=t.left/100*e,n.y=t.top/100*i,n.width=(t.right-t.left)/100*e,n.height=(t.bottom-t.top)/100*i):(n.x=t.left,n.y=t.top,n.width=t.right-t.left,n.height=t.bottom-t.top)}return n.x=Math.round(n.x),n.y=Math.round(n.y),n.width=Math.round(n.width),n.height=Math.round(n.height),n}}var Fi,Pi;class ki{constructor(){Fi.set(this,new Map),Pi.set(this,!1)}get disposed(){return Ve(this,Pi,"f")}on(t,e){t=t.toLowerCase();const i=Ve(this,Fi,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else Ve(this,Fi,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=Ve(this,Fi,"f").get(t);if(!i)return;const n=i.indexOf(e);-1!==n&&i.splice(n,1)}offAll(t){t=t.toLowerCase();const e=Ve(this,Fi,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const n=Ve(this,Fi,"f").get(t);if(n&&n.length){i=Object.assign({async:!1,copy:!0},i);for(let r of n){if(!r)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let o=!1;if(i.async)setTimeout((()=>{this.disposed||n.includes(r)&&r.apply(i.target,s)}),0);else try{o=r.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){Ge(this,Pi,!0,"f")}}function Bi(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function Ni(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function ji(t,e,i,n){let r=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(n[1]-e[1])+e[0]*(t[1]-n[1])+n[0]*(e[1]-t[1]);return!((r^s)>=0&&0!==r&&0!==s||(r=i[0]*(t[1]-n[1])+n[0]*(i[1]-t[1])+t[0]*(n[1]-i[1]),s=i[0]*(e[1]-n[1])+n[0]*(i[1]-e[1])+e[0]*(n[1]-i[1]),(r^s)>=0&&0!==r&&0!==s))}Fi=new WeakMap,Pi=new WeakMap;const Ui=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const n=document.createElement("div");if(n.insertAdjacentHTML("beforeend",i),1===n.childElementCount&&n.firstChild instanceof HTMLTemplateElement)return n.firstChild.content;const r=new DocumentFragment;for(let t of n.children)r.append(t);return r};var Vi,Gi,Wi,Yi,Hi,Xi,zi,qi,Zi,Ki,Ji,Qi,$i,tn,en,nn,rn,sn,on,an,hn,ln,cn,un,dn,fn,gn,mn,pn,_n,vn,yn,wn,Cn;class En{static createDrawingStyle(t){if(!Li(t))throw new Error("Invalid style definition.");let e,i=En.USER_START_STYLE_ID;for(;Ve(En,Vi,"f",Gi).has(i);)i++;e=i;const n=JSON.parse(JSON.stringify(t));n.id=e;for(let t in Ve(En,Vi,"f",Wi))n.hasOwnProperty(t)||(n[t]=Ve(En,Vi,"f",Wi)[t]);return Ve(En,Vi,"f",Gi).set(e,n),n.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=Ve(En,Vi,"f",Gi).get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}static getDrawingStyle(t){return this._getDrawingStyle(t,!0)}static getAllDrawingStyles(){return JSON.parse(JSON.stringify(Array.from(Ve(En,Vi,"f",Gi).values())))}static _updateDrawingStyle(t,e){if(!Li(e))throw new Error("Invalid style definition.");const i=Ve(En,Vi,"f",Gi).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}Vi=En,En.STYLE_BLUE_STROKE=1,En.STYLE_GREEN_STROKE=2,En.STYLE_ORANGE_STROKE=3,En.STYLE_YELLOW_STROKE=4,En.STYLE_BLUE_STROKE_FILL=5,En.STYLE_GREEN_STROKE_FILL=6,En.STYLE_ORANGE_STROKE_FILL=7,En.STYLE_YELLOW_STROKE_FILL=8,En.STYLE_BLUE_STROKE_TRANSPARENT=9,En.STYLE_GREEN_STROKE_TRANSPARENT=10,En.STYLE_ORANGE_STROKE_TRANSPARENT=11,En.USER_START_STYLE_ID=1024,Gi={value:new Map([[En.STYLE_BLUE_STROKE,{id:En.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[En.STYLE_GREEN_STROKE,{id:En.STYLE_GREEN_STROKE,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[En.STYLE_ORANGE_STROKE,{id:En.STYLE_ORANGE_STROKE,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[En.STYLE_YELLOW_STROKE,{id:En.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[En.STYLE_BLUE_STROKE_FILL,{id:En.STYLE_BLUE_STROKE_FILL,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[En.STYLE_GREEN_STROKE_FILL,{id:En.STYLE_GREEN_STROKE_FILL,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[En.STYLE_ORANGE_STROKE_FILL,{id:En.STYLE_ORANGE_STROKE_FILL,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[En.STYLE_YELLOW_STROKE_FILL,{id:En.STYLE_YELLOW_STROKE_FILL,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[En.STYLE_BLUE_STROKE_TRANSPARENT,{id:En.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[En.STYLE_GREEN_STROKE_TRANSPARENT,{id:En.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[En.STYLE_ORANGE_STROKE_TRANSPARENT,{id:En.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},Wi={value:{lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}},"undefined"!=typeof document&&"undefined"!=typeof window&&(ei.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(ei.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),ei.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},ei.Object.prototype.transparentCorners=!1,ei.Object.prototype.cornerSize=20,ei.Object.prototype.touchCornerSize=100,ei.Object.prototype.cornerColor="rgb(254,142,20)",ei.Object.prototype.cornerStyle="circle",ei.Object.prototype.strokeUniform=!0,ei.Object.prototype.hasBorders=!1,ei.Canvas.prototype.containerClass="",ei.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i,n=this.upperCanvasEl,r=ei.util.getPointer(t,n),s=n.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(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,e||(r=this.restorePointerVpt(r));var h=this.getRetinaScaling();if(1!==h&&(r.x/=h,r.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(n).objectFit,c=n.width,u=n.height,d=o,f=a;i={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:r.x*i.width,y:(r.y-(f-m)/2)*i.width}):(g=f*p,m=f,{x:(r.x-(d-g)/2)*i.height,y:r.y*i.height}):"cover"===l?p>_?{x:(c-i.height*d)/2+r.x*i.height,y:r.y*i.height}:{x:r.x*i.width,y:(u-i.width*f)/2+r.y*i.width}:{x:r.x*i.width,y:r.y*i.height}}return i={width:1,height:1},{x:r.x*i.width,y:r.y*i.height}},ei.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,n=this._getEventPrefix();ei.util.addListener(ei.document,"touchend",this._onTouchEnd,{passive:!1}),ei.util.addListener(ei.document,"touchmove",this._onMouseMove,{passive:!1}),ei.util.removeListener(i,n+"down",this._onMouseDown)},ei.Textbox.prototype._wrapLine=function(t,e,i,n){const r=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!r||!r.length);var o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?ei.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,m=0,p=0,_=!0,v=this._getWidthOfCharSpacing();n=n||0,0===c.length&&c.push([]),i-=n;for(var y=0;yi&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+n),h});class Sn{get width(){return this.fabricCanvas.width}get height(){return this.fabricCanvas.height}set _allowMultiSelect(t){this.fabricCanvas.selection=t,this.fabricCanvas.renderAll()}get _allowMultiSelect(){return this.fabricCanvas.selection}constructor(t,e,i){if(this.mapType_StateAndStyleId=new Map,this.mode="viewer",this.onSelectionChanged=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas"))this.fabricCanvas=t.getFabricCanvas();else{let e=this.fabricCanvas=new ei.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.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 n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])}),0)}})),e.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 n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{const e=[];for(let n of i)t.hasDrawingItem(n)&&e.push(n);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)}),0)}})),e.on("selection:updated",(function(t){const e=t.selected,i=t.deselected,n=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of n){const n=[],r=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&n.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&r.push(i)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(n,r)}),0)}})),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let n,r;switch(this.id=e,e){case Sn.DDN_LAYER_ID:n=En.getDrawingStyle(En.STYLE_BLUE_STROKE),r=En.getDrawingStyle(En.STYLE_BLUE_STROKE_FILL);break;case Sn.DBR_LAYER_ID:n=En.getDrawingStyle(En.STYLE_ORANGE_STROKE),r=En.getDrawingStyle(En.STYLE_ORANGE_STROKE_FILL);break;case Sn.DLR_LAYER_ID:n=En.getDrawingStyle(En.STYLE_GREEN_STROKE),r=En.getDrawingStyle(En.STYLE_GREEN_STROKE_FILL);break;default:n=En.getDrawingStyle(En.STYLE_YELLOW_STROKE),r=En.getDrawingStyle(En.STYLE_YELLOW_STROKE_FILL)}for(let t of mi.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:n.id,selected:r.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return En.getDrawingStyle(t.styleId);return En.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,n){const r=this.getDrawingItems((e=>e._mediaType===t));for(let t of r)t.styleSelector===e&&this._changeItemStyle(t,i,!0);n||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const n=t._getFabricObject();"number"==typeof t.styleId&&(e=En.getDrawingStyle(t.styleId)),n.strokeWidth=e.lineWidth,"fill"===e.paintMode?(n.fill=e.fillStyle,n.stroke=e.fillStyle):"stroke"===e.paintMode?(n.fill="transparent",n.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(n.fill=e.fillStyle,n.stroke=e.strokeStyle),n.fontFamily&&(n.fontFamily=e.fontFamily),n.fontSize&&(n.fontSize=e.fontSize),n.group||(n.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const n=t.getChildDrawingItems();if("add"===i){if(n.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=En.getDrawingStyle(e.styleId);else{const n=this.mapType_StateAndStyleId.get(e._mediaType);i=En.getDrawingStyle(n[t.styleSelector]);const r=()=>{this._changeItemStyle(e,En.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,En.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",r),e._on("deselected",s),e._funcChangeStyleToSelected=r,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!n.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof mi))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const n=this.fabricCanvas.getObjects();let r,s;if(n.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){r=t.getChildDrawingItems();for(let t of r)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(r){for(let t of r){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of mi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=En.getDrawingStyle(t.styleId);else{s=En.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,En.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},n=()=>{this._changeItemStyle(t,En.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of mi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=En.getDrawingStyle(t.styleId);else{s=En.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,En.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},n=()=>{this._changeItemStyle(t,En.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=n.length;if(o)a=n.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;et.toLowerCase())):e=mi.arrMediaTypes,i?i.forEach((t=>t.toLowerCase())):i=mi.arrStyleSelectors;const n=En.getDrawingStyle(t);if(!n)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let r;for(let s of e)if(r=this.mapType_StateAndStyleId.get(s),r)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,n,!0),r[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const n=[];i&Je.DIMT_RECTANGLE&&n.push("rect"),i&Je.DIMT_QUADRILATERAL&&n.push("quad"),i&Je.DIMT_TEXT&&n.push("text"),i&Je.DIMT_ARC&&n.push("arc"),i&Je.DIMT_IMAGE&&n.push("image"),i&Je.DIMT_POLYGON&&n.push("polygon"),i&Je.DIMT_LINE&&n.push("line");const r=[];e&Qe.DIS_DEFAULT&&r.push("default"),e&Qe.DIS_SELECTED&&r.push("selected"),this._setDefaultStyle(t,n.length?n:null,r.length?r:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}Sn.DDN_LAYER_ID=1,Sn.DBR_LAYER_ID=2,Sn.DLR_LAYER_ID=3,Sn.USER_DEFINED_LAYER_BASE_ID=100,Sn.TIP_LAYER_ID=999;class Tn{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new Sn(t,e,{enableRetinaScaling:!1});return i._manager=this,this._arrDrawingLayer.push(i),this._switchPointerEvent(),i}deleteDrawingLayer(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}getAllDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._getFabricCanvas().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){if(!this._arrDrawingLayer.length)return;this._getFabricCanvas().wrapperEl.style.display=t?"block":"none"}_getFabricCanvas(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0].fabricCanvas:null}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class bn extends Ti{constructor(t,e,i,n,r){super(t,{x:e,y:i,width:n,height:0},r),Yi.set(this,void 0),Hi.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&Ge(this,Hi,setTimeout((()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()}),Ve(this,Yi,"f")),"f")}getDuration(){return Ve(this,Yi,"f")}}Yi=new WeakMap,Hi=new WeakMap;class In{constructor(){Xi.add(this),zi.set(this,void 0),qi.set(this,void 0),Zi.set(this,void 0),Ki.set(this,!0),this._drawingLayerManager=new Tn}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const n=document.createElement("canvas");return n.width==t&&n.height==e||(n.width=t,n.height=e),n.style.objectFit=i,n}_createDrawingLayer(t,e,i,n){if(!this._layerBaseCvs){let r;try{r=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==r?void 0:r.width)||1280),i||(i=(null==r?void 0:r.height)||720),n||(n=(null==r?void 0:r.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,n)}const r=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(r,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",r.parentElement),s}createDrawingLayer(){let t;for(let e=Sn.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==Sn.TIP_LAYER_ID){t=e;break}return this._createDrawingLayer(t)}deleteDrawingLayer(t){var e;this._drawingLayerManager.deleteDrawingLayer(t),this._drawingLayerManager.getAllDrawingLayers().length||(null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null)}deleteUserDefinedDrawingLayer(t){if("number"!=typeof t)throw new TypeError("Invalid id.");if(tt.getId()>=0&&t.getId()!==Sn.TIP_LAYER_ID))}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(Ri(e=t)&&b(e.topLeftPoint)&&ii(e.width))||e.width<=0||!ii(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;Ge(this,zi,JSON.parse(JSON.stringify(t)),"f"),Ve(this,zi,"f").coordinateBase||(Ve(this,zi,"f").coordinateBase="view"),Ge(this,Zi,t.duration,"f"),Ve(this,Xi,"m",tn).call(this)}getTipConfig(){return Ve(this,zi,"f")?Ve(this,zi,"f"):null}setTipVisible(t){if("boolean"!=typeof t)throw new TypeError("Invalid value.");this._tip&&(this._tip.set("visible",t),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll()),Ge(this,Ki,t,"f")}isTipVisible(){return Ve(this,Ki,"f")}updateTipMessage(t){if(!Ve(this,zi,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=En.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(Sn.TIP_LAYER_ID)||this._createDrawingLayer(Sn.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=Ve(this,Xi,"m",Ji).call(this,t,Ve(this,zi,"f").topLeftPoint.x,Ve(this,zi,"f").topLeftPoint.y,Ve(this,zi,"f").width,Ve(this,zi,"f").coordinateBase,this._tipStyleId),Ve(this,Xi,"m",Qi).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",Ve(this,Ki,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),Ve(this,qi,"f")&&clearTimeout(Ve(this,qi,"f")),Ve(this,Zi,"f")>=0&&Ge(this,qi,setTimeout((()=>{Ve(this,Xi,"m",$i).call(this)}),Ve(this,Zi,"f")),"f")}}zi=new WeakMap,qi=new WeakMap,Zi=new WeakMap,Ki=new WeakMap,Xi=new WeakSet,Ji=function(t,e,i,n,r,s){const o=new bn(t,e,i,n,s);return o.coordinateBase=r,o},Qi=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},$i=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},tn=function(){if(!this._tip)return;const t=Ve(this,zi,"f");this._tip.coordinateBase=t.coordinateBase,this._tip.setTextRect({x:t.topLeftPoint.x,y:t.topLeftPoint.y,width:t.width,height:0}),this._tip.set("width",this._tip.get("width")),this._tip._drawingLayer&&this._tip._drawingLayer.renderAll()};class xn extends HTMLElement{constructor(){super(),en.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),Ge(this,en,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const n=document.createElement("slot");n.setAttribute("name","content"),e.append(n);const r=document.createElement("slot");r.setAttribute("name","drawing-layer"),e.append(r);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return Ve(this,en,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach((t=>t.remove()))}}en=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",xn);class On extends In{static get engineResourcePath(){return L(vt.engineResourcePaths).dce}static set defaultUIElementURL(t){On._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=On._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",On.engineResourcePath)}static async createInstance(t){const e=new On;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",On.engineResourcePath)),await e.setUIElement(t||On.defaultUIElementURL),e}static _transformCoordinates(t,e,i,n,r,s,o){const a=s/n,h=o/r;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==Ve(this,dn,"f")){if(Ge(this,dn,t,"f"),Ve(this,nn,"m",mn).call(this))Ge(this,an,null,"f"),this._videoContainer=null,this._innerComponent.removeElement("content"),this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block");else if(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none"),!Ve(this,an,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(je.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Ge(this,an,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}Ve(this,nn,"m",mn).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading())}}get _singleFrameMode(){return Ve(this,dn,"f")}get disposed(){return Ve(this,gn,"f")}constructor(){super(),nn.add(this),rn.set(this,void 0),sn.set(this,void 0),on.set(this,void 0),this.containerClassName="dce-video-container",an.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,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,hn.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,ln.set(this,!1),cn.set(this,!1),un.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{Ve(this,nn,"m",wn).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout((()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&Ve(this,nn,"m",yn).call(this))}),this._updateLayersTimeout)},this._windowResizeListener=()=>{On._onLog&&On._onLog("window resize event triggered."),Ve(this,un,"f").width===document.documentElement.clientWidth&&Ve(this,un,"f").height===document.documentElement.clientHeight||(Ve(this,un,"f").width=document.documentElement.clientWidth,Ve(this,un,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},dn.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!Ve(this,nn,"m",mn).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise(((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i},i=(t,e,i,n)=>{t.width==i&&t.height==n||(t.width=i,t.height=n);const r=t.getContext("2d");r.clearRect(0,0,t.width,t.height),r.drawImage(e,0,0)},n=await t(e),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,n,r,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout((()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)}),0)})),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},fn.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,n,r,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(n=o.cropRegion)||void 0===n?void 0:n.top)||0,c=(null===(r=o.cropRegion)||void 0===r?void 0:r.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,n,r,s,o,a,h=[],l)=>{e.forEach((t=>On._transformCoordinates(t,i,n,r,s,o,a)));const c=new Oi({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},l);for(let t of h)c.addNote(t);t.addDrawingItems([c]),Ve(this,fn,"f").push(c)};let m,p;for(let t of a)switch(t.type){case yt.CRIT_ORIGINAL_IMAGE:break;case yt.CRIT_BARCODE:m=this.getDrawingLayer(Sn.DBR_LAYER_ID),p=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==e?void 0:e.isBarcodeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,En.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case yt.CRIT_TEXT_LINE:m=this.getDrawingLayer(Sn.DLR_LAYER_ID),p=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,En.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case yt.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(Sn.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.crossVerificationStatus===xt.CVS_PASSED?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],En.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case yt.CRIT_NORMALIZED_IMAGE:m=this.getDrawingLayer(Sn.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.crossVerificationStatus===xt.CVS_PASSED?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],En.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case yt.CRIT_PARSED_RESULT:break;default:throw new Error("Illegal item type.")}}},gn.set(this,!1),this.eventHandler=new ki,this.eventHandler.on("content:updated",(()=>{Ve(this,rn,"f")&&clearTimeout(Ve(this,rn,"f")),Ge(this,rn,setTimeout((()=>{if(this.disposed)return;let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(t),this.updateConvertedRegion(t)}),0),"f")})),this.eventHandler.on("videoEl:resized",(()=>{Ve(this,sn,"f")&&clearTimeout(Ve(this,sn,"f")),Ge(this,sn,setTimeout((()=>{this.disposed||this._updateVideoContainer()}),0),"f")}))}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Ui(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let n=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!n)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=document.createElement("dce-component"),n.appendChild(this._innerComponent),Ve(this,nn,"m",mn).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(je.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Ge(this,an,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._selRsl&&(this._hideDefaultSelection||Ve(this,nn,"m",mn).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||Ve(this,nn,"m",mn).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||Ve(this,nn,"m",wn).call(this),Ve(this,nn,"m",mn).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),Ve(this,nn,"m",mn).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading()),window.ResizeObserver){this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{var e;On._onLog&&On._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()})));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}Ve(this,un,"f").width=document.documentElement.clientWidth,Ve(this,un,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,n;Ve(this,nn,"m",mn).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),Ve(this,nn,"m",wn).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,Ge(this,an,null,"f"),null===(n=this._videoContainer)||void 0===n||n.remove(),this._videoContainer=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._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let n of e){const e=document.createElement("option");e.value=n.deviceId,e.innerText=n.label,this._selCam.append(e),n.deviceId&&t&&t.deviceId==n.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),n=Math.min(t.width,t.height);e=n<=1080?n+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return Ve(this,an,"f")}isVideoLoaded(){return!(!Ve(this,an,"f")||!this.cameraEnhancer)&&this.cameraEnhancer.isOpen()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!Ve(this,an,"f"))return;if(Ve(this,an,"f").style.objectFit=t,Ve(this,nn,"m",mn).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Ve(this,nn,"m",Cn).call(this,e,this.getConvertedRegion()),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,n;let r,s,o;if(Ve(this,nn,"m",mn).call(this)?(r=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(n=this._cvsSingleFrameMode)||void 0===n?void 0:n.height,o="contain"):(r=null===(t=Ve(this,an,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=Ve(this,an,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!r||!s)throw new Error("Invalid content dimensions.");return{width:r,height:s,objectFit:o}}updateConvertedRegion(t){const e=Mi.convert(this.scanRegion,t.width,t.height);Ge(this,hn,e,"f"),Ve(this,on,"f")&&clearTimeout(Ve(this,on,"f")),Ge(this,on,setTimeout((()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Ve(this,nn,"m",pn).call(this,t,e),Ve(this,nn,"m",Cn).call(this,t,e)}),0),"f")}getConvertedRegion(){return Ve(this,hn,"f")}setScanRegion(t){if(null!=t&&!E(t)&&!O(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=Ve(this,an,"f").videoWidth,i=Ve(this,an,"f").videoHeight,n=this.getVideoFit(),{width:r,height:s}=this._innerComponent.getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===n&&(r/s1){const t=Ve(this,an,"f").videoWidth,e=Ve(this,an,"f").videoHeight,{width:n,height:r}=this._innerComponent.getBoundingClientRect(),s=t/e;if(n/rt.remove())),Ve(this,fn,"f").length=0}dispose(){this._unbindUI(),Ge(this,gn,!0,"f")}}function An(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Rn(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}rn=new WeakMap,sn=new WeakMap,on=new WeakMap,an=new WeakMap,hn=new WeakMap,ln=new WeakMap,cn=new WeakMap,un=new WeakMap,dn=new WeakMap,fn=new WeakMap,gn=new WeakMap,nn=new WeakSet,mn=function(){return"disabled"!==this._singleFrameMode},pn=function(t,e){!e||0===e.x&&0===e.y&&e.width===t.width&&e.height===t.height?this.clearScanRegionMask():this.setScanRegionMask(e.x,e.y,e.width,e.height)},_n=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},vn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},yn=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},wn=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Cn=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:n,objectFit:r}=t;e||(e={x:0,y:0,width:i,height:n});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/n;let l,c,u,d,f=1;if("contain"===r)a66||"Safari"===kn.browser&&kn.version>13||"OPR"===kn.browser&&kn.version>43||"Edge"===kn.browser&&kn.version,"function"==typeof SuppressedError&&SuppressedError;class jn{static multiply(t,e){const i=[];for(let n=0;n<3;n++){const r=e.slice(3*n,3*n+3);for(let e=0;e<3;e++){const n=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*r[i]),0);i.push(n)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return jn.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),n=Math.sin(e);return jn.multiply(t,[i,-n,0,n,i,0,0,0,1])}static scale(t,e,i){return jn.multiply(t,[e,0,0,0,i,0,0,0,1])}}var Un,Vn,Gn,Wn,Yn,Hn,Xn,zn,qn,Zn,Kn,Jn,Qn,$n,tr,er,ir,nr,rr,sr,or,ar,hr,lr,cr,ur,dr,fr,gr,mr,pr,_r,vr,yr,wr,Cr,Er,Sr,Tr,br,Ir,xr,Or,Ar,Rr,Dr,Lr,Mr,Fr,Pr;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(Un||(Un={}));class kr{static get version(){return"1.1.3"}static get webGLSupported(){return void 0===kr._webGLSupported&&(kr._webGLSupported=!!document.createElement("canvas").getContext("webgl")),kr._webGLSupported}get disposed(){return Bn(this,Xn,"f")}constructor(){Vn.set(this,Un.RGBA),Gn.set(this,null),Wn.set(this,null),Yn.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,Hn.set(this,null),Xn.set(this,!1)}drawImage(t,e,i,n,r,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!n)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if((null==s?void 0:s.bUseWebGL)&&!kr.webGLSupported)throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;kr._onLog&&(o=Date.now(),kr._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=n,u=0,d=0,f=i,g=n;r&&(r.sx&&(a=Math.round(r.sx)),r.sy&&(h=Math.round(r.sy)),r.sWidth&&(l=Math.round(r.sWidth)),r.sHeight&&(c=Math.round(r.sHeight)),r.dx&&(u=Math.round(r.dx)),r.dy&&(d=Math.round(r.dy)),r.dWidth&&(f=Math.round(r.dWidth)),r.dHeight&&(g=Math.round(r.dHeight)));let m,p=Un.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!kr.webGLSupported||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){kr._onLog&&kr._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=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},n=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},r=(t,e,i)=>{const n=t.createShader(e);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(n)}.`);throw e.name="WebGLError",e}return n},s="\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\n\nuniform mat3 u_matrix;\nuniform mat3 u_textureMatrix;\n\nvarying vec2 v_texCoord;\nvoid main(void) {\ngl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\nv_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n}";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_image;\nuniform float uColorFactor;\n\nvoid main() {\nvec4 sample = texture2D(u_image, v_texCoord);\nfloat grey = 0.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\ngl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n}`,h=n(t,[r(t,t.VERTEX_SHADER,s),r(t,t.FRAGMENT_SHADER,a)]);Nn(this,Wn,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),Nn(this,Yn,e(t),"f"),Nn(this,Gn,i(t),"f"),Nn(this,Vn,p,"f")}const r=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const n=t.RGBA,r=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,n,r,s,i)},v=(t,e,s,o)=>{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),r(t,s.positions,e.attribLocations.vertexPosition),r(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[Un.GREY,Un.GREY32].includes(p)?1:0);let m,_,v=jn.translate(jn.identity(),-1,-1);v=jn.scale(v,2,2),v=jn.scale(v,1/t.canvas.width,1/t.canvas.height),m=jn.translate(v,u,d),m=jn.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=jn.translate(jn.identity(),a/i,h/n),_=jn.scale(_,l/i,c/n),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,Bn(this,Gn,"f"),e),v(t,Bn(this,Wn,"f"),Bn(this,Yn,"f"),Bn(this,Gn,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){kr._onLog&&kr._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return kr._onLog&&kr._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===Un.GREY?Un.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return kr._onLog&&kr._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,n,r,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let n,r=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(r=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),n=new Uint8Array(i.buffer,0,4*o*a)):(n=new Uint8Array(4*o*a),e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,n))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(r,s,o,a),n=new Uint8Array(e.data.buffer),null==i||i.set(n)}return n}transformPixelFormat(t,e,i,n){let r,s;if(kr._onLog&&(r=Date.now(),kr._onLog("transformPixelFormat(), START: "+r)),e===i)return kr._onLog&&kr._onLog("transformPixelFormat() end. Costs: "+(Date.now()-r)),n?new Uint8Array(t):t;const o=[Un.RGBA,Un.RBGA,Un.GRBA,Un.GBRA,Un.BRGA,Un.BGRA];if(o.includes(e))if(i===Un.GREY){s=new Uint8Array(t.length/4);for(let e=0;eh||e.sy+e.sHeight>l)throw new Error("Invalid position.");null===(n=kr._onLog)||void 0===n||n.call(kr,"getImageData(), START: "+(c=Date.now()));const d=Math.round(e.sx),f=Math.round(e.sy),g=Math.round(e.sWidth),m=Math.round(e.sHeight),p=Math.round(e.dWidth),_=Math.round(e.dHeight);let v,y=(null==i?void 0:i.pixelFormat)||Un.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(Un.GREY===y&&w.length{this.disposed||n.includes(r)&&r.apply(i.target,s)}),0);else try{o=r.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){Rn(this,qn,!0,"f")}}zn=new WeakMap,qn=new WeakMap;const Nr=(t,e,i,n)=>{if(!i)return t;let r=e+Math.round((t-e)/i)*i;return n&&(r=Math.min(r,n)),r};class jr{static get version(){return"2.0.18"}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 findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find((t=>e.includes(t.label.toLowerCase())));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],n=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],r=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!r.length)return null;const s=r.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const o=r.find((t=>{const e=t.label.toLowerCase();return n.some((t=>e.includes(t)))}));return o?o.deviceId:r[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(kn.OS))return jr.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(kn.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise((async(n,r)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),n(t)},l=t=>{s&&clearTimeout(s),o(),r(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise((t=>{g=t})),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise((t=>{setTimeout(t,1e3)})),!a){i&&(s=setTimeout((()=>{o(),r(new Error("Failed to play video. Timeout."))}),i)),await m;try{await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a)try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}}))}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let n;try{n=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==n||n.getTracks().forEach((t=>{t.stop()}))}return{ok:!0}}get state(){if(!An(this,hr,"f"))return"closed";if("pending"===An(this,hr,"f"))return"opening";if("fulfilled"===An(this,hr,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?jr.isStorageAvailable("localStorage")?Rn(this,rr,!0,"f"):(Rn(this,rr,!1,"f"),console.warn("Local storage is unavailable")):Rn(this,rr,!1,"f")}get ifSaveLastUsedCamera(){return An(this,rr,"f")}get isVideoPlaying(){return!(!An(this,Jn,"f")||An(this,Jn,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,n;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=An(this,gr,"f"))||void 0===e||e.removeEventListener("click",An(this,fr,"f")),null===(i=An(this,gr,"f"))||void 0===i||i.removeEventListener("touchend",An(this,fr,"f")),null===(n=An(this,gr,"f"))||void 0===n||n.removeEventListener("touchmove",An(this,dr,"f")),Rn(this,gr,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(kn.OS)?(t.addEventListener("touchend",An(this,fr,"f")),t.addEventListener("touchmove",An(this,dr,"f"))):t.addEventListener("click",An(this,fr,"f")))}get tapFocusEventBoundEl(){return An(this,gr,"f")}get disposed(){return An(this,Sr,"f")}constructor(t){var e,i;Kn.add(this),Jn.set(this,null),Qn.set(this,void 0),$n.set(this,(()=>{"opened"===this.state&&An(this,vr,"f").fire("resumed",null,{target:this,async:!1})})),tr.set(this,(()=>{An(this,vr,"f").fire("paused",null,{target:this,async:!1})})),er.set(this,void 0),ir.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],nr.set(this,void 0),rr.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,sr.set(this,void 0),or.set(this,!0),ar.set(this,void 0),hr.set(this,void 0),lr.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},cr.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,n;const r=window.getComputedStyle(An(this,Jn,"f")).objectFit,s=this.getResolution(),o=An(this,Jn,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=An(this,Jn,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===r)d>u?(f=l/s.width,i=(t-a)/f,n=(e-h-(c-l/d)/2)/f):(f=c/s.height,n=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==r)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,n=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,n=(e-h+(l/d-c)/2)/f)}return{x:i,y:n}},ur.set(this,!1),dr.set(this,(()=>{Rn(this,ur,!0,"f")})),fr.set(this,(async t=>{var e;if(An(this,ur,"f"))return void Rn(this,ur,!1,"f");if(!An(this,cr,"f"))return;if(!this.isVideoPlaying)return;if(!An(this,Qn,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,n=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,n=t.changedTouches[0].clientY}const r=this.getResolution(),s=2*Math.round(Math.min(r.width,r.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,n)}catch(t){}if(o.x<0||o.x>r.width||o.y<0||o.y>r.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;jr._onLog&&(c=Date.now());try{await An(this,Kn,"m",Mr).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(jr._onLog)throw jr._onLog(t),t}jr._onLog&&jr._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout((()=>{var t;jr._onLog&&jr._onLog("Back to continuous focus."),null===(t=An(this,Qn,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime),An(this,vr,"f").fire("tapfocus",null,{target:this,async:!1})})),gr.set(this,null),mr.set(this,1),pr.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!An(this,Jn,"f"))return;const t=An(this,mr,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)An(this,Jn,"f").style.transform="";else{const e=window.getComputedStyle(An(this,Jn,"f")).objectFit,i=An(this,Jn,"f").videoWidth,n=An(this,Jn,"f").videoHeight,{width:r,height:s}=An(this,Jn,"f").getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=r/s,a=i/n;let h=1;"contain"===e?h=oo?s/(i/t):r/(n/t));const l=h*(1-1/t)*(i/2-An(this,pr,"f").x),c=h*(1-1/t)*(n/2-An(this,pr,"f").y);An(this,Jn,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},_r.set(this,(function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===Un.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(jr._onLog&&jr._onLog("document visible. video paused: "+(null===(t=An(this,Jn,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){jr._onLog&&jr._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){jr._onLog&&jr._onLog("document visible. 1st resume video failed, try open instead.")}e||await An(this,Kn,"m",Or).call(this)}if(await new Promise((t=>setTimeout(t,300))),!this.isVideoPlaying){jr._onLog&&jr._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){jr._onLog&&jr._onLog("document visible. 2rd resume video failed, try open instead.")}e||await An(this,Kn,"m",Or).call(this)}}}else"hidden"===document.visibilityState&&(jr._onLog&&jr._onLog("document hidden. video paused: "+(null===(e=An(this,Jn,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())})),Sr.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout((()=>{jr.onWarning&&jr.onWarning("The browser is too old or the page is loaded from an insecure origin.")}),0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),Rn(this,vr,new Br,"f"),this.imageDataGetter=new kr,document.addEventListener("visibilitychange",An(this,Er,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",An(this,$n,"f")),t.addEventListener("pause",An(this,tr,"f")),Rn(this,Jn,t,"f")}getVideoEl(){return An(this,Jn,"f")}releaseVideoEl(){var t,e;null===(t=An(this,Jn,"f"))||void 0===t||t.removeEventListener("play",An(this,$n,"f")),null===(e=An(this,Jn,"f"))||void 0===e||e.removeEventListener("pause",An(this,tr,"f")),Rn(this,Jn,null,"f")}isVideoLoaded(){return!!An(this,Jn,"f")&&4==An(this,Jn,"f").readyState}async open(){if(An(this,ar,"f")&&!An(this,or,"f")){if("pending"===An(this,hr,"f"))return An(this,ar,"f");if("fulfilled"===An(this,hr,"f"))return}An(this,vr,"f").fire("before:open",null,{target:this}),await An(this,Kn,"m",Or).call(this),An(this,vr,"f").fire("played",null,{target:this,async:!1}),An(this,vr,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;An(this,vr,"f").fire("before:close",null,{target:this});const t=An(this,ar,"f");if(An(this,Kn,"m",Rr).call(this),t&&"pending"===An(this,hr,"f")){try{await t}catch(t){}if(!1===An(this,or,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}Rn(this,ar,null,"f"),Rn(this,hr,null,"f"),An(this,vr,"f").fire("closed",null,{target:this,async:!1})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");An(this,Jn,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await An(this,Jn,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof An(this,er,"f").video&&(An(this,er,"f").video={}),delete An(this,er,"f").video.facingMode,An(this,er,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&An(this,or,"f"))){An(this,vr,"f").fire("before:camera:change",[],{target:this,async:!1}),await An(this,Kn,"m",Ar).call(this);try{this.resetSoftwareScale()}catch(t){}return An(this,ir,"f")}}async switchToFrontCamera(t){if("object"!=typeof An(this,er,"f").video&&(An(this,er,"f").video={}),(null==t?void 0:t.resolution)&&(An(this,er,"f").video.width={ideal:t.resolution.width},An(this,er,"f").video.height={ideal:t.resolution.height}),delete An(this,er,"f").video.deviceId,An(this,er,"f").video.facingMode={exact:"user"},Rn(this,nr,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&An(this,or,"f"))){An(this,vr,"f").fire("before:camera:change",[],{target:this,async:!1}),An(this,Kn,"m",Ar).call(this);try{this.resetSoftwareScale()}catch(t){}return An(this,ir,"f")}}getCamera(){var t;if(An(this,ir,"f"))return An(this,ir,"f");{let e=(null===(t=An(this,er,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});n=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}else n=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));const r=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind));return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof An(this,er,"f").video&&(An(this,er,"f").video={}),i?(An(this,er,"f").video.width={exact:t},An(this,er,"f").video.height={exact:e}):(An(this,er,"f").video.width={ideal:t},An(this,er,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&An(this,or,"f"))return null;An(this,vr,"f").fire("before:resolution:change",[],{target:this,async:!1}),await An(this,Kn,"m",Ar).call(this);try{this.resetSoftwareScale()}catch(t){}const n=this.getResolution();return{width:n.width,height:n.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&An(this,Jn,"f"))return{width:An(this,Jn,"f").videoWidth,height:An(this,Jn,"f").videoHeight};if(An(this,Qn,"f")){const t=An(this,Qn,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:An(this,Jn,"f").videoWidth,height:An(this,Jn,"f").videoHeight};{const t={width:0,height:0};let e=An(this,er,"f").video.width||0,i=An(this,er,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,n,r,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=An(this,wr,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){d=null===(u=An(this,ir,"f"))||void 0===u?void 0:u.deviceId;let e=An(this,wr,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],An(this,wr,"f").set(d,e),Rn(this,lr,!0,"f");try{for(let t of this.detectedResolutions){await An(this,Qn,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),An(this,Kn,"m",br).call(this);const i=An(this,Qn,"f").getSettings(),n={width:i.width,height:i.height};f(d,n)||e.push({width:n.width,height:n.height})}}catch(t){throw An(this,Kn,"m",Rr).call(this),Rn(this,lr,!1,"f"),t}try{await An(this,Kn,"m",Or).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{Rn(this,lr,!1,"f")}return e}{const e=async(t,e,i)=>{const n={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let r=null;try{r=await navigator.mediaDevices.getUserMedia(n)}catch(t){return null}if(!r)return null;const s=r.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=r,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach((t=>{t.stop()})),o};let i=(null===(s=null===(r=null===(n=An(this,er,"f"))||void 0===n?void 0:n.video)||void 0===r?void 0:r.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=An(this,er,"f"))||void 0===o?void 0:o.video)||void 0===a?void 0:a.deviceId)||void 0===h?void 0:h.ideal)||(null===(c=null===(l=An(this,er,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=An(this,wr,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],An(this,wr,"f").set(i,u);for(let t of this.detectedResolutions){const n=await e(i,t.width,t.height);n&&!f(i,n)&&u.push({width:n.width,height:n.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");Rn(this,er,JSON.parse(JSON.stringify(t)),"f"),Rn(this,nr,null,"f"),e&&An(this,Kn,"m",Ar).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(An(this,er,"f")))}resetMediaStreamConstraints(){Rn(this,er,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!An(this,Qn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return An(this,Qn,"f").getCapabilities?An(this,Qn,"f").getCapabilities():{}}getCameraSettings(){if(!An(this,Qn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return An(this,Qn,"f").getSettings()}async turnOnTorch(){if(!An(this,Qn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await An(this,Qn,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!An(this,Qn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await An(this,Qn,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!An(this,Qn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Nr(t,n.min,n.step,n.max)),await An(this,Qn,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!An(this,Qn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Nr(t,n.min,n.step,n.max)),await An(this,Qn,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!An(this,Qn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!n)throw Error("Not supported.");e&&(tn.max&&(t=n.max));const r=this.getResolution();return await An(this,Qn,"f").applyConstraints({width:{ideal:Math.max(r.width,r.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!An(this,Qn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),n=null==i?void 0:i.focusMode,r=null==i?void 0:i.focusDistance;if(!n)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!n.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!r)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(ir.max&&(i=r.max),i=Nr(i,r.min,r.step,r.max)),this._focusParameters.focusArea=null,await An(this,Qn,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,n=t.area.height;if(!i||!n){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),n||(n=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:n},await An(this,Kn,"m",Mr).call(this,e,i,n)}}}else this._focusParameters.focusArea=null,await An(this,Qn,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async enableTapToFocus(){Rn(this,cr,!0,"f")}disableTapToFocus(){Rn(this,cr,!1,"f")}isTapToFocusEnabled(){return An(this,cr,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"!==this.state)throw new Error("Video is not playing.");t.centerPoint?An(this,Kn,"m",Fr).call(this,t.centerPoint):this.resetScaleCenter();try{if(An(this,Kn,"m",Pr).call(this,An(this,pr,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*An(this,mr,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!An(this,Qn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Nr(t,n.min,n.step,n.max)),await An(this,Qn,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&An(this,Kn,"m",Fr).call(this,e),Rn(this,mr,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return An(this,mr,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();Rn(this,pr,{x:t.width/2,y:t.height/2},"f")}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(An(this,lr,"f"))return null;const e=Date.now();jr._onLog&&jr._onLog("getFrameData() START: "+e);const i=An(this,Jn,"f").videoWidth,n=An(this,Jn,"f").videoHeight;let r={sx:0,sy:0,sWidth:i,sHeight:n,dWidth:i,dHeight:n};(null==t?void 0:t.position)&&(r=JSON.parse(JSON.stringify(t.position)));let s=Un.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=An(this,mr,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=An(this,pr,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,r=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))r=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.scaleCenter.y)/100*n}if(isNaN(e)||isNaN(r))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(r)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==n)return null;1!==o&&(r.sWidth=Math.round(r.sWidth/o),r.sHeight=Math.round(r.sHeight/o),r.sx=Math.round((1-1/o)*a.x+r.sx/o),r.sy=Math.round((1-1/o)*a.y+r.sy/o));const l=this.imageDataGetter.getImageData(An(this,Jn,"f"),r,{pixelFormat:s,bufferContainer:h});if(!l)return null;const c=Date.now();return jr._onLog&&jr._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:An(this,_r,"f")}}on(t,e){if(!An(this,yr,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);An(this,vr,"f").on(t,e)}off(t,e){An(this,vr,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),An(this,vr,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",An(this,Er,"f")),Rn(this,Sr,!0,"f")}}var Ur,Vr,Gr,Wr,Yr,Hr,Xr,zr,qr,Zr,Kr,Jr,Qr,$r,ts,es,is,ns,rs,ss,os,as,hs,ls,cs,us,ds,fs,gs,ms,ps,_s,vs,ys,ws;Jn=new WeakMap,Qn=new WeakMap,$n=new WeakMap,tr=new WeakMap,er=new WeakMap,ir=new WeakMap,nr=new WeakMap,rr=new WeakMap,sr=new WeakMap,or=new WeakMap,ar=new WeakMap,hr=new WeakMap,lr=new WeakMap,cr=new WeakMap,ur=new WeakMap,dr=new WeakMap,fr=new WeakMap,gr=new WeakMap,mr=new WeakMap,pr=new WeakMap,_r=new WeakMap,vr=new WeakMap,yr=new WeakMap,wr=new WeakMap,Cr=new WeakMap,Er=new WeakMap,Sr=new WeakMap,Kn=new WeakSet,Tr=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(An(this,nr,"f"))delete t.video.facingMode,t.video.deviceId={exact:An(this,nr,"f")};else if(this.ifSaveLastUsedCamera&&jr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(kn.OS)?(await this._getCameras(!1),An(this,Kn,"m",br).call(this),e=jr.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(kn.OS)||(await this._getCameras(!1),An(this,Kn,"m",br).call(this),e=jr.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const n=await e(i);n&&(delete t.video.facingMode,t.video.deviceId={exact:n})}return t},br=function(){if(An(this,or,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},Ir=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;try{jr._onLog&&jr._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const r=async t=>{for(let r of e){r&&(await new Promise((t=>setTimeout(t,r))),An(this,Kn,"m",br).call(this));try{jr._onLog&&jr._onLog("ask "+JSON.stringify(t)),n=await navigator.mediaDevices.getUserMedia(t),An(this,Kn,"m",br).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,jr._onLog&&jr._onLog(t.message||t)}}};if(await r(t),n||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await r(t)),!n&&t.video.facingMode&&(delete t.video.facingMode,await r(t)),n||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await r(t))),!n)throw i;return n}catch(t){throw null==n||n.getTracks().forEach((t=>{t.stop()})),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},xr=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach((t=>{t.stop()})),this._mediaStream=null),Rn(this,Qn,null,"f")},Or=async function(){Rn(this,or,!1,"f");const t=Rn(this,sr,Symbol(),"f");if(An(this,ar,"f")&&"pending"===An(this,hr,"f")){try{await An(this,ar,"f")}catch(t){}An(this,Kn,"m",br).call(this)}if(t!==An(this,sr,"f"))return;const e=Rn(this,ar,(async()=>{Rn(this,hr,"pending","f");try{if(this.videoSrc){if(!An(this,Jn,"f"))throw new Error("'videoEl' should be set.");await jr.playVideo(An(this,Jn,"f"),this.videoSrc,this.cameraOpenTimeout),An(this,Kn,"m",br).call(this)}else{let t=await An(this,Kn,"m",Tr).call(this);An(this,Kn,"m",xr).call(this);let e=await An(this,Kn,"m",Ir).call(this,t);await this._getCameras(!1),An(this,Kn,"m",br).call(this);const i=()=>{const t=e.getVideoTracks();let i,n;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,n=e;break}}return n},n=An(this,er,"f");if("object"==typeof n.video){let r=n.video.facingMode;if(r instanceof Array&&r.length&&(r=r[0]),"object"==typeof r&&(r=r.exact||r.ideal),!(An(this,nr,"f")||this.ifSaveLastUsedCamera&&jr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||n.video.deviceId)){const n=i(),s=jr.findBestCamera(this._arrCameras,r,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==n?void 0:n.deviceId)&&(e.getTracks().forEach((t=>{t.stop()})),t.video.deviceId={exact:s},e=await An(this,Kn,"m",Ir).call(this,t),An(this,Kn,"m",br).call(this))}}const r=i();(null==r?void 0:r.deviceId)&&(Rn(this,nr,r&&r.deviceId,"f"),this.ifSaveLastUsedCamera&&jr.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",An(this,nr,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),An(this,Jn,"f")&&(await jr.playVideo(An(this,Jn,"f"),e,this.cameraOpenTimeout),An(this,Kn,"m",br).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&Rn(this,Qn,s[0],"f"),Rn(this,ir,r,"f")}}catch(t){throw An(this,Kn,"m",Rr).call(this),Rn(this,hr,null,"f"),t}Rn(this,hr,"fulfilled","f")})(),"f");return e},Ar=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=An(this,ir,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await An(this,Kn,"m",Or).call(this);const n=this.getResolution();e&&e!==An(this,ir,"f").deviceId&&An(this,vr,"f").fire("camera:changed",[An(this,ir,"f").deviceId,e],{target:this,async:!1}),i.width==n.width&&i.height==n.height||An(this,vr,"f").fire("resolution:changed",[{width:n.width,height:n.height},{width:i.width,height:i.height}],{target:this,async:!1}),An(this,vr,"f").fire("played",null,{target:this,async:!1})},Rr=function(){An(this,Kn,"m",xr).call(this),Rn(this,ir,null,"f"),An(this,Jn,"f")&&(An(this,Jn,"f").srcObject=null,this.videoSrc&&(An(this,Jn,"f").pause(),An(this,Jn,"f").currentTime=0)),Rn(this,or,!0,"f");try{this.resetSoftwareScale()}catch(t){}},Dr=async function t(e,i){const n=t=>{if(!An(this,Qn,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){An(this,Qn,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;i=Nr(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await An(this,Qn,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),n(e),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise((t=>{setTimeout(t,r)})),n(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h),a>l.width&&(a=l.width),h>l.height&&(h=l.height),s<0?s=0:s+a>l.width&&(s=l.width-a),o<0?o=0:o+h>l.height&&(o=l.height-h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(An(this,Jn,"f"),{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:Un.RGBA,bufferContainer:d}))return An(this,Kn,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await An(this,Kn,"m",t).call(this,e,o,a,r,s,c,u)}else{let h=await An(this,Kn,"m",Dr).call(this,e,c);if(a>h)return await An(this,Kn,"m",t).call(this,e,o,a,r,s,c,h);if(a==h)return await An(this,Kn,"m",t).call(this,e,o,a,c,h);let u=await An(this,Kn,"m",Dr).call(this,e,l);if(u>a&&ao.width||h<0||h>o.height)throw new Error("Invalid 'centerPoint'.");let l=0;if(e.endsWith("px"))l=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");l=parseFloat(e)/100*o.width}if(isNaN(l)||l<0)throw new Error("Invalid 'width'.");let c=0;if(i.endsWith("px"))c=parseFloat(i);else{if(!i.endsWith("%"))throw new Error("Invalid 'height'.");c=parseFloat(i)/100*o.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==An(this,mr,"f")){const t=An(this,mr,"f"),e=An(this,pr,"f");l/=t,c/=t,a=(1-1/t)*e.x+a/t,h=(1-1/t)*e.y+h/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const u={focusL:a,focusT:h,focusW:l,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let n=Nr(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=Nr(Math.sqrt((e||this._focusParameters.fds.step)*n),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Nr(Math.sqrt(n*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await An(this,Kn,"m",Dr).call(this,t,s),a=await An(this,Kn,"m",Dr).call(this,t,r),h=await An(this,Kn,"m",Dr).call(this,t,n);if(a>h&&ho&&a>o){let e=await An(this,Kn,"m",Dr).call(this,t,i);const r=await An(this,Kn,"m",Lr).call(this,t,n,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,r}if(a==h&&hh){const e=await An(this,Kn,"m",Lr).call(this,t,n,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,n,r)},Fr=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,n=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))n=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(n))throw new Error("Invalid scale center.");Rn(this,pr,{x:i,y:n},"f")},Pr=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},jr.browserInfo=kn,jr.onWarning=null===(Zn=null===window||void 0===window?void 0:window.console)||void 0===Zn?void 0:Zn.warn;class Cs{constructor(t){Ur.add(this),Vr.set(this,void 0),Gr.set(this,0),Wr.set(this,void 0),Yr.set(this,0),Hr.set(this,!1),Ge(this,Vr,t,"f")}startCharging(){Ve(this,Hr,"f")||(Cs._onLog&&Cs._onLog("start charging."),Ve(this,Ur,"m",zr).call(this),Ge(this,Hr,!0,"f"))}stopCharging(){Ve(this,Wr,"f")&&clearTimeout(Ve(this,Wr,"f")),Ve(this,Hr,"f")&&(Cs._onLog&&Cs._onLog("stop charging."),Ge(this,Gr,Date.now()-Ve(this,Yr,"f"),"f"),Ge(this,Hr,!1,"f"))}}Vr=new WeakMap,Gr=new WeakMap,Wr=new WeakMap,Yr=new WeakMap,Hr=new WeakMap,Ur=new WeakSet,Xr=function(){vt.cfd(1),Cs._onLog&&Cs._onLog("charge 1.")},zr=function t(){0==Ve(this,Gr,"f")&&Ve(this,Ur,"m",Xr).call(this),Ge(this,Yr,Date.now(),"f"),Ve(this,Wr,"f")&&clearTimeout(Ve(this,Wr,"f")),Ge(this,Wr,setTimeout((()=>{Ge(this,Gr,0,"f"),Ve(this,Ur,"m",t).call(this)}),Ve(this,Vr,"f")-Ve(this,Gr,"f")),"f")};class Es{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-Ve(this,qr,"f",Jr)<100)){if(Ge(this,qr,e,"f",Jr),Ve(this,qr,"f",Zr).size&&(t=Ve(this,qr,"f",Zr).values().next().value,this.beepSoundSource==t.src?(Ve(this,qr,"f",Zr).delete(t),t.play()):t=null),!t)if(Ve(this,qr,"f",Kr).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout((()=>{Ve(this,qr,"f",Kr).delete(t)}),2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",(()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,Ve(this,qr,"f",Kr).delete(t),Ve(this,qr,"f",Zr).add(t)}))}else Ve(this,qr,"f",Qr)||(Ge(this,qr,!0,"f",Qr),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&Ve(this,qr,"f",Kr).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(Es.vibrateDuration)}}}qr=Es,Zr={value:new Set},Kr={value:new Set},Jr={value:0},Qr={value:!1},Es.allowBeep=!0,Es.beepSoundSource="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",Es.allowVibrate=!0,Es.vibrateDuration=300;const Ss=new Map([[Un.GREY,a.IPF_GRAYSCALED],[Un.RGBA,a.IPF_ABGR_8888]]),Ts="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};class bs extends J{static set _onLog(t){Ge(bs,ts,t,"f",es),jr._onLog=t,Cs._onLog=t}static get _onLog(){return Ve(bs,ts,"f",es)}static async detectEnvironment(){return await(async()=>({wasm:We,worker:Ye,getUserMedia:He,camera:await Xe(),browser:je.browser,version:je.version,OS:je.OS}))()}static async testCameraAccess(){const t=await jr.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(t){var e,i;if(t&&!(t instanceof On))throw new TypeError("Invalid view.");if(null===(e=gt.license)||void 0===e?void 0:e.LicenseManager){if(!(null===(i=gt.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await vt.loadWasm(["license"]),await gt.license.dynamsoft()}const n=new bs(t);return bs.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{bs.onWarning&&bs.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{bs.onWarning&&bs.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),n}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");Ge(this,rs,t,"f")}get singleFrameMode(){return Ve(this,rs,"f")}get _isFetchingStarted(){return Ve(this,cs,"f")}get disposed(){return Ve(this,ms,"f")}constructor(t){if(super(),$r.add(this),is.set(this,"closed"),ns.set(this,void 0),this.isTorchOn=void 0,rs.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},ss.set(this,((t,e,i,n)=>{const r=Date.now(),s={sx:n.x,sy:n.y,sWidth:n.width,sHeight:n.height,dWidth:n.width,dHeight:n.height},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const h=this.cameraManager.imageDataGetter.getImageData(t,s,{pixelFormat:this.getPixelFormat()===a.IPF_GRAYSCALED?Un.GREY:Un.RGBA});let l=null;if(h){const t=Date.now();let o;o=h.pixelFormat===Un.GREY?h.width:4*h.width;let a=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(a=!1),l={bytes:h.data,width:h.width,height:h.height,stride:o,format:Ss.get(h.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:Tt.ITT_FILE_IMAGE,isCropped:a,cropRegion:{left:n.x,top:n.y,right:n.x+n.width,bottom:n.y+n.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:h.width,currentHeight:h.height,timeSpent:t-r,timeStamp:t},toCanvas:Ve(this,os,"f"),isDCEFrame:!0}}return l})),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():Mi.convert(Ve(this,hs,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height});const i=Ve(this,ss,"f").call(this,t,t.width,t.height,e);Ve(this,ns,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},os.set(this,(function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.format===a.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(je.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",(()=>{Ve(this,gs,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("camera:changed",(()=>{this.clearBuffer()})),this._on("before:resolution:change",(()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("resolution:changed",(()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})})),this._on("paused",(()=>{Ve(this,gs,"f").stopCharging();const t=this.cameraView;t&&t.disposed})),this._on("resumed",(()=>{const t=this.cameraView;t&&t.disposed})),this._on("tapfocus",(()=>{Ve(this,ds,"f").tapToFocus&&Ve(this,gs,"f").startCharging()})),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,n,r,s;if(Ve(this,$r,"m",ps).call(this)||!this.isOpen()||this.isPaused())return;const o=t.intermediateResultUnits;bs._onLog&&(bs._onLog("intermediateResultUnits:"),bs._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===Ot.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===Ot.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(bs._onLog&&(bs._onLog("hasLocalizedBarcodes:"),bs._onLog(h)),Ve(this,ds,"f").autoZoom||Ve(this,ds,"f").enhancedFocus)if(a)Ve(this,fs,"f").autoZoomInFrameArray.length=0,Ve(this,fs,"f").autoZoomOutFrameCount=0,Ve(this,fs,"f").frameArrayInIdealZoom.length=0,Ve(this,fs,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),Ve(this,ds,"f").autoZoom&&Ve(this,gs,"f").startCharging()},a=async t=>{await this.setFocus(t),Ve(this,ds,"f").enhancedFocus&&Ve(this,gs,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(n=h.cropRegion)||void 0===n?void 0:n.top)||0,u=(null===(r=h.cropRegion)||void 0===r?void 0:r.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,n,r;{const t=this.video.videoWidth*(1-Ve(this,fs,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+Ve(this,fs,"f").autoZoomDetectionArea)/2,i=e,n=t,s=this.video.videoHeight*(1-Ve(this,fs,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+Ve(this,fs,"f").autoZoomDetectionArea)/2;r=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:n,y:a}]}bs._onLog&&(bs._onLog("detectionArea:"),bs._onLog(r));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let n=!1;const r=t.length;if(r<=2)return!1;for(let s=0;s0!=Ni(a.y-i)>0&&Ni(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(n=!n)}return n}(e,t.x,t.y)},n=(t,e)=>!!(ji([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||ji([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||ji([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||ji([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(n([e[0].x,e[0].y,e[1].x,e[1].y],t)||n([e[1].x,e[1].y,e[2].x,e[2].y],t)||n([e[2].x,e[2].y,e[3].x,e[3].y],t)||n([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of o)if(e.unitType===Ot.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach((t=>{On._transformCoordinates(t,l,c,u,d,f,g)})),t(r,e)&&s.push(i)}if(bs._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=En.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===Ot.IRUT_LOCALIZED_BARCODES)for(let n of i.localizedBarcodes){if(!n)continue;const i=n.location.points,r=new Ci({points:i},e);t.addDrawingItems([r])}}}if(bs._onLog&&(bs._onLog("intersectedResults:"),bs._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter((t=>t.possibleFormats==Ts.BF_QR_CODE||t.possibleFormats==Ts.BF_DATAMATRIX));if(t.length||(t=s.filter((t=>t.possibleFormats==Ts.BF_ONED)),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,n=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(n-g/2)*(n-g/2)};a=t[0];let i=e(a);if(1!=t.length)for(let n=1;n1.1*a.confidence||t[n].confidence>.9*a.confidence&&ri&&s>i&&o>i&&h>i&&m.result.moduleSize{})),Ve(this,fs,"f").autoZoomInFrameArray.filter((t=>!0===t)).length>=Ve(this,fs,"f").autoZoomInFrameLimit[1]){Ve(this,fs,"f").autoZoomInFrameArray.length=0;const i=[(.5-n)/(.5-r),(.5-n)/(.5-s),(.5-n)/(.5-o),(.5-n)/(.5-h)].filter((t=>t>0)),a=Math.min(...i,Ve(this,fs,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/Ve(this,fs,"f").autoZoomInMaxTimes),Ve(this,fs,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max(Ve(this,fs,"f").minValue,u),u=Math.min(Ve(this,fs,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(Ve(this,fs,"f").autoZoomInFrameArray.length=0,Ve(this,fs,"f").frameArrayInIdealZoom.push(!0),Ve(this,fs,"f").frameArrayInIdealZoom.splice(0,Ve(this,fs,"f").frameArrayInIdealZoom.length-Ve(this,fs,"f").frameLimitInIdealZoom[0]),Ve(this,fs,"f").frameArrayInIdealZoom.filter((t=>!0===t)).length>=Ve(this,fs,"f").frameLimitInIdealZoom[1]&&(Ve(this,fs,"f").frameArrayInIdealZoom.length=0,Ve(this,ds,"f").enhancedFocus)){const e=m.points;try{await a({mode:"manual",area:{centerPoint:{x:(e[0].x+e[2].x)/2+"px",y:(e[0].y+e[2].y)/2+"px"},width:e[2].x-e[0].x+"px",height:e[2].y-e[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}if(!Ve(this,ds,"f").autoZoom&&Ve(this,ds,"f").enhancedFocus&&(Ve(this,fs,"f").autoFocusFrameArray.push(!0),Ve(this,fs,"f").autoFocusFrameArray.splice(0,Ve(this,fs,"f").autoFocusFrameArray.length-Ve(this,fs,"f").autoFocusFrameLimit[0]),Ve(this,fs,"f").autoFocusFrameArray.filter((t=>!0===t)).length>=Ve(this,fs,"f").autoFocusFrameLimit[1])){Ve(this,fs,"f").autoFocusFrameArray.length=0;try{const t=m.points;await a({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(Ve(this,ds,"f").autoZoom){if(Ve(this,fs,"f").autoZoomInFrameArray.push(!1),Ve(this,fs,"f").autoZoomInFrameArray.splice(0,Ve(this,fs,"f").autoZoomInFrameArray.length-Ve(this,fs,"f").autoZoomInFrameLimit[0]),Ve(this,fs,"f").autoZoomOutFrameCount++,Ve(this,fs,"f").frameArrayInIdealZoom.push(!1),Ve(this,fs,"f").frameArrayInIdealZoom.splice(0,Ve(this,fs,"f").frameArrayInIdealZoom.length-Ve(this,fs,"f").frameLimitInIdealZoom[0]),Ve(this,fs,"f").autoZoomOutFrameCount>=Ve(this,fs,"f").autoZoomOutFrameLimit){Ve(this,fs,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let n=i-Math.max((i-1)*Ve(this,fs,"f").autoZoomOutStepRate,Ve(this,fs,"f").autoZoomOutMinStep);n=Math.max(Ve(this,fs,"f").minValue,n),n=Math.min(Ve(this,fs,"f").maxValue,n);try{await e({factor:n})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}Ve(this,ds,"f").enhancedFocus&&a({mode:"continuous"}).catch((()=>{}))}!Ve(this,ds,"f").autoZoom&&Ve(this,ds,"f").enhancedFocus&&(Ve(this,fs,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch((()=>{})))}}},Ge(this,gs,new Cs(1e4),"f")}setCameraView(t){if(!(t instanceof On))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),Ve(this,$r,"m",ps).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;Ve(this,$r,"m",ps).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return Ve(this,$r,"m",ps).call(this)?Ve(this,is,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){const t=this.cameraView;if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");t&&(t._singleFrameMode=this.singleFrameMode,Ve(this,$r,"m",ps).call(this)?t._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(t.getVideoElement()),t._startLoading()));let e={width:0,height:0,deviceId:""};if(Ve(this,$r,"m",ps).call(this));else{try{await this.cameraManager.open()}catch(e){throw t&&t._stopLoading(),"NotFoundError"===e.name?new Error(`No camera devices were detected. Please ensure a camera is connected and recognized by your system. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):"NotAllowedError"===e.name?new Error(`Camera access is blocked. Please check your browser settings or grant permission to use the camera. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):e}let i,n=t.getUIElement();if(n=n.shadowRoot||n,i=n.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=n.elTorchAuto=n.querySelector(".dce-mn-torch-auto"),e=n.elTorchOn=n.querySelector(".dce-mn-torch-on"),r=n.elTorchOff=n.querySelector(".dce-mn-torch-off");t&&(e.style.display=null==this.isTorchOn?"":"none"),e&&(e.style.display=1==this.isTorchOn?"":"none"),r&&(r.style.display=0==this.isTorchOn?"":"none");let s=n.elBeepOn=n.querySelector(".dce-mn-beep-on"),o=n.elBeepOff=n.querySelector(".dce-mn-beep-off");s&&(s.style.display=Es.allowBeep?"":"none"),o&&(o.style.display=Es.allowBeep?"none":"");let a=n.elVibrateOn=n.querySelector(".dce-mn-vibrate-on"),h=n.elVibrateOff=n.querySelector(".dce-mn-vibrate-off");a&&(a.style.display=Es.allowVibrate?"":"none"),h&&(h.style.display=Es.allowVibrate?"none":""),n.elResolutionBox=n.querySelector(".dce-mn-resolution-box");let l,c=n.elZoom=n.querySelector(".dce-mn-zoom");c&&(c.style.display="none",l=n.elZoomSpan=c.querySelector("span"));let u=n.elToast=n.querySelector(".dce-mn-toast"),d=n.elCameraClose=n.querySelector(".dce-mn-camera-close"),f=n.elTakePhoto=n.querySelector(".dce-mn-take-photo"),g=n.elCameraSwitch=n.querySelector(".dce-mn-camera-switch"),m=n.elCameraAndResolutionSettings=n.querySelector(".dce-mn-camera-and-resolution-settings");m&&(m.style.display="none");const p=n.dceMnFs={},_=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",_);const v=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",v);const y=()=>{this.turnAutoTorch()};null==r||r.addEventListener("pointerdown",y);const w=()=>{Es.allowBeep=!Es.allowBeep,s&&(s.style.display=Es.allowBeep?"":"none"),o&&(o.style.display=Es.allowBeep?"none":"")};for(let t of[o,s])null==t||t.addEventListener("pointerdown",w);const C=()=>{Es.allowVibrate=!Es.allowVibrate,a&&(a.style.display=Es.allowVibrate?"":"none"),h&&(h.style.display=Es.allowVibrate?"none":"")};for(let t of[h,a])null==t||t.addEventListener("pointerdown",C);const E=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),n=parseInt(e.getAttribute("data-height")),r=await this.setResolution({width:i,height:n});{let e=Math.max(r.width,r.height),i=Math.min(r.width,r.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&b(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?m&&(m.style.display=m.style.display?"":"none"):m&&""===m.style.display&&(m.style.display="none"))};n.addEventListener("click",E);let S=null;p.funcInfoZoomChange=(t,e=3e3)=>{c&&l&&(l.textContent=t.toFixed(1),c.style.display="",null!=S&&(clearTimeout(S),S=null),S=setTimeout((()=>{c.style.display="none",S=null}),e))};let T=null,b=p.funcShowToast=(t,e=3e3)=>{u&&(u.textContent=t,u.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout((()=>{u.style.display="none",T=null}),e))};const I=()=>{this.close()};null==d||d.addEventListener("click",I);const x=()=>{};null==f||f.addEventListener("pointerdown",x);const O=()=>{var t,e;let i,n=this.getVideoSettings(),r=n.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),o=null==s?void 0:s.indexOf("front");-1===o&&(o=null==s?void 0:s.indexOf("前"));let a=null==s?void 0:s.indexOf("back");-1===a&&(a=null==s?void 0:s.indexOf("后")),"number"==typeof o&&-1!==o?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i&&(i="user"===((null==r?void 0:r.ideal)||(null==r?void 0:r.exact)||r)),n.video.facingMode={ideal:i?"environment":"user"},delete n.video.deviceId,this.updateVideoSettings(n)};null==g||g.addEventListener("pointerdown",O);let A=-1/0,R=1;const D=t=>{let e=Date.now();e-A>1e3&&(R=this.getZoomSettings().factor),R-=t.deltaY/200,R>20&&(R=20),R<1&&(R=1),this.setZoom({factor:R}),A=e};i.addEventListener("wheel",D);const L=new Map;let M=!1;const F=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],n=t.touches[1],r=L.get(i.identifier),s=L.get(n.identifier);if(!r||!s)break;let o=Math.pow(Math.pow(r.x-s.x,2)+Math.pow(r.y-s.y,2),.5),a=Math.pow(Math.pow(i.clientX-n.clientX,2)+Math.pow(i.clientY-n.clientY,2),.5),h=Date.now();if(M||h-A<100)return;h-A>1e3&&(R=this.getZoomSettings().factor),R*=a/o,R>20&&(R=20),R<1&&(R=1);let l=!1;"safari"==(null===(e=null==je?void 0:je.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/o>1&&R<2?(R=2,l=!0):a/o<1&&R<2&&(R=1,l=!0)),M=!0,l&&b("zooming..."),await this.setZoom({factor:R}),l&&(u.textContent=""),M=!1,A=Date.now();break}L.clear();for(let e of t.touches)L.set(e.identifier,{x:e.clientX,y:e.clientY})};n.addEventListener("touchstart",F),n.addEventListener("touchmove",F),n.addEventListener("touchend",F),n.addEventListener("touchcancel",F),p.unbind=()=>{null==t||t.removeEventListener("pointerdown",_),null==e||e.removeEventListener("pointerdown",v),null==r||r.removeEventListener("pointerdown",y);for(let t of[o,s])null==t||t.removeEventListener("pointerdown",w);for(let t of[h,a])null==t||t.removeEventListener("pointerdown",C);n.removeEventListener("click",E),null==d||d.removeEventListener("click",I),null==f||f.removeEventListener("pointerdown",x),null==g||g.removeEventListener("pointerdown",O),i.removeEventListener("wheel",D),n.removeEventListener("touchstart",F),n.removeEventListener("touchmove",F),n.removeEventListener("touchend",F),n.removeEventListener("touchcancel",F),delete n.dceMnFs,i.style.display="none"},i.style.display="",t&&null==this.isTorchOn&&setTimeout((()=>{this.turnAutoTorch(1e3)}),0)}this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const r=this.getResolution();e.width=r.width,e.height=r.height,e.deviceId=this.getSelectedCamera().deviceId}return Ge(this,is,"open","f"),t&&(t._innerComponent.style.display="",Ve(this,$r,"m",ps).call(this)||(t._stopLoading(),t._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),t._renderResolutionInfo({width:e.width,height:e.height}),t.eventHandler.fire("content:updated",null,{async:!1}),t.eventHandler.fire("videoEl:resized",null,{async:!1}))),Ve(this,ns,"f").fire("opened",null,{target:this,async:!1}),e}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),Ve(this,$r,"m",ps).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}Ge(this,is,"closed","f"),Ve(this,gs,"f").stopCharging(),e&&(e._innerComponent.style.display="none",Ve(this,$r,"m",ps).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),Ve(this,ns,"f").fire("closed",null,{target:this,async:!1})}pause(){if(Ve(this,$r,"m",ps).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!Ve(this,$r,"m",ps).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(Ve(this,$r,"m",ps).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){if(!t)throw new Error("Invalid value.");let e;e="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(e),this.isTorchOn=!1;const i=this.getResolution(),n=this.cameraView;return n&&!n.disposed&&(n._stopLoading(),n._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),n._renderResolutionInfo({width:i.width,height:i.height})),{width:i.width,height:i.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Ve(this,ns,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Ve(this,ns,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._on(n,e)}off(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._off(n,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(Ve(this,$r,"m",ps).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(Ve(this,$r,"m",ps).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){if(null!=this._taskid4AutoTorch){if(!(t{var t,r,s;if(this.disposed||e||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++n>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let o;try{o=this.fetchImage()}catch(t){}if(!o||!o.width||!o.height)return;let h=0;if(a.IPF_GRAYSCALED===o.format){for(let t=0;t=this.maxDarkCount4AutoTroch){null===(t=bs._onLog)||void 0===t||t.call(bs,`darkCount ${i}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(r=null==t?void 0:t.dceMnFs)||void 0===r||r.funcShowToast("Torch Auto On")}catch(t){console.warn(t),e=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,null===(s=null==i?void 0:i.dceMnFs)||void 0===s||s.funcShowToast("Torch Not Supported")}}}else i=0};this._taskid4AutoTorch=setInterval(r,t),this.isTorchOn=void 0,r();let s=this.cameraView.getUIElement();s=s.shadowRoot||s,s.elTorchAuto&&(s.elTorchAuto.style.display=""),s.elTorchOn&&(s.elTorchOn.style.display="none"),s.elTorchOff&&(s.elTorchOff.style.display="none")}async setColorTemperature(t){if(Ve(this,$r,"m",ps).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(Ve(this,$r,"m",ps).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,n;if(Ve(this,$r,"m",ps).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(n=null==e?void 0:e.dceMnFs)||void 0===n||n.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(Ve(this,$r,"m",ps).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(Ve(this,$r,"m",ps).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(Ve(this,$r,"m",ps).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){Ve(this,fs,"f").minValue=t.min,Ve(this,fs,"f").maxValue=t.max}getAutoZoomRange(){return{min:Ve(this,fs,"f").minValue,max:Ve(this,fs,"f").maxValue}}async enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=gt.license)||void 0===e?void 0:e.LicenseManager)||void 0===i?void 0:i.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==vt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&$e.EF_ENHANCED_FOCUS&&(Ve(this,ds,"f").enhancedFocus=!0),t&$e.EF_AUTO_ZOOM&&(Ve(this,ds,"f").autoZoom=!0),t&$e.EF_TAP_TO_FOCUS&&(Ve(this,ds,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&$e.EF_ENHANCED_FOCUS&&(Ve(this,ds,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch((()=>{}))),t&$e.EF_AUTO_ZOOM&&(Ve(this,ds,"f").autoZoom=!1,this.resetZoom().catch((()=>{}))),t&$e.EF_TAP_TO_FOCUS&&(Ve(this,ds,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),Ve(this,$r,"m",vs).call(this)&&Ve(this,$r,"m",_s).call(this)||Ve(this,gs,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!E(t)&&!O(t))throw TypeError("Invalid 'region'.");Ge(this,hs,t?JSON.parse(JSON.stringify(t)):null,"f"),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(Ve(this,hs,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");Ge(this,as,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||Ve(this,$r,"m",ps).call(this))}startFetching(){if(Ve(this,$r,"m",ps).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");Ve(this,cs,"f")||(Ge(this,cs,!0,"f"),Ve(this,$r,"m",ys).call(this))}stopFetching(){Ve(this,cs,"f")&&(bs._onLog&&bs._onLog("DCE: stop fetching loop: "+Date.now()),Ve(this,us,"f")&&clearTimeout(Ve(this,us,"f")),Ge(this,cs,!1,"f"))}fetchImage(){if(Ve(this,$r,"m",ps).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(4!==this.video.readyState)throw new Error("The video is not loaded.");const t=this.getResolution();if(!(null==t?void 0:t.width)||!(null==t?void 0:t.height))throw new Error("The video is not loaded.");let e;if(e=Mi.convert(Ve(this,hs,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height}),e.x>t.width||e.y>t.height)throw new Error("Invalid scan region.");e.x+e.width>t.width&&(e.width=t.width-e.x),e.y+e.height>t.height&&(e.height=t.height-e.y);const i={sx:e.x,sy:e.y,sWidth:e.width,sHeight:e.height,dWidth:e.width,dHeight:e.height},n=Math.max(i.dWidth,i.dHeight);if(this.canvasSizeLimit&&n>this.canvasSizeLimit){const t=this.canvasSizeLimit/n;i.dWidth>i.dHeight?(i.dWidth=this.canvasSizeLimit,i.dHeight=Math.round(i.dHeight*t)):(i.dWidth=Math.round(i.dWidth*t),i.dHeight=this.canvasSizeLimit)}const r=this.cameraManager.getFrameData({position:i,pixelFormat:this.getPixelFormat()===a.IPF_GRAYSCALED?Un.GREY:Un.RGBA});if(!r)return null;let s;s=r.pixelFormat===Un.GREY?r.width:4*r.width;let o=!0;return 0===i.sx&&0===i.sy&&i.sWidth===t.width&&i.sHeight===t.height&&(o=!1),{bytes:r.data,width:r.width,height:r.height,stride:s,format:Ss.get(r.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:Tt.ITT_VIDEO_FRAME,isCropped:o,cropRegion:{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height,isMeasuredInPercentage:!1},originalWidth:t.width,originalHeight:t.height,currentWidth:r.width,currentHeight:r.height,timeSpent:r.timeSpent,timeStamp:r.timeStamp},toCanvas:Ve(this,os,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,Ve(this,cs,"f")&&(Ve(this,us,"f")&&clearTimeout(Ve(this,us,"f")),Ge(this,us,setTimeout((()=>{this.disposed||Ve(this,$r,"m",ys).call(this)}),t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){Ge(this,ls,t,"f")}getPixelFormat(){return Ve(this,ls,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(Ve(this,$r,"m",ps).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",(()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",(()=>{t&&this.open(),e.remove()}),{once:!0})})),e.addEventListener("change",(async()=>{const i=e.files[0],n=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise(((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(i),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let o=Mi.convert(Ve(this,hs,"f"),r,s);o||(o={x:0,y:0,width:r,height:s});const a=Ve(this,ss,"f").call(this,n,r,s,o);t&&t(a)})),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=Ve(this,$r,"m",ws).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=Ve(this,$r,"m",ws).call(this,t);return{x:e.clientX,y:e.clientY}}convertToScanRegionCoordinates(t){if(!Ve(this,hs,"f"))return JSON.parse(JSON.stringify(t));let e,i,n=Ve(this,hs,"f").left||Ve(this,hs,"f").x||0,r=Ve(this,hs,"f").top||Ve(this,hs,"f").y||0;if(!Ve(this,hs,"f").isMeasuredInPercentage)return{x:t.x-n,y:t.y-r};if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!Ve(this,$r,"m",ps).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Ve(this,$r,"m",ps).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(Ve(this,$r,"m",ps).call(this)){const t=this.cameraView._innerComponent.getElement("content");e=t.width,i=t.height}else{const t=this.getVideoEl();e=t.videoWidth,i=t.videoHeight}return{x:t.x-Math.round(n*e/100),y:t.y-Math.round(r*i/100)}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),Ge(this,ms,!0,"f")}}var Is,xs,Os,As,Rs,Ds,Ls,Ms;ts=bs,is=new WeakMap,ns=new WeakMap,rs=new WeakMap,ss=new WeakMap,os=new WeakMap,as=new WeakMap,hs=new WeakMap,ls=new WeakMap,cs=new WeakMap,us=new WeakMap,ds=new WeakMap,fs=new WeakMap,gs=new WeakMap,ms=new WeakMap,$r=new WeakSet,ps=function(){return"disabled"!==this.singleFrameMode},_s=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},vs=function(){for(let t in Ve(this,ds,"f"))if(1==Ve(this,ds,"f")[t])return!0;return!1},ys=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!Ve(this,cs,"f"))return Ve(this,us,"f")&&clearTimeout(Ve(this,us,"f")),void Ge(this,us,setTimeout((()=>{this.disposed||Ve(this,$r,"m",t).call(this)}),this.fetchInterval),"f");const e=()=>{var t;let e;bs._onLog&&bs._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{e=this.fetchImage()}catch(e){const i=e.message||e;if("The video is not loaded."===i)return;if(null===(t=Ve(this,as,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout((()=>{var t;null===(t=Ve(this,as,"f"))||void 0===t||t.onErrorReceived(Ct.EC_IMAGE_READ_FAILED,i)}),0);console.warn(e)}e?(this.addImageToBuffer(e),bs._onLog&&bs._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),Ve(this,ns,"f").fire("frameAddedToBuffer",null,{async:!1})):bs._onLog&&bs._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case s.BOPM_BLOCK:break;case s.BOPM_UPDATE:e()}else e();Ve(this,us,"f")&&clearTimeout(Ve(this,us,"f")),Ge(this,us,setTimeout((()=>{this.disposed||Ve(this,$r,"m",t).call(this)}),this.fetchInterval),"f")},ws=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!Ve(this,$r,"m",ps).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Ve(this,$r,"m",ps).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,n=e.top,r=i+window.scrollX,s=n+window.scrollY,{width:o,height:a}=this.cameraView._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(Ve(this,$r,"m",ps).call(this)){const t=this.cameraView._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=this.cameraView.getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)u{var e;if(!this.isUseMagnifier)return;if(Ve(this,As,"f")||Ge(this,As,new Fs,"f"),!Ve(this,As,"f").magnifierCanvas)return;document.body.contains(Ve(this,As,"f").magnifierCanvas)||(Ve(this,As,"f").magnifierCanvas.style.position="fixed",Ve(this,As,"f").magnifierCanvas.style.boxSizing="content-box",Ve(this,As,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(Ve(this,As,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void Ve(this,Ds,"f").call(this);const n=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!n)return;const r=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*r,o=[{image:i,width:i.width,height:i.height},{image:n,width:n.width,height:n.height}];Ve(this,As,"f").update(s,t.pointer,r,o);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(Ve(this,As,"f").magnifierCanvas.style.left="auto",Ve(this,As,"f").magnifierCanvas.style.top="0",Ve(this,As,"f").magnifierCanvas.style.right="0"):(Ve(this,As,"f").magnifierCanvas.style.left="0",Ve(this,As,"f").magnifierCanvas.style.top="0",Ve(this,As,"f").magnifierCanvas.style.right="auto")}Ve(this,As,"f").show()})),Ds.set(this,(()=>{Ve(this,As,"f")&&Ve(this,As,"f").hide()})),Ls.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Ui(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=document.createElement("dce-component"),e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let n=this._innerComponent.getElement("content");n||(n=document.createElement("canvas"),n.style.objectFit="contain",this._innerComponent.setElement("content",n)),n.width===e&&n.height===i||(n.width=e,n.height=i);const r=n.getContext("2d");r.clearRect(0,0,n.width,n.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),r.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&r.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(C(t)){Ge(this,Os,t,"f");const{width:e,height:i,bytes:n,format:r}=Object.assign({},t);let s;if(r===a.IPF_GRAYSCALED){s=new Uint8ClampedArray(e*i*4);for(let t=0;t{if(!Ns){if(!ks&&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"./"}})(),Us=t=>t&&"object"==typeof t&&"function"==typeof t.then,Vs=(async()=>{})().constructor;let Gs=class extends Vs{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,Us(t)?e=t:"function"==typeof t&&(e=new Vs(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}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(Us(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Ws=" is not allowed to change after `createInstance` or `loadWasm` is called.",Ys=!ks&&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"))||"",Hs=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Ws);i._license=e}};!ks&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Xs=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{e=Xs(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Ws);i._licenseServer=e}},qs=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Ws);i._deviceFriendlyName=e}};let Zs,Ks,Js,Qs,$s;"undefined"!=typeof navigator&&(Zs=navigator,Ks=Zs.userAgent,Js=Zs.platform,Qs=Zs.mediaDevices),function(){if(!ks){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Zs.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Js,search:"Win"},Mac:{str:Js},Linux:{str:Js}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||Ks,o=r.search||e,a=r.verStr||Ks,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Ks,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=Ks.indexOf("Windows NT")&&(r="HarmonyOS"),$s={browser:i,version:n,OS:r}}ks&&($s={browser:"ssr",version:0,OS:"ssr"})}(),Qs&&Qs.getUserMedia,"Chrome"===$s.browser&&$s.version>66||"Safari"===$s.browser&&$s.version>13||"OPR"===$s.browser&&$s.version>43||"Edge"===$s.browser&&$s.version;const to=()=>(_t("license"),rt("dynamsoft_inited",(async()=>{let{lt:t,l:e,ls:i,sp:n,rmk:r,cv:s}=((t,e=!1)=>{const i=io;if(i._pLoad.isEmpty){let n,r,s,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(r=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=Xs(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),n=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(Bs.crypto||(s="Please upgrade your browser to support online key."),Bs.crypto.subtle||(s="Require https to use online key in this browser."))),s)throw new Error(s);return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:n,cv:r}}throw new Error("Can't preprocess license again"+Ws)})(),o=new Gs;io._pLoad.task=o,(async()=>{try{await io._pLoad}catch(t){}})();let a=at();ht[a]=e=>{if(e.message&&io._onAuthMessage){let t=io._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,n=!1;if(1===t&&(n=!0),e.success?(lt&<("init license success"),e.message&&console.warn(e.message),vt._bSupportIRTModule=e.bSupportIRTModule,vt._bSupportDce4Module=e.bSupportDce4Module,io.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):o.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),n||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(n=!0)),n){const t=L(vt.engineResourcePaths);(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let n=await fetch(t.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 s=document.createElement("div");s.innerHTML=r;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("["),n=e.indexOf("]",i),r=e.indexOf("(",n),s=e.indexOf(")",r);if(-1==i||-1==n||-1==r||-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,n);o.innerText=a;let h=e.substring(r+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)}})({_bNeverShowDialog:io._bNeverShowDialog,engineResourcePath:t.license,_onLog:lt},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await nt("core"),st.postMessage({type:"license_dynamsoft",body:{v:"3.4.31",brtk:!!t,bptk:1===t,l:e,os:$s,fn:io.deviceFriendlyName,ls:i,sp:n,rmk:r,cv:s},id:a}),io.bCallInitLicense=!0,await o})));let eo;gt.license={},gt.license.dynamsoft=to,gt.license.getAR=async()=>{{let t=it.dynamsoft_inited;t&&t.isRejected&&await t}return st?new Promise(((t,e)=>{let i=at();ht[i]=async i=>{if(i.success){delete i.success;{let t=io.license;t&&(t.startsWith("t")||t.startsWith("f"))&&(i.pk=t)}if(Object.keys(i).length){if(i.lem){let t=Error(i.lem);t.ltsErrorCode=i.lec,delete i.lem,delete i.lec,i.ae=t}t(i)}else t(null)}else{let t=Error(i.message);i.stack&&(t.stack=i.stack),e(t)}},st.postMessage({type:"license_getAR",id:i})})):null};let io=class t{static setLicenseServer(e){zs(t,e)}static get license(){return this._license}static set license(e){Hs(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){zs(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){qs(t,e)}static initLicense(e,i){if(Hs(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return to()}static setDeviceFriendlyName(e){qs(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await rt("dynamsoft_uuid",(async()=>{await _t();let t=new Gs,e=at();ht[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},st.postMessage({type:"license_getDeviceUUID",id:e}),eo=await t})),eo))()}};io._pLoad=new Gs,io.bPassValidation=!1,io.bCallInitLicense=!1,io._license=Ys,io._licenseServer=[],io._deviceFriendlyName="",vt.engineResourcePaths.license={version:"3.4.31",path:js,isInternal:!0},mt.license={wasm:!0,js:!0},gt.license.LicenseManager=io;const no="1.4.21";"string"!=typeof vt.engineResourcePaths.std&&D(vt.engineResourcePaths.std.version,no)<0&&(vt.engineResourcePaths.std={version:no,path:(t=>{if(null==t&&(t="./"),ks||Ns);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(js+`../../dynamsoft-capture-vision-std@${no}/dist/`),isInternal:!0});let ro=class{static getVersion(){return`3.4.31(Worker: ${ft.license&&ft.license.worker||"Not Loaded"}, Wasm: ${ft.license&&ft.license.wasm||"Not Loaded"})`}};const so=()=>window.matchMedia("(orientation: landscape)").matches;function oo(t,e){for(const n in e)"Object"===(i=e[n],Object.prototype.toString.call(i).slice(8,-1))&&n in t?oo(t[n],e[n]):t[n]=e[n];var i;return t}const ao=async t=>{let e;await new Promise(((i,n)=>{e=new Image,e.onload=()=>i(e),e.onerror=n,e.src=URL.createObjectURL(t)}));const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=e.width,i.height=e.height,n.drawImage(e,0,0),{bytes:Uint8Array.from(n.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:10}};class ho{async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const n=B(t);return M(n,e,i)}async drawOnImage(t,e,i,n=4294901760,r=1,s){let o;if(t instanceof Blob)o=await ao(t);else if("string"==typeof t){let e=await A(t,"blob");o=await ao(e)}return await new Promise(((t,a)=>{let h=at();ht[h]=async e=>{if(e.success)return s&&this.saveToFile(e.image,"test.png",s),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},st.postMessage({type:"utility_drawOnImage",id:h,body:{dsImage:o,drawingItem:e instanceof Array?e:[e],color:n,thickness:r,type:i}})}))}}const lo="undefined"==typeof self,co="function"==typeof importScripts,uo=(()=>{if(!co){if(!lo&&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"./"}})(),fo=t=>{if(null==t&&(t="./"),lo||co);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};vt.engineResourcePaths.utility={version:"1.4.32",path:uo,isInternal:!0},mt.utility={js:!0,wasm:!0};const go="1.4.21";"string"!=typeof vt.engineResourcePaths.std&&D(vt.engineResourcePaths.std.version,go)<0&&(vt.engineResourcePaths.std={version:go,path:fo(uo+`../../dynamsoft-capture-vision-std@${go}/dist/`),isInternal:!0});const mo="2.4.31";(!vt.engineResourcePaths.dip||"string"!=typeof vt.engineResourcePaths.dip&&D(vt.engineResourcePaths.dip.version,mo)<0)&&(vt.engineResourcePaths.dip={version:mo,path:fo(uo+`../../dynamsoft-image-processing@${mo}/dist/`),isInternal:!0});class po{static getVersion(){return`1.4.32(Worker: ${ft.utility&&ft.utility.worker||"Not Loaded"}, Wasm: ${ft.utility&&ft.utility.wasm||"Not Loaded"})`}}function _o(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}var vo,yo,wo,Co,Eo;function So(t,e){let i=!0;for(let o=0;o1)return Math.sqrt((h-o)**2+(l-a)**2);{const t=r+u*(o-r),e=s+u*(a-s);return Math.sqrt((h-t)**2+(l-e)**2)}}function Io(t){const e=[];for(let i=0;i=0&&h<=1&&l>=0&&l<=1?{x:t.x+l*r,y:t.y+l*s}:null}function Ao(t){let e=0;for(let i=0;i0}function Do(t,e){for(let i=0;i<4;i++)if(!Ro(t.points[i],t.points[(i+1)%4],e))return!1;return!0}"function"==typeof SuppressedError&&SuppressedError;function Lo(t,e,i,n){const r=t.points,s=e.points;let o=8*i;o=Math.max(o,5);const a=Io(r)[3],h=Io(r)[1],l=Io(s)[3],c=Io(s)[1];let u,d=0;if(u=Math.max(Math.abs(bo(a,e.points[0])),Math.abs(bo(a,e.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(bo(h,e.points[1])),Math.abs(bo(h,e.points[2]))),u>d&&(d=u),u=Math.max(Math.abs(bo(l,t.points[0])),Math.abs(bo(l,t.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(bo(c,t.points[1])),Math.abs(bo(c,t.points[2]))),u>d&&(d=u),d>o)return!1;const f=xo(Io(r)[0]),g=xo(Io(r)[2]),m=xo(Io(s)[0]),p=xo(Io(s)[2]),_=To(f,p),v=To(m,g),y=_>v,w=Math.min(_,v),C=To(f,g),E=To(m,p);let S=12*i;return S=Math.max(S,5),S=Math.min(S,C),S=Math.min(S,E),!!(w{e.x+=t,e.y+=i})),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,n=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-n.area)>.4*i.area)return!1;let r=new Array(4).fill(0),s=new Array(4).fill(0),o=0,a=0;for(let t=0;t<4;++t)r[t]=Math.round(100*(n.points[t].x-i.points[t].x))/100,o+=r[t],s[t]=Math.round(100*(n.points[t].y-i.points[t].y))/100,a+=s[t];o/=4,a/=4;for(let t=0;t<4;++t){if(Math.abs(r[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1;if(Math.abs(s[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1}return e.x=o,e.y=a,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(Do(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(Do(this.location,e))return!0}else{for(let e=0;e<4;e++)if(Do(t,this.location.points[e]))return!0;if(Do(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const n=[this.location.points[0],this.location.points[3]],r=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],s=0===t||3===t?n:r;if(Math.abs(bo(s,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const n=t.location.points[i],r=this.location.points[i];if(!(Math.abs(r.x+e.x-n.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const n=Object.assign({},t.location);for(let t=0;t<4;t++)n.points[t].x-=e.x,n.points[t].y-=e.y;if(!this.isLocationOverlap(n,t.location.area))return!1;if(i){const t=.75;return function(t,e){const i=[];for(let n=0;n<4;n++)for(let r=0;r<4;r++){const s=Oo(t[n],t[(n+1)%4],e[r],e[(r+1)%4]);s&&i.push(s)}return t.forEach((t=>{So(e,t)&&i.push(t)})),e.forEach((e=>{So(t,e)&&i.push(e)})),Ao(function(t){if(t.length<=1)return t;t.sort(((t,e)=>t.x-e.x||t.y-e.y));const e=t.shift();return t.sort(((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x))),[e,...t]}(i))}([...this.location.points],n.points)>this.locationArea*t}return!0}}const Fo={BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096)},Po={barcode:2,text_line:4,detected_quad:8,normalized_image:16},ko=t=>Object.values(Po).includes(t)||Po.hasOwnProperty(t),Bo=(t,e)=>"string"==typeof t?e[Po[t]]:e[t],No=(t,e,i)=>{"string"==typeof t?e[Po[t]]=i:e[t]=i},jo=(t,e,i)=>{const n=[8,16].includes(i);if(!n&&t.isResultCrossVerificationEnabled(i))for(let t=0;t{No(e,this.verificationEnabled,t)})),_o(this,yo,"f").forEach(((t,e)=>{No(e,this.duplicateFilterEnabled,t)})),_o(this,wo,"f").forEach(((t,e)=>{No(e,this.duplicateForgetTime,t)})),_o(this,Co,"f").forEach(((t,e)=>{No(e,this.latestOverlappingEnabled,t)})),_o(this,Eo,"f").forEach(((t,e)=>{No(e,this.maxOverlappingFrames,t)}))}enableResultCrossVerification(t,e){ko(t)&&_o(this,vo,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!ko(t)&&Bo(t,this.verificationEnabled)}enableResultDeduplication(t,e){ko(t)&&(e&&this.enableLatestOverlapping(t,!1),_o(this,yo,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!ko(t)&&Bo(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){ko(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),_o(this,wo,"f").set(t,e))}getDuplicateForgetTime(t){return ko(t)?Bo(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){ko(t)&&_o(this,Eo,"f").set(t,e)}getMaxOverlappingFrames(t){return ko(t)?Bo(t,this.maxOverlappingFrames):-1}enableLatestOverlapping(t,e){ko(t)&&(e&&this.enableResultDeduplication(t,!1),_o(this,Co,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!ko(t)&&Bo(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[yt.CRIT_BARCODE,yt.CRIT_TEXT_LINE,yt.CRIT_DETECTED_QUAD,yt.CRIT_NORMALIZED_IMAGE];for(let i=0;i{if(1!==t.type){const e=(BigInt(t.format)&BigInt(Fo.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Fo.BF_GS1_DATABAR))!=BigInt(0);return new Mo(h,e?1:2,e,t)}})).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(l).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t)).length;r>p&&(p=r,m=n,g.x=i.x,g.y=i.y)}}if(0===p){for(let e=0;e-1!=t)).length}let i=this.overlapSet.length<=3?p>=1:p>=2;if(!i&&s&&u>0){let t=0;for(let e=0;e=1:t>=3}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach(((t,e)=>{if(1!==t.type){const i=Object.assign({},t),n=(BigInt(t.format)&BigInt(Fo.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Fo.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0)))}f.sort(((t,e)=>e-t)).forEach(((e,i)=>{t.items.splice(e,1)})),d.forEach((e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))}))}}onDecodedBarcodesReceived(t){this.latestOverlappingFilter(t),jo(this,t.items,yt.CRIT_BARCODE)}onRecognizedTextLinesReceived(t){jo(this,t.items,yt.CRIT_TEXT_LINE)}onDetectedQuadsReceived(t){jo(this,t.items,yt.CRIT_DETECTED_QUAD)}onNormalizedImagesReceived(t){jo(this,t.items,yt.CRIT_NORMALIZED_IMAGE)}}var Vo,Go,Wo,Yo,Ho,Xo,zo,qo,Zo,Ko,Jo,Qo,$o,ta,ea,ia,na,ra,sa,oa,aa;vo=new WeakMap,yo=new WeakMap,wo=new WeakMap,Co=new WeakMap,Eo=new WeakMap;class ha{constructor(t){if(Vo.add(this),Yo.set(this,void 0),Ho.set(this,{status:{code:Ut.RS_SUCCESS,message:"Success."},barcodeResults:[]}),Xo.set(this,!1),zo.set(this,void 0),qo.set(this,void 0),this.config=Vt,t&&"object"!=typeof t||Array.isArray(t))throw"Invalid config.";oo(this.config,t)}async launch(){if(Lt(this,Xo,"f"))throw new Error("The BarcodeScanner instance has been destroyed.");if(Lt(ha,Go,"f",Wo)&&!Lt(ha,Go,"f",Wo).isFulfilled)throw new Error("Cannot call `launch()` while a previous task is still running.");return Mt(ha,Go,new Yt,"f",Wo),await Lt(this,Vo,"m",Zo).call(this),Lt(ha,Go,"f",Wo)}async decode(t,e="ReadBarcodes_Default"){return Mt(this,qo,e,"f"),await Lt(this,Vo,"m",Ko).call(this,!0),this._cvRouter.capture(t,e)}dispose(){Mt(this,Xo,!0,"f"),Lt(ha,Go,"f",Wo)&&Lt(ha,Go,"f",Wo).isPending&&Lt(ha,Go,"f",Wo).resolve(Lt(this,Ho,"f")),this._cameraEnhancer?.dispose(),this._cameraView?.dispose(),this._cvRouter?.dispose(),this._cameraEnhancer=null,this._cameraView=null,this._cvRouter=null,window.removeEventListener("resize",Lt(this,Yo,"f")),document.querySelector(".scanner-view-container")?.remove(),document.querySelector(".result-view-container")?.remove(),document.querySelector(".barcode-scanner-container")?.remove(),document.querySelector(".loading-page")?.remove()}}Go=ha,Yo=new WeakMap,Ho=new WeakMap,Xo=new WeakMap,zo=new WeakMap,qo=new WeakMap,Vo=new WeakSet,Zo=async function(){try{await Lt(this,Vo,"m",Ko).call(this);try{await this._cameraEnhancer.open()}catch(t){Lt(this,Vo,"m",aa).call(this);document.querySelector(".no-camera-view").style.display="flex"}await this._cvRouter.startCapturing(Lt(this,qo,"f"))}catch(t){Lt(this,Ho,"f").status={code:Ut.RS_FAILED,message:t.message||t},Lt(ha,Go,"f",Wo).reject(new Error(Lt(this,Ho,"f").status.message)),this.dispose()}finally{const t=document.querySelector(".loading-page");t&&(t.style.display="none")}},Ko=async function(t=!1){vt.engineResourcePaths=this.config.engineResourcePaths,t||(this._cameraView=await On.createInstance(),this.config.scanMode===Nt.SM_SINGLE&&(this._cameraView._capturedResultReceiver.onCapturedResultReceived=()=>{}),await Lt(this,Vo,"m",Qo).call(this)),await io.initLicense(this.config.license||"",{executeNow:!0}),this._cvRouter=this._cvRouter||await be.createInstance(),await Lt(this,Vo,"m",Jo).call(this,t),t||(this._cameraEnhancer=await bs.createInstance(this._cameraView),this._cvRouter.setInput(this._cameraEnhancer),Lt(this,Vo,"m",$o).call(this),await Lt(this,Vo,"m",ta).call(this))},Jo=async function(t=!1){t||(this.config.scanMode===Nt.SM_SINGLE?Mt(this,qo,this.config.utilizedTemplateNames.single,"f"):this.config.scanMode===Nt.SM_MULTI_UNIQUE&&Mt(this,qo,this.config.utilizedTemplateNames.multi_unique,"f")),this.config.templateFilePath&&await this._cvRouter.initSettings(this.config.templateFilePath);const e=await this._cvRouter.getSimplifiedSettings(Lt(this,qo,"f"));t||this.config.scanMode!==Nt.SM_SINGLE||(e.capturedResultItemTypes=yt.CRIT_ORIGINAL_IMAGE|yt.CRIT_BARCODE);let i=this.config.barcodeFormats;if(i){Array.isArray(i)||(i=[i]),e.barcodeSettings.barcodeFormatIds=BigInt(0);for(let t=0;t{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const n=document.createElement("div");if(n.insertAdjacentHTML("beforeend",i),1===n.childElementCount&&n.firstChild instanceof HTMLTemplateElement)return n.firstChild.content;const r=new DocumentFragment;for(let t of n.children)r.append(t);return r})(e);i.querySelectorAll("style").forEach((t=>{document.head.appendChild(t.cloneNode(!0))})),Mt(this,zo,i.querySelector(".result-item"),"f");const n=i.querySelector(".btn-clear");if(n&&(n.addEventListener("click",(()=>{Lt(this,Ho,"f").barcodeResults=[],Lt(this,Vo,"m",sa).call(this)})),this.config?.resultViewConfig?.toolbarButtonsConfig?.clear)){const t=this.config.resultViewConfig.toolbarButtonsConfig.clear;n.style.display=t.isHidden?"none":"flex",n.className=t.className?t.className:"btn-clear",n.innerText=t.label?t.label:"Clear",t.isHidden&&(i.querySelector(".toolbar-btns").style.justifyContent="center")}const r=i.querySelector(".btn-done");if(r&&(r.addEventListener("click",(()=>{const t=document.querySelector(".loading-page");t&&"none"===getComputedStyle(t).display&&this.dispose()})),this.config?.resultViewConfig?.toolbarButtonsConfig?.done)){const t=this.config.resultViewConfig.toolbarButtonsConfig.done;r.style.display=t.isHidden?"none":"flex",r.className=t.className?t.className:"btn-done",r.innerText=t.label?t.label:"Done",t.isHidden&&(i.querySelector(".toolbar-btns").style.justifyContent="center")}const s=this.config?.scannerViewConfig?.showCloseButton;if(s){const t=i.querySelector(".btn-close");t&&(t.style.display="",t.addEventListener("click",(()=>{Lt(this,Ho,"f").barcodeResults=[],Lt(this,Ho,"f").status={code:Ut.RS_CANCELLED,message:"Cancelled."},this.dispose()})))}this.config.showUploadImageButton&&Lt(this,Vo,"m",aa).call(this,i.querySelector(".btn-upload-image"));const o=this._cameraView.getUIElement();o.shadowRoot.querySelector(".dce-sel-camera").remove(),o.shadowRoot.querySelector(".dce-sel-resolution").remove(),this._cameraView.setVideoFit("cover");const a=i.querySelector(".barcode-scanner-container");a.style.display=so()?"flex":"";const h=this.config.showResultView&&this.config.scanMode!==Nt.SM_SINGLE;let l;if(this.config.container?(a.style.position="relative",l=this.config.container):l=document.body,"string"==typeof l&&(l=document.querySelector(l),null===l))throw new Error("Failed to get the container");let c=this.config.scannerViewConfig.container;if("string"==typeof c&&(c=document.querySelector(c),null===c))throw new Error("Failed to get the container of the scanner view.");let u=this.config.resultViewConfig.container;if("string"==typeof u&&(u=document.querySelector(u),null===u))throw new Error("Failed to get the container of the result view.");const d=i.querySelector(".scanner-view-container"),f=i.querySelector(".result-view-container"),g=i.querySelector(".loading-page");d.append(g),c&&(d.append(o),c.append(d)),u&&u.append(f),c||u?c&&!u?(this.config.container||(f.style.position="absolute"),u=f,l.append(f)):!c&&u&&(this.config.container||(d.style.position="absolute"),c=d,d.append(o),l.append(d)):(c=d,u=f,h&&(Object.assign(d.style,{width:so()?"50%":"100%",height:so()?"100%":"50%"}),Object.assign(f.style,{width:so()?"50%":"100%",height:so()?"100%":"50%"})),d.append(o),l.append(a)),document.querySelector(".result-view-container").style.display=h?"":"none",this.config.removePoweredByMessage&&(o.shadowRoot.querySelector(".dce-msg-poweredby").style.display="none",document.querySelector(".no-result-svg").style.display="none"),Mt(this,Yo,(()=>{Object.assign(a.style,{display:so()?"flex":""}),!h||this.config.scannerViewConfig.container||this.config.resultViewConfig.container||(Object.assign(c.style,{width:so()?"50%":"100%",height:so()?"100%":"50%"}),Object.assign(u.style,{width:so()?"50%":"100%",height:so()?"100%":"50%"}))}),"f"),window.addEventListener("resize",Lt(this,Yo,"f")),this._cameraView._createDrawingLayer(2)},$o=function(){const t=new Ae;let e=0;t.onCapturedResultReceived=async t=>{t.barcodeResultItems&&(this.config.scanMode===Nt.SM_SINGLE?2==++e&&Lt(this,Vo,"m",ea).call(this,t):Lt(this,Vo,"m",ia).call(this,t))},this._cvRouter.addResultReceiver(t)},ta=async function(){const t=new Uo;t.enableResultCrossVerification(2,!0),t.enableResultDeduplication(2,!0),t.setDuplicateForgetTime(2,this.config.duplicateForgetTime),t.onDecodedBarcodesReceived=()=>{},await this._cvRouter.addResultFilter(t)},ea=function(t){const e=this._cameraView.getUIElement().shadowRoot;let i=new Promise((i=>{if(t.barcodeResultItems.length>1){Lt(this,Vo,"m",ra).call(this);for(let n of t.barcodeResultItems){let t=0,r=0;for(let e=0;e<4;++e){let i=n.location.points[e];t+=i.x,r+=i.y}let s=this._cameraEnhancer.convertToClientCoordinates({x:t/4,y:r/4}),o=document.createElement("div");o.className="single-barcode-result-option",Object.assign(o.style,{position:"fixed",width:"32px",height:"32px",border:"#fff solid 4px","box-sizing":"border-box","border-radius":"16px",background:"#080",cursor:"pointer",transform:"translate(-50%, -50%)"}),o.style.left=s.x+"px",o.style.top=s.y+"px",o.addEventListener("click",(()=>{i(n)})),e.append(o)}}else i(t.barcodeResultItems[0])}));i.then((e=>{const i=t.items.filter((t=>t.type===yt.CRIT_ORIGINAL_IMAGE))[0].imageData,n={status:{code:Ut.RS_SUCCESS,message:"Success."},originalImageResult:i,barcodeImage:(()=>{const t=F(i),n=e.location.points,r=Math.min(...n.map((t=>t.x))),s=Math.min(...n.map((t=>t.y))),o=Math.max(...n.map((t=>t.x))),h=Math.max(...n.map((t=>t.y))),l=o-r,c=h-s,u=document.createElement("canvas");u.width=l,u.height=c;const d=u.getContext("2d");d.beginPath(),d.moveTo(n[0].x-r,n[0].y-s);for(let t=1;tt.id===`${i.formatString}_${i.text}`));-1===t?(i.count=1,Lt(this,Ho,"f").barcodeResults.unshift(i),Lt(this,Vo,"m",sa).call(this,i)):(Lt(this,Ho,"f").barcodeResults[t].count++,Lt(this,Vo,"m",oa).call(this,t)),this.config.onUniqueBarcodeScanned&&this.config.onUniqueBarcodeScanned(i)}},na=function(t){const e=Lt(this,zo,"f").cloneNode(!0);e.querySelector(".format-string").innerText=t.formatString;e.querySelector(".text-string").innerText=t.text.replace(/\n|\r/g,""),e.id=`${t.formatString}_${t.text}`;return e.querySelector(".delete-icon").addEventListener("click",(()=>{const e=[...document.querySelectorAll(".main-list .result-item")],i=e.findIndex((e=>e.id===`${t.formatString}_${t.text}`));Lt(this,Ho,"f").barcodeResults.splice(i,1),e[i].remove()})),e},ra=function(){const t=this._cameraView.getUIElement().shadowRoot;if(t.querySelector(".single-mode-mask"))return;const e=document.createElement("div");e.className="single-mode-mask",Object.assign(e.style,{width:"100%",height:"100%",position:"absolute",top:"0",left:"0",right:"0",bottom:"0","background-color":"#4C4C4C",opacity:"0.5"}),t.append(e),this._cameraEnhancer.pause(),this._cvRouter.stopCapturing()},sa=function(t){const e=document.querySelector(".no-result-svg");if(!(this.config.showResultView&&this.config.scanMode!==Nt.SM_SINGLE))return;const i=document.querySelector(".main-list");if(!t)return i.textContent="",void(e.style.display="");e.style.display="none";const n=Lt(this,Vo,"m",na).call(this,t);i.insertBefore(n,document.querySelector(".result-item"))},oa=function(t){const e=document.querySelectorAll(".main-list .result-item"),i=e[t].querySelector(".result-count");let n=parseInt(i.textContent.replace("x",""));e[t].querySelector(".result-count").textContent="x"+ ++n},aa=function(t){t||(t=document.querySelector(".btn-upload-image")),t&&(t.style.display="",t.addEventListener("change",(async t=>{const e=t.target.files,i={status:{code:Ut.RS_SUCCESS,message:"Success."},barcodeResults:[]};for(let t of e)try{const e=await this.decode(t,this.config.utilizedTemplateNames.image);e.barcodeResultItems&&i.barcodeResults.push(...e.barcodeResultItems)}catch(t){i.status={code:Ut.RS_FAILED,message:t.message||t},Lt(ha,Go,"f",Wo).reject(i.status.message),this.dispose()}Lt(ha,Go,"f",Wo).resolve(i),this.dispose()})))},Wo={value:null};const la="undefined"==typeof self,ca="function"==typeof importScripts,ua=(()=>{if(!ca){if(!la&&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"./"}})(),da=t=>{if(null==t&&(t="./"),la||ca);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};vt.engineResourcePaths.dbr={version:"10.4.31",path:ua,isInternal:!0},mt.dbr={js:!1,wasm:!0,deps:["license","dip"]},gt.dbr={};const fa="1.4.21";"string"!=typeof vt.engineResourcePaths.std&&D(vt.engineResourcePaths.std.version,fa)<0&&(vt.engineResourcePaths.std={version:fa,path:da(ua+`../../dynamsoft-capture-vision-std@${fa}/dist/`),isInternal:!0});const ga="2.4.31";(!vt.engineResourcePaths.dip||"string"!=typeof vt.engineResourcePaths.dip&&D(vt.engineResourcePaths.dip.version,ga)<0)&&(vt.engineResourcePaths.dip={version:ga,path:da(ua+`../../dynamsoft-image-processing@${ga}/dist/`),isInternal:!0});class ma{static getVersion(){const t=ft.dbr&&ft.dbr.wasm;return`10.4.31(Worker: ${ft.dbr&&ft.dbr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}}const pa={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)};var _a,va,ya,wa;!function(t){t[t.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",t[t.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",t[t.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(_a||(_a={})),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"}(va||(va={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",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",t[t.LM_SKIP=0]="LM_SKIP"}(ya||(ya={})),function(t){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",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP"}(wa||(wa={})),be._defaultTemplate="ReadSingleBarcode";export{ma as BarcodeReaderModule,ha as BarcodeScanner,bs as CameraEnhancer,Ue as CameraEnhancerModule,On as CameraView,be as CaptureVisionRouter,ae as CaptureVisionRouterModule,Ae as CapturedResultReceiver,vt as CoreModule,mi as DrawingItem,En as DrawingStyleManager,pa as EnumBarcodeFormat,s as EnumBufferOverflowProtectionMode,yt as EnumCapturedResultItemType,o as EnumColourChannelUsageType,wt as EnumCornerType,xt as EnumCrossVerificationStatus,wa as EnumDeblurMode,Je as EnumDrawingItemMediaType,Qe as EnumDrawingItemState,$e as EnumEnhancedFeatures,Ct as EnumErrorCode,_a as EnumExtendedBarcodeResultType,Et as EnumGrayscaleEnhancementMode,St as EnumGrayscaleTransformationMode,a as EnumImagePixelFormat,le as EnumImageSourceState,Tt as EnumImageTagType,Ot as EnumIntermediateResultUnitType,ya as EnumLocalizationMode,jt as EnumOptimizationMode,bt as EnumPDFReadingMode,De as EnumPresetTemplate,va as EnumQRCodeErrorCorrectionLevel,It as EnumRasterDataSource,At as EnumRegionObjectElementType,Ut as EnumResultStatus,Nt as EnumScanMode,Rt as EnumSectionType,Es as Feedback,Ai as GroupDrawingItem,Ei as ImageDrawingItem,Ps as ImageEditorView,ho as ImageManager,J as ImageSourceAdapter,Re as IntermediateResultReceiver,io as LicenseManager,ro as LicenseModule,xi as LineDrawingItem,Uo as MultiFrameResultCrossFilter,Oi as QuadDrawingItem,pi as RectDrawingItem,Ti as TextDrawingItem,po as UtilityModule,B as _getNorImageData,M as _saveToFile,k as _toBlob,F as _toCanvas,P as _toImage,ut as bDebug,R as checkIsLink,D as compareVersion,rt as doOrWaitAsyncDependency,at as getNextTaskID,L as handleEngineResourcePaths,ft as innerVersions,_ as isArc,v as isContour,C as isDSImageData,E as isDSRect,S as isImageTag,T as isLineSegment,p as isObject,w as isOriginalDsImageData,b as isPoint,I as isPolygon,x as isQuad,O as isRect,_t as loadWasm,it as mapAsyncDependency,gt as mapPackageRegister,ht as mapTaskCallBack,lt as onLog,A as requestResource,dt as setBDebug,ct as setOnLog,nt as waitAsyncDependency,st as worker,mt as workerAutoResources}; diff --git a/dist/dbr.no-content-bundle.esm.js b/dist/dbr.no-content-bundle.esm.js index ccd0ac5..26f55b6 100644 --- a/dist/dbr.no-content-bundle.esm.js +++ b/dist/dbr.no-content-bundle.esm.js @@ -4,8 +4,8 @@ * @website http://www.dynamsoft.com * @copyright Copyright 2025, Dynamsoft Corporation * @author Dynamsoft -* @version 10.4.3100 +* @version 10.5.3000 * @fileoverview Dynamsoft JavaScript Library for Barcode Reader * More info on dbr JS: https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/ */ -import{CaptureVisionRouter as o}from"dynamsoft-capture-vision-router";export*from"dynamsoft-capture-vision-router";export*from"dynamsoft-core";export*from"dynamsoft-license";export*from"dynamsoft-camera-enhancer";export*from"dynamsoft-barcode-reader";export*from"dynamsoft-utility";o._defaultTemplate="ReadSingleBarcode"; +import{CoreModule as e,EnumCapturedResultItemType as t,_toCanvas as i,EnumImagePixelFormat as s}from"dynamsoft-core";export*from"dynamsoft-core";import{CaptureVisionRouter as n,CapturedResultReceiver as o}from"dynamsoft-capture-vision-router";export*from"dynamsoft-capture-vision-router";import{CameraView as r,CameraEnhancer as a}from"dynamsoft-camera-enhancer";export*from"dynamsoft-camera-enhancer";import{LicenseManager as c}from"dynamsoft-license";export*from"dynamsoft-license";import{MultiFrameResultCrossFilter as l}from"dynamsoft-utility";export*from"dynamsoft-utility";export*from"dynamsoft-barcode-reader";function d(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)}function u(e,t,i,s,n){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?n.call(e,i):n?n.value=i:t.set(e,i),i}"function"==typeof SuppressedError&&SuppressedError;const h="undefined"==typeof self,f="function"==typeof importScripts,m=(()=>{if(!f){if(!h&&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"./"}})(),g=e=>{if(null==e&&(e="./"),h||f);else{let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e};var p,y,w;!function(e){e[e.SM_SINGLE=0]="SM_SINGLE",e[e.SM_MULTI_UNIQUE=1]="SM_MULTI_UNIQUE"}(p||(p={})),function(e){e[e.OM_NONE=0]="OM_NONE",e[e.OM_SPEED=1]="OM_SPEED",e[e.OM_COVERAGE=2]="OM_COVERAGE",e[e.OM_BALANCE=3]="OM_BALANCE",e[e.OM_DPM=4]="OM_DPM",e[e.OM_DENSE=5]="OM_DENSE"}(y||(y={})),function(e){e[e.RS_SUCCESS=0]="RS_SUCCESS",e[e.RS_CANCELLED=1]="RS_CANCELLED",e[e.RS_FAILED=2]="RS_FAILED"}(w||(w={}));var S={license:"",scanMode:p.SM_SINGLE,templateFilePath:void 0,utilizedTemplateNames:{single:"ReadSingleBarcode",multi_unique:"ReadBarcodes_SpeedFirst",image:"ReadBarcodes_ReadRateFirst"},engineResourcePaths:{rootDirectory:m},barcodeFormats:void 0,duplicateForgetTime:3e3,container:void 0,onUniqueBarcodeScanned:void 0,showResultView:!1,showUploadImageButton:!1,removePoweredByMessage:!1,uiPath:m,scannerViewConfig:{container:void 0,showCloseButton:!1},resultViewConfig:{container:void 0,toolbarButtonsConfig:{clear:{label:"Clear",className:"btn-clear",isHidden:!1},done:{label:"Done",className:"btn-done",isHidden:!1}}}};const _=e=>e&&"object"==typeof e&&"function"==typeof e.then,b=(async()=>{})().constructor;class E extends b{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,_(e)?t=e:"function"==typeof e&&(t=new b(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}constructor(e){let t,i;super(((e,s)=>{t=e,i=s})),this._s="pending",this.resolve=e=>{this.isPending&&(_(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",i(e))},this.task=e}}const v=()=>window.matchMedia("(orientation: landscape)").matches;function R(e,t){for(const s in t)"Object"===(i=t[s],Object.prototype.toString.call(i).slice(8,-1))&&s in e?R(e[s],t[s]):e[s]=t[s];var i;return e}var C,I,x,M,N,q,L,T,O,A,V,B,k,D,F,P,U,j,G,H,W;class z{constructor(e){if(C.add(this),M.set(this,void 0),N.set(this,{status:{code:w.RS_SUCCESS,message:"Success."},barcodeResults:[]}),q.set(this,!1),L.set(this,void 0),T.set(this,void 0),this.config=S,e&&"object"!=typeof e||Array.isArray(e))throw"Invalid config.";R(this.config,e)}async launch(){if(d(this,q,"f"))throw new Error("The BarcodeScanner instance has been destroyed.");if(d(z,I,"f",x)&&!d(z,I,"f",x).isFulfilled)throw new Error("Cannot call `launch()` while a previous task is still running.");return u(z,I,new E,"f",x),await d(this,C,"m",O).call(this),d(z,I,"f",x)}async decode(e,t="ReadBarcodes_Default"){return u(this,T,t,"f"),await d(this,C,"m",A).call(this,!0),this._cvRouter.capture(e,t)}dispose(){u(this,q,!0,"f"),d(z,I,"f",x)&&d(z,I,"f",x).isPending&&d(z,I,"f",x).resolve(d(this,N,"f")),this._cameraEnhancer?.dispose(),this._cameraView?.dispose(),this._cvRouter?.dispose(),this._cameraEnhancer=null,this._cameraView=null,this._cvRouter=null,window.removeEventListener("resize",d(this,M,"f")),document.querySelector(".scanner-view-container")?.remove(),document.querySelector(".result-view-container")?.remove(),document.querySelector(".barcode-scanner-container")?.remove(),document.querySelector(".loading-page")?.remove()}}I=z,M=new WeakMap,N=new WeakMap,q=new WeakMap,L=new WeakMap,T=new WeakMap,C=new WeakSet,O=async function(){try{await d(this,C,"m",A).call(this);try{await this._cameraEnhancer.open()}catch(e){d(this,C,"m",W).call(this);document.querySelector(".no-camera-view").style.display="flex"}await this._cvRouter.startCapturing(d(this,T,"f"))}catch(e){d(this,N,"f").status={code:w.RS_FAILED,message:e.message||e},d(z,I,"f",x).reject(new Error(d(this,N,"f").status.message)),this.dispose()}finally{const e=document.querySelector(".loading-page");e&&(e.style.display="none")}},A=async function(t=!1){e.engineResourcePaths=this.config.engineResourcePaths,t||(this._cameraView=await r.createInstance(),this.config.scanMode===p.SM_SINGLE&&(this._cameraView._capturedResultReceiver.onCapturedResultReceived=()=>{}),await d(this,C,"m",B).call(this)),await c.initLicense(this.config.license||"",{executeNow:!0}),this._cvRouter=this._cvRouter||await n.createInstance(),await d(this,C,"m",V).call(this,t),t||(this._cameraEnhancer=await a.createInstance(this._cameraView),this._cvRouter.setInput(this._cameraEnhancer),d(this,C,"m",k).call(this),await d(this,C,"m",D).call(this))},V=async function(e=!1){e||(this.config.scanMode===p.SM_SINGLE?u(this,T,this.config.utilizedTemplateNames.single,"f"):this.config.scanMode===p.SM_MULTI_UNIQUE&&u(this,T,this.config.utilizedTemplateNames.multi_unique,"f")),this.config.templateFilePath&&await this._cvRouter.initSettings(this.config.templateFilePath);const i=await this._cvRouter.getSimplifiedSettings(d(this,T,"f"));e||this.config.scanMode!==p.SM_SINGLE||(i.capturedResultItemTypes=t.CRIT_ORIGINAL_IMAGE|t.CRIT_BARCODE);let s=this.config.barcodeFormats;if(s){Array.isArray(s)||(s=[s]),i.barcodeSettings.barcodeFormatIds=BigInt(0);for(let e=0;e{if("string"!=typeof e)throw new TypeError("Invalid url.");const t=await fetch(e);if(!t.ok)throw Error("Network Error: "+t.statusText);const i=await t.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const s=document.createElement("div");if(s.insertAdjacentHTML("beforeend",i),1===s.childElementCount&&s.firstChild instanceof HTMLTemplateElement)return s.firstChild.content;const n=new DocumentFragment;for(let e of s.children)n.append(e);return n})(t);i.querySelectorAll("style").forEach((e=>{document.head.appendChild(e.cloneNode(!0))})),u(this,L,i.querySelector(".result-item"),"f");const s=i.querySelector(".btn-clear");if(s&&(s.addEventListener("click",(()=>{d(this,N,"f").barcodeResults=[],d(this,C,"m",G).call(this)})),this.config?.resultViewConfig?.toolbarButtonsConfig?.clear)){const e=this.config.resultViewConfig.toolbarButtonsConfig.clear;s.style.display=e.isHidden?"none":"flex",s.className=e.className?e.className:"btn-clear",s.innerText=e.label?e.label:"Clear",e.isHidden&&(i.querySelector(".toolbar-btns").style.justifyContent="center")}const n=i.querySelector(".btn-done");if(n&&(n.addEventListener("click",(()=>{const e=document.querySelector(".loading-page");e&&"none"===getComputedStyle(e).display&&this.dispose()})),this.config?.resultViewConfig?.toolbarButtonsConfig?.done)){const e=this.config.resultViewConfig.toolbarButtonsConfig.done;n.style.display=e.isHidden?"none":"flex",n.className=e.className?e.className:"btn-done",n.innerText=e.label?e.label:"Done",e.isHidden&&(i.querySelector(".toolbar-btns").style.justifyContent="center")}const o=this.config?.scannerViewConfig?.showCloseButton;if(o){const e=i.querySelector(".btn-close");e&&(e.style.display="",e.addEventListener("click",(()=>{d(this,N,"f").barcodeResults=[],d(this,N,"f").status={code:w.RS_CANCELLED,message:"Cancelled."},this.dispose()})))}this.config.showUploadImageButton&&d(this,C,"m",W).call(this,i.querySelector(".btn-upload-image"));const r=this._cameraView.getUIElement();r.shadowRoot.querySelector(".dce-sel-camera").remove(),r.shadowRoot.querySelector(".dce-sel-resolution").remove(),this._cameraView.setVideoFit("cover");const a=i.querySelector(".barcode-scanner-container");a.style.display=v()?"flex":"";const c=this.config.showResultView&&this.config.scanMode!==p.SM_SINGLE;let l;if(this.config.container?(a.style.position="relative",l=this.config.container):l=document.body,"string"==typeof l&&(l=document.querySelector(l),null===l))throw new Error("Failed to get the container");let h=this.config.scannerViewConfig.container;if("string"==typeof h&&(h=document.querySelector(h),null===h))throw new Error("Failed to get the container of the scanner view.");let f=this.config.resultViewConfig.container;if("string"==typeof f&&(f=document.querySelector(f),null===f))throw new Error("Failed to get the container of the result view.");const m=i.querySelector(".scanner-view-container"),y=i.querySelector(".result-view-container"),S=i.querySelector(".loading-page");m.append(S),h&&(m.append(r),h.append(m)),f&&f.append(y),h||f?h&&!f?(this.config.container||(y.style.position="absolute"),f=y,l.append(y)):!h&&f&&(this.config.container||(m.style.position="absolute"),h=m,m.append(r),l.append(m)):(h=m,f=y,c&&(Object.assign(m.style,{width:v()?"50%":"100%",height:v()?"100%":"50%"}),Object.assign(y.style,{width:v()?"50%":"100%",height:v()?"100%":"50%"})),m.append(r),l.append(a)),document.querySelector(".result-view-container").style.display=c?"":"none",this.config.removePoweredByMessage&&(r.shadowRoot.querySelector(".dce-msg-poweredby").style.display="none",document.querySelector(".no-result-svg").style.display="none"),u(this,M,(()=>{Object.assign(a.style,{display:v()?"flex":""}),!c||this.config.scannerViewConfig.container||this.config.resultViewConfig.container||(Object.assign(h.style,{width:v()?"50%":"100%",height:v()?"100%":"50%"}),Object.assign(f.style,{width:v()?"50%":"100%",height:v()?"100%":"50%"}))}),"f"),window.addEventListener("resize",d(this,M,"f")),this._cameraView._createDrawingLayer(2)},k=function(){const e=new o;let t=0;e.onCapturedResultReceived=async e=>{e.barcodeResultItems&&(this.config.scanMode===p.SM_SINGLE?2==++t&&d(this,C,"m",F).call(this,e):d(this,C,"m",P).call(this,e))},this._cvRouter.addResultReceiver(e)},D=async function(){const e=new l;e.enableResultCrossVerification(2,!0),e.enableResultDeduplication(2,!0),e.setDuplicateForgetTime(2,this.config.duplicateForgetTime),e.onDecodedBarcodesReceived=()=>{},await this._cvRouter.addResultFilter(e)},F=function(e){const n=this._cameraView.getUIElement().shadowRoot;new Promise((t=>{if(e.barcodeResultItems.length>1){d(this,C,"m",j).call(this);for(let i of e.barcodeResultItems){let e=0,s=0;for(let t=0;t<4;++t){let n=i.location.points[t];e+=n.x,s+=n.y}let o=this._cameraEnhancer.convertToClientCoordinates({x:e/4,y:s/4}),r=document.createElement("div");r.className="single-barcode-result-option",Object.assign(r.style,{position:"fixed",width:"32px",height:"32px",border:"#fff solid 4px","box-sizing":"border-box","border-radius":"16px",background:"#080",cursor:"pointer",transform:"translate(-50%, -50%)"}),r.style.left=o.x+"px",r.style.top=o.y+"px",r.addEventListener("click",(()=>{t(i)})),n.append(r)}}else t(e.barcodeResultItems[0])})).then((n=>{const o=e.items.filter((e=>e.type===t.CRIT_ORIGINAL_IMAGE))[0].imageData,r={status:{code:w.RS_SUCCESS,message:"Success."},originalImageResult:o,barcodeImage:(()=>{const e=i(o),t=n.location.points,r=Math.min(...t.map((e=>e.x))),a=Math.min(...t.map((e=>e.y))),c=Math.max(...t.map((e=>e.x)))-r,l=Math.max(...t.map((e=>e.y)))-a,d=document.createElement("canvas");d.width=c,d.height=l;const u=d.getContext("2d");u.beginPath(),u.moveTo(t[0].x-r,t[0].y-a);for(let e=1;ee.id===`${i.formatString}_${i.text}`));-1===e?(i.count=1,d(this,N,"f").barcodeResults.unshift(i),d(this,C,"m",G).call(this,i)):(d(this,N,"f").barcodeResults[e].count++,d(this,C,"m",H).call(this,e)),this.config.onUniqueBarcodeScanned&&this.config.onUniqueBarcodeScanned(i)}},U=function(e){const t=d(this,L,"f").cloneNode(!0);t.querySelector(".format-string").innerText=e.formatString;t.querySelector(".text-string").innerText=e.text.replace(/\n|\r/g,""),t.id=`${e.formatString}_${e.text}`;return t.querySelector(".delete-icon").addEventListener("click",(()=>{const t=[...document.querySelectorAll(".main-list .result-item")],i=t.findIndex((t=>t.id===`${e.formatString}_${e.text}`));d(this,N,"f").barcodeResults.splice(i,1),t[i].remove()})),t},j=function(){const e=this._cameraView.getUIElement().shadowRoot;if(e.querySelector(".single-mode-mask"))return;const t=document.createElement("div");t.className="single-mode-mask",Object.assign(t.style,{width:"100%",height:"100%",position:"absolute",top:"0",left:"0",right:"0",bottom:"0","background-color":"#4C4C4C",opacity:"0.5"}),e.append(t),this._cameraEnhancer.pause(),this._cvRouter.stopCapturing()},G=function(e){const t=document.querySelector(".no-result-svg");if(!(this.config.showResultView&&this.config.scanMode!==p.SM_SINGLE))return;const i=document.querySelector(".main-list");if(!e)return i.textContent="",void(t.style.display="");t.style.display="none";const s=d(this,C,"m",U).call(this,e);i.insertBefore(s,document.querySelector(".result-item"))},H=function(e){const t=document.querySelectorAll(".main-list .result-item"),i=t[e].querySelector(".result-count");let s=parseInt(i.textContent.replace("x",""));t[e].querySelector(".result-count").textContent="x"+ ++s},W=function(e){e||(e=document.querySelector(".btn-upload-image")),e&&(e.style.display="",e.addEventListener("change",(async e=>{const t=e.target.files,i={status:{code:w.RS_SUCCESS,message:"Success."},barcodeResults:[]};for(let e of t)try{const t=await this.decode(e,this.config.utilizedTemplateNames.image);t.barcodeResultItems&&i.barcodeResults.push(...t.barcodeResultItems)}catch(e){i.status={code:w.RS_FAILED,message:e.message||e},d(z,I,"f",x).reject(i.status.message),this.dispose()}d(z,I,"f",x).resolve(i),this.dispose()})))},x={value:null},n._defaultTemplate="ReadSingleBarcode";export{z as BarcodeScanner,y as EnumOptimizationMode,w as EnumResultStatus,p as EnumScanMode}; diff --git a/dist/dynamsoft-barcode-reader@10.4.31/dist/DBR-PresetTemplates.json b/dist/dynamsoft-barcode-reader@10.4.31/dist/DBR-PresetTemplates.json new file mode 100644 index 0000000..8bc3616 --- /dev/null +++ b/dist/dynamsoft-barcode-reader@10.4.31/dist/DBR-PresetTemplates.json @@ -0,0 +1,628 @@ +{ + "CaptureVisionTemplates": [ + { + "Name": "ReadBarcodes_Default", + "ImageROIProcessingNameArray": [ + "roi-read-barcodes" + ], + "Timeout": 10000 + }, + { + "Name": "ReadBarcodes_SpeedFirst", + "ImageROIProcessingNameArray": [ + "roi-read-barcodes-speed-first" + ], + "Timeout": 10000 + }, + { + "Name": "ReadBarcodes_ReadRateFirst", + "ImageROIProcessingNameArray": [ + "roi-read-barcodes-read-rate" + ], + "Timeout": 100000 + }, + { + "Name": "ReadSingleBarcode", + "ImageROIProcessingNameArray": [ + "roi-read-single-barcode" + ], + "Timeout": 10000 + }, + { + "Name": "ReadBarcodes_Balance", + "ImageROIProcessingNameArray": [ + "roi-read-barcodes-balance" + ], + "Timeout": 100000 + }, + { + "Name": "ReadDenseBarcodes", + "ImageROIProcessingNameArray": [ + "roi-read-barcodes-dense" + ], + "Timeout": 10000 + }, + { + "Name": "ReadDistantBarcodes", + "ImageROIProcessingNameArray": [ + "roi-read-barcodes-distant" + ], + "Timeout": 10000 + } + ], + "TargetROIDefOptions": [ + { + "Name": "roi-read-barcodes", + "TaskSettingNameArray": [ + "task-read-barcodes" + ] + }, + { + "Name": "roi-read-barcodes-speed-first", + "TaskSettingNameArray": [ + "task-read-barcodes-speed-first" + ] + }, + { + "Name": "roi-read-barcodes-read-rate", + "TaskSettingNameArray": [ + "task-read-barcodes-read-rate" + ] + }, + { + "Name": "roi-read-single-barcode", + "TaskSettingNameArray": [ + "task-read-single-barcode" + ] + }, + { + "Name": "roi-read-barcodes-balance", + "TaskSettingNameArray": [ + "task-read-barcodes-balance" + ] + }, + { + "Name": "roi-read-barcodes-dense", + "TaskSettingNameArray": [ + "task-read-barcodes-dense" + ] + }, + { + "Name": "roi-read-barcodes-distant", + "TaskSettingNameArray": [ + "task-read-barcodes-distant" + ] + } + ], + "BarcodeFormatSpecificationOptions": [ + { + "Name": "bfs1", + "BarcodeFormatIds": [ + "BF_PDF417", + "BF_QR_CODE", + "BF_DATAMATRIX", + "BF_AZTEC", + "BF_MICRO_QR", + "BF_MICRO_PDF417", + "BF_DOTCODE" + ], + "MirrorMode": "MM_BOTH" + }, + { + "Name": "bfs2", + "BarcodeFormatIds": [ + "BF_ALL" + ], + "MirrorMode": "MM_NORMAL" + }, + { + "Name": "bfs1-speed-first", + "BaseBarcodeFormatSpecification": "bfs1" + }, + { + "Name": "bfs2-speed-first", + "BaseBarcodeFormatSpecification": "bfs2" + }, + { + "Name": "bfs1-read-rate-first", + "BaseBarcodeFormatSpecification": "bfs1" + }, + { + "Name": "bfs2-read-rate-first", + "BaseBarcodeFormatSpecification": "bfs2" + }, + { + "Name": "bfs1-single-barcode", + "BaseBarcodeFormatSpecification": "bfs1" + }, + { + "Name": "bfs2-single-barcode", + "BaseBarcodeFormatSpecification": "bfs2" + }, + { + "Name": "bfs1-balance", + "BaseBarcodeFormatSpecification": "bfs1" + }, + { + "Name": "bfs2-balance", + "BaseBarcodeFormatSpecification": "bfs2" + }, + { + "Name": "bfs1-dense", + "BaseBarcodeFormatSpecification": "bfs1" + }, + { + "Name": "bfs2-dense", + "BaseBarcodeFormatSpecification": "bfs2" + }, + { + "Name": "bfs1-distant", + "BaseBarcodeFormatSpecification": "bfs1" + }, + { + "Name": "bfs2-distant", + "BaseBarcodeFormatSpecification": "bfs2" + } + ], + "BarcodeReaderTaskSettingOptions": [ + { + "Name": "task-read-barcodes", + "ExpectedBarcodesCount": 0, + "LocalizationModes": [ + { + "Mode": "LM_CONNECTED_BLOCKS" + }, + { + "Mode": "LM_LINES" + } + ], + "DeblurModes": [ + { + "Mode": "DM_BASED_ON_LOC_BIN" + }, + { + "Mode": "DM_THRESHOLD_BINARIZATION" + } + ], + "BarcodeFormatSpecificationNameArray": [ + "bfs1", + "bfs2" + ], + "SectionImageParameterArray": [ + { + "Section": "ST_REGION_PREDETECTION", + "ImageParameterName": "ip-read-barcodes" + }, + { + "Section": "ST_BARCODE_LOCALIZATION", + "ImageParameterName": "ip-read-barcodes" + }, + { + "Section": "ST_BARCODE_DECODING", + "ImageParameterName": "ip-read-barcodes" + } + ] + }, + { + "Name": "task-read-barcodes-speed-first", + "ExpectedBarcodesCount": 0, + "LocalizationModes": [ + { + "Mode": "LM_SCAN_DIRECTLY", + "ScanDirection": 2 + }, + { + "Mode": "LM_CONNECTED_BLOCKS" + } + ], + "DeblurModes": [ + { + "Mode": "DM_BASED_ON_LOC_BIN" + }, + { + "Mode": "DM_THRESHOLD_BINARIZATION" + }, + { + "Mode": "DM_DEEP_ANALYSIS" + } + ], + "BarcodeFormatSpecificationNameArray": [ + "bfs1-speed-first", + "bfs2-speed-first" + ], + "SectionImageParameterArray": [ + { + "Section": "ST_REGION_PREDETECTION", + "ImageParameterName": "ip-read-barcodes-speed-first" + }, + { + "Section": "ST_BARCODE_LOCALIZATION", + "ImageParameterName": "ip-read-barcodes-speed-first" + }, + { + "Section": "ST_BARCODE_DECODING", + "ImageParameterName": "ip-read-barcodes-speed-first" + } + ] + }, + { + "Name": "task-read-barcodes-read-rate", + "ExpectedBarcodesCount": 999, + "LocalizationModes": [ + { + "Mode": "LM_CONNECTED_BLOCKS" + }, + { + "Mode": "LM_LINES" + }, + { + "Mode": "LM_STATISTICS" + } + ], + "DeblurModes": [ + { + "Mode": "DM_BASED_ON_LOC_BIN" + }, + { + "Mode": "DM_THRESHOLD_BINARIZATION" + }, + { + "Mode": "DM_DIRECT_BINARIZATION" + }, + { + "Mode": "DM_SMOOTHING" + } + ], + "BarcodeFormatSpecificationNameArray": [ + "bfs1-read-rate-first", + "bfs2-read-rate-first" + ], + "SectionImageParameterArray": [ + { + "Section": "ST_REGION_PREDETECTION", + "ImageParameterName": "ip-read-barcodes-read-rate" + }, + { + "Section": "ST_BARCODE_LOCALIZATION", + "ImageParameterName": "ip-read-barcodes-read-rate" + }, + { + "Section": "ST_BARCODE_DECODING", + "ImageParameterName": "ip-read-barcodes-read-rate" + } + ] + }, + { + "Name": "task-read-single-barcode", + "ExpectedBarcodesCount": 1, + "LocalizationModes": [ + { + "Mode": "LM_SCAN_DIRECTLY", + "ScanDirection": 2 + }, + { + "Mode": "LM_CONNECTED_BLOCKS" + } + ], + "DeblurModes": [ + { + "Mode": "DM_BASED_ON_LOC_BIN" + }, + { + "Mode": "DM_THRESHOLD_BINARIZATION" + }, + { + "Mode": "DM_DEEP_ANALYSIS" + } + ], + "BarcodeFormatSpecificationNameArray": [ + "bfs1-single-barcode", + "bfs2-single-barcode" + ], + "SectionImageParameterArray": [ + { + "Section": "ST_REGION_PREDETECTION", + "ImageParameterName": "ip-read-single-barcode" + }, + { + "Section": "ST_BARCODE_LOCALIZATION", + "ImageParameterName": "ip-read-single-barcode" + }, + { + "Section": "ST_BARCODE_DECODING", + "ImageParameterName": "ip-read-single-barcode" + } + ] + }, + { + "Name": "task-read-barcodes-balance", + "ExpectedBarcodesCount": 999, + "LocalizationModes": [ + { + "Mode": "LM_CONNECTED_BLOCKS" + }, + { + "Mode": "LM_SCAN_DIRECTLY" + } + ], + "DeblurModes": [ + { + "Mode": "DM_BASED_ON_LOC_BIN" + }, + { + "Mode": "DM_THRESHOLD_BINARIZATION" + }, + { + "Mode": "DM_DIRECT_BINARIZATION" + } + ], + "BarcodeFormatSpecificationNameArray": [ + "bfs1-balance", + "bfs2-balance" + ], + "SectionImageParameterArray": [ + { + "Section": "ST_REGION_PREDETECTION", + "ImageParameterName": "ip-read-barcodes-balance" + }, + { + "Section": "ST_BARCODE_LOCALIZATION", + "ImageParameterName": "ip-read-barcodes-balance" + }, + { + "Section": "ST_BARCODE_DECODING", + "ImageParameterName": "ip-read-barcodes-balance" + } + ] + }, + { + "Name": "task-read-barcodes-dense", + "ExpectedBarcodesCount": 0, + "LocalizationModes": [ + { + "Mode": "LM_CONNECTED_BLOCKS" + }, + { + "Mode": "LM_LINES" + } + ], + "DeblurModes": [ + { + "Mode": "DM_BASED_ON_LOC_BIN" + }, + { + "Mode": "DM_THRESHOLD_BINARIZATION" + }, + { + "Mode": "DM_DIRECT_BINARIZATION" + }, + { + "Mode": "DM_SMOOTHING" + }, + { + "Mode": "DM_GRAY_EQUALIZATION" + } + ], + "BarcodeFormatSpecificationNameArray": [ + "bfs1-dense", + "bfs2-dense" + ], + "SectionImageParameterArray": [ + { + "Section": "ST_REGION_PREDETECTION", + "ImageParameterName": "ip-read-barcodes-dense" + }, + { + "Section": "ST_BARCODE_LOCALIZATION", + "ImageParameterName": "ip-read-barcodes-dense" + }, + { + "Section": "ST_BARCODE_DECODING", + "ImageParameterName": "ip-read-barcodes-dense" + } + ] + }, + { + "Name": "task-read-barcodes-distant", + "ExpectedBarcodesCount": 0, + "LocalizationModes": [ + { + "Mode": "LM_CONNECTED_BLOCKS" + }, + { + "Mode": "LM_LINES" + } + ], + "DeblurModes": [ + { + "Mode": "DM_BASED_ON_LOC_BIN" + }, + { + "Mode": "DM_THRESHOLD_BINARIZATION" + }, + { + "Mode": "DM_DIRECT_BINARIZATION" + } + ], + "BarcodeFormatSpecificationNameArray": [ + "bfs1-distant", + "bfs2-distant" + ], + "SectionImageParameterArray": [ + { + "Section": "ST_REGION_PREDETECTION", + "ImageParameterName": "ip-read-barcodes-distant" + }, + { + "Section": "ST_BARCODE_LOCALIZATION", + "ImageParameterName": "ip-read-barcodes-distant" + }, + { + "Section": "ST_BARCODE_DECODING", + "ImageParameterName": "ip-read-barcodes-distant" + } + ] + } + ], + "ImageParameterOptions": [ + { + "Name": "ip-read-barcodes", + "TextDetectionMode": { + "Mode": "TTDM_LINE", + "Direction": "UNKNOWN", + "Sensitivity": 3 + }, + "IfEraseTextZone": 1, + "BinarizationModes": [ + { + "Mode": "BM_LOCAL_BLOCK", + "BlockSizeX": 71, + "BlockSizeY": 71, + "EnableFillBinaryVacancy": 0 + } + ], + "GrayscaleTransformationModes": [ + { + "Mode": "GTM_ORIGINAL" + } + ] + }, + { + "Name": "ip-read-barcodes-speed-first", + "TextDetectionMode": { + "Mode": "TTDM_LINE", + "Direction": "UNKNOWN", + "Sensitivity": 3 + }, + "IfEraseTextZone": 1, + "BinarizationModes": [ + { + "Mode": "BM_LOCAL_BLOCK", + "BlockSizeX": 27, + "BlockSizeY": 27, + "EnableFillBinaryVacancy": 1 + } + ], + "GrayscaleTransformationModes": [ + { + "Mode": "GTM_ORIGINAL" + } + ], + "ScaleDownThreshold": 2300 + }, + { + "Name": "ip-read-barcodes-read-rate", + "TextDetectionMode": { + "Mode": "TTDM_LINE", + "Direction": "UNKNOWN", + "Sensitivity": 3 + }, + "IfEraseTextZone": 1, + "BinarizationModes": [ + { + "Mode": "BM_LOCAL_BLOCK", + "BlockSizeX": 0, + "BlockSizeY": 0, + "EnableFillBinaryVacancy": 1 + } + ], + "GrayscaleTransformationModes": [ + { + "Mode": "GTM_ORIGINAL" + } + ], + "ScaleDownThreshold": 100000 + }, + { + "Name": "ip-read-single-barcode", + "TextDetectionMode": { + "Mode": "TTDM_LINE", + "Direction": "UNKNOWN", + "Sensitivity": 3 + }, + "IfEraseTextZone": 1, + "BinarizationModes": [ + { + "Mode": "BM_LOCAL_BLOCK", + "BlockSizeX": 27, + "BlockSizeY": 27, + "EnableFillBinaryVacancy": 0 + } + ], + "GrayscaleTransformationModes": [ + { + "Mode": "GTM_ORIGINAL" + } + ], + "ScaleDownThreshold": 2300 + }, + { + "Name": "ip-read-barcodes-balance", + "TextDetectionMode": { + "Mode": "TTDM_LINE", + "Direction": "UNKNOWN", + "Sensitivity": 3 + }, + "IfEraseTextZone": 1, + "BinarizationModes": [ + { + "Mode": "BM_LOCAL_BLOCK", + "BlockSizeX": 0, + "BlockSizeY": 0, + "EnableFillBinaryVacancy": 1 + } + ], + "GrayscaleTransformationModes": [ + { + "Mode": "GTM_ORIGINAL" + } + ] + }, + { + "Name": "ip-read-barcodes-dense", + "TextDetectionMode": { + "Mode": "TTDM_LINE", + "Direction": "UNKNOWN", + "Sensitivity": 3 + }, + "IfEraseTextZone": 1, + "BinarizationModes": [ + { + "Mode": "BM_LOCAL_BLOCK", + "BlockSizeX": 0, + "BlockSizeY": 0, + "EnableFillBinaryVacancy": 1 + } + ], + "GrayscaleTransformationModes": [ + { + "Mode": "GTM_ORIGINAL" + } + ], + "ScaleDownThreshold": 100000 + }, + { + "Name": "ip-read-barcodes-distant", + "TextDetectionMode": { + "Mode": "TTDM_LINE", + "Direction": "UNKNOWN", + "Sensitivity": 3 + }, + "IfEraseTextZone": 1, + "BinarizationModes": [ + { + "Mode": "BM_LOCAL_BLOCK", + "BlockSizeX": 0, + "BlockSizeY": 0, + "EnableFillBinaryVacancy": 1 + } + ], + "GrayscaleTransformationModes": [ + { + "Mode": "GTM_ORIGINAL" + } + ], + "ScaleDownThreshold": 2300 + } + ] +} \ No newline at end of file diff --git a/dist/dynamsoft-barcode-reader@10.4.31/dist/dbr.d.ts b/dist/dynamsoft-barcode-reader@10.4.31/dist/dbr.d.ts new file mode 100644 index 0000000..7e39e52 --- /dev/null +++ b/dist/dynamsoft-barcode-reader@10.4.31/dist/dbr.d.ts @@ -0,0 +1,383 @@ +import { CapturedResultItem, Quadrilateral, ImageTag, RegionObjectElement, DSImageData, EnumGrayscaleTransformationMode, EnumGrayscaleEnhancementMode, IntermediateResultExtraInfo, IntermediateResultUnit } from 'dynamsoft-core'; + +declare class BarcodeReaderModule { + static getVersion(): string; +} + +declare const EnumBarcodeFormat: { + /**No barcode format in BarcodeFormat*/ + BF_NULL: bigint; + /**All supported formats in BarcodeFormat*/ + BF_ALL: bigint; + /**Use the default barcode format settings*/ + BF_DEFAULT: bigint; + /**Combined value of BF_CODABAR, BF_CODE_128, BF_CODE_39, BF_CODE_39_Extended, BF_CODE_93, BF_EAN_13, BF_EAN_8, INDUSTRIAL_25, BF_ITF, BF_UPC_A, BF_UPC_E, BF_MSI_CODE; */ + BF_ONED: bigint; + /**Combined value of BF_GS1_DATABAR_OMNIDIRECTIONAL, BF_GS1_DATABAR_TRUNCATED, BF_GS1_DATABAR_STACKED, BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL, BF_GS1_DATABAR_EXPANDED, BF_GS1_DATABAR_EXPANDED_STACKED, BF_GS1_DATABAR_LIMITED*/ + BF_GS1_DATABAR: bigint; + /**Code 39 */ + BF_CODE_39: bigint; + /**Code 128 */ + BF_CODE_128: bigint; + /**Code 93 */ + BF_CODE_93: bigint; + /**Codabar */ + BF_CODABAR: bigint; + /**Interleaved 2 of 5 */ + BF_ITF: bigint; + /**EAN-13 */ + BF_EAN_13: bigint; + /**EAN-8 */ + BF_EAN_8: bigint; + /**UPC-A */ + BF_UPC_A: bigint; + /**UPC-E */ + BF_UPC_E: bigint; + /**Industrial 2 of 5 */ + BF_INDUSTRIAL_25: bigint; + /**CODE39 Extended */ + BF_CODE_39_EXTENDED: bigint; + /**GS1 Databar Omnidirectional*/ + BF_GS1_DATABAR_OMNIDIRECTIONAL: bigint; + /**GS1 Databar Truncated*/ + BF_GS1_DATABAR_TRUNCATED: bigint; + /**GS1 Databar Stacked*/ + BF_GS1_DATABAR_STACKED: bigint; + /**GS1 Databar Stacked Omnidirectional*/ + BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL: bigint; + /**GS1 Databar Expanded*/ + BF_GS1_DATABAR_EXPANDED: bigint; + /**GS1 Databar Expaned Stacked*/ + BF_GS1_DATABAR_EXPANDED_STACKED: bigint; + /**GS1 Databar Limited*/ + BF_GS1_DATABAR_LIMITED: bigint; + /**Patch code. */ + BF_PATCHCODE: bigint; + /**PDF417 */ + BF_CODE_32: bigint; + /**PDF417 */ + BF_PDF417: bigint; + /**QRCode */ + BF_QR_CODE: bigint; + /**DataMatrix */ + BF_DATAMATRIX: bigint; + /**AZTEC */ + BF_AZTEC: bigint; + /**MAXICODE */ + BF_MAXICODE: bigint; + /**Micro QR Code*/ + BF_MICRO_QR: bigint; + /**Micro PDF417*/ + BF_MICRO_PDF417: bigint; + /**GS1 Composite Code*/ + BF_GS1_COMPOSITE: bigint; + /**MSI Code*/ + BF_MSI_CODE: bigint; + BF_CODE_11: bigint; + BF_TWO_DIGIT_ADD_ON: bigint; + BF_FIVE_DIGIT_ADD_ON: bigint; + BF_MATRIX_25: bigint; + /**Combined value of BF2_USPSINTELLIGENTMAIL, BF2_POSTNET, BF2_PLANET, BF2_AUSTRALIANPOST, BF2_RM4SCC.*/ + BF_POSTALCODE: bigint; + /**Nonstandard barcode */ + BF_NONSTANDARD_BARCODE: bigint; + /**USPS Intelligent Mail.*/ + BF_USPSINTELLIGENTMAIL: bigint; + /**Postnet.*/ + BF_POSTNET: bigint; + /**Planet.*/ + BF_PLANET: bigint; + /**Australian Post.*/ + BF_AUSTRALIANPOST: bigint; + /**Royal Mail 4-State Customer Barcode.*/ + BF_RM4SCC: bigint; + /**KIX.*/ + BF_KIX: bigint; + /**DotCode.*/ + BF_DOTCODE: bigint; + /**_PHARMACODE_ONE_TRACK.*/ + BF_PHARMACODE_ONE_TRACK: bigint; + /**PHARMACODE_TWO_TRACK.*/ + BF_PHARMACODE_TWO_TRACK: bigint; + /**PHARMACODE.*/ + BF_PHARMACODE: bigint; +}; +type EnumBarcodeFormat = bigint; + +declare enum EnumExtendedBarcodeResultType { + EBRT_STANDARD_RESULT = 0, + EBRT_CANDIDATE_RESULT = 1, + EBRT_PARTIAL_RESULT = 2 +} + +declare enum EnumQRCodeErrorCorrectionLevel { + QRECL_ERROR_CORRECTION_H = 0, + QRECL_ERROR_CORRECTION_L = 1, + QRECL_ERROR_CORRECTION_M = 2, + QRECL_ERROR_CORRECTION_Q = 3 +} + +/** Label: DBRJS10.0.10-Check + * @enum EnumLocalizationMode + * + * Describes the localization mode. + */ +declare enum EnumLocalizationMode { + /**Not supported yet. */ + LM_AUTO = 1, + /**Localizes barcodes by searching for connected blocks. This algorithm usually gives best result and it is recommended to set ConnectedBlocks to the highest priority. */ + LM_CONNECTED_BLOCKS = 2, + /**Localizes barcodes by groups of contiguous black-white regions. This is optimized for QRCode and DataMatrix. */ + LM_STATISTICS = 4, + /**Localizes barcodes by searching for groups of lines. This is optimized for 1D and PDF417 barcodes. */ + LM_LINES = 8, + /**Localizes barcodes quickly. This mode is recommended in interactive scenario. Check @ref LM for available argument settings.*/ + LM_SCAN_DIRECTLY = 16, + /**Localizes barcodes by groups of marks.This is optimized for DPM codes. */ + LM_STATISTICS_MARKS = 32, + /**Localizes barcodes by groups of connected blocks and lines.This is optimized for postal codes. */ + LM_STATISTICS_POSTAL_CODE = 64, + /**Localizes barcodes from the centre of the image. Check @ref LM for available argument settings. */ + LM_CENTRE = 128, + /**Localizes 1D barcodes fast. Check @ref LM for available argument settings. */ + LM_ONED_FAST_SCAN = 256, + LM_REV = -2147483648, + /**Skips localization. */ + LM_SKIP = 0 +} + +/** Label: DBRJS10.0.10-Check + * @enum EnumDeblurMode + * + * Describes the deblur mode. + */ +declare enum EnumDeblurMode { + /**Performs deblur process using the direct binarization algorithm.*/ + DM_DIRECT_BINARIZATION = 1, + /**Performs deblur process using the threshold binarization algorithm.*/ + DM_THRESHOLD_BINARIZATION = 2, + /**Performs deblur process using the gray equalization algorithm.*/ + DM_GRAY_EQUALIZATION = 4, + /**Performs deblur process using the smoothing algorithm.*/ + DM_SMOOTHING = 8, + /**Performs deblur process using the morphing algorithm.*/ + DM_MORPHING = 16, + /**Performs deblur process using the deep analysis algorithm.*/ + DM_DEEP_ANALYSIS = 32, + /**Performs deblur process using the sharpening algorithm.*/ + DM_SHARPENING = 64, + /**Performs deblur process based on the binary image from the localization process.*/ + DM_BASED_ON_LOC_BIN = 128, + /**Performs deblur process using the sharpening and smoothing algorithm.*/ + DM_SHARPENING_SMOOTHING = 256, + /**Reserved setting for deblur mode.*/ + DM_REV = -2147483648, + /**Skips the deblur process.*/ + DM_SKIP = 0 +} + +interface BarcodeDetails { +} + +interface AztecDetails extends BarcodeDetails { + rows: number; + columns: number; + layerNumber: number; +} + +interface BarcodeResultItem extends CapturedResultItem { + format: EnumBarcodeFormat; + formatString: string; + text: string; + bytes: Uint8Array; + location: Quadrilateral; + confidence: number; + angle: number; + moduleSize: number; + details: BarcodeDetails; + isMirrored: boolean; + isDPM: boolean; +} + +interface DataMatrixDetails extends BarcodeDetails { + rows: number; + columns: number; + dataRegionRows: number; + dataRegionColumns: number; + dataRegionNumber: number; +} + +interface DecodedBarcodesResult { + readonly originalImageHashId: string; + readonly originalImageTag: ImageTag; + readonly barcodeResultItems: Array; + readonly errorCode: number; + readonly errorString: string; +} +declare module "dynamsoft-capture-vision-router" { + interface CapturedResultReceiver { + onDecodedBarcodesReceived?: (result: DecodedBarcodesResult) => void; + } + interface CapturedResultFilter { + onDecodedBarcodesReceived?: (result: DecodedBarcodesResult) => void; + } +} + +interface DecodedBarcodeElement extends RegionObjectElement { + format: EnumBarcodeFormat; + formatString: string; + text: string; + bytes: Uint8Array; + details: BarcodeDetails; + isDPM: boolean; + isMirrored: boolean; + angle: number; + moduleSize: number; + confidence: number; + extendedBarcodeResults: Array; +} + +interface ExtendedBarcodeResult extends DecodedBarcodeElement { + extendedBarcodeResultType: EnumExtendedBarcodeResultType; + deformation: number; + clarity: number; + samplingImage: DSImageData; +} + +interface OneDCodeDetails extends BarcodeDetails { + startCharsBytes: Array; + stopCharsBytes: Array; + checkDigitBytes: Array; + startPatternRange: number; + middlePatternRange: number; + endPatternRange: number; +} + +interface PDF417Details extends BarcodeDetails { + rows: number; + columns: number; + errorCorrectionLevel: number; + hasLeftRowIndicator: boolean; + hasRightRowIndicator: boolean; +} + +interface QRCodeDetails extends BarcodeDetails { + rows: number; + columns: number; + errorCorrectionLevel: number; + version: number; + model: number; + mode: number; + page: number; + totalPage: number; + parityData: number; + dataMaskPattern: number; + codewords: Array; +} + +interface SimplifiedBarcodeReaderSettings { + barcodeFormatIds: EnumBarcodeFormat; + expectedBarcodesCount: number; + grayscaleTransformationModes: Array; + grayscaleEnhancementModes: Array; + localizationModes: Array; + deblurModes: Array; + minResultConfidence: number; + minBarcodeTextLength: number; + barcodeTextRegExPattern: string; +} + +/** + * The `CandidateBarcodeZone` interface represents a candidate barcode zone. + */ +interface CandidateBarcodeZone { + /** Location of the candidate barcode zone within the image. */ + location: Quadrilateral; + /** Possible formats of the localized barcode. */ + possibleFormats: EnumBarcodeFormat; +} + +/** + * The `CandidateBarcodeZonesUnit` interface extends the `IntermediateResultUnit` interface and represents a unit of candidate barcode zones. + */ +interface CandidateBarcodeZonesUnit extends IntermediateResultUnit { + /** Array of candidate barcode zones represented as quadrilaterals. */ + candidateBarcodeZones: Array; +} +declare module "dynamsoft-capture-vision-router" { + interface IntermediateResultReceiver { + onCandidateBarcodeZonesUnitReceived?: (result: CandidateBarcodeZonesUnit, info: IntermediateResultExtraInfo) => void; + } +} + +interface ComplementedBarcodeImageUnit extends IntermediateResultUnit { + imageData: DSImageData; + location: Quadrilateral; +} +declare module "dynamsoft-capture-vision-router" { + interface IntermediateResultReceiver { + onComplementedBarcodeImageUnitReceived?: (result: ComplementedBarcodeImageUnit, info: IntermediateResultExtraInfo) => void; + } +} + +interface DecodedBarcodesUnit extends IntermediateResultUnit { + decodedBarcodes: Array; +} +declare module "dynamsoft-capture-vision-router" { + interface IntermediateResultReceiver { + onDecodedBarcodesReceived?: (result: DecodedBarcodesUnit, info: IntermediateResultExtraInfo) => void; + } +} + +/** + * The `DeformationResistedBarcode` interface represents a deformation-resisted barcode image. + */ +interface DeformationResistedBarcode { + /** Format of the barcode, as defined by `EnumBarcodeFormat`. */ + format: EnumBarcodeFormat; + /** Image data of the deformation-resisted barcode image. */ + imageData: DSImageData; + /** Location of the deformation-resisted barcode within the image. */ + location: Quadrilateral; +} + +/** + * The `DeformationResistedBarcodeImageUnit` interface extends the `IntermediateResultUnit` interface and represents a unit that holds the deformation-resisted barcode which includes the corresponding image data, its location, and the barcode format. + */ +interface DeformationResistedBarcodeImageUnit extends IntermediateResultUnit { + /** The deformation-resisted barcode. */ + deformationResistedBarcode: DeformationResistedBarcode; +} +declare module "dynamsoft-capture-vision-router" { + interface IntermediateResultReceiver { + onDeformationResistedBarcodeImageUnitReceived?: (result: DeformationResistedBarcodeImageUnit, info: IntermediateResultExtraInfo) => void; + } +} + +interface LocalizedBarcodeElement extends RegionObjectElement { + possibleFormats: EnumBarcodeFormat; + possibleFormatsString: string; + angle: number; + moduleSize: number; + confidence: number; +} + +interface LocalizedBarcodesUnit extends IntermediateResultUnit { + localizedBarcodes: Array; +} +declare module "dynamsoft-capture-vision-router" { + interface IntermediateResultReceiver { + onLocalizedBarcodesReceived?: (result: LocalizedBarcodesUnit, info: IntermediateResultExtraInfo) => void; + } +} + +interface ScaledUpBarcodeImageUnit extends IntermediateResultUnit { + imageData: DSImageData; +} +declare module "dynamsoft-capture-vision-router" { + interface IntermediateResultReceiver { + onScaledUpBarcodeImageUnitReceived?: (result: ScaledUpBarcodeImageUnit, info: IntermediateResultExtraInfo) => void; + } +} + +export { AztecDetails, BarcodeDetails, BarcodeReaderModule, BarcodeResultItem, CandidateBarcodeZone, CandidateBarcodeZonesUnit, ComplementedBarcodeImageUnit, DataMatrixDetails, DecodedBarcodeElement, DecodedBarcodesResult, DecodedBarcodesUnit, DeformationResistedBarcode, DeformationResistedBarcodeImageUnit, EnumBarcodeFormat, EnumDeblurMode, EnumExtendedBarcodeResultType, EnumLocalizationMode, EnumQRCodeErrorCorrectionLevel, ExtendedBarcodeResult, LocalizedBarcodeElement, LocalizedBarcodesUnit, OneDCodeDetails, PDF417Details, QRCodeDetails, ScaledUpBarcodeImageUnit, SimplifiedBarcodeReaderSettings }; diff --git a/dist/dynamsoft-barcode-reader@10.4.31/dist/dbr.esm.js b/dist/dynamsoft-barcode-reader@10.4.31/dist/dbr.esm.js new file mode 100644 index 0000000..92e4c66 --- /dev/null +++ b/dist/dynamsoft-barcode-reader@10.4.31/dist/dbr.esm.js @@ -0,0 +1,11 @@ +/*! +* Dynamsoft JavaScript Library +* @product Dynamsoft Barcode Reader JS Edition +* @website http://www.dynamsoft.com +* @copyright Copyright 2024, Dynamsoft Corporation +* @author Dynamsoft +* @version 10.4.31 +* @fileoverview Dynamsoft JavaScript Library for Barcode Reader +* More info on dbr JS: https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/ +*/ +import{CoreModule as _,workerAutoResources as I,mapPackageRegister as B,compareVersion as R,innerVersions as n}from"dynamsoft-core";const t="undefined"==typeof self,A="function"==typeof importScripts,E=(()=>{if(!A){if(!t&&document.currentScript){let _=document.currentScript.src,I=_.indexOf("?");if(-1!=I)_=_.substring(0,I);else{let I=_.indexOf("#");-1!=I&&(_=_.substring(0,I))}return _.substring(0,_.lastIndexOf("/")+1)}return"./"}})(),T=_=>{if(null==_&&(_="./"),t||A);else{let I=document.createElement("a");I.href=_,_=I.href}return _.endsWith("/")||(_+="/"),_};_.engineResourcePaths.dbr={version:"10.4.31",path:E,isInternal:!0},I.dbr={js:!1,wasm:!0,deps:["license","dip"]},B.dbr={};const i="1.4.21";"string"!=typeof _.engineResourcePaths.std&&R(_.engineResourcePaths.std.version,i)<0&&(_.engineResourcePaths.std={version:i,path:T(E+`../../dynamsoft-capture-vision-std@${i}/dist/`),isInternal:!0});const D="2.4.31";(!_.engineResourcePaths.dip||"string"!=typeof _.engineResourcePaths.dip&&R(_.engineResourcePaths.dip.version,D)<0)&&(_.engineResourcePaths.dip={version:D,path:T(E+`../../dynamsoft-image-processing@${D}/dist/`),isInternal:!0});class O{static getVersion(){const _=n.dbr&&n.dbr.wasm,I=n.dbr&&n.dbr.worker;return`10.4.31(Worker: ${I||"Not Loaded"}, Wasm: ${_||"Not Loaded"})`}}const e={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)};var C,S,N,L;!function(_){_[_.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",_[_.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",_[_.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(C||(C={})),function(_){_[_.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",_[_.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",_[_.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",_[_.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(S||(S={})),function(_){_[_.LM_AUTO=1]="LM_AUTO",_[_.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",_[_.LM_STATISTICS=4]="LM_STATISTICS",_[_.LM_LINES=8]="LM_LINES",_[_.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",_[_.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",_[_.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",_[_.LM_CENTRE=128]="LM_CENTRE",_[_.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",_[_.LM_REV=-2147483648]="LM_REV",_[_.LM_SKIP=0]="LM_SKIP"}(N||(N={})),function(_){_[_.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",_[_.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",_[_.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",_[_.DM_SMOOTHING=8]="DM_SMOOTHING",_[_.DM_MORPHING=16]="DM_MORPHING",_[_.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",_[_.DM_SHARPENING=64]="DM_SHARPENING",_[_.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",_[_.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",_[_.DM_REV=-2147483648]="DM_REV",_[_.DM_SKIP=0]="DM_SKIP"}(L||(L={}));export{O as BarcodeReaderModule,e as EnumBarcodeFormat,L as EnumDeblurMode,C as EnumExtendedBarcodeResultType,N as EnumLocalizationMode,S as EnumQRCodeErrorCorrectionLevel}; diff --git a/dist/dynamsoft-barcode-reader@10.4.31/dist/dbr.js b/dist/dynamsoft-barcode-reader@10.4.31/dist/dbr.js new file mode 100644 index 0000000..7b8b3d0 --- /dev/null +++ b/dist/dynamsoft-barcode-reader@10.4.31/dist/dbr.js @@ -0,0 +1,11 @@ +/*! +* Dynamsoft JavaScript Library +* @product Dynamsoft Barcode Reader JS Edition +* @website http://www.dynamsoft.com +* @copyright Copyright 2024, Dynamsoft Corporation +* @author Dynamsoft +* @version 10.4.31 +* @fileoverview Dynamsoft JavaScript Library for Barcode Reader +* More info on dbr JS: https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/ +*/ +!function(_,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("dynamsoft-core")):"function"==typeof define&&define.amd?define(["exports","dynamsoft-core"],e):e(((_="undefined"!=typeof globalThis?globalThis:_||self).Dynamsoft=_.Dynamsoft||{},_.Dynamsoft.DBR={}),_.Dynamsoft.Core)}(this,(function(_,e){"use strict";const n="undefined"==typeof self,t="function"==typeof importScripts,I=(()=>{if(!t){if(!n&&document.currentScript){let _=document.currentScript.src,e=_.indexOf("?");if(-1!=e)_=_.substring(0,e);else{let e=_.indexOf("#");-1!=e&&(_=_.substring(0,e))}return _.substring(0,_.lastIndexOf("/")+1)}return"./"}})(),E=_=>{if(null==_&&(_="./"),n||t);else{let e=document.createElement("a");e.href=_,_=e.href}return _.endsWith("/")||(_+="/"),_};e.CoreModule.engineResourcePaths.dbr={version:"10.4.31",path:I,isInternal:!0},e.workerAutoResources.dbr={js:!1,wasm:!0,deps:["license","dip"]},e.mapPackageRegister.dbr={};const R="1.4.21";"string"!=typeof e.CoreModule.engineResourcePaths.std&&e.compareVersion(e.CoreModule.engineResourcePaths.std.version,R)<0&&(e.CoreModule.engineResourcePaths.std={version:R,path:E(I+`../../dynamsoft-capture-vision-std@${R}/dist/`),isInternal:!0});const i="2.4.31";(!e.CoreModule.engineResourcePaths.dip||"string"!=typeof e.CoreModule.engineResourcePaths.dip&&e.compareVersion(e.CoreModule.engineResourcePaths.dip.version,i)<0)&&(e.CoreModule.engineResourcePaths.dip={version:i,path:E(I+`../../dynamsoft-image-processing@${i}/dist/`),isInternal:!0});const B={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)};var o,A,T,r;_.EnumExtendedBarcodeResultType=void 0,(o=_.EnumExtendedBarcodeResultType||(_.EnumExtendedBarcodeResultType={}))[o.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",o[o.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",o[o.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT",_.EnumQRCodeErrorCorrectionLevel=void 0,(A=_.EnumQRCodeErrorCorrectionLevel||(_.EnumQRCodeErrorCorrectionLevel={}))[A.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",A[A.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",A[A.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",A[A.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q",_.EnumLocalizationMode=void 0,(T=_.EnumLocalizationMode||(_.EnumLocalizationMode={}))[T.LM_AUTO=1]="LM_AUTO",T[T.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",T[T.LM_STATISTICS=4]="LM_STATISTICS",T[T.LM_LINES=8]="LM_LINES",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",T[T.LM_SKIP=0]="LM_SKIP",_.EnumDeblurMode=void 0,(r=_.EnumDeblurMode||(_.EnumDeblurMode={}))[r.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",r[r.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",r[r.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",r[r.DM_SMOOTHING=8]="DM_SMOOTHING",r[r.DM_MORPHING=16]="DM_MORPHING",r[r.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",r[r.DM_SHARPENING=64]="DM_SHARPENING",r[r.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",r[r.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",r[r.DM_REV=-2147483648]="DM_REV",r[r.DM_SKIP=0]="DM_SKIP",_.BarcodeReaderModule=class{static getVersion(){const _=e.innerVersions.dbr&&e.innerVersions.dbr.wasm,n=e.innerVersions.dbr&&e.innerVersions.dbr.worker;return`10.4.31(Worker: ${n||"Not Loaded"}, Wasm: ${_||"Not Loaded"})`}},_.EnumBarcodeFormat=B})); diff --git a/dist/dynamsoft-camera-enhancer@4.1.1/dist/dce.d.ts b/dist/dynamsoft-camera-enhancer@4.1.1/dist/dce.d.ts new file mode 100644 index 0000000..591b651 --- /dev/null +++ b/dist/dynamsoft-camera-enhancer@4.1.1/dist/dce.d.ts @@ -0,0 +1,1877 @@ +import { ImageTag, DSRect, DSImageData, Point, Rect, Polygon, LineSegment, Quadrilateral, ImageSourceAdapter, Warning, ImageSourceErrorListener, EnumImagePixelFormat } from 'dynamsoft-core'; + +declare class CameraEnhancerModule { + static getVersion(): string; +} + +interface VideoFrameTag extends ImageTag { + isCropped: boolean; + cropRegion: DSRect; + originalWidth: number; + originalHeight: number; + currentWidth: number; + currentHeight: number; + timeSpent: number; + timeStamp: number; +} + +interface DCEFrame extends DSImageData { + toCanvas: () => HTMLCanvasElement; + isDCEFrame: boolean; + tag?: VideoFrameTag; +} + +interface DrawingItemEvent extends Event { + targetItem: DrawingItem; + itemClientX: number; + itemClientY: number; + itemPageX: number; + itemPageY: number; +} + +interface DrawingStyle { + id?: number; + lineWidth?: number; + fillStyle?: string; + strokeStyle?: string; + paintMode?: "fill" | "stroke" | "strokeAndFill"; + fontFamily?: string; + fontSize?: number; +} + +interface Note { + name: string; + content: any; +} + +interface PlayCallbackInfo { + height: number; + width: number; + deviceId: string; +} + +interface Resolution { + width: number; + height: number; +} + +interface TipConfig { + topLeftPoint: Point; + width: number; + duration: number; + coordinateBase?: "view" | "image"; +} + +interface VideoDeviceInfo { + deviceId: string; + label: string; + /** @ignore */ + _checked: boolean; +} + +declare enum EnumDrawingItemMediaType { + DIMT_RECTANGLE = 1, + DIMT_QUADRILATERAL = 2, + DIMT_TEXT = 4, + DIMT_ARC = 8, + DIMT_IMAGE = 16, + DIMT_POLYGON = 32, + DIMT_LINE = 64, + DIMT_GROUP = 128 +} + +declare enum EnumDrawingItemState { + DIS_DEFAULT = 1, + DIS_SELECTED = 2 +} + +declare enum EnumEnhancedFeatures { + EF_ENHANCED_FOCUS = 4, + EF_AUTO_ZOOM = 16, + EF_TAP_TO_FOCUS = 64 +} + +declare enum EnumItemType { + ARC = 0, + IMAGE = 1, + LINE = 2, + POLYGON = 3, + QUAD = 4, + RECT = 5, + TEXT = 6, + GROUP = 7 +} +declare enum EnumItemState { + DEFAULT = 0, + SELECTED = 1 +} +declare abstract class DrawingItem { + #private; + /** + * TODO: replace with enum + * @ignore + */ + static arrMediaTypes: string[]; + /** + * @ignore + */ + static mapItemType: Map; + /** + * TOOD: replace with enum + * @ignore + */ + static arrStyleSelectors: string[]; + /** + * @ignore + */ + static mapItemState: Map; + protected _fabricObject: any; + /** + * TODO: make it private and replace it with 'mediaType' + * @ignore + */ + _mediaType: string; + /** + * @ignore + */ + get mediaType(): EnumDrawingItemMediaType; + /** + * TODO: rename it to 'state' and return enum + */ + get styleSelector(): string; + /** + * @ignore + */ + styleId?: number; + /** + * Returns or sets the numeric ID for the `DrawingStyle` that applies to this `DrawingItem`. + * Invoke `renderAll()` for the new `DrawingStyle` to take effect. + */ + set drawingStyleId(id: number); + get drawingStyleId(): number; + /** + * Returns or sets the coordinate system base with a string: + * - "view" for viewport-based coordinates or + * - "image" for image-based coordinates. + */ + set coordinateBase(base: "view" | "image"); + get coordinateBase(): "view" | "image"; + /** + * @ignore + */ + _zIndex?: number; + /** + * @ignore + */ + _drawingLayer: any; + /** + * @ignore + */ + _drawingLayerId: number; + /** + * Returns the numeric ID for the `DrawingLayer` this `DrawingItem` belongs to. + */ + get drawingLayerId(): number; + /** + * record the item's styles + * TODO: use enum + * @ignore + */ + _mapState_StyleId: Map; + protected mapEvent_Callbacks: Map>; + protected mapNoteName_Content: Map>; + /** + * @ignore + */ + readonly isDrawingItem: boolean; + /** + * + * @param fabricObject + * @param drawingStyleId + * @ignore + */ + constructor(fabricObject?: any, drawingStyleId?: number); + protected _setFabricObject(fabricObject: any): void; + /** + * + * @returns + * @ignore + */ + _getFabricObject(): any; + /** + * + * @param state + * @ignore + */ + setState(state: EnumDrawingItemState): void; + /** + * Returns the current state of the `DrawingItem`. + * + * @returns The current state of the `DrawingItem`, of type `EnumDrawingItemState`. + */ + getState(): EnumDrawingItemState; + /** + * @ignore + */ + _on(eventName: string, listener: (event: DrawingItemEvent) => void): void; + /** + * Binds a listener for a specific event. + * The event name is limited to "mousedown" | "mouseup" | "dblclick" | "mouseover" | "mouseout". + * @param eventName Specifies the event by its name. + * @param listener The event listener. + */ + on(eventName: "mousedown" | "mouseup" | "dblclick" | "mouseover" | "mouseout", listener: (event: DrawingItemEvent) => void): void; + /** + * @ignore + */ + _off(eventName: string, listener: (event: DrawingItemEvent) => void): void; + /** + * Unbinds a listener for a specific event. + * The event name is limited to "mousedown" | "mouseup" | "dblclick" | "mouseover" | "mouseout". + * @param eventName Specifies the event by its name. + * @param listener The event listener. + */ + off(eventName: "mousedown" | "mouseup" | "dblclick" | "mouseover" | "mouseout", listener: (event: DrawingItemEvent) => void): void; + /** + * Set if this item can be edited. + * @param editable + * @ignore + */ + _setEditable(editable: boolean): void; + /** + * Checks if a `Note` object with the specified name exists. + * @param name Specifies the name of the `Note` object. + * + * @returns Boolean indicating whether the `Note` object exists. + */ + hasNote(name: string): boolean; + /** + * Adds a `Note` object to this `DrawingItem`. + * @param note Specifies the `Note` object. + * @param replace [Optional] Whether to replace an existing note if the notes share the same name. + */ + addNote(note: Note, replace?: boolean): void; + /** + * Returns a `Note` object specified by its name, if it exists. + * @param name Specifies the name of the `Note` object. + * + * @returns The corresponding `Note` object specified by its name, if it exists. + */ + getNote(name: string): Note; + /** + * Returns a collection of all existing `Note` objects on this `DrawingItem`. + * + * @returns All existing `Note` objects on this `DrawingItem`. + */ + getNotes(): Array; + /** + * Updates the content of a specified `Note` object. + * @param name Specifies the name of the `Note` object. + * @param content Specifies the new content, can be of any type. + * @param mergeContent [Optional] Whether to merge the new content with the existing one. + */ + updateNote(name: string, content: any, mergeContent?: boolean): void; + /** + * Deletes a `Note` object specified by its name. + * @param name Specifies the name of the `Note` object. + */ + deleteNote(name: string): void; + /** + * Deletes all `Note` objects on this `DrawingItem`. + */ + clearNotes(): void; + protected abstract extendSet(property: string, value: any): boolean; + protected abstract extendGet(property: string): any; + /** + * + * @param property + * @returns + * @ignore + */ + set(property: string, value: any): void; + /** + * + * @param property + * @returns + * @ignore + */ + get(property: string): any; + /** + * Remove this item from drawing layer. + * @ignore + */ + remove(): void; + /** + * Convert item's property(width, height, x, y, etc.) from related to image/video to related to view/page. + * @param value + * @returns + */ + protected convertPropFromImageToView(value: number): number; + /** + * Convert item's property(width, height, x, y, etc.) from related to view/page to related to image/video. + * @param value + * @returns + */ + protected convertPropFromViewToImage(value: number): number; + protected abstract updateCoordinateBaseFromImageToView(): void; + protected abstract updateCoordinateBaseFromViewToImage(): void; + /** + * @ignore + */ + _setLineWidth(value: number): void; + /** + * @ignore + */ + _getLineWidth(): number; + /** + * @ignore + */ + _setFontSize(value: number): void; + /** + * @ignore + */ + _getFontSize(): number; + /** + * @ignore + */ + abstract setPosition(position: any): void; + /** + * @ignore + */ + abstract getPosition(): any; + /** + * Update item's propertys(width, height, x, y, etc.). + * It is called when item is added to layer. + * @ignore + */ + abstract updatePosition(): void; +} + +declare class DT_Rect extends DrawingItem { + #private; + constructor(rect: Rect, drawingStyleId?: number); + protected extendSet(property: string, value: any): boolean; + protected extendGet(property: string): void; + protected updateCoordinateBaseFromImageToView(): void; + protected updateCoordinateBaseFromViewToImage(): void; + setPosition(position: any): void; + getPosition(): any; + updatePosition(): void; + setRect(rect: Rect): void; + getRect(): Rect; +} + +declare class DT_Polygon extends DrawingItem { + #private; + constructor(polygon: Polygon, drawingStyleId?: number); + protected extendSet(property: string, value: any): boolean; + protected extendGet(property: string): any; + protected updateCoordinateBaseFromImageToView(): void; + protected updateCoordinateBaseFromViewToImage(): void; + setPosition(position: any): void; + getPosition(): any; + updatePosition(): void; + setPolygon(polygon: Polygon): void; + getPolygon(): Polygon; +} + +declare class DT_Image extends DrawingItem { + #private; + private image; + set maintainAspectRatio(value: boolean); + get maintainAspectRatio(): boolean; + constructor(image: DSImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, rect: Rect, maintainAspectRatio: boolean, drawingStyleId?: number); + protected extendSet(property: string, value: any): boolean; + protected extendGet(property: string): any; + protected updateCoordinateBaseFromImageToView(): void; + protected updateCoordinateBaseFromViewToImage(): void; + setPosition(position: any): void; + getPosition(): any; + updatePosition(): void; + setImage(image: DSImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement): void; + getImage(): DSImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement; + setImageRect(rect: Rect): void; + getImageRect(): Rect; +} + +declare class DT_Text extends DrawingItem { + #private; + private _text; + constructor(text: string, rect: Rect, drawingStyleId?: number); + protected extendSet(property: string, value: any): boolean; + protected extendGet(property: string): any; + protected updateCoordinateBaseFromImageToView(): void; + protected updateCoordinateBaseFromViewToImage(): void; + setPosition(position: any): void; + getPosition(): any; + updatePosition(): void; + setText(text: string): void; + getText(): string; + setTextRect(rect: Rect): void; + getTextRect(): Rect; +} + +declare class DT_Line extends DT_Polygon { + #private; + constructor(line: LineSegment, drawingStyleId?: number); + protected extendSet(property: string, value: any): boolean; + protected extendGet(property: string): any; + protected updateCoordinateBaseFromImageToView(): void; + protected updateCoordinateBaseFromViewToImage(): void; + setPosition(position: any): void; + getPosition(): any; + updatePosition(): void; + /** + * @ignore + */ + setPolygon(): void; + /** + * @ignore + */ + getPolygon(): Polygon; + setLine(line: LineSegment): void; + getLine(): LineSegment; +} + +declare class DT_Quad extends DT_Polygon { + #private; + constructor(quad: Quadrilateral, drawingStyleId?: number); + setPosition(position: any): void; + getPosition(): any; + updatePosition(): void; + /** + * @ignore + */ + setPolygon(): void; + /** + * @ignore + */ + getPolygon(): Polygon; + setQuad(quad: Quadrilateral): void; + getQuad(): Quadrilateral; +} + +declare class DT_Group extends DrawingItem { + constructor(childItems: Array); + protected extendSet(property: string, value: any): boolean; + protected extendGet(property: string): void; + protected updateCoordinateBaseFromImageToView(): void; + protected updateCoordinateBaseFromViewToImage(): void; + setPosition(): void; + getPosition(): any; + updatePosition(): void; + getChildDrawingItems(): Array; + setChildDrawingItems(item: DrawingItem): void; + removeChildItem(item: DrawingItem): void; +} + +declare class DrawingLayer { + static DDN_LAYER_ID: number; + static DBR_LAYER_ID: number; + static DLR_LAYER_ID: number; + static USER_DEFINED_LAYER_BASE_ID: number; + /** + * @ignore + */ + static TIP_LAYER_ID: number; + /** + * returns the 'fabric.Canvas' object + * @ignore + */ + fabricCanvas: any; + private id; + /** + * @ignore + */ + get width(): number; + /** + * @ignore + */ + get height(): number; + private mapType_StateAndStyleId; + private mode; + /** + * Event triggered whenever there is a change in which `DrawingItem` objects are selected or deselected. + * @param selectedDrawingItems An array of `DrawingItem` objects that have been selected as a result of the latest selection change. + * @param deselectedDrawingItems An array of `DrawingItem` objects that have been deselected as a result of the latest selection change. + * [NOTE]: This event is only functional when the `DrawingLayer` in which it is defined belongs to an `ImageEditorView` instance. + */ + onSelectionChanged: (selectedDrawingItems: Array, deselectedDrawingItems: Array) => void; + private _arrDrwaingItem; + private _arrFabricObject; + private _visible; + /** + * @ignore + */ + _manager: any; + /** + * @ignore + */ + set _allowMultiSelect(value: boolean); + get _allowMultiSelect(): boolean; + /** + * @ignore + */ + constructor(canvas: HTMLCanvasElement, id: number, options?: Object); + /** + * Retrieves the unique identifier of the layer. + */ + getId(): number; + /** + * Sets the visibility of the layer. + * @param visible Whether to show or hide the layer. + */ + setVisible(visible: boolean): void; + /** + * Retrieves the visibility status of the layer. + * + * @returns Boolean indicating whether the layer is visible. + */ + isVisible(): boolean; + private _getItemCurrentStyle; + /** + * Change style of drawingItems of specific media type in specific style selector. + * DrawingItems that have 'styleId' won't be changed. + * @param mediaType the mediaType of drawingItems that attend to change + * @param styleSelector + * @param drawingStyle + * @private + */ + private _changeMediaTypeCurStyleInStyleSelector; + /** + * Change the style of specific drawingItem. + * DrawingItem that has 'styleId' won't be changed. + * @param drawingItem + * @param drawingStyle + * @private + */ + private _changeItemStyle; + /** + * + * @param targetGroup + * @param item + * @param addOrRemove + * @returns + * @ignore + */ + _updateGroupItem(targetGroup: DrawingItem, item: DrawingItem, addOrRemove: string): void; + private _addDrawingItem; + /** + * Add a drawing item to the drawing layer. + * Drawing items in drawing layer with higher id are always above those in drawing layer with lower id. + * In a same drawing layer, the later added is above the previous added. + * @param drawingItem + * @ignore + */ + private addDrawingItem; + /** + * Adds an array of `DrawingItem` objects to the layer. + * @param drawingItems An array of `DrawingItem` objects. + */ + addDrawingItems(drawingItems: Array): void; + /** + * + * @param drawingItem + * @returns + * @ignore + */ + private removeDrawingItem; + /** + * Removes specified `DrawingItem` objects from the layer. + * @param drawingItems An array of `DrawingItem` objects. + */ + removeDrawingItems(drawingItems: Array): void; + /** + * Sets the layer's `DrawingItem` objects, replacing any existing items. + * @param drawingItems An array of `DrawingItem` objects. + */ + setDrawingItems(drawingItems: Array): void; + /** + * Retrieves `DrawingItem` objects from the layer, optionally filtered by a custom function. + * @param filter [Optional] A predicate function used to select a subset of `DrawingItem` objects based on specific criteria. Only items for which this function returns `true` are included in the result. + * + */ + getDrawingItems(filter?: (item: DrawingItem) => boolean): Array; + /** + * Returns an array of all selected DrawingItem instances. + * + * @returns An array of `DrawingItem` objects. + */ + getSelectedDrawingItems(): Array; + /** + * Checks if a specific `DrawingItem` exists within the layer. + * @param drawingItem Specifies the `DrawingItem`. + * + * @returns Boolean indicating whether the specific `DrawingItem` exists. + */ + hasDrawingItem(drawingItem: DrawingItem): boolean; + /** + * Clears all `DrawingItem` objects from the layer. + */ + clearDrawingItems(): void; + private _setDefaultStyle; + /** + * Establishes the baseline styling preferences for `DrawingItem` objects on the layer. + * This method offers flexible styling options tailored to the diverse requirements of `DrawingItem` objects based on their state and type: + * - Universal Application: By default, without specifying `state` or `mediaType`, the designated style is universally applied to all `DrawingItem` objects on the layer, ensuring a cohesive look and feel. + * - State-Specific Styling: Specifying only the state parameter allows the method to target `DrawingItem` objects matching that particular state, enabling differentiated styling that reflects their current status or condition. + * - Refined Targeting with State and MediaType: Providing both `state` and `mediaType` parameters focuses the style application even further, affecting only those `DrawingItem` objects that align with the specified type while in the given state. + * + * This precision is particularly useful for creating visually distinct interactions or highlighting specific elements based on their content and interaction state. + * @param drawingStyleId The unique ID of the `DrawingStyle` to be applied. + * @param state [Optional] Allows the styling to be conditional based on the `DrawingItem`'s current state. + * @param mediaType [Optional] Further refines the application of the style based on the the `DrawingItem`'s type. + */ + setDefaultStyle(drawingStyleId: number, state?: EnumDrawingItemState, mediaType?: EnumDrawingItemMediaType): void; + /** + * Change drawing layer mode, "viewer" or "editor". + * @param newMode + * @ignore + */ + setMode(newMode: string): void; + /** + * + * @returns + * @ignore + */ + getMode(): string; + /** + * Update the dimensions of drawing layer. + * @param dimensions + * @param options + * @ignore + */ + _setDimensions(dimensions: { + width: number | string; + height: number | string; + }, options?: { + backstoreOnly?: boolean; + cssOnly?: boolean; + }): void; + /** + * Update the object-fit of drawing layer. + * @param value + * @ignore + */ + _setObjectFit(value: string): void; + /** + * + * @returns + * @ignore + */ + _getObjectFit(): string; + /** + * Forces a re-render of all `DrawingItem` objects on the layer. + * Invoke this method to ensure any modifications made to existing `DrawingItem` objects are visually reflected on the layer. + */ + renderAll(): void; + /** + * @ignore + */ + dispose(): void; +} + +declare class DrawingLayerManager { + _arrDrawingLayer: DrawingLayer[]; + createDrawingLayer(baseCvs: HTMLCanvasElement, drawingLayerId: number): DrawingLayer; + deleteDrawingLayer(drawingLayerId: number): void; + clearDrawingLayers(): void; + getDrawingLayer(drawingLayerId: number): DrawingLayer; + getAllDrawingLayers(): Array; + getSelectedDrawingItems(): Array; + setDimensions(dimensions: { + width: number | string; + height: number | string; + }, options?: { + backstoreOnly?: boolean; + cssOnly?: boolean; + }): void; + setObjectFit(value: string): void; + getObjectFit(): string; + setVisible(visible: boolean): void; + _getFabricCanvas(): any; + _switchPointerEvent(): void; +} + +declare class InnerComponent extends HTMLElement { + #private; + constructor(); + getWrapper(): HTMLDivElement; + setElement(slot: "content" | "single-frame-input-container" | "drawing-layer", el: HTMLElement): void; + getElement(slot: "content" | "single-frame-input-container" | "drawing-layer"): HTMLElement; + removeElement(slot: "content" | "single-frame-input-container" | "drawing-layer"): void; +} + +declare class DT_Tip extends DT_Text { + #private; + constructor(text: string, x: number, y: number, width: number, styleId?: number); + /** + * Make the tip hidden after a period of time. + * @param duration if less then 0, it clears the timer. + */ + setDuration(duration: number): void; + getDuration(): number; +} +declare abstract class View { + #private; + /** + * @ignore + */ + _innerComponent: InnerComponent; + /** @ignore */ + _drawingLayerManager: DrawingLayerManager; + /** @ignore */ + _layerBaseCvs: HTMLCanvasElement; + /** @ignore */ + _drawingLayerOfTip: DrawingLayer; + private _tipStyleId; + /** @ignore */ + _tip: DT_Tip; + constructor(); + /** + * get the dimensions of content which the view shows. In 'CameraView', the 'content' usually means the video; in 'ImageEditorView', the 'content' usually means the image. + */ + protected abstract getContentDimensions(): { + width: number; + height: number; + objectFit: string; + }; + /** + * Create a native 'canvas' element, which will be passed to 'fabric' to create a 'fabric.Canvas'. + * In fact, all drawing layers are in one canvas. + * @ignore + */ + protected createDrawingLayerBaseCvs(width: number, height: number, objectFit?: string): HTMLCanvasElement; + /** + * Create drawing layer with specified id and size. + * Differ from 'createDrawingLayer()', the drawing layers created'createDrawingLayer()' can not Specified id, and their size is the same as video. + * @ignore + */ + _createDrawingLayer(drawingLayerId: number, width?: number, height?: number, objectFit?: string): DrawingLayer; + /** + * Creates a new `DrawingLayer` object and returns it. + * + * @returns The created `DrawingLayer` object. + */ + createDrawingLayer(): DrawingLayer; + /** + * Differ from 'deleteUserDefinedDrawingLayer()', 'deleteDrawingLayer()' can delete any layer, while 'deleteUserDefinedDrawingLayer()' can only delete user defined layer. + */ + protected deleteDrawingLayer(drawingLayerId: number): void; + /** + * Deletes a user-defined `DrawingLayer` object specified by its unique identifier (ID). + * @param id The unique identifier (ID) of the `DrawingLayer` object. + */ + deleteUserDefinedDrawingLayer(id: number): void; + /** + * Not used yet. + * @ignore + */ + _clearDrawingLayers(): void; + /** + * Clears all user-defined `DrawingLayer` objects, resetting the drawing space without affecting default built-in `DrawingLayer` objects. + */ + clearUserDefinedDrawingLayers(): void; + /** + * Retrieves a `DrawingLayer` object by its unique identifier (ID). + * @param id The unique identifier (ID) of the `DrawingLayer` object. + * + * @returns The `DrawingLayer` object specified by its unique identifier (ID) or `null`. + */ + getDrawingLayer(drawingLayerId: number): DrawingLayer; + /** + * Returns an array of all `DrawingLayer` objects . + * + * @returns An array of all `DrawingLayer` objects. + */ + getAllDrawingLayers(): Array; + /** + * update drawing layers according to content(video/image) dimensions. + */ + protected updateDrawingLayers(contentDimensions: { + width: number; + height: number; + objectFit: string; + }): void; + /** + * Returns an array of all selected DrawingItem instances across different layers, supporting complex selection scenarios. + * + * @returns An array of `DrawingItem` objects. + */ + getSelectedDrawingItems(): Array; + /** + * Applies configuration settings to the tip message box. + * This includes its position, size, display duration, and the coordinate system basis. + * @param tipConfig Configuration object for the tip message box, including top-left position, width, display duration, and coordinate system basis. + */ + setTipConfig(tipConfig: TipConfig): void; + /** + * Retrieves the current configuration of the tip message box, reflecting its position, size, display duration, and the coordinate system basis. + * + * @returns The current configuration settings of the tip message box. + */ + getTipConfig(): TipConfig; + /** + * Controls the visibility of the tip message box on the screen. + * This can be used to show or hide the tip based on user interaction or other criteria. + * @param visible Boolean flag indicating whether the tip message box should be visible (`true`) or hidden (`false`). + */ + setTipVisible(visible: boolean): void; + /** + * Checks whether the tip message box is currently visible to the user. + * + * @returns Boolean indicating the visibility of the tip message box (`true` for visible, `false` for hidden). + */ + isTipVisible(): boolean; + /** + * Updates the message displayed in the tip message box. + * This can be used to provide dynamic feedback or information to the user. + * @param message The new message to be displayed in the tip message box. + */ + updateTipMessage(message: string): void; +} + +declare class EventHandler { + #private; + get disposed(): boolean; + on(event: string, listener: Function): void; + off(event: string, listener: Function): void; + offAll(event: string): void; + fire(event: string, params?: Array, options?: { + target?: object; + async?: boolean; + copy?: boolean; + }): void; + dispose(): void; +} + +declare class CameraEnhancer extends ImageSourceAdapter { + #private; + /** @ignore */ + static _debug: boolean; + static set _onLog(value: (message: any) => void); + static get _onLog(): (message: any) => void; + /** + * @ignore + */ + static browserInfo: { + browser: string; + version: number; + OS: string; + }; + /** + * Event triggered when the running environment is not ideal. + * @param warning The warning message. + */ + static onWarning: (warning: Warning) => void; + /** + * Detect environment and get a report. + * ```js + * console.log(Dynamsoft.DCE.CameraEnhancer.detectEnvironment()); + * // {"wasm":true, "worker":true, "getUserMedia":true, "camera":true, "browser":"Chrome", "version":90, "OS":"Windows"} + * ``` + */ + static detectEnvironment(): Promise; + /** + * Tests whether the application has access to the camera. + * This static method can be used before initializing a `CameraEnhancer` instance to ensure that the device's camera can be accessed, providing a way to handle permissions or other access issues preemptively. + * This method offers the additional advantage of accelerating the camera opening process for the first time. + * + * @returns A promise that resolves with an object containing: + * - `ok`: Boolean indicating whether camera access is available. + * - `message`: A string providing additional information or the reason why camera access is not available, if applicable. + */ + static testCameraAccess(): Promise<{ + ok: boolean; + message: string; + }>; + /** + * Initializes a new instance of the `CameraEnhancer` class. + * @param view [Optional] Specifies a `CameraView` instance to provide the user interface element to display the live feed from the camera. + * + * @returns A promise that resolves with the initialized `CameraEnhancer` instance. + */ + static createInstance(view?: CameraView): Promise; + private cameraManager; + private cameraView; + /** + * @ignore + */ + private _imageDataGetter; + /** + * @ignore + */ + get video(): HTMLVideoElement; + /** + * Sets or returns the source URL for the video stream to be used by the `CameraEnhancer`. + * 1. You can use this property to specify an existing video as the source to play which will be processed the same way as the video feed from a live camera. + * 2. When playing an existing video, the camera selection and video selection boxes will be hidden. + * + * It is particularly useful for applications that need to process or display video from a specific source rather than the device's default camera. + */ + set videoSrc(src: string); + get videoSrc(): string; + /** + * Determines whether the last used camera settings should be saved and reused the next time the `CameraEnhancer` is initialized. + * + * The default is `false`. + * + * When set to `true`, the enhancer attempts to restore the previously used camera settings, offering a more seamless user experience across sessions. + * + * - This feature makes use of the [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) of the browser. + * - This feature only works on mainstream browsers like Chrome, Firefox, and Safari. Other browsers may change the device IDs dynamically thus making it impossible to track the camera. + */ + set ifSaveLastUsedCamera(value: boolean); + get ifSaveLastUsedCamera(): boolean; + /** + * Determines whether to skip the initial camera inspection process. + * + * The default is `false`, which means to opt for an optimal rear camera at the first `open()`. + * + * Setting this property to `true` bypasses the automatic inspection and configuration that typically occurs when a camera connection is established. + * This can be useful for scenarios where the default inspection process may not be desirable or necessary. + * + * Note that if a previously used camera is already available in the [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage), the inspection is skipped automatically. Read more on `ifSaveLastUsedCamera`. + */ + set ifSkipCameraInspection(value: boolean); + get ifSkipCameraInspection(): boolean; + /** + * Specifies the timeout in milliseconds for opening the camera. The default value is 15000 ms. + * + * Setting 0 means canceling the timeout or waiting indefinitely. + * + * This property sets a limit on how long the `CameraEnhancer` will attempt to open the camera before timing out. + * It can be adjusted to accommodate different devices and scenarios, ensuring that the application does not hang indefinitely while trying to access the camera. + */ + set cameraOpenTimeout(value: number); + get cameraOpenTimeout(): number; + isTorchOn: undefined | boolean; + set singleFrameMode(value: "disabled" | "camera" | "image"); + get singleFrameMode(): "disabled" | "camera" | "image"; + /** + * Event handler in camera selection in default UI. + * @ignore + */ + private _onCameraSelChange; + /** + * Event handler in resolution selection in default UI. + * @ignore + */ + private _onResolutionSelChange; + /** + * Event handler in close button in default UI. + * + * Now the close button is removed, so it is useless. + * @ignore + */ + private _onCloseBtnClick; + /** + * Event handler for single frame mode. + * @ignore + */ + private _onSingleFrameAcquired; + _intermediateResultReceiver: any; + /** + * @ignore + */ + get _isFetchingStarted(): boolean; + /** + * Set the size limit of the gotten images. + * + * By default, there is no limit. + * @ignore + */ + canvasSizeLimit: number; + /** + * It is used in `DCEFrame.tag.imageId`. + * @ignore + */ + _imageId: number; + private fetchInterval; + /** + * Returns whether the `CameraEnhancer` instance has been disposed of. + * + * @returns Boolean indicating whether the `CameraEnhancer` instance has been disposed of. + */ + get disposed(): boolean; + readonly isCameraEnhancer = true; + private constructor(); + /** + * Sets the `CameraView` instance to be used with the `CameraEnhancer`. + * This method allows for specifying a custom camera view, which can be used to display the camera feed and interface elements. + * + * @param view A `CameraView` instance that will be used to display the camera's video feed and any associated UI components. + */ + setCameraView(view: CameraView): void; + /** + * Retrieves the current `CameraView` instance associated with the `CameraEnhancer`. + * This method allows for accessing the camera view, which can be useful for manipulating the view or accessing its properties and methods. + * + * @returns The current `CameraView` instance used by the `CameraEnhancer`. + */ + getCameraView(): CameraView; + /** + * + * @returns + * @ignore + */ + private releaseCameraView; + /** + * Add some event listeners to UI element in camera view. + * @returns + * @ignore + */ + private addListenerToView; + /** + * Remove event listeners from UI element in camera view. + * @returns + */ + private removeListenerFromView; + /** + * Retrieves the current state of the camera. + * + * @returns A string indicating the camera's current state, which can be "opening", "open", or "closed". + */ + getCameraState(): string; + /** + * Checks if the camera is currently open and streaming video. + * + * @returns Boolean indicating whether the camera is open (`true`) or not (`false`). + */ + isOpen(): boolean; + /** + * Retrieves the HTMLVideoElement used by the `CameraEnhancer` for displaying the camera feed. + * This method provides direct access to the video element, enabling further customization or interaction with the video stream. + * + * @returns The `HTMLVideoElement` that is being used to display the camera's video feed. + */ + getVideoEl(): HTMLVideoElement; + /** + * Opens the currently selected camera and starts the video stream. + * + * @returns A promise that resolves with a `PlayCallbackInfo` object with details about the operation's outcome. + */ + open(): Promise; + /** + * Closes the currently active camera and stops the video stream. + */ + close(): void; + /** + * Pauses the video stream without closing the camera. + * This can be useful for temporarily halting video processing while keeping the camera ready. + */ + pause(): void; + /** + * Checks if the video stream is currently paused. + * + * @returns Boolean indicating whether the video stream is paused (`true`) or active (`false`). + */ + isPaused(): boolean; + /** + * Resumes the video stream from a paused state. + * + * @returns A promise that resolves when the video stream resumes. It does not provide any value upon resolution. + */ + resume(): Promise; + /** + * Selects a specific camera for use by the `CameraEnhancer`. The camera can be specified by a `VideoDeviceInfo` object or by its device ID. + * If called before `open()` or `show()`, the selected camera will be used. Otherwise, the system will decide which one to use. + * @param cameraObjectOrDeviceID The `VideoDeviceInfo` object or device ID string of the camera to select. + * + * @returns A promise that resolves with a `PlayCallbackInfo` object indicating the outcome of the camera selection operation. + */ + selectCamera(videoDeviceInfoOrDeviceId: VideoDeviceInfo | string): Promise; + /** + * Returns the currently selected camera device. + * + * @returns The `VideoDeviceInfo` object representing the currently active camera. + */ + getSelectedCamera(): VideoDeviceInfo; + /** + * Retrieves a list of all available video input devices (cameras) on the current device. + * + * @returns A promise that resolves with an array of `VideoDeviceInfo` objects representing each available camera. + */ + getAllCameras(): Promise>; + /** + * Sets the resolution of the video stream to a specified value. + * If the specified resolution is not exactly supported, the closest resolution will be applied. + * If called before `open()` or `show()`, the camera will use the set resolution when it opens. Otherwise, the default resolution used is 1920x1080 on desktop and 1280x720 on mobile devices. + * @param resolution The `Resolution` to which the video stream should be set. + * + * @returns A promise that resolves with a `PlayCallbackInfo` object with details about the operation's outcome. + */ + setResolution(resolution: Resolution): Promise; + /** + * Gets the current resolution of the video stream. + * + * @returns The current `Resolution` of the video stream. + */ + getResolution(): Resolution; + /** + * Retrieves a list of available resolutions supported by the currently selected camera. + * + * - The returned resolutions are limited to these values "160 by 120", "320 by 240", "480 by 360", "640 by 480", "800 by 600", "960 by 720", "1280 by 720", "1920 by 1080", "2560 by 1440", "3840 by 2160". + * - The SDK tests all these resolutions to find out which ones are supported. As a result, the method may be time-consuming. + * + * @returns A promise that resolves with an array of `Resolution` objects representing each supported resolution. + */ + getAvailableResolutions(): Promise>; + /** + * 'on()' is the wrapper of '_on()'. + * @param event includes + * @param listener + * @ignore + */ + private _on; + /** + * 'off()' is the wrapper of '_off()'. + * @param event + * @param listener + * @ignore + */ + private _off; + /** + * Registers an event listener for specific camera-related events. + * This method allows you to respond to various changes and states in the camera lifecycle. + * @param eventName The name of the event to listen for. Possible values include "cameraOpen", "cameraClose", "cameraChange", "resolutionChange", "played", "singleFrameAcquired", and "frameAddedToBuffer". + * @param listener The callback function to be invoked when the event occurs. + */ + on(eventName: "cameraOpen" | "cameraClose" | "cameraChange" | "resolutionChange" | "played" | "singleFrameAcquired" | "frameAddedToBuffer", listener: Function): void; + /** + * Removes an event listener previously registered with the `on` method. + * @param eventName The name of the event for which to remove the listener. + * @param listener The callback function that was originally registered for the event. + */ + off(eventName: "cameraOpen" | "cameraClose" | "cameraChange" | "resolutionChange" | "played" | "singleFrameAcquired" | "frameAddedToBuffer", listener: Function): void; + /** + * Retrieves the current video settings applied to the camera stream. + * + * @returns The current `MediaStreamConstraints` object representing the video stream's settings. + */ + getVideoSettings(): MediaStreamConstraints; + /** + * Updates the video settings for the camera stream with new constraints. + * @param constraints The new `MediaStreamConstraints` to apply to the video stream. + * + * @returns A promise that resolves when the new `MediaStreamConstraints` is applied. It does not provide any value upon resolution. + */ + updateVideoSettings(mediaStreamConstraints: MediaStreamConstraints): Promise; + /** + * Gets the capabilities of the current camera. + * + * At present, this method only works in Edge, Safari, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open. + * @returns A `MediaTrackCapabilities` object representing the capabilities of the camera's video track. + */ + getCapabilities(): MediaTrackCapabilities; + /** + * Retrieves the current settings of the camera. + * + * @returns The `MediaTrackSettings` object representing the current settings of the camera's video track. + */ + getCameraSettings(): MediaTrackSettings; + /** + * Turns on the camera's torch (flashlight) mode, if supported. + * This method should be called when the camera is turned on. Note that it only works with Chromium-based browsers such as Edge and Chrome on Windows or Android. Other browsers such as Firefox or Safari are not supported. Note that all browsers on iOS (including Chrome) use WebKit as the rendering engine and are not supported. + * @returns A promise that resolves when the torch has been successfully turned on. It does not provide any value upon resolution. + */ + turnOnTorch(): Promise; + /** + * Turns off the camera's torch (flashlight) mode. + * This method should be called when the camera is turned on. Note that it only works with Chromium-based browsers such as Edge and Chrome on Windows or Android. Other browsers such as Firefox or Safari are not supported. Note that all browsers on iOS (including Chrome) use WebKit as the rendering engine and are not supported. + * + * @returns A promise that resolves when the torch has been successfully turned off. It does not provide any value upon resolution. + */ + turnOffTorch(): Promise; + _taskid4AutoTorch: any; + _delay4AutoTorch: number; + grayThreshold4AutoTorch: number; + maxDarkCount4AutoTroch: number; + turnAutoTorch(delay?: number): Promise; + /** + * Sets the color temperature of the camera's video feed. + * This method should be called when the camera is turned on. Note that it only works with Chromium-based browsers such as Edge and Chrome on Windows or Android. Other browsers such as Firefox or Safari are not supported. Note that all browsers on iOS (including Chrome) use WebKit as the rendering engine and are not supported. + * @param colorTemperature The desired color temperature in Kelvin. + * + * @returns A promise that resolves when the color temperature has been successfully set. It does not provide any value upon resolution. + */ + setColorTemperature(value: number): Promise; + /** + * Retrieves the current color temperature setting of the camera's video feed. + * + * This method should be called when the camera is turned on. Note that it only works with Chromium-based browsers such as Edge and Chrome on Windows or Android. Other browsers such as Firefox or Safari are not supported. Note that all browsers on iOS (including Chrome) use WebKit as the rendering engine and are not supported. + * + * @returns The current color temperature in Kelvin. + */ + getColorTemperature(): number; + /** + * Sets the exposure compensation of the camera's video feed. + * This method should be called when the camera is turned on. Note that it only works with Chromium-based browsers such as Edge and Chrome on Windows or Android. Other browsers such as Firefox or Safari are not supported. Note that all browsers on iOS (including Chrome) use WebKit as the rendering engine and are not supported. + * @param exposureCompensation The desired exposure compensation value. + * + * @returns A promise that resolves when the exposure compensation has been successfully set. It does not provide any value upon resolution. + */ + setExposureCompensation(value: number): Promise; + /** + * Retrieves the current exposure compensation setting of the camera's video feed. + * This method should be called when the camera is turned on. Note that it only works with Chromium-based browsers such as Edge and Chrome on Windows or Android. Other browsers such as Firefox or Safari are not supported. Note that all browsers on iOS (including Chrome) use WebKit as the rendering engine and are not supported. + * + * @returns The current exposure compensation value. + */ + getExposureCompensation(): number; + /** + * 'setZoom()' is the wrapper of '_setZoom()'. '_setZoom()' can set the zoom center, which is not tested and there are no plans to make it open to clients. + * @ignore + */ + private _setZoom; + /** + * Sets the zoom level of the camera. + * + * - How it works: + * 1. If the camera supports zooming and the zoom factor is within its supported range, zooming is done directly by the camera. + * 2. If the camera does not support zooming, software-based magnification is used instead. + * 3. If the camera supports zooming but the zoom factor is beyond what it supports, the camera's maximum zoom is used, and software-based magnification is used to do the rest. (In this case, you may see a brief video flicker between the two zooming processes). + * @param settings An object containing the zoom settings. + * @param settings.factor: A number specifying the zoom level. At present, it is the only available setting. + * + * @returns A promise that resolves when the zoom level has been successfully set. It does not provide any value upon resolution. + */ + setZoom(settings: { + factor: number; + }): Promise; + /** + * Retrieves the current zoom settings of the camera. + * + * @returns An object containing the current zoom settings. As present, it contains only the zoom factor. + */ + getZoomSettings(): { + factor: number; + }; + /** + * Resets the zoom level of the camera to its default value. + * + * @returns A promise that resolves when the zoom level has been successfully reset. It does not provide any value upon resolution. + */ + resetZoom(): Promise; + /** + * Sets the frame rate of the camera's video stream. + * - At present, this method only works in Edge, Safari, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open. + * - If you provide a value that exceeds the camera's capabilities, we will automatically adjust it to the maximum value that can be applied. + * + * @param rate The desired frame rate in frames per second (fps). + * + * @returns A promise that resolves when the frame rate has been successfully set. It does not provide any value upon resolution. + */ + setFrameRate(value: number): Promise; + /** + * Retrieves the current frame rate of the camera's video stream. + * + * @returns The current frame rate in frames per second (fps). + */ + getFrameRate(): number; + /** + * Sets the focus mode of the camera. This method allows for both manual and continuous focus configurations, as well as specifying a focus area. + * - This method should be called when the camera is turned on. Note that it only works with Chromium-based browsers such as Edge and Chrome on Windows or Android. Other browsers such as Firefox or Safari are not supported. Note that all browsers on iOS (including Chrome) use WebKit as the rendering engine and are not supported. + * - Typically, `continuous` mode works best. `manual` mode based on a specific area helps the camera focus on that particular area which may seem blurry under `continuous` mode. `manual` mode with specified distances is for those rare cases where the camera distance must be fine-tuned to get the best results. + * @param settings An object describing the focus settings. The structure of this object varies depending on the mode specified (`continuous`, `manual` with fixed `distance`, or `manual` with specific `area`). + * + * @returns A promise that resolves when the focus settings have been successfully applied. It does not provide any value upon resolution. + */ + setFocus(settings: { + mode: string; + } | { + mode: "manual"; + distance: number; + } | { + mode: "manual"; + area: { + centerPoint: { + x: string; + y: string; + }; + width?: string; + height?: string; + }; + }): Promise; + /** + * Retrieves the current focus settings of the camera. + * + * @returns An object representing the current focus settings or null. + */ + getFocusSettings(): Object; + /** + * Sets the auto zoom range for the camera. + * `EF_AUTO_ZOOM` is one of the enhanced features that require a license, and is only effective when used in conjunction with other functional products of Dynamsoft. + * This method allows for specifying the minimum and maximum zoom levels that the camera can automatically adjust to. + * + * @param range An object specifying the minimum and maximum zoom levels. Both `min` and `max` should be positive numbers, with `min` less than or equal to `max`. The default is `{min: 1, max: 999}`. + */ + setAutoZoomRange(range: { + min: number; + max: number; + }): void; + /** + * Retrieves the current auto zoom range settings for the camera. + * `EF_AUTO_ZOOM` is one of the enhanced features that require a license, and is only effective when used in conjunction with other functional products of Dynamsoft. + * + * @returns An object representing the current auto zoom range, including the minimum and maximum zoom levels. + */ + getAutoZoomRange(): { + min: number; + max: number; + }; + /** + * Enables one or more enhanced features. + * This method allows for activating specific advanced capabilities that may be available. + * + * - The enhanced features require a license, and only take effect when used in conjunction with other functional products under the Dynamsoft Capture Vision(DCV)architecture. + * - `EF_ENHANCED_FOCUS` and `EF_TAP_TO_FOCUS` only works with Chromium-based browsers such as Edge and Chrome on Windows or Android. Other browsers such as Firefox or Safari are not supported. Note that all browsers on iOS (including Chrome) use WebKit as the rendering engine and are not supported. + * @param enhancedFeatures An enum value or a bitwise combination of `EnumEnhancedFeatures` indicating the features to be enabled. + * + * @returns A promise that resolves when the specified enhanced features have been successfully enabled. It does not provide any value upon resolution. + */ + enableEnhancedFeatures(enhancedFeatures: EnumEnhancedFeatures): Promise; + /** + * Disables one or more previously enabled enhanced features. + * This method can be used to deactivate specific features that are no longer needed or to revert to default behavior. + * + * @param enhancedFeatures An enum value or a bitwise combination of `EnumEnhancedFeatures` indicating the features to be disabled. + */ + disableEnhancedFeatures(enhancedFeatures: EnumEnhancedFeatures): void; + /** + * Differ from 'setScanRegion()', 'setScanRegion()' will update the UI in camera view, while '_setScanRegion()' not. + * @param region + * @ignore + */ + private _setScanRegion; + /** + * Sets the scan region within the camera's view which limits the frame acquisition to a specific area of the video feed. + * + * Note: The region is always specified relative to the original video size, regardless of any transformations or zoom applied to the video display. + * + * @param region Specifies the scan region. + */ + setScanRegion(region: DSRect | Rect): void; + /** + * Retrieves the current scan region set within the camera's view. + * + * Note: If no scan region has been explicitly set before calling this method, an error may be thrown, indicating the necessity to define a scan region beforehand. + * + * @returns A `DSRect` or `Rect` object representing the current scan region. + * + * @throws Error indicating that no scan region has been set, if applicable. + */ + getScanRegion(): DSRect | Rect; + /** + * Sets an error listener to receive notifications about errors that occur during image source operations. + * + * @param listener An instance of `ImageSourceErrorListener` or its derived class to handle error notifications. + */ + setErrorListener(listener: ImageSourceErrorListener): void; + /** + * Determines whether there are more images available to fetch. + * + * @returns Boolean indicating whether more images can be fetched. `false` means the image source is closed or exhausted. + */ + hasNextImageToFetch(): boolean; + /** + * Starts the process of fetching images. + */ + startFetching(): void; + /** + * Stops the process of fetching images. + * to false, indicating that image fetching has been halted. + */ + stopFetching(): void; + /** + * Fetches the current frame from the camera's video feed. + * This method is used to obtain the latest image captured by the camera. + * + * @returns A `DCEFrame` object representing the current frame. + * The structure and content of this object will depend on the pixel format set by `setPixelFormat()` and other settings. + */ + fetchImage(): DCEFrame; + /** + * Sets the interval at which images are continuously fetched from the camera's video feed. + * This method allows for controlling how frequently new frames are obtained when `startFetching()` is invoked, + * which can be useful for reducing computational load or for pacing the frame processing rate. + * + * @param interval The desired interval between fetches, specified in milliseconds. + */ + setImageFetchInterval(interval: number): void; + /** + * Retrieves the current interval at which images are continuously fetched from the camera's video feed. + * + * @returns The current fetch interval, specified in milliseconds. + */ + getImageFetchInterval(): number; + /** + * Sets the pixel format for the images fetched from the camera, which determines the format of the images added to the buffer when the `fetchImage()` or `startFetching()` method is called. + * It can affect both the performance of image processing tasks and the compatibility with certain analysis algorithms. + * + * @param pixelFormat The desired pixel format for the images. Supported formats include `IPF_GRAYSCALED`, `IPF_ABGR_8888`, and `IPF_ARGB_8888`. + */ + setPixelFormat(format: EnumImagePixelFormat.IPF_GRAYSCALED | EnumImagePixelFormat.IPF_ABGR_8888): void; + /** + * Retrieves the current pixel format used for images fetched from the camera. + * + * @returns The current pixel format, which could be one of the following: `IPF_GRAYSCALED`, `IPF_ABGR_8888`, and `IPF_ARGB_8888`. + */ + getPixelFormat(): EnumImagePixelFormat; + /** + * Initiates a sequence to capture a single frame from the camera, only valid when the camera was open. halting the video stream temporarily. + * This method prompts the user to either select a local image or capture a new one using the system camera, similar to the behavior in `singleFrameMode` but without changing the mode. + * + * Note: This method is intended for use cases where capturing a single, user-obtained image is necessary while the application is otherwise utilizing a live video stream. + * + * Steps performed by `takePhoto`: + * 1. Stops the video stream and releases the camera, if it was in use. + * 2. Prompts the user to take a new image with the system camera (on desktop, it prompts the user to select an image from the disk). This behavior mirrors that of `singleFrameMode[=="camera"]` + * 3. Returns the obtained image in a callback function, this differs from `singleFrameMode` which would display the image in the view. + * NOTE: user should resume the video stream after the image has been obtained to keep the video stream going. + * @param listener A callback function that is invoked with a `DCEFrame` object containing the obtained image. + */ + takePhoto(listener: (dceFrame: DCEFrame) => void): void; + /** + * Converts coordinates from the video's coordinate system to coordinates relative to the whole page. + * This is useful for overlaying HTML elements on top of specific points in the video, aligning with the page's layout. + * + * @param point A `Point` object representing the x and y coordinates within the video's coordinate system. + * + * @returns A `Point` object representing the converted x and y coordinates relative to the page. + */ + convertToPageCoordinates(point: Point): Point; + /** + * Converts coordinates from the video's coordinate system to coordinates relative to the viewport. + * This is useful for positioning HTML elements in relation to the video element on the screen, regardless of page scrolling. + * + * @param point A `Point` object representing the x and y coordinates within the video's coordinate system. + * + * @returns A `Point` object representing the converted x and y coordinates relative to the viewport. + */ + convertToClientCoordinates(point: Point): Point; + /** + * Converts coordinates from the video's coordinate system to coordinates relative to the viewport. + * This is useful for positioning HTML elements in relation to the video element on the screen, regardless of page scrolling. + * + * @param point A `Point` object representing the x and y coordinates within the video's coordinate system. + * + * @returns A `Point` object representing the converted x and y coordinates relative to the viewport. + */ + convertToScanRegionCoordinates(point: Point): Point; + /** + * Releases all resources used by the `CameraEnhancer` instance. + */ + dispose(): void; +} + +declare class CameraView extends View { + #private; + /** + * @ignore + */ + static _onLog: (message: any) => void; + private static get engineResourcePath(); + private static _defaultUIElementURL; + /** + * Specifies the URL to a default UI definition file. + * This URL is used as a fallback source for the UI of the `CameraView` class when the `createInstance()` method is invoked without specifying a `HTMLDivElement`. + * This ensures that `CameraView` has a user interface even when no custom UI is provided. + */ + static set defaultUIElementURL(value: string); + static get defaultUIElementURL(): string; + /** + * Initializes a new instance of the `CameraView` class. + * This method allows for optional customization of the user interface (UI) through a specified HTML element or an HTML file. + */ + static createInstance(elementOrUrl?: HTMLElement | string): Promise; + /** + * Transform the coordinates from related to scan region to related to the whole video/image. + * @param coord The coordinates related to scan region. + * @param sx The x coordinate of scan region related to the whole video/image. + * @param sy The y coordinate of scan region related to the whole video/image. + * @param sWidth The width of scan region. + * @param sHeight The height of scan region. + * @param dWidth The width of cropped image. Its value is different from `sWidth` when the image is compressed. + * @param dHeight The height of cropped image. Its value is different from `sHeight` when the image is compressed. + * @ignore + */ + static _transformCoordinates(coord: { + x: number; + y: number; + }, sx: number, sy: number, sWidth: number, sHeight: number, dWidth: number, dHeight: number): void; + cameraEnhancer: CameraEnhancer; + /** + * @ignore + */ + eventHandler: EventHandler; + private UIElement; + /** + * @ignore + */ + containerClassName: string; + _videoContainer: HTMLDivElement; + private videoFit; + /** @ignore */ + _hideDefaultSelection: boolean; + /** @ignore */ + _divScanArea: any; + /** @ignore */ + _divScanLight: any; + /** @ignore */ + _bgLoading: any; + /** @ignore */ + _selCam: any; + /** @ignore */ + _bgCamera: any; + /** @ignore */ + _selRsl: any; + /** @ignore */ + _optGotRsl: any; + /** @ignore */ + _btnClose: any; + /** @ignore */ + _selMinLtr: any; + /** @ignore */ + _optGotMinLtr: any; + /** @ignore */ + _cvsSingleFrameMode: HTMLCanvasElement; + private scanRegion; + private _drawingLayerOfMask; + private _maskBackRectStyleId; + private _maskCenterRectStyleId; + private regionMaskFillStyle; + private regionMaskStrokeStyle; + private regionMaskLineWidth; + /** + * @ignore + */ + _userSetMaskVisible: boolean; + /** + * @ignore + */ + _userSetLaserVisible: boolean; + private _updateLayersTimeoutId; + private _updateLayersTimeout; + /** + * Trigger when the css dimensions of the container of video element changed, or window changed. + */ + private _videoResizeListener; + private _windowResizeListener; + private _resizeObserver; + /** + * @ignore + */ + set _singleFrameMode(value: "disabled" | "camera" | "image"); + get _singleFrameMode(): "disabled" | "camera" | "image"; + _onSingleFrameAcquired: (canvas: HTMLCanvasElement) => void; + private _singleFrameInputContainer; + _clickIptSingleFrameMode: () => void; + _capturedResultReceiver: any; + /** + * Returns whether the `CameraView` instance has been disposed of. + * + * @returns Boolean indicating whether the `CameraView` instance has been disposed of. + */ + get disposed(): boolean; + private constructor(); + /** + * Differ from 'setUIElement()', 'setUIElement()' allow parameter of 'string' type, which means a url, '_setUIElement()' only accept parameter of 'HTMLElement' type. + * @param element + */ + private _setUIElement; + setUIElement(elementOrUrl: HTMLElement | string): Promise; + getUIElement(): HTMLElement; + private _bindUI; + private _unbindUI; + /** + * Show loading animation. + * @ignore + */ + _startLoading(): void; + /** + * Hide loading animation. + * @ignore + */ + _stopLoading(): void; + /** + * Render cameras info in camera selection in default UI. + * @ignore + */ + _renderCamerasInfo(curCamera: { + deviceId: string; + label: string; + }, cameraList: Array<{ + deviceId: string; + label: string; + }>): void; + /** + * Render resolution list in resolution selection in default UI. + * @ignore + */ + _renderResolutionInfo(curResolution: { + width: number; + height: number; + }): void; + /** + * Retrieves the `HTMLVideoElement` that is currently being used for displaying the video in this `CameraView` instance. + * This method allows access to the underlying video element, enabling direct interaction or further customization. + * + * @returns The `HTMLVideoElement` currently used by this `CameraView` instance for video display. + */ + getVideoElement(): HTMLVideoElement; + /** + * tell if video is loaded. + * @ignore + */ + isVideoLoaded(): boolean; + /** + * Sets the `object-fit` CSS property of the `HTMLVideoElement` used by this `CameraView` instance. + * The `object-fit` property specifies how the video content should be resized to fit the container in a way that maintains its aspect ratio. + * @param objectFit The value for the `object-fit` property. At present, only "cover" and "contain" are allowed and the default is "contain". + * Check out more on [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit). + */ + setVideoFit(value: "contain" | "cover"): void; + /** + * Retrieves the current value of the `object-fit` CSS property from the `HTMLVideoElement` used by this `CameraView` instance. + * The `object-fit` property determines how the video content is resized to fit its container. + * + * @returns The current value of the `object-fit` property applied to the video element. At present, the value is limited to "cover" and "contain". + * Check out more on [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit). + */ + getVideoFit(): "contain" | "cover"; + /** + * Get dimensions of content(video, or image in single frame mode). It decides what dimensions the layers should be created. + * @returns + */ + protected getContentDimensions(): { + width: number; + height: number; + objectFit: string; + }; + /** + * Update prop '#convertedRegion' and update related UI. + * @param contentDimensions + * @ignore + */ + private updateConvertedRegion; + /** + * @ignore + */ + getConvertedRegion(): { + x: number; + y: number; + width: number; + height: number; + }; + /** + * @ignore + */ + setScanRegion(region: DSRect | Rect): void; + /** + * @ignore + */ + getScanRegion(): any; + /** + * Returns the region of the video that is currently visible to the user. + * @param options [Optional] Specifies how the visible region should be returned. + * @param options.inPixels [Optional] If `true`, the coordinates of the visible region are returned in pixels. If `false` or omitted, the coordinates are returned as a percentage of the video element's size. + * + * @returns An object representing the visible region of the video. + */ + getVisibleRegionOfVideo(options: { + inPixels?: boolean; + }): Rect; + private setScanRegionMask; + private clearScanRegionMask; + /** + * Not used yet. + * @ignore + */ + private deleteScanRegionMask; + /** + * + * @param visible + * @ignore + */ + _setScanRegionMaskVisible(visible: boolean): void; + /** + * Sets the visibility of the scan region mask. This can be used to show or hide the mask. + * @param visible Boolean indicating whether the scan region mask should be visible (`true`) or not (`false`). + */ + setScanRegionMaskVisible(visible: boolean): void; + /** + * Checks if the scan region mask is currently visible. + * + * @returns Boolean indicating whether the scan region mask is visible (`true`) or not (`false`). + */ + isScanRegionMaskVisible(): boolean; + /** + * Sets the style of the scan region mask. This style includes the line width, stroke color, and fill color. + * @param style An object containing the new style settings for the scan region mask. + * @param style.lineWidth The width of the line used to draw the border of the scan region mask. + * @param style.strokeStyle The color of the stroke (border) of the scan region mask. + * @param style.fillStyle The fill color of the scan region mask. + */ + setScanRegionMaskStyle(style: { + lineWidth: number; + strokeStyle: string; + fillStyle: string; + }): void; + /** + * Retrieves the current style of the scan region mask. This includes the line width, stroke color, and fill color. + */ + getScanRegionMaskStyle(): { + fillStyle: string; + strokeStyle: string; + lineWidth: number; + }; + /** + * @ignore + */ + private _setScanLaserVisible; + /** + * Sets the visibility of the scan laser effect. This can be used to show or hide the scan laser. + * @param visible Boolean indicating whether the scan laser should be visible (`true`) or not (`false`). + */ + setScanLaserVisible(visible: boolean): void; + /** + * Checks if the scan laser effect is currently visible. + * + * @returns Boolean indicating whether the scan laser is visible (`true`) or not (`false`). + */ + isScanLaserVisible(): boolean; + /** + * @ignore + */ + _updateVideoContainer(): void; + /** + * Update all layers(scan laser, drawing layers, scan region mask). Not used yet. + * @ignore + */ + private updateLayers; + /** + * Clears all system-defined `DrawingItem` objects while keeping user-defined ones. + */ + clearAllInnerDrawingItems(): void; + /** + * Remove added elements. Remove event listeners. + */ + dispose(): void; +} + +declare class ImageEditorView extends View { + #private; + static createInstance(elementOrUrl?: HTMLElement | string): Promise; + private UIElement; + /** + * @ignore + */ + containerClassName: string; + /** + * Control if enable magnifier function. + * @ignore + */ + private isUseMagnifier; + /** + * Returns whether the `ImageEditorView` instance has been disposed of. + * + * @returns Boolean indicating whether the `ImageEditorView` instance has been disposed of. + */ + get disposed(): boolean; + private constructor(); + /** + * Differ from 'setUIElement()', 'setUIElement()' allow parameter of 'string' type, which means a url, '_setUIElement()' only accept parameter of 'HTMLElement' type. + * @param element + */ + private _setUIElement; + setUIElement(elementOrUrl: HTMLElement | string): Promise; + getUIElement(): HTMLElement; + private _bindUI; + private _unbindUI; + /** + * Draw image in inner canvas. + * @ignore + */ + private setImage; + /** + * Not used yet. + * @ignore + */ + private getImage; + /** + * Not used yet. + * @ignore + */ + private clearImage; + /** + * Not used yet. + * @ignore + */ + private removeImage; + /** + * Sets the image to be drawn on the `ImageEditorView`. + * This method allows for the initialization or updating of the image. + * @param image The image to be drawn on the `ImageEditorView`. + */ + setOriginalImage(img: DSImageData | HTMLCanvasElement | HTMLImageElement): void; + /** + * Returns the current image drawn on the `ImageEditorView`. + * + * @returns The current image drawn on the `ImageEditorView`. The returned type will match the format of the image originally set via `setOriginalImage()`. + */ + getOriginalImage(): DSImageData | HTMLCanvasElement | HTMLImageElement; + /** + * Get dimensions of content(that is, the image). It decides what dimensions the layers should be created. + * @returns + */ + protected getContentDimensions(): { + width: number; + height: number; + objectFit: string; + }; + /** + * Create drawing layer with specified id and size. + * Differ from 'createDrawingLayer()', the drawing layers created'createDrawingLayer()' can not Specified id, and their size is the same as video. + * @ignore + */ + _createDrawingLayer(drawingLayerId: number, width?: number, height?: number, objectFit?: string): DrawingLayer; + /** + * Releases all resources used by the `ImageEditorView` instance. + */ + dispose(): void; +} + +declare class Feedback { + #private; + static allowBeep: boolean; + static beepSoundSource: string; + static beep(): void; + static allowVibrate: boolean; + static vibrateDuration: number; + static vibrate(): void; +} + +declare class DrawingStyleManager { + #private; + static STYLE_BLUE_STROKE: number; + static STYLE_GREEN_STROKE: number; + static STYLE_ORANGE_STROKE: number; + static STYLE_YELLOW_STROKE: number; + static STYLE_BLUE_STROKE_FILL: number; + static STYLE_GREEN_STROKE_FILL: number; + static STYLE_ORANGE_STROKE_FILL: number; + static STYLE_YELLOW_STROKE_FILL: number; + static STYLE_BLUE_STROKE_TRANSPARENT: number; + static STYLE_GREEN_STROKE_TRANSPARENT: number; + static STYLE_ORANGE_STROKE_TRANSPARENT: number; + static USER_START_STYLE_ID: number; + static createDrawingStyle(styleDefinition: DrawingStyle): number; + private static _getDrawingStyle; + static getDrawingStyle(styleId: number): DrawingStyle; + static getAllDrawingStyles(): Array; + private static _updateDrawingStyle; + static updateDrawingStyle(styleId: number, styleDefinition: DrawingStyle): void; +} + +export { CameraEnhancer, CameraEnhancerModule, CameraView, DCEFrame, DrawingItem, DrawingItemEvent, DrawingLayer, DrawingStyle, DrawingStyleManager, EnumDrawingItemMediaType, EnumDrawingItemState, EnumEnhancedFeatures, Feedback, DT_Group as GroupDrawingItem, DT_Image as ImageDrawingItem, ImageEditorView, DT_Line as LineDrawingItem, Note, PlayCallbackInfo, DT_Quad as QuadDrawingItem, DT_Rect as RectDrawingItem, Resolution, DT_Text as TextDrawingItem, TipConfig, VideoDeviceInfo, VideoFrameTag }; diff --git a/dist/dynamsoft-camera-enhancer@4.1.1/dist/dce.esm.js b/dist/dynamsoft-camera-enhancer@4.1.1/dist/dce.esm.js new file mode 100644 index 0000000..d64709a --- /dev/null +++ b/dist/dynamsoft-camera-enhancer@4.1.1/dist/dce.esm.js @@ -0,0 +1,11 @@ +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft Camera Enhancer JS Edition + * @website https://www.dynamsoft.com + * @copyright Copyright 2024, Dynamsoft Corporation + * @author Dynamsoft + * @version 4.1.1 + * @fileoverview Dynamsoft JavaScript Library for Camera Enhancer + * More info on DCE JS: https://www.dynamsoft.com/camera-enhancer/docs/programming/javascript/?ver=latest + */ +import{CoreModule as t,workerAutoResources as e,mapPackageRegister as i,isRect as r,isPolygon as n,isDSImageData as s,EnumImagePixelFormat as o,isLineSegment as a,isQuad as h,isPoint as l,isDSRect as c,handleEngineResourcePaths as u,EnumCapturedResultItemType as d,EnumCrossVerificationStatus as f,ImageSourceAdapter as g,EnumImageTagType as m,EnumIntermediateResultUnitType as p,EnumBufferOverflowProtectionMode as v,EnumErrorCode as y}from"dynamsoft-core";const _="undefined"==typeof self,w="function"==typeof importScripts,b=(()=>{if(!w){if(!_&&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"./"}})();t.engineResourcePaths.dce={version:"4.1.1",path:b,isInternal:!0},e.dce={wasm:!1,js:!1},i.dce={};class x{static getVersion(){return"4.1.1"}}function C(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function S(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}let T,E,O,A,I;"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(T=navigator,E=T.userAgent,O=T.platform,A=T.mediaDevices),function(){if(!_){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:T.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:O,search:"Win"},Mac:{str:O},Linux:{str:O}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||E,o=n.search||e,a=n.verStr||E,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||E,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=E.indexOf("Windows NT")&&(n="HarmonyOS"),I={browser:i,version:r,OS:n}}_&&(I={browser:"ssr",version:0,OS:"ssr"})}();const L="undefined"!=typeof WebAssembly&&E&&!(/Safari/.test(E)&&!/Chrome/.test(E)&&/\(.+\s11_2_([2-6]).*\)/.test(E)),D=!("undefined"==typeof Worker),M=!(!A||!A.getUserMedia),F=async()=>{let t=!1;if(M)try{(await A.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===I.browser&&I.version>66||"Safari"===I.browser&&I.version>13||"OPR"===I.browser&&I.version>43||"Edge"===I.browser&&I.version;var P={653:(t,e,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,m,p,v,y,_,w,b,x,C,S=S||{version:"5.2.1"};if(e.fabric=S,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?S.document=document:S.document=document.implementation.createHTMLDocument(""),S.window=window;else{var T=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;S.document=T.document,S.jsdomImplForWrapper=i(898).implForWrapper,S.nodeCanvas=i(245).Canvas,S.window=T,DOMParser=S.window.DOMParser}function E(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 O(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)}S.isTouchSupported="ontouchstart"in S.window||"ontouchstart"in S.document||S.window&&S.window.navigator&&S.window.navigator.maxTouchPoints>0,S.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,S.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"],S.DPI=96,S.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",S.commaWsp="(?:\\s+,?\\s*|,\\s*)",S.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,S.reNonWord=/[ \n\.,;!\?\-]/,S.fontPaths={},S.iMatrix=[1,0,0,1,0,0],S.svgNS="http://www.w3.org/2000/svg",S.perfLimitSizeTotal=2097152,S.maxCacheSideLimit=4096,S.minCacheSideLimit=256,S.charWidthsCache={},S.textureSize=2048,S.disableStyleCopyPaste=!1,S.enableGLFiltering=!0,S.devicePixelRatio=S.window.devicePixelRatio||S.window.webkitDevicePixelRatio||S.window.mozDevicePixelRatio||1,S.browserShadowBlurConstant=1,S.arcToSegmentsCache={},S.boundsOfCurveCache={},S.cachesBoundsOfCurve=!0,S.forceGLPutImageData=!1,S.initFilterBackend=function(){return S.enableGLFiltering&&S.isWebglSupported&&S.isWebglSupported(S.textureSize)?(console.log("max texture size: "+S.maxTextureSize),new S.WebglFilterBackend({tileSize:S.textureSize})):S.Canvas2dFilterBackend?new S.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=S),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:S.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)}S.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)}},S.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof S.Gradient||this.set(e,new S.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof S.Pattern?i&&i():this.set(e,new S.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,S.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 S.Point(t.x-e.x,t.y-e.y),n=S.util.rotateVector(r,i);return new S.Point(n.x,n.y).addEquals(e)},rotateVector:function(t,e){var i=S.util.sin(e),r=S.util.cos(e);return{x:t.x*r-t.y*i,y:t.x*i+t.y*r}},createVector:function(t,e){return new S.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 S.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var r=S.util.createVector(t,e),n=S.util.createVector(t,i),s=S.util.calcAngleBetweenVectors(r,n),o=s*(0===S.util.calcAngleBetweenVectors(S.util.rotateVector(r,s),n)?1:-1)/2;return{vector:S.util.getHatVector(S.util.rotateVector(r,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var r=[],n=e.strokeWidth/2,s=e.strokeUniform?new S.Point(1/e.scaleX,1/e.scaleY):new S.Point(1,1),o=function(t){var e=n/Math.hypot(t.x,t.y);return new S.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 S.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(S.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(S.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=S.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-n/Math.sin(p/2),f=new S.Point(m.x*d*s.x,m.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 S.Point(m.x*d*s.x,m.y*d*s.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(t,e,i){return i?new S.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new S.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=S.util.sin(c),d=S.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,v=(i=Math.abs(i))*i,y=(s=Math.abs(s))*s,_=p*p,w=m*m,b=v*y-v*_-y*w,x=0;if(b<0){var C=Math.sqrt(1-b/(v*y));i*=C,s*=C}else x=(o===a?-1:1)*Math.sqrt(b/(v*_+y*w));var T=x*i*p/s,E=-x*s*m/i,O=d*T-u*E+.5*t,A=u*T+d*E+.5*e,I=n(1,0,(m-T)/i,(p-E)/s),L=n((m-T)/i,(p-E)/s,(-m-T)/i,(-p-E)/s);0===a&&L>0?L-=2*l:1===a&&L<0&&(L+=2*l);for(var D=Math.ceil(Math.abs(L/l*2)),M=[],F=L/D,P=8/3*Math.sin(F/4)*Math.sin(F/4)/Math.sin(F/2),k=I+F,R=0;Rx)for(var T=1,E=m.length;T2;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},S.util.getPathSegmentsInfo=d,S.util.getBoundsOfCurve=function(e,i,r,n,s,o,a,h){var l;if(S.cachesBoundsOfCurve&&(l=t.call(arguments),S.boundsOfCurveCache[l]))return S.boundsOfCurveCache[l];var c,u,d,f,g,m,p,v,y=Math.sqrt,_=Math.min,w=Math.max,b=Math.abs,x=[],C=[[],[]];u=6*e-12*r+6*s,c=-3*e+9*r-9*s+3*a,d=3*r-3*e;for(var T=0;T<2;++T)if(T>0&&(u=6*i-12*n+6*o,c=-3*i+9*n-9*o+3*h,d=3*n-3*i),b(c)<1e-12){if(b(u)<1e-12)continue;0<(f=-d/u)&&f<1&&x.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(v=y(p)))/(2*c))&&g<1&&x.push(g),0<(m=(-u-v)/(2*c))&&m<1&&x.push(m));for(var E,O,A,I=x.length,L=I;I--;)E=(A=1-(f=x[I]))*A*A*e+3*A*A*f*r+3*A*f*f*s+f*f*f*a,C[0][I]=E,O=A*A*A*i+3*A*A*f*n+3*A*f*f*o+f*f*f*h,C[1][I]=O;C[0][L]=e,C[1][L]=i,C[0][L+1]=a,C[1][L+1]=h;var D=[{x:_.apply(null,C[0]),y:_.apply(null,C[1])},{x:w.apply(null,C[0]),y:w.apply(null,C[1])}];return S.cachesBoundsOfCurve&&(S.boundsOfCurveCache[l]=D),D},S.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)}},S.util.transformPath=function(t,e,i){return i&&(e=S.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(!S.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}S.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)}S.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=S.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=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}),S.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?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var r in e)"opacity"===r?m(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(S.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=S.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=S.document.documentElement,n=S.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===S.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=S.document.defaultView&&S.document.defaultView.getComputedStyle?function(t,e){var i=S.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=S.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",S.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=S.util.falseFunction),r?t.style[r]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},S.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),r?t.style[r]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},S.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},S.util.getById=function(t){return"string"==typeof t?S.document.getElementById(t):t},S.util.toArray=s,S.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},S.util.makeElement=o,S.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},S.util.getScrollLeftTop=a,S.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}},S.util.getNodeCanvas=function(t){var e=S.jsdomImplForWrapper(t);return e._canvas||e._image},S.util.cleanUpJsdomNode=function(t){if(S.isLikelyNode){var e=S.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}S.util.request=function(e,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",n=i.onComplete||function(){},s=new S.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}}(),S.log=console.log,S.warn=console.warn,function(){var t=S.util.object.extend,e=S.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}S.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=S.window.requestAnimationFrame||S.window.webkitRequestAnimationFrame||S.window.mozRequestAnimationFrame||S.window.oRequestAnimationFrame||S.window.msRequestAnimationFrame||function(t){return S.window.setTimeout(t,1e3/60)},o=S.window.cancelAnimationFrame||S.window.clearTimeout;function a(){return s.apply(S.window,arguments)}S.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=S.runningAnimations.indexOf(s);return t>-1&&S.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}),S.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,m=i.easing||n,p="startValue"in i&&i.startValue.length>0,v="startValue"in i?i.startValue:0,y="endValue"in i?i.endValue:100,_=i.byValue||(p?v.map((function(t,e){return y[e]-v[e]})):y-v);i.onStart&&i.onStart(),function t(i){var r=(e=i||+new Date)>u?c:e-l,n=r/c,w=p?v.map((function(t,e){return m(r,v[e],_[e],c)})):m(r,v,_,c),b=p?Math.abs((w[0]-v[0])/_[0]):Math.abs((w-v)/_);if(s.currentValue=p?w.slice():w,s.completionRate=b,s.durationRate=n,!o){if(!f(w,b,n))return e>u?(s.currentValue=p?y.slice():y,s.completionRate=1,s.durationRate=1,d(p?y.slice():y,1,1),g(y,1,1),void h()):(d(w,b,n),void a(t));h()}}(l)})),s.cancel},S.util.requestAnimFrame=a,S.util.cancelAnimFrame=function(){return o.apply(S.window,arguments)},S.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))+")"}S.util.animateColor=function(e,i,r,n){var s=new S.Color(e).getSource(),o=new S.Color(i).getSource(),a=n.onComplete,h=n.onChange;return n=n||{},S.util.animate(S.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 y=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function _(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,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",v=!l||!(l=l.match(y)),_=!d||!f||"100%"===d||"100%"===f,w=v&&_,b={},x="",C=0,S=0;if(b.width=0,b.height=0,b.toBeParsed=w,v&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(x=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+x,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return b;if(v)return b.width=s(d),b.height=s(f),b;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),n=parseFloat(l[3]),o=parseFloat(l[4]),b.minX=i,b.minY=r,b.viewBoxWidth=n,b.viewBoxHeight=o,_?(b.width=n,b.height=o):(b.width=s(d),b.height=s(f),c=b.width/n,u=b.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),C=b.width-n*c,S=b.height-o*c,"Mid"===p.alignX&&(C/=2),"Mid"===p.alignY&&(S/=2),"Min"===p.alignX&&(C=0),"Min"===p.alignY&&(S=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===m)return b;if((g||m)&&"#document"!==t.parentNode.nodeName&&(x=" translate("+s(g)+" "+s(m)+") "),a=x+" matrix("+c+" 0 0 "+u+" "+(i*c+C)+" "+(r*u+S)+") ","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),b}function w(t,e){var i="xlink:href",r=v(t,e.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&w(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 m(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 v(t,e,i){var r=t.lockScalingX,n=t.lockScalingY;return!((!r||!n)&&(e||!r&&!n||!i)&&(!r||"x"!==e)&&(!n||"y"!==e))}function y(t,e,i,r){return{e:t,transform:e,pointer:{x:i,y:r}}}function _(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 w(t,e){return function(i,r,n,s){var o=e(i,r,n,s);return o&&g(t,y(i,r,n,s)),o}}function b(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 x(t){return t.flipX!==t.flipY}function C(t,e,i,r,n){if(0!==t[e]){var s=n/t._getTransformedDimensions()[r]*t[i];t.set(i,s)}}function S(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=b(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),x(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",n),C(l,"skewY","scaleY","y",p)}return m}function T(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=b(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),x(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",n),C(l,"skewX","scaleX","x",p)}return m}function E(t,e,i,r,n){n=n||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,y=f.lockScalingY,_=n.by,w=m(t,f),x=v(f,_,w),C=e.gestureScale;if(x)return!1;if(C)o=e.scaleX*C,a=e.scaleY*C;else{if(s=b(e,e.originX,e.originY,i,r),l="y"!==_?d(s.x):1,u="x"!==_?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(),w&&!_){var S=Math.abs(s.x)+Math.abs(s.y),T=e.original,E=S/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*E,a=T.scaleY*E}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"!==_&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==_&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var O=f.scaleX,A=f.scaleY;return _?("x"===_&&f.set("scaleX",o),"y"===_&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!y&&f.set("scaleY",a)),O!==f.scaleX||A!==f.scaleY}n.scaleCursorStyleHandler=function(t,e,r){var n=m(t,r),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),v(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=w("rotating",_((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,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),x(h)&&(n=n===s?a:s)),e.originX=n,w("skewing",_(S))(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=b(e,l,l,i,r).y>0?o:h:(c>0&&(n=u===s?o:h),c<0&&(n=u===s?h:o),x(a)&&(n=n===o?h:o)),e.originY=n,w("skewing",_(T))(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",y(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=_,n.wrapWithFireEvent=w,n.getLocalPoint=b,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),m=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(m),l=f*e.util.sin(m)}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 S.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*e,{offset:a,color:i.toRgb(),opacity:n}}var e=S.util.object.clone;S.Gradient=S.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+="_"+S.Object.__uid++:this.id=S.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 S.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 S.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():S.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+" ":"")+S.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=m/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=S.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,m=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=S.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,m=-i.top),new S.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:m})}})}(),v=S.util.toFixed,S.Pattern=S.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=S.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=S.util.createImage(),S.util.loadImage(t.source,(function(t,r){i.source=t,e&&e(i,r)}),null,this.crossOrigin)}},toObject:function(t){var e,i,r=S.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:v(this.offsetX,r),offsetY:v(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},S.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(S.StaticCanvas)S.warn("fabric.StaticCanvas is already defined.");else{var t=S.util.object.extend,e=S.util.getElementOffset,i=S.util.removeFromArray,r=S.util.toFixed,n=S.util.transformPoint,s=S.util.invertTransform,o=S.util.getNodeCanvas,a=S.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");S.StaticCanvas=S.util.createClass(S.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:S.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 S.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,S.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=S.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?S.util.loadImage(e,(function(e,n){if(e){var s=new S.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=S.util.getById(t)||this._createCanvasElement(),S.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=S.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 ",S.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+S.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?S.util.matrixToSVG(n):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,r,n,s,o,a,h="",l={},c=S.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(S.StaticCanvas.prototype,S.Observable),t(S.StaticCanvas.prototype,S.Collection),t(S.StaticCanvas.prototype,S.DataURLExporter),t(S.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}}),S.StaticCanvas.prototype.toJSON=S.StaticCanvas.prototype.toObject,S.isLikelyNode&&(S.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},S.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),S.BaseBrush=S.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*=S.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*r,i.shadowOffsetX=e.offsetX*r,i.shadowOffsetY=e.offsetY*r}},needsFullRender:function(){return new S.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()}}),S.PencilBrush=S.util.createClass(S.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 S.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 S.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 S.Point(r.x,r.y),n=new S.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})}}}),S.CircleBrush=S.util.createClass(S.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=S.util.invertTransform(i),n=this.restorePointerVpt(e);return S.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 S.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,S.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):S.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:S.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 S.Point(e.ex,e.ey),r=S.util.transformPoint(i,this.viewportTransform),n=new S.Point(e.ex+e.left,e.ey+e.top),s=S.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,S.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 S.Group&&(r=this._searchPossibleTargets(i._objects,e))&&this.targets.push(r);break}}return i},restorePointerVpt:function(t){return S.util.transformPoint(t,S.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),S.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=S.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),S.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),S.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;S.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,S.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){S.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,S.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]})),S.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(),S.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),S.StaticCanvas)"prototype"!==r&&(S.Canvas[r]=S.StaticCanvas[r])}(),function(){var t=S.util.addListener,e=S.util.removeListener,i={passive:!1};function r(t,e){return t.button&&t.button===e-1}S.util.object.extend(S.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(S.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(S.document,t+"up",this._onMouseUp),e(S.document,"touchend",this._onTouchEnd,i),e(S.document,t+"move",this._onMouseMove,i),e(S.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(S.document,"touchend",this._onTouchEnd,i),t(S.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(S.document,s+"up",this._onMouseUp),t(S.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(S.document,"touchend",this._onTouchEnd,i),e(S.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(S.document,s+"up",this._onMouseUp),e(S.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),S.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 S.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 S.Point(y(r,s),y(n,o)),h=new S.Point(_(r,s),_(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}}),S.util.object.extend(S.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 S.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=S.util.createCanvasElement(),m=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=m,g}}),S.util.object.extend(S.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var r="string"==typeof t?JSON.parse(t):S.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?S.util.enlivenObjects([e],(function(e){n[t]=e[0],i[t]=!0,r&&r()})):this["set"+S.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,r&&r()}))},_enlivenObjects:function(t,e,i){t&&0!==t.length?S.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=S.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new S.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,m=f||g,p=0,v=0,y=!1;if(f){var _=this._cacheCanvas.width,w=this._cacheCanvas.height,b=l>_||c>w;y=b||(l<.9*_||c<.9*w)&&_>h&&w>h,b&&!a.capped&&(l>h||c>h)&&(p=.1*l,v=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,y=!0,p+=this.getHeightOfLine(0)*this.zoomX,v+=this.getHeightOfLine(0)*this.zoomY),!!m&&(y?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+v)):(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,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.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 v=this.canvas;p.add(this);var y=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",v),n&&(this.group=n),this.set(r).setCoords(),p._objects=[],p.dispose(),p=null,y},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),w=S.util.degreesToRadians,b={left:-.5,center:0,right:.5},x={top:-.5,center:0,bottom:.5},S.util.object.extend(S.Object.prototype,{translateToGivenOrigin:function(t,e,i,r,n){var s,o,a,h=t.x,l=t.y;return"string"==typeof e?e=b[e]:e-=.5,"string"==typeof r?r=b[r]:r-=.5,"string"==typeof i?i=x[i]:i-=.5,"string"==typeof n?n=x[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 S.Point(h,l)},translateToCenterPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?S.util.rotatePoint(r,t,w(this.angle)):r},translateToOriginPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?S.util.rotatePoint(r,t,w(this.angle)):r},getCenterPoint:function(){var t=new S.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 S.Point(this.left,this.top),n=new S.Point(t.x,t.y),this.angle&&(n=S.util.rotatePoint(n,s,-w(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=w(this.angle),n=this.getScaledWidth(),s=S.util.cos(r)*n,o=S.util.sin(r)*n;e="string"==typeof this.originX?b[this.originX]:this.originX-.5,i="string"==typeof t?b[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=S.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,r=t.transformPoint;t.object.extend(S.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 S.Point(i.tl.x,i.tl.y),new S.Point(i.tr.x,i.tr.y),new S.Point(i.br.x,i.br.y),new S.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,r){var n=this.getCoords(i,r);return"Intersection"===S.Intersection.intersectPolygonRectangle(n,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===S.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=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+S.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[m]=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=S.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=S.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=S.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(){}})}(),S.util.object.extend(S.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return S.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 S.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 S.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()}})}}),S.util.object.extend(S.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?S.util.animateColor(h.startValue,h.endValue,h.duration,h):S.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 S.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);S.filterBackend||(S.filterBackend=S.initFilterBackend());var o=S.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,S.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=S.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 S.filterBackend||(S.filterBackend=S.initFilterBackend()),S.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){S.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){S.util.setImageSmoothing(t,this.imageSmoothing),S.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),m=o(s*r,u-f),p=-n/2,v=-s/2,y=o(n,c/i-h),_=o(s,u/r-l);e&&t.drawImage(e,d,f,g,m,p,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(S.util.getById(t),e),S.util.addClass(this.getElement(),S.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?S.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=S.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=S.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=S.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}}}),S.Image.CSS_CANVAS="canvas-img",S.Image.prototype.getSvgSrc=S.Image.prototype.getSrc,S.Image.fromObject=function(t,e){var i=S.util.object.clone(t);S.util.loadImage(i.src,(function(t,r){r?e&&e(null,!0):S.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],S.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],S.util.enlivenObjectEnlivables(i,i,(function(){var r=new S.Image(t,i);e(r,!1)}))}))}))}),null,i.crossOrigin)},S.Image.fromURL=function(t,e,i){S.util.loadImage(t,(function(t,r){e&&e(new S.Image(t,i),r)}),null,i&&i.crossOrigin)},S.Image.ATTRIBUTE_NAMES=S.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),S.Image.fromElement=function(t,i,r){var n=S.parseAttributes(t,S.Image.ATTRIBUTE_NAMES);S.Image.fromURL(n["xlink:href"],i,e(r?S.util.object.clone(r):{},n))})}(e),S.util.object.extend(S.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 S.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()}})}}),S.util.object.extend(S.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()}S.isWebglSupported=function(e){if(S.isLikelyNode)return!1;e=e||S.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),n=!1;if(r){S.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),n=S.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(r,s[o])){S.webGlPrecision=s[o];break}}return this.isSupported=n,n},S.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=S.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(S.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=O);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),E.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),O.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=O):this.copyGLTo2D=E}},createWebGLCanvas:function(t,e){var i=S.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:E,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(){}S.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}}}(),S.Image=S.Image||{},S.Image.filters=S.Image.filters||{},S.Image.filters.BaseFilter=S.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"!==S.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+S.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=S.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()}}),S.Image.filters.BaseFilter.fromObject=function(t,e){var i=new S.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=w||o<0||o>=_||(h=4*(a*_+o),l=p[f*v+d],e+=m[h]*l,i+=m[h+1]*l,r+=m[h+2]*l,C||(n+=m[h+3]*l));x[s]=e,x[s+1]=i,x[s+2]=r,x[s+3]=C?m[s+3]:n}t.imageData=b},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,m=e.filterBackend.resources,p=0,v=0,y=i,_=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){M=r(1e3*s(S-b.x)),w[M]||(w[M]={});for(var P=x.y-_;P<=x.y+_;P++)P<0||P>=o||(F=r(1e3*s(P-b.y)),w[M][F]||(w[M][F]=f(n(i(M*p,2)+i(F*v,2))/1e3)),(T=w[M][F])>0&&(O+=T,A+=T*c[E=4*(P*e+S)],I+=T*c[E+1],L+=T*c[E+2],D+=T*c[E+3]))}d[E=4*(C*a+h)]=A/O,d[E+1]=I/O,d[E+2]=L/O,d[E+3]=D/O}return++h1&&F<-1||(_=2*F*F*F-3*F*F+1)>0&&(T+=_*f[3+(M=4*(D+O*e))],b+=_,f[M+3]<255&&(_=_*f[M+3]/250),x+=_*f[M],C+=_*f[M+1],S+=_*f[M+2],w+=_)}m[y]=x/w,m[y+1]=C/w,m[y+2]=S/w,m[y+3]=T/b}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,m=this._textLines.length;g=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 O=y+s+u;"rtl"===this.direction&&(O=this.width-O-d),l&&v&&(t.fillStyle=v,t.fillRect(O,c+x*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,v=p,r=n,o=a}else d+=f.kernedWidth;O=y+s+u,"rtl"===this.direction&&(O=this.width-O-d),t.fillStyle=p,g&&p&&t.fillRect(O,c+x*r+o,d-b,this.fontSize/15),_+=i}else _+=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)}S.IText=S.util.createClass(S.Text,S.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),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var y=t.left+f+m,_=p-m,w=g,b=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,b=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(y=this.width-y-_),e.fillRect(y,t.top+t.topOffset+b,_,w),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}}}),S.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]);S.Object._fromObject("IText",e,i,"text")}}(),C=S.util.object.clone,S.util.object.extend(S.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||[],S.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=S.util.string.graphemeSplit(r).length;if(t===e)return{selectionStart:n,selectionEnd:n};var s=i.slice(t,e);return{selectionStart:n,selectionEnd:n+S.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,m=c.clientWidth/u,p=c.clientHeight/d;return h=S.util.transformPoint(h,a),(h=S.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,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=C(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:C(r[i-1])}:n?this.styles[t+i]={0:C(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?C(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]=C(r[i]));else if(n)for(var h=n[e?e-1:1];h&&i--;)this.styles[t][e+i]=C(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)}}),S.util.object.extend(S.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}}),S.util.object.extend(S.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=S.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):S.document.body.appendChild(this.hiddenTextarea),S.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),S.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),S.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),S.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),S.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),S.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),S.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),S.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),S.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(S.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),m=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=S.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=S.util.toFixed,e=/ +/g;S.util.object.extend(S.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",S.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,m=f.length-1;g<=m;g++)h=g===m||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=S.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+=v,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return y&&a.push(h),m+n>this.dynamicMinWidth&&(this.dynamicMinWidth=m-v+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:()=>{}},k={};function R(t){var e=k[t];if(void 0!==e)return e.exports;var i=k[t]={exports:{}};return P[t](i,i.exports,R),i.exports}R.d=(t,e)=>{for(var i in e)R.o(e,i)&&!R.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},R.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var B={};(()=>{let t;R.d(B,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?R(653).fabric:{version:"5.2.1"}})();var j,V,W,N,U=B.R;!function(t){t[t.DIMT_RECTANGLE=1]="DIMT_RECTANGLE",t[t.DIMT_QUADRILATERAL=2]="DIMT_QUADRILATERAL",t[t.DIMT_TEXT=4]="DIMT_TEXT",t[t.DIMT_ARC=8]="DIMT_ARC",t[t.DIMT_IMAGE=16]="DIMT_IMAGE",t[t.DIMT_POLYGON=32]="DIMT_POLYGON",t[t.DIMT_LINE=64]="DIMT_LINE",t[t.DIMT_GROUP=128]="DIMT_GROUP"}(j||(j={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(V||(V={})),function(t){t[t.EF_ENHANCED_FOCUS=4]="EF_ENHANCED_FOCUS",t[t.EF_AUTO_ZOOM=16]="EF_AUTO_ZOOM",t[t.EF_TAP_TO_FOCUS=64]="EF_TAP_TO_FOCUS"}(W||(W={})),function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(N||(N={}));const G=t=>"number"==typeof t&&!Number.isNaN(t),Y=t=>"string"==typeof t;var H,X,z,q,K,Z,J,Q,$,tt,et;!function(t){t[t.ARC=0]="ARC",t[t.IMAGE=1]="IMAGE",t[t.LINE=2]="LINE",t[t.POLYGON=3]="POLYGON",t[t.QUAD=4]="QUAD",t[t.RECT=5]="RECT",t[t.TEXT=6]="TEXT",t[t.GROUP=7]="GROUP"}(K||(K={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(Z||(Z={}));class it{get mediaType(){return new Map([["rect",j.DIMT_RECTANGLE],["quad",j.DIMT_QUADRILATERAL],["text",j.DIMT_TEXT],["arc",j.DIMT_ARC],["image",j.DIMT_IMAGE],["polygon",j.DIMT_POLYGON],["line",j.DIMT_LINE],["group",j.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(C(this,X,"f")){case V.DIS_DEFAULT:return"default";case V.DIS_SELECTED:return"selected"}}set drawingStyleId(t){this.styleId=t}get drawingStyleId(){return this.styleId}set coordinateBase(t){if(!["view","image"].includes(t))throw new Error("Invalid 'coordinateBase'.");this._drawingLayer&&("image"===C(this,z,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===C(this,z,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),S(this,z,t,"f")}get coordinateBase(){return C(this,z,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(H.add(this),X.set(this,void 0),z.set(this,"image"),this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapState_StyleId=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,null!=e&&!G(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(V.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",(()=>{this.setState(V.DIS_SELECTED)})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(V.DIS_SELECTED):this.setState(V.DIS_DEFAULT),"textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}setState(t){S(this,X,t,"f")}getState(){return C(this,X,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),r=this.mapEvent_Callbacks.get(i);if(!r)throw new Error(`Event '${t}' does not exist.`);let n=r.get(e);n||(n=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const r={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,n,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,n=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,v,y=1;if("contain"===f)u0?i-1:r,ot),actionName:"modifyPolygon",pointIndex:i}),t}),{}),S(this,Q,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,r){return t["p"+r]=new U.Control({positionHandler:nt,actionHandler:at(r>0?r-1:i,ot),actionName:"modifyPolygon",pointIndex:r}),t}),{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let r=i.x-e.pathOffset.x,n=i.y-e.pathOffset.y;const s=U.util.transformPoint({x:r,y:n},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){C(this,Q,"f")&&this.setPolygon(C(this,Q,"f"))}setPolygon(t){if(!n(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else S(this,Q,JSON.parse(JSON.stringify(t)),"f")}getPolygon(){if(this._drawingLayer){if("view"===this.coordinateBase){return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))}}if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return C(this,Q,"f")?JSON.parse(JSON.stringify(C(this,Q,"f"))):null}}Q=new WeakMap;class lt extends it{set maintainAspectRatio(t){t&&this.set("scaleY",this.get("scaleX"))}get maintainAspectRatio(){return C(this,tt,"f")}constructor(t,e,i,n){if(super(null,n),$.set(this,void 0),tt.set(this,void 0),!r(e))throw new TypeError("Invalid 'rect'.");if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)this._setFabricObject(new U.Image(t,{left:e.x,top:e.y}));else{if(!s(t))throw new TypeError("Invalid 'image'.");{const i=document.createElement("canvas");let r;i.width=t.width,i.height=t.height;if(t.format===o.IPF_GRAYSCALED){r=new Uint8ClampedArray(t.width*t.height*4);for(let e=0;e{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let r=0;ri&&(i=n.length))}if(-1===i)break;for(let r=0;r=t[r].length-1)continue;let n=" ".repeat(i+2-t[r][e].length);t[r][e]=t[r][e].concat(n)}}})(e),(t=>{let e="";for(let i=0;i({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const r=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new U.Control({positionHandler:nt,actionHandler:at(i>0?i-1:r,ot),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let r=t.x-i.pathOffset.x,n=t.y-i.pathOffset.y;const s=U.util.transformPoint({x:r,y:n},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){C(this,dt,"f")&&this.setLine(C(this,dt,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!a(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else S(this,dt,JSON.parse(JSON.stringify(t)),"f")}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return C(this,dt,"f")?JSON.parse(JSON.stringify(C(this,dt,"f"))):null}}dt=new WeakMap;class mt extends ht{constructor(t,e){if(super({points:null==t?void 0:t.points},e),ft.set(this,void 0),!h(t))throw new TypeError("Invalid 'quad'.");S(this,ft,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="quad"}setPosition(t){this.setQuad(t)}getPosition(){return this.getQuad()}updatePosition(){C(this,ft,"f")&&this.setQuad(C(this,ft,"f"))}setPolygon(){}getPolygon(){return null}setQuad(t){if(!h(t))throw new TypeError("Invalid 'quad'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else S(this,ft,JSON.parse(JSON.stringify(t)),"f")}getQuad(){if(this._drawingLayer){if("view"===this.coordinateBase){return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))}}if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return C(this,ft,"f")?JSON.parse(JSON.stringify(C(this,ft,"f"))):null}}ft=new WeakMap;class pt extends it{constructor(t){super(new U.Group(t.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.setState(V.DIS_SELECTED);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.setState(V.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}setChildDrawingItems(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()))}}const vt=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),yt=t=>!!Y(t)&&""!==t,_t=t=>!!vt(t)&&(!("id"in t&&!G(t.id))&&(!("lineWidth"in t&&!G(t.lineWidth))&&(!("fillStyle"in t&&!yt(t.fillStyle))&&(!("strokeStyle"in t&&!yt(t.strokeStyle))&&(!("paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode))&&(!("fontFamily"in t&&!yt(t.fontFamily))&&!("fontSize"in t&&!G(t.fontSize))))))));class wt{static convert(t,e,i){const n={x:0,y:0,width:e,height:i};if(!t)return n;if(r(t))t.isMeasuredInPercentage?(n.x=t.x/100*e,n.y=t.y/100*i,n.width=t.width/100*e,n.height=t.height/100*i):(n.x=t.x,n.y=t.y,n.width=t.width,n.height=t.height);else{if(!c(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?(n.x=t.left/100*e,n.y=t.top/100*i,n.width=(t.right-t.left)/100*e,n.height=(t.bottom-t.top)/100*i):(n.x=t.left,n.y=t.top,n.width=t.right-t.left,n.height=t.bottom-t.top)}return n.x=Math.round(n.x),n.y=Math.round(n.y),n.width=Math.round(n.width),n.height=Math.round(n.height),n}}var bt,xt;class Ct{constructor(){bt.set(this,new Map),xt.set(this,!1)}get disposed(){return C(this,xt,"f")}on(t,e){t=t.toLowerCase();const i=C(this,bt,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else C(this,bt,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=C(this,bt,"f").get(t);if(!i)return;const r=i.indexOf(e);-1!==r&&i.splice(r,1)}offAll(t){t=t.toLowerCase();const e=C(this,bt,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const r=C(this,bt,"f").get(t);if(r&&r.length){i=Object.assign({async:!1,copy:!0},i);for(let t of r){if(!t)continue;let n=[];if(i.copy)for(let t of e){try{t=JSON.parse(JSON.stringify(t))}catch(t){}n.push(t)}else n=e;let s=!1;if(i.async)setTimeout((()=>{this.disposed||r.includes(t)&&t.apply(i.target,n)}),0);else try{s=t.apply(i.target,n)}catch(t){}if(!0===s)break}}}dispose(){S(this,xt,!0,"f")}}function St(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function Tt(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function Et(t,e,i,r){let n=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(r[1]-e[1])+e[0]*(t[1]-r[1])+r[0]*(e[1]-t[1]);return!((n^s)>=0&&0!==n&&0!==s)&&(n=i[0]*(t[1]-r[1])+r[0]*(i[1]-t[1])+t[0]*(r[1]-i[1]),s=i[0]*(e[1]-r[1])+r[0]*(i[1]-e[1])+e[0]*(r[1]-i[1]),!((n^s)>=0&&0!==n&&0!==s))}bt=new WeakMap,xt=new WeakMap;const Ot=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const r=document.createElement("div");if(r.insertAdjacentHTML("beforeend",i),1===r.childElementCount&&r.firstChild instanceof HTMLTemplateElement)return r.firstChild.content;const n=new DocumentFragment;for(let t of r.children)n.append(t);return n};var At,It,Lt,Dt,Mt,Ft,Pt,kt,Rt,Bt,jt,Vt,Wt,Nt,Ut,Gt,Yt,Ht,Xt,zt,qt,Kt,Zt,Jt,Qt,$t,te,ee,ie,re,ne,se,oe,ae;class he{static createDrawingStyle(t){if(!_t(t))throw new Error("Invalid style definition.");let e,i=he.USER_START_STYLE_ID;for(;C(he,At,"f",It).has(i);)i++;e=i;const r=JSON.parse(JSON.stringify(t));r.id=e;for(let t in C(he,At,"f",Lt))r.hasOwnProperty(t)||(r[t]=C(he,At,"f",Lt)[t]);return C(he,At,"f",It).set(e,r),r.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=C(he,At,"f",It).get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}static getDrawingStyle(t){return this._getDrawingStyle(t,!0)}static getAllDrawingStyles(){return JSON.parse(JSON.stringify(Array.from(C(he,At,"f",It).values())))}static _updateDrawingStyle(t,e){if(!_t(e))throw new Error("Invalid style definition.");const i=C(he,At,"f",It).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}At=he,he.STYLE_BLUE_STROKE=1,he.STYLE_GREEN_STROKE=2,he.STYLE_ORANGE_STROKE=3,he.STYLE_YELLOW_STROKE=4,he.STYLE_BLUE_STROKE_FILL=5,he.STYLE_GREEN_STROKE_FILL=6,he.STYLE_ORANGE_STROKE_FILL=7,he.STYLE_YELLOW_STROKE_FILL=8,he.STYLE_BLUE_STROKE_TRANSPARENT=9,he.STYLE_GREEN_STROKE_TRANSPARENT=10,he.STYLE_ORANGE_STROKE_TRANSPARENT=11,he.USER_START_STYLE_ID=1024,It={value:new Map([[he.STYLE_BLUE_STROKE,{id:he.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[he.STYLE_GREEN_STROKE,{id:he.STYLE_GREEN_STROKE,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[he.STYLE_ORANGE_STROKE,{id:he.STYLE_ORANGE_STROKE,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[he.STYLE_YELLOW_STROKE,{id:he.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[he.STYLE_BLUE_STROKE_FILL,{id:he.STYLE_BLUE_STROKE_FILL,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[he.STYLE_GREEN_STROKE_FILL,{id:he.STYLE_GREEN_STROKE_FILL,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[he.STYLE_ORANGE_STROKE_FILL,{id:he.STYLE_ORANGE_STROKE_FILL,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[he.STYLE_YELLOW_STROKE_FILL,{id:he.STYLE_YELLOW_STROKE_FILL,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[he.STYLE_BLUE_STROKE_TRANSPARENT,{id:he.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[he.STYLE_GREEN_STROKE_TRANSPARENT,{id:he.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[he.STYLE_ORANGE_STROKE_TRANSPARENT,{id:he.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},Lt={value:{lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}},"undefined"!=typeof document&&"undefined"!=typeof window&&(U.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(U.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),U.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},U.Object.prototype.transparentCorners=!1,U.Object.prototype.cornerSize=20,U.Object.prototype.touchCornerSize=100,U.Object.prototype.cornerColor="rgb(254,142,20)",U.Object.prototype.cornerStyle="circle",U.Object.prototype.strokeUniform=!0,U.Object.prototype.hasBorders=!1,U.Canvas.prototype.containerClass="",U.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=U.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,m,p=c/u,v=d/f;return"contain"===l?p>v?(g=d,m=d/p,{x:n.x*i.width,y:(n.y-(f-m)/2)*i.width}):(g=f*p,m=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===l?p>v?{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}},U.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,r=this._getEventPrefix();U.util.addListener(U.document,"touchend",this._onTouchEnd,{passive:!1}),U.util.addListener(U.document,"touchmove",this._onMouseMove,{passive:!1}),U.util.removeListener(i,r+"down",this._onMouseDown)},U.Textbox.prototype._wrapLine=function(t,e,i,r){const n=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!n||!n.length);var o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?U.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,m=0,p=0,v=!0,y=this._getWidthOfCharSpacing();r=r||0;0===c.length&&c.push([]),i-=r;for(var _=0;_i&&!v?(h.push(l),l=[],o=g,v=!0):o+=y,v||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,v=!1,g>p&&(p=g);return _&&h.push(l),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-y+r),h});class le{get width(){return this.fabricCanvas.width}get height(){return this.fabricCanvas.height}set _allowMultiSelect(t){this.fabricCanvas.selection=t,this.fabricCanvas.renderAll()}get _allowMultiSelect(){return this.fabricCanvas.selection}constructor(t,e,i){if(this.mapType_StateAndStyleId=new Map,this.mode="viewer",this.onSelectionChanged=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas"))this.fabricCanvas=t.getFabricCanvas();else{let e=this.fabricCanvas=new U.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.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.onSelectionChanged&&t.onSelectionChanged(i,[])}),0)}})),e.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.onSelectionChanged&&t.onSelectionChanged([],e)}),0)}})),e.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.onSelectionChanged&&t.onSelectionChanged(r,n)}),0)}})),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let r,n;switch(this.id=e,e){case le.DDN_LAYER_ID:r=he.getDrawingStyle(he.STYLE_BLUE_STROKE),n=he.getDrawingStyle(he.STYLE_BLUE_STROKE_FILL);break;case le.DBR_LAYER_ID:r=he.getDrawingStyle(he.STYLE_ORANGE_STROKE),n=he.getDrawingStyle(he.STYLE_ORANGE_STROKE_FILL);break;case le.DLR_LAYER_ID:r=he.getDrawingStyle(he.STYLE_GREEN_STROKE),n=he.getDrawingStyle(he.STYLE_GREEN_STROKE_FILL);break;default:r=he.getDrawingStyle(he.STYLE_YELLOW_STROKE),n=he.getDrawingStyle(he.STYLE_YELLOW_STROKE_FILL)}for(let t of it.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:r.id,selected:n.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return he.getDrawingStyle(t.styleId);const e=he.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector));return e||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,r){const n=this.getDrawingItems((e=>e._mediaType===t));for(let t of n)t.styleSelector===e&&this._changeItemStyle(t,i,!0);r||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const r=t._getFabricObject();"number"==typeof t.styleId&&(e=he.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.getChildDrawingItems();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=he.getDrawingStyle(e.styleId);else{const r=this.mapType_StateAndStyleId.get(e._mediaType);i=he.getDrawingStyle(r[t.styleSelector]);const n=()=>{this._changeItemStyle(e,he.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,he.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",n),e._on("deselected",s),e._funcChangeStyleToSelected=n,e._funcChangeStyleToDefault=s}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("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof it))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}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.getChildDrawingItems();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){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of it.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=he.getDrawingStyle(t.styleId);else{s=he.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,he.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},r=()=>{this._changeItemStyle(t,he.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",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{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of it.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=he.getDrawingStyle(t.styleId);else{s=he.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,he.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},r=()=>{this._changeItemStyle(t,he.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",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;et.toLowerCase())):e=it.arrMediaTypes,i?i.forEach((t=>t.toLowerCase())):i=it.arrStyleSelectors;const r=he.getDrawingStyle(t);if(!r)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let n;for(let s of e)if(n=this.mapType_StateAndStyleId.get(s),n)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,r,!0),n[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const r=[];i&j.DIMT_RECTANGLE&&r.push("rect"),i&j.DIMT_QUADRILATERAL&&r.push("quad"),i&j.DIMT_TEXT&&r.push("text"),i&j.DIMT_ARC&&r.push("arc"),i&j.DIMT_IMAGE&&r.push("image"),i&j.DIMT_POLYGON&&r.push("polygon"),i&j.DIMT_LINE&&r.push("line");const n=[];e&V.DIS_DEFAULT&&n.push("default"),e&V.DIS_SELECTED&&n.push("selected"),this._setDefaultStyle(t,r.length?r:null,n.length?n:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}le.DDN_LAYER_ID=1,le.DBR_LAYER_ID=2,le.DLR_LAYER_ID=3,le.USER_DEFINED_LAYER_BASE_ID=100,le.TIP_LAYER_ID=999;class ce{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new le(t,e,{enableRetinaScaling:!1});return i._manager=this,this._arrDrawingLayer.push(i),this._switchPointerEvent(),i}deleteDrawingLayer(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}getAllDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._getFabricCanvas().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){if(!this._arrDrawingLayer.length)return;const e=this._getFabricCanvas();e.wrapperEl.style.display=t?"block":"none"}_getFabricCanvas(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0].fabricCanvas:null}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class ue extends ut{constructor(t,e,i,r,n){super(t,{x:e,y:i,width:r,height:0},n),Dt.set(this,void 0),Mt.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&S(this,Mt,setTimeout((()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()}),C(this,Dt,"f")),"f")}getDuration(){return C(this,Dt,"f")}}Dt=new WeakMap,Mt=new WeakMap;class de{constructor(){Ft.add(this),Pt.set(this,void 0),kt.set(this,void 0),Rt.set(this,void 0),Bt.set(this,!0),this._drawingLayerManager=new ce}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const r=document.createElement("canvas");return r.width==t&&r.height==e||(r.width=t,r.height=e),r.style.objectFit=i,r}_createDrawingLayer(t,e,i,r){if(!this._layerBaseCvs){let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==t?void 0:t.width)||1280),i||(i=(null==t?void 0:t.height)||720),r||(r=(null==t?void 0:t.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,r)}const n=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(n,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",n.parentElement),s}createDrawingLayer(){let t;for(let e=le.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==le.TIP_LAYER_ID){t=e;break}return this._createDrawingLayer(t)}deleteDrawingLayer(t){var e;this._drawingLayerManager.deleteDrawingLayer(t),this._drawingLayerManager.getAllDrawingLayers().length||(null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null)}deleteUserDefinedDrawingLayer(t){if("number"!=typeof t)throw new TypeError("Invalid id.");if(tt.getId()>=0&&t.getId()!==le.TIP_LAYER_ID))}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(vt(e=t)&&l(e.topLeftPoint)&&G(e.width))||e.width<=0||!G(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;S(this,Pt,JSON.parse(JSON.stringify(t)),"f"),C(this,Pt,"f").coordinateBase||(C(this,Pt,"f").coordinateBase="view"),S(this,Rt,t.duration,"f"),C(this,Ft,"m",Nt).call(this)}getTipConfig(){return C(this,Pt,"f")?C(this,Pt,"f"):null}setTipVisible(t){if("boolean"!=typeof t)throw new TypeError("Invalid value.");this._tip&&(this._tip.set("visible",t),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll()),S(this,Bt,t,"f")}isTipVisible(){return C(this,Bt,"f")}updateTipMessage(t){if(!C(this,Pt,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=he.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(le.TIP_LAYER_ID)||this._createDrawingLayer(le.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=C(this,Ft,"m",jt).call(this,t,C(this,Pt,"f").topLeftPoint.x,C(this,Pt,"f").topLeftPoint.y,C(this,Pt,"f").width,C(this,Pt,"f").coordinateBase,this._tipStyleId),C(this,Ft,"m",Vt).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",C(this,Bt,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),C(this,kt,"f")&&clearTimeout(C(this,kt,"f")),C(this,Rt,"f")>=0&&S(this,kt,setTimeout((()=>{C(this,Ft,"m",Wt).call(this)}),C(this,Rt,"f")),"f")}}Pt=new WeakMap,kt=new WeakMap,Rt=new WeakMap,Bt=new WeakMap,Ft=new WeakSet,jt=function(t,e,i,r,n,s){const o=new ue(t,e,i,r,s);return o.coordinateBase=n,o},Vt=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},Wt=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},Nt=function(){if(!this._tip)return;const t=C(this,Pt,"f");this._tip.coordinateBase=t.coordinateBase,this._tip.setTextRect({x:t.topLeftPoint.x,y:t.topLeftPoint.y,width:t.width,height:0}),this._tip.set("width",this._tip.get("width")),this._tip._drawingLayer&&this._tip._drawingLayer.renderAll()};class fe extends HTMLElement{constructor(){super(),Ut.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),S(this,Ut,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const r=document.createElement("slot");r.setAttribute("name","content"),e.append(r);const n=document.createElement("slot");n.setAttribute("name","drawing-layer"),e.append(n);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return C(this,Ut,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach((t=>t.remove()))}}Ut=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",fe);class ge extends de{static get engineResourcePath(){return u(t.engineResourcePaths).dce}static set defaultUIElementURL(t){ge._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=ge._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",ge.engineResourcePath)}static async createInstance(t){const e=new ge;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",ge.engineResourcePath)),await e.setUIElement(t||ge.defaultUIElementURL),e}static _transformCoordinates(t,e,i,r,n,s,o){const a=s/r,h=o/n;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==C(this,Qt,"f")){if(S(this,Qt,t,"f"),C(this,Gt,"m",ee).call(this))S(this,zt,null,"f"),this._videoContainer=null,this._innerComponent.removeElement("content"),this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block");else if(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none"),!C(this,zt,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(I.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),S(this,zt,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}C(this,Gt,"m",ee).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading())}}get _singleFrameMode(){return C(this,Qt,"f")}get disposed(){return C(this,te,"f")}constructor(){super(),Gt.add(this),Yt.set(this,void 0),Ht.set(this,void 0),Xt.set(this,void 0),this.containerClassName="dce-video-container",zt.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,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,qt.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,Kt.set(this,!1),Zt.set(this,!1),Jt.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{C(this,Gt,"m",oe).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout((()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&C(this,Gt,"m",se).call(this))}),this._updateLayersTimeout)},this._windowResizeListener=()=>{ge._onLog&&ge._onLog("window resize event triggered."),C(this,Jt,"f").width===document.documentElement.clientWidth&&C(this,Jt,"f").height===document.documentElement.clientHeight||(C(this,Jt,"f").width=document.documentElement.clientWidth,C(this,Jt,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},Qt.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!C(this,Gt,"m",ee).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i},i=(t,e,i,r)=>{t.width==i&&t.height==r||(t.width=i,t.height=r);const n=t.getContext("2d");n.clearRect(0,0,t.width,t.height),n.drawImage(e,0,0)},r=await t(e),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,r,n,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout((()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)}),0)})),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},$t.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,r,n,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(r=o.cropRegion)||void 0===r?void 0:r.top)||0,c=(null===(n=o.cropRegion)||void 0===n?void 0:n.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,g=o.currentWidth,m=o.currentHeight,p=(t,e,i,r,n,s,o,a,h=[],l)=>{e.forEach((t=>ge._transformCoordinates(t,i,r,n,s,o,a)));const c=new mt({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},l);for(let t of h)c.addNote(t);t.addDrawingItems([c]),C(this,$t,"f").push(c)};let v,y;for(let t of a)switch(t.type){case d.CRIT_ORIGINAL_IMAGE:break;case d.CRIT_BARCODE:v=this.getDrawingLayer(le.DBR_LAYER_ID),y=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==e?void 0:e.isBarcodeVerifyOpen)?t.verified?p(v,t.location.points,h,l,c,u,g,m,y):p(v,t.location.points,h,l,c,u,g,m,y,he.STYLE_ORANGE_STROKE_TRANSPARENT):p(v,t.location.points,h,l,c,u,g,m,y);break;case d.CRIT_TEXT_LINE:v=this.getDrawingLayer(le.DLR_LAYER_ID),y=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?p(v,t.location.points,h,l,c,u,g,m,y):p(v,t.location.points,h,l,c,u,g,m,y,he.STYLE_GREEN_STROKE_TRANSPARENT):p(v,t.location.points,h,l,c,u,g,m,y);break;case d.CRIT_DETECTED_QUAD:v=this.getDrawingLayer(le.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.crossVerificationStatus===f.CVS_PASSED?p(v,t.location.points,h,l,c,u,g,m,[]):p(v,t.location.points,h,l,c,u,g,m,[],he.STYLE_BLUE_STROKE_TRANSPARENT):p(v,t.location.points,h,l,c,u,g,m,[]);break;case d.CRIT_NORMALIZED_IMAGE:v=this.getDrawingLayer(le.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.crossVerificationStatus===f.CVS_PASSED?p(v,t.location.points,h,l,c,u,g,m,[]):p(v,t.location.points,h,l,c,u,g,m,[],he.STYLE_BLUE_STROKE_TRANSPARENT):p(v,t.location.points,h,l,c,u,g,m,[]);break;case d.CRIT_PARSED_RESULT:break;default:throw new Error("Illegal item type.")}}},te.set(this,!1),this.eventHandler=new Ct,this.eventHandler.on("content:updated",(()=>{C(this,Yt,"f")&&clearTimeout(C(this,Yt,"f")),S(this,Yt,setTimeout((()=>{if(this.disposed)return;let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(t),this.updateConvertedRegion(t)}),0),"f")})),this.eventHandler.on("videoEl:resized",(()=>{C(this,Ht,"f")&&clearTimeout(C(this,Ht,"f")),S(this,Ht,setTimeout((()=>{this.disposed||this._updateVideoContainer()}),0),"f")}))}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Ot(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let r=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!r)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=document.createElement("dce-component"),r.appendChild(this._innerComponent),C(this,Gt,"m",ee).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(I.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),S(this,zt,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._selRsl&&(this._hideDefaultSelection||C(this,Gt,"m",ee).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||C(this,Gt,"m",ee).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||C(this,Gt,"m",oe).call(this),C(this,Gt,"m",ee).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),C(this,Gt,"m",ee).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading()),window.ResizeObserver){this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{var e;ge._onLog&&ge._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()})));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}C(this,Jt,"f").width=document.documentElement.clientWidth,C(this,Jt,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,r;C(this,Gt,"m",ee).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),C(this,Gt,"m",oe).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,S(this,zt,null,"f"),null===(r=this._videoContainer)||void 0===r||r.remove(),this._videoContainer=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._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let r of e){const e=document.createElement("option");e.value=r.deviceId,e.innerText=r.label,this._selCam.append(e),r.deviceId&&t&&t.deviceId==r.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),r=Math.min(t.width,t.height);e=r<=1080?r+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return C(this,zt,"f")}isVideoLoaded(){return!(!C(this,zt,"f")||!this.cameraEnhancer)&&this.cameraEnhancer.isOpen()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!C(this,zt,"f"))return;if(C(this,zt,"f").style.objectFit=t,C(this,Gt,"m",ee).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}C(this,Gt,"m",ae).call(this,e,this.getConvertedRegion()),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,r;let n,s,o;if(C(this,Gt,"m",ee).call(this)?(n=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(r=this._cvsSingleFrameMode)||void 0===r?void 0:r.height,o="contain"):(n=null===(t=C(this,zt,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=C(this,zt,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!n||!s)throw new Error("Invalid content dimensions.");return{width:n,height:s,objectFit:o}}updateConvertedRegion(t){const e=wt.convert(this.scanRegion,t.width,t.height);S(this,qt,e,"f"),C(this,Xt,"f")&&clearTimeout(C(this,Xt,"f")),S(this,Xt,setTimeout((()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}C(this,Gt,"m",ie).call(this,t,e),C(this,Gt,"m",ae).call(this,t,e)}),0),"f")}getConvertedRegion(){return C(this,qt,"f")}setScanRegion(t){if(null!=t&&!c(t)&&!r(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=C(this,zt,"f").videoWidth,i=C(this,zt,"f").videoHeight,r=this.getVideoFit(),{width:n,height:s}=this._innerComponent.getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===r&&(n/s1){const t=C(this,zt,"f").videoWidth,e=C(this,zt,"f").videoHeight,{width:r,height:n}=this._innerComponent.getBoundingClientRect(),s=t/e;if(r/nt.remove())),C(this,$t,"f").length=0}dispose(){this._unbindUI(),S(this,te,!0,"f")}}function me(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function pe(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}Yt=new WeakMap,Ht=new WeakMap,Xt=new WeakMap,zt=new WeakMap,qt=new WeakMap,Kt=new WeakMap,Zt=new WeakMap,Jt=new WeakMap,Qt=new WeakMap,$t=new WeakMap,te=new WeakMap,Gt=new WeakSet,ee=function(){return"disabled"!==this._singleFrameMode},ie=function(t,e){e&&(0!==e.x||0!==e.y||e.width!==t.width||e.height!==t.height)?this.setScanRegionMask(e.x,e.y,e.width,e.height):this.clearScanRegionMask()},re=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},ne=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},se=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},oe=function(){this._divScanLight&&(this._divScanLight.style.display="none")},ae=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:r,objectFit:n}=t;e||(e={x:0,y:0,width:i,height:r});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/r;let l,c,u,d,f=1;if("contain"===n)a66||"Safari"===xe.browser&&xe.version>13||"OPR"===xe.browser&&xe.version>43||"Edge"===xe.browser&&xe.version,"function"==typeof SuppressedError&&SuppressedError;class Te{static multiply(t,e){const i=[];for(let r=0;r<3;r++){const n=e.slice(3*r,3*r+3);for(let e=0;e<3;e++){const r=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return Te.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),r=Math.sin(e);return Te.multiply(t,[i,-r,0,r,i,0,0,0,1])}static scale(t,e,i){return Te.multiply(t,[e,0,0,0,i,0,0,0,1])}}var Ee,Oe,Ae,Ie,Le,De,Me;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(Ee||(Ee={}));class Fe{static get version(){return"1.1.3"}static get webGLSupported(){return void 0===Fe._webGLSupported&&(Fe._webGLSupported=!!document.createElement("canvas").getContext("webgl")),Fe._webGLSupported}get disposed(){return Ce(this,Me,"f")}constructor(){Oe.set(this,Ee.RGBA),Ae.set(this,null),Ie.set(this,null),Le.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,De.set(this,null),Me.set(this,!1)}drawImage(t,e,i,r,n,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!r)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if((null==s?void 0:s.bUseWebGL)&&!Fe.webGLSupported)throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;Fe._onLog&&(o=Date.now(),Fe._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;n&&(n.sx&&(a=Math.round(n.sx)),n.sy&&(h=Math.round(n.sy)),n.sWidth&&(l=Math.round(n.sWidth)),n.sHeight&&(c=Math.round(n.sHeight)),n.dx&&(u=Math.round(n.dx)),n.dy&&(d=Math.round(n.dy)),n.dWidth&&(f=Math.round(n.dWidth)),n.dHeight&&(g=Math.round(n.dHeight)));let m,p=Ee.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const v=t;if(!Fe.webGLSupported||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){Fe._onLog&&Fe._onLog("drawImage() in context2d."),v.ctx2d||(v.ctx2d=v.getContext("2d",{willReadFrequently:!0}));const t=v.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(v.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=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},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},n=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},s="\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\n\nuniform mat3 u_matrix;\nuniform mat3 u_textureMatrix;\n\nvarying vec2 v_texCoord;\nvoid main(void) {\ngl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\nv_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n}";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_image;\nuniform float uColorFactor;\n\nvoid main() {\nvec4 sample = texture2D(u_image, v_texCoord);\nfloat grey = 0.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\ngl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n}`,h=r(t,[n(t,t.VERTEX_SHADER,s),n(t,t.FRAGMENT_SHADER,a)]);Se(this,Ie,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),Se(this,Le,e(t),"f"),Se(this,Ae,i(t),"f"),Se(this,Oe,p,"f")}const n=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(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)},y=(t,e,s,o)=>{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),n(t,s.positions,e.attribLocations.vertexPosition),n(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[Ee.GREY,Ee.GREY32].includes(p)?1:0);let m,v,y=Te.translate(Te.identity(),-1,-1);y=Te.scale(y,2,2),y=Te.scale(y,1/t.canvas.width,1/t.canvas.height),m=Te.translate(y,u,d),m=Te.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),v=Te.translate(Te.identity(),a/i,h/r),v=Te.scale(v,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,v),t.drawArrays(t.TRIANGLES,0,6)};s(t,Ce(this,Ae,"f"),e),y(t,Ce(this,Ie,"f"),Ce(this,Le,"f"),Ce(this,Ae,"f"));const _=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,_),255!==_[3]){Fe._onLog&&Fe._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return Fe._onLog&&Fe._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===Ee.GREY?Ee.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return Fe._onLog&&Fe._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,r,n,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let r,n=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(n=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),r=new Uint8Array(i.buffer,0,4*o*a)):(r=new Uint8Array(4*o*a),e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,r))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(n,s,o,a),r=new Uint8Array(e.data.buffer),null==i||i.set(r)}return r}transformPixelFormat(t,e,i,r){let n,s;if(Fe._onLog&&(n=Date.now(),Fe._onLog("transformPixelFormat(), START: "+n)),e===i)return Fe._onLog&&Fe._onLog("transformPixelFormat() end. Costs: "+(Date.now()-n)),r?new Uint8Array(t):t;const o=[Ee.RGBA,Ee.RBGA,Ee.GRBA,Ee.GBRA,Ee.BRGA,Ee.BGRA];if(o.includes(e))if(i===Ee.GREY){s=new Uint8Array(t.length/4);for(let e=0;eh||e.sy+e.sHeight>l)throw new Error("Invalid position.");null===(r=Fe._onLog)||void 0===r||r.call(Fe,"getImageData(), START: "+(c=Date.now()));const d=Math.round(e.sx),f=Math.round(e.sy),g=Math.round(e.sWidth),m=Math.round(e.sHeight),p=Math.round(e.dWidth),v=Math.round(e.dHeight);let y,_=(null==i?void 0:i.pixelFormat)||Ee.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(Ee.GREY===_&&w.length{this.disposed||r.includes(t)&&t.apply(i.target,n)}),0);else try{s=t.apply(i.target,n)}catch(t){}if(!0===s)break}}}dispose(){pe(this,ke,!0,"f")}}Pe=new WeakMap,ke=new WeakMap;const Si=(t,e,i,r)=>{if(!i)return t;let n=e+Math.round((t-e)/i)*i;return r&&(n=Math.min(n,r)),n};class Ti{static get version(){return"2.0.18"}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 findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find((t=>e.includes(t.label.toLowerCase())));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],r=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],n=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!n.length)return null;const s=n.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const o=n.find((t=>{const e=t.label.toLowerCase();return r.some((t=>e.includes(t)))}));return o?o.deviceId:n[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(xe.OS))return Ti.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(xe.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise((async(r,n)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),r(t)},l=t=>{s&&clearTimeout(s),o(),n(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise((t=>{g=t})),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise((t=>{setTimeout(t,1e3)})),!a){i&&(s=setTimeout((()=>{o(),n(new Error("Failed to play video. Timeout."))}),i)),await m;try{await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a)try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}}))}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let r;try{r=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==r||r.getTracks().forEach((t=>{t.stop()}))}return{ok:!0}}get state(){if(!me(this,Ke,"f"))return"closed";if("pending"===me(this,Ke,"f"))return"opening";if("fulfilled"===me(this,Ke,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Ti.isStorageAvailable("localStorage")?pe(this,He,!0,"f"):(pe(this,He,!1,"f"),console.warn("Local storage is unavailable")):pe(this,He,!1,"f")}get ifSaveLastUsedCamera(){return me(this,He,"f")}get isVideoPlaying(){return!(!me(this,je,"f")||me(this,je,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,r;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=me(this,ei,"f"))||void 0===e||e.removeEventListener("click",me(this,ti,"f")),null===(i=me(this,ei,"f"))||void 0===i||i.removeEventListener("touchend",me(this,ti,"f")),null===(r=me(this,ei,"f"))||void 0===r||r.removeEventListener("touchmove",me(this,$e,"f")),pe(this,ei,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(xe.OS)?(t.addEventListener("touchend",me(this,ti,"f")),t.addEventListener("touchmove",me(this,$e,"f"))):t.addEventListener("click",me(this,ti,"f")))}get tapFocusEventBoundEl(){return me(this,ei,"f")}get disposed(){return me(this,ci,"f")}constructor(t){var e,i;Be.add(this),je.set(this,null),Ve.set(this,void 0),We.set(this,(()=>{"opened"===this.state&&me(this,si,"f").fire("resumed",null,{target:this,async:!1})})),Ne.set(this,(()=>{me(this,si,"f").fire("paused",null,{target:this,async:!1})})),Ue.set(this,void 0),Ge.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],Ye.set(this,void 0),He.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,Xe.set(this,void 0),ze.set(this,!0),qe.set(this,void 0),Ke.set(this,void 0),Ze.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},Je.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,r;const n=window.getComputedStyle(me(this,je,"f")).objectFit,s=this.getResolution(),o=me(this,je,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=me(this,je,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===n)d>u?(f=l/s.width,i=(t-a)/f,r=(e-h-(c-l/d)/2)/f):(f=c/s.height,r=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==n)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,r=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,r=(e-h+(l/d-c)/2)/f)}return{x:i,y:r}},Qe.set(this,!1),$e.set(this,(()=>{pe(this,Qe,!0,"f")})),ti.set(this,(async t=>{var e;if(me(this,Qe,"f"))return void pe(this,Qe,!1,"f");if(!me(this,Je,"f"))return;if(!this.isVideoPlaying)return;if(!me(this,Ve,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,r;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,r=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,r=t.changedTouches[0].clientY}const n=this.getResolution(),s=2*Math.round(Math.min(n.width,n.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,r)}catch(t){}if(o.x<0||o.x>n.width||o.y<0||o.y>n.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;Ti._onLog&&(c=Date.now());try{await me(this,Be,"m",wi).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Ti._onLog)throw Ti._onLog(t),t}Ti._onLog&&Ti._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout((()=>{var t;Ti._onLog&&Ti._onLog("Back to continuous focus."),null===(t=me(this,Ve,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime),me(this,si,"f").fire("tapfocus",null,{target:this,async:!1})})),ei.set(this,null),ii.set(this,1),ri.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!me(this,je,"f"))return;const t=me(this,ii,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)me(this,je,"f").style.transform="";else{const e=window.getComputedStyle(me(this,je,"f")).objectFit,i=me(this,je,"f").videoWidth,r=me(this,je,"f").videoHeight,{width:n,height:s}=me(this,je,"f").getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=n/s,a=i/r;let h=1;"contain"===e?h=oo?s/(i/t):n/(r/t));const l=h*(1-1/t)*(i/2-me(this,ri,"f").x),c=h*(1-1/t)*(r/2-me(this,ri,"f").y);me(this,je,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},ni.set(this,(function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===Ee.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(Ti._onLog&&Ti._onLog("document visible. video paused: "+(null===(t=me(this,je,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let t=!1;if(!this.isVideoPlaying){Ti._onLog&&Ti._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),t=!0}catch(t){Ti._onLog&&Ti._onLog("document visible. 1st resume video failed, try open instead.")}t||await me(this,Be,"m",mi).call(this)}if(await new Promise((t=>setTimeout(t,300))),!this.isVideoPlaying){Ti._onLog&&Ti._onLog("document visible. 1st open failed. 2rd resume start."),t=!1;try{await this.resume(),t=!0}catch(t){Ti._onLog&&Ti._onLog("document visible. 2rd resume video failed, try open instead.")}t||await me(this,Be,"m",mi).call(this)}}}else"hidden"===document.visibilityState&&(Ti._onLog&&Ti._onLog("document hidden. video paused: "+(null===(e=me(this,je,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())})),ci.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout((()=>{Ti.onWarning&&Ti.onWarning("The browser is too old or the page is loaded from an insecure origin.")}),0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),pe(this,si,new Ci,"f"),this.imageDataGetter=new Fe,document.addEventListener("visibilitychange",me(this,li,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",me(this,We,"f")),t.addEventListener("pause",me(this,Ne,"f")),pe(this,je,t,"f")}getVideoEl(){return me(this,je,"f")}releaseVideoEl(){var t,e;null===(t=me(this,je,"f"))||void 0===t||t.removeEventListener("play",me(this,We,"f")),null===(e=me(this,je,"f"))||void 0===e||e.removeEventListener("pause",me(this,Ne,"f")),pe(this,je,null,"f")}isVideoLoaded(){return!!me(this,je,"f")&&4==me(this,je,"f").readyState}async open(){if(me(this,qe,"f")&&!me(this,ze,"f")){if("pending"===me(this,Ke,"f"))return me(this,qe,"f");if("fulfilled"===me(this,Ke,"f"))return}me(this,si,"f").fire("before:open",null,{target:this}),await me(this,Be,"m",mi).call(this),me(this,si,"f").fire("played",null,{target:this,async:!1}),me(this,si,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;me(this,si,"f").fire("before:close",null,{target:this});const t=me(this,qe,"f");if(me(this,Be,"m",vi).call(this),t&&"pending"===me(this,Ke,"f")){try{await t}catch(t){}if(!1===me(this,ze,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}pe(this,qe,null,"f"),pe(this,Ke,null,"f"),me(this,si,"f").fire("closed",null,{target:this,async:!1})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");me(this,je,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await me(this,je,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof me(this,Ue,"f").video&&(me(this,Ue,"f").video={}),delete me(this,Ue,"f").video.facingMode,me(this,Ue,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&me(this,ze,"f"))){me(this,si,"f").fire("before:camera:change",[],{target:this,async:!1}),await me(this,Be,"m",pi).call(this);try{this.resetSoftwareScale()}catch(t){}return me(this,Ge,"f")}}async switchToFrontCamera(t){if("object"!=typeof me(this,Ue,"f").video&&(me(this,Ue,"f").video={}),(null==t?void 0:t.resolution)&&(me(this,Ue,"f").video.width={ideal:t.resolution.width},me(this,Ue,"f").video.height={ideal:t.resolution.height}),delete me(this,Ue,"f").video.deviceId,me(this,Ue,"f").video.facingMode={exact:"user"},pe(this,Ye,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&me(this,ze,"f"))){me(this,si,"f").fire("before:camera:change",[],{target:this,async:!1}),me(this,Be,"m",pi).call(this);try{this.resetSoftwareScale()}catch(t){}return me(this,Ge,"f")}}getCamera(){var t;if(me(this,Ge,"f"))return me(this,Ge,"f");{let e=(null===(t=me(this,Ue,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}else r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));const n=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind));return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof me(this,Ue,"f").video&&(me(this,Ue,"f").video={}),i?(me(this,Ue,"f").video.width={exact:t},me(this,Ue,"f").video.height={exact:e}):(me(this,Ue,"f").video.width={ideal:t},me(this,Ue,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&me(this,ze,"f"))return null;me(this,si,"f").fire("before:resolution:change",[],{target:this,async:!1}),await me(this,Be,"m",pi).call(this);try{this.resetSoftwareScale()}catch(t){}const r=this.getResolution();return{width:r.width,height:r.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&me(this,je,"f"))return{width:me(this,je,"f").videoWidth,height:me(this,je,"f").videoHeight};if(me(this,Ve,"f")){const t=me(this,Ve,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:me(this,je,"f").videoWidth,height:me(this,je,"f").videoHeight};{const t={width:0,height:0};let e=me(this,Ue,"f").video.width||0,i=me(this,Ue,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,r,n,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=me(this,ai,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){d=null===(u=me(this,Ge,"f"))||void 0===u?void 0:u.deviceId;let e=me(this,ai,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],me(this,ai,"f").set(d,e),pe(this,Ze,!0,"f");try{for(let t of this.detectedResolutions){await me(this,Ve,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),me(this,Be,"m",di).call(this);const i=me(this,Ve,"f").getSettings(),r={width:i.width,height:i.height};f(d,r)||e.push({width:r.width,height:r.height})}}catch(t){throw me(this,Be,"m",vi).call(this),pe(this,Ze,!1,"f"),t}try{await me(this,Be,"m",mi).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{pe(this,Ze,!1,"f")}return e}{const e=async(t,e,i)=>{const r={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let n=null;try{n=await 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};let i=(null===(s=null===(n=null===(r=me(this,Ue,"f"))||void 0===r?void 0:r.video)||void 0===n?void 0:n.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=me(this,Ue,"f"))||void 0===o?void 0:o.video)||void 0===a?void 0:a.deviceId)||void 0===h?void 0:h.ideal)||(null===(c=null===(l=me(this,Ue,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=me(this,ai,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],me(this,ai,"f").set(i,u);for(let t of this.detectedResolutions){const r=await e(i,t.width,t.height);r&&!f(i,r)&&u.push({width:r.width,height:r.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");pe(this,Ue,JSON.parse(JSON.stringify(t)),"f"),pe(this,Ye,null,"f"),e&&me(this,Be,"m",pi).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(me(this,Ue,"f")))}resetMediaStreamConstraints(){pe(this,Ue,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!me(this,Ve,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return me(this,Ve,"f").getCapabilities?me(this,Ve,"f").getCapabilities():{}}getCameraSettings(){if(!me(this,Ve,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return me(this,Ve,"f").getSettings()}async turnOnTorch(){if(!me(this,Ve,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await me(this,Ve,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!me(this,Ve,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await me(this,Ve,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!me(this,Ve,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Si(t,r.min,r.step,r.max)),await me(this,Ve,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!me(this,Ve,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Si(t,r.min,r.step,r.max)),await me(this,Ve,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!me(this,Ve,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!r)throw Error("Not supported.");e&&(tr.max&&(t=r.max));const n=this.getResolution();return await me(this,Ve,"f").applyConstraints({width:{ideal:Math.max(n.width,n.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!me(this,Ve,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),r=null==i?void 0:i.focusMode,n=null==i?void 0:i.focusDistance;if(!r)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!r.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!n)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(in.max&&(i=n.max),i=Si(i,n.min,n.step,n.max)),this._focusParameters.focusArea=null,await me(this,Ve,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,r=t.area.height;if(!i||!r){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),r||(r=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:r},await me(this,Be,"m",wi).call(this,e,i,r)}}}else this._focusParameters.focusArea=null,await me(this,Ve,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async enableTapToFocus(){pe(this,Je,!0,"f")}disableTapToFocus(){pe(this,Je,!1,"f")}isTapToFocusEnabled(){return me(this,Je,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"!==this.state)throw new Error("Video is not playing.");t.centerPoint?me(this,Be,"m",bi).call(this,t.centerPoint):this.resetScaleCenter();try{if(me(this,Be,"m",xi).call(this,me(this,ri,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*me(this,ii,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!me(this,Ve,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Si(t,r.min,r.step,r.max)),await me(this,Ve,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&me(this,Be,"m",bi).call(this,e),pe(this,ii,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return me(this,ii,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();pe(this,ri,{x:t.width/2,y:t.height/2},"f")}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(me(this,Ze,"f"))return null;const e=Date.now();Ti._onLog&&Ti._onLog("getFrameData() START: "+e);const i=me(this,je,"f").videoWidth,r=me(this,je,"f").videoHeight;let n={sx:0,sy:0,sWidth:i,sHeight:r,dWidth:i,dHeight:r};(null==t?void 0:t.position)&&(n=JSON.parse(JSON.stringify(t.position)));let s=Ee.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=me(this,ii,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=me(this,ri,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,n=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))n=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.scaleCenter.y)/100*r}if(isNaN(e)||isNaN(n))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(n)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==r)return null;1!==o&&(n.sWidth=Math.round(n.sWidth/o),n.sHeight=Math.round(n.sHeight/o),n.sx=Math.round((1-1/o)*a.x+n.sx/o),n.sy=Math.round((1-1/o)*a.y+n.sy/o));const l=this.imageDataGetter.getImageData(me(this,je,"f"),n,{pixelFormat:s,bufferContainer:h});if(!l)return null;const c=Date.now();return Ti._onLog&&Ti._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:me(this,ni,"f")}}on(t,e){if(!me(this,oi,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);me(this,si,"f").on(t,e)}off(t,e){me(this,si,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),me(this,si,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",me(this,li,"f")),pe(this,ci,!0,"f")}}var Ei,Oi,Ai,Ii,Li,Di,Mi,Fi,Pi,ki,Ri,Bi,ji,Vi,Wi,Ni,Ui,Gi,Yi,Hi,Xi,zi,qi,Ki,Zi,Ji,Qi,$i,tr,er,ir,rr,nr,sr,or;je=new WeakMap,Ve=new WeakMap,We=new WeakMap,Ne=new WeakMap,Ue=new WeakMap,Ge=new WeakMap,Ye=new WeakMap,He=new WeakMap,Xe=new WeakMap,ze=new WeakMap,qe=new WeakMap,Ke=new WeakMap,Ze=new WeakMap,Je=new WeakMap,Qe=new WeakMap,$e=new WeakMap,ti=new WeakMap,ei=new WeakMap,ii=new WeakMap,ri=new WeakMap,ni=new WeakMap,si=new WeakMap,oi=new WeakMap,ai=new WeakMap,hi=new WeakMap,li=new WeakMap,ci=new WeakMap,Be=new WeakSet,ui=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(me(this,Ye,"f"))delete t.video.facingMode,t.video.deviceId={exact:me(this,Ye,"f")};else if(this.ifSaveLastUsedCamera&&Ti.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(xe.OS)?(await this._getCameras(!1),me(this,Be,"m",di).call(this),e=Ti.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(xe.OS)||(await this._getCameras(!1),me(this,Be,"m",di).call(this),e=Ti.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const r=await e(i);r&&(delete t.video.facingMode,t.video.deviceId={exact:r})}return t},di=function(){if(me(this,ze,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},fi=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;try{Ti._onLog&&Ti._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const n=async t=>{for(let n of e){n&&(await new Promise((t=>setTimeout(t,n))),me(this,Be,"m",di).call(this));try{Ti._onLog&&Ti._onLog("ask "+JSON.stringify(t)),r=await navigator.mediaDevices.getUserMedia(t),me(this,Be,"m",di).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Ti._onLog&&Ti._onLog(t.message||t)}}};if(await n(t),r||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await n(t)),!r&&t.video.facingMode&&(delete t.video.facingMode,await n(t)),r||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await n(t))),!r)throw i;return r}catch(t){throw null==r||r.getTracks().forEach((t=>{t.stop()})),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},gi=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach((t=>{t.stop()})),this._mediaStream=null),pe(this,Ve,null,"f")},mi=async function(){pe(this,ze,!1,"f");const t=pe(this,Xe,Symbol(),"f");if(me(this,qe,"f")&&"pending"===me(this,Ke,"f")){try{await me(this,qe,"f")}catch(t){}me(this,Be,"m",di).call(this)}if(t!==me(this,Xe,"f"))return;const e=pe(this,qe,(async()=>{pe(this,Ke,"pending","f");try{if(this.videoSrc){if(!me(this,je,"f"))throw new Error("'videoEl' should be set.");await Ti.playVideo(me(this,je,"f"),this.videoSrc,this.cameraOpenTimeout),me(this,Be,"m",di).call(this)}else{let t=await me(this,Be,"m",ui).call(this);me(this,Be,"m",gi).call(this);let e=await me(this,Be,"m",fi).call(this,t);await this._getCameras(!1),me(this,Be,"m",di).call(this);const i=()=>{const t=e.getVideoTracks();let i,r;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,r=e;break}}return r},r=me(this,Ue,"f");if("object"==typeof r.video){let n=r.video.facingMode;if(n instanceof Array&&n.length&&(n=n[0]),"object"==typeof n&&(n=n.exact||n.ideal),!(me(this,Ye,"f")||this.ifSaveLastUsedCamera&&Ti.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||r.video.deviceId)){const r=i(),s=Ti.findBestCamera(this._arrCameras,n,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==r?void 0:r.deviceId)&&(e.getTracks().forEach((t=>{t.stop()})),t.video.deviceId={exact:s},e=await me(this,Be,"m",fi).call(this,t),me(this,Be,"m",di).call(this))}}const n=i();(null==n?void 0:n.deviceId)&&(pe(this,Ye,n&&n.deviceId,"f"),this.ifSaveLastUsedCamera&&Ti.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",me(this,Ye,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),me(this,je,"f")&&(await Ti.playVideo(me(this,je,"f"),e,this.cameraOpenTimeout),me(this,Be,"m",di).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&pe(this,Ve,s[0],"f"),pe(this,Ge,n,"f")}}catch(t){throw me(this,Be,"m",vi).call(this),pe(this,Ke,null,"f"),t}pe(this,Ke,"fulfilled","f")})(),"f");return e},pi=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=me(this,Ge,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await me(this,Be,"m",mi).call(this);const r=this.getResolution();e&&e!==me(this,Ge,"f").deviceId&&me(this,si,"f").fire("camera:changed",[me(this,Ge,"f").deviceId,e],{target:this,async:!1}),i.width==r.width&&i.height==r.height||me(this,si,"f").fire("resolution:changed",[{width:r.width,height:r.height},{width:i.width,height:i.height}],{target:this,async:!1}),me(this,si,"f").fire("played",null,{target:this,async:!1})},vi=function(){me(this,Be,"m",gi).call(this),pe(this,Ge,null,"f"),me(this,je,"f")&&(me(this,je,"f").srcObject=null,this.videoSrc&&(me(this,je,"f").pause(),me(this,je,"f").currentTime=0)),pe(this,ze,!0,"f");try{this.resetSoftwareScale()}catch(t){}},yi=async function t(e,i){const r=t=>{if(!me(this,Ve,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){me(this,Ve,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let n;i=Si(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await me(this,Ve,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),r(e),n=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise((t=>{setTimeout(t,n)})),r(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h),a>l.width&&(a=l.width),h>l.height&&(h=l.height),s<0?s=0:s+a>l.width&&(s=l.width-a),o<0?o=0:o+h>l.height&&(o=l.height-h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(me(this,je,"f"),{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:Ee.RGBA,bufferContainer:d}))return me(this,Be,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await me(this,Be,"m",t).call(this,e,o,a,n,s,c,u)}else{let h=await me(this,Be,"m",yi).call(this,e,c);if(a>h)return await me(this,Be,"m",t).call(this,e,o,a,n,s,c,h);if(a==h)return await me(this,Be,"m",t).call(this,e,o,a,c,h);let u=await me(this,Be,"m",yi).call(this,e,l);if(u>a&&ao.width||h<0||h>o.height)throw new Error("Invalid 'centerPoint'.");let l=0;if(e.endsWith("px"))l=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");l=parseFloat(e)/100*o.width}if(isNaN(l)||l<0)throw new Error("Invalid 'width'.");let c=0;if(i.endsWith("px"))c=parseFloat(i);else{if(!i.endsWith("%"))throw new Error("Invalid 'height'.");c=parseFloat(i)/100*o.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==me(this,ii,"f")){const t=me(this,ii,"f"),e=me(this,ri,"f");l/=t,c/=t,a=(1-1/t)*e.x+a/t,h=(1-1/t)*e.y+h/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const u={focusL:a,focusT:h,focusW:l,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let r=Si(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=Si(Math.sqrt((e||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Si(Math.sqrt(r*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await me(this,Be,"m",yi).call(this,t,s),a=await me(this,Be,"m",yi).call(this,t,n),h=await me(this,Be,"m",yi).call(this,t,r);if(a>h&&ho&&a>o){let e=await me(this,Be,"m",yi).call(this,t,i);const n=await me(this,Be,"m",_i).call(this,t,r,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,n}if(a==h&&hh){const e=await me(this,Be,"m",_i).call(this,t,r,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,r,n)},bi=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,r=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))r=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(r))throw new Error("Invalid scale center.");pe(this,ri,{x:i,y:r},"f")},xi=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},Ti.browserInfo=xe,Ti.onWarning=null===(Re=null===window||void 0===window?void 0:window.console)||void 0===Re?void 0:Re.warn;class ar{constructor(t){Ei.add(this),Oi.set(this,void 0),Ai.set(this,0),Ii.set(this,void 0),Li.set(this,0),Di.set(this,!1),S(this,Oi,t,"f")}startCharging(){C(this,Di,"f")||(ar._onLog&&ar._onLog("start charging."),C(this,Ei,"m",Fi).call(this),S(this,Di,!0,"f"))}stopCharging(){C(this,Ii,"f")&&clearTimeout(C(this,Ii,"f")),C(this,Di,"f")&&(ar._onLog&&ar._onLog("stop charging."),S(this,Ai,Date.now()-C(this,Li,"f"),"f"),S(this,Di,!1,"f"))}}Oi=new WeakMap,Ai=new WeakMap,Ii=new WeakMap,Li=new WeakMap,Di=new WeakMap,Ei=new WeakSet,Mi=function(){t.cfd(1),ar._onLog&&ar._onLog("charge 1.")},Fi=function t(){0==C(this,Ai,"f")&&C(this,Ei,"m",Mi).call(this),S(this,Li,Date.now(),"f"),C(this,Ii,"f")&&clearTimeout(C(this,Ii,"f")),S(this,Ii,setTimeout((()=>{S(this,Ai,0,"f"),C(this,Ei,"m",t).call(this)}),C(this,Oi,"f")-C(this,Ai,"f")),"f")};class hr{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-C(this,Pi,"f",Bi)<100)){if(S(this,Pi,e,"f",Bi),C(this,Pi,"f",ki).size&&(t=C(this,Pi,"f",ki).values().next().value,this.beepSoundSource==t.src?(C(this,Pi,"f",ki).delete(t),t.play()):t=null),!t)if(C(this,Pi,"f",Ri).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout((()=>{C(this,Pi,"f",Ri).delete(t)}),2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",(()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,C(this,Pi,"f",Ri).delete(t),C(this,Pi,"f",ki).add(t)}))}else C(this,Pi,"f",ji)||(S(this,Pi,!0,"f",ji),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&C(this,Pi,"f",Ri).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(hr.vibrateDuration)}}}Pi=hr,ki={value:new Set},Ri={value:new Set},Bi={value:0},ji={value:!1},hr.allowBeep=!0,hr.beepSoundSource="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",hr.allowVibrate=!0,hr.vibrateDuration=300;const lr=new Map([[Ee.GREY,o.IPF_GRAYSCALED],[Ee.RGBA,o.IPF_ABGR_8888]]),cr="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};class ur extends g{static set _onLog(t){S(ur,Wi,t,"f",Ni),Ti._onLog=t,ar._onLog=t}static get _onLog(){return C(ur,Wi,"f",Ni)}static async detectEnvironment(){return await(async()=>({wasm:L,worker:D,getUserMedia:M,camera:await F(),browser:I.browser,version:I.version,OS:I.OS}))()}static async testCameraAccess(){const t=await Ti.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(e){var r,n;if(e&&!(e instanceof ge))throw new TypeError("Invalid view.");if(null===(r=i.license)||void 0===r?void 0:r.LicenseManager){if(!(null===(n=i.license)||void 0===n?void 0:n.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await t.loadWasm(["license"]),await i.license.dynamsoft()}const s=new ur(e);return ur.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{ur.onWarning&&ur.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{ur.onWarning&&ur.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),s}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");S(this,Yi,t,"f")}get singleFrameMode(){return C(this,Yi,"f")}get _isFetchingStarted(){return C(this,Zi,"f")}get disposed(){return C(this,er,"f")}constructor(t){if(super(),Vi.add(this),Ui.set(this,"closed"),Gi.set(this,void 0),this.isTorchOn=void 0,Yi.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},Hi.set(this,((t,e,i,r)=>{const n=Date.now(),s={sx:r.x,sy:r.y,sWidth:r.width,sHeight:r.height,dWidth:r.width,dHeight:r.height},a=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&a>this.canvasSizeLimit){const t=this.canvasSizeLimit/a;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const h=this.cameraManager.imageDataGetter.getImageData(t,s,{pixelFormat:this.getPixelFormat()===o.IPF_GRAYSCALED?Ee.GREY:Ee.RGBA});let l=null;if(h){const t=Date.now();let o;if(h.pixelFormat===Ee.GREY)o=h.width;else o=4*h.width;let a=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(a=!1),l={bytes:h.data,width:h.width,height:h.height,stride:o,format:lr.get(h.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:m.ITT_FILE_IMAGE,isCropped:a,cropRegion:{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:h.width,currentHeight:h.height,timeSpent:t-n,timeStamp:t},toCanvas:C(this,Xi,"f"),isDCEFrame:!0}}return l})),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():wt.convert(C(this,qi,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height});const i=C(this,Hi,"f").call(this,t,t.width,t.height,e);C(this,Gi,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},Xi.set(this,(function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;t.width=this.width,t.height=this.height;if(this.format===o.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(I.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",(()=>{C(this,tr,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("camera:changed",(()=>{this.clearBuffer()})),this._on("before:resolution:change",(()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("resolution:changed",(()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})})),this._on("paused",(()=>{C(this,tr,"f").stopCharging();const t=this.cameraView;t&&t.disposed})),this._on("resumed",(()=>{const t=this.cameraView;t&&t.disposed})),this._on("tapfocus",(()=>{C(this,Qi,"f").tapToFocus&&C(this,tr,"f").startCharging()})),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,r,n,s;if(C(this,Vi,"m",ir).call(this)||!this.isOpen()||this.isPaused())return;const o=t.intermediateResultUnits;ur._onLog&&(ur._onLog("intermediateResultUnits:"),ur._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===p.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===p.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(ur._onLog&&(ur._onLog("hasLocalizedBarcodes:"),ur._onLog(h)),C(this,Qi,"f").autoZoom||C(this,Qi,"f").enhancedFocus)if(a)C(this,$i,"f").autoZoomInFrameArray.length=0,C(this,$i,"f").autoZoomOutFrameCount=0,C(this,$i,"f").frameArrayInIdealZoom.length=0,C(this,$i,"f").autoFocusFrameArray.length=0;else{const t=async t=>{await this.setZoom(t),C(this,Qi,"f").autoZoom&&C(this,tr,"f").startCharging()},e=async t=>{await this.setFocus(t),C(this,Qi,"f").enhancedFocus&&C(this,tr,"f").startCharging()};if(h){const a=o[0].originalImageTag,h=(null===(i=a.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(r=a.cropRegion)||void 0===r?void 0:r.top)||0,c=(null===(n=a.cropRegion)||void 0===n?void 0:n.right)?a.cropRegion.right-h:a.originalWidth,u=(null===(s=a.cropRegion)||void 0===s?void 0:s.bottom)?a.cropRegion.bottom-l:a.originalHeight,d=a.currentWidth,f=a.currentHeight;let g;{let t,e,i,r,n;{const t=this.video.videoWidth*(1-C(this,$i,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+C(this,$i,"f").autoZoomDetectionArea)/2,i=e,r=t,s=this.video.videoHeight*(1-C(this,$i,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+C(this,$i,"f").autoZoomDetectionArea)/2;n=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:r,y:a}]}ur._onLog&&(ur._onLog("detectionArea:"),ur._onLog(n));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let r=!1;const n=t.length;if(n<=2)return!1;for(let s=0;s0!=Tt(a.y-i)>0&&Tt(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(r=!r)}return r}(e,t.x,t.y)},r=(t,e)=>!!(Et([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||Et([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||Et([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||Et([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||(!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(r([e[0].x,e[0].y,e[1].x,e[1].y],t)||r([e[1].x,e[1].y,e[2].x,e[2].y],t)||r([e[2].x,e[2].y,e[3].x,e[3].y],t)||r([e[3].x,e[3].y,e[0].x,e[0].y],t)))};for(let e of o)if(e.unitType===p.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach((t=>{ge._transformCoordinates(t,h,l,c,u,d,f)})),t(n,e)&&s.push(i)}if(ur._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=he.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===p.IRUT_LOCALIZED_BARCODES)for(let r of i.localizedBarcodes){if(!r)continue;const i=r.location.points,n=new ht({points:i},e);t.addDrawingItems([n])}}}if(ur._onLog&&(ur._onLog("intersectedResults:"),ur._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter((t=>t.possibleFormats==cr.BF_QR_CODE||t.possibleFormats==cr.BF_DATAMATRIX));if(t.length||(t=s.filter((t=>t.possibleFormats==cr.BF_ONED)),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,r=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-d/2)*(i-d/2)+(r-f/2)*(r-f/2)};a=t[0];let i=e(a);if(1!=t.length)for(let r=1;r1.1*a.confidence?(a=t[r],i=n):t[r].confidence>.9*a.confidence&&ni&&s>i&&o>i&&a>i&&g.result.moduleSize{})),C(this,$i,"f").autoZoomInFrameArray.filter((t=>!0===t)).length>=C(this,$i,"f").autoZoomInFrameLimit[1]){C(this,$i,"f").autoZoomInFrameArray.length=0;const e=[(.5-r)/(.5-n),(.5-r)/(.5-s),(.5-r)/(.5-o),(.5-r)/(.5-a)].filter((t=>t>0)),i=Math.min(...e,C(this,$i,"f").autoZoomInIdealModuleSize/g.result.moduleSize),h=this.getZoomSettings().factor;let l=Math.max(Math.pow(h*i,1/C(this,$i,"f").autoZoomInMaxTimes),C(this,$i,"f").autoZoomInMinStep);l=Math.min(l,i);let c=h*l;c=Math.max(C(this,$i,"f").minValue,c),c=Math.min(C(this,$i,"f").maxValue,c);try{await t({factor:c})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(C(this,$i,"f").autoZoomInFrameArray.length=0,C(this,$i,"f").frameArrayInIdealZoom.push(!0),C(this,$i,"f").frameArrayInIdealZoom.splice(0,C(this,$i,"f").frameArrayInIdealZoom.length-C(this,$i,"f").frameLimitInIdealZoom[0]),C(this,$i,"f").frameArrayInIdealZoom.filter((t=>!0===t)).length>=C(this,$i,"f").frameLimitInIdealZoom[1]&&(C(this,$i,"f").frameArrayInIdealZoom.length=0,C(this,Qi,"f").enhancedFocus)){const t=g.points;try{await e({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}if(!C(this,Qi,"f").autoZoom&&C(this,Qi,"f").enhancedFocus&&(C(this,$i,"f").autoFocusFrameArray.push(!0),C(this,$i,"f").autoFocusFrameArray.splice(0,C(this,$i,"f").autoFocusFrameArray.length-C(this,$i,"f").autoFocusFrameLimit[0]),C(this,$i,"f").autoFocusFrameArray.filter((t=>!0===t)).length>=C(this,$i,"f").autoFocusFrameLimit[1])){C(this,$i,"f").autoFocusFrameArray.length=0;try{const t=g.points;await e({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(C(this,Qi,"f").autoZoom){if(C(this,$i,"f").autoZoomInFrameArray.push(!1),C(this,$i,"f").autoZoomInFrameArray.splice(0,C(this,$i,"f").autoZoomInFrameArray.length-C(this,$i,"f").autoZoomInFrameLimit[0]),C(this,$i,"f").autoZoomOutFrameCount++,C(this,$i,"f").frameArrayInIdealZoom.push(!1),C(this,$i,"f").frameArrayInIdealZoom.splice(0,C(this,$i,"f").frameArrayInIdealZoom.length-C(this,$i,"f").frameLimitInIdealZoom[0]),C(this,$i,"f").autoZoomOutFrameCount>=C(this,$i,"f").autoZoomOutFrameLimit){C(this,$i,"f").autoZoomOutFrameCount=0;const e=this.getZoomSettings().factor;let i=e-Math.max((e-1)*C(this,$i,"f").autoZoomOutStepRate,C(this,$i,"f").autoZoomOutMinStep);i=Math.max(C(this,$i,"f").minValue,i),i=Math.min(C(this,$i,"f").maxValue,i);try{await t({factor:i})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}C(this,Qi,"f").enhancedFocus&&e({mode:"continuous"}).catch((()=>{}))}!C(this,Qi,"f").autoZoom&&C(this,Qi,"f").enhancedFocus&&(C(this,$i,"f").autoFocusFrameArray.length=0,e({mode:"continuous"}).catch((()=>{})))}}},S(this,tr,new ar(1e4),"f")}setCameraView(t){if(!(t instanceof ge))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),C(this,Vi,"m",ir).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;C(this,Vi,"m",ir).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return C(this,Vi,"m",ir).call(this)?C(this,Ui,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){const t=this.cameraView;if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");t&&(t._singleFrameMode=this.singleFrameMode,C(this,Vi,"m",ir).call(this)?t._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(t.getVideoElement()),t._startLoading()));let e={width:0,height:0,deviceId:""};if(C(this,Vi,"m",ir).call(this));else{try{await this.cameraManager.open()}catch(e){throw t&&t._stopLoading(),"NotFoundError"===e.name?new Error(`No camera devices were detected. Please ensure a camera is connected and recognized by your system. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):"NotAllowedError"===e.name?new Error(`Camera access is blocked. Please check your browser settings or grant permission to use the camera. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):e}let i,r=t.getUIElement();if(r=r.shadowRoot||r,i=r.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=r.elTorchAuto=r.querySelector(".dce-mn-torch-auto"),e=r.elTorchOn=r.querySelector(".dce-mn-torch-on"),n=r.elTorchOff=r.querySelector(".dce-mn-torch-off");t&&(e.style.display=null==this.isTorchOn?"":"none"),e&&(e.style.display=1==this.isTorchOn?"":"none"),n&&(n.style.display=0==this.isTorchOn?"":"none");let s=r.elBeepOn=r.querySelector(".dce-mn-beep-on"),o=r.elBeepOff=r.querySelector(".dce-mn-beep-off");s&&(s.style.display=hr.allowBeep?"":"none"),o&&(o.style.display=hr.allowBeep?"none":"");let a=r.elVibrateOn=r.querySelector(".dce-mn-vibrate-on"),h=r.elVibrateOff=r.querySelector(".dce-mn-vibrate-off");a&&(a.style.display=hr.allowVibrate?"":"none"),h&&(h.style.display=hr.allowVibrate?"none":""),r.elResolutionBox=r.querySelector(".dce-mn-resolution-box");let l,c=r.elZoom=r.querySelector(".dce-mn-zoom");c&&(c.style.display="none",l=r.elZoomSpan=c.querySelector("span"));let u=r.elToast=r.querySelector(".dce-mn-toast"),d=r.elCameraClose=r.querySelector(".dce-mn-camera-close"),f=r.elTakePhoto=r.querySelector(".dce-mn-take-photo"),g=r.elCameraSwitch=r.querySelector(".dce-mn-camera-switch"),m=r.elCameraAndResolutionSettings=r.querySelector(".dce-mn-camera-and-resolution-settings");m&&(m.style.display="none");const p=r.dceMnFs={},v=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",v);const y=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",y);const _=()=>{this.turnAutoTorch()};null==n||n.addEventListener("pointerdown",_);const w=()=>{hr.allowBeep=!hr.allowBeep,s&&(s.style.display=hr.allowBeep?"":"none"),o&&(o.style.display=hr.allowBeep?"none":"")};for(let t of[o,s])null==t||t.addEventListener("pointerdown",w);const b=()=>{hr.allowVibrate=!hr.allowVibrate,a&&(a.style.display=hr.allowVibrate?"":"none"),h&&(h.style.display=hr.allowVibrate?"none":"")};for(let t of[h,a])null==t||t.addEventListener("pointerdown",b);const x=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),r=parseInt(e.getAttribute("data-height")),n=await this.setResolution({width:i,height:r});{let e=Math.max(n.width,n.height),i=Math.min(n.width,n.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&T(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?m&&(m.style.display=m.style.display?"":"none"):m&&""===m.style.display&&(m.style.display="none"))};r.addEventListener("click",x);let C=null;p.funcInfoZoomChange=(t,e=3e3)=>{c&&l&&(l.textContent=t.toFixed(1),c.style.display="",null!=C&&(clearTimeout(C),C=null),C=setTimeout((()=>{c.style.display="none",C=null}),e))};let S=null,T=p.funcShowToast=(t,e=3e3)=>{u&&(u.textContent=t,u.style.display="",null!=S&&(clearTimeout(S),S=null),S=setTimeout((()=>{u.style.display="none",S=null}),e))};const E=()=>{this.close()};null==d||d.addEventListener("click",E);const O=()=>{};null==f||f.addEventListener("pointerdown",O);const A=()=>{var t,e;let i,r=this.getVideoSettings(),n=r.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),o=null==s?void 0:s.indexOf("front");-1===o&&(o=null==s?void 0:s.indexOf("前"));let a=null==s?void 0:s.indexOf("back");if(-1===a&&(a=null==s?void 0:s.indexOf("后")),"number"==typeof o&&-1!==o?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i){i="user"===((null==n?void 0:n.ideal)||(null==n?void 0:n.exact)||n)}r.video.facingMode={ideal:i?"environment":"user"},delete r.video.deviceId,this.updateVideoSettings(r)};null==g||g.addEventListener("pointerdown",A);let L=-1/0,D=1;const M=t=>{let e=Date.now();e-L>1e3&&(D=this.getZoomSettings().factor),D-=t.deltaY/200,D>20&&(D=20),D<1&&(D=1),this.setZoom({factor:D}),L=e};i.addEventListener("wheel",M);const F=new Map;let P=!1;const k=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],r=t.touches[1],n=F.get(i.identifier),s=F.get(r.identifier);if(!n||!s)break;let o=Math.pow(Math.pow(n.x-s.x,2)+Math.pow(n.y-s.y,2),.5),a=Math.pow(Math.pow(i.clientX-r.clientX,2)+Math.pow(i.clientY-r.clientY,2),.5),h=Date.now();if(P||h-L<100)return;h-L>1e3&&(D=this.getZoomSettings().factor),D*=a/o,D>20&&(D=20),D<1&&(D=1);let l=!1;"safari"==(null===(e=null==I?void 0:I.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/o>1&&D<2?(D=2,l=!0):a/o<1&&D<2&&(D=1,l=!0)),P=!0,l&&T("zooming..."),await this.setZoom({factor:D}),l&&(u.textContent=""),P=!1,L=Date.now();break}F.clear();for(let e of t.touches)F.set(e.identifier,{x:e.clientX,y:e.clientY})};r.addEventListener("touchstart",k),r.addEventListener("touchmove",k),r.addEventListener("touchend",k),r.addEventListener("touchcancel",k),p.unbind=()=>{null==t||t.removeEventListener("pointerdown",v),null==e||e.removeEventListener("pointerdown",y),null==n||n.removeEventListener("pointerdown",_);for(let t of[o,s])null==t||t.removeEventListener("pointerdown",w);for(let t of[h,a])null==t||t.removeEventListener("pointerdown",b);r.removeEventListener("click",x),null==d||d.removeEventListener("click",E),null==f||f.removeEventListener("pointerdown",O),null==g||g.removeEventListener("pointerdown",A),i.removeEventListener("wheel",M),r.removeEventListener("touchstart",k),r.removeEventListener("touchmove",k),r.removeEventListener("touchend",k),r.removeEventListener("touchcancel",k),delete r.dceMnFs,i.style.display="none"},i.style.display="",t&&null==this.isTorchOn&&setTimeout((()=>{this.turnAutoTorch(1e3)}),0)}this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const n=this.getResolution();e.width=n.width,e.height=n.height,e.deviceId=this.getSelectedCamera().deviceId}return S(this,Ui,"open","f"),t&&(t._innerComponent.style.display="",C(this,Vi,"m",ir).call(this)||(t._stopLoading(),t._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),t._renderResolutionInfo({width:e.width,height:e.height}),t.eventHandler.fire("content:updated",null,{async:!1}),t.eventHandler.fire("videoEl:resized",null,{async:!1}))),C(this,Gi,"f").fire("opened",null,{target:this,async:!1}),e}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),C(this,Vi,"m",ir).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}S(this,Ui,"closed","f"),C(this,tr,"f").stopCharging(),e&&(e._innerComponent.style.display="none",C(this,Vi,"m",ir).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),C(this,Gi,"f").fire("closed",null,{target:this,async:!1})}pause(){if(C(this,Vi,"m",ir).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!C(this,Vi,"m",ir).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(C(this,Vi,"m",ir).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){if(!t)throw new Error("Invalid value.");let e;e="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(e),this.isTorchOn=!1;const i=this.getResolution(),r=this.cameraView;return r&&!r.disposed&&(r._stopLoading(),r._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),r._renderResolutionInfo({width:i.width,height:i.height})),{width:i.width,height:i.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?C(this,Gi,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?C(this,Gi,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._on(r,e)}off(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._off(r,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(C(this,Vi,"m",ir).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(C(this,Vi,"m",ir).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){if(null!=this._taskid4AutoTorch){if(!(t{var t,n,s;if(this.disposed||e||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++r>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let a;try{a=this.fetchImage()}catch(t){}if(!a||!a.width||!a.height)return;let h=0;if(o.IPF_GRAYSCALED===a.format){for(let t=0;t=this.maxDarkCount4AutoTroch){null===(t=ur._onLog)||void 0===t||t.call(ur,`darkCount ${i}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(n=null==t?void 0:t.dceMnFs)||void 0===n||n.funcShowToast("Torch Auto On")}catch(t){console.warn(t),e=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,null===(s=null==i?void 0:i.dceMnFs)||void 0===s||s.funcShowToast("Torch Not Supported")}}}else i=0};this._taskid4AutoTorch=setInterval(n,t),this.isTorchOn=void 0,n();let s=this.cameraView.getUIElement();s=s.shadowRoot||s,s.elTorchAuto&&(s.elTorchAuto.style.display=""),s.elTorchOn&&(s.elTorchOn.style.display="none"),s.elTorchOff&&(s.elTorchOff.style.display="none")}async setColorTemperature(t){if(C(this,Vi,"m",ir).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(C(this,Vi,"m",ir).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,r;if(C(this,Vi,"m",ir).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(r=null==e?void 0:e.dceMnFs)||void 0===r||r.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(C(this,Vi,"m",ir).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(C(this,Vi,"m",ir).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(C(this,Vi,"m",ir).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){C(this,$i,"f").minValue=t.min,C(this,$i,"f").maxValue=t.max}getAutoZoomRange(){return{min:C(this,$i,"f").minValue,max:C(this,$i,"f").maxValue}}async enableEnhancedFeatures(e){var r,n;if(!(null===(n=null===(r=i.license)||void 0===r?void 0:r.LicenseManager)||void 0===n?void 0:n.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==t.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");e&W.EF_ENHANCED_FOCUS&&(C(this,Qi,"f").enhancedFocus=!0),e&W.EF_AUTO_ZOOM&&(C(this,Qi,"f").autoZoom=!0),e&W.EF_TAP_TO_FOCUS&&(C(this,Qi,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&W.EF_ENHANCED_FOCUS&&(C(this,Qi,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch((()=>{}))),t&W.EF_AUTO_ZOOM&&(C(this,Qi,"f").autoZoom=!1,this.resetZoom().catch((()=>{}))),t&W.EF_TAP_TO_FOCUS&&(C(this,Qi,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),C(this,Vi,"m",nr).call(this)&&C(this,Vi,"m",rr).call(this)||C(this,tr,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!c(t)&&!r(t))throw TypeError("Invalid 'region'.");S(this,qi,t?JSON.parse(JSON.stringify(t)):null,"f"),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(C(this,qi,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");S(this,zi,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||C(this,Vi,"m",ir).call(this))}startFetching(){if(C(this,Vi,"m",ir).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");C(this,Zi,"f")||(S(this,Zi,!0,"f"),C(this,Vi,"m",sr).call(this))}stopFetching(){C(this,Zi,"f")&&(ur._onLog&&ur._onLog("DCE: stop fetching loop: "+Date.now()),C(this,Ji,"f")&&clearTimeout(C(this,Ji,"f")),S(this,Zi,!1,"f"))}fetchImage(){if(C(this,Vi,"m",ir).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(4!==this.video.readyState)throw new Error("The video is not loaded.");const t=this.getResolution();if(!(null==t?void 0:t.width)||!(null==t?void 0:t.height))throw new Error("The video is not loaded.");let e;if(e=wt.convert(C(this,qi,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height}),e.x>t.width||e.y>t.height)throw new Error("Invalid scan region.");e.x+e.width>t.width&&(e.width=t.width-e.x),e.y+e.height>t.height&&(e.height=t.height-e.y);const i={sx:e.x,sy:e.y,sWidth:e.width,sHeight:e.height,dWidth:e.width,dHeight:e.height},r=Math.max(i.dWidth,i.dHeight);if(this.canvasSizeLimit&&r>this.canvasSizeLimit){const t=this.canvasSizeLimit/r;i.dWidth>i.dHeight?(i.dWidth=this.canvasSizeLimit,i.dHeight=Math.round(i.dHeight*t)):(i.dWidth=Math.round(i.dWidth*t),i.dHeight=this.canvasSizeLimit)}const n=this.cameraManager.getFrameData({position:i,pixelFormat:this.getPixelFormat()===o.IPF_GRAYSCALED?Ee.GREY:Ee.RGBA});if(!n)return null;let s;if(n.pixelFormat===Ee.GREY)s=n.width;else s=4*n.width;let a=!0;0===i.sx&&0===i.sy&&i.sWidth===t.width&&i.sHeight===t.height&&(a=!1);return{bytes:n.data,width:n.width,height:n.height,stride:s,format:lr.get(n.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:m.ITT_VIDEO_FRAME,isCropped:a,cropRegion:{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height,isMeasuredInPercentage:!1},originalWidth:t.width,originalHeight:t.height,currentWidth:n.width,currentHeight:n.height,timeSpent:n.timeSpent,timeStamp:n.timeStamp},toCanvas:C(this,Xi,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,C(this,Zi,"f")&&(C(this,Ji,"f")&&clearTimeout(C(this,Ji,"f")),S(this,Ji,setTimeout((()=>{this.disposed||C(this,Vi,"m",sr).call(this)}),t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){S(this,Ki,t,"f")}getPixelFormat(){return C(this,Ki,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(C(this,Vi,"m",ir).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",(()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",(()=>{t&&this.open(),e.remove()}),{once:!0})})),e.addEventListener("change",(async()=>{const i=e.files[0],r=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(i),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=wt.convert(C(this,qi,"f"),n,s);o||(o={x:0,y:0,width:n,height:s});const a=C(this,Hi,"f").call(this,r,n,s,o);t&&t(a)})),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=C(this,Vi,"m",or).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=C(this,Vi,"m",or).call(this,t);return{x:e.clientX,y:e.clientY}}convertToScanRegionCoordinates(t){if(!C(this,qi,"f"))return JSON.parse(JSON.stringify(t));let e,i,r=C(this,qi,"f").left||C(this,qi,"f").x||0,n=C(this,qi,"f").top||C(this,qi,"f").y||0;if(!C(this,qi,"f").isMeasuredInPercentage)return{x:t.x-r,y:t.y-n};if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!C(this,Vi,"m",ir).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(C(this,Vi,"m",ir).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(C(this,Vi,"m",ir).call(this)){const t=this.cameraView._innerComponent.getElement("content");e=t.width,i=t.height}else{const t=this.getVideoEl();e=t.videoWidth,i=t.videoHeight}return{x:t.x-Math.round(r*e/100),y:t.y-Math.round(n*i/100)}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),S(this,er,!0,"f")}}var dr,fr,gr,mr,pr,vr,yr,_r;Wi=ur,Ui=new WeakMap,Gi=new WeakMap,Yi=new WeakMap,Hi=new WeakMap,Xi=new WeakMap,zi=new WeakMap,qi=new WeakMap,Ki=new WeakMap,Zi=new WeakMap,Ji=new WeakMap,Qi=new WeakMap,$i=new WeakMap,tr=new WeakMap,er=new WeakMap,Vi=new WeakSet,ir=function(){return"disabled"!==this.singleFrameMode},rr=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},nr=function(){for(let t in C(this,Qi,"f"))if(1==C(this,Qi,"f")[t])return!0;return!1},sr=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!C(this,Zi,"f"))return C(this,Ji,"f")&&clearTimeout(C(this,Ji,"f")),void S(this,Ji,setTimeout((()=>{this.disposed||C(this,Vi,"m",t).call(this)}),this.fetchInterval),"f");const e=()=>{var t;let e;ur._onLog&&ur._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{e=this.fetchImage()}catch(e){const i=e.message||e;if("The video is not loaded."===i)return;if(null===(t=C(this,zi,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout((()=>{var t;null===(t=C(this,zi,"f"))||void 0===t||t.onErrorReceived(y.EC_IMAGE_READ_FAILED,i)}),0);console.warn(e)}e?(this.addImageToBuffer(e),ur._onLog&&ur._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),C(this,Gi,"f").fire("frameAddedToBuffer",null,{async:!1})):ur._onLog&&ur._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case v.BOPM_BLOCK:break;case v.BOPM_UPDATE:e()}else e();C(this,Ji,"f")&&clearTimeout(C(this,Ji,"f")),S(this,Ji,setTimeout((()=>{this.disposed||C(this,Vi,"m",t).call(this)}),this.fetchInterval),"f")},or=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!C(this,Vi,"m",ir).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(C(this,Vi,"m",ir).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,r=e.top,n=i+window.scrollX,s=r+window.scrollY,{width:o,height:a}=this.cameraView._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(C(this,Vi,"m",ir).call(this)){const t=this.cameraView._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=this.cameraView.getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,v=1;if("contain"===c)u{var e;if(!this.isUseMagnifier)return;if(C(this,mr,"f")||S(this,mr,new wr,"f"),!C(this,mr,"f").magnifierCanvas)return;document.body.contains(C(this,mr,"f").magnifierCanvas)||(C(this,mr,"f").magnifierCanvas.style.position="fixed",C(this,mr,"f").magnifierCanvas.style.boxSizing="content-box",C(this,mr,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(C(this,mr,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void C(this,vr,"f").call(this);const r=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!r)return;const n=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*n,o=[{image:i,width:i.width,height:i.height},{image:r,width:r.width,height:r.height}];C(this,mr,"f").update(s,t.pointer,n,o);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(C(this,mr,"f").magnifierCanvas.style.left="auto",C(this,mr,"f").magnifierCanvas.style.top="0",C(this,mr,"f").magnifierCanvas.style.right="0"):(C(this,mr,"f").magnifierCanvas.style.left="0",C(this,mr,"f").magnifierCanvas.style.top="0",C(this,mr,"f").magnifierCanvas.style.right="auto")}C(this,mr,"f").show()})),vr.set(this,(()=>{C(this,mr,"f")&&C(this,mr,"f").hide()})),yr.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Ot(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=document.createElement("dce-component"),e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let r=this._innerComponent.getElement("content");r||(r=document.createElement("canvas"),r.style.objectFit="contain",this._innerComponent.setElement("content",r)),r.width===e&&r.height===i||(r.width=e,r.height=i);const n=r.getContext("2d");n.clearRect(0,0,r.width,r.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),n.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&n.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(s(t)){S(this,gr,t,"f");const{width:e,height:i,bytes:r,format:n}=Object.assign({},t);let s;if(n===o.IPF_GRAYSCALED){s=new Uint8ClampedArray(e*i*4);for(let t=0;t{if(!n){if(!i&&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"./"}})();e.CoreModule.engineResourcePaths.dce={version:"4.1.1",path:r,isInternal:!0},e.workerAutoResources.dce={wasm:!1,js:!1},e.mapPackageRegister.dce={};function s(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function o(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}let a,h,l,c,u;"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(a=navigator,h=a.userAgent,l=a.platform,c=a.mediaDevices),function(){if(!i){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:a.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:l,search:"Win"},Mac:{str:l},Linux:{str:l}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||h,o=r.search||e,a=r.verStr||h,l=r.verSearch||e;if(l instanceof Array||(l=[l]),-1!=s.indexOf(o)){i=e;for(let t of l){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||h,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=h.indexOf("Windows NT")&&(r="HarmonyOS"),u={browser:i,version:n,OS:r}}i&&(u={browser:"ssr",version:0,OS:"ssr"})}();const d="undefined"!=typeof WebAssembly&&h&&!(/Safari/.test(h)&&!/Chrome/.test(h)&&/\(.+\s11_2_([2-6]).*\)/.test(h)),f=!("undefined"==typeof Worker),g=!(!c||!c.getUserMedia),m=async()=>{let t=!1;if(g)try{(await c.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===u.browser&&u.version>66||"Safari"===u.browser&&u.version>13||"OPR"===u.browser&&u.version>43||"Edge"===u.browser&&u.version;var p={653:(t,e,i)=>{var n,r,s,o,a,h,l,c,u,d,f,g,m,p,v,y,_,w,b,x,C,S=S||{version:"5.2.1"};if(e.fabric=S,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?S.document=document:S.document=document.implementation.createHTMLDocument(""),S.window=window;else{var T=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;S.document=T.document,S.jsdomImplForWrapper=i(898).implForWrapper,S.nodeCanvas=i(245).Canvas,S.window=T,DOMParser=S.window.DOMParser}function E(t,e){var i=t.canvas,n=e.targetCanvas,r=n.getContext("2d");r.translate(0,n.height),r.scale(1,-1);var s=i.height-n.height;r.drawImage(i,0,s,n.width,n.height,0,0,n.width,n.height)}function O(t,e){var i=e.targetCanvas.getContext("2d"),n=e.destinationWidth,r=e.destinationHeight,s=n*r*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,n,r);i.putImageData(h,0,0)}S.isTouchSupported="ontouchstart"in S.window||"ontouchstart"in S.document||S.window&&S.window.navigator&&S.window.navigator.maxTouchPoints>0,S.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,S.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"],S.DPI=96,S.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",S.commaWsp="(?:\\s+,?\\s*|,\\s*)",S.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,S.reNonWord=/[ \n\.,;!\?\-]/,S.fontPaths={},S.iMatrix=[1,0,0,1,0,0],S.svgNS="http://www.w3.org/2000/svg",S.perfLimitSizeTotal=2097152,S.maxCacheSideLimit=4096,S.minCacheSideLimit=256,S.charWidthsCache={},S.textureSize=2048,S.disableStyleCopyPaste=!1,S.enableGLFiltering=!0,S.devicePixelRatio=S.window.devicePixelRatio||S.window.webkitDevicePixelRatio||S.window.mozDevicePixelRatio||1,S.browserShadowBlurConstant=1,S.arcToSegmentsCache={},S.boundsOfCurveCache={},S.cachesBoundsOfCurve=!0,S.forceGLPutImageData=!1,S.initFilterBackend=function(){return S.enableGLFiltering&&S.isWebglSupported&&S.isWebglSupported(S.textureSize)?(console.log("max texture size: "+S.maxTextureSize),new S.WebglFilterBackend({tileSize:S.textureSize})):S.Canvas2dFilterBackend?new S.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=S),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:S.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)}S.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var n=0,r=i.length;n-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)}},S.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof S.Gradient||this.set(e,new S.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof S.Pattern?i&&i():this.set(e,new S.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]}},n=e,r=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,S.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 n=new S.Point(t.x-e.x,t.y-e.y),r=S.util.rotateVector(n,i);return new S.Point(r.x,r.y).addEquals(e)},rotateVector:function(t,e){var i=S.util.sin(e),n=S.util.cos(e);return{x:t.x*n-t.y*i,y:t.x*i+t.y*n}},createVector:function(t,e){return new S.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 S.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var n=S.util.createVector(t,e),r=S.util.createVector(t,i),s=S.util.calcAngleBetweenVectors(n,r),o=s*(0===S.util.calcAngleBetweenVectors(S.util.rotateVector(n,s),r)?1:-1)/2;return{vector:S.util.getHatVector(S.util.rotateVector(n,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var n=[],r=e.strokeWidth/2,s=e.strokeUniform?new S.Point(1/e.scaleX,1/e.scaleY):new S.Point(1,1),o=function(t){var e=r/Math.hypot(t.x,t.y);return new S.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 S.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(S.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(S.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=S.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-r/Math.sin(p/2),f=new S.Point(m.x*d*s.x,m.y*d*s.y),Math.hypot(f.x,f.y)/r<=e.strokeMiterLimit))return n.push(u.add(f)),void n.push(u.subtract(f));d=-r*Math.SQRT2,f=new S.Point(m.x*d*s.x,m.y*d*s.y),n.push(u.add(f)),n.push(u.subtract(f))})),n},transformPoint:function(t,e,i){return i?new S.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new S.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>n?e-=n:e=0,i>n?i-=n:i=0);var r,s=!0,o=t.getImageData(e,i,2*n||1,2*n||1),a=o.data.length;for(r=3;r=r?s-r:2*Math.PI-(r-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=S.util.sin(c),d=S.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,v=(i=Math.abs(i))*i,y=(s=Math.abs(s))*s,_=p*p,w=m*m,b=v*y-v*_-y*w,x=0;if(b<0){var C=Math.sqrt(1-b/(v*y));i*=C,s*=C}else x=(o===a?-1:1)*Math.sqrt(b/(v*_+y*w));var T=x*i*p/s,E=-x*s*m/i,O=d*T-u*E+.5*t,I=u*T+d*E+.5*e,A=r(1,0,(m-T)/i,(p-E)/s),D=r((m-T)/i,(p-E)/s,(-m-T)/i,(-p-E)/s);0===a&&D>0?D-=2*l:1===a&&D<0&&(D+=2*l);for(var L=Math.ceil(Math.abs(D/l*2)),M=[],F=D/L,P=8/3*Math.sin(F/4)*Math.sin(F/4)/Math.sin(F/2),k=A+F,R=0;Rx)for(var T=1,E=m.length;T2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:r.x===t[i-2].x?0:-1,h=r.y>t[i-2].y?1:r.y===t[i-2].y?0:-1),n.push(["L",r.x+a*e,r.y+h*e]),n},S.util.getPathSegmentsInfo=d,S.util.getBoundsOfCurve=function(e,i,n,r,s,o,a,h){var l;if(S.cachesBoundsOfCurve&&(l=t.call(arguments),S.boundsOfCurveCache[l]))return S.boundsOfCurveCache[l];var c,u,d,f,g,m,p,v,y=Math.sqrt,_=Math.min,w=Math.max,b=Math.abs,x=[],C=[[],[]];u=6*e-12*n+6*s,c=-3*e+9*n-9*s+3*a,d=3*n-3*e;for(var T=0;T<2;++T)if(T>0&&(u=6*i-12*r+6*o,c=-3*i+9*r-9*o+3*h,d=3*r-3*i),b(c)<1e-12){if(b(u)<1e-12)continue;0<(f=-d/u)&&f<1&&x.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(v=y(p)))/(2*c))&&g<1&&x.push(g),0<(m=(-u-v)/(2*c))&&m<1&&x.push(m));for(var E,O,I,A=x.length,D=A;A--;)E=(I=1-(f=x[A]))*I*I*e+3*I*I*f*n+3*I*f*f*s+f*f*f*a,C[0][A]=E,O=I*I*I*i+3*I*I*f*r+3*I*f*f*o+f*f*f*h,C[1][A]=O;C[0][D]=e,C[1][D]=i,C[0][D+1]=a,C[1][D+1]=h;var L=[{x:_.apply(null,C[0]),y:_.apply(null,C[1])},{x:w.apply(null,C[0]),y:w.apply(null,C[1])}];return S.cachesBoundsOfCurve&&(S.boundsOfCurveCache[l]=L),L},S.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var n=0;e-i[n].length>0&&n1e-4;)i=h(s),r=s,(n=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=n);return i.angle=u(r),i}(s,e)}},S.util.transformPath=function(t,e,i){return i&&(e=S.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map((function(t){for(var i=t.slice(0),n={},r=1;r=e}))}}}(),function(){function t(e,i,n){if(n)if(!S.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var r=0,s=i.length;r57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var n=t.charCodeAt(e+1);if(56320>n||n>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 r=t.charCodeAt(e-1);if(55296>r||r>56319)throw"Low surrogate without preceding high surrogate";return!1}S.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,n=0,r=[];for(n=0;n-1?t.prototype[r]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=n;var r=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return r}}(r):t.prototype[r]=e[r],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function r(){}function s(e){for(var i=null,n=this;n.constructor.superclass;){var r=n.constructor.superclass.prototype[e];if(n[e]!==r){i=r;break}n=n.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)}S.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&&(r.prototype=i.prototype,a.prototype=new r,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===t.pointerType},d="string"==typeof(u=S.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=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}),S.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?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var n in e)"opacity"===n?m(t,e[n]):i["float"===n||"cssFloat"===n?void 0===i.styleFloat?"cssFloat":"styleFloat":n]=e[n];return t},function(){var t,e,i,n,r=Array.prototype.slice,s=function(t){return r.call(t,0)};try{t=s(S.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=S.document.createElement(t);for(var n in e)"class"===n?i.className=e[n]:"for"===n?i.htmlFor=e[n]:i.setAttribute(n,e[n]);return i}function a(t){for(var e=0,i=0,n=S.document.documentElement,r=S.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===S.document?(e=r.scrollLeft||n.scrollLeft||0,i=r.scrollTop||n.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=S.document.defaultView&&S.document.defaultView.getComputedStyle?function(t,e){var i=S.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=S.document.documentElement.style,n="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",S.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=S.util.falseFunction),n?t.style[n]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},S.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),n?t.style[n]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},S.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},S.util.getById=function(t){return"string"==typeof t?S.document.getElementById(t):t},S.util.toArray=s,S.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},S.util.makeElement=o,S.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},S.util.getScrollLeftTop=a,S.util.getElementOffset=function(t){var i,n,r=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!r)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=r.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),n=a(t),{left:s.left+n.left-(i.clientLeft||0)+o.left,top:s.top+n.top-(i.clientTop||0)+o.top}},S.util.getNodeCanvas=function(t){var e=S.jsdomImplForWrapper(t);return e._canvas||e._image},S.util.cleanUpJsdomNode=function(t){if(S.isLikelyNode){var e=S.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}S.util.request=function(e,i){i||(i={});var n=i.method?i.method.toUpperCase():"GET",r=i.onComplete||function(){},s=new S.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(r(s),s.onreadystatechange=t)},"GET"===n&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(n,e,!0),"POST"!==n&&"PUT"!==n||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),S.log=console.log,S.warn=console.warn,function(){var t=S.util.object.extend,e=S.util.object.clone,i=[];function n(){return!1}function r(t,e,i,n){return-i*Math.cos(t/n*(Math.PI/2))+i+e}S.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=S.window.requestAnimationFrame||S.window.webkitRequestAnimationFrame||S.window.mozRequestAnimationFrame||S.window.oRequestAnimationFrame||S.window.msRequestAnimationFrame||function(t){return S.window.setTimeout(t,1e3/60)},o=S.window.cancelAnimationFrame||S.window.clearTimeout;function a(){return s.apply(S.window,arguments)}S.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=S.runningAnimations.indexOf(s);return t>-1&&S.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}),S.runningAnimations.push(s),a((function(t){var e,l=t||+new Date,c=i.duration||500,u=l+c,d=i.onChange||n,f=i.abort||n,g=i.onComplete||n,m=i.easing||r,p="startValue"in i&&i.startValue.length>0,v="startValue"in i?i.startValue:0,y="endValue"in i?i.endValue:100,_=i.byValue||(p?v.map((function(t,e){return y[e]-v[e]})):y-v);i.onStart&&i.onStart(),function t(i){var n=(e=i||+new Date)>u?c:e-l,r=n/c,w=p?v.map((function(t,e){return m(n,v[e],_[e],c)})):m(n,v,_,c),b=p?Math.abs((w[0]-v[0])/_[0]):Math.abs((w-v)/_);if(s.currentValue=p?w.slice():w,s.completionRate=b,s.durationRate=r,!o){if(!f(w,b,r))return e>u?(s.currentValue=p?y.slice():y,s.completionRate=1,s.durationRate=1,d(p?y.slice():y,1,1),g(y,1,1),void h()):(d(w,b,r),void a(t));h()}}(l)})),s.cancel},S.util.requestAnimFrame=a,S.util.cancelAnimFrame=function(){return o.apply(S.window,arguments)},S.runningAnimations=i}(),function(){function t(t,e,i){var n="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(n+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}S.util.animateColor=function(e,i,n,r){var s=new S.Color(e).getSource(),o=new S.Color(i).getSource(),a=r.onComplete,h=r.onChange;return r=r||{},S.util.animate(S.util.object.extend(r,{duration:n||500,startValue:s,endValue:o,byValue:o,easing:function(e,i,n,s){return t(i,n,r.colorEasing?r.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,n){if(a)return a(t(o,o,0),i,n)},onChange:function(e,i,n){if(h){if(Array.isArray(e))return h(t(e,e,0),i,n);h(e,i,n)}}}))}}(),function(){function t(t,e,i,n){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,r)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,n,r,s,o=[];for(r=0,s=e.length;r1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();var y=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function _(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,n,r,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",v=!l||!(l=l.match(y)),_=!d||!f||"100%"===d||"100%"===f,w=v&&_,b={},x="",C=0,S=0;if(b.width=0,b.height=0,b.toBeParsed=w,v&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(x=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+x,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return b;if(v)return b.width=s(d),b.height=s(f),b;if(i=-parseFloat(l[1]),n=-parseFloat(l[2]),r=parseFloat(l[3]),o=parseFloat(l[4]),b.minX=i,b.minY=n,b.viewBoxWidth=r,b.viewBoxHeight=o,_?(b.width=r,b.height=o):(b.width=s(d),b.height=s(f),c=b.width/r,u=b.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),C=b.width-r*c,S=b.height-o*c,"Mid"===p.alignX&&(C/=2),"Mid"===p.alignY&&(S/=2),"Min"===p.alignX&&(C=0),"Min"===p.alignY&&(S=0)),1===c&&1===u&&0===i&&0===n&&0===g&&0===m)return b;if((g||m)&&"#document"!==t.parentNode.nodeName&&(x=" translate("+s(g)+" "+s(m)+") "),a=x+" matrix("+c+" 0 0 "+u+" "+(i*c+C)+" "+(n*u+S)+") ","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),b}function w(t,e){var i="xlink:href",n=v(t,e.getAttribute(i).slice(1));if(n&&n.getAttribute(i)&&w(t,n),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(t){n&&!e.hasAttribute(t)&&n.hasAttribute(t)&&e.setAttribute(t,n.getAttribute(t))})),!e.children.length)for(var r=n.cloneNode(!0);r.firstChild;)e.appendChild(r.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,r,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),n=0;i.length&&nt.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,n,r,s){var o,a=(s.x-r.x)*(t.y-r.y)-(s.y-r.y)*(t.x-r.x),h=(n.x-t.x)*(t.y-r.y)-(n.y-t.y)*(t.x-r.x),l=(s.y-r.y)*(n.x-t.x)-(s.x-r.x)*(n.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*(n.x-t.x),t.y+c*(n.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,n){var r,s,o,a,h=new i,l=n.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var n,r=new i,s=t.length;for(n=0;n0&&(r.status="Intersection"),r},e.Intersection.intersectPolygonRectangle=function(t,n,r){var s=n.min(r),o=n.max(r),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 n(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,n){t/=255,i/=255,n/=255;var r,s,o,a=e.util.array.max([t,i,n]),h=e.util.array.min([t,i,n]);if(o=(a+h)/2,a===h)r=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:r=(i-n)/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 n=i.transform.target,r=n.canvas,s=e.util.object.clone(i);s.target=n,r&&r.fire("object:"+t,s),n.fire(t,i)}function m(t,e){var i=e.canvas,n=t[i.uniScaleKey];return i.uniformScaling&&!n||!i.uniformScaling&&n}function p(t){return t.originX===l&&t.originY===l}function v(t,e,i){var n=t.lockScalingX,r=t.lockScalingY;return!((!n||!r)&&(e||!n&&!r||!i)&&(!n||"x"!==e)&&(!r||"y"!==e))}function y(t,e,i,n){return{e:t,transform:e,pointer:{x:i,y:n}}}function _(t){return function(e,i,n,r){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,n,r);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function w(t,e){return function(i,n,r,s){var o=e(i,n,r,s);return o&&g(t,y(i,n,r,s)),o}}function b(t,i,n,r,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(r,s),i,n);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 x(t){return t.flipX!==t.flipY}function C(t,e,i,n,r){if(0!==t[e]){var s=r/t._getTransformedDimensions()[n]*t[i];t.set(i,s)}}function S(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=b(e,e.originX,e.originY,i,n),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?r=0:(r=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),x(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",r),C(l,"skewY","scaleY","y",p)}return m}function T(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=b(e,e.originX,e.originY,i,n),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?r=0:(r=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),x(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",r),C(l,"skewX","scaleX","x",p)}return m}function E(t,e,i,n,r){r=r||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,y=f.lockScalingY,_=r.by,w=m(t,f),x=v(f,_,w),C=e.gestureScale;if(x)return!1;if(C)o=e.scaleX*C,a=e.scaleY*C;else{if(s=b(e,e.originX,e.originY,i,n),l="y"!==_?d(s.x):1,u="x"!==_?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(),w&&!_){var S=Math.abs(s.x)+Math.abs(s.y),T=e.original,E=S/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*E,a=T.scaleY*E}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"!==_&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==_&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var O=f.scaleX,I=f.scaleY;return _?("x"===_&&f.set("scaleX",o),"y"===_&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!y&&f.set("scaleY",a)),O!==f.scaleX||I!==f.scaleY}r.scaleCursorStyleHandler=function(t,e,n){var r=m(t,n),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),v(n,s,r))return"not-allowed";var o=f(n,e);return i[o]+"-resize"},r.skewCursorStyleHandler=function(t,e,i){var r="not-allowed";if(0!==e.x&&i.lockSkewingY)return r;if(0!==e.y&&i.lockSkewingX)return r;var s=f(i,e)%4;return n[s]+"-resize"},r.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?r.skewCursorStyleHandler(t,e,i):r.scaleCursorStyleHandler(t,e,i)},r.rotationWithSnapping=w("rotating",_((function(t,e,i,n){var r=e,s=r.target,o=s.translateToOriginPoint(s.getCenterPoint(),r.originX,r.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(r.ey-o.y,r.ex-o.x),l=Math.atan2(n-o.y,i-o.x),c=u(l-h+r.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(r=u===o?s:a),c<0&&(r=u===o?a:s),x(h)&&(r=r===s?a:s)),e.originX=r,w("skewing",_(S))(t,e,i,n))},r.skewHandlerY=function(t,e,i,n){var r,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?r=b(e,l,l,i,n).y>0?o:h:(c>0&&(r=u===s?o:h),c<0&&(r=u===s?h:o),x(a)&&(r=r===o?h:o)),e.originY=r,w("skewing",_(T))(t,e,i,n))},r.dragHandler=function(t,e,i,n){var r=e.target,s=i-e.offsetX,o=n-e.offsetY,a=!r.get("lockMovementX")&&r.left!==s,h=!r.get("lockMovementY")&&r.top!==o;return a&&r.set("left",s),h&&r.set("top",o),(a||h)&&g("moving",y(t,e,i,n)),a||h},r.scaleOrSkewActionName=function(t,e,i){var n=t[i.canvas.altActionKey];return 0===e.x?n?"skewX":"scaleY":0===e.y?n?"skewY":"scaleX":void 0},r.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},r.fireEvent=g,r.wrapWithFixedAnchor=_,r.wrapWithFireEvent=w,r.getLocalPoint=b,e.controlsUtils=r}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,n=e.controlsUtils;n.renderCircleControl=function(t,e,i,n,r){n=n||{};var s,o=this.sizeX||n.cornerSize||r.cornerSize,a=this.sizeY||n.cornerSize||r.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:r.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||r.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=n.cornerColor||r.cornerColor,t.strokeStyle=n.cornerStrokeColor||r.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()},n.renderSquareControl=function(t,e,n,r,s){r=r||{};var o=this.sizeX||r.cornerSize||s.cornerSize,a=this.sizeY||r.cornerSize||s.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=r.cornerColor||s.cornerColor,t.strokeStyle=r.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,n),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,n,r,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),m=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(m),l=f*e.util.sin(m)}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:n-l,y:r-h},tr:{x:n+o,y:r-a},bl:{x:n-o,y:r+a},br:{x:n+l,y:r+h}}},render:function(t,i,n,r,s){"circle"===((r=r||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,n,r,s):e.controlsUtils.renderSquareControl.call(this,t,i,n,r,s)}}}(e),function(){function t(t,e){var i,n,r,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&&(r=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),r||(r=t.getAttribute("stop-opacity")),n=(i=new S.Color(i)).getAlpha(),r=isNaN(parseFloat(r))?1:parseFloat(r),r*=n*e,{offset:a,color:i.toRgb(),opacity:r}}var e=S.util.object.clone;S.Gradient=S.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+="_"+S.Object.__uid++:this.id=S.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 S.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 S.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var n,r,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():S.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+" ":"")+S.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),n=0,r=h.length;n0){var p=m/Math.max(a.r1,a.r2);for(n=0,r=h.length;n\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,n,r=S.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(r.x1,r.y1,r.x2,r.y2):"radial"===this.type&&(e=t.createRadialGradient(r.x1,r.y1,r.r1,r.x2,r.y2,r.r2)),i=0,n=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,m=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=S.parseTransformAttribute(d),function(t,e,i,n){var r,s;Object.keys(e).forEach((function(t){"Infinity"===(r=e[t])?s=1:"-Infinity"===r?s=0:(s=parseFloat(e[t],10),"string"==typeof r&&/^(\d+\.\d+)%|(\d+)%$/.test(r)&&(s*=.01,"pixels"===n&&("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,r,u),"pixels"===u&&(g=-i.left,m=-i.top),new S.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:m})}})}(),v=S.util.toFixed,S.Pattern=S.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=S.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=S.util.createImage(),S.util.loadImage(t.source,(function(t,n){i.source=t,e&&e(i,n)}),null,this.crossOrigin)}},toObject:function(t){var e,i,n=S.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:v(this.offsetX,n),offsetY:v(this.offsetY,n),patternTransform:this.patternTransform?this.patternTransform.concat():null},S.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,n=e.height/t.height,r=this.offsetX/t.width,s=this.offsetY/t.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(n=1,s&&(n+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,r&&(i+=Math.abs(r))),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(),n=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(n[1],10)||0,offsetY:parseFloat(n[2],10)||0,blur:parseFloat(n[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var n=40,r=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&&(n=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,r=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(S.StaticCanvas)S.warn("fabric.StaticCanvas is already defined.");else{var t=S.util.object.extend,e=S.util.getElementOffset,i=S.util.removeFromArray,n=S.util.toFixed,r=S.util.transformPoint,s=S.util.invertTransform,o=S.util.getNodeCanvas,a=S.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");S.StaticCanvas=S.util.createClass(S.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:S.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 S.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,S.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=S.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,n){return"string"==typeof e?S.util.loadImage(e,(function(e,r){if(e){var s=new S.Image(e,n);this[t]=s,s.canvas=this}i&&i(e,r)}),this,n&&n.crossOrigin):(n&&e.setOptions(n),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=S.util.getById(t)||this._createCanvasElement(),S.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 n in e=e||{},t)i=t[n],e.cssOnly||(this._setBackstoreDimension(n,t[n]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(n,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,n,r=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,n=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,r=e.width||this.width,s=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=S.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="'+n(-i[4]/i[0],a)+" "+n(-i[5]/i[3],a)+" "+n(this.width/i[0],a)+" "+n(this.height/i[3],a)+'" '),t.push("\n',"Created with Fabric.js ",S.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+S.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 n=t[e+"Vpt"],r=t.viewportTransform,s={width:t.width/(n?r[0]:1),height:t.height/(n?r[3]:1)};return i.toSVG(s,{additionalTransform:n?S.util.matrixToSVG(r):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,n,r,s,o,a,h="",l={},c=S.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,n,r,s=this._objects;for(n=0,r=s.length;n\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(r=s._objects).length;e--;)n=r[e],i(this._objects,n),this._objects.unshift(n);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(r=s._objects,e=0;e0+l&&(o=s-1,i(this._objects,r),this._objects.splice(o,0,r)),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 n,r;if(i){for(n=e,r=e-1;r>=0;--r)if(t.intersectsWithObject(this._objects[r])||t.isContainedWithinObject(this._objects[r])||this._objects[r].isContainedWithinObject(t)){n=r;break}}else n=e-1;return n},bringForward:function(t,e){if(!t)return this;var n,r,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(n=(a=h._objects).length;n--;)r=a[n],(s=this._objects.indexOf(r))"}}),t(S.StaticCanvas.prototype,S.Observable),t(S.StaticCanvas.prototype,S.Collection),t(S.StaticCanvas.prototype,S.DataURLExporter),t(S.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}}),S.StaticCanvas.prototype.toJSON=S.StaticCanvas.prototype.toObject,S.isLikelyNode&&(S.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},S.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),S.BaseBrush=S.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,n=t.getZoom();t&&t._isRetinaScaling()&&(n*=S.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*n,i.shadowOffsetX=e.offsetX*n,i.shadowOffsetY=e.offsetY*n}},needsFullRender:function(){return new S.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()}}),S.PencilBrush=S.util.createClass(S.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 n=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,n.x,n.y),n},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,n=i.length,r=this.canvas.contextTop;this._saveAndTransform(r),this.oldEnd&&(r.beginPath(),r.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(r,i[n-2],i[n-1],!0),r.stroke(),r.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 S.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 S.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,n=this._points[0],r=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&n.x===r.x&&n.y===r.y){var s=this.width/1e3;n=new S.Point(n.x,n.y),r=new S.Point(r.x,r.y),n.x-=s,r.x+=s}for(t.moveTo(n.x,n.y),e=1,i=this._points.length;e=r&&(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})}}}),S.CircleBrush=S.util.createClass(S.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,n=this.points;for(this._saveAndTransform(i),t=0,e=n.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var r=0,s=this._objects.length;r1&&(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(),n=S.util.invertTransform(i),r=this.restorePointerVpt(e);return S.util.transformPoint(r,n)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var n=this._normalizePointer(t,{x:e,y:i}),r=Math.max(t.cacheTranslationX+n.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+n.y*t.zoomY,0);return S.util.isTransparent(t._cacheContext,Math.round(r),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,S.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(),n=this._activeObject;return!e||e&&n&&i.length>1&&-1===i.indexOf(e)&&n!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&n&&n!==e},_shouldCenterTransform:function(t,e,i){var n;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?n=this.centeredScaling||t.centeredScaling:"rotate"===e&&(n=this.centeredRotation||t.centeredRotation),n?!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,n){if(!e||!t)return"drag";var r=n.controls[e];return r.getActionName(i,r,n)},_setupCurrentTransform:function(t,i,n){if(i){var r=this.getPointer(t),s=i.__corner,o=i.controls[s],a=n&&s?o.getActionHandler(t,i,o):S.controlsUtils.dragHandler,h=this._getActionFromCorner(n,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:r.x-i.left,offsetY:r.y-i.top,originX:l.x,originY:l.y,ex:r.x,ey:r.y,lastX:r.x,lastY:r.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:S.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 S.Point(e.ex,e.ey),n=S.util.transformPoint(i,this.viewportTransform),r=new S.Point(e.ex+e.left,e.ey+e.top),s=S.util.transformPoint(r,this.viewportTransform),o=Math.min(n.x,s.x),a=Math.min(n.y,s.y),h=Math.max(n.x,s.x),l=Math.max(n.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,S.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var n,r,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;n=o,r=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&n&&c!==n&&(c=n,this.targets=r),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,n,r=t.length;r--;){var s=t[r],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,s,e)){(i=t[r]).subTargetCheck&&i instanceof S.Group&&(n=this._searchPossibleTargets(i._objects,e))&&this.targets.push(n);break}}return i},restorePointerVpt:function(t){return S.util.transformPoint(t,S.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var n,r=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(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,i||(r=this.restorePointerVpt(r));var l=this.getRetinaScaling();return 1!==l&&(r.x/=l,r.y/=l),n=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:r.x*n.width,y:r.y*n.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),S.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=S.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),S.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),S.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;S.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,S.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,n=this.getActiveObjects(),r=[],s=[];t.forEach((function(t){-1===n.indexOf(t)&&(i=!0,t.fire("deselected",{e:e,target:t}),s.push(t))})),n.forEach((function(n){-1===t.indexOf(n)&&(i=!0,n.fire("selected",{e:e,target:n}),r.push(n))})),t.length>0&&n.length>0?i&&this.fire("selection:updated",{e:e,selected:r,deselected:s}):n.length>0?this.fire("selection:created",{e:e,selected:r}):t.length>0&&this.fire("selection:cleared",{e: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: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){S.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,S.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 n=this._realizeGroupTransformOnObject(t),r=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,n),r},_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]})),S.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,n)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),S.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),S.StaticCanvas)"prototype"!==n&&(S.Canvas[n]=S.StaticCanvas[n])}(),function(){var t=S.util.addListener,e=S.util.removeListener,i={passive:!1};function n(t,e){return t.button&&t.button===e-1}S.util.object.extend(S.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 n=this.upperCanvasEl,r=this._getEventPrefix();t(S.window,"resize",this._onResize),t(n,r+"down",this._onMouseDown),t(n,r+"move",this._onMouseMove,i),t(n,r+"out",this._onMouseOut),t(n,r+"enter",this._onMouseEnter),t(n,"wheel",this._onMouseWheel),t(n,"contextmenu",this._onContextMenu),t(n,"dblclick",this._onDoubleClick),t(n,"dragover",this._onDragOver),t(n,"dragenter",this._onDragEnter),t(n,"dragleave",this._onDragLeave),t(n,"drop",this._onDrop),this.enablePointerEvents||t(n,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](n,"gesture",this._onGesture),eventjs[e](n,"drag",this._onDrag),eventjs[e](n,"orientation",this._onOrientationChange),eventjs[e](n,"shake",this._onShake),eventjs[e](n,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(S.document,t+"up",this._onMouseUp),e(S.document,"touchend",this._onTouchEnd,i),e(S.document,t+"move",this._onMouseMove,i),e(S.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(n){i.fire("mouse:out",{target:e,e:t}),n&&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(n){n.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(n)),this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();t(S.document,"touchend",this._onTouchEnd,i),t(S.document,"touchmove",this._onMouseMove,i),e(r,s+"down",this._onMouseDown)},_onMouseDown:function(n){this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();e(r,s+"move",this._onMouseMove,i),t(S.document,s+"up",this._onMouseUp),t(S.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(n){if(!(n.touches.length>0)){this.__onMouseUp(n),this._resetTransformEventData(),this.mainTouchId=null;var r=this._getEventPrefix();e(S.document,"touchend",this._onTouchEnd,i),e(S.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){t(s.upperCanvasEl,r+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(n){this.__onMouseUp(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(n)&&(e(S.document,s+"up",this._onMouseUp),e(S.document,s+"move",this._onMouseMove,i),t(r,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,r=this._groupSelector,s=!1,o=!r||0===r.left&&0===r.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),n(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(n(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),S.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),n=this.targets,r={e:e,target:i,subTargets:n};if(this.fire(t,r),i&&i.fire(t,r),!n)return i;for(var s=0;s1&&(e=new S.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],n=this._groupSelector.ex,r=this._groupSelector.ey,s=n+this._groupSelector.left,o=r+this._groupSelector.top,a=new S.Point(y(n,s),y(r,o)),h=new S.Point(_(n,s),_(r,o)),l=!this.selectionFullyContained,c=n===s&&r===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}}),S.util.object.extend(S.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,n=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),r=this.toCanvasElement(n,t);return S.util.toDataURL(r,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,n=(e.height||this.height)*t,r=this.getZoom(),s=this.width,o=this.height,a=r*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=S.util.createCanvasElement(),m=this.contextTop;return g.width=i,g.height=n,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=n,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=m,g}}),S.util.object.extend(S.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var n="string"==typeof t?JSON.parse(t):S.util.object.clone(t),r=this,s=n.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete n.clipPath,this._enlivenObjects(n.objects,(function(t){r.clear(),r._setBgOverlay(n,(function(){s?r._enlivenObjects([s],(function(i){r.clipPath=i[0],r.__setupCanvas.call(r,n,t,o,e)})):r.__setupCanvas.call(r,n,t,o,e)}))}),i),this}},__setupCanvas:function(t,e,i,n){var r=this;e.forEach((function(t,e){r.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(),n&&n()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var n=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,n),this.__setBgOverlay("overlayImage",t.overlayImage,i,n),this.__setBgOverlay("backgroundColor",t.background,i,n),this.__setBgOverlay("overlayColor",t.overlay,i,n)}else e&&e()},__setBgOverlay:function(t,e,i,n){var r=this;if(!e)return i[t]=!0,void(n&&n());"backgroundImage"===t||"overlayImage"===t?S.util.enlivenObjects([e],(function(e){r[t]=e[0],i[t]=!0,n&&n()})):this["set"+S.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,n&&n()}))},_enlivenObjects:function(t,e,i){t&&0!==t.length?S.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(n){i(n.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=S.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new S.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,n=e.util.object.clone,r=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,n=t.width,r=t.height,s=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(n<=s&&r<=s&&n*r<=i)return nc&&(t.zoomX/=n/c,t.width=c,t.capped=!0),r>u&&(t.zoomY/=r/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,n=e.y*t.scaleY/this.scaleY;return{width:i+2,height:n+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:n}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,n=t._currentTransform.action;if(this===i&&n.slice&&"scale"===n.slice(0,5))return!1}var r,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,m=f||g,p=0,v=0,y=!1;if(f){var _=this._cacheCanvas.width,w=this._cacheCanvas.height,b=l>_||c>w;y=b||(l<.9*_||c<.9*w)&&_>h&&w>h,b&&!a.capped&&(l>h||c>h)&&(p=.1*l,v=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,y=!0,p+=this.getHeightOfLine(0)*this.zoomX,v+=this.getHeightOfLine(0)*this.zoomY),!!m&&(y?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+v)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),r=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-r)+r,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,n={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:r(this.left,i),top:r(this.top,i),width:r(this.width,i),height:r(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:r(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:r(this.strokeMiterLimit,i),scaleX:r(this.scaleX,i),scaleY:r(this.scaleY,i),angle:r(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:r(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:r(this.skewX,i),skewY:r(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(n.clipPath=this.clipPath.toObject(t),n.clipPath.inverted=this.clipPath.inverted,n.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,n,t),this.includeDefaultValues||(n=this._removeDefaultValues(n)),n},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 n=this.canvas.getZoom(),r=this.canvas.getRetinaScaling();e*=n*r,i*=n*r}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var n="scaleX"===t||"scaleY"===t,r=this[t]!==i,s=!1;return n&&(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,r&&(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 n=e.util.invertTransform(this.calcTransformMatrix());t.transform(n[0],n[1],n[2],n[3],n[4],n[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,n=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=n},_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 n,r,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();r=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),n=e.util.qrDecompose(h),t.save(),t.translate(n.translateX,n.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(n.angle-=180),t.rotate(o(this.group?n.angle:this.angle)),i.forActiveSelection||this.group?r&&this.drawBordersInGroup(t,n,i):r&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,n=this.shadow,r=this.canvas,s=r&&r.viewportTransform[0]||1,o=r&&r.viewportTransform[3]||1;i=n.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),r&&r._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=n.color,t.shadowBlur=n.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=n.offsetX*s*i.scaleX,t.shadowOffsetY=n.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,n=-this.width/2+e.offsetX||0,r=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,n,r):t.transform(1,0,0,1,n,r),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:n,offsetY:r}},_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 n,r=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=r.x/this.scaleX/o,h=r.y/this.scaleY/o;s.width=a,s.height=h,(n=s.getContext("2d")).beginPath(),n.moveTo(0,0),n.lineTo(a,0),n.lineTo(a,h),n.lineTo(0,h),n.closePath(),n.translate(a/2,h/2),n.scale(r.zoomX/this.scaleX/o,r.zoomY/this.scaleY/o),this._applyPatternGradientTransform(n,i),n.fillStyle=i.toLive(t),n.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/r.zoomX,o*this.scaleY/r.zoomY),t.strokeStyle=n.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 n=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(n,t):e.Object._fromObject("Object",n,t)},cloneAsImage:function(t,i){var n=this.toCanvasElement(i);return t&&t(new e.Image(n)),this},toCanvasElement:function(t){t||(t={});var i=e.util,n=i.saveObjectTransform(this),r=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,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.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 v=this.canvas;p.add(this);var y=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",v),r&&(this.group=r),this.set(n).setCoords(),p._objects=[],p.dispose(),p=null,y},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 n=new e.Point(i.x,i.y),r=this._getLeftTopCoords();return this.angle&&(n=e.util.rotatePoint(n,r,o(-this.angle))),{x:n.x-r.x,y:n.y-r.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,r,s){var o=e[t];i=n(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);r&&r(t)}))}))},e.Object.__uid=0)}(e),w=S.util.degreesToRadians,b={left:-.5,center:0,right:.5},x={top:-.5,center:0,bottom:.5},S.util.object.extend(S.Object.prototype,{translateToGivenOrigin:function(t,e,i,n,r){var s,o,a,h=t.x,l=t.y;return"string"==typeof e?e=b[e]:e-=.5,"string"==typeof n?n=b[n]:n-=.5,"string"==typeof i?i=x[i]:i-=.5,"string"==typeof r?r=x[r]:r-=.5,o=r-i,((s=n-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+s*a.x,l=t.y+o*a.y),new S.Point(h,l)},translateToCenterPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?S.util.rotatePoint(n,t,w(this.angle)):n},translateToOriginPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?S.util.rotatePoint(n,t,w(this.angle)):n},getCenterPoint:function(){var t=new S.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 n,r,s=this.getCenterPoint();return n=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new S.Point(this.left,this.top),r=new S.Point(t.x,t.y),this.angle&&(r=S.util.rotatePoint(r,s,-w(this.angle))),r.subtractEquals(n)},setPositionByOrigin:function(t,e,i){var n=this.translateToCenterPoint(t,e,i),r=this.translateToOriginPoint(n,this.originX,this.originY);this.set("left",r.x),this.set("top",r.y)},adjustPosition:function(t){var e,i,n=w(this.angle),r=this.getScaledWidth(),s=S.util.cos(n)*r,o=S.util.sin(n)*r;e="string"==typeof this.originX?b[this.originX]:this.originX-.5,i="string"==typeof t?b[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=S.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,n=t.transformPoint;t.object.extend(S.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 S.Point(i.tl.x,i.tl.y),new S.Point(i.tr.x,i.tr.y),new S.Point(i.br.x,i.br.y),new S.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,n){var r=this.getCoords(i,n);return"Intersection"===S.Intersection.intersectPolygonRectangle(r,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===S.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 n=this.getCoords(e,i),r=e?t.aCoords:t.lineCoords,s=0,o=t._getImageLines(r);s<4;s++)if(!t.containsPoint(n[s],o))return!1;return!0},isContainedWithinRect:function(t,e,i,n){var r=this.getBoundingRect(i,n);return r.left>=t.x&&r.left+r.width<=e.x&&r.top>=t.y&&r.top+r.height<=e.y},containsPoint:function(t,e,i,n){var r=this._getCoords(i,n),s=(e=e||this._getImageLines(r),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 n={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(n,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,n,r,s=0;for(var o in e)if(!((r=e[o]).o.y=t.y&&r.d.y>=t.y||(r.o.x===r.d.x&&r.o.x>=t.x?n=r.o.x:(i=(r.d.y-r.o.y)/(r.d.x-r.o.x),n=-(t.y-0*t.x-(r.o.y-i*r.o.x))/(0-i)),n>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var n=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(n)},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,n=e.additionalTransform||"",r=[this.getSvgTransform(!0,n),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=r,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,n,r=(e=e||{}).noStyle,s=e.reviver,o=r?"":'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=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+S.Object.__uid++,n='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,r?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=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(n),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=S.util.object.extend,e="stateProperties";function i(e,i,n){var r={};n.forEach((function(t){r[t]=e[t]})),t(e[i],r,!0)}function n(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var r=0,s=t.length;r=0;h--)if(r=a[h],this.isControlVisible(r)&&(n=this._getImageLines(e?this.oCoords[r].touchCorner:this.oCoords[r].corner),0!==(i=this._findCrossPoints({x:s,y:o},n))&&i%2==1))return this.__corner=r,r;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(),n=this._calculateCurrentDimensions(),r=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/r[0],1/r[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-n.x/2,-n.y/2,n.x,n.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),n=this.borderScaleFactor,r=i.x+n,s=i.y+n,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(-r/2,-s/2,r,s),o&&(t.beginPath(),this.forEachControl((function(e,i,n){e.withConnection&&e.getVisibility(n,i)&&(a=!0,t.moveTo(e.x*r,e.y*s),t.lineTo(e.x*r+e.offsetX,e.y*s+e.offsetY))})),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var n=S.util.sizeAfterTransform(this.width,this.height,e),r=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=n.x+r*(s?this.canvas.getZoom():e.scaleX)+o,h=n.y+r*(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,n,r=this.canvas.getRetinaScaling();return t.setTransform(r,0,0,r,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(r,s,o){n=o.oCoords[s],r.getVisibility(o,s)&&(i&&(n=S.util.transformPoint(n,i)),r.render(t,n.x,n.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(){}})}(),S.util.object.extend(S.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return S.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxCenterObjectV:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return S.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxRemove:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return S.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),r()},onComplete:function(){s.remove(t),n()}})}}),S.util.object.extend(S.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],n=[];for(t in arguments[0])i.push(t);for(var r=0,s=i.length;r-1||r&&s.colorProperties.indexOf(r[1])>-1,a=r?this.get(r[0])[r[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,n){return i.abort.call(s,t,e,n)},onChange:function(e,o,a){r?s[r[0]][r[1]]=e:s.set(t,e),n||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,r){n||(s.setCoords(),i.onComplete&&i.onComplete(t,e,r))}};return o?S.util.animateColor(h.startValue,h.endValue,h.duration,h):S.util.animate(h)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,n=t.axis1,r=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(n),this.get(r));case a:return Math.min(this.get(n),this.get(r))+.5*this.get(s);case h:return Math.max(this.get(n),this.get(r))}}}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!==r[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,n=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:n,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,n,r){r=r||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];n(new e.Line(o,i(s,r)))},e.Line.fromObject=function(t,i){var r=n(t,!0);r.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",r,(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,n=(this.endAngle-this.startAngle)%360;if(0===n)t=["\n'];else{var r=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 n,r=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(n=r)&&n.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");r.left=(r.left||0)-r.radius,r.top=(r.top||0)-r.radius,i(new e.Circle(r))},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 n=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);n.left=(n.left||0)-n.rx,n.top=(n.top||0)-n.ry,i(new e.Ellipse(n))},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,n=this.width,r=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+n-e,o),a&&t.bezierCurveTo(s+n-h*e,o,s+n,o+h*i,s+n,o+i),t.lineTo(s+n,o+r-i),a&&t.bezierCurveTo(s+n,o+r-h*i,s+n-h*e,o+r,s+n-e,o+r),t.lineTo(s+e,o+r),a&&t.bezierCurveTo(s+h*e,o+r,s,o+r-h*i,s,o+r-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,n,r){if(!t)return n(null);r=r||{};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(r?e.util.object.clone(r):{},s));o.visible=o.visible&&o.width>0&&o.height>0,n(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,n=e.util.array.min,r=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),n=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-n,this.height=i.height-n,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+n/2,y:i.top-this.strokeWidth/2+n/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+n/2,y:i.top+this.height/2+n/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=n(t,"x")||0,i=n(t,"y")||0;return{left:e,top:i,width:(r(t,"x")||0)-e,height:(r(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,n=this.pathOffset.y,r=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,n=this.pathOffset.x,r=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-n,this.points[0].y-r);for(var s=0;s"},toObject:function(t){return r(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,r,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 n=this._objects.length;if(this.useSetOnGroup)for(;n--;)this._objects[n].setOnGroup(t,i);if("canvas"===t)for(;n--;)this._objects[n]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,n=this._objects.filter((function(t){return!t.excludeFromExport})).map((function(e){var n=e.includeDefaultValues;e.includeDefaultValues=i;var r=e.toObject(t);return e.includeDefaultValues=n,r})),r=e.Object.prototype.toObject.call(this,t);return r.objects=n,r},toDatalessObject:function(t){var i,n=this.sourcePath;if(n)i=n;else{var r=this.includeDefaultValues;i=this._objects.map((function(e){var i=e.includeDefaultValues;e.includeDefaultValues=r;var n=e.toDatalessObject(t);return e.includeDefaultValues=i,n}))}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,n=this._objects.length;i\n"],i=0,n=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,n=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 n=0,r=this._objects.length;n\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 S.util.loadImage(t,(function(t,n){this.setElement(t,i),this._setWidthHeight(),e&&e(this,n)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),n=i.scaleX,r=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||n>e&&r>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=n,void(this._lastScaleY=r);S.filterBackend||(S.filterBackend=S.initFilterBackend());var o=S.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=n,this._lastScaleY=t.scaleY=r,S.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,n=e.naturalHeight||e.height;if(this._element===this._originalElement){var r=S.util.createCanvasElement();r.width=i,r.height=n,this._element=r,this._filteredEl=r}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,n),this._lastScaleX=1,this._lastScaleY=1;return S.filterBackend||(S.filterBackend=S.initFilterBackend()),S.filterBackend.applyFilters(t,this._originalElement,i,n,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){S.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){S.util.setImageSmoothing(t,this.imageSmoothing),S.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,n=this._filterScalingY,r=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*n,g=o(r*i,c-d),m=o(s*n,u-f),p=-r/2,v=-s/2,y=o(r,c/i-h),_=o(s,u/n-l);e&&t.drawImage(e,d,f,g,m,p,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(S.util.getById(t),e),S.util.addClass(this.getElement(),S.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?S.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=S.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,n=this._element.height,r=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?(r=c/i,s=u/n):("meet"===e.meetOrSlice&&(t=(c-i*(r=s=S.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-n*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(r=s=S.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=n-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/r,n=u/s)),{width:i,height:n,scaleX:r,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),S.Image.CSS_CANVAS="canvas-img",S.Image.prototype.getSvgSrc=S.Image.prototype.getSrc,S.Image.fromObject=function(t,e){var i=S.util.object.clone(t);S.util.loadImage(i.src,(function(t,n){n?e&&e(null,!0):S.Image.prototype._initFilters.call(i,i.filters,(function(n){i.filters=n||[],S.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(n){i.resizeFilter=n[0],S.util.enlivenObjectEnlivables(i,i,(function(){var n=new S.Image(t,i);e(n,!1)}))}))}))}),null,i.crossOrigin)},S.Image.fromURL=function(t,e,i){S.util.loadImage(t,(function(t,n){e&&e(new S.Image(t,i),n)}),null,i&&i.crossOrigin)},S.Image.ATTRIBUTE_NAMES=S.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),S.Image.fromElement=function(t,i,n){var r=S.parseAttributes(t,S.Image.ATTRIBUTE_NAMES);S.Image.fromURL(r["xlink:href"],i,e(n?S.util.object.clone(n):{},r))})}(e),S.util.object.extend(S.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,n=t.onChange||e,r=this;return S.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){r.rotate(t),n()},onComplete:function(){r.setCoords(),i()}})}}),S.util.object.extend(S.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(){}",n=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(n,i),t.compileShader(n),!!t.getShaderParameter(n,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}S.isWebglSupported=function(e){if(S.isLikelyNode)return!1;e=e||S.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),n=i.getContext("webgl")||i.getContext("experimental-webgl"),r=!1;if(n){S.maxTextureSize=n.getParameter(n.MAX_TEXTURE_SIZE),r=S.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(n,s[o])){S.webGlPrecision=s[o];break}}return this.isSupported=r,r},S.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,n=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var r="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(n&&i&&r&&s){var o=S.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(S.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=O);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),E.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),O.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=O):this.copyGLTo2D=E}},createWebGLCanvas:function(t,e){var i=S.util.createCanvasElement();i.width=t,i.height=e;var n={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},r=i.getContext("webgl",n);r||(r=i.getContext("experimental-webgl",n)),r&&(r.clearColor(0,0,0,0),this.canvas=i,this.gl=r)},applyFilters:function(t,e,i,n,r,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:n,destinationWidth:i,destinationHeight:n,context:a,sourceTexture:this.createTexture(a,i,n,!o&&e),targetTexture:this.createTexture(a,i,n),originalTexture:o||this.createTexture(a,i,n,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:r},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,n=e.height,r=t.destinationWidth,s=t.destinationHeight;i===r&&n===s||(e.width=r,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),r.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,n){var r=t.createTexture();return t.bindTexture(t.TEXTURE_2D,r),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),n?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,n):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),r},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:E,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 n=t.getParameter(i.UNMASKED_RENDERER_WEBGL),r=t.getParameter(i.UNMASKED_VENDOR_WEBGL);n&&(e.renderer=n.toLowerCase()),r&&(e.vendor=r.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}S.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,n,r){var s=r.getContext("2d");s.drawImage(e,0,0,i,n);var o={sourceWidth:i,sourceHeight:n,imageData:s.getImageData(0,0,i,n),originalEl:e,originalImageData:s.getImageData(0,0,i,n),canvasEl:r,ctx:s,filterBackend:this};return t.forEach((function(t){t.applyTo(o)})),o.imageData.width===i&&o.imageData.height===n||(r.width=o.imageData.width,r.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),S.Image=S.Image||{},S.Image.filters=S.Image.filters||{},S.Image.filters.BaseFilter=S.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"!==S.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+S.webGlPrecision+" float"));var n=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var r=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var s=t.createProgram();if(t.attachShader(s,n),t.attachShader(s,r),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 n=e.aPosition,r=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,r),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,n=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(n.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(n,e,i)),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t.targetTexture,0)):(n.bindFramebuffer(n.FRAMEBUFFER,null),n.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=S.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()}}),S.Image.filters.BaseFilter.fromObject=function(t,e){var i=new S.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.ColorMatrix=n(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,n,r,s,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=w||o<0||o>=_||(h=4*(a*_+o),l=p[f*v+d],e+=m[h]*l,i+=m[h+1]*l,n+=m[h+2]*l,C||(r+=m[h+3]*l));x[s]=e,x[s+1]=i,x[s+2]=n,x[s+3]=C?m[s+3]:r}t.imageData=b},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,n=e.util.createClass;i.Grayscale=n(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,n=t.imageData.data,r=n.length,s=this.mode;for(e=0;el[0]&&r>l[1]&&s>l[2]&&n 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,n,r,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,n=h[1]*this.alpha,r=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,n=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/n;var r,s=e.width,a=e.height,h=o(s*i),l=o(a*n);"sliceHack"===this.resizeType?r=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?r=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?r=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(r=this.lanczosResize(t,s,a,h,l)),t.imageData=r},sliceByTwo:function(t,i,r,s,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=r*c,m=e.filterBackend.resources,p=0,v=0,y=i,_=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){M=n(1e3*s(S-b.x)),w[M]||(w[M]={});for(var P=x.y-_;P<=x.y+_;P++)P<0||P>=o||(F=n(1e3*s(P-b.y)),w[M][F]||(w[M][F]=f(r(i(M*p,2)+i(F*v,2))/1e3)),(T=w[M][F])>0&&(O+=T,I+=T*c[E=4*(P*e+S)],A+=T*c[E+1],D+=T*c[E+2],L+=T*c[E+3]))}d[E=4*(C*a+h)]=I/O,d[E+1]=A/O,d[E+2]=D/O,d[E+3]=L/O}return++h1&&F<-1||(_=2*F*F*F-3*F*F+1)>0&&(T+=_*f[3+(M=4*(L+O*e))],b+=_,f[M+3]<255&&(_=_*f[M+3]/250),x+=_*f[M],C+=_*f[M+1],S+=_*f[M+2],w+=_)}m[y]=x/w,m[y+1]=C/w,m[y+2]=S/w,m[y+3]=T/b}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,n=e.util.createClass;i.Contrast=n(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,n=i.length,r=Math.floor(255*this.contrast),s=259*(r+255)/(255*(259-r));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,n=e.util.createClass;i.Gamma=n(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,n=this.gamma,r=i.length,s=1/n[0],o=1/n[1],a=1/n[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,r=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=n)}return t},_renderTextLine:function(t,e,i,n,r,s){this._renderChars(t,e,i,n,r,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,n,r,s,o,a,h=t.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,m=this._textLines.length;g=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,n){var r=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,r,s.segmentsInfo);i.renderLeft=o.x-n.x,i.renderTop=o.y-n.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,n,r){var s,o=this.getCompleteStyleDeclaration(e,i),a=n?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,n,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&&!r){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),n=1,r=e.length;n0){var O=y+s+u;"rtl"===this.direction&&(O=this.width-O-d),l&&v&&(t.fillStyle=v,t.fillRect(O,c+x*n+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,v=p,n=r,o=a}else d+=f.kernedWidth;O=y+s+u,"rtl"===this.direction&&(O=this.width-O-d),t.fillStyle=p,g&&p&&t.fillRect(O,c+x*n+o,d-b,this.fontSize/15),_+=i}else _+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var n=t||this,r=this.fontFamily,s=e.Text.genericFonts.indexOf(r.toLowerCase())>-1,o=void 0===r||r.indexOf("'")>-1||r.indexOf(",")>-1||r.indexOf('"')>-1||s?n.fontFamily:'"'+n.fontFamily+'"';return[e.isLikelyNode?n.fontWeight:n.fontStyle,e.isLikelyNode?n.fontStyle:n.fontWeight,i?this.CACHE_FONT_SIZE+"px":n.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),n=new Array(i.length),r=["\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)}S.IText=S.util.createClass(S.Text,S.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(),n=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:n.left,topOffset:n.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,n,r,s=0,o=0,a=this.get2DCursorLocation(t);n=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(r.left*=-1),this.cursorOffsetCache=r,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),n=i.lineIndex,r=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(n,r,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(n,r,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(n)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(n,r,"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,n=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,r=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(n),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),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var y=t.left+f+m,_=p-m,w=g,b=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,b=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(y=this.width-y-_),e.fillRect(y,t.top+t.topOffset+b,_,w),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}}}),S.IText.fromObject=function(e,i){if(t(e),e.styles)for(var n in e.styles)for(var r in e.styles[n])t(e.styles[n][r]);S.Object._fromObject("IText",e,i,"text")}}(),C=S.util.object.clone,S.util.object.extend(S.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||[],S.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,n){var r;return r={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){r.isAborted||t[n]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return r.isAborted}}),r},_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&&nthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(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 n=i.slice(0,t),r=S.util.string.graphemeSplit(n).length;if(t===e)return{selectionStart:r,selectionEnd:r};var s=i.slice(t,e);return{selectionStart:r,selectionEnd:r+S.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var n=i.slice(0,t).join("").length;return t===e?{selectionStart:n,selectionEnd:n}:{selectionStart:n,selectionEnd:n+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),n=i.lineIndex,r=i.charIndex,s=this.getValueOfPropertyAt(n,r,"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,m=c.clientWidth/u,p=c.clientHeight/d;return h=S.util.transformPoint(h,a),(h=S.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,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,n,r=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),o=r.lineIndex,a=r.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(n[c-d]=n[u],delete n[u])}},shiftLineStyles:function(t,e){var i=C(this.styles);for(var n in this.styles){var r=parseInt(n,10);r>t&&(this.styles[r+e]=i[r],i[r-e]||delete this.styles[r])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,n){var r,s={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(r=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;)n&&n[i-1]?this.styles[t+i]={0:C(n[i-1])}:r?this.styles[t+i]={0:C(r)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,n){this.styles||(this.styles={});var r=this.styles[t],s=r?C(r):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(r[a+i]=s[a],s[a-i]||delete r[a])}if(this._forceClearCache=!0,n)for(;i--;)Object.keys(n[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=C(n[i]));else if(r)for(var h=r[e?e-1:1];h&&i--;)this.styles[t][e+i]=C(h)},insertNewStyleBlock:function(t,e,i){for(var n=this.get2DCursorLocation(e,!0),r=[0],s=0,o=0;o0&&(this.insertCharStyleObject(n.lineIndex,n.charIndex,r[0],i),i=i&&i.slice(r[0]+1)),s&&this.insertNewlineStyleObject(n.lineIndex,n.charIndex+r[0],s),o=1;o0?this.insertCharStyleObject(n.lineIndex+o,0,r[o],i):i&&this.styles[n.lineIndex+o]&&i[0]&&(this.styles[n.lineIndex+o][0]=i[0]),i=i&&i.slice(r[o]+1);r[o]>0&&this.insertCharStyleObject(n.lineIndex+o,0,r[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)}}),S.util.object.extend(S.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,n=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,n,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),n=0,r=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));r=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+r);for(var c=0,u=e.length;cs||o<0?0:1);return this.flipX&&(a=r-a),a>this._text.length&&(a=this._text.length),a}}),S.util.object.extend(S.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=S.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):S.document.body.appendChild(this.hiddenTextarea),S.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),S.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),S.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),S.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),S.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),S.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),S.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),S.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),S.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(S.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,n,r,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),m=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(n+=(i=this.__charBounds[t][e-1]).left+i.width),n},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(r===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=n.charIndex,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r+1,o);return this._textLines[r].slice(s).length+a+1+this.missingNewlineOffset(r)},_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),n=this.get2DCursorLocation(i),r=n.lineIndex;if(0===r||t.metaKey||33===t.keyCode)return-i;var s=n.charIndex,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r-1,o),h=this._textLines[r].slice(0,s),l=this.missingNewlineOffset(r-1);return-this._textLines[r-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,n,r=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=r.length;ae){n=!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 n;if(t.altKey)n=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;n=this["findLineBoundary"+i](this[e])}if(void 0!==typeof n&&this[e]!==n)return this[e]=n,!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,n){void 0===n&&(n=i),n>i&&this.removeStyleFromTo(i,n);var r=S.util.string.graphemeSplit(t);this.insertNewStyleBlock(r,i,e),this._text=[].concat(this._text.slice(0,i),r,this._text.slice(n)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=S.util.toFixed,e=/ +/g;S.util.object.extend(S.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,n=[],r=[],s=t;this._setSVGBg(r);for(var o=0,a=this._textLines.length;o",S.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,n){var r,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];n+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)h=g===m||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||(r=r||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(r,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,n)),u="",r=s,i+=d,d=0)},_pushTextBgRect:function(e,i,n,r,s,o){var a=S.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,n){for(var r,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,n=0,r={},s=0;s0?(i=0,n++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[n])&&s>0&&(i++,n++),r[s]={line:e,offset:i},n+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return r},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var n=this._styleMap[i];n&&(i=n.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,n=0,r=!1,s=this._styleMap[t],o=this._styleMap[t+1];for(var a in s&&(t=s.line,n=s.offset),o&&(r=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=n&&(!r||hn&&!p?(a.push(h),h=[],s=f,p=!0):s+=v,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return y&&a.push(h),m+r>this.dynamicMinWidth&&(this.dynamicMinWidth=m-v+r),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),n=this._wrapText(i.lines,this.width),r=new Array(n.length),s=0;s{},898:()=>{},245:()=>{}},v={};function y(t){var e=v[t];if(void 0!==e)return e.exports;var i=v[t]={exports:{}};return p[t](i,i.exports,y),i.exports}y.d=(t,e)=>{for(var i in e)y.o(e,i)&&!y.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},y.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var _={};(()=>{let t;y.d(_,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?y(653).fabric:{version:"5.2.1"}})();var w,b,x,C,S=_.R;t.EnumDrawingItemMediaType=void 0,(w=t.EnumDrawingItemMediaType||(t.EnumDrawingItemMediaType={}))[w.DIMT_RECTANGLE=1]="DIMT_RECTANGLE",w[w.DIMT_QUADRILATERAL=2]="DIMT_QUADRILATERAL",w[w.DIMT_TEXT=4]="DIMT_TEXT",w[w.DIMT_ARC=8]="DIMT_ARC",w[w.DIMT_IMAGE=16]="DIMT_IMAGE",w[w.DIMT_POLYGON=32]="DIMT_POLYGON",w[w.DIMT_LINE=64]="DIMT_LINE",w[w.DIMT_GROUP=128]="DIMT_GROUP",t.EnumDrawingItemState=void 0,(b=t.EnumDrawingItemState||(t.EnumDrawingItemState={}))[b.DIS_DEFAULT=1]="DIS_DEFAULT",b[b.DIS_SELECTED=2]="DIS_SELECTED",t.EnumEnhancedFeatures=void 0,(x=t.EnumEnhancedFeatures||(t.EnumEnhancedFeatures={}))[x.EF_ENHANCED_FOCUS=4]="EF_ENHANCED_FOCUS",x[x.EF_AUTO_ZOOM=16]="EF_AUTO_ZOOM",x[x.EF_TAP_TO_FOCUS=64]="EF_TAP_TO_FOCUS",function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(C||(C={}));const T=t=>"number"==typeof t&&!Number.isNaN(t),E=t=>"string"==typeof t;var O,I,A,D,L,M,F,P,k,R,B;!function(t){t[t.ARC=0]="ARC",t[t.IMAGE=1]="IMAGE",t[t.LINE=2]="LINE",t[t.POLYGON=3]="POLYGON",t[t.QUAD=4]="QUAD",t[t.RECT=5]="RECT",t[t.TEXT=6]="TEXT",t[t.GROUP=7]="GROUP"}(L||(L={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(M||(M={}));class j{get mediaType(){return new Map([["rect",t.EnumDrawingItemMediaType.DIMT_RECTANGLE],["quad",t.EnumDrawingItemMediaType.DIMT_QUADRILATERAL],["text",t.EnumDrawingItemMediaType.DIMT_TEXT],["arc",t.EnumDrawingItemMediaType.DIMT_ARC],["image",t.EnumDrawingItemMediaType.DIMT_IMAGE],["polygon",t.EnumDrawingItemMediaType.DIMT_POLYGON],["line",t.EnumDrawingItemMediaType.DIMT_LINE],["group",t.EnumDrawingItemMediaType.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(s(this,I,"f")){case t.EnumDrawingItemState.DIS_DEFAULT:return"default";case t.EnumDrawingItemState.DIS_SELECTED:return"selected"}}set drawingStyleId(t){this.styleId=t}get drawingStyleId(){return this.styleId}set coordinateBase(t){if(!["view","image"].includes(t))throw new Error("Invalid 'coordinateBase'.");this._drawingLayer&&("image"===s(this,A,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===s(this,A,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),o(this,A,t,"f")}get coordinateBase(){return s(this,A,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(e,i){if(O.add(this),I.set(this,void 0),A.set(this,"image"),this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapState_StyleId=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,null!=i&&!T(i))throw new TypeError("Invalid 'drawingStyleId'.");e&&this._setFabricObject(e),this.setState(t.EnumDrawingItemState.DIS_DEFAULT),this.styleId=i}_setFabricObject(e){this._fabricObject=e,this._fabricObject.on("selected",(()=>{this.setState(t.EnumDrawingItemState.DIS_SELECTED)})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(t.EnumDrawingItemState.DIS_SELECTED):this.setState(t.EnumDrawingItemState.DIS_DEFAULT),"textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),e.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}setState(t){o(this,I,t,"f")}getState(){return s(this,I,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),n=this.mapEvent_Callbacks.get(i);if(!n)throw new Error(`Event '${t}' does not exist.`);let r=n.get(e);r||(r=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const n={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,r,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,r=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,v,y=1;if("contain"===f)u0?i-1:r,U),actionName:"modifyPolygon",pointIndex:i}),t}),{}),o(this,P,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,n){return t["p"+n]=new S.Control({positionHandler:W,actionHandler:G(n>0?n-1:i,U),actionName:"modifyPolygon",pointIndex:n}),t}),{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let n=i.x-e.pathOffset.x,r=i.y-e.pathOffset.y;const s=S.util.transformPoint({x:n,y:r},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){s(this,P,"f")&&this.setPolygon(s(this,P,"f"))}setPolygon(t){if(!e.isPolygon(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else o(this,P,JSON.parse(JSON.stringify(t)),"f")}getPolygon(){if(this._drawingLayer){if("view"===this.coordinateBase){return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))}}if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return s(this,P,"f")?JSON.parse(JSON.stringify(s(this,P,"f"))):null}}P=new WeakMap;k=new WeakMap,R=new WeakMap;const H=t=>{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let n=0;ni&&(i=r.length))}if(-1===i)break;for(let n=0;n=t[n].length-1)continue;let r=" ".repeat(i+2-t[n][e].length);t[n][e]=t[n][e].concat(r)}}})(e),(t=>{let e="";for(let i=0;i({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else o(this,q,JSON.parse(JSON.stringify(t)),"f")}getQuad(){if(this._drawingLayer){if("view"===this.coordinateBase){return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))}}if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return s(this,q,"f")?JSON.parse(JSON.stringify(s(this,q,"f"))):null}}q=new WeakMap;class Z extends j{constructor(e){super(new S.Group(e.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.setState(t.EnumDrawingItemState.DIS_SELECTED);const e=this._fabricObject._objects;for(let t of e)setTimeout((()=>{t&&t.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.setState(t.EnumDrawingItemState.DIS_DEFAULT);const e=this._fabricObject._objects;for(let t of e)setTimeout((()=>{t&&t.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}setChildDrawingItems(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()))}}const J=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),Q=t=>!!E(t)&&""!==t,$=t=>!!J(t)&&(!("id"in t&&!T(t.id))&&(!("lineWidth"in t&&!T(t.lineWidth))&&(!("fillStyle"in t&&!Q(t.fillStyle))&&(!("strokeStyle"in t&&!Q(t.strokeStyle))&&(!("paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode))&&(!("fontFamily"in t&&!Q(t.fontFamily))&&!("fontSize"in t&&!T(t.fontSize))))))));class tt{static convert(t,i,n){const r={x:0,y:0,width:i,height:n};if(!t)return r;if(e.isRect(t))t.isMeasuredInPercentage?(r.x=t.x/100*i,r.y=t.y/100*n,r.width=t.width/100*i,r.height=t.height/100*n):(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height);else{if(!e.isDSRect(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?(r.x=t.left/100*i,r.y=t.top/100*n,r.width=(t.right-t.left)/100*i,r.height=(t.bottom-t.top)/100*n):(r.x=t.left,r.y=t.top,r.width=t.right-t.left,r.height=t.bottom-t.top)}return r.x=Math.round(r.x),r.y=Math.round(r.y),r.width=Math.round(r.width),r.height=Math.round(r.height),r}}var et,it;class nt{constructor(){et.set(this,new Map),it.set(this,!1)}get disposed(){return s(this,it,"f")}on(t,e){t=t.toLowerCase();const i=s(this,et,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else s(this,et,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=s(this,et,"f").get(t);if(!i)return;const n=i.indexOf(e);-1!==n&&i.splice(n,1)}offAll(t){t=t.toLowerCase();const e=s(this,et,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const n=s(this,et,"f").get(t);if(n&&n.length){i=Object.assign({async:!1,copy:!0},i);for(let t of n){if(!t)continue;let r=[];if(i.copy)for(let t of e){try{t=JSON.parse(JSON.stringify(t))}catch(t){}r.push(t)}else r=e;let s=!1;if(i.async)setTimeout((()=>{this.disposed||n.includes(t)&&t.apply(i.target,r)}),0);else try{s=t.apply(i.target,r)}catch(t){}if(!0===s)break}}}dispose(){o(this,it,!0,"f")}}function rt(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function st(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function ot(t,e,i,n){let r=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(n[1]-e[1])+e[0]*(t[1]-n[1])+n[0]*(e[1]-t[1]);return!((r^s)>=0&&0!==r&&0!==s)&&(r=i[0]*(t[1]-n[1])+n[0]*(i[1]-t[1])+t[0]*(n[1]-i[1]),s=i[0]*(e[1]-n[1])+n[0]*(i[1]-e[1])+e[0]*(n[1]-i[1]),!((r^s)>=0&&0!==r&&0!==s))}et=new WeakMap,it=new WeakMap;const at=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const n=document.createElement("div");if(n.insertAdjacentHTML("beforeend",i),1===n.childElementCount&&n.firstChild instanceof HTMLTemplateElement)return n.firstChild.content;const r=new DocumentFragment;for(let t of n.children)r.append(t);return r};var ht,lt,ct,ut,dt,ft,gt,mt,pt,vt,yt,_t,wt,bt,xt,Ct,St,Tt,Et,Ot,It,At,Dt,Lt,Mt,Ft,Pt,kt,Rt,Bt,jt,Vt,Wt,Nt;class Ut{static createDrawingStyle(t){if(!$(t))throw new Error("Invalid style definition.");let e,i=Ut.USER_START_STYLE_ID;for(;s(Ut,ht,"f",lt).has(i);)i++;e=i;const n=JSON.parse(JSON.stringify(t));n.id=e;for(let t in s(Ut,ht,"f",ct))n.hasOwnProperty(t)||(n[t]=s(Ut,ht,"f",ct)[t]);return s(Ut,ht,"f",lt).set(e,n),n.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=s(Ut,ht,"f",lt).get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}static getDrawingStyle(t){return this._getDrawingStyle(t,!0)}static getAllDrawingStyles(){return JSON.parse(JSON.stringify(Array.from(s(Ut,ht,"f",lt).values())))}static _updateDrawingStyle(t,e){if(!$(e))throw new Error("Invalid style definition.");const i=s(Ut,ht,"f",lt).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}ht=Ut,Ut.STYLE_BLUE_STROKE=1,Ut.STYLE_GREEN_STROKE=2,Ut.STYLE_ORANGE_STROKE=3,Ut.STYLE_YELLOW_STROKE=4,Ut.STYLE_BLUE_STROKE_FILL=5,Ut.STYLE_GREEN_STROKE_FILL=6,Ut.STYLE_ORANGE_STROKE_FILL=7,Ut.STYLE_YELLOW_STROKE_FILL=8,Ut.STYLE_BLUE_STROKE_TRANSPARENT=9,Ut.STYLE_GREEN_STROKE_TRANSPARENT=10,Ut.STYLE_ORANGE_STROKE_TRANSPARENT=11,Ut.USER_START_STYLE_ID=1024,lt={value:new Map([[Ut.STYLE_BLUE_STROKE,{id:Ut.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Ut.STYLE_GREEN_STROKE,{id:Ut.STYLE_GREEN_STROKE,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Ut.STYLE_ORANGE_STROKE,{id:Ut.STYLE_ORANGE_STROKE,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Ut.STYLE_YELLOW_STROKE,{id:Ut.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Ut.STYLE_BLUE_STROKE_FILL,{id:Ut.STYLE_BLUE_STROKE_FILL,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Ut.STYLE_GREEN_STROKE_FILL,{id:Ut.STYLE_GREEN_STROKE_FILL,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Ut.STYLE_ORANGE_STROKE_FILL,{id:Ut.STYLE_ORANGE_STROKE_FILL,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Ut.STYLE_YELLOW_STROKE_FILL,{id:Ut.STYLE_YELLOW_STROKE_FILL,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Ut.STYLE_BLUE_STROKE_TRANSPARENT,{id:Ut.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Ut.STYLE_GREEN_STROKE_TRANSPARENT,{id:Ut.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Ut.STYLE_ORANGE_STROKE_TRANSPARENT,{id:Ut.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},ct={value:{lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}},"undefined"!=typeof document&&"undefined"!=typeof window&&(S.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(S.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),S.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},S.Object.prototype.transparentCorners=!1,S.Object.prototype.cornerSize=20,S.Object.prototype.touchCornerSize=100,S.Object.prototype.cornerColor="rgb(254,142,20)",S.Object.prototype.cornerStyle="circle",S.Object.prototype.strokeUniform=!0,S.Object.prototype.hasBorders=!1,S.Canvas.prototype.containerClass="",S.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i,n=this.upperCanvasEl,r=S.util.getPointer(t,n),s=n.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(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,e||(r=this.restorePointerVpt(r));var h=this.getRetinaScaling();if(1!==h&&(r.x/=h,r.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(n).objectFit,c=n.width,u=n.height,d=o,f=a;i={width:c/d,height:u/f};var g,m,p=c/u,v=d/f;return"contain"===l?p>v?(g=d,m=d/p,{x:r.x*i.width,y:(r.y-(f-m)/2)*i.width}):(g=f*p,m=f,{x:(r.x-(d-g)/2)*i.height,y:r.y*i.height}):"cover"===l?p>v?{x:(c-i.height*d)/2+r.x*i.height,y:r.y*i.height}:{x:r.x*i.width,y:(u-i.width*f)/2+r.y*i.width}:{x:r.x*i.width,y:r.y*i.height}}return i={width:1,height:1},{x:r.x*i.width,y:r.y*i.height}},S.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,n=this._getEventPrefix();S.util.addListener(S.document,"touchend",this._onTouchEnd,{passive:!1}),S.util.addListener(S.document,"touchmove",this._onMouseMove,{passive:!1}),S.util.removeListener(i,n+"down",this._onMouseDown)},S.Textbox.prototype._wrapLine=function(t,e,i,n){const r=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!r||!r.length);var o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?S.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,m=0,p=0,v=!0,y=this._getWidthOfCharSpacing();n=n||0;0===c.length&&c.push([]),i-=n;for(var _=0;_i&&!v?(h.push(l),l=[],o=g,v=!0):o+=y,v||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,v=!1,g>p&&(p=g);return _&&h.push(l),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-y+n),h});class Gt{get width(){return this.fabricCanvas.width}get height(){return this.fabricCanvas.height}set _allowMultiSelect(t){this.fabricCanvas.selection=t,this.fabricCanvas.renderAll()}get _allowMultiSelect(){return this.fabricCanvas.selection}constructor(t,e,i){if(this.mapType_StateAndStyleId=new Map,this.mode="viewer",this.onSelectionChanged=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas"))this.fabricCanvas=t.getFabricCanvas();else{let e=this.fabricCanvas=new S.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.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 n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])}),0)}})),e.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 n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{const e=[];for(let n of i)t.hasDrawingItem(n)&&e.push(n);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)}),0)}})),e.on("selection:updated",(function(t){const e=t.selected,i=t.deselected,n=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of n){const n=[],r=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&n.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&r.push(i)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(n,r)}),0)}})),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let n,r;switch(this.id=e,e){case Gt.DDN_LAYER_ID:n=Ut.getDrawingStyle(Ut.STYLE_BLUE_STROKE),r=Ut.getDrawingStyle(Ut.STYLE_BLUE_STROKE_FILL);break;case Gt.DBR_LAYER_ID:n=Ut.getDrawingStyle(Ut.STYLE_ORANGE_STROKE),r=Ut.getDrawingStyle(Ut.STYLE_ORANGE_STROKE_FILL);break;case Gt.DLR_LAYER_ID:n=Ut.getDrawingStyle(Ut.STYLE_GREEN_STROKE),r=Ut.getDrawingStyle(Ut.STYLE_GREEN_STROKE_FILL);break;default:n=Ut.getDrawingStyle(Ut.STYLE_YELLOW_STROKE),r=Ut.getDrawingStyle(Ut.STYLE_YELLOW_STROKE_FILL)}for(let t of j.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:n.id,selected:r.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return Ut.getDrawingStyle(t.styleId);const e=Ut.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector));return e||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,n){const r=this.getDrawingItems((e=>e._mediaType===t));for(let t of r)t.styleSelector===e&&this._changeItemStyle(t,i,!0);n||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const n=t._getFabricObject();"number"==typeof t.styleId&&(e=Ut.getDrawingStyle(t.styleId)),n.strokeWidth=e.lineWidth,"fill"===e.paintMode?(n.fill=e.fillStyle,n.stroke=e.fillStyle):"stroke"===e.paintMode?(n.fill="transparent",n.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(n.fill=e.fillStyle,n.stroke=e.strokeStyle),n.fontFamily&&(n.fontFamily=e.fontFamily),n.fontSize&&(n.fontSize=e.fontSize),n.group||(n.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const n=t.getChildDrawingItems();if("add"===i){if(n.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=Ut.getDrawingStyle(e.styleId);else{const n=this.mapType_StateAndStyleId.get(e._mediaType);i=Ut.getDrawingStyle(n[t.styleSelector]);const r=()=>{this._changeItemStyle(e,Ut.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,Ut.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",r),e._on("deselected",s),e._funcChangeStyleToSelected=r,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!n.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof j))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const n=this.fabricCanvas.getObjects();let r,s;if(n.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){r=t.getChildDrawingItems();for(let t of r)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(r){for(let t of r){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of j.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Ut.getDrawingStyle(t.styleId);else{s=Ut.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Ut.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},n=()=>{this._changeItemStyle(t,Ut.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of j.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Ut.getDrawingStyle(t.styleId);else{s=Ut.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Ut.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},n=()=>{this._changeItemStyle(t,Ut.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=n.length;if(o)a=n.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;et.toLowerCase())):e=j.arrMediaTypes,i?i.forEach((t=>t.toLowerCase())):i=j.arrStyleSelectors;const n=Ut.getDrawingStyle(t);if(!n)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let r;for(let s of e)if(r=this.mapType_StateAndStyleId.get(s),r)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,n,!0),r[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(e,i,n){const r=[];n&t.EnumDrawingItemMediaType.DIMT_RECTANGLE&&r.push("rect"),n&t.EnumDrawingItemMediaType.DIMT_QUADRILATERAL&&r.push("quad"),n&t.EnumDrawingItemMediaType.DIMT_TEXT&&r.push("text"),n&t.EnumDrawingItemMediaType.DIMT_ARC&&r.push("arc"),n&t.EnumDrawingItemMediaType.DIMT_IMAGE&&r.push("image"),n&t.EnumDrawingItemMediaType.DIMT_POLYGON&&r.push("polygon"),n&t.EnumDrawingItemMediaType.DIMT_LINE&&r.push("line");const s=[];i&t.EnumDrawingItemState.DIS_DEFAULT&&s.push("default"),i&t.EnumDrawingItemState.DIS_SELECTED&&s.push("selected"),this._setDefaultStyle(e,r.length?r:null,s.length?s:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}Gt.DDN_LAYER_ID=1,Gt.DBR_LAYER_ID=2,Gt.DLR_LAYER_ID=3,Gt.USER_DEFINED_LAYER_BASE_ID=100,Gt.TIP_LAYER_ID=999;class Yt{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new Gt(t,e,{enableRetinaScaling:!1});return i._manager=this,this._arrDrawingLayer.push(i),this._switchPointerEvent(),i}deleteDrawingLayer(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}getAllDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._getFabricCanvas().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){if(!this._arrDrawingLayer.length)return;const e=this._getFabricCanvas();e.wrapperEl.style.display=t?"block":"none"}_getFabricCanvas(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0].fabricCanvas:null}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class Ht extends X{constructor(t,e,i,n,r){super(t,{x:e,y:i,width:n,height:0},r),ut.set(this,void 0),dt.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&o(this,dt,setTimeout((()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()}),s(this,ut,"f")),"f")}getDuration(){return s(this,ut,"f")}}ut=new WeakMap,dt=new WeakMap;class Xt{constructor(){ft.add(this),gt.set(this,void 0),mt.set(this,void 0),pt.set(this,void 0),vt.set(this,!0),this._drawingLayerManager=new Yt}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const n=document.createElement("canvas");return n.width==t&&n.height==e||(n.width=t,n.height=e),n.style.objectFit=i,n}_createDrawingLayer(t,e,i,n){if(!this._layerBaseCvs){let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==t?void 0:t.width)||1280),i||(i=(null==t?void 0:t.height)||720),n||(n=(null==t?void 0:t.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,n)}const r=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(r,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",r.parentElement),s}createDrawingLayer(){let t;for(let e=Gt.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==Gt.TIP_LAYER_ID){t=e;break}return this._createDrawingLayer(t)}deleteDrawingLayer(t){var e;this._drawingLayerManager.deleteDrawingLayer(t),this._drawingLayerManager.getAllDrawingLayers().length||(null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null)}deleteUserDefinedDrawingLayer(t){if("number"!=typeof t)throw new TypeError("Invalid id.");if(tt.getId()>=0&&t.getId()!==Gt.TIP_LAYER_ID))}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(J(i=t)&&e.isPoint(i.topLeftPoint)&&T(i.width))||i.width<=0||!T(i.duration)||"coordinateBase"in i&&!["view","image"].includes(i.coordinateBase))throw new Error("Invalid tip config.");var i;o(this,gt,JSON.parse(JSON.stringify(t)),"f"),s(this,gt,"f").coordinateBase||(s(this,gt,"f").coordinateBase="view"),o(this,pt,t.duration,"f"),s(this,ft,"m",bt).call(this)}getTipConfig(){return s(this,gt,"f")?s(this,gt,"f"):null}setTipVisible(t){if("boolean"!=typeof t)throw new TypeError("Invalid value.");this._tip&&(this._tip.set("visible",t),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll()),o(this,vt,t,"f")}isTipVisible(){return s(this,vt,"f")}updateTipMessage(t){if(!s(this,gt,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=Ut.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(Gt.TIP_LAYER_ID)||this._createDrawingLayer(Gt.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=s(this,ft,"m",yt).call(this,t,s(this,gt,"f").topLeftPoint.x,s(this,gt,"f").topLeftPoint.y,s(this,gt,"f").width,s(this,gt,"f").coordinateBase,this._tipStyleId),s(this,ft,"m",_t).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",s(this,vt,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),s(this,mt,"f")&&clearTimeout(s(this,mt,"f")),s(this,pt,"f")>=0&&o(this,mt,setTimeout((()=>{s(this,ft,"m",wt).call(this)}),s(this,pt,"f")),"f")}}gt=new WeakMap,mt=new WeakMap,pt=new WeakMap,vt=new WeakMap,ft=new WeakSet,yt=function(t,e,i,n,r,s){const o=new Ht(t,e,i,n,s);return o.coordinateBase=r,o},_t=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},wt=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},bt=function(){if(!this._tip)return;const t=s(this,gt,"f");this._tip.coordinateBase=t.coordinateBase,this._tip.setTextRect({x:t.topLeftPoint.x,y:t.topLeftPoint.y,width:t.width,height:0}),this._tip.set("width",this._tip.get("width")),this._tip._drawingLayer&&this._tip._drawingLayer.renderAll()};class zt extends HTMLElement{constructor(){super(),xt.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),o(this,xt,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const n=document.createElement("slot");n.setAttribute("name","content"),e.append(n);const r=document.createElement("slot");r.setAttribute("name","drawing-layer"),e.append(r);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return s(this,xt,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach((t=>t.remove()))}}xt=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",zt);class qt extends Xt{static get engineResourcePath(){return e.handleEngineResourcePaths(e.CoreModule.engineResourcePaths).dce}static set defaultUIElementURL(t){qt._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=qt._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",qt.engineResourcePath)}static async createInstance(t){const e=new qt;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",qt.engineResourcePath)),await e.setUIElement(t||qt.defaultUIElementURL),e}static _transformCoordinates(t,e,i,n,r,s,o){const a=s/n,h=o/r;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==s(this,Mt,"f")){if(o(this,Mt,t,"f"),s(this,Ct,"m",kt).call(this))o(this,Ot,null,"f"),this._videoContainer=null,this._innerComponent.removeElement("content"),this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block");else if(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none"),!s(this,Ot,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(u.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),o(this,Ot,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}s(this,Ct,"m",kt).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading())}}get _singleFrameMode(){return s(this,Mt,"f")}get disposed(){return s(this,Pt,"f")}constructor(){super(),Ct.add(this),St.set(this,void 0),Tt.set(this,void 0),Et.set(this,void 0),this.containerClassName="dce-video-container",Ot.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,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,It.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,At.set(this,!1),Dt.set(this,!1),Lt.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{s(this,Ct,"m",Wt).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout((()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&s(this,Ct,"m",Vt).call(this))}),this._updateLayersTimeout)},this._windowResizeListener=()=>{qt._onLog&&qt._onLog("window resize event triggered."),s(this,Lt,"f").width===document.documentElement.clientWidth&&s(this,Lt,"f").height===document.documentElement.clientHeight||(s(this,Lt,"f").width=document.documentElement.clientWidth,s(this,Lt,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},Mt.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!s(this,Ct,"m",kt).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise(((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i},i=(t,e,i,n)=>{t.width==i&&t.height==n||(t.width=i,t.height=n);const r=t.getContext("2d");r.clearRect(0,0,t.width,t.height),r.drawImage(e,0,0)},n=await t(e),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,n,r,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout((()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)}),0)})),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},Ft.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,i)=>{var n,r,o,a;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const h=t.originalImageTag;if(!h)return;const l=t.items;if(!(null==l?void 0:l.length))return;const c=(null===(n=h.cropRegion)||void 0===n?void 0:n.left)||0,u=(null===(r=h.cropRegion)||void 0===r?void 0:r.top)||0,d=(null===(o=h.cropRegion)||void 0===o?void 0:o.right)?h.cropRegion.right-c:h.originalWidth,f=(null===(a=h.cropRegion)||void 0===a?void 0:a.bottom)?h.cropRegion.bottom-u:h.originalHeight,g=h.currentWidth,m=h.currentHeight,p=(t,e,i,n,r,o,a,h,l=[],c)=>{e.forEach((t=>qt._transformCoordinates(t,i,n,r,o,a,h)));const u=new K({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},c);for(let t of l)u.addNote(t);t.addDrawingItems([u]),s(this,Ft,"f").push(u)};let v,y;for(let t of l)switch(t.type){case e.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE:break;case e.EnumCapturedResultItemType.CRIT_BARCODE:v=this.getDrawingLayer(Gt.DBR_LAYER_ID),y=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==i?void 0:i.isBarcodeVerifyOpen)?t.verified?p(v,t.location.points,c,u,d,f,g,m,y):p(v,t.location.points,c,u,d,f,g,m,y,Ut.STYLE_ORANGE_STROKE_TRANSPARENT):p(v,t.location.points,c,u,d,f,g,m,y);break;case e.EnumCapturedResultItemType.CRIT_TEXT_LINE:v=this.getDrawingLayer(Gt.DLR_LAYER_ID),y=[{name:"text",content:t.text}],i.isLabelVerifyOpen?t.verified?p(v,t.location.points,c,u,d,f,g,m,y):p(v,t.location.points,c,u,d,f,g,m,y,Ut.STYLE_GREEN_STROKE_TRANSPARENT):p(v,t.location.points,c,u,d,f,g,m,y);break;case e.EnumCapturedResultItemType.CRIT_DETECTED_QUAD:v=this.getDrawingLayer(Gt.DDN_LAYER_ID),(null==i?void 0:i.isDetectVerifyOpen)?t.crossVerificationStatus===e.EnumCrossVerificationStatus.CVS_PASSED?p(v,t.location.points,c,u,d,f,g,m,[]):p(v,t.location.points,c,u,d,f,g,m,[],Ut.STYLE_BLUE_STROKE_TRANSPARENT):p(v,t.location.points,c,u,d,f,g,m,[]);break;case e.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE:v=this.getDrawingLayer(Gt.DDN_LAYER_ID),(null==i?void 0:i.isNormalizeVerifyOpen)?t.crossVerificationStatus===e.EnumCrossVerificationStatus.CVS_PASSED?p(v,t.location.points,c,u,d,f,g,m,[]):p(v,t.location.points,c,u,d,f,g,m,[],Ut.STYLE_BLUE_STROKE_TRANSPARENT):p(v,t.location.points,c,u,d,f,g,m,[]);break;case e.EnumCapturedResultItemType.CRIT_PARSED_RESULT:break;default:throw new Error("Illegal item type.")}}},Pt.set(this,!1),this.eventHandler=new nt,this.eventHandler.on("content:updated",(()=>{s(this,St,"f")&&clearTimeout(s(this,St,"f")),o(this,St,setTimeout((()=>{if(this.disposed)return;let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(t),this.updateConvertedRegion(t)}),0),"f")})),this.eventHandler.on("videoEl:resized",(()=>{s(this,Tt,"f")&&clearTimeout(s(this,Tt,"f")),o(this,Tt,setTimeout((()=>{this.disposed||this._updateVideoContainer()}),0),"f")}))}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await at(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let n=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!n)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=document.createElement("dce-component"),n.appendChild(this._innerComponent),s(this,Ct,"m",kt).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(u.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),o(this,Ot,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._selRsl&&(this._hideDefaultSelection||s(this,Ct,"m",kt).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||s(this,Ct,"m",kt).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||s(this,Ct,"m",Wt).call(this),s(this,Ct,"m",kt).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),s(this,Ct,"m",kt).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading()),window.ResizeObserver){this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{var e;qt._onLog&&qt._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()})));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}s(this,Lt,"f").width=document.documentElement.clientWidth,s(this,Lt,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,n;s(this,Ct,"m",kt).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),s(this,Ct,"m",Wt).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,o(this,Ot,null,"f"),null===(n=this._videoContainer)||void 0===n||n.remove(),this._videoContainer=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._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let n of e){const e=document.createElement("option");e.value=n.deviceId,e.innerText=n.label,this._selCam.append(e),n.deviceId&&t&&t.deviceId==n.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),n=Math.min(t.width,t.height);e=n<=1080?n+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return s(this,Ot,"f")}isVideoLoaded(){return!(!s(this,Ot,"f")||!this.cameraEnhancer)&&this.cameraEnhancer.isOpen()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!s(this,Ot,"f"))return;if(s(this,Ot,"f").style.objectFit=t,s(this,Ct,"m",kt).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}s(this,Ct,"m",Nt).call(this,e,this.getConvertedRegion()),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,n;let r,o,a;if(s(this,Ct,"m",kt).call(this)?(r=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,o=null===(n=this._cvsSingleFrameMode)||void 0===n?void 0:n.height,a="contain"):(r=null===(t=s(this,Ot,"f"))||void 0===t?void 0:t.videoWidth,o=null===(e=s(this,Ot,"f"))||void 0===e?void 0:e.videoHeight,a=this.getVideoFit()),!r||!o)throw new Error("Invalid content dimensions.");return{width:r,height:o,objectFit:a}}updateConvertedRegion(t){const e=tt.convert(this.scanRegion,t.width,t.height);o(this,It,e,"f"),s(this,Et,"f")&&clearTimeout(s(this,Et,"f")),o(this,Et,setTimeout((()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}s(this,Ct,"m",Rt).call(this,t,e),s(this,Ct,"m",Nt).call(this,t,e)}),0),"f")}getConvertedRegion(){return s(this,It,"f")}setScanRegion(t){if(null!=t&&!e.isDSRect(t)&&!e.isRect(t))throw TypeError("Invalid 'region'.");let i;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{i=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(i)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=s(this,Ot,"f").videoWidth,i=s(this,Ot,"f").videoHeight,n=this.getVideoFit(),{width:r,height:o}=this._innerComponent.getBoundingClientRect();if(r<=0||o<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");let a;const h={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===n&&(r/o1){const t=s(this,Ot,"f").videoWidth,e=s(this,Ot,"f").videoHeight,{width:n,height:r}=this._innerComponent.getBoundingClientRect(),o=t/e;if(n/rt.remove())),s(this,Ft,"f").length=0}dispose(){this._unbindUI(),o(this,Pt,!0,"f")}}function Kt(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Zt(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}St=new WeakMap,Tt=new WeakMap,Et=new WeakMap,Ot=new WeakMap,It=new WeakMap,At=new WeakMap,Dt=new WeakMap,Lt=new WeakMap,Mt=new WeakMap,Ft=new WeakMap,Pt=new WeakMap,Ct=new WeakSet,kt=function(){return"disabled"!==this._singleFrameMode},Rt=function(t,e){e&&(0!==e.x||0!==e.y||e.width!==t.width||e.height!==t.height)?this.setScanRegionMask(e.x,e.y,e.width,e.height):this.clearScanRegionMask()},Bt=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},jt=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},Vt=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},Wt=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Nt=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:n,objectFit:r}=t;e||(e={x:0,y:0,width:i,height:n});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/n;let l,c,u,d,f=1;if("contain"===r)a66||"Safari"===ie.browser&&ie.version>13||"OPR"===ie.browser&&ie.version>43||"Edge"===ie.browser&&ie.version,"function"==typeof SuppressedError&&SuppressedError;class se{static multiply(t,e){const i=[];for(let n=0;n<3;n++){const r=e.slice(3*n,3*n+3);for(let e=0;e<3;e++){const n=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*r[i]),0);i.push(n)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return se.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),n=Math.sin(e);return se.multiply(t,[i,-n,0,n,i,0,0,0,1])}static scale(t,e,i){return se.multiply(t,[e,0,0,0,i,0,0,0,1])}}var oe,ae,he,le,ce,ue,de;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(oe||(oe={}));class fe{static get version(){return"1.1.3"}static get webGLSupported(){return void 0===fe._webGLSupported&&(fe._webGLSupported=!!document.createElement("canvas").getContext("webgl")),fe._webGLSupported}get disposed(){return ne(this,de,"f")}constructor(){ae.set(this,oe.RGBA),he.set(this,null),le.set(this,null),ce.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,ue.set(this,null),de.set(this,!1)}drawImage(t,e,i,n,r,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!n)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if((null==s?void 0:s.bUseWebGL)&&!fe.webGLSupported)throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;fe._onLog&&(o=Date.now(),fe._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=n,u=0,d=0,f=i,g=n;r&&(r.sx&&(a=Math.round(r.sx)),r.sy&&(h=Math.round(r.sy)),r.sWidth&&(l=Math.round(r.sWidth)),r.sHeight&&(c=Math.round(r.sHeight)),r.dx&&(u=Math.round(r.dx)),r.dy&&(d=Math.round(r.dy)),r.dWidth&&(f=Math.round(r.dWidth)),r.dHeight&&(g=Math.round(r.dHeight)));let m,p=oe.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const v=t;if(!fe.webGLSupported||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){fe._onLog&&fe._onLog("drawImage() in context2d."),v.ctx2d||(v.ctx2d=v.getContext("2d",{willReadFrequently:!0}));const t=v.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(v.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=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},n=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},r=(t,e,i)=>{const n=t.createShader(e);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(n)}.`);throw e.name="WebGLError",e}return n},s="\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\n\nuniform mat3 u_matrix;\nuniform mat3 u_textureMatrix;\n\nvarying vec2 v_texCoord;\nvoid main(void) {\ngl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\nv_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n}";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_image;\nuniform float uColorFactor;\n\nvoid main() {\nvec4 sample = texture2D(u_image, v_texCoord);\nfloat grey = 0.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\ngl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n}`,h=n(t,[r(t,t.VERTEX_SHADER,s),r(t,t.FRAGMENT_SHADER,a)]);re(this,le,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),re(this,ce,e(t),"f"),re(this,he,i(t),"f"),re(this,ae,p,"f")}const r=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const n=t.RGBA,r=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,n,r,s,i)},y=(t,e,s,o)=>{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),r(t,s.positions,e.attribLocations.vertexPosition),r(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[oe.GREY,oe.GREY32].includes(p)?1:0);let m,v,y=se.translate(se.identity(),-1,-1);y=se.scale(y,2,2),y=se.scale(y,1/t.canvas.width,1/t.canvas.height),m=se.translate(y,u,d),m=se.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),v=se.translate(se.identity(),a/i,h/n),v=se.scale(v,l/i,c/n),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,v),t.drawArrays(t.TRIANGLES,0,6)};s(t,ne(this,he,"f"),e),y(t,ne(this,le,"f"),ne(this,ce,"f"),ne(this,he,"f"));const _=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,_),255!==_[3]){fe._onLog&&fe._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return fe._onLog&&fe._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===oe.GREY?oe.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return fe._onLog&&fe._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,n,r,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let n,r=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(r=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),n=new Uint8Array(i.buffer,0,4*o*a)):(n=new Uint8Array(4*o*a),e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,n))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(r,s,o,a),n=new Uint8Array(e.data.buffer),null==i||i.set(n)}return n}transformPixelFormat(t,e,i,n){let r,s;if(fe._onLog&&(r=Date.now(),fe._onLog("transformPixelFormat(), START: "+r)),e===i)return fe._onLog&&fe._onLog("transformPixelFormat() end. Costs: "+(Date.now()-r)),n?new Uint8Array(t):t;const o=[oe.RGBA,oe.RBGA,oe.GRBA,oe.GBRA,oe.BRGA,oe.BGRA];if(o.includes(e))if(i===oe.GREY){s=new Uint8Array(t.length/4);for(let e=0;eh||e.sy+e.sHeight>l)throw new Error("Invalid position.");null===(n=fe._onLog)||void 0===n||n.call(fe,"getImageData(), START: "+(c=Date.now()));const d=Math.round(e.sx),f=Math.round(e.sy),g=Math.round(e.sWidth),m=Math.round(e.sHeight),p=Math.round(e.dWidth),v=Math.round(e.dHeight);let y,_=(null==i?void 0:i.pixelFormat)||oe.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(oe.GREY===_&&w.length{this.disposed||n.includes(t)&&t.apply(i.target,r)}),0);else try{s=t.apply(i.target,r)}catch(t){}if(!0===s)break}}}dispose(){Zt(this,me,!0,"f")}}ge=new WeakMap,me=new WeakMap;const ri=(t,e,i,n)=>{if(!i)return t;let r=e+Math.round((t-e)/i)*i;return n&&(r=Math.min(r,n)),r};class si{static get version(){return"2.0.18"}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 findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find((t=>e.includes(t.label.toLowerCase())));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],n=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],r=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!r.length)return null;const s=r.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const o=r.find((t=>{const e=t.label.toLowerCase();return n.some((t=>e.includes(t)))}));return o?o.deviceId:r[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(ie.OS))return si.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(ie.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise((async(n,r)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),n(t)},l=t=>{s&&clearTimeout(s),o(),r(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise((t=>{g=t})),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise((t=>{setTimeout(t,1e3)})),!a){i&&(s=setTimeout((()=>{o(),r(new Error("Failed to play video. Timeout."))}),i)),await m;try{await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a)try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}}))}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let n;try{n=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==n||n.getTracks().forEach((t=>{t.stop()}))}return{ok:!0}}get state(){if(!Kt(this,Ae,"f"))return"closed";if("pending"===Kt(this,Ae,"f"))return"opening";if("fulfilled"===Kt(this,Ae,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?si.isStorageAvailable("localStorage")?Zt(this,Te,!0,"f"):(Zt(this,Te,!1,"f"),console.warn("Local storage is unavailable")):Zt(this,Te,!1,"f")}get ifSaveLastUsedCamera(){return Kt(this,Te,"f")}get isVideoPlaying(){return!(!Kt(this,ye,"f")||Kt(this,ye,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,n;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=Kt(this,ke,"f"))||void 0===e||e.removeEventListener("click",Kt(this,Pe,"f")),null===(i=Kt(this,ke,"f"))||void 0===i||i.removeEventListener("touchend",Kt(this,Pe,"f")),null===(n=Kt(this,ke,"f"))||void 0===n||n.removeEventListener("touchmove",Kt(this,Fe,"f")),Zt(this,ke,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(ie.OS)?(t.addEventListener("touchend",Kt(this,Pe,"f")),t.addEventListener("touchmove",Kt(this,Fe,"f"))):t.addEventListener("click",Kt(this,Pe,"f")))}get tapFocusEventBoundEl(){return Kt(this,ke,"f")}get disposed(){return Kt(this,Ye,"f")}constructor(t){var e,i;ve.add(this),ye.set(this,null),_e.set(this,void 0),we.set(this,(()=>{"opened"===this.state&&Kt(this,Ve,"f").fire("resumed",null,{target:this,async:!1})})),be.set(this,(()=>{Kt(this,Ve,"f").fire("paused",null,{target:this,async:!1})})),xe.set(this,void 0),Ce.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],Se.set(this,void 0),Te.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,Ee.set(this,void 0),Oe.set(this,!0),Ie.set(this,void 0),Ae.set(this,void 0),De.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},Le.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,n;const r=window.getComputedStyle(Kt(this,ye,"f")).objectFit,s=this.getResolution(),o=Kt(this,ye,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=Kt(this,ye,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===r)d>u?(f=l/s.width,i=(t-a)/f,n=(e-h-(c-l/d)/2)/f):(f=c/s.height,n=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==r)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,n=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,n=(e-h+(l/d-c)/2)/f)}return{x:i,y:n}},Me.set(this,!1),Fe.set(this,(()=>{Zt(this,Me,!0,"f")})),Pe.set(this,(async t=>{var e;if(Kt(this,Me,"f"))return void Zt(this,Me,!1,"f");if(!Kt(this,Le,"f"))return;if(!this.isVideoPlaying)return;if(!Kt(this,_e,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,n=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,n=t.changedTouches[0].clientY}const r=this.getResolution(),s=2*Math.round(Math.min(r.width,r.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,n)}catch(t){}if(o.x<0||o.x>r.width||o.y<0||o.y>r.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;si._onLog&&(c=Date.now());try{await Kt(this,ve,"m",ti).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(si._onLog)throw si._onLog(t),t}si._onLog&&si._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout((()=>{var t;si._onLog&&si._onLog("Back to continuous focus."),null===(t=Kt(this,_e,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime),Kt(this,Ve,"f").fire("tapfocus",null,{target:this,async:!1})})),ke.set(this,null),Re.set(this,1),Be.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!Kt(this,ye,"f"))return;const t=Kt(this,Re,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)Kt(this,ye,"f").style.transform="";else{const e=window.getComputedStyle(Kt(this,ye,"f")).objectFit,i=Kt(this,ye,"f").videoWidth,n=Kt(this,ye,"f").videoHeight,{width:r,height:s}=Kt(this,ye,"f").getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=r/s,a=i/n;let h=1;"contain"===e?h=oo?s/(i/t):r/(n/t));const l=h*(1-1/t)*(i/2-Kt(this,Be,"f").x),c=h*(1-1/t)*(n/2-Kt(this,Be,"f").y);Kt(this,ye,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},je.set(this,(function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===oe.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(si._onLog&&si._onLog("document visible. video paused: "+(null===(t=Kt(this,ye,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let t=!1;if(!this.isVideoPlaying){si._onLog&&si._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),t=!0}catch(t){si._onLog&&si._onLog("document visible. 1st resume video failed, try open instead.")}t||await Kt(this,ve,"m",Ke).call(this)}if(await new Promise((t=>setTimeout(t,300))),!this.isVideoPlaying){si._onLog&&si._onLog("document visible. 1st open failed. 2rd resume start."),t=!1;try{await this.resume(),t=!0}catch(t){si._onLog&&si._onLog("document visible. 2rd resume video failed, try open instead.")}t||await Kt(this,ve,"m",Ke).call(this)}}}else"hidden"===document.visibilityState&&(si._onLog&&si._onLog("document hidden. video paused: "+(null===(e=Kt(this,ye,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())})),Ye.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout((()=>{si.onWarning&&si.onWarning("The browser is too old or the page is loaded from an insecure origin.")}),0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),Zt(this,Ve,new ni,"f"),this.imageDataGetter=new fe,document.addEventListener("visibilitychange",Kt(this,Ge,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",Kt(this,we,"f")),t.addEventListener("pause",Kt(this,be,"f")),Zt(this,ye,t,"f")}getVideoEl(){return Kt(this,ye,"f")}releaseVideoEl(){var t,e;null===(t=Kt(this,ye,"f"))||void 0===t||t.removeEventListener("play",Kt(this,we,"f")),null===(e=Kt(this,ye,"f"))||void 0===e||e.removeEventListener("pause",Kt(this,be,"f")),Zt(this,ye,null,"f")}isVideoLoaded(){return!!Kt(this,ye,"f")&&4==Kt(this,ye,"f").readyState}async open(){if(Kt(this,Ie,"f")&&!Kt(this,Oe,"f")){if("pending"===Kt(this,Ae,"f"))return Kt(this,Ie,"f");if("fulfilled"===Kt(this,Ae,"f"))return}Kt(this,Ve,"f").fire("before:open",null,{target:this}),await Kt(this,ve,"m",Ke).call(this),Kt(this,Ve,"f").fire("played",null,{target:this,async:!1}),Kt(this,Ve,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;Kt(this,Ve,"f").fire("before:close",null,{target:this});const t=Kt(this,Ie,"f");if(Kt(this,ve,"m",Je).call(this),t&&"pending"===Kt(this,Ae,"f")){try{await t}catch(t){}if(!1===Kt(this,Oe,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}Zt(this,Ie,null,"f"),Zt(this,Ae,null,"f"),Kt(this,Ve,"f").fire("closed",null,{target:this,async:!1})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");Kt(this,ye,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await Kt(this,ye,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof Kt(this,xe,"f").video&&(Kt(this,xe,"f").video={}),delete Kt(this,xe,"f").video.facingMode,Kt(this,xe,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&Kt(this,Oe,"f"))){Kt(this,Ve,"f").fire("before:camera:change",[],{target:this,async:!1}),await Kt(this,ve,"m",Ze).call(this);try{this.resetSoftwareScale()}catch(t){}return Kt(this,Ce,"f")}}async switchToFrontCamera(t){if("object"!=typeof Kt(this,xe,"f").video&&(Kt(this,xe,"f").video={}),(null==t?void 0:t.resolution)&&(Kt(this,xe,"f").video.width={ideal:t.resolution.width},Kt(this,xe,"f").video.height={ideal:t.resolution.height}),delete Kt(this,xe,"f").video.deviceId,Kt(this,xe,"f").video.facingMode={exact:"user"},Zt(this,Se,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&Kt(this,Oe,"f"))){Kt(this,Ve,"f").fire("before:camera:change",[],{target:this,async:!1}),Kt(this,ve,"m",Ze).call(this);try{this.resetSoftwareScale()}catch(t){}return Kt(this,Ce,"f")}}getCamera(){var t;if(Kt(this,Ce,"f"))return Kt(this,Ce,"f");{let e=(null===(t=Kt(this,xe,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});n=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}else n=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));const r=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind));return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof Kt(this,xe,"f").video&&(Kt(this,xe,"f").video={}),i?(Kt(this,xe,"f").video.width={exact:t},Kt(this,xe,"f").video.height={exact:e}):(Kt(this,xe,"f").video.width={ideal:t},Kt(this,xe,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&Kt(this,Oe,"f"))return null;Kt(this,Ve,"f").fire("before:resolution:change",[],{target:this,async:!1}),await Kt(this,ve,"m",Ze).call(this);try{this.resetSoftwareScale()}catch(t){}const n=this.getResolution();return{width:n.width,height:n.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&Kt(this,ye,"f"))return{width:Kt(this,ye,"f").videoWidth,height:Kt(this,ye,"f").videoHeight};if(Kt(this,_e,"f")){const t=Kt(this,_e,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:Kt(this,ye,"f").videoWidth,height:Kt(this,ye,"f").videoHeight};{const t={width:0,height:0};let e=Kt(this,xe,"f").video.width||0,i=Kt(this,xe,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,n,r,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=Kt(this,Ne,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){d=null===(u=Kt(this,Ce,"f"))||void 0===u?void 0:u.deviceId;let e=Kt(this,Ne,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],Kt(this,Ne,"f").set(d,e),Zt(this,De,!0,"f");try{for(let t of this.detectedResolutions){await Kt(this,_e,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),Kt(this,ve,"m",Xe).call(this);const i=Kt(this,_e,"f").getSettings(),n={width:i.width,height:i.height};f(d,n)||e.push({width:n.width,height:n.height})}}catch(t){throw Kt(this,ve,"m",Je).call(this),Zt(this,De,!1,"f"),t}try{await Kt(this,ve,"m",Ke).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{Zt(this,De,!1,"f")}return e}{const e=async(t,e,i)=>{const n={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let r=null;try{r=await navigator.mediaDevices.getUserMedia(n)}catch(t){return null}if(!r)return null;const s=r.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=r,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach((t=>{t.stop()})),o};let i=(null===(s=null===(r=null===(n=Kt(this,xe,"f"))||void 0===n?void 0:n.video)||void 0===r?void 0:r.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=Kt(this,xe,"f"))||void 0===o?void 0:o.video)||void 0===a?void 0:a.deviceId)||void 0===h?void 0:h.ideal)||(null===(c=null===(l=Kt(this,xe,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=Kt(this,Ne,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],Kt(this,Ne,"f").set(i,u);for(let t of this.detectedResolutions){const n=await e(i,t.width,t.height);n&&!f(i,n)&&u.push({width:n.width,height:n.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");Zt(this,xe,JSON.parse(JSON.stringify(t)),"f"),Zt(this,Se,null,"f"),e&&Kt(this,ve,"m",Ze).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(Kt(this,xe,"f")))}resetMediaStreamConstraints(){Zt(this,xe,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!Kt(this,_e,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Kt(this,_e,"f").getCapabilities?Kt(this,_e,"f").getCapabilities():{}}getCameraSettings(){if(!Kt(this,_e,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Kt(this,_e,"f").getSettings()}async turnOnTorch(){if(!Kt(this,_e,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Kt(this,_e,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!Kt(this,_e,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Kt(this,_e,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Kt(this,_e,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=ri(t,n.min,n.step,n.max)),await Kt(this,_e,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Kt(this,_e,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=ri(t,n.min,n.step,n.max)),await Kt(this,_e,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Kt(this,_e,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!n)throw Error("Not supported.");e&&(tn.max&&(t=n.max));const r=this.getResolution();return await Kt(this,_e,"f").applyConstraints({width:{ideal:Math.max(r.width,r.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!Kt(this,_e,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),n=null==i?void 0:i.focusMode,r=null==i?void 0:i.focusDistance;if(!n)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!n.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!r)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(ir.max&&(i=r.max),i=ri(i,r.min,r.step,r.max)),this._focusParameters.focusArea=null,await Kt(this,_e,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,n=t.area.height;if(!i||!n){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),n||(n=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:n},await Kt(this,ve,"m",ti).call(this,e,i,n)}}}else this._focusParameters.focusArea=null,await Kt(this,_e,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async enableTapToFocus(){Zt(this,Le,!0,"f")}disableTapToFocus(){Zt(this,Le,!1,"f")}isTapToFocusEnabled(){return Kt(this,Le,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"!==this.state)throw new Error("Video is not playing.");t.centerPoint?Kt(this,ve,"m",ei).call(this,t.centerPoint):this.resetScaleCenter();try{if(Kt(this,ve,"m",ii).call(this,Kt(this,Be,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*Kt(this,Re,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!Kt(this,_e,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=ri(t,n.min,n.step,n.max)),await Kt(this,_e,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&Kt(this,ve,"m",ei).call(this,e),Zt(this,Re,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return Kt(this,Re,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();Zt(this,Be,{x:t.width/2,y:t.height/2},"f")}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(Kt(this,De,"f"))return null;const e=Date.now();si._onLog&&si._onLog("getFrameData() START: "+e);const i=Kt(this,ye,"f").videoWidth,n=Kt(this,ye,"f").videoHeight;let r={sx:0,sy:0,sWidth:i,sHeight:n,dWidth:i,dHeight:n};(null==t?void 0:t.position)&&(r=JSON.parse(JSON.stringify(t.position)));let s=oe.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=Kt(this,Re,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=Kt(this,Be,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,r=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))r=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.scaleCenter.y)/100*n}if(isNaN(e)||isNaN(r))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(r)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==n)return null;1!==o&&(r.sWidth=Math.round(r.sWidth/o),r.sHeight=Math.round(r.sHeight/o),r.sx=Math.round((1-1/o)*a.x+r.sx/o),r.sy=Math.round((1-1/o)*a.y+r.sy/o));const l=this.imageDataGetter.getImageData(Kt(this,ye,"f"),r,{pixelFormat:s,bufferContainer:h});if(!l)return null;const c=Date.now();return si._onLog&&si._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:Kt(this,je,"f")}}on(t,e){if(!Kt(this,We,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);Kt(this,Ve,"f").on(t,e)}off(t,e){Kt(this,Ve,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),Kt(this,Ve,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",Kt(this,Ge,"f")),Zt(this,Ye,!0,"f")}}var oi,ai,hi,li,ci,ui,di,fi,gi,mi,pi,vi,yi,_i,wi,bi,xi,Ci,Si,Ti,Ei,Oi,Ii,Ai,Di,Li,Mi,Fi,Pi,ki,Ri,Bi,ji,Vi,Wi;ye=new WeakMap,_e=new WeakMap,we=new WeakMap,be=new WeakMap,xe=new WeakMap,Ce=new WeakMap,Se=new WeakMap,Te=new WeakMap,Ee=new WeakMap,Oe=new WeakMap,Ie=new WeakMap,Ae=new WeakMap,De=new WeakMap,Le=new WeakMap,Me=new WeakMap,Fe=new WeakMap,Pe=new WeakMap,ke=new WeakMap,Re=new WeakMap,Be=new WeakMap,je=new WeakMap,Ve=new WeakMap,We=new WeakMap,Ne=new WeakMap,Ue=new WeakMap,Ge=new WeakMap,Ye=new WeakMap,ve=new WeakSet,He=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(Kt(this,Se,"f"))delete t.video.facingMode,t.video.deviceId={exact:Kt(this,Se,"f")};else if(this.ifSaveLastUsedCamera&&si.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(ie.OS)?(await this._getCameras(!1),Kt(this,ve,"m",Xe).call(this),e=si.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(ie.OS)||(await this._getCameras(!1),Kt(this,ve,"m",Xe).call(this),e=si.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const n=await e(i);n&&(delete t.video.facingMode,t.video.deviceId={exact:n})}return t},Xe=function(){if(Kt(this,Oe,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},ze=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;try{si._onLog&&si._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const r=async t=>{for(let r of e){r&&(await new Promise((t=>setTimeout(t,r))),Kt(this,ve,"m",Xe).call(this));try{si._onLog&&si._onLog("ask "+JSON.stringify(t)),n=await navigator.mediaDevices.getUserMedia(t),Kt(this,ve,"m",Xe).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,si._onLog&&si._onLog(t.message||t)}}};if(await r(t),n||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await r(t)),!n&&t.video.facingMode&&(delete t.video.facingMode,await r(t)),n||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await r(t))),!n)throw i;return n}catch(t){throw null==n||n.getTracks().forEach((t=>{t.stop()})),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},qe=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach((t=>{t.stop()})),this._mediaStream=null),Zt(this,_e,null,"f")},Ke=async function(){Zt(this,Oe,!1,"f");const t=Zt(this,Ee,Symbol(),"f");if(Kt(this,Ie,"f")&&"pending"===Kt(this,Ae,"f")){try{await Kt(this,Ie,"f")}catch(t){}Kt(this,ve,"m",Xe).call(this)}if(t!==Kt(this,Ee,"f"))return;const e=Zt(this,Ie,(async()=>{Zt(this,Ae,"pending","f");try{if(this.videoSrc){if(!Kt(this,ye,"f"))throw new Error("'videoEl' should be set.");await si.playVideo(Kt(this,ye,"f"),this.videoSrc,this.cameraOpenTimeout),Kt(this,ve,"m",Xe).call(this)}else{let t=await Kt(this,ve,"m",He).call(this);Kt(this,ve,"m",qe).call(this);let e=await Kt(this,ve,"m",ze).call(this,t);await this._getCameras(!1),Kt(this,ve,"m",Xe).call(this);const i=()=>{const t=e.getVideoTracks();let i,n;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,n=e;break}}return n},n=Kt(this,xe,"f");if("object"==typeof n.video){let r=n.video.facingMode;if(r instanceof Array&&r.length&&(r=r[0]),"object"==typeof r&&(r=r.exact||r.ideal),!(Kt(this,Se,"f")||this.ifSaveLastUsedCamera&&si.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||n.video.deviceId)){const n=i(),s=si.findBestCamera(this._arrCameras,r,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==n?void 0:n.deviceId)&&(e.getTracks().forEach((t=>{t.stop()})),t.video.deviceId={exact:s},e=await Kt(this,ve,"m",ze).call(this,t),Kt(this,ve,"m",Xe).call(this))}}const r=i();(null==r?void 0:r.deviceId)&&(Zt(this,Se,r&&r.deviceId,"f"),this.ifSaveLastUsedCamera&&si.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",Kt(this,Se,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),Kt(this,ye,"f")&&(await si.playVideo(Kt(this,ye,"f"),e,this.cameraOpenTimeout),Kt(this,ve,"m",Xe).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&Zt(this,_e,s[0],"f"),Zt(this,Ce,r,"f")}}catch(t){throw Kt(this,ve,"m",Je).call(this),Zt(this,Ae,null,"f"),t}Zt(this,Ae,"fulfilled","f")})(),"f");return e},Ze=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=Kt(this,Ce,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await Kt(this,ve,"m",Ke).call(this);const n=this.getResolution();e&&e!==Kt(this,Ce,"f").deviceId&&Kt(this,Ve,"f").fire("camera:changed",[Kt(this,Ce,"f").deviceId,e],{target:this,async:!1}),i.width==n.width&&i.height==n.height||Kt(this,Ve,"f").fire("resolution:changed",[{width:n.width,height:n.height},{width:i.width,height:i.height}],{target:this,async:!1}),Kt(this,Ve,"f").fire("played",null,{target:this,async:!1})},Je=function(){Kt(this,ve,"m",qe).call(this),Zt(this,Ce,null,"f"),Kt(this,ye,"f")&&(Kt(this,ye,"f").srcObject=null,this.videoSrc&&(Kt(this,ye,"f").pause(),Kt(this,ye,"f").currentTime=0)),Zt(this,Oe,!0,"f");try{this.resetSoftwareScale()}catch(t){}},Qe=async function t(e,i){const n=t=>{if(!Kt(this,_e,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){Kt(this,_e,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;i=ri(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await Kt(this,_e,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),n(e),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise((t=>{setTimeout(t,r)})),n(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h),a>l.width&&(a=l.width),h>l.height&&(h=l.height),s<0?s=0:s+a>l.width&&(s=l.width-a),o<0?o=0:o+h>l.height&&(o=l.height-h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(Kt(this,ye,"f"),{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:oe.RGBA,bufferContainer:d}))return Kt(this,ve,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await Kt(this,ve,"m",t).call(this,e,o,a,r,s,c,u)}else{let h=await Kt(this,ve,"m",Qe).call(this,e,c);if(a>h)return await Kt(this,ve,"m",t).call(this,e,o,a,r,s,c,h);if(a==h)return await Kt(this,ve,"m",t).call(this,e,o,a,c,h);let u=await Kt(this,ve,"m",Qe).call(this,e,l);if(u>a&&ao.width||h<0||h>o.height)throw new Error("Invalid 'centerPoint'.");let l=0;if(e.endsWith("px"))l=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");l=parseFloat(e)/100*o.width}if(isNaN(l)||l<0)throw new Error("Invalid 'width'.");let c=0;if(i.endsWith("px"))c=parseFloat(i);else{if(!i.endsWith("%"))throw new Error("Invalid 'height'.");c=parseFloat(i)/100*o.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==Kt(this,Re,"f")){const t=Kt(this,Re,"f"),e=Kt(this,Be,"f");l/=t,c/=t,a=(1-1/t)*e.x+a/t,h=(1-1/t)*e.y+h/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const u={focusL:a,focusT:h,focusW:l,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let n=ri(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=ri(Math.sqrt((e||this._focusParameters.fds.step)*n),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=ri(Math.sqrt(n*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await Kt(this,ve,"m",Qe).call(this,t,s),a=await Kt(this,ve,"m",Qe).call(this,t,r),h=await Kt(this,ve,"m",Qe).call(this,t,n);if(a>h&&ho&&a>o){let e=await Kt(this,ve,"m",Qe).call(this,t,i);const r=await Kt(this,ve,"m",$e).call(this,t,n,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,r}if(a==h&&hh){const e=await Kt(this,ve,"m",$e).call(this,t,n,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,n,r)},ei=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,n=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))n=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(n))throw new Error("Invalid scale center.");Zt(this,Be,{x:i,y:n},"f")},ii=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},si.browserInfo=ie,si.onWarning=null===(pe=null===window||void 0===window?void 0:window.console)||void 0===pe?void 0:pe.warn;class Ni{constructor(t){oi.add(this),ai.set(this,void 0),hi.set(this,0),li.set(this,void 0),ci.set(this,0),ui.set(this,!1),o(this,ai,t,"f")}startCharging(){s(this,ui,"f")||(Ni._onLog&&Ni._onLog("start charging."),s(this,oi,"m",fi).call(this),o(this,ui,!0,"f"))}stopCharging(){s(this,li,"f")&&clearTimeout(s(this,li,"f")),s(this,ui,"f")&&(Ni._onLog&&Ni._onLog("stop charging."),o(this,hi,Date.now()-s(this,ci,"f"),"f"),o(this,ui,!1,"f"))}}ai=new WeakMap,hi=new WeakMap,li=new WeakMap,ci=new WeakMap,ui=new WeakMap,oi=new WeakSet,di=function(){e.CoreModule.cfd(1),Ni._onLog&&Ni._onLog("charge 1.")},fi=function t(){0==s(this,hi,"f")&&s(this,oi,"m",di).call(this),o(this,ci,Date.now(),"f"),s(this,li,"f")&&clearTimeout(s(this,li,"f")),o(this,li,setTimeout((()=>{o(this,hi,0,"f"),s(this,oi,"m",t).call(this)}),s(this,ai,"f")-s(this,hi,"f")),"f")};class Ui{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-s(this,gi,"f",vi)<100)){if(o(this,gi,e,"f",vi),s(this,gi,"f",mi).size&&(t=s(this,gi,"f",mi).values().next().value,this.beepSoundSource==t.src?(s(this,gi,"f",mi).delete(t),t.play()):t=null),!t)if(s(this,gi,"f",pi).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout((()=>{s(this,gi,"f",pi).delete(t)}),2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",(()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,s(this,gi,"f",pi).delete(t),s(this,gi,"f",mi).add(t)}))}else s(this,gi,"f",yi)||(o(this,gi,!0,"f",yi),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&s(this,gi,"f",pi).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(Ui.vibrateDuration)}}}gi=Ui,mi={value:new Set},pi={value:new Set},vi={value:0},yi={value:!1},Ui.allowBeep=!0,Ui.beepSoundSource="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",Ui.allowVibrate=!0,Ui.vibrateDuration=300;const Gi=new Map([[oe.GREY,e.EnumImagePixelFormat.IPF_GRAYSCALED],[oe.RGBA,e.EnumImagePixelFormat.IPF_ABGR_8888]]),Yi="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};class Hi extends e.ImageSourceAdapter{static set _onLog(t){o(Hi,wi,t,"f",bi),si._onLog=t,Ni._onLog=t}static get _onLog(){return s(Hi,wi,"f",bi)}static async detectEnvironment(){return await(async()=>({wasm:d,worker:f,getUserMedia:g,camera:await m(),browser:u.browser,version:u.version,OS:u.OS}))()}static async testCameraAccess(){const t=await si.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(t){var i,n;if(t&&!(t instanceof qt))throw new TypeError("Invalid view.");if(null===(i=e.mapPackageRegister.license)||void 0===i?void 0:i.LicenseManager){if(!(null===(n=e.mapPackageRegister.license)||void 0===n?void 0:n.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await e.CoreModule.loadWasm(["license"]),await e.mapPackageRegister.license.dynamsoft()}const r=new Hi(t);return Hi.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{Hi.onWarning&&Hi.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{Hi.onWarning&&Hi.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),r}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");o(this,Si,t,"f")}get singleFrameMode(){return s(this,Si,"f")}get _isFetchingStarted(){return s(this,Di,"f")}get disposed(){return s(this,ki,"f")}constructor(t){if(super(),_i.add(this),xi.set(this,"closed"),Ci.set(this,void 0),this.isTorchOn=void 0,Si.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},Ti.set(this,((t,i,n,r)=>{const o=Date.now(),a={sx:r.x,sy:r.y,sWidth:r.width,sHeight:r.height,dWidth:r.width,dHeight:r.height},h=Math.max(a.dWidth,a.dHeight);if(this.canvasSizeLimit&&h>this.canvasSizeLimit){const t=this.canvasSizeLimit/h;a.dWidth>a.dHeight?(a.dWidth=this.canvasSizeLimit,a.dHeight=Math.round(a.dHeight*t)):(a.dWidth=Math.round(a.dWidth*t),a.dHeight=this.canvasSizeLimit)}const l=this.cameraManager.imageDataGetter.getImageData(t,a,{pixelFormat:this.getPixelFormat()===e.EnumImagePixelFormat.IPF_GRAYSCALED?oe.GREY:oe.RGBA});let c=null;if(l){const t=Date.now();let h;if(l.pixelFormat===oe.GREY)h=l.width;else h=4*l.width;let u=!0;0===a.sx&&0===a.sy&&a.sWidth===i&&a.sHeight===n&&(u=!1),c={bytes:l.data,width:l.width,height:l.height,stride:h,format:Gi.get(l.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:e.EnumImageTagType.ITT_FILE_IMAGE,isCropped:u,cropRegion:{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height,isMeasuredInPercentage:!1},originalWidth:i,originalHeight:n,currentWidth:l.width,currentHeight:l.height,timeSpent:t-o,timeStamp:t},toCanvas:s(this,Ei,"f"),isDCEFrame:!0}}return c})),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():tt.convert(s(this,Ii,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height});const i=s(this,Ti,"f").call(this,t,t.width,t.height,e);s(this,Ci,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},Ei.set(this,(function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let i;t.width=this.width,t.height=this.height;if(this.format===e.EnumImagePixelFormat.IPF_GRAYSCALED){i=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(u.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",(()=>{s(this,Pi,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("camera:changed",(()=>{this.clearBuffer()})),this._on("before:resolution:change",(()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("resolution:changed",(()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})})),this._on("paused",(()=>{s(this,Pi,"f").stopCharging();const t=this.cameraView;t&&t.disposed})),this._on("resumed",(()=>{const t=this.cameraView;t&&t.disposed})),this._on("tapfocus",(()=>{s(this,Mi,"f").tapToFocus&&s(this,Pi,"f").startCharging()})),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,i)=>{var n,r,o,a;if(s(this,_i,"m",Ri).call(this)||!this.isOpen()||this.isPaused())return;const h=t.intermediateResultUnits;Hi._onLog&&(Hi._onLog("intermediateResultUnits:"),Hi._onLog(h));let l=!1,c=!1;for(let t of h){if(t.unitType===e.EnumIntermediateResultUnitType.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){l=!0;break}t.unitType===e.EnumIntermediateResultUnitType.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(c=!0)}if(Hi._onLog&&(Hi._onLog("hasLocalizedBarcodes:"),Hi._onLog(c)),s(this,Mi,"f").autoZoom||s(this,Mi,"f").enhancedFocus)if(l)s(this,Fi,"f").autoZoomInFrameArray.length=0,s(this,Fi,"f").autoZoomOutFrameCount=0,s(this,Fi,"f").frameArrayInIdealZoom.length=0,s(this,Fi,"f").autoFocusFrameArray.length=0;else{const t=async t=>{await this.setZoom(t),s(this,Mi,"f").autoZoom&&s(this,Pi,"f").startCharging()},i=async t=>{await this.setFocus(t),s(this,Mi,"f").enhancedFocus&&s(this,Pi,"f").startCharging()};if(c){const l=h[0].originalImageTag,c=(null===(n=l.cropRegion)||void 0===n?void 0:n.left)||0,u=(null===(r=l.cropRegion)||void 0===r?void 0:r.top)||0,d=(null===(o=l.cropRegion)||void 0===o?void 0:o.right)?l.cropRegion.right-c:l.originalWidth,f=(null===(a=l.cropRegion)||void 0===a?void 0:a.bottom)?l.cropRegion.bottom-u:l.originalHeight,g=l.currentWidth,m=l.currentHeight;let p;{let t,i,n,r,o;{const t=this.video.videoWidth*(1-s(this,Fi,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+s(this,Fi,"f").autoZoomDetectionArea)/2,i=e,n=t,r=this.video.videoHeight*(1-s(this,Fi,"f").autoZoomDetectionArea)/2,a=r,h=this.video.videoHeight*(1+s(this,Fi,"f").autoZoomDetectionArea)/2;o=[{x:t,y:r},{x:e,y:a},{x:i,y:h},{x:n,y:h}]}Hi._onLog&&(Hi._onLog("detectionArea:"),Hi._onLog(o));const a=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let n=!1;const r=t.length;if(r<=2)return!1;for(let s=0;s0!=st(a.y-i)>0&&st(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(n=!n)}return n}(e,t.x,t.y)},n=(t,e)=>!!(ot([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||ot([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||ot([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||ot([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||(!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(n([e[0].x,e[0].y,e[1].x,e[1].y],t)||n([e[1].x,e[1].y,e[2].x,e[2].y],t)||n([e[2].x,e[2].y,e[3].x,e[3].y],t)||n([e[3].x,e[3].y,e[0].x,e[0].y],t)))};for(let i of h)if(i.unitType===e.EnumIntermediateResultUnitType.IRUT_LOCALIZED_BARCODES)for(let e of i.localizedBarcodes){if(!e)continue;const i=e.location.points;i.forEach((t=>{qt._transformCoordinates(t,c,u,d,f,g,m)})),t(o,i)&&a.push(e)}if(Hi._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const i=this.__styleId2||(this.__styleId2=Ut.createDrawingStyle({strokeStyle:"red"}));for(let n of h)if(n.unitType===e.EnumIntermediateResultUnitType.IRUT_LOCALIZED_BARCODES)for(let e of n.localizedBarcodes){if(!e)continue;const n=e.location.points,r=new Y({points:n},i);t.addDrawingItems([r])}}}if(Hi._onLog&&(Hi._onLog("intersectedResults:"),Hi._onLog(a)),!a.length)return;let l;if(a.length){let t=a.filter((t=>t.possibleFormats==Yi.BF_QR_CODE||t.possibleFormats==Yi.BF_DATAMATRIX));if(t.length||(t=a.filter((t=>t.possibleFormats==Yi.BF_ONED)),t.length||(t=a)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,n=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-g/2)*(i-g/2)+(n-m/2)*(n-m/2)};l=t[0];let i=e(l);if(1!=t.length)for(let n=1;n1.1*l.confidence?(l=t[n],i=r):t[n].confidence>.9*l.confidence&&re&&o>e&&a>e&&h>e&&p.result.moduleSize{})),s(this,Fi,"f").autoZoomInFrameArray.filter((t=>!0===t)).length>=s(this,Fi,"f").autoZoomInFrameLimit[1]){s(this,Fi,"f").autoZoomInFrameArray.length=0;const e=[(.5-n)/(.5-r),(.5-n)/(.5-o),(.5-n)/(.5-a),(.5-n)/(.5-h)].filter((t=>t>0)),i=Math.min(...e,s(this,Fi,"f").autoZoomInIdealModuleSize/p.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*i,1/s(this,Fi,"f").autoZoomInMaxTimes),s(this,Fi,"f").autoZoomInMinStep);c=Math.min(c,i);let u=l*c;u=Math.max(s(this,Fi,"f").minValue,u),u=Math.min(s(this,Fi,"f").maxValue,u);try{await t({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(s(this,Fi,"f").autoZoomInFrameArray.length=0,s(this,Fi,"f").frameArrayInIdealZoom.push(!0),s(this,Fi,"f").frameArrayInIdealZoom.splice(0,s(this,Fi,"f").frameArrayInIdealZoom.length-s(this,Fi,"f").frameLimitInIdealZoom[0]),s(this,Fi,"f").frameArrayInIdealZoom.filter((t=>!0===t)).length>=s(this,Fi,"f").frameLimitInIdealZoom[1]&&(s(this,Fi,"f").frameArrayInIdealZoom.length=0,s(this,Mi,"f").enhancedFocus)){const t=p.points;try{await i({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}if(!s(this,Mi,"f").autoZoom&&s(this,Mi,"f").enhancedFocus&&(s(this,Fi,"f").autoFocusFrameArray.push(!0),s(this,Fi,"f").autoFocusFrameArray.splice(0,s(this,Fi,"f").autoFocusFrameArray.length-s(this,Fi,"f").autoFocusFrameLimit[0]),s(this,Fi,"f").autoFocusFrameArray.filter((t=>!0===t)).length>=s(this,Fi,"f").autoFocusFrameLimit[1])){s(this,Fi,"f").autoFocusFrameArray.length=0;try{const t=p.points;await i({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(s(this,Mi,"f").autoZoom){if(s(this,Fi,"f").autoZoomInFrameArray.push(!1),s(this,Fi,"f").autoZoomInFrameArray.splice(0,s(this,Fi,"f").autoZoomInFrameArray.length-s(this,Fi,"f").autoZoomInFrameLimit[0]),s(this,Fi,"f").autoZoomOutFrameCount++,s(this,Fi,"f").frameArrayInIdealZoom.push(!1),s(this,Fi,"f").frameArrayInIdealZoom.splice(0,s(this,Fi,"f").frameArrayInIdealZoom.length-s(this,Fi,"f").frameLimitInIdealZoom[0]),s(this,Fi,"f").autoZoomOutFrameCount>=s(this,Fi,"f").autoZoomOutFrameLimit){s(this,Fi,"f").autoZoomOutFrameCount=0;const e=this.getZoomSettings().factor;let i=e-Math.max((e-1)*s(this,Fi,"f").autoZoomOutStepRate,s(this,Fi,"f").autoZoomOutMinStep);i=Math.max(s(this,Fi,"f").minValue,i),i=Math.min(s(this,Fi,"f").maxValue,i);try{await t({factor:i})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}s(this,Mi,"f").enhancedFocus&&i({mode:"continuous"}).catch((()=>{}))}!s(this,Mi,"f").autoZoom&&s(this,Mi,"f").enhancedFocus&&(s(this,Fi,"f").autoFocusFrameArray.length=0,i({mode:"continuous"}).catch((()=>{})))}}},o(this,Pi,new Ni(1e4),"f")}setCameraView(t){if(!(t instanceof qt))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),s(this,_i,"m",Ri).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;s(this,_i,"m",Ri).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return s(this,_i,"m",Ri).call(this)?s(this,xi,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){const t=this.cameraView;if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");t&&(t._singleFrameMode=this.singleFrameMode,s(this,_i,"m",Ri).call(this)?t._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(t.getVideoElement()),t._startLoading()));let e={width:0,height:0,deviceId:""};if(s(this,_i,"m",Ri).call(this));else{try{await this.cameraManager.open()}catch(e){throw t&&t._stopLoading(),"NotFoundError"===e.name?new Error(`No camera devices were detected. Please ensure a camera is connected and recognized by your system. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):"NotAllowedError"===e.name?new Error(`Camera access is blocked. Please check your browser settings or grant permission to use the camera. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):e}let i,n=t.getUIElement();if(n=n.shadowRoot||n,i=n.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=n.elTorchAuto=n.querySelector(".dce-mn-torch-auto"),e=n.elTorchOn=n.querySelector(".dce-mn-torch-on"),r=n.elTorchOff=n.querySelector(".dce-mn-torch-off");t&&(e.style.display=null==this.isTorchOn?"":"none"),e&&(e.style.display=1==this.isTorchOn?"":"none"),r&&(r.style.display=0==this.isTorchOn?"":"none");let s=n.elBeepOn=n.querySelector(".dce-mn-beep-on"),o=n.elBeepOff=n.querySelector(".dce-mn-beep-off");s&&(s.style.display=Ui.allowBeep?"":"none"),o&&(o.style.display=Ui.allowBeep?"none":"");let a=n.elVibrateOn=n.querySelector(".dce-mn-vibrate-on"),h=n.elVibrateOff=n.querySelector(".dce-mn-vibrate-off");a&&(a.style.display=Ui.allowVibrate?"":"none"),h&&(h.style.display=Ui.allowVibrate?"none":""),n.elResolutionBox=n.querySelector(".dce-mn-resolution-box");let l,c=n.elZoom=n.querySelector(".dce-mn-zoom");c&&(c.style.display="none",l=n.elZoomSpan=c.querySelector("span"));let d=n.elToast=n.querySelector(".dce-mn-toast"),f=n.elCameraClose=n.querySelector(".dce-mn-camera-close"),g=n.elTakePhoto=n.querySelector(".dce-mn-take-photo"),m=n.elCameraSwitch=n.querySelector(".dce-mn-camera-switch"),p=n.elCameraAndResolutionSettings=n.querySelector(".dce-mn-camera-and-resolution-settings");p&&(p.style.display="none");const v=n.dceMnFs={},y=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",y);const _=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",_);const w=()=>{this.turnAutoTorch()};null==r||r.addEventListener("pointerdown",w);const b=()=>{Ui.allowBeep=!Ui.allowBeep,s&&(s.style.display=Ui.allowBeep?"":"none"),o&&(o.style.display=Ui.allowBeep?"none":"")};for(let t of[o,s])null==t||t.addEventListener("pointerdown",b);const x=()=>{Ui.allowVibrate=!Ui.allowVibrate,a&&(a.style.display=Ui.allowVibrate?"":"none"),h&&(h.style.display=Ui.allowVibrate?"none":"")};for(let t of[h,a])null==t||t.addEventListener("pointerdown",x);const C=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),n=parseInt(e.getAttribute("data-height")),r=await this.setResolution({width:i,height:n});{let e=Math.max(r.width,r.height),i=Math.min(r.width,r.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&E(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?p&&(p.style.display=p.style.display?"":"none"):p&&""===p.style.display&&(p.style.display="none"))};n.addEventListener("click",C);let S=null;v.funcInfoZoomChange=(t,e=3e3)=>{c&&l&&(l.textContent=t.toFixed(1),c.style.display="",null!=S&&(clearTimeout(S),S=null),S=setTimeout((()=>{c.style.display="none",S=null}),e))};let T=null,E=v.funcShowToast=(t,e=3e3)=>{d&&(d.textContent=t,d.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout((()=>{d.style.display="none",T=null}),e))};const O=()=>{this.close()};null==f||f.addEventListener("click",O);const I=()=>{};null==g||g.addEventListener("pointerdown",I);const A=()=>{var t,e;let i,n=this.getVideoSettings(),r=n.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),o=null==s?void 0:s.indexOf("front");-1===o&&(o=null==s?void 0:s.indexOf("前"));let a=null==s?void 0:s.indexOf("back");if(-1===a&&(a=null==s?void 0:s.indexOf("后")),"number"==typeof o&&-1!==o?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i){i="user"===((null==r?void 0:r.ideal)||(null==r?void 0:r.exact)||r)}n.video.facingMode={ideal:i?"environment":"user"},delete n.video.deviceId,this.updateVideoSettings(n)};null==m||m.addEventListener("pointerdown",A);let D=-1/0,L=1;const M=t=>{let e=Date.now();e-D>1e3&&(L=this.getZoomSettings().factor),L-=t.deltaY/200,L>20&&(L=20),L<1&&(L=1),this.setZoom({factor:L}),D=e};i.addEventListener("wheel",M);const F=new Map;let P=!1;const k=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],n=t.touches[1],r=F.get(i.identifier),s=F.get(n.identifier);if(!r||!s)break;let o=Math.pow(Math.pow(r.x-s.x,2)+Math.pow(r.y-s.y,2),.5),a=Math.pow(Math.pow(i.clientX-n.clientX,2)+Math.pow(i.clientY-n.clientY,2),.5),h=Date.now();if(P||h-D<100)return;h-D>1e3&&(L=this.getZoomSettings().factor),L*=a/o,L>20&&(L=20),L<1&&(L=1);let l=!1;"safari"==(null===(e=null==u?void 0:u.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/o>1&&L<2?(L=2,l=!0):a/o<1&&L<2&&(L=1,l=!0)),P=!0,l&&E("zooming..."),await this.setZoom({factor:L}),l&&(d.textContent=""),P=!1,D=Date.now();break}F.clear();for(let e of t.touches)F.set(e.identifier,{x:e.clientX,y:e.clientY})};n.addEventListener("touchstart",k),n.addEventListener("touchmove",k),n.addEventListener("touchend",k),n.addEventListener("touchcancel",k),v.unbind=()=>{null==t||t.removeEventListener("pointerdown",y),null==e||e.removeEventListener("pointerdown",_),null==r||r.removeEventListener("pointerdown",w);for(let t of[o,s])null==t||t.removeEventListener("pointerdown",b);for(let t of[h,a])null==t||t.removeEventListener("pointerdown",x);n.removeEventListener("click",C),null==f||f.removeEventListener("click",O),null==g||g.removeEventListener("pointerdown",I),null==m||m.removeEventListener("pointerdown",A),i.removeEventListener("wheel",M),n.removeEventListener("touchstart",k),n.removeEventListener("touchmove",k),n.removeEventListener("touchend",k),n.removeEventListener("touchcancel",k),delete n.dceMnFs,i.style.display="none"},i.style.display="",t&&null==this.isTorchOn&&setTimeout((()=>{this.turnAutoTorch(1e3)}),0)}this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const r=this.getResolution();e.width=r.width,e.height=r.height,e.deviceId=this.getSelectedCamera().deviceId}return o(this,xi,"open","f"),t&&(t._innerComponent.style.display="",s(this,_i,"m",Ri).call(this)||(t._stopLoading(),t._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),t._renderResolutionInfo({width:e.width,height:e.height}),t.eventHandler.fire("content:updated",null,{async:!1}),t.eventHandler.fire("videoEl:resized",null,{async:!1}))),s(this,Ci,"f").fire("opened",null,{target:this,async:!1}),e}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),s(this,_i,"m",Ri).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}o(this,xi,"closed","f"),s(this,Pi,"f").stopCharging(),e&&(e._innerComponent.style.display="none",s(this,_i,"m",Ri).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),s(this,Ci,"f").fire("closed",null,{target:this,async:!1})}pause(){if(s(this,_i,"m",Ri).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!s(this,_i,"m",Ri).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(s(this,_i,"m",Ri).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){if(!t)throw new Error("Invalid value.");let e;e="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(e),this.isTorchOn=!1;const i=this.getResolution(),n=this.cameraView;return n&&!n.disposed&&(n._stopLoading(),n._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),n._renderResolutionInfo({width:i.width,height:i.height})),{width:i.width,height:i.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?s(this,Ci,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?s(this,Ci,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._on(n,e)}off(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._off(n,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(s(this,_i,"m",Ri).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(s(this,_i,"m",Ri).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){if(null!=this._taskid4AutoTorch){if(!(t{var t,s,o;if(this.disposed||i||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++r>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let a;try{a=this.fetchImage()}catch(t){}if(!a||!a.width||!a.height)return;let h=0;if(e.EnumImagePixelFormat.IPF_GRAYSCALED===a.format){for(let t=0;t=this.maxDarkCount4AutoTroch){null===(t=Hi._onLog)||void 0===t||t.call(Hi,`darkCount ${n}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(s=null==t?void 0:t.dceMnFs)||void 0===s||s.funcShowToast("Torch Auto On")}catch(t){console.warn(t),i=!0;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,null===(o=null==e?void 0:e.dceMnFs)||void 0===o||o.funcShowToast("Torch Not Supported")}}}else n=0};this._taskid4AutoTorch=setInterval(s,t),this.isTorchOn=void 0,s();let o=this.cameraView.getUIElement();o=o.shadowRoot||o,o.elTorchAuto&&(o.elTorchAuto.style.display=""),o.elTorchOn&&(o.elTorchOn.style.display="none"),o.elTorchOff&&(o.elTorchOff.style.display="none")}async setColorTemperature(t){if(s(this,_i,"m",Ri).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(s(this,_i,"m",Ri).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,n;if(s(this,_i,"m",Ri).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(n=null==e?void 0:e.dceMnFs)||void 0===n||n.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(s(this,_i,"m",Ri).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(s(this,_i,"m",Ri).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(s(this,_i,"m",Ri).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){s(this,Fi,"f").minValue=t.min,s(this,Fi,"f").maxValue=t.max}getAutoZoomRange(){return{min:s(this,Fi,"f").minValue,max:s(this,Fi,"f").maxValue}}async enableEnhancedFeatures(i){var n,r;if(!(null===(r=null===(n=e.mapPackageRegister.license)||void 0===n?void 0:n.LicenseManager)||void 0===r?void 0:r.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==e.CoreModule.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");i&t.EnumEnhancedFeatures.EF_ENHANCED_FOCUS&&(s(this,Mi,"f").enhancedFocus=!0),i&t.EnumEnhancedFeatures.EF_AUTO_ZOOM&&(s(this,Mi,"f").autoZoom=!0),i&t.EnumEnhancedFeatures.EF_TAP_TO_FOCUS&&(s(this,Mi,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(e){e&t.EnumEnhancedFeatures.EF_ENHANCED_FOCUS&&(s(this,Mi,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch((()=>{}))),e&t.EnumEnhancedFeatures.EF_AUTO_ZOOM&&(s(this,Mi,"f").autoZoom=!1,this.resetZoom().catch((()=>{}))),e&t.EnumEnhancedFeatures.EF_TAP_TO_FOCUS&&(s(this,Mi,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),s(this,_i,"m",ji).call(this)&&s(this,_i,"m",Bi).call(this)||s(this,Pi,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!e.isDSRect(t)&&!e.isRect(t))throw TypeError("Invalid 'region'.");o(this,Ii,t?JSON.parse(JSON.stringify(t)):null,"f"),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(s(this,Ii,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");o(this,Oi,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||s(this,_i,"m",Ri).call(this))}startFetching(){if(s(this,_i,"m",Ri).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");s(this,Di,"f")||(o(this,Di,!0,"f"),s(this,_i,"m",Vi).call(this))}stopFetching(){s(this,Di,"f")&&(Hi._onLog&&Hi._onLog("DCE: stop fetching loop: "+Date.now()),s(this,Li,"f")&&clearTimeout(s(this,Li,"f")),o(this,Di,!1,"f"))}fetchImage(){if(s(this,_i,"m",Ri).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(4!==this.video.readyState)throw new Error("The video is not loaded.");const t=this.getResolution();if(!(null==t?void 0:t.width)||!(null==t?void 0:t.height))throw new Error("The video is not loaded.");let i;if(i=tt.convert(s(this,Ii,"f"),t.width,t.height),i||(i={x:0,y:0,width:t.width,height:t.height}),i.x>t.width||i.y>t.height)throw new Error("Invalid scan region.");i.x+i.width>t.width&&(i.width=t.width-i.x),i.y+i.height>t.height&&(i.height=t.height-i.y);const n={sx:i.x,sy:i.y,sWidth:i.width,sHeight:i.height,dWidth:i.width,dHeight:i.height},r=Math.max(n.dWidth,n.dHeight);if(this.canvasSizeLimit&&r>this.canvasSizeLimit){const t=this.canvasSizeLimit/r;n.dWidth>n.dHeight?(n.dWidth=this.canvasSizeLimit,n.dHeight=Math.round(n.dHeight*t)):(n.dWidth=Math.round(n.dWidth*t),n.dHeight=this.canvasSizeLimit)}const o=this.cameraManager.getFrameData({position:n,pixelFormat:this.getPixelFormat()===e.EnumImagePixelFormat.IPF_GRAYSCALED?oe.GREY:oe.RGBA});if(!o)return null;let a;if(o.pixelFormat===oe.GREY)a=o.width;else a=4*o.width;let h=!0;0===n.sx&&0===n.sy&&n.sWidth===t.width&&n.sHeight===t.height&&(h=!1);return{bytes:o.data,width:o.width,height:o.height,stride:a,format:Gi.get(o.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:e.EnumImageTagType.ITT_VIDEO_FRAME,isCropped:h,cropRegion:{left:i.x,top:i.y,right:i.x+i.width,bottom:i.y+i.height,isMeasuredInPercentage:!1},originalWidth:t.width,originalHeight:t.height,currentWidth:o.width,currentHeight:o.height,timeSpent:o.timeSpent,timeStamp:o.timeStamp},toCanvas:s(this,Ei,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,s(this,Di,"f")&&(s(this,Li,"f")&&clearTimeout(s(this,Li,"f")),o(this,Li,setTimeout((()=>{this.disposed||s(this,_i,"m",Vi).call(this)}),t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){o(this,Ai,t,"f")}getPixelFormat(){return s(this,Ai,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(s(this,_i,"m",Ri).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",(()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",(()=>{t&&this.open(),e.remove()}),{once:!0})})),e.addEventListener("change",(async()=>{const i=e.files[0],n=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise(((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(i),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,o=n instanceof HTMLImageElement?n.naturalHeight:n.height;let a=tt.convert(s(this,Ii,"f"),r,o);a||(a={x:0,y:0,width:r,height:o});const h=s(this,Ti,"f").call(this,n,r,o,a);t&&t(h)})),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=s(this,_i,"m",Wi).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=s(this,_i,"m",Wi).call(this,t);return{x:e.clientX,y:e.clientY}}convertToScanRegionCoordinates(t){if(!s(this,Ii,"f"))return JSON.parse(JSON.stringify(t));let e,i,n=s(this,Ii,"f").left||s(this,Ii,"f").x||0,r=s(this,Ii,"f").top||s(this,Ii,"f").y||0;if(!s(this,Ii,"f").isMeasuredInPercentage)return{x:t.x-n,y:t.y-r};if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!s(this,_i,"m",Ri).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(s(this,_i,"m",Ri).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(s(this,_i,"m",Ri).call(this)){const t=this.cameraView._innerComponent.getElement("content");e=t.width,i=t.height}else{const t=this.getVideoEl();e=t.videoWidth,i=t.videoHeight}return{x:t.x-Math.round(n*e/100),y:t.y-Math.round(r*i/100)}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),o(this,ki,!0,"f")}}var Xi,zi,qi,Ki,Zi,Ji,Qi,$i;wi=Hi,xi=new WeakMap,Ci=new WeakMap,Si=new WeakMap,Ti=new WeakMap,Ei=new WeakMap,Oi=new WeakMap,Ii=new WeakMap,Ai=new WeakMap,Di=new WeakMap,Li=new WeakMap,Mi=new WeakMap,Fi=new WeakMap,Pi=new WeakMap,ki=new WeakMap,_i=new WeakSet,Ri=function(){return"disabled"!==this.singleFrameMode},Bi=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},ji=function(){for(let t in s(this,Mi,"f"))if(1==s(this,Mi,"f")[t])return!0;return!1},Vi=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!s(this,Di,"f"))return s(this,Li,"f")&&clearTimeout(s(this,Li,"f")),void o(this,Li,setTimeout((()=>{this.disposed||s(this,_i,"m",t).call(this)}),this.fetchInterval),"f");const i=()=>{var t;let i;Hi._onLog&&Hi._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{i=this.fetchImage()}catch(i){const n=i.message||i;if("The video is not loaded."===n)return;if(null===(t=s(this,Oi,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout((()=>{var t;null===(t=s(this,Oi,"f"))||void 0===t||t.onErrorReceived(e.EnumErrorCode.EC_IMAGE_READ_FAILED,n)}),0);console.warn(i)}i?(this.addImageToBuffer(i),Hi._onLog&&Hi._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),s(this,Ci,"f").fire("frameAddedToBuffer",null,{async:!1})):Hi._onLog&&Hi._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case e.EnumBufferOverflowProtectionMode.BOPM_BLOCK:break;case e.EnumBufferOverflowProtectionMode.BOPM_UPDATE:i()}else i();s(this,Li,"f")&&clearTimeout(s(this,Li,"f")),o(this,Li,setTimeout((()=>{this.disposed||s(this,_i,"m",t).call(this)}),this.fetchInterval),"f")},Wi=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!s(this,_i,"m",Ri).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(s(this,_i,"m",Ri).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,n=e.top,r=i+window.scrollX,o=n+window.scrollY,{width:a,height:h}=this.cameraView._innerComponent.getBoundingClientRect();if(a<=0||h<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let l,c,u;if(s(this,_i,"m",Ri).call(this)){const t=this.cameraView._innerComponent.getElement("content");l=t.width,c=t.height,u="contain"}else{const t=this.getVideoEl();l=t.videoWidth,c=t.videoHeight,u=this.cameraView.getVideoFit()}const d=a/h,f=l/c;let g,m,p,v,y=1;if("contain"===u)d{var e;if(!this.isUseMagnifier)return;if(s(this,Ki,"f")||o(this,Ki,new tn,"f"),!s(this,Ki,"f").magnifierCanvas)return;document.body.contains(s(this,Ki,"f").magnifierCanvas)||(s(this,Ki,"f").magnifierCanvas.style.position="fixed",s(this,Ki,"f").magnifierCanvas.style.boxSizing="content-box",s(this,Ki,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(s(this,Ki,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void s(this,Ji,"f").call(this);const n=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!n)return;const r=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),a=1.5*r,h=[{image:i,width:i.width,height:i.height},{image:n,width:n.width,height:n.height}];s(this,Ki,"f").update(a,t.pointer,r,h);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*a&&i<1.5*a?(s(this,Ki,"f").magnifierCanvas.style.left="auto",s(this,Ki,"f").magnifierCanvas.style.top="0",s(this,Ki,"f").magnifierCanvas.style.right="0"):(s(this,Ki,"f").magnifierCanvas.style.left="0",s(this,Ki,"f").magnifierCanvas.style.top="0",s(this,Ki,"f").magnifierCanvas.style.right="auto")}s(this,Ki,"f").show()})),Ji.set(this,(()=>{s(this,Ki,"f")&&s(this,Ki,"f").hide()})),Qi.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await at(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=document.createElement("dce-component"),e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let n=this._innerComponent.getElement("content");n||(n=document.createElement("canvas"),n.style.objectFit="contain",this._innerComponent.setElement("content",n)),n.width===e&&n.height===i||(n.width=e,n.height=i);const r=n.getContext("2d");r.clearRect(0,0,n.width,n.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),r.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&r.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(e.isDSImageData(t)){o(this,qi,t,"f");const{width:i,height:n,bytes:r,format:s}=Object.assign({},t);let a;if(s===e.EnumImagePixelFormat.IPF_GRAYSCALED){a=new Uint8ClampedArray(i*n*4);for(let t=0;t({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const n=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new S.Control({positionHandler:W,actionHandler:G(i>0?i-1:n,U),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let n=t.x-i.pathOffset.x,r=t.y-i.pathOffset.y;const s=S.util.transformPoint({x:n,y:r},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){s(this,z,"f")&&this.setLine(s(this,z,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!e.isLineSegment(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else o(this,z,JSON.parse(JSON.stringify(t)),"f")}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return s(this,z,"f")?JSON.parse(JSON.stringify(s(this,z,"f"))):null}},t.QuadDrawingItem=K,t.RectDrawingItem=V,t.TextDrawingItem=X})); diff --git a/dist/dynamsoft-camera-enhancer@4.1.1/dist/dce.mobile-native.ui.html b/dist/dynamsoft-camera-enhancer@4.1.1/dist/dce.mobile-native.ui.html new file mode 100644 index 0000000..eda6104 --- /dev/null +++ b/dist/dynamsoft-camera-enhancer@4.1.1/dist/dce.mobile-native.ui.html @@ -0,0 +1,222 @@ +
+ + +
+
+ +
+ +
+ + \ No newline at end of file diff --git a/dist/dynamsoft-camera-enhancer@4.1.1/dist/dce.ui.html b/dist/dynamsoft-camera-enhancer@4.1.1/dist/dce.ui.html new file mode 100644 index 0000000..0960c88 --- /dev/null +++ b/dist/dynamsoft-camera-enhancer@4.1.1/dist/dce.ui.html @@ -0,0 +1,115 @@ + diff --git a/dist/dynamsoft-capture-vision-router@2.4.33/dist/cvr.d.ts b/dist/dynamsoft-capture-vision-router@2.4.33/dist/cvr.d.ts new file mode 100644 index 0000000..7c7632e --- /dev/null +++ b/dist/dynamsoft-capture-vision-router@2.4.33/dist/cvr.d.ts @@ -0,0 +1,663 @@ +import { ImageTag, CapturedResultItem, Quadrilateral, DSImageData, OriginalImageResultItem, ObservationParameters, IntermediateResult, IntermediateResultExtraInfo, PredetectedRegionsUnit, ColourImageUnit, ScaledDownColourImageUnit, GrayscaleImageUnit, TransformedGrayscaleImageUnit, EnhancedGrayscaleImageUnit, BinaryImageUnit, TextureDetectionResultUnit, TextureRemovedGrayscaleImageUnit, TextureRemovedBinaryImageUnit, ContoursUnit, LineSegmentsUnit, TextZonesUnit, TextRemovedBinaryImageUnit, ShortLinesUnit, EnumCapturedResultItemType, EnumGrayscaleTransformationMode, EnumGrayscaleEnhancementMode, ImageSourceAdapter } from 'dynamsoft-core'; + +declare const EnumBarcodeFormat: { + /**No barcode format in BarcodeFormat*/ + BF_NULL: bigint; + /**All supported formats in BarcodeFormat*/ + BF_ALL: bigint; + /**Use the default barcode format settings*/ + BF_DEFAULT: bigint; + /**Combined value of BF_CODABAR, BF_CODE_128, BF_CODE_39, BF_CODE_39_Extended, BF_CODE_93, BF_EAN_13, BF_EAN_8, INDUSTRIAL_25, BF_ITF, BF_UPC_A, BF_UPC_E, BF_MSI_CODE; */ + BF_ONED: bigint; + /**Combined value of BF_GS1_DATABAR_OMNIDIRECTIONAL, BF_GS1_DATABAR_TRUNCATED, BF_GS1_DATABAR_STACKED, BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL, BF_GS1_DATABAR_EXPANDED, BF_GS1_DATABAR_EXPANDED_STACKED, BF_GS1_DATABAR_LIMITED*/ + BF_GS1_DATABAR: bigint; + /**Code 39 */ + BF_CODE_39: bigint; + /**Code 128 */ + BF_CODE_128: bigint; + /**Code 93 */ + BF_CODE_93: bigint; + /**Codabar */ + BF_CODABAR: bigint; + /**Interleaved 2 of 5 */ + BF_ITF: bigint; + /**EAN-13 */ + BF_EAN_13: bigint; + /**EAN-8 */ + BF_EAN_8: bigint; + /**UPC-A */ + BF_UPC_A: bigint; + /**UPC-E */ + BF_UPC_E: bigint; + /**Industrial 2 of 5 */ + BF_INDUSTRIAL_25: bigint; + /**CODE39 Extended */ + BF_CODE_39_EXTENDED: bigint; + /**GS1 Databar Omnidirectional*/ + BF_GS1_DATABAR_OMNIDIRECTIONAL: bigint; + /**GS1 Databar Truncated*/ + BF_GS1_DATABAR_TRUNCATED: bigint; + /**GS1 Databar Stacked*/ + BF_GS1_DATABAR_STACKED: bigint; + /**GS1 Databar Stacked Omnidirectional*/ + BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL: bigint; + /**GS1 Databar Expanded*/ + BF_GS1_DATABAR_EXPANDED: bigint; + /**GS1 Databar Expaned Stacked*/ + BF_GS1_DATABAR_EXPANDED_STACKED: bigint; + /**GS1 Databar Limited*/ + BF_GS1_DATABAR_LIMITED: bigint; + /**Patch code. */ + BF_PATCHCODE: bigint; + /**PDF417 */ + BF_CODE_32: bigint; + /**PDF417 */ + BF_PDF417: bigint; + /**QRCode */ + BF_QR_CODE: bigint; + /**DataMatrix */ + BF_DATAMATRIX: bigint; + /**AZTEC */ + BF_AZTEC: bigint; + /**MAXICODE */ + BF_MAXICODE: bigint; + /**Micro QR Code*/ + BF_MICRO_QR: bigint; + /**Micro PDF417*/ + BF_MICRO_PDF417: bigint; + /**GS1 Composite Code*/ + BF_GS1_COMPOSITE: bigint; + /**MSI Code*/ + BF_MSI_CODE: bigint; + BF_CODE_11: bigint; + BF_TWO_DIGIT_ADD_ON: bigint; + BF_FIVE_DIGIT_ADD_ON: bigint; + BF_MATRIX_25: bigint; + /**Combined value of BF2_USPSINTELLIGENTMAIL, BF2_POSTNET, BF2_PLANET, BF2_AUSTRALIANPOST, BF2_RM4SCC.*/ + BF_POSTALCODE: bigint; + /**Nonstandard barcode */ + BF_NONSTANDARD_BARCODE: bigint; + /**USPS Intelligent Mail.*/ + BF_USPSINTELLIGENTMAIL: bigint; + /**Postnet.*/ + BF_POSTNET: bigint; + /**Planet.*/ + BF_PLANET: bigint; + /**Australian Post.*/ + BF_AUSTRALIANPOST: bigint; + /**Royal Mail 4-State Customer Barcode.*/ + BF_RM4SCC: bigint; + /**KIX.*/ + BF_KIX: bigint; + /**DotCode.*/ + BF_DOTCODE: bigint; + /**_PHARMACODE_ONE_TRACK.*/ + BF_PHARMACODE_ONE_TRACK: bigint; + /**PHARMACODE_TWO_TRACK.*/ + BF_PHARMACODE_TWO_TRACK: bigint; + /**PHARMACODE.*/ + BF_PHARMACODE: bigint; +}; +type EnumBarcodeFormat = bigint; +interface BarcodeDetails { +} +interface BarcodeResultItem extends CapturedResultItem { + format: EnumBarcodeFormat; + formatString: string; + text: string; + bytes: Uint8Array; + location: Quadrilateral; + confidence: number; + angle: number; + moduleSize: number; + details: BarcodeDetails; + isMirrored: boolean; + isDPM: boolean; +} +interface CharacterResult { + characterH: string; + characterM: string; + characterL: string; + characterHConfidence: number; + characterMConfidence: number; + characterLConfidence: number; + location: Quadrilateral; +} +interface TextLineResultItem extends CapturedResultItem { + text: string; + location: Quadrilateral; + confidence: number; + /** The following are new as of 2023/09/13 */ + characterResults: Array; +} +interface DetectedQuadResultItem extends CapturedResultItem { + location: Quadrilateral; + confidenceAsDocumentBoundary: number; +} +interface NormalizedImageResultItem extends CapturedResultItem { + imageData: DSImageData; + location: Quadrilateral; + toCanvas: () => HTMLCanvasElement; + toImage: (MIMEType: "image/png" | "image/jpeg") => HTMLImageElement; + toBlob: (MIMEType: "image/png" | "image/jpeg") => Promise; + saveToFile: (name: string, download?: boolean) => Promise; +} +declare enum EnumMappingStatus { + MS_NONE = 0, + MS_SUCCEEDED = 1, + MS_FAILED = 2 +} +declare enum EnumValidationStatus { + VS_NONE = 0, + VS_SUCCEEDED = 1, + VS_FAILED = 2 +} +interface ParsedResultItem extends CapturedResultItem { + codeType: string; + jsonString: string; + parsedFields: Array<{ + FieldName: string; + Value: string; + }>; + getFieldValue(fieldName: string): string; + getFieldMappingStatus: (fieldName: string) => EnumMappingStatus; + getFieldValidationStatus: (fieldName: string) => EnumValidationStatus; +} +interface CapturedResult { + readonly errorCode: number; + readonly errorString: string; + readonly originalImageHashId: string; + readonly originalImageTag: ImageTag; + readonly items: Array; + readonly barcodeResultItems?: Array; + readonly textLineResultItems?: Array; + readonly detectedQuadResultItems?: Array; + readonly normalizedImageResultItems?: Array; + readonly parsedResultItems?: Array; +} + +declare class CapturedResultReceiver { + /** + * Event triggered when a generic captured result is available, occurring each time an image finishes its processing. + * This event can be used for any result that does not fit into the specific categories of the other callback events. + * @param result The captured result, an instance of `CapturedResult`. + */ + onCapturedResultReceived?: (result: CapturedResult) => void; + /** + * Event triggered when the original image result is available. + * This event is used to handle the original image captured by an image source such as Dynamsoft Camera Enhancer. + * @param result The original image result, an instance of `OriginalImageResultItem`. + */ + onOriginalImageResultReceived?: (result: OriginalImageResultItem) => void; + [key: string]: any; +} + +interface BufferedCharacterItem { + character: string; + image: DSImageData; + features: Map; +} +interface BufferedCharacterItemSet { + items: Array; + characterClusters: Array; +} +interface CharacterCluster { + character: string; + mean: BufferedCharacterItem; +} +declare class BufferedItemsManager { + private _cvr; + constructor(cvr: any); + /** + * Gets the maximum number of buffered items. + * @returns Returns the maximum number of buffered items. + */ + getMaxBufferedItems(): Promise; + /** + * Sets the maximum number of buffered items. + * @param count the maximum number of buffered items + */ + setMaxBufferedItems(count: number): Promise; + /** + * Gets the buffered character items. + * @return the buffered character items + */ + getBufferedCharacterItemSet(): Promise>; +} + +declare class IntermediateResultReceiver { + private _observedResultUnitTypes; + private _observedTaskMap; + private _parameters; + /** + * Gets the observed parameters of the intermediate result receiver. Allowing for configuration of intermediate result observation. + * @return The observed parameters, of type ObservationParameters. The default parameters are to observe all intermediate result unit types and all tasks. + */ + getObservationParameters(): ObservationParameters; + onTaskResultsReceived?: (result: IntermediateResult, info: IntermediateResultExtraInfo) => void; + onPredetectedRegionsReceived?: (result: PredetectedRegionsUnit, info: IntermediateResultExtraInfo) => void; + onColourImageUnitReceived?: (result: ColourImageUnit, info: IntermediateResultExtraInfo) => void; + onScaledDownColourImageUnitReceived?: (result: ScaledDownColourImageUnit, info: IntermediateResultExtraInfo) => void; + onGrayscaleImageUnitReceived?: (result: GrayscaleImageUnit, info: IntermediateResultExtraInfo) => void; + onTransformedGrayscaleImageUnitReceived?: (result: TransformedGrayscaleImageUnit, info: IntermediateResultExtraInfo) => void; + onEnhancedGrayscaleImageUnitReceived?: (result: EnhancedGrayscaleImageUnit, info: IntermediateResultExtraInfo) => void; + onBinaryImageUnitReceived?: (result: BinaryImageUnit, info: IntermediateResultExtraInfo) => void; + onTextureDetectionResultUnitReceived?: (result: TextureDetectionResultUnit, info: IntermediateResultExtraInfo) => void; + onTextureRemovedGrayscaleImageUnitReceived?: (result: TextureRemovedGrayscaleImageUnit, info: IntermediateResultExtraInfo) => void; + onTextureRemovedBinaryImageUnitReceived?: (result: TextureRemovedBinaryImageUnit, info: IntermediateResultExtraInfo) => void; + onContoursUnitReceived?: (result: ContoursUnit, info: IntermediateResultExtraInfo) => void; + onLineSegmentsUnitReceived?: (result: LineSegmentsUnit, info: IntermediateResultExtraInfo) => void; + onTextZonesUnitReceived?: (result: TextZonesUnit, info: IntermediateResultExtraInfo) => void; + onTextRemovedBinaryImageUnitReceived?: (result: TextRemovedBinaryImageUnit, info: IntermediateResultExtraInfo) => void; + onShortLinesUnitReceived?: (result: ShortLinesUnit, info: IntermediateResultExtraInfo) => void; +} + +declare class IntermediateResultManager { + private _cvr; + private _irrRegistryState; + _intermediateResultReceiverSet: Set; + constructor(cvr: any); + /** + * Adds a `IntermediateResultReceiver` object as the receiver of intermediate results. + * @param receiver The receiver object, of type `IntermediateResultReceiver`. + */ + addResultReceiver(receiver: IntermediateResultReceiver): Promise; + /** + * Removes the specified `IntermediateResultReceiver` object. + * @param receiver The receiver object, of type `IntermediateResultReceiver`. + */ + removeResultReceiver(receiver: IntermediateResultReceiver): Promise; + /** + * Retrieves the original image data. + * + * @returns A promise that resolves when the operation has successfully completed. It provides the original image upon resolution. + */ + getOriginalImage(): DSImageData; +} + +declare enum EnumImageSourceState { + ISS_BUFFER_EMPTY = 0, + ISS_EXHAUSTED = 1 +} + +interface ImageSourceStateListener { + onImageSourceStateReceived?: (status: EnumImageSourceState) => void; +} + +interface SimplifiedBarcodeReaderSettings { + barcodeFormatIds: bigint; + expectedBarcodesCount: number; + grayscaleTransformationModes: Array; + grayscaleEnhancementModes: Array; + localizationModes: Array; + deblurModes: Array; + minResultConfidence: number; + minBarcodeTextLength: number; + barcodeTextRegExPattern: string; +} +interface SimplifiedLabelRecognizerSettings { + characterModelName: string; + lineStringRegExPattern: string; + grayscaleTransformationModes: Array; + grayscaleEnhancementModes: Array; +} +declare enum EnumImageColourMode { + /** Output image in color mode. */ + ICM_COLOUR = 0, + /** Output image in grayscale mode. */ + ICM_GRAYSCALE = 1, + /** Output image in binary mode. */ + ICM_BINARY = 2 +} +/** + * The `SimplifiedDocumentNormalizerSettings` interface defines simplified settings for document detection and normalization. + */ +interface SimplifiedDocumentNormalizerSettings { + /** Grayscale enhancement modes to apply for improving detection in challenging conditions. */ + grayscaleEnhancementModes: Array; + /** Grayscale transformation modes to apply, enhancing detection capability. */ + grayscaleTransformationModes: Array; + /** Color mode of the anticipated normalized page */ + colourMode: EnumImageColourMode; + /** Width and height of the anticipated normalized page. */ + pageSize: [number, number]; + /** Anticipated brightness level of the normalized image. */ + brightness: number; + /** Anticipated contrast level of the normalized image. */ + contrast: number; + /** + * Threshold for reducing the size of large images to speed up processing. + * If the size of the image's shorter edge exceeds this threshold, the image may be downscaled to decrease processing time. The standard setting is 2300. + */ + scaleDownThreshold: number; + /** The minimum ratio between the target document area and the total image area. Only those exceedingthis value will be output (measured in percentages).*/ + minQuadrilateralAreaRatio: number; + /** The number of documents expected to be detected.*/ + expectedDocumentsCount: number; +} +interface SimplifiedCaptureVisionSettings { + capturedResultItemTypes: EnumCapturedResultItemType; + roi: Quadrilateral; + roiMeasuredInPercentage: boolean; + timeout: number; + /** + * @brief Minimum time interval (in milliseconds) allowed between consecutive image captures. + * + * This property represents the minimum time interval (in milliseconds) that must + * elapse before the next image capture operation can be initiated. + * Setting a larger value for this property will introduce a delay between image + * captures, while setting a smaller value allows for more frequent captures. It + * can be used to reduce the computational frequency, which can effectively lower + * energy consumption. + * + * @note The actual time interval between captures may be longer than the specified + * minimum interval due to various factors, such as image processing time and + * hardware limitations. + * + */ + minImageCaptureInterval: number; + /** + * Specifies the basic settings for the barcode reader module. It is of type `SimplifiedBarcodeReaderSettings`. + */ + barcodeSettings: SimplifiedBarcodeReaderSettings; + /** + * Specifies the basic settings for the document normalizer module. It is of type `SimplifiedDocumentNormalizerSettings`. + */ + documentSettings: SimplifiedDocumentNormalizerSettings; + /** + * Specifies the basic settings for the label recognizer module. It is of type `SimplifiedLabelRecognizerSettings`. + */ + labelSettings: SimplifiedLabelRecognizerSettings; +} + +interface CapturedResultFilter { + onOriginalImageResultReceived?: (result: OriginalImageResultItem) => void; + [key: string]: any; +} + +declare class CaptureVisionRouter { + #private; + static _onLog: (message: string) => void; + static _defaultTemplate: string; + maxImageSideLength: number; + _instanceID: number; + private _dsImage; + private _loopReadVideoTimeoutId; + private _isPauseScan; + private _isOutputOriginalImage; + private _templateName; + private _isOpenDetectVerify; + private _isOpenNormalizeVerify; + private _isOpenBarcodeVerify; + private _isOpenLabelVerify; + private _minImageCaptureInterval; + private _averageProcessintTimeArray; + private _averageFetchImageTimeArray; + private _currentSettings; + private _averageTime; + /** + * Returns whether the `CaptureVisionRouter` instance has been disposed of. + * + * @returns Boolean indicating whether the `CaptureVisionRouter` instance has been disposed of. + */ + get disposed(): boolean; + /** + * Initializes a new instance of the `CaptureVisionRouter` class. + * + * @returns A promise that resolves with the initialized `CaptureVisionRouter` instance. + */ + static createInstance(): Promise; + private _singleFrameModeCallback; + private _singleFrameModeCallbackBind; + /** + * Sets up an image source to provide images for continuous processing. + * @param imageSource The image source which is compliant with the `ImageSourceAdapter` interface. + */ + setInput(imageSource: ImageSourceAdapter): void; + /** + * Returns the image source object. + */ + getInput(): ImageSourceAdapter; + /** + * Adds or removes listeners for image source state change. + */ + addImageSourceStateListener(listener: ImageSourceStateListener): void; + removeImageSourceStateListener(listener: ImageSourceStateListener): boolean; + /** + * Adds a `CapturedResultReceiver` object as the receiver of captured results. + * @param receiver The receiver object, of type `CapturedResultReceiver`. + */ + addResultReceiver(receiver: CapturedResultReceiver): void; + /** + * Removes the specified `CapturedResultReceiver` object. + * @param receiver The receiver object, of type `CapturedResultReceiver`. + */ + removeResultReceiver(receiver: CapturedResultReceiver): void; + private _setCrrRegistry; + /** + * Adds a `MultiFrameResultCrossFilter` object to filter non-essential results. + * @param filter The filter object, of type `MultiFrameResultCrossFilter`. + * + * @returns A promise that resolves when the operation has successfully completed. It does not provide any value upon resolution. + */ + addResultFilter(filter: CapturedResultFilter): Promise; + /** + * Removes the specified `MultiFrameResultCrossFilter` object. + * @param filter The filter object, of type `MultiFrameResultCrossFilter`. + * + * @returns A promise that resolves when the operation has successfully completed. It does not provide any value upon resolution. + */ + removeResultFilter(filter: CapturedResultFilter): Promise; + private _handleFilterUpdate; + /** + * Initiates a capturing process based on a specified template. This process is repeated for each image fetched from the source. + * @param templateName [Optional] Specifies a "CaptureVisionTemplate" to use. + * + * @returns A promise that resolves when the capturing process has successfully started. It does not provide any value upon resolution. + */ + startCapturing(templateName: string): Promise; + /** + * Stops the capturing process. + */ + stopCapturing(): void; + containsTask(templateName: string): Promise; + /** + * Video stream capture, recursive call, loop frame capture + */ + private _loopReadVideo; + private _reRunCurrnetFunc; + /** + * Processes a single image or a file containing a single image to derive important information. + * @param imageOrFile Specifies the image or file to be processed. The following data types are accepted: `Blob`, `HTMLImageElement`, `HTMLCanvasElement`, `HTMLVideoElement`, `DSImageData`, `string`. + * @param templateName [Optional] Specifies a "CaptureVisionTemplate" to use. + * + * @returns A promise that resolves with a `CapturedResult` object which contains the derived information from the image processed. + */ + capture(imageOrFile: Blob | string | DSImageData | HTMLImageElement | HTMLVideoElement | HTMLCanvasElement, templateName?: string): Promise; + private _captureDsimage; + private _captureUrl; + private _captureBase64; + private _captureBlob; + private _captureImage; + private _captureCanvas; + private _captureVideo; + private _captureInWorker; + /** + * Configures runtime settings using a provided JSON string, an object, or a URL pointing to an object, which contains settings for one or more `CaptureVisionTemplates`. + * @param settings A JSON string, an object, or a URL pointing to an object that contains settings for one or more `CaptureVisionTemplates`. + * + * @returns A promise that resolves when the operation has completed. It provides an object that describes the result. + */ + initSettings(settings: string | object): Promise; + /** + * Returns an object that contains settings for the specified `CaptureVisionTemplate`. + * @param templateName Specifies a `CaptureVisionTemplate` by its name. If passed "*", the returned object will contain all templates. + * + * @returns A promise that resolves with the object that contains settings for the specified template or all templates. + */ + outputSettings(templateName?: string): Promise; + /** + * Generates a Blob object or initiates a JSON file download containing the settings for the specified `CaptureVisionTemplate`. + * @param templateName Specifies a `CaptureVisionTemplate` by its name. If passed "*", the returned object will contain all templates. + * @param fileName Specifies the name of the file. + * @param download Boolean that specifies whether to initiates a file download. + * + * @returns A promise that resolves with the Blob object that contains settings for the specified template or all templates. + */ + outputSettingsToFile(templateName: string, fileName: string, download?: boolean): Promise; + getTemplateNames(): Promise>; + /** + * Retrieves a JSON object that contains simplified settings for the specified `CaptureVisionTemplate`. + * @param templateName Specifies a `CaptureVisionTemplate` by its name. + * + * @returns A promise that resolves with a JSON object, of type `SimplifiedCaptureVisionSettings`, which represents the simplified settings for the specified template. + * @remarks If the settings of the specified template are too complex, we cannot create a SimplifiedCaptureVisionSettings, and as a result, it will return an error. + */ + getSimplifiedSettings(templateName: string): Promise; + /** + * Updates the specified `CaptureVisionTemplate` with an updated `SimplifiedCaptureVisionSettings` object. + * @param templateName Specifies a `CaptureVisionTemplate` by its name. + * @param settings The `SimplifiedCaptureVisionSettings` object that contains updated settings. + * + * @returns A promise that resolves when the operation has completed. It provides an object that describes the result. + */ + updateSettings(templateName: string, settings: SimplifiedCaptureVisionSettings): Promise; + /** + * Restores all runtime settings to their original default values. + * + * @returns A promise that resolves when the operation has completed. It provides an object that describes the result. + */ + resetSettings(): Promise; + /** + * Returns an object, of type `BufferedItemsManager`, that manages buffered items. + * @returns The `BufferedItemsManager` object. + */ + getBufferedItemsManager(): BufferedItemsManager; + /** + * Returns an object, of type `IntermediateResultManager`, that manages intermediate results. + * + * @returns The `IntermediateResultManager` object. + */ + getIntermediateResultManager(): IntermediateResultManager; + parseRequiredResources(templateName: string): Promise<{ + models: string[]; + specss: string[]; + }>; + /** + * Releases all resources used by the `CaptureVisionRouter` instance. + * + * @returns A promise that resolves when the resources have been successfully released. It does not provide any value upon resolution. + */ + dispose(): Promise; + /** + * For Debug + */ + private _getInternalData; + private _getWasmFilterState; +} + +declare class CaptureVisionRouterModule { + private static _version; + static getVersion(): string; +} + +interface RawImageResultItem extends CapturedResultItem { + readonly imageData: DSImageData; +} + +declare enum EnumPresetTemplate { + /** + * @brief Versatile function for barcode reading, document detection, or text recognition. + */ + PT_DEFAULT = "Default", + /** + * @brief Scans a single barcode. + */ + PT_READ_BARCODES = "ReadBarcodes_Default", + /** + * @brief Identifies and reads any text present. + */ + PT_RECOGNIZE_TEXT_LINES = "RecognizeTextLines_Default", + /** + * @brief RIdentifies the edges of a document. + */ + PT_DETECT_DOCUMENT_BOUNDARIES = "DetectDocumentBoundaries_Default", + /** + * @brief Detects document edges and standardizes its format. + */ + PT_DETECT_AND_NORMALIZE_DOCUMENT = "DetectAndNormalizeDocument_Default", + /** + * @brief Adjusts a document to a standard format using detected borders. + */ + PT_NORMALIZE_DOCUMENT = "NormalizeDocument_Default", + /** + * @brief Represents a barcode reading mode where speed is prioritized. + * + * In this mode, the barcode reader will optimize for faster barcode detection + * and decoding, sacrificing some level of accuracy and read rate. It is suitable + * for situations where a quick response time is more important than perfect + * barcode recognition. + */ + PT_READ_BARCODES_SPEED_FIRST = "ReadBarcodes_SpeedFirst", + /** + * @brief Represents a barcode reading mode where barcode read rate is prioritized. + * + * In this mode, the barcode reader will optimize for higher barcode read rates, + * even if it may sometimes result in reduced accuracy and speed. It is suitable for + * scenarios where maximizing the number of successfully read barcodes is critical. + */ + PT_READ_BARCODES_READ_RATE_FIRST = "ReadBarcodes_ReadRateFirst", + /** + * @brief Represents a balanced barcode reading mode. + * + * This mode aims for a reasonable balance between speed and read rate in barcode + * recognition. It is suitable for most common use cases where a compromise between + * speed and read rate is acceptable. + */ + PT_READ_BARCODES_BALANCE = "ReadBarcodes_Balance", + /** + * @brief Represents a barcode reading mode for single barcode code detection. + * + * In this mode, the barcode reader will focus on detecting and decoding a single + * barcode code, ignoring any additional codes in the same image. It is efficient + * when the target image has only one barcode. + */ + PT_READ_SINGLE_BARCODE = "ReadBarcodes_Balanced", + /** + * @brief Represents a barcode reading mode optimized for dense barcode codes. + * + * This mode is designed to handle dense or closely packed barcode codes where + * accuracy is paramount. It may operate slower than other modes but is suitable + * for challenging scenarios where code density is high. + */ + PT_READ_DENSE_BARCODES = "ReadDenseBarcodes", + /** + * @brief Represents a barcode reading mode optimized for distant barcode codes. + * + * This mode is designed to scanning a barcode that is placed far from the device. + */ + PT_READ_DISTANT_BARCODES = "ReadDistantBarcodes", + /** + * @brief Represents a text recognition mode focused on recognizing numbers. + */ + PT_RECOGNIZE_NUMBERS = "RecognizeNumbers", + /** + * @brief Represents a text recognition mode focused on recognizing alphabetic characters (letters). + * + */ + PT_RECOGNIZE_LETTERS = "RecognizeLetters", + /** + * @brief Represents a text recognition mode that combines numbers and alphabetic characters (letters) recognition. + */ + PT_RECOGNIZE_NUMBERS_AND_LETTERS = "RecognizeNumbersAndLetters", + /** + * @brief Represents a text recognition mode that combines numbers and uppercase letters recognition. + */ + PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS = "RecognizeNumbersAndUppercaseLetters", + /** + * @brief Represents a text recognition mode focused on recognizing uppercase letters. + */ + PT_RECOGNIZE_UPPERCASE_LETTERS = "RecognizeUppercaseLetters" +} + +export { CaptureVisionRouter, CaptureVisionRouterModule, CapturedResult, CapturedResultFilter, CapturedResultReceiver, EnumImageSourceState, EnumPresetTemplate, ImageSourceStateListener, IntermediateResultReceiver, RawImageResultItem, SimplifiedCaptureVisionSettings }; diff --git a/dist/dynamsoft-capture-vision-router@2.4.33/dist/cvr.esm.js b/dist/dynamsoft-capture-vision-router@2.4.33/dist/cvr.esm.js new file mode 100644 index 0000000..e9f6632 --- /dev/null +++ b/dist/dynamsoft-capture-vision-router@2.4.33/dist/cvr.esm.js @@ -0,0 +1,2121 @@ +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft Capture Vision Router JS Edition + * @website http://www.dynamsoft.com + * @copyright Copyright 2024, Dynamsoft Corporation + * @author Dynamsoft + * @version "2.4.33" + * @fileoverview Dynamsoft JavaScript Library for Capture Vision + * More info on cvr JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/capture-vision-router-module.html + */ +import { getNextTaskID, mapTaskCallBack, worker, CoreModule, workerAutoResources, mapPackageRegister, compareVersion, innerVersions, EnumCapturedResultItemType, loadWasm, handleEngineResourcePaths, EnumImagePixelFormat, EnumColourChannelUsageType, isDSImageData, requestResource, EnumIntermediateResultUnitType } from 'dynamsoft-core'; + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + + +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +const isPromiseLike = (value) => (value && "object" === typeof value && "function" === typeof value.then); +// get original `Promise`, avoid other js change the `Promise` +const Promise$1 = (async () => { })().constructor; +class MutablePromise extends Promise$1 { + 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(value) { + //if(!this.isPending){ return; } + this._task = value; + let p; + if (isPromiseLike(value)) { + p = value; + } + else if ("function" === typeof value) { + p = new Promise$1(value); + } + if (p) { + (async () => { + try { + const ret = await p; + // make sure task not change + if (value === this._task) { + this.resolve(ret); + } + } + catch (reason) { + // make sure task not change + if (value === this._task) { + this.reject(reason); + } + } + })(); + } + } + get isEmpty() { return null == this._task; } + constructor(executor) { + let rs; + let rj; + const fn = (_rs, _rj) => { rs = _rs; rj = _rj; }; + super(fn); + // walkaround babel which can not extend builtin class + // let _this = this; + // let then = new Promise(fn).then; + // this.then = function(){ then.apply(_this, arguments) } as any; + this._s = "pending"; + this.resolve = (value) => { + if (this.isPending) { + if (isPromiseLike(value)) { + this.task = value; + } + else { + this._s = "fulfilled"; + rs(value); + } + } + }; + this.reject = (reason) => { + if (this.isPending) { + this._s = "rejected"; + rj(reason); + } + }; + this.task = executor; + } +} + +class BufferedItemsManager { + constructor(cvr) { + this._cvr = cvr; + } + /** + * Gets the maximum number of buffered items. + * @returns Returns the maximum number of buffered items. + */ + async getMaxBufferedItems() { + return await new Promise((rs, rj) => { + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + return rs(body.count); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return rj(ex); + } + }; + worker.postMessage({ + type: "cvr_getMaxBufferedItems", + id: taskID, + instanceID: this._cvr._instanceID + }); + }); + } + ; + /** + * Sets the maximum number of buffered items. + * @param count the maximum number of buffered items + */ + async setMaxBufferedItems(count) { + return await new Promise((rs, rj) => { + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + return rs(); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return rj(ex); + } + }; + worker.postMessage({ + type: "cvr_setMaxBufferedItems", + id: taskID, + instanceID: this._cvr._instanceID, + body: { + count + } + }); + }); + } + ; + /** + * Gets the buffered character items. + * @return the buffered character items + */ + async getBufferedCharacterItemSet() { + return await new Promise((rs, rj) => { + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + return rs(body.itemSet); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return rj(ex); + } + }; + worker.postMessage({ + type: "cvr_getBufferedCharacterItemSet", + id: taskID, + instanceID: this._cvr._instanceID + }); + }); + } + ; +} + +var irrRegistryState = { + onTaskResultsReceived: false, + onTaskResultsReceivedForDce: false, + // section + onPredetectedRegionsReceived: false, + onLocalizedBarcodesReceived: false, + onDecodedBarcodesReceived: false, + onLocalizedTextLinesReceived: false, + onRecognizedTextLinesReceived: false, + onDetectedQuadsReceived: false, + onNormalizedImagesReceived: false, + // stage + onColourImageUnitReceived: false, + onScaledDownColourImageUnitReceived: false, + onGrayscaleImageUnitReceived: false, + onTransformedGrayscaleImageUnitReceived: false, + onEnhancedGrayscaleImageUnitReceived: false, + onBinaryImageUnitReceived: false, + onTextureDetectionResultUnitReceived: false, + onTextureRemovedGrayscaleImageUnitReceived: false, + onTextureRemovedBinaryImageUnitReceived: false, + onContoursUnitReceived: false, + onLineSegmentsUnitReceived: false, + onTextZonesUnitReceived: false, + onTextRemovedBinaryImageUnitReceived: false, + onRawTextLinesReceived: false, + onLongLinesUnitReceived: false, + onCornersUnitReceived: false, + onCandidateQuadEdgesUnitReceived: false, + onCandidateBarcodeZonesUnitReceived: false, + onScaledUpBarcodeImageUnitReceived: false, + onDeformationResistedBarcodeImageUnitReceived: false, + onComplementedBarcodeImageUnitReceived: false, + onShortLinesUnitReceived: false, + onLogicLinesReceived: false +}; + +const _handleIntermediateResultReceiver = (irr) => { + for (let irs in irr._irrRegistryState) { + irr._irrRegistryState[irs] = false; + } + for (let receiver of irr._intermediateResultReceiverSet) { + if (receiver.isDce || receiver.isFilter) { + irr._irrRegistryState.onTaskResultsReceivedForDce = true; + continue; + } + for (let r in receiver) { + if (!irr._irrRegistryState[r]) { + irr._irrRegistryState[r] = !!receiver[r]; + } + } + } +}; +class IntermediateResultManager { + constructor(cvr) { + this._irrRegistryState = irrRegistryState; + this._intermediateResultReceiverSet = new Set(); + this._cvr = cvr; + } + /** + * Adds a `IntermediateResultReceiver` object as the receiver of intermediate results. + * @param receiver The receiver object, of type `IntermediateResultReceiver`. + */ + async addResultReceiver(receiver) { + if (typeof receiver !== "object") + throw new Error(`Invalid receiver.`); + this._intermediateResultReceiverSet.add(receiver); + _handleIntermediateResultReceiver(this); + let observedResultUnitTypes = -1; + let observedTaskMap = {}; + if (!receiver.isDce && !receiver.isFilter) { + if (!receiver._observedResultUnitTypes || !receiver._observedTaskMap) { + throw new Error("Invalid Intermediate Result Receiver."); + } + observedResultUnitTypes = receiver._observedResultUnitTypes; + receiver._observedTaskMap.forEach((value, key) => { + observedTaskMap[key] = value; + }); + receiver._observedTaskMap.clear(); + } + return await new Promise((rs, rj) => { + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + return rs(); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return rj(ex); + } + }; + worker.postMessage({ + type: "cvr_setIrrRegistry", + id: taskID, + instanceID: this._cvr._instanceID, + body: { + receiverObj: this._irrRegistryState, + observedResultUnitTypes: observedResultUnitTypes.toString(), + observedTaskMap + } + }); + }); + } + ; + /** + * Removes the specified `IntermediateResultReceiver` object. + * @param receiver The receiver object, of type `IntermediateResultReceiver`. + */ + async removeResultReceiver(receiver) { + this._intermediateResultReceiverSet.delete(receiver); + _handleIntermediateResultReceiver(this); + return await new Promise((rs, rj) => { + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + return rs(); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return rj(ex); + } + }; + worker.postMessage({ + type: "cvr_setIrrRegistry", + id: taskID, + instanceID: this._cvr._instanceID, + body: { + receiverObj: this._irrRegistryState + } + }); + }); + } + ; + /** + * Retrieves the original image data. + * + * @returns A promise that resolves when the operation has successfully completed. It provides the original image upon resolution. + */ + getOriginalImage() { + return this._cvr._dsImage; + } + ; +} + +const bSSR = "undefined" == typeof self; + +const isWebWorker = "function" == typeof importScripts, curScriptDir = (() => { + if (!isWebWorker) { + if (!bSSR && document.currentScript) { + let src = document.currentScript.src, idxSearch = src.indexOf("?"); + if (-1 != idxSearch) src = src.substring(0, idxSearch); else { + let idxHash = src.indexOf("#"); + -1 != idxHash && (src = src.substring(0, idxHash)); + } + return src.substring(0, src.lastIndexOf("/") + 1); + } + return "./"; + } +})(), getAbsoluteDir = value => { + if (null == value && (value = "./"), bSSR || isWebWorker) ; else { + let a = document.createElement("a"); + a.href = value, value = a.href; + } + return value.endsWith("/") || (value += "/"), value; +}; + +var _a; +CoreModule.engineResourcePaths.cvr = { version: "2.4.33", path: curScriptDir, isInternal: true }; +workerAutoResources.cvr = { js: true, wasm: true, deps: ["license", "dip"] }; +mapPackageRegister.cvr = {}; +const stdVersion = "1.4.21"; +if ('string' != typeof CoreModule.engineResourcePaths.std && compareVersion(CoreModule.engineResourcePaths.std.version, stdVersion) < 0) { + CoreModule.engineResourcePaths.std = { version: stdVersion, path: getAbsoluteDir(curScriptDir + `../../dynamsoft-capture-vision-std@${stdVersion}/dist/`), isInternal: true }; +} +const dipVersion = "2.4.31"; +if (!CoreModule.engineResourcePaths.dip || 'string' != typeof CoreModule.engineResourcePaths.dip && compareVersion(CoreModule.engineResourcePaths.dip.version, dipVersion) < 0) { + CoreModule.engineResourcePaths.dip = { version: dipVersion, path: getAbsoluteDir(curScriptDir + `../../dynamsoft-image-processing@${dipVersion}/dist/`), isInternal: true }; +} +class CaptureVisionRouterModule { + static getVersion() { + return this._version; + } +} +CaptureVisionRouterModule._version = `${"2.4.33"}(Worker: ${(_a = innerVersions.cvr) === null || _a === void 0 ? void 0 : _a.worker}, Wasm: loading...`; + +const resultItemMapConfig = { + "barcodeResultItems": { + type: EnumCapturedResultItemType.CRIT_BARCODE, + reveiver: "onDecodedBarcodesReceived", + isNeedFilter: true + }, + "textLineResultItems": { + type: EnumCapturedResultItemType.CRIT_TEXT_LINE, + reveiver: "onRecognizedTextLinesReceived", + isNeedFilter: true + }, + "detectedQuadResultItems": { + type: EnumCapturedResultItemType.CRIT_DETECTED_QUAD, + reveiver: "onDetectedQuadsReceived", + isNeedFilter: false + }, + "normalizedImageResultItems": { + type: EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE, + reveiver: "onNormalizedImagesReceived", + isNeedFilter: false + }, + "parsedResultItems": { + type: EnumCapturedResultItemType.CRIT_PARSED_RESULT, + reveiver: "onParsedResultsReceived", + isNeedFilter: false + } +}; + +var EnumImageSourceState; +(function (EnumImageSourceState) { + EnumImageSourceState[EnumImageSourceState["ISS_BUFFER_EMPTY"] = 0] = "ISS_BUFFER_EMPTY"; + EnumImageSourceState[EnumImageSourceState["ISS_EXHAUSTED"] = 1] = "ISS_EXHAUSTED"; +})(EnumImageSourceState || (EnumImageSourceState = {})); + +function convertCoordinates(item, compressRate) { + if (item && item.location) { + const points = item.location.points; + for (let point of points) { + point.x = point.x / compressRate; + point.y = point.y / compressRate; + } + convertCoordinates(item.referencedItem, compressRate); + } +} +function checkIsDisposed(cvr) { + if (cvr.disposed) { + throw new Error(`"CaptureVisionRouter" instance has been disposed`); + } +} + +var _CaptureVisionRouter_isa, _CaptureVisionRouter_canvas, _CaptureVisionRouter_promiseStartScan, _CaptureVisionRouter_intermediateResultManager, _CaptureVisionRouter_bufferdItemsManager, _CaptureVisionRouter_resultReceiverSet, _CaptureVisionRouter_isaStateListenerSet, _CaptureVisionRouter_resultFilterSet, _CaptureVisionRouter_compressRate, _CaptureVisionRouter_isScanner, _CaptureVisionRouter_innerUseTag, _CaptureVisionRouter_isDestroyed; +const _intermediateResultReceiverOfFilter = { + onTaskResultsReceived: () => { }, + isFilter: true +}; +class CaptureVisionRouter { + constructor() { + this.maxImageSideLength = ["iPhone", "Android", "HarmonyOS"].includes(CoreModule.browserInfo.OS) ? 2048 : 4096; + this._instanceID = undefined; + this._dsImage = null; + this._isPauseScan = true; + this._isOutputOriginalImage = false; + this._isOpenDetectVerify = false; + this._isOpenNormalizeVerify = false; + this._isOpenBarcodeVerify = false; + this._isOpenLabelVerify = false; + this._minImageCaptureInterval = 0; + this._averageProcessintTimeArray = []; + this._averageFetchImageTimeArray = []; + this._currentSettings = null; + this._averageTime = 999; + _CaptureVisionRouter_isa.set(this, null); + _CaptureVisionRouter_canvas.set(this, null); + _CaptureVisionRouter_promiseStartScan.set(this, null); + _CaptureVisionRouter_intermediateResultManager.set(this, null); + _CaptureVisionRouter_bufferdItemsManager.set(this, null); + _CaptureVisionRouter_resultReceiverSet.set(this, new Set()); + _CaptureVisionRouter_isaStateListenerSet.set(this, new Set()); + _CaptureVisionRouter_resultFilterSet.set(this, new Set()); + _CaptureVisionRouter_compressRate.set(this, 0); + _CaptureVisionRouter_isScanner.set(this, false); + _CaptureVisionRouter_innerUseTag.set(this, false); + _CaptureVisionRouter_isDestroyed.set(this, false); + this._singleFrameModeCallbackBind = this._singleFrameModeCallback.bind(this); + } + /** + * Returns whether the `CaptureVisionRouter` instance has been disposed of. + * + * @returns Boolean indicating whether the `CaptureVisionRouter` instance has been disposed of. + */ + get disposed() { + return __classPrivateFieldGet(this, _CaptureVisionRouter_isDestroyed, "f"); + } + /** + * Initializes a new instance of the `CaptureVisionRouter` class. + * + * @returns A promise that resolves with the initialized `CaptureVisionRouter` instance. + */ + static async createInstance() { + if (!mapPackageRegister.license) { + throw Error('Module `license` is not existed.'); + } + await mapPackageRegister.license.dynamsoft(); + await loadWasm(["cvr"]); + const captureVisionRouter = new CaptureVisionRouter(); + const p = new MutablePromise(); + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + var _a; + if (body.success) { + captureVisionRouter._instanceID = body.instanceID; + captureVisionRouter._currentSettings = JSON.parse(JSON.parse(body.outputSettings).data); + CaptureVisionRouterModule._version = `${"2.4.33"}(Worker: ${(_a = innerVersions.cvr) === null || _a === void 0 ? void 0 : _a.worker}, Wasm: ${body.version})`; + __classPrivateFieldSet(captureVisionRouter, _CaptureVisionRouter_innerUseTag, true, "f"); + __classPrivateFieldSet(captureVisionRouter, _CaptureVisionRouter_intermediateResultManager, captureVisionRouter.getIntermediateResultManager(), "f"); + __classPrivateFieldSet(captureVisionRouter, _CaptureVisionRouter_innerUseTag, false, "f"); + p.resolve(captureVisionRouter); + } + else { + const err = Error(body.message); + if (body.stack) { + err.stack = body.stack; + } + p.reject(err); + } + }; + worker.postMessage({ + type: 'cvr_createInstance', + id: taskID, + }); + return p; + } + ; + async _singleFrameModeCallback(dsImage) { + for (let receiver of __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f")) { + this._isOutputOriginalImage && receiver.onOriginalImageResultReceived && receiver.onOriginalImageResultReceived({ imageData: dsImage }); + } + const copyDsImageData = { + bytes: new Uint8Array(dsImage.bytes), + width: dsImage.width, + height: dsImage.height, + stride: dsImage.stride, + format: dsImage.format, + tag: dsImage.tag + }; + if (!this._templateName) + this._templateName = this._currentSettings.CaptureVisionTemplates[0].Name; + const result = await this.capture(copyDsImageData, this._templateName); + result.originalImageTag = dsImage.tag; + const resultCommonPart = { + originalImageHashId: result.originalImageHashId, + originalImageTag: result.originalImageTag, + errorCode: result.errorCode, + errorString: result.errorString + }; + for (let receiver of __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f")) { + if (receiver.isDce) { + receiver.onCapturedResultReceived(result, { + isDetectVerifyOpen: false, + isNormalizeVerifyOpen: false, + isBarcodeVerifyOpen: false, + isLabelVerifyOpen: false, + }); + continue; + } + for (let resultItem in resultItemMapConfig) { + const _itemType = resultItem; + const _itemConfig = resultItemMapConfig[_itemType]; + receiver[_itemConfig.reveiver] && result[_itemType] && receiver[_itemConfig.reveiver](Object.assign(Object.assign({}, resultCommonPart), { [_itemType]: result[_itemType] })); + } + receiver.onCapturedResultReceived && receiver.onCapturedResultReceived(result); + } + } + /** + * Sets up an image source to provide images for continuous processing. + * @param imageSource The image source which is compliant with the `ImageSourceAdapter` interface. + */ + setInput(imageSource) { + checkIsDisposed(this); + if (!imageSource) { + __classPrivateFieldSet(this, _CaptureVisionRouter_isa, null, "f"); + return; + } + __classPrivateFieldSet(this, _CaptureVisionRouter_isa, imageSource, "f"); + if (imageSource.isCameraEnhancer) { + if (__classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f")) { + __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f")._intermediateResultReceiver.isDce = true; + __classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f").addResultReceiver(__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f")._intermediateResultReceiver); + } + const cameraView = __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").getCameraView(); + if (cameraView) { + const dceCrr = cameraView._capturedResultReceiver; + dceCrr.isDce = true; + __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f").add(dceCrr); + } + // TODO: think about off. + //(imageSource as any).on("singleFrameAcquired", this._singleFrameModeCallback); + } + } + ; + /** + * Returns the image source object. + */ + getInput() { + return __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f"); + } + ; + /** + * Adds or removes listeners for image source state change. + */ + addImageSourceStateListener(listener) { + checkIsDisposed(this); + if (typeof listener !== "object") + return console.warn(`Invalid ISA state listener.`); + if (!listener || !Object.keys(listener)) + return; + __classPrivateFieldGet(this, _CaptureVisionRouter_isaStateListenerSet, "f").add(listener); + } + ; + removeImageSourceStateListener(listener) { + checkIsDisposed(this); + return __classPrivateFieldGet(this, _CaptureVisionRouter_isaStateListenerSet, "f").delete(listener); + } + /** + * Adds a `CapturedResultReceiver` object as the receiver of captured results. + * @param receiver The receiver object, of type `CapturedResultReceiver`. + */ + addResultReceiver(receiver) { + checkIsDisposed(this); + if (typeof receiver !== "object") + throw new Error(`Invalid receiver.`); + if (!receiver || !Object.keys(receiver).length) + return; + __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f").add(receiver); + this._setCrrRegistry(); + } + ; + /** + * Removes the specified `CapturedResultReceiver` object. + * @param receiver The receiver object, of type `CapturedResultReceiver`. + */ + removeResultReceiver(receiver) { + checkIsDisposed(this); + __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f").delete(receiver); + this._setCrrRegistry(); + } + async _setCrrRegistry() { + const receiver = { + onCapturedResultReceived: false, + onDecodedBarcodesReceived: false, + onRecognizedTextLinesReceived: false, + onDetectedQuadsReceived: false, + onNormalizedImagesReceived: false, + onParsedResultsReceived: false + }; + for (let r of __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f")) { + if (r.isDce) + continue; + receiver.onCapturedResultReceived = !!r["onCapturedResultReceived"]; + receiver.onDecodedBarcodesReceived = !!r["onDecodedBarcodesReceived"]; + receiver.onRecognizedTextLinesReceived = !!r["onRecognizedTextLinesReceived"]; + receiver.onDetectedQuadsReceived = !!r["onDetectedQuadsReceived"]; + receiver.onNormalizedImagesReceived = !!r["onNormalizedImagesReceived"]; + receiver.onParsedResultsReceived = !!r["onParsedResultsReceived"]; + } + const p = new MutablePromise(); + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + p.resolve(); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + p.reject(); + } + }; + worker.postMessage({ + type: "cvr_setCrrRegistry", + id: taskID, + instanceID: this._instanceID, + body: { + receiver: JSON.stringify(receiver) + } + }); + return p; + } + /** + * Adds a `MultiFrameResultCrossFilter` object to filter non-essential results. + * @param filter The filter object, of type `MultiFrameResultCrossFilter`. + * + * @returns A promise that resolves when the operation has successfully completed. It does not provide any value upon resolution. + */ + async addResultFilter(filter) { + checkIsDisposed(this); + if (!filter || typeof filter !== "object" || !Object.keys(filter).length) { + return console.warn(`Invalid filter.`); + } + __classPrivateFieldGet(this, _CaptureVisionRouter_resultFilterSet, "f").add(filter); + // When cvr.addResultFilter is called, this method will automatically be invoked to batch update the filter statuses that were set before calling addResultFilter. + filter._dynamsoft(); + await this._handleFilterUpdate(); + } + ; + /** + * Removes the specified `MultiFrameResultCrossFilter` object. + * @param filter The filter object, of type `MultiFrameResultCrossFilter`. + * + * @returns A promise that resolves when the operation has successfully completed. It does not provide any value upon resolution. + */ + async removeResultFilter(filter) { + checkIsDisposed(this); + __classPrivateFieldGet(this, _CaptureVisionRouter_resultFilterSet, "f").delete(filter); + await this._handleFilterUpdate(); + } + async _handleFilterUpdate() { + /** + * Each time a "filter" is added or removed, the "filter set" will be re-traversed, + * and _intermediateResultReceiverOfFilter will be added when necessary. + * This ensures that _intermediateResultReceiverOfFilter is not left in the "filter set" when the "filter set" is empty or when no filter in the "filter set" has isLatestOverlappingEnabled set to true. + */ + __classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f").removeResultReceiver(_intermediateResultReceiverOfFilter); + if (__classPrivateFieldGet(this, _CaptureVisionRouter_resultFilterSet, "f").size === 0) { + this._isOpenBarcodeVerify = false; + this._isOpenLabelVerify = false; + this._isOpenDetectVerify = false; + this._isOpenNormalizeVerify = false; + const _verificationEnabled = { + [EnumCapturedResultItemType.CRIT_BARCODE]: false, + [EnumCapturedResultItemType.CRIT_TEXT_LINE]: false, + [EnumCapturedResultItemType.CRIT_DETECTED_QUAD]: false, + [EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE]: false + }; + const _duplicateFilterEnabled = { + [EnumCapturedResultItemType.CRIT_BARCODE]: false, + [EnumCapturedResultItemType.CRIT_TEXT_LINE]: false, + [EnumCapturedResultItemType.CRIT_DETECTED_QUAD]: false, + [EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE]: false + }; + await _enableResultCrossVerification(this, _verificationEnabled); + await _enableResultDeduplication(this, _duplicateFilterEnabled); + return; + } + for (let filter of __classPrivateFieldGet(this, _CaptureVisionRouter_resultFilterSet, "f")) { + this._isOpenBarcodeVerify = filter.isResultCrossVerificationEnabled(EnumCapturedResultItemType.CRIT_BARCODE); + this._isOpenLabelVerify = filter.isResultCrossVerificationEnabled(EnumCapturedResultItemType.CRIT_TEXT_LINE); + this._isOpenDetectVerify = filter.isResultCrossVerificationEnabled(EnumCapturedResultItemType.CRIT_DETECTED_QUAD); + this._isOpenNormalizeVerify = filter.isResultCrossVerificationEnabled(EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE); + if (filter.isLatestOverlappingEnabled(EnumCapturedResultItemType.CRIT_BARCODE)) { + const _isExist = [...__classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f")._intermediateResultReceiverSet.values()].find((receiver) => { return receiver.isFilter; }); + if (!_isExist) { + __classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f").addResultReceiver(_intermediateResultReceiverOfFilter); + } + } + await _enableResultCrossVerification(this, filter.verificationEnabled); + await _enableResultDeduplication(this, filter.duplicateFilterEnabled); + await _setDuplicateForgetTime(this, filter.duplicateForgetTime); + } + } + /** + * Initiates a capturing process based on a specified template. This process is repeated for each image fetched from the source. + * @param templateName [Optional] Specifies a "CaptureVisionTemplate" to use. + * + * @returns A promise that resolves when the capturing process has successfully started. It does not provide any value upon resolution. + */ + async startCapturing(templateName) { + var _a, _b; + checkIsDisposed(this); + if (!this._isPauseScan) + return; + if (!__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f")) + throw new Error(`'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'`); + if (!templateName) + templateName = CaptureVisionRouter._defaultTemplate; + const tasks = await this.containsTask(templateName); + await loadWasm(tasks); + /* + * Why do we need to re-add an existing "filter" when calling "startCapturing"? + * Because there may be a situation where the corresponding wasm module has not been loaded when adding "filter", + * so after checking the required wasm module in "startCapturing", we will add "filter" again to ensure that "filter" takes effect in wasm. + * + * Why not check for the required wasm when adding the "filter"? + * Because each result type has a default value, we cannot know which wasm modules are actually needed through the passed "filter" + * + * This part of the logic has room for optimization. will do. + **/ + for (let filter of __classPrivateFieldGet(this, _CaptureVisionRouter_resultFilterSet, "f")) { + await this.addResultFilter(filter); + } + if (tasks.includes("dlr") && !((_a = mapPackageRegister.dlr) === null || _a === void 0 ? void 0 : _a.bLoadConfusableCharsData)) { + const _engineResourcePaths = handleEngineResourcePaths(CoreModule.engineResourcePaths); + await ((_b = mapPackageRegister.dlr) === null || _b === void 0 ? void 0 : _b.loadRecognitionData("ConfusableChars", _engineResourcePaths.dlr)); + } + if (__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").isCameraEnhancer) { + if (tasks.includes("ddn")) { + __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").setPixelFormat(EnumImagePixelFormat.IPF_ABGR_8888); + } + else { + __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").setPixelFormat(EnumImagePixelFormat.IPF_GRAYSCALED); + } + } + if (__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").singleFrameMode !== undefined && __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").singleFrameMode !== "disabled") { + this._templateName = templateName; + __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").on("singleFrameAcquired", this._singleFrameModeCallbackBind); + return; + } + const colourChannelUsageType = __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").getColourChannelUsageType(); + if (colourChannelUsageType === EnumColourChannelUsageType.CCUT_AUTO) { + __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").setColourChannelUsageType(tasks.includes("ddn") ? + EnumColourChannelUsageType.CCUT_FULL_CHANNEL + : + EnumColourChannelUsageType.CCUT_Y_CHANNEL_ONLY); + } + if (__classPrivateFieldGet(this, _CaptureVisionRouter_promiseStartScan, "f") && __classPrivateFieldGet(this, _CaptureVisionRouter_promiseStartScan, "f").isPending) + return __classPrivateFieldGet(this, _CaptureVisionRouter_promiseStartScan, "f"); + __classPrivateFieldSet(this, _CaptureVisionRouter_promiseStartScan, new MutablePromise((rs, rj) => { + if (this.disposed) + return; + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (!__classPrivateFieldGet(this, _CaptureVisionRouter_promiseStartScan, "f") || __classPrivateFieldGet(this, _CaptureVisionRouter_promiseStartScan, "f").isFulfilled) + return; + if (body.success) { + this._isPauseScan = false; + this._isOutputOriginalImage = body.isOutputOriginalImage; + this._loopReadVideoTimeoutId && clearTimeout(this._loopReadVideoTimeoutId); + this._loopReadVideoTimeoutId = setTimeout(async () => { + if (this._minImageCaptureInterval !== -1) { + __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").startFetching(); + } + this._loopReadVideo(templateName); + // try { + // await this._loopReadVideo(templateName); + // } catch (ex) { + // rj(ex); + // } + rs(); + }, 0); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return rj(ex); + } + }; + worker.postMessage({ + type: "cvr_startCapturing", + id: taskID, + instanceID: this._instanceID, + body: { templateName } + }); + }), "f"); + return await __classPrivateFieldGet(this, _CaptureVisionRouter_promiseStartScan, "f"); + } + /** + * Stops the capturing process. + */ + stopCapturing() { + checkIsDisposed(this); + if (!__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f")) + return; + if (__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").isCameraEnhancer) { + if (__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").singleFrameMode !== undefined && __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").singleFrameMode !== "disabled") { + __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").off("singleFrameAcquired", this._singleFrameModeCallbackBind); + return; + } + } + _clearVerifyList(this); + __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").stopFetching(); + this._averageProcessintTimeArray = []; + this._averageTime = 999; + this._isPauseScan = true; + __classPrivateFieldSet(this, _CaptureVisionRouter_promiseStartScan, null, "f"); + __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").setColourChannelUsageType(EnumColourChannelUsageType.CCUT_AUTO); + } + async containsTask(templateName) { + checkIsDisposed(this); + return await new Promise((rs, rj) => { + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + return rs(JSON.parse(body.tasks)); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return rj(ex); + } + }; + worker.postMessage({ + type: "cvr_containsTask", + id: taskID, + instanceID: this._instanceID, + body: { + templateName + } + }); + }); + } + /** + * Video stream capture, recursive call, loop frame capture + */ + async _loopReadVideo(templateName) { + if ((this.disposed || this._isPauseScan)) { + return; + } + __classPrivateFieldSet(this, _CaptureVisionRouter_isScanner, true, "f"); + if (__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").isBufferEmpty()) { + if (__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").hasNextImageToFetch()) { + for (let listener of __classPrivateFieldGet(this, _CaptureVisionRouter_isaStateListenerSet, "f")) { + listener.onImageSourceStateReceived && listener.onImageSourceStateReceived(EnumImageSourceState.ISS_BUFFER_EMPTY); + } + } + else if (!(__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").hasNextImageToFetch())) { + for (let listener of __classPrivateFieldGet(this, _CaptureVisionRouter_isaStateListenerSet, "f")) { + listener.onImageSourceStateReceived && listener.onImageSourceStateReceived(EnumImageSourceState.ISS_EXHAUSTED); + } + } + } + if (this._minImageCaptureInterval === -1 || __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").isBufferEmpty()) { + try { + if (__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").isBufferEmpty() && CaptureVisionRouter._onLog) + CaptureVisionRouter._onLog(`buffer is empty so fetch image`); + if (CaptureVisionRouter._onLog) { + CaptureVisionRouter._onLog(`DCE: start fetching a frame: ${Date.now()}`); + } + this._dsImage = __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").fetchImage(); + if (CaptureVisionRouter._onLog) { + CaptureVisionRouter._onLog(`DCE: finish fetching a frame: ${Date.now()}`); + } + __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").setImageFetchInterval(this._averageTime); + } + catch (e) { + this._reRunCurrnetFunc(templateName); + return; + } + } + else { + __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").setImageFetchInterval(this._averageTime - (this._dsImage && this._dsImage.tag ? this._dsImage.tag.timeSpent : 0)); + this._dsImage = __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").getImage(); + if (this._dsImage.tag) { + if (Date.now() - this._dsImage.tag.timeStamp > 200) { + this._reRunCurrnetFunc(templateName); + return; + } + } + } + if (!this._dsImage) { + this._reRunCurrnetFunc(templateName); + return; + } + for (let receiver of __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f")) { + this._isOutputOriginalImage && receiver.onOriginalImageResultReceived && receiver.onOriginalImageResultReceived({ imageData: this._dsImage }); + } + // capture + // try { + // const captureStartTime = Date.now(); + // const result = await this._captureDsimage(this._dsImage, templateName); + // if (CaptureVisionRouter._onLog) CaptureVisionRouter._onLog(`no js handle time: ${Date.now() - captureStartTime}`); + // if (this._isPauseScan) { + // this._reRunCurrnetFunc(templateName); + // return; + // } + // (result as any).originalImageTag = this._dsImage.tag ? this._dsImage.tag : null; + // const resultCommonPart = { + // originalImageHashId: result.originalImageHashId, + // originalImageTag: result.originalImageTag, + // errorCode: result.errorCode, + // errorString: result.errorString + // } + // for (let receiver of this.#resultReceiverSet) { + // if ((receiver as any).isDce) { + // const drawTime = Date.now(); + // (receiver as any).onCapturedResultReceived(result, { + // isDetectVerifyOpen: this._isOpenDetectVerify, + // isNormalizeVerifyOpen: this._isOpenNormalizeVerify, + // isBarcodeVerifyOpen: this._isOpenBarcodeVerify, + // isLabelVerifyOpen: this._isOpenLabelVerify, + // }); + // if (CaptureVisionRouter._onLog) { + // const time = Date.now() - drawTime; + // if (time > 10) CaptureVisionRouter._onLog(`draw result time: ${time}`) + // }; + // } + // receiver.onDecodedBarcodesReceived && result.barcodeResultItems && receiver.onDecodedBarcodesReceived({ + // ...resultCommonPart, + // barcodeResultItems: result.barcodeResultItems.filter((item: any) => { return !item.isFilter }) + // } as DecodedBarcodesResult); + // receiver.onRecognizedTextLinesReceived && result.textLineResultItems && receiver.onRecognizedTextLinesReceived({ + // ...resultCommonPart, + // textLineResultItems: result.textLineResultItems.filter((item: any) => { return !item.isFilter }) + // } as RecognizedTextLinesResult); + // receiver.onDetectedQuadsReceived && result.detectedQuadResultItems && receiver.onDetectedQuadsReceived({ + // ...resultCommonPart, + // detectedQuadResultItems: result.detectedQuadResultItems.filter((item: any) => { return !item.isFilter }) + // } as DetectedQuadsResult); + // receiver.onNormalizedImagesReceived && result.normalizedImageResultItems && receiver.onNormalizedImagesReceived({ + // ...resultCommonPart, + // normalizedImageResultItems: result.normalizedImageResultItems.filter((item: any) => { return !item.isFilter }) + // } as NormalizedImagesResult); + // receiver.onParsedResultsReceived && result.parsedResultItems && receiver.onParsedResultsReceived({ + // ...resultCommonPart, + // parsedResultItems: result.parsedResultItems.filter((item: any) => { return !item.isFilter }) + // } as ParsedResult); + // if (receiver.onCapturedResultReceived && !(receiver as any).isDce) { + // (result as any).items = result.items.filter((item: any) => { return !item.isFilter }); + // if ((result as any).barcodeResultItems) (result as any).barcodeResultItems = result.barcodeResultItems.filter((item: any) => { return !item.isFilter }); + // if ((result as any).textLineResultItems) (result as any).textLineResultItems = result.textLineResultItems.filter((item: any) => { return !item.isFilter }); + // if ((result as any).detectedQuadResultItems) (result as any).detectedQuadResultItems = result.detectedQuadResultItems.filter((item: any) => { return !item.isFilter }); + // if ((result as any).normalizedImageResultItems) (result as any).normalizedImageResultItems = result.normalizedImageResultItems.filter((item: any) => { return !item.isFilter }); + // if ((result as any).parsedResultItems) (result as any).parsedResultItems = result.parsedResultItems.filter((item: any) => { return !item.isFilter }); + // receiver.onCapturedResultReceived(result); + // } + // } + // const fetchImageCalculateStartTime = Date.now(); + // if (this._minImageCaptureInterval > -1) { + // if (this._averageProcessintTimeArray.length === 5) this._averageProcessintTimeArray.shift(); + // if (this._averageFetchImageTimeArray.length === 5) this._averageFetchImageTimeArray.shift(); + // this._averageProcessintTimeArray.push(Date.now() - captureStartTime); + // //this._averageTime = this._averageProcessintTimeArray.reduce((time, value) => time + value, 0) / this._averageProcessintTimeArray.length; + // this._averageFetchImageTimeArray.push((this._dsImage && this._dsImage.tag ? (this._dsImage.tag as any).timeSpent : 0)); + // this._averageTime = Math.min(...this._averageProcessintTimeArray) - Math.max(...this._averageFetchImageTimeArray); + // this._averageTime = this._averageTime > 0 ? this._averageTime : 0; + // if (CaptureVisionRouter._onLog) { + // CaptureVisionRouter._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`); + // CaptureVisionRouter._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`); + // CaptureVisionRouter._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`); + // CaptureVisionRouter._onLog(`averageTime: ${this._averageTime}`); + // }; + // } + // if (CaptureVisionRouter._onLog) { + // const time = Date.now() - fetchImageCalculateStartTime; + // if (time > 10) CaptureVisionRouter._onLog(`fetch image calculate time: ${time}`) + // }; + // if (CaptureVisionRouter._onLog) CaptureVisionRouter._onLog(`time finish decode: ${Date.now()}`) + // if (CaptureVisionRouter._onLog) CaptureVisionRouter._onLog(`main time: ${Date.now() - captureStartTime}`); + // if (CaptureVisionRouter._onLog) CaptureVisionRouter._onLog("===================================================="); + // this._loopReadVideoTimeoutId && clearTimeout(this._loopReadVideoTimeoutId); + // if (this._minImageCaptureInterval > 0 && this._minImageCaptureInterval >= this._averageTime) { + // this._loopReadVideoTimeoutId = setTimeout(() => { + // this._loopReadVideo(templateName); + // }, this._minImageCaptureInterval - this._averageTime); + // } else { + // this._loopReadVideoTimeoutId = setTimeout(() => { + // this._loopReadVideo(templateName); + // }, Math.max(this._minImageCaptureInterval, 0)); + // } + // } catch (ex) { + // this.#isa.stopFetching(); + // this._loopReadVideoTimeoutId && clearTimeout(this._loopReadVideoTimeoutId); + // this._loopReadVideoTimeoutId = setTimeout(() => { + // this.#isa.startFetching(); + // this._loopReadVideo(templateName); + // }, Math.max(this._minImageCaptureInterval, 1000)); + // if (!(ex.message === 'platform error')) { + // throw ex; + // } + // } + const captureStartTime = Date.now(); + this._captureDsimage(this._dsImage, templateName).then(async (result) => { + if (CaptureVisionRouter._onLog) + CaptureVisionRouter._onLog(`no js handle time: ${Date.now() - captureStartTime}`); + if (this._isPauseScan) { + this._reRunCurrnetFunc(templateName); + return; + } + result.originalImageTag = this._dsImage.tag ? this._dsImage.tag : null; + const resultCommonPart = { + originalImageHashId: result.originalImageHashId, + originalImageTag: result.originalImageTag, + errorCode: result.errorCode, + errorString: result.errorString + }; + for (let receiver of __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f")) { + if (receiver.isDce) { + const drawTime = Date.now(); + receiver.onCapturedResultReceived(result, { + isDetectVerifyOpen: this._isOpenDetectVerify, + isNormalizeVerifyOpen: this._isOpenNormalizeVerify, + isBarcodeVerifyOpen: this._isOpenBarcodeVerify, + isLabelVerifyOpen: this._isOpenLabelVerify, + }); + if (CaptureVisionRouter._onLog) { + const time = Date.now() - drawTime; + if (time > 10) + CaptureVisionRouter._onLog(`draw result time: ${time}`); + } + continue; + } + for (let resultItem in resultItemMapConfig) { + const _itemType = resultItem; + const _itemConfig = resultItemMapConfig[_itemType]; + receiver[_itemConfig.reveiver]; + receiver[_itemConfig.reveiver] && result[_itemType] && receiver[_itemConfig.reveiver](Object.assign(Object.assign({}, resultCommonPart), { [_itemType]: result[_itemType].filter((item) => { + return !_itemConfig.isNeedFilter || !item.isFilter; + }) })); + if (result[_itemType]) + result[_itemType] = result[_itemType].filter((item) => { + return !_itemConfig.isNeedFilter || !item.isFilter; + }); + } + if (receiver.onCapturedResultReceived) { + result.items = result.items.filter((item) => { + return [EnumCapturedResultItemType.CRIT_DETECTED_QUAD, EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE].includes(item.type) || !item.isFilter; + }); + receiver.onCapturedResultReceived(result); + } + } + const fetchImageCalculateStartTime = Date.now(); + if (this._minImageCaptureInterval > -1) { + if (this._averageProcessintTimeArray.length === 5) + this._averageProcessintTimeArray.shift(); + if (this._averageFetchImageTimeArray.length === 5) + this._averageFetchImageTimeArray.shift(); + this._averageProcessintTimeArray.push(Date.now() - captureStartTime); + //this._averageTime = this._averageProcessintTimeArray.reduce((time, value) => time + value, 0) / this._averageProcessintTimeArray.length; + this._averageFetchImageTimeArray.push((this._dsImage && this._dsImage.tag ? this._dsImage.tag.timeSpent : 0)); + this._averageTime = Math.min(...this._averageProcessintTimeArray) - Math.max(...this._averageFetchImageTimeArray); + this._averageTime = this._averageTime > 0 ? this._averageTime : 0; + if (CaptureVisionRouter._onLog) { + CaptureVisionRouter._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`); + CaptureVisionRouter._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`); + CaptureVisionRouter._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`); + CaptureVisionRouter._onLog(`averageTime: ${this._averageTime}`); + } + } + if (CaptureVisionRouter._onLog) { + const time = Date.now() - fetchImageCalculateStartTime; + if (time > 10) + CaptureVisionRouter._onLog(`fetch image calculate time: ${time}`); + } + if (CaptureVisionRouter._onLog) + CaptureVisionRouter._onLog(`time finish decode: ${Date.now()}`); + if (CaptureVisionRouter._onLog) + CaptureVisionRouter._onLog(`main time: ${Date.now() - captureStartTime}`); + if (CaptureVisionRouter._onLog) + CaptureVisionRouter._onLog("===================================================="); + this._loopReadVideoTimeoutId && clearTimeout(this._loopReadVideoTimeoutId); + if (this._minImageCaptureInterval > 0 && this._minImageCaptureInterval >= this._averageTime) { + this._loopReadVideoTimeoutId = setTimeout(() => { + this._loopReadVideo(templateName); + }, this._minImageCaptureInterval - this._averageTime); + } + else { + this._loopReadVideoTimeoutId = setTimeout(() => { + this._loopReadVideo(templateName); + }, Math.max(this._minImageCaptureInterval, 0)); + } + }).catch((ex) => { + __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").stopFetching(); + if (ex.errorCode && ex.errorCode === 0) { + this._loopReadVideoTimeoutId && clearTimeout(this._loopReadVideoTimeoutId); + this._loopReadVideoTimeoutId = setTimeout(() => { + __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").startFetching(); + this._loopReadVideo(templateName); + }, Math.max(this._minImageCaptureInterval, 1000)); + } + if (!(ex.message === 'platform error')) { + setTimeout(() => { throw ex; }, 0); + } + }); + } + _reRunCurrnetFunc(templateName) { + this._loopReadVideoTimeoutId && clearTimeout(this._loopReadVideoTimeoutId); + this._loopReadVideoTimeoutId = setTimeout(() => { + this._loopReadVideo(templateName); + }, 0); + } + /** + * Processes a single image or a file containing a single image to derive important information. + * @param imageOrFile Specifies the image or file to be processed. The following data types are accepted: `Blob`, `HTMLImageElement`, `HTMLCanvasElement`, `HTMLVideoElement`, `DSImageData`, `string`. + * @param templateName [Optional] Specifies a "CaptureVisionTemplate" to use. + * + * @returns A promise that resolves with a `CapturedResult` object which contains the derived information from the image processed. + */ + async capture(imageOrFile, templateName) { + var _a, _b; + checkIsDisposed(this); + if (!templateName) + templateName = CaptureVisionRouter._defaultTemplate; + const tasks = await this.containsTask(templateName); + await loadWasm(tasks); + if (tasks.includes("dlr") && !((_a = mapPackageRegister.dlr) === null || _a === void 0 ? void 0 : _a.bLoadConfusableCharsData)) { + const _engineResourcePaths = handleEngineResourcePaths(CoreModule.engineResourcePaths); + await ((_b = mapPackageRegister.dlr) === null || _b === void 0 ? void 0 : _b.loadRecognitionData("ConfusableChars", _engineResourcePaths.dlr)); + } + let result; + __classPrivateFieldSet(this, _CaptureVisionRouter_isScanner, false, "f"); + if (isDSImageData(imageOrFile)) { + result = await this._captureDsimage(imageOrFile, templateName); + } + else if (typeof imageOrFile === "string") { + if (imageOrFile.substring(0, 11) == "data:image/") { + result = await this._captureBase64(imageOrFile, templateName); + } + else { + result = await this._captureUrl(imageOrFile, templateName); + } + } + else if (imageOrFile instanceof Blob) { + result = await this._captureBlob(imageOrFile, templateName); + } + else if (imageOrFile instanceof HTMLImageElement) { + result = await this._captureImage(imageOrFile, templateName); + } + else if (imageOrFile instanceof HTMLCanvasElement) { + result = await this._captureCanvas(imageOrFile, templateName); + } + else if (imageOrFile instanceof HTMLVideoElement) { + result = await this._captureVideo(imageOrFile, templateName); + } + else { + throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'."); + } + return result; + } + ; + async _captureDsimage(imageOrFile, templateName) { + return await this._captureInWorker(imageOrFile, templateName); + } + async _captureUrl(imageOrFile, templateName) { + let blob = await requestResource(imageOrFile, "blob"); + return await this._captureBlob(blob, templateName); + } + async _captureBase64(base64Str, templateName) { + base64Str = base64Str.substring(base64Str.indexOf(',') + 1); + let binaryStr = atob(base64Str); + let n = binaryStr.length; + let u8arr = new Uint8Array(n); + while (n--) { + u8arr[n] = binaryStr.charCodeAt(n); + } + return await this._captureBlob(new Blob([u8arr]), templateName); + } + async _captureBlob(imageOrFile, templateName) { + const useObjurlToDrawBlobToImg = async function (blob) { + return await new Promise((rs, rj) => { + let objUrl = URL.createObjectURL(blob); + let image = new Image(); + image.src = objUrl; + image.onload = () => { + URL.revokeObjectURL(image.dbrObjUrl); // relese memory + rs(image); + }; + image.onerror = ev => { + rj(new Error("Can't convert blob to image : " + (ev instanceof Event ? ev.type : ev))); + }; + }); + }; + let imageBitmap = null; + let img = null; + if (typeof createImageBitmap !== "undefined") { + try { + imageBitmap = await createImageBitmap(imageOrFile); + } + catch (ex) { + // createImageBitmap maybe fail in a lot of sense + // although objurl can pass + } + } + if (!imageBitmap) { + img = await useObjurlToDrawBlobToImg(imageOrFile); + } + let results = await this._captureImage(imageBitmap || img, templateName); + if (imageBitmap) { + imageBitmap.close(); + } // release memory + return results; + } + async _captureImage(image, templateName) { + let imgW = image instanceof HTMLImageElement ? image.naturalWidth : image.width; + let imgH = image instanceof HTMLImageElement ? image.naturalHeight : image.height; + let maxNaturalWH = Math.max(imgW, imgH); + let acceptW, acceptH; + if (maxNaturalWH > this.maxImageSideLength) { + __classPrivateFieldSet(this, _CaptureVisionRouter_compressRate, this.maxImageSideLength / maxNaturalWH, "f"); + acceptW = Math.round(imgW * __classPrivateFieldGet(this, _CaptureVisionRouter_compressRate, "f")); + acceptH = Math.round(imgH * __classPrivateFieldGet(this, _CaptureVisionRouter_compressRate, "f")); + } + else { + acceptW = imgW; + acceptH = imgH; + } + if (!__classPrivateFieldGet(this, _CaptureVisionRouter_canvas, "f")) { + __classPrivateFieldSet(this, _CaptureVisionRouter_canvas, document.createElement('canvas'), "f"); + } + const cvs = __classPrivateFieldGet(this, _CaptureVisionRouter_canvas, "f"); + if (cvs.width !== acceptW || cvs.height !== acceptH) { + cvs.width = acceptW; + cvs.height = acceptH; + } + if (!cvs.ctx2d) { + cvs.ctx2d = cvs.getContext('2d', { willReadFrequently: true }); + } + const ctx = cvs.ctx2d; + ctx.drawImage(image, 0, 0, imgW, imgH, 0, 0, acceptW, acceptH); + if (image.dbrObjUrl) { + URL.revokeObjectURL(image.dbrObjUrl); // relese memory + } + return await this._captureCanvas(cvs, templateName); + } + async _captureCanvas(canvas, templateName) { + if (canvas.crossOrigin && "anonymous" != canvas.crossOrigin) { // canvas has crossOrigin to detect if cors, is native api + throw "cors"; + } + if ([canvas.width, canvas.height].includes(0)) { + throw Error(`The width or height of the 'canvas' is 0.`); + } + const ctx = canvas.ctx2d || canvas.getContext("2d", { willReadFrequently: true }); + const imgData = Uint8Array.from(ctx.getImageData(0, 0, canvas.width, canvas.height).data); + const DsImageData = { + bytes: imgData, + width: canvas.width, + height: canvas.height, + stride: canvas.width * 4, + format: 10, + }; + return await this._captureInWorker(DsImageData, templateName); + } + async _captureVideo(video, templateName) { + if (video.crossOrigin && "anonymous" != video.crossOrigin) { + throw "cors"; + } + let imgW = video.videoWidth; + let imgH = video.videoHeight; + let maxNaturalWH = Math.max(imgW, imgH); + let acceptW, acceptH; + if (maxNaturalWH > this.maxImageSideLength) { + __classPrivateFieldSet(this, _CaptureVisionRouter_compressRate, this.maxImageSideLength / maxNaturalWH, "f"); + acceptW = Math.round(imgW * __classPrivateFieldGet(this, _CaptureVisionRouter_compressRate, "f")); + acceptH = Math.round(imgH * __classPrivateFieldGet(this, _CaptureVisionRouter_compressRate, "f")); + } + else { + acceptW = imgW; + acceptH = imgH; + } + if (!__classPrivateFieldGet(this, _CaptureVisionRouter_canvas, "f")) { + __classPrivateFieldSet(this, _CaptureVisionRouter_canvas, document.createElement('canvas'), "f"); + } + const cvs = __classPrivateFieldGet(this, _CaptureVisionRouter_canvas, "f"); + if (cvs.width !== acceptW || cvs.height !== acceptH) { + cvs.width = acceptW; + cvs.height = acceptH; + } + if (!cvs.ctx2d) { + cvs.ctx2d = cvs.getContext('2d', { willReadFrequently: true }); + } + const ctx = cvs.ctx2d; + ctx.drawImage(video, 0, 0, imgW, imgH, 0, 0, acceptW, acceptH); + return await this._captureCanvas(cvs, templateName); + } + async _captureInWorker(DsImageData, templateName) { + const { bytes, width, height, stride, format } = DsImageData; + let taskID = getNextTaskID(); + const p = new MutablePromise(); + mapTaskCallBack[taskID] = async (body) => { + var _a, _b; + if (body.success) { + const getResultFromWorkerTime = Date.now(); + if (CaptureVisionRouter._onLog) { + CaptureVisionRouter._onLog(`get result time from worker: ${getResultFromWorkerTime}`); + CaptureVisionRouter._onLog(`worker to main time consume: ${getResultFromWorkerTime - body.workerReturnMsgTime}`); + } + try { + const captureResult = body.captureResult; + if (captureResult.errorCode !== 0) { + let error = new Error(captureResult.errorString); + error.errorCode = captureResult.errorCode; + return p.reject(error); + } + DsImageData.bytes = body.bytes; + for (let item of captureResult.items) { + if (__classPrivateFieldGet(this, _CaptureVisionRouter_compressRate, "f") !== 0) { + convertCoordinates(item, __classPrivateFieldGet(this, _CaptureVisionRouter_compressRate, "f")); + } + if (item.type === EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE) { + item.imageData = DsImageData; + } + else if (item.type === EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE) { + (_a = mapPackageRegister.ddn) === null || _a === void 0 ? void 0 : _a.handleNormalizedImageResultItem(item); + } + else if (item.type === EnumCapturedResultItemType.CRIT_PARSED_RESULT) { + (_b = mapPackageRegister.dcp) === null || _b === void 0 ? void 0 : _b.handleParsedResultItem(item); + } + } + if (__classPrivateFieldGet(this, _CaptureVisionRouter_isScanner, "f")) { + for (let filter of __classPrivateFieldGet(this, _CaptureVisionRouter_resultFilterSet, "f")) { + filter.onDecodedBarcodesReceived(captureResult); + filter.onRecognizedTextLinesReceived(captureResult); + filter.onDetectedQuadsReceived(captureResult); + filter.onNormalizedImagesReceived(captureResult); + } + } + for (let itemName in resultItemMapConfig) { + const _itemName = itemName; + const filterItems = captureResult.items.filter((item) => { + return item.type === resultItemMapConfig[_itemName].type; + }); + if (filterItems.length) { + captureResult[itemName] = filterItems; + } + } + if (!this._isPauseScan || !__classPrivateFieldGet(this, _CaptureVisionRouter_isScanner, "f")) { + const irs = captureResult.intermediateResult; // irs => intermediateResults + if (irs) { + let irrSetCount = 0; + for (let irr of __classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f")._intermediateResultReceiverSet) { + irrSetCount++; + for (let cb of irs) { + if (cb.info.callbackName === "onTaskResultsReceived") { + for (let unit of cb.intermediateResultUnits) { + unit.originalImageTag = DsImageData.tag ? DsImageData.tag : null; + } + if (irr[cb.info.callbackName]) { + irr[cb.info.callbackName]({ intermediateResultUnits: cb.intermediateResultUnits }, cb.info); + } + } + else { + if (irr[cb.info.callbackName]) { + irr[cb.info.callbackName](cb.result, cb.info); + } + } + if (irrSetCount === __classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f")._intermediateResultReceiverSet.size) { + delete cb.info.callbackName; + } + } + } + } + } + captureResult && captureResult.hasOwnProperty("intermediateResult") && delete captureResult.intermediateResult; + __classPrivateFieldSet(this, _CaptureVisionRouter_compressRate, 0, "f"); + return p.resolve(captureResult); + } + catch (ex) { + return p.reject(ex); + } + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return p.reject(ex); + } + }; + if (CaptureVisionRouter._onLog) { + CaptureVisionRouter._onLog(`send buffer to worker: ${Date.now()}`); + } + worker.postMessage({ + type: "cvr_capture", + id: taskID, + instanceID: this._instanceID, + body: { + bytes, + width, + height, + stride, + format, + templateName: templateName ? templateName : "", + isScanner: __classPrivateFieldGet(this, _CaptureVisionRouter_isScanner, "f") + } + }, [bytes.buffer]); + return p; + } + ; + /** + * Configures runtime settings using a provided JSON string, an object, or a URL pointing to an object, which contains settings for one or more `CaptureVisionTemplates`. + * @param settings A JSON string, an object, or a URL pointing to an object that contains settings for one or more `CaptureVisionTemplates`. + * + * @returns A promise that resolves when the operation has completed. It provides an object that describes the result. + */ + async initSettings(settings) { + checkIsDisposed(this); + if (!settings || !["string", "object"].includes(typeof settings)) { + return console.error("Invalid template."); + } + if (typeof settings === "string") { + if (!settings.trimStart().startsWith("{")) { + settings = await requestResource(settings, "text"); + } + } + else if (typeof settings === "object") { + settings = JSON.stringify(settings); + } + return await new Promise((rs, rj) => { + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + const response = JSON.parse(body.response); + if (response.errorCode !== 0) { + let error = new Error(response.errorString ? response.errorString : "Init Settings Failed."); + error.errorCode = response.errorCode; + return rj(error); + } + const _parsedSettings = JSON.parse(settings); + this._currentSettings = _parsedSettings; + let modules = []; + let templateNames = _parsedSettings.CaptureVisionTemplates; + for (let i = 0; i < templateNames.length; i++) { + let tasks = await this.containsTask(templateNames[i].Name); + modules = modules.concat(tasks); + } + await loadWasm([...new Set(modules)]); + this._isOutputOriginalImage = (this._currentSettings.CaptureVisionTemplates[0].OutputOriginalImage === 1); + CaptureVisionRouter._defaultTemplate = this._currentSettings.CaptureVisionTemplates[0].Name; + return rs(response); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return rj(ex); + } + }; + worker.postMessage({ + type: "cvr_initSettings", + id: taskID, + instanceID: this._instanceID, + body: { settings }, + }); + }); + } + ; + /** + * Returns an object that contains settings for the specified `CaptureVisionTemplate`. + * @param templateName Specifies a `CaptureVisionTemplate` by its name. If passed "*", the returned object will contain all templates. + * + * @returns A promise that resolves with the object that contains settings for the specified template or all templates. + */ + async outputSettings(templateName) { + checkIsDisposed(this); + return await new Promise((rs, rj) => { + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + const response = JSON.parse(body.response); + if (response.errorCode !== 0) { + let error = new Error(response.errorString); + error.errorCode = response.errorCode; + return rj(error); + } + return rs(JSON.parse(response.data)); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return rj(ex); + } + }; + worker.postMessage({ + type: "cvr_outputSettings", + id: taskID, + instanceID: this._instanceID, + body: { + templateName: templateName ? templateName : "*" + } + }); + }); + } + ; + /** + * Generates a Blob object or initiates a JSON file download containing the settings for the specified `CaptureVisionTemplate`. + * @param templateName Specifies a `CaptureVisionTemplate` by its name. If passed "*", the returned object will contain all templates. + * @param fileName Specifies the name of the file. + * @param download Boolean that specifies whether to initiates a file download. + * + * @returns A promise that resolves with the Blob object that contains settings for the specified template or all templates. + */ + async outputSettingsToFile(templateName, fileName, download) { + const settings = await this.outputSettings(templateName); + const jsonBlob = new Blob([JSON.stringify(settings, null, 2, function (_, value) { + if (value instanceof Array) { + return JSON.stringify(value); + } + else { + return value; + } + }, 2)], { type: "application/json" }); + if (download) { + const downloadLink = document.createElement("a"); + downloadLink.href = URL.createObjectURL(jsonBlob); + if (fileName.endsWith(".json")) { + fileName = fileName.replace(".json", ""); + } + downloadLink.download = `${fileName}.json`; + downloadLink.onclick = () => { + setTimeout(() => { + URL.revokeObjectURL(downloadLink.href); + }, 500); + }; + downloadLink.click(); + } + return jsonBlob; + } + async getTemplateNames() { + checkIsDisposed(this); + return await new Promise((rs, rj) => { + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + const response = JSON.parse(body.response); + if (response.errorCode !== 0) { + let error = new Error(response.errorString); + error.errorCode = response.errorCode; + return rj(error); + } + return rs(JSON.parse(response.data)); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return rj(ex); + } + }; + worker.postMessage({ + type: "cvr_getTemplateNames", + id: taskID, + instanceID: this._instanceID + }); + }); + } + /** + * Retrieves a JSON object that contains simplified settings for the specified `CaptureVisionTemplate`. + * @param templateName Specifies a `CaptureVisionTemplate` by its name. + * + * @returns A promise that resolves with a JSON object, of type `SimplifiedCaptureVisionSettings`, which represents the simplified settings for the specified template. + * @remarks If the settings of the specified template are too complex, we cannot create a SimplifiedCaptureVisionSettings, and as a result, it will return an error. + */ + async getSimplifiedSettings(templateName) { + checkIsDisposed(this); + if (!templateName) + templateName = this._currentSettings.CaptureVisionTemplates[0].Name; + const tasks = await this.containsTask(templateName); + await loadWasm(tasks); + return await new Promise((rs, rj) => { + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + const response = JSON.parse(body.response); + if (response.errorCode !== 0) { + let error = new Error(response.errorString); + error.errorCode = response.errorCode; + return rj(error); + } + const responseData = JSON.parse(response.data, (k, v) => { + if (k === "barcodeFormatIds") { + return BigInt(v); + } + return v; + }); + responseData.minImageCaptureInterval = this._minImageCaptureInterval; + return rs(responseData); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return rj(ex); + } + }; + worker.postMessage({ + type: "cvr_getSimplifiedSettings", + id: taskID, + instanceID: this._instanceID, + body: { templateName } + }); + }); + } + ; + /** + * Updates the specified `CaptureVisionTemplate` with an updated `SimplifiedCaptureVisionSettings` object. + * @param templateName Specifies a `CaptureVisionTemplate` by its name. + * @param settings The `SimplifiedCaptureVisionSettings` object that contains updated settings. + * + * @returns A promise that resolves when the operation has completed. It provides an object that describes the result. + */ + async updateSettings(templateName, settings) { + checkIsDisposed(this); + const tasks = await this.containsTask(templateName); + await loadWasm(tasks); + return await new Promise((rs, rj) => { + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + const response = JSON.parse(body.response); + if (settings.minImageCaptureInterval && settings.minImageCaptureInterval >= -1) { + this._minImageCaptureInterval = settings.minImageCaptureInterval; + } + this._isOutputOriginalImage = body.isOutputOriginalImage; + if (response.errorCode !== 0) { + let error = new Error(response.errorString ? response.errorString : "Update Settings Failed."); + error.errorCode = response.errorCode; + return rj(error); + } + this._currentSettings = await this.outputSettings("*"); + return rs(response); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return rj(ex); + } + }; + worker.postMessage({ + type: "cvr_updateSettings", + id: taskID, + instanceID: this._instanceID, + body: { + settings, + templateName + } + }); + }); + } + /** + * Restores all runtime settings to their original default values. + * + * @returns A promise that resolves when the operation has completed. It provides an object that describes the result. + */ + async resetSettings() { + checkIsDisposed(this); + return await new Promise((rs, rj) => { + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + const response = JSON.parse(body.response); + if (response.errorCode !== 0) { + let error = new Error(response.errorString ? response.errorString : "Reset Settings Failed."); + error.errorCode = response.errorCode; + return rj(error); + } + this._currentSettings = await this.outputSettings("*"); + return rs(response); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return rj(ex); + } + }; + worker.postMessage({ + type: "cvr_resetSettings", + id: taskID, + instanceID: this._instanceID + }); + }); + } + ; + /** + * Returns an object, of type `BufferedItemsManager`, that manages buffered items. + * @returns The `BufferedItemsManager` object. + */ + getBufferedItemsManager() { + if (!__classPrivateFieldGet(this, _CaptureVisionRouter_bufferdItemsManager, "f")) { + __classPrivateFieldSet(this, _CaptureVisionRouter_bufferdItemsManager, new BufferedItemsManager(this), "f"); + } + return __classPrivateFieldGet(this, _CaptureVisionRouter_bufferdItemsManager, "f"); + } + /** + * Returns an object, of type `IntermediateResultManager`, that manages intermediate results. + * + * @returns The `IntermediateResultManager` object. + */ + getIntermediateResultManager() { + checkIsDisposed(this); + if (!__classPrivateFieldGet(this, _CaptureVisionRouter_innerUseTag, "f") && CoreModule.bSupportIRTModule !== 0) { + throw new Error("The current license does not support the use of intermediate results."); + } + if (!__classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f")) { + __classPrivateFieldSet(this, _CaptureVisionRouter_intermediateResultManager, new IntermediateResultManager(this), "f"); + } + return __classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f"); + } + ; + async parseRequiredResources(templateName) { + checkIsDisposed(this); + return await new Promise((rs, rj) => { + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + return rs(JSON.parse(body.resources)); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return rj(ex); + } + }; + worker.postMessage({ + type: "cvr_parseRequiredResources", + id: taskID, + instanceID: this._instanceID, + body: { + templateName + } + }); + }); + } + /** + * Releases all resources used by the `CaptureVisionRouter` instance. + * + * @returns A promise that resolves when the resources have been successfully released. It does not provide any value upon resolution. + */ + async dispose() { + checkIsDisposed(this); + if (__classPrivateFieldGet(this, _CaptureVisionRouter_promiseStartScan, "f")) { + this.stopCapturing(); + } + __classPrivateFieldSet(this, _CaptureVisionRouter_isa, null, "f"); + __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f").clear(); + __classPrivateFieldGet(this, _CaptureVisionRouter_isaStateListenerSet, "f").clear(); + __classPrivateFieldGet(this, _CaptureVisionRouter_resultFilterSet, "f").clear(); + __classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f")._intermediateResultReceiverSet.clear(); + __classPrivateFieldSet(this, _CaptureVisionRouter_isDestroyed, true, "f"); + // this._captureStateListenerSet.clear(); + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = (body) => { + if (body.success) ; + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + throw ex; + } + }; + worker.postMessage({ + type: 'cvr_dispose', + id: taskID, + instanceID: this._instanceID + }); + } + ; + /** + * For Debug + */ + _getInternalData() { + return { + isa: __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f"), + promiseStartScan: __classPrivateFieldGet(this, _CaptureVisionRouter_promiseStartScan, "f"), + intermediateResultManager: __classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f"), + bufferdItemsManager: __classPrivateFieldGet(this, _CaptureVisionRouter_bufferdItemsManager, "f"), + resultReceiverSet: __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f"), + isaStateListenerSet: __classPrivateFieldGet(this, _CaptureVisionRouter_isaStateListenerSet, "f"), + resultFilterSet: __classPrivateFieldGet(this, _CaptureVisionRouter_resultFilterSet, "f"), + compressRate: __classPrivateFieldGet(this, _CaptureVisionRouter_compressRate, "f"), + canvas: __classPrivateFieldGet(this, _CaptureVisionRouter_canvas, "f"), + isScanner: __classPrivateFieldGet(this, _CaptureVisionRouter_isScanner, "f"), + innerUseTag: __classPrivateFieldGet(this, _CaptureVisionRouter_innerUseTag, "f"), + isDestroyed: __classPrivateFieldGet(this, _CaptureVisionRouter_isDestroyed, "f") + }; + } + async _getWasmFilterState() { + return await new Promise((rs, rj) => { + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + const response = JSON.parse(body.response); + return rs(response); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return rj(ex); + } + }; + worker.postMessage({ + type: "cvr_getWasmFilterState", + id: taskID, + instanceID: this._instanceID + }); + }); + } +} +_CaptureVisionRouter_isa = new WeakMap(), _CaptureVisionRouter_canvas = new WeakMap(), _CaptureVisionRouter_promiseStartScan = new WeakMap(), _CaptureVisionRouter_intermediateResultManager = new WeakMap(), _CaptureVisionRouter_bufferdItemsManager = new WeakMap(), _CaptureVisionRouter_resultReceiverSet = new WeakMap(), _CaptureVisionRouter_isaStateListenerSet = new WeakMap(), _CaptureVisionRouter_resultFilterSet = new WeakMap(), _CaptureVisionRouter_compressRate = new WeakMap(), _CaptureVisionRouter_isScanner = new WeakMap(), _CaptureVisionRouter_innerUseTag = new WeakMap(), _CaptureVisionRouter_isDestroyed = new WeakMap(); +CaptureVisionRouter._defaultTemplate = "Default"; +async function _enableResultCrossVerification(cvr, verificationEnabled) { + checkIsDisposed(cvr); + return await new Promise((rs, rj) => { + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + return rs(body.result); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return rj(ex); + } + }; + worker.postMessage({ + type: "cvr_enableResultCrossVerification", + id: taskID, + instanceID: cvr._instanceID, + body: { + verificationEnabled + } + }); + }); +} +async function _enableResultDeduplication(cvr, duplicateFilterEnabled) { + checkIsDisposed(cvr); + return await new Promise((rs, rj) => { + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + return rs(body.result); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return rj(ex); + } + }; + worker.postMessage({ + type: "cvr_enableResultDeduplication", + id: taskID, + instanceID: cvr._instanceID, + body: { + duplicateFilterEnabled + } + }); + }); +} +async function _setDuplicateForgetTime(cvr, duplicateForgetTime) { + checkIsDisposed(cvr); + return await new Promise((rs, rj) => { + let taskID = getNextTaskID(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + return rs(body.result); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return rj(ex); + } + }; + worker.postMessage({ + type: "cvr_setDuplicateForgetTime", + id: taskID, + instanceID: cvr._instanceID, + body: { + duplicateForgetTime + } + }); + }); +} +async function _clearVerifyList(cvr) { + let taskID = getNextTaskID(); + const p = new MutablePromise(); + mapTaskCallBack[taskID] = async (body) => { + if (body.success) { + return p.resolve(); + } + else { + let ex = new Error(body.message); + ex.stack = body.stack + '\n' + ex.stack; + return p.reject(ex); + } + }; + worker.postMessage({ + type: "cvr_clearVerifyList", + id: taskID, + instanceID: cvr._instanceID + }); + return p; +} + +// TODO +class CapturedResultReceiver { + constructor() { + /** + * Event triggered when a generic captured result is available, occurring each time an image finishes its processing. + * This event can be used for any result that does not fit into the specific categories of the other callback events. + * @param result The captured result, an instance of `CapturedResult`. + */ + this.onCapturedResultReceived = null; + /** + * Event triggered when the original image result is available. + * This event is used to handle the original image captured by an image source such as Dynamsoft Camera Enhancer. + * @param result The original image result, an instance of `OriginalImageResultItem`. + */ + this.onOriginalImageResultReceived = null; + } +} + +class IntermediateResultReceiver { + constructor() { + this._observedResultUnitTypes = EnumIntermediateResultUnitType.IRUT_ALL; + this._observedTaskMap = new Map(); + this._parameters = { + setObservedResultUnitTypes: (types) => { + this._observedResultUnitTypes = types; + }, + getObservedResultUnitTypes: () => { + return this._observedResultUnitTypes; + }, + isResultUnitTypeObserved: (type) => { + return !!(type & this._observedResultUnitTypes); + }, + addObservedTask: (taskName) => { + this._observedTaskMap.set(taskName, true); + }, + removeObservedTask: (taskName) => { + this._observedTaskMap.set(taskName, false); + }, + isTaskObserved: (taskName) => { + if (this._observedTaskMap.size === 0) + return true; + return !!(this._observedTaskMap.get(taskName)); + } + }; + this.onTaskResultsReceived = null; + // section + this.onPredetectedRegionsReceived = null; + // The remaining callback definitions will be automatically injected when imported into other modules + // stage + this.onColourImageUnitReceived = null; + this.onScaledDownColourImageUnitReceived = null; + this.onGrayscaleImageUnitReceived = null; + this.onTransformedGrayscaleImageUnitReceived = null; + this.onEnhancedGrayscaleImageUnitReceived = null; + this.onBinaryImageUnitReceived = null; + this.onTextureDetectionResultUnitReceived = null; + this.onTextureRemovedGrayscaleImageUnitReceived = null; + this.onTextureRemovedBinaryImageUnitReceived = null; + this.onContoursUnitReceived = null; + this.onLineSegmentsUnitReceived = null; + this.onTextZonesUnitReceived = null; + this.onTextRemovedBinaryImageUnitReceived = null; + this.onShortLinesUnitReceived = null; + // The remaining callback definitions will be automatically injected when imported into other modules + } + /** + * Gets the observed parameters of the intermediate result receiver. Allowing for configuration of intermediate result observation. + * @return The observed parameters, of type ObservationParameters. The default parameters are to observe all intermediate result unit types and all tasks. + */ + getObservationParameters() { + return this._parameters; + } +} + +var EnumPresetTemplate; +(function (EnumPresetTemplate) { + /** + * @brief Versatile function for barcode reading, document detection, or text recognition. + */ + EnumPresetTemplate["PT_DEFAULT"] = "Default"; + /** + * @brief Scans a single barcode. + */ + EnumPresetTemplate["PT_READ_BARCODES"] = "ReadBarcodes_Default"; + /** + * @brief Identifies and reads any text present. + */ + EnumPresetTemplate["PT_RECOGNIZE_TEXT_LINES"] = "RecognizeTextLines_Default"; + /** + * @brief RIdentifies the edges of a document. + */ + EnumPresetTemplate["PT_DETECT_DOCUMENT_BOUNDARIES"] = "DetectDocumentBoundaries_Default"; + /** + * @brief Detects document edges and standardizes its format. + */ + EnumPresetTemplate["PT_DETECT_AND_NORMALIZE_DOCUMENT"] = "DetectAndNormalizeDocument_Default"; + /** + * @brief Adjusts a document to a standard format using detected borders. + */ + EnumPresetTemplate["PT_NORMALIZE_DOCUMENT"] = "NormalizeDocument_Default"; + /** + * @brief Represents a barcode reading mode where speed is prioritized. + * + * In this mode, the barcode reader will optimize for faster barcode detection + * and decoding, sacrificing some level of accuracy and read rate. It is suitable + * for situations where a quick response time is more important than perfect + * barcode recognition. + */ + EnumPresetTemplate["PT_READ_BARCODES_SPEED_FIRST"] = "ReadBarcodes_SpeedFirst"; + /** + * @brief Represents a barcode reading mode where barcode read rate is prioritized. + * + * In this mode, the barcode reader will optimize for higher barcode read rates, + * even if it may sometimes result in reduced accuracy and speed. It is suitable for + * scenarios where maximizing the number of successfully read barcodes is critical. + */ + EnumPresetTemplate["PT_READ_BARCODES_READ_RATE_FIRST"] = "ReadBarcodes_ReadRateFirst"; + /** + * @brief Represents a balanced barcode reading mode. + * + * This mode aims for a reasonable balance between speed and read rate in barcode + * recognition. It is suitable for most common use cases where a compromise between + * speed and read rate is acceptable. + */ + EnumPresetTemplate["PT_READ_BARCODES_BALANCE"] = "ReadBarcodes_Balance"; + /** + * @brief Represents a barcode reading mode for single barcode code detection. + * + * In this mode, the barcode reader will focus on detecting and decoding a single + * barcode code, ignoring any additional codes in the same image. It is efficient + * when the target image has only one barcode. + */ + EnumPresetTemplate["PT_READ_SINGLE_BARCODE"] = "ReadBarcodes_Balanced"; + /** + * @brief Represents a barcode reading mode optimized for dense barcode codes. + * + * This mode is designed to handle dense or closely packed barcode codes where + * accuracy is paramount. It may operate slower than other modes but is suitable + * for challenging scenarios where code density is high. + */ + EnumPresetTemplate["PT_READ_DENSE_BARCODES"] = "ReadDenseBarcodes"; + /** + * @brief Represents a barcode reading mode optimized for distant barcode codes. + * + * This mode is designed to scanning a barcode that is placed far from the device. + */ + EnumPresetTemplate["PT_READ_DISTANT_BARCODES"] = "ReadDistantBarcodes"; + /** + * @brief Represents a text recognition mode focused on recognizing numbers. + */ + EnumPresetTemplate["PT_RECOGNIZE_NUMBERS"] = "RecognizeNumbers"; + /** + * @brief Represents a text recognition mode focused on recognizing alphabetic characters (letters). + * + */ + EnumPresetTemplate["PT_RECOGNIZE_LETTERS"] = "RecognizeLetters"; + /** + * @brief Represents a text recognition mode that combines numbers and alphabetic characters (letters) recognition. + */ + EnumPresetTemplate["PT_RECOGNIZE_NUMBERS_AND_LETTERS"] = "RecognizeNumbersAndLetters"; + /** + * @brief Represents a text recognition mode that combines numbers and uppercase letters recognition. + */ + EnumPresetTemplate["PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS"] = "RecognizeNumbersAndUppercaseLetters"; + /** + * @brief Represents a text recognition mode focused on recognizing uppercase letters. + */ + EnumPresetTemplate["PT_RECOGNIZE_UPPERCASE_LETTERS"] = "RecognizeUppercaseLetters"; +})(EnumPresetTemplate || (EnumPresetTemplate = {})); + +export { CaptureVisionRouter, CaptureVisionRouterModule, CapturedResultReceiver, EnumImageSourceState, EnumPresetTemplate, IntermediateResultReceiver }; diff --git a/dist/dynamsoft-capture-vision-router@2.4.33/dist/cvr.js b/dist/dynamsoft-capture-vision-router@2.4.33/dist/cvr.js new file mode 100644 index 0000000..0e220b4 --- /dev/null +++ b/dist/dynamsoft-capture-vision-router@2.4.33/dist/cvr.js @@ -0,0 +1,11 @@ +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft Capture Vision Router JS Edition + * @website http://www.dynamsoft.com + * @copyright Copyright 2024, Dynamsoft Corporation + * @author Dynamsoft + * @version "2.4.33" + * @fileoverview Dynamsoft JavaScript Library for Capture Vision + * More info on cvr JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/capture-vision-router-module.html + */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("dynamsoft-core")):"function"==typeof define&&define.amd?define(["exports","dynamsoft-core"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).Dynamsoft=e.Dynamsoft||{},e.Dynamsoft.CVR={}),e.Dynamsoft.Core)}(this,(function(e,t){"use strict";function s(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)}function i(e,t,s,i,a){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!a)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?a.call(e,s):a?a.value=s:t.set(e,s),s}"function"==typeof SuppressedError&&SuppressedError;const a=e=>e&&"object"==typeof e&&"function"==typeof e.then,r=(async()=>{})().constructor;class n extends r{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 r(e)),t&&(async()=>{try{const s=await t;e===this._task&&this.resolve(s)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}constructor(e){let t,s;super(((e,i)=>{t=e,s=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",s(e))},this.task=e}}class o{constructor(e){this._cvr=e}async getMaxBufferedItems(){return await new Promise(((e,s)=>{let i=t.getNextTaskID();t.mapTaskCallBack[i]=async t=>{if(t.success)return e(t.count);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,s(e)}},t.worker.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})}))}async setMaxBufferedItems(e){return await new Promise(((s,i)=>{let a=t.getNextTaskID();t.mapTaskCallBack[a]=async e=>{if(e.success)return s();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}},t.worker.postMessage({type:"cvr_setMaxBufferedItems",id:a,instanceID:this._cvr._instanceID,body:{count:e}})}))}async getBufferedCharacterItemSet(){return await new Promise(((e,s)=>{let i=t.getNextTaskID();t.mapTaskCallBack[i]=async t=>{if(t.success)return e(t.itemSet);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,s(e)}},t.worker.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})}))}}var c={onTaskResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onColourImageUnitReceived:!1,onScaledDownColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledUpBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesReceived:!1};const l=e=>{for(let t in e._irrRegistryState)e._irrRegistryState[t]=!1;for(let t of e._intermediateResultReceiverSet)if(t.isDce||t.isFilter)e._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let s in t)e._irrRegistryState[s]||(e._irrRegistryState[s]=!!t[s])};class d{constructor(e){this._irrRegistryState=c,this._intermediateResultReceiverSet=new Set,this._cvr=e}async addResultReceiver(e){if("object"!=typeof e)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(e),l(this);let s=-1,i={};if(!e.isDce&&!e.isFilter){if(!e._observedResultUnitTypes||!e._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");s=e._observedResultUnitTypes,e._observedTaskMap.forEach(((e,t)=>{i[t]=e})),e._observedTaskMap.clear()}return await new Promise(((e,a)=>{let r=t.getNextTaskID();t.mapTaskCallBack[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,a(e)}},t.worker.postMessage({type:"cvr_setIrrRegistry",id:r,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:s.toString(),observedTaskMap:i}})}))}async removeResultReceiver(e){return this._intermediateResultReceiverSet.delete(e),l(this),await new Promise(((e,s)=>{let i=t.getNextTaskID();t.mapTaskCallBack[i]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,s(e)}},t.worker.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})}))}getOriginalImage(){return this._cvr._dsImage}}const u="undefined"==typeof self,m="function"==typeof importScripts,h=(()=>{if(!m){if(!u&&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"./"}})(),g=e=>{if(null==e&&(e="./"),u||m);else{let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e};var p;t.CoreModule.engineResourcePaths.cvr={version:"2.4.33",path:h,isInternal:!0},t.workerAutoResources.cvr={js:!0,wasm:!0,deps:["license","dip"]},t.mapPackageRegister.cvr={};const f="1.4.21";"string"!=typeof t.CoreModule.engineResourcePaths.std&&t.compareVersion(t.CoreModule.engineResourcePaths.std.version,f)<0&&(t.CoreModule.engineResourcePaths.std={version:f,path:g(h+`../../dynamsoft-capture-vision-std@${f}/dist/`),isInternal:!0});const R="2.4.31";(!t.CoreModule.engineResourcePaths.dip||"string"!=typeof t.CoreModule.engineResourcePaths.dip&&t.compareVersion(t.CoreModule.engineResourcePaths.dip.version,R)<0)&&(t.CoreModule.engineResourcePaths.dip={version:R,path:g(h+`../../dynamsoft-image-processing@${R}/dist/`),isInternal:!0});class _{static getVersion(){return this._version}}_._version=`2.4.33(Worker: ${null===(p=t.innerVersions.cvr)||void 0===p?void 0:p.worker}, Wasm: loading...`;const I={barcodeResultItems:{type:t.EnumCapturedResultItemType.CRIT_BARCODE,reveiver:"onDecodedBarcodesReceived",isNeedFilter:!0},textLineResultItems:{type:t.EnumCapturedResultItemType.CRIT_TEXT_LINE,reveiver:"onRecognizedTextLinesReceived",isNeedFilter:!0},detectedQuadResultItems:{type:t.EnumCapturedResultItemType.CRIT_DETECTED_QUAD,reveiver:"onDetectedQuadsReceived",isNeedFilter:!1},normalizedImageResultItems:{type:t.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE,reveiver:"onNormalizedImagesReceived",isNeedFilter:!1},parsedResultItems:{type:t.EnumCapturedResultItemType.CRIT_PARSED_RESULT,reveiver:"onParsedResultsReceived",isNeedFilter:!1}};var v,T,y,C,w,k,E,D,S,b,O,N,M;function L(e,t){if(e&&e.location){const s=e.location.points;for(let e of s)e.x=e.x/t,e.y=e.y/t;L(e.referencedItem,t)}}function U(e){if(e.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}e.EnumImageSourceState=void 0,(v=e.EnumImageSourceState||(e.EnumImageSourceState={}))[v.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",v[v.ISS_EXHAUSTED=1]="ISS_EXHAUSTED";const P={onTaskResultsReceived:()=>{},isFilter:!0};class B{constructor(){this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(t.CoreModule.browserInfo.OS)?2048:4096,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,T.set(this,null),y.set(this,null),C.set(this,null),w.set(this,null),k.set(this,null),E.set(this,new Set),D.set(this,new Set),S.set(this,new Set),b.set(this,0),O.set(this,!1),N.set(this,!1),M.set(this,!1),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return s(this,M,"f")}static async createInstance(){if(!t.mapPackageRegister.license)throw Error("Module `license` is not existed.");await t.mapPackageRegister.license.dynamsoft(),await t.loadWasm(["cvr"]);const e=new B,s=new n;let a=t.getNextTaskID();return t.mapTaskCallBack[a]=async a=>{var r;if(a.success)e._instanceID=a.instanceID,e._currentSettings=JSON.parse(JSON.parse(a.outputSettings).data),_._version=`2.4.33(Worker: ${null===(r=t.innerVersions.cvr)||void 0===r?void 0:r.worker}, Wasm: ${a.version})`,i(e,N,!0,"f"),i(e,w,e.getIntermediateResultManager(),"f"),i(e,N,!1,"f"),s.resolve(e);else{const e=Error(a.message);a.stack&&(e.stack=a.stack),s.reject(e)}},t.worker.postMessage({type:"cvr_createInstance",id:a}),s}async _singleFrameModeCallback(e){for(let t of s(this,E,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:e});const t={bytes:new Uint8Array(e.bytes),width:e.width,height:e.height,stride:e.stride,format:e.format,tag:e.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(t,this._templateName);i.originalImageTag=e.tag;const a={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let e of s(this,E,"f"))if(e.isDce)e.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1});else{for(let t in I){const s=t,r=I[s];e[r.reveiver]&&i[s]&&e[r.reveiver](Object.assign(Object.assign({},a),{[s]:i[s]}))}e.onCapturedResultReceived&&e.onCapturedResultReceived(i)}}setInput(e){if(U(this),e){if(i(this,T,e,"f"),e.isCameraEnhancer){s(this,w,"f")&&(s(this,T,"f")._intermediateResultReceiver.isDce=!0,s(this,w,"f").addResultReceiver(s(this,T,"f")._intermediateResultReceiver));const e=s(this,T,"f").getCameraView();if(e){const t=e._capturedResultReceiver;t.isDce=!0,s(this,E,"f").add(t)}}}else i(this,T,null,"f")}getInput(){return s(this,T,"f")}addImageSourceStateListener(e){if(U(this),"object"!=typeof e)return console.warn("Invalid ISA state listener.");e&&Object.keys(e)&&s(this,D,"f").add(e)}removeImageSourceStateListener(e){return U(this),s(this,D,"f").delete(e)}addResultReceiver(e){if(U(this),"object"!=typeof e)throw new Error("Invalid receiver.");e&&Object.keys(e).length&&(s(this,E,"f").add(e),this._setCrrRegistry())}removeResultReceiver(e){U(this),s(this,E,"f").delete(e),this._setCrrRegistry()}async _setCrrRegistry(){const e={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onParsedResultsReceived:!1};for(let t of s(this,E,"f"))t.isDce||(e.onCapturedResultReceived=!!t.onCapturedResultReceived,e.onDecodedBarcodesReceived=!!t.onDecodedBarcodesReceived,e.onRecognizedTextLinesReceived=!!t.onRecognizedTextLinesReceived,e.onDetectedQuadsReceived=!!t.onDetectedQuadsReceived,e.onNormalizedImagesReceived=!!t.onNormalizedImagesReceived,e.onParsedResultsReceived=!!t.onParsedResultsReceived);const i=new n;let a=t.getNextTaskID();return t.mapTaskCallBack[a]=async e=>{if(e.success)i.resolve();else{let t=new Error(e.message);t.stack=e.stack+"\n"+t.stack,i.reject()}},t.worker.postMessage({type:"cvr_setCrrRegistry",id:a,instanceID:this._instanceID,body:{receiver:JSON.stringify(e)}}),i}async addResultFilter(e){if(U(this),!e||"object"!=typeof e||!Object.keys(e).length)return console.warn("Invalid filter.");s(this,S,"f").add(e),e._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(e){U(this),s(this,S,"f").delete(e),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(s(this,w,"f").removeResultReceiver(P),0===s(this,S,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const e={[t.EnumCapturedResultItemType.CRIT_BARCODE]:!1,[t.EnumCapturedResultItemType.CRIT_TEXT_LINE]:!1,[t.EnumCapturedResultItemType.CRIT_DETECTED_QUAD]:!1,[t.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE]:!1},s={[t.EnumCapturedResultItemType.CRIT_BARCODE]:!1,[t.EnumCapturedResultItemType.CRIT_TEXT_LINE]:!1,[t.EnumCapturedResultItemType.CRIT_DETECTED_QUAD]:!1,[t.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE]:!1};return await A(this,e),void await F(this,s)}for(let e of s(this,S,"f")){if(this._isOpenBarcodeVerify=e.isResultCrossVerificationEnabled(t.EnumCapturedResultItemType.CRIT_BARCODE),this._isOpenLabelVerify=e.isResultCrossVerificationEnabled(t.EnumCapturedResultItemType.CRIT_TEXT_LINE),this._isOpenDetectVerify=e.isResultCrossVerificationEnabled(t.EnumCapturedResultItemType.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=e.isResultCrossVerificationEnabled(t.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE),e.isLatestOverlappingEnabled(t.EnumCapturedResultItemType.CRIT_BARCODE)){[...s(this,w,"f")._intermediateResultReceiverSet.values()].find((e=>e.isFilter))||s(this,w,"f").addResultReceiver(P)}await A(this,e.verificationEnabled),await F(this,e.duplicateFilterEnabled),await x(this,e.duplicateForgetTime)}}async startCapturing(e){var a,r;if(U(this),!this._isPauseScan)return;if(!s(this,T,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");e||(e=B._defaultTemplate);const o=await this.containsTask(e);await t.loadWasm(o);for(let e of s(this,S,"f"))await this.addResultFilter(e);if(o.includes("dlr")&&!(null===(a=t.mapPackageRegister.dlr)||void 0===a?void 0:a.bLoadConfusableCharsData)){const e=t.handleEngineResourcePaths(t.CoreModule.engineResourcePaths);await(null===(r=t.mapPackageRegister.dlr)||void 0===r?void 0:r.loadRecognitionData("ConfusableChars",e.dlr))}if(s(this,T,"f").isCameraEnhancer&&(o.includes("ddn")?s(this,T,"f").setPixelFormat(t.EnumImagePixelFormat.IPF_ABGR_8888):s(this,T,"f").setPixelFormat(t.EnumImagePixelFormat.IPF_GRAYSCALED)),void 0!==s(this,T,"f").singleFrameMode&&"disabled"!==s(this,T,"f").singleFrameMode)return this._templateName=e,void s(this,T,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind);return s(this,T,"f").getColourChannelUsageType()===t.EnumColourChannelUsageType.CCUT_AUTO&&s(this,T,"f").setColourChannelUsageType(o.includes("ddn")?t.EnumColourChannelUsageType.CCUT_FULL_CHANNEL:t.EnumColourChannelUsageType.CCUT_Y_CHANNEL_ONLY),s(this,C,"f")&&s(this,C,"f").isPending?s(this,C,"f"):(i(this,C,new n(((i,a)=>{if(this.disposed)return;let r=t.getNextTaskID();t.mapTaskCallBack[r]=async t=>{if(s(this,C,"f")&&!s(this,C,"f").isFulfilled){if(!t.success){let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,a(e)}this._isPauseScan=!1,this._isOutputOriginalImage=t.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((async()=>{-1!==this._minImageCaptureInterval&&s(this,T,"f").startFetching(),this._loopReadVideo(e),i()}),0)}},t.worker.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:e}})})),"f"),await s(this,C,"f"))}stopCapturing(){U(this),s(this,T,"f")&&(s(this,T,"f").isCameraEnhancer&&void 0!==s(this,T,"f").singleFrameMode&&"disabled"!==s(this,T,"f").singleFrameMode?s(this,T,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(!async function(e){let s=t.getNextTaskID();const i=new n;t.mapTaskCallBack[s]=async e=>{if(e.success)return i.resolve();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i.reject(t)}},t.worker.postMessage({type:"cvr_clearVerifyList",id:s,instanceID:e._instanceID})}(this),s(this,T,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,i(this,C,null,"f"),s(this,T,"f").setColourChannelUsageType(t.EnumColourChannelUsageType.CCUT_AUTO)))}async containsTask(e){return U(this),await new Promise(((s,i)=>{let a=t.getNextTaskID();t.mapTaskCallBack[a]=async e=>{if(e.success)return s(JSON.parse(e.tasks));{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}},t.worker.postMessage({type:"cvr_containsTask",id:a,instanceID:this._instanceID,body:{templateName:e}})}))}async _loopReadVideo(a){if(this.disposed||this._isPauseScan)return;if(i(this,O,!0,"f"),s(this,T,"f").isBufferEmpty())if(s(this,T,"f").hasNextImageToFetch())for(let t of s(this,D,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(e.EnumImageSourceState.ISS_BUFFER_EMPTY);else if(!s(this,T,"f").hasNextImageToFetch())for(let t of s(this,D,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(e.EnumImageSourceState.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||s(this,T,"f").isBufferEmpty())try{s(this,T,"f").isBufferEmpty()&&B._onLog&&B._onLog("buffer is empty so fetch image"),B._onLog&&B._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=s(this,T,"f").fetchImage(),B._onLog&&B._onLog(`DCE: finish fetching a frame: ${Date.now()}`),s(this,T,"f").setImageFetchInterval(this._averageTime)}catch(e){return void this._reRunCurrnetFunc(a)}else if(s(this,T,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=s(this,T,"f").getImage(),this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(a);if(!this._dsImage)return void this._reRunCurrnetFunc(a);for(let e of s(this,E,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:this._dsImage});const r=Date.now();this._captureDsimage(this._dsImage,a).then((async e=>{if(B._onLog&&B._onLog("no js handle time: "+(Date.now()-r)),this._isPauseScan)return void this._reRunCurrnetFunc(a);e.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;const i={originalImageHashId:e.originalImageHashId,originalImageTag:e.originalImageTag,errorCode:e.errorCode,errorString:e.errorString};for(let a of s(this,E,"f"))if(a.isDce){const t=Date.now();if(a.onCapturedResultReceived(e,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify}),B._onLog){const e=Date.now()-t;e>10&&B._onLog(`draw result time: ${e}`)}}else{for(let t in I){const s=t,r=I[s];a[r.reveiver],a[r.reveiver]&&e[s]&&a[r.reveiver](Object.assign(Object.assign({},i),{[s]:e[s].filter((e=>!r.isNeedFilter||!e.isFilter))})),e[s]&&(e[s]=e[s].filter((e=>!r.isNeedFilter||!e.isFilter)))}a.onCapturedResultReceived&&(e.items=e.items.filter((e=>[t.EnumCapturedResultItemType.CRIT_DETECTED_QUAD,t.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE].includes(e.type)||!e.isFilter)),a.onCapturedResultReceived(e))}const n=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-r),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,B._onLog&&(B._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),B._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),B._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),B._onLog(`averageTime: ${this._averageTime}`))),B._onLog){const e=Date.now()-n;e>10&&B._onLog(`fetch image calculate time: ${e}`)}B._onLog&&B._onLog(`time finish decode: ${Date.now()}`),B._onLog&&B._onLog("main time: "+(Date.now()-r)),B._onLog&&B._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(a)}),this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(a)}),Math.max(this._minImageCaptureInterval,0))})).catch((e=>{s(this,T,"f").stopFetching(),e.errorCode&&0===e.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{s(this,T,"f").startFetching(),this._loopReadVideo(a)}),Math.max(this._minImageCaptureInterval,1e3))),"platform error"!==e.message&&setTimeout((()=>{throw e}),0)}))}_reRunCurrnetFunc(e){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(e)}),0)}async capture(e,s){var a,r;U(this),s||(s=B._defaultTemplate);const n=await this.containsTask(s);if(await t.loadWasm(n),n.includes("dlr")&&!(null===(a=t.mapPackageRegister.dlr)||void 0===a?void 0:a.bLoadConfusableCharsData)){const e=t.handleEngineResourcePaths(t.CoreModule.engineResourcePaths);await(null===(r=t.mapPackageRegister.dlr)||void 0===r?void 0:r.loadRecognitionData("ConfusableChars",e.dlr))}let o;if(i(this,O,!1,"f"),t.isDSImageData(e))o=await this._captureDsimage(e,s);else if("string"==typeof e)o="data:image/"==e.substring(0,11)?await this._captureBase64(e,s):await this._captureUrl(e,s);else if(e instanceof Blob)o=await this._captureBlob(e,s);else if(e instanceof HTMLImageElement)o=await this._captureImage(e,s);else if(e instanceof HTMLCanvasElement)o=await this._captureCanvas(e,s);else{if(!(e instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");o=await this._captureVideo(e,s)}return o}async _captureDsimage(e,t){return await this._captureInWorker(e,t)}async _captureUrl(e,s){let i=await t.requestResource(e,"blob");return await this._captureBlob(i,s)}async _captureBase64(e,t){e=e.substring(e.indexOf(",")+1);let s=atob(e),i=s.length,a=new Uint8Array(i);for(;i--;)a[i]=s.charCodeAt(i);return await this._captureBlob(new Blob([a]),t)}async _captureBlob(e,t){let s=null,i=null;if("undefined"!=typeof createImageBitmap)try{s=await createImageBitmap(e)}catch(e){}s||(i=await async function(e){return await new Promise(((t,s)=>{let i=URL.createObjectURL(e),a=new Image;a.src=i,a.onload=()=>{URL.revokeObjectURL(a.dbrObjUrl),t(a)},a.onerror=e=>{s(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let a=await this._captureImage(s||i,t);return s&&s.close(),a}async _captureImage(e,t){let a,r,n=e instanceof HTMLImageElement?e.naturalWidth:e.width,o=e instanceof HTMLImageElement?e.naturalHeight:e.height,c=Math.max(n,o);c>this.maxImageSideLength?(i(this,b,this.maxImageSideLength/c,"f"),a=Math.round(n*s(this,b,"f")),r=Math.round(o*s(this,b,"f"))):(a=n,r=o),s(this,y,"f")||i(this,y,document.createElement("canvas"),"f");const l=s(this,y,"f");l.width===a&&l.height===r||(l.width=a,l.height=r),l.ctx2d||(l.ctx2d=l.getContext("2d",{willReadFrequently:!0}));return l.ctx2d.drawImage(e,0,0,n,o,0,0,a,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._captureCanvas(l,t)}async _captureCanvas(e,t){if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";if([e.width,e.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const s=e.ctx2d||e.getContext("2d",{willReadFrequently:!0}),i={bytes:Uint8Array.from(s.getImageData(0,0,e.width,e.height).data),width:e.width,height:e.height,stride:4*e.width,format:10};return await this._captureInWorker(i,t)}async _captureVideo(e,t){if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";let a,r,n=e.videoWidth,o=e.videoHeight,c=Math.max(n,o);c>this.maxImageSideLength?(i(this,b,this.maxImageSideLength/c,"f"),a=Math.round(n*s(this,b,"f")),r=Math.round(o*s(this,b,"f"))):(a=n,r=o),s(this,y,"f")||i(this,y,document.createElement("canvas"),"f");const l=s(this,y,"f");l.width===a&&l.height===r||(l.width=a,l.height=r),l.ctx2d||(l.ctx2d=l.getContext("2d",{willReadFrequently:!0}));return l.ctx2d.drawImage(e,0,0,n,o,0,0,a,r),await this._captureCanvas(l,t)}async _captureInWorker(e,a){const{bytes:r,width:o,height:c,stride:l,format:d}=e;let u=t.getNextTaskID();const m=new n;return t.mapTaskCallBack[u]=async a=>{var r,n;if(!a.success){let e=new Error(a.message);return e.stack=a.stack+"\n"+e.stack,m.reject(e)}{const o=Date.now();B._onLog&&(B._onLog(`get result time from worker: ${o}`),B._onLog("worker to main time consume: "+(o-a.workerReturnMsgTime)));try{const o=a.captureResult;if(0!==o.errorCode){let e=new Error(o.errorString);return e.errorCode=o.errorCode,m.reject(e)}e.bytes=a.bytes;for(let i of o.items)0!==s(this,b,"f")&&L(i,s(this,b,"f")),i.type===t.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE?i.imageData=e:i.type===t.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE?null===(r=t.mapPackageRegister.ddn)||void 0===r||r.handleNormalizedImageResultItem(i):i.type===t.EnumCapturedResultItemType.CRIT_PARSED_RESULT&&(null===(n=t.mapPackageRegister.dcp)||void 0===n||n.handleParsedResultItem(i));if(s(this,O,"f"))for(let e of s(this,S,"f"))e.onDecodedBarcodesReceived(o),e.onRecognizedTextLinesReceived(o),e.onDetectedQuadsReceived(o),e.onNormalizedImagesReceived(o);for(let e in I){const t=e,s=o.items.filter((e=>e.type===I[t].type));s.length&&(o[e]=s)}if(!this._isPauseScan||!s(this,O,"f")){const t=o.intermediateResult;if(t){let i=0;for(let a of s(this,w,"f")._intermediateResultReceiverSet){i++;for(let r of t){if("onTaskResultsReceived"===r.info.callbackName){for(let t of r.intermediateResultUnits)t.originalImageTag=e.tag?e.tag:null;a[r.info.callbackName]&&a[r.info.callbackName]({intermediateResultUnits:r.intermediateResultUnits},r.info)}else a[r.info.callbackName]&&a[r.info.callbackName](r.result,r.info);i===s(this,w,"f")._intermediateResultReceiverSet.size&&delete r.info.callbackName}}}}return o&&o.hasOwnProperty("intermediateResult")&&delete o.intermediateResult,i(this,b,0,"f"),m.resolve(o)}catch(e){return m.reject(e)}}},B._onLog&&B._onLog(`send buffer to worker: ${Date.now()}`),t.worker.postMessage({type:"cvr_capture",id:u,instanceID:this._instanceID,body:{bytes:r,width:o,height:c,stride:l,format:d,templateName:a||"",isScanner:s(this,O,"f")}},[r.buffer]),m}async initSettings(e){return U(this),e&&["string","object"].includes(typeof e)?("string"==typeof e?e.trimStart().startsWith("{")||(e=await t.requestResource(e,"text")):"object"==typeof e&&(e=JSON.stringify(e)),await new Promise(((s,i)=>{let a=t.getNextTaskID();t.mapTaskCallBack[a]=async a=>{if(a.success){const r=JSON.parse(a.response);if(0!==r.errorCode){let e=new Error(r.errorString?r.errorString:"Init Settings Failed.");return e.errorCode=r.errorCode,i(e)}const n=JSON.parse(e);this._currentSettings=n;let o=[],c=n.CaptureVisionTemplates;for(let e=0;e{let a=t.getNextTaskID();t.mapTaskCallBack[a]=async e=>{if(e.success){const t=JSON.parse(e.response);if(0!==t.errorCode){let e=new Error(t.errorString);return e.errorCode=t.errorCode,i(e)}return s(JSON.parse(t.data))}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}},t.worker.postMessage({type:"cvr_outputSettings",id:a,instanceID:this._instanceID,body:{templateName:e||"*"}})}))}async outputSettingsToFile(e,t,s){const i=await this.outputSettings(e),a=new Blob([JSON.stringify(i,null,2,(function(e,t){return t instanceof Array?JSON.stringify(t):t}),2)],{type:"application/json"});if(s){const e=document.createElement("a");e.href=URL.createObjectURL(a),t.endsWith(".json")&&(t=t.replace(".json","")),e.download=`${t}.json`,e.onclick=()=>{setTimeout((()=>{URL.revokeObjectURL(e.href)}),500)},e.click()}return a}async getTemplateNames(){return U(this),await new Promise(((e,s)=>{let i=t.getNextTaskID();t.mapTaskCallBack[i]=async t=>{if(t.success){const i=JSON.parse(t.response);if(0!==i.errorCode){let e=new Error(i.errorString);return e.errorCode=i.errorCode,s(e)}return e(JSON.parse(i.data))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,s(e)}},t.worker.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})}))}async getSimplifiedSettings(e){U(this),e||(e=this._currentSettings.CaptureVisionTemplates[0].Name);const s=await this.containsTask(e);return await t.loadWasm(s),await new Promise(((s,i)=>{let a=t.getNextTaskID();t.mapTaskCallBack[a]=async e=>{if(e.success){const t=JSON.parse(e.response);if(0!==t.errorCode){let e=new Error(t.errorString);return e.errorCode=t.errorCode,i(e)}const a=JSON.parse(t.data,((e,t)=>"barcodeFormatIds"===e?BigInt(t):t));return a.minImageCaptureInterval=this._minImageCaptureInterval,s(a)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}},t.worker.postMessage({type:"cvr_getSimplifiedSettings",id:a,instanceID:this._instanceID,body:{templateName:e}})}))}async updateSettings(e,s){U(this);const i=await this.containsTask(e);return await t.loadWasm(i),await new Promise(((i,a)=>{let r=t.getNextTaskID();t.mapTaskCallBack[r]=async e=>{if(e.success){const t=JSON.parse(e.response);if(s.minImageCaptureInterval&&s.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=s.minImageCaptureInterval),this._isOutputOriginalImage=e.isOutputOriginalImage,0!==t.errorCode){let e=new Error(t.errorString?t.errorString:"Update Settings Failed.");return e.errorCode=t.errorCode,a(e)}return this._currentSettings=await this.outputSettings("*"),i(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},t.worker.postMessage({type:"cvr_updateSettings",id:r,instanceID:this._instanceID,body:{settings:s,templateName:e}})}))}async resetSettings(){return U(this),await new Promise(((e,s)=>{let i=t.getNextTaskID();t.mapTaskCallBack[i]=async t=>{if(t.success){const i=JSON.parse(t.response);if(0!==i.errorCode){let e=new Error(i.errorString?i.errorString:"Reset Settings Failed.");return e.errorCode=i.errorCode,s(e)}return this._currentSettings=await this.outputSettings("*"),e(i)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,s(e)}},t.worker.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})}))}getBufferedItemsManager(){return s(this,k,"f")||i(this,k,new o(this),"f"),s(this,k,"f")}getIntermediateResultManager(){if(U(this),!s(this,N,"f")&&0!==t.CoreModule.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return s(this,w,"f")||i(this,w,new d(this),"f"),s(this,w,"f")}async parseRequiredResources(e){return U(this),await new Promise(((s,i)=>{let a=t.getNextTaskID();t.mapTaskCallBack[a]=async e=>{if(e.success)return s(JSON.parse(e.resources));{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}},t.worker.postMessage({type:"cvr_parseRequiredResources",id:a,instanceID:this._instanceID,body:{templateName:e}})}))}async dispose(){U(this),s(this,C,"f")&&this.stopCapturing(),i(this,T,null,"f"),s(this,E,"f").clear(),s(this,D,"f").clear(),s(this,S,"f").clear(),s(this,w,"f")._intermediateResultReceiverSet.clear(),i(this,M,!0,"f");let e=t.getNextTaskID();t.mapTaskCallBack[e]=e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}},t.worker.postMessage({type:"cvr_dispose",id:e,instanceID:this._instanceID})}_getInternalData(){return{isa:s(this,T,"f"),promiseStartScan:s(this,C,"f"),intermediateResultManager:s(this,w,"f"),bufferdItemsManager:s(this,k,"f"),resultReceiverSet:s(this,E,"f"),isaStateListenerSet:s(this,D,"f"),resultFilterSet:s(this,S,"f"),compressRate:s(this,b,"f"),canvas:s(this,y,"f"),isScanner:s(this,O,"f"),innerUseTag:s(this,N,"f"),isDestroyed:s(this,M,"f")}}async _getWasmFilterState(){return await new Promise(((e,s)=>{let i=t.getNextTaskID();t.mapTaskCallBack[i]=async t=>{if(t.success){const s=JSON.parse(t.response);return e(s)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,s(e)}},t.worker.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})}))}}async function A(e,s){return U(e),await new Promise(((i,a)=>{let r=t.getNextTaskID();t.mapTaskCallBack[r]=async e=>{if(e.success)return i(e.result);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},t.worker.postMessage({type:"cvr_enableResultCrossVerification",id:r,instanceID:e._instanceID,body:{verificationEnabled:s}})}))}async function F(e,s){return U(e),await new Promise(((i,a)=>{let r=t.getNextTaskID();t.mapTaskCallBack[r]=async e=>{if(e.success)return i(e.result);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},t.worker.postMessage({type:"cvr_enableResultDeduplication",id:r,instanceID:e._instanceID,body:{duplicateFilterEnabled:s}})}))}async function x(e,s){return U(e),await new Promise(((i,a)=>{let r=t.getNextTaskID();t.mapTaskCallBack[r]=async e=>{if(e.success)return i(e.result);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},t.worker.postMessage({type:"cvr_setDuplicateForgetTime",id:r,instanceID:e._instanceID,body:{duplicateForgetTime:s}})}))}T=new WeakMap,y=new WeakMap,C=new WeakMap,w=new WeakMap,k=new WeakMap,E=new WeakMap,D=new WeakMap,S=new WeakMap,b=new WeakMap,O=new WeakMap,N=new WeakMap,M=new WeakMap,B._defaultTemplate="Default";var V;e.EnumPresetTemplate=void 0,(V=e.EnumPresetTemplate||(e.EnumPresetTemplate={})).PT_DEFAULT="Default",V.PT_READ_BARCODES="ReadBarcodes_Default",V.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",V.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",V.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",V.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",V.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",V.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",V.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",V.PT_READ_SINGLE_BARCODE="ReadBarcodes_Balanced",V.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",V.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",V.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",V.PT_RECOGNIZE_LETTERS="RecognizeLetters",V.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",V.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",V.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters",e.CaptureVisionRouter=B,e.CaptureVisionRouterModule=_,e.CapturedResultReceiver=class{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}},e.IntermediateResultReceiver=class{constructor(){this._observedResultUnitTypes=t.EnumIntermediateResultUnitType.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:e=>{this._observedResultUnitTypes=e},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:e=>!!(e&this._observedResultUnitTypes),addObservedTask:e=>{this._observedTaskMap.set(e,!0)},removeObservedTask:e=>{this._observedTaskMap.set(e,!1)},isTaskObserved:e=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(e)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledDownColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}}})); diff --git a/dist/dynamsoft-capture-vision-router@2.4.33/dist/cvr.worker.js b/dist/dynamsoft-capture-vision-router@2.4.33/dist/cvr.worker.js new file mode 100644 index 0000000..d1e4e30 --- /dev/null +++ b/dist/dynamsoft-capture-vision-router@2.4.33/dist/cvr.worker.js @@ -0,0 +1,21 @@ +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft Capture Vision Router JS Edition + * @website http://www.dynamsoft.com + * @copyright Copyright 2024, Dynamsoft Corporation + * @author Dynamsoft + * @version "2.4.33" + * @fileoverview Dynamsoft JavaScript Library for Capture Vision + * More info on cvr JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/capture-vision-router-module.html + */ +!function(){"use strict"; +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft Core JS Edition + * @website https://www.dynamsoft.com + * @copyright Copyright 2024, Dynamsoft Corporation + * @author Dynamsoft + * @version 3.4.30 + * @fileoverview Dynamsoft JavaScript Library for Core + * More info on Dynamsoft Core JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/core/core-module.html + */var _,e,E,t;"function"==typeof SuppressedError&&SuppressedError,(t=_||(_={}))[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE",function(_){_[_.CCUT_AUTO=0]="CCUT_AUTO",_[_.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",_[_.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",_[_.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",_[_.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",_[_.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(e||(e={})),function(_){_[_.IPF_BINARY=0]="IPF_BINARY",_[_.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",_[_.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",_[_.IPF_NV21=3]="IPF_NV21",_[_.IPF_RGB_565=4]="IPF_RGB_565",_[_.IPF_RGB_555=5]="IPF_RGB_555",_[_.IPF_RGB_888=6]="IPF_RGB_888",_[_.IPF_ARGB_8888=7]="IPF_ARGB_8888",_[_.IPF_RGB_161616=8]="IPF_RGB_161616",_[_.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",_[_.IPF_ABGR_8888=10]="IPF_ABGR_8888",_[_.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",_[_.IPF_BGR_888=12]="IPF_BGR_888",_[_.IPF_BINARY_8=13]="IPF_BINARY_8",_[_.IPF_NV12=14]="IPF_NV12",_[_.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(E||(E={}));const s=_=>"number"==typeof _&&!Number.isNaN(_),I=_=>null!==_&&"object"==typeof _&&!Array.isArray(_),r=_=>!(!(_=>!(!I(_)||!s(_.width)||_.width<=0||!s(_.height)||_.height<=0||!s(_.stride)||_.stride<=0||!("format"in _)||"tag"in _&&!n(_.tag)))(_)||!s(_.bytes.length)&&!s(_.bytes.ptr)),n=_=>null===_||!!I(_)&&!!s(_.imageId)&&"type"in _,C="undefined"==typeof self,T="function"==typeof importScripts,a=(()=>{if(!T){if(!C&&document.currentScript){let _=document.currentScript.src,e=_.indexOf("?");if(-1!=e)_=_.substring(0,e);else{let e=_.indexOf("#");-1!=e&&(_=_.substring(0,e))}return _.substring(0,_.lastIndexOf("/")+1)}return"./"}})();let A,i,R,N,D;async function O(_,e){return await new Promise(((E,t)=>{let s=new XMLHttpRequest;s.open("GET",_,!0),s.responseType=e,s.send(),s.onloadend=async()=>{s.status<200||s.status>=300?t(_+" "+s.status):E(s.response)},s.onerror=()=>{t(new Error("Network Error: "+s.statusText))}}))}var L,o,S,c,l,m,p,u,d;"undefined"!=typeof navigator&&(A=navigator,i=A.userAgent,R=A.platform,N=A.mediaDevices),function(){if(!C){const _={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:A.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:R,search:"Win"},Mac:{str:R},Linux:{str:R}};let E="unknownBrowser",t=0,s="unknownOS";for(let e in _){const s=_[e]||{};let I=s.str||i,r=s.search||e,n=s.verStr||i,C=s.verSearch||e;if(C instanceof Array||(C=[C]),-1!=I.indexOf(r)){E=e;for(let _ of C){let e=n.indexOf(_);if(-1!=e){t=parseFloat(n.substring(e+_.length+1));break}}break}}for(let _ in e){const E=e[_]||{};let t=E.str||i,I=E.search||_;if(-1!=t.indexOf(I)){s=_;break}}"Linux"==s&&-1!=i.indexOf("Windows NT")&&(s="HarmonyOS"),D={browser:E,version:t,OS:s}}C&&(D={browser:"ssr",version:0,OS:"ssr"})}(),N&&N.getUserMedia,"Chrome"===D.browser&&D.version>66||"Safari"===D.browser&&D.version>13||"OPR"===D.browser&&D.version>43||"Edge"===D.browser&&D.version,(_=>{if(null==_&&(_="./"),C||T);else{let e=document.createElement("a");e.href=_,_=e.href}_.endsWith("/")||(_+="/")})(a+"../../dynamsoft-capture-vision-std@1.4.10/dist/"),function(_){_[_.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",_[_.CRIT_BARCODE=2]="CRIT_BARCODE",_[_.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",_[_.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",_[_.CRIT_NORMALIZED_IMAGE=16]="CRIT_NORMALIZED_IMAGE",_[_.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT"}(L||(L={})),function(_){_[_.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",_[_.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",_[_.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",_[_.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(o||(o={})),function(_){_[_.EC_OK=0]="EC_OK",_[_.EC_UNKNOWN=-1e4]="EC_UNKNOWN",_[_.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",_[_.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",_[_.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",_[_.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",_[_.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",_[_.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",_[_.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",_[_.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",_[_.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",_[_.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",_[_.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",_[_.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",_[_.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",_[_.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",_[_.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",_[_.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",_[_.EC_TIMEOUT=-10026]="EC_TIMEOUT",_[_.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",_[_.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",_[_.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",_[_.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",_[_.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",_[_.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",_[_.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",_[_.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",_[_.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",_[_.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",_[_.EC_RESERVED_INFO_NOT_MATCH=-10040]="EC_RESERVED_INFO_NOT_MATCH",_[_.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",_[_.EC_REQUEST_FAILED=-10044]="EC_REQUEST_FAILED",_[_.EC_LICENSE_INIT_FAILED=-10045]="EC_LICENSE_INIT_FAILED",_[_.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",_[_.EC_LICENSE_CONTENT_INVALID=-10052]="EC_LICENSE_CONTENT_INVALID",_[_.EC_LICENSE_KEY_INVALID=-10053]="EC_LICENSE_KEY_INVALID",_[_.EC_LICENSE_DEVICE_RUNS_OUT=-10054]="EC_LICENSE_DEVICE_RUNS_OUT",_[_.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",_[_.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",_[_.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",_[_.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",_[_.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",_[_.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",_[_.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",_[_.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",_[_.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",_[_.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",_[_.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",_[_.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",_[_.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",_[_.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",_[_.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",_[_.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",_[_.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",_[_.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",_[_.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",_[_.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",_[_.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",_[_.EC_HANDSHAKE_CODE_INVALID=-20001]="EC_HANDSHAKE_CODE_INVALID",_[_.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",_[_.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",_[_.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",_[_.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",_[_.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",_[_.EC_LICENSE_INIT_SEQUENCE_FAILED=-20009]="EC_LICENSE_INIT_SEQUENCE_FAILED",_[_.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",_[_.EC_FAILED_TO_REACH_DLS=-20200]="EC_FAILED_TO_REACH_DLS",_[_.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",_[_.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",_[_.EC_QR_LICENSE_INVALID=-30016]="EC_QR_LICENSE_INVALID",_[_.EC_1D_LICENSE_INVALID=-30017]="EC_1D_LICENSE_INVALID",_[_.EC_PDF417_LICENSE_INVALID=-30019]="EC_PDF417_LICENSE_INVALID",_[_.EC_DATAMATRIX_LICENSE_INVALID=-30020]="EC_DATAMATRIX_LICENSE_INVALID",_[_.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",_[_.EC_AZTEC_LICENSE_INVALID=-30041]="EC_AZTEC_LICENSE_INVALID",_[_.EC_PATCHCODE_LICENSE_INVALID=-30046]="EC_PATCHCODE_LICENSE_INVALID",_[_.EC_POSTALCODE_LICENSE_INVALID=-30047]="EC_POSTALCODE_LICENSE_INVALID",_[_.EC_DPM_LICENSE_INVALID=-30048]="EC_DPM_LICENSE_INVALID",_[_.EC_FRAME_DECODING_THREAD_EXISTS=-30049]="EC_FRAME_DECODING_THREAD_EXISTS",_[_.EC_STOP_DECODING_THREAD_FAILED=-30050]="EC_STOP_DECODING_THREAD_FAILED",_[_.EC_MAXICODE_LICENSE_INVALID=-30057]="EC_MAXICODE_LICENSE_INVALID",_[_.EC_GS1_DATABAR_LICENSE_INVALID=-30058]="EC_GS1_DATABAR_LICENSE_INVALID",_[_.EC_GS1_COMPOSITE_LICENSE_INVALID=-30059]="EC_GS1_COMPOSITE_LICENSE_INVALID",_[_.EC_DOTCODE_LICENSE_INVALID=-30061]="EC_DOTCODE_LICENSE_INVALID",_[_.EC_PHARMACODE_LICENSE_INVALID=-30062]="EC_PHARMACODE_LICENSE_INVALID",_[_.EC_CHARACTER_MODEL_FILE_NOT_FOUND=-40100]="EC_CHARACTER_MODEL_FILE_NOT_FOUND",_[_.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",_[_.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",_[_.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",_[_.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",_[_.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",_[_.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",_[_.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",_[_.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",_[_.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",_[_.EC_ZA_DL_LICENSE_INVALID=-90006]="EC_ZA_DL_LICENSE_INVALID",_[_.EC_AAMVA_DL_ID_LICENSE_INVALID=-90007]="EC_AAMVA_DL_ID_LICENSE_INVALID",_[_.EC_AADHAAR_LICENSE_INVALID=-90008]="EC_AADHAAR_LICENSE_INVALID",_[_.EC_MRTD_LICENSE_INVALID=-90009]="EC_MRTD_LICENSE_INVALID",_[_.EC_VIN_LICENSE_INVALID=-90010]="EC_VIN_LICENSE_INVALID",_[_.EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID=-90011]="EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID",_[_.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",_[_.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",_[_.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",_[_.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",_[_.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(S||(S={})),function(_){_[_.GEM_SKIP=0]="GEM_SKIP",_[_.GEM_AUTO=1]="GEM_AUTO",_[_.GEM_GENERAL=2]="GEM_GENERAL",_[_.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",_[_.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",_[_.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",_[_.GEM_REV=-2147483648]="GEM_REV"}(c||(c={})),function(_){_[_.GTM_SKIP=0]="GTM_SKIP",_[_.GTM_INVERTED=1]="GTM_INVERTED",_[_.GTM_ORIGINAL=2]="GTM_ORIGINAL",_[_.GTM_AUTO=4]="GTM_AUTO",_[_.GTM_REV=-2147483648]="GTM_REV"}(l||(l={})),function(_){_[_.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",_[_.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(m||(m={})),function(_){_[_.PDFRM_VECTOR=1]="PDFRM_VECTOR",_[_.PDFRM_RASTER=2]="PDFRM_RASTER",_[_.PDFRM_REV=-2147483648]="PDFRM_REV"}(p||(p={})),function(_){_[_.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",_[_.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(u||(u={})),function(_){_[_.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",_[_.CVS_PASSED=1]="CVS_PASSED",_[_.CVS_FAILED=2]="CVS_FAILED"}(d||(d={}));const U={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_DOWN_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_UP_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_NORMALIZED_IMAGES:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var M,g;function F(_,e){for(let E of _)if(E.result){if([U.IRUT_BINARY_IMAGE,U.IRUT_COLOUR_IMAGE,U.IRUT_COMPLEMENTED_BARCODE_IMAGE,U.IRUT_ENHANCED_GRAYSCALE_IMAGE,U.IRUT_GRAYSCALE_IMAGE,U.IRUT_SCALED_DOWN_COLOUR_IMAGE,U.IRUT_SCALED_UP_BARCODE_IMAGE,U.IRUT_TEXTURE_REMOVED_BINARY_IMAGE,U.IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE,U.IRUT_TEXT_REMOVED_BINARY_IMAGE,U.IRUT_TRANSOFORMED_GRAYSCALE_IMAGE].includes(BigInt(E.result.unitType))){let _=E.result.imageData.bytes;_&&(_=new Uint8Array(new Uint8Array(e.buffer,_.ptr,_.length)),E.result.imageData.bytes=_)}else if([U.IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE].includes(BigInt(E.result.unitType))){let _=E.result.deformationResistedBarcode.imageData.bytes;_&&(_=new Uint8Array(new Uint8Array(e.buffer,_.ptr,_.length)),E.result.deformationResistedBarcode.imageData.bytes=_)}else if([U.IRUT_CONTOURS].includes(BigInt(E.result.unitType))){let _=E.result.contours,t=E.result.contoursOffset;if(_&&t){_=new Uint8Array(new Uint8Array(e.buffer,_.ptr,_.length)),t=new Uint8Array(new Uint8Array(e.buffer,t.ptr,t.length));const s=new DataView(_.buffer),I=[];for(let e=0;e<_.length;e+=4)I.push(s.getInt32(e,!0));const r=new DataView(t.buffer),n=[0];for(let _=0;_{ep();const E=JSON.parse(UTF8ToString(wasmImports.emscripten_bind_CvrWasm_ParseRequiredResources_1(_,es(e.templateName))));for(let _=0;_{try{let _=wasmImports.emscripten_bind_CvrWasm_CvrWasm_0();engineResourcePaths.dbr&&(P=await O(engineResourcePaths.dbr+"DBR-PresetTemplates.json","text"),ep(),wasmImports.emscripten_bind_CvrWasm_AppendParameterContent_1(_,es(P))),engineResourcePaths.dlr&&(f=await O(engineResourcePaths.dlr+"DLR-PresetTemplates.json","text"),ep(),wasmImports.emscripten_bind_CvrWasm_AppendParameterContent_1(_,es(f))),engineResourcePaths.ddn&&(G=await O(engineResourcePaths.ddn+"DDN-PresetTemplates.json","text"),ep(),wasmImports.emscripten_bind_CvrWasm_AppendParameterContent_1(_,es(G))),wasmImports.emscripten_bind_CvrWasm_InitParameter_0(_),ep();const E=UTF8ToString(wasmImports.emscripten_bind_CvrWasm_OutputSettings_1(_,es("*")));let t=JSON.parse(UTF8ToString(wasmImports.emscripten_bind_CoreWasm_GetModuleVersion_0())).CVR;h.add(_),handleTaskRes(e,{instanceID:_,version:t,outputSettings:E})}catch(_){console.log(_),handleTaskErr(e,_)}},cvr_initSettings:async(_,e,E)=>{let t;try{const s=_.settings;ep(),t=UTF8ToString(wasmImports.emscripten_bind_CvrWasm_InitSettings_1(E,es(s))),handleTaskRes(e,{success:!0,response:t})}catch(_){handleTaskErr(e,_)}},cvr_setCrrRegistry:async(_,e,E)=>{try{h.has(E)&&(ep(),wasmImports.emscripten_bind_CvrWasm_SetCrrRegistry_1(E,es(_.receiver))),handleTaskRes(e,{success:!0})}catch(_){handleTaskErr(e,_)}},cvr_startCapturing:async(_,e,E)=>{let t=!1;try{ep();const s=JSON.parse(UTF8ToString(wasmImports.emscripten_bind_CvrWasm_OutputSettings_1(E,es(_.templateName))));if(s&&0!==s.errorCode)throw new Error(s.errorString);t=1===JSON.parse(s.data).CaptureVisionTemplates[0].OutputOriginalImage,await V(E,_),handleTaskRes(e,{success:!0,isOutputOriginalImage:t})}catch(_){handleTaskErr(e,_)}},cvr_parseRequiredResources:async(_,e,E)=>{let t;try{ep(),t=UTF8ToString(wasmImports.emscripten_bind_CvrWasm_ParseRequiredResources_1(E,es(_.templateName))),handleTaskRes(e,{success:!0,resources:t})}catch(_){handleTaskErr(e,_)}},cvr_clearVerifyList:(_,e,E)=>{try{wasmImports.emscripten_bind_CvrWasm_ClearVerifyList_0(E),handleTaskRes(e,{success:!0})}catch(_){handleTaskErr(e,_)}},cvr_getIntermediateResult:(_,e,E)=>{let t={};try{t=JSON.parse(UTF8ToString(wasmImports.emscripten_bind_CvrWasm_GetIntermediateResult_0(E)),((_,e)=>["format","possibleFormats","unitType"].includes(_)?BigInt(e):e)),t&&F(t,HEAP8)}catch(_){handleTaskErr(e,_)}handleTaskRes(e,{success:!0,result:t})},cvr_setObservedResultUnitTypes:(_,e,E)=>{try{ep(),wasmImports.emscripten_bind_CvrWasm_SetObservedResultUnitTypes_1(E,es(_.types))}catch(_){handleTaskErr(e,_)}handleTaskRes(e,{success:!0})},cvr_getObservedResultUnitTypes:(_,e,E)=>{let t;try{ep(),t=UTF8ToString(wasmImports.emscripten_bind_CvrWasm_GetObservedResultUnitTypes_0(E))}catch(_){handleTaskErr(e,_)}handleTaskRes(e,{success:!0,result:t})},cvr_isResultUnitTypeObserved:(_,e,E)=>{let t;try{ep(),t=wasmImports.emscripten_bind_CvrWasm_IsResultUnitTypeObserved_1(E,es(_.type))}catch(_){handleTaskErr(e,_)}handleTaskRes(e,{success:!0,result:t})},cvr_capture:async(_,e,E)=>{let t,s,I;await checkAndReauth(),log(`time worker get msg: ${Date.now()}`);try{let e=Date.now();await V(E,_),log("appendResourceTime: "+(Date.now()-e)),y&&(wasmImports.emscripten_bind_Destory_CImageData(y),y=null),y=wasmImports.emscripten_bind_Create_CImageData(_.bytes.length,setBufferIntoWasm(_.bytes,0),_.width,_.height,_.stride,_.format,0);let n=Date.now();log(`start worker capture: ${n}`),ep(),s=UTF8ToString(wasmImports.emscripten_bind_CvrWasm_Capture_3(E,y,es(_.templateName),_.isScanner));let C=Date.now();log("worker time: "+(C-n)),log(`end worker capture: ${C}`),s=JSON.parse(s,(function(_,e){return"format"!==_||r(this)?e:BigInt(e)}));let T=Date.now();log("capture result parsed: "+(T-C));for(let _=0;_["format","possibleFormats","unitType"].includes(_)?BigInt(e):e)),t&&F(t,HEAP8),s.intermediateResult=t;let A=Date.now();log("get intermediate result: "+(A-a)),log("after capture handle time: "+(Date.now()-C))}catch(_){return void handleTaskErr(e,_)}const n=Date.now();log(`time worker return msg: ${n}`),postMessage({type:"task",id:e,body:{success:!0,bytes:_.bytes,captureResult:s,workerReturnMsgTime:n}},[_.bytes.buffer])},cvr_outputSettings:async(_,e,E)=>{let t;try{ep(),t=UTF8ToString(wasmImports.emscripten_bind_CvrWasm_OutputSettings_1(E,es(_.templateName))),handleTaskRes(e,{success:!0,response:t})}catch(_){handleTaskErr(e,_)}},cvr_getTemplateNames:async(_,e,E)=>{let t;try{ep(),t=UTF8ToString(wasmImports.emscripten_bind_CvrWasm_GetTemplateNames_0(E)),handleTaskRes(e,{success:!0,response:t})}catch(_){console.log(_),handleTaskErr(e,_)}},cvr_getSimplifiedSettings:async(_,e,E)=>{let t;try{ep(),t=UTF8ToString(wasmImports.emscripten_bind_CvrWasm_GetSimplifiedSettings_1(E,es(_.templateName))),handleTaskRes(e,{success:!0,response:t})}catch(_){handleTaskErr(e,_)}},cvr_updateSettings:async(_,e,E)=>{let t,s=!1;try{let I=_.settings,r=_.templateName;"object"==typeof I&&I.hasOwnProperty("barcodeSettings")&&(I.barcodeSettings.barcodeFormatIds=I.barcodeSettings.barcodeFormatIds.toString()),ep(),t=UTF8ToString(wasmImports.emscripten_bind_CvrWasm_UpdateSettings_2(E,es(r),es(JSON.stringify(I)))),ep();const n=JSON.parse(UTF8ToString(wasmImports.emscripten_bind_CvrWasm_OutputSettings_1(E,es(r))));if(!n.errorCode){s=1===JSON.parse(n.data).CaptureVisionTemplates[0].OutputOriginalImage}handleTaskRes(e,{success:!0,response:t,isOutputOriginalImage:s})}catch(_){handleTaskErr(e,_)}},cvr_resetSettings:async(_,e,E)=>{let t;try{wasmImports.emscripten_bind_CvrWasm_ResetSettings_0(E),ep(),P&&wasmImports.emscripten_bind_CvrWasm_AppendParameterContent_1(E,es(P)),ep(),f&&wasmImports.emscripten_bind_CvrWasm_AppendParameterContent_1(E,es(f)),ep(),G&&wasmImports.emscripten_bind_CvrWasm_AppendParameterContent_1(E,es(G)),ep(),t=UTF8ToString(wasmImports.emscripten_bind_CvrWasm_InitParameter_0(E)),handleTaskRes(e,{success:!0,response:t})}catch(_){handleTaskErr(e,_)}},cvr_getMaxBufferedItems:async(_,e,E)=>{let t;try{t=wasmImports.emscripten_bind_CvrWasm_GetMaxBufferedItems_0(E),handleTaskRes(e,{success:!0,count:t})}catch(_){handleTaskErr(e,_)}},cvr_setMaxBufferedItems:async(_,e,E)=>{let t;try{t=wasmImports.emscripten_bind_CvrWasm_SetMaxBufferedItems_1(E,_.count),handleTaskRes(e,{success:!0})}catch(_){handleTaskErr(e,_)}},cvr_getBufferedCharacterItemSet:async(_,e,E)=>{let t;try{t=JSON.parse(UTF8ToString(wasmImports.emscripten_bind_CvrWasm_GetBufferedCharacterItemSet_0(E)));for(let _ of t.items){let e=_.image.bytes;e&&(e=new Uint8Array(new Uint8Array(HEAP8.buffer,e.ptr,e.length)),_.image.bytes=e)}for(let _ of t.characterClusters){let e=_.mean.image.bytes;e&&(e=new Uint8Array(new Uint8Array(HEAP8.buffer,e.ptr,e.length)),_.mean.image.bytes=e)}handleTaskRes(e,{success:!0,itemSet:t})}catch(_){handleTaskErr(e,_)}},cvr_setIrrRegistry:async(_,e,E)=>{try{if(h.has(E)){ep(),wasmImports.emscripten_bind_CvrWasm_SetIrrRegistry_1(E,es(JSON.stringify(_.receiverObj))),_.observedResultUnitTypes&&"-1"!==_.observedResultUnitTypes&&(ep(),wasmImports.emscripten_bind_CvrWasm_SetObservedResultUnitTypes_1(E,es(_.observedResultUnitTypes)));for(let e in _.observedTaskMap)_.observedTaskMap[e]?(ep(),wasmImports.emscripten_bind_CvrWasm_AddObservedTask_1(E,es(e))):(ep(),wasmImports.emscripten_bind_CvrWasm_RemoveObservedTask_1(E,es(e)))}handleTaskRes(e,{success:!0})}catch(_){handleTaskErr(e,_)}},cvr_enableResultCrossVerification:async(_,e,E)=>{let t;try{for(let e in _.verificationEnabled)t=wasmImports.emscripten_bind_CvrWasm_EnableResultCrossVerification_2(E,Number(e),_.verificationEnabled[e]);handleTaskRes(e,{success:!0,result:t})}catch(_){handleTaskErr(e,_)}},cvr_enableResultDeduplication:async(_,e,E)=>{let t;try{for(let e in _.duplicateFilterEnabled)t=wasmImports.emscripten_bind_CvrWasm_EnableResultDeduplication_2(E,Number(e),_.duplicateFilterEnabled[e]);handleTaskRes(e,{success:!0,result:t})}catch(_){handleTaskErr(e,_)}},cvr_setDuplicateForgetTime:async(_,e,E)=>{let t;try{for(let e in _.duplicateForgetTime)t=wasmImports.emscripten_bind_CvrWasm_SetDuplicateForgetTime_2(E,Number(e),_.duplicateForgetTime[e]);handleTaskRes(e,{success:!0,result:t})}catch(_){handleTaskErr(e,_)}},cvr_getDuplicateForgetTime:async(_,e,E)=>{let t;try{t=wasmImports.emscripten_bind_CvrWasm_GetDuplicateForgetTime_1(E,_.type),handleTaskRes(e,{success:!0,time:t})}catch(_){handleTaskErr(e,_)}},cvr_containsTask:async(_,e,E)=>{try{ep();const t=UTF8ToString(wasmImports.emscripten_bind_CvrWasm_ContainsTask_1(E,es(_.templateName)));handleTaskRes(e,{success:!0,tasks:t})}catch(_){handleTaskErr(e,_)}},cvr_dispose:async(_,e,E)=>{try{h.delete(E),wasmImports.emscripten_bind_Destory_CImageData(y),y=null,wasmImports.emscripten_bind_CvrWasm___destroy___0(E),handleTaskRes(e,{success:!0})}catch(_){handleTaskErr(e,_)}},cvr_getWasmFilterState:async(_,e,E)=>{let t;try{t=UTF8ToString(wasmImports.emscripten_bind_CvrWasm_GetFilterState_0(E)),handleTaskRes(e,{success:!0,response:t})}catch(_){handleTaskErr(e,_)}}})}(); diff --git a/dist/dynamsoft-capture-vision-std@1.4.21/dist/dynamsoft-barcode-reader-bundle.js b/dist/dynamsoft-capture-vision-std@1.4.21/dist/dynamsoft-barcode-reader-bundle.js new file mode 100644 index 0000000..60ecac5 --- /dev/null +++ b/dist/dynamsoft-capture-vision-std@1.4.21/dist/dynamsoft-barcode-reader-bundle.js @@ -0,0 +1 @@ +"use strict"; var readAsync, readBinary, Module = void 0 !== Module ? Module : {}, ENVIRONMENT_IS_WEB = !1, ENVIRONMENT_IS_WORKER = !0, ENVIRONMENT_IS_NODE = !1, moduleOverrides = Object.assign({}, Module), thisProgram = "./this.program", quit_ = (e, r) => { throw r }, scriptDirectory = ""; function locateFile(e) { return Module.locateFile ? Module.locateFile(e, scriptDirectory) : scriptDirectory + e } (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) && (ENVIRONMENT_IS_WORKER ? scriptDirectory = self.location.href : "undefined" != typeof document && document.currentScript && (scriptDirectory = document.currentScript.src), scriptDirectory = scriptDirectory.startsWith("blob:") ? "" : scriptDirectory.slice(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1), ENVIRONMENT_IS_WORKER && (readBinary = e => { var r = new XMLHttpRequest; return r.open("GET", e, !1), r.responseType = "arraybuffer", r.send(null), new Uint8Array(r.response) }), readAsync = async e => { var r = await fetch(e, { credentials: "same-origin" }); if (r.ok) return r.arrayBuffer(); throw new Error(r.status + " : " + r.url) }); var wasmBinary, wasmMemory, out = Module.print || console.log.bind(console), err = Module.printErr || console.error.bind(console); Object.assign(Module, moduleOverrides), moduleOverrides = null; var EXITSTATUS, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAP64, HEAPU64, HEAPF64, ABORT = !1, runtimeInitialized = !1, dataURIPrefix = "data:application/octet-stream;base64,", isDataURI = e => e.startsWith(dataURIPrefix); function updateMemoryViews() { var e = wasmMemory.buffer; Module.HEAP8 = HEAP8 = new Int8Array(e), HEAP16 = new Int16Array(e), Module.HEAPU8 = HEAPU8 = new Uint8Array(e), HEAPU16 = new Uint16Array(e), HEAP32 = new Int32Array(e), HEAPU32 = new Uint32Array(e), HEAPF32 = new Float32Array(e), HEAPF64 = new Float64Array(e), HEAP64 = new BigInt64Array(e), HEAPU64 = new BigUint64Array(e) } var __ATPRERUN__ = [], __ATINIT__ = [], __ATPOSTRUN__ = []; function preRun() { callRuntimeCallbacks(__ATPRERUN__) } function initRuntime() { runtimeInitialized = !0, Module.noFSInit || FS.initialized || FS.init(), FS.ignorePermissions = !1, TTY.init(), SOCKFS.root = FS.mount(SOCKFS, {}, null), callRuntimeCallbacks(__ATINIT__) } function postRun() { callRuntimeCallbacks(__ATPOSTRUN__) } function addOnInit(e) { __ATINIT__.unshift(e) } var wasmBinaryFile, runDependencies = 0, dependenciesFulfilled = null; function getUniqueRunDependency(e) { return e } function addRunDependency(e) { runDependencies++ } function removeRunDependency(e) { if (0 == --runDependencies && dependenciesFulfilled) { var r = dependenciesFulfilled; dependenciesFulfilled = null, r() } } function abort(e) { throw err(e = "Aborted(" + e + ")"), ABORT = !0, e += ". Build with -sASSERTIONS for more info.", new WebAssembly.RuntimeError(e) } function findWasmBinary() { var e = "dynamsoft-barcode-reader-bundle.wasm"; return isDataURI(e) ? e : locateFile(e) } function getBinarySync(e) { if (e == wasmBinaryFile && wasmBinary) return new Uint8Array(wasmBinary); if (readBinary) return readBinary(e); throw "both async and sync fetching of the wasm failed" } async function getWasmBinary(e) { if (!wasmBinary) try { var r = await readAsync(e); return new Uint8Array(r) } catch { } return getBinarySync(e) } async function instantiateArrayBuffer(e, r) { try { var t = await getWasmBinary(e); return await WebAssembly.instantiate(t, r) } catch (e) { err(`failed to asynchronously prepare wasm: ${e}`), abort(e) } } async function instantiateAsync(e, r, t) { if (!e && "function" == typeof WebAssembly.instantiateStreaming && !isDataURI(r)) try { var n = fetch(r, { credentials: "same-origin" }); return await WebAssembly.instantiateStreaming(n, t) } catch (e) { err(`wasm streaming compile failed: ${e}`), err("falling back to ArrayBuffer instantiation") } return instantiateArrayBuffer(r, t) } function getWasmImports() { return { env: wasmImports, wasi_snapshot_preview1: wasmImports } } async function createWasm() { addRunDependency("wasm-instantiate"); var e = getWasmImports(); wasmBinaryFile ??= findWasmBinary(); var r = function (e) { return r = e.instance, wasmExports = r.exports, wasmMemory = wasmExports.memory, updateMemoryViews(), wasmTable = wasmExports.__indirect_function_table, addOnInit(wasmExports.__wasm_call_ctors), exportWasmSymbols(wasmExports), removeRunDependency("wasm-instantiate"), wasmExports; var r }(await instantiateAsync(wasmBinary, wasmBinaryFile, e)); return r } class ExitStatus { name = "ExitStatus"; constructor(e) { this.message = `Program terminated with exit(${e})`, this.status = e } } var wasmTable, callRuntimeCallbacks = e => { for (; e.length > 0;)e.shift()(Module) }, asmjsMangle = e => ("__main_argc_argv" == e && (e = "main"), e.startsWith("dynCall_") ? e : "_" + e), exportWasmSymbols = e => { for (var r in e) { var t = asmjsMangle(r); this[t] = Module[t] = e[r] } }, UTF8Decoder = "undefined" != typeof TextDecoder ? new TextDecoder : void 0, UTF8ArrayToString = (e, r = 0, t = NaN) => { for (var n = r + t, o = r; e[o] && !(o >= n);)++o; if (o - r > 16 && e.buffer && UTF8Decoder) return UTF8Decoder.decode(e.subarray(r, o)); for (var a = ""; r < o;) { var s = e[r++]; if (128 & s) { var i = 63 & e[r++]; if (192 != (224 & s)) { var l = 63 & e[r++]; if ((s = 224 == (240 & s) ? (15 & s) << 12 | i << 6 | l : (7 & s) << 18 | i << 12 | l << 6 | 63 & e[r++]) < 65536) a += String.fromCharCode(s); else { var c = s - 65536; a += String.fromCharCode(55296 | c >> 10, 56320 | 1023 & c) } } else a += String.fromCharCode((31 & s) << 6 | i) } else a += String.fromCharCode(s) } return a }, UTF8ToString = (e, r) => e ? UTF8ArrayToString(HEAPU8, e, r) : "", ___assert_fail = (e, r, t, n) => abort(`Assertion failed: ${UTF8ToString(e)}, at: ` + [r ? UTF8ToString(r) : "unknown filename", t, n ? UTF8ToString(n) : "unknown function"]), getWasmTableEntry = e => wasmTable.get(e), ___call_sighandler = (e, r) => getWasmTableEntry(e)(r); class ExceptionInfo { constructor(e) { this.excPtr = e, this.ptr = e - 24 } set_type(e) { HEAPU32[this.ptr + 4 >> 2] = e } get_type() { return HEAPU32[this.ptr + 4 >> 2] } set_destructor(e) { HEAPU32[this.ptr + 8 >> 2] = e } get_destructor() { return HEAPU32[this.ptr + 8 >> 2] } set_caught(e) { e = e ? 1 : 0, HEAP8[this.ptr + 12] = e } get_caught() { return 0 != HEAP8[this.ptr + 12] } set_rethrown(e) { e = e ? 1 : 0, HEAP8[this.ptr + 13] = e } get_rethrown() { return 0 != HEAP8[this.ptr + 13] } init(e, r) { this.set_adjusted_ptr(0), this.set_type(e), this.set_destructor(r) } set_adjusted_ptr(e) { HEAPU32[this.ptr + 16 >> 2] = e } get_adjusted_ptr() { return HEAPU32[this.ptr + 16 >> 2] } } var exceptionLast = 0, uncaughtExceptionCount = 0, ___cxa_throw = (e, r, t) => { throw new ExceptionInfo(e).init(r, t), uncaughtExceptionCount++, exceptionLast = e }, PATH = { isAbs: e => "/" === e.charAt(0), splitPath: e => /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1), normalizeArray: (e, r) => { for (var t = 0, n = e.length - 1; n >= 0; n--) { var o = e[n]; "." === o ? e.splice(n, 1) : ".." === o ? (e.splice(n, 1), t++) : t && (e.splice(n, 1), t--) } if (r) for (; t; t--)e.unshift(".."); return e }, normalize: e => { var r = PATH.isAbs(e), t = "/" === e.slice(-1); return (e = PATH.normalizeArray(e.split("/").filter((e => !!e)), !r).join("/")) || r || (e = "."), e && t && (e += "/"), (r ? "/" : "") + e }, dirname: e => { var r = PATH.splitPath(e), t = r[0], n = r[1]; return t || n ? (n && (n = n.slice(0, -1)), t + n) : "." }, basename: e => e && e.match(/([^\/]+|\/)\/*$/)[1], join: (...e) => PATH.normalize(e.join("/")), join2: (e, r) => PATH.normalize(e + "/" + r) }, initRandomFill = () => e => crypto.getRandomValues(e), randomFill = e => { (randomFill = initRandomFill())(e) }, PATH_FS = { resolve: (...e) => { for (var r = "", t = !1, n = e.length - 1; n >= -1 && !t; n--) { var o = n >= 0 ? e[n] : FS.cwd(); if ("string" != typeof o) throw new TypeError("Arguments to path.resolve must be strings"); if (!o) return ""; r = o + "/" + r, t = PATH.isAbs(o) } return (t ? "/" : "") + (r = PATH.normalizeArray(r.split("/").filter((e => !!e)), !t).join("/")) || "." }, relative: (e, r) => { function t(e) { for (var r = 0; r < e.length && "" === e[r]; r++); for (var t = e.length - 1; t >= 0 && "" === e[t]; t--); return r > t ? [] : e.slice(r, t - r + 1) } e = PATH_FS.resolve(e).slice(1), r = PATH_FS.resolve(r).slice(1); for (var n = t(e.split("/")), o = t(r.split("/")), a = Math.min(n.length, o.length), s = a, i = 0; i < a; i++)if (n[i] !== o[i]) { s = i; break } var l = []; for (i = s; i < n.length; i++)l.push(".."); return (l = l.concat(o.slice(s))).join("/") } }, FS_stdin_getChar_buffer = [], lengthBytesUTF8 = e => { for (var r = 0, t = 0; t < e.length; ++t) { var n = e.charCodeAt(t); n <= 127 ? r++ : n <= 2047 ? r += 2 : n >= 55296 && n <= 57343 ? (r += 4, ++t) : r += 3 } return r }, stringToUTF8Array = (e, r, t, n) => { if (!(n > 0)) return 0; for (var o = t, a = t + n - 1, s = 0; s < e.length; ++s) { var i = e.charCodeAt(s); if (i >= 55296 && i <= 57343) i = 65536 + ((1023 & i) << 10) | 1023 & e.charCodeAt(++s); if (i <= 127) { if (t >= a) break; r[t++] = i } else if (i <= 2047) { if (t + 1 >= a) break; r[t++] = 192 | i >> 6, r[t++] = 128 | 63 & i } else if (i <= 65535) { if (t + 2 >= a) break; r[t++] = 224 | i >> 12, r[t++] = 128 | i >> 6 & 63, r[t++] = 128 | 63 & i } else { if (t + 3 >= a) break; r[t++] = 240 | i >> 18, r[t++] = 128 | i >> 12 & 63, r[t++] = 128 | i >> 6 & 63, r[t++] = 128 | 63 & i } } return r[t] = 0, t - o }, intArrayFromString = (e, r, t) => { var n = t > 0 ? t : lengthBytesUTF8(e) + 1, o = new Array(n), a = stringToUTF8Array(e, o, 0, o.length); return r && (o.length = a), o }, FS_stdin_getChar = () => { if (!FS_stdin_getChar_buffer.length) { return null } return FS_stdin_getChar_buffer.shift() }, TTY = { ttys: [], init() { }, shutdown() { }, register(e, r) { TTY.ttys[e] = { input: [], output: [], ops: r }, FS.registerDevice(e, TTY.stream_ops) }, stream_ops: { open(e) { var r = TTY.ttys[e.node.rdev]; if (!r) throw new FS.ErrnoError(43); e.tty = r, e.seekable = !1 }, close(e) { e.tty.ops.fsync(e.tty) }, fsync(e) { e.tty.ops.fsync(e.tty) }, read(e, r, t, n, o) { if (!e.tty || !e.tty.ops.get_char) throw new FS.ErrnoError(60); for (var a = 0, s = 0; s < n; s++) { var i; try { i = e.tty.ops.get_char(e.tty) } catch (e) { throw new FS.ErrnoError(29) } if (void 0 === i && 0 === a) throw new FS.ErrnoError(6); if (null == i) break; a++, r[t + s] = i } return a && (e.node.atime = Date.now()), a }, write(e, r, t, n, o) { if (!e.tty || !e.tty.ops.put_char) throw new FS.ErrnoError(60); try { for (var a = 0; a < n; a++)e.tty.ops.put_char(e.tty, r[t + a]) } catch (e) { throw new FS.ErrnoError(29) } return n && (e.node.mtime = e.node.ctime = Date.now()), a } }, default_tty_ops: { get_char: e => FS_stdin_getChar(), put_char(e, r) { null === r || 10 === r ? (out(UTF8ArrayToString(e.output)), e.output = []) : 0 != r && e.output.push(r) }, fsync(e) { e.output?.length > 0 && (out(UTF8ArrayToString(e.output)), e.output = []) }, ioctl_tcgets: e => ({ c_iflag: 25856, c_oflag: 5, c_cflag: 191, c_lflag: 35387, c_cc: [3, 28, 127, 21, 4, 0, 1, 0, 17, 19, 26, 0, 18, 15, 23, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }), ioctl_tcsets: (e, r, t) => 0, ioctl_tiocgwinsz: e => [24, 80] }, default_tty1_ops: { put_char(e, r) { null === r || 10 === r ? (err(UTF8ArrayToString(e.output)), e.output = []) : 0 != r && e.output.push(r) }, fsync(e) { e.output?.length > 0 && (err(UTF8ArrayToString(e.output)), e.output = []) } } }, alignMemory = (e, r) => Math.ceil(e / r) * r, mmapAlloc = e => { abort() }, MEMFS = { ops_table: null, mount: e => MEMFS.createNode(null, "/", 16895, 0), createNode(e, r, t, n) { if (FS.isBlkdev(t) || FS.isFIFO(t)) throw new FS.ErrnoError(63); MEMFS.ops_table ||= { dir: { node: { getattr: MEMFS.node_ops.getattr, setattr: MEMFS.node_ops.setattr, lookup: MEMFS.node_ops.lookup, mknod: MEMFS.node_ops.mknod, rename: MEMFS.node_ops.rename, unlink: MEMFS.node_ops.unlink, rmdir: MEMFS.node_ops.rmdir, readdir: MEMFS.node_ops.readdir, symlink: MEMFS.node_ops.symlink }, stream: { llseek: MEMFS.stream_ops.llseek } }, file: { node: { getattr: MEMFS.node_ops.getattr, setattr: MEMFS.node_ops.setattr }, stream: { llseek: MEMFS.stream_ops.llseek, read: MEMFS.stream_ops.read, write: MEMFS.stream_ops.write, allocate: MEMFS.stream_ops.allocate, mmap: MEMFS.stream_ops.mmap, msync: MEMFS.stream_ops.msync } }, link: { node: { getattr: MEMFS.node_ops.getattr, setattr: MEMFS.node_ops.setattr, readlink: MEMFS.node_ops.readlink }, stream: {} }, chrdev: { node: { getattr: MEMFS.node_ops.getattr, setattr: MEMFS.node_ops.setattr }, stream: FS.chrdev_stream_ops } }; var o = FS.createNode(e, r, t, n); return FS.isDir(o.mode) ? (o.node_ops = MEMFS.ops_table.dir.node, o.stream_ops = MEMFS.ops_table.dir.stream, o.contents = {}) : FS.isFile(o.mode) ? (o.node_ops = MEMFS.ops_table.file.node, o.stream_ops = MEMFS.ops_table.file.stream, o.usedBytes = 0, o.contents = null) : FS.isLink(o.mode) ? (o.node_ops = MEMFS.ops_table.link.node, o.stream_ops = MEMFS.ops_table.link.stream) : FS.isChrdev(o.mode) && (o.node_ops = MEMFS.ops_table.chrdev.node, o.stream_ops = MEMFS.ops_table.chrdev.stream), o.atime = o.mtime = o.ctime = Date.now(), e && (e.contents[r] = o, e.atime = e.mtime = e.ctime = o.atime), o }, getFileDataAsTypedArray: e => e.contents ? e.contents.subarray ? e.contents.subarray(0, e.usedBytes) : new Uint8Array(e.contents) : new Uint8Array(0), expandFileStorage(e, r) { var t = e.contents ? e.contents.length : 0; if (!(t >= r)) { r = Math.max(r, t * (t < 1048576 ? 2 : 1.125) >>> 0), 0 != t && (r = Math.max(r, 256)); var n = e.contents; e.contents = new Uint8Array(r), e.usedBytes > 0 && e.contents.set(n.subarray(0, e.usedBytes), 0) } }, resizeFileStorage(e, r) { if (e.usedBytes != r) if (0 == r) e.contents = null, e.usedBytes = 0; else { var t = e.contents; e.contents = new Uint8Array(r), t && e.contents.set(t.subarray(0, Math.min(r, e.usedBytes))), e.usedBytes = r } }, node_ops: { getattr(e) { var r = {}; return r.dev = FS.isChrdev(e.mode) ? e.id : 1, r.ino = e.id, r.mode = e.mode, r.nlink = 1, r.uid = 0, r.gid = 0, r.rdev = e.rdev, FS.isDir(e.mode) ? r.size = 4096 : FS.isFile(e.mode) ? r.size = e.usedBytes : FS.isLink(e.mode) ? r.size = e.link.length : r.size = 0, r.atime = new Date(e.atime), r.mtime = new Date(e.mtime), r.ctime = new Date(e.ctime), r.blksize = 4096, r.blocks = Math.ceil(r.size / r.blksize), r }, setattr(e, r) { for (const t of ["mode", "atime", "mtime", "ctime"]) null != r[t] && (e[t] = r[t]); void 0 !== r.size && MEMFS.resizeFileStorage(e, r.size) }, lookup(e, r) { throw MEMFS.doesNotExistError }, mknod: (e, r, t, n) => MEMFS.createNode(e, r, t, n), rename(e, r, t) { var n; try { n = FS.lookupNode(r, t) } catch (e) { } if (n) { if (FS.isDir(e.mode)) for (var o in n.contents) throw new FS.ErrnoError(55); FS.hashRemoveNode(n) } delete e.parent.contents[e.name], r.contents[t] = e, e.name = t, r.ctime = r.mtime = e.parent.ctime = e.parent.mtime = Date.now() }, unlink(e, r) { delete e.contents[r], e.ctime = e.mtime = Date.now() }, rmdir(e, r) { var t = FS.lookupNode(e, r); for (var n in t.contents) throw new FS.ErrnoError(55); delete e.contents[r], e.ctime = e.mtime = Date.now() }, readdir: e => [".", "..", ...Object.keys(e.contents)], symlink(e, r, t) { var n = MEMFS.createNode(e, r, 41471, 0); return n.link = t, n }, readlink(e) { if (!FS.isLink(e.mode)) throw new FS.ErrnoError(28); return e.link } }, stream_ops: { read(e, r, t, n, o) { var a = e.node.contents; if (o >= e.node.usedBytes) return 0; var s = Math.min(e.node.usedBytes - o, n); if (s > 8 && a.subarray) r.set(a.subarray(o, o + s), t); else for (var i = 0; i < s; i++)r[t + i] = a[o + i]; return s }, write(e, r, t, n, o, a) { if (r.buffer === HEAP8.buffer && (a = !1), !n) return 0; var s = e.node; if (s.mtime = s.ctime = Date.now(), r.subarray && (!s.contents || s.contents.subarray)) { if (a) return s.contents = r.subarray(t, t + n), s.usedBytes = n, n; if (0 === s.usedBytes && 0 === o) return s.contents = r.slice(t, t + n), s.usedBytes = n, n; if (o + n <= s.usedBytes) return s.contents.set(r.subarray(t, t + n), o), n } if (MEMFS.expandFileStorage(s, o + n), s.contents.subarray && r.subarray) s.contents.set(r.subarray(t, t + n), o); else for (var i = 0; i < n; i++)s.contents[o + i] = r[t + i]; return s.usedBytes = Math.max(s.usedBytes, o + n), n }, llseek(e, r, t) { var n = r; if (1 === t ? n += e.position : 2 === t && FS.isFile(e.node.mode) && (n += e.node.usedBytes), n < 0) throw new FS.ErrnoError(28); return n }, allocate(e, r, t) { MEMFS.expandFileStorage(e.node, r + t), e.node.usedBytes = Math.max(e.node.usedBytes, r + t) }, mmap(e, r, t, n, o) { if (!FS.isFile(e.node.mode)) throw new FS.ErrnoError(43); var a, s, i = e.node.contents; if (2 & o || !i || i.buffer !== HEAP8.buffer) { if (s = !0, !(a = mmapAlloc(r))) throw new FS.ErrnoError(48); i && ((t > 0 || t + r < i.length) && (i = i.subarray ? i.subarray(t, t + r) : Array.prototype.slice.call(i, t, t + r)), HEAP8.set(i, a)) } else s = !1, a = i.byteOffset; return { ptr: a, allocated: s } }, msync: (e, r, t, n, o) => (MEMFS.stream_ops.write(e, r, 0, n, t, !1), 0) } }, asyncLoad = async e => { var r = await readAsync(e); return new Uint8Array(r) }, FS_createDataFile = (e, r, t, n, o, a) => { FS.createDataFile(e, r, t, n, o, a) }, preloadPlugins = [], FS_handledByPreloadPlugin = (e, r, t, n) => { "undefined" != typeof Browser && Browser.init(); var o = !1; return preloadPlugins.forEach((a => { o || a.canHandle(r) && (a.handle(e, r, t, n), o = !0) })), o }, FS_createPreloadedFile = (e, r, t, n, o, a, s, i, l, c) => { var d = r ? PATH_FS.resolve(PATH.join2(e, r)) : e, u = getUniqueRunDependency(`cp ${d}`); function m(t) { function m(t) { c?.(), i || FS_createDataFile(e, r, t, n, o, l), a?.(), removeRunDependency(u) } FS_handledByPreloadPlugin(t, d, m, (() => { s?.(), removeRunDependency(u) })) || m(t) } addRunDependency(u), "string" == typeof t ? asyncLoad(t).then(m, s) : m(t) }, FS_modeStringToFlags = e => { var r = { r: 0, "r+": 2, w: 577, "w+": 578, a: 1089, "a+": 1090 }[e]; if (void 0 === r) throw new Error(`Unknown file open mode: ${e}`); return r }, FS_getMode = (e, r) => { var t = 0; return e && (t |= 365), r && (t |= 146), t }, FS = { root: null, mounts: [], devices: {}, streams: [], nextInode: 1, nameTable: null, currentPath: "/", initialized: !1, ignorePermissions: !0, ErrnoError: class { name = "ErrnoError"; constructor(e) { this.errno = e } }, filesystems: null, syncFSRequests: 0, FSStream: class { shared = {}; get object() { return this.node } set object(e) { this.node = e } get isRead() { return 1 != (2097155 & this.flags) } get isWrite() { return !!(2097155 & this.flags) } get isAppend() { return 1024 & this.flags } get flags() { return this.shared.flags } set flags(e) { this.shared.flags = e } get position() { return this.shared.position } set position(e) { this.shared.position = e } }, FSNode: class { node_ops = {}; stream_ops = {}; readMode = 365; writeMode = 146; mounted = null; constructor(e, r, t, n) { e || (e = this), this.parent = e, this.mount = e.mount, this.id = FS.nextInode++, this.name = r, this.mode = t, this.rdev = n, this.atime = this.mtime = this.ctime = Date.now() } get read() { return (this.mode & this.readMode) === this.readMode } set read(e) { e ? this.mode |= this.readMode : this.mode &= ~this.readMode } get write() { return (this.mode & this.writeMode) === this.writeMode } set write(e) { e ? this.mode |= this.writeMode : this.mode &= ~this.writeMode } get isFolder() { return FS.isDir(this.mode) } get isDevice() { return FS.isChrdev(this.mode) } }, lookupPath(e, r = {}) { if (!e) throw new FS.ErrnoError(44); r.follow_mount ??= !0, PATH.isAbs(e) || (e = FS.cwd() + "/" + e); e: for (var t = 0; t < 40; t++) { for (var n = e.split("/").filter((e => !!e)), o = FS.root, a = "/", s = 0; s < n.length; s++) { var i = s === n.length - 1; if (i && r.parent) break; if ("." !== n[s]) if (".." !== n[s]) { a = PATH.join2(a, n[s]); try { o = FS.lookupNode(o, n[s]) } catch (e) { if (44 === e?.errno && i && r.noent_okay) return { path: a }; throw e } if (!FS.isMountpoint(o) || i && !r.follow_mount || (o = o.mounted.root), FS.isLink(o.mode) && (!i || r.follow)) { if (!o.node_ops.readlink) throw new FS.ErrnoError(52); var l = o.node_ops.readlink(o); PATH.isAbs(l) || (l = PATH.dirname(a) + "/" + l), e = l + "/" + n.slice(s + 1).join("/"); continue e } } else a = PATH.dirname(a), o = o.parent } return { path: a, node: o } } throw new FS.ErrnoError(32) }, getPath(e) { for (var r; ;) { if (FS.isRoot(e)) { var t = e.mount.mountpoint; return r ? "/" !== t[t.length - 1] ? `${t}/${r}` : t + r : t } r = r ? `${e.name}/${r}` : e.name, e = e.parent } }, hashName(e, r) { for (var t = 0, n = 0; n < r.length; n++)t = (t << 5) - t + r.charCodeAt(n) | 0; return (e + t >>> 0) % FS.nameTable.length }, hashAddNode(e) { var r = FS.hashName(e.parent.id, e.name); e.name_next = FS.nameTable[r], FS.nameTable[r] = e }, hashRemoveNode(e) { var r = FS.hashName(e.parent.id, e.name); if (FS.nameTable[r] === e) FS.nameTable[r] = e.name_next; else for (var t = FS.nameTable[r]; t;) { if (t.name_next === e) { t.name_next = e.name_next; break } t = t.name_next } }, lookupNode(e, r) { var t = FS.mayLookup(e); if (t) throw new FS.ErrnoError(t); for (var n = FS.hashName(e.id, r), o = FS.nameTable[n]; o; o = o.name_next) { var a = o.name; if (o.parent.id === e.id && a === r) return o } return FS.lookup(e, r) }, createNode(e, r, t, n) { var o = new FS.FSNode(e, r, t, n); return FS.hashAddNode(o), o }, destroyNode(e) { FS.hashRemoveNode(e) }, isRoot: e => e === e.parent, isMountpoint: e => !!e.mounted, isFile: e => 32768 == (61440 & e), isDir: e => 16384 == (61440 & e), isLink: e => 40960 == (61440 & e), isChrdev: e => 8192 == (61440 & e), isBlkdev: e => 24576 == (61440 & e), isFIFO: e => 4096 == (61440 & e), isSocket: e => !(49152 & ~e), flagsToPermissionString(e) { var r = ["r", "w", "rw"][3 & e]; return 512 & e && (r += "w"), r }, nodePermissions: (e, r) => FS.ignorePermissions || (!r.includes("r") || 292 & e.mode) && (!r.includes("w") || 146 & e.mode) && (!r.includes("x") || 73 & e.mode) ? 0 : 2, mayLookup(e) { if (!FS.isDir(e.mode)) return 54; var r = FS.nodePermissions(e, "x"); return r || (e.node_ops.lookup ? 0 : 2) }, mayCreate(e, r) { if (!FS.isDir(e.mode)) return 54; try { FS.lookupNode(e, r); return 20 } catch (e) { } return FS.nodePermissions(e, "wx") }, mayDelete(e, r, t) { var n; try { n = FS.lookupNode(e, r) } catch (e) { return e.errno } var o = FS.nodePermissions(e, "wx"); if (o) return o; if (t) { if (!FS.isDir(n.mode)) return 54; if (FS.isRoot(n) || FS.getPath(n) === FS.cwd()) return 10 } else if (FS.isDir(n.mode)) return 31; return 0 }, mayOpen: (e, r) => e ? FS.isLink(e.mode) ? 32 : FS.isDir(e.mode) && ("r" !== FS.flagsToPermissionString(r) || 576 & r) ? 31 : FS.nodePermissions(e, FS.flagsToPermissionString(r)) : 44, checkOpExists(e, r) { if (!e) throw new FS.ErrnoError(r); return e }, MAX_OPEN_FDS: 4096, nextfd() { for (var e = 0; e <= FS.MAX_OPEN_FDS; e++)if (!FS.streams[e]) return e; throw new FS.ErrnoError(33) }, getStreamChecked(e) { var r = FS.getStream(e); if (!r) throw new FS.ErrnoError(8); return r }, getStream: e => FS.streams[e], createStream: (e, r = -1) => (e = Object.assign(new FS.FSStream, e), -1 == r && (r = FS.nextfd()), e.fd = r, FS.streams[r] = e, e), closeStream(e) { FS.streams[e] = null }, dupStream(e, r = -1) { var t = FS.createStream(e, r); return t.stream_ops?.dup?.(t), t }, doSetAttr(e, r, t) { var n = e?.stream_ops.setattr, o = n ? e : r; n ??= r.node_ops.setattr, FS.checkOpExists(n, 63), n(o, t) }, chrdev_stream_ops: { open(e) { var r = FS.getDevice(e.node.rdev); e.stream_ops = r.stream_ops, e.stream_ops.open?.(e) }, llseek() { throw new FS.ErrnoError(70) } }, major: e => e >> 8, minor: e => 255 & e, makedev: (e, r) => e << 8 | r, registerDevice(e, r) { FS.devices[e] = { stream_ops: r } }, getDevice: e => FS.devices[e], getMounts(e) { for (var r = [], t = [e]; t.length;) { var n = t.pop(); r.push(n), t.push(...n.mounts) } return r }, syncfs(e, r) { "function" == typeof e && (r = e, e = !1), FS.syncFSRequests++, FS.syncFSRequests > 1 && err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`); var t = FS.getMounts(FS.root.mount), n = 0; function o(e) { return FS.syncFSRequests--, r(e) } function a(e) { if (e) return a.errored ? void 0 : (a.errored = !0, o(e)); ++n >= t.length && o(null) } t.forEach((r => { if (!r.type.syncfs) return a(null); r.type.syncfs(r, e, a) })) }, mount(e, r, t) { var n, o = "/" === t, a = !t; if (o && FS.root) throw new FS.ErrnoError(10); if (!o && !a) { var s = FS.lookupPath(t, { follow_mount: !1 }); if (t = s.path, n = s.node, FS.isMountpoint(n)) throw new FS.ErrnoError(10); if (!FS.isDir(n.mode)) throw new FS.ErrnoError(54) } var i = { type: e, opts: r, mountpoint: t, mounts: [] }, l = e.mount(i); return l.mount = i, i.root = l, o ? FS.root = l : n && (n.mounted = i, n.mount && n.mount.mounts.push(i)), l }, unmount(e) { var r = FS.lookupPath(e, { follow_mount: !1 }); if (!FS.isMountpoint(r.node)) throw new FS.ErrnoError(28); var t = r.node, n = t.mounted, o = FS.getMounts(n); Object.keys(FS.nameTable).forEach((e => { for (var r = FS.nameTable[e]; r;) { var t = r.name_next; o.includes(r.mount) && FS.destroyNode(r), r = t } })), t.mounted = null; var a = t.mount.mounts.indexOf(n); t.mount.mounts.splice(a, 1) }, lookup: (e, r) => e.node_ops.lookup(e, r), mknod(e, r, t) { var n = FS.lookupPath(e, { parent: !0 }).node, o = PATH.basename(e); if (!o) throw new FS.ErrnoError(28); if ("." === o || ".." === o) throw new FS.ErrnoError(20); var a = FS.mayCreate(n, o); if (a) throw new FS.ErrnoError(a); if (!n.node_ops.mknod) throw new FS.ErrnoError(63); return n.node_ops.mknod(n, o, r, t) }, statfs: e => FS.statfsNode(FS.lookupPath(e, { follow: !0 }).node), statfsStream: e => FS.statfsNode(e.node), statfsNode(e) { var r = { bsize: 4096, frsize: 4096, blocks: 1e6, bfree: 5e5, bavail: 5e5, files: FS.nextInode, ffree: FS.nextInode - 1, fsid: 42, flags: 2, namelen: 255 }; return e.node_ops.statfs && Object.assign(r, e.node_ops.statfs(e.mount.opts.root)), r }, create: (e, r = 438) => (r &= 4095, r |= 32768, FS.mknod(e, r, 0)), mkdir: (e, r = 511) => (r &= 1023, r |= 16384, FS.mknod(e, r, 0)), mkdirTree(e, r) { for (var t = e.split("/"), n = "", o = 0; o < t.length; ++o)if (t[o]) { n += "/" + t[o]; try { FS.mkdir(n, r) } catch (e) { if (20 != e.errno) throw e } } }, mkdev: (e, r, t) => (void 0 === t && (t = r, r = 438), r |= 8192, FS.mknod(e, r, t)), symlink(e, r) { if (!PATH_FS.resolve(e)) throw new FS.ErrnoError(44); var t = FS.lookupPath(r, { parent: !0 }).node; if (!t) throw new FS.ErrnoError(44); var n = PATH.basename(r), o = FS.mayCreate(t, n); if (o) throw new FS.ErrnoError(o); if (!t.node_ops.symlink) throw new FS.ErrnoError(63); return t.node_ops.symlink(t, n, e) }, rename(e, r) { var t, n, o = PATH.dirname(e), a = PATH.dirname(r), s = PATH.basename(e), i = PATH.basename(r); if (t = FS.lookupPath(e, { parent: !0 }).node, n = FS.lookupPath(r, { parent: !0 }).node, !t || !n) throw new FS.ErrnoError(44); if (t.mount !== n.mount) throw new FS.ErrnoError(75); var l, c = FS.lookupNode(t, s), d = PATH_FS.relative(e, a); if ("." !== d.charAt(0)) throw new FS.ErrnoError(28); if ("." !== (d = PATH_FS.relative(r, o)).charAt(0)) throw new FS.ErrnoError(55); try { l = FS.lookupNode(n, i) } catch (e) { } if (c !== l) { var u = FS.isDir(c.mode), m = FS.mayDelete(t, s, u); if (m) throw new FS.ErrnoError(m); if (m = l ? FS.mayDelete(n, i, u) : FS.mayCreate(n, i)) throw new FS.ErrnoError(m); if (!t.node_ops.rename) throw new FS.ErrnoError(63); if (FS.isMountpoint(c) || l && FS.isMountpoint(l)) throw new FS.ErrnoError(10); if (n !== t && (m = FS.nodePermissions(t, "w"))) throw new FS.ErrnoError(m); FS.hashRemoveNode(c); try { t.node_ops.rename(c, n, i), c.parent = n } catch (e) { throw e } finally { FS.hashAddNode(c) } } }, rmdir(e) { var r = FS.lookupPath(e, { parent: !0 }).node, t = PATH.basename(e), n = FS.lookupNode(r, t), o = FS.mayDelete(r, t, !0); if (o) throw new FS.ErrnoError(o); if (!r.node_ops.rmdir) throw new FS.ErrnoError(63); if (FS.isMountpoint(n)) throw new FS.ErrnoError(10); r.node_ops.rmdir(r, t), FS.destroyNode(n) }, readdir(e) { var r = FS.lookupPath(e, { follow: !0 }).node; return FS.checkOpExists(r.node_ops.readdir, 54)(r) }, unlink(e) { var r = FS.lookupPath(e, { parent: !0 }).node; if (!r) throw new FS.ErrnoError(44); var t = PATH.basename(e), n = FS.lookupNode(r, t), o = FS.mayDelete(r, t, !1); if (o) throw new FS.ErrnoError(o); if (!r.node_ops.unlink) throw new FS.ErrnoError(63); if (FS.isMountpoint(n)) throw new FS.ErrnoError(10); r.node_ops.unlink(r, t), FS.destroyNode(n) }, readlink(e) { var r = FS.lookupPath(e).node; if (!r) throw new FS.ErrnoError(44); if (!r.node_ops.readlink) throw new FS.ErrnoError(28); return r.node_ops.readlink(r) }, stat(e, r) { var t = FS.lookupPath(e, { follow: !r }).node; return FS.checkOpExists(t.node_ops.getattr, 63)(t) }, fstat(e) { var r = FS.getStreamChecked(e), t = r.node, n = r.stream_ops.getattr, o = n ? r : t; return n ??= t.node_ops.getattr, FS.checkOpExists(n, 63), n(o) }, lstat: e => FS.stat(e, !0), doChmod(e, r, t, n) { FS.doSetAttr(e, r, { mode: 4095 & t | -4096 & r.mode, ctime: Date.now(), dontFollow: n }) }, chmod(e, r, t) { var n; "string" == typeof e ? n = FS.lookupPath(e, { follow: !t }).node : n = e; FS.doChmod(null, n, r, t) }, lchmod(e, r) { FS.chmod(e, r, !0) }, fchmod(e, r) { var t = FS.getStreamChecked(e); FS.doChmod(t, t.node, r, !1) }, doChown(e, r, t) { FS.doSetAttr(e, r, { timestamp: Date.now(), dontFollow: t }) }, chown(e, r, t, n) { var o; "string" == typeof e ? o = FS.lookupPath(e, { follow: !n }).node : o = e; FS.doChown(null, o, n) }, lchown(e, r, t) { FS.chown(e, r, t, !0) }, fchown(e, r, t) { var n = FS.getStreamChecked(e); FS.doChown(n, n.node, !1) }, doTruncate(e, r, t) { if (FS.isDir(r.mode)) throw new FS.ErrnoError(31); if (!FS.isFile(r.mode)) throw new FS.ErrnoError(28); var n = FS.nodePermissions(r, "w"); if (n) throw new FS.ErrnoError(n); FS.doSetAttr(e, r, { size: t, timestamp: Date.now() }) }, truncate(e, r) { if (r < 0) throw new FS.ErrnoError(28); var t; "string" == typeof e ? t = FS.lookupPath(e, { follow: !0 }).node : t = e; FS.doTruncate(null, t, r) }, ftruncate(e, r) { var t = FS.getStreamChecked(e); if (r < 0 || !(2097155 & t.flags)) throw new FS.ErrnoError(28); FS.doTruncate(t, t.node, r) }, utime(e, r, t) { var n = FS.lookupPath(e, { follow: !0 }).node; FS.checkOpExists(n.node_ops.setattr, 63)(n, { atime: r, mtime: t }) }, open(e, r, t = 438) { if ("" === e) throw new FS.ErrnoError(44); var n, o; if (t = 64 & (r = "string" == typeof r ? FS_modeStringToFlags(r) : r) ? 4095 & t | 32768 : 0, "object" == typeof e) n = e; else { o = e.endsWith("/"); var a = FS.lookupPath(e, { follow: !(131072 & r), noent_okay: !0 }); n = a.node, e = a.path } var s = !1; if (64 & r) if (n) { if (128 & r) throw new FS.ErrnoError(20) } else { if (o) throw new FS.ErrnoError(31); n = FS.mknod(e, 511 | t, 0), s = !0 } if (!n) throw new FS.ErrnoError(44); if (FS.isChrdev(n.mode) && (r &= -513), 65536 & r && !FS.isDir(n.mode)) throw new FS.ErrnoError(54); if (!s) { var i = FS.mayOpen(n, r); if (i) throw new FS.ErrnoError(i) } 512 & r && !s && FS.truncate(n, 0), r &= -131713; var l = FS.createStream({ node: n, path: FS.getPath(n), flags: r, seekable: !0, position: 0, stream_ops: n.stream_ops, ungotten: [], error: !1 }); return l.stream_ops.open && l.stream_ops.open(l), s && FS.chmod(n, 511 & t), l }, close(e) { if (FS.isClosed(e)) throw new FS.ErrnoError(8); e.getdents && (e.getdents = null); try { e.stream_ops.close && e.stream_ops.close(e) } catch (e) { throw e } finally { FS.closeStream(e.fd) } e.fd = null }, isClosed: e => null === e.fd, llseek(e, r, t) { if (FS.isClosed(e)) throw new FS.ErrnoError(8); if (!e.seekable || !e.stream_ops.llseek) throw new FS.ErrnoError(70); if (0 != t && 1 != t && 2 != t) throw new FS.ErrnoError(28); return e.position = e.stream_ops.llseek(e, r, t), e.ungotten = [], e.position }, read(e, r, t, n, o) { if (n < 0 || o < 0) throw new FS.ErrnoError(28); if (FS.isClosed(e)) throw new FS.ErrnoError(8); if (1 == (2097155 & e.flags)) throw new FS.ErrnoError(8); if (FS.isDir(e.node.mode)) throw new FS.ErrnoError(31); if (!e.stream_ops.read) throw new FS.ErrnoError(28); var a = void 0 !== o; if (a) { if (!e.seekable) throw new FS.ErrnoError(70) } else o = e.position; var s = e.stream_ops.read(e, r, t, n, o); return a || (e.position += s), s }, write(e, r, t, n, o, a) { if (n < 0 || o < 0) throw new FS.ErrnoError(28); if (FS.isClosed(e)) throw new FS.ErrnoError(8); if (!(2097155 & e.flags)) throw new FS.ErrnoError(8); if (FS.isDir(e.node.mode)) throw new FS.ErrnoError(31); if (!e.stream_ops.write) throw new FS.ErrnoError(28); e.seekable && 1024 & e.flags && FS.llseek(e, 0, 2); var s = void 0 !== o; if (s) { if (!e.seekable) throw new FS.ErrnoError(70) } else o = e.position; var i = e.stream_ops.write(e, r, t, n, o, a); return s || (e.position += i), i }, allocate(e, r, t) { if (FS.isClosed(e)) throw new FS.ErrnoError(8); if (r < 0 || t <= 0) throw new FS.ErrnoError(28); if (!(2097155 & e.flags)) throw new FS.ErrnoError(8); if (!FS.isFile(e.node.mode) && !FS.isDir(e.node.mode)) throw new FS.ErrnoError(43); if (!e.stream_ops.allocate) throw new FS.ErrnoError(138); e.stream_ops.allocate(e, r, t) }, mmap(e, r, t, n, o) { if (2 & n && !(2 & o) && 2 != (2097155 & e.flags)) throw new FS.ErrnoError(2); if (1 == (2097155 & e.flags)) throw new FS.ErrnoError(2); if (!e.stream_ops.mmap) throw new FS.ErrnoError(43); if (!r) throw new FS.ErrnoError(28); return e.stream_ops.mmap(e, r, t, n, o) }, msync: (e, r, t, n, o) => e.stream_ops.msync ? e.stream_ops.msync(e, r, t, n, o) : 0, ioctl(e, r, t) { if (!e.stream_ops.ioctl) throw new FS.ErrnoError(59); return e.stream_ops.ioctl(e, r, t) }, readFile(e, r = {}) { if (r.flags = r.flags || 0, r.encoding = r.encoding || "binary", "utf8" !== r.encoding && "binary" !== r.encoding) throw new Error(`Invalid encoding type "${r.encoding}"`); var t, n = FS.open(e, r.flags), o = FS.stat(e).size, a = new Uint8Array(o); return FS.read(n, a, 0, o, 0), "utf8" === r.encoding ? t = UTF8ArrayToString(a) : "binary" === r.encoding && (t = a), FS.close(n), t }, writeFile(e, r, t = {}) { t.flags = t.flags || 577; var n = FS.open(e, t.flags, t.mode); if ("string" == typeof r) { var o = new Uint8Array(lengthBytesUTF8(r) + 1), a = stringToUTF8Array(r, o, 0, o.length); FS.write(n, o, 0, a, void 0, t.canOwn) } else { if (!ArrayBuffer.isView(r)) throw new Error("Unsupported data type"); FS.write(n, r, 0, r.byteLength, void 0, t.canOwn) } FS.close(n) }, cwd: () => FS.currentPath, chdir(e) { var r = FS.lookupPath(e, { follow: !0 }); if (null === r.node) throw new FS.ErrnoError(44); if (!FS.isDir(r.node.mode)) throw new FS.ErrnoError(54); var t = FS.nodePermissions(r.node, "x"); if (t) throw new FS.ErrnoError(t); FS.currentPath = r.path }, createDefaultDirectories() { FS.mkdir("/tmp"), FS.mkdir("/home"), FS.mkdir("/home/web_user") }, createDefaultDevices() { FS.mkdir("/dev"), FS.registerDevice(FS.makedev(1, 3), { read: () => 0, write: (e, r, t, n, o) => n, llseek: () => 0 }), FS.mkdev("/dev/null", FS.makedev(1, 3)), TTY.register(FS.makedev(5, 0), TTY.default_tty_ops), TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops), FS.mkdev("/dev/tty", FS.makedev(5, 0)), FS.mkdev("/dev/tty1", FS.makedev(6, 0)); var e = new Uint8Array(1024), r = 0, t = () => (0 === r && (randomFill(e), r = e.byteLength), e[--r]); FS.createDevice("/dev", "random", t), FS.createDevice("/dev", "urandom", t), FS.mkdir("/dev/shm"), FS.mkdir("/dev/shm/tmp") }, createSpecialDirectories() { FS.mkdir("/proc"); var e = FS.mkdir("/proc/self"); FS.mkdir("/proc/self/fd"), FS.mount({ mount() { var r = FS.createNode(e, "fd", 16895, 73); return r.stream_ops = { llseek: MEMFS.stream_ops.llseek }, r.node_ops = { lookup(e, r) { var t = +r, n = FS.getStreamChecked(t), o = { parent: null, mount: { mountpoint: "fake" }, node_ops: { readlink: () => n.path }, id: t + 1 }; return o.parent = o, o }, readdir: () => Array.from(FS.streams.entries()).filter((([e, r]) => r)).map((([e, r]) => e.toString())) }, r } }, {}, "/proc/self/fd") }, createStandardStreams(e, r, t) { e ? FS.createDevice("/dev", "stdin", e) : FS.symlink("/dev/tty", "/dev/stdin"), r ? FS.createDevice("/dev", "stdout", null, r) : FS.symlink("/dev/tty", "/dev/stdout"), t ? FS.createDevice("/dev", "stderr", null, t) : FS.symlink("/dev/tty1", "/dev/stderr"); FS.open("/dev/stdin", 0), FS.open("/dev/stdout", 1), FS.open("/dev/stderr", 1) }, staticInit() { FS.nameTable = new Array(4096), FS.mount(MEMFS, {}, "/"), FS.createDefaultDirectories(), FS.createDefaultDevices(), FS.createSpecialDirectories(), FS.filesystems = { MEMFS: MEMFS } }, init(e, r, t) { FS.initialized = !0, FS.createStandardStreams(e, r, t) }, quit() { FS.initialized = !1; for (var e = 0; e < FS.streams.length; e++) { var r = FS.streams[e]; r && FS.close(r) } }, findObject(e, r) { var t = FS.analyzePath(e, r); return t.exists ? t.object : null }, analyzePath(e, r) { try { e = (n = FS.lookupPath(e, { follow: !r })).path } catch (e) { } var t = { isRoot: !1, exists: !1, error: 0, name: null, path: null, object: null, parentExists: !1, parentPath: null, parentObject: null }; try { var n = FS.lookupPath(e, { parent: !0 }); t.parentExists = !0, t.parentPath = n.path, t.parentObject = n.node, t.name = PATH.basename(e), n = FS.lookupPath(e, { follow: !r }), t.exists = !0, t.path = n.path, t.object = n.node, t.name = n.node.name, t.isRoot = "/" === n.path } catch (e) { t.error = e.errno } return t }, createPath(e, r, t, n) { e = "string" == typeof e ? e : FS.getPath(e); for (var o = r.split("/").reverse(); o.length;) { var a = o.pop(); if (a) { var s = PATH.join2(e, a); try { FS.mkdir(s) } catch (e) { } e = s } } return s }, createFile(e, r, t, n, o) { var a = PATH.join2("string" == typeof e ? e : FS.getPath(e), r), s = FS_getMode(n, o); return FS.create(a, s) }, createDataFile(e, r, t, n, o, a) { var s = r; e && (e = "string" == typeof e ? e : FS.getPath(e), s = r ? PATH.join2(e, r) : e); var i = FS_getMode(n, o), l = FS.create(s, i); if (t) { if ("string" == typeof t) { for (var c = new Array(t.length), d = 0, u = t.length; d < u; ++d)c[d] = t.charCodeAt(d); t = c } FS.chmod(l, 146 | i); var m = FS.open(l, 577); FS.write(m, t, 0, t.length, 0, a), FS.close(m), FS.chmod(l, i) } }, createDevice(e, r, t, n) { var o = PATH.join2("string" == typeof e ? e : FS.getPath(e), r), a = FS_getMode(!!t, !!n); FS.createDevice.major ??= 64; var s = FS.makedev(FS.createDevice.major++, 0); return FS.registerDevice(s, { open(e) { e.seekable = !1 }, close(e) { n?.buffer?.length && n(10) }, read(e, r, n, o, a) { for (var s = 0, i = 0; i < o; i++) { var l; try { l = t() } catch (e) { throw new FS.ErrnoError(29) } if (void 0 === l && 0 === s) throw new FS.ErrnoError(6); if (null == l) break; s++, r[n + i] = l } return s && (e.node.atime = Date.now()), s }, write(e, r, t, o, a) { for (var s = 0; s < o; s++)try { n(r[t + s]) } catch (e) { throw new FS.ErrnoError(29) } return o && (e.node.mtime = e.node.ctime = Date.now()), s } }), FS.mkdev(o, a, s) }, forceLoadFile(e) { if (e.isDevice || e.isFolder || e.link || e.contents) return !0; if ("undefined" != typeof XMLHttpRequest) throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread."); try { e.contents = readBinary(e.url), e.usedBytes = e.contents.length } catch (e) { throw new FS.ErrnoError(29) } }, createLazyFile(e, r, t, n, o) { class a { lengthKnown = !1; chunks = []; get(e) { if (!(e > this.length - 1 || e < 0)) { var r = e % this.chunkSize, t = e / this.chunkSize | 0; return this.getter(t)[r] } } setDataGetter(e) { this.getter = e } cacheLength() { var e = new XMLHttpRequest; if (e.open("HEAD", t, !1), e.send(null), !(e.status >= 200 && e.status < 300 || 304 === e.status)) throw new Error("Couldn't load " + t + ". Status: " + e.status); var r, n = Number(e.getResponseHeader("Content-length")), o = (r = e.getResponseHeader("Accept-Ranges")) && "bytes" === r, a = (r = e.getResponseHeader("Content-Encoding")) && "gzip" === r, s = 1048576; o || (s = n); var i = this; i.setDataGetter((e => { var r = e * s, o = (e + 1) * s - 1; if (o = Math.min(o, n - 1), void 0 === i.chunks[e] && (i.chunks[e] = ((e, r) => { if (e > r) throw new Error("invalid range (" + e + ", " + r + ") or no bytes requested!"); if (r > n - 1) throw new Error("only " + n + " bytes available! programmer error!"); var o = new XMLHttpRequest; if (o.open("GET", t, !1), n !== s && o.setRequestHeader("Range", "bytes=" + e + "-" + r), o.responseType = "arraybuffer", o.overrideMimeType && o.overrideMimeType("text/plain; charset=x-user-defined"), o.send(null), !(o.status >= 200 && o.status < 300 || 304 === o.status)) throw new Error("Couldn't load " + t + ". Status: " + o.status); return void 0 !== o.response ? new Uint8Array(o.response || []) : intArrayFromString(o.responseText || "", !0) })(r, o)), void 0 === i.chunks[e]) throw new Error("doXHR failed!"); return i.chunks[e] })), !a && n || (s = n = 1, n = this.getter(0).length, s = n, out("LazyFiles on gzip forces download of the whole file when length is accessed")), this._length = n, this._chunkSize = s, this.lengthKnown = !0 } get length() { return this.lengthKnown || this.cacheLength(), this._length } get chunkSize() { return this.lengthKnown || this.cacheLength(), this._chunkSize } } if ("undefined" != typeof XMLHttpRequest) { if (!ENVIRONMENT_IS_WORKER) throw "Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc"; var s = { isDevice: !1, contents: new a } } else s = { isDevice: !1, url: t }; var i = FS.createFile(e, r, s, n, o); s.contents ? i.contents = s.contents : s.url && (i.contents = null, i.url = s.url), Object.defineProperties(i, { usedBytes: { get: function () { return this.contents.length } } }); var l = {}; function c(e, r, t, n, o) { var a = e.node.contents; if (o >= a.length) return 0; var s = Math.min(a.length - o, n); if (a.slice) for (var i = 0; i < s; i++)r[t + i] = a[o + i]; else for (i = 0; i < s; i++)r[t + i] = a.get(o + i); return s } return Object.keys(i.stream_ops).forEach((e => { var r = i.stream_ops[e]; l[e] = (...e) => (FS.forceLoadFile(i), r(...e)) })), l.read = (e, r, t, n, o) => (FS.forceLoadFile(i), c(e, r, t, n, o)), l.mmap = (e, r, t, n, o) => { FS.forceLoadFile(i); var a = mmapAlloc(r); if (!a) throw new FS.ErrnoError(48); return c(e, HEAP8, a, r, t), { ptr: a, allocated: !0 } }, i.stream_ops = l, i } }, SYSCALLS = { DEFAULT_POLLMASK: 5, calculateAt(e, r, t) { if (PATH.isAbs(r)) return r; var n; -100 === e ? n = FS.cwd() : n = SYSCALLS.getStreamFromFD(e).path; if (0 == r.length) { if (!t) throw new FS.ErrnoError(44); return n } return n + "/" + r }, writeStat(e, r) { HEAP32[e >> 2] = r.dev, HEAP32[e + 4 >> 2] = r.mode, HEAPU32[e + 8 >> 2] = r.nlink, HEAP32[e + 12 >> 2] = r.uid, HEAP32[e + 16 >> 2] = r.gid, HEAP32[e + 20 >> 2] = r.rdev, HEAP64[e + 24 >> 3] = BigInt(r.size), HEAP32[e + 32 >> 2] = 4096, HEAP32[e + 36 >> 2] = r.blocks; var t = r.atime.getTime(), n = r.mtime.getTime(), o = r.ctime.getTime(); return HEAP64[e + 40 >> 3] = BigInt(Math.floor(t / 1e3)), HEAPU32[e + 48 >> 2] = t % 1e3 * 1e3 * 1e3, HEAP64[e + 56 >> 3] = BigInt(Math.floor(n / 1e3)), HEAPU32[e + 64 >> 2] = n % 1e3 * 1e3 * 1e3, HEAP64[e + 72 >> 3] = BigInt(Math.floor(o / 1e3)), HEAPU32[e + 80 >> 2] = o % 1e3 * 1e3 * 1e3, HEAP64[e + 88 >> 3] = BigInt(r.ino), 0 }, writeStatFs(e, r) { HEAP32[e + 4 >> 2] = r.bsize, HEAP32[e + 40 >> 2] = r.bsize, HEAP32[e + 8 >> 2] = r.blocks, HEAP32[e + 12 >> 2] = r.bfree, HEAP32[e + 16 >> 2] = r.bavail, HEAP32[e + 20 >> 2] = r.files, HEAP32[e + 24 >> 2] = r.ffree, HEAP32[e + 28 >> 2] = r.fsid, HEAP32[e + 44 >> 2] = r.flags, HEAP32[e + 36 >> 2] = r.namelen }, doMsync(e, r, t, n, o) { if (!FS.isFile(r.node.mode)) throw new FS.ErrnoError(43); if (2 & n) return 0; var a = HEAPU8.slice(e, e + t); FS.msync(r, a, o, t, n) }, getStreamFromFD: e => FS.getStreamChecked(e), varargs: void 0, getStr: e => UTF8ToString(e) }, ___syscall__newselect = function (e, r, t, n, o) { try { for (var a = 0, s = r ? HEAP32[r >> 2] : 0, i = r ? HEAP32[r + 4 >> 2] : 0, l = t ? HEAP32[t >> 2] : 0, c = t ? HEAP32[t + 4 >> 2] : 0, d = n ? HEAP32[n >> 2] : 0, u = n ? HEAP32[n + 4 >> 2] : 0, m = 0, S = 0, f = 0, _ = 0, F = 0, p = 0, h = (r ? HEAP32[r >> 2] : 0) | (t ? HEAP32[t >> 2] : 0) | (n ? HEAP32[n >> 2] : 0), E = (r ? HEAP32[r + 4 >> 2] : 0) | (t ? HEAP32[t + 4 >> 2] : 0) | (n ? HEAP32[n + 4 >> 2] : 0), g = (e, r, t, n) => e < 32 ? r & n : t & n, w = 0; w < e; w++) { var v = 1 << w % 32; if (g(w, h, E, v)) { var y = SYSCALLS.getStreamFromFD(w), A = SYSCALLS.DEFAULT_POLLMASK; if (y.stream_ops.poll) { var k = -1; if (o) k = 1e3 * ((r ? HEAP32[o >> 2] : 0) + (r ? HEAP32[o + 4 >> 2] : 0) / 1e6); A = y.stream_ops.poll(y, k) } 1 & A && g(w, s, i, v) && (w < 32 ? m |= v : S |= v, a++), 4 & A && g(w, l, c, v) && (w < 32 ? f |= v : _ |= v, a++), 2 & A && g(w, d, u, v) && (w < 32 ? F |= v : p |= v, a++) } } return r && (HEAP32[r >> 2] = m, HEAP32[r + 4 >> 2] = S), t && (HEAP32[t >> 2] = f, HEAP32[t + 4 >> 2] = _), n && (HEAP32[n >> 2] = F, HEAP32[n + 4 >> 2] = p), a } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return -e.errno } }; function ___syscall_chmod(e, r) { try { return e = SYSCALLS.getStr(e), FS.chmod(e, r), 0 } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return -e.errno } } var SOCKFS = { callbacks: {}, on(e, r) { SOCKFS.callbacks[e] = r }, emit(e, r) { SOCKFS.callbacks[e]?.(r) }, mount: e => FS.createNode(null, "/", 16895, 0), createSocket(e, r, t) { if (1 == (r &= -526337) && t && 6 != t) throw new FS.ErrnoError(66); var n = { family: e, type: r, protocol: t, server: null, error: null, peers: {}, pending: [], recv_queue: [], sock_ops: SOCKFS.websocket_sock_ops }, o = SOCKFS.nextname(), a = FS.createNode(SOCKFS.root, o, 49152, 0); a.sock = n; var s = FS.createStream({ path: o, node: a, flags: 2, seekable: !1, stream_ops: SOCKFS.stream_ops }); return n.stream = s, n }, getSocket(e) { var r = FS.getStream(e); return r && FS.isSocket(r.node.mode) ? r.node.sock : null }, stream_ops: { poll(e) { var r = e.node.sock; return r.sock_ops.poll(r) }, ioctl(e, r, t) { var n = e.node.sock; return n.sock_ops.ioctl(n, r, t) }, read(e, r, t, n, o) { var a = e.node.sock, s = a.sock_ops.recvmsg(a, n); return s ? (r.set(s.buffer, t), s.buffer.length) : 0 }, write(e, r, t, n, o) { var a = e.node.sock; return a.sock_ops.sendmsg(a, r, t, n) }, close(e) { var r = e.node.sock; r.sock_ops.close(r) } }, nextname: () => (SOCKFS.nextname.current || (SOCKFS.nextname.current = 0), `socket[${SOCKFS.nextname.current++}]`), websocket_sock_ops: { createPeer(e, r, t) { var n; if ("object" == typeof r && (n = r, r = null, t = null), n) if (n._socket) r = n._socket.remoteAddress, t = n._socket.remotePort; else { var o = /ws[s]?:\/\/([^:]+):(\d+)/.exec(n.url); if (!o) throw new Error("WebSocket URL must be in the format ws(s)://address:port"); r = o[1], t = parseInt(o[2], 10) } else try { var a = "ws:#".replace("#", "//"), s = "binary", i = void 0; if ("ws://" === a || "wss://" === a) { var l = r.split("/"); a = a + l[0] + ":" + t + "/" + l.slice(1).join("/") } "null" !== s && (i = s = s.replace(/^ +| +$/g, "").split(/ *, */)), (n = new WebSocket(a, i)).binaryType = "arraybuffer" } catch (e) { throw new FS.ErrnoError(23) } var c = { addr: r, port: t, socket: n, msg_send_queue: [] }; return SOCKFS.websocket_sock_ops.addPeer(e, c), SOCKFS.websocket_sock_ops.handlePeerEvents(e, c), 2 === e.type && void 0 !== e.sport && c.msg_send_queue.push(new Uint8Array([255, 255, 255, 255, "p".charCodeAt(0), "o".charCodeAt(0), "r".charCodeAt(0), "t".charCodeAt(0), (65280 & e.sport) >> 8, 255 & e.sport])), c }, getPeer: (e, r, t) => e.peers[r + ":" + t], addPeer(e, r) { e.peers[r.addr + ":" + r.port] = r }, removePeer(e, r) { delete e.peers[r.addr + ":" + r.port] }, handlePeerEvents(e, r) { var t = !0, n = function () { e.connecting = !1, SOCKFS.emit("open", e.stream.fd); try { for (var t = r.msg_send_queue.shift(); t;)r.socket.send(t), t = r.msg_send_queue.shift() } catch (e) { r.socket.close() } }; function o(n) { if ("string" == typeof n) { n = (new TextEncoder).encode(n) } else { if (assert(void 0 !== n.byteLength), 0 == n.byteLength) return; n = new Uint8Array(n) } var o = t; if (t = !1, o && 10 === n.length && 255 === n[0] && 255 === n[1] && 255 === n[2] && 255 === n[3] && n[4] === "p".charCodeAt(0) && n[5] === "o".charCodeAt(0) && n[6] === "r".charCodeAt(0) && n[7] === "t".charCodeAt(0)) { var a = n[8] << 8 | n[9]; return SOCKFS.websocket_sock_ops.removePeer(e, r), r.port = a, void SOCKFS.websocket_sock_ops.addPeer(e, r) } e.recv_queue.push({ addr: r.addr, port: r.port, data: n }), SOCKFS.emit("message", e.stream.fd) } ENVIRONMENT_IS_NODE ? (r.socket.on("open", n), r.socket.on("message", (function (e, r) { r && o(new Uint8Array(e).buffer) })), r.socket.on("close", (function () { SOCKFS.emit("close", e.stream.fd) })), r.socket.on("error", (function (r) { e.error = 14, SOCKFS.emit("error", [e.stream.fd, e.error, "ECONNREFUSED: Connection refused"]) }))) : (r.socket.onopen = n, r.socket.onclose = function () { SOCKFS.emit("close", e.stream.fd) }, r.socket.onmessage = function (e) { o(e.data) }, r.socket.onerror = function (r) { e.error = 14, SOCKFS.emit("error", [e.stream.fd, e.error, "ECONNREFUSED: Connection refused"]) }) }, poll(e) { if (1 === e.type && e.server) return e.pending.length ? 65 : 0; var r = 0, t = 1 === e.type ? SOCKFS.websocket_sock_ops.getPeer(e, e.daddr, e.dport) : null; return (e.recv_queue.length || !t || t && t.socket.readyState === t.socket.CLOSING || t && t.socket.readyState === t.socket.CLOSED) && (r |= 65), (!t || t && t.socket.readyState === t.socket.OPEN) && (r |= 4), (t && t.socket.readyState === t.socket.CLOSING || t && t.socket.readyState === t.socket.CLOSED) && (e.connecting ? r |= 4 : r |= 16), r }, ioctl(e, r, t) { if (21531 === r) { var n = 0; return e.recv_queue.length && (n = e.recv_queue[0].data.length), HEAP32[t >> 2] = n, 0 } return 28 }, close(e) { if (e.server) { try { e.server.close() } catch (e) { } e.server = null } for (var r = Object.keys(e.peers), t = 0; t < r.length; t++) { var n = e.peers[r[t]]; try { n.socket.close() } catch (e) { } SOCKFS.websocket_sock_ops.removePeer(e, n) } return 0 }, bind(e, r, t) { if (void 0 !== e.saddr || void 0 !== e.sport) throw new FS.ErrnoError(28); if (e.saddr = r, e.sport = t, 2 === e.type) { e.server && (e.server.close(), e.server = null); try { e.sock_ops.listen(e, 0) } catch (e) { if ("ErrnoError" !== e.name) throw e; if (138 !== e.errno) throw e } } }, connect(e, r, t) { if (e.server) throw new FS.ErrnoError(138); if (void 0 !== e.daddr && void 0 !== e.dport) { var n = SOCKFS.websocket_sock_ops.getPeer(e, e.daddr, e.dport); if (n) throw n.socket.readyState === n.socket.CONNECTING ? new FS.ErrnoError(7) : new FS.ErrnoError(30) } var o = SOCKFS.websocket_sock_ops.createPeer(e, r, t); e.daddr = o.addr, e.dport = o.port, e.connecting = !0 }, listen(e, r) { if (!ENVIRONMENT_IS_NODE) throw new FS.ErrnoError(138) }, accept(e) { if (!e.server || !e.pending.length) throw new FS.ErrnoError(28); var r = e.pending.shift(); return r.stream.flags = e.stream.flags, r }, getname(e, r) { var t, n; if (r) { if (void 0 === e.daddr || void 0 === e.dport) throw new FS.ErrnoError(53); t = e.daddr, n = e.dport } else t = e.saddr || 0, n = e.sport || 0; return { addr: t, port: n } }, sendmsg(e, r, t, n, o, a) { if (2 === e.type) { if (void 0 !== o && void 0 !== a || (o = e.daddr, a = e.dport), void 0 === o || void 0 === a) throw new FS.ErrnoError(17) } else o = e.daddr, a = e.dport; var s = SOCKFS.websocket_sock_ops.getPeer(e, o, a); if (1 === e.type && (!s || s.socket.readyState === s.socket.CLOSING || s.socket.readyState === s.socket.CLOSED)) throw new FS.ErrnoError(53); ArrayBuffer.isView(r) && (t += r.byteOffset, r = r.buffer); var i = r.slice(t, t + n); if (!s || s.socket.readyState !== s.socket.OPEN) return 2 === e.type && (s && s.socket.readyState !== s.socket.CLOSING && s.socket.readyState !== s.socket.CLOSED || (s = SOCKFS.websocket_sock_ops.createPeer(e, o, a))), s.msg_send_queue.push(i), n; try { return s.socket.send(i), n } catch (e) { throw new FS.ErrnoError(28) } }, recvmsg(e, r) { if (1 === e.type && e.server) throw new FS.ErrnoError(53); var t = e.recv_queue.shift(); if (!t) { if (1 === e.type) { var n = SOCKFS.websocket_sock_ops.getPeer(e, e.daddr, e.dport); if (!n) throw new FS.ErrnoError(53); if (n.socket.readyState === n.socket.CLOSING || n.socket.readyState === n.socket.CLOSED) return null; throw new FS.ErrnoError(6) } throw new FS.ErrnoError(6) } var o = t.data.byteLength || t.data.length, a = t.data.byteOffset || 0, s = t.data.buffer || t.data, i = Math.min(r, o), l = { buffer: new Uint8Array(s, a, i), addr: t.addr, port: t.port }; if (1 === e.type && i < o) { var c = o - i; t.data = new Uint8Array(s, a + i, c), e.recv_queue.unshift(t) } return l } } }, getSocketFromFD = e => { var r = SOCKFS.getSocket(e); if (!r) throw new FS.ErrnoError(8); return r }, inetNtop4 = e => (255 & e) + "." + (e >> 8 & 255) + "." + (e >> 16 & 255) + "." + (e >> 24 & 255), inetNtop6 = e => { var r = "", t = 0, n = 0, o = 0, a = 0, s = 0, i = 0, l = [65535 & e[0], e[0] >> 16, 65535 & e[1], e[1] >> 16, 65535 & e[2], e[2] >> 16, 65535 & e[3], e[3] >> 16], c = !0, d = ""; for (i = 0; i < 5; i++)if (0 !== l[i]) { c = !1; break } if (c) { if (d = inetNtop4(l[6] | l[7] << 16), -1 === l[5]) return r = "::ffff:", r += d; if (0 === l[5]) return r = "::", "0.0.0.0" === d && (d = ""), "0.0.0.1" === d && (d = "1"), r += d } for (t = 0; t < 8; t++)0 === l[t] && (t - o > 1 && (s = 0), o = t, s++), s > n && (a = t - (n = s) + 1); for (t = 0; t < 8; t++)n > 1 && 0 === l[t] && t >= a && t < a + n ? t === a && (r += ":", 0 === a && (r += ":")) : (r += Number(_ntohs(65535 & l[t])).toString(16), r += t < 7 ? ":" : ""); return r }, readSockaddr = (e, r) => { var t, n = HEAP16[e >> 1], o = _ntohs(HEAPU16[e + 2 >> 1]); switch (n) { case 2: if (16 !== r) return { errno: 28 }; t = HEAP32[e + 4 >> 2], t = inetNtop4(t); break; case 10: if (28 !== r) return { errno: 28 }; t = [HEAP32[e + 8 >> 2], HEAP32[e + 12 >> 2], HEAP32[e + 16 >> 2], HEAP32[e + 20 >> 2]], t = inetNtop6(t); break; default: return { errno: 5 } }return { family: n, addr: t, port: o } }, inetPton4 = e => { for (var r = e.split("."), t = 0; t < 4; t++) { var n = Number(r[t]); if (isNaN(n)) return null; r[t] = n } return (r[0] | r[1] << 8 | r[2] << 16 | r[3] << 24) >>> 0 }, jstoi_q = e => parseInt(e), inetPton6 = e => { var r, t, n, o, a = []; if (!/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i.test(e)) return null; if ("::" === e) return [0, 0, 0, 0, 0, 0, 0, 0]; for ((e = e.startsWith("::") ? e.replace("::", "Z:") : e.replace("::", ":Z:")).indexOf(".") > 0 ? ((r = (e = e.replace(new RegExp("[.]", "g"), ":")).split(":"))[r.length - 4] = jstoi_q(r[r.length - 4]) + 256 * jstoi_q(r[r.length - 3]), r[r.length - 3] = jstoi_q(r[r.length - 2]) + 256 * jstoi_q(r[r.length - 1]), r = r.slice(0, r.length - 2)) : r = e.split(":"), n = 0, o = 0, t = 0; t < r.length; t++)if ("string" == typeof r[t]) if ("Z" === r[t]) { for (o = 0; o < 8 - r.length + 1; o++)a[t + o] = 0; n = o - 1 } else a[t + n] = _htons(parseInt(r[t], 16)); else a[t + n] = r[t]; return [a[1] << 16 | a[0], a[3] << 16 | a[2], a[5] << 16 | a[4], a[7] << 16 | a[6]] }, DNS = { address_map: { id: 1, addrs: {}, names: {} }, lookup_name(e) { var r, t = inetPton4(e); if (null !== t) return e; if (null !== (t = inetPton6(e))) return e; if (DNS.address_map.addrs[e]) r = DNS.address_map.addrs[e]; else { var n = DNS.address_map.id++; assert(n < 65535, "exceeded max address mappings of 65535"), r = "172.29." + (255 & n) + "." + (65280 & n), DNS.address_map.names[r] = e, DNS.address_map.addrs[e] = r } return r }, lookup_addr: e => DNS.address_map.names[e] ? DNS.address_map.names[e] : null }, getSocketAddress = (e, r) => { var t = readSockaddr(e, r); if (t.errno) throw new FS.ErrnoError(t.errno); return t.addr = DNS.lookup_addr(t.addr) || t.addr, t }; function ___syscall_connect(e, r, t, n, o, a) { try { var s = getSocketFromFD(e), i = getSocketAddress(r, t); return s.sock_ops.connect(s, i.addr, i.port), 0 } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return -e.errno } } function ___syscall_fchmod(e, r) { try { return FS.fchmod(e, r), 0 } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return -e.errno } } var syscallGetVarargI = () => { var e = HEAP32[+SYSCALLS.varargs >> 2]; return SYSCALLS.varargs += 4, e }, syscallGetVarargP = syscallGetVarargI; function ___syscall_fcntl64(e, r, t) { SYSCALLS.varargs = t; try { var n = SYSCALLS.getStreamFromFD(e); switch (r) { case 0: if ((o = syscallGetVarargI()) < 0) return -28; for (; FS.streams[o];)o++; return FS.dupStream(n, o).fd; case 1: case 2: case 13: case 14: return 0; case 3: return n.flags; case 4: var o = syscallGetVarargI(); return n.flags |= o, 0; case 12: o = syscallGetVarargP(); return HEAP16[o + 0 >> 1] = 2, 0 }return -28 } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return -e.errno } } function ___syscall_fstat64(e, r) { try { return SYSCALLS.writeStat(r, FS.fstat(e)) } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return -e.errno } } var INT53_MAX = 9007199254740992, INT53_MIN = -9007199254740992, bigintToI53Checked = e => e < INT53_MIN || e > INT53_MAX ? NaN : Number(e); function ___syscall_ftruncate64(e, r) { r = bigintToI53Checked(r); try { return isNaN(r) ? 61 : (FS.ftruncate(e, r), 0) } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return -e.errno } } var stringToUTF8 = (e, r, t) => stringToUTF8Array(e, HEAPU8, r, t); function ___syscall_getdents64(e, r, t) { try { var n = SYSCALLS.getStreamFromFD(e); n.getdents ||= FS.readdir(n.path); for (var o = 280, a = 0, s = FS.llseek(n, 0, 1), i = Math.floor(s / o), l = Math.min(n.getdents.length, i + Math.floor(t / o)), c = i; c < l; c++) { var d, u, m = n.getdents[c]; if ("." === m) d = n.node.id, u = 4; else if (".." === m) { d = FS.lookupPath(n.path, { parent: !0 }).node.id, u = 4 } else { var S; try { S = FS.lookupNode(n.node, m) } catch (e) { if (28 === e?.errno) continue; throw e } d = S.id, u = FS.isChrdev(S.mode) ? 2 : FS.isDir(S.mode) ? 4 : FS.isLink(S.mode) ? 10 : 8 } HEAP64[r + a >> 3] = BigInt(d), HEAP64[r + a + 8 >> 3] = BigInt((c + 1) * o), HEAP16[r + a + 16 >> 1] = 280, HEAP8[r + a + 18] = u, stringToUTF8(m, r + a + 19, 256), a += o } return FS.llseek(n, c * o, 0), a } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return -e.errno } } function ___syscall_getuid32() { abort("missing function: __syscall_getuid32") } function ___syscall_ioctl(e, r, t) { SYSCALLS.varargs = t; try { var n = SYSCALLS.getStreamFromFD(e); switch (r) { case 21509: case 21510: case 21511: case 21512: case 21524: case 21515: return n.tty ? 0 : -59; case 21505: if (!n.tty) return -59; if (n.tty.ops.ioctl_tcgets) { var o = n.tty.ops.ioctl_tcgets(n), a = syscallGetVarargP(); HEAP32[a >> 2] = o.c_iflag || 0, HEAP32[a + 4 >> 2] = o.c_oflag || 0, HEAP32[a + 8 >> 2] = o.c_cflag || 0, HEAP32[a + 12 >> 2] = o.c_lflag || 0; for (var s = 0; s < 32; s++)HEAP8[a + s + 17] = o.c_cc[s] || 0; return 0 } return 0; case 21506: case 21507: case 21508: if (!n.tty) return -59; if (n.tty.ops.ioctl_tcsets) { a = syscallGetVarargP(); var i = HEAP32[a >> 2], l = HEAP32[a + 4 >> 2], c = HEAP32[a + 8 >> 2], d = HEAP32[a + 12 >> 2], u = []; for (s = 0; s < 32; s++)u.push(HEAP8[a + s + 17]); return n.tty.ops.ioctl_tcsets(n.tty, r, { c_iflag: i, c_oflag: l, c_cflag: c, c_lflag: d, c_cc: u }) } return 0; case 21519: if (!n.tty) return -59; a = syscallGetVarargP(); return HEAP32[a >> 2] = 0, 0; case 21520: return n.tty ? -28 : -59; case 21531: a = syscallGetVarargP(); return FS.ioctl(n, r, a); case 21523: if (!n.tty) return -59; if (n.tty.ops.ioctl_tiocgwinsz) { var m = n.tty.ops.ioctl_tiocgwinsz(n.tty); a = syscallGetVarargP(); HEAP16[a >> 1] = m[0], HEAP16[a + 2 >> 1] = m[1] } return 0; default: return -28 } } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return -e.errno } } function ___syscall_linkat() { abort("missing function: __syscall_linkat") } function ___syscall_lstat64(e, r) { try { return e = SYSCALLS.getStr(e), SYSCALLS.writeStat(r, FS.lstat(e)) } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return -e.errno } } function ___syscall_mkdirat(e, r, t) { try { return r = SYSCALLS.getStr(r), r = SYSCALLS.calculateAt(e, r), FS.mkdir(r, t, 0), 0 } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return -e.errno } } function ___syscall_newfstatat(e, r, t, n) { try { r = SYSCALLS.getStr(r); var o = 256 & n, a = 4096 & n; return n &= -6401, r = SYSCALLS.calculateAt(e, r, a), SYSCALLS.writeStat(t, o ? FS.lstat(r) : FS.stat(r)) } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return -e.errno } } function ___syscall_openat(e, r, t, n) { SYSCALLS.varargs = n; try { r = SYSCALLS.getStr(r), r = SYSCALLS.calculateAt(e, r); var o = n ? syscallGetVarargI() : 0; return FS.open(r, t, o).fd } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return -e.errno } } function ___syscall_readlinkat(e, r, t, n) { try { if (r = SYSCALLS.getStr(r), r = SYSCALLS.calculateAt(e, r), n <= 0) return -28; var o = FS.readlink(r), a = Math.min(n, lengthBytesUTF8(o)), s = HEAP8[t + a]; return stringToUTF8(o, t, n + 1), HEAP8[t + a] = s, a } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return -e.errno } } function ___syscall_socket(e, r, t) { try { return SOCKFS.createSocket(e, r, t).stream.fd } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return -e.errno } } function ___syscall_stat64(e, r) { try { return e = SYSCALLS.getStr(e), SYSCALLS.writeStat(r, FS.stat(e)) } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return -e.errno } } function ___syscall_symlinkat(e, r, t) { try { return e = SYSCALLS.getStr(e), t = SYSCALLS.getStr(t), t = SYSCALLS.calculateAt(r, t), FS.symlink(e, t), 0 } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return -e.errno } } ___syscall_getuid32.stub = !0, ___syscall_linkat.stub = !0; var __abort_js = () => abort(""), runtimeKeepaliveCounter = 0, __emscripten_runtime_keepalive_clear = () => { runtimeKeepaliveCounter = 0 }; function __gmtime_js(e, r) { e = bigintToI53Checked(e); var t = new Date(1e3 * e); HEAP32[r >> 2] = t.getUTCSeconds(), HEAP32[r + 4 >> 2] = t.getUTCMinutes(), HEAP32[r + 8 >> 2] = t.getUTCHours(), HEAP32[r + 12 >> 2] = t.getUTCDate(), HEAP32[r + 16 >> 2] = t.getUTCMonth(), HEAP32[r + 20 >> 2] = t.getUTCFullYear() - 1900, HEAP32[r + 24 >> 2] = t.getUTCDay(); var n = Date.UTC(t.getUTCFullYear(), 0, 1, 0, 0, 0, 0), o = (t.getTime() - n) / 864e5 | 0; HEAP32[r + 28 >> 2] = o } var isLeapYear = e => e % 4 == 0 && (e % 100 != 0 || e % 400 == 0), MONTH_DAYS_LEAP_CUMULATIVE = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], MONTH_DAYS_REGULAR_CUMULATIVE = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], ydayFromDate = e => (isLeapYear(e.getFullYear()) ? MONTH_DAYS_LEAP_CUMULATIVE : MONTH_DAYS_REGULAR_CUMULATIVE)[e.getMonth()] + e.getDate() - 1; function __localtime_js(e, r) { e = bigintToI53Checked(e); var t = new Date(1e3 * e); HEAP32[r >> 2] = t.getSeconds(), HEAP32[r + 4 >> 2] = t.getMinutes(), HEAP32[r + 8 >> 2] = t.getHours(), HEAP32[r + 12 >> 2] = t.getDate(), HEAP32[r + 16 >> 2] = t.getMonth(), HEAP32[r + 20 >> 2] = t.getFullYear() - 1900, HEAP32[r + 24 >> 2] = t.getDay(); var n = 0 | ydayFromDate(t); HEAP32[r + 28 >> 2] = n, HEAP32[r + 36 >> 2] = -60 * t.getTimezoneOffset(); var o = new Date(t.getFullYear(), 0, 1), a = new Date(t.getFullYear(), 6, 1).getTimezoneOffset(), s = o.getTimezoneOffset(), i = 0 | (a != s && t.getTimezoneOffset() == Math.min(s, a)); HEAP32[r + 32 >> 2] = i } var timers = {}, handleException = e => { if (e instanceof ExitStatus || "unwind" == e) return EXITSTATUS; quit_(1, e) }, keepRuntimeAlive = () => !0, _proc_exit = e => { EXITSTATUS = e, keepRuntimeAlive() || (ABORT = !0), quit_(e, new ExitStatus(e)) }, exitJS = (e, r) => { EXITSTATUS = e, _proc_exit(e) }, _exit = exitJS, maybeExit = () => { if (!keepRuntimeAlive()) try { _exit(EXITSTATUS) } catch (e) { handleException(e) } }, callUserCallback = e => { if (!ABORT) try { e(), maybeExit() } catch (e) { handleException(e) } }, _emscripten_get_now = () => performance.now(), __setitimer_js = (e, r) => { if (timers[e] && (clearTimeout(timers[e].id), delete timers[e]), !r) return 0; var t = setTimeout((() => { delete timers[e], callUserCallback((() => __emscripten_timeout(e, _emscripten_get_now()))) }), r); return timers[e] = { id: t, timeout_ms: r }, 0 }, __tzset_js = (e, r, t, n) => { var o = (new Date).getFullYear(), a = new Date(o, 0, 1), s = new Date(o, 6, 1), i = a.getTimezoneOffset(), l = s.getTimezoneOffset(), c = Math.max(i, l); HEAPU32[e >> 2] = 60 * c, HEAP32[r >> 2] = Number(i != l); var d = e => { var r = e >= 0 ? "-" : "+", t = Math.abs(e); return `UTC${r}${String(Math.floor(t / 60)).padStart(2, "0")}${String(t % 60).padStart(2, "0")}` }, u = d(i), m = d(l); l < i ? (stringToUTF8(u, t, 17), stringToUTF8(m, n, 17)) : (stringToUTF8(u, n, 17), stringToUTF8(m, t, 17)) }, _emscripten_date_now = () => Date.now(), nowIsMonotonic = 1, checkWasiClock = e => e >= 0 && e <= 3; function _clock_time_get(e, r, t) { if (r = bigintToI53Checked(r), !checkWasiClock(e)) return 28; var n; if (0 === e) n = _emscripten_date_now(); else { if (!nowIsMonotonic) return 52; n = _emscripten_get_now() } var o = Math.round(1e3 * n * 1e3); return HEAP64[t >> 3] = BigInt(o), 0 } var reallyNegative = e => e < 0 || 0 === e && 1 / e == -1 / 0, convertI32PairToI53 = (e, r) => (e >>> 0) + 4294967296 * r, convertU32PairToI53 = (e, r) => (e >>> 0) + 4294967296 * (r >>> 0), reSign = (e, r) => { if (e <= 0) return e; var t = r <= 32 ? Math.abs(1 << r - 1) : Math.pow(2, r - 1); return e >= t && (r <= 32 || e > t) && (e = -2 * t + e), e }, unSign = (e, r) => e >= 0 ? e : r <= 32 ? 2 * Math.abs(1 << r - 1) + e : Math.pow(2, r) + e, strLen = e => { for (var r = e; HEAPU8[r];)++r; return r - e }, formatString = (e, r) => { var t = e, n = r; function o(e) { var r; return n = function (e, r) { return "double" !== r && "i64" !== r || 7 & e && (e += 4), e }(n, e), "double" === e ? (r = HEAPF64[n >> 3], n += 8) : "i64" == e ? (r = [HEAP32[n >> 2], HEAP32[n + 4 >> 2]], n += 8) : (e = "i32", r = HEAP32[n >> 2], n += 4), r } for (var a, s, i, l = []; ;) { var c = t; if (0 === (a = HEAP8[t])) break; if (s = HEAP8[t + 1], 37 == a) { var d = !1, u = !1, m = !1, S = !1, f = !1; e: for (; ;) { switch (s) { case 43: d = !0; break; case 45: u = !0; break; case 35: m = !0; break; case 48: if (S) break e; S = !0; break; case 32: f = !0; break; default: break e }t++, s = HEAP8[t + 1] } var _ = 0; if (42 == s) _ = o("i32"), t++, s = HEAP8[t + 1]; else for (; s >= 48 && s <= 57;)_ = 10 * _ + (s - 48), t++, s = HEAP8[t + 1]; var F, p = !1, h = -1; if (46 == s) { if (h = 0, p = !0, t++, 42 == (s = HEAP8[t + 1])) h = o("i32"), t++; else for (; ;) { var E = HEAP8[t + 1]; if (E < 48 || E > 57) break; h = 10 * h + (E - 48), t++ } s = HEAP8[t + 1] } switch (h < 0 && (h = 6, p = !1), String.fromCharCode(s)) { case "h": 104 == HEAP8[t + 2] ? (t++, F = 1) : F = 2; break; case "l": 108 == HEAP8[t + 2] ? (t++, F = 8) : F = 4; break; case "L": case "q": case "j": F = 8; break; case "z": case "t": case "I": F = 4; break; default: F = null }switch (F && t++, s = HEAP8[t + 1], String.fromCharCode(s)) { case "d": case "i": case "u": case "o": case "x": case "X": case "p": var g = 100 == s || 105 == s; if (i = o("i" + 8 * (F = F || 4)), 8 == F && (i = 117 == s ? convertU32PairToI53(i[0], i[1]) : convertI32PairToI53(i[0], i[1])), F <= 4) { var w = Math.pow(256, F) - 1; i = (g ? reSign : unSign)(i & w, 8 * F) } var v = Math.abs(i), y = ""; if (100 == s || 105 == s) T = reSign(i, 8 * F).toString(10); else if (117 == s) T = unSign(i, 8 * F).toString(10), i = Math.abs(i); else if (111 == s) T = (m ? "0" : "") + v.toString(8); else if (120 == s || 88 == s) { if (y = m && 0 != i ? "0x" : "", i < 0) { i = -i, T = (v - 1).toString(16); for (var A = [], k = 0; k < T.length; k++)A.push((15 - parseInt(T[k], 16)).toString(16)); for (T = A.join(""); T.length < 2 * F;)T = "f" + T } else T = v.toString(16); 88 == s && (y = y.toUpperCase(), T = T.toUpperCase()) } else 112 == s && (0 === v ? T = "(nil)" : (y = "0x", T = v.toString(16))); if (p) for (; T.length < h;)T = "0" + T; for (i >= 0 && (d ? y = "+" + y : f && (y = " " + y)), "-" == T.charAt(0) && (y = "-" + y, T = T.slice(1)); y.length + T.length < _;)u ? T += " " : S ? T = "0" + T : y = " " + y; (T = y + T).split("").forEach((e => l.push(e.charCodeAt(0)))); break; case "f": case "F": case "e": case "E": case "g": case "G": var T; if (i = o("double"), isNaN(i)) T = "nan", S = !1; else if (isFinite(i)) { var P = !1, b = Math.min(h, 20); if (103 == s || 71 == s) { P = !0, h = h || 1; var M = parseInt(i.toExponential(b).split("e")[1], 10); h > M && M >= -4 ? (s = (103 == s ? "f" : "F").charCodeAt(0), h -= M + 1) : (s = (103 == s ? "e" : "E").charCodeAt(0), h--), b = Math.min(h, 20) } 101 == s || 69 == s ? (T = i.toExponential(b), /[eE][-+]\d$/.test(T) && (T = T.slice(0, -1) + "0" + T.slice(-1))) : 102 != s && 70 != s || (T = i.toFixed(b), 0 === i && reallyNegative(i) && (T = "-" + T)); var C = T.split("e"); if (P && !m) for (; C[0].length > 1 && C[0].includes(".") && ("0" == C[0].slice(-1) || "." == C[0].slice(-1));)C[0] = C[0].slice(0, -1); else for (m && -1 == T.indexOf(".") && (C[0] += "."); h > b++;)C[0] += "0"; T = C[0] + (C.length > 1 ? "e" + C[1] : ""), 69 == s && (T = T.toUpperCase()), i >= 0 && (d ? T = "+" + T : f && (T = " " + T)) } else T = (i < 0 ? "-" : "") + "inf", S = !1; for (; T.length < _;)u ? T += " " : T = !S || "-" != T[0] && "+" != T[0] ? (S ? "0" : " ") + T : T[0] + "0" + T.slice(1); s < 97 && (T = T.toUpperCase()), T.split("").forEach((e => l.push(e.charCodeAt(0)))); break; case "s": var D = o("i8*"), H = D ? strLen(D) : 6; if (p && (H = Math.min(H, h)), !u) for (; H < _--;)l.push(32); if (D) for (k = 0; k < H; k++)l.push(HEAPU8[D++]); else l = l.concat(intArrayFromString("(null)".slice(0, H), !0)); if (u) for (; H < _--;)l.push(32); break; case "c": for (u && l.push(o("i8")); --_ > 0;)l.push(32); u || l.push(o("i8")); break; case "n": var N = o("i32*"); HEAP32[N >> 2] = l.length; break; case "%": l.push(a); break; default: for (k = c; k < t + 2; k++)l.push(HEAP8[k]) }t += 2 } else l.push(a), t += 1 } return l }, jsStackTrace = () => (new Error).stack.toString(), warnOnce = e => { warnOnce.shown ||= {}, warnOnce.shown[e] || (warnOnce.shown[e] = 1, err(e)) }, getCallstack = e => { var r = jsStackTrace(), t = r.lastIndexOf("_emscripten_log"), n = r.lastIndexOf("_emscripten_get_callstack"), o = r.indexOf("\n", Math.max(t, n)) + 1; r = r.slice(o), 8 & e && "undefined" == typeof emscripten_source_map && (warnOnce('Source map information is not available, emscripten_log with EM_LOG_C_STACK will be ignored. Build with "--pre-js $EMSCRIPTEN/src/emscripten-source-map.min.js" linker flag to add source map loading to code.'), e ^= 8, e |= 16); var a = r.split("\n"); r = ""; var s = new RegExp("\\s*(.*?)@(.*?):([0-9]+):([0-9]+)"), i = new RegExp("\\s*(.*?)@(.*):(.*)(:(.*))?"), l = new RegExp("\\s*at (.*?) \\((.*):(.*):(.*)\\)"); for (var c in a) { var d = a[c], u = "", m = "", S = 0, f = 0, _ = l.exec(d); if (5 == _?.length) u = _[1], m = _[2], S = _[3], f = _[4]; else { if (_ = s.exec(d) || i.exec(d), !(_?.length >= 4)) { r += d + "\n"; continue } u = _[1], m = _[2], S = _[3], f = 0 | _[4] } var F = !1; if (8 & e) { var p = emscripten_source_map.originalPositionFor({ line: S, column: f }); F = p?.source, F && (64 & e && (p.source = p.source.substring(p.source.replace(/\\/g, "/").lastIndexOf("/") + 1)), r += ` at ${u} (${p.source}:${p.line}:${p.column})\n`) } (16 & e || !F) && (64 & e && (m = m.substring(m.replace(/\\/g, "/").lastIndexOf("/") + 1)), r += (F ? ` = ${u}` : ` at ${u}`) + ` (${m}:${S}:${f})\n`) } return r = r.replace(/\s+$/, "") }, emscriptenLog = (e, r) => { 24 & e && (r = r.replace(/\s+$/, ""), r += (r.length > 0 ? "\n" : "") + getCallstack(e)), 1 & e ? 4 & e || 2 & e ? err(r) : out(r) : 6 & e ? err(r) : out(r) }, _emscripten_log = (e, r, t) => { var n = formatString(r, t), o = UTF8ArrayToString(n); emscriptenLog(e, o) }, getHeapMax = () => 2147483648, growMemory = e => { var r = (e - wasmMemory.buffer.byteLength + 65535) / 65536 | 0; try { return wasmMemory.grow(r), updateMemoryViews(), 1 } catch (e) { } }, _emscripten_resize_heap = e => { var r = HEAPU8.length; e >>>= 0; var t = getHeapMax(); if (e > t) return !1; for (var n = 1; n <= 4; n *= 2) { var o = r * (1 + .2 / n); o = Math.min(o, e + 100663296); var a = Math.min(t, alignMemory(Math.max(e, o), 65536)); if (growMemory(a)) return !0 } return !1 }, ENV = {}, getExecutableName = () => thisProgram || "./this.program", getEnvStrings = () => { if (!getEnvStrings.strings) { var e = { USER: "web_user", LOGNAME: "web_user", PATH: "/", PWD: "/", HOME: "/home/web_user", LANG: ("object" == typeof navigator && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8", _: getExecutableName() }; for (var r in ENV) void 0 === ENV[r] ? delete e[r] : e[r] = ENV[r]; var t = []; for (var r in e) t.push(`${r}=${e[r]}`); getEnvStrings.strings = t } return getEnvStrings.strings }, stringToAscii = (e, r) => { for (var t = 0; t < e.length; ++t)HEAP8[r++] = e.charCodeAt(t); HEAP8[r] = 0 }, _environ_get = (e, r) => { var t = 0; return getEnvStrings().forEach(((n, o) => { var a = r + t; HEAPU32[e + 4 * o >> 2] = a, stringToAscii(n, a), t += n.length + 1 })), 0 }, _environ_sizes_get = (e, r) => { var t = getEnvStrings(); HEAPU32[e >> 2] = t.length; var n = 0; return t.forEach((e => n += e.length + 1)), HEAPU32[r >> 2] = n, 0 }; function _fd_close(e) { try { var r = SYSCALLS.getStreamFromFD(e); return FS.close(r), 0 } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return e.errno } } function _fd_fdstat_get(e, r) { try { var t = SYSCALLS.getStreamFromFD(e), n = t.tty ? 2 : FS.isDir(t.mode) ? 3 : FS.isLink(t.mode) ? 7 : 4; return HEAP8[r] = n, HEAP16[r + 2 >> 1] = 0, HEAP64[r + 8 >> 3] = BigInt(0), HEAP64[r + 16 >> 3] = BigInt(0), 0 } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return e.errno } } var doReadv = (e, r, t, n) => { for (var o = 0, a = 0; a < t; a++) { var s = HEAPU32[r >> 2], i = HEAPU32[r + 4 >> 2]; r += 8; var l = FS.read(e, HEAP8, s, i, n); if (l < 0) return -1; if (o += l, l < i) break; void 0 !== n && (n += l) } return o }; function _fd_read(e, r, t, n) { try { var o = SYSCALLS.getStreamFromFD(e), a = doReadv(o, r, t); return HEAPU32[n >> 2] = a, 0 } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return e.errno } } function _fd_seek(e, r, t, n) { r = bigintToI53Checked(r); try { if (isNaN(r)) return 61; var o = SYSCALLS.getStreamFromFD(e); return FS.llseek(o, r, t), HEAP64[n >> 3] = BigInt(o.position), o.getdents && 0 === r && 0 === t && (o.getdents = null), 0 } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return e.errno } } var doWritev = (e, r, t, n) => { for (var o = 0, a = 0; a < t; a++) { var s = HEAPU32[r >> 2], i = HEAPU32[r + 4 >> 2]; r += 8; var l = FS.write(e, HEAP8, s, i, n); if (l < 0) return -1; if (o += l, l < i) break; void 0 !== n && (n += l) } return o }; function _fd_write(e, r, t, n) { try { var o = SYSCALLS.getStreamFromFD(e), a = doWritev(o, r, t); return HEAPU32[n >> 2] = a, 0 } catch (e) { if (void 0 === FS || "ErrnoError" !== e.name) throw e; return e.errno } } var functionsInTableMap, uleb128Encode = (e, r) => { e < 128 ? r.push(e) : r.push(e % 128 | 128, e >> 7) }, sigToWasmTypes = e => { for (var r = { i: "i32", j: "i64", f: "f32", d: "f64", e: "externref", p: "i32" }, t = { parameters: [], results: "v" == e[0] ? [] : [r[e[0]]] }, n = 1; n < e.length; ++n)t.parameters.push(r[e[n]]); return t }, generateFuncType = (e, r) => { var t = e.slice(0, 1), n = e.slice(1), o = { i: 127, p: 127, j: 126, f: 125, d: 124, e: 111 }; r.push(96), uleb128Encode(n.length, r); for (var a = 0; a < n.length; ++a)r.push(o[n[a]]); "v" == t ? r.push(0) : r.push(1, o[t]) }, convertJsFunctionToWasm = (e, r) => { if ("function" == typeof WebAssembly.Function) return new WebAssembly.Function(sigToWasmTypes(r), e); var t = [1]; generateFuncType(r, t); var n = [0, 97, 115, 109, 1, 0, 0, 0, 1]; uleb128Encode(t.length, n), n.push(...t), n.push(2, 7, 1, 1, 101, 1, 102, 0, 0, 7, 5, 1, 1, 102, 0, 0); var o = new WebAssembly.Module(new Uint8Array(n)); return new WebAssembly.Instance(o, { e: { f: e } }).exports.f }, updateTableMap = (e, r) => { if (functionsInTableMap) for (var t = e; t < e + r; t++) { var n = getWasmTableEntry(t); n && functionsInTableMap.set(n, t) } }, getFunctionAddress = e => (functionsInTableMap || (functionsInTableMap = new WeakMap, updateTableMap(0, wasmTable.length)), functionsInTableMap.get(e) || 0), freeTableIndexes = [], getEmptyTableSlot = () => { if (freeTableIndexes.length) return freeTableIndexes.pop(); try { wasmTable.grow(1) } catch (e) { if (!(e instanceof RangeError)) throw e; throw "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH." } return wasmTable.length - 1 }, setWasmTableEntry = (e, r) => wasmTable.set(e, r), addFunction = (e, r) => { var t = getFunctionAddress(e); if (t) return t; var n = getEmptyTableSlot(); try { setWasmTableEntry(n, e) } catch (t) { if (!(t instanceof TypeError)) throw t; var o = convertJsFunctionToWasm(e, r); setWasmTableEntry(n, o) } return functionsInTableMap.set(e, n), n }; FS.createPreloadedFile = FS_createPreloadedFile, FS.staticInit(), MEMFS.doesNotExistError = new FS.ErrnoError(44), MEMFS.doesNotExistError.stack = ""; var wasmExports, a = () => { }, wasmImports = { CreateDirectoryFetcher: a, DDN_ConvertElement: a, DDN_CreateDDNResult: a, DDN_CreateDDNResultItem: a, DDN_CreateParameters: a, DDN_CreateTargetRoiDefConditionFilter: a, DDN_CreateTaskAlgEntity: a, DDN_HasSection: a, DDN_ReadTaskSetting: a, DLR_ConvertElement: a, DLR_CreateBufferedCharacterItemSet: a, DLR_CreateParameters: a, DLR_CreateRecognizedTextLinesResult: a, DLR_CreateTargetRoiDefConditionFilter: a, DLR_CreateTaskAlgEntity: a, DLR_CreateTextLineResultItem: a, DLR_ReadTaskSetting: a, DMImage_GetDIB: a, DMImage_GetFormatFromHandle: a, DMImage_GetFormatFromStream: a, DMImage_GetOrientation: a, DeleteDirectoryFetcher: a, _Z22DM_GetNodeFromFormatID15DM_IMAGE_FORMAT: a, _ZN11DMImageNode9SetHandleEPvj: a, _ZN19LabelRecognizerWasm10getVersionEv: a, _ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv: a, _ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv: a, _ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi: a, _ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb: a, _ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb: a, _ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb: a, _ZN19LabelRecognizerWasm12DlrWasmClassC1Ev: a, _ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE: a, _ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE: a, _ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE: a, _ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE: a, _ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE: a, _ZN22DocumentNormalizerWasm10getVersionEv: a, _ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv: a, _ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi: a, _ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii: a, _ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib: a, _ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib: a, _ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb: a, _ZN22DocumentNormalizerWasm12DdnWasmClass34getJvFromNormalizedImageResultItemEPKN9dynamsoft3ddn26CNormalizedImageResultItemEPKcb: a, _ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev: a, _ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE: a, _ZN22DocumentNormalizerWasm39getJvFromNormalizedImageResultItem_JustEPKN9dynamsoft3ddn26CNormalizedImageResultItemE: a, _ZN9dynamsoft3dnn20CNeuralNetworkModule10GetVersionEv: a, _ZN9dynamsoft7utility14CUtilityModule10GetVersionEv: a, __assert_fail: ___assert_fail, __call_sighandler: ___call_sighandler, __cxa_throw: ___cxa_throw, __syscall__newselect: ___syscall__newselect, __syscall_chmod: ___syscall_chmod, __syscall_connect: ___syscall_connect, __syscall_fchmod: ___syscall_fchmod, __syscall_fcntl64: ___syscall_fcntl64, __syscall_fstat64: ___syscall_fstat64, __syscall_ftruncate64: ___syscall_ftruncate64, __syscall_getdents64: ___syscall_getdents64, __syscall_getuid32: ___syscall_getuid32, __syscall_ioctl: ___syscall_ioctl, __syscall_linkat: ___syscall_linkat, __syscall_lstat64: ___syscall_lstat64, __syscall_mkdirat: ___syscall_mkdirat, __syscall_newfstatat: ___syscall_newfstatat, __syscall_openat: ___syscall_openat, __syscall_readlinkat: ___syscall_readlinkat, __syscall_socket: ___syscall_socket, __syscall_stat64: ___syscall_stat64, __syscall_symlinkat: ___syscall_symlinkat, _abort_js: __abort_js, _emscripten_runtime_keepalive_clear: __emscripten_runtime_keepalive_clear, _gmtime_js: __gmtime_js, _localtime_js: __localtime_js, _setitimer_js: __setitimer_js, _tzset_js: __tzset_js, clock_time_get: _clock_time_get, emscripten_date_now: _emscripten_date_now, emscripten_log: _emscripten_log, emscripten_resize_heap: _emscripten_resize_heap, environ_get: _environ_get, environ_sizes_get: _environ_sizes_get, fd_close: _fd_close, fd_fdstat_get: _fd_fdstat_get, fd_read: _fd_read, fd_seek: _fd_seek, fd_write: _fd_write, proc_exit: _proc_exit }; createWasm(), Module.addFunction = addFunction; var stringToUTF8OnStack = e => { var r = lengthBytesUTF8(e) + 1, t = __emscripten_stack_alloc(r); return stringToUTF8(e, t, r), t }, loadDynamicLibrary = () => { }; function run() { runDependencies > 0 ? dependenciesFulfilled = run : (preRun(), runDependencies > 0 ? dependenciesFulfilled = run : (Module.calledRun = !0, ABORT || (initRuntime(), Module.UTF8ToString = UTF8ToString, wasmImports = wasmExports, _emscripten_bind_funcs(addFunction(((e, r, t) => stringToUTF8OnStack(self[UTF8ToString(e)][UTF8ToString(r)]()[UTF8ToString(t)]())), "iiii")), _emscripten_bind_funcs(addFunction(((e, r, t) => stringToUTF8OnStack((new (self[UTF8ToString(e)]))[UTF8ToString(r)](UTF8ToString(t)))), "iiii")), _emscripten_bind_funcs(addFunction(((e, r, t, n) => { self[UTF8ToString(e)](null, UTF8ToString(r).trim(), UTF8ToString(t), n) }), "viiii")), _emscripten_bind_funcs(addFunction(((e, r, t, n) => stringToUTF8OnStack(self[UTF8ToString(e)][UTF8ToString(r)][UTF8ToString(t)](UTF8ToString(n)) ? "" : self[UTF8ToString(e)][UTF8ToString(r)])), "iiiii")), Module.onRuntimeInitialized?.(), postRun()))) } run(); \ No newline at end of file diff --git a/dist/dynamsoft-capture-vision-std@1.4.21/dist/dynamsoft-barcode-reader-bundle.wasm b/dist/dynamsoft-capture-vision-std@1.4.21/dist/dynamsoft-barcode-reader-bundle.wasm new file mode 100644 index 0000000..c0288ab Binary files /dev/null and b/dist/dynamsoft-capture-vision-std@1.4.21/dist/dynamsoft-barcode-reader-bundle.wasm differ diff --git a/dist/dynamsoft-core@3.4.31/dist/core.d.ts b/dist/dynamsoft-core@3.4.31/dist/core.d.ts new file mode 100644 index 0000000..05cfdc7 --- /dev/null +++ b/dist/dynamsoft-core@3.4.31/dist/core.d.ts @@ -0,0 +1,1019 @@ +interface WorkerAutoResources { + [key: string]: { + js?: string[] | boolean; + wasm?: string[] | boolean; + deps?: string[]; + }; +} +interface PostMessageBody { + needLoadCore?: boolean; + bLog?: boolean; + bd?: boolean; + dm?: string; + value?: boolean; + count?: number; + engineResourcePaths?: EngineResourcePaths; + autoResources?: WorkerAutoResources; + names?: string[]; +} +type PathInfo = { + version: string; + path: string; + isInternal?: boolean; +}; +type DwtInfo = { + resourcesPath?: string; + serviceInstallerLocation?: string; +}; +interface EngineResourcePaths { + "rootDirectory"?: string; + "std"?: string | PathInfo; + "dip"?: string | PathInfo; + "dnn"?: string | PathInfo; + "core"?: string | PathInfo; + "license"?: string | PathInfo; + "cvr"?: string | PathInfo; + "utility"?: string | PathInfo; + "dbr"?: string | PathInfo; + "dlr"?: string | PathInfo; + "ddn"?: string | PathInfo; + "dcp"?: string | PathInfo; + "dce"?: string | PathInfo; + "dlrData"?: string | PathInfo; + "ddv"?: string | PathInfo; + "dwt"?: string | DwtInfo; +} +interface InnerVersions { + [key: string]: { + worker?: string; + wasm?: string; + }; +} +interface WasmVersions { + "DIP"?: string; + "DNN"?: string; + "CORE"?: string; + "LICENSE"?: string; + "CVR"?: string; + "UTILITY"?: string; + "DBR"?: string; + "DLR"?: string; + "DDN"?: string; + "DCP"?: string; +} +interface MapController { + [key: string]: ((body: any, taskID: number, instanceID?: number) => void); +} +type MimeType = "image/png" | "image/jpeg"; + +declare const mapAsyncDependency: { + [key: string]: any; +}; +declare const waitAsyncDependency: (depName: string | string[]) => Promise; +declare const doOrWaitAsyncDependency: (depName: string | string[], asyncFunc: () => Promise) => Promise; +declare let worker: Worker; +declare const getNextTaskID: () => number; +declare const mapTaskCallBack: { + [key: string]: Function; +}; +declare let onLog: (message: string) => void | undefined; +declare const setOnLog: (value: typeof onLog) => void; +declare let bDebug: boolean; +declare const setBDebug: (value: boolean) => void; +declare const innerVersions: InnerVersions; +declare const mapPackageRegister: { + [key: string]: any; +}; +declare const workerAutoResources: WorkerAutoResources; +declare const loadWasm: (names?: string[] | string) => Promise; +declare class CoreModule { + static get engineResourcePaths(): EngineResourcePaths; + static set engineResourcePaths(value: EngineResourcePaths); + private static _bSupportDce4Module; + static get bSupportDce4Module(): number; + private static _bSupportIRTModule; + static get bSupportIRTModule(): number; + private static _versions; + static get versions(): any; + static get _onLog(): (message: string) => void; + static set _onLog(value: (message: string) => void); + static get _bDebug(): boolean; + static set _bDebug(value: boolean); + static _workerName: string; + /** + * Determine if the decoding module has been loaded successfully. + * @category Initialize and Destroy + */ + static isModuleLoaded(name?: string): boolean; + static loadWasm(names?: string[] | string): Promise; + /** + * Detect environment and get a report. + */ + static detectEnvironment(): Promise; + /** + * modify from https://gist.github.com/2107/5529665 + * @ignore + */ + static browserInfo: any; + static getModuleVersion(): Promise; + static getVersion(): string; + static enableLogging(): void; + static disableLogging(): void; + static cfd(count: number): Promise; +} + +declare enum EnumImageTagType { + ITT_FILE_IMAGE = 0, + ITT_VIDEO_FRAME = 1 +} + +interface ImageTag { + imageId: number; + type: EnumImageTagType; +} + +declare enum EnumImagePixelFormat { + IPF_BINARY = 0, + IPF_BINARYINVERTED = 1, + IPF_GRAYSCALED = 2, + IPF_NV21 = 3, + IPF_RGB_565 = 4, + IPF_RGB_555 = 5, + IPF_RGB_888 = 6, + IPF_ARGB_8888 = 7, + IPF_RGB_161616 = 8, + IPF_ARGB_16161616 = 9, + IPF_ABGR_8888 = 10, + IPF_ABGR_16161616 = 11, + IPF_BGR_888 = 12, + IPF_BINARY_8 = 13, + IPF_NV12 = 14, + IPF_BINARY_8_INVERTED = 15 +} + +interface DSImageData { + bytes: Uint8Array; + width: number; + height: number; + stride: number; + format: EnumImagePixelFormat; + tag?: ImageTag; +} + +declare enum EnumBufferOverflowProtectionMode { + /** New images are blocked when the buffer is full.*/ + BOPM_BLOCK = 0, + /** New images are appended at the end, and oldest images are pushed out from the beginning if the buffer is full.*/ + BOPM_UPDATE = 1 +} + +declare enum EnumColourChannelUsageType { + CCUT_AUTO = 0, + CCUT_FULL_CHANNEL = 1, + CCUT_Y_CHANNEL_ONLY = 2, + CCUT_RGB_R_CHANNEL_ONLY = 3, + CCUT_RGB_G_CHANNEL_ONLY = 4, + CCUT_RGB_B_CHANNEL_ONLY = 5 +} + +declare enum EnumCapturedResultItemType { + CRIT_ORIGINAL_IMAGE = 1, + CRIT_BARCODE = 2, + CRIT_TEXT_LINE = 4, + CRIT_DETECTED_QUAD = 8, + CRIT_NORMALIZED_IMAGE = 16, + CRIT_PARSED_RESULT = 32 +} + +interface CapturedResultItem { + readonly type: EnumCapturedResultItemType; + readonly referenceItem: CapturedResultItem | null; + readonly targetROIDefName: string; + readonly taskName: string; +} + +interface OriginalImageResultItem extends CapturedResultItem { + readonly imageData: DSImageData; +} + +interface Point { + x: number; + y: number; +} + +interface Contour { + points: Array; +} + +declare enum EnumCornerType { + CT_NORMAL_INTERSECTED = 0, + CT_T_INTERSECTED = 1, + CT_CROSS_INTERSECTED = 2, + CT_NOT_INTERSECTED = 3 +} + +/** + * `ErrorCode` enumerates the specific error codes that the SDK may return, providing a systematic way to identify and handle errors encountered during its operation. + */ +declare enum EnumErrorCode { + /** Operation completed successfully. */ + EC_OK = 0, + /** An unspecified error occurred. */ + EC_UNKNOWN = -10000, + /** The system does not have enough memory to perform the requested operation. */ + EC_NO_MEMORY = -10001, + /** A null pointer was encountered where a valid pointer was required. */ + EC_NULL_POINTER = -10002, + /** The provided license is not valid. */ + EC_LICENSE_INVALID = -10003, + /** The provided license has expired. */ + EC_LICENSE_EXPIRED = -10004, + /** The specified file could not be found. */ + EC_FILE_NOT_FOUND = -10005, + /** The file type is not supported for processing. */ + EC_FILE_TYPE_NOT_SUPPORTED = -10006, + /** The image's bits per pixel (BPP) is not supported. */ + EC_BPP_NOT_SUPPORTED = -10007, + /** The specified index is out of the valid range. */ + EC_INDEX_INVALID = -10008, + /** The specified custom region value is invalid or out of range. */ + EC_CUSTOM_REGION_INVALID = -10010, + /** Failed to read the image due to an error in accessing or interpreting the image data. */ + EC_IMAGE_READ_FAILED = -10012, + /** Failed to read a TIFF image, possibly due to corruption or unsupported format. */ + EC_TIFF_READ_FAILED = -10013, + /** The provided DIB (Device-Independent Bitmaps) buffer is invalid or corrupted. */ + EC_DIB_BUFFER_INVALID = -10018, + /** Failed to read a PDF image, possibly due to corruption or unsupported format. */ + EC_PDF_READ_FAILED = -10021, + /** Required PDF processing DLL is missing. */ + EC_PDF_DLL_MISSING = -10022, + /** The specified page number is invalid or out of bounds for the document. */ + EC_PAGE_NUMBER_INVALID = -10023, + /** The specified custom size is invalid or not supported. */ + EC_CUSTOM_SIZE_INVALID = -10024, + /** The operation timed out. */ + EC_TIMEOUT = -10026, + /** Failed to parse JSON input. */ + EC_JSON_PARSE_FAILED = -10030, + /** The JSON type is invalid for the expected context. */ + EC_JSON_TYPE_INVALID = -10031, + /** The JSON key is invalid or unrecognized in the current context. */ + EC_JSON_KEY_INVALID = -10032, + /** The JSON value is invalid for the specified key. */ + EC_JSON_VALUE_INVALID = -10033, + /** The required "Name" key is missing in the JSON data. */ + EC_JSON_NAME_KEY_MISSING = -10034, + /** The value of the "Name" key is duplicated and conflicts with existing data. */ + EC_JSON_NAME_VALUE_DUPLICATED = -10035, + /** The template name is invalid or does not match any known template. */ + EC_TEMPLATE_NAME_INVALID = -10036, + /** The reference made by the "Name" key is invalid or points to nonexistent data. */ + EC_JSON_NAME_REFERENCE_INVALID = -10037, + /** The parameter value provided is invalid or out of the expected range. */ + EC_PARAMETER_VALUE_INVALID = -10038, + /** The domain of the current site does not match the domain bound to the current product key. */ + EC_DOMAIN_NOT_MATCH = -10039, + /** The reserved information does not match the reserved info bound to the current product key. */ + EC_RESERVED_INFO_NOT_MATCH = -10040, + /** The license key does not match the license content. */ + EC_LICENSE_KEY_NOT_MATCH = -10043, + /** Failed to request the license content from the server. */ + EC_REQUEST_FAILED = -10044, + /** Failed to initialize the license. */ + EC_LICENSE_INIT_FAILED = -10045, + /** Error setting the mode's argument, indicating invalid or incompatible arguments. */ + EC_SET_MODE_ARGUMENT_ERROR = -10051, + /** The license content is invalid or corrupted. */ + EC_LICENSE_CONTENT_INVALID = -10052, + /** The license key is invalid or does not match any known valid keys. */ + EC_LICENSE_KEY_INVALID = -10053, + /** The license key has reached its maximum allowed usage and has no remaining quota. */ + EC_LICENSE_DEVICE_RUNS_OUT = -10054, + /** Failed to retrieve the mode's argument, possibly due to invalid state or configuration. */ + EC_GET_MODE_ARGUMENT_ERROR = -10055, + /** The Intermediate Result Types (IRT) license is invalid or not present. */ + EC_IRT_LICENSE_INVALID = -10056, + /** Failed to save the file, possibly due to permissions, space, or an invalid path. */ + EC_FILE_SAVE_FAILED = -10058, + /** The specified stage type is invalid or not supported in the current context. */ + EC_STAGE_TYPE_INVALID = -10059, + /** The specified image orientation is invalid or not supported. */ + EC_IMAGE_ORIENTATION_INVALID = -10060, + /** Failed to convert complex template to simplified settings, indicating a configuration or compatibility issue. */ + EC_CONVERT_COMPLEX_TEMPLATE_ERROR = -10061, + /** Rejecting function call while capturing is in progress, to prevent conflicts or data corruption. */ + EC_CALL_REJECTED_WHEN_CAPTURING = -10062, + /** The specified image source was not found, indicating a missing or inaccessible input source. */ + EC_NO_IMAGE_SOURCE = -10063, + /** Failed to read the directory, possibly due to permissions, non-existence, or other access issues. */ + EC_READ_DIRECTORY_FAILED = -10064, + /** A required module (e.g., DynamsoftBarcodeReader, DynamsoftLabelRecognizer) was not found. */ + EC_MODULE_NOT_FOUND = -10065, + /** The operation does not support multi-page files; use FileFetcher for processing such files. */ + EC_MULTI_PAGES_NOT_SUPPORTED = -10066, + /** Indicates an attempt to write to a file that already exists, with overwriting explicitly disabled. This error suggests the need for either enabling overwriting or ensuring unique file names to avoid conflicts. */ + EC_FILE_ALREADY_EXISTS = -10067, + /** The specified file path does not exist and could not be created. This error could be due to insufficient permissions, a read-only filesystem, or other environmental constraints preventing file creation. */ + EC_CREATE_FILE_FAILED = -10068, + /** The input ImageData object contains invalid parameters. This could be due to incorrect data types, out-of-range values, or improperly formatted data being passed to a function expecting ImageData. */ + EC_IMGAE_DATA_INVALID = -10069, + /** The size of the input image does not meet the requirements. */ + EC_IMAGE_SIZE_NOT_MATCH = -10070, + /** The pixel format of the input image does not meet the requirements. */ + EC_IMAGE_PIXEL_FORMAT_NOT_MATCH = -10071, + /** The section level result is irreplaceable. */ + EC_SECTION_LEVEL_RESULT_IRREPLACEABLE = -10072, + /** Incorrect axis definition. */ + EC_AXIS_DEFINITION_INCORRECT = -10073, + /**The result is not replaceable due to type mismatch*/ + EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE = -10074, + /**Failed to load the PDF library.*/ + EC_PDF_LIBRARY_LOAD_FAILED = -10075, + /** Indicates no license is available or the license is not set. */ + EC_NO_LICENSE = -20000, + /** The provided Handshake Code is invalid or does not match expected format. */ + EC_HANDSHAKE_CODE_INVALID = -20001, + /** Encountered failures while attempting to read or write to the license buffer. */ + EC_LICENSE_BUFFER_FAILED = -20002, + /** Synchronization with the license server failed, possibly due to network issues or server unavailability. */ + EC_LICENSE_SYNC_FAILED = -20003, + /** The device attempting to use the license does not match the device specified in the license buffer. */ + EC_DEVICE_NOT_MATCH = -20004, + /** Binding the device to the license failed, indicating possible issues with the license or device identifier. */ + EC_BIND_DEVICE_FAILED = -20005, + /** The number of instances using the license exceeds the limit allowed by the license terms. */ + EC_INSTANCE_COUNT_OVER_LIMIT = -20008, + /** InitLicenseFromDLS must be called before any SDK objects are created to ensure proper license initialization. */ + EC_LICENSE_INIT_SEQUENCE_FAILED = -20009, + /** Indicates the license in use is a trial version with limited functionality or usage time. */ + EC_TRIAL_LICENSE = -20010, + /** The system failed to reach the License Server, likely due to network connectivity issues. */ + EC_FAILED_TO_REACH_DLS = -20200, + /** Online license validation failed due to network issues. Using cached license information for validation.*/ + EC_LICENSE_CACHE_USED = -20012, + /** The specified barcode format is invalid or unsupported. */ + EC_BARCODE_FORMAT_INVALID = -30009, + /** The license for decoding QR Codes is invalid or not present. */ + EC_QR_LICENSE_INVALID = -30016, + /** The license for decoding 1D barcodes is invalid or not present. */ + EC_1D_LICENSE_INVALID = -30017, + /** The license for decoding PDF417 barcodes is invalid or not present. */ + EC_PDF417_LICENSE_INVALID = -30019, + /** The license for decoding DataMatrix barcodes is invalid or not present. */ + EC_DATAMATRIX_LICENSE_INVALID = -30020, + /** The specified custom module size for barcode generation is invalid or outside acceptable limits. */ + EC_CUSTOM_MODULESIZE_INVALID = -30025, + /** The license for decoding Aztec barcodes is invalid or not present. */ + EC_AZTEC_LICENSE_INVALID = -30041, + /** The license for decoding Patchcode barcodes is invalid or not present. */ + EC_PATCHCODE_LICENSE_INVALID = -30046, + /** The license for decoding postal code formats is invalid or not present. */ + EC_POSTALCODE_LICENSE_INVALID = -30047, + /** The license for Direct Part Marking (DPM) decoding is invalid or not present. */ + EC_DPM_LICENSE_INVALID = -30048, + /** A frame decoding thread is already running, indicating a concurrent operation conflict. */ + EC_FRAME_DECODING_THREAD_EXISTS = -30049, + /** Stopping the frame decoding thread failed, indicating potential issues with thread management. */ + EC_STOP_DECODING_THREAD_FAILED = -30050, + /** The license for decoding MaxiCode barcodes is invalid or not present. */ + EC_MAXICODE_LICENSE_INVALID = -30057, + /** The license for decoding GS1 DataBar barcodes is invalid or not present. */ + EC_GS1_DATABAR_LICENSE_INVALID = -30058, + /** The license for decoding GS1 Composite codes is invalid or not present. */ + EC_GS1_COMPOSITE_LICENSE_INVALID = -30059, + /** The license for decoding DotCode barcodes is invalid or not present. */ + EC_DOTCODE_LICENSE_INVALID = -30061, + /** The license for decoding Pharmacode barcodes is invalid or not present. */ + EC_PHARMACODE_LICENSE_INVALID = -30062, + /** Indicates that the required character model file was not found, possibly due to incorrect paths or missing files. */ + EC_CHARACTER_MODEL_FILE_NOT_FOUND = -40100, + /**There is a conflict in the layout of TextLineGroup. */ + EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT = -40101, + /**There is a conflict in the regex of TextLineGroup. */ + EC_TEXT_LINE_GROUP_REGEX_CONFLICT = -40102, + /** The specified quadrilateral is invalid, potentially due to incorrect points or an unprocessable shape. */ + EC_QUADRILATERAL_INVALID = -50057, + /** The license for generating or processing panoramas is invalid or missing. */ + EC_PANORAMA_LICENSE_INVALID = -70060, + /** The specified resource path does not exist, indicating a missing directory or incorrect path specification. */ + EC_RESOURCE_PATH_NOT_EXIST = -90001, + /** Failed to load the specified resource, which might be due to missing files, access rights, or other issues preventing loading. */ + EC_RESOURCE_LOAD_FAILED = -90002, + /** The code specification required for processing was not found, indicating a missing or incorrect specification. */ + EC_CODE_SPECIFICATION_NOT_FOUND = -90003, + /** The full code string provided is empty, indicating no data was provided for processing. */ + EC_FULL_CODE_EMPTY = -90004, + /** Preprocessing the full code string failed, possibly due to invalid format, corruption, or unsupported features. */ + EC_FULL_CODE_PREPROCESS_FAILED = -90005, + /** The license required for parsing South Africa Driver License data is invalid or not present. */ + EC_ZA_DL_LICENSE_INVALID = -90006, + /** The license required for parsing North America DL/ID (AAMVA) data is invalid or not present. */ + EC_AAMVA_DL_ID_LICENSE_INVALID = -90007, + /** The license required for parsing Aadhaar data is invalid or not present. */ + EC_AADHAAR_LICENSE_INVALID = -90008, + /** The license required for parsing Machine Readable Travel Documents (MRTD) is invalid or not present. */ + EC_MRTD_LICENSE_INVALID = -90009, + /** The license required for parsing Vehicle Identification Number (VIN) data is invalid or not present. */ + EC_VIN_LICENSE_INVALID = -90010, + /** The license required for parsing customized code types is invalid or not present. */ + EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID = -90011, + /**The license is initialized successfully but detected invalid content in your key.*/ + EC_LICENSE_WARNING = -10076, + /** [Barcode Reader] No license found.*/ + EC_BARCODE_READER_LICENSE_NOT_FOUND = -30063, + /**[Label Recognizer] No license found.*/ + EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND = -40103, + /**[Document Normalizer] No license found.*/ + EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND = -50058, + /**[Code Parser] No license found.*/ + EC_CODE_PARSER_LICENSE_NOT_FOUND = -90012 +} + +declare enum EnumGrayscaleEnhancementMode { + /**Skips grayscale transformation. */ + GEM_SKIP = 0, + /**Not supported yet. */ + GEM_AUTO = 1, + /**Takes the unpreprocessed image for following operations. */ + GEM_GENERAL = 2, + /**Preprocesses the image using the gray equalization algorithm. Check @ref IPM for available argument settings.*/ + GEM_GRAY_EQUALIZE = 4, + /**Preprocesses the image using the gray smoothing algorithm. Check @ref IPM for available argument settings.*/ + GEM_GRAY_SMOOTH = 8, + /**Preprocesses the image using the sharpening and smoothing algorithm. Check @ref IPM for available argument settings.*/ + GEM_SHARPEN_SMOOTH = 16, + /**Skips image preprocessing. */ + GEM_REV = -2147483648 +} + +declare enum EnumGrayscaleTransformationMode { + /**Skips grayscale transformation. */ + GTM_SKIP = 0, + /**Transforms to inverted grayscale. Recommended for light on dark images. */ + GTM_INVERTED = 1, + /**Keeps the original grayscale. Recommended for dark on light images. */ + GTM_ORIGINAL = 2, + /**Lets the library choose an algorithm automatically for grayscale transformation.*/ + GTM_AUTO = 4, + /**Reserved setting for grayscale transformation mode.*/ + GTM_REV = -2147483648 +} + +declare enum EnumPDFReadingMode { + /** Outputs vector data found in the PDFs.*/ + PDFRM_VECTOR = 1, + /** The default value. + * Outputs raster data found in the PDFs. + * Depending on the argument Resolution, + * the SDK may rasterize the PDF pages. + * Check the template for available argument settings.*/ + PDFRM_RASTER = 2, + PDFRM_REV = -2147483648 +} + +declare enum EnumRasterDataSource { + /** Specifies the target type for reading a PDF. */ + RDS_RASTERIZED_PAGES = 0, + RDS_EXTRACTED_IMAGES = 1 +} + +declare enum EnumCrossVerificationStatus { + /** The cross verification has not been performed yet. */ + CVS_NOT_VERIFIED = 0, + /** The cross verification has been passed successfully. */ + CVS_PASSED = 1, + /** The cross verification has failed. */ + CVS_FAILED = 2 +} + +declare const EnumIntermediateResultUnitType: { + /** No intermediate result. */ + IRUT_NULL: bigint; + /** A full-color image. */ + IRUT_COLOUR_IMAGE: bigint; + /** A color image that has been scaled down for efficiency. */ + IRUT_SCALED_DOWN_COLOUR_IMAGE: bigint; + /** A grayscale image derived from the original input. */ + IRUT_GRAYSCALE_IMAGE: bigint; + /** A grayscale image that has undergone transformation. */ + IRUT_TRANSOFORMED_GRAYSCALE_IMAGE: bigint; + /** A grayscale image enhanced for further processing. */ + IRUT_ENHANCED_GRAYSCALE_IMAGE: bigint; + /** Regions pre-detected as potentially relevant for further analysis. */ + IRUT_PREDETECTED_REGIONS: bigint; + /** A binary (black and white) image. */ + IRUT_BINARY_IMAGE: bigint; + /** Results from detecting textures within the image. */ + IRUT_TEXTURE_DETECTION_RESULT: bigint; + /** A grayscale image with textures removed to enhance subject details like text or barcodes. */ + IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE: bigint; + /** A binary image with textures removed), useful for clear detection of subjects without background noise. */ + IRUT_TEXTURE_REMOVED_BINARY_IMAGE: bigint; + /** Detected contours within the image), which can help in identifying shapes and objects. */ + IRUT_CONTOURS: bigint; + /** Detected line segments), useful in structural analysis of the image content. */ + IRUT_LINE_SEGMENTS: bigint; + /** Identified text zones), indicating areas with potential textual content. */ + IRUT_TEXT_ZONES: bigint; + /** A binary image with text regions removed. */ + IRUT_TEXT_REMOVED_BINARY_IMAGE: bigint; + /** Zones identified as potential barcode areas), aiding in focused barcode detection. */ + IRUT_CANDIDATE_BARCODE_ZONES: bigint; + /** Barcodes that have been localized but not yet decoded. */ + IRUT_LOCALIZED_BARCODES: bigint; + /** Barcode images scaled up for improved readability or decoding accuracy. */ + IRUT_SCALED_UP_BARCODE_IMAGE: bigint; + /** Images of barcodes processed to resist deformation and improve decoding success. */ + IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE: bigint; + /** Barcode images that have been complemented. */ + IRUT_COMPLEMENTED_BARCODE_IMAGE: bigint; + /** Successfully decoded barcodes. */ + IRUT_DECODED_BARCODES: bigint; + /** Detected long lines. */ + IRUT_LONG_LINES: bigint; + /** Detected corners within the image. */ + IRUT_CORNERS: bigint; + /** Candidate edges identified as potential components of quadrilaterals. */ + IRUT_CANDIDATE_QUAD_EDGES: bigint; + /** Successfully detected quadrilaterals. */ + IRUT_DETECTED_QUADS: bigint; + /** Text lines that have been localized in preparation for recognition. */ + IRUT_LOCALIZED_TEXT_LINES: bigint; + /** Successfully recognized text lines. */ + IRUT_RECOGNIZED_TEXT_LINES: bigint; + /** Successfully normalized images. */ + IRUT_NORMALIZED_IMAGES: bigint; + /** Successfully detected short lines. */ + IRUT_SHORT_LINES: bigint; + IRUT_RAW_TEXT_LINES: bigint; + /** Detected logic lines. */ + IRUT_LOGIC_LINES: bigint; + /** A mask to select all types of intermediate results. */ + IRUT_ALL: bigint; +}; +type EnumIntermediateResultUnitType = bigint; + +declare enum EnumRegionObjectElementType { + ROET_PREDETECTED_REGION = 0, + ROET_LOCALIZED_BARCODE = 1, + ROET_DECODED_BARCODE = 2, + ROET_LOCALIZED_TEXT_LINE = 3, + ROET_RECOGNIZED_TEXT_LINE = 4, + ROET_DETECTED_QUAD = 5, + ROET_NORMALIZED_IMAGE = 6, + ROET_SOURCE_IMAGE = 7, + ROET_TARGET_ROI = 8 +} + +declare enum EnumSectionType { + ST_NULL = 0, + ST_REGION_PREDETECTION = 1, + ST_BARCODE_LOCALIZATION = 2, + ST_BARCODE_DECODING = 3, + ST_TEXT_LINE_LOCALIZATION = 4, + ST_TEXT_LINE_RECOGNITION = 5, + ST_DOCUMENT_DETECTION = 6, + ST_DOCUMENT_NORMALIZATION = 7 +} + +interface LineSegment { + startPoint: Point; + endPoint: Point; +} + +interface Corner { + type: EnumCornerType; + intersection: Point; + line1: LineSegment; + line2: LineSegment; +} + +interface Rect { + x: number; + y: number; + width: number; + height: number; + isMeasuredInPercentage?: boolean; +} + +interface Arc { + x: number; + y: number; + radius: number; + startAngle: number; + endAngle: number; +} + +interface Polygon { + points: Array; +} + +interface DSRect { + left: number; + right: number; + top: number; + bottom: number; + isMeasuredInPercentage: boolean; +} + +interface Edge { + startCorner: Corner; + endCorner: Corner; +} + +interface FileImageTag extends ImageTag { + filePath: string; + pageNumber: number; + totalPages: number; +} + +interface ImageSourceErrorListener { + /** + * Called when an error is received from the image source. + * + * @param errorCode An enumeration value of type "EnumErrorCode" indicating the type of error. + * @param errorMessage A C-style string containing the error message providing + * additional information about the error. + */ + onErrorReceived: (errorCode: EnumErrorCode, errorMessage: string) => void; +} + +interface PDFReadingParameter { + mode: EnumPDFReadingMode; + dpi: number; + rasterDataSource: EnumRasterDataSource; +} + +interface Quadrilateral { + points: [Point, Point, Point, Point]; + area?: number; +} + +interface DSFile extends File { + download: () => void; +} + +interface Warning { + id: number; + message: string; +} + +declare enum EnumTransformMatrixType { + TMT_LOCAL_TO_ORIGINAL_IMAGE = 0, + TMT_ORIGINAL_TO_LOCAL_IMAGE = 1 +} + +interface IntermediateResultUnit { + hashId: string; + originalImageHashId: string; + originalImageTag: ImageTag; + unitType: EnumIntermediateResultUnitType; + /** + * For the two types TMT_LOCAL_TO_ORIGINAL_IMAGE & TMT_ORIGINAL_TO_LOCAL_IMAGE, we can get both from C++ and then keep the + * information in JS. Only return the information when customer calls getTransformMatrix with a specified type. + */ + getTransformMatrix: (matrixType: EnumTransformMatrixType) => Array; +} + +interface BinaryImageUnit extends IntermediateResultUnit { + imageData: DSImageData; +} + +interface ColourImageUnit extends IntermediateResultUnit { + imageData: DSImageData; +} + +interface ContoursUnit extends IntermediateResultUnit { + contours: Array; +} + +interface EnhancedGrayscaleImageUnit extends IntermediateResultUnit { + imageData: DSImageData; +} + +interface GrayscaleImageUnit extends IntermediateResultUnit { + imageData: DSImageData; +} + +interface IntermediateResult { + intermediateResultUnits: Array; +} + +interface IntermediateResultExtraInfo { + targetROIDefName: string; + taskName: string; + isSectionLevelResult: boolean; + sectionType: EnumSectionType; +} + +interface LineSegmentsUnit extends IntermediateResultUnit { + lineSegments: Array; +} + +interface RegionObjectElement { + /** + * location was readonly before v3.2.0 + * In 3.2.0 onwards, it can be set as well + * When setting, specify the location as well as + * the matrixToOriginalImage + */ + location: Quadrilateral; + referencedElement: RegionObjectElement; + elementType: EnumRegionObjectElementType; +} + +interface PredetectedRegionElement extends RegionObjectElement { + modeName: string; +} + +interface PredetectedRegionsUnit extends IntermediateResultUnit { + predetectedRegions: Array; +} + +interface ScaledDownColourImageUnit extends IntermediateResultUnit { + imageData: DSImageData; +} + +interface ShortLinesUnit extends IntermediateResultUnit { + shortLines: Array; +} + +interface TextRemovedBinaryImageUnit extends IntermediateResultUnit { + imageData: DSImageData; +} + +interface TextureDetectionResultUnit extends IntermediateResultUnit { + xSpacing: number; + ySpacing: number; +} + +interface TextureRemovedBinaryImageUnit extends IntermediateResultUnit { + imageData: DSImageData; +} + +interface TextureRemovedGrayscaleImageUnit extends IntermediateResultUnit { + imageData: DSImageData; +} + +interface TextZone { + location: Quadrilateral; + charContoursIndices: Array; +} + +interface TextZonesUnit extends IntermediateResultUnit { + textZones: Array; +} + +interface TransformedGrayscaleImageUnit extends IntermediateResultUnit { + imageData: DSImageData; +} + +/** + * The `ObservationParameters` interface represents an object used to configure intermediate result observation. + */ +interface ObservationParameters { + /** + * Sets the types of intermediate result units that are observed. + * @param types The types of intermediate result units to observe. + * @returns A promise that resolves when the types have been successfully set. It does not provide any value upon resolution. + */ + setObservedResultUnitTypes: (types: bigint) => void; + /** + * Retrieves the types of intermediate result units that are observed. + * @returns A promise that resolves with a number that represents the types that are observed. + */ + getObservedResultUnitTypes: () => bigint; + /** + * Determines whether the specified result unit type is observed. + * @param type The result unit type to check. + * @returns Boolean indicating whether the result unit type is observed. + */ + isResultUnitTypeObserved: (type: EnumIntermediateResultUnitType) => boolean; + /** + * Adds an observed task by its name. + * @param taskName The name of the task. + */ + addObservedTask: (taskName: string) => void; + /** + * Removes an observed task by its name. + * @param taskName The name of the task. + */ + removeObservedTask: (taskName: string) => void; + /** + * Determines whether the specified task is observed. + * @param taskName The name of the task. + * @returns Boolean indicating whether the task is observed. + */ + isTaskObserved: (taskName: string) => boolean; +} + +declare abstract class ImageSourceAdapter { + #private; + /** + * @ignore + */ + static _onLog: (message: any) => void; + /** + * @ignore + */ + get _isFetchingStarted(): boolean; + constructor(); + abstract hasNextImageToFetch(): boolean; + /** + * @brief Sets the error listener for the image source. + * + * This function allows you to set an error listener object that will receive + * notifications when errors occur during image source operations. + * If an error occurs, the error information will be passed to the listener's + * OnErrorReceived method. + * + * @param listener An instance of ImageSourceErrorListener or its + * derived class, which will handle error notifications. + */ + setErrorListener(listener: ImageSourceErrorListener): void; + /** + * Adds an image to the internal buffer. + * + * @param image An instance of `DSImageData` containing the image to buffer. + */ + addImageToBuffer(image: DSImageData): void; + /** + * Retrieves a buffered image, of type `DSImageData`. + * + * This function retrieves the latest image added to the buffer, and removes it from the buffer in the process. + * + * @returns A `DSImageData` object retrieved from the buffer which contains the image data of the frame and related information. + */ + getImage(): DSImageData; + /** + * Sets the processing priority of a specific image. This can affect the order in which images are returned by getImage. + * + * @param imageId The ID of the image to prioritize. + * @param keepInBuffer [Optional] Boolean indicating whether to keep the image in the buffer after it has been returned. + */ + setNextImageToReturn(imageId: number, keepInBuffer?: boolean): void; + /** + * @ignore + */ + _resetNextReturnedImage(): void; + /** + * Checks if an image with the specified ID is present in the buffer. + * + * @param imageId The ID of the image to check. + * + * @returns Boolean indicating whether the image is present in the buffer. + */ + hasImage(imageId: number): boolean; + /** + * Starts the process of fetching images. + */ + startFetching(): void; + /** + * Stops the process of fetching images. + * to false, indicating that image fetching has been halted. + */ + stopFetching(): void; + /** + * Sets the maximum number of images that can be buffered at any time. Implementing classes should attempt to keep the buffer within this limit. + * + * @param count The maximum number of images the buffer can hold. + */ + setMaxImageCount(count: number): void; + /** + * Retrieves the maximum number of images that can be buffered. + * + * @returns The maximum image count for the buffer. + */ + getMaxImageCount(): number; + /** + * Retrieves the current number of images in the buffer. + * + * @returns The current image count in the buffer. + */ + getImageCount(): number; + /** + * Clears all images from the buffer, resetting the state for new image fetching. + */ + clearBuffer(): void; + /** + * Determines whether the buffer is currently empty. + * + * @returns Boolean indicating whether the buffer is empty. + */ + isBufferEmpty(): boolean; + /** + * Sets the behavior for handling new incoming images when the buffer is full. Implementations should adhere to the specified mode to manage buffer overflow. + * + * @param mode One of the modes defined in EnumBufferOverflowProtectionMode, specifying how to handle buffer overflow. + */ + setBufferOverflowProtectionMode(mode: EnumBufferOverflowProtectionMode): void; + /** + * Retrieves the current mode for handling buffer overflow. + * + * @returns The current buffer overflow protection mode. + */ + getBufferOverflowProtectionMode(): EnumBufferOverflowProtectionMode; + /** + * Sets the usage type for color channels in images. + * + * @param type One of the types defined in EnumColourChannelUsageType, specifying how color channels should be used. + */ + setColourChannelUsageType(type: EnumColourChannelUsageType): void; + /** + * Retrieves the current mode for handling buffer overflow. + * + * @returns The current buffer overflow protection mode. + */ + getColourChannelUsageType(): EnumColourChannelUsageType; +} + +/** + * Judge if the input is an object(exclude array and function). If `null` or `undefined`, return `false`. + * @param value + * @returns + */ +declare const isObject: (value: any) => value is Object; +/** + * Judge is the input is a {@link Arc} object. + * @param value + * @returns + * @ignore + */ +declare const isArc: (value: any) => value is Arc; +/** + * Judge is the input is a {@link Contour} object. + * @param value + * @returns + * @ignore + */ +declare const isContour: (value: any) => value is Contour; +declare const isOriginalDsImageData: (value: any) => boolean; +/** + * Judge is the input is a {@link DSImageData} object. + * @param value + * @returns + * @ignore + */ +declare const isDSImageData: (value: any) => value is DSImageData; +/** + * Judge is the input is a {@link DSRect} object. + * @param value + * @returns + * @ignore + */ +declare const isDSRect: (value: any) => value is DSRect; +/** + * Judge is the input is a {@link ImageTag} object. + * @param value + * @returns + * @ignore + */ +declare const isImageTag: (value: any) => value is ImageTag; +/** + * Judge is the input is a {@link LineSegment} object. + * @param value + * @returns + * @ignore + */ +declare const isLineSegment: (value: any) => value is LineSegment; +/** + * Judge is the input is a {@link Point} object. + * @param value + * @returns + * @ignore + */ +declare const isPoint: (value: any) => value is Point; +/** + * Judge is the input is a {@link Polygon} object. + * @param value + * @returns + * @ignore + */ +declare const isPolygon: (value: any) => value is Polygon; +/** + * Judge is the input is a {@link Quadrilateral} object. + * @param value + * @returns + * @ignore + */ +declare const isQuad: (value: any) => value is Quadrilateral; +/** + * Judge is the input is a {@link Rect} object. + * @param value + * @returns + * @ignore + */ +declare const isRect: (value: any) => value is Rect; + +declare const requestResource: (url: string, type: "text" | "blob" | "arraybuffer") => Promise; +declare const checkIsLink: (str: string) => boolean; +declare const compareVersion: (strV1: string, strV2: string) => number; +declare const handleEngineResourcePaths: (engineResourcePaths: EngineResourcePaths) => EngineResourcePaths; +declare const _saveToFile: (imageData: ImageData, name: string, download?: boolean) => Promise; +declare const _toCanvas: (imageData: ImageData | DSImageData) => HTMLCanvasElement; +declare const _toImage: (MIMEType: MimeType, imageData: ImageData | DSImageData) => HTMLImageElement; +declare const _toBlob: (MIMEType: MimeType, imageData: ImageData | DSImageData) => Promise; +declare const _getNorImageData: (dsImageData: DSImageData) => ImageData; + +export { Arc, BinaryImageUnit, CapturedResultItem, ColourImageUnit, Contour, ContoursUnit, CoreModule, Corner, DSFile, DSImageData, DSRect, DwtInfo, Edge, EngineResourcePaths, EnhancedGrayscaleImageUnit, EnumBufferOverflowProtectionMode, EnumCapturedResultItemType, EnumColourChannelUsageType, EnumCornerType, EnumCrossVerificationStatus, EnumErrorCode, EnumGrayscaleEnhancementMode, EnumGrayscaleTransformationMode, EnumImagePixelFormat, EnumImageTagType, EnumIntermediateResultUnitType, EnumPDFReadingMode, EnumRasterDataSource, EnumRegionObjectElementType, EnumSectionType, FileImageTag, GrayscaleImageUnit, ImageSourceAdapter, ImageSourceErrorListener, ImageTag, InnerVersions, IntermediateResult, IntermediateResultExtraInfo, IntermediateResultUnit, LineSegment, LineSegmentsUnit, MapController, MimeType, ObservationParameters, OriginalImageResultItem, PDFReadingParameter, PathInfo, Point, Polygon, PostMessageBody, PredetectedRegionElement, PredetectedRegionsUnit, Quadrilateral, Rect, RegionObjectElement, ScaledDownColourImageUnit, ShortLinesUnit, TextRemovedBinaryImageUnit, TextZonesUnit, TextureDetectionResultUnit, TextureRemovedBinaryImageUnit, TextureRemovedGrayscaleImageUnit, TransformedGrayscaleImageUnit, Warning, WasmVersions, WorkerAutoResources, _getNorImageData, _saveToFile, _toBlob, _toCanvas, _toImage, bDebug, checkIsLink, compareVersion, doOrWaitAsyncDependency, getNextTaskID, handleEngineResourcePaths, innerVersions, isArc, isContour, isDSImageData, isDSRect, isImageTag, isLineSegment, isObject, isOriginalDsImageData, isPoint, isPolygon, isQuad, isRect, loadWasm, mapAsyncDependency, mapPackageRegister, mapTaskCallBack, onLog, requestResource, setBDebug, setOnLog, waitAsyncDependency, worker, workerAutoResources }; diff --git a/dist/dynamsoft-core@3.4.31/dist/core.esm.js b/dist/dynamsoft-core@3.4.31/dist/core.esm.js new file mode 100644 index 0000000..e60777c --- /dev/null +++ b/dist/dynamsoft-core@3.4.31/dist/core.esm.js @@ -0,0 +1,11 @@ +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft Core JS Edition + * @website https://www.dynamsoft.com + * @copyright Copyright 2024, Dynamsoft Corporation + * @author Dynamsoft + * @version 3.4.31 + * @fileoverview Dynamsoft JavaScript Library for Core + * More info on Dynamsoft Core JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/core/core-module.html + */ +const _=_=>_&&"object"==typeof _&&"function"==typeof _.then,E=(async()=>{})().constructor;class e extends 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,_(e)?t=e:"function"==typeof e&&(t=new E(e)),t&&(async()=>{try{const _=await t;e===this._task&&this.resolve(_)}catch(_){e===this._task&&this.reject(_)}})()}get isEmpty(){return null==this._task}constructor(E){let e,t;super(((_,E)=>{e=_,t=E})),this._s="pending",this.resolve=E=>{this.isPending&&(_(E)?this.task=E:(this._s="fulfilled",e(E)))},this.reject=_=>{this.isPending&&(this._s="rejected",t(_))},this.task=E}}function t(_,E,e,t){if("a"===e&&!t)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof E?_!==E||!t:!E.has(_))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===e?t:"a"===e?t.call(_):t?t.value:E.get(_)}function I(_,E,e,t,I){if("m"===t)throw new TypeError("Private method is not writable");if("a"===t&&!I)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof E?_!==E||!I:!E.has(_))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===t?I.call(_,e):I?I.value=e:E.set(_,e),e}var r,s,n;"function"==typeof SuppressedError&&SuppressedError,function(_){_[_.BOPM_BLOCK=0]="BOPM_BLOCK",_[_.BOPM_UPDATE=1]="BOPM_UPDATE"}(r||(r={})),function(_){_[_.CCUT_AUTO=0]="CCUT_AUTO",_[_.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",_[_.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",_[_.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",_[_.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",_[_.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(s||(s={})),function(_){_[_.IPF_BINARY=0]="IPF_BINARY",_[_.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",_[_.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",_[_.IPF_NV21=3]="IPF_NV21",_[_.IPF_RGB_565=4]="IPF_RGB_565",_[_.IPF_RGB_555=5]="IPF_RGB_555",_[_.IPF_RGB_888=6]="IPF_RGB_888",_[_.IPF_ARGB_8888=7]="IPF_ARGB_8888",_[_.IPF_RGB_161616=8]="IPF_RGB_161616",_[_.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",_[_.IPF_ABGR_8888=10]="IPF_ABGR_8888",_[_.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",_[_.IPF_BGR_888=12]="IPF_BGR_888",_[_.IPF_BINARY_8=13]="IPF_BINARY_8",_[_.IPF_NV12=14]="IPF_NV12",_[_.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(n||(n={}));const C="undefined"==typeof self,i="function"==typeof importScripts,A=(()=>{if(!i){if(!C&&document.currentScript){let _=document.currentScript.src,E=_.indexOf("?");if(-1!=E)_=_.substring(0,E);else{let E=_.indexOf("#");-1!=E&&(_=_.substring(0,E))}return _.substring(0,_.lastIndexOf("/")+1)}return"./"}})(),o=_=>{if(null==_&&(_="./"),C||i);else{let E=document.createElement("a");E.href=_,_=E.href}return _.endsWith("/")||(_+="/"),_},N=_=>Object.prototype.toString.call(_),a=_=>Array.isArray?Array.isArray(_):"[object Array]"===N(_),T=_=>"[object Boolean]"===N(_),R=_=>"number"==typeof _&&!Number.isNaN(_),L=_=>null!==_&&"object"==typeof _&&!Array.isArray(_),D=_=>!!L(_)&&(!!R(_.x)&&(!!R(_.y)&&(!!R(_.radius)&&(!(_.radius<0)&&(!!R(_.startAngle)&&!!R(_.endAngle)))))),O=_=>!!L(_)&&(!!a(_.points)&&(0!=_.points.length&&!_.points.some((_=>!P(_))))),c=_=>!!L(_)&&(!!R(_.width)&&(!(_.width<=0)&&(!!R(_.height)&&(!(_.height<=0)&&(!!R(_.stride)&&(!(_.stride<=0)&&("format"in _&&!("tag"in _&&!h(_.tag))))))))),S=_=>!!c(_)&&!(!R(_.bytes.length)&&!R(_.bytes.ptr)),l=_=>!!c(_)&&_.bytes instanceof Uint8Array,f=_=>!!L(_)&&(!!R(_.left)&&(!(_.left<0)&&(!!R(_.top)&&(!(_.top<0)&&(!!R(_.right)&&(!(_.right<0)&&(!!R(_.bottom)&&(!(_.bottom<0)&&(!(_.left>=_.right)&&(!(_.top>=_.bottom)&&!!T(_.isMeasuredInPercentage))))))))))),h=_=>null===_||!!L(_)&&(!!R(_.imageId)&&"type"in _),d=_=>!!L(_)&&(!!P(_.startPoint)&&(!!P(_.endPoint)&&(_.startPoint.x!=_.endPoint.x||_.startPoint.y!=_.endPoint.y))),P=_=>!!L(_)&&(!!R(_.x)&&!!R(_.y)),g=_=>!!L(_)&&(!!a(_.points)&&(0!=_.points.length&&!_.points.some((_=>!P(_))))),M=_=>!!L(_)&&(!!a(_.points)&&(0!=_.points.length&&4==_.points.length&&!_.points.some((_=>!P(_))))),u=_=>!!L(_)&&(!!R(_.x)&&(!!R(_.y)&&(!!R(_.width)&&(!(_.width<0)&&(!!R(_.height)&&(!(_.height<0)&&!("isMeasuredInPercentage"in _&&!T(_.isMeasuredInPercentage)))))))),F=async(_,E)=>await new Promise(((e,t)=>{let I=new XMLHttpRequest;I.open("GET",_,!0),I.responseType=E,I.send(),I.onloadend=async()=>{I.status<200||I.status>=300?t(new Error(_+" "+I.status)):e(I.response)},I.onerror=()=>{t(new Error("Network Error: "+I.statusText))}})),G=_=>/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(_),U=(_,E)=>{let e=_.split("."),t=E.split(".");for(let _=0;_{const E={},e={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcpd:"dynamsoft-code-parser",dlrData:"dynamsoft-label-recognizer-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer"};for(let t in _){if("rootDirectory"===t)continue;let I=t,r=_[I],s=r&&"object"==typeof r&&r.path?r.path:r,n=_.rootDirectory;if(n&&!n.endsWith("/")&&(n+="/"),"object"==typeof r&&r.isInternal)n&&(s=_[I].version?`${n}${e[I]}@${_[I].version}/dist/${"ddv"===I?"engine":""}`:`${n}${e[I]}/dist/${"ddv"===I?"engine":""}`);else{const e=/^@engineRootDirectory(\/?)/;if("string"==typeof s&&(s=s.replace(e,n||"")),"object"==typeof s&&"dwt"===I){const t=_[I].resourcesPath,r=_[I].serviceInstallerLocation;E[I]={resourcesPath:t.replace(e,n||""),serviceInstallerLocation:r.replace(e,n||"")};continue}}E[I]=o(s)}return E},p=async(_,E,e)=>await new Promise((async(t,I)=>{try{const I=E.split(".");let r=I[I.length-1];const s=await w(`image/${r}`,_);I.length<=1&&(r="png");const n=new File([s],E,{type:`image/${r}`});if(e){const _=URL.createObjectURL(n),e=document.createElement("a");e.href=_,e.download=E,e.click()}return t(n)}catch(_){return I()}})),m=_=>{l(_)&&(_=V(_));const E=document.createElement("canvas");E.width=_.width,E.height=_.height;return E.getContext("2d",{willReadFrequently:!0}).putImageData(_,0,0),E},y=(_,E)=>{l(E)&&(E=V(E));const e=m(E);let t=new Image,I=e.toDataURL(_);return t.src=I,t},w=async(_,E)=>{l(E)&&(E=V(E));const e=m(E);return new Promise(((E,t)=>{e.toBlob((_=>E(_)),_)}))},V=_=>{let E,e=_.bytes;if(!(e&&e instanceof Uint8Array))throw Error("Parameter type error");if(Number(_.format)===n.IPF_BGR_888){const _=e.length/3;E=new Uint8ClampedArray(4*_);for(let t=0;t<_;++t)E[4*t]=e[3*t],E[4*t+1]=e[3*t+1],E[4*t+2]=e[3*t+2],E[4*t+3]=255}else if(Number(_.format)===n.IPF_RGB_888){const _=e.length/3;E=new Uint8ClampedArray(4*_);for(let t=0;t<_;++t)E[4*t]=e[3*t+2],E[4*t+1]=e[3*t+1],E[4*t+2]=e[3*t],E[4*t+3]=255}else if(Number(_.format)===n.IPF_GRAYSCALED){const _=e.length;E=new Uint8ClampedArray(4*_);for(let t=0;t<_;t++)E[4*t]=E[4*t+1]=E[4*t+2]=e[t],E[4*t+3]=255}else if(Number(_.format)===n.IPF_BINARY_8){const t=e.length,I=_.width,r=_.height,s=_.stride;E=new Uint8ClampedArray(I*r*4);for(let _=0;_=I)break;E[s]=E[s+1]=E[s+2]=(128&t)/128*255,E[s+3]=255,t<<=1}}}else if(Number(_.format)===n.IPF_ABGR_8888){const _=e.length/4;E=new Uint8ClampedArray(e.length);for(let t=0;t<_;++t)E[4*t]=e[4*t],E[4*t+1]=e[4*t+1],E[4*t+2]=e[4*t+2],E[4*t+3]=e[4*t+3]}else if(Number(_.format)===n.IPF_ARGB_8888){const _=e.length/4;E=new Uint8ClampedArray(e.length);for(let t=0;t<_;++t)E[4*t]=e[4*t+2],E[4*t+1]=e[4*t+1],E[4*t+2]=e[4*t],E[4*t+3]=e[4*t+3]}else if(Number(_.format)===n.IPF_BINARY_8_INVERTED){const t=e.length,I=_.width,r=_.height,s=_.stride;E=new Uint8ClampedArray(I*r*4);for(let _=0;_=I)break;E[s]=E[s+1]=E[s+2]=128&t?0:255,E[s+3]=255,t<<=1}}}return new ImageData(E,_.width,_.height)};var b,v,Y,H,k,X,Z,x;class W{get _isFetchingStarted(){return t(this,k,"f")}constructor(){b.add(this),v.set(this,[]),Y.set(this,1),H.set(this,r.BOPM_BLOCK),k.set(this,!1),X.set(this,void 0),Z.set(this,s.CCUT_AUTO)}setErrorListener(_){}addImageToBuffer(_){var E;if(!l(_))throw new TypeError("Invalid 'image'.");if((null===(E=_.tag)||void 0===E?void 0:E.hasOwnProperty("imageId"))&&"number"==typeof _.tag.imageId&&this.hasImage(_.tag.imageId))throw new Error("Existed imageId.");if(t(this,v,"f").length>=t(this,Y,"f"))switch(t(this,H,"f")){case r.BOPM_BLOCK:break;case r.BOPM_UPDATE:if(t(this,v,"f").push(_),L(t(this,X,"f"))&&R(t(this,X,"f").imageId)&&1==t(this,X,"f").keepInBuffer)for(;t(this,v,"f").length>t(this,Y,"f");){const _=t(this,v,"f").findIndex((_=>{var E;return(null===(E=_.tag)||void 0===E?void 0:E.imageId)!==t(this,X,"f").imageId}));t(this,v,"f").splice(_,1)}else t(this,v,"f").splice(0,t(this,v,"f").length-t(this,Y,"f"))}else t(this,v,"f").push(_)}getImage(){if(0===t(this,v,"f").length)return null;let _;if(t(this,X,"f")&&R(t(this,X,"f").imageId)){const E=t(this,b,"m",x).call(this,t(this,X,"f").imageId);if(E<0)throw new Error(`Image with id ${t(this,X,"f").imageId} doesn't exist.`);_=t(this,v,"f").slice(E,E+1)[0]}else _=t(this,v,"f").pop();if([n.IPF_RGB_565,n.IPF_RGB_555,n.IPF_RGB_888,n.IPF_ARGB_8888,n.IPF_RGB_161616,n.IPF_ARGB_16161616,n.IPF_ABGR_8888,n.IPF_ABGR_16161616,n.IPF_BGR_888].includes(_.format)){if(t(this,Z,"f")===s.CCUT_RGB_R_CHANNEL_ONLY){W._onLog&&W._onLog("only get R channel data.");const E=new Uint8Array(_.width*_.height);for(let e=0;e0!==_.length&&_.every((_=>R(_))))(_))throw new TypeError("Invalid 'imageId'.");if(void 0!==E&&!T(E))throw new TypeError("Invalid 'keepInBuffer'.");I(this,X,{imageId:_,keepInBuffer:E},"f")}_resetNextReturnedImage(){I(this,X,null,"f")}hasImage(_){return t(this,b,"m",x).call(this,_)>=0}startFetching(){I(this,k,!0,"f")}stopFetching(){I(this,k,!1,"f")}setMaxImageCount(_){if("number"!=typeof _)throw new TypeError("Invalid 'count'.");if(_<1||Math.round(_)!==_)throw new Error("Invalid 'count'.");for(I(this,Y,_,"f");t(this,v,"f")&&t(this,v,"f").length>_;)t(this,v,"f").shift()}getMaxImageCount(){return t(this,Y,"f")}getImageCount(){return t(this,v,"f").length}clearBuffer(){t(this,v,"f").length=0}isBufferEmpty(){return 0===t(this,v,"f").length}setBufferOverflowProtectionMode(_){I(this,H,_,"f")}getBufferOverflowProtectionMode(){return t(this,H,"f")}setColourChannelUsageType(_){I(this,Z,_,"f")}getColourChannelUsageType(){return t(this,Z,"f")}}let j,K,J,Q,$;v=new WeakMap,Y=new WeakMap,H=new WeakMap,k=new WeakMap,X=new WeakMap,Z=new WeakMap,b=new WeakSet,x=function(_){if("number"!=typeof _)throw new TypeError("Invalid 'imageId'.");return t(this,v,"f").findIndex((E=>{var e;return(null===(e=E.tag)||void 0===e?void 0:e.imageId)===_}))},"undefined"!=typeof navigator&&(j=navigator,K=j.userAgent,J=j.platform,Q=j.mediaDevices),function(){if(!C){const _={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:j.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},E={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:J,search:"Win"},Mac:{str:J},Linux:{str:J}};let e="unknownBrowser",t=0,I="unknownOS";for(let E in _){const I=_[E]||{};let r=I.str||K,s=I.search||E,n=I.verStr||K,C=I.verSearch||E;if(C instanceof Array||(C=[C]),-1!=r.indexOf(s)){e=E;for(let _ of C){let E=n.indexOf(_);if(-1!=E){t=parseFloat(n.substring(E+_.length+1));break}}break}}for(let _ in E){const e=E[_]||{};let t=e.str||K,r=e.search||_;if(-1!=t.indexOf(r)){I=_;break}}"Linux"==I&&-1!=K.indexOf("Windows NT")&&(I="HarmonyOS"),$={browser:e,version:t,OS:I}}C&&($={browser:"ssr",version:0,OS:"ssr"})}();const z="undefined"!=typeof WebAssembly&&K&&!(/Safari/.test(K)&&!/Chrome/.test(K)&&/\(.+\s11_2_([2-6]).*\)/.test(K)),q=!("undefined"==typeof Worker),__=!(!Q||!Q.getUserMedia),E_=async()=>{let _=!1;if(__)try{(await Q.getUserMedia({video:!0})).getTracks().forEach((_=>{_.stop()})),_=!0}catch(_){}return _};"Chrome"===$.browser&&$.version>66||"Safari"===$.browser&&$.version>13||"OPR"===$.browser&&$.version>43||"Edge"===$.browser&&$.version;const e_={},t_=async _=>{let E="string"==typeof _?[_]:_,t=[];for(let _ of E)t.push(e_[_]=e_[_]||new e);await Promise.all(t)},I_=async(_,E)=>{let t,I="string"==typeof _?[_]:_,r=[];for(let _ of I){let I;r.push(I=e_[_]=e_[_]||new e(t=t||E())),I.isEmpty&&(I.task=t=t||E())}await Promise.all(r)};let r_,s_=0;const n_=()=>s_++,C_={};let i_;const A_=_=>{i_=_,r_&&r_.postMessage({type:"setBLog",body:{value:!!_}})};let o_=!1;const N_=_=>{o_=_,r_&&r_.postMessage({type:"setBDebug",body:{value:!!_}})},a_={},T_={},R_={dip:{wasm:!0}},L_={std:{version:"1.4.21",path:o(A+"../../dynamsoft-capture-vision-std@1.4.21/dist/"),isInternal:!0},core:{version:"3.4.31",path:A,isInternal:!0}},D_=async _=>{let E;_ instanceof Array||(_=_?[_]:[]);let t=e_.core;E=!t||t.isEmpty;let I=new Map;const r=_=>{if("std"==(_=_.toLowerCase())||"core"==_)return;if(!R_[_])throw Error("The '"+_+"' module cannot be found.");let E=R_[_].deps;if(null==E?void 0:E.length)for(let _ of E)r(_);let e=e_[_];I.has(_)||I.set(_,!e||e.isEmpty)};for(let E of _)r(E);let s=[];E&&s.push("core"),s.push(...I.keys());const n=[...I.entries()].filter((_=>!_[1])).map((_=>_[0]));await I_(s,(async()=>{const _=[...I.entries()].filter((_=>_[1])).map((_=>_[0]));await t_(n);const t=B(L_),r={};for(let E of _)r[E]=R_[E];const s={engineResourcePaths:t,autoResources:r,names:_};let C=new e;if(E){s.needLoadCore=!0;let _=t.core+O_._workerName;_.startsWith(location.origin)||(_=await fetch(_).then((_=>_.blob())).then((_=>URL.createObjectURL(_)))),r_=new Worker(_),r_.onerror=_=>{let E=new Error(_.message);C.reject(E)},r_.addEventListener("message",(_=>{let E=_.data?_.data:_,e=E.type,t=E.id,I=E.body;switch(e){case"log":i_&&i_(E.message);break;case"task":try{C_[t](I),delete C_[t]}catch(_){throw delete C_[t],_}break;case"event":try{C_[t](I)}catch(_){throw _}break;default:console.log(_)}})),s.bLog=!!i_,s.bd=o_,s.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await t_("core");let i=s_++;C_[i]=_=>{if(_.success)Object.assign(a_,_.versions),"{}"!==JSON.stringify(_.versions)&&(O_._versions=_.versions),C.resolve(void 0);else{const E=Error(_.message);_.stack&&(E.stack=_.stack),C.reject(E)}},r_.postMessage({type:"loadWasm",body:s,id:i}),await C}))};class O_{static get engineResourcePaths(){return L_}static set engineResourcePaths(_){Object.assign(L_,_)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return i_}static set _onLog(_){A_(_)}static get _bDebug(){return o_}static set _bDebug(_){N_(_)}static isModuleLoaded(_){return _=(_=_||"core").toLowerCase(),!!e_[_]&&e_[_].isFulfilled}static async loadWasm(_){return await D_(_)}static async detectEnvironment(){return await(async()=>({wasm:z,worker:q,getUserMedia:__,camera:await E_(),browser:$.browser,version:$.version,OS:$.OS}))()}static async getModuleVersion(){return await new Promise(((_,E)=>{let e=n_();C_[e]=async e=>{if(e.success)return _(e.versions);{let _=new Error(e.message);return _.stack=e.stack+"\n"+_.stack,E(_)}},r_.postMessage({type:"getModuleVersion",id:e})}))}static getVersion(){const _=a_.core&&a_.core.worker,E=a_.core&&a_.core.wasm;return`3.4.31(Worker: ${_||"Not Loaded"}, Wasm: ${E||"Not Loaded"})`}static enableLogging(){W._onLog=console.log,O_._onLog=console.log}static disableLogging(){W._onLog=null,O_._onLog=null}static async cfd(_){return await new Promise(((E,e)=>{let t=n_();C_[t]=async _=>{if(_.success)return E();{let E=new Error(_.message);return E.stack=_.stack+"\n"+E.stack,e(E)}},r_.postMessage({type:"cfd",id:t,body:{count:_}})}))}}var c_,S_,l_,f_,h_,d_,P_,g_,M_;O_._bSupportDce4Module=-1,O_._bSupportIRTModule=-1,O_._versions=null,O_._workerName="core.worker.js",O_.browserInfo=$,function(_){_[_.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",_[_.CRIT_BARCODE=2]="CRIT_BARCODE",_[_.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",_[_.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",_[_.CRIT_NORMALIZED_IMAGE=16]="CRIT_NORMALIZED_IMAGE",_[_.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT"}(c_||(c_={})),function(_){_[_.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",_[_.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",_[_.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",_[_.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(S_||(S_={})),function(_){_[_.EC_OK=0]="EC_OK",_[_.EC_UNKNOWN=-1e4]="EC_UNKNOWN",_[_.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",_[_.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",_[_.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",_[_.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",_[_.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",_[_.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",_[_.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",_[_.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",_[_.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",_[_.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",_[_.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",_[_.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",_[_.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",_[_.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",_[_.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",_[_.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",_[_.EC_TIMEOUT=-10026]="EC_TIMEOUT",_[_.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",_[_.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",_[_.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",_[_.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",_[_.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",_[_.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",_[_.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",_[_.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",_[_.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",_[_.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",_[_.EC_RESERVED_INFO_NOT_MATCH=-10040]="EC_RESERVED_INFO_NOT_MATCH",_[_.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",_[_.EC_REQUEST_FAILED=-10044]="EC_REQUEST_FAILED",_[_.EC_LICENSE_INIT_FAILED=-10045]="EC_LICENSE_INIT_FAILED",_[_.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",_[_.EC_LICENSE_CONTENT_INVALID=-10052]="EC_LICENSE_CONTENT_INVALID",_[_.EC_LICENSE_KEY_INVALID=-10053]="EC_LICENSE_KEY_INVALID",_[_.EC_LICENSE_DEVICE_RUNS_OUT=-10054]="EC_LICENSE_DEVICE_RUNS_OUT",_[_.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",_[_.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",_[_.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",_[_.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",_[_.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",_[_.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",_[_.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",_[_.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",_[_.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",_[_.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",_[_.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",_[_.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",_[_.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",_[_.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",_[_.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",_[_.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",_[_.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",_[_.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",_[_.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",_[_.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",_[_.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",_[_.EC_HANDSHAKE_CODE_INVALID=-20001]="EC_HANDSHAKE_CODE_INVALID",_[_.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",_[_.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",_[_.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",_[_.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",_[_.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",_[_.EC_LICENSE_INIT_SEQUENCE_FAILED=-20009]="EC_LICENSE_INIT_SEQUENCE_FAILED",_[_.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",_[_.EC_FAILED_TO_REACH_DLS=-20200]="EC_FAILED_TO_REACH_DLS",_[_.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",_[_.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",_[_.EC_QR_LICENSE_INVALID=-30016]="EC_QR_LICENSE_INVALID",_[_.EC_1D_LICENSE_INVALID=-30017]="EC_1D_LICENSE_INVALID",_[_.EC_PDF417_LICENSE_INVALID=-30019]="EC_PDF417_LICENSE_INVALID",_[_.EC_DATAMATRIX_LICENSE_INVALID=-30020]="EC_DATAMATRIX_LICENSE_INVALID",_[_.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",_[_.EC_AZTEC_LICENSE_INVALID=-30041]="EC_AZTEC_LICENSE_INVALID",_[_.EC_PATCHCODE_LICENSE_INVALID=-30046]="EC_PATCHCODE_LICENSE_INVALID",_[_.EC_POSTALCODE_LICENSE_INVALID=-30047]="EC_POSTALCODE_LICENSE_INVALID",_[_.EC_DPM_LICENSE_INVALID=-30048]="EC_DPM_LICENSE_INVALID",_[_.EC_FRAME_DECODING_THREAD_EXISTS=-30049]="EC_FRAME_DECODING_THREAD_EXISTS",_[_.EC_STOP_DECODING_THREAD_FAILED=-30050]="EC_STOP_DECODING_THREAD_FAILED",_[_.EC_MAXICODE_LICENSE_INVALID=-30057]="EC_MAXICODE_LICENSE_INVALID",_[_.EC_GS1_DATABAR_LICENSE_INVALID=-30058]="EC_GS1_DATABAR_LICENSE_INVALID",_[_.EC_GS1_COMPOSITE_LICENSE_INVALID=-30059]="EC_GS1_COMPOSITE_LICENSE_INVALID",_[_.EC_DOTCODE_LICENSE_INVALID=-30061]="EC_DOTCODE_LICENSE_INVALID",_[_.EC_PHARMACODE_LICENSE_INVALID=-30062]="EC_PHARMACODE_LICENSE_INVALID",_[_.EC_CHARACTER_MODEL_FILE_NOT_FOUND=-40100]="EC_CHARACTER_MODEL_FILE_NOT_FOUND",_[_.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",_[_.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",_[_.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",_[_.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",_[_.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",_[_.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",_[_.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",_[_.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",_[_.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",_[_.EC_ZA_DL_LICENSE_INVALID=-90006]="EC_ZA_DL_LICENSE_INVALID",_[_.EC_AAMVA_DL_ID_LICENSE_INVALID=-90007]="EC_AAMVA_DL_ID_LICENSE_INVALID",_[_.EC_AADHAAR_LICENSE_INVALID=-90008]="EC_AADHAAR_LICENSE_INVALID",_[_.EC_MRTD_LICENSE_INVALID=-90009]="EC_MRTD_LICENSE_INVALID",_[_.EC_VIN_LICENSE_INVALID=-90010]="EC_VIN_LICENSE_INVALID",_[_.EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID=-90011]="EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID",_[_.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",_[_.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",_[_.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",_[_.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",_[_.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(l_||(l_={})),function(_){_[_.GEM_SKIP=0]="GEM_SKIP",_[_.GEM_AUTO=1]="GEM_AUTO",_[_.GEM_GENERAL=2]="GEM_GENERAL",_[_.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",_[_.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",_[_.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",_[_.GEM_REV=-2147483648]="GEM_REV"}(f_||(f_={})),function(_){_[_.GTM_SKIP=0]="GTM_SKIP",_[_.GTM_INVERTED=1]="GTM_INVERTED",_[_.GTM_ORIGINAL=2]="GTM_ORIGINAL",_[_.GTM_AUTO=4]="GTM_AUTO",_[_.GTM_REV=-2147483648]="GTM_REV"}(h_||(h_={})),function(_){_[_.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",_[_.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(d_||(d_={})),function(_){_[_.PDFRM_VECTOR=1]="PDFRM_VECTOR",_[_.PDFRM_RASTER=2]="PDFRM_RASTER",_[_.PDFRM_REV=-2147483648]="PDFRM_REV"}(P_||(P_={})),function(_){_[_.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",_[_.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(g_||(g_={})),function(_){_[_.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",_[_.CVS_PASSED=1]="CVS_PASSED",_[_.CVS_FAILED=2]="CVS_FAILED"}(M_||(M_={}));const u_={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_DOWN_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_UP_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_NORMALIZED_IMAGES:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var F_,G_;!function(_){_[_.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",_[_.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",_[_.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",_[_.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",_[_.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",_[_.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",_[_.ROET_NORMALIZED_IMAGE=6]="ROET_NORMALIZED_IMAGE",_[_.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",_[_.ROET_TARGET_ROI=8]="ROET_TARGET_ROI"}(F_||(F_={})),function(_){_[_.ST_NULL=0]="ST_NULL",_[_.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",_[_.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",_[_.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",_[_.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",_[_.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",_[_.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",_[_.ST_DOCUMENT_NORMALIZATION=7]="ST_DOCUMENT_NORMALIZATION"}(G_||(G_={}));export{O_ as CoreModule,r as EnumBufferOverflowProtectionMode,c_ as EnumCapturedResultItemType,s as EnumColourChannelUsageType,S_ as EnumCornerType,M_ as EnumCrossVerificationStatus,l_ as EnumErrorCode,f_ as EnumGrayscaleEnhancementMode,h_ as EnumGrayscaleTransformationMode,n as EnumImagePixelFormat,d_ as EnumImageTagType,u_ as EnumIntermediateResultUnitType,P_ as EnumPDFReadingMode,g_ as EnumRasterDataSource,F_ as EnumRegionObjectElementType,G_ as EnumSectionType,W as ImageSourceAdapter,V as _getNorImageData,p as _saveToFile,w as _toBlob,m as _toCanvas,y as _toImage,o_ as bDebug,G as checkIsLink,U as compareVersion,I_ as doOrWaitAsyncDependency,n_ as getNextTaskID,B as handleEngineResourcePaths,a_ as innerVersions,D as isArc,O as isContour,l as isDSImageData,f as isDSRect,h as isImageTag,d as isLineSegment,L as isObject,S as isOriginalDsImageData,P as isPoint,g as isPolygon,M as isQuad,u as isRect,D_ as loadWasm,e_ as mapAsyncDependency,T_ as mapPackageRegister,C_ as mapTaskCallBack,i_ as onLog,F as requestResource,N_ as setBDebug,A_ as setOnLog,t_ as waitAsyncDependency,r_ as worker,R_ as workerAutoResources}; diff --git a/dist/dynamsoft-core@3.4.31/dist/core.js b/dist/dynamsoft-core@3.4.31/dist/core.js new file mode 100644 index 0000000..ad62755 --- /dev/null +++ b/dist/dynamsoft-core@3.4.31/dist/core.js @@ -0,0 +1,11 @@ +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft Core JS Edition + * @website https://www.dynamsoft.com + * @copyright Copyright 2024, Dynamsoft Corporation + * @author Dynamsoft + * @version 3.4.31 + * @fileoverview Dynamsoft JavaScript Library for Core + * More info on Dynamsoft Core JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/core/core-module.html + */ +!function(e,E){"object"==typeof exports&&"undefined"!=typeof module?E(exports):"function"==typeof define&&define.amd?define(["exports"],E):E(((e="undefined"!=typeof globalThis?globalThis:e||self).Dynamsoft=e.Dynamsoft||{},e.Dynamsoft.Core={}))}(this,(function(e){"use strict";const E=e=>e&&"object"==typeof e&&"function"==typeof e.then,_=(async()=>{})().constructor;class t extends _{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,E(e)?t=e:"function"==typeof e&&(t=new _(e)),t&&(async()=>{try{const E=await t;e===this._task&&this.resolve(E)}catch(E){e===this._task&&this.reject(E)}})()}get isEmpty(){return null==this._task}constructor(e){let _,t;super(((e,E)=>{_=e,t=E})),this._s="pending",this.resolve=e=>{this.isPending&&(E(e)?this.task=e:(this._s="fulfilled",_(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",t(e))},this.task=e}}function I(e,E,_,t){if("a"===_&&!t)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof E?e!==E||!t:!E.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===_?t:"a"===_?t.call(e):t?t.value:E.get(e)}function r(e,E,_,t,I){if("m"===t)throw new TypeError("Private method is not writable");if("a"===t&&!I)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof E?e!==E||!I:!E.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===t?I.call(e,_):I?I.value=_:E.set(e,_),_}var n,o,a;"function"==typeof SuppressedError&&SuppressedError,e.EnumBufferOverflowProtectionMode=void 0,(n=e.EnumBufferOverflowProtectionMode||(e.EnumBufferOverflowProtectionMode={}))[n.BOPM_BLOCK=0]="BOPM_BLOCK",n[n.BOPM_UPDATE=1]="BOPM_UPDATE",e.EnumColourChannelUsageType=void 0,(o=e.EnumColourChannelUsageType||(e.EnumColourChannelUsageType={}))[o.CCUT_AUTO=0]="CCUT_AUTO",o[o.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",o[o.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",o[o.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",o[o.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",o[o.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY",e.EnumImagePixelFormat=void 0,(a=e.EnumImagePixelFormat||(e.EnumImagePixelFormat={}))[a.IPF_BINARY=0]="IPF_BINARY",a[a.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",a[a.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",a[a.IPF_NV21=3]="IPF_NV21",a[a.IPF_RGB_565=4]="IPF_RGB_565",a[a.IPF_RGB_555=5]="IPF_RGB_555",a[a.IPF_RGB_888=6]="IPF_RGB_888",a[a.IPF_ARGB_8888=7]="IPF_ARGB_8888",a[a.IPF_RGB_161616=8]="IPF_RGB_161616",a[a.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",a[a.IPF_ABGR_8888=10]="IPF_ABGR_8888",a[a.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",a[a.IPF_BGR_888=12]="IPF_BGR_888",a[a.IPF_BINARY_8=13]="IPF_BINARY_8",a[a.IPF_NV12=14]="IPF_NV12",a[a.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED";const s="undefined"==typeof self,i="function"==typeof importScripts,C=(()=>{if(!i){if(!s&&document.currentScript){let e=document.currentScript.src,E=e.indexOf("?");if(-1!=E)e=e.substring(0,E);else{let E=e.indexOf("#");-1!=E&&(e=e.substring(0,E))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"}})(),A=e=>{if(null==e&&(e="./"),s||i);else{let E=document.createElement("a");E.href=e,e=E.href}return e.endsWith("/")||(e+="/"),e},T=e=>Object.prototype.toString.call(e),N=e=>Array.isArray?Array.isArray(e):"[object Array]"===T(e),R=e=>"[object Boolean]"===T(e),L=e=>"number"==typeof e&&!Number.isNaN(e),D=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),O=e=>!!D(e)&&(!!L(e.width)&&(!(e.width<=0)&&(!!L(e.height)&&(!(e.height<=0)&&(!!L(e.stride)&&(!(e.stride<=0)&&("format"in e&&!("tag"in e&&!m(e.tag))))))))),l=e=>!!O(e)&&e.bytes instanceof Uint8Array,m=e=>null===e||!!D(e)&&(!!L(e.imageId)&&"type"in e),c=e=>!!D(e)&&(!!L(e.x)&&!!L(e.y)),u=e=>{const E={},_={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcpd:"dynamsoft-code-parser",dlrData:"dynamsoft-label-recognizer-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer"};for(let t in e){if("rootDirectory"===t)continue;let I=t,r=e[I],n=r&&"object"==typeof r&&r.path?r.path:r,o=e.rootDirectory;if(o&&!o.endsWith("/")&&(o+="/"),"object"==typeof r&&r.isInternal)o&&(n=e[I].version?`${o}${_[I]}@${e[I].version}/dist/${"ddv"===I?"engine":""}`:`${o}${_[I]}/dist/${"ddv"===I?"engine":""}`);else{const _=/^@engineRootDirectory(\/?)/;if("string"==typeof n&&(n=n.replace(_,o||"")),"object"==typeof n&&"dwt"===I){const t=e[I].resourcesPath,r=e[I].serviceInstallerLocation;E[I]={resourcesPath:t.replace(_,o||""),serviceInstallerLocation:r.replace(_,o||"")};continue}}E[I]=A(n)}return E},S=e=>{l(e)&&(e=d(e));const E=document.createElement("canvas");E.width=e.width,E.height=e.height;return E.getContext("2d",{willReadFrequently:!0}).putImageData(e,0,0),E},g=async(e,E)=>{l(E)&&(E=d(E));const _=S(E);return new Promise(((E,t)=>{_.toBlob((e=>E(e)),e)}))},d=E=>{let _,t=E.bytes;if(!(t&&t instanceof Uint8Array))throw Error("Parameter type error");if(Number(E.format)===e.EnumImagePixelFormat.IPF_BGR_888){const e=t.length/3;_=new Uint8ClampedArray(4*e);for(let E=0;E=I)break;_[n]=_[n+1]=_[n+2]=(128&e)/128*255,_[n+3]=255,e<<=1}}}else if(Number(E.format)===e.EnumImagePixelFormat.IPF_ABGR_8888){const e=t.length/4;_=new Uint8ClampedArray(t.length);for(let E=0;E=I)break;_[n]=_[n+1]=_[n+2]=128&e?0:255,_[n+3]=255,e<<=1}}}return new ImageData(_,E.width,E.height)};var P,f,F,h,M,G,U,p;class y{get _isFetchingStarted(){return I(this,M,"f")}constructor(){P.add(this),f.set(this,[]),F.set(this,1),h.set(this,e.EnumBufferOverflowProtectionMode.BOPM_BLOCK),M.set(this,!1),G.set(this,void 0),U.set(this,e.EnumColourChannelUsageType.CCUT_AUTO)}setErrorListener(e){}addImageToBuffer(E){var _;if(!l(E))throw new TypeError("Invalid 'image'.");if((null===(_=E.tag)||void 0===_?void 0:_.hasOwnProperty("imageId"))&&"number"==typeof E.tag.imageId&&this.hasImage(E.tag.imageId))throw new Error("Existed imageId.");if(I(this,f,"f").length>=I(this,F,"f"))switch(I(this,h,"f")){case e.EnumBufferOverflowProtectionMode.BOPM_BLOCK:break;case e.EnumBufferOverflowProtectionMode.BOPM_UPDATE:if(I(this,f,"f").push(E),D(I(this,G,"f"))&&L(I(this,G,"f").imageId)&&1==I(this,G,"f").keepInBuffer)for(;I(this,f,"f").length>I(this,F,"f");){const e=I(this,f,"f").findIndex((e=>{var E;return(null===(E=e.tag)||void 0===E?void 0:E.imageId)!==I(this,G,"f").imageId}));I(this,f,"f").splice(e,1)}else I(this,f,"f").splice(0,I(this,f,"f").length-I(this,F,"f"))}else I(this,f,"f").push(E)}getImage(){if(0===I(this,f,"f").length)return null;let E;if(I(this,G,"f")&&L(I(this,G,"f").imageId)){const e=I(this,P,"m",p).call(this,I(this,G,"f").imageId);if(e<0)throw new Error(`Image with id ${I(this,G,"f").imageId} doesn't exist.`);E=I(this,f,"f").slice(e,e+1)[0]}else E=I(this,f,"f").pop();if([e.EnumImagePixelFormat.IPF_RGB_565,e.EnumImagePixelFormat.IPF_RGB_555,e.EnumImagePixelFormat.IPF_RGB_888,e.EnumImagePixelFormat.IPF_ARGB_8888,e.EnumImagePixelFormat.IPF_RGB_161616,e.EnumImagePixelFormat.IPF_ARGB_16161616,e.EnumImagePixelFormat.IPF_ABGR_8888,e.EnumImagePixelFormat.IPF_ABGR_16161616,e.EnumImagePixelFormat.IPF_BGR_888].includes(E.format)){if(I(this,U,"f")===e.EnumColourChannelUsageType.CCUT_RGB_R_CHANNEL_ONLY){y._onLog&&y._onLog("only get R channel data.");const _=new Uint8Array(E.width*E.height);for(let t=0;t<_.length;t++)switch(E.format){case e.EnumImagePixelFormat.IPF_RGB_565:case e.EnumImagePixelFormat.IPF_RGB_555:case e.EnumImagePixelFormat.IPF_RGB_888:case e.EnumImagePixelFormat.IPF_RGB_161616:_[t]=E.bytes[3*t+2];break;case e.EnumImagePixelFormat.IPF_ARGB_8888:case e.EnumImagePixelFormat.IPF_ARGB_16161616:_[t]=E.bytes[4*t+2];break;case e.EnumImagePixelFormat.IPF_BGR_888:_[t]=E.bytes[3*t];break;case e.EnumImagePixelFormat.IPF_ABGR_8888:case e.EnumImagePixelFormat.IPF_ABGR_16161616:_[t]=E.bytes[4*t]}E.bytes=_,E.stride=E.width,E.format=e.EnumImagePixelFormat.IPF_GRAYSCALED}else if(I(this,U,"f")===e.EnumColourChannelUsageType.CCUT_RGB_G_CHANNEL_ONLY){y._onLog&&y._onLog("only get G channel data.");const _=new Uint8Array(E.width*E.height);for(let t=0;t<_.length;t++)switch(E.format){case e.EnumImagePixelFormat.IPF_RGB_565:case e.EnumImagePixelFormat.IPF_RGB_555:case e.EnumImagePixelFormat.IPF_RGB_888:case e.EnumImagePixelFormat.IPF_RGB_161616:case e.EnumImagePixelFormat.IPF_BGR_888:_[t]=E.bytes[3*t+1];break;case e.EnumImagePixelFormat.IPF_ARGB_8888:case e.EnumImagePixelFormat.IPF_ARGB_16161616:case e.EnumImagePixelFormat.IPF_ABGR_8888:case e.EnumImagePixelFormat.IPF_ABGR_16161616:_[t]=E.bytes[4*t+1]}E.bytes=_,E.stride=E.width,E.format=e.EnumImagePixelFormat.IPF_GRAYSCALED}else if(I(this,U,"f")===e.EnumColourChannelUsageType.CCUT_RGB_B_CHANNEL_ONLY){y._onLog&&y._onLog("only get B channel data.");const _=new Uint8Array(E.width*E.height);for(let t=0;t<_.length;t++)switch(E.format){case e.EnumImagePixelFormat.IPF_RGB_565:case e.EnumImagePixelFormat.IPF_RGB_555:case e.EnumImagePixelFormat.IPF_RGB_888:case e.EnumImagePixelFormat.IPF_RGB_161616:_[t]=E.bytes[3*t];break;case e.EnumImagePixelFormat.IPF_ARGB_8888:case e.EnumImagePixelFormat.IPF_ARGB_16161616:_[t]=E.bytes[4*t];break;case e.EnumImagePixelFormat.IPF_BGR_888:_[t]=E.bytes[3*t+2];break;case e.EnumImagePixelFormat.IPF_ABGR_8888:case e.EnumImagePixelFormat.IPF_ABGR_16161616:_[t]=E.bytes[4*t+2]}E.bytes=_,E.stride=E.width,E.format=e.EnumImagePixelFormat.IPF_GRAYSCALED}}else[e.EnumImagePixelFormat.IPF_NV21,e.EnumImagePixelFormat.IPF_NV12].includes(E.format)&&y._onLog&&y._onLog("NV21 or NV12 is not supported.");return E}setNextImageToReturn(e,E){if(!((...e)=>0!==e.length&&e.every((e=>L(e))))(e))throw new TypeError("Invalid 'imageId'.");if(void 0!==E&&!R(E))throw new TypeError("Invalid 'keepInBuffer'.");r(this,G,{imageId:e,keepInBuffer:E},"f")}_resetNextReturnedImage(){r(this,G,null,"f")}hasImage(e){return I(this,P,"m",p).call(this,e)>=0}startFetching(){r(this,M,!0,"f")}stopFetching(){r(this,M,!1,"f")}setMaxImageCount(e){if("number"!=typeof e)throw new TypeError("Invalid 'count'.");if(e<1||Math.round(e)!==e)throw new Error("Invalid 'count'.");for(r(this,F,e,"f");I(this,f,"f")&&I(this,f,"f").length>e;)I(this,f,"f").shift()}getMaxImageCount(){return I(this,F,"f")}getImageCount(){return I(this,f,"f").length}clearBuffer(){I(this,f,"f").length=0}isBufferEmpty(){return 0===I(this,f,"f").length}setBufferOverflowProtectionMode(e){r(this,h,e,"f")}getBufferOverflowProtectionMode(){return I(this,h,"f")}setColourChannelUsageType(e){r(this,U,e,"f")}getColourChannelUsageType(){return I(this,U,"f")}}let B,w,V,b,v;f=new WeakMap,F=new WeakMap,h=new WeakMap,M=new WeakMap,G=new WeakMap,U=new WeakMap,P=new WeakSet,p=function(e){if("number"!=typeof e)throw new TypeError("Invalid 'imageId'.");return I(this,f,"f").findIndex((E=>{var _;return(null===(_=E.tag)||void 0===_?void 0:_.imageId)===e}))},"undefined"!=typeof navigator&&(B=navigator,w=B.userAgent,V=B.platform,b=B.mediaDevices),function(){if(!s){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:B.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},E={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:V,search:"Win"},Mac:{str:V},Linux:{str:V}};let _="unknownBrowser",t=0,I="unknownOS";for(let E in e){const I=e[E]||{};let r=I.str||w,n=I.search||E,o=I.verStr||w,a=I.verSearch||E;if(a instanceof Array||(a=[a]),-1!=r.indexOf(n)){_=E;for(let e of a){let E=o.indexOf(e);if(-1!=E){t=parseFloat(o.substring(E+e.length+1));break}}break}}for(let e in E){const _=E[e]||{};let t=_.str||w,r=_.search||e;if(-1!=t.indexOf(r)){I=e;break}}"Linux"==I&&-1!=w.indexOf("Windows NT")&&(I="HarmonyOS"),v={browser:_,version:t,OS:I}}s&&(v={browser:"ssr",version:0,OS:"ssr"})}();const x="undefined"!=typeof WebAssembly&&w&&!(/Safari/.test(w)&&!/Chrome/.test(w)&&/\(.+\s11_2_([2-6]).*\)/.test(w)),k=!("undefined"==typeof Worker),Y=!(!b||!b.getUserMedia),H=async()=>{let e=!1;if(Y)try{(await b.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===v.browser&&v.version>66||"Safari"===v.browser&&v.version>13||"OPR"===v.browser&&v.version>43||"Edge"===v.browser&&v.version;const X={},Z=async e=>{let E="string"==typeof e?[e]:e,_=[];for(let e of E)_.push(X[e]=X[e]||new t);await Promise.all(_)},W=async(e,E)=>{let _,I="string"==typeof e?[e]:e,r=[];for(let e of I){let I;r.push(I=X[e]=X[e]||new t(_=_||E())),I.isEmpty&&(I.task=_=_||E())}await Promise.all(r)};e.worker=void 0;let j=0;const K=()=>j++,J={};e.onLog=void 0;const Q=E=>{e.onLog=E,e.worker&&e.worker.postMessage({type:"setBLog",body:{value:!!E}})};e.bDebug=!1;const $=E=>{e.bDebug=E,e.worker&&e.worker.postMessage({type:"setBDebug",body:{value:!!E}})},z={},q={dip:{wasm:!0}},ee={std:{version:"1.4.21",path:A(C+"../../dynamsoft-capture-vision-std@1.4.21/dist/"),isInternal:!0},core:{version:"3.4.31",path:C,isInternal:!0}},Ee=async E=>{let _;E instanceof Array||(E=E?[E]:[]);let I=X.core;_=!I||I.isEmpty;let r=new Map;const n=e=>{if("std"==(e=e.toLowerCase())||"core"==e)return;if(!q[e])throw Error("The '"+e+"' module cannot be found.");let E=q[e].deps;if(null==E?void 0:E.length)for(let e of E)n(e);let _=X[e];r.has(e)||r.set(e,!_||_.isEmpty)};for(let e of E)n(e);let o=[];_&&o.push("core"),o.push(...r.keys());const a=[...r.entries()].filter((e=>!e[1])).map((e=>e[0]));await W(o,(async()=>{const E=[...r.entries()].filter((e=>e[1])).map((e=>e[0]));await Z(a);const I=u(ee),n={};for(let e of E)n[e]=q[e];const o={engineResourcePaths:I,autoResources:n,names:E};let s=new t;if(_){o.needLoadCore=!0;let E=I.core+_e._workerName;E.startsWith(location.origin)||(E=await fetch(E).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),e.worker=new Worker(E),e.worker.onerror=e=>{let E=new Error(e.message);s.reject(E)},e.worker.addEventListener("message",(E=>{let _=E.data?E.data:E,t=_.type,I=_.id,r=_.body;switch(t){case"log":e.onLog&&e.onLog(_.message);break;case"task":try{J[I](r),delete J[I]}catch(e){throw delete J[I],e}break;case"event":try{J[I](r)}catch(e){throw e}break;default:console.log(E)}})),o.bLog=!!e.onLog,o.bd=e.bDebug,o.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await Z("core");let i=j++;J[i]=e=>{if(e.success)Object.assign(z,e.versions),"{}"!==JSON.stringify(e.versions)&&(_e._versions=e.versions),s.resolve(void 0);else{const E=Error(e.message);e.stack&&(E.stack=e.stack),s.reject(E)}},e.worker.postMessage({type:"loadWasm",body:o,id:i}),await s}))};class _e{static get engineResourcePaths(){return ee}static set engineResourcePaths(e){Object.assign(ee,e)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return e.onLog}static set _onLog(e){Q(e)}static get _bDebug(){return e.bDebug}static set _bDebug(e){$(e)}static isModuleLoaded(e){return e=(e=e||"core").toLowerCase(),!!X[e]&&X[e].isFulfilled}static async loadWasm(e){return await Ee(e)}static async detectEnvironment(){return await(async()=>({wasm:x,worker:k,getUserMedia:Y,camera:await H(),browser:v.browser,version:v.version,OS:v.OS}))()}static async getModuleVersion(){return await new Promise(((E,_)=>{let t=K();J[t]=async e=>{if(e.success)return E(e.versions);{let E=new Error(e.message);return E.stack=e.stack+"\n"+E.stack,_(E)}},e.worker.postMessage({type:"getModuleVersion",id:t})}))}static getVersion(){const e=z.core&&z.core.worker,E=z.core&&z.core.wasm;return`3.4.31(Worker: ${e||"Not Loaded"}, Wasm: ${E||"Not Loaded"})`}static enableLogging(){y._onLog=console.log,_e._onLog=console.log}static disableLogging(){y._onLog=null,_e._onLog=null}static async cfd(E){return await new Promise(((_,t)=>{let I=K();J[I]=async e=>{if(e.success)return _();{let E=new Error(e.message);return E.stack=e.stack+"\n"+E.stack,t(E)}},e.worker.postMessage({type:"cfd",id:I,body:{count:E}})}))}}var te,Ie,re,ne,oe,ae,se,ie,Ce;_e._bSupportDce4Module=-1,_e._bSupportIRTModule=-1,_e._versions=null,_e._workerName="core.worker.js",_e.browserInfo=v,e.EnumCapturedResultItemType=void 0,(te=e.EnumCapturedResultItemType||(e.EnumCapturedResultItemType={}))[te.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",te[te.CRIT_BARCODE=2]="CRIT_BARCODE",te[te.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",te[te.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",te[te.CRIT_NORMALIZED_IMAGE=16]="CRIT_NORMALIZED_IMAGE",te[te.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT",e.EnumCornerType=void 0,(Ie=e.EnumCornerType||(e.EnumCornerType={}))[Ie.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",Ie[Ie.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",Ie[Ie.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",Ie[Ie.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED",e.EnumErrorCode=void 0,(re=e.EnumErrorCode||(e.EnumErrorCode={}))[re.EC_OK=0]="EC_OK",re[re.EC_UNKNOWN=-1e4]="EC_UNKNOWN",re[re.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",re[re.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",re[re.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",re[re.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",re[re.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",re[re.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",re[re.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",re[re.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",re[re.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",re[re.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",re[re.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",re[re.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",re[re.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",re[re.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",re[re.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",re[re.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",re[re.EC_TIMEOUT=-10026]="EC_TIMEOUT",re[re.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",re[re.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",re[re.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",re[re.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",re[re.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",re[re.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",re[re.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",re[re.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",re[re.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",re[re.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",re[re.EC_RESERVED_INFO_NOT_MATCH=-10040]="EC_RESERVED_INFO_NOT_MATCH",re[re.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",re[re.EC_REQUEST_FAILED=-10044]="EC_REQUEST_FAILED",re[re.EC_LICENSE_INIT_FAILED=-10045]="EC_LICENSE_INIT_FAILED",re[re.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",re[re.EC_LICENSE_CONTENT_INVALID=-10052]="EC_LICENSE_CONTENT_INVALID",re[re.EC_LICENSE_KEY_INVALID=-10053]="EC_LICENSE_KEY_INVALID",re[re.EC_LICENSE_DEVICE_RUNS_OUT=-10054]="EC_LICENSE_DEVICE_RUNS_OUT",re[re.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",re[re.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",re[re.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",re[re.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",re[re.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",re[re.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",re[re.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",re[re.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",re[re.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",re[re.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",re[re.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",re[re.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",re[re.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",re[re.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",re[re.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",re[re.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",re[re.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",re[re.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",re[re.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",re[re.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",re[re.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",re[re.EC_HANDSHAKE_CODE_INVALID=-20001]="EC_HANDSHAKE_CODE_INVALID",re[re.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",re[re.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",re[re.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",re[re.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",re[re.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",re[re.EC_LICENSE_INIT_SEQUENCE_FAILED=-20009]="EC_LICENSE_INIT_SEQUENCE_FAILED",re[re.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",re[re.EC_FAILED_TO_REACH_DLS=-20200]="EC_FAILED_TO_REACH_DLS",re[re.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",re[re.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",re[re.EC_QR_LICENSE_INVALID=-30016]="EC_QR_LICENSE_INVALID",re[re.EC_1D_LICENSE_INVALID=-30017]="EC_1D_LICENSE_INVALID",re[re.EC_PDF417_LICENSE_INVALID=-30019]="EC_PDF417_LICENSE_INVALID",re[re.EC_DATAMATRIX_LICENSE_INVALID=-30020]="EC_DATAMATRIX_LICENSE_INVALID",re[re.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",re[re.EC_AZTEC_LICENSE_INVALID=-30041]="EC_AZTEC_LICENSE_INVALID",re[re.EC_PATCHCODE_LICENSE_INVALID=-30046]="EC_PATCHCODE_LICENSE_INVALID",re[re.EC_POSTALCODE_LICENSE_INVALID=-30047]="EC_POSTALCODE_LICENSE_INVALID",re[re.EC_DPM_LICENSE_INVALID=-30048]="EC_DPM_LICENSE_INVALID",re[re.EC_FRAME_DECODING_THREAD_EXISTS=-30049]="EC_FRAME_DECODING_THREAD_EXISTS",re[re.EC_STOP_DECODING_THREAD_FAILED=-30050]="EC_STOP_DECODING_THREAD_FAILED",re[re.EC_MAXICODE_LICENSE_INVALID=-30057]="EC_MAXICODE_LICENSE_INVALID",re[re.EC_GS1_DATABAR_LICENSE_INVALID=-30058]="EC_GS1_DATABAR_LICENSE_INVALID",re[re.EC_GS1_COMPOSITE_LICENSE_INVALID=-30059]="EC_GS1_COMPOSITE_LICENSE_INVALID",re[re.EC_DOTCODE_LICENSE_INVALID=-30061]="EC_DOTCODE_LICENSE_INVALID",re[re.EC_PHARMACODE_LICENSE_INVALID=-30062]="EC_PHARMACODE_LICENSE_INVALID",re[re.EC_CHARACTER_MODEL_FILE_NOT_FOUND=-40100]="EC_CHARACTER_MODEL_FILE_NOT_FOUND",re[re.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",re[re.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",re[re.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",re[re.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",re[re.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",re[re.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",re[re.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",re[re.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",re[re.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",re[re.EC_ZA_DL_LICENSE_INVALID=-90006]="EC_ZA_DL_LICENSE_INVALID",re[re.EC_AAMVA_DL_ID_LICENSE_INVALID=-90007]="EC_AAMVA_DL_ID_LICENSE_INVALID",re[re.EC_AADHAAR_LICENSE_INVALID=-90008]="EC_AADHAAR_LICENSE_INVALID",re[re.EC_MRTD_LICENSE_INVALID=-90009]="EC_MRTD_LICENSE_INVALID",re[re.EC_VIN_LICENSE_INVALID=-90010]="EC_VIN_LICENSE_INVALID",re[re.EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID=-90011]="EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID",re[re.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",re[re.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",re[re.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",re[re.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",re[re.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND",e.EnumGrayscaleEnhancementMode=void 0,(ne=e.EnumGrayscaleEnhancementMode||(e.EnumGrayscaleEnhancementMode={}))[ne.GEM_SKIP=0]="GEM_SKIP",ne[ne.GEM_AUTO=1]="GEM_AUTO",ne[ne.GEM_GENERAL=2]="GEM_GENERAL",ne[ne.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",ne[ne.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",ne[ne.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",ne[ne.GEM_REV=-2147483648]="GEM_REV",e.EnumGrayscaleTransformationMode=void 0,(oe=e.EnumGrayscaleTransformationMode||(e.EnumGrayscaleTransformationMode={}))[oe.GTM_SKIP=0]="GTM_SKIP",oe[oe.GTM_INVERTED=1]="GTM_INVERTED",oe[oe.GTM_ORIGINAL=2]="GTM_ORIGINAL",oe[oe.GTM_AUTO=4]="GTM_AUTO",oe[oe.GTM_REV=-2147483648]="GTM_REV",e.EnumImageTagType=void 0,(ae=e.EnumImageTagType||(e.EnumImageTagType={}))[ae.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",ae[ae.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME",e.EnumPDFReadingMode=void 0,(se=e.EnumPDFReadingMode||(e.EnumPDFReadingMode={}))[se.PDFRM_VECTOR=1]="PDFRM_VECTOR",se[se.PDFRM_RASTER=2]="PDFRM_RASTER",se[se.PDFRM_REV=-2147483648]="PDFRM_REV",e.EnumRasterDataSource=void 0,(ie=e.EnumRasterDataSource||(e.EnumRasterDataSource={}))[ie.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",ie[ie.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES",e.EnumCrossVerificationStatus=void 0,(Ce=e.EnumCrossVerificationStatus||(e.EnumCrossVerificationStatus={}))[Ce.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",Ce[Ce.CVS_PASSED=1]="CVS_PASSED",Ce[Ce.CVS_FAILED=2]="CVS_FAILED";const Ae={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_DOWN_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_UP_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_NORMALIZED_IMAGES:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var Te,Ne;e.EnumRegionObjectElementType=void 0,(Te=e.EnumRegionObjectElementType||(e.EnumRegionObjectElementType={}))[Te.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",Te[Te.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",Te[Te.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",Te[Te.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",Te[Te.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",Te[Te.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",Te[Te.ROET_NORMALIZED_IMAGE=6]="ROET_NORMALIZED_IMAGE",Te[Te.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",Te[Te.ROET_TARGET_ROI=8]="ROET_TARGET_ROI",e.EnumSectionType=void 0,(Ne=e.EnumSectionType||(e.EnumSectionType={}))[Ne.ST_NULL=0]="ST_NULL",Ne[Ne.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",Ne[Ne.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",Ne[Ne.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",Ne[Ne.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",Ne[Ne.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",Ne[Ne.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",Ne[Ne.ST_DOCUMENT_NORMALIZATION=7]="ST_DOCUMENT_NORMALIZATION",e.CoreModule=_e,e.EnumIntermediateResultUnitType=Ae,e.ImageSourceAdapter=y,e._getNorImageData=d,e._saveToFile=async(e,E,_)=>await new Promise((async(t,I)=>{try{const I=E.split(".");let r=I[I.length-1];const n=await g(`image/${r}`,e);I.length<=1&&(r="png");const o=new File([n],E,{type:`image/${r}`});if(_){const e=URL.createObjectURL(o),_=document.createElement("a");_.href=e,_.download=E,_.click()}return t(o)}catch(e){return I()}})),e._toBlob=g,e._toCanvas=S,e._toImage=(e,E)=>{l(E)&&(E=d(E));const _=S(E);let t=new Image,I=_.toDataURL(e);return t.src=I,t},e.checkIsLink=e=>/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(e),e.compareVersion=(e,E)=>{let _=e.split("."),t=E.split(".");for(let e=0;e<_.length&&e!!D(e)&&(!!L(e.x)&&(!!L(e.y)&&(!!L(e.radius)&&(!(e.radius<0)&&(!!L(e.startAngle)&&!!L(e.endAngle)))))),e.isContour=e=>!!D(e)&&(!!N(e.points)&&(0!=e.points.length&&!e.points.some((e=>!c(e))))),e.isDSImageData=l,e.isDSRect=e=>!!D(e)&&(!!L(e.left)&&(!(e.left<0)&&(!!L(e.top)&&(!(e.top<0)&&(!!L(e.right)&&(!(e.right<0)&&(!!L(e.bottom)&&(!(e.bottom<0)&&(!(e.left>=e.right)&&(!(e.top>=e.bottom)&&!!R(e.isMeasuredInPercentage))))))))))),e.isImageTag=m,e.isLineSegment=e=>!!D(e)&&(!!c(e.startPoint)&&(!!c(e.endPoint)&&(e.startPoint.x!=e.endPoint.x||e.startPoint.y!=e.endPoint.y))),e.isObject=D,e.isOriginalDsImageData=e=>!!O(e)&&!(!L(e.bytes.length)&&!L(e.bytes.ptr)),e.isPoint=c,e.isPolygon=e=>!!D(e)&&(!!N(e.points)&&(0!=e.points.length&&!e.points.some((e=>!c(e))))),e.isQuad=e=>!!D(e)&&(!!N(e.points)&&(0!=e.points.length&&4==e.points.length&&!e.points.some((e=>!c(e))))),e.isRect=e=>!!D(e)&&(!!L(e.x)&&(!!L(e.y)&&(!!L(e.width)&&(!(e.width<0)&&(!!L(e.height)&&(!(e.height<0)&&!("isMeasuredInPercentage"in e&&!R(e.isMeasuredInPercentage)))))))),e.loadWasm=Ee,e.mapAsyncDependency=X,e.mapPackageRegister={},e.mapTaskCallBack=J,e.requestResource=async(e,E)=>await new Promise(((_,t)=>{let I=new XMLHttpRequest;I.open("GET",e,!0),I.responseType=E,I.send(),I.onloadend=async()=>{I.status<200||I.status>=300?t(new Error(e+" "+I.status)):_(I.response)},I.onerror=()=>{t(new Error("Network Error: "+I.statusText))}})),e.setBDebug=$,e.setOnLog=Q,e.waitAsyncDependency=Z,e.workerAutoResources=q})); diff --git a/dist/dynamsoft-core@3.4.31/dist/core.worker.js b/dist/dynamsoft-core@3.4.31/dist/core.worker.js new file mode 100644 index 0000000..60245fb --- /dev/null +++ b/dist/dynamsoft-core@3.4.31/dist/core.worker.js @@ -0,0 +1,11 @@ +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft Core JS Edition + * @website https://www.dynamsoft.com + * @copyright Copyright 2024, Dynamsoft Corporation + * @author Dynamsoft + * @version 3.4.31 + * @fileoverview Dynamsoft JavaScript Library for Core + * More info on Dynamsoft Core JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/core/core-module.html + */ +!function(){"use strict";const e=e=>e&&"object"==typeof e&&"function"==typeof e.then,s=(async()=>{})().constructor;class t extends s{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 o;this._task=t,e(t)?o=t:"function"==typeof t&&(o=new s(t)),o&&(async()=>{try{const e=await o;t===this._task&&this.resolve(e)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(s){let t,o;super(((e,s)=>{t=e,o=s})),this._s="pending",this.resolve=s=>{this.isPending&&(e(s)?this.task=s:(this._s="fulfilled",t(s)))},this.reject=e=>{this.isPending&&(this._s="rejected",o(e))},this.task=s}}const o=self,r={};o.coreWorkerVersion="3.4.31",o.versions=r;const a={},n=o.waitAsyncDependency=async e=>{let s="string"==typeof e?[e]:e,o=[];for(let e of s)o.push(a[e]=a[e]||new t);await Promise.all(o)},i=async(e,s)=>{let o,r="string"==typeof e?[e]:e,n=[];for(let e of r){let r;n.push(r=a[e]=a[e]||new t(o=o||s())),r.isEmpty&&(r.task=o=o||s())}await Promise.all(n)},c=[];o.setBufferIntoWasm=(e,s=0,t=0,o=0)=>{t&&(e=o?e.subarray(t,o):e.subarray(t));let r=c[s]=c[s]||{ptr:0,size:0,maxSize:0};return e.length>r.maxSize&&(r.ptr&&m._free(r.ptr),r.ptr=m._malloc(e.length),r.maxSize=e.length),m.HEAPU8.set(e,r.ptr),r.size=e.length,r.ptr};const l={buffer:0,size:0,pos:0,temps:[],needed:0,prepare:function(){if(l.needed){for(let e=0;e=l.size?(l.needed+=r,t=m._malloc(r),l.temps.push(t)):(t=l.buffer+l.pos,l.pos+=r),t},copy:function(e,s,t){switch(t>>>=0,s.BYTES_PER_ELEMENT){case 2:t>>>=1;break;case 4:t>>>=2;break;case 8:t>>>=3}for(let o=0;o{let s=intArrayFromString(e),t=l.alloc(s,m.HEAP8);return l.copy(s,m.HEAP8,t),t},m=o.Module={print:e=>{o.bLog&&w(e)},printErr:e=>{o.bLog&&w(e)},locateFile:(e,s)=>["dynamsoft-barcode-reader-bundle.wasm","core.wasm"].includes(e)?u.std+e:e},u=o.engineResourcePaths={},g=o.loadCore=async()=>{const e="core";await i(e,(async()=>{let s=o.bLog&&(w(e+" loading..."),Date.now())||0,t=new Promise((t=>{Module.onRuntimeInitialized=()=>{o.bLog&&w(e+" initialized, cost "+(Date.now()-s)+" ms"),t(void 0)}})),r=u.std+"dynamsoft-barcode-reader-bundle.js";importScripts(r),await t}))},f=o.loadSideModule=async(e,{js:s,wasm:t})=>{await i(e,(async()=>{await n("core");let t=o.bLog&&(w(e+" loading..."),Date.now())||0;if(s instanceof Array)for(let t of s){let s=u[e]+t;importScripts(s)}else if(s){let s=u[e]+e+".worker.js";importScripts(s)}wasmImports.emscripten_bind_CoreWasm_PreSetModuleExist&&(d(),wasmImports.emscripten_bind_CoreWasm_PreSetModuleExist(p(e.toUpperCase()))),wasmImports.emscripten_bind_CvrWasm_SetModuleExist&&(d(),wasmImports.emscripten_bind_CvrWasm_SetModuleExist(p(e.toUpperCase())));const a=JSON.parse(UTF8ToString(wasmImports.emscripten_bind_CoreWasm_GetModuleVersion_0())),i=o[`${e}WorkerVersion`];r[e]={worker:`${i||"No Worker"}`,wasm:a[e.toUpperCase()]},o.bLog&&w(e+" initialized, cost "+(Date.now()-t)+" ms")}))},_=o.mapController={loadWasm:async(e,s)=>{try{Object.assign(u,e.engineResourcePaths),e.needLoadCore&&(e.bLog&&(o.bLog=!0),e.dm&&(o.strDomain=e.dm),e.bd&&(o.bDebug=!0),await g());for(let s of e.names)await f(s,e.autoResources[s]);if(e.needLoadCore){const e=JSON.parse(UTF8ToString(wasmImports.emscripten_bind_CoreWasm_GetModuleVersion_0()));r.core={worker:o.coreWorkerVersion,wasm:e.CORE}}for(let e in r)r[e].wasm&&(r[e].wasm=r[e].wasm.replace("20250211","23472-single-wasm"));h(s,{versions:r})}catch(e){console.log(e),b(s,e)}},setBLog:e=>{o.bLog=e.value},setBDebug:e=>{o.bDebug=e.value},getModuleVersion:async(e,s)=>{try{let e=UTF8ToString(wasmImports.emscripten_bind_CoreWasm_GetModuleVersion_0());h(s,{versions:JSON.parse(e)})}catch(e){b(s,e)}},cfd:async(e,s)=>{try{wasmImports.emscripten_bind_CoreWasm_static_CFD_1(e.count),h(s,{})}catch(e){b(s,e)}}};addEventListener("message",(e=>{const s=e.data?e.data:e,t=s.body,o=s.id,r=s.instanceID,a=_[s.type];if(!a)throw new Error("Unmatched task: "+s.type);"license_dynamsoft"==a&&(t.v="3.4.31-single-wasm"),a(t,o,r)}));const h=o.handleTaskRes=(e,s)=>{postMessage({type:"task",id:e,body:Object.assign({success:!0},s)})},b=o.handleTaskErr=(e,s)=>{postMessage({type:"task",id:e,body:{success:!1,message:(null==s?void 0:s.message)||"No have error message.",stack:o.bDebug&&(null==s?void 0:s.stack)||"No have stack."}})},w=o.log=e=>{postMessage({type:"log",message:e})}}(); \ No newline at end of file diff --git a/dist/dynamsoft-license@3.4.31/dist/dls.license.dialog.html b/dist/dynamsoft-license@3.4.31/dist/dls.license.dialog.html new file mode 100644 index 0000000..724e9de --- /dev/null +++ b/dist/dynamsoft-license@3.4.31/dist/dls.license.dialog.html @@ -0,0 +1,20 @@ + +
+
+
+ + + x +
+
+
+
+ \ No newline at end of file diff --git a/dist/dynamsoft-license@3.4.31/dist/license.d.ts b/dist/dynamsoft-license@3.4.31/dist/license.d.ts new file mode 100644 index 0000000..2e2e0b6 --- /dev/null +++ b/dist/dynamsoft-license@3.4.31/dist/license.d.ts @@ -0,0 +1,40 @@ +declare class LicenseModule { + static getVersion(): string; +} + +declare class LicenseManager { + private static setLicenseServer; + static _pLoad: any; + static bPassValidation: boolean; + static bCallInitLicense: boolean; + private static _license; + static get license(): string; + static set license(license: string); + /** + * Specify the license server URL. + */ + private static _licenseServer?; + static get licenseServer(): string[] | string; + static set licenseServer(value: string[] | string); + private static _deviceFriendlyName; + static get deviceFriendlyName(): string; + static set deviceFriendlyName(value: string); + /** + * License the components. + * @param license the license key to be used. + * @remarks - for an online license, LicenseManager asks DLS for the license associated with the 'license' key and gets all usable modules + - for an offline license, LicenseManager parses it to get a list of usable modules + * @returns a promise resolving to true or false to indicate whether the license was initialized successfully. + */ + static initLicense(license: string, options?: { + executeNow: boolean; + } | boolean): void | Promise; + /** + * The following methods should be called before `initLicense`. + */ + static setDeviceFriendlyName(name: string): void; + static getDeviceFriendlyName(): string; + static getDeviceUUID(): Promise; +} + +export { LicenseManager, LicenseModule }; diff --git a/dist/dynamsoft-license@3.4.31/dist/license.esm.js b/dist/dynamsoft-license@3.4.31/dist/license.esm.js new file mode 100644 index 0000000..1c759d3 --- /dev/null +++ b/dist/dynamsoft-license@3.4.31/dist/license.esm.js @@ -0,0 +1,11 @@ +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft License JS Edition + * @website https://www.dynamsoft.com + * @copyright Copyright 2024, Dynamsoft Corporation + * @author Dynamsoft + * @version 3.4.31 + * @fileoverview Dynamsoft JavaScript Library for Core + * More info DL JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/license/license-module.html + */ +import{mapPackageRegister as e,loadWasm as t,doOrWaitAsyncDependency as s,getNextTaskID as r,mapTaskCallBack as n,onLog as i,CoreModule as o,handleEngineResourcePaths as a,waitAsyncDependency as c,worker as l,mapAsyncDependency as d,workerAutoResources as u,compareVersion as f,innerVersions as h}from"dynamsoft-core";const g="undefined"==typeof self,m=g?{}:self,p="function"==typeof importScripts,y=(()=>{if(!p){if(!g&&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"./"}})(),v=e=>{if(null==e&&(e="./"),g||p);else{let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e},w=e=>e&&"object"==typeof e&&"function"==typeof e.then,b=(async()=>{})().constructor;class S extends b{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,w(e)?t=e:"function"==typeof e&&(t=new b(e)),t&&(async()=>{try{const s=await t;e===this._task&&this.resolve(s)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}constructor(e){let t,s;super(((e,r)=>{t=e,s=r})),this._s="pending",this.resolve=e=>{this.isPending&&(w(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",s(e))},this.task=e}}const _=" is not allowed to change after `createInstance` or `loadWasm` is called.",k=!g&&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"))||"",E=(e,t)=>{const s=e;if(s._license!==t){if(!s._pLoad.isEmpty)throw new Error("`license`"+_);s._license=t}};!g&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const L=e=>{if(null==e)e=[];else{e=e instanceof Array?[...e]:[e];for(let t=0;t{t=L(t);const s=e;if(s._licenseServer!==t){if(!s._pLoad.isEmpty)throw new Error("`licenseServer`"+_);s._licenseServer=t}},x=(e,t)=>{t=t||"";const s=e;if(s._deviceFriendlyName!==t){if(!s._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+_);s._deviceFriendlyName=t}};let C,P,N,I,R;"undefined"!=typeof navigator&&(C=navigator,P=C.userAgent,N=C.platform,I=C.mediaDevices),function(){if(!g){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:C.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},t={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:N,search:"Win"},Mac:{str:N},Linux:{str:N}};let s="unknownBrowser",r=0,n="unknownOS";for(let t in e){const n=e[t]||{};let i=n.str||P,o=n.search||t,a=n.verStr||P,c=n.verSearch||t;if(c instanceof Array||(c=[c]),-1!=i.indexOf(o)){s=t;for(let e of c){let t=a.indexOf(e);if(-1!=t){r=parseFloat(a.substring(t+e.length+1));break}}break}}for(let e in t){const s=t[e]||{};let r=s.str||P,i=s.search||e;if(-1!=r.indexOf(i)){n=e;break}}"Linux"==n&&-1!=P.indexOf("Windows NT")&&(n="HarmonyOS"),R={browser:s,version:r,OS:n}}g&&(R={browser:"ssr",version:0,OS:"ssr"})}(),I&&I.getUserMedia,"Chrome"===R.browser&&R.version>66||"Safari"===R.browser&&R.version>13||"OPR"===R.browser&&R.version>43||"Edge"===R.browser&&R.version;const W=()=>(t("license"),s("dynamsoft_inited",(async()=>{let{lt:e,l:t,ls:s,sp:d,rmk:u,cv:f}=((e,t=!1)=>{const s=e;if(s._pLoad.isEmpty){let e,r,n,i=s._license||"",o=JSON.parse(JSON.stringify(s._licenseServer)),a=s._sessionPassword,c=0;if(i.startsWith("t")||i.startsWith("f"))c=0;else if(0===i.length||i.startsWith("P")||i.startsWith("L")||i.startsWith("Y")||i.startsWith("A"))c=1;else{c=2;const t=i.indexOf(":");-1!=t&&(i=i.substring(t+1));const s=i.indexOf("?");if(-1!=s&&(r=i.substring(s+1),i=i.substring(0,s)),i.startsWith("DLC2"))c=0;else{if(i.startsWith("DLS2")){let t;try{let e=i.substring(4);e=atob(e),t=JSON.parse(e)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(i=t.handshakeCode?t.handshakeCode:t.organizationID?t.organizationID:"","number"==typeof i&&(i=JSON.stringify(i)),0===o.length){let e=[];t.mainServerURL&&(e[0]=t.mainServerURL),t.standbyServerURL&&(e[1]=t.standbyServerURL),o=L(e)}!a&&t.sessionPassword&&(a=t.sessionPassword),e=t.remark}i&&"200001"!==i&&!i.startsWith("200001-")||(c=1)}}if(c&&(t||(m.crypto||(n="Please upgrade your browser to support online key."),m.crypto.subtle||(n="Require https to use online key in this browser."))),n)throw new Error(n);return 1===c&&(i="",console.warn("Applying for a public trial license ...")),{lt:c,l:i,ls:o,sp:a,rmk:e,cv:r}}throw new Error("Can't preprocess license again"+_)})(D),h=new S;D._pLoad.task=h,(async()=>{try{await D._pLoad}catch(e){}})();let g=r();n[g]=t=>{if(t.message&&D._onAuthMessage){let e=D._onAuthMessage(t.message);null!=e&&(t.message=e)}let s,r=!1;if(1===e&&(r=!0),t.success?(i&&i("init license success"),t.message&&console.warn(t.message),o._bSupportIRTModule=t.bSupportIRTModule,o._bSupportDce4Module=t.bSupportDce4Module,D.bPassValidation=!0,[0,-10076].includes(t.initLicenseInfo.errorCode)?[-10076].includes(t.initLicenseInfo.errorCode)&&console.warn(t.initLicenseInfo.errorString):h.reject(new Error(t.initLicenseInfo.errorString))):(s=Error(t.message),t.stack&&(s.stack=t.stack),t.ltsErrorCode&&(s.ltsErrorCode=t.ltsErrorCode),r||111==t.ltsErrorCode&&-1!=t.message.toLowerCase().indexOf("trial license")&&(r=!0)),r){const e=a(o.engineResourcePaths);(async(e,t,s)=>{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 i=document.createElement("div");i.innerHTML=n;let o=[];for(let e=0;e{if(e==t.target){a.remove();for(let e of o)e.remove()}}));else if(!l&&e.classList.contains("dls-license-icon-close"))l=e,e.addEventListener("click",(()=>{a.remove();for(let e of o)e.remove()}));else if(!d&&e.classList.contains("dls-license-icon-error"))d=e,"error"!=t&&e.remove();else if(!u&&e.classList.contains("dls-license-icon-warn"))u=e,"warn"!=t&&e.remove();else if(!f&&e.classList.contains("dls-license-msg-content")){f=e;let t=s;for(;t;){let s=t.indexOf("["),r=t.indexOf("]",s),n=t.indexOf("(",r),i=t.indexOf(")",n);if(-1==s||-1==r||-1==n||-1==i){e.appendChild(new Text(t));break}s>0&&e.appendChild(new Text(t.substring(0,s)));let o=document.createElement("a"),a=t.substring(s+1,r);o.innerText=a;let c=t.substring(n+1,i);o.setAttribute("href",c),o.setAttribute("target","_blank"),e.appendChild(o),t=t.substring(i+1)}}document.body.appendChild(a)}catch(t){e._onLog&&e._onLog(t.message||t)}})({_bNeverShowDialog:D._bNeverShowDialog,engineResourcePath:e.license,_onLog:i},t.success?"warn":"error",t.message)}t.success?h.resolve(void 0):h.reject(s)},await c("core"),l.postMessage({type:"license_dynamsoft",body:{v:"3.4.31",brtk:!!e,bptk:1===e,l:t,os:R,fn:D.deviceFriendlyName,ls:s,sp:d,rmk:u,cv:f},id:g}),D.bCallInitLicense=!0,await h})));let A;e.license={},e.license.dynamsoft=W,e.license.getAR=async()=>{{let e=d.dynamsoft_inited;e&&e.isRejected&&await e}return l?new Promise(((e,t)=>{let s=r();n[s]=async s=>{if(s.success){delete s.success;{let e=D.license;e&&(e.startsWith("t")||e.startsWith("f"))&&(s.pk=e)}if(Object.keys(s).length){if(s.lem){let e=Error(s.lem);e.ltsErrorCode=s.lec,delete s.lem,delete s.lec,s.ae=e}e(s)}else e(null)}else{let e=Error(s.message);s.stack&&(e.stack=s.stack),t(e)}},l.postMessage({type:"license_getAR",id:s})})):null};class D{static setLicenseServer(e){O(D,e)}static get license(){return this._license}static set license(e){E(D,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){O(D,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){x(D,e)}static initLicense(e,t){if(E(D,e),D.bCallInitLicense=!0,"boolean"==typeof t&&t||"object"==typeof t&&t.executeNow)return W()}static setDeviceFriendlyName(e){x(D,e)}static getDeviceFriendlyName(){return D._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await s("dynamsoft_uuid",(async()=>{await t();let e=new S,s=r();n[s]=t=>{if(t.success)e.resolve(t.uuid);else{const s=Error(t.message);t.stack&&(s.stack=t.stack),e.reject(s)}},l.postMessage({type:"license_getDeviceUUID",id:s}),A=await e})),A))()}}D._pLoad=new S,D.bPassValidation=!1,D.bCallInitLicense=!1,D._license=k,D._licenseServer=[],D._deviceFriendlyName="",o.engineResourcePaths.license={version:"3.4.31",path:y,isInternal:!0},u.license={wasm:!0,js:!0},e.license.LicenseManager=D;const M="1.4.21";"string"!=typeof o.engineResourcePaths.std&&f(o.engineResourcePaths.std.version,M)<0&&(o.engineResourcePaths.std={version:M,path:v(y+`../../dynamsoft-capture-vision-std@${M}/dist/`),isInternal:!0});class F{static getVersion(){return`3.4.31(Worker: ${h.license&&h.license.worker||"Not Loaded"}, Wasm: ${h.license&&h.license.wasm||"Not Loaded"})`}}export{D as LicenseManager,F as LicenseModule}; diff --git a/dist/dynamsoft-license@3.4.31/dist/license.js b/dist/dynamsoft-license@3.4.31/dist/license.js new file mode 100644 index 0000000..ad561c0 --- /dev/null +++ b/dist/dynamsoft-license@3.4.31/dist/license.js @@ -0,0 +1,11 @@ +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft License JS Edition + * @website https://www.dynamsoft.com + * @copyright Copyright 2024, Dynamsoft Corporation + * @author Dynamsoft + * @version 3.4.31 + * @fileoverview Dynamsoft JavaScript Library for Core + * More info DL JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/license/license-module.html + */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("dynamsoft-core")):"function"==typeof define&&define.amd?define(["exports","dynamsoft-core"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).Dynamsoft=e.Dynamsoft||{},e.Dynamsoft.License={}),e.Dynamsoft.Core)}(this,(function(e,t){"use strict";const s="undefined"==typeof self,r=s?{}:self,n="function"==typeof importScripts,i=(()=>{if(!n){if(!s&&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"./"}})(),o=e=>{if(null==e&&(e="./"),s||n);else{let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e},a=e=>e&&"object"==typeof e&&"function"==typeof e.then,c=(async()=>{})().constructor;class l extends c{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 c(e)),t&&(async()=>{try{const s=await t;e===this._task&&this.resolve(s)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}constructor(e){let t,s;super(((e,r)=>{t=e,s=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",s(e))},this.task=e}}const d=" is not allowed to change after `createInstance` or `loadWasm` is called.",u=!s&&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,t)=>{const s=e;if(s._license!==t){if(!s._pLoad.isEmpty)throw new Error("`license`"+d);s._license=t}};!s&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const h=e=>{if(null==e)e=[];else{e=e instanceof Array?[...e]:[e];for(let t=0;t{t=h(t);const s=e;if(s._licenseServer!==t){if(!s._pLoad.isEmpty)throw new Error("`licenseServer`"+d);s._licenseServer=t}},p=(e,t)=>{t=t||"";const s=e;if(s._deviceFriendlyName!==t){if(!s._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+d);s._deviceFriendlyName=t}};let m,y,w,v,k;"undefined"!=typeof navigator&&(m=navigator,y=m.userAgent,w=m.platform,v=m.mediaDevices),function(){if(!s){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:m.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},t={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:w,search:"Win"},Mac:{str:w},Linux:{str:w}};let s="unknownBrowser",r=0,n="unknownOS";for(let t in e){const n=e[t]||{};let i=n.str||y,o=n.search||t,a=n.verStr||y,c=n.verSearch||t;if(c instanceof Array||(c=[c]),-1!=i.indexOf(o)){s=t;for(let e of c){let t=a.indexOf(e);if(-1!=t){r=parseFloat(a.substring(t+e.length+1));break}}break}}for(let e in t){const s=t[e]||{};let r=s.str||y,i=s.search||e;if(-1!=r.indexOf(i)){n=e;break}}"Linux"==n&&-1!=y.indexOf("Windows NT")&&(n="HarmonyOS"),k={browser:s,version:r,OS:n}}s&&(k={browser:"ssr",version:0,OS:"ssr"})}(),v&&v.getUserMedia,"Chrome"===k.browser&&k.version>66||"Safari"===k.browser&&k.version>13||"OPR"===k.browser&&k.version>43||"Edge"===k.browser&&k.version;const b=()=>(t.loadWasm("license"),t.doOrWaitAsyncDependency("dynamsoft_inited",(async()=>{let{lt:e,l:s,ls:n,sp:i,rmk:o,cv:a}=((e,t=!1)=>{const s=e;if(s._pLoad.isEmpty){let e,n,i,o=s._license||"",a=JSON.parse(JSON.stringify(s._licenseServer)),c=s._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const t=o.indexOf(":");-1!=t&&(o=o.substring(t+1));const s=o.indexOf("?");if(-1!=s&&(n=o.substring(s+1),o=o.substring(0,s)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let t;try{let e=o.substring(4);e=atob(e),t=JSON.parse(e)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(o=t.handshakeCode?t.handshakeCode:t.organizationID?t.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let e=[];t.mainServerURL&&(e[0]=t.mainServerURL),t.standbyServerURL&&(e[1]=t.standbyServerURL),a=h(e)}!c&&t.sessionPassword&&(c=t.sessionPassword),e=t.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(t||(r.crypto||(i="Please upgrade your browser to support online key."),r.crypto.subtle||(i="Require https to use online key in this browser."))),i)throw new Error(i);return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:c,rmk:e,cv:n}}throw new Error("Can't preprocess license again"+d)})(_),c=new l;_._pLoad.task=c,(async()=>{try{await _._pLoad}catch(e){}})();let u=t.getNextTaskID();t.mapTaskCallBack[u]=s=>{if(s.message&&_._onAuthMessage){let e=_._onAuthMessage(s.message);null!=e&&(s.message=e)}let r,n=!1;if(1===e&&(n=!0),s.success?(t.onLog&&t.onLog("init license success"),s.message&&console.warn(s.message),t.CoreModule._bSupportIRTModule=s.bSupportIRTModule,t.CoreModule._bSupportDce4Module=s.bSupportDce4Module,_.bPassValidation=!0,[0,-10076].includes(s.initLicenseInfo.errorCode)?[-10076].includes(s.initLicenseInfo.errorCode)&&console.warn(s.initLicenseInfo.errorString):c.reject(new Error(s.initLicenseInfo.errorString))):(r=Error(s.message),s.stack&&(r.stack=s.stack),s.ltsErrorCode&&(r.ltsErrorCode=s.ltsErrorCode),n||111==s.ltsErrorCode&&-1!=s.message.toLowerCase().indexOf("trial license")&&(n=!0)),n){const e=t.handleEngineResourcePaths(t.CoreModule.engineResourcePaths);(async(e,t,s)=>{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 i=document.createElement("div");i.innerHTML=n;let o=[];for(let e=0;e{if(e==t.target){a.remove();for(let e of o)e.remove()}}));else if(!l&&e.classList.contains("dls-license-icon-close"))l=e,e.addEventListener("click",(()=>{a.remove();for(let e of o)e.remove()}));else if(!d&&e.classList.contains("dls-license-icon-error"))d=e,"error"!=t&&e.remove();else if(!u&&e.classList.contains("dls-license-icon-warn"))u=e,"warn"!=t&&e.remove();else if(!f&&e.classList.contains("dls-license-msg-content")){f=e;let t=s;for(;t;){let s=t.indexOf("["),r=t.indexOf("]",s),n=t.indexOf("(",r),i=t.indexOf(")",n);if(-1==s||-1==r||-1==n||-1==i){e.appendChild(new Text(t));break}s>0&&e.appendChild(new Text(t.substring(0,s)));let o=document.createElement("a"),a=t.substring(s+1,r);o.innerText=a;let c=t.substring(n+1,i);o.setAttribute("href",c),o.setAttribute("target","_blank"),e.appendChild(o),t=t.substring(i+1)}}document.body.appendChild(a)}catch(t){e._onLog&&e._onLog(t.message||t)}})({_bNeverShowDialog:_._bNeverShowDialog,engineResourcePath:e.license,_onLog:t.onLog},s.success?"warn":"error",s.message)}s.success?c.resolve(void 0):c.reject(r)},await t.waitAsyncDependency("core"),t.worker.postMessage({type:"license_dynamsoft",body:{v:"3.4.31",brtk:!!e,bptk:1===e,l:s,os:k,fn:_.deviceFriendlyName,ls:n,sp:i,rmk:o,cv:a},id:u}),_.bCallInitLicense=!0,await c})));let S;t.mapPackageRegister.license={},t.mapPackageRegister.license.dynamsoft=b,t.mapPackageRegister.license.getAR=async()=>{{let e=t.mapAsyncDependency.dynamsoft_inited;e&&e.isRejected&&await e}return t.worker?new Promise(((e,s)=>{let r=t.getNextTaskID();t.mapTaskCallBack[r]=async t=>{if(t.success){delete t.success;{let e=_.license;e&&(e.startsWith("t")||e.startsWith("f"))&&(t.pk=e)}if(Object.keys(t).length){if(t.lem){let e=Error(t.lem);e.ltsErrorCode=t.lec,delete t.lem,delete t.lec,t.ae=e}e(t)}else e(null)}else{let e=Error(t.message);t.stack&&(e.stack=t.stack),s(e)}},t.worker.postMessage({type:"license_getAR",id:r})})):null};class _{static setLicenseServer(e){g(_,e)}static get license(){return this._license}static set license(e){f(_,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){g(_,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){p(_,e)}static initLicense(e,t){if(f(_,e),_.bCallInitLicense=!0,"boolean"==typeof t&&t||"object"==typeof t&&t.executeNow)return b()}static setDeviceFriendlyName(e){p(_,e)}static getDeviceFriendlyName(){return _._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await t.doOrWaitAsyncDependency("dynamsoft_uuid",(async()=>{await t.loadWasm();let e=new l,s=t.getNextTaskID();t.mapTaskCallBack[s]=t=>{if(t.success)e.resolve(t.uuid);else{const s=Error(t.message);t.stack&&(s.stack=t.stack),e.reject(s)}},t.worker.postMessage({type:"license_getDeviceUUID",id:s}),S=await e})),S))()}}_._pLoad=new l,_.bPassValidation=!1,_.bCallInitLicense=!1,_._license=u,_._licenseServer=[],_._deviceFriendlyName="",t.CoreModule.engineResourcePaths.license={version:"3.4.31",path:i,isInternal:!0},t.workerAutoResources.license={wasm:!0,js:!0},t.mapPackageRegister.license.LicenseManager=_;const L="1.4.21";"string"!=typeof t.CoreModule.engineResourcePaths.std&&t.compareVersion(t.CoreModule.engineResourcePaths.std.version,L)<0&&(t.CoreModule.engineResourcePaths.std={version:L,path:o(i+`../../dynamsoft-capture-vision-std@${L}/dist/`),isInternal:!0});e.LicenseManager=_,e.LicenseModule=class{static getVersion(){return`3.4.31(Worker: ${t.innerVersions.license&&t.innerVersions.license.worker||"Not Loaded"}, Wasm: ${t.innerVersions.license&&t.innerVersions.license.wasm||"Not Loaded"})`}}})); diff --git a/dist/dynamsoft-license@3.4.31/dist/license.worker.js b/dist/dynamsoft-license@3.4.31/dist/license.worker.js new file mode 100644 index 0000000..f6b18f1 --- /dev/null +++ b/dist/dynamsoft-license@3.4.31/dist/license.worker.js @@ -0,0 +1,11 @@ +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft License JS Edition + * @website https://www.dynamsoft.com + * @copyright Copyright 2024, Dynamsoft Corporation + * @author Dynamsoft + * @version 3.4.31 + * @fileoverview Dynamsoft JavaScript Library for Core + * More info DL JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/license/license-module.html + */ +!function(){"use strict";const e="undefined"==typeof self,t=e?{}:self;let r,n,o,i,a;"undefined"!=typeof navigator&&(r=navigator,n=r.userAgent,o=r.platform,i=r.mediaDevices),function(){if(!e){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:r.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},t={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:o,search:"Win"},Mac:{str:o},Linux:{str:o}};let i="unknownBrowser",s=0,c="unknownOS";for(let t in e){const r=e[t]||{};let o=r.str||n,a=r.search||t,c=r.verStr||n,l=r.verSearch||t;if(l instanceof Array||(l=[l]),-1!=o.indexOf(a)){i=t;for(let e of l){let t=c.indexOf(e);if(-1!=t){s=parseFloat(c.substring(t+e.length+1));break}}break}}for(let e in t){const r=t[e]||{};let o=r.str||n,i=r.search||e;if(-1!=o.indexOf(i)){c=e;break}}"Linux"==c&&-1!=n.indexOf("Windows NT")&&(c="HarmonyOS"),a={browser:i,version:s,OS:c}}e&&(a={browser:"ssr",version:0,OS:"ssr"})}(),i&&i.getUserMedia;const s="Chrome"===a.browser&&a.version>66||"Safari"===a.browser&&a.version>13||"OPR"===a.browser&&a.version>43||"Edge"===a.browser&&a.version>15;var c=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 y=e,y}))}function _(e){var t=p[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 S(e){var t=p[e.name].deferredOperations.pop();if(t)return t.resolve(),t.promise}function I(e,t){var r=p[e.name].deferredOperations.pop();if(r)return r.reject(t),r.promise}function x(e,t){return new Promise((function(r,n){if(p[e.name]=p[e.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},e.db){if(!t)return r(e.db);_(e),e.db.close()}var o=[e.name];t&&o.push(e.version);var i=c.open.apply(c,o);t&&(i.onupgradeneeded=function(t){var r=i.result;try{r.createObjectStore(e.storeName),t.oldVersion<=1&&r.createObjectStore(m)}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),S(e)}}))}function k(e){return x(e,!1)}function C(e){return x(e,!0)}function D(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 P(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){_(e);for(var t=p[e.name],r=t.forages,n=0;n(e.db=t,D(e)?C(e):t))).then((n=>{e.db=t.db=n;for(var o=0;o{throw I(e,t),t}))}(e).then((function(){N(e,t,r,n-1)})))).catch(r);r(o)}}var E={_driver:"asyncStorage",_initStorage:function(e){var t=this,r={db:null};if(e)for(var n in e)r[n]=e[n];var o=p[r.name];o||(o={forages:[],db:null,dbReady:null,deferredOperations:[]},p[r.name]=o),o.forages.push(t),t._initReady||(t._initReady=t.ready,t.ready=T);var i=[];function a(){return Promise.resolve()}for(var s=0;s{const r=p[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;_(e);const n=p[e.name],o=n.forages;t.close();for(let e=0;e{const o=c.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(I(e,t)||Promise.resolve()).catch((()=>{})),t}))})):t.then((t=>{_(e);const r=p[e.name],n=r.forages;t.close();for(var o=0;o{var n=c.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(I(e,t)||Promise.resolve()).catch((()=>{})),t}))}))}else r=Promise.reject("Invalid arguments");return d(r,t),r}};const O=new Map;function M(e,t){let r=e.name+"/";return e.storeName!==t.storeName&&(r+=e.storeName+"/"),r}var R={_driver:"tempStorageWrapper",_initStorage:async function(e){const t={};if(e)for(let r in e)t[r]=e[r];const r=t.keyPrefix=M(e,this._defaultConfig);this._dbInfo=t,O.has(r)||O.set(r,new Map)},getItem:function(e,t){e=f(e);const r=this.ready().then((()=>O.get(this._dbInfo.keyPrefix).get(e)));return d(r,t),r},setItem:function(e,t,r){e=f(e);const n=this.ready().then((()=>(void 0===t&&(t=null),O.get(this._dbInfo.keyPrefix).set(e,t),t)));return d(n,r),n},removeItem:function(e,t){e=f(e);const r=this.ready().then((()=>{O.get(this._dbInfo.keyPrefix).delete(e)}));return d(r,t),r},clear:function(e){const t=this.ready().then((()=>{const e=this._dbInfo.keyPrefix;O.has(e)&&O.delete(e)}));return d(t,e),t},length:function(e){const t=this.ready().then((()=>O.get(this._dbInfo.keyPrefix).size));return d(t,e),t},keys:function(e){const t=this.ready().then((()=>[...O.get(this._dbInfo.keyPrefix).keys()]));return d(t,e),t},dropInstance:function(e,t){if(t=h.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(M(e,this._defaultConfig)):t(`${e.name}/`)})).then((e=>{O.delete(e)})):Promise.reject("Invalid arguments"),d(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=J.concat("_initStorage");for(let t=0,n=i.length;t(null===t._ready&&(t._ready=t._initDriver()),t._ready)));return u(r,e,e),r}setDriver(e,t,r){const n=this;B(e)||(e=[e]);const o=this._getSupportedDrivers(e);function i(){n._config.driver=n.driver()}function a(e){return n._extend(e),i(),n._ready=n._initStorage(n._config),n._ready}const s=null!==this._driverSet?this._driverSet.catch((()=>Promise.resolve())):Promise.resolve();return this._driverSet=s.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})),u(this._driverSet,t,r),this._driverSet}supports(e){return!!U[e]}_extend(e){z(this,e)}_getSupportedDrivers(e){const t=[];for(let r=0,n=e.length;re&&"object"==typeof e&&"function"==typeof e.then,K=(async()=>{})().constructor;class q extends K{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,G(e)?t=e:"function"==typeof e&&(t=new K(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}constructor(e){let t,r;super(((e,n)=>{t=e,r=n})),this._s="pending",this.resolve=e=>{this.isPending&&(G(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",r(e))},this.task=e}}Date.prototype.kUtilFormat=function(e){const t={"M+":this.getUTCMonth()+1,"d+":this.getUTCDate(),"H+":this.getUTCHours(),"h+":this.getUTCHours()%12||12,"m+":this.getUTCMinutes(),"s+":this.getUTCSeconds(),"q+":Math.floor((this.getUTCMonth()+3)/3),"S+":this.getUTCMilliseconds()};/(y+)/.test(e)&&(e=e.replace(RegExp.$1,(this.getUTCFullYear()+"").substr(4-RegExp.$1.length)));for(let r in t)new RegExp("("+r+")").test(e)&&(e=e.replace(RegExp.$1,1==RegExp.$1.length?t[r]:("000"+t[r]).substr(("000"+t[r]).length-RegExp.$1.length)));return e};let X=e=>{let r,n,o,i,a,c,l,d,u,f,h,m,y,p,g,v,b,w,_,S,I=t.btoa,x=t.atob,k=e.bd,C=e.pd,D=e.vm,P=e.hs,T=e.dt,N=e.dm,E=["https://mlts.dynamsoft.com/","https://slts.dynamsoft.com/"],O=!1,M=Promise.resolve(),R=e.log&&((...t)=>{try{e.log.apply(null,t)}catch(e){setTimeout((()=>{throw e}),0)}})||(()=>{}),j=k&&R||(()=>{}),B=e=>e.join(""),A={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]},U=()=>t[B(A.c)][B(A.e)][B(A.f)]("raw",new Uint8Array(A.a.concat(A.b,A.d,A.k)),B(A.g),!0,[B(A.h),B(A.i)]),F=async e=>{if(t[B(A.c)]&&t[B(A.c)][B(A.e)]&&t[B(A.c)][B(A.e)][B(A.f)]){let r=x(e),n=new Uint8Array(r.length);for(let e=0;ex(x(e.replace(/\n/g,"+").replace(/\s/g,"=")).substring(1)),H=e=>I(String.fromCharCode(97+25*Math.random())+I(e)).replace(/\+/g,"\n").replace(/=/g," "),J=()=>{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)}))};const L="Failed to connect to the Dynamsoft License Server: ",$=" Check your Internet connection or contact Dynamsoft Support (support@dynamsoft.com) to acquire an offline license.",z={dlsErrorAndCacheExpire:L+"The cached license has expired. Please get connected to the network as soon as possible or contact the site administrator for more information.",publicTrialNetworkTimeout:L+"network timed out."+$,networkTimeout:L+"network timed out. Check your Internet connection or contact the site administrator for more information.",publicTrialFailConnect:L+"network connection error."+$,failConnect:L+"network connection error. Check your Internet connection or contact the site administrator for more information.",checkLocalTime:"Your system date and time appear to have been changed, causing the license to fail. Please correct the system date and time, then try again.",idbTimeout:"Failed to open indexedDB: Timeout.",dlsOfflineLicenseExpired:"The DLS2 Offline license has expired. Please contact the site administrator for more information."};let V,G,K,X,Y=async()=>{if(V)return V;V=new q,await(async()=>{m||(m=Z)})(),await Promise.race([(async()=>{let e=await m.createInstance({name:"dynamjssdkhello"});await e.setItem("dynamjssdkhello","available")})(),new Promise(((e,t)=>{setTimeout((()=>t(new Error(z.idbTimeout))),5e3)}))]),p=await m.createInstance({name:"dynamdlsinfo"}),g=I(I("v2")+String.fromCharCode(N.charCodeAt(N.length/2)+1)+I(N));try{let e=await p.getItem(g),t=null;self.indexedDB&&(t=await self.indexedDB.databases());let r=t&&t.some((e=>{if(e)return"dynamltsinfo"===e.name}));if(!e&&r){let t=await m.createInstance({name:"dynamltsinfo"});e=await t.getItem(g),e&&await p.setItem(g,e)}e&&([o,f]=JSON.parse(await W(e)))}catch(e){}try{null==o&&(o=J(),p.setItem(g,await H(JSON.stringify([o,null]))))}catch(e){}V.resolve()},Q=async()=>{v=I(String.fromCharCode(P.charCodeAt(0)+10)+I(C)+I(P)+D+I(""+T)),y=await m.createInstance({name:"dynamdlsuns"+I(I("v2"))+I(String.fromCharCode(P.charCodeAt(0)+10)+I(C)+I(P)+D+I(""+T))});try{n=await p.getItem(v)}catch(e){}B=e=>x(String.fromCharCode.apply(null,e).replace(/\n/g,"+").replace(/\s/g,"="))},ee=async e=>{if(K=Date.now(),G)return G;G=new q;try{let t={pd:C,vm:D,v:r,dt:T||"browser",ed:"javascript",cu:o,ad:N,os:i,fn:a};d&&(t.rmk=d),P&&(-1!=P.indexOf("-")?t.hs=P:t.og=P);let s={};if(f){let e=await p.getItem(g);e&&([o,f]=JSON.parse(await W(e))),s["lts-time"]=f}l&&(t.sp=l);let h=await Promise.race([(async()=>{let r,i=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ");f&&(p.setItem(g,await H(JSON.stringify([o,i]))),f=i);let a="auth/?ext="+encodeURIComponent(I(JSON.stringify(t)));u&&(a+="&"+encodeURIComponent(u));let l,d=!1,h=!1,m=async e=>{if(e&&!e.ok)try{let t=await e.text();if(t){let e=JSON.parse(t);e.errorCode&&(l=e,e.errorCode>100&&e.errorCode<200&&(n=null,d=!0,h=!0))}}catch(e){}};try{r=await Promise.race([fetch(E[0]+a,{headers:s,cache:e?"reload":"default",mode:"cors"}),new Promise(((e,t)=>setTimeout(t,1e4)))]),await m(r)}catch(e){}if(!(n||r&&r.ok||d))try{r=await Promise.race([fetch(E[1]+a,{headers:s,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))])}catch(e){}if(!(n||r&&r.ok||d))try{r=await Promise.race([fetch(E[0]+a,{headers:s,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await m(r)}catch(e){}l&&151==l.errorCode&&(p.removeItem(g),p.removeItem(v),o=J(),t.cu=o,f=void 0,a="auth/?ext="+encodeURIComponent(I(JSON.stringify(t))),r=await Promise.race([fetch(E[0]+a,{headers:s,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await m(r)),(()=>{if(!r||!r.ok){let e;h&&p.setItem(v,""),l?111==l.errorCode?e=l.message:(e=l.message.trim(),e.endsWith(".")||(e+="."),e=c?`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=c?z.publicTrialFailConnect:z.failConnect;let t=Error(e);throw l&&l.errorCode&&(t.ltsErrorCode=l.errorCode),t}})();let y=await r.text();try{f||(p.setItem(g,await H(JSON.stringify([o,i]))),f=i),p.setItem(v,y)}catch(e){}return y})(),new Promise(((e,t)=>{let r;r=c?z.publicTrialNetworkTimeout:z.networkTimeout,setTimeout((()=>t(new Error(r))),n?3e3:15e3)}))]);n=h}catch(e){k&&console.error(e),h=e}G.resolve(),G=null},te=async()=>{X||(X=(async()=>{if(j(o),!n){if(!O)throw R(h.message),h;return}let e={dm:N};k&&(e.bd=!0),e.brtk=!0,e.ls=E[0],P&&(-1!=P.indexOf("-")?e.hs=P:e.og=P),e.cu=o,a&&(e.fn=a),C&&(e.pd=C),r&&(e.v=r),T&&(e.dt=T),i&&(e.os=i),d&&(e.rmk=d),j(n);try{let t=JSON.parse(await F(n));t.pv&&(e.pv=JSON.stringify(t.pv)),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:h?e.msg=h.message||h:t.msg&&(e.msg=t.msg),e.ar=t.in,e.bafc=!!h}catch(e){}j(e);try{await b(e)}catch(e){j("error updl")}await re(),O||(O=!0),X=null})()),await X},re=async()=>{let e=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),t=await _();if(j(t),t&&t(M=M.then((async()=>{try{let r=await y.keys();if(t||(ne.isFulfilled?e&&(r=r.filter((t=>t{C=e.pd,r=e.v,D=r.split(".")[0],e.dt&&(T=e.dt),P=e.l||"",i="string"!=typeof e.os?JSON.stringify(e.os):e.os,a=e.fn,"string"==typeof a&&(a=a.substring(0,255)),e.ls&&e.ls.length&&(E=e.ls,1==E.length&&E.push(E[0])),c=!P||"200001"===P||P.startsWith("200001-"),l=e.sp,d=e.rmk,"string"==typeof d&&(d=d.substring(0,255)),e.cv&&(u=""+e.cv),b=e.updl,w=e.mnet,_=e.mxet,await Y(),await Q(),await ee(),await te(),(!h||h.ltsErrorCode>=102&&h.ltsErrorCode<=120)&&ie(null,!0)},i2:async({updl:e,mxet:t,strDLC2:r})=>{b=e,_=t,await Y(),B=e=>x(String.fromCharCode.apply(null,e).replace(/\n/g,"+").replace(/\s/g,"="));let i={pk:r,dm:N};k&&(i.bd=!0),i.cu=o;try{n=r.substring(4);let e=JSON.parse(await F(n));e.pv&&(i.pv=JSON.stringify(e.pv)),e.ba&&(i.ba=e.ba),i.ar=e.in}catch(e){}j(i);try{await b(i)}catch(e){j("error updl")}let a=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),s=await _();if(s&&s{let e=new Date;if(e.getTime()te()))}},s:async(e,r,n,o)=>{try{let e;e=r.startsWith("{")&&r.endsWith("}")?await(async e=>{if(t[B(A.c)]&&t[B(A.c)][B(A.e)]&&t[B(A.c)][B(A.e)][B(A.f)]){let r=new Uint8Array(e.length);for(let t=0;t{await ie()}),36e4)},p:ne,u:async()=>(await Y(),o),ar:()=>n,pt:()=>c,ae:()=>h}};const Y=self;let Q,ee,te,re;Y.licenseWorkerVersion="3.4.31";const ne=async e=>{await waitAsyncDependency("core"),await waitAsyncDependency("license"),Q=e.trial,ee=e.msg,ep(),re=JSON.parse(UTF8ToString(wasmImports.emscripten_bind_CoreWasm_static_init_1(es(JSON.stringify(e)))))},oe=()=>{let e=Module.getMinExpireTime;return e?e():null},ie=()=>{let e=Module.getMaxExpireTime;return e?e():null};Y.checkAndReauth=async()=>{},Object.assign(mapController,{license_dynamsoft:async(e,t)=>{try{let r,n=e.l,o=e.brtk,i=async()=>{te=te||X({dm:strDomain,log,bd:bDebug}),Y.scsd=te.s,e.pd="",e.v="0."+e.v,e.updl=ne,e.mnet=oe,e.mxet=ie,await te.i(e)},a=async()=>{if(n.startsWith("DLC2"))te=te||X({dm:strDomain,log,bd:bDebug}),await te.i2({updl:ne,mxet:ie,strDLC2:n});else{let e={pk:n,dm:strDomain};bDebug&&(e.bd=!0),await ne(e)}};o?await i():await a(),handleTaskRes(t,{trial:Q,ltsErrorCode:r,message:ee,initLicenseInfo:re,bSupportDce4Module:wasmImports.emscripten_bind_CoreWasm_static_GetIsSupportDceModule_0(),bSupportIRTModule:wasmImports.emscripten_bind_CoreWasm_static_GetIsSupportIRTModule_0()})}catch(e){handleTaskErr(t,e)}},license_getDeviceUUID:async(e,t)=>{try{te=te||X({dm:strDomain,log,bd:bDebug});let e=await te.u();handleTaskRes(t,{uuid:e})}catch(e){handleTaskErr(t,e)}},license_getAR:async(e,t)=>{try{if(te){let e={u:await te.u(),pt:te.pt()},r=te.ar();r&&(e.ar=r);let n=te.ae();n&&(e.lem=n.message,e.lec=n.ltsErrorCode),handleTaskRes(t,e)}else handleTaskRes(t,null)}catch(e){handleTaskErr(t,e)}}})}(); diff --git a/dist/dynamsoft-utility@1.4.32/dist/utility.d.ts b/dist/dynamsoft-utility@1.4.32/dist/utility.d.ts new file mode 100644 index 0000000..d23be74 --- /dev/null +++ b/dist/dynamsoft-utility@1.4.32/dist/utility.d.ts @@ -0,0 +1,118 @@ +import { DSImageData, Quadrilateral, LineSegment, Contour, Corner, Edge, EnumCapturedResultItemType, OriginalImageResultItem } from 'dynamsoft-core'; + +declare class ImageManager { + /** + * This method saves an image in either PNG or JPG format. The desired file format is inferred from the file extension provided in the 'name' parameter. Should the specified file format be omitted or unsupported, the data will default to being exported in PNG format. + * + * @param image The image to be saved, of type `DSImageData`. + * @param name The name of the file, as a string, under which the image will be saved. + * @param download An optional boolean flag that, when set to true, triggers the download of the file. + * + * @returns A promise that resolves with the saved File object. + */ + saveToFile(image: DSImageData, name: string, download?: boolean): Promise; + drawOnImage(image: Blob | string, drawingItem: Array | Quadrilateral | Array | LineSegment | Array | Contour | Array | Corner | Array | Edge, type: "quads" | "lines" | "contours" | "corners" | "edges", color?: number, thickness?: number, download?: boolean): Promise; +} + +declare class UtilityModule { + static getVersion(): string; +} + +type resultItemTypesString = "barcode" | "text_line" | "detected_quad" | "normalized_image"; +interface CapturedResultFilter { + onOriginalImageResultReceived?: (result: OriginalImageResultItem) => void; + onDecodedBarcodesReceived?: (result: any) => void; + onRecognizedTextLinesReceived?: (result: any) => void; + onDetectedQuadsReceived?: (result: any) => void; + onNormalizedImagesReceived?: (result: any) => void; + onParsedResultsReceived?: (result: any) => void; +} +declare class MultiFrameResultCrossFilter implements CapturedResultFilter { + #private; + verificationEnabled: { + [key: number]: boolean; + }; + duplicateFilterEnabled: { + [key: number]: boolean; + }; + duplicateForgetTime: { + [key: number]: number; + }; + private latestOverlappingEnabled; + private maxOverlappingFrames; + private overlapSet; + private stabilityCount; + private crossVerificationFrames; + _dynamsoft(): void; + /** + * Enables or disables the verification of one or multiple specific result item types. + * @param resultItemTypes Specifies one or multiple specific result item types, which can be defined using EnumCapturedResultItemType or a string. If using a string, only one type can be specified, and valid values include "barcode", "text_line", "detected_quad", and "normalized_image". + * @param enabled Boolean to toggle verification on or off. + */ + enableResultCrossVerification(resultItemTypes: EnumCapturedResultItemType | resultItemTypesString, enabled: boolean): void; + /** + * Checks if verification is active for a given result item type. + * @param resultItemType Specifies the result item type, either with EnumCapturedResultItemType or a string. When using a string, the valid values include "barcode", "text_line", "detected_quad", and "normalized_image". + * @returns Boolean indicating the status of verification for the specified type. + */ + isResultCrossVerificationEnabled(resultItemTypes: EnumCapturedResultItemType | resultItemTypesString): boolean; + /** + * Enables or disables the deduplication process for one or multiple specific result item types. + * @param resultItemTypes Specifies one or multiple specific result item types, which can be defined using EnumCapturedResultItemType or a string. If using a string, only one type can be specified, and valid values include "barcode", "text_line", "detected_quad", and "normalized_image". + * @param enabled Boolean to toggle deduplication on or off. + */ + enableResultDeduplication(resultItemTypes: EnumCapturedResultItemType | resultItemTypesString, enabled: boolean): void; + /** + * Checks if deduplication is active for a given result item type. + * @param resultItemType Specifies the result item type, either with EnumCapturedResultItemType or a string. When using a string, the valid values include "barcode", "text_line", "detected_quad", and "normalized_image". + * @returns Boolean indicating the deduplication status for the specified type. + */ + isResultDeduplicationEnabled(resultItemTypes: EnumCapturedResultItemType | resultItemTypesString): boolean; + /** + * Sets the interval during which duplicates are disregarded for specific result item types. + * @param resultItemTypes Specifies one or multiple specific result item types, which can be defined using EnumCapturedResultItemType or a string. If using a string, only one type can be specified, and valid values include "barcode", "text_line", "detected_quad", and "normalized_image". + * @param time Time in milliseconds during which duplicates are disregarded. + */ + setDuplicateForgetTime(resultItemTypes: EnumCapturedResultItemType | resultItemTypesString, time: number): void; + /** + * Retrieves the interval during which duplicates are disregarded for a given result item type. + * @param resultItemType Specifies the result item type, either with EnumCapturedResultItemType or a string. When using a string, the valid values include "barcode", "text_line", "detected_quad", and "normalized_image". + * @returns The set interval for the specified item type. + */ + getDuplicateForgetTime(resultItemTypes: EnumCapturedResultItemType | resultItemTypesString): number; + /** + * Set the max referencing frames count for the to-the-latest overlapping feature. + * + * @param resultItemTypes Specifies the result item type, either with EnumCapturedResultItemType or a string. When using a string, the valid values include "barcode", "text_line", "detected_quad", and "normalized_image". + * @param maxOverlappingFrames The max referencing frames count for the to-the-latest overlapping feature. + */ + setMaxOverlappingFrames(resultItemTypes: EnumCapturedResultItemType | resultItemTypesString, maxOverlappingFrames: number): void; + /** + * Get the max referencing frames count for the to-the-latest overlapping feature. + * @param resultItemTypes Specifies the result item type, either with EnumCapturedResultItemType or a string. When using a string, the valid values include "barcode", "text_line", "detected_quad", and "normalized_image". + * @return Returns the max referencing frames count for the to-the-latest overlapping feature. + */ + getMaxOverlappingFrames(resultItemType: EnumCapturedResultItemType): number; + /** + * Enables or disables the deduplication process for one or multiple specific result item types. + * @param resultItemTypes Specifies one or multiple specific result item types, which can be defined using EnumCapturedResultItemType or a string. If using a string, only one type can be specified, and valid values include "barcode", "text_line", "detected_quad", and "normalized_image". + * @param enabled Boolean to toggle deduplication on or off. + */ + enableLatestOverlapping(resultItemTypes: EnumCapturedResultItemType | resultItemTypesString, enabled: boolean): void; + /** + * Checks if deduplication is active for a given result item type. + * @param resultItemType Specifies the result item type, either with EnumCapturedResultItemType or a string. When using a string, the valid values include "barcode", "text_line", "detected_quad", and "normalized_image". + * + * @returns Boolean indicating the deduplication status for the specified type. + */ + isLatestOverlappingEnabled(resultItemType: EnumCapturedResultItemType | resultItemTypesString): boolean; + getFilteredResultItemTypes(): number; + onOriginalImageResultReceived(result: OriginalImageResultItem): void; + latestOverlappingFilter(result: any): void; + onDecodedBarcodesReceived(result: any): void; + onRecognizedTextLinesReceived(result: any): void; + onDetectedQuadsReceived(result: any): void; + onNormalizedImagesReceived(result: any): void; +} + +export { ImageManager, MultiFrameResultCrossFilter, UtilityModule }; diff --git a/dist/dynamsoft-utility@1.4.32/dist/utility.esm.js b/dist/dynamsoft-utility@1.4.32/dist/utility.esm.js new file mode 100644 index 0000000..f8ed85e --- /dev/null +++ b/dist/dynamsoft-utility@1.4.32/dist/utility.esm.js @@ -0,0 +1,11 @@ +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft Utility JS Edition + * @website https://www.dynamsoft.com + * @copyright Copyright 2024, Dynamsoft Corporation + * @author Dynamsoft + * @version 1.4.32 + * @fileoverview Dynamsoft JavaScript Library for Utility + * More info DU JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/utility/utility-module.html + */ +import{_getNorImageData as t,_saveToFile as e,requestResource as i,getNextTaskID as n,mapTaskCallBack as o,worker as s,CoreModule as a,workerAutoResources as r,compareVersion as l,innerVersions as c,EnumCapturedResultItemType as h}from"dynamsoft-core";const f=async t=>{let e;await new Promise(((i,n)=>{e=new Image,e.onload=()=>i(e),e.onerror=n,e.src=URL.createObjectURL(t)}));const i=document.createElement("canvas"),n=i.getContext("2d");i.width=e.width,i.height=e.height,n.drawImage(e,0,0);return{bytes:Uint8Array.from(n.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:10}};class p{async saveToFile(i,n,o){if(!i||!n)return null;if("string"!=typeof n)throw new TypeError("FileName must be of type string.");const s=t(i);return e(s,n,o)}async drawOnImage(t,e,a,r=4294901760,l=1,c){let h;if(t instanceof Blob)h=await f(t);else if("string"==typeof t){let e=await i(t,"blob");h=await f(e)}return await new Promise(((t,i)=>{let f=n();o[f]=async e=>{if(e.success)return c&&this.saveToFile(e.image,"test.png",c),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}},s.postMessage({type:"utility_drawOnImage",id:f,body:{dsImage:h,drawingItem:e instanceof Array?e:[e],color:r,thickness:l,type:a}})}))}}const u="undefined"==typeof self,g="function"==typeof importScripts,d=(()=>{if(!g){if(!u&&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"./"}})(),y=t=>{if(null==t&&(t="./"),u||g);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};a.engineResourcePaths.utility={version:"1.4.32",path:d,isInternal:!0},r.utility={js:!0,wasm:!0};const m="1.4.21";"string"!=typeof a.engineResourcePaths.std&&l(a.engineResourcePaths.std.version,m)<0&&(a.engineResourcePaths.std={version:m,path:y(d+`../../dynamsoft-capture-vision-std@${m}/dist/`),isInternal:!0});const v="2.4.31";(!a.engineResourcePaths.dip||"string"!=typeof a.engineResourcePaths.dip&&l(a.engineResourcePaths.dip.version,v)<0)&&(a.engineResourcePaths.dip={version:v,path:y(d+`../../dynamsoft-image-processing@${v}/dist/`),isInternal:!0});class x{static getVersion(){return`1.4.32(Worker: ${c.utility&&c.utility.worker||"Not Loaded"}, Wasm: ${c.utility&&c.utility.wasm||"Not Loaded"})`}}function I(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}var E,b,R,T,_;function C(t,e){let i=!0;for(let a=0;a1)return Math.sqrt((l-a)**2+(c-r)**2);{const t=o+f*(a-o),e=s+f*(r-s);return Math.sqrt((l-t)**2+(c-e)**2)}}function M(t){const e=[];for(let i=0;i{C(e,t)&&i.push(t)})),e.forEach((e=>{C(t,e)&&i.push(e)}));return w(function(t){if(t.length<=1)return t;t.sort(((t,e)=>t.x-e.x||t.y-e.y));const e=t.shift();return t.sort(((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x))),[e,...t]}(i))}function S(t,e,i,n){const o=e.x-t.x,s=e.y-t.y,a=n.x-i.x,r=n.y-i.y,l=(-s*(t.x-i.x)+o*(t.y-i.y))/(-a*s+o*r),c=(a*(t.y-i.y)-r*(t.x-i.x))/(-a*s+o*r);return l>=0&&l<=1&&c>=0&&c<=1?{x:t.x+c*o,y:t.y+c*s}:null}function w(t){let e=0;for(let i=0;i0}function L(t,e){for(let i=0;i<4;i++)if(!F(t.points[i],t.points[(i+1)%4],e))return!1;return!0}"function"==typeof SuppressedError&&SuppressedError;const N=3,k=1,P=1,W=2,G=3,j=5,V=15,U=5;function Q(t,e,i,n){const o=t.points,s=e.points;let a=8*i;a=Math.max(a,5);const r=M(o)[3],l=M(o)[1],c=M(s)[3],h=M(s)[1];let f,p=0;if(f=Math.max(Math.abs(B(r,e.points[0])),Math.abs(B(r,e.points[3]))),f>p&&(p=f),f=Math.max(Math.abs(B(l,e.points[1])),Math.abs(B(l,e.points[2]))),f>p&&(p=f),f=Math.max(Math.abs(B(c,t.points[0])),Math.abs(B(c,t.points[3]))),f>p&&(p=f),f=Math.max(Math.abs(B(h,t.points[1])),Math.abs(B(h,t.points[2]))),f>p&&(p=f),p>a)return!1;const u=A(M(o)[0]),g=A(M(o)[2]),d=A(M(s)[0]),y=A(M(s)[2]),m=O(u,y),v=O(d,g),x=m>v,I=Math.min(m,v),E=O(u,g),b=O(d,y);let R=12*i;R=Math.max(R,5),R=Math.min(R,E),R=Math.min(R,b);return!!(I{e.x+=t,e.y+=i})),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,n=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-n.area)>.4*i.area)return!1;let o=new Array(4).fill(0),s=new Array(4).fill(0),a=0,r=0;for(let t=0;t<4;++t)o[t]=Math.round(100*(n.points[t].x-i.points[t].x))/100,a+=o[t],s[t]=Math.round(100*(n.points[t].y-i.points[t].y))/100,r+=s[t];a/=4,r/=4;for(let t=0;t<4;++t){if(Math.abs(o[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1;if(Math.abs(s[t]-r)>this.strictLimit||Math.abs(r)>.8)return!1}return e.x=a,e.y=r,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(L(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(L(this.location,e))return!0}else{for(let e=0;e<4;e++)if(L(t,this.location.points[e]))return!0;if(L(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const n=[this.location.points[0],this.location.points[3]],o=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],s=0===t||3===t?n:o;if(Math.abs(B(s,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const n=t.location.points[i],o=this.location.points[i];if(!(Math.abs(o.x+e.x-n.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const n=Object.assign({},t.location);for(let t=0;t<4;t++)n.points[t].x-=e.x,n.points[t].y-=e.y;if(!this.isLocationOverlap(n,t.location.area))return!1;if(i){const t=.75;return D([...this.location.points],n.points)>this.locationArea*t}return!0}}const Z={BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096)},q={barcode:2,text_line:4,detected_quad:8,normalized_image:16},z=t=>Object.values(q).includes(t)||q.hasOwnProperty(t),$=(t,e)=>"string"==typeof t?e[q[t]]:e[t],H=(t,e,i)=>{"string"==typeof t?e[q[t]]=i:e[t]=i},J=(t,e,i)=>{const n=[8,16].includes(i);if(!n&&t.isResultCrossVerificationEnabled(i))for(let t=0;t{H(e,this.verificationEnabled,t)})),I(this,b,"f").forEach(((t,e)=>{H(e,this.duplicateFilterEnabled,t)})),I(this,R,"f").forEach(((t,e)=>{H(e,this.duplicateForgetTime,t)})),I(this,T,"f").forEach(((t,e)=>{H(e,this.latestOverlappingEnabled,t)})),I(this,_,"f").forEach(((t,e)=>{H(e,this.maxOverlappingFrames,t)}))}enableResultCrossVerification(t,e){z(t)&&I(this,E,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!z(t)&&$(t,this.verificationEnabled)}enableResultDeduplication(t,e){z(t)&&(e&&this.enableLatestOverlapping(t,!1),I(this,b,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!z(t)&&$(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){z(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),I(this,R,"f").set(t,e))}getDuplicateForgetTime(t){return z(t)?$(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){z(t)&&I(this,_,"f").set(t,e)}getMaxOverlappingFrames(t){return z(t)?$(t,this.maxOverlappingFrames):-1}enableLatestOverlapping(t,e){z(t)&&(e&&this.enableResultDeduplication(t,!1),I(this,T,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!z(t)&&$(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[h.CRIT_BARCODE,h.CRIT_TEXT_LINE,h.CRIT_DETECTED_QUAD,h.CRIT_NORMALIZED_IMAGE];for(let i=0;i{if(1!==t.type){const e=(BigInt(t.format)&BigInt(Z.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Z.BF_GS1_DATABAR))!=BigInt(0);return new X(l,e?1:2,e,t)}})).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(c).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t)).length;o>m&&(m=o,y=n,d.x=i.x,d.y=i.y)}}if(0===m){for(let e=0;e-1!=t)).length}let i=this.overlapSet.length<=N?m>=k:m>=W;if(!i&&s&&p>0){let t=0;for(let e=0;e=P:t>=G}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach(((t,e)=>{if(1!==t.type){const i=Object.assign({},t),n=(BigInt(t.format)&BigInt(Z.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Z.BF_GS1_DATABAR))!=BigInt(0),s=t.confidenceU||Math.abs(d.y)>U)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0)))}g.sort(((t,e)=>e-t)).forEach(((e,i)=>{t.items.splice(e,1)})),u.forEach((e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))}))}}onDecodedBarcodesReceived(t){this.latestOverlappingFilter(t),J(this,t.items,h.CRIT_BARCODE)}onRecognizedTextLinesReceived(t){J(this,t.items,h.CRIT_TEXT_LINE)}onDetectedQuadsReceived(t){J(this,t.items,h.CRIT_DETECTED_QUAD)}onNormalizedImagesReceived(t){J(this,t.items,h.CRIT_NORMALIZED_IMAGE)}}E=new WeakMap,b=new WeakMap,R=new WeakMap,T=new WeakMap,_=new WeakMap;export{p as ImageManager,K as MultiFrameResultCrossFilter,x as UtilityModule}; diff --git a/dist/dynamsoft-utility@1.4.32/dist/utility.js b/dist/dynamsoft-utility@1.4.32/dist/utility.js new file mode 100644 index 0000000..5b2de74 --- /dev/null +++ b/dist/dynamsoft-utility@1.4.32/dist/utility.js @@ -0,0 +1,11 @@ +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft Utility JS Edition + * @website https://www.dynamsoft.com + * @copyright Copyright 2024, Dynamsoft Corporation + * @author Dynamsoft + * @version 1.4.32 + * @fileoverview Dynamsoft JavaScript Library for Utility + * More info DU JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/utility/utility-module.html + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("dynamsoft-core")):"function"==typeof define&&define.amd?define(["exports","dynamsoft-core"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).Dynamsoft=t.Dynamsoft||{},t.Dynamsoft.Utility={}),t.Dynamsoft.Core)}(this,(function(t,e){"use strict";const i=async t=>{let e;await new Promise(((i,n)=>{e=new Image,e.onload=()=>i(e),e.onerror=n,e.src=URL.createObjectURL(t)}));const i=document.createElement("canvas"),n=i.getContext("2d");i.width=e.width,i.height=e.height,n.drawImage(e,0,0);return{bytes:Uint8Array.from(n.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:10}};const n="undefined"==typeof self,s="function"==typeof importScripts,o=(()=>{if(!s){if(!n&&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"./"}})(),a=t=>{if(null==t&&(t="./"),n||s);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};e.CoreModule.engineResourcePaths.utility={version:"1.4.32",path:o,isInternal:!0},e.workerAutoResources.utility={js:!0,wasm:!0};const r="1.4.21";"string"!=typeof e.CoreModule.engineResourcePaths.std&&e.compareVersion(e.CoreModule.engineResourcePaths.std.version,r)<0&&(e.CoreModule.engineResourcePaths.std={version:r,path:a(o+`../../dynamsoft-capture-vision-std@${r}/dist/`),isInternal:!0});const l="2.4.31";(!e.CoreModule.engineResourcePaths.dip||"string"!=typeof e.CoreModule.engineResourcePaths.dip&&e.compareVersion(e.CoreModule.engineResourcePaths.dip.version,l)<0)&&(e.CoreModule.engineResourcePaths.dip={version:l,path:a(o+`../../dynamsoft-image-processing@${l}/dist/`),isInternal:!0});function c(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}var u,p,h,f,m;function d(t,e){let i=!0;for(let a=0;a1)return Math.sqrt((l-a)**2+(c-r)**2);{const t=s+p*(a-s),e=o+p*(r-o);return Math.sqrt((l-t)**2+(c-e)**2)}}function I(t){const e=[];for(let i=0;i{d(e,t)&&i.push(t)})),e.forEach((e=>{d(t,e)&&i.push(e)}));return R(function(t){if(t.length<=1)return t;t.sort(((t,e)=>t.x-e.x||t.y-e.y));const e=t.shift();return t.sort(((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x))),[e,...t]}(i))}function T(t,e,i,n){const s=e.x-t.x,o=e.y-t.y,a=n.x-i.x,r=n.y-i.y,l=(-o*(t.x-i.x)+s*(t.y-i.y))/(-a*o+s*r),c=(a*(t.y-i.y)-r*(t.x-i.x))/(-a*o+s*r);return l>=0&&l<=1&&c>=0&&c<=1?{x:t.x+c*s,y:t.y+c*o}:null}function R(t){let e=0;for(let i=0;i0}function v(t,e){for(let i=0;i<4;i++)if(!x(t.points[i],t.points[(i+1)%4],e))return!1;return!0}"function"==typeof SuppressedError&&SuppressedError;const b=3,M=1,_=1,O=2,B=3,D=5,A=15,w=5;function S(t,e,i,n){const s=t.points,o=e.points;let a=8*i;a=Math.max(a,5);const r=I(s)[3],l=I(s)[1],c=I(o)[3],u=I(o)[1];let p,h=0;if(p=Math.max(Math.abs(g(r,e.points[0])),Math.abs(g(r,e.points[3]))),p>h&&(h=p),p=Math.max(Math.abs(g(l,e.points[1])),Math.abs(g(l,e.points[2]))),p>h&&(h=p),p=Math.max(Math.abs(g(c,t.points[0])),Math.abs(g(c,t.points[3]))),p>h&&(h=p),p=Math.max(Math.abs(g(u,t.points[1])),Math.abs(g(u,t.points[2]))),p>h&&(h=p),h>a)return!1;const f=E(I(s)[0]),m=E(I(s)[2]),C=E(I(o)[0]),T=E(I(o)[2]),x=y(f,T),v=y(C,m),b=x>v,M=Math.min(x,v),_=y(f,m),O=y(C,T);let B=12*i;B=Math.max(B,5),B=Math.min(B,_),B=Math.min(B,O);return!!(M{e.x+=t,e.y+=i})),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,n=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-n.area)>.4*i.area)return!1;let s=new Array(4).fill(0),o=new Array(4).fill(0),a=0,r=0;for(let t=0;t<4;++t)s[t]=Math.round(100*(n.points[t].x-i.points[t].x))/100,a+=s[t],o[t]=Math.round(100*(n.points[t].y-i.points[t].y))/100,r+=o[t];a/=4,r/=4;for(let t=0;t<4;++t){if(Math.abs(s[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1;if(Math.abs(o[t]-r)>this.strictLimit||Math.abs(r)>.8)return!1}return e.x=a,e.y=r,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(v(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(v(this.location,e))return!0}else{for(let e=0;e<4;e++)if(v(t,this.location.points[e]))return!0;if(v(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const n=[this.location.points[0],this.location.points[3]],s=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],o=0===t||3===t?n:s;if(Math.abs(g(o,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const n=t.location.points[i],s=this.location.points[i];if(!(Math.abs(s.x+e.x-n.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const n=Object.assign({},t.location);for(let t=0;t<4;t++)n.points[t].x-=e.x,n.points[t].y-=e.y;if(!this.isLocationOverlap(n,t.location.area))return!1;if(i){const t=.75;return C([...this.location.points],n.points)>this.locationArea*t}return!0}}const L={BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096)},k={barcode:2,text_line:4,detected_quad:8,normalized_image:16},N=t=>Object.values(k).includes(t)||k.hasOwnProperty(t),V=(t,e)=>"string"==typeof t?e[k[t]]:e[t],P=(t,e,i)=>{"string"==typeof t?e[k[t]]=i:e[t]=i},W=(t,e,i)=>{const n=[8,16].includes(i);if(!n&&t.isResultCrossVerificationEnabled(i))for(let t=0;t{let c=e.getNextTaskID();e.mapTaskCallBack[c]=async e=>{if(e.success)return r&&this.saveToFile(e.image,"test.png",r),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}},e.worker.postMessage({type:"utility_drawOnImage",id:c,body:{dsImage:l,drawingItem:n instanceof Array?n:[n],color:o,thickness:a,type:s}})}))}},t.MultiFrameResultCrossFilter=class{constructor(){this.verificationEnabled={[e.EnumCapturedResultItemType.CRIT_BARCODE]:!1,[e.EnumCapturedResultItemType.CRIT_TEXT_LINE]:!0,[e.EnumCapturedResultItemType.CRIT_DETECTED_QUAD]:!0,[e.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE]:!1},this.duplicateFilterEnabled={[e.EnumCapturedResultItemType.CRIT_BARCODE]:!1,[e.EnumCapturedResultItemType.CRIT_TEXT_LINE]:!1,[e.EnumCapturedResultItemType.CRIT_DETECTED_QUAD]:!1,[e.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE]:!1},this.duplicateForgetTime={[e.EnumCapturedResultItemType.CRIT_BARCODE]:3e3,[e.EnumCapturedResultItemType.CRIT_TEXT_LINE]:3e3,[e.EnumCapturedResultItemType.CRIT_DETECTED_QUAD]:3e3,[e.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE]:3e3},this.latestOverlappingEnabled={[e.EnumCapturedResultItemType.CRIT_BARCODE]:!1,[e.EnumCapturedResultItemType.CRIT_TEXT_LINE]:!1,[e.EnumCapturedResultItemType.CRIT_DETECTED_QUAD]:!1,[e.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE]:!1},this.maxOverlappingFrames={[e.EnumCapturedResultItemType.CRIT_BARCODE]:5,[e.EnumCapturedResultItemType.CRIT_TEXT_LINE]:5,[e.EnumCapturedResultItemType.CRIT_DETECTED_QUAD]:5,[e.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE]:5},this.overlapSet=[],this.stabilityCount=0,this.crossVerificationFrames=5,u.set(this,new Map),p.set(this,new Map),h.set(this,new Map),f.set(this,new Map),m.set(this,new Map)}_dynamsoft(){c(this,u,"f").forEach(((t,e)=>{P(e,this.verificationEnabled,t)})),c(this,p,"f").forEach(((t,e)=>{P(e,this.duplicateFilterEnabled,t)})),c(this,h,"f").forEach(((t,e)=>{P(e,this.duplicateForgetTime,t)})),c(this,f,"f").forEach(((t,e)=>{P(e,this.latestOverlappingEnabled,t)})),c(this,m,"f").forEach(((t,e)=>{P(e,this.maxOverlappingFrames,t)}))}enableResultCrossVerification(t,e){N(t)&&c(this,u,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!N(t)&&V(t,this.verificationEnabled)}enableResultDeduplication(t,e){N(t)&&(e&&this.enableLatestOverlapping(t,!1),c(this,p,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!N(t)&&V(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){N(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),c(this,h,"f").set(t,e))}getDuplicateForgetTime(t){return N(t)?V(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){N(t)&&c(this,m,"f").set(t,e)}getMaxOverlappingFrames(t){return N(t)?V(t,this.maxOverlappingFrames):-1}enableLatestOverlapping(t,e){N(t)&&(e&&this.enableResultDeduplication(t,!1),c(this,f,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!N(t)&&V(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const i=[e.EnumCapturedResultItemType.CRIT_BARCODE,e.EnumCapturedResultItemType.CRIT_TEXT_LINE,e.EnumCapturedResultItemType.CRIT_DETECTED_QUAD,e.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE];for(let e=0;e{if(1!==t.type){const e=(BigInt(t.format)&BigInt(L.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(L.BF_GS1_DATABAR))!=BigInt(0);return new F(c,e?1:2,e,t)}})).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(u).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t)).length;s>g&&(g=s,y=n,d.x=i.x,d.y=i.y)}}if(0===g){for(let e=0;e-1!=t)).length}let i=this.overlapSet.length<=b?g>=M:g>=O;if(!i&&a&&h>0){let t=0;for(let e=0;e=_:t>=B}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach(((t,e)=>{if(1!==t.type){const i=Object.assign({},t),n=(BigInt(t.format)&BigInt(L.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(L.BF_GS1_DATABAR))!=BigInt(0),s=t.confidencew||Math.abs(d.y)>w)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0)))}m.sort(((t,e)=>e-t)).forEach(((e,i)=>{t.items.splice(e,1)})),f.forEach((e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))}))}}onDecodedBarcodesReceived(t){this.latestOverlappingFilter(t),W(this,t.items,e.EnumCapturedResultItemType.CRIT_BARCODE)}onRecognizedTextLinesReceived(t){W(this,t.items,e.EnumCapturedResultItemType.CRIT_TEXT_LINE)}onDetectedQuadsReceived(t){W(this,t.items,e.EnumCapturedResultItemType.CRIT_DETECTED_QUAD)}onNormalizedImagesReceived(t){W(this,t.items,e.EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE)}},t.UtilityModule=class{static getVersion(){return`1.4.32(Worker: ${e.innerVersions.utility&&e.innerVersions.utility.worker||"Not Loaded"}, Wasm: ${e.innerVersions.utility&&e.innerVersions.utility.wasm||"Not Loaded"})`}}})); diff --git a/dist/dynamsoft-utility@1.4.32/dist/utility.worker.js b/dist/dynamsoft-utility@1.4.32/dist/utility.worker.js new file mode 100644 index 0000000..62c5058 --- /dev/null +++ b/dist/dynamsoft-utility@1.4.32/dist/utility.worker.js @@ -0,0 +1,11 @@ +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft Utility JS Edition + * @website https://www.dynamsoft.com + * @copyright Copyright 2024, Dynamsoft Corporation + * @author Dynamsoft + * @version 1.4.32 + * @fileoverview Dynamsoft JavaScript Library for Utility + * More info DU JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/utility/utility-module.html + */ +!function(){"use strict";self.utilityWorkerVersion="1.4.32",Object.assign(mapController,{utility_drawOnImage:async(e,t)=>{let s;try{let a=wasmImports.emscripten_bind_Create_CImageData(e.dsImage.bytes.length,setBufferIntoWasm(e.dsImage.bytes,0),e.dsImage.width,e.dsImage.height,e.dsImage.stride,e.dsImage.format,0);const r=e.type.charAt(0).toUpperCase()+e.type.slice(1);ep(),s=JSON.parse(UTF8ToString(wasmImports[`emscripten_bind_UtilityWasm_DrawOnImage${r}_5`](a,es(JSON.stringify(e.drawingItem)),e.drawingItem.length,e.color,e.thickness)));let n=s.bytes;n&&(n=new Uint8Array(new Uint8Array(HEAP8.buffer,n.ptr,n.length)),s.bytes=n),wasmImports.emscripten_bind_Destory_CImageData(a),handleTaskRes(t,{success:!0,image:s})}catch(e){return console.log(e),void handleTaskErr(t,e)}}})}(); diff --git a/package.json b/package.json index 5de9810..6ab8f7b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dynamsoft-barcode-reader-bundle", - "version": "10.4.3100", + "version": "10.5.3000", "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.", "main": "dist/dbr.bundle.js", "module": "dist/dbr.no-content-bundle.esm.js", @@ -22,12 +22,14 @@ "LEGAL.txt", "LICENSE", "samples.url", - "API Reference.url" + "API_Reference_BarcodeScanner.url", + "API_Reference_Foundational.url" ], "scripts": { "build": "rollup -c --environment BUILD:production", + "build-dev": "rollup -c --environment BUILD:development", "test": "echo \"Error: no test specified\" && exit 1", - "update:readme": "updateReadme --package=dynamsoft-barcode-reader-bundle --version=latest --branch=preview --html", + "update:readme": "updateReadme --package=dynamsoft-barcode-reader-bundle --version=latest --branch=preview --html --rtu", "updateLink:npm": "updateLink --source=npm", "updateLink:zip": "updateLink --source=zip", "updateLink:github": "updateLink --source=github", @@ -66,12 +68,13 @@ "tag": "latest" }, "devDependencies": { - "@dynamsoft/rd2-scripts": "^0.1.36", + "@dynamsoft/rd2-scripts": "^0.1.38", "@rollup/plugin-node-resolve": "^15.2.3", "@rollup/plugin-replace": "^5.0.5", "@rollup/plugin-terser": "^0.4.4", "@rollup/plugin-typescript": "^11.1.6", - "@scannerproxy/curscript-path": "^2.0.1", + "@scannerproxy/curscript-path": "^2.0.6", + "mutable-promise": "^1.1.15", "rollup": "^3.29.3", "rollup-plugin-dts": "^6.1.0", "tslib": "^2.6.2", diff --git a/samples.url b/samples.url index 7ef97fa..ef659ac 100644 --- a/samples.url +++ b/samples.url @@ -1,2 +1,2 @@ [InternetShortcut] -URL=https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.4.31 \ No newline at end of file +URL=https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.5.30 \ No newline at end of file