summaryrefslogtreecommitdiffstats
path: root/toolkit/components/ml/vendor/ort-dev.js
diff options
context:
space:
mode:
Diffstat (limited to 'toolkit/components/ml/vendor/ort-dev.js')
-rw-r--r--toolkit/components/ml/vendor/ort-dev.js29506
1 files changed, 29506 insertions, 0 deletions
diff --git a/toolkit/components/ml/vendor/ort-dev.js b/toolkit/components/ml/vendor/ort-dev.js
new file mode 100644
index 0000000000..8c53b1521d
--- /dev/null
+++ b/toolkit/components/ml/vendor/ort-dev.js
@@ -0,0 +1,29506 @@
+/*!
+* ONNX Runtime Web v1.14.0
+* Copyright (c) Microsoft Corporation. All rights reserved.
+* Licensed under the MIT License.
+*/
+(function webpackUniversalModuleDefinition(root, factory) {
+ if(typeof exports === 'object' && typeof module === 'object')
+ module.exports = factory();
+ else if(typeof define === 'function' && define.amd)
+ define([], factory);
+ else if(typeof exports === 'object')
+ exports["ort"] = factory();
+ else
+ root["ort"] = factory();
+})(self, () => {
+return /******/ (() => { // webpackBootstrap
+/******/ var __webpack_modules__ = ({
+
+/***/ "../common/dist/lib/backend-impl.js":
+/*!******************************************!*\
+ !*** ../common/dist/lib/backend-impl.js ***!
+ \******************************************/
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "registerBackend": () => (/* binding */ registerBackend),
+/* harmony export */ "resolveBackend": () => (/* binding */ resolveBackend)
+/* harmony export */ });
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+const backends = {};
+const backendsSortedByPriority = [];
+/**
+ * Register a backend.
+ *
+ * @param name - the name as a key to lookup as an execution provider.
+ * @param backend - the backend object.
+ * @param priority - an integer indicating the priority of the backend. Higher number means higher priority. if priority
+ * < 0, it will be considered as a 'beta' version and will not be used as a fallback backend by default.
+ *
+ * @internal
+ */
+const registerBackend = (name, backend, priority) => {
+ if (backend && typeof backend.init === 'function' && typeof backend.createSessionHandler === 'function') {
+ const currentBackend = backends[name];
+ if (currentBackend === undefined) {
+ backends[name] = { backend, priority };
+ }
+ else if (currentBackend.priority > priority) {
+ // same name is already registered with a higher priority. skip registeration.
+ return;
+ }
+ else if (currentBackend.priority === priority) {
+ if (currentBackend.backend !== backend) {
+ throw new Error(`cannot register backend "${name}" using priority ${priority}`);
+ }
+ }
+ if (priority >= 0) {
+ const i = backendsSortedByPriority.indexOf(name);
+ if (i !== -1) {
+ backendsSortedByPriority.splice(i, 1);
+ }
+ for (let i = 0; i < backendsSortedByPriority.length; i++) {
+ if (backends[backendsSortedByPriority[i]].priority <= priority) {
+ backendsSortedByPriority.splice(i, 0, name);
+ return;
+ }
+ }
+ backendsSortedByPriority.push(name);
+ }
+ return;
+ }
+ throw new TypeError('not a valid backend');
+};
+/**
+ * Resolve backend by specified hints.
+ *
+ * @param backendHints - a list of execution provider names to lookup. If omitted use registered backends as list.
+ * @returns a promise that resolves to the backend.
+ *
+ * @internal
+ */
+const resolveBackend = async (backendHints) => {
+ const backendNames = backendHints.length === 0 ? backendsSortedByPriority : backendHints;
+ const errors = [];
+ for (const backendName of backendNames) {
+ const backendInfo = backends[backendName];
+ if (backendInfo) {
+ if (backendInfo.initialized) {
+ return backendInfo.backend;
+ }
+ else if (backendInfo.aborted) {
+ continue; // current backend is unavailable; try next
+ }
+ const isInitializing = !!backendInfo.initPromise;
+ try {
+ if (!isInitializing) {
+ backendInfo.initPromise = backendInfo.backend.init();
+ }
+ await backendInfo.initPromise;
+ backendInfo.initialized = true;
+ return backendInfo.backend;
+ }
+ catch (e) {
+ if (!isInitializing) {
+ errors.push({ name: backendName, err: e });
+ }
+ backendInfo.aborted = true;
+ }
+ finally {
+ delete backendInfo.initPromise;
+ }
+ }
+ }
+ throw new Error(`no available backend found. ERR: ${errors.map(e => `[${e.name}] ${e.err}`).join(', ')}`);
+};
+//# sourceMappingURL=backend-impl.js.map
+
+/***/ }),
+
+/***/ "../common/dist/lib/backend.js":
+/*!*************************************!*\
+ !*** ../common/dist/lib/backend.js ***!
+ \*************************************/
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "registerBackend": () => (/* reexport safe */ _backend_impl__WEBPACK_IMPORTED_MODULE_0__.registerBackend)
+/* harmony export */ });
+/* harmony import */ var _backend_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backend-impl */ "../common/dist/lib/backend-impl.js");
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//# sourceMappingURL=backend.js.map
+
+/***/ }),
+
+/***/ "../common/dist/lib/env-impl.js":
+/*!**************************************!*\
+ !*** ../common/dist/lib/env-impl.js ***!
+ \**************************************/
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "EnvImpl": () => (/* binding */ EnvImpl)
+/* harmony export */ });
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+class EnvImpl {
+ constructor() {
+ this.wasm = {};
+ this.webgl = {};
+ this.logLevelInternal = 'warning';
+ }
+ // TODO standadize the getter and setter convention in env for other fields.
+ set logLevel(value) {
+ if (value === undefined) {
+ return;
+ }
+ if (typeof value !== 'string' || ['verbose', 'info', 'warning', 'error', 'fatal'].indexOf(value) === -1) {
+ throw new Error(`Unsupported logging level: ${value}`);
+ }
+ this.logLevelInternal = value;
+ }
+ get logLevel() {
+ return this.logLevelInternal;
+ }
+}
+//# sourceMappingURL=env-impl.js.map
+
+/***/ }),
+
+/***/ "../common/dist/lib/env.js":
+/*!*********************************!*\
+ !*** ../common/dist/lib/env.js ***!
+ \*********************************/
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "env": () => (/* binding */ env)
+/* harmony export */ });
+/* harmony import */ var _env_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./env-impl */ "../common/dist/lib/env-impl.js");
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+/**
+ * Represent a set of flags as a global singleton.
+ */
+const env = new _env_impl__WEBPACK_IMPORTED_MODULE_0__.EnvImpl();
+//# sourceMappingURL=env.js.map
+
+/***/ }),
+
+/***/ "../common/dist/lib/index.js":
+/*!***********************************!*\
+ !*** ../common/dist/lib/index.js ***!
+ \***********************************/
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "InferenceSession": () => (/* reexport safe */ _inference_session__WEBPACK_IMPORTED_MODULE_2__.InferenceSession),
+/* harmony export */ "Tensor": () => (/* reexport safe */ _tensor__WEBPACK_IMPORTED_MODULE_3__.Tensor),
+/* harmony export */ "env": () => (/* reexport safe */ _env__WEBPACK_IMPORTED_MODULE_1__.env),
+/* harmony export */ "registerBackend": () => (/* reexport safe */ _backend__WEBPACK_IMPORTED_MODULE_0__.registerBackend)
+/* harmony export */ });
+/* harmony import */ var _backend__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backend */ "../common/dist/lib/backend.js");
+/* harmony import */ var _env__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./env */ "../common/dist/lib/env.js");
+/* harmony import */ var _inference_session__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./inference-session */ "../common/dist/lib/inference-session.js");
+/* harmony import */ var _tensor__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./tensor */ "../common/dist/lib/tensor.js");
+/* harmony import */ var _onnx_value__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./onnx-value */ "../common/dist/lib/onnx-value.js");
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+/**
+ * # ONNX Runtime JavaScript API
+ *
+ * ONNX Runtime JavaScript API is a unified API for all JavaScript usages, including the following NPM packages:
+ *
+ * - [onnxruntime-node](https://www.npmjs.com/package/onnxruntime-node)
+ * - [onnxruntime-web](https://www.npmjs.com/package/onnxruntime-web)
+ * - [onnxruntime-react-native](https://www.npmjs.com/package/onnxruntime-react-native)
+ *
+ * See also:
+ * - [Get Started](https://onnxruntime.ai/docs/get-started/with-javascript.html)
+ * - [Inference examples](https://github.com/microsoft/onnxruntime-inference-examples/tree/main/js)
+ *
+ * @packageDocumentation
+ */
+
+
+
+
+
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ "../common/dist/lib/inference-session-impl.js":
+/*!****************************************************!*\
+ !*** ../common/dist/lib/inference-session-impl.js ***!
+ \****************************************************/
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "InferenceSession": () => (/* binding */ InferenceSession)
+/* harmony export */ });
+/* harmony import */ var _backend_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backend-impl */ "../common/dist/lib/backend-impl.js");
+/* harmony import */ var _tensor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./tensor */ "../common/dist/lib/tensor.js");
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+
+class InferenceSession {
+ constructor(handler) {
+ this.handler = handler;
+ }
+ async run(feeds, arg1, arg2) {
+ const fetches = {};
+ let options = {};
+ // check inputs
+ if (typeof feeds !== 'object' || feeds === null || feeds instanceof _tensor__WEBPACK_IMPORTED_MODULE_1__.Tensor || Array.isArray(feeds)) {
+ throw new TypeError('\'feeds\' must be an object that use input names as keys and OnnxValue as corresponding values.');
+ }
+ let isFetchesEmpty = true;
+ // determine which override is being used
+ if (typeof arg1 === 'object') {
+ if (arg1 === null) {
+ throw new TypeError('Unexpected argument[1]: cannot be null.');
+ }
+ if (arg1 instanceof _tensor__WEBPACK_IMPORTED_MODULE_1__.Tensor) {
+ throw new TypeError('\'fetches\' cannot be a Tensor');
+ }
+ if (Array.isArray(arg1)) {
+ if (arg1.length === 0) {
+ throw new TypeError('\'fetches\' cannot be an empty array.');
+ }
+ isFetchesEmpty = false;
+ // output names
+ for (const name of arg1) {
+ if (typeof name !== 'string') {
+ throw new TypeError('\'fetches\' must be a string array or an object.');
+ }
+ if (this.outputNames.indexOf(name) === -1) {
+ throw new RangeError(`'fetches' contains invalid output name: ${name}.`);
+ }
+ fetches[name] = null;
+ }
+ if (typeof arg2 === 'object' && arg2 !== null) {
+ options = arg2;
+ }
+ else if (typeof arg2 !== 'undefined') {
+ throw new TypeError('\'options\' must be an object.');
+ }
+ }
+ else {
+ // decide whether arg1 is fetches or options
+ // if any output name is present and its value is valid OnnxValue, we consider it fetches
+ let isFetches = false;
+ const arg1Keys = Object.getOwnPropertyNames(arg1);
+ for (const name of this.outputNames) {
+ if (arg1Keys.indexOf(name) !== -1) {
+ const v = arg1[name];
+ if (v === null || v instanceof _tensor__WEBPACK_IMPORTED_MODULE_1__.Tensor) {
+ isFetches = true;
+ isFetchesEmpty = false;
+ fetches[name] = v;
+ }
+ }
+ }
+ if (isFetches) {
+ if (typeof arg2 === 'object' && arg2 !== null) {
+ options = arg2;
+ }
+ else if (typeof arg2 !== 'undefined') {
+ throw new TypeError('\'options\' must be an object.');
+ }
+ }
+ else {
+ options = arg1;
+ }
+ }
+ }
+ else if (typeof arg1 !== 'undefined') {
+ throw new TypeError('Unexpected argument[1]: must be \'fetches\' or \'options\'.');
+ }
+ // check if all inputs are in feed
+ for (const name of this.inputNames) {
+ if (typeof feeds[name] === 'undefined') {
+ throw new Error(`input '${name}' is missing in 'feeds'.`);
+ }
+ }
+ // if no fetches is specified, we use the full output names list
+ if (isFetchesEmpty) {
+ for (const name of this.outputNames) {
+ fetches[name] = null;
+ }
+ }
+ // feeds, fetches and options are prepared
+ const results = await this.handler.run(feeds, fetches, options);
+ const returnValue = {};
+ for (const key in results) {
+ if (Object.hasOwnProperty.call(results, key)) {
+ returnValue[key] = new _tensor__WEBPACK_IMPORTED_MODULE_1__.Tensor(results[key].type, results[key].data, results[key].dims);
+ }
+ }
+ return returnValue;
+ }
+ static async create(arg0, arg1, arg2, arg3) {
+ // either load from a file or buffer
+ let filePathOrUint8Array;
+ let options = {};
+ if (typeof arg0 === 'string') {
+ filePathOrUint8Array = arg0;
+ if (typeof arg1 === 'object' && arg1 !== null) {
+ options = arg1;
+ }
+ else if (typeof arg1 !== 'undefined') {
+ throw new TypeError('\'options\' must be an object.');
+ }
+ }
+ else if (arg0 instanceof Uint8Array) {
+ filePathOrUint8Array = arg0;
+ if (typeof arg1 === 'object' && arg1 !== null) {
+ options = arg1;
+ }
+ else if (typeof arg1 !== 'undefined') {
+ throw new TypeError('\'options\' must be an object.');
+ }
+ }
+ else if (arg0 instanceof ArrayBuffer ||
+ (typeof SharedArrayBuffer !== 'undefined' && arg0 instanceof SharedArrayBuffer)) {
+ const buffer = arg0;
+ let byteOffset = 0;
+ let byteLength = arg0.byteLength;
+ if (typeof arg1 === 'object' && arg1 !== null) {
+ options = arg1;
+ }
+ else if (typeof arg1 === 'number') {
+ byteOffset = arg1;
+ if (!Number.isSafeInteger(byteOffset)) {
+ throw new RangeError('\'byteOffset\' must be an integer.');
+ }
+ if (byteOffset < 0 || byteOffset >= buffer.byteLength) {
+ throw new RangeError(`'byteOffset' is out of range [0, ${buffer.byteLength}).`);
+ }
+ byteLength = arg0.byteLength - byteOffset;
+ if (typeof arg2 === 'number') {
+ byteLength = arg2;
+ if (!Number.isSafeInteger(byteLength)) {
+ throw new RangeError('\'byteLength\' must be an integer.');
+ }
+ if (byteLength <= 0 || byteOffset + byteLength > buffer.byteLength) {
+ throw new RangeError(`'byteLength' is out of range (0, ${buffer.byteLength - byteOffset}].`);
+ }
+ if (typeof arg3 === 'object' && arg3 !== null) {
+ options = arg3;
+ }
+ else if (typeof arg3 !== 'undefined') {
+ throw new TypeError('\'options\' must be an object.');
+ }
+ }
+ else if (typeof arg2 !== 'undefined') {
+ throw new TypeError('\'byteLength\' must be a number.');
+ }
+ }
+ else if (typeof arg1 !== 'undefined') {
+ throw new TypeError('\'options\' must be an object.');
+ }
+ filePathOrUint8Array = new Uint8Array(buffer, byteOffset, byteLength);
+ }
+ else {
+ throw new TypeError('Unexpected argument[0]: must be \'path\' or \'buffer\'.');
+ }
+ // get backend hints
+ const eps = options.executionProviders || [];
+ const backendHints = eps.map(i => typeof i === 'string' ? i : i.name);
+ const backend = await (0,_backend_impl__WEBPACK_IMPORTED_MODULE_0__.resolveBackend)(backendHints);
+ const handler = await backend.createSessionHandler(filePathOrUint8Array, options);
+ return new InferenceSession(handler);
+ }
+ startProfiling() {
+ this.handler.startProfiling();
+ }
+ endProfiling() {
+ this.handler.endProfiling();
+ }
+ get inputNames() {
+ return this.handler.inputNames;
+ }
+ get outputNames() {
+ return this.handler.outputNames;
+ }
+}
+//# sourceMappingURL=inference-session-impl.js.map
+
+/***/ }),
+
+/***/ "../common/dist/lib/inference-session.js":
+/*!***********************************************!*\
+ !*** ../common/dist/lib/inference-session.js ***!
+ \***********************************************/
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "InferenceSession": () => (/* binding */ InferenceSession)
+/* harmony export */ });
+/* harmony import */ var _inference_session_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./inference-session-impl */ "../common/dist/lib/inference-session-impl.js");
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const InferenceSession = _inference_session_impl__WEBPACK_IMPORTED_MODULE_0__.InferenceSession;
+//# sourceMappingURL=inference-session.js.map
+
+/***/ }),
+
+/***/ "../common/dist/lib/onnx-value.js":
+/*!****************************************!*\
+ !*** ../common/dist/lib/onnx-value.js ***!
+ \****************************************/
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+//# sourceMappingURL=onnx-value.js.map
+
+/***/ }),
+
+/***/ "../common/dist/lib/tensor-impl.js":
+/*!*****************************************!*\
+ !*** ../common/dist/lib/tensor-impl.js ***!
+ \*****************************************/
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "Tensor": () => (/* binding */ Tensor)
+/* harmony export */ });
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+const isBigInt64ArrayAvailable = typeof BigInt64Array !== 'undefined' && typeof BigInt64Array.from === 'function';
+const isBigUint64ArrayAvailable = typeof BigUint64Array !== 'undefined' && typeof BigUint64Array.from === 'function';
+// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.
+const NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = new Map([
+ ['float32', Float32Array],
+ ['uint8', Uint8Array],
+ ['int8', Int8Array],
+ ['uint16', Uint16Array],
+ ['int16', Int16Array],
+ ['int32', Int32Array],
+ ['bool', Uint8Array],
+ ['float64', Float64Array],
+ ['uint32', Uint32Array],
+]);
+// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.
+const NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = new Map([
+ [Float32Array, 'float32'],
+ [Uint8Array, 'uint8'],
+ [Int8Array, 'int8'],
+ [Uint16Array, 'uint16'],
+ [Int16Array, 'int16'],
+ [Int32Array, 'int32'],
+ [Float64Array, 'float64'],
+ [Uint32Array, 'uint32'],
+]);
+if (isBigInt64ArrayAvailable) {
+ NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('int64', BigInt64Array);
+ NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, 'int64');
+}
+if (isBigUint64ArrayAvailable) {
+ NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('uint64', BigUint64Array);
+ NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, 'uint64');
+}
+/**
+ * calculate size from dims.
+ *
+ * @param dims the dims array. May be an illegal input.
+ */
+const calculateSize = (dims) => {
+ let size = 1;
+ for (let i = 0; i < dims.length; i++) {
+ const dim = dims[i];
+ if (typeof dim !== 'number' || !Number.isSafeInteger(dim)) {
+ throw new TypeError(`dims[${i}] must be an integer, got: ${dim}`);
+ }
+ if (dim < 0) {
+ throw new RangeError(`dims[${i}] must be a non-negative integer, got: ${dim}`);
+ }
+ size *= dim;
+ }
+ return size;
+};
+class Tensor {
+ constructor(arg0, arg1, arg2) {
+ let type;
+ let data;
+ let dims;
+ // check whether arg0 is type or data
+ if (typeof arg0 === 'string') {
+ //
+ // Override: constructor(type, data, ...)
+ //
+ type = arg0;
+ dims = arg2;
+ if (arg0 === 'string') {
+ // string tensor
+ if (!Array.isArray(arg1)) {
+ throw new TypeError('A string tensor\'s data must be a string array.');
+ }
+ // we don't check whether every element in the array is string; this is too slow. we assume it's correct and
+ // error will be populated at inference
+ data = arg1;
+ }
+ else {
+ // numeric tensor
+ const typedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(arg0);
+ if (typedArrayConstructor === undefined) {
+ throw new TypeError(`Unsupported tensor type: ${arg0}.`);
+ }
+ if (Array.isArray(arg1)) {
+ // use 'as any' here because TypeScript's check on type of 'SupportedTypedArrayConstructors.from()' produces
+ // incorrect results.
+ // 'typedArrayConstructor' should be one of the typed array prototype objects.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ data = typedArrayConstructor.from(arg1);
+ }
+ else if (arg1 instanceof typedArrayConstructor) {
+ data = arg1;
+ }
+ else {
+ throw new TypeError(`A ${type} tensor's data must be type of ${typedArrayConstructor}`);
+ }
+ }
+ }
+ else {
+ //
+ // Override: constructor(data, ...)
+ //
+ dims = arg1;
+ if (Array.isArray(arg0)) {
+ // only boolean[] and string[] is supported
+ if (arg0.length === 0) {
+ throw new TypeError('Tensor type cannot be inferred from an empty array.');
+ }
+ const firstElementType = typeof arg0[0];
+ if (firstElementType === 'string') {
+ type = 'string';
+ data = arg0;
+ }
+ else if (firstElementType === 'boolean') {
+ type = 'bool';
+ // 'arg0' is of type 'boolean[]'. Uint8Array.from(boolean[]) actually works, but typescript thinks this is
+ // wrong type. We use 'as any' to make it happy.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ data = Uint8Array.from(arg0);
+ }
+ else {
+ throw new TypeError(`Invalid element type of data array: ${firstElementType}.`);
+ }
+ }
+ else {
+ // get tensor type from TypedArray
+ const mappedType = NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(arg0.constructor);
+ if (mappedType === undefined) {
+ throw new TypeError(`Unsupported type for tensor data: ${arg0.constructor}.`);
+ }
+ type = mappedType;
+ data = arg0;
+ }
+ }
+ // type and data is processed, now processing dims
+ if (dims === undefined) {
+ // assume 1-D tensor if dims omitted
+ dims = [data.length];
+ }
+ else if (!Array.isArray(dims)) {
+ throw new TypeError('A tensor\'s dims must be a number array');
+ }
+ // perform check
+ const size = calculateSize(dims);
+ if (size !== data.length) {
+ throw new Error(`Tensor's size(${size}) does not match data length(${data.length}).`);
+ }
+ this.dims = dims;
+ this.type = type;
+ this.data = data;
+ this.size = size;
+ }
+ // #endregion
+ /**
+ * Create a new tensor object from image object
+ *
+ * @param buffer - Extracted image buffer data - assuming RGBA format
+ * @param imageFormat - input image configuration - required configurations height, width, format
+ * @param tensorFormat - output tensor configuration - Default is RGB format
+ */
+ static bufferToTensor(buffer, options) {
+ if (buffer === undefined) {
+ throw new Error('Image buffer must be defined');
+ }
+ if (options.height === undefined || options.width === undefined) {
+ throw new Error('Image height and width must be defined');
+ }
+ const { height, width } = options;
+ const norm = options.norm;
+ let normMean;
+ let normBias;
+ if (norm === undefined || norm.mean === undefined) {
+ normMean = 255;
+ }
+ else {
+ normMean = norm.mean;
+ }
+ if (norm === undefined || norm.bias === undefined) {
+ normBias = 0;
+ }
+ else {
+ normBias = norm.bias;
+ }
+ const inputformat = options.bitmapFormat !== undefined ? options.bitmapFormat : 'RGBA';
+ // default value is RGBA since imagedata and HTMLImageElement uses it
+ const outputformat = options.tensorFormat !== undefined ?
+ (options.tensorFormat !== undefined ? options.tensorFormat : 'RGB') :
+ 'RGB';
+ const offset = height * width;
+ const float32Data = outputformat === 'RGBA' ? new Float32Array(offset * 4) : new Float32Array(offset * 3);
+ // Default pointer assignments
+ let step = 4, rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;
+ let rTensorPointer = 0, gTensorPointer = offset, bTensorPointer = offset * 2, aTensorPointer = -1;
+ // Updating the pointer assignments based on the input image format
+ if (inputformat === 'RGB') {
+ step = 3;
+ rImagePointer = 0;
+ gImagePointer = 1;
+ bImagePointer = 2;
+ aImagePointer = -1;
+ }
+ // Updating the pointer assignments based on the output tensor format
+ if (outputformat === 'RGBA') {
+ aTensorPointer = offset * 3;
+ }
+ else if (outputformat === 'RBG') {
+ rTensorPointer = 0;
+ bTensorPointer = offset;
+ gTensorPointer = offset * 2;
+ }
+ else if (outputformat === 'BGR') {
+ bTensorPointer = 0;
+ gTensorPointer = offset;
+ rTensorPointer = offset * 2;
+ }
+ for (let i = 0; i < offset; i++, rImagePointer += step, bImagePointer += step, gImagePointer += step, aImagePointer += step) {
+ float32Data[rTensorPointer++] = (buffer[rImagePointer] + normBias) / normMean;
+ float32Data[gTensorPointer++] = (buffer[gImagePointer] + normBias) / normMean;
+ float32Data[bTensorPointer++] = (buffer[bImagePointer] + normBias) / normMean;
+ if (aTensorPointer !== -1 && aImagePointer !== -1) {
+ float32Data[aTensorPointer++] = (buffer[aImagePointer] + normBias) / normMean;
+ }
+ }
+ // Float32Array -> ort.Tensor
+ const outputTensor = outputformat === 'RGBA' ? new Tensor('float32', float32Data, [1, 4, height, width]) :
+ new Tensor('float32', float32Data, [1, 3, height, width]);
+ return outputTensor;
+ }
+ static async fromImage(image, options) {
+ // checking the type of image object
+ const isHTMLImageEle = typeof (HTMLImageElement) !== 'undefined' && image instanceof HTMLImageElement;
+ const isImageDataEle = typeof (ImageData) !== 'undefined' && image instanceof ImageData;
+ const isImageBitmap = typeof (ImageBitmap) !== 'undefined' && image instanceof ImageBitmap;
+ const isURL = typeof (String) !== 'undefined' && (image instanceof String || typeof image === 'string');
+ let data;
+ let tensorConfig = {};
+ // filling and checking image configuration options
+ if (isHTMLImageEle) {
+ // HTMLImageElement - image object - format is RGBA by default
+ const canvas = document.createElement('canvas');
+ const pixels2DContext = canvas.getContext('2d');
+ if (pixels2DContext != null) {
+ let height = image.naturalHeight;
+ let width = image.naturalWidth;
+ if (options !== undefined && options.resizedHeight !== undefined && options.resizedWidth !== undefined) {
+ height = options.resizedHeight;
+ width = options.resizedWidth;
+ }
+ if (options !== undefined) {
+ tensorConfig = options;
+ if (options.tensorFormat !== undefined) {
+ throw new Error('Image input config format must be RGBA for HTMLImageElement');
+ }
+ else {
+ tensorConfig.tensorFormat = 'RGBA';
+ }
+ if (options.height !== undefined && options.height !== height) {
+ throw new Error('Image input config height doesn\'t match HTMLImageElement height');
+ }
+ else {
+ tensorConfig.height = height;
+ }
+ if (options.width !== undefined && options.width !== width) {
+ throw new Error('Image input config width doesn\'t match HTMLImageElement width');
+ }
+ else {
+ tensorConfig.width = width;
+ }
+ }
+ else {
+ tensorConfig.tensorFormat = 'RGBA';
+ tensorConfig.height = height;
+ tensorConfig.width = width;
+ }
+ canvas.width = width;
+ canvas.height = height;
+ pixels2DContext.drawImage(image, 0, 0, width, height);
+ data = pixels2DContext.getImageData(0, 0, width, height).data;
+ }
+ else {
+ throw new Error('Can not access image data');
+ }
+ }
+ else if (isImageDataEle) {
+ // ImageData - image object - format is RGBA by default
+ const format = 'RGBA';
+ let height;
+ let width;
+ if (options !== undefined && options.resizedWidth !== undefined && options.resizedHeight !== undefined) {
+ height = options.resizedHeight;
+ width = options.resizedWidth;
+ }
+ else {
+ height = image.height;
+ width = image.width;
+ }
+ if (options !== undefined) {
+ tensorConfig = options;
+ if (options.bitmapFormat !== undefined && options.bitmapFormat !== format) {
+ throw new Error('Image input config format must be RGBA for ImageData');
+ }
+ else {
+ tensorConfig.bitmapFormat = 'RGBA';
+ }
+ }
+ else {
+ tensorConfig.bitmapFormat = 'RGBA';
+ }
+ tensorConfig.height = height;
+ tensorConfig.width = width;
+ if (options !== undefined) {
+ const tempCanvas = document.createElement('canvas');
+ tempCanvas.width = width;
+ tempCanvas.height = height;
+ const pixels2DContext = tempCanvas.getContext('2d');
+ if (pixels2DContext != null) {
+ pixels2DContext.putImageData(image, 0, 0);
+ data = pixels2DContext.getImageData(0, 0, width, height).data;
+ }
+ else {
+ throw new Error('Can not access image data');
+ }
+ }
+ else {
+ data = image.data;
+ }
+ }
+ else if (isImageBitmap) {
+ // ImageBitmap - image object - format must be provided by user
+ if (options === undefined) {
+ throw new Error('Please provide image config with format for Imagebitmap');
+ }
+ if (options.bitmapFormat !== undefined) {
+ throw new Error('Image input config format must be defined for ImageBitmap');
+ }
+ const pixels2DContext = document.createElement('canvas').getContext('2d');
+ if (pixels2DContext != null) {
+ const height = image.height;
+ const width = image.width;
+ pixels2DContext.drawImage(image, 0, 0, width, height);
+ data = pixels2DContext.getImageData(0, 0, width, height).data;
+ if (options !== undefined) {
+ // using square brackets to avoid TS error - type 'never'
+ if (options.height !== undefined && options.height !== height) {
+ throw new Error('Image input config height doesn\'t match ImageBitmap height');
+ }
+ else {
+ tensorConfig.height = height;
+ }
+ // using square brackets to avoid TS error - type 'never'
+ if (options.width !== undefined && options.width !== width) {
+ throw new Error('Image input config width doesn\'t match ImageBitmap width');
+ }
+ else {
+ tensorConfig.width = width;
+ }
+ }
+ else {
+ tensorConfig.height = height;
+ tensorConfig.width = width;
+ }
+ return Tensor.bufferToTensor(data, tensorConfig);
+ }
+ else {
+ throw new Error('Can not access image data');
+ }
+ }
+ else if (isURL) {
+ return new Promise((resolve, reject) => {
+ const canvas = document.createElement('canvas');
+ const context = canvas.getContext('2d');
+ if (!image || !context) {
+ return reject();
+ }
+ const newImage = new Image();
+ newImage.crossOrigin = 'Anonymous';
+ newImage.src = image;
+ newImage.onload = () => {
+ canvas.width = newImage.width;
+ canvas.height = newImage.height;
+ context.drawImage(newImage, 0, 0, canvas.width, canvas.height);
+ const img = context.getImageData(0, 0, canvas.width, canvas.height);
+ if (options !== undefined) {
+ // using square brackets to avoid TS error - type 'never'
+ if (options.height !== undefined && options.height !== canvas.height) {
+ throw new Error('Image input config height doesn\'t match ImageBitmap height');
+ }
+ else {
+ tensorConfig.height = canvas.height;
+ }
+ // using square brackets to avoid TS error - type 'never'
+ if (options.width !== undefined && options.width !== canvas.width) {
+ throw new Error('Image input config width doesn\'t match ImageBitmap width');
+ }
+ else {
+ tensorConfig.width = canvas.width;
+ }
+ }
+ else {
+ tensorConfig.height = canvas.height;
+ tensorConfig.width = canvas.width;
+ }
+ resolve(Tensor.bufferToTensor(img.data, tensorConfig));
+ };
+ });
+ }
+ else {
+ throw new Error('Input data provided is not supported - aborted tensor creation');
+ }
+ if (data !== undefined) {
+ return Tensor.bufferToTensor(data, tensorConfig);
+ }
+ else {
+ throw new Error('Input data provided is not supported - aborted tensor creation');
+ }
+ }
+ toImageData(options) {
+ var _a, _b;
+ const pixels2DContext = document.createElement('canvas').getContext('2d');
+ let image;
+ if (pixels2DContext != null) {
+ // Default values for height and width & format
+ const width = this.dims[3];
+ const height = this.dims[2];
+ const channels = this.dims[1];
+ const inputformat = options !== undefined ? (options.format !== undefined ? options.format : 'RGB') : 'RGB';
+ const normMean = options !== undefined ? (((_a = options.norm) === null || _a === void 0 ? void 0 : _a.mean) !== undefined ? options.norm.mean : 255) : 255;
+ const normBias = options !== undefined ? (((_b = options.norm) === null || _b === void 0 ? void 0 : _b.bias) !== undefined ? options.norm.bias : 0) : 0;
+ const offset = height * width;
+ if (options !== undefined) {
+ if (options.height !== undefined && options.height !== height) {
+ throw new Error('Image output config height doesn\'t match tensor height');
+ }
+ if (options.width !== undefined && options.width !== width) {
+ throw new Error('Image output config width doesn\'t match tensor width');
+ }
+ if (options.format !== undefined && (channels === 4 && options.format !== 'RGBA') ||
+ (channels === 3 && (options.format !== 'RGB' && options.format !== 'BGR'))) {
+ throw new Error('Tensor format doesn\'t match input tensor dims');
+ }
+ }
+ // Default pointer assignments
+ const step = 4;
+ let rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;
+ let rTensorPointer = 0, gTensorPointer = offset, bTensorPointer = offset * 2, aTensorPointer = -1;
+ // Updating the pointer assignments based on the input image format
+ if (inputformat === 'RGBA') {
+ rTensorPointer = 0;
+ gTensorPointer = offset;
+ bTensorPointer = offset * 2;
+ aTensorPointer = offset * 3;
+ }
+ else if (inputformat === 'RGB') {
+ rTensorPointer = 0;
+ gTensorPointer = offset;
+ bTensorPointer = offset * 2;
+ }
+ else if (inputformat === 'RBG') {
+ rTensorPointer = 0;
+ bTensorPointer = offset;
+ gTensorPointer = offset * 2;
+ }
+ image = pixels2DContext.createImageData(width, height);
+ for (let i = 0; i < height * width; rImagePointer += step, gImagePointer += step, bImagePointer += step, aImagePointer += step, i++) {
+ image.data[rImagePointer] = (this.data[rTensorPointer++] - normBias) * normMean; // R value
+ image.data[gImagePointer] = (this.data[gTensorPointer++] - normBias) * normMean; // G value
+ image.data[bImagePointer] = (this.data[bTensorPointer++] - normBias) * normMean; // B value
+ image.data[aImagePointer] =
+ aTensorPointer === -1 ? 255 : (this.data[aTensorPointer++] - normBias) * normMean; // A value
+ }
+ }
+ else {
+ throw new Error('Can not access image data');
+ }
+ return image;
+ }
+ // #endregion
+ // #region tensor utilities
+ reshape(dims) {
+ return new Tensor(this.type, this.data, dims);
+ }
+}
+//# sourceMappingURL=tensor-impl.js.map
+
+/***/ }),
+
+/***/ "../common/dist/lib/tensor.js":
+/*!************************************!*\
+ !*** ../common/dist/lib/tensor.js ***!
+ \************************************/
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "Tensor": () => (/* binding */ Tensor)
+/* harmony export */ });
+/* harmony import */ var _tensor_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./tensor-impl */ "../common/dist/lib/tensor-impl.js");
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const Tensor = _tensor_impl__WEBPACK_IMPORTED_MODULE_0__.Tensor;
+//# sourceMappingURL=tensor.js.map
+
+/***/ }),
+
+/***/ "./lib/wasm/binding/ort-wasm-threaded.js":
+/*!***********************************************!*\
+ !*** ./lib/wasm/binding/ort-wasm-threaded.js ***!
+ \***********************************************/
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+var __filename = "/index.js";
+var __dirname = "/";
+
+var ortWasmThreaded = (() => {
+ var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;
+ if (true) _scriptDir = _scriptDir || __filename;
+ return (
+function(ortWasmThreaded) {
+ ortWasmThreaded = ortWasmThreaded || {};
+
+
+function d(){m.buffer!=n&&p(m.buffer);return aa}function q(){m.buffer!=n&&p(m.buffer);return ba}function r(){m.buffer!=n&&p(m.buffer);return ca}function v(){m.buffer!=n&&p(m.buffer);return da}function ea(){m.buffer!=n&&p(m.buffer);return fa}var x;x||(x=typeof ortWasmThreaded !== 'undefined' ? ortWasmThreaded : {});var ha,ia;x.ready=new Promise(function(a,b){ha=a;ia=b});
+var ja=Object.assign({},x),ka="./this.program",la=(a,b)=>{throw b;},ma="object"==typeof window,y="function"==typeof importScripts,B="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,C=x.ENVIRONMENT_IS_PTHREAD||!1,D="";function na(a){return x.locateFile?x.locateFile(a,D):D+a}var oa,pa,qa,fs,ra,sa;
+if(B){D=y?(__webpack_require__(/*! path */ "?75c6").dirname)(D)+"/":__dirname+"/";sa=()=>{ra||(fs=__webpack_require__(/*! fs */ "?63c8"),ra=__webpack_require__(/*! path */ "?75c6"))};oa=function(b,c){sa();b=ra.normalize(b);return fs.readFileSync(b,c?void 0:"utf8")};qa=b=>{b=oa(b,!0);b.buffer||(b=new Uint8Array(b));return b};pa=(b,c,e)=>{sa();b=ra.normalize(b);fs.readFile(b,function(f,h){f?e(f):c(h.buffer)})};1<process.argv.length&&(ka=process.argv[1].replace(/\\/g,"/"));process.argv.slice(2);process.on("uncaughtException",function(b){if(!(b instanceof E))throw b;});process.on("unhandledRejection",
+function(b){throw b;});la=(b,c)=>{if(F())throw process.exitCode=b,c;c instanceof E||G("exiting due to exception: "+c);process.exit(b)};x.inspect=function(){return"[Emscripten Module object]"};let a;try{a=__webpack_require__(/*! worker_threads */ "?c6f7")}catch(b){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),b;}__webpack_require__.g.Worker=a.Worker}else if(ma||y)y?D=self.location.href:"undefined"!=typeof document&&document.currentScript&&(D=document.currentScript.src),
+_scriptDir&&(D=_scriptDir),0!==D.indexOf("blob:")?D=D.substr(0,D.replace(/[?#].*/,"").lastIndexOf("/")+1):D="",B||(oa=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.send(null);return b.responseText},y&&(qa=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer";b.send(null);return new Uint8Array(b.response)}),pa=(a,b,c)=>{var e=new XMLHttpRequest;e.open("GET",a,!0);e.responseType="arraybuffer";e.onload=()=>{200==e.status||0==e.status&&e.response?b(e.response):c()};e.onerror=
+c;e.send(null)});B&&"undefined"==typeof performance&&(__webpack_require__.g.performance=(__webpack_require__(/*! perf_hooks */ "?674f").performance));var ta=console.log.bind(console),ua=console.warn.bind(console);B&&(sa(),ta=a=>fs.writeSync(1,a+"\n"),ua=a=>fs.writeSync(2,a+"\n"));var va=x.print||ta,G=x.printErr||ua;Object.assign(x,ja);ja=null;x.thisProgram&&(ka=x.thisProgram);x.quit&&(la=x.quit);var H;x.wasmBinary&&(H=x.wasmBinary);var noExitRuntime=x.noExitRuntime||!1;"object"!=typeof WebAssembly&&I("no native wasm support detected");
+var m,wa,xa=!1,ya="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;
+function za(a,b,c){b>>>=0;var e=b+c;for(c=b;a[c]&&!(c>=e);)++c;if(16<c-b&&a.buffer&&ya)return ya.decode(a.buffer instanceof SharedArrayBuffer?a.slice(b,c):a.subarray(b,c));for(e="";b<c;){var f=a[b++];if(f&128){var h=a[b++]&63;if(192==(f&224))e+=String.fromCharCode((f&31)<<6|h);else{var k=a[b++]&63;f=224==(f&240)?(f&15)<<12|h<<6|k:(f&7)<<18|h<<12|k<<6|a[b++]&63;65536>f?e+=String.fromCharCode(f):(f-=65536,e+=String.fromCharCode(55296|f>>10,56320|f&1023))}}else e+=String.fromCharCode(f)}return e}
+function Aa(a,b){return(a>>>=0)?za(q(),a,b):""}
+function Ba(a,b,c,e){c>>>=0;if(!(0<e))return 0;var f=c;e=c+e-1;for(var h=0;h<a.length;++h){var k=a.charCodeAt(h);if(55296<=k&&57343>=k){var l=a.charCodeAt(++h);k=65536+((k&1023)<<10)|l&1023}if(127>=k){if(c>=e)break;b[c++>>>0]=k}else{if(2047>=k){if(c+1>=e)break;b[c++>>>0]=192|k>>6}else{if(65535>=k){if(c+2>=e)break;b[c++>>>0]=224|k>>12}else{if(c+3>=e)break;b[c++>>>0]=240|k>>18;b[c++>>>0]=128|k>>12&63}b[c++>>>0]=128|k>>6&63}b[c++>>>0]=128|k&63}}b[c>>>0]=0;return c-f}
+function Ca(a){for(var b=0,c=0;c<a.length;++c){var e=a.charCodeAt(c);127>=e?b++:2047>=e?b+=2:55296<=e&&57343>=e?(b+=4,++c):b+=3}return b}var n,aa,ba,ca,da,fa;C&&(n=x.buffer);function p(a){n=a;x.HEAP8=aa=new Int8Array(a);x.HEAP16=new Int16Array(a);x.HEAP32=ca=new Int32Array(a);x.HEAPU8=ba=new Uint8Array(a);x.HEAPU16=new Uint16Array(a);x.HEAPU32=da=new Uint32Array(a);x.HEAPF32=new Float32Array(a);x.HEAPF64=fa=new Float64Array(a)}var Da=x.INITIAL_MEMORY||16777216;
+if(C)m=x.wasmMemory,n=x.buffer;else if(x.wasmMemory)m=x.wasmMemory;else if(m=new WebAssembly.Memory({initial:Da/65536,maximum:65536,shared:!0}),!(m.buffer instanceof SharedArrayBuffer))throw G("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),B&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),
+Error("bad memory");m&&(n=m.buffer);Da=n.byteLength;p(n);var Ea,Fa=[],Ga=[],Ha=[],Ia=[],Ja=0;function F(){return noExitRuntime||0<Ja}function Ka(){var a=x.preRun.shift();Fa.unshift(a)}var L=0,La=null,M=null;function I(a){if(C)postMessage({cmd:"onAbort",arg:a});else if(x.onAbort)x.onAbort(a);a="Aborted("+a+")";G(a);xa=!0;a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info.");ia(a);throw a;}function Ma(){return O.startsWith("data:application/octet-stream;base64,")}var O;O="ort-wasm-threaded.wasm";
+Ma()||(O=na(O));function Na(){var a=O;try{if(a==O&&H)return new Uint8Array(H);if(qa)return qa(a);throw"both async and sync fetching of the wasm failed";}catch(b){I(b)}}
+function Oa(){if(!H&&(ma||y)){if("function"==typeof fetch&&!O.startsWith("file://"))return fetch(O,{credentials:"same-origin"}).then(function(a){if(!a.ok)throw"failed to load wasm binary file at '"+O+"'";return a.arrayBuffer()}).catch(function(){return Na()});if(pa)return new Promise(function(a,b){pa(O,function(c){a(new Uint8Array(c))},b)})}return Promise.resolve().then(function(){return Na()})}var Pa={};
+function E(a){this.name="ExitStatus";this.message="Program terminated with exit("+a+")";this.status=a}function Qa(a){(a=P.Vb[a])||I();P.mc(a)}function Ra(a){var b=P.Cc();if(!b)return 6;P.ac.push(b);P.Vb[a.Ub]=b;b.Ub=a.Ub;var c={cmd:"run",start_routine:a.Ic,arg:a.zc,pthread_ptr:a.Ub};b.$b=()=>{c.time=performance.now();b.postMessage(c,a.Nc)};b.loaded&&(b.$b(),delete b.$b);return 0}function Sa(a){if(C)return Q(1,1,a);if(!F()){P.oc();if(x.onExit)x.onExit(a);xa=!0}la(a,new E(a))}
+function Ta(a,b){if(!b&&C)throw Ua(a),"unwind";F()||C||(Va(),R(Ha),Wa(0),Xa[1].length&&Ya(1,10),Xa[2].length&&Ya(2,10),P.oc());Sa(a)}
+var P={Yb:[],ac:[],qc:[],Vb:{},fc:function(){C&&P.Ec()},Pc:function(){},Ec:function(){P.receiveObjectTransfer=P.Gc;P.threadInitTLS=P.pc;P.setExitStatus=P.nc;noExitRuntime=!1},nc:function(){},oc:function(){for(var a of Object.values(P.Vb))P.mc(a);for(a of P.Yb)a.terminate();P.Yb=[]},mc:function(a){var b=a.Ub;delete P.Vb[b];P.Yb.push(a);P.ac.splice(P.ac.indexOf(a),1);a.Ub=0;Za(b)},Gc:function(){},pc:function(){P.qc.forEach(a=>a())},Fc:function(a,b){a.onmessage=c=>{c=c.data;var e=c.cmd;a.Ub&&(P.Bc=a.Ub);
+if(c.targetThread&&c.targetThread!=$a()){var f=P.Vb[c.Qc];f?f.postMessage(c,c.transferList):G('Internal error! Worker sent a message "'+e+'" to target pthread '+c.targetThread+", but that thread no longer exists!")}else if("processProxyingQueue"===e)ab(c.queue);else if("spawnThread"===e)Ra(c);else if("cleanupThread"===e)Qa(c.thread);else if("killThread"===e)c=c.thread,e=P.Vb[c],delete P.Vb[c],e.terminate(),Za(c),P.ac.splice(P.ac.indexOf(e),1),e.Ub=0;else if("cancelThread"===e)P.Vb[c.thread].postMessage({cmd:"cancel"});
+else if("loaded"===e)a.loaded=!0,b&&b(a),a.$b&&(a.$b(),delete a.$b);else if("print"===e)va("Thread "+c.threadId+": "+c.text);else if("printErr"===e)G("Thread "+c.threadId+": "+c.text);else if("alert"===e)alert("Thread "+c.threadId+": "+c.text);else if("setimmediate"===c.target)a.postMessage(c);else if("onAbort"===e){if(x.onAbort)x.onAbort(c.arg)}else e&&G("worker sent an unknown command "+e);P.Bc=void 0};a.onerror=c=>{G("worker sent an error! "+c.filename+":"+c.lineno+": "+c.message);throw c;};B&&
+(a.on("message",function(c){a.onmessage({data:c})}),a.on("error",function(c){a.onerror(c)}),a.on("detachedExit",function(){}));a.postMessage({cmd:"load",urlOrBlob:x.mainScriptUrlOrBlob||_scriptDir,wasmMemory:m,wasmModule:wa})},yc:function(){var a=na("ort-wasm-threaded.worker.js");P.Yb.push(new Worker(a))},Cc:function(){0==P.Yb.length&&(P.yc(),P.Fc(P.Yb[0]));return P.Yb.pop()}};x.PThread=P;function R(a){for(;0<a.length;)a.shift()(x)}function bb(a){var b=S();a=a();U(b);return a}
+x.establishStackSpace=function(){var a=$a(),b=r()[a+44>>2>>>0];a=r()[a+48>>2>>>0];cb(b,b-a);U(b)};function Ua(a){if(C)return Q(2,0,a);try{Ta(a)}catch(b){b instanceof E||"unwind"==b||la(1,b)}}var db=[];function V(a){var b=db[a];b||(a>=db.length&&(db.length=a+1),db[a]=b=Ea.get(a));return b}x.invokeEntryPoint=function(a,b){a=V(a)(b);F()?P.nc(a):eb(a)};function fb(a,b){d().set(a,b>>>0)}var gb=[],hb=0,W=0;
+function X(a){this.Zb=a;this.Sb=a-24;this.xc=function(b){v()[this.Sb+4>>2>>>0]=b};this.bc=function(){return v()[this.Sb+4>>2>>>0]};this.wc=function(b){v()[this.Sb+8>>2>>>0]=b};this.Dc=function(){return v()[this.Sb+8>>2>>>0]};this.rc=function(){r()[this.Sb>>2>>>0]=0};this.hc=function(b){b=b?1:0;d()[this.Sb+12>>0>>>0]=b};this.uc=function(){return 0!=d()[this.Sb+12>>0>>>0]};this.ic=function(b){b=b?1:0;d()[this.Sb+13>>0>>>0]=b};this.kc=function(){return 0!=d()[this.Sb+13>>0>>>0]};this.fc=function(b,c){this.cc(0);
+this.xc(b);this.wc(c);this.rc();this.hc(!1);this.ic(!1)};this.sc=function(){Atomics.add(r(),this.Sb>>2,1)};this.Hc=function(){return 1===Atomics.sub(r(),this.Sb>>2,1)};this.cc=function(b){v()[this.Sb+16>>2>>>0]=b};this.tc=function(){return v()[this.Sb+16>>2>>>0]};this.vc=function(){if(ib(this.bc()))return v()[this.Zb>>2>>>0];var b=this.tc();return 0!==b?b:this.Zb}}function jb(a){return kb((new X(a)).Sb)}function lb(a,b,c,e){return C?Q(3,1,a,b,c,e):mb(a,b,c,e)}
+function mb(a,b,c,e){if("undefined"==typeof SharedArrayBuffer)return G("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var f=[];if(C&&0===f.length)return lb(a,b,c,e);a={Ic:c,Ub:a,zc:e,Nc:f};return C?(a.Oc="spawnThread",postMessage(a,f),0):Ra(a)}function nb(a,b,c){return C?Q(4,1,a,b,c):0}function ob(a,b){if(C)return Q(5,1,a,b)}function pb(a,b){if(C)return Q(6,1,a,b)}function qb(a,b,c){if(C)return Q(7,1,a,b,c)}function rb(a,b,c){return C?Q(8,1,a,b,c):0}
+function sb(a,b){if(C)return Q(9,1,a,b)}function tb(a,b,c){if(C)return Q(10,1,a,b,c)}function ub(a,b,c,e){if(C)return Q(11,1,a,b,c,e)}function vb(a,b,c,e){if(C)return Q(12,1,a,b,c,e)}function wb(a,b,c,e){if(C)return Q(13,1,a,b,c,e)}function xb(a){if(C)return Q(14,1,a)}function yb(a,b){if(C)return Q(15,1,a,b)}function zb(a,b,c){if(C)return Q(16,1,a,b,c)}function ab(a){Atomics.store(r(),a>>2,1);$a()&&Ab(a);Atomics.compareExchange(r(),a>>2,1,0)}x.executeNotifiedProxyingQueue=ab;
+function Bb(a){return v()[a>>>2]+4294967296*r()[a+4>>>2]}function Cb(a,b,c,e,f,h){return C?Q(17,1,a,b,c,e,f,h):-52}function Db(a,b,c,e,f,h){if(C)return Q(18,1,a,b,c,e,f,h)}function Eb(a){var b=Ca(a)+1,c=Fb(b);c&&Ba(a,d(),c,b);return c}
+function Gb(a,b,c){function e(t){return(t=t.toTimeString().match(/\(([A-Za-z ]+)\)$/))?t[1]:"GMT"}if(C)return Q(19,1,a,b,c);var f=(new Date).getFullYear(),h=new Date(f,0,1),k=new Date(f,6,1);f=h.getTimezoneOffset();var l=k.getTimezoneOffset(),u=Math.max(f,l);r()[a>>2>>>0]=60*u;r()[b>>2>>>0]=Number(f!=l);a=e(h);b=e(k);a=Eb(a);b=Eb(b);l<f?(v()[c>>2>>>0]=a,v()[c+4>>2>>>0]=b):(v()[c>>2>>>0]=b,v()[c+4>>2>>>0]=a)}function Hb(a,b,c){Hb.Ac||(Hb.Ac=!0,Gb(a,b,c))}var Ib,Jb;
+Jb=B?()=>{var a=process.hrtime();return 1E3*a[0]+a[1]/1E6}:C?()=>performance.now()-x.__performance_now_clock_drift:()=>performance.now();function Q(a,b){var c=arguments.length-2,e=arguments;return bb(()=>{for(var f=Kb(8*c),h=f>>3,k=0;k<c;k++){var l=e[2+k];ea()[h+k>>>0]=l}return Lb(a,c,f,b)})}var Mb=[],Nb={};
+function Ob(){if(!Pb){var a={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",_:ka||"./this.program"},b;for(b in Nb)void 0===Nb[b]?delete a[b]:a[b]=Nb[b];var c=[];for(b in a)c.push(b+"="+a[b]);Pb=c}return Pb}var Pb;
+function Qb(a,b){if(C)return Q(20,1,a,b);var c=0;Ob().forEach(function(e,f){var h=b+c;f=v()[a+4*f>>2>>>0]=h;for(h=0;h<e.length;++h)d()[f++>>0>>>0]=e.charCodeAt(h);d()[f>>0>>>0]=0;c+=e.length+1});return 0}function Rb(a,b){if(C)return Q(21,1,a,b);var c=Ob();v()[a>>2>>>0]=c.length;var e=0;c.forEach(function(f){e+=f.length+1});v()[b>>2>>>0]=e;return 0}function Sb(a){return C?Q(22,1,a):52}function Tb(a,b,c,e){return C?Q(23,1,a,b,c,e):52}function Ub(a,b,c,e,f){return C?Q(24,1,a,b,c,e,f):70}
+var Xa=[null,[],[]];function Ya(a,b){var c=Xa[a];0===b||10===b?((1===a?va:G)(za(c,0)),c.length=0):c.push(b)}function Vb(a,b,c,e){if(C)return Q(25,1,a,b,c,e);for(var f=0,h=0;h<c;h++){var k=v()[b>>2>>>0],l=v()[b+4>>2>>>0];b+=8;for(var u=0;u<l;u++)Ya(a,q()[k+u>>>0]);f+=l}v()[e>>2>>>0]=f;return 0}var Y=0;
+function Wb(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var a=new Uint8Array(1);return()=>{crypto.getRandomValues(a);return a[0]}}if(B)try{var b=__webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module 'crypto'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()));return()=>b.randomBytes(1)[0]}catch(c){}return()=>I("randomDevice")}function Xb(a,b){Xb.lc||(Xb.lc=Wb());for(var c=0;c<b;c++)d()[a+c>>0>>>0]=Xb.lc();return 0}function Yb(a){return 0===a%4&&(0!==a%100||0===a%400)}var Zb=[31,29,31,30,31,30,31,31,30,31,30,31],$b=[31,28,31,30,31,30,31,31,30,31,30,31];
+function ac(a){var b=Array(Ca(a)+1);Ba(a,b,0,b.length);return b}
+function bc(a,b,c,e){function f(g,w,z){for(g="number"==typeof g?g.toString():g||"";g.length<w;)g=z[0]+g;return g}function h(g,w){return f(g,w,"0")}function k(g,w){function z(T){return 0>T?-1:0<T?1:0}var N;0===(N=z(g.getFullYear()-w.getFullYear()))&&0===(N=z(g.getMonth()-w.getMonth()))&&(N=z(g.getDate()-w.getDate()));return N}function l(g){switch(g.getDay()){case 0:return new Date(g.getFullYear()-1,11,29);case 1:return g;case 2:return new Date(g.getFullYear(),0,3);case 3:return new Date(g.getFullYear(),
+0,2);case 4:return new Date(g.getFullYear(),0,1);case 5:return new Date(g.getFullYear()-1,11,31);case 6:return new Date(g.getFullYear()-1,11,30)}}function u(g){var w=g.Wb;for(g=new Date((new Date(g.Xb+1900,0,1)).getTime());0<w;){var z=g.getMonth(),N=(Yb(g.getFullYear())?Zb:$b)[z];if(w>N-g.getDate())w-=N-g.getDate()+1,g.setDate(1),11>z?g.setMonth(z+1):(g.setMonth(0),g.setFullYear(g.getFullYear()+1));else{g.setDate(g.getDate()+w);break}}z=new Date(g.getFullYear()+1,0,4);w=l(new Date(g.getFullYear(),
+0,4));z=l(z);return 0>=k(w,g)?0>=k(z,g)?g.getFullYear()+1:g.getFullYear():g.getFullYear()-1}var t=r()[e+40>>2>>>0];e={Lc:r()[e>>2>>>0],Kc:r()[e+4>>2>>>0],dc:r()[e+8>>2>>>0],jc:r()[e+12>>2>>>0],ec:r()[e+16>>2>>>0],Xb:r()[e+20>>2>>>0],Tb:r()[e+24>>2>>>0],Wb:r()[e+28>>2>>>0],Rc:r()[e+32>>2>>>0],Jc:r()[e+36>>2>>>0],Mc:t?Aa(t):""};c=Aa(c);t={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C",
+"%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var A in t)c=c.replace(new RegExp(A,"g"),t[A]);var K="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),J="January February March April May June July August September October November December".split(" ");t={"%a":function(g){return K[g.Tb].substring(0,3)},"%A":function(g){return K[g.Tb]},
+"%b":function(g){return J[g.ec].substring(0,3)},"%B":function(g){return J[g.ec]},"%C":function(g){return h((g.Xb+1900)/100|0,2)},"%d":function(g){return h(g.jc,2)},"%e":function(g){return f(g.jc,2," ")},"%g":function(g){return u(g).toString().substring(2)},"%G":function(g){return u(g)},"%H":function(g){return h(g.dc,2)},"%I":function(g){g=g.dc;0==g?g=12:12<g&&(g-=12);return h(g,2)},"%j":function(g){for(var w=0,z=0;z<=g.ec-1;w+=(Yb(g.Xb+1900)?Zb:$b)[z++]);return h(g.jc+w,3)},"%m":function(g){return h(g.ec+
+1,2)},"%M":function(g){return h(g.Kc,2)},"%n":function(){return"\n"},"%p":function(g){return 0<=g.dc&&12>g.dc?"AM":"PM"},"%S":function(g){return h(g.Lc,2)},"%t":function(){return"\t"},"%u":function(g){return g.Tb||7},"%U":function(g){return h(Math.floor((g.Wb+7-g.Tb)/7),2)},"%V":function(g){var w=Math.floor((g.Wb+7-(g.Tb+6)%7)/7);2>=(g.Tb+371-g.Wb-2)%7&&w++;if(w)53==w&&(z=(g.Tb+371-g.Wb)%7,4==z||3==z&&Yb(g.Xb)||(w=1));else{w=52;var z=(g.Tb+7-g.Wb-1)%7;(4==z||5==z&&Yb(g.Xb%400-1))&&w++}return h(w,
+2)},"%w":function(g){return g.Tb},"%W":function(g){return h(Math.floor((g.Wb+7-(g.Tb+6)%7)/7),2)},"%y":function(g){return(g.Xb+1900).toString().substring(2)},"%Y":function(g){return g.Xb+1900},"%z":function(g){g=g.Jc;var w=0<=g;g=Math.abs(g)/60;return(w?"+":"-")+String("0000"+(g/60*100+g%60)).slice(-4)},"%Z":function(g){return g.Mc},"%%":function(){return"%"}};c=c.replace(/%%/g,"\x00\x00");for(A in t)c.includes(A)&&(c=c.replace(new RegExp(A,"g"),t[A](e)));c=c.replace(/\0\0/g,"%");A=ac(c);if(A.length>
+b)return 0;fb(A,a);return A.length-1}P.fc();
+var cc=[null,Sa,Ua,lb,nb,ob,pb,qb,rb,sb,tb,ub,vb,wb,xb,yb,zb,Cb,Db,Gb,Qb,Rb,Sb,Tb,Ub,Vb],Pc={b:function(a){return Fb(a+24)+24},n:function(a){a=new X(a);a.uc()||(a.hc(!0),hb--);a.ic(!1);gb.push(a);a.sc();return a.vc()},ma:function(a){G("Unexpected exception thrown, this is not properly supported - aborting");xa=!0;throw a;},x:function(){Z(0);var a=gb.pop();if(a.Hc()&&!a.kc()){var b=a.Dc();b&&V(b)(a.Zb);jb(a.Zb)}W=0},e:function(){var a=W;if(!a)return Y=0;var b=new X(a);b.cc(a);var c=b.bc();if(!c)return Y=
+0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;if(dc(h,c,b.Sb+16))return Y=h,a}Y=c;return a},l:function(){var a=W;if(!a)return Y=0;var b=new X(a);b.cc(a);var c=b.bc();if(!c)return Y=0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;if(dc(h,c,b.Sb+16))return Y=h,a}Y=c;return a},h:function(){var a=W;if(!a)return Y=0;var b=new X(a);b.cc(a);var c=b.bc();if(!c)return Y=0,a;for(var e=Array.prototype.slice.call(arguments),
+f=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;if(dc(h,c,b.Sb+16))return Y=h,a}Y=c;return a},t:jb,M:function(){var a=gb.pop();a||I("no exception to throw");var b=a.Zb;a.kc()||(gb.push(a),a.ic(!0),a.hc(!1),hb++);W=b;throw b;},c:function(a,b,c){(new X(a)).fc(b,c);W=a;hb++;throw a;},pa:function(){return hb},Fa:function(a){ec(a,!y,1,!ma);P.pc()},T:function(a){C?postMessage({cmd:"cleanupThread",thread:a}):Qa(a)},xa:mb,j:function(a){W||(W=a);throw a;},H:nb,Ma:ob,ua:pb,wa:qb,oa:rb,Ka:sb,Ca:tb,Ja:ub,
+V:vb,va:wb,sa:xb,La:yb,ta:zb,Ta:function(){},X:function(){I("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ua:function(){I("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},W:function(){return Date.now()},ya:function(){return 2097152},Oa:function(){return!0},za:function(a,b,c,e){if(a==b)setTimeout(()=>ab(e));else if(C)postMessage({targetThread:a,cmd:"processProxyingQueue",
+queue:e});else{a=P.Vb[a];if(!a)return;a.postMessage({cmd:"processProxyingQueue",queue:e})}return 1},Ea:function(){return-1},Pa:function(a,b){a=new Date(1E3*Bb(a));r()[b>>2>>>0]=a.getUTCSeconds();r()[b+4>>2>>>0]=a.getUTCMinutes();r()[b+8>>2>>>0]=a.getUTCHours();r()[b+12>>2>>>0]=a.getUTCDate();r()[b+16>>2>>>0]=a.getUTCMonth();r()[b+20>>2>>>0]=a.getUTCFullYear()-1900;r()[b+24>>2>>>0]=a.getUTCDay();a=(a.getTime()-Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0))/864E5|0;r()[b+28>>2>>>0]=a},Qa:function(a,b){a=
+new Date(1E3*Bb(a));r()[b>>2>>>0]=a.getSeconds();r()[b+4>>2>>>0]=a.getMinutes();r()[b+8>>2>>>0]=a.getHours();r()[b+12>>2>>>0]=a.getDate();r()[b+16>>2>>>0]=a.getMonth();r()[b+20>>2>>>0]=a.getFullYear()-1900;r()[b+24>>2>>>0]=a.getDay();var c=new Date(a.getFullYear(),0,1),e=(a.getTime()-c.getTime())/864E5|0;r()[b+28>>2>>>0]=e;r()[b+36>>2>>>0]=-(60*a.getTimezoneOffset());e=(new Date(a.getFullYear(),6,1)).getTimezoneOffset();c=c.getTimezoneOffset();a=(e!=c&&a.getTimezoneOffset()==Math.min(c,e))|0;r()[b+
+32>>2>>>0]=a},Ra:function(a){var b=new Date(r()[a+20>>2>>>0]+1900,r()[a+16>>2>>>0],r()[a+12>>2>>>0],r()[a+8>>2>>>0],r()[a+4>>2>>>0],r()[a>>2>>>0],0),c=r()[a+32>>2>>>0],e=b.getTimezoneOffset(),f=new Date(b.getFullYear(),0,1),h=(new Date(b.getFullYear(),6,1)).getTimezoneOffset(),k=f.getTimezoneOffset(),l=Math.min(k,h);0>c?r()[a+32>>2>>>0]=Number(h!=k&&l==e):0<c!=(l==e)&&(h=Math.max(k,h),b.setTime(b.getTime()+6E4*((0<c?l:h)-e)));r()[a+24>>2>>>0]=b.getDay();c=(b.getTime()-f.getTime())/864E5|0;r()[a+28>>
+2>>>0]=c;r()[a>>2>>>0]=b.getSeconds();r()[a+4>>2>>>0]=b.getMinutes();r()[a+8>>2>>>0]=b.getHours();r()[a+12>>2>>>0]=b.getDate();r()[a+16>>2>>>0]=b.getMonth();return b.getTime()/1E3|0},Aa:Cb,Ba:Db,Sa:Hb,y:function(){I("")},U:function(){if(!B&&!y){var a="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";Ib||(Ib={});Ib[a]||(Ib[a]=1,B&&(a="warning: "+a),G(a))}},ra:function(){return 4294901760},B:Jb,Ia:function(a,b,
+c){q().copyWithin(a>>>0,b>>>0,b+c>>>0)},F:function(){return B?(__webpack_require__(/*! os */ "?aedb").cpus)().length:navigator.hardwareConcurrency},Da:function(a,b,c){Mb.length=b;c>>=3;for(var e=0;e<b;e++)Mb[e]=ea()[c+e>>>0];return(0>a?Pa[-a-1]:cc[a]).apply(null,Mb)},qa:function(a){var b=q().length;a>>>=0;if(a<=b||4294901760<a)return!1;for(var c=1;4>=c;c*=2){var e=b*(1+.2/c);e=Math.min(e,a+100663296);var f=Math;e=Math.max(a,e);f=f.min.call(f,4294901760,e+(65536-e%65536)%65536);a:{try{m.grow(f-n.byteLength+65535>>>16);p(m.buffer);
+var h=1;break a}catch(k){}h=void 0}if(h)return!0}return!1},Na:function(){throw"unwind";},Ga:Qb,Ha:Rb,J:Ta,I:Sb,S:Tb,ga:Ub,R:Vb,d:function(){return Y},na:Xb,ia:fc,ja:gc,K:hc,f:ic,P:jc,Q:kc,k:lc,p:mc,q:nc,N:oc,s:pc,w:qc,L:rc,E:sc,aa:tc,_:uc,Z:vc,ca:wc,$:xc,ba:yc,Y:zc,g:Ac,r:Bc,i:Cc,ha:Dc,m:Ec,v:Fc,u:Gc,O:Hc,A:Ic,ka:Jc,C:Kc,D:Lc,fa:Mc,da:Nc,ea:Oc,o:function(a){return a},a:m||x.wasmMemory,G:function(a){Y=a},la:bc,z:function(a,b,c,e){return bc(a,b,c,e)}};
+(function(){function a(f,h){x.asm=f.exports;P.qc.push(x.asm.sb);Ea=x.asm.ub;Ga.unshift(x.asm.Va);wa=h;C||(L--,x.monitorRunDependencies&&x.monitorRunDependencies(L),0==L&&(null!==La&&(clearInterval(La),La=null),M&&(f=M,M=null,f())))}function b(f){a(f.instance,f.module)}function c(f){return Oa().then(function(h){return WebAssembly.instantiate(h,e)}).then(function(h){return h}).then(f,function(h){G("failed to asynchronously prepare wasm: "+h);I(h)})}var e={a:Pc};C||(L++,x.monitorRunDependencies&&x.monitorRunDependencies(L));
+if(x.instantiateWasm)try{return x.instantiateWasm(e,a)}catch(f){return G("Module.instantiateWasm callback failed with error: "+f),!1}(function(){return H||"function"!=typeof WebAssembly.instantiateStreaming||Ma()||O.startsWith("file://")||B||"function"!=typeof fetch?c(b):fetch(O,{credentials:"same-origin"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(b,function(h){G("wasm streaming compile failed: "+h);G("falling back to ArrayBuffer instantiation");return c(b)})})})().catch(ia);
+return{}})();x.___wasm_call_ctors=function(){return(x.___wasm_call_ctors=x.asm.Va).apply(null,arguments)};x._OrtInit=function(){return(x._OrtInit=x.asm.Wa).apply(null,arguments)};x._OrtCreateSessionOptions=function(){return(x._OrtCreateSessionOptions=x.asm.Xa).apply(null,arguments)};x._OrtAppendExecutionProvider=function(){return(x._OrtAppendExecutionProvider=x.asm.Ya).apply(null,arguments)};x._OrtAddSessionConfigEntry=function(){return(x._OrtAddSessionConfigEntry=x.asm.Za).apply(null,arguments)};
+x._OrtReleaseSessionOptions=function(){return(x._OrtReleaseSessionOptions=x.asm._a).apply(null,arguments)};x._OrtCreateSession=function(){return(x._OrtCreateSession=x.asm.$a).apply(null,arguments)};x._OrtReleaseSession=function(){return(x._OrtReleaseSession=x.asm.ab).apply(null,arguments)};x._OrtGetInputCount=function(){return(x._OrtGetInputCount=x.asm.bb).apply(null,arguments)};x._OrtGetOutputCount=function(){return(x._OrtGetOutputCount=x.asm.cb).apply(null,arguments)};
+x._OrtGetInputName=function(){return(x._OrtGetInputName=x.asm.db).apply(null,arguments)};x._OrtGetOutputName=function(){return(x._OrtGetOutputName=x.asm.eb).apply(null,arguments)};x._OrtFree=function(){return(x._OrtFree=x.asm.fb).apply(null,arguments)};x._OrtCreateTensor=function(){return(x._OrtCreateTensor=x.asm.gb).apply(null,arguments)};x._OrtGetTensorData=function(){return(x._OrtGetTensorData=x.asm.hb).apply(null,arguments)};
+x._OrtReleaseTensor=function(){return(x._OrtReleaseTensor=x.asm.ib).apply(null,arguments)};x._OrtCreateRunOptions=function(){return(x._OrtCreateRunOptions=x.asm.jb).apply(null,arguments)};x._OrtAddRunConfigEntry=function(){return(x._OrtAddRunConfigEntry=x.asm.kb).apply(null,arguments)};x._OrtReleaseRunOptions=function(){return(x._OrtReleaseRunOptions=x.asm.lb).apply(null,arguments)};x._OrtRun=function(){return(x._OrtRun=x.asm.mb).apply(null,arguments)};
+x._OrtEndProfiling=function(){return(x._OrtEndProfiling=x.asm.nb).apply(null,arguments)};var $a=x._pthread_self=function(){return($a=x._pthread_self=x.asm.ob).apply(null,arguments)},Fb=x._malloc=function(){return(Fb=x._malloc=x.asm.pb).apply(null,arguments)},kb=x._free=function(){return(kb=x._free=x.asm.qb).apply(null,arguments)},Wa=x._fflush=function(){return(Wa=x._fflush=x.asm.rb).apply(null,arguments)};x.__emscripten_tls_init=function(){return(x.__emscripten_tls_init=x.asm.sb).apply(null,arguments)};
+var Va=x.___funcs_on_exit=function(){return(Va=x.___funcs_on_exit=x.asm.tb).apply(null,arguments)},ec=x.__emscripten_thread_init=function(){return(ec=x.__emscripten_thread_init=x.asm.vb).apply(null,arguments)};x.__emscripten_thread_crashed=function(){return(x.__emscripten_thread_crashed=x.asm.wb).apply(null,arguments)};
+var Lb=x._emscripten_run_in_main_runtime_thread_js=function(){return(Lb=x._emscripten_run_in_main_runtime_thread_js=x.asm.xb).apply(null,arguments)},Ab=x.__emscripten_proxy_execute_task_queue=function(){return(Ab=x.__emscripten_proxy_execute_task_queue=x.asm.yb).apply(null,arguments)},Za=x.__emscripten_thread_free_data=function(){return(Za=x.__emscripten_thread_free_data=x.asm.zb).apply(null,arguments)},eb=x.__emscripten_thread_exit=function(){return(eb=x.__emscripten_thread_exit=x.asm.Ab).apply(null,
+arguments)},Z=x._setThrew=function(){return(Z=x._setThrew=x.asm.Bb).apply(null,arguments)},cb=x._emscripten_stack_set_limits=function(){return(cb=x._emscripten_stack_set_limits=x.asm.Cb).apply(null,arguments)},S=x.stackSave=function(){return(S=x.stackSave=x.asm.Db).apply(null,arguments)},U=x.stackRestore=function(){return(U=x.stackRestore=x.asm.Eb).apply(null,arguments)},Kb=x.stackAlloc=function(){return(Kb=x.stackAlloc=x.asm.Fb).apply(null,arguments)},dc=x.___cxa_can_catch=function(){return(dc=x.___cxa_can_catch=
+x.asm.Gb).apply(null,arguments)},ib=x.___cxa_is_pointer_type=function(){return(ib=x.___cxa_is_pointer_type=x.asm.Hb).apply(null,arguments)},Qc=x.dynCall_j=function(){return(Qc=x.dynCall_j=x.asm.Ib).apply(null,arguments)},Rc=x.dynCall_iiiiij=function(){return(Rc=x.dynCall_iiiiij=x.asm.Jb).apply(null,arguments)},Sc=x.dynCall_jii=function(){return(Sc=x.dynCall_jii=x.asm.Kb).apply(null,arguments)},Tc=x.dynCall_viiiiij=function(){return(Tc=x.dynCall_viiiiij=x.asm.Lb).apply(null,arguments)},Uc=x.dynCall_vjji=
+function(){return(Uc=x.dynCall_vjji=x.asm.Mb).apply(null,arguments)},Vc=x.dynCall_viiijjjii=function(){return(Vc=x.dynCall_viiijjjii=x.asm.Nb).apply(null,arguments)},Wc=x.dynCall_iij=function(){return(Wc=x.dynCall_iij=x.asm.Ob).apply(null,arguments)},Xc=x.dynCall_ji=function(){return(Xc=x.dynCall_ji=x.asm.Pb).apply(null,arguments)},Yc=x.dynCall_iiiiiij=function(){return(Yc=x.dynCall_iiiiiij=x.asm.Qb).apply(null,arguments)},Zc=x.dynCall_iiij=function(){return(Zc=x.dynCall_iiij=x.asm.Rb).apply(null,
+arguments)};function ic(a,b){var c=S();try{return V(a)(b)}catch(e){U(c);if(e!==e+0)throw e;Z(1,0)}}function Bc(a,b){var c=S();try{V(a)(b)}catch(e){U(c);if(e!==e+0)throw e;Z(1,0)}}function Cc(a,b,c){var e=S();try{V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function lc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function mc(a,b,c,e){var f=S();try{return V(a)(b,c,e)}catch(h){U(f);if(h!==h+0)throw h;Z(1,0)}}
+function qc(a,b,c,e,f,h,k){var l=S();try{return V(a)(b,c,e,f,h,k)}catch(u){U(l);if(u!==u+0)throw u;Z(1,0)}}function Ac(a){var b=S();try{V(a)()}catch(c){U(b);if(c!==c+0)throw c;Z(1,0)}}function pc(a,b,c,e,f,h){var k=S();try{return V(a)(b,c,e,f,h)}catch(l){U(k);if(l!==l+0)throw l;Z(1,0)}}function nc(a,b,c,e,f){var h=S();try{return V(a)(b,c,e,f)}catch(k){U(h);if(k!==k+0)throw k;Z(1,0)}}function Ec(a,b,c,e){var f=S();try{V(a)(b,c,e)}catch(h){U(f);if(h!==h+0)throw h;Z(1,0)}}
+function Gc(a,b,c,e,f,h){var k=S();try{V(a)(b,c,e,f,h)}catch(l){U(k);if(l!==l+0)throw l;Z(1,0)}}function Fc(a,b,c,e,f){var h=S();try{V(a)(b,c,e,f)}catch(k){U(h);if(k!==k+0)throw k;Z(1,0)}}function Ic(a,b,c,e,f,h,k,l){var u=S();try{V(a)(b,c,e,f,h,k,l)}catch(t){U(u);if(t!==t+0)throw t;Z(1,0)}}function kc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function jc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}
+function Jc(a,b,c,e,f,h,k,l,u){var t=S();try{V(a)(b,c,e,f,h,k,l,u)}catch(A){U(t);if(A!==A+0)throw A;Z(1,0)}}function Hc(a,b,c,e,f,h,k){var l=S();try{V(a)(b,c,e,f,h,k)}catch(u){U(l);if(u!==u+0)throw u;Z(1,0)}}function oc(a,b,c,e,f,h){var k=S();try{return V(a)(b,c,e,f,h)}catch(l){U(k);if(l!==l+0)throw l;Z(1,0)}}function rc(a,b,c,e,f,h,k,l){var u=S();try{return V(a)(b,c,e,f,h,k,l)}catch(t){U(u);if(t!==t+0)throw t;Z(1,0)}}
+function sc(a,b,c,e,f,h,k,l,u,t,A,K){var J=S();try{return V(a)(b,c,e,f,h,k,l,u,t,A,K)}catch(g){U(J);if(g!==g+0)throw g;Z(1,0)}}function Kc(a,b,c,e,f,h,k,l,u,t,A){var K=S();try{V(a)(b,c,e,f,h,k,l,u,t,A)}catch(J){U(K);if(J!==J+0)throw J;Z(1,0)}}function Lc(a,b,c,e,f,h,k,l,u,t,A,K,J,g,w,z){var N=S();try{V(a)(b,c,e,f,h,k,l,u,t,A,K,J,g,w,z)}catch(T){U(N);if(T!==T+0)throw T;Z(1,0)}}function hc(a){var b=S();try{return V(a)()}catch(c){U(b);if(c!==c+0)throw c;Z(1,0)}}
+function gc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function fc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function Dc(a,b,c,e){var f=S();try{V(a)(b,c,e)}catch(h){U(f);if(h!==h+0)throw h;Z(1,0)}}function Mc(a,b,c,e,f,h,k,l){var u=S();try{Tc(a,b,c,e,f,h,k,l)}catch(t){U(u);if(t!==t+0)throw t;Z(1,0)}}function Oc(a,b,c,e,f,h){var k=S();try{Uc(a,b,c,e,f,h)}catch(l){U(k);if(l!==l+0)throw l;Z(1,0)}}
+function Nc(a,b,c,e,f,h,k,l,u,t,A,K){var J=S();try{Vc(a,b,c,e,f,h,k,l,u,t,A,K)}catch(g){U(J);if(g!==g+0)throw g;Z(1,0)}}function wc(a,b,c,e){var f=S();try{return Wc(a,b,c,e)}catch(h){U(f);if(h!==h+0)throw h;Z(1,0)}}function yc(a,b){var c=S();try{return Xc(a,b)}catch(e){U(c);if(e!==e+0)throw e;Z(1,0)}}function tc(a,b,c,e,f,h,k,l){var u=S();try{return Yc(a,b,c,e,f,h,k,l)}catch(t){U(u);if(t!==t+0)throw t;Z(1,0)}}function xc(a){var b=S();try{return Qc(a)}catch(c){U(b);if(c!==c+0)throw c;Z(1,0)}}
+function uc(a,b,c,e,f,h,k){var l=S();try{return Rc(a,b,c,e,f,h,k)}catch(u){U(l);if(u!==u+0)throw u;Z(1,0)}}function vc(a,b,c,e,f){var h=S();try{return Zc(a,b,c,e,f)}catch(k){U(h);if(k!==k+0)throw k;Z(1,0)}}function zc(a,b,c){var e=S();try{return Sc(a,b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}x.UTF8ToString=Aa;x.stringToUTF8=function(a,b,c){return Ba(a,q(),b,c)};x.lengthBytesUTF8=Ca;x.keepRuntimeAlive=F;x.wasmMemory=m;x.stackSave=S;x.stackRestore=U;x.stackAlloc=Kb;x.ExitStatus=E;x.PThread=P;var $c;
+M=function ad(){$c||bd();$c||(M=ad)};
+function bd(){function a(){if(!$c&&($c=!0,x.calledRun=!0,!xa)){C||R(Ga);ha(x);if(x.onRuntimeInitialized)x.onRuntimeInitialized();if(!C){if(x.postRun)for("function"==typeof x.postRun&&(x.postRun=[x.postRun]);x.postRun.length;){var b=x.postRun.shift();Ia.unshift(b)}R(Ia)}}}if(!(0<L))if(C)ha(x),C||R(Ga),postMessage({cmd:"loaded"});else{if(x.preRun)for("function"==typeof x.preRun&&(x.preRun=[x.preRun]);x.preRun.length;)Ka();R(Fa);0<L||(x.setStatus?(x.setStatus("Running..."),setTimeout(function(){setTimeout(function(){x.setStatus("")},
+1);a()},1)):a())}}if(x.preInit)for("function"==typeof x.preInit&&(x.preInit=[x.preInit]);0<x.preInit.length;)x.preInit.pop()();bd();
+
+
+ return ortWasmThreaded.ready
+}
+);
+})();
+if (true)
+ module.exports = ortWasmThreaded;
+else {}
+
+
+/***/ }),
+
+/***/ "./lib/wasm/binding/ort-wasm.js":
+/*!**************************************!*\
+ !*** ./lib/wasm/binding/ort-wasm.js ***!
+ \**************************************/
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+var __filename = "/index.js";
+var __dirname = "/";
+
+var ortWasm = (() => {
+ var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;
+ if (true) _scriptDir = _scriptDir || __filename;
+ return (
+function(ortWasm) {
+ ortWasm = ortWasm || {};
+
+
+var d;d||(d=typeof ortWasm !== 'undefined' ? ortWasm : {});var aa,ba;d.ready=new Promise(function(a,b){aa=a;ba=b});var ca=Object.assign({},d),da="./this.program",ea=(a,b)=>{throw b;},fa="object"==typeof window,m="function"==typeof importScripts,p="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,q="",ha,r,v,fs,y,ia;
+if(p)q=m?(__webpack_require__(/*! path */ "?75c6").dirname)(q)+"/":__dirname+"/",ia=()=>{y||(fs=__webpack_require__(/*! fs */ "?63c8"),y=__webpack_require__(/*! path */ "?75c6"))},ha=function(a,b){ia();a=y.normalize(a);return fs.readFileSync(a,b?void 0:"utf8")},v=a=>{a=ha(a,!0);a.buffer||(a=new Uint8Array(a));return a},r=(a,b,c)=>{ia();a=y.normalize(a);fs.readFile(a,function(e,f){e?c(e):b(f.buffer)})},1<process.argv.length&&(da=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",function(a){if(!(a instanceof ja))throw a;}),process.on("unhandledRejection",
+function(a){throw a;}),ea=(a,b)=>{if(noExitRuntime||0<ka)throw process.exitCode=a,b;b instanceof ja||z("exiting due to exception: "+b);process.exit(a)},d.inspect=function(){return"[Emscripten Module object]"};else if(fa||m)m?q=self.location.href:"undefined"!=typeof document&&document.currentScript&&(q=document.currentScript.src),_scriptDir&&(q=_scriptDir),0!==q.indexOf("blob:")?q=q.substr(0,q.replace(/[?#].*/,"").lastIndexOf("/")+1):q="",ha=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.send(null);
+return b.responseText},m&&(v=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer";b.send(null);return new Uint8Array(b.response)}),r=(a,b,c)=>{var e=new XMLHttpRequest;e.open("GET",a,!0);e.responseType="arraybuffer";e.onload=()=>{200==e.status||0==e.status&&e.response?b(e.response):c()};e.onerror=c;e.send(null)};var la=d.print||console.log.bind(console),z=d.printErr||console.warn.bind(console);Object.assign(d,ca);ca=null;d.thisProgram&&(da=d.thisProgram);d.quit&&(ea=d.quit);
+var A;d.wasmBinary&&(A=d.wasmBinary);var noExitRuntime=d.noExitRuntime||!1;"object"!=typeof WebAssembly&&B("no native wasm support detected");var ma,D=!1,na="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;
+function oa(a,b,c){b>>>=0;var e=b+c;for(c=b;a[c]&&!(c>=e);)++c;if(16<c-b&&a.buffer&&na)return na.decode(a.subarray(b,c));for(e="";b<c;){var f=a[b++];if(f&128){var h=a[b++]&63;if(192==(f&224))e+=String.fromCharCode((f&31)<<6|h);else{var k=a[b++]&63;f=224==(f&240)?(f&15)<<12|h<<6|k:(f&7)<<18|h<<12|k<<6|a[b++]&63;65536>f?e+=String.fromCharCode(f):(f-=65536,e+=String.fromCharCode(55296|f>>10,56320|f&1023))}}else e+=String.fromCharCode(f)}return e}function pa(a,b){return(a>>>=0)?oa(G,a,b):""}
+function qa(a,b,c,e){c>>>=0;if(!(0<e))return 0;var f=c;e=c+e-1;for(var h=0;h<a.length;++h){var k=a.charCodeAt(h);if(55296<=k&&57343>=k){var l=a.charCodeAt(++h);k=65536+((k&1023)<<10)|l&1023}if(127>=k){if(c>=e)break;b[c++>>>0]=k}else{if(2047>=k){if(c+1>=e)break;b[c++>>>0]=192|k>>6}else{if(65535>=k){if(c+2>=e)break;b[c++>>>0]=224|k>>12}else{if(c+3>=e)break;b[c++>>>0]=240|k>>18;b[c++>>>0]=128|k>>12&63}b[c++>>>0]=128|k>>6&63}b[c++>>>0]=128|k&63}}b[c>>>0]=0;return c-f}
+function ra(a){for(var b=0,c=0;c<a.length;++c){var e=a.charCodeAt(c);127>=e?b++:2047>=e?b+=2:55296<=e&&57343>=e?(b+=4,++c):b+=3}return b}var sa,H,G,I,J;function ta(){var a=ma.buffer;sa=a;d.HEAP8=H=new Int8Array(a);d.HEAP16=new Int16Array(a);d.HEAP32=I=new Int32Array(a);d.HEAPU8=G=new Uint8Array(a);d.HEAPU16=new Uint16Array(a);d.HEAPU32=J=new Uint32Array(a);d.HEAPF32=new Float32Array(a);d.HEAPF64=new Float64Array(a)}var ua,va=[],wa=[],xa=[],ya=[],ka=0;
+function za(){var a=d.preRun.shift();va.unshift(a)}var K=0,Aa=null,L=null;function B(a){if(d.onAbort)d.onAbort(a);a="Aborted("+a+")";z(a);D=!0;a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info.");ba(a);throw a;}function Ba(){return N.startsWith("data:application/octet-stream;base64,")}var N;N="ort-wasm.wasm";if(!Ba()){var Ca=N;N=d.locateFile?d.locateFile(Ca,q):q+Ca}
+function Da(){var a=N;try{if(a==N&&A)return new Uint8Array(A);if(v)return v(a);throw"both async and sync fetching of the wasm failed";}catch(b){B(b)}}
+function Ea(){if(!A&&(fa||m)){if("function"==typeof fetch&&!N.startsWith("file://"))return fetch(N,{credentials:"same-origin"}).then(function(a){if(!a.ok)throw"failed to load wasm binary file at '"+N+"'";return a.arrayBuffer()}).catch(function(){return Da()});if(r)return new Promise(function(a,b){r(N,function(c){a(new Uint8Array(c))},b)})}return Promise.resolve().then(function(){return Da()})}function ja(a){this.name="ExitStatus";this.message="Program terminated with exit("+a+")";this.status=a}
+function O(a){for(;0<a.length;)a.shift()(d)}var P=[],Q=0,R=0;
+function S(a){this.Db=a;this.zb=a-24;this.Ub=function(b){J[this.zb+4>>2>>>0]=b};this.Eb=function(){return J[this.zb+4>>2>>>0]};this.Sb=function(b){J[this.zb+8>>2>>>0]=b};this.Wb=function(){return J[this.zb+8>>2>>>0]};this.Tb=function(){I[this.zb>>2>>>0]=0};this.Ib=function(b){H[this.zb+12>>0>>>0]=b?1:0};this.Pb=function(){return 0!=H[this.zb+12>>0>>>0]};this.Jb=function(b){H[this.zb+13>>0>>>0]=b?1:0};this.Lb=function(){return 0!=H[this.zb+13>>0>>>0]};this.Rb=function(b,c){this.Fb(0);this.Ub(b);this.Sb(c);
+this.Tb();this.Ib(!1);this.Jb(!1)};this.Nb=function(){I[this.zb>>2>>>0]+=1};this.Xb=function(){var b=I[this.zb>>2>>>0];I[this.zb>>2>>>0]=b-1;return 1===b};this.Fb=function(b){J[this.zb+16>>2>>>0]=b};this.Ob=function(){return J[this.zb+16>>2>>>0]};this.Qb=function(){if(Fa(this.Eb()))return J[this.Db>>2>>>0];var b=this.Ob();return 0!==b?b:this.Db}}function Ga(a){return Ha((new S(a)).zb)}var T=[];function U(a){var b=T[a];b||(a>=T.length&&(T.length=a+1),T[a]=b=ua.get(a));return b}
+function Ia(a){var b=ra(a)+1,c=Ja(b);c&&qa(a,H,c,b);return c}function Ka(a,b,c){function e(n){return(n=n.toTimeString().match(/\(([A-Za-z ]+)\)$/))?n[1]:"GMT"}var f=(new Date).getFullYear(),h=new Date(f,0,1),k=new Date(f,6,1);f=h.getTimezoneOffset();var l=k.getTimezoneOffset();I[a>>2>>>0]=60*Math.max(f,l);I[b>>2>>>0]=Number(f!=l);a=e(h);b=e(k);a=Ia(a);b=Ia(b);l<f?(J[c>>2>>>0]=a,J[c+4>>2>>>0]=b):(J[c>>2>>>0]=b,J[c+4>>2>>>0]=a)}function La(a,b,c){La.Vb||(La.Vb=!0,Ka(a,b,c))}var Ma={};
+function Na(){if(!Oa){var a={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",_:da||"./this.program"},b;for(b in Ma)void 0===Ma[b]?delete a[b]:a[b]=Ma[b];var c=[];for(b in a)c.push(b+"="+a[b]);Oa=c}return Oa}var Oa,Pa=[null,[],[]];function Qa(a,b){var c=Pa[a];0===b||10===b?((1===a?la:z)(oa(c,0)),c.length=0):c.push(b)}var V=0;
+function Ra(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var a=new Uint8Array(1);return()=>{crypto.getRandomValues(a);return a[0]}}if(p)try{var b=__webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module 'crypto'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()));return()=>b.randomBytes(1)[0]}catch(c){}return()=>B("randomDevice")}function W(a,b){W.Mb||(W.Mb=Ra());for(var c=0;c<b;c++)H[a+c>>0>>>0]=W.Mb();return 0}function Sa(a){return 0===a%4&&(0!==a%100||0===a%400)}var Ta=[31,29,31,30,31,30,31,31,30,31,30,31],Ua=[31,28,31,30,31,30,31,31,30,31,30,31];
+function Va(a){var b=Array(ra(a)+1);qa(a,b,0,b.length);return b}
+function Wa(a,b,c,e){function f(g,u,w){for(g="number"==typeof g?g.toString():g||"";g.length<u;)g=w[0]+g;return g}function h(g,u){return f(g,u,"0")}function k(g,u){function w(M){return 0>M?-1:0<M?1:0}var F;0===(F=w(g.getFullYear()-u.getFullYear()))&&0===(F=w(g.getMonth()-u.getMonth()))&&(F=w(g.getDate()-u.getDate()));return F}function l(g){switch(g.getDay()){case 0:return new Date(g.getFullYear()-1,11,29);case 1:return g;case 2:return new Date(g.getFullYear(),0,3);case 3:return new Date(g.getFullYear(),
+0,2);case 4:return new Date(g.getFullYear(),0,1);case 5:return new Date(g.getFullYear()-1,11,31);case 6:return new Date(g.getFullYear()-1,11,30)}}function n(g){var u=g.Bb;for(g=new Date((new Date(g.Cb+1900,0,1)).getTime());0<u;){var w=g.getMonth(),F=(Sa(g.getFullYear())?Ta:Ua)[w];if(u>F-g.getDate())u-=F-g.getDate()+1,g.setDate(1),11>w?g.setMonth(w+1):(g.setMonth(0),g.setFullYear(g.getFullYear()+1));else{g.setDate(g.getDate()+u);break}}w=new Date(g.getFullYear()+1,0,4);u=l(new Date(g.getFullYear(),
+0,4));w=l(w);return 0>=k(u,g)?0>=k(w,g)?g.getFullYear()+1:g.getFullYear():g.getFullYear()-1}var t=I[e+40>>2>>>0];e={$b:I[e>>2>>>0],Zb:I[e+4>>2>>>0],Gb:I[e+8>>2>>>0],Kb:I[e+12>>2>>>0],Hb:I[e+16>>2>>>0],Cb:I[e+20>>2>>>0],Ab:I[e+24>>2>>>0],Bb:I[e+28>>2>>>0],bc:I[e+32>>2>>>0],Yb:I[e+36>>2>>>0],ac:t?pa(t):""};c=pa(c);t={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y",
+"%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var x in t)c=c.replace(new RegExp(x,"g"),t[x]);var E="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),C="January February March April May June July August September October November December".split(" ");t={"%a":function(g){return E[g.Ab].substring(0,3)},"%A":function(g){return E[g.Ab]},"%b":function(g){return C[g.Hb].substring(0,
+3)},"%B":function(g){return C[g.Hb]},"%C":function(g){return h((g.Cb+1900)/100|0,2)},"%d":function(g){return h(g.Kb,2)},"%e":function(g){return f(g.Kb,2," ")},"%g":function(g){return n(g).toString().substring(2)},"%G":function(g){return n(g)},"%H":function(g){return h(g.Gb,2)},"%I":function(g){g=g.Gb;0==g?g=12:12<g&&(g-=12);return h(g,2)},"%j":function(g){for(var u=0,w=0;w<=g.Hb-1;u+=(Sa(g.Cb+1900)?Ta:Ua)[w++]);return h(g.Kb+u,3)},"%m":function(g){return h(g.Hb+1,2)},"%M":function(g){return h(g.Zb,
+2)},"%n":function(){return"\n"},"%p":function(g){return 0<=g.Gb&&12>g.Gb?"AM":"PM"},"%S":function(g){return h(g.$b,2)},"%t":function(){return"\t"},"%u":function(g){return g.Ab||7},"%U":function(g){return h(Math.floor((g.Bb+7-g.Ab)/7),2)},"%V":function(g){var u=Math.floor((g.Bb+7-(g.Ab+6)%7)/7);2>=(g.Ab+371-g.Bb-2)%7&&u++;if(u)53==u&&(w=(g.Ab+371-g.Bb)%7,4==w||3==w&&Sa(g.Cb)||(u=1));else{u=52;var w=(g.Ab+7-g.Bb-1)%7;(4==w||5==w&&Sa(g.Cb%400-1))&&u++}return h(u,2)},"%w":function(g){return g.Ab},"%W":function(g){return h(Math.floor((g.Bb+
+7-(g.Ab+6)%7)/7),2)},"%y":function(g){return(g.Cb+1900).toString().substring(2)},"%Y":function(g){return g.Cb+1900},"%z":function(g){g=g.Yb;var u=0<=g;g=Math.abs(g)/60;return(u?"+":"-")+String("0000"+(g/60*100+g%60)).slice(-4)},"%Z":function(g){return g.ac},"%%":function(){return"%"}};c=c.replace(/%%/g,"\x00\x00");for(x in t)c.includes(x)&&(c=c.replace(new RegExp(x,"g"),t[x](e)));c=c.replace(/\0\0/g,"%");x=Va(c);if(x.length>b)return 0;H.set(x,a>>>0);return x.length-1}
+var Jb={a:function(a){return Ja(a+24)+24},m:function(a){a=new S(a);a.Pb()||(a.Ib(!0),Q--);a.Jb(!1);P.push(a);a.Nb();return a.Qb()},ia:function(a){z("Unexpected exception thrown, this is not properly supported - aborting");D=!0;throw a;},w:function(){X(0);var a=P.pop();if(a.Xb()&&!a.Lb()){var b=a.Wb();b&&U(b)(a.Db);Ga(a.Db)}R=0},d:function(){var a=R;if(!a)return V=0;var b=new S(a);b.Fb(a);var c=b.Eb();if(!c)return V=0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];
+if(0===h||h===c)break;if(Xa(h,c,b.zb+16))return V=h,a}V=c;return a},k:function(){var a=R;if(!a)return V=0;var b=new S(a);b.Fb(a);var c=b.Eb();if(!c)return V=0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;if(Xa(h,c,b.zb+16))return V=h,a}V=c;return a},g:function(){var a=R;if(!a)return V=0;var b=new S(a);b.Fb(a);var c=b.Eb();if(!c)return V=0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;
+if(Xa(h,c,b.zb+16))return V=h,a}V=c;return a},s:Ga,L:function(){var a=P.pop();a||B("no exception to throw");var b=a.Db;a.Lb()||(P.push(a),a.Jb(!0),a.Ib(!1),Q++);R=b;throw b;},b:function(a,b,c){(new S(a)).Rb(b,c);R=a;Q++;throw a;},la:function(){return Q},i:function(a){R||(R=a);throw a;},H:function(){return 0},Ba:function(){},pa:function(){},ra:function(){},ka:function(){return 0},za:function(){},ua:function(){},ya:function(){},R:function(){},qa:function(){},na:function(){},Aa:function(){},oa:function(){},
+Ha:function(){},Ja:function(){B("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ia:function(){B("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},S:function(){return Date.now()},Ca:function(){return!0},Da:function(a,b){a=new Date(1E3*(J[a>>>2]+4294967296*I[a+4>>>2]));I[b>>2>>>0]=a.getUTCSeconds();I[b+4>>2>>>0]=a.getUTCMinutes();I[b+8>>2>>>0]=a.getUTCHours();I[b+12>>2>>>
+0]=a.getUTCDate();I[b+16>>2>>>0]=a.getUTCMonth();I[b+20>>2>>>0]=a.getUTCFullYear()-1900;I[b+24>>2>>>0]=a.getUTCDay();I[b+28>>2>>>0]=(a.getTime()-Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0))/864E5|0},Ea:function(a,b){a=new Date(1E3*(J[a>>>2]+4294967296*I[a+4>>>2]));I[b>>2>>>0]=a.getSeconds();I[b+4>>2>>>0]=a.getMinutes();I[b+8>>2>>>0]=a.getHours();I[b+12>>2>>>0]=a.getDate();I[b+16>>2>>>0]=a.getMonth();I[b+20>>2>>>0]=a.getFullYear()-1900;I[b+24>>2>>>0]=a.getDay();var c=new Date(a.getFullYear(),0,1);I[b+
+28>>2>>>0]=(a.getTime()-c.getTime())/864E5|0;I[b+36>>2>>>0]=-(60*a.getTimezoneOffset());var e=(new Date(a.getFullYear(),6,1)).getTimezoneOffset();c=c.getTimezoneOffset();I[b+32>>2>>>0]=(e!=c&&a.getTimezoneOffset()==Math.min(c,e))|0},Fa:function(a){var b=new Date(I[a+20>>2>>>0]+1900,I[a+16>>2>>>0],I[a+12>>2>>>0],I[a+8>>2>>>0],I[a+4>>2>>>0],I[a>>2>>>0],0),c=I[a+32>>2>>>0],e=b.getTimezoneOffset(),f=new Date(b.getFullYear(),0,1),h=(new Date(b.getFullYear(),6,1)).getTimezoneOffset(),k=f.getTimezoneOffset(),
+l=Math.min(k,h);0>c?I[a+32>>2>>>0]=Number(h!=k&&l==e):0<c!=(l==e)&&(h=Math.max(k,h),b.setTime(b.getTime()+6E4*((0<c?l:h)-e)));I[a+24>>2>>>0]=b.getDay();I[a+28>>2>>>0]=(b.getTime()-f.getTime())/864E5|0;I[a>>2>>>0]=b.getSeconds();I[a+4>>2>>>0]=b.getMinutes();I[a+8>>2>>>0]=b.getHours();I[a+12>>2>>>0]=b.getDate();I[a+16>>2>>>0]=b.getMonth();return b.getTime()/1E3|0},sa:function(){return-52},ta:function(){},Ga:La,B:function(){B("")},ma:function(){return 4294901760},I:p?()=>{var a=process.hrtime();return 1E3*
+a[0]+a[1]/1E6}:()=>performance.now(),xa:function(a,b,c){G.copyWithin(a>>>0,b>>>0,b+c>>>0)},G:function(a){var b=G.length;a>>>=0;if(4294901760<a)return!1;for(var c=1;4>=c;c*=2){var e=b*(1+.2/c);e=Math.min(e,a+100663296);var f=Math;e=Math.max(a,e);f=f.min.call(f,4294901760,e+(65536-e%65536)%65536);a:{try{ma.grow(f-sa.byteLength+65535>>>16);ta();var h=1;break a}catch(k){}h=void 0}if(h)return!0}return!1},va:function(a,b){var c=0;Na().forEach(function(e,f){var h=b+c;f=J[a+4*f>>2>>>0]=h;for(h=0;h<e.length;++h)H[f++>>
+0>>>0]=e.charCodeAt(h);H[f>>0>>>0]=0;c+=e.length+1});return 0},wa:function(a,b){var c=Na();J[a>>2>>>0]=c.length;var e=0;c.forEach(function(f){e+=f.length+1});J[b>>2>>>0]=e;return 0},ba:function(a){noExitRuntime||0<ka||(Ya(),O(xa),Za(0),Pa[1].length&&Qa(1,10),Pa[2].length&&Qa(2,10));if(!(noExitRuntime||0<ka)){if(d.onExit)d.onExit(a);D=!0}ea(a,new ja(a))},E:function(){return 52},Q:function(){return 52},ca:function(){return 70},P:function(a,b,c,e){for(var f=0,h=0;h<c;h++){var k=J[b>>2>>>0],l=J[b+4>>
+2>>>0];b+=8;for(var n=0;n<l;n++)Qa(a,G[k+n>>>0]);f+=l}J[e>>2>>>0]=f;return 0},c:function(){return V},ja:W,ea:$a,fa:ab,J:bb,e:cb,N:db,O:eb,j:fb,o:gb,p:hb,M:ib,r:jb,v:kb,K:lb,D:mb,X:nb,V:ob,U:pb,Z:qb,W:rb,Y:sb,T:tb,f:ub,q:vb,h:wb,da:xb,l:yb,t:zb,u:Ab,x:Bb,z:Cb,ga:Db,A:Eb,C:Fb,aa:Gb,_:Hb,$:Ib,n:function(a){return a},F:function(a){V=a},ha:Wa,y:function(a,b,c,e){return Wa(a,b,c,e)}};
+(function(){function a(f){d.asm=f.exports;ma=d.asm.Ka;ta();ua=d.asm.ib;wa.unshift(d.asm.La);K--;d.monitorRunDependencies&&d.monitorRunDependencies(K);0==K&&(null!==Aa&&(clearInterval(Aa),Aa=null),L&&(f=L,L=null,f()))}function b(f){a(f.instance)}function c(f){return Ea().then(function(h){return WebAssembly.instantiate(h,e)}).then(function(h){return h}).then(f,function(h){z("failed to asynchronously prepare wasm: "+h);B(h)})}var e={a:Jb};K++;d.monitorRunDependencies&&d.monitorRunDependencies(K);if(d.instantiateWasm)try{return d.instantiateWasm(e,
+a)}catch(f){return z("Module.instantiateWasm callback failed with error: "+f),!1}(function(){return A||"function"!=typeof WebAssembly.instantiateStreaming||Ba()||N.startsWith("file://")||p||"function"!=typeof fetch?c(b):fetch(N,{credentials:"same-origin"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(b,function(h){z("wasm streaming compile failed: "+h);z("falling back to ArrayBuffer instantiation");return c(b)})})})().catch(ba);return{}})();
+d.___wasm_call_ctors=function(){return(d.___wasm_call_ctors=d.asm.La).apply(null,arguments)};d._OrtInit=function(){return(d._OrtInit=d.asm.Ma).apply(null,arguments)};d._OrtCreateSessionOptions=function(){return(d._OrtCreateSessionOptions=d.asm.Na).apply(null,arguments)};d._OrtAppendExecutionProvider=function(){return(d._OrtAppendExecutionProvider=d.asm.Oa).apply(null,arguments)};d._OrtAddSessionConfigEntry=function(){return(d._OrtAddSessionConfigEntry=d.asm.Pa).apply(null,arguments)};
+d._OrtReleaseSessionOptions=function(){return(d._OrtReleaseSessionOptions=d.asm.Qa).apply(null,arguments)};d._OrtCreateSession=function(){return(d._OrtCreateSession=d.asm.Ra).apply(null,arguments)};d._OrtReleaseSession=function(){return(d._OrtReleaseSession=d.asm.Sa).apply(null,arguments)};d._OrtGetInputCount=function(){return(d._OrtGetInputCount=d.asm.Ta).apply(null,arguments)};d._OrtGetOutputCount=function(){return(d._OrtGetOutputCount=d.asm.Ua).apply(null,arguments)};
+d._OrtGetInputName=function(){return(d._OrtGetInputName=d.asm.Va).apply(null,arguments)};d._OrtGetOutputName=function(){return(d._OrtGetOutputName=d.asm.Wa).apply(null,arguments)};d._OrtFree=function(){return(d._OrtFree=d.asm.Xa).apply(null,arguments)};d._OrtCreateTensor=function(){return(d._OrtCreateTensor=d.asm.Ya).apply(null,arguments)};d._OrtGetTensorData=function(){return(d._OrtGetTensorData=d.asm.Za).apply(null,arguments)};
+d._OrtReleaseTensor=function(){return(d._OrtReleaseTensor=d.asm._a).apply(null,arguments)};d._OrtCreateRunOptions=function(){return(d._OrtCreateRunOptions=d.asm.$a).apply(null,arguments)};d._OrtAddRunConfigEntry=function(){return(d._OrtAddRunConfigEntry=d.asm.ab).apply(null,arguments)};d._OrtReleaseRunOptions=function(){return(d._OrtReleaseRunOptions=d.asm.bb).apply(null,arguments)};d._OrtRun=function(){return(d._OrtRun=d.asm.cb).apply(null,arguments)};
+d._OrtEndProfiling=function(){return(d._OrtEndProfiling=d.asm.db).apply(null,arguments)};
+var Ja=d._malloc=function(){return(Ja=d._malloc=d.asm.eb).apply(null,arguments)},Ha=d._free=function(){return(Ha=d._free=d.asm.fb).apply(null,arguments)},Za=d._fflush=function(){return(Za=d._fflush=d.asm.gb).apply(null,arguments)},Ya=d.___funcs_on_exit=function(){return(Ya=d.___funcs_on_exit=d.asm.hb).apply(null,arguments)},X=d._setThrew=function(){return(X=d._setThrew=d.asm.jb).apply(null,arguments)},Y=d.stackSave=function(){return(Y=d.stackSave=d.asm.kb).apply(null,arguments)},Z=d.stackRestore=
+function(){return(Z=d.stackRestore=d.asm.lb).apply(null,arguments)},Kb=d.stackAlloc=function(){return(Kb=d.stackAlloc=d.asm.mb).apply(null,arguments)},Xa=d.___cxa_can_catch=function(){return(Xa=d.___cxa_can_catch=d.asm.nb).apply(null,arguments)},Fa=d.___cxa_is_pointer_type=function(){return(Fa=d.___cxa_is_pointer_type=d.asm.ob).apply(null,arguments)},Lb=d.dynCall_j=function(){return(Lb=d.dynCall_j=d.asm.pb).apply(null,arguments)},Mb=d.dynCall_iiiiij=function(){return(Mb=d.dynCall_iiiiij=d.asm.qb).apply(null,
+arguments)},Nb=d.dynCall_jii=function(){return(Nb=d.dynCall_jii=d.asm.rb).apply(null,arguments)},Ob=d.dynCall_viiiiij=function(){return(Ob=d.dynCall_viiiiij=d.asm.sb).apply(null,arguments)},Pb=d.dynCall_vjji=function(){return(Pb=d.dynCall_vjji=d.asm.tb).apply(null,arguments)},Qb=d.dynCall_viiijjjii=function(){return(Qb=d.dynCall_viiijjjii=d.asm.ub).apply(null,arguments)},Rb=d.dynCall_iij=function(){return(Rb=d.dynCall_iij=d.asm.vb).apply(null,arguments)},Sb=d.dynCall_ji=function(){return(Sb=d.dynCall_ji=
+d.asm.wb).apply(null,arguments)},Tb=d.dynCall_iiiiiij=function(){return(Tb=d.dynCall_iiiiiij=d.asm.xb).apply(null,arguments)},Ub=d.dynCall_iiij=function(){return(Ub=d.dynCall_iiij=d.asm.yb).apply(null,arguments)};function cb(a,b){var c=Y();try{return U(a)(b)}catch(e){Z(c);if(e!==e+0)throw e;X(1,0)}}function vb(a,b){var c=Y();try{U(a)(b)}catch(e){Z(c);if(e!==e+0)throw e;X(1,0)}}function wb(a,b,c){var e=Y();try{U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}
+function fb(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function gb(a,b,c,e){var f=Y();try{return U(a)(b,c,e)}catch(h){Z(f);if(h!==h+0)throw h;X(1,0)}}function kb(a,b,c,e,f,h,k){var l=Y();try{return U(a)(b,c,e,f,h,k)}catch(n){Z(l);if(n!==n+0)throw n;X(1,0)}}function ub(a){var b=Y();try{U(a)()}catch(c){Z(b);if(c!==c+0)throw c;X(1,0)}}function jb(a,b,c,e,f,h){var k=Y();try{return U(a)(b,c,e,f,h)}catch(l){Z(k);if(l!==l+0)throw l;X(1,0)}}
+function hb(a,b,c,e,f){var h=Y();try{return U(a)(b,c,e,f)}catch(k){Z(h);if(k!==k+0)throw k;X(1,0)}}function yb(a,b,c,e){var f=Y();try{U(a)(b,c,e)}catch(h){Z(f);if(h!==h+0)throw h;X(1,0)}}function Ab(a,b,c,e,f,h){var k=Y();try{U(a)(b,c,e,f,h)}catch(l){Z(k);if(l!==l+0)throw l;X(1,0)}}function zb(a,b,c,e,f){var h=Y();try{U(a)(b,c,e,f)}catch(k){Z(h);if(k!==k+0)throw k;X(1,0)}}function Bb(a,b,c,e,f,h,k){var l=Y();try{U(a)(b,c,e,f,h,k)}catch(n){Z(l);if(n!==n+0)throw n;X(1,0)}}
+function Cb(a,b,c,e,f,h,k,l){var n=Y();try{U(a)(b,c,e,f,h,k,l)}catch(t){Z(n);if(t!==t+0)throw t;X(1,0)}}function eb(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function db(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function Db(a,b,c,e,f,h,k,l,n){var t=Y();try{U(a)(b,c,e,f,h,k,l,n)}catch(x){Z(t);if(x!==x+0)throw x;X(1,0)}}function ib(a,b,c,e,f,h){var k=Y();try{return U(a)(b,c,e,f,h)}catch(l){Z(k);if(l!==l+0)throw l;X(1,0)}}
+function lb(a,b,c,e,f,h,k,l){var n=Y();try{return U(a)(b,c,e,f,h,k,l)}catch(t){Z(n);if(t!==t+0)throw t;X(1,0)}}function mb(a,b,c,e,f,h,k,l,n,t,x,E){var C=Y();try{return U(a)(b,c,e,f,h,k,l,n,t,x,E)}catch(g){Z(C);if(g!==g+0)throw g;X(1,0)}}function Eb(a,b,c,e,f,h,k,l,n,t,x){var E=Y();try{U(a)(b,c,e,f,h,k,l,n,t,x)}catch(C){Z(E);if(C!==C+0)throw C;X(1,0)}}function Fb(a,b,c,e,f,h,k,l,n,t,x,E,C,g,u,w){var F=Y();try{U(a)(b,c,e,f,h,k,l,n,t,x,E,C,g,u,w)}catch(M){Z(F);if(M!==M+0)throw M;X(1,0)}}
+function bb(a){var b=Y();try{return U(a)()}catch(c){Z(b);if(c!==c+0)throw c;X(1,0)}}function ab(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function $a(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function xb(a,b,c,e){var f=Y();try{U(a)(b,c,e)}catch(h){Z(f);if(h!==h+0)throw h;X(1,0)}}function Gb(a,b,c,e,f,h,k,l){var n=Y();try{Ob(a,b,c,e,f,h,k,l)}catch(t){Z(n);if(t!==t+0)throw t;X(1,0)}}
+function Ib(a,b,c,e,f,h){var k=Y();try{Pb(a,b,c,e,f,h)}catch(l){Z(k);if(l!==l+0)throw l;X(1,0)}}function Hb(a,b,c,e,f,h,k,l,n,t,x,E){var C=Y();try{Qb(a,b,c,e,f,h,k,l,n,t,x,E)}catch(g){Z(C);if(g!==g+0)throw g;X(1,0)}}function qb(a,b,c,e){var f=Y();try{return Rb(a,b,c,e)}catch(h){Z(f);if(h!==h+0)throw h;X(1,0)}}function sb(a,b){var c=Y();try{return Sb(a,b)}catch(e){Z(c);if(e!==e+0)throw e;X(1,0)}}
+function nb(a,b,c,e,f,h,k,l){var n=Y();try{return Tb(a,b,c,e,f,h,k,l)}catch(t){Z(n);if(t!==t+0)throw t;X(1,0)}}function rb(a){var b=Y();try{return Lb(a)}catch(c){Z(b);if(c!==c+0)throw c;X(1,0)}}function ob(a,b,c,e,f,h,k){var l=Y();try{return Mb(a,b,c,e,f,h,k)}catch(n){Z(l);if(n!==n+0)throw n;X(1,0)}}function pb(a,b,c,e,f){var h=Y();try{return Ub(a,b,c,e,f)}catch(k){Z(h);if(k!==k+0)throw k;X(1,0)}}function tb(a,b,c){var e=Y();try{return Nb(a,b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}
+d.UTF8ToString=pa;d.stringToUTF8=function(a,b,c){return qa(a,G,b,c)};d.lengthBytesUTF8=ra;d.stackSave=Y;d.stackRestore=Z;d.stackAlloc=Kb;var Vb;L=function Wb(){Vb||Xb();Vb||(L=Wb)};
+function Xb(){function a(){if(!Vb&&(Vb=!0,d.calledRun=!0,!D)){O(wa);aa(d);if(d.onRuntimeInitialized)d.onRuntimeInitialized();if(d.postRun)for("function"==typeof d.postRun&&(d.postRun=[d.postRun]);d.postRun.length;){var b=d.postRun.shift();ya.unshift(b)}O(ya)}}if(!(0<K)){if(d.preRun)for("function"==typeof d.preRun&&(d.preRun=[d.preRun]);d.preRun.length;)za();O(va);0<K||(d.setStatus?(d.setStatus("Running..."),setTimeout(function(){setTimeout(function(){d.setStatus("")},1);a()},1)):a())}}
+if(d.preInit)for("function"==typeof d.preInit&&(d.preInit=[d.preInit]);0<d.preInit.length;)d.preInit.pop()();Xb();
+
+
+ return ortWasm.ready
+}
+);
+})();
+if (true)
+ module.exports = ortWasm;
+else {}
+
+
+/***/ }),
+
+/***/ "./node_modules/@protobufjs/aspromise/index.js":
+/*!*****************************************************!*\
+ !*** ./node_modules/@protobufjs/aspromise/index.js ***!
+ \*****************************************************/
+/***/ ((module) => {
+
+"use strict";
+
+module.exports = asPromise;
+
+/**
+ * Callback as used by {@link util.asPromise}.
+ * @typedef asPromiseCallback
+ * @type {function}
+ * @param {Error|null} error Error, if any
+ * @param {...*} params Additional arguments
+ * @returns {undefined}
+ */
+
+/**
+ * Returns a promise from a node-style callback function.
+ * @memberof util
+ * @param {asPromiseCallback} fn Function to call
+ * @param {*} ctx Function context
+ * @param {...*} params Function arguments
+ * @returns {Promise<*>} Promisified function
+ */
+function asPromise(fn, ctx/*, varargs */) {
+ var params = new Array(arguments.length - 1),
+ offset = 0,
+ index = 2,
+ pending = true;
+ while (index < arguments.length)
+ params[offset++] = arguments[index++];
+ return new Promise(function executor(resolve, reject) {
+ params[offset] = function callback(err/*, varargs */) {
+ if (pending) {
+ pending = false;
+ if (err)
+ reject(err);
+ else {
+ var params = new Array(arguments.length - 1),
+ offset = 0;
+ while (offset < params.length)
+ params[offset++] = arguments[offset];
+ resolve.apply(null, params);
+ }
+ }
+ };
+ try {
+ fn.apply(ctx || null, params);
+ } catch (err) {
+ if (pending) {
+ pending = false;
+ reject(err);
+ }
+ }
+ });
+}
+
+
+/***/ }),
+
+/***/ "./node_modules/@protobufjs/base64/index.js":
+/*!**************************************************!*\
+ !*** ./node_modules/@protobufjs/base64/index.js ***!
+ \**************************************************/
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+
+/**
+ * A minimal base64 implementation for number arrays.
+ * @memberof util
+ * @namespace
+ */
+var base64 = exports;
+
+/**
+ * Calculates the byte length of a base64 encoded string.
+ * @param {string} string Base64 encoded string
+ * @returns {number} Byte length
+ */
+base64.length = function length(string) {
+ var p = string.length;
+ if (!p)
+ return 0;
+ var n = 0;
+ while (--p % 4 > 1 && string.charAt(p) === "=")
+ ++n;
+ return Math.ceil(string.length * 3) / 4 - n;
+};
+
+// Base64 encoding table
+var b64 = new Array(64);
+
+// Base64 decoding table
+var s64 = new Array(123);
+
+// 65..90, 97..122, 48..57, 43, 47
+for (var i = 0; i < 64;)
+ s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;
+
+/**
+ * Encodes a buffer to a base64 encoded string.
+ * @param {Uint8Array} buffer Source buffer
+ * @param {number} start Source start
+ * @param {number} end Source end
+ * @returns {string} Base64 encoded string
+ */
+base64.encode = function encode(buffer, start, end) {
+ var parts = null,
+ chunk = [];
+ var i = 0, // output index
+ j = 0, // goto index
+ t; // temporary
+ while (start < end) {
+ var b = buffer[start++];
+ switch (j) {
+ case 0:
+ chunk[i++] = b64[b >> 2];
+ t = (b & 3) << 4;
+ j = 1;
+ break;
+ case 1:
+ chunk[i++] = b64[t | b >> 4];
+ t = (b & 15) << 2;
+ j = 2;
+ break;
+ case 2:
+ chunk[i++] = b64[t | b >> 6];
+ chunk[i++] = b64[b & 63];
+ j = 0;
+ break;
+ }
+ if (i > 8191) {
+ (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
+ i = 0;
+ }
+ }
+ if (j) {
+ chunk[i++] = b64[t];
+ chunk[i++] = 61;
+ if (j === 1)
+ chunk[i++] = 61;
+ }
+ if (parts) {
+ if (i)
+ parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
+ return parts.join("");
+ }
+ return String.fromCharCode.apply(String, chunk.slice(0, i));
+};
+
+var invalidEncoding = "invalid encoding";
+
+/**
+ * Decodes a base64 encoded string to a buffer.
+ * @param {string} string Source string
+ * @param {Uint8Array} buffer Destination buffer
+ * @param {number} offset Destination offset
+ * @returns {number} Number of bytes written
+ * @throws {Error} If encoding is invalid
+ */
+base64.decode = function decode(string, buffer, offset) {
+ var start = offset;
+ var j = 0, // goto index
+ t; // temporary
+ for (var i = 0; i < string.length;) {
+ var c = string.charCodeAt(i++);
+ if (c === 61 && j > 1)
+ break;
+ if ((c = s64[c]) === undefined)
+ throw Error(invalidEncoding);
+ switch (j) {
+ case 0:
+ t = c;
+ j = 1;
+ break;
+ case 1:
+ buffer[offset++] = t << 2 | (c & 48) >> 4;
+ t = c;
+ j = 2;
+ break;
+ case 2:
+ buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;
+ t = c;
+ j = 3;
+ break;
+ case 3:
+ buffer[offset++] = (t & 3) << 6 | c;
+ j = 0;
+ break;
+ }
+ }
+ if (j === 1)
+ throw Error(invalidEncoding);
+ return offset - start;
+};
+
+/**
+ * Tests if the specified string appears to be base64 encoded.
+ * @param {string} string String to test
+ * @returns {boolean} `true` if probably base64 encoded, otherwise false
+ */
+base64.test = function test(string) {
+ return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);
+};
+
+
+/***/ }),
+
+/***/ "./node_modules/@protobufjs/eventemitter/index.js":
+/*!********************************************************!*\
+ !*** ./node_modules/@protobufjs/eventemitter/index.js ***!
+ \********************************************************/
+/***/ ((module) => {
+
+"use strict";
+
+module.exports = EventEmitter;
+
+/**
+ * Constructs a new event emitter instance.
+ * @classdesc A minimal event emitter.
+ * @memberof util
+ * @constructor
+ */
+function EventEmitter() {
+
+ /**
+ * Registered listeners.
+ * @type {Object.<string,*>}
+ * @private
+ */
+ this._listeners = {};
+}
+
+/**
+ * Registers an event listener.
+ * @param {string} evt Event name
+ * @param {function} fn Listener
+ * @param {*} [ctx] Listener context
+ * @returns {util.EventEmitter} `this`
+ */
+EventEmitter.prototype.on = function on(evt, fn, ctx) {
+ (this._listeners[evt] || (this._listeners[evt] = [])).push({
+ fn : fn,
+ ctx : ctx || this
+ });
+ return this;
+};
+
+/**
+ * Removes an event listener or any matching listeners if arguments are omitted.
+ * @param {string} [evt] Event name. Removes all listeners if omitted.
+ * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.
+ * @returns {util.EventEmitter} `this`
+ */
+EventEmitter.prototype.off = function off(evt, fn) {
+ if (evt === undefined)
+ this._listeners = {};
+ else {
+ if (fn === undefined)
+ this._listeners[evt] = [];
+ else {
+ var listeners = this._listeners[evt];
+ for (var i = 0; i < listeners.length;)
+ if (listeners[i].fn === fn)
+ listeners.splice(i, 1);
+ else
+ ++i;
+ }
+ }
+ return this;
+};
+
+/**
+ * Emits an event by calling its listeners with the specified arguments.
+ * @param {string} evt Event name
+ * @param {...*} args Arguments
+ * @returns {util.EventEmitter} `this`
+ */
+EventEmitter.prototype.emit = function emit(evt) {
+ var listeners = this._listeners[evt];
+ if (listeners) {
+ var args = [],
+ i = 1;
+ for (; i < arguments.length;)
+ args.push(arguments[i++]);
+ for (i = 0; i < listeners.length;)
+ listeners[i].fn.apply(listeners[i++].ctx, args);
+ }
+ return this;
+};
+
+
+/***/ }),
+
+/***/ "./node_modules/@protobufjs/float/index.js":
+/*!*************************************************!*\
+ !*** ./node_modules/@protobufjs/float/index.js ***!
+ \*************************************************/
+/***/ ((module) => {
+
+"use strict";
+
+
+module.exports = factory(factory);
+
+/**
+ * Reads / writes floats / doubles from / to buffers.
+ * @name util.float
+ * @namespace
+ */
+
+/**
+ * Writes a 32 bit float to a buffer using little endian byte order.
+ * @name util.float.writeFloatLE
+ * @function
+ * @param {number} val Value to write
+ * @param {Uint8Array} buf Target buffer
+ * @param {number} pos Target buffer offset
+ * @returns {undefined}
+ */
+
+/**
+ * Writes a 32 bit float to a buffer using big endian byte order.
+ * @name util.float.writeFloatBE
+ * @function
+ * @param {number} val Value to write
+ * @param {Uint8Array} buf Target buffer
+ * @param {number} pos Target buffer offset
+ * @returns {undefined}
+ */
+
+/**
+ * Reads a 32 bit float from a buffer using little endian byte order.
+ * @name util.float.readFloatLE
+ * @function
+ * @param {Uint8Array} buf Source buffer
+ * @param {number} pos Source buffer offset
+ * @returns {number} Value read
+ */
+
+/**
+ * Reads a 32 bit float from a buffer using big endian byte order.
+ * @name util.float.readFloatBE
+ * @function
+ * @param {Uint8Array} buf Source buffer
+ * @param {number} pos Source buffer offset
+ * @returns {number} Value read
+ */
+
+/**
+ * Writes a 64 bit double to a buffer using little endian byte order.
+ * @name util.float.writeDoubleLE
+ * @function
+ * @param {number} val Value to write
+ * @param {Uint8Array} buf Target buffer
+ * @param {number} pos Target buffer offset
+ * @returns {undefined}
+ */
+
+/**
+ * Writes a 64 bit double to a buffer using big endian byte order.
+ * @name util.float.writeDoubleBE
+ * @function
+ * @param {number} val Value to write
+ * @param {Uint8Array} buf Target buffer
+ * @param {number} pos Target buffer offset
+ * @returns {undefined}
+ */
+
+/**
+ * Reads a 64 bit double from a buffer using little endian byte order.
+ * @name util.float.readDoubleLE
+ * @function
+ * @param {Uint8Array} buf Source buffer
+ * @param {number} pos Source buffer offset
+ * @returns {number} Value read
+ */
+
+/**
+ * Reads a 64 bit double from a buffer using big endian byte order.
+ * @name util.float.readDoubleBE
+ * @function
+ * @param {Uint8Array} buf Source buffer
+ * @param {number} pos Source buffer offset
+ * @returns {number} Value read
+ */
+
+// Factory function for the purpose of node-based testing in modified global environments
+function factory(exports) {
+
+ // float: typed array
+ if (typeof Float32Array !== "undefined") (function() {
+
+ var f32 = new Float32Array([ -0 ]),
+ f8b = new Uint8Array(f32.buffer),
+ le = f8b[3] === 128;
+
+ function writeFloat_f32_cpy(val, buf, pos) {
+ f32[0] = val;
+ buf[pos ] = f8b[0];
+ buf[pos + 1] = f8b[1];
+ buf[pos + 2] = f8b[2];
+ buf[pos + 3] = f8b[3];
+ }
+
+ function writeFloat_f32_rev(val, buf, pos) {
+ f32[0] = val;
+ buf[pos ] = f8b[3];
+ buf[pos + 1] = f8b[2];
+ buf[pos + 2] = f8b[1];
+ buf[pos + 3] = f8b[0];
+ }
+
+ /* istanbul ignore next */
+ exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;
+ /* istanbul ignore next */
+ exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;
+
+ function readFloat_f32_cpy(buf, pos) {
+ f8b[0] = buf[pos ];
+ f8b[1] = buf[pos + 1];
+ f8b[2] = buf[pos + 2];
+ f8b[3] = buf[pos + 3];
+ return f32[0];
+ }
+
+ function readFloat_f32_rev(buf, pos) {
+ f8b[3] = buf[pos ];
+ f8b[2] = buf[pos + 1];
+ f8b[1] = buf[pos + 2];
+ f8b[0] = buf[pos + 3];
+ return f32[0];
+ }
+
+ /* istanbul ignore next */
+ exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;
+ /* istanbul ignore next */
+ exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;
+
+ // float: ieee754
+ })(); else (function() {
+
+ function writeFloat_ieee754(writeUint, val, buf, pos) {
+ var sign = val < 0 ? 1 : 0;
+ if (sign)
+ val = -val;
+ if (val === 0)
+ writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);
+ else if (isNaN(val))
+ writeUint(2143289344, buf, pos);
+ else if (val > 3.4028234663852886e+38) // +-Infinity
+ writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);
+ else if (val < 1.1754943508222875e-38) // denormal
+ writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);
+ else {
+ var exponent = Math.floor(Math.log(val) / Math.LN2),
+ mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;
+ writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);
+ }
+ }
+
+ exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);
+ exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);
+
+ function readFloat_ieee754(readUint, buf, pos) {
+ var uint = readUint(buf, pos),
+ sign = (uint >> 31) * 2 + 1,
+ exponent = uint >>> 23 & 255,
+ mantissa = uint & 8388607;
+ return exponent === 255
+ ? mantissa
+ ? NaN
+ : sign * Infinity
+ : exponent === 0 // denormal
+ ? sign * 1.401298464324817e-45 * mantissa
+ : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);
+ }
+
+ exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);
+ exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);
+
+ })();
+
+ // double: typed array
+ if (typeof Float64Array !== "undefined") (function() {
+
+ var f64 = new Float64Array([-0]),
+ f8b = new Uint8Array(f64.buffer),
+ le = f8b[7] === 128;
+
+ function writeDouble_f64_cpy(val, buf, pos) {
+ f64[0] = val;
+ buf[pos ] = f8b[0];
+ buf[pos + 1] = f8b[1];
+ buf[pos + 2] = f8b[2];
+ buf[pos + 3] = f8b[3];
+ buf[pos + 4] = f8b[4];
+ buf[pos + 5] = f8b[5];
+ buf[pos + 6] = f8b[6];
+ buf[pos + 7] = f8b[7];
+ }
+
+ function writeDouble_f64_rev(val, buf, pos) {
+ f64[0] = val;
+ buf[pos ] = f8b[7];
+ buf[pos + 1] = f8b[6];
+ buf[pos + 2] = f8b[5];
+ buf[pos + 3] = f8b[4];
+ buf[pos + 4] = f8b[3];
+ buf[pos + 5] = f8b[2];
+ buf[pos + 6] = f8b[1];
+ buf[pos + 7] = f8b[0];
+ }
+
+ /* istanbul ignore next */
+ exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;
+ /* istanbul ignore next */
+ exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;
+
+ function readDouble_f64_cpy(buf, pos) {
+ f8b[0] = buf[pos ];
+ f8b[1] = buf[pos + 1];
+ f8b[2] = buf[pos + 2];
+ f8b[3] = buf[pos + 3];
+ f8b[4] = buf[pos + 4];
+ f8b[5] = buf[pos + 5];
+ f8b[6] = buf[pos + 6];
+ f8b[7] = buf[pos + 7];
+ return f64[0];
+ }
+
+ function readDouble_f64_rev(buf, pos) {
+ f8b[7] = buf[pos ];
+ f8b[6] = buf[pos + 1];
+ f8b[5] = buf[pos + 2];
+ f8b[4] = buf[pos + 3];
+ f8b[3] = buf[pos + 4];
+ f8b[2] = buf[pos + 5];
+ f8b[1] = buf[pos + 6];
+ f8b[0] = buf[pos + 7];
+ return f64[0];
+ }
+
+ /* istanbul ignore next */
+ exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;
+ /* istanbul ignore next */
+ exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;
+
+ // double: ieee754
+ })(); else (function() {
+
+ function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {
+ var sign = val < 0 ? 1 : 0;
+ if (sign)
+ val = -val;
+ if (val === 0) {
+ writeUint(0, buf, pos + off0);
+ writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);
+ } else if (isNaN(val)) {
+ writeUint(0, buf, pos + off0);
+ writeUint(2146959360, buf, pos + off1);
+ } else if (val > 1.7976931348623157e+308) { // +-Infinity
+ writeUint(0, buf, pos + off0);
+ writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);
+ } else {
+ var mantissa;
+ if (val < 2.2250738585072014e-308) { // denormal
+ mantissa = val / 5e-324;
+ writeUint(mantissa >>> 0, buf, pos + off0);
+ writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);
+ } else {
+ var exponent = Math.floor(Math.log(val) / Math.LN2);
+ if (exponent === 1024)
+ exponent = 1023;
+ mantissa = val * Math.pow(2, -exponent);
+ writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);
+ writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);
+ }
+ }
+ }
+
+ exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);
+ exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);
+
+ function readDouble_ieee754(readUint, off0, off1, buf, pos) {
+ var lo = readUint(buf, pos + off0),
+ hi = readUint(buf, pos + off1);
+ var sign = (hi >> 31) * 2 + 1,
+ exponent = hi >>> 20 & 2047,
+ mantissa = 4294967296 * (hi & 1048575) + lo;
+ return exponent === 2047
+ ? mantissa
+ ? NaN
+ : sign * Infinity
+ : exponent === 0 // denormal
+ ? sign * 5e-324 * mantissa
+ : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);
+ }
+
+ exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);
+ exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);
+
+ })();
+
+ return exports;
+}
+
+// uint helpers
+
+function writeUintLE(val, buf, pos) {
+ buf[pos ] = val & 255;
+ buf[pos + 1] = val >>> 8 & 255;
+ buf[pos + 2] = val >>> 16 & 255;
+ buf[pos + 3] = val >>> 24;
+}
+
+function writeUintBE(val, buf, pos) {
+ buf[pos ] = val >>> 24;
+ buf[pos + 1] = val >>> 16 & 255;
+ buf[pos + 2] = val >>> 8 & 255;
+ buf[pos + 3] = val & 255;
+}
+
+function readUintLE(buf, pos) {
+ return (buf[pos ]
+ | buf[pos + 1] << 8
+ | buf[pos + 2] << 16
+ | buf[pos + 3] << 24) >>> 0;
+}
+
+function readUintBE(buf, pos) {
+ return (buf[pos ] << 24
+ | buf[pos + 1] << 16
+ | buf[pos + 2] << 8
+ | buf[pos + 3]) >>> 0;
+}
+
+
+/***/ }),
+
+/***/ "./node_modules/@protobufjs/inquire/index.js":
+/*!***************************************************!*\
+ !*** ./node_modules/@protobufjs/inquire/index.js ***!
+ \***************************************************/
+/***/ ((module) => {
+
+"use strict";
+
+module.exports = inquire;
+
+/**
+ * Requires a module only if available.
+ * @memberof util
+ * @param {string} moduleName Module to require
+ * @returns {?Object} Required module if available and not empty, otherwise `null`
+ */
+function inquire(moduleName) {
+ return null;
+}
+
+
+/***/ }),
+
+/***/ "./node_modules/@protobufjs/pool/index.js":
+/*!************************************************!*\
+ !*** ./node_modules/@protobufjs/pool/index.js ***!
+ \************************************************/
+/***/ ((module) => {
+
+"use strict";
+
+module.exports = pool;
+
+/**
+ * An allocator as used by {@link util.pool}.
+ * @typedef PoolAllocator
+ * @type {function}
+ * @param {number} size Buffer size
+ * @returns {Uint8Array} Buffer
+ */
+
+/**
+ * A slicer as used by {@link util.pool}.
+ * @typedef PoolSlicer
+ * @type {function}
+ * @param {number} start Start offset
+ * @param {number} end End offset
+ * @returns {Uint8Array} Buffer slice
+ * @this {Uint8Array}
+ */
+
+/**
+ * A general purpose buffer pool.
+ * @memberof util
+ * @function
+ * @param {PoolAllocator} alloc Allocator
+ * @param {PoolSlicer} slice Slicer
+ * @param {number} [size=8192] Slab size
+ * @returns {PoolAllocator} Pooled allocator
+ */
+function pool(alloc, slice, size) {
+ var SIZE = size || 8192;
+ var MAX = SIZE >>> 1;
+ var slab = null;
+ var offset = SIZE;
+ return function pool_alloc(size) {
+ if (size < 1 || size > MAX)
+ return alloc(size);
+ if (offset + size > SIZE) {
+ slab = alloc(SIZE);
+ offset = 0;
+ }
+ var buf = slice.call(slab, offset, offset += size);
+ if (offset & 7) // align to 32 bit
+ offset = (offset | 7) + 1;
+ return buf;
+ };
+}
+
+
+/***/ }),
+
+/***/ "./node_modules/@protobufjs/utf8/index.js":
+/*!************************************************!*\
+ !*** ./node_modules/@protobufjs/utf8/index.js ***!
+ \************************************************/
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+
+/**
+ * A minimal UTF8 implementation for number arrays.
+ * @memberof util
+ * @namespace
+ */
+var utf8 = exports;
+
+/**
+ * Calculates the UTF8 byte length of a string.
+ * @param {string} string String
+ * @returns {number} Byte length
+ */
+utf8.length = function utf8_length(string) {
+ var len = 0,
+ c = 0;
+ for (var i = 0; i < string.length; ++i) {
+ c = string.charCodeAt(i);
+ if (c < 128)
+ len += 1;
+ else if (c < 2048)
+ len += 2;
+ else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {
+ ++i;
+ len += 4;
+ } else
+ len += 3;
+ }
+ return len;
+};
+
+/**
+ * Reads UTF8 bytes as a string.
+ * @param {Uint8Array} buffer Source buffer
+ * @param {number} start Source start
+ * @param {number} end Source end
+ * @returns {string} String read
+ */
+utf8.read = function utf8_read(buffer, start, end) {
+ var len = end - start;
+ if (len < 1)
+ return "";
+ var parts = null,
+ chunk = [],
+ i = 0, // char offset
+ t; // temporary
+ while (start < end) {
+ t = buffer[start++];
+ if (t < 128)
+ chunk[i++] = t;
+ else if (t > 191 && t < 224)
+ chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;
+ else if (t > 239 && t < 365) {
+ t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;
+ chunk[i++] = 0xD800 + (t >> 10);
+ chunk[i++] = 0xDC00 + (t & 1023);
+ } else
+ chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;
+ if (i > 8191) {
+ (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
+ i = 0;
+ }
+ }
+ if (parts) {
+ if (i)
+ parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
+ return parts.join("");
+ }
+ return String.fromCharCode.apply(String, chunk.slice(0, i));
+};
+
+/**
+ * Writes a string as UTF8 bytes.
+ * @param {string} string Source string
+ * @param {Uint8Array} buffer Destination buffer
+ * @param {number} offset Destination offset
+ * @returns {number} Bytes written
+ */
+utf8.write = function utf8_write(string, buffer, offset) {
+ var start = offset,
+ c1, // character 1
+ c2; // character 2
+ for (var i = 0; i < string.length; ++i) {
+ c1 = string.charCodeAt(i);
+ if (c1 < 128) {
+ buffer[offset++] = c1;
+ } else if (c1 < 2048) {
+ buffer[offset++] = c1 >> 6 | 192;
+ buffer[offset++] = c1 & 63 | 128;
+ } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {
+ c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);
+ ++i;
+ buffer[offset++] = c1 >> 18 | 240;
+ buffer[offset++] = c1 >> 12 & 63 | 128;
+ buffer[offset++] = c1 >> 6 & 63 | 128;
+ buffer[offset++] = c1 & 63 | 128;
+ } else {
+ buffer[offset++] = c1 >> 12 | 224;
+ buffer[offset++] = c1 >> 6 & 63 | 128;
+ buffer[offset++] = c1 & 63 | 128;
+ }
+ }
+ return offset - start;
+};
+
+
+/***/ }),
+
+/***/ "./node_modules/guid-typescript/dist/guid.js":
+/*!***************************************************!*\
+ !*** ./node_modules/guid-typescript/dist/guid.js ***!
+ \***************************************************/
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+exports.__esModule = true;
+var Guid = /** @class */ (function () {
+ function Guid(guid) {
+ if (!guid) {
+ throw new TypeError("Invalid argument; `value` has no value.");
+ }
+ this.value = Guid.EMPTY;
+ if (guid && Guid.isGuid(guid)) {
+ this.value = guid;
+ }
+ }
+ Guid.isGuid = function (guid) {
+ var value = guid.toString();
+ return guid && (guid instanceof Guid || Guid.validator.test(value));
+ };
+ Guid.create = function () {
+ return new Guid([Guid.gen(2), Guid.gen(1), Guid.gen(1), Guid.gen(1), Guid.gen(3)].join("-"));
+ };
+ Guid.createEmpty = function () {
+ return new Guid("emptyguid");
+ };
+ Guid.parse = function (guid) {
+ return new Guid(guid);
+ };
+ Guid.raw = function () {
+ return [Guid.gen(2), Guid.gen(1), Guid.gen(1), Guid.gen(1), Guid.gen(3)].join("-");
+ };
+ Guid.gen = function (count) {
+ var out = "";
+ for (var i = 0; i < count; i++) {
+ // tslint:disable-next-line:no-bitwise
+ out += (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
+ }
+ return out;
+ };
+ Guid.prototype.equals = function (other) {
+ // Comparing string `value` against provided `guid` will auto-call
+ // toString on `guid` for comparison
+ return Guid.isGuid(other) && this.value === other.toString();
+ };
+ Guid.prototype.isEmpty = function () {
+ return this.value === Guid.EMPTY;
+ };
+ Guid.prototype.toString = function () {
+ return this.value;
+ };
+ Guid.prototype.toJSON = function () {
+ return {
+ value: this.value
+ };
+ };
+ Guid.validator = new RegExp("^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$", "i");
+ Guid.EMPTY = "00000000-0000-0000-0000-000000000000";
+ return Guid;
+}());
+exports.Guid = Guid;
+
+
+/***/ }),
+
+/***/ "./node_modules/long/src/long.js":
+/*!***************************************!*\
+ !*** ./node_modules/long/src/long.js ***!
+ \***************************************/
+/***/ ((module) => {
+
+module.exports = Long;
+
+/**
+ * wasm optimizations, to do native i64 multiplication and divide
+ */
+var wasm = null;
+
+try {
+ wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([
+ 0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11
+ ])), {}).exports;
+} catch (e) {
+ // no wasm support :(
+}
+
+/**
+ * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
+ * See the from* functions below for more convenient ways of constructing Longs.
+ * @exports Long
+ * @class A Long class for representing a 64 bit two's-complement integer value.
+ * @param {number} low The low (signed) 32 bits of the long
+ * @param {number} high The high (signed) 32 bits of the long
+ * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
+ * @constructor
+ */
+function Long(low, high, unsigned) {
+
+ /**
+ * The low 32 bits as a signed value.
+ * @type {number}
+ */
+ this.low = low | 0;
+
+ /**
+ * The high 32 bits as a signed value.
+ * @type {number}
+ */
+ this.high = high | 0;
+
+ /**
+ * Whether unsigned or not.
+ * @type {boolean}
+ */
+ this.unsigned = !!unsigned;
+}
+
+// The internal representation of a long is the two given signed, 32-bit values.
+// We use 32-bit pieces because these are the size of integers on which
+// Javascript performs bit-operations. For operations like addition and
+// multiplication, we split each number into 16 bit pieces, which can easily be
+// multiplied within Javascript's floating-point representation without overflow
+// or change in sign.
+//
+// In the algorithms below, we frequently reduce the negative case to the
+// positive case by negating the input(s) and then post-processing the result.
+// Note that we must ALWAYS check specially whether those values are MIN_VALUE
+// (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
+// a positive number, it overflows back into a negative). Not handling this
+// case would often result in infinite recursion.
+//
+// Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
+// methods on which they depend.
+
+/**
+ * An indicator used to reliably determine if an object is a Long or not.
+ * @type {boolean}
+ * @const
+ * @private
+ */
+Long.prototype.__isLong__;
+
+Object.defineProperty(Long.prototype, "__isLong__", { value: true });
+
+/**
+ * @function
+ * @param {*} obj Object
+ * @returns {boolean}
+ * @inner
+ */
+function isLong(obj) {
+ return (obj && obj["__isLong__"]) === true;
+}
+
+/**
+ * Tests if the specified object is a Long.
+ * @function
+ * @param {*} obj Object
+ * @returns {boolean}
+ */
+Long.isLong = isLong;
+
+/**
+ * A cache of the Long representations of small integer values.
+ * @type {!Object}
+ * @inner
+ */
+var INT_CACHE = {};
+
+/**
+ * A cache of the Long representations of small unsigned integer values.
+ * @type {!Object}
+ * @inner
+ */
+var UINT_CACHE = {};
+
+/**
+ * @param {number} value
+ * @param {boolean=} unsigned
+ * @returns {!Long}
+ * @inner
+ */
+function fromInt(value, unsigned) {
+ var obj, cachedObj, cache;
+ if (unsigned) {
+ value >>>= 0;
+ if (cache = (0 <= value && value < 256)) {
+ cachedObj = UINT_CACHE[value];
+ if (cachedObj)
+ return cachedObj;
+ }
+ obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
+ if (cache)
+ UINT_CACHE[value] = obj;
+ return obj;
+ } else {
+ value |= 0;
+ if (cache = (-128 <= value && value < 128)) {
+ cachedObj = INT_CACHE[value];
+ if (cachedObj)
+ return cachedObj;
+ }
+ obj = fromBits(value, value < 0 ? -1 : 0, false);
+ if (cache)
+ INT_CACHE[value] = obj;
+ return obj;
+ }
+}
+
+/**
+ * Returns a Long representing the given 32 bit integer value.
+ * @function
+ * @param {number} value The 32 bit integer in question
+ * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
+ * @returns {!Long} The corresponding Long value
+ */
+Long.fromInt = fromInt;
+
+/**
+ * @param {number} value
+ * @param {boolean=} unsigned
+ * @returns {!Long}
+ * @inner
+ */
+function fromNumber(value, unsigned) {
+ if (isNaN(value))
+ return unsigned ? UZERO : ZERO;
+ if (unsigned) {
+ if (value < 0)
+ return UZERO;
+ if (value >= TWO_PWR_64_DBL)
+ return MAX_UNSIGNED_VALUE;
+ } else {
+ if (value <= -TWO_PWR_63_DBL)
+ return MIN_VALUE;
+ if (value + 1 >= TWO_PWR_63_DBL)
+ return MAX_VALUE;
+ }
+ if (value < 0)
+ return fromNumber(-value, unsigned).neg();
+ return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
+}
+
+/**
+ * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
+ * @function
+ * @param {number} value The number in question
+ * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
+ * @returns {!Long} The corresponding Long value
+ */
+Long.fromNumber = fromNumber;
+
+/**
+ * @param {number} lowBits
+ * @param {number} highBits
+ * @param {boolean=} unsigned
+ * @returns {!Long}
+ * @inner
+ */
+function fromBits(lowBits, highBits, unsigned) {
+ return new Long(lowBits, highBits, unsigned);
+}
+
+/**
+ * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
+ * assumed to use 32 bits.
+ * @function
+ * @param {number} lowBits The low 32 bits
+ * @param {number} highBits The high 32 bits
+ * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
+ * @returns {!Long} The corresponding Long value
+ */
+Long.fromBits = fromBits;
+
+/**
+ * @function
+ * @param {number} base
+ * @param {number} exponent
+ * @returns {number}
+ * @inner
+ */
+var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)
+
+/**
+ * @param {string} str
+ * @param {(boolean|number)=} unsigned
+ * @param {number=} radix
+ * @returns {!Long}
+ * @inner
+ */
+function fromString(str, unsigned, radix) {
+ if (str.length === 0)
+ throw Error('empty string');
+ if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
+ return ZERO;
+ if (typeof unsigned === 'number') {
+ // For goog.math.long compatibility
+ radix = unsigned,
+ unsigned = false;
+ } else {
+ unsigned = !! unsigned;
+ }
+ radix = radix || 10;
+ if (radix < 2 || 36 < radix)
+ throw RangeError('radix');
+
+ var p;
+ if ((p = str.indexOf('-')) > 0)
+ throw Error('interior hyphen');
+ else if (p === 0) {
+ return fromString(str.substring(1), unsigned, radix).neg();
+ }
+
+ // Do several (8) digits each time through the loop, so as to
+ // minimize the calls to the very expensive emulated div.
+ var radixToPower = fromNumber(pow_dbl(radix, 8));
+
+ var result = ZERO;
+ for (var i = 0; i < str.length; i += 8) {
+ var size = Math.min(8, str.length - i),
+ value = parseInt(str.substring(i, i + size), radix);
+ if (size < 8) {
+ var power = fromNumber(pow_dbl(radix, size));
+ result = result.mul(power).add(fromNumber(value));
+ } else {
+ result = result.mul(radixToPower);
+ result = result.add(fromNumber(value));
+ }
+ }
+ result.unsigned = unsigned;
+ return result;
+}
+
+/**
+ * Returns a Long representation of the given string, written using the specified radix.
+ * @function
+ * @param {string} str The textual representation of the Long
+ * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed
+ * @param {number=} radix The radix in which the text is written (2-36), defaults to 10
+ * @returns {!Long} The corresponding Long value
+ */
+Long.fromString = fromString;
+
+/**
+ * @function
+ * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val
+ * @param {boolean=} unsigned
+ * @returns {!Long}
+ * @inner
+ */
+function fromValue(val, unsigned) {
+ if (typeof val === 'number')
+ return fromNumber(val, unsigned);
+ if (typeof val === 'string')
+ return fromString(val, unsigned);
+ // Throws for non-objects, converts non-instanceof Long:
+ return fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
+}
+
+/**
+ * Converts the specified value to a Long using the appropriate from* function for its type.
+ * @function
+ * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
+ * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
+ * @returns {!Long}
+ */
+Long.fromValue = fromValue;
+
+// NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
+// no runtime penalty for these.
+
+/**
+ * @type {number}
+ * @const
+ * @inner
+ */
+var TWO_PWR_16_DBL = 1 << 16;
+
+/**
+ * @type {number}
+ * @const
+ * @inner
+ */
+var TWO_PWR_24_DBL = 1 << 24;
+
+/**
+ * @type {number}
+ * @const
+ * @inner
+ */
+var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
+
+/**
+ * @type {number}
+ * @const
+ * @inner
+ */
+var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
+
+/**
+ * @type {number}
+ * @const
+ * @inner
+ */
+var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
+
+/**
+ * @type {!Long}
+ * @const
+ * @inner
+ */
+var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
+
+/**
+ * @type {!Long}
+ * @inner
+ */
+var ZERO = fromInt(0);
+
+/**
+ * Signed zero.
+ * @type {!Long}
+ */
+Long.ZERO = ZERO;
+
+/**
+ * @type {!Long}
+ * @inner
+ */
+var UZERO = fromInt(0, true);
+
+/**
+ * Unsigned zero.
+ * @type {!Long}
+ */
+Long.UZERO = UZERO;
+
+/**
+ * @type {!Long}
+ * @inner
+ */
+var ONE = fromInt(1);
+
+/**
+ * Signed one.
+ * @type {!Long}
+ */
+Long.ONE = ONE;
+
+/**
+ * @type {!Long}
+ * @inner
+ */
+var UONE = fromInt(1, true);
+
+/**
+ * Unsigned one.
+ * @type {!Long}
+ */
+Long.UONE = UONE;
+
+/**
+ * @type {!Long}
+ * @inner
+ */
+var NEG_ONE = fromInt(-1);
+
+/**
+ * Signed negative one.
+ * @type {!Long}
+ */
+Long.NEG_ONE = NEG_ONE;
+
+/**
+ * @type {!Long}
+ * @inner
+ */
+var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);
+
+/**
+ * Maximum signed value.
+ * @type {!Long}
+ */
+Long.MAX_VALUE = MAX_VALUE;
+
+/**
+ * @type {!Long}
+ * @inner
+ */
+var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);
+
+/**
+ * Maximum unsigned value.
+ * @type {!Long}
+ */
+Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
+
+/**
+ * @type {!Long}
+ * @inner
+ */
+var MIN_VALUE = fromBits(0, 0x80000000|0, false);
+
+/**
+ * Minimum signed value.
+ * @type {!Long}
+ */
+Long.MIN_VALUE = MIN_VALUE;
+
+/**
+ * @alias Long.prototype
+ * @inner
+ */
+var LongPrototype = Long.prototype;
+
+/**
+ * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
+ * @returns {number}
+ */
+LongPrototype.toInt = function toInt() {
+ return this.unsigned ? this.low >>> 0 : this.low;
+};
+
+/**
+ * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
+ * @returns {number}
+ */
+LongPrototype.toNumber = function toNumber() {
+ if (this.unsigned)
+ return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
+ return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
+};
+
+/**
+ * Converts the Long to a string written in the specified radix.
+ * @param {number=} radix Radix (2-36), defaults to 10
+ * @returns {string}
+ * @override
+ * @throws {RangeError} If `radix` is out of range
+ */
+LongPrototype.toString = function toString(radix) {
+ radix = radix || 10;
+ if (radix < 2 || 36 < radix)
+ throw RangeError('radix');
+ if (this.isZero())
+ return '0';
+ if (this.isNegative()) { // Unsigned Longs are never negative
+ if (this.eq(MIN_VALUE)) {
+ // We need to change the Long value before it can be negated, so we remove
+ // the bottom-most digit in this base and then recurse to do the rest.
+ var radixLong = fromNumber(radix),
+ div = this.div(radixLong),
+ rem1 = div.mul(radixLong).sub(this);
+ return div.toString(radix) + rem1.toInt().toString(radix);
+ } else
+ return '-' + this.neg().toString(radix);
+ }
+
+ // Do several (6) digits each time through the loop, so as to
+ // minimize the calls to the very expensive emulated div.
+ var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),
+ rem = this;
+ var result = '';
+ while (true) {
+ var remDiv = rem.div(radixToPower),
+ intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,
+ digits = intval.toString(radix);
+ rem = remDiv;
+ if (rem.isZero())
+ return digits + result;
+ else {
+ while (digits.length < 6)
+ digits = '0' + digits;
+ result = '' + digits + result;
+ }
+ }
+};
+
+/**
+ * Gets the high 32 bits as a signed integer.
+ * @returns {number} Signed high bits
+ */
+LongPrototype.getHighBits = function getHighBits() {
+ return this.high;
+};
+
+/**
+ * Gets the high 32 bits as an unsigned integer.
+ * @returns {number} Unsigned high bits
+ */
+LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
+ return this.high >>> 0;
+};
+
+/**
+ * Gets the low 32 bits as a signed integer.
+ * @returns {number} Signed low bits
+ */
+LongPrototype.getLowBits = function getLowBits() {
+ return this.low;
+};
+
+/**
+ * Gets the low 32 bits as an unsigned integer.
+ * @returns {number} Unsigned low bits
+ */
+LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
+ return this.low >>> 0;
+};
+
+/**
+ * Gets the number of bits needed to represent the absolute value of this Long.
+ * @returns {number}
+ */
+LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
+ if (this.isNegative()) // Unsigned Longs are never negative
+ return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
+ var val = this.high != 0 ? this.high : this.low;
+ for (var bit = 31; bit > 0; bit--)
+ if ((val & (1 << bit)) != 0)
+ break;
+ return this.high != 0 ? bit + 33 : bit + 1;
+};
+
+/**
+ * Tests if this Long's value equals zero.
+ * @returns {boolean}
+ */
+LongPrototype.isZero = function isZero() {
+ return this.high === 0 && this.low === 0;
+};
+
+/**
+ * Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}.
+ * @returns {boolean}
+ */
+LongPrototype.eqz = LongPrototype.isZero;
+
+/**
+ * Tests if this Long's value is negative.
+ * @returns {boolean}
+ */
+LongPrototype.isNegative = function isNegative() {
+ return !this.unsigned && this.high < 0;
+};
+
+/**
+ * Tests if this Long's value is positive.
+ * @returns {boolean}
+ */
+LongPrototype.isPositive = function isPositive() {
+ return this.unsigned || this.high >= 0;
+};
+
+/**
+ * Tests if this Long's value is odd.
+ * @returns {boolean}
+ */
+LongPrototype.isOdd = function isOdd() {
+ return (this.low & 1) === 1;
+};
+
+/**
+ * Tests if this Long's value is even.
+ * @returns {boolean}
+ */
+LongPrototype.isEven = function isEven() {
+ return (this.low & 1) === 0;
+};
+
+/**
+ * Tests if this Long's value equals the specified's.
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+LongPrototype.equals = function equals(other) {
+ if (!isLong(other))
+ other = fromValue(other);
+ if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
+ return false;
+ return this.high === other.high && this.low === other.low;
+};
+
+/**
+ * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+LongPrototype.eq = LongPrototype.equals;
+
+/**
+ * Tests if this Long's value differs from the specified's.
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+LongPrototype.notEquals = function notEquals(other) {
+ return !this.eq(/* validates */ other);
+};
+
+/**
+ * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+LongPrototype.neq = LongPrototype.notEquals;
+
+/**
+ * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+LongPrototype.ne = LongPrototype.notEquals;
+
+/**
+ * Tests if this Long's value is less than the specified's.
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+LongPrototype.lessThan = function lessThan(other) {
+ return this.comp(/* validates */ other) < 0;
+};
+
+/**
+ * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+LongPrototype.lt = LongPrototype.lessThan;
+
+/**
+ * Tests if this Long's value is less than or equal the specified's.
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
+ return this.comp(/* validates */ other) <= 0;
+};
+
+/**
+ * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+LongPrototype.lte = LongPrototype.lessThanOrEqual;
+
+/**
+ * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+LongPrototype.le = LongPrototype.lessThanOrEqual;
+
+/**
+ * Tests if this Long's value is greater than the specified's.
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+LongPrototype.greaterThan = function greaterThan(other) {
+ return this.comp(/* validates */ other) > 0;
+};
+
+/**
+ * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+LongPrototype.gt = LongPrototype.greaterThan;
+
+/**
+ * Tests if this Long's value is greater than or equal the specified's.
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
+ return this.comp(/* validates */ other) >= 0;
+};
+
+/**
+ * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+LongPrototype.gte = LongPrototype.greaterThanOrEqual;
+
+/**
+ * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+LongPrototype.ge = LongPrototype.greaterThanOrEqual;
+
+/**
+ * Compares this Long's value with the specified's.
+ * @param {!Long|number|string} other Other value
+ * @returns {number} 0 if they are the same, 1 if the this is greater and -1
+ * if the given one is greater
+ */
+LongPrototype.compare = function compare(other) {
+ if (!isLong(other))
+ other = fromValue(other);
+ if (this.eq(other))
+ return 0;
+ var thisNeg = this.isNegative(),
+ otherNeg = other.isNegative();
+ if (thisNeg && !otherNeg)
+ return -1;
+ if (!thisNeg && otherNeg)
+ return 1;
+ // At this point the sign bits are the same
+ if (!this.unsigned)
+ return this.sub(other).isNegative() ? -1 : 1;
+ // Both are positive if at least one is unsigned
+ return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
+};
+
+/**
+ * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {number} 0 if they are the same, 1 if the this is greater and -1
+ * if the given one is greater
+ */
+LongPrototype.comp = LongPrototype.compare;
+
+/**
+ * Negates this Long's value.
+ * @returns {!Long} Negated Long
+ */
+LongPrototype.negate = function negate() {
+ if (!this.unsigned && this.eq(MIN_VALUE))
+ return MIN_VALUE;
+ return this.not().add(ONE);
+};
+
+/**
+ * Negates this Long's value. This is an alias of {@link Long#negate}.
+ * @function
+ * @returns {!Long} Negated Long
+ */
+LongPrototype.neg = LongPrototype.negate;
+
+/**
+ * Returns the sum of this and the specified Long.
+ * @param {!Long|number|string} addend Addend
+ * @returns {!Long} Sum
+ */
+LongPrototype.add = function add(addend) {
+ if (!isLong(addend))
+ addend = fromValue(addend);
+
+ // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
+
+ var a48 = this.high >>> 16;
+ var a32 = this.high & 0xFFFF;
+ var a16 = this.low >>> 16;
+ var a00 = this.low & 0xFFFF;
+
+ var b48 = addend.high >>> 16;
+ var b32 = addend.high & 0xFFFF;
+ var b16 = addend.low >>> 16;
+ var b00 = addend.low & 0xFFFF;
+
+ var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
+ c00 += a00 + b00;
+ c16 += c00 >>> 16;
+ c00 &= 0xFFFF;
+ c16 += a16 + b16;
+ c32 += c16 >>> 16;
+ c16 &= 0xFFFF;
+ c32 += a32 + b32;
+ c48 += c32 >>> 16;
+ c32 &= 0xFFFF;
+ c48 += a48 + b48;
+ c48 &= 0xFFFF;
+ return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
+};
+
+/**
+ * Returns the difference of this and the specified Long.
+ * @param {!Long|number|string} subtrahend Subtrahend
+ * @returns {!Long} Difference
+ */
+LongPrototype.subtract = function subtract(subtrahend) {
+ if (!isLong(subtrahend))
+ subtrahend = fromValue(subtrahend);
+ return this.add(subtrahend.neg());
+};
+
+/**
+ * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
+ * @function
+ * @param {!Long|number|string} subtrahend Subtrahend
+ * @returns {!Long} Difference
+ */
+LongPrototype.sub = LongPrototype.subtract;
+
+/**
+ * Returns the product of this and the specified Long.
+ * @param {!Long|number|string} multiplier Multiplier
+ * @returns {!Long} Product
+ */
+LongPrototype.multiply = function multiply(multiplier) {
+ if (this.isZero())
+ return ZERO;
+ if (!isLong(multiplier))
+ multiplier = fromValue(multiplier);
+
+ // use wasm support if present
+ if (wasm) {
+ var low = wasm.mul(this.low,
+ this.high,
+ multiplier.low,
+ multiplier.high);
+ return fromBits(low, wasm.get_high(), this.unsigned);
+ }
+
+ if (multiplier.isZero())
+ return ZERO;
+ if (this.eq(MIN_VALUE))
+ return multiplier.isOdd() ? MIN_VALUE : ZERO;
+ if (multiplier.eq(MIN_VALUE))
+ return this.isOdd() ? MIN_VALUE : ZERO;
+
+ if (this.isNegative()) {
+ if (multiplier.isNegative())
+ return this.neg().mul(multiplier.neg());
+ else
+ return this.neg().mul(multiplier).neg();
+ } else if (multiplier.isNegative())
+ return this.mul(multiplier.neg()).neg();
+
+ // If both longs are small, use float multiplication
+ if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
+ return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
+
+ // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
+ // We can skip products that would overflow.
+
+ var a48 = this.high >>> 16;
+ var a32 = this.high & 0xFFFF;
+ var a16 = this.low >>> 16;
+ var a00 = this.low & 0xFFFF;
+
+ var b48 = multiplier.high >>> 16;
+ var b32 = multiplier.high & 0xFFFF;
+ var b16 = multiplier.low >>> 16;
+ var b00 = multiplier.low & 0xFFFF;
+
+ var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
+ c00 += a00 * b00;
+ c16 += c00 >>> 16;
+ c00 &= 0xFFFF;
+ c16 += a16 * b00;
+ c32 += c16 >>> 16;
+ c16 &= 0xFFFF;
+ c16 += a00 * b16;
+ c32 += c16 >>> 16;
+ c16 &= 0xFFFF;
+ c32 += a32 * b00;
+ c48 += c32 >>> 16;
+ c32 &= 0xFFFF;
+ c32 += a16 * b16;
+ c48 += c32 >>> 16;
+ c32 &= 0xFFFF;
+ c32 += a00 * b32;
+ c48 += c32 >>> 16;
+ c32 &= 0xFFFF;
+ c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
+ c48 &= 0xFFFF;
+ return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
+};
+
+/**
+ * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
+ * @function
+ * @param {!Long|number|string} multiplier Multiplier
+ * @returns {!Long} Product
+ */
+LongPrototype.mul = LongPrototype.multiply;
+
+/**
+ * Returns this Long divided by the specified. The result is signed if this Long is signed or
+ * unsigned if this Long is unsigned.
+ * @param {!Long|number|string} divisor Divisor
+ * @returns {!Long} Quotient
+ */
+LongPrototype.divide = function divide(divisor) {
+ if (!isLong(divisor))
+ divisor = fromValue(divisor);
+ if (divisor.isZero())
+ throw Error('division by zero');
+
+ // use wasm support if present
+ if (wasm) {
+ // guard against signed division overflow: the largest
+ // negative number / -1 would be 1 larger than the largest
+ // positive number, due to two's complement.
+ if (!this.unsigned &&
+ this.high === -0x80000000 &&
+ divisor.low === -1 && divisor.high === -1) {
+ // be consistent with non-wasm code path
+ return this;
+ }
+ var low = (this.unsigned ? wasm.div_u : wasm.div_s)(
+ this.low,
+ this.high,
+ divisor.low,
+ divisor.high
+ );
+ return fromBits(low, wasm.get_high(), this.unsigned);
+ }
+
+ if (this.isZero())
+ return this.unsigned ? UZERO : ZERO;
+ var approx, rem, res;
+ if (!this.unsigned) {
+ // This section is only relevant for signed longs and is derived from the
+ // closure library as a whole.
+ if (this.eq(MIN_VALUE)) {
+ if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
+ return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
+ else if (divisor.eq(MIN_VALUE))
+ return ONE;
+ else {
+ // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
+ var halfThis = this.shr(1);
+ approx = halfThis.div(divisor).shl(1);
+ if (approx.eq(ZERO)) {
+ return divisor.isNegative() ? ONE : NEG_ONE;
+ } else {
+ rem = this.sub(divisor.mul(approx));
+ res = approx.add(rem.div(divisor));
+ return res;
+ }
+ }
+ } else if (divisor.eq(MIN_VALUE))
+ return this.unsigned ? UZERO : ZERO;
+ if (this.isNegative()) {
+ if (divisor.isNegative())
+ return this.neg().div(divisor.neg());
+ return this.neg().div(divisor).neg();
+ } else if (divisor.isNegative())
+ return this.div(divisor.neg()).neg();
+ res = ZERO;
+ } else {
+ // The algorithm below has not been made for unsigned longs. It's therefore
+ // required to take special care of the MSB prior to running it.
+ if (!divisor.unsigned)
+ divisor = divisor.toUnsigned();
+ if (divisor.gt(this))
+ return UZERO;
+ if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true
+ return UONE;
+ res = UZERO;
+ }
+
+ // Repeat the following until the remainder is less than other: find a
+ // floating-point that approximates remainder / other *from below*, add this
+ // into the result, and subtract it from the remainder. It is critical that
+ // the approximate value is less than or equal to the real value so that the
+ // remainder never becomes negative.
+ rem = this;
+ while (rem.gte(divisor)) {
+ // Approximate the result of division. This may be a little greater or
+ // smaller than the actual value.
+ approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
+
+ // We will tweak the approximate result by changing it in the 48-th digit or
+ // the smallest non-fractional digit, whichever is larger.
+ var log2 = Math.ceil(Math.log(approx) / Math.LN2),
+ delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),
+
+ // Decrease the approximation until it is smaller than the remainder. Note
+ // that if it is too large, the product overflows and is negative.
+ approxRes = fromNumber(approx),
+ approxRem = approxRes.mul(divisor);
+ while (approxRem.isNegative() || approxRem.gt(rem)) {
+ approx -= delta;
+ approxRes = fromNumber(approx, this.unsigned);
+ approxRem = approxRes.mul(divisor);
+ }
+
+ // We know the answer can't be zero... and actually, zero would cause
+ // infinite recursion since we would make no progress.
+ if (approxRes.isZero())
+ approxRes = ONE;
+
+ res = res.add(approxRes);
+ rem = rem.sub(approxRem);
+ }
+ return res;
+};
+
+/**
+ * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
+ * @function
+ * @param {!Long|number|string} divisor Divisor
+ * @returns {!Long} Quotient
+ */
+LongPrototype.div = LongPrototype.divide;
+
+/**
+ * Returns this Long modulo the specified.
+ * @param {!Long|number|string} divisor Divisor
+ * @returns {!Long} Remainder
+ */
+LongPrototype.modulo = function modulo(divisor) {
+ if (!isLong(divisor))
+ divisor = fromValue(divisor);
+
+ // use wasm support if present
+ if (wasm) {
+ var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(
+ this.low,
+ this.high,
+ divisor.low,
+ divisor.high
+ );
+ return fromBits(low, wasm.get_high(), this.unsigned);
+ }
+
+ return this.sub(this.div(divisor).mul(divisor));
+};
+
+/**
+ * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
+ * @function
+ * @param {!Long|number|string} divisor Divisor
+ * @returns {!Long} Remainder
+ */
+LongPrototype.mod = LongPrototype.modulo;
+
+/**
+ * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
+ * @function
+ * @param {!Long|number|string} divisor Divisor
+ * @returns {!Long} Remainder
+ */
+LongPrototype.rem = LongPrototype.modulo;
+
+/**
+ * Returns the bitwise NOT of this Long.
+ * @returns {!Long}
+ */
+LongPrototype.not = function not() {
+ return fromBits(~this.low, ~this.high, this.unsigned);
+};
+
+/**
+ * Returns the bitwise AND of this Long and the specified.
+ * @param {!Long|number|string} other Other Long
+ * @returns {!Long}
+ */
+LongPrototype.and = function and(other) {
+ if (!isLong(other))
+ other = fromValue(other);
+ return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
+};
+
+/**
+ * Returns the bitwise OR of this Long and the specified.
+ * @param {!Long|number|string} other Other Long
+ * @returns {!Long}
+ */
+LongPrototype.or = function or(other) {
+ if (!isLong(other))
+ other = fromValue(other);
+ return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
+};
+
+/**
+ * Returns the bitwise XOR of this Long and the given one.
+ * @param {!Long|number|string} other Other Long
+ * @returns {!Long}
+ */
+LongPrototype.xor = function xor(other) {
+ if (!isLong(other))
+ other = fromValue(other);
+ return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
+};
+
+/**
+ * Returns this Long with bits shifted to the left by the given amount.
+ * @param {number|!Long} numBits Number of bits
+ * @returns {!Long} Shifted Long
+ */
+LongPrototype.shiftLeft = function shiftLeft(numBits) {
+ if (isLong(numBits))
+ numBits = numBits.toInt();
+ if ((numBits &= 63) === 0)
+ return this;
+ else if (numBits < 32)
+ return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
+ else
+ return fromBits(0, this.low << (numBits - 32), this.unsigned);
+};
+
+/**
+ * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.
+ * @function
+ * @param {number|!Long} numBits Number of bits
+ * @returns {!Long} Shifted Long
+ */
+LongPrototype.shl = LongPrototype.shiftLeft;
+
+/**
+ * Returns this Long with bits arithmetically shifted to the right by the given amount.
+ * @param {number|!Long} numBits Number of bits
+ * @returns {!Long} Shifted Long
+ */
+LongPrototype.shiftRight = function shiftRight(numBits) {
+ if (isLong(numBits))
+ numBits = numBits.toInt();
+ if ((numBits &= 63) === 0)
+ return this;
+ else if (numBits < 32)
+ return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
+ else
+ return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
+};
+
+/**
+ * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.
+ * @function
+ * @param {number|!Long} numBits Number of bits
+ * @returns {!Long} Shifted Long
+ */
+LongPrototype.shr = LongPrototype.shiftRight;
+
+/**
+ * Returns this Long with bits logically shifted to the right by the given amount.
+ * @param {number|!Long} numBits Number of bits
+ * @returns {!Long} Shifted Long
+ */
+LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
+ if (isLong(numBits))
+ numBits = numBits.toInt();
+ numBits &= 63;
+ if (numBits === 0)
+ return this;
+ else {
+ var high = this.high;
+ if (numBits < 32) {
+ var low = this.low;
+ return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
+ } else if (numBits === 32)
+ return fromBits(high, 0, this.unsigned);
+ else
+ return fromBits(high >>> (numBits - 32), 0, this.unsigned);
+ }
+};
+
+/**
+ * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
+ * @function
+ * @param {number|!Long} numBits Number of bits
+ * @returns {!Long} Shifted Long
+ */
+LongPrototype.shru = LongPrototype.shiftRightUnsigned;
+
+/**
+ * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
+ * @function
+ * @param {number|!Long} numBits Number of bits
+ * @returns {!Long} Shifted Long
+ */
+LongPrototype.shr_u = LongPrototype.shiftRightUnsigned;
+
+/**
+ * Converts this Long to signed.
+ * @returns {!Long} Signed long
+ */
+LongPrototype.toSigned = function toSigned() {
+ if (!this.unsigned)
+ return this;
+ return fromBits(this.low, this.high, false);
+};
+
+/**
+ * Converts this Long to unsigned.
+ * @returns {!Long} Unsigned long
+ */
+LongPrototype.toUnsigned = function toUnsigned() {
+ if (this.unsigned)
+ return this;
+ return fromBits(this.low, this.high, true);
+};
+
+/**
+ * Converts this Long to its byte representation.
+ * @param {boolean=} le Whether little or big endian, defaults to big endian
+ * @returns {!Array.<number>} Byte representation
+ */
+LongPrototype.toBytes = function toBytes(le) {
+ return le ? this.toBytesLE() : this.toBytesBE();
+};
+
+/**
+ * Converts this Long to its little endian byte representation.
+ * @returns {!Array.<number>} Little endian byte representation
+ */
+LongPrototype.toBytesLE = function toBytesLE() {
+ var hi = this.high,
+ lo = this.low;
+ return [
+ lo & 0xff,
+ lo >>> 8 & 0xff,
+ lo >>> 16 & 0xff,
+ lo >>> 24 ,
+ hi & 0xff,
+ hi >>> 8 & 0xff,
+ hi >>> 16 & 0xff,
+ hi >>> 24
+ ];
+};
+
+/**
+ * Converts this Long to its big endian byte representation.
+ * @returns {!Array.<number>} Big endian byte representation
+ */
+LongPrototype.toBytesBE = function toBytesBE() {
+ var hi = this.high,
+ lo = this.low;
+ return [
+ hi >>> 24 ,
+ hi >>> 16 & 0xff,
+ hi >>> 8 & 0xff,
+ hi & 0xff,
+ lo >>> 24 ,
+ lo >>> 16 & 0xff,
+ lo >>> 8 & 0xff,
+ lo & 0xff
+ ];
+};
+
+/**
+ * Creates a Long from its byte representation.
+ * @param {!Array.<number>} bytes Byte representation
+ * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
+ * @param {boolean=} le Whether little or big endian, defaults to big endian
+ * @returns {Long} The corresponding Long value
+ */
+Long.fromBytes = function fromBytes(bytes, unsigned, le) {
+ return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
+};
+
+/**
+ * Creates a Long from its little endian byte representation.
+ * @param {!Array.<number>} bytes Little endian byte representation
+ * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
+ * @returns {Long} The corresponding Long value
+ */
+Long.fromBytesLE = function fromBytesLE(bytes, unsigned) {
+ return new Long(
+ bytes[0] |
+ bytes[1] << 8 |
+ bytes[2] << 16 |
+ bytes[3] << 24,
+ bytes[4] |
+ bytes[5] << 8 |
+ bytes[6] << 16 |
+ bytes[7] << 24,
+ unsigned
+ );
+};
+
+/**
+ * Creates a Long from its big endian byte representation.
+ * @param {!Array.<number>} bytes Big endian byte representation
+ * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
+ * @returns {Long} The corresponding Long value
+ */
+Long.fromBytesBE = function fromBytesBE(bytes, unsigned) {
+ return new Long(
+ bytes[4] << 24 |
+ bytes[5] << 16 |
+ bytes[6] << 8 |
+ bytes[7],
+ bytes[0] << 24 |
+ bytes[1] << 16 |
+ bytes[2] << 8 |
+ bytes[3],
+ unsigned
+ );
+};
+
+
+/***/ }),
+
+/***/ "./node_modules/onnx-proto/dist/onnx.js":
+/*!**********************************************!*\
+ !*** ./node_modules/onnx-proto/dist/onnx.js ***!
+ \**********************************************/
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/
+
+
+var $protobuf = __webpack_require__(/*! protobufjs/minimal */ "./node_modules/protobufjs/minimal.js");
+
+// Common aliases
+var $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;
+
+// Exported root namespace
+var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {});
+
+$root.onnx = (function() {
+
+ /**
+ * Namespace onnx.
+ * @exports onnx
+ * @namespace
+ */
+ var onnx = {};
+
+ /**
+ * Version enum.
+ * @name onnx.Version
+ * @enum {string}
+ * @property {number} _START_VERSION=0 _START_VERSION value
+ * @property {number} IR_VERSION_2017_10_10=1 IR_VERSION_2017_10_10 value
+ * @property {number} IR_VERSION_2017_10_30=2 IR_VERSION_2017_10_30 value
+ * @property {number} IR_VERSION_2017_11_3=3 IR_VERSION_2017_11_3 value
+ * @property {number} IR_VERSION_2019_1_22=4 IR_VERSION_2019_1_22 value
+ * @property {number} IR_VERSION=5 IR_VERSION value
+ */
+ onnx.Version = (function() {
+ var valuesById = {}, values = Object.create(valuesById);
+ values[valuesById[0] = "_START_VERSION"] = 0;
+ values[valuesById[1] = "IR_VERSION_2017_10_10"] = 1;
+ values[valuesById[2] = "IR_VERSION_2017_10_30"] = 2;
+ values[valuesById[3] = "IR_VERSION_2017_11_3"] = 3;
+ values[valuesById[4] = "IR_VERSION_2019_1_22"] = 4;
+ values[valuesById[5] = "IR_VERSION"] = 5;
+ return values;
+ })();
+
+ onnx.AttributeProto = (function() {
+
+ /**
+ * Properties of an AttributeProto.
+ * @memberof onnx
+ * @interface IAttributeProto
+ * @property {string|null} [name] AttributeProto name
+ * @property {string|null} [refAttrName] AttributeProto refAttrName
+ * @property {string|null} [docString] AttributeProto docString
+ * @property {onnx.AttributeProto.AttributeType|null} [type] AttributeProto type
+ * @property {number|null} [f] AttributeProto f
+ * @property {number|Long|null} [i] AttributeProto i
+ * @property {Uint8Array|null} [s] AttributeProto s
+ * @property {onnx.ITensorProto|null} [t] AttributeProto t
+ * @property {onnx.IGraphProto|null} [g] AttributeProto g
+ * @property {Array.<number>|null} [floats] AttributeProto floats
+ * @property {Array.<number|Long>|null} [ints] AttributeProto ints
+ * @property {Array.<Uint8Array>|null} [strings] AttributeProto strings
+ * @property {Array.<onnx.ITensorProto>|null} [tensors] AttributeProto tensors
+ * @property {Array.<onnx.IGraphProto>|null} [graphs] AttributeProto graphs
+ */
+
+ /**
+ * Constructs a new AttributeProto.
+ * @memberof onnx
+ * @classdesc Represents an AttributeProto.
+ * @implements IAttributeProto
+ * @constructor
+ * @param {onnx.IAttributeProto=} [properties] Properties to set
+ */
+ function AttributeProto(properties) {
+ this.floats = [];
+ this.ints = [];
+ this.strings = [];
+ this.tensors = [];
+ this.graphs = [];
+ if (properties)
+ for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
+ if (properties[keys[i]] != null)
+ this[keys[i]] = properties[keys[i]];
+ }
+
+ /**
+ * AttributeProto name.
+ * @member {string} name
+ * @memberof onnx.AttributeProto
+ * @instance
+ */
+ AttributeProto.prototype.name = "";
+
+ /**
+ * AttributeProto refAttrName.
+ * @member {string} refAttrName
+ * @memberof onnx.AttributeProto
+ * @instance
+ */
+ AttributeProto.prototype.refAttrName = "";
+
+ /**
+ * AttributeProto docString.
+ * @member {string} docString
+ * @memberof onnx.AttributeProto
+ * @instance
+ */
+ AttributeProto.prototype.docString = "";
+
+ /**
+ * AttributeProto type.
+ * @member {onnx.AttributeProto.AttributeType} type
+ * @memberof onnx.AttributeProto
+ * @instance
+ */
+ AttributeProto.prototype.type = 0;
+
+ /**
+ * AttributeProto f.
+ * @member {number} f
+ * @memberof onnx.AttributeProto
+ * @instance
+ */
+ AttributeProto.prototype.f = 0;
+
+ /**
+ * AttributeProto i.
+ * @member {number|Long} i
+ * @memberof onnx.AttributeProto
+ * @instance
+ */
+ AttributeProto.prototype.i = $util.Long ? $util.Long.fromBits(0,0,false) : 0;
+
+ /**
+ * AttributeProto s.
+ * @member {Uint8Array} s
+ * @memberof onnx.AttributeProto
+ * @instance
+ */
+ AttributeProto.prototype.s = $util.newBuffer([]);
+
+ /**
+ * AttributeProto t.
+ * @member {onnx.ITensorProto|null|undefined} t
+ * @memberof onnx.AttributeProto
+ * @instance
+ */
+ AttributeProto.prototype.t = null;
+
+ /**
+ * AttributeProto g.
+ * @member {onnx.IGraphProto|null|undefined} g
+ * @memberof onnx.AttributeProto
+ * @instance
+ */
+ AttributeProto.prototype.g = null;
+
+ /**
+ * AttributeProto floats.
+ * @member {Array.<number>} floats
+ * @memberof onnx.AttributeProto
+ * @instance
+ */
+ AttributeProto.prototype.floats = $util.emptyArray;
+
+ /**
+ * AttributeProto ints.
+ * @member {Array.<number|Long>} ints
+ * @memberof onnx.AttributeProto
+ * @instance
+ */
+ AttributeProto.prototype.ints = $util.emptyArray;
+
+ /**
+ * AttributeProto strings.
+ * @member {Array.<Uint8Array>} strings
+ * @memberof onnx.AttributeProto
+ * @instance
+ */
+ AttributeProto.prototype.strings = $util.emptyArray;
+
+ /**
+ * AttributeProto tensors.
+ * @member {Array.<onnx.ITensorProto>} tensors
+ * @memberof onnx.AttributeProto
+ * @instance
+ */
+ AttributeProto.prototype.tensors = $util.emptyArray;
+
+ /**
+ * AttributeProto graphs.
+ * @member {Array.<onnx.IGraphProto>} graphs
+ * @memberof onnx.AttributeProto
+ * @instance
+ */
+ AttributeProto.prototype.graphs = $util.emptyArray;
+
+ /**
+ * Creates a new AttributeProto instance using the specified properties.
+ * @function create
+ * @memberof onnx.AttributeProto
+ * @static
+ * @param {onnx.IAttributeProto=} [properties] Properties to set
+ * @returns {onnx.AttributeProto} AttributeProto instance
+ */
+ AttributeProto.create = function create(properties) {
+ return new AttributeProto(properties);
+ };
+
+ /**
+ * Encodes the specified AttributeProto message. Does not implicitly {@link onnx.AttributeProto.verify|verify} messages.
+ * @function encode
+ * @memberof onnx.AttributeProto
+ * @static
+ * @param {onnx.IAttributeProto} message AttributeProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ AttributeProto.encode = function encode(message, writer) {
+ if (!writer)
+ writer = $Writer.create();
+ if (message.name != null && message.hasOwnProperty("name"))
+ writer.uint32(/* id 1, wireType 2 =*/10).string(message.name);
+ if (message.f != null && message.hasOwnProperty("f"))
+ writer.uint32(/* id 2, wireType 5 =*/21).float(message.f);
+ if (message.i != null && message.hasOwnProperty("i"))
+ writer.uint32(/* id 3, wireType 0 =*/24).int64(message.i);
+ if (message.s != null && message.hasOwnProperty("s"))
+ writer.uint32(/* id 4, wireType 2 =*/34).bytes(message.s);
+ if (message.t != null && message.hasOwnProperty("t"))
+ $root.onnx.TensorProto.encode(message.t, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim();
+ if (message.g != null && message.hasOwnProperty("g"))
+ $root.onnx.GraphProto.encode(message.g, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim();
+ if (message.floats != null && message.floats.length) {
+ writer.uint32(/* id 7, wireType 2 =*/58).fork();
+ for (var i = 0; i < message.floats.length; ++i)
+ writer.float(message.floats[i]);
+ writer.ldelim();
+ }
+ if (message.ints != null && message.ints.length) {
+ writer.uint32(/* id 8, wireType 2 =*/66).fork();
+ for (var i = 0; i < message.ints.length; ++i)
+ writer.int64(message.ints[i]);
+ writer.ldelim();
+ }
+ if (message.strings != null && message.strings.length)
+ for (var i = 0; i < message.strings.length; ++i)
+ writer.uint32(/* id 9, wireType 2 =*/74).bytes(message.strings[i]);
+ if (message.tensors != null && message.tensors.length)
+ for (var i = 0; i < message.tensors.length; ++i)
+ $root.onnx.TensorProto.encode(message.tensors[i], writer.uint32(/* id 10, wireType 2 =*/82).fork()).ldelim();
+ if (message.graphs != null && message.graphs.length)
+ for (var i = 0; i < message.graphs.length; ++i)
+ $root.onnx.GraphProto.encode(message.graphs[i], writer.uint32(/* id 11, wireType 2 =*/90).fork()).ldelim();
+ if (message.docString != null && message.hasOwnProperty("docString"))
+ writer.uint32(/* id 13, wireType 2 =*/106).string(message.docString);
+ if (message.type != null && message.hasOwnProperty("type"))
+ writer.uint32(/* id 20, wireType 0 =*/160).int32(message.type);
+ if (message.refAttrName != null && message.hasOwnProperty("refAttrName"))
+ writer.uint32(/* id 21, wireType 2 =*/170).string(message.refAttrName);
+ return writer;
+ };
+
+ /**
+ * Encodes the specified AttributeProto message, length delimited. Does not implicitly {@link onnx.AttributeProto.verify|verify} messages.
+ * @function encodeDelimited
+ * @memberof onnx.AttributeProto
+ * @static
+ * @param {onnx.IAttributeProto} message AttributeProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ AttributeProto.encodeDelimited = function encodeDelimited(message, writer) {
+ return this.encode(message, writer).ldelim();
+ };
+
+ /**
+ * Decodes an AttributeProto message from the specified reader or buffer.
+ * @function decode
+ * @memberof onnx.AttributeProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @param {number} [length] Message length if known beforehand
+ * @returns {onnx.AttributeProto} AttributeProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ AttributeProto.decode = function decode(reader, length) {
+ if (!(reader instanceof $Reader))
+ reader = $Reader.create(reader);
+ var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.AttributeProto();
+ while (reader.pos < end) {
+ var tag = reader.uint32();
+ switch (tag >>> 3) {
+ case 1:
+ message.name = reader.string();
+ break;
+ case 21:
+ message.refAttrName = reader.string();
+ break;
+ case 13:
+ message.docString = reader.string();
+ break;
+ case 20:
+ message.type = reader.int32();
+ break;
+ case 2:
+ message.f = reader.float();
+ break;
+ case 3:
+ message.i = reader.int64();
+ break;
+ case 4:
+ message.s = reader.bytes();
+ break;
+ case 5:
+ message.t = $root.onnx.TensorProto.decode(reader, reader.uint32());
+ break;
+ case 6:
+ message.g = $root.onnx.GraphProto.decode(reader, reader.uint32());
+ break;
+ case 7:
+ if (!(message.floats && message.floats.length))
+ message.floats = [];
+ if ((tag & 7) === 2) {
+ var end2 = reader.uint32() + reader.pos;
+ while (reader.pos < end2)
+ message.floats.push(reader.float());
+ } else
+ message.floats.push(reader.float());
+ break;
+ case 8:
+ if (!(message.ints && message.ints.length))
+ message.ints = [];
+ if ((tag & 7) === 2) {
+ var end2 = reader.uint32() + reader.pos;
+ while (reader.pos < end2)
+ message.ints.push(reader.int64());
+ } else
+ message.ints.push(reader.int64());
+ break;
+ case 9:
+ if (!(message.strings && message.strings.length))
+ message.strings = [];
+ message.strings.push(reader.bytes());
+ break;
+ case 10:
+ if (!(message.tensors && message.tensors.length))
+ message.tensors = [];
+ message.tensors.push($root.onnx.TensorProto.decode(reader, reader.uint32()));
+ break;
+ case 11:
+ if (!(message.graphs && message.graphs.length))
+ message.graphs = [];
+ message.graphs.push($root.onnx.GraphProto.decode(reader, reader.uint32()));
+ break;
+ default:
+ reader.skipType(tag & 7);
+ break;
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Decodes an AttributeProto message from the specified reader or buffer, length delimited.
+ * @function decodeDelimited
+ * @memberof onnx.AttributeProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @returns {onnx.AttributeProto} AttributeProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ AttributeProto.decodeDelimited = function decodeDelimited(reader) {
+ if (!(reader instanceof $Reader))
+ reader = new $Reader(reader);
+ return this.decode(reader, reader.uint32());
+ };
+
+ /**
+ * Verifies an AttributeProto message.
+ * @function verify
+ * @memberof onnx.AttributeProto
+ * @static
+ * @param {Object.<string,*>} message Plain object to verify
+ * @returns {string|null} `null` if valid, otherwise the reason why it is not
+ */
+ AttributeProto.verify = function verify(message) {
+ if (typeof message !== "object" || message === null)
+ return "object expected";
+ if (message.name != null && message.hasOwnProperty("name"))
+ if (!$util.isString(message.name))
+ return "name: string expected";
+ if (message.refAttrName != null && message.hasOwnProperty("refAttrName"))
+ if (!$util.isString(message.refAttrName))
+ return "refAttrName: string expected";
+ if (message.docString != null && message.hasOwnProperty("docString"))
+ if (!$util.isString(message.docString))
+ return "docString: string expected";
+ if (message.type != null && message.hasOwnProperty("type"))
+ switch (message.type) {
+ default:
+ return "type: enum value expected";
+ case 0:
+ case 1:
+ case 2:
+ case 3:
+ case 4:
+ case 5:
+ case 6:
+ case 7:
+ case 8:
+ case 9:
+ case 10:
+ break;
+ }
+ if (message.f != null && message.hasOwnProperty("f"))
+ if (typeof message.f !== "number")
+ return "f: number expected";
+ if (message.i != null && message.hasOwnProperty("i"))
+ if (!$util.isInteger(message.i) && !(message.i && $util.isInteger(message.i.low) && $util.isInteger(message.i.high)))
+ return "i: integer|Long expected";
+ if (message.s != null && message.hasOwnProperty("s"))
+ if (!(message.s && typeof message.s.length === "number" || $util.isString(message.s)))
+ return "s: buffer expected";
+ if (message.t != null && message.hasOwnProperty("t")) {
+ var error = $root.onnx.TensorProto.verify(message.t);
+ if (error)
+ return "t." + error;
+ }
+ if (message.g != null && message.hasOwnProperty("g")) {
+ var error = $root.onnx.GraphProto.verify(message.g);
+ if (error)
+ return "g." + error;
+ }
+ if (message.floats != null && message.hasOwnProperty("floats")) {
+ if (!Array.isArray(message.floats))
+ return "floats: array expected";
+ for (var i = 0; i < message.floats.length; ++i)
+ if (typeof message.floats[i] !== "number")
+ return "floats: number[] expected";
+ }
+ if (message.ints != null && message.hasOwnProperty("ints")) {
+ if (!Array.isArray(message.ints))
+ return "ints: array expected";
+ for (var i = 0; i < message.ints.length; ++i)
+ if (!$util.isInteger(message.ints[i]) && !(message.ints[i] && $util.isInteger(message.ints[i].low) && $util.isInteger(message.ints[i].high)))
+ return "ints: integer|Long[] expected";
+ }
+ if (message.strings != null && message.hasOwnProperty("strings")) {
+ if (!Array.isArray(message.strings))
+ return "strings: array expected";
+ for (var i = 0; i < message.strings.length; ++i)
+ if (!(message.strings[i] && typeof message.strings[i].length === "number" || $util.isString(message.strings[i])))
+ return "strings: buffer[] expected";
+ }
+ if (message.tensors != null && message.hasOwnProperty("tensors")) {
+ if (!Array.isArray(message.tensors))
+ return "tensors: array expected";
+ for (var i = 0; i < message.tensors.length; ++i) {
+ var error = $root.onnx.TensorProto.verify(message.tensors[i]);
+ if (error)
+ return "tensors." + error;
+ }
+ }
+ if (message.graphs != null && message.hasOwnProperty("graphs")) {
+ if (!Array.isArray(message.graphs))
+ return "graphs: array expected";
+ for (var i = 0; i < message.graphs.length; ++i) {
+ var error = $root.onnx.GraphProto.verify(message.graphs[i]);
+ if (error)
+ return "graphs." + error;
+ }
+ }
+ return null;
+ };
+
+ /**
+ * Creates an AttributeProto message from a plain object. Also converts values to their respective internal types.
+ * @function fromObject
+ * @memberof onnx.AttributeProto
+ * @static
+ * @param {Object.<string,*>} object Plain object
+ * @returns {onnx.AttributeProto} AttributeProto
+ */
+ AttributeProto.fromObject = function fromObject(object) {
+ if (object instanceof $root.onnx.AttributeProto)
+ return object;
+ var message = new $root.onnx.AttributeProto();
+ if (object.name != null)
+ message.name = String(object.name);
+ if (object.refAttrName != null)
+ message.refAttrName = String(object.refAttrName);
+ if (object.docString != null)
+ message.docString = String(object.docString);
+ switch (object.type) {
+ case "UNDEFINED":
+ case 0:
+ message.type = 0;
+ break;
+ case "FLOAT":
+ case 1:
+ message.type = 1;
+ break;
+ case "INT":
+ case 2:
+ message.type = 2;
+ break;
+ case "STRING":
+ case 3:
+ message.type = 3;
+ break;
+ case "TENSOR":
+ case 4:
+ message.type = 4;
+ break;
+ case "GRAPH":
+ case 5:
+ message.type = 5;
+ break;
+ case "FLOATS":
+ case 6:
+ message.type = 6;
+ break;
+ case "INTS":
+ case 7:
+ message.type = 7;
+ break;
+ case "STRINGS":
+ case 8:
+ message.type = 8;
+ break;
+ case "TENSORS":
+ case 9:
+ message.type = 9;
+ break;
+ case "GRAPHS":
+ case 10:
+ message.type = 10;
+ break;
+ }
+ if (object.f != null)
+ message.f = Number(object.f);
+ if (object.i != null)
+ if ($util.Long)
+ (message.i = $util.Long.fromValue(object.i)).unsigned = false;
+ else if (typeof object.i === "string")
+ message.i = parseInt(object.i, 10);
+ else if (typeof object.i === "number")
+ message.i = object.i;
+ else if (typeof object.i === "object")
+ message.i = new $util.LongBits(object.i.low >>> 0, object.i.high >>> 0).toNumber();
+ if (object.s != null)
+ if (typeof object.s === "string")
+ $util.base64.decode(object.s, message.s = $util.newBuffer($util.base64.length(object.s)), 0);
+ else if (object.s.length)
+ message.s = object.s;
+ if (object.t != null) {
+ if (typeof object.t !== "object")
+ throw TypeError(".onnx.AttributeProto.t: object expected");
+ message.t = $root.onnx.TensorProto.fromObject(object.t);
+ }
+ if (object.g != null) {
+ if (typeof object.g !== "object")
+ throw TypeError(".onnx.AttributeProto.g: object expected");
+ message.g = $root.onnx.GraphProto.fromObject(object.g);
+ }
+ if (object.floats) {
+ if (!Array.isArray(object.floats))
+ throw TypeError(".onnx.AttributeProto.floats: array expected");
+ message.floats = [];
+ for (var i = 0; i < object.floats.length; ++i)
+ message.floats[i] = Number(object.floats[i]);
+ }
+ if (object.ints) {
+ if (!Array.isArray(object.ints))
+ throw TypeError(".onnx.AttributeProto.ints: array expected");
+ message.ints = [];
+ for (var i = 0; i < object.ints.length; ++i)
+ if ($util.Long)
+ (message.ints[i] = $util.Long.fromValue(object.ints[i])).unsigned = false;
+ else if (typeof object.ints[i] === "string")
+ message.ints[i] = parseInt(object.ints[i], 10);
+ else if (typeof object.ints[i] === "number")
+ message.ints[i] = object.ints[i];
+ else if (typeof object.ints[i] === "object")
+ message.ints[i] = new $util.LongBits(object.ints[i].low >>> 0, object.ints[i].high >>> 0).toNumber();
+ }
+ if (object.strings) {
+ if (!Array.isArray(object.strings))
+ throw TypeError(".onnx.AttributeProto.strings: array expected");
+ message.strings = [];
+ for (var i = 0; i < object.strings.length; ++i)
+ if (typeof object.strings[i] === "string")
+ $util.base64.decode(object.strings[i], message.strings[i] = $util.newBuffer($util.base64.length(object.strings[i])), 0);
+ else if (object.strings[i].length)
+ message.strings[i] = object.strings[i];
+ }
+ if (object.tensors) {
+ if (!Array.isArray(object.tensors))
+ throw TypeError(".onnx.AttributeProto.tensors: array expected");
+ message.tensors = [];
+ for (var i = 0; i < object.tensors.length; ++i) {
+ if (typeof object.tensors[i] !== "object")
+ throw TypeError(".onnx.AttributeProto.tensors: object expected");
+ message.tensors[i] = $root.onnx.TensorProto.fromObject(object.tensors[i]);
+ }
+ }
+ if (object.graphs) {
+ if (!Array.isArray(object.graphs))
+ throw TypeError(".onnx.AttributeProto.graphs: array expected");
+ message.graphs = [];
+ for (var i = 0; i < object.graphs.length; ++i) {
+ if (typeof object.graphs[i] !== "object")
+ throw TypeError(".onnx.AttributeProto.graphs: object expected");
+ message.graphs[i] = $root.onnx.GraphProto.fromObject(object.graphs[i]);
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Creates a plain object from an AttributeProto message. Also converts values to other types if specified.
+ * @function toObject
+ * @memberof onnx.AttributeProto
+ * @static
+ * @param {onnx.AttributeProto} message AttributeProto
+ * @param {$protobuf.IConversionOptions} [options] Conversion options
+ * @returns {Object.<string,*>} Plain object
+ */
+ AttributeProto.toObject = function toObject(message, options) {
+ if (!options)
+ options = {};
+ var object = {};
+ if (options.arrays || options.defaults) {
+ object.floats = [];
+ object.ints = [];
+ object.strings = [];
+ object.tensors = [];
+ object.graphs = [];
+ }
+ if (options.defaults) {
+ object.name = "";
+ object.f = 0;
+ if ($util.Long) {
+ var long = new $util.Long(0, 0, false);
+ object.i = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
+ } else
+ object.i = options.longs === String ? "0" : 0;
+ if (options.bytes === String)
+ object.s = "";
+ else {
+ object.s = [];
+ if (options.bytes !== Array)
+ object.s = $util.newBuffer(object.s);
+ }
+ object.t = null;
+ object.g = null;
+ object.docString = "";
+ object.type = options.enums === String ? "UNDEFINED" : 0;
+ object.refAttrName = "";
+ }
+ if (message.name != null && message.hasOwnProperty("name"))
+ object.name = message.name;
+ if (message.f != null && message.hasOwnProperty("f"))
+ object.f = options.json && !isFinite(message.f) ? String(message.f) : message.f;
+ if (message.i != null && message.hasOwnProperty("i"))
+ if (typeof message.i === "number")
+ object.i = options.longs === String ? String(message.i) : message.i;
+ else
+ object.i = options.longs === String ? $util.Long.prototype.toString.call(message.i) : options.longs === Number ? new $util.LongBits(message.i.low >>> 0, message.i.high >>> 0).toNumber() : message.i;
+ if (message.s != null && message.hasOwnProperty("s"))
+ object.s = options.bytes === String ? $util.base64.encode(message.s, 0, message.s.length) : options.bytes === Array ? Array.prototype.slice.call(message.s) : message.s;
+ if (message.t != null && message.hasOwnProperty("t"))
+ object.t = $root.onnx.TensorProto.toObject(message.t, options);
+ if (message.g != null && message.hasOwnProperty("g"))
+ object.g = $root.onnx.GraphProto.toObject(message.g, options);
+ if (message.floats && message.floats.length) {
+ object.floats = [];
+ for (var j = 0; j < message.floats.length; ++j)
+ object.floats[j] = options.json && !isFinite(message.floats[j]) ? String(message.floats[j]) : message.floats[j];
+ }
+ if (message.ints && message.ints.length) {
+ object.ints = [];
+ for (var j = 0; j < message.ints.length; ++j)
+ if (typeof message.ints[j] === "number")
+ object.ints[j] = options.longs === String ? String(message.ints[j]) : message.ints[j];
+ else
+ object.ints[j] = options.longs === String ? $util.Long.prototype.toString.call(message.ints[j]) : options.longs === Number ? new $util.LongBits(message.ints[j].low >>> 0, message.ints[j].high >>> 0).toNumber() : message.ints[j];
+ }
+ if (message.strings && message.strings.length) {
+ object.strings = [];
+ for (var j = 0; j < message.strings.length; ++j)
+ object.strings[j] = options.bytes === String ? $util.base64.encode(message.strings[j], 0, message.strings[j].length) : options.bytes === Array ? Array.prototype.slice.call(message.strings[j]) : message.strings[j];
+ }
+ if (message.tensors && message.tensors.length) {
+ object.tensors = [];
+ for (var j = 0; j < message.tensors.length; ++j)
+ object.tensors[j] = $root.onnx.TensorProto.toObject(message.tensors[j], options);
+ }
+ if (message.graphs && message.graphs.length) {
+ object.graphs = [];
+ for (var j = 0; j < message.graphs.length; ++j)
+ object.graphs[j] = $root.onnx.GraphProto.toObject(message.graphs[j], options);
+ }
+ if (message.docString != null && message.hasOwnProperty("docString"))
+ object.docString = message.docString;
+ if (message.type != null && message.hasOwnProperty("type"))
+ object.type = options.enums === String ? $root.onnx.AttributeProto.AttributeType[message.type] : message.type;
+ if (message.refAttrName != null && message.hasOwnProperty("refAttrName"))
+ object.refAttrName = message.refAttrName;
+ return object;
+ };
+
+ /**
+ * Converts this AttributeProto to JSON.
+ * @function toJSON
+ * @memberof onnx.AttributeProto
+ * @instance
+ * @returns {Object.<string,*>} JSON object
+ */
+ AttributeProto.prototype.toJSON = function toJSON() {
+ return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
+ };
+
+ /**
+ * AttributeType enum.
+ * @name onnx.AttributeProto.AttributeType
+ * @enum {string}
+ * @property {number} UNDEFINED=0 UNDEFINED value
+ * @property {number} FLOAT=1 FLOAT value
+ * @property {number} INT=2 INT value
+ * @property {number} STRING=3 STRING value
+ * @property {number} TENSOR=4 TENSOR value
+ * @property {number} GRAPH=5 GRAPH value
+ * @property {number} FLOATS=6 FLOATS value
+ * @property {number} INTS=7 INTS value
+ * @property {number} STRINGS=8 STRINGS value
+ * @property {number} TENSORS=9 TENSORS value
+ * @property {number} GRAPHS=10 GRAPHS value
+ */
+ AttributeProto.AttributeType = (function() {
+ var valuesById = {}, values = Object.create(valuesById);
+ values[valuesById[0] = "UNDEFINED"] = 0;
+ values[valuesById[1] = "FLOAT"] = 1;
+ values[valuesById[2] = "INT"] = 2;
+ values[valuesById[3] = "STRING"] = 3;
+ values[valuesById[4] = "TENSOR"] = 4;
+ values[valuesById[5] = "GRAPH"] = 5;
+ values[valuesById[6] = "FLOATS"] = 6;
+ values[valuesById[7] = "INTS"] = 7;
+ values[valuesById[8] = "STRINGS"] = 8;
+ values[valuesById[9] = "TENSORS"] = 9;
+ values[valuesById[10] = "GRAPHS"] = 10;
+ return values;
+ })();
+
+ return AttributeProto;
+ })();
+
+ onnx.ValueInfoProto = (function() {
+
+ /**
+ * Properties of a ValueInfoProto.
+ * @memberof onnx
+ * @interface IValueInfoProto
+ * @property {string|null} [name] ValueInfoProto name
+ * @property {onnx.ITypeProto|null} [type] ValueInfoProto type
+ * @property {string|null} [docString] ValueInfoProto docString
+ */
+
+ /**
+ * Constructs a new ValueInfoProto.
+ * @memberof onnx
+ * @classdesc Represents a ValueInfoProto.
+ * @implements IValueInfoProto
+ * @constructor
+ * @param {onnx.IValueInfoProto=} [properties] Properties to set
+ */
+ function ValueInfoProto(properties) {
+ if (properties)
+ for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
+ if (properties[keys[i]] != null)
+ this[keys[i]] = properties[keys[i]];
+ }
+
+ /**
+ * ValueInfoProto name.
+ * @member {string} name
+ * @memberof onnx.ValueInfoProto
+ * @instance
+ */
+ ValueInfoProto.prototype.name = "";
+
+ /**
+ * ValueInfoProto type.
+ * @member {onnx.ITypeProto|null|undefined} type
+ * @memberof onnx.ValueInfoProto
+ * @instance
+ */
+ ValueInfoProto.prototype.type = null;
+
+ /**
+ * ValueInfoProto docString.
+ * @member {string} docString
+ * @memberof onnx.ValueInfoProto
+ * @instance
+ */
+ ValueInfoProto.prototype.docString = "";
+
+ /**
+ * Creates a new ValueInfoProto instance using the specified properties.
+ * @function create
+ * @memberof onnx.ValueInfoProto
+ * @static
+ * @param {onnx.IValueInfoProto=} [properties] Properties to set
+ * @returns {onnx.ValueInfoProto} ValueInfoProto instance
+ */
+ ValueInfoProto.create = function create(properties) {
+ return new ValueInfoProto(properties);
+ };
+
+ /**
+ * Encodes the specified ValueInfoProto message. Does not implicitly {@link onnx.ValueInfoProto.verify|verify} messages.
+ * @function encode
+ * @memberof onnx.ValueInfoProto
+ * @static
+ * @param {onnx.IValueInfoProto} message ValueInfoProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ ValueInfoProto.encode = function encode(message, writer) {
+ if (!writer)
+ writer = $Writer.create();
+ if (message.name != null && message.hasOwnProperty("name"))
+ writer.uint32(/* id 1, wireType 2 =*/10).string(message.name);
+ if (message.type != null && message.hasOwnProperty("type"))
+ $root.onnx.TypeProto.encode(message.type, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();
+ if (message.docString != null && message.hasOwnProperty("docString"))
+ writer.uint32(/* id 3, wireType 2 =*/26).string(message.docString);
+ return writer;
+ };
+
+ /**
+ * Encodes the specified ValueInfoProto message, length delimited. Does not implicitly {@link onnx.ValueInfoProto.verify|verify} messages.
+ * @function encodeDelimited
+ * @memberof onnx.ValueInfoProto
+ * @static
+ * @param {onnx.IValueInfoProto} message ValueInfoProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ ValueInfoProto.encodeDelimited = function encodeDelimited(message, writer) {
+ return this.encode(message, writer).ldelim();
+ };
+
+ /**
+ * Decodes a ValueInfoProto message from the specified reader or buffer.
+ * @function decode
+ * @memberof onnx.ValueInfoProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @param {number} [length] Message length if known beforehand
+ * @returns {onnx.ValueInfoProto} ValueInfoProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ ValueInfoProto.decode = function decode(reader, length) {
+ if (!(reader instanceof $Reader))
+ reader = $Reader.create(reader);
+ var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.ValueInfoProto();
+ while (reader.pos < end) {
+ var tag = reader.uint32();
+ switch (tag >>> 3) {
+ case 1:
+ message.name = reader.string();
+ break;
+ case 2:
+ message.type = $root.onnx.TypeProto.decode(reader, reader.uint32());
+ break;
+ case 3:
+ message.docString = reader.string();
+ break;
+ default:
+ reader.skipType(tag & 7);
+ break;
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Decodes a ValueInfoProto message from the specified reader or buffer, length delimited.
+ * @function decodeDelimited
+ * @memberof onnx.ValueInfoProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @returns {onnx.ValueInfoProto} ValueInfoProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ ValueInfoProto.decodeDelimited = function decodeDelimited(reader) {
+ if (!(reader instanceof $Reader))
+ reader = new $Reader(reader);
+ return this.decode(reader, reader.uint32());
+ };
+
+ /**
+ * Verifies a ValueInfoProto message.
+ * @function verify
+ * @memberof onnx.ValueInfoProto
+ * @static
+ * @param {Object.<string,*>} message Plain object to verify
+ * @returns {string|null} `null` if valid, otherwise the reason why it is not
+ */
+ ValueInfoProto.verify = function verify(message) {
+ if (typeof message !== "object" || message === null)
+ return "object expected";
+ if (message.name != null && message.hasOwnProperty("name"))
+ if (!$util.isString(message.name))
+ return "name: string expected";
+ if (message.type != null && message.hasOwnProperty("type")) {
+ var error = $root.onnx.TypeProto.verify(message.type);
+ if (error)
+ return "type." + error;
+ }
+ if (message.docString != null && message.hasOwnProperty("docString"))
+ if (!$util.isString(message.docString))
+ return "docString: string expected";
+ return null;
+ };
+
+ /**
+ * Creates a ValueInfoProto message from a plain object. Also converts values to their respective internal types.
+ * @function fromObject
+ * @memberof onnx.ValueInfoProto
+ * @static
+ * @param {Object.<string,*>} object Plain object
+ * @returns {onnx.ValueInfoProto} ValueInfoProto
+ */
+ ValueInfoProto.fromObject = function fromObject(object) {
+ if (object instanceof $root.onnx.ValueInfoProto)
+ return object;
+ var message = new $root.onnx.ValueInfoProto();
+ if (object.name != null)
+ message.name = String(object.name);
+ if (object.type != null) {
+ if (typeof object.type !== "object")
+ throw TypeError(".onnx.ValueInfoProto.type: object expected");
+ message.type = $root.onnx.TypeProto.fromObject(object.type);
+ }
+ if (object.docString != null)
+ message.docString = String(object.docString);
+ return message;
+ };
+
+ /**
+ * Creates a plain object from a ValueInfoProto message. Also converts values to other types if specified.
+ * @function toObject
+ * @memberof onnx.ValueInfoProto
+ * @static
+ * @param {onnx.ValueInfoProto} message ValueInfoProto
+ * @param {$protobuf.IConversionOptions} [options] Conversion options
+ * @returns {Object.<string,*>} Plain object
+ */
+ ValueInfoProto.toObject = function toObject(message, options) {
+ if (!options)
+ options = {};
+ var object = {};
+ if (options.defaults) {
+ object.name = "";
+ object.type = null;
+ object.docString = "";
+ }
+ if (message.name != null && message.hasOwnProperty("name"))
+ object.name = message.name;
+ if (message.type != null && message.hasOwnProperty("type"))
+ object.type = $root.onnx.TypeProto.toObject(message.type, options);
+ if (message.docString != null && message.hasOwnProperty("docString"))
+ object.docString = message.docString;
+ return object;
+ };
+
+ /**
+ * Converts this ValueInfoProto to JSON.
+ * @function toJSON
+ * @memberof onnx.ValueInfoProto
+ * @instance
+ * @returns {Object.<string,*>} JSON object
+ */
+ ValueInfoProto.prototype.toJSON = function toJSON() {
+ return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
+ };
+
+ return ValueInfoProto;
+ })();
+
+ onnx.NodeProto = (function() {
+
+ /**
+ * Properties of a NodeProto.
+ * @memberof onnx
+ * @interface INodeProto
+ * @property {Array.<string>|null} [input] NodeProto input
+ * @property {Array.<string>|null} [output] NodeProto output
+ * @property {string|null} [name] NodeProto name
+ * @property {string|null} [opType] NodeProto opType
+ * @property {string|null} [domain] NodeProto domain
+ * @property {Array.<onnx.IAttributeProto>|null} [attribute] NodeProto attribute
+ * @property {string|null} [docString] NodeProto docString
+ */
+
+ /**
+ * Constructs a new NodeProto.
+ * @memberof onnx
+ * @classdesc Represents a NodeProto.
+ * @implements INodeProto
+ * @constructor
+ * @param {onnx.INodeProto=} [properties] Properties to set
+ */
+ function NodeProto(properties) {
+ this.input = [];
+ this.output = [];
+ this.attribute = [];
+ if (properties)
+ for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
+ if (properties[keys[i]] != null)
+ this[keys[i]] = properties[keys[i]];
+ }
+
+ /**
+ * NodeProto input.
+ * @member {Array.<string>} input
+ * @memberof onnx.NodeProto
+ * @instance
+ */
+ NodeProto.prototype.input = $util.emptyArray;
+
+ /**
+ * NodeProto output.
+ * @member {Array.<string>} output
+ * @memberof onnx.NodeProto
+ * @instance
+ */
+ NodeProto.prototype.output = $util.emptyArray;
+
+ /**
+ * NodeProto name.
+ * @member {string} name
+ * @memberof onnx.NodeProto
+ * @instance
+ */
+ NodeProto.prototype.name = "";
+
+ /**
+ * NodeProto opType.
+ * @member {string} opType
+ * @memberof onnx.NodeProto
+ * @instance
+ */
+ NodeProto.prototype.opType = "";
+
+ /**
+ * NodeProto domain.
+ * @member {string} domain
+ * @memberof onnx.NodeProto
+ * @instance
+ */
+ NodeProto.prototype.domain = "";
+
+ /**
+ * NodeProto attribute.
+ * @member {Array.<onnx.IAttributeProto>} attribute
+ * @memberof onnx.NodeProto
+ * @instance
+ */
+ NodeProto.prototype.attribute = $util.emptyArray;
+
+ /**
+ * NodeProto docString.
+ * @member {string} docString
+ * @memberof onnx.NodeProto
+ * @instance
+ */
+ NodeProto.prototype.docString = "";
+
+ /**
+ * Creates a new NodeProto instance using the specified properties.
+ * @function create
+ * @memberof onnx.NodeProto
+ * @static
+ * @param {onnx.INodeProto=} [properties] Properties to set
+ * @returns {onnx.NodeProto} NodeProto instance
+ */
+ NodeProto.create = function create(properties) {
+ return new NodeProto(properties);
+ };
+
+ /**
+ * Encodes the specified NodeProto message. Does not implicitly {@link onnx.NodeProto.verify|verify} messages.
+ * @function encode
+ * @memberof onnx.NodeProto
+ * @static
+ * @param {onnx.INodeProto} message NodeProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ NodeProto.encode = function encode(message, writer) {
+ if (!writer)
+ writer = $Writer.create();
+ if (message.input != null && message.input.length)
+ for (var i = 0; i < message.input.length; ++i)
+ writer.uint32(/* id 1, wireType 2 =*/10).string(message.input[i]);
+ if (message.output != null && message.output.length)
+ for (var i = 0; i < message.output.length; ++i)
+ writer.uint32(/* id 2, wireType 2 =*/18).string(message.output[i]);
+ if (message.name != null && message.hasOwnProperty("name"))
+ writer.uint32(/* id 3, wireType 2 =*/26).string(message.name);
+ if (message.opType != null && message.hasOwnProperty("opType"))
+ writer.uint32(/* id 4, wireType 2 =*/34).string(message.opType);
+ if (message.attribute != null && message.attribute.length)
+ for (var i = 0; i < message.attribute.length; ++i)
+ $root.onnx.AttributeProto.encode(message.attribute[i], writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim();
+ if (message.docString != null && message.hasOwnProperty("docString"))
+ writer.uint32(/* id 6, wireType 2 =*/50).string(message.docString);
+ if (message.domain != null && message.hasOwnProperty("domain"))
+ writer.uint32(/* id 7, wireType 2 =*/58).string(message.domain);
+ return writer;
+ };
+
+ /**
+ * Encodes the specified NodeProto message, length delimited. Does not implicitly {@link onnx.NodeProto.verify|verify} messages.
+ * @function encodeDelimited
+ * @memberof onnx.NodeProto
+ * @static
+ * @param {onnx.INodeProto} message NodeProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ NodeProto.encodeDelimited = function encodeDelimited(message, writer) {
+ return this.encode(message, writer).ldelim();
+ };
+
+ /**
+ * Decodes a NodeProto message from the specified reader or buffer.
+ * @function decode
+ * @memberof onnx.NodeProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @param {number} [length] Message length if known beforehand
+ * @returns {onnx.NodeProto} NodeProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ NodeProto.decode = function decode(reader, length) {
+ if (!(reader instanceof $Reader))
+ reader = $Reader.create(reader);
+ var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.NodeProto();
+ while (reader.pos < end) {
+ var tag = reader.uint32();
+ switch (tag >>> 3) {
+ case 1:
+ if (!(message.input && message.input.length))
+ message.input = [];
+ message.input.push(reader.string());
+ break;
+ case 2:
+ if (!(message.output && message.output.length))
+ message.output = [];
+ message.output.push(reader.string());
+ break;
+ case 3:
+ message.name = reader.string();
+ break;
+ case 4:
+ message.opType = reader.string();
+ break;
+ case 7:
+ message.domain = reader.string();
+ break;
+ case 5:
+ if (!(message.attribute && message.attribute.length))
+ message.attribute = [];
+ message.attribute.push($root.onnx.AttributeProto.decode(reader, reader.uint32()));
+ break;
+ case 6:
+ message.docString = reader.string();
+ break;
+ default:
+ reader.skipType(tag & 7);
+ break;
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Decodes a NodeProto message from the specified reader or buffer, length delimited.
+ * @function decodeDelimited
+ * @memberof onnx.NodeProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @returns {onnx.NodeProto} NodeProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ NodeProto.decodeDelimited = function decodeDelimited(reader) {
+ if (!(reader instanceof $Reader))
+ reader = new $Reader(reader);
+ return this.decode(reader, reader.uint32());
+ };
+
+ /**
+ * Verifies a NodeProto message.
+ * @function verify
+ * @memberof onnx.NodeProto
+ * @static
+ * @param {Object.<string,*>} message Plain object to verify
+ * @returns {string|null} `null` if valid, otherwise the reason why it is not
+ */
+ NodeProto.verify = function verify(message) {
+ if (typeof message !== "object" || message === null)
+ return "object expected";
+ if (message.input != null && message.hasOwnProperty("input")) {
+ if (!Array.isArray(message.input))
+ return "input: array expected";
+ for (var i = 0; i < message.input.length; ++i)
+ if (!$util.isString(message.input[i]))
+ return "input: string[] expected";
+ }
+ if (message.output != null && message.hasOwnProperty("output")) {
+ if (!Array.isArray(message.output))
+ return "output: array expected";
+ for (var i = 0; i < message.output.length; ++i)
+ if (!$util.isString(message.output[i]))
+ return "output: string[] expected";
+ }
+ if (message.name != null && message.hasOwnProperty("name"))
+ if (!$util.isString(message.name))
+ return "name: string expected";
+ if (message.opType != null && message.hasOwnProperty("opType"))
+ if (!$util.isString(message.opType))
+ return "opType: string expected";
+ if (message.domain != null && message.hasOwnProperty("domain"))
+ if (!$util.isString(message.domain))
+ return "domain: string expected";
+ if (message.attribute != null && message.hasOwnProperty("attribute")) {
+ if (!Array.isArray(message.attribute))
+ return "attribute: array expected";
+ for (var i = 0; i < message.attribute.length; ++i) {
+ var error = $root.onnx.AttributeProto.verify(message.attribute[i]);
+ if (error)
+ return "attribute." + error;
+ }
+ }
+ if (message.docString != null && message.hasOwnProperty("docString"))
+ if (!$util.isString(message.docString))
+ return "docString: string expected";
+ return null;
+ };
+
+ /**
+ * Creates a NodeProto message from a plain object. Also converts values to their respective internal types.
+ * @function fromObject
+ * @memberof onnx.NodeProto
+ * @static
+ * @param {Object.<string,*>} object Plain object
+ * @returns {onnx.NodeProto} NodeProto
+ */
+ NodeProto.fromObject = function fromObject(object) {
+ if (object instanceof $root.onnx.NodeProto)
+ return object;
+ var message = new $root.onnx.NodeProto();
+ if (object.input) {
+ if (!Array.isArray(object.input))
+ throw TypeError(".onnx.NodeProto.input: array expected");
+ message.input = [];
+ for (var i = 0; i < object.input.length; ++i)
+ message.input[i] = String(object.input[i]);
+ }
+ if (object.output) {
+ if (!Array.isArray(object.output))
+ throw TypeError(".onnx.NodeProto.output: array expected");
+ message.output = [];
+ for (var i = 0; i < object.output.length; ++i)
+ message.output[i] = String(object.output[i]);
+ }
+ if (object.name != null)
+ message.name = String(object.name);
+ if (object.opType != null)
+ message.opType = String(object.opType);
+ if (object.domain != null)
+ message.domain = String(object.domain);
+ if (object.attribute) {
+ if (!Array.isArray(object.attribute))
+ throw TypeError(".onnx.NodeProto.attribute: array expected");
+ message.attribute = [];
+ for (var i = 0; i < object.attribute.length; ++i) {
+ if (typeof object.attribute[i] !== "object")
+ throw TypeError(".onnx.NodeProto.attribute: object expected");
+ message.attribute[i] = $root.onnx.AttributeProto.fromObject(object.attribute[i]);
+ }
+ }
+ if (object.docString != null)
+ message.docString = String(object.docString);
+ return message;
+ };
+
+ /**
+ * Creates a plain object from a NodeProto message. Also converts values to other types if specified.
+ * @function toObject
+ * @memberof onnx.NodeProto
+ * @static
+ * @param {onnx.NodeProto} message NodeProto
+ * @param {$protobuf.IConversionOptions} [options] Conversion options
+ * @returns {Object.<string,*>} Plain object
+ */
+ NodeProto.toObject = function toObject(message, options) {
+ if (!options)
+ options = {};
+ var object = {};
+ if (options.arrays || options.defaults) {
+ object.input = [];
+ object.output = [];
+ object.attribute = [];
+ }
+ if (options.defaults) {
+ object.name = "";
+ object.opType = "";
+ object.docString = "";
+ object.domain = "";
+ }
+ if (message.input && message.input.length) {
+ object.input = [];
+ for (var j = 0; j < message.input.length; ++j)
+ object.input[j] = message.input[j];
+ }
+ if (message.output && message.output.length) {
+ object.output = [];
+ for (var j = 0; j < message.output.length; ++j)
+ object.output[j] = message.output[j];
+ }
+ if (message.name != null && message.hasOwnProperty("name"))
+ object.name = message.name;
+ if (message.opType != null && message.hasOwnProperty("opType"))
+ object.opType = message.opType;
+ if (message.attribute && message.attribute.length) {
+ object.attribute = [];
+ for (var j = 0; j < message.attribute.length; ++j)
+ object.attribute[j] = $root.onnx.AttributeProto.toObject(message.attribute[j], options);
+ }
+ if (message.docString != null && message.hasOwnProperty("docString"))
+ object.docString = message.docString;
+ if (message.domain != null && message.hasOwnProperty("domain"))
+ object.domain = message.domain;
+ return object;
+ };
+
+ /**
+ * Converts this NodeProto to JSON.
+ * @function toJSON
+ * @memberof onnx.NodeProto
+ * @instance
+ * @returns {Object.<string,*>} JSON object
+ */
+ NodeProto.prototype.toJSON = function toJSON() {
+ return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
+ };
+
+ return NodeProto;
+ })();
+
+ onnx.ModelProto = (function() {
+
+ /**
+ * Properties of a ModelProto.
+ * @memberof onnx
+ * @interface IModelProto
+ * @property {number|Long|null} [irVersion] ModelProto irVersion
+ * @property {Array.<onnx.IOperatorSetIdProto>|null} [opsetImport] ModelProto opsetImport
+ * @property {string|null} [producerName] ModelProto producerName
+ * @property {string|null} [producerVersion] ModelProto producerVersion
+ * @property {string|null} [domain] ModelProto domain
+ * @property {number|Long|null} [modelVersion] ModelProto modelVersion
+ * @property {string|null} [docString] ModelProto docString
+ * @property {onnx.IGraphProto|null} [graph] ModelProto graph
+ * @property {Array.<onnx.IStringStringEntryProto>|null} [metadataProps] ModelProto metadataProps
+ */
+
+ /**
+ * Constructs a new ModelProto.
+ * @memberof onnx
+ * @classdesc Represents a ModelProto.
+ * @implements IModelProto
+ * @constructor
+ * @param {onnx.IModelProto=} [properties] Properties to set
+ */
+ function ModelProto(properties) {
+ this.opsetImport = [];
+ this.metadataProps = [];
+ if (properties)
+ for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
+ if (properties[keys[i]] != null)
+ this[keys[i]] = properties[keys[i]];
+ }
+
+ /**
+ * ModelProto irVersion.
+ * @member {number|Long} irVersion
+ * @memberof onnx.ModelProto
+ * @instance
+ */
+ ModelProto.prototype.irVersion = $util.Long ? $util.Long.fromBits(0,0,false) : 0;
+
+ /**
+ * ModelProto opsetImport.
+ * @member {Array.<onnx.IOperatorSetIdProto>} opsetImport
+ * @memberof onnx.ModelProto
+ * @instance
+ */
+ ModelProto.prototype.opsetImport = $util.emptyArray;
+
+ /**
+ * ModelProto producerName.
+ * @member {string} producerName
+ * @memberof onnx.ModelProto
+ * @instance
+ */
+ ModelProto.prototype.producerName = "";
+
+ /**
+ * ModelProto producerVersion.
+ * @member {string} producerVersion
+ * @memberof onnx.ModelProto
+ * @instance
+ */
+ ModelProto.prototype.producerVersion = "";
+
+ /**
+ * ModelProto domain.
+ * @member {string} domain
+ * @memberof onnx.ModelProto
+ * @instance
+ */
+ ModelProto.prototype.domain = "";
+
+ /**
+ * ModelProto modelVersion.
+ * @member {number|Long} modelVersion
+ * @memberof onnx.ModelProto
+ * @instance
+ */
+ ModelProto.prototype.modelVersion = $util.Long ? $util.Long.fromBits(0,0,false) : 0;
+
+ /**
+ * ModelProto docString.
+ * @member {string} docString
+ * @memberof onnx.ModelProto
+ * @instance
+ */
+ ModelProto.prototype.docString = "";
+
+ /**
+ * ModelProto graph.
+ * @member {onnx.IGraphProto|null|undefined} graph
+ * @memberof onnx.ModelProto
+ * @instance
+ */
+ ModelProto.prototype.graph = null;
+
+ /**
+ * ModelProto metadataProps.
+ * @member {Array.<onnx.IStringStringEntryProto>} metadataProps
+ * @memberof onnx.ModelProto
+ * @instance
+ */
+ ModelProto.prototype.metadataProps = $util.emptyArray;
+
+ /**
+ * Creates a new ModelProto instance using the specified properties.
+ * @function create
+ * @memberof onnx.ModelProto
+ * @static
+ * @param {onnx.IModelProto=} [properties] Properties to set
+ * @returns {onnx.ModelProto} ModelProto instance
+ */
+ ModelProto.create = function create(properties) {
+ return new ModelProto(properties);
+ };
+
+ /**
+ * Encodes the specified ModelProto message. Does not implicitly {@link onnx.ModelProto.verify|verify} messages.
+ * @function encode
+ * @memberof onnx.ModelProto
+ * @static
+ * @param {onnx.IModelProto} message ModelProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ ModelProto.encode = function encode(message, writer) {
+ if (!writer)
+ writer = $Writer.create();
+ if (message.irVersion != null && message.hasOwnProperty("irVersion"))
+ writer.uint32(/* id 1, wireType 0 =*/8).int64(message.irVersion);
+ if (message.producerName != null && message.hasOwnProperty("producerName"))
+ writer.uint32(/* id 2, wireType 2 =*/18).string(message.producerName);
+ if (message.producerVersion != null && message.hasOwnProperty("producerVersion"))
+ writer.uint32(/* id 3, wireType 2 =*/26).string(message.producerVersion);
+ if (message.domain != null && message.hasOwnProperty("domain"))
+ writer.uint32(/* id 4, wireType 2 =*/34).string(message.domain);
+ if (message.modelVersion != null && message.hasOwnProperty("modelVersion"))
+ writer.uint32(/* id 5, wireType 0 =*/40).int64(message.modelVersion);
+ if (message.docString != null && message.hasOwnProperty("docString"))
+ writer.uint32(/* id 6, wireType 2 =*/50).string(message.docString);
+ if (message.graph != null && message.hasOwnProperty("graph"))
+ $root.onnx.GraphProto.encode(message.graph, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim();
+ if (message.opsetImport != null && message.opsetImport.length)
+ for (var i = 0; i < message.opsetImport.length; ++i)
+ $root.onnx.OperatorSetIdProto.encode(message.opsetImport[i], writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim();
+ if (message.metadataProps != null && message.metadataProps.length)
+ for (var i = 0; i < message.metadataProps.length; ++i)
+ $root.onnx.StringStringEntryProto.encode(message.metadataProps[i], writer.uint32(/* id 14, wireType 2 =*/114).fork()).ldelim();
+ return writer;
+ };
+
+ /**
+ * Encodes the specified ModelProto message, length delimited. Does not implicitly {@link onnx.ModelProto.verify|verify} messages.
+ * @function encodeDelimited
+ * @memberof onnx.ModelProto
+ * @static
+ * @param {onnx.IModelProto} message ModelProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ ModelProto.encodeDelimited = function encodeDelimited(message, writer) {
+ return this.encode(message, writer).ldelim();
+ };
+
+ /**
+ * Decodes a ModelProto message from the specified reader or buffer.
+ * @function decode
+ * @memberof onnx.ModelProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @param {number} [length] Message length if known beforehand
+ * @returns {onnx.ModelProto} ModelProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ ModelProto.decode = function decode(reader, length) {
+ if (!(reader instanceof $Reader))
+ reader = $Reader.create(reader);
+ var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.ModelProto();
+ while (reader.pos < end) {
+ var tag = reader.uint32();
+ switch (tag >>> 3) {
+ case 1:
+ message.irVersion = reader.int64();
+ break;
+ case 8:
+ if (!(message.opsetImport && message.opsetImport.length))
+ message.opsetImport = [];
+ message.opsetImport.push($root.onnx.OperatorSetIdProto.decode(reader, reader.uint32()));
+ break;
+ case 2:
+ message.producerName = reader.string();
+ break;
+ case 3:
+ message.producerVersion = reader.string();
+ break;
+ case 4:
+ message.domain = reader.string();
+ break;
+ case 5:
+ message.modelVersion = reader.int64();
+ break;
+ case 6:
+ message.docString = reader.string();
+ break;
+ case 7:
+ message.graph = $root.onnx.GraphProto.decode(reader, reader.uint32());
+ break;
+ case 14:
+ if (!(message.metadataProps && message.metadataProps.length))
+ message.metadataProps = [];
+ message.metadataProps.push($root.onnx.StringStringEntryProto.decode(reader, reader.uint32()));
+ break;
+ default:
+ reader.skipType(tag & 7);
+ break;
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Decodes a ModelProto message from the specified reader or buffer, length delimited.
+ * @function decodeDelimited
+ * @memberof onnx.ModelProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @returns {onnx.ModelProto} ModelProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ ModelProto.decodeDelimited = function decodeDelimited(reader) {
+ if (!(reader instanceof $Reader))
+ reader = new $Reader(reader);
+ return this.decode(reader, reader.uint32());
+ };
+
+ /**
+ * Verifies a ModelProto message.
+ * @function verify
+ * @memberof onnx.ModelProto
+ * @static
+ * @param {Object.<string,*>} message Plain object to verify
+ * @returns {string|null} `null` if valid, otherwise the reason why it is not
+ */
+ ModelProto.verify = function verify(message) {
+ if (typeof message !== "object" || message === null)
+ return "object expected";
+ if (message.irVersion != null && message.hasOwnProperty("irVersion"))
+ if (!$util.isInteger(message.irVersion) && !(message.irVersion && $util.isInteger(message.irVersion.low) && $util.isInteger(message.irVersion.high)))
+ return "irVersion: integer|Long expected";
+ if (message.opsetImport != null && message.hasOwnProperty("opsetImport")) {
+ if (!Array.isArray(message.opsetImport))
+ return "opsetImport: array expected";
+ for (var i = 0; i < message.opsetImport.length; ++i) {
+ var error = $root.onnx.OperatorSetIdProto.verify(message.opsetImport[i]);
+ if (error)
+ return "opsetImport." + error;
+ }
+ }
+ if (message.producerName != null && message.hasOwnProperty("producerName"))
+ if (!$util.isString(message.producerName))
+ return "producerName: string expected";
+ if (message.producerVersion != null && message.hasOwnProperty("producerVersion"))
+ if (!$util.isString(message.producerVersion))
+ return "producerVersion: string expected";
+ if (message.domain != null && message.hasOwnProperty("domain"))
+ if (!$util.isString(message.domain))
+ return "domain: string expected";
+ if (message.modelVersion != null && message.hasOwnProperty("modelVersion"))
+ if (!$util.isInteger(message.modelVersion) && !(message.modelVersion && $util.isInteger(message.modelVersion.low) && $util.isInteger(message.modelVersion.high)))
+ return "modelVersion: integer|Long expected";
+ if (message.docString != null && message.hasOwnProperty("docString"))
+ if (!$util.isString(message.docString))
+ return "docString: string expected";
+ if (message.graph != null && message.hasOwnProperty("graph")) {
+ var error = $root.onnx.GraphProto.verify(message.graph);
+ if (error)
+ return "graph." + error;
+ }
+ if (message.metadataProps != null && message.hasOwnProperty("metadataProps")) {
+ if (!Array.isArray(message.metadataProps))
+ return "metadataProps: array expected";
+ for (var i = 0; i < message.metadataProps.length; ++i) {
+ var error = $root.onnx.StringStringEntryProto.verify(message.metadataProps[i]);
+ if (error)
+ return "metadataProps." + error;
+ }
+ }
+ return null;
+ };
+
+ /**
+ * Creates a ModelProto message from a plain object. Also converts values to their respective internal types.
+ * @function fromObject
+ * @memberof onnx.ModelProto
+ * @static
+ * @param {Object.<string,*>} object Plain object
+ * @returns {onnx.ModelProto} ModelProto
+ */
+ ModelProto.fromObject = function fromObject(object) {
+ if (object instanceof $root.onnx.ModelProto)
+ return object;
+ var message = new $root.onnx.ModelProto();
+ if (object.irVersion != null)
+ if ($util.Long)
+ (message.irVersion = $util.Long.fromValue(object.irVersion)).unsigned = false;
+ else if (typeof object.irVersion === "string")
+ message.irVersion = parseInt(object.irVersion, 10);
+ else if (typeof object.irVersion === "number")
+ message.irVersion = object.irVersion;
+ else if (typeof object.irVersion === "object")
+ message.irVersion = new $util.LongBits(object.irVersion.low >>> 0, object.irVersion.high >>> 0).toNumber();
+ if (object.opsetImport) {
+ if (!Array.isArray(object.opsetImport))
+ throw TypeError(".onnx.ModelProto.opsetImport: array expected");
+ message.opsetImport = [];
+ for (var i = 0; i < object.opsetImport.length; ++i) {
+ if (typeof object.opsetImport[i] !== "object")
+ throw TypeError(".onnx.ModelProto.opsetImport: object expected");
+ message.opsetImport[i] = $root.onnx.OperatorSetIdProto.fromObject(object.opsetImport[i]);
+ }
+ }
+ if (object.producerName != null)
+ message.producerName = String(object.producerName);
+ if (object.producerVersion != null)
+ message.producerVersion = String(object.producerVersion);
+ if (object.domain != null)
+ message.domain = String(object.domain);
+ if (object.modelVersion != null)
+ if ($util.Long)
+ (message.modelVersion = $util.Long.fromValue(object.modelVersion)).unsigned = false;
+ else if (typeof object.modelVersion === "string")
+ message.modelVersion = parseInt(object.modelVersion, 10);
+ else if (typeof object.modelVersion === "number")
+ message.modelVersion = object.modelVersion;
+ else if (typeof object.modelVersion === "object")
+ message.modelVersion = new $util.LongBits(object.modelVersion.low >>> 0, object.modelVersion.high >>> 0).toNumber();
+ if (object.docString != null)
+ message.docString = String(object.docString);
+ if (object.graph != null) {
+ if (typeof object.graph !== "object")
+ throw TypeError(".onnx.ModelProto.graph: object expected");
+ message.graph = $root.onnx.GraphProto.fromObject(object.graph);
+ }
+ if (object.metadataProps) {
+ if (!Array.isArray(object.metadataProps))
+ throw TypeError(".onnx.ModelProto.metadataProps: array expected");
+ message.metadataProps = [];
+ for (var i = 0; i < object.metadataProps.length; ++i) {
+ if (typeof object.metadataProps[i] !== "object")
+ throw TypeError(".onnx.ModelProto.metadataProps: object expected");
+ message.metadataProps[i] = $root.onnx.StringStringEntryProto.fromObject(object.metadataProps[i]);
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Creates a plain object from a ModelProto message. Also converts values to other types if specified.
+ * @function toObject
+ * @memberof onnx.ModelProto
+ * @static
+ * @param {onnx.ModelProto} message ModelProto
+ * @param {$protobuf.IConversionOptions} [options] Conversion options
+ * @returns {Object.<string,*>} Plain object
+ */
+ ModelProto.toObject = function toObject(message, options) {
+ if (!options)
+ options = {};
+ var object = {};
+ if (options.arrays || options.defaults) {
+ object.opsetImport = [];
+ object.metadataProps = [];
+ }
+ if (options.defaults) {
+ if ($util.Long) {
+ var long = new $util.Long(0, 0, false);
+ object.irVersion = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
+ } else
+ object.irVersion = options.longs === String ? "0" : 0;
+ object.producerName = "";
+ object.producerVersion = "";
+ object.domain = "";
+ if ($util.Long) {
+ var long = new $util.Long(0, 0, false);
+ object.modelVersion = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
+ } else
+ object.modelVersion = options.longs === String ? "0" : 0;
+ object.docString = "";
+ object.graph = null;
+ }
+ if (message.irVersion != null && message.hasOwnProperty("irVersion"))
+ if (typeof message.irVersion === "number")
+ object.irVersion = options.longs === String ? String(message.irVersion) : message.irVersion;
+ else
+ object.irVersion = options.longs === String ? $util.Long.prototype.toString.call(message.irVersion) : options.longs === Number ? new $util.LongBits(message.irVersion.low >>> 0, message.irVersion.high >>> 0).toNumber() : message.irVersion;
+ if (message.producerName != null && message.hasOwnProperty("producerName"))
+ object.producerName = message.producerName;
+ if (message.producerVersion != null && message.hasOwnProperty("producerVersion"))
+ object.producerVersion = message.producerVersion;
+ if (message.domain != null && message.hasOwnProperty("domain"))
+ object.domain = message.domain;
+ if (message.modelVersion != null && message.hasOwnProperty("modelVersion"))
+ if (typeof message.modelVersion === "number")
+ object.modelVersion = options.longs === String ? String(message.modelVersion) : message.modelVersion;
+ else
+ object.modelVersion = options.longs === String ? $util.Long.prototype.toString.call(message.modelVersion) : options.longs === Number ? new $util.LongBits(message.modelVersion.low >>> 0, message.modelVersion.high >>> 0).toNumber() : message.modelVersion;
+ if (message.docString != null && message.hasOwnProperty("docString"))
+ object.docString = message.docString;
+ if (message.graph != null && message.hasOwnProperty("graph"))
+ object.graph = $root.onnx.GraphProto.toObject(message.graph, options);
+ if (message.opsetImport && message.opsetImport.length) {
+ object.opsetImport = [];
+ for (var j = 0; j < message.opsetImport.length; ++j)
+ object.opsetImport[j] = $root.onnx.OperatorSetIdProto.toObject(message.opsetImport[j], options);
+ }
+ if (message.metadataProps && message.metadataProps.length) {
+ object.metadataProps = [];
+ for (var j = 0; j < message.metadataProps.length; ++j)
+ object.metadataProps[j] = $root.onnx.StringStringEntryProto.toObject(message.metadataProps[j], options);
+ }
+ return object;
+ };
+
+ /**
+ * Converts this ModelProto to JSON.
+ * @function toJSON
+ * @memberof onnx.ModelProto
+ * @instance
+ * @returns {Object.<string,*>} JSON object
+ */
+ ModelProto.prototype.toJSON = function toJSON() {
+ return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
+ };
+
+ return ModelProto;
+ })();
+
+ onnx.StringStringEntryProto = (function() {
+
+ /**
+ * Properties of a StringStringEntryProto.
+ * @memberof onnx
+ * @interface IStringStringEntryProto
+ * @property {string|null} [key] StringStringEntryProto key
+ * @property {string|null} [value] StringStringEntryProto value
+ */
+
+ /**
+ * Constructs a new StringStringEntryProto.
+ * @memberof onnx
+ * @classdesc Represents a StringStringEntryProto.
+ * @implements IStringStringEntryProto
+ * @constructor
+ * @param {onnx.IStringStringEntryProto=} [properties] Properties to set
+ */
+ function StringStringEntryProto(properties) {
+ if (properties)
+ for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
+ if (properties[keys[i]] != null)
+ this[keys[i]] = properties[keys[i]];
+ }
+
+ /**
+ * StringStringEntryProto key.
+ * @member {string} key
+ * @memberof onnx.StringStringEntryProto
+ * @instance
+ */
+ StringStringEntryProto.prototype.key = "";
+
+ /**
+ * StringStringEntryProto value.
+ * @member {string} value
+ * @memberof onnx.StringStringEntryProto
+ * @instance
+ */
+ StringStringEntryProto.prototype.value = "";
+
+ /**
+ * Creates a new StringStringEntryProto instance using the specified properties.
+ * @function create
+ * @memberof onnx.StringStringEntryProto
+ * @static
+ * @param {onnx.IStringStringEntryProto=} [properties] Properties to set
+ * @returns {onnx.StringStringEntryProto} StringStringEntryProto instance
+ */
+ StringStringEntryProto.create = function create(properties) {
+ return new StringStringEntryProto(properties);
+ };
+
+ /**
+ * Encodes the specified StringStringEntryProto message. Does not implicitly {@link onnx.StringStringEntryProto.verify|verify} messages.
+ * @function encode
+ * @memberof onnx.StringStringEntryProto
+ * @static
+ * @param {onnx.IStringStringEntryProto} message StringStringEntryProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ StringStringEntryProto.encode = function encode(message, writer) {
+ if (!writer)
+ writer = $Writer.create();
+ if (message.key != null && message.hasOwnProperty("key"))
+ writer.uint32(/* id 1, wireType 2 =*/10).string(message.key);
+ if (message.value != null && message.hasOwnProperty("value"))
+ writer.uint32(/* id 2, wireType 2 =*/18).string(message.value);
+ return writer;
+ };
+
+ /**
+ * Encodes the specified StringStringEntryProto message, length delimited. Does not implicitly {@link onnx.StringStringEntryProto.verify|verify} messages.
+ * @function encodeDelimited
+ * @memberof onnx.StringStringEntryProto
+ * @static
+ * @param {onnx.IStringStringEntryProto} message StringStringEntryProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ StringStringEntryProto.encodeDelimited = function encodeDelimited(message, writer) {
+ return this.encode(message, writer).ldelim();
+ };
+
+ /**
+ * Decodes a StringStringEntryProto message from the specified reader or buffer.
+ * @function decode
+ * @memberof onnx.StringStringEntryProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @param {number} [length] Message length if known beforehand
+ * @returns {onnx.StringStringEntryProto} StringStringEntryProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ StringStringEntryProto.decode = function decode(reader, length) {
+ if (!(reader instanceof $Reader))
+ reader = $Reader.create(reader);
+ var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.StringStringEntryProto();
+ while (reader.pos < end) {
+ var tag = reader.uint32();
+ switch (tag >>> 3) {
+ case 1:
+ message.key = reader.string();
+ break;
+ case 2:
+ message.value = reader.string();
+ break;
+ default:
+ reader.skipType(tag & 7);
+ break;
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Decodes a StringStringEntryProto message from the specified reader or buffer, length delimited.
+ * @function decodeDelimited
+ * @memberof onnx.StringStringEntryProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @returns {onnx.StringStringEntryProto} StringStringEntryProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ StringStringEntryProto.decodeDelimited = function decodeDelimited(reader) {
+ if (!(reader instanceof $Reader))
+ reader = new $Reader(reader);
+ return this.decode(reader, reader.uint32());
+ };
+
+ /**
+ * Verifies a StringStringEntryProto message.
+ * @function verify
+ * @memberof onnx.StringStringEntryProto
+ * @static
+ * @param {Object.<string,*>} message Plain object to verify
+ * @returns {string|null} `null` if valid, otherwise the reason why it is not
+ */
+ StringStringEntryProto.verify = function verify(message) {
+ if (typeof message !== "object" || message === null)
+ return "object expected";
+ if (message.key != null && message.hasOwnProperty("key"))
+ if (!$util.isString(message.key))
+ return "key: string expected";
+ if (message.value != null && message.hasOwnProperty("value"))
+ if (!$util.isString(message.value))
+ return "value: string expected";
+ return null;
+ };
+
+ /**
+ * Creates a StringStringEntryProto message from a plain object. Also converts values to their respective internal types.
+ * @function fromObject
+ * @memberof onnx.StringStringEntryProto
+ * @static
+ * @param {Object.<string,*>} object Plain object
+ * @returns {onnx.StringStringEntryProto} StringStringEntryProto
+ */
+ StringStringEntryProto.fromObject = function fromObject(object) {
+ if (object instanceof $root.onnx.StringStringEntryProto)
+ return object;
+ var message = new $root.onnx.StringStringEntryProto();
+ if (object.key != null)
+ message.key = String(object.key);
+ if (object.value != null)
+ message.value = String(object.value);
+ return message;
+ };
+
+ /**
+ * Creates a plain object from a StringStringEntryProto message. Also converts values to other types if specified.
+ * @function toObject
+ * @memberof onnx.StringStringEntryProto
+ * @static
+ * @param {onnx.StringStringEntryProto} message StringStringEntryProto
+ * @param {$protobuf.IConversionOptions} [options] Conversion options
+ * @returns {Object.<string,*>} Plain object
+ */
+ StringStringEntryProto.toObject = function toObject(message, options) {
+ if (!options)
+ options = {};
+ var object = {};
+ if (options.defaults) {
+ object.key = "";
+ object.value = "";
+ }
+ if (message.key != null && message.hasOwnProperty("key"))
+ object.key = message.key;
+ if (message.value != null && message.hasOwnProperty("value"))
+ object.value = message.value;
+ return object;
+ };
+
+ /**
+ * Converts this StringStringEntryProto to JSON.
+ * @function toJSON
+ * @memberof onnx.StringStringEntryProto
+ * @instance
+ * @returns {Object.<string,*>} JSON object
+ */
+ StringStringEntryProto.prototype.toJSON = function toJSON() {
+ return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
+ };
+
+ return StringStringEntryProto;
+ })();
+
+ onnx.TensorAnnotation = (function() {
+
+ /**
+ * Properties of a TensorAnnotation.
+ * @memberof onnx
+ * @interface ITensorAnnotation
+ * @property {string|null} [tensorName] TensorAnnotation tensorName
+ * @property {Array.<onnx.IStringStringEntryProto>|null} [quantParameterTensorNames] TensorAnnotation quantParameterTensorNames
+ */
+
+ /**
+ * Constructs a new TensorAnnotation.
+ * @memberof onnx
+ * @classdesc Represents a TensorAnnotation.
+ * @implements ITensorAnnotation
+ * @constructor
+ * @param {onnx.ITensorAnnotation=} [properties] Properties to set
+ */
+ function TensorAnnotation(properties) {
+ this.quantParameterTensorNames = [];
+ if (properties)
+ for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
+ if (properties[keys[i]] != null)
+ this[keys[i]] = properties[keys[i]];
+ }
+
+ /**
+ * TensorAnnotation tensorName.
+ * @member {string} tensorName
+ * @memberof onnx.TensorAnnotation
+ * @instance
+ */
+ TensorAnnotation.prototype.tensorName = "";
+
+ /**
+ * TensorAnnotation quantParameterTensorNames.
+ * @member {Array.<onnx.IStringStringEntryProto>} quantParameterTensorNames
+ * @memberof onnx.TensorAnnotation
+ * @instance
+ */
+ TensorAnnotation.prototype.quantParameterTensorNames = $util.emptyArray;
+
+ /**
+ * Creates a new TensorAnnotation instance using the specified properties.
+ * @function create
+ * @memberof onnx.TensorAnnotation
+ * @static
+ * @param {onnx.ITensorAnnotation=} [properties] Properties to set
+ * @returns {onnx.TensorAnnotation} TensorAnnotation instance
+ */
+ TensorAnnotation.create = function create(properties) {
+ return new TensorAnnotation(properties);
+ };
+
+ /**
+ * Encodes the specified TensorAnnotation message. Does not implicitly {@link onnx.TensorAnnotation.verify|verify} messages.
+ * @function encode
+ * @memberof onnx.TensorAnnotation
+ * @static
+ * @param {onnx.ITensorAnnotation} message TensorAnnotation message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ TensorAnnotation.encode = function encode(message, writer) {
+ if (!writer)
+ writer = $Writer.create();
+ if (message.tensorName != null && message.hasOwnProperty("tensorName"))
+ writer.uint32(/* id 1, wireType 2 =*/10).string(message.tensorName);
+ if (message.quantParameterTensorNames != null && message.quantParameterTensorNames.length)
+ for (var i = 0; i < message.quantParameterTensorNames.length; ++i)
+ $root.onnx.StringStringEntryProto.encode(message.quantParameterTensorNames[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();
+ return writer;
+ };
+
+ /**
+ * Encodes the specified TensorAnnotation message, length delimited. Does not implicitly {@link onnx.TensorAnnotation.verify|verify} messages.
+ * @function encodeDelimited
+ * @memberof onnx.TensorAnnotation
+ * @static
+ * @param {onnx.ITensorAnnotation} message TensorAnnotation message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ TensorAnnotation.encodeDelimited = function encodeDelimited(message, writer) {
+ return this.encode(message, writer).ldelim();
+ };
+
+ /**
+ * Decodes a TensorAnnotation message from the specified reader or buffer.
+ * @function decode
+ * @memberof onnx.TensorAnnotation
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @param {number} [length] Message length if known beforehand
+ * @returns {onnx.TensorAnnotation} TensorAnnotation
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ TensorAnnotation.decode = function decode(reader, length) {
+ if (!(reader instanceof $Reader))
+ reader = $Reader.create(reader);
+ var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.TensorAnnotation();
+ while (reader.pos < end) {
+ var tag = reader.uint32();
+ switch (tag >>> 3) {
+ case 1:
+ message.tensorName = reader.string();
+ break;
+ case 2:
+ if (!(message.quantParameterTensorNames && message.quantParameterTensorNames.length))
+ message.quantParameterTensorNames = [];
+ message.quantParameterTensorNames.push($root.onnx.StringStringEntryProto.decode(reader, reader.uint32()));
+ break;
+ default:
+ reader.skipType(tag & 7);
+ break;
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Decodes a TensorAnnotation message from the specified reader or buffer, length delimited.
+ * @function decodeDelimited
+ * @memberof onnx.TensorAnnotation
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @returns {onnx.TensorAnnotation} TensorAnnotation
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ TensorAnnotation.decodeDelimited = function decodeDelimited(reader) {
+ if (!(reader instanceof $Reader))
+ reader = new $Reader(reader);
+ return this.decode(reader, reader.uint32());
+ };
+
+ /**
+ * Verifies a TensorAnnotation message.
+ * @function verify
+ * @memberof onnx.TensorAnnotation
+ * @static
+ * @param {Object.<string,*>} message Plain object to verify
+ * @returns {string|null} `null` if valid, otherwise the reason why it is not
+ */
+ TensorAnnotation.verify = function verify(message) {
+ if (typeof message !== "object" || message === null)
+ return "object expected";
+ if (message.tensorName != null && message.hasOwnProperty("tensorName"))
+ if (!$util.isString(message.tensorName))
+ return "tensorName: string expected";
+ if (message.quantParameterTensorNames != null && message.hasOwnProperty("quantParameterTensorNames")) {
+ if (!Array.isArray(message.quantParameterTensorNames))
+ return "quantParameterTensorNames: array expected";
+ for (var i = 0; i < message.quantParameterTensorNames.length; ++i) {
+ var error = $root.onnx.StringStringEntryProto.verify(message.quantParameterTensorNames[i]);
+ if (error)
+ return "quantParameterTensorNames." + error;
+ }
+ }
+ return null;
+ };
+
+ /**
+ * Creates a TensorAnnotation message from a plain object. Also converts values to their respective internal types.
+ * @function fromObject
+ * @memberof onnx.TensorAnnotation
+ * @static
+ * @param {Object.<string,*>} object Plain object
+ * @returns {onnx.TensorAnnotation} TensorAnnotation
+ */
+ TensorAnnotation.fromObject = function fromObject(object) {
+ if (object instanceof $root.onnx.TensorAnnotation)
+ return object;
+ var message = new $root.onnx.TensorAnnotation();
+ if (object.tensorName != null)
+ message.tensorName = String(object.tensorName);
+ if (object.quantParameterTensorNames) {
+ if (!Array.isArray(object.quantParameterTensorNames))
+ throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: array expected");
+ message.quantParameterTensorNames = [];
+ for (var i = 0; i < object.quantParameterTensorNames.length; ++i) {
+ if (typeof object.quantParameterTensorNames[i] !== "object")
+ throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: object expected");
+ message.quantParameterTensorNames[i] = $root.onnx.StringStringEntryProto.fromObject(object.quantParameterTensorNames[i]);
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Creates a plain object from a TensorAnnotation message. Also converts values to other types if specified.
+ * @function toObject
+ * @memberof onnx.TensorAnnotation
+ * @static
+ * @param {onnx.TensorAnnotation} message TensorAnnotation
+ * @param {$protobuf.IConversionOptions} [options] Conversion options
+ * @returns {Object.<string,*>} Plain object
+ */
+ TensorAnnotation.toObject = function toObject(message, options) {
+ if (!options)
+ options = {};
+ var object = {};
+ if (options.arrays || options.defaults)
+ object.quantParameterTensorNames = [];
+ if (options.defaults)
+ object.tensorName = "";
+ if (message.tensorName != null && message.hasOwnProperty("tensorName"))
+ object.tensorName = message.tensorName;
+ if (message.quantParameterTensorNames && message.quantParameterTensorNames.length) {
+ object.quantParameterTensorNames = [];
+ for (var j = 0; j < message.quantParameterTensorNames.length; ++j)
+ object.quantParameterTensorNames[j] = $root.onnx.StringStringEntryProto.toObject(message.quantParameterTensorNames[j], options);
+ }
+ return object;
+ };
+
+ /**
+ * Converts this TensorAnnotation to JSON.
+ * @function toJSON
+ * @memberof onnx.TensorAnnotation
+ * @instance
+ * @returns {Object.<string,*>} JSON object
+ */
+ TensorAnnotation.prototype.toJSON = function toJSON() {
+ return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
+ };
+
+ return TensorAnnotation;
+ })();
+
+ onnx.GraphProto = (function() {
+
+ /**
+ * Properties of a GraphProto.
+ * @memberof onnx
+ * @interface IGraphProto
+ * @property {Array.<onnx.INodeProto>|null} [node] GraphProto node
+ * @property {string|null} [name] GraphProto name
+ * @property {Array.<onnx.ITensorProto>|null} [initializer] GraphProto initializer
+ * @property {string|null} [docString] GraphProto docString
+ * @property {Array.<onnx.IValueInfoProto>|null} [input] GraphProto input
+ * @property {Array.<onnx.IValueInfoProto>|null} [output] GraphProto output
+ * @property {Array.<onnx.IValueInfoProto>|null} [valueInfo] GraphProto valueInfo
+ * @property {Array.<onnx.ITensorAnnotation>|null} [quantizationAnnotation] GraphProto quantizationAnnotation
+ */
+
+ /**
+ * Constructs a new GraphProto.
+ * @memberof onnx
+ * @classdesc Represents a GraphProto.
+ * @implements IGraphProto
+ * @constructor
+ * @param {onnx.IGraphProto=} [properties] Properties to set
+ */
+ function GraphProto(properties) {
+ this.node = [];
+ this.initializer = [];
+ this.input = [];
+ this.output = [];
+ this.valueInfo = [];
+ this.quantizationAnnotation = [];
+ if (properties)
+ for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
+ if (properties[keys[i]] != null)
+ this[keys[i]] = properties[keys[i]];
+ }
+
+ /**
+ * GraphProto node.
+ * @member {Array.<onnx.INodeProto>} node
+ * @memberof onnx.GraphProto
+ * @instance
+ */
+ GraphProto.prototype.node = $util.emptyArray;
+
+ /**
+ * GraphProto name.
+ * @member {string} name
+ * @memberof onnx.GraphProto
+ * @instance
+ */
+ GraphProto.prototype.name = "";
+
+ /**
+ * GraphProto initializer.
+ * @member {Array.<onnx.ITensorProto>} initializer
+ * @memberof onnx.GraphProto
+ * @instance
+ */
+ GraphProto.prototype.initializer = $util.emptyArray;
+
+ /**
+ * GraphProto docString.
+ * @member {string} docString
+ * @memberof onnx.GraphProto
+ * @instance
+ */
+ GraphProto.prototype.docString = "";
+
+ /**
+ * GraphProto input.
+ * @member {Array.<onnx.IValueInfoProto>} input
+ * @memberof onnx.GraphProto
+ * @instance
+ */
+ GraphProto.prototype.input = $util.emptyArray;
+
+ /**
+ * GraphProto output.
+ * @member {Array.<onnx.IValueInfoProto>} output
+ * @memberof onnx.GraphProto
+ * @instance
+ */
+ GraphProto.prototype.output = $util.emptyArray;
+
+ /**
+ * GraphProto valueInfo.
+ * @member {Array.<onnx.IValueInfoProto>} valueInfo
+ * @memberof onnx.GraphProto
+ * @instance
+ */
+ GraphProto.prototype.valueInfo = $util.emptyArray;
+
+ /**
+ * GraphProto quantizationAnnotation.
+ * @member {Array.<onnx.ITensorAnnotation>} quantizationAnnotation
+ * @memberof onnx.GraphProto
+ * @instance
+ */
+ GraphProto.prototype.quantizationAnnotation = $util.emptyArray;
+
+ /**
+ * Creates a new GraphProto instance using the specified properties.
+ * @function create
+ * @memberof onnx.GraphProto
+ * @static
+ * @param {onnx.IGraphProto=} [properties] Properties to set
+ * @returns {onnx.GraphProto} GraphProto instance
+ */
+ GraphProto.create = function create(properties) {
+ return new GraphProto(properties);
+ };
+
+ /**
+ * Encodes the specified GraphProto message. Does not implicitly {@link onnx.GraphProto.verify|verify} messages.
+ * @function encode
+ * @memberof onnx.GraphProto
+ * @static
+ * @param {onnx.IGraphProto} message GraphProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ GraphProto.encode = function encode(message, writer) {
+ if (!writer)
+ writer = $Writer.create();
+ if (message.node != null && message.node.length)
+ for (var i = 0; i < message.node.length; ++i)
+ $root.onnx.NodeProto.encode(message.node[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();
+ if (message.name != null && message.hasOwnProperty("name"))
+ writer.uint32(/* id 2, wireType 2 =*/18).string(message.name);
+ if (message.initializer != null && message.initializer.length)
+ for (var i = 0; i < message.initializer.length; ++i)
+ $root.onnx.TensorProto.encode(message.initializer[i], writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim();
+ if (message.docString != null && message.hasOwnProperty("docString"))
+ writer.uint32(/* id 10, wireType 2 =*/82).string(message.docString);
+ if (message.input != null && message.input.length)
+ for (var i = 0; i < message.input.length; ++i)
+ $root.onnx.ValueInfoProto.encode(message.input[i], writer.uint32(/* id 11, wireType 2 =*/90).fork()).ldelim();
+ if (message.output != null && message.output.length)
+ for (var i = 0; i < message.output.length; ++i)
+ $root.onnx.ValueInfoProto.encode(message.output[i], writer.uint32(/* id 12, wireType 2 =*/98).fork()).ldelim();
+ if (message.valueInfo != null && message.valueInfo.length)
+ for (var i = 0; i < message.valueInfo.length; ++i)
+ $root.onnx.ValueInfoProto.encode(message.valueInfo[i], writer.uint32(/* id 13, wireType 2 =*/106).fork()).ldelim();
+ if (message.quantizationAnnotation != null && message.quantizationAnnotation.length)
+ for (var i = 0; i < message.quantizationAnnotation.length; ++i)
+ $root.onnx.TensorAnnotation.encode(message.quantizationAnnotation[i], writer.uint32(/* id 14, wireType 2 =*/114).fork()).ldelim();
+ return writer;
+ };
+
+ /**
+ * Encodes the specified GraphProto message, length delimited. Does not implicitly {@link onnx.GraphProto.verify|verify} messages.
+ * @function encodeDelimited
+ * @memberof onnx.GraphProto
+ * @static
+ * @param {onnx.IGraphProto} message GraphProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ GraphProto.encodeDelimited = function encodeDelimited(message, writer) {
+ return this.encode(message, writer).ldelim();
+ };
+
+ /**
+ * Decodes a GraphProto message from the specified reader or buffer.
+ * @function decode
+ * @memberof onnx.GraphProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @param {number} [length] Message length if known beforehand
+ * @returns {onnx.GraphProto} GraphProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ GraphProto.decode = function decode(reader, length) {
+ if (!(reader instanceof $Reader))
+ reader = $Reader.create(reader);
+ var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.GraphProto();
+ while (reader.pos < end) {
+ var tag = reader.uint32();
+ switch (tag >>> 3) {
+ case 1:
+ if (!(message.node && message.node.length))
+ message.node = [];
+ message.node.push($root.onnx.NodeProto.decode(reader, reader.uint32()));
+ break;
+ case 2:
+ message.name = reader.string();
+ break;
+ case 5:
+ if (!(message.initializer && message.initializer.length))
+ message.initializer = [];
+ message.initializer.push($root.onnx.TensorProto.decode(reader, reader.uint32()));
+ break;
+ case 10:
+ message.docString = reader.string();
+ break;
+ case 11:
+ if (!(message.input && message.input.length))
+ message.input = [];
+ message.input.push($root.onnx.ValueInfoProto.decode(reader, reader.uint32()));
+ break;
+ case 12:
+ if (!(message.output && message.output.length))
+ message.output = [];
+ message.output.push($root.onnx.ValueInfoProto.decode(reader, reader.uint32()));
+ break;
+ case 13:
+ if (!(message.valueInfo && message.valueInfo.length))
+ message.valueInfo = [];
+ message.valueInfo.push($root.onnx.ValueInfoProto.decode(reader, reader.uint32()));
+ break;
+ case 14:
+ if (!(message.quantizationAnnotation && message.quantizationAnnotation.length))
+ message.quantizationAnnotation = [];
+ message.quantizationAnnotation.push($root.onnx.TensorAnnotation.decode(reader, reader.uint32()));
+ break;
+ default:
+ reader.skipType(tag & 7);
+ break;
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Decodes a GraphProto message from the specified reader or buffer, length delimited.
+ * @function decodeDelimited
+ * @memberof onnx.GraphProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @returns {onnx.GraphProto} GraphProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ GraphProto.decodeDelimited = function decodeDelimited(reader) {
+ if (!(reader instanceof $Reader))
+ reader = new $Reader(reader);
+ return this.decode(reader, reader.uint32());
+ };
+
+ /**
+ * Verifies a GraphProto message.
+ * @function verify
+ * @memberof onnx.GraphProto
+ * @static
+ * @param {Object.<string,*>} message Plain object to verify
+ * @returns {string|null} `null` if valid, otherwise the reason why it is not
+ */
+ GraphProto.verify = function verify(message) {
+ if (typeof message !== "object" || message === null)
+ return "object expected";
+ if (message.node != null && message.hasOwnProperty("node")) {
+ if (!Array.isArray(message.node))
+ return "node: array expected";
+ for (var i = 0; i < message.node.length; ++i) {
+ var error = $root.onnx.NodeProto.verify(message.node[i]);
+ if (error)
+ return "node." + error;
+ }
+ }
+ if (message.name != null && message.hasOwnProperty("name"))
+ if (!$util.isString(message.name))
+ return "name: string expected";
+ if (message.initializer != null && message.hasOwnProperty("initializer")) {
+ if (!Array.isArray(message.initializer))
+ return "initializer: array expected";
+ for (var i = 0; i < message.initializer.length; ++i) {
+ var error = $root.onnx.TensorProto.verify(message.initializer[i]);
+ if (error)
+ return "initializer." + error;
+ }
+ }
+ if (message.docString != null && message.hasOwnProperty("docString"))
+ if (!$util.isString(message.docString))
+ return "docString: string expected";
+ if (message.input != null && message.hasOwnProperty("input")) {
+ if (!Array.isArray(message.input))
+ return "input: array expected";
+ for (var i = 0; i < message.input.length; ++i) {
+ var error = $root.onnx.ValueInfoProto.verify(message.input[i]);
+ if (error)
+ return "input." + error;
+ }
+ }
+ if (message.output != null && message.hasOwnProperty("output")) {
+ if (!Array.isArray(message.output))
+ return "output: array expected";
+ for (var i = 0; i < message.output.length; ++i) {
+ var error = $root.onnx.ValueInfoProto.verify(message.output[i]);
+ if (error)
+ return "output." + error;
+ }
+ }
+ if (message.valueInfo != null && message.hasOwnProperty("valueInfo")) {
+ if (!Array.isArray(message.valueInfo))
+ return "valueInfo: array expected";
+ for (var i = 0; i < message.valueInfo.length; ++i) {
+ var error = $root.onnx.ValueInfoProto.verify(message.valueInfo[i]);
+ if (error)
+ return "valueInfo." + error;
+ }
+ }
+ if (message.quantizationAnnotation != null && message.hasOwnProperty("quantizationAnnotation")) {
+ if (!Array.isArray(message.quantizationAnnotation))
+ return "quantizationAnnotation: array expected";
+ for (var i = 0; i < message.quantizationAnnotation.length; ++i) {
+ var error = $root.onnx.TensorAnnotation.verify(message.quantizationAnnotation[i]);
+ if (error)
+ return "quantizationAnnotation." + error;
+ }
+ }
+ return null;
+ };
+
+ /**
+ * Creates a GraphProto message from a plain object. Also converts values to their respective internal types.
+ * @function fromObject
+ * @memberof onnx.GraphProto
+ * @static
+ * @param {Object.<string,*>} object Plain object
+ * @returns {onnx.GraphProto} GraphProto
+ */
+ GraphProto.fromObject = function fromObject(object) {
+ if (object instanceof $root.onnx.GraphProto)
+ return object;
+ var message = new $root.onnx.GraphProto();
+ if (object.node) {
+ if (!Array.isArray(object.node))
+ throw TypeError(".onnx.GraphProto.node: array expected");
+ message.node = [];
+ for (var i = 0; i < object.node.length; ++i) {
+ if (typeof object.node[i] !== "object")
+ throw TypeError(".onnx.GraphProto.node: object expected");
+ message.node[i] = $root.onnx.NodeProto.fromObject(object.node[i]);
+ }
+ }
+ if (object.name != null)
+ message.name = String(object.name);
+ if (object.initializer) {
+ if (!Array.isArray(object.initializer))
+ throw TypeError(".onnx.GraphProto.initializer: array expected");
+ message.initializer = [];
+ for (var i = 0; i < object.initializer.length; ++i) {
+ if (typeof object.initializer[i] !== "object")
+ throw TypeError(".onnx.GraphProto.initializer: object expected");
+ message.initializer[i] = $root.onnx.TensorProto.fromObject(object.initializer[i]);
+ }
+ }
+ if (object.docString != null)
+ message.docString = String(object.docString);
+ if (object.input) {
+ if (!Array.isArray(object.input))
+ throw TypeError(".onnx.GraphProto.input: array expected");
+ message.input = [];
+ for (var i = 0; i < object.input.length; ++i) {
+ if (typeof object.input[i] !== "object")
+ throw TypeError(".onnx.GraphProto.input: object expected");
+ message.input[i] = $root.onnx.ValueInfoProto.fromObject(object.input[i]);
+ }
+ }
+ if (object.output) {
+ if (!Array.isArray(object.output))
+ throw TypeError(".onnx.GraphProto.output: array expected");
+ message.output = [];
+ for (var i = 0; i < object.output.length; ++i) {
+ if (typeof object.output[i] !== "object")
+ throw TypeError(".onnx.GraphProto.output: object expected");
+ message.output[i] = $root.onnx.ValueInfoProto.fromObject(object.output[i]);
+ }
+ }
+ if (object.valueInfo) {
+ if (!Array.isArray(object.valueInfo))
+ throw TypeError(".onnx.GraphProto.valueInfo: array expected");
+ message.valueInfo = [];
+ for (var i = 0; i < object.valueInfo.length; ++i) {
+ if (typeof object.valueInfo[i] !== "object")
+ throw TypeError(".onnx.GraphProto.valueInfo: object expected");
+ message.valueInfo[i] = $root.onnx.ValueInfoProto.fromObject(object.valueInfo[i]);
+ }
+ }
+ if (object.quantizationAnnotation) {
+ if (!Array.isArray(object.quantizationAnnotation))
+ throw TypeError(".onnx.GraphProto.quantizationAnnotation: array expected");
+ message.quantizationAnnotation = [];
+ for (var i = 0; i < object.quantizationAnnotation.length; ++i) {
+ if (typeof object.quantizationAnnotation[i] !== "object")
+ throw TypeError(".onnx.GraphProto.quantizationAnnotation: object expected");
+ message.quantizationAnnotation[i] = $root.onnx.TensorAnnotation.fromObject(object.quantizationAnnotation[i]);
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Creates a plain object from a GraphProto message. Also converts values to other types if specified.
+ * @function toObject
+ * @memberof onnx.GraphProto
+ * @static
+ * @param {onnx.GraphProto} message GraphProto
+ * @param {$protobuf.IConversionOptions} [options] Conversion options
+ * @returns {Object.<string,*>} Plain object
+ */
+ GraphProto.toObject = function toObject(message, options) {
+ if (!options)
+ options = {};
+ var object = {};
+ if (options.arrays || options.defaults) {
+ object.node = [];
+ object.initializer = [];
+ object.input = [];
+ object.output = [];
+ object.valueInfo = [];
+ object.quantizationAnnotation = [];
+ }
+ if (options.defaults) {
+ object.name = "";
+ object.docString = "";
+ }
+ if (message.node && message.node.length) {
+ object.node = [];
+ for (var j = 0; j < message.node.length; ++j)
+ object.node[j] = $root.onnx.NodeProto.toObject(message.node[j], options);
+ }
+ if (message.name != null && message.hasOwnProperty("name"))
+ object.name = message.name;
+ if (message.initializer && message.initializer.length) {
+ object.initializer = [];
+ for (var j = 0; j < message.initializer.length; ++j)
+ object.initializer[j] = $root.onnx.TensorProto.toObject(message.initializer[j], options);
+ }
+ if (message.docString != null && message.hasOwnProperty("docString"))
+ object.docString = message.docString;
+ if (message.input && message.input.length) {
+ object.input = [];
+ for (var j = 0; j < message.input.length; ++j)
+ object.input[j] = $root.onnx.ValueInfoProto.toObject(message.input[j], options);
+ }
+ if (message.output && message.output.length) {
+ object.output = [];
+ for (var j = 0; j < message.output.length; ++j)
+ object.output[j] = $root.onnx.ValueInfoProto.toObject(message.output[j], options);
+ }
+ if (message.valueInfo && message.valueInfo.length) {
+ object.valueInfo = [];
+ for (var j = 0; j < message.valueInfo.length; ++j)
+ object.valueInfo[j] = $root.onnx.ValueInfoProto.toObject(message.valueInfo[j], options);
+ }
+ if (message.quantizationAnnotation && message.quantizationAnnotation.length) {
+ object.quantizationAnnotation = [];
+ for (var j = 0; j < message.quantizationAnnotation.length; ++j)
+ object.quantizationAnnotation[j] = $root.onnx.TensorAnnotation.toObject(message.quantizationAnnotation[j], options);
+ }
+ return object;
+ };
+
+ /**
+ * Converts this GraphProto to JSON.
+ * @function toJSON
+ * @memberof onnx.GraphProto
+ * @instance
+ * @returns {Object.<string,*>} JSON object
+ */
+ GraphProto.prototype.toJSON = function toJSON() {
+ return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
+ };
+
+ return GraphProto;
+ })();
+
+ onnx.TensorProto = (function() {
+
+ /**
+ * Properties of a TensorProto.
+ * @memberof onnx
+ * @interface ITensorProto
+ * @property {Array.<number|Long>|null} [dims] TensorProto dims
+ * @property {number|null} [dataType] TensorProto dataType
+ * @property {onnx.TensorProto.ISegment|null} [segment] TensorProto segment
+ * @property {Array.<number>|null} [floatData] TensorProto floatData
+ * @property {Array.<number>|null} [int32Data] TensorProto int32Data
+ * @property {Array.<Uint8Array>|null} [stringData] TensorProto stringData
+ * @property {Array.<number|Long>|null} [int64Data] TensorProto int64Data
+ * @property {string|null} [name] TensorProto name
+ * @property {string|null} [docString] TensorProto docString
+ * @property {Uint8Array|null} [rawData] TensorProto rawData
+ * @property {Array.<onnx.IStringStringEntryProto>|null} [externalData] TensorProto externalData
+ * @property {onnx.TensorProto.DataLocation|null} [dataLocation] TensorProto dataLocation
+ * @property {Array.<number>|null} [doubleData] TensorProto doubleData
+ * @property {Array.<number|Long>|null} [uint64Data] TensorProto uint64Data
+ */
+
+ /**
+ * Constructs a new TensorProto.
+ * @memberof onnx
+ * @classdesc Represents a TensorProto.
+ * @implements ITensorProto
+ * @constructor
+ * @param {onnx.ITensorProto=} [properties] Properties to set
+ */
+ function TensorProto(properties) {
+ this.dims = [];
+ this.floatData = [];
+ this.int32Data = [];
+ this.stringData = [];
+ this.int64Data = [];
+ this.externalData = [];
+ this.doubleData = [];
+ this.uint64Data = [];
+ if (properties)
+ for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
+ if (properties[keys[i]] != null)
+ this[keys[i]] = properties[keys[i]];
+ }
+
+ /**
+ * TensorProto dims.
+ * @member {Array.<number|Long>} dims
+ * @memberof onnx.TensorProto
+ * @instance
+ */
+ TensorProto.prototype.dims = $util.emptyArray;
+
+ /**
+ * TensorProto dataType.
+ * @member {number} dataType
+ * @memberof onnx.TensorProto
+ * @instance
+ */
+ TensorProto.prototype.dataType = 0;
+
+ /**
+ * TensorProto segment.
+ * @member {onnx.TensorProto.ISegment|null|undefined} segment
+ * @memberof onnx.TensorProto
+ * @instance
+ */
+ TensorProto.prototype.segment = null;
+
+ /**
+ * TensorProto floatData.
+ * @member {Array.<number>} floatData
+ * @memberof onnx.TensorProto
+ * @instance
+ */
+ TensorProto.prototype.floatData = $util.emptyArray;
+
+ /**
+ * TensorProto int32Data.
+ * @member {Array.<number>} int32Data
+ * @memberof onnx.TensorProto
+ * @instance
+ */
+ TensorProto.prototype.int32Data = $util.emptyArray;
+
+ /**
+ * TensorProto stringData.
+ * @member {Array.<Uint8Array>} stringData
+ * @memberof onnx.TensorProto
+ * @instance
+ */
+ TensorProto.prototype.stringData = $util.emptyArray;
+
+ /**
+ * TensorProto int64Data.
+ * @member {Array.<number|Long>} int64Data
+ * @memberof onnx.TensorProto
+ * @instance
+ */
+ TensorProto.prototype.int64Data = $util.emptyArray;
+
+ /**
+ * TensorProto name.
+ * @member {string} name
+ * @memberof onnx.TensorProto
+ * @instance
+ */
+ TensorProto.prototype.name = "";
+
+ /**
+ * TensorProto docString.
+ * @member {string} docString
+ * @memberof onnx.TensorProto
+ * @instance
+ */
+ TensorProto.prototype.docString = "";
+
+ /**
+ * TensorProto rawData.
+ * @member {Uint8Array} rawData
+ * @memberof onnx.TensorProto
+ * @instance
+ */
+ TensorProto.prototype.rawData = $util.newBuffer([]);
+
+ /**
+ * TensorProto externalData.
+ * @member {Array.<onnx.IStringStringEntryProto>} externalData
+ * @memberof onnx.TensorProto
+ * @instance
+ */
+ TensorProto.prototype.externalData = $util.emptyArray;
+
+ /**
+ * TensorProto dataLocation.
+ * @member {onnx.TensorProto.DataLocation} dataLocation
+ * @memberof onnx.TensorProto
+ * @instance
+ */
+ TensorProto.prototype.dataLocation = 0;
+
+ /**
+ * TensorProto doubleData.
+ * @member {Array.<number>} doubleData
+ * @memberof onnx.TensorProto
+ * @instance
+ */
+ TensorProto.prototype.doubleData = $util.emptyArray;
+
+ /**
+ * TensorProto uint64Data.
+ * @member {Array.<number|Long>} uint64Data
+ * @memberof onnx.TensorProto
+ * @instance
+ */
+ TensorProto.prototype.uint64Data = $util.emptyArray;
+
+ /**
+ * Creates a new TensorProto instance using the specified properties.
+ * @function create
+ * @memberof onnx.TensorProto
+ * @static
+ * @param {onnx.ITensorProto=} [properties] Properties to set
+ * @returns {onnx.TensorProto} TensorProto instance
+ */
+ TensorProto.create = function create(properties) {
+ return new TensorProto(properties);
+ };
+
+ /**
+ * Encodes the specified TensorProto message. Does not implicitly {@link onnx.TensorProto.verify|verify} messages.
+ * @function encode
+ * @memberof onnx.TensorProto
+ * @static
+ * @param {onnx.ITensorProto} message TensorProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ TensorProto.encode = function encode(message, writer) {
+ if (!writer)
+ writer = $Writer.create();
+ if (message.dims != null && message.dims.length) {
+ writer.uint32(/* id 1, wireType 2 =*/10).fork();
+ for (var i = 0; i < message.dims.length; ++i)
+ writer.int64(message.dims[i]);
+ writer.ldelim();
+ }
+ if (message.dataType != null && message.hasOwnProperty("dataType"))
+ writer.uint32(/* id 2, wireType 0 =*/16).int32(message.dataType);
+ if (message.segment != null && message.hasOwnProperty("segment"))
+ $root.onnx.TensorProto.Segment.encode(message.segment, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim();
+ if (message.floatData != null && message.floatData.length) {
+ writer.uint32(/* id 4, wireType 2 =*/34).fork();
+ for (var i = 0; i < message.floatData.length; ++i)
+ writer.float(message.floatData[i]);
+ writer.ldelim();
+ }
+ if (message.int32Data != null && message.int32Data.length) {
+ writer.uint32(/* id 5, wireType 2 =*/42).fork();
+ for (var i = 0; i < message.int32Data.length; ++i)
+ writer.int32(message.int32Data[i]);
+ writer.ldelim();
+ }
+ if (message.stringData != null && message.stringData.length)
+ for (var i = 0; i < message.stringData.length; ++i)
+ writer.uint32(/* id 6, wireType 2 =*/50).bytes(message.stringData[i]);
+ if (message.int64Data != null && message.int64Data.length) {
+ writer.uint32(/* id 7, wireType 2 =*/58).fork();
+ for (var i = 0; i < message.int64Data.length; ++i)
+ writer.int64(message.int64Data[i]);
+ writer.ldelim();
+ }
+ if (message.name != null && message.hasOwnProperty("name"))
+ writer.uint32(/* id 8, wireType 2 =*/66).string(message.name);
+ if (message.rawData != null && message.hasOwnProperty("rawData"))
+ writer.uint32(/* id 9, wireType 2 =*/74).bytes(message.rawData);
+ if (message.doubleData != null && message.doubleData.length) {
+ writer.uint32(/* id 10, wireType 2 =*/82).fork();
+ for (var i = 0; i < message.doubleData.length; ++i)
+ writer.double(message.doubleData[i]);
+ writer.ldelim();
+ }
+ if (message.uint64Data != null && message.uint64Data.length) {
+ writer.uint32(/* id 11, wireType 2 =*/90).fork();
+ for (var i = 0; i < message.uint64Data.length; ++i)
+ writer.uint64(message.uint64Data[i]);
+ writer.ldelim();
+ }
+ if (message.docString != null && message.hasOwnProperty("docString"))
+ writer.uint32(/* id 12, wireType 2 =*/98).string(message.docString);
+ if (message.externalData != null && message.externalData.length)
+ for (var i = 0; i < message.externalData.length; ++i)
+ $root.onnx.StringStringEntryProto.encode(message.externalData[i], writer.uint32(/* id 13, wireType 2 =*/106).fork()).ldelim();
+ if (message.dataLocation != null && message.hasOwnProperty("dataLocation"))
+ writer.uint32(/* id 14, wireType 0 =*/112).int32(message.dataLocation);
+ return writer;
+ };
+
+ /**
+ * Encodes the specified TensorProto message, length delimited. Does not implicitly {@link onnx.TensorProto.verify|verify} messages.
+ * @function encodeDelimited
+ * @memberof onnx.TensorProto
+ * @static
+ * @param {onnx.ITensorProto} message TensorProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ TensorProto.encodeDelimited = function encodeDelimited(message, writer) {
+ return this.encode(message, writer).ldelim();
+ };
+
+ /**
+ * Decodes a TensorProto message from the specified reader or buffer.
+ * @function decode
+ * @memberof onnx.TensorProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @param {number} [length] Message length if known beforehand
+ * @returns {onnx.TensorProto} TensorProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ TensorProto.decode = function decode(reader, length) {
+ if (!(reader instanceof $Reader))
+ reader = $Reader.create(reader);
+ var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.TensorProto();
+ while (reader.pos < end) {
+ var tag = reader.uint32();
+ switch (tag >>> 3) {
+ case 1:
+ if (!(message.dims && message.dims.length))
+ message.dims = [];
+ if ((tag & 7) === 2) {
+ var end2 = reader.uint32() + reader.pos;
+ while (reader.pos < end2)
+ message.dims.push(reader.int64());
+ } else
+ message.dims.push(reader.int64());
+ break;
+ case 2:
+ message.dataType = reader.int32();
+ break;
+ case 3:
+ message.segment = $root.onnx.TensorProto.Segment.decode(reader, reader.uint32());
+ break;
+ case 4:
+ if (!(message.floatData && message.floatData.length))
+ message.floatData = [];
+ if ((tag & 7) === 2) {
+ var end2 = reader.uint32() + reader.pos;
+ while (reader.pos < end2)
+ message.floatData.push(reader.float());
+ } else
+ message.floatData.push(reader.float());
+ break;
+ case 5:
+ if (!(message.int32Data && message.int32Data.length))
+ message.int32Data = [];
+ if ((tag & 7) === 2) {
+ var end2 = reader.uint32() + reader.pos;
+ while (reader.pos < end2)
+ message.int32Data.push(reader.int32());
+ } else
+ message.int32Data.push(reader.int32());
+ break;
+ case 6:
+ if (!(message.stringData && message.stringData.length))
+ message.stringData = [];
+ message.stringData.push(reader.bytes());
+ break;
+ case 7:
+ if (!(message.int64Data && message.int64Data.length))
+ message.int64Data = [];
+ if ((tag & 7) === 2) {
+ var end2 = reader.uint32() + reader.pos;
+ while (reader.pos < end2)
+ message.int64Data.push(reader.int64());
+ } else
+ message.int64Data.push(reader.int64());
+ break;
+ case 8:
+ message.name = reader.string();
+ break;
+ case 12:
+ message.docString = reader.string();
+ break;
+ case 9:
+ message.rawData = reader.bytes();
+ break;
+ case 13:
+ if (!(message.externalData && message.externalData.length))
+ message.externalData = [];
+ message.externalData.push($root.onnx.StringStringEntryProto.decode(reader, reader.uint32()));
+ break;
+ case 14:
+ message.dataLocation = reader.int32();
+ break;
+ case 10:
+ if (!(message.doubleData && message.doubleData.length))
+ message.doubleData = [];
+ if ((tag & 7) === 2) {
+ var end2 = reader.uint32() + reader.pos;
+ while (reader.pos < end2)
+ message.doubleData.push(reader.double());
+ } else
+ message.doubleData.push(reader.double());
+ break;
+ case 11:
+ if (!(message.uint64Data && message.uint64Data.length))
+ message.uint64Data = [];
+ if ((tag & 7) === 2) {
+ var end2 = reader.uint32() + reader.pos;
+ while (reader.pos < end2)
+ message.uint64Data.push(reader.uint64());
+ } else
+ message.uint64Data.push(reader.uint64());
+ break;
+ default:
+ reader.skipType(tag & 7);
+ break;
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Decodes a TensorProto message from the specified reader or buffer, length delimited.
+ * @function decodeDelimited
+ * @memberof onnx.TensorProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @returns {onnx.TensorProto} TensorProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ TensorProto.decodeDelimited = function decodeDelimited(reader) {
+ if (!(reader instanceof $Reader))
+ reader = new $Reader(reader);
+ return this.decode(reader, reader.uint32());
+ };
+
+ /**
+ * Verifies a TensorProto message.
+ * @function verify
+ * @memberof onnx.TensorProto
+ * @static
+ * @param {Object.<string,*>} message Plain object to verify
+ * @returns {string|null} `null` if valid, otherwise the reason why it is not
+ */
+ TensorProto.verify = function verify(message) {
+ if (typeof message !== "object" || message === null)
+ return "object expected";
+ if (message.dims != null && message.hasOwnProperty("dims")) {
+ if (!Array.isArray(message.dims))
+ return "dims: array expected";
+ for (var i = 0; i < message.dims.length; ++i)
+ if (!$util.isInteger(message.dims[i]) && !(message.dims[i] && $util.isInteger(message.dims[i].low) && $util.isInteger(message.dims[i].high)))
+ return "dims: integer|Long[] expected";
+ }
+ if (message.dataType != null && message.hasOwnProperty("dataType"))
+ if (!$util.isInteger(message.dataType))
+ return "dataType: integer expected";
+ if (message.segment != null && message.hasOwnProperty("segment")) {
+ var error = $root.onnx.TensorProto.Segment.verify(message.segment);
+ if (error)
+ return "segment." + error;
+ }
+ if (message.floatData != null && message.hasOwnProperty("floatData")) {
+ if (!Array.isArray(message.floatData))
+ return "floatData: array expected";
+ for (var i = 0; i < message.floatData.length; ++i)
+ if (typeof message.floatData[i] !== "number")
+ return "floatData: number[] expected";
+ }
+ if (message.int32Data != null && message.hasOwnProperty("int32Data")) {
+ if (!Array.isArray(message.int32Data))
+ return "int32Data: array expected";
+ for (var i = 0; i < message.int32Data.length; ++i)
+ if (!$util.isInteger(message.int32Data[i]))
+ return "int32Data: integer[] expected";
+ }
+ if (message.stringData != null && message.hasOwnProperty("stringData")) {
+ if (!Array.isArray(message.stringData))
+ return "stringData: array expected";
+ for (var i = 0; i < message.stringData.length; ++i)
+ if (!(message.stringData[i] && typeof message.stringData[i].length === "number" || $util.isString(message.stringData[i])))
+ return "stringData: buffer[] expected";
+ }
+ if (message.int64Data != null && message.hasOwnProperty("int64Data")) {
+ if (!Array.isArray(message.int64Data))
+ return "int64Data: array expected";
+ for (var i = 0; i < message.int64Data.length; ++i)
+ if (!$util.isInteger(message.int64Data[i]) && !(message.int64Data[i] && $util.isInteger(message.int64Data[i].low) && $util.isInteger(message.int64Data[i].high)))
+ return "int64Data: integer|Long[] expected";
+ }
+ if (message.name != null && message.hasOwnProperty("name"))
+ if (!$util.isString(message.name))
+ return "name: string expected";
+ if (message.docString != null && message.hasOwnProperty("docString"))
+ if (!$util.isString(message.docString))
+ return "docString: string expected";
+ if (message.rawData != null && message.hasOwnProperty("rawData"))
+ if (!(message.rawData && typeof message.rawData.length === "number" || $util.isString(message.rawData)))
+ return "rawData: buffer expected";
+ if (message.externalData != null && message.hasOwnProperty("externalData")) {
+ if (!Array.isArray(message.externalData))
+ return "externalData: array expected";
+ for (var i = 0; i < message.externalData.length; ++i) {
+ var error = $root.onnx.StringStringEntryProto.verify(message.externalData[i]);
+ if (error)
+ return "externalData." + error;
+ }
+ }
+ if (message.dataLocation != null && message.hasOwnProperty("dataLocation"))
+ switch (message.dataLocation) {
+ default:
+ return "dataLocation: enum value expected";
+ case 0:
+ case 1:
+ break;
+ }
+ if (message.doubleData != null && message.hasOwnProperty("doubleData")) {
+ if (!Array.isArray(message.doubleData))
+ return "doubleData: array expected";
+ for (var i = 0; i < message.doubleData.length; ++i)
+ if (typeof message.doubleData[i] !== "number")
+ return "doubleData: number[] expected";
+ }
+ if (message.uint64Data != null && message.hasOwnProperty("uint64Data")) {
+ if (!Array.isArray(message.uint64Data))
+ return "uint64Data: array expected";
+ for (var i = 0; i < message.uint64Data.length; ++i)
+ if (!$util.isInteger(message.uint64Data[i]) && !(message.uint64Data[i] && $util.isInteger(message.uint64Data[i].low) && $util.isInteger(message.uint64Data[i].high)))
+ return "uint64Data: integer|Long[] expected";
+ }
+ return null;
+ };
+
+ /**
+ * Creates a TensorProto message from a plain object. Also converts values to their respective internal types.
+ * @function fromObject
+ * @memberof onnx.TensorProto
+ * @static
+ * @param {Object.<string,*>} object Plain object
+ * @returns {onnx.TensorProto} TensorProto
+ */
+ TensorProto.fromObject = function fromObject(object) {
+ if (object instanceof $root.onnx.TensorProto)
+ return object;
+ var message = new $root.onnx.TensorProto();
+ if (object.dims) {
+ if (!Array.isArray(object.dims))
+ throw TypeError(".onnx.TensorProto.dims: array expected");
+ message.dims = [];
+ for (var i = 0; i < object.dims.length; ++i)
+ if ($util.Long)
+ (message.dims[i] = $util.Long.fromValue(object.dims[i])).unsigned = false;
+ else if (typeof object.dims[i] === "string")
+ message.dims[i] = parseInt(object.dims[i], 10);
+ else if (typeof object.dims[i] === "number")
+ message.dims[i] = object.dims[i];
+ else if (typeof object.dims[i] === "object")
+ message.dims[i] = new $util.LongBits(object.dims[i].low >>> 0, object.dims[i].high >>> 0).toNumber();
+ }
+ if (object.dataType != null)
+ message.dataType = object.dataType | 0;
+ if (object.segment != null) {
+ if (typeof object.segment !== "object")
+ throw TypeError(".onnx.TensorProto.segment: object expected");
+ message.segment = $root.onnx.TensorProto.Segment.fromObject(object.segment);
+ }
+ if (object.floatData) {
+ if (!Array.isArray(object.floatData))
+ throw TypeError(".onnx.TensorProto.floatData: array expected");
+ message.floatData = [];
+ for (var i = 0; i < object.floatData.length; ++i)
+ message.floatData[i] = Number(object.floatData[i]);
+ }
+ if (object.int32Data) {
+ if (!Array.isArray(object.int32Data))
+ throw TypeError(".onnx.TensorProto.int32Data: array expected");
+ message.int32Data = [];
+ for (var i = 0; i < object.int32Data.length; ++i)
+ message.int32Data[i] = object.int32Data[i] | 0;
+ }
+ if (object.stringData) {
+ if (!Array.isArray(object.stringData))
+ throw TypeError(".onnx.TensorProto.stringData: array expected");
+ message.stringData = [];
+ for (var i = 0; i < object.stringData.length; ++i)
+ if (typeof object.stringData[i] === "string")
+ $util.base64.decode(object.stringData[i], message.stringData[i] = $util.newBuffer($util.base64.length(object.stringData[i])), 0);
+ else if (object.stringData[i].length)
+ message.stringData[i] = object.stringData[i];
+ }
+ if (object.int64Data) {
+ if (!Array.isArray(object.int64Data))
+ throw TypeError(".onnx.TensorProto.int64Data: array expected");
+ message.int64Data = [];
+ for (var i = 0; i < object.int64Data.length; ++i)
+ if ($util.Long)
+ (message.int64Data[i] = $util.Long.fromValue(object.int64Data[i])).unsigned = false;
+ else if (typeof object.int64Data[i] === "string")
+ message.int64Data[i] = parseInt(object.int64Data[i], 10);
+ else if (typeof object.int64Data[i] === "number")
+ message.int64Data[i] = object.int64Data[i];
+ else if (typeof object.int64Data[i] === "object")
+ message.int64Data[i] = new $util.LongBits(object.int64Data[i].low >>> 0, object.int64Data[i].high >>> 0).toNumber();
+ }
+ if (object.name != null)
+ message.name = String(object.name);
+ if (object.docString != null)
+ message.docString = String(object.docString);
+ if (object.rawData != null)
+ if (typeof object.rawData === "string")
+ $util.base64.decode(object.rawData, message.rawData = $util.newBuffer($util.base64.length(object.rawData)), 0);
+ else if (object.rawData.length)
+ message.rawData = object.rawData;
+ if (object.externalData) {
+ if (!Array.isArray(object.externalData))
+ throw TypeError(".onnx.TensorProto.externalData: array expected");
+ message.externalData = [];
+ for (var i = 0; i < object.externalData.length; ++i) {
+ if (typeof object.externalData[i] !== "object")
+ throw TypeError(".onnx.TensorProto.externalData: object expected");
+ message.externalData[i] = $root.onnx.StringStringEntryProto.fromObject(object.externalData[i]);
+ }
+ }
+ switch (object.dataLocation) {
+ case "DEFAULT":
+ case 0:
+ message.dataLocation = 0;
+ break;
+ case "EXTERNAL":
+ case 1:
+ message.dataLocation = 1;
+ break;
+ }
+ if (object.doubleData) {
+ if (!Array.isArray(object.doubleData))
+ throw TypeError(".onnx.TensorProto.doubleData: array expected");
+ message.doubleData = [];
+ for (var i = 0; i < object.doubleData.length; ++i)
+ message.doubleData[i] = Number(object.doubleData[i]);
+ }
+ if (object.uint64Data) {
+ if (!Array.isArray(object.uint64Data))
+ throw TypeError(".onnx.TensorProto.uint64Data: array expected");
+ message.uint64Data = [];
+ for (var i = 0; i < object.uint64Data.length; ++i)
+ if ($util.Long)
+ (message.uint64Data[i] = $util.Long.fromValue(object.uint64Data[i])).unsigned = true;
+ else if (typeof object.uint64Data[i] === "string")
+ message.uint64Data[i] = parseInt(object.uint64Data[i], 10);
+ else if (typeof object.uint64Data[i] === "number")
+ message.uint64Data[i] = object.uint64Data[i];
+ else if (typeof object.uint64Data[i] === "object")
+ message.uint64Data[i] = new $util.LongBits(object.uint64Data[i].low >>> 0, object.uint64Data[i].high >>> 0).toNumber(true);
+ }
+ return message;
+ };
+
+ /**
+ * Creates a plain object from a TensorProto message. Also converts values to other types if specified.
+ * @function toObject
+ * @memberof onnx.TensorProto
+ * @static
+ * @param {onnx.TensorProto} message TensorProto
+ * @param {$protobuf.IConversionOptions} [options] Conversion options
+ * @returns {Object.<string,*>} Plain object
+ */
+ TensorProto.toObject = function toObject(message, options) {
+ if (!options)
+ options = {};
+ var object = {};
+ if (options.arrays || options.defaults) {
+ object.dims = [];
+ object.floatData = [];
+ object.int32Data = [];
+ object.stringData = [];
+ object.int64Data = [];
+ object.doubleData = [];
+ object.uint64Data = [];
+ object.externalData = [];
+ }
+ if (options.defaults) {
+ object.dataType = 0;
+ object.segment = null;
+ object.name = "";
+ if (options.bytes === String)
+ object.rawData = "";
+ else {
+ object.rawData = [];
+ if (options.bytes !== Array)
+ object.rawData = $util.newBuffer(object.rawData);
+ }
+ object.docString = "";
+ object.dataLocation = options.enums === String ? "DEFAULT" : 0;
+ }
+ if (message.dims && message.dims.length) {
+ object.dims = [];
+ for (var j = 0; j < message.dims.length; ++j)
+ if (typeof message.dims[j] === "number")
+ object.dims[j] = options.longs === String ? String(message.dims[j]) : message.dims[j];
+ else
+ object.dims[j] = options.longs === String ? $util.Long.prototype.toString.call(message.dims[j]) : options.longs === Number ? new $util.LongBits(message.dims[j].low >>> 0, message.dims[j].high >>> 0).toNumber() : message.dims[j];
+ }
+ if (message.dataType != null && message.hasOwnProperty("dataType"))
+ object.dataType = message.dataType;
+ if (message.segment != null && message.hasOwnProperty("segment"))
+ object.segment = $root.onnx.TensorProto.Segment.toObject(message.segment, options);
+ if (message.floatData && message.floatData.length) {
+ object.floatData = [];
+ for (var j = 0; j < message.floatData.length; ++j)
+ object.floatData[j] = options.json && !isFinite(message.floatData[j]) ? String(message.floatData[j]) : message.floatData[j];
+ }
+ if (message.int32Data && message.int32Data.length) {
+ object.int32Data = [];
+ for (var j = 0; j < message.int32Data.length; ++j)
+ object.int32Data[j] = message.int32Data[j];
+ }
+ if (message.stringData && message.stringData.length) {
+ object.stringData = [];
+ for (var j = 0; j < message.stringData.length; ++j)
+ object.stringData[j] = options.bytes === String ? $util.base64.encode(message.stringData[j], 0, message.stringData[j].length) : options.bytes === Array ? Array.prototype.slice.call(message.stringData[j]) : message.stringData[j];
+ }
+ if (message.int64Data && message.int64Data.length) {
+ object.int64Data = [];
+ for (var j = 0; j < message.int64Data.length; ++j)
+ if (typeof message.int64Data[j] === "number")
+ object.int64Data[j] = options.longs === String ? String(message.int64Data[j]) : message.int64Data[j];
+ else
+ object.int64Data[j] = options.longs === String ? $util.Long.prototype.toString.call(message.int64Data[j]) : options.longs === Number ? new $util.LongBits(message.int64Data[j].low >>> 0, message.int64Data[j].high >>> 0).toNumber() : message.int64Data[j];
+ }
+ if (message.name != null && message.hasOwnProperty("name"))
+ object.name = message.name;
+ if (message.rawData != null && message.hasOwnProperty("rawData"))
+ object.rawData = options.bytes === String ? $util.base64.encode(message.rawData, 0, message.rawData.length) : options.bytes === Array ? Array.prototype.slice.call(message.rawData) : message.rawData;
+ if (message.doubleData && message.doubleData.length) {
+ object.doubleData = [];
+ for (var j = 0; j < message.doubleData.length; ++j)
+ object.doubleData[j] = options.json && !isFinite(message.doubleData[j]) ? String(message.doubleData[j]) : message.doubleData[j];
+ }
+ if (message.uint64Data && message.uint64Data.length) {
+ object.uint64Data = [];
+ for (var j = 0; j < message.uint64Data.length; ++j)
+ if (typeof message.uint64Data[j] === "number")
+ object.uint64Data[j] = options.longs === String ? String(message.uint64Data[j]) : message.uint64Data[j];
+ else
+ object.uint64Data[j] = options.longs === String ? $util.Long.prototype.toString.call(message.uint64Data[j]) : options.longs === Number ? new $util.LongBits(message.uint64Data[j].low >>> 0, message.uint64Data[j].high >>> 0).toNumber(true) : message.uint64Data[j];
+ }
+ if (message.docString != null && message.hasOwnProperty("docString"))
+ object.docString = message.docString;
+ if (message.externalData && message.externalData.length) {
+ object.externalData = [];
+ for (var j = 0; j < message.externalData.length; ++j)
+ object.externalData[j] = $root.onnx.StringStringEntryProto.toObject(message.externalData[j], options);
+ }
+ if (message.dataLocation != null && message.hasOwnProperty("dataLocation"))
+ object.dataLocation = options.enums === String ? $root.onnx.TensorProto.DataLocation[message.dataLocation] : message.dataLocation;
+ return object;
+ };
+
+ /**
+ * Converts this TensorProto to JSON.
+ * @function toJSON
+ * @memberof onnx.TensorProto
+ * @instance
+ * @returns {Object.<string,*>} JSON object
+ */
+ TensorProto.prototype.toJSON = function toJSON() {
+ return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
+ };
+
+ /**
+ * DataType enum.
+ * @name onnx.TensorProto.DataType
+ * @enum {string}
+ * @property {number} UNDEFINED=0 UNDEFINED value
+ * @property {number} FLOAT=1 FLOAT value
+ * @property {number} UINT8=2 UINT8 value
+ * @property {number} INT8=3 INT8 value
+ * @property {number} UINT16=4 UINT16 value
+ * @property {number} INT16=5 INT16 value
+ * @property {number} INT32=6 INT32 value
+ * @property {number} INT64=7 INT64 value
+ * @property {number} STRING=8 STRING value
+ * @property {number} BOOL=9 BOOL value
+ * @property {number} FLOAT16=10 FLOAT16 value
+ * @property {number} DOUBLE=11 DOUBLE value
+ * @property {number} UINT32=12 UINT32 value
+ * @property {number} UINT64=13 UINT64 value
+ * @property {number} COMPLEX64=14 COMPLEX64 value
+ * @property {number} COMPLEX128=15 COMPLEX128 value
+ * @property {number} BFLOAT16=16 BFLOAT16 value
+ */
+ TensorProto.DataType = (function() {
+ var valuesById = {}, values = Object.create(valuesById);
+ values[valuesById[0] = "UNDEFINED"] = 0;
+ values[valuesById[1] = "FLOAT"] = 1;
+ values[valuesById[2] = "UINT8"] = 2;
+ values[valuesById[3] = "INT8"] = 3;
+ values[valuesById[4] = "UINT16"] = 4;
+ values[valuesById[5] = "INT16"] = 5;
+ values[valuesById[6] = "INT32"] = 6;
+ values[valuesById[7] = "INT64"] = 7;
+ values[valuesById[8] = "STRING"] = 8;
+ values[valuesById[9] = "BOOL"] = 9;
+ values[valuesById[10] = "FLOAT16"] = 10;
+ values[valuesById[11] = "DOUBLE"] = 11;
+ values[valuesById[12] = "UINT32"] = 12;
+ values[valuesById[13] = "UINT64"] = 13;
+ values[valuesById[14] = "COMPLEX64"] = 14;
+ values[valuesById[15] = "COMPLEX128"] = 15;
+ values[valuesById[16] = "BFLOAT16"] = 16;
+ return values;
+ })();
+
+ TensorProto.Segment = (function() {
+
+ /**
+ * Properties of a Segment.
+ * @memberof onnx.TensorProto
+ * @interface ISegment
+ * @property {number|Long|null} [begin] Segment begin
+ * @property {number|Long|null} [end] Segment end
+ */
+
+ /**
+ * Constructs a new Segment.
+ * @memberof onnx.TensorProto
+ * @classdesc Represents a Segment.
+ * @implements ISegment
+ * @constructor
+ * @param {onnx.TensorProto.ISegment=} [properties] Properties to set
+ */
+ function Segment(properties) {
+ if (properties)
+ for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
+ if (properties[keys[i]] != null)
+ this[keys[i]] = properties[keys[i]];
+ }
+
+ /**
+ * Segment begin.
+ * @member {number|Long} begin
+ * @memberof onnx.TensorProto.Segment
+ * @instance
+ */
+ Segment.prototype.begin = $util.Long ? $util.Long.fromBits(0,0,false) : 0;
+
+ /**
+ * Segment end.
+ * @member {number|Long} end
+ * @memberof onnx.TensorProto.Segment
+ * @instance
+ */
+ Segment.prototype.end = $util.Long ? $util.Long.fromBits(0,0,false) : 0;
+
+ /**
+ * Creates a new Segment instance using the specified properties.
+ * @function create
+ * @memberof onnx.TensorProto.Segment
+ * @static
+ * @param {onnx.TensorProto.ISegment=} [properties] Properties to set
+ * @returns {onnx.TensorProto.Segment} Segment instance
+ */
+ Segment.create = function create(properties) {
+ return new Segment(properties);
+ };
+
+ /**
+ * Encodes the specified Segment message. Does not implicitly {@link onnx.TensorProto.Segment.verify|verify} messages.
+ * @function encode
+ * @memberof onnx.TensorProto.Segment
+ * @static
+ * @param {onnx.TensorProto.ISegment} message Segment message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ Segment.encode = function encode(message, writer) {
+ if (!writer)
+ writer = $Writer.create();
+ if (message.begin != null && message.hasOwnProperty("begin"))
+ writer.uint32(/* id 1, wireType 0 =*/8).int64(message.begin);
+ if (message.end != null && message.hasOwnProperty("end"))
+ writer.uint32(/* id 2, wireType 0 =*/16).int64(message.end);
+ return writer;
+ };
+
+ /**
+ * Encodes the specified Segment message, length delimited. Does not implicitly {@link onnx.TensorProto.Segment.verify|verify} messages.
+ * @function encodeDelimited
+ * @memberof onnx.TensorProto.Segment
+ * @static
+ * @param {onnx.TensorProto.ISegment} message Segment message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ Segment.encodeDelimited = function encodeDelimited(message, writer) {
+ return this.encode(message, writer).ldelim();
+ };
+
+ /**
+ * Decodes a Segment message from the specified reader or buffer.
+ * @function decode
+ * @memberof onnx.TensorProto.Segment
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @param {number} [length] Message length if known beforehand
+ * @returns {onnx.TensorProto.Segment} Segment
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ Segment.decode = function decode(reader, length) {
+ if (!(reader instanceof $Reader))
+ reader = $Reader.create(reader);
+ var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.TensorProto.Segment();
+ while (reader.pos < end) {
+ var tag = reader.uint32();
+ switch (tag >>> 3) {
+ case 1:
+ message.begin = reader.int64();
+ break;
+ case 2:
+ message.end = reader.int64();
+ break;
+ default:
+ reader.skipType(tag & 7);
+ break;
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Decodes a Segment message from the specified reader or buffer, length delimited.
+ * @function decodeDelimited
+ * @memberof onnx.TensorProto.Segment
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @returns {onnx.TensorProto.Segment} Segment
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ Segment.decodeDelimited = function decodeDelimited(reader) {
+ if (!(reader instanceof $Reader))
+ reader = new $Reader(reader);
+ return this.decode(reader, reader.uint32());
+ };
+
+ /**
+ * Verifies a Segment message.
+ * @function verify
+ * @memberof onnx.TensorProto.Segment
+ * @static
+ * @param {Object.<string,*>} message Plain object to verify
+ * @returns {string|null} `null` if valid, otherwise the reason why it is not
+ */
+ Segment.verify = function verify(message) {
+ if (typeof message !== "object" || message === null)
+ return "object expected";
+ if (message.begin != null && message.hasOwnProperty("begin"))
+ if (!$util.isInteger(message.begin) && !(message.begin && $util.isInteger(message.begin.low) && $util.isInteger(message.begin.high)))
+ return "begin: integer|Long expected";
+ if (message.end != null && message.hasOwnProperty("end"))
+ if (!$util.isInteger(message.end) && !(message.end && $util.isInteger(message.end.low) && $util.isInteger(message.end.high)))
+ return "end: integer|Long expected";
+ return null;
+ };
+
+ /**
+ * Creates a Segment message from a plain object. Also converts values to their respective internal types.
+ * @function fromObject
+ * @memberof onnx.TensorProto.Segment
+ * @static
+ * @param {Object.<string,*>} object Plain object
+ * @returns {onnx.TensorProto.Segment} Segment
+ */
+ Segment.fromObject = function fromObject(object) {
+ if (object instanceof $root.onnx.TensorProto.Segment)
+ return object;
+ var message = new $root.onnx.TensorProto.Segment();
+ if (object.begin != null)
+ if ($util.Long)
+ (message.begin = $util.Long.fromValue(object.begin)).unsigned = false;
+ else if (typeof object.begin === "string")
+ message.begin = parseInt(object.begin, 10);
+ else if (typeof object.begin === "number")
+ message.begin = object.begin;
+ else if (typeof object.begin === "object")
+ message.begin = new $util.LongBits(object.begin.low >>> 0, object.begin.high >>> 0).toNumber();
+ if (object.end != null)
+ if ($util.Long)
+ (message.end = $util.Long.fromValue(object.end)).unsigned = false;
+ else if (typeof object.end === "string")
+ message.end = parseInt(object.end, 10);
+ else if (typeof object.end === "number")
+ message.end = object.end;
+ else if (typeof object.end === "object")
+ message.end = new $util.LongBits(object.end.low >>> 0, object.end.high >>> 0).toNumber();
+ return message;
+ };
+
+ /**
+ * Creates a plain object from a Segment message. Also converts values to other types if specified.
+ * @function toObject
+ * @memberof onnx.TensorProto.Segment
+ * @static
+ * @param {onnx.TensorProto.Segment} message Segment
+ * @param {$protobuf.IConversionOptions} [options] Conversion options
+ * @returns {Object.<string,*>} Plain object
+ */
+ Segment.toObject = function toObject(message, options) {
+ if (!options)
+ options = {};
+ var object = {};
+ if (options.defaults) {
+ if ($util.Long) {
+ var long = new $util.Long(0, 0, false);
+ object.begin = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
+ } else
+ object.begin = options.longs === String ? "0" : 0;
+ if ($util.Long) {
+ var long = new $util.Long(0, 0, false);
+ object.end = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
+ } else
+ object.end = options.longs === String ? "0" : 0;
+ }
+ if (message.begin != null && message.hasOwnProperty("begin"))
+ if (typeof message.begin === "number")
+ object.begin = options.longs === String ? String(message.begin) : message.begin;
+ else
+ object.begin = options.longs === String ? $util.Long.prototype.toString.call(message.begin) : options.longs === Number ? new $util.LongBits(message.begin.low >>> 0, message.begin.high >>> 0).toNumber() : message.begin;
+ if (message.end != null && message.hasOwnProperty("end"))
+ if (typeof message.end === "number")
+ object.end = options.longs === String ? String(message.end) : message.end;
+ else
+ object.end = options.longs === String ? $util.Long.prototype.toString.call(message.end) : options.longs === Number ? new $util.LongBits(message.end.low >>> 0, message.end.high >>> 0).toNumber() : message.end;
+ return object;
+ };
+
+ /**
+ * Converts this Segment to JSON.
+ * @function toJSON
+ * @memberof onnx.TensorProto.Segment
+ * @instance
+ * @returns {Object.<string,*>} JSON object
+ */
+ Segment.prototype.toJSON = function toJSON() {
+ return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
+ };
+
+ return Segment;
+ })();
+
+ /**
+ * DataLocation enum.
+ * @name onnx.TensorProto.DataLocation
+ * @enum {string}
+ * @property {number} DEFAULT=0 DEFAULT value
+ * @property {number} EXTERNAL=1 EXTERNAL value
+ */
+ TensorProto.DataLocation = (function() {
+ var valuesById = {}, values = Object.create(valuesById);
+ values[valuesById[0] = "DEFAULT"] = 0;
+ values[valuesById[1] = "EXTERNAL"] = 1;
+ return values;
+ })();
+
+ return TensorProto;
+ })();
+
+ onnx.TensorShapeProto = (function() {
+
+ /**
+ * Properties of a TensorShapeProto.
+ * @memberof onnx
+ * @interface ITensorShapeProto
+ * @property {Array.<onnx.TensorShapeProto.IDimension>|null} [dim] TensorShapeProto dim
+ */
+
+ /**
+ * Constructs a new TensorShapeProto.
+ * @memberof onnx
+ * @classdesc Represents a TensorShapeProto.
+ * @implements ITensorShapeProto
+ * @constructor
+ * @param {onnx.ITensorShapeProto=} [properties] Properties to set
+ */
+ function TensorShapeProto(properties) {
+ this.dim = [];
+ if (properties)
+ for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
+ if (properties[keys[i]] != null)
+ this[keys[i]] = properties[keys[i]];
+ }
+
+ /**
+ * TensorShapeProto dim.
+ * @member {Array.<onnx.TensorShapeProto.IDimension>} dim
+ * @memberof onnx.TensorShapeProto
+ * @instance
+ */
+ TensorShapeProto.prototype.dim = $util.emptyArray;
+
+ /**
+ * Creates a new TensorShapeProto instance using the specified properties.
+ * @function create
+ * @memberof onnx.TensorShapeProto
+ * @static
+ * @param {onnx.ITensorShapeProto=} [properties] Properties to set
+ * @returns {onnx.TensorShapeProto} TensorShapeProto instance
+ */
+ TensorShapeProto.create = function create(properties) {
+ return new TensorShapeProto(properties);
+ };
+
+ /**
+ * Encodes the specified TensorShapeProto message. Does not implicitly {@link onnx.TensorShapeProto.verify|verify} messages.
+ * @function encode
+ * @memberof onnx.TensorShapeProto
+ * @static
+ * @param {onnx.ITensorShapeProto} message TensorShapeProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ TensorShapeProto.encode = function encode(message, writer) {
+ if (!writer)
+ writer = $Writer.create();
+ if (message.dim != null && message.dim.length)
+ for (var i = 0; i < message.dim.length; ++i)
+ $root.onnx.TensorShapeProto.Dimension.encode(message.dim[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();
+ return writer;
+ };
+
+ /**
+ * Encodes the specified TensorShapeProto message, length delimited. Does not implicitly {@link onnx.TensorShapeProto.verify|verify} messages.
+ * @function encodeDelimited
+ * @memberof onnx.TensorShapeProto
+ * @static
+ * @param {onnx.ITensorShapeProto} message TensorShapeProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ TensorShapeProto.encodeDelimited = function encodeDelimited(message, writer) {
+ return this.encode(message, writer).ldelim();
+ };
+
+ /**
+ * Decodes a TensorShapeProto message from the specified reader or buffer.
+ * @function decode
+ * @memberof onnx.TensorShapeProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @param {number} [length] Message length if known beforehand
+ * @returns {onnx.TensorShapeProto} TensorShapeProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ TensorShapeProto.decode = function decode(reader, length) {
+ if (!(reader instanceof $Reader))
+ reader = $Reader.create(reader);
+ var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.TensorShapeProto();
+ while (reader.pos < end) {
+ var tag = reader.uint32();
+ switch (tag >>> 3) {
+ case 1:
+ if (!(message.dim && message.dim.length))
+ message.dim = [];
+ message.dim.push($root.onnx.TensorShapeProto.Dimension.decode(reader, reader.uint32()));
+ break;
+ default:
+ reader.skipType(tag & 7);
+ break;
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Decodes a TensorShapeProto message from the specified reader or buffer, length delimited.
+ * @function decodeDelimited
+ * @memberof onnx.TensorShapeProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @returns {onnx.TensorShapeProto} TensorShapeProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ TensorShapeProto.decodeDelimited = function decodeDelimited(reader) {
+ if (!(reader instanceof $Reader))
+ reader = new $Reader(reader);
+ return this.decode(reader, reader.uint32());
+ };
+
+ /**
+ * Verifies a TensorShapeProto message.
+ * @function verify
+ * @memberof onnx.TensorShapeProto
+ * @static
+ * @param {Object.<string,*>} message Plain object to verify
+ * @returns {string|null} `null` if valid, otherwise the reason why it is not
+ */
+ TensorShapeProto.verify = function verify(message) {
+ if (typeof message !== "object" || message === null)
+ return "object expected";
+ if (message.dim != null && message.hasOwnProperty("dim")) {
+ if (!Array.isArray(message.dim))
+ return "dim: array expected";
+ for (var i = 0; i < message.dim.length; ++i) {
+ var error = $root.onnx.TensorShapeProto.Dimension.verify(message.dim[i]);
+ if (error)
+ return "dim." + error;
+ }
+ }
+ return null;
+ };
+
+ /**
+ * Creates a TensorShapeProto message from a plain object. Also converts values to their respective internal types.
+ * @function fromObject
+ * @memberof onnx.TensorShapeProto
+ * @static
+ * @param {Object.<string,*>} object Plain object
+ * @returns {onnx.TensorShapeProto} TensorShapeProto
+ */
+ TensorShapeProto.fromObject = function fromObject(object) {
+ if (object instanceof $root.onnx.TensorShapeProto)
+ return object;
+ var message = new $root.onnx.TensorShapeProto();
+ if (object.dim) {
+ if (!Array.isArray(object.dim))
+ throw TypeError(".onnx.TensorShapeProto.dim: array expected");
+ message.dim = [];
+ for (var i = 0; i < object.dim.length; ++i) {
+ if (typeof object.dim[i] !== "object")
+ throw TypeError(".onnx.TensorShapeProto.dim: object expected");
+ message.dim[i] = $root.onnx.TensorShapeProto.Dimension.fromObject(object.dim[i]);
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Creates a plain object from a TensorShapeProto message. Also converts values to other types if specified.
+ * @function toObject
+ * @memberof onnx.TensorShapeProto
+ * @static
+ * @param {onnx.TensorShapeProto} message TensorShapeProto
+ * @param {$protobuf.IConversionOptions} [options] Conversion options
+ * @returns {Object.<string,*>} Plain object
+ */
+ TensorShapeProto.toObject = function toObject(message, options) {
+ if (!options)
+ options = {};
+ var object = {};
+ if (options.arrays || options.defaults)
+ object.dim = [];
+ if (message.dim && message.dim.length) {
+ object.dim = [];
+ for (var j = 0; j < message.dim.length; ++j)
+ object.dim[j] = $root.onnx.TensorShapeProto.Dimension.toObject(message.dim[j], options);
+ }
+ return object;
+ };
+
+ /**
+ * Converts this TensorShapeProto to JSON.
+ * @function toJSON
+ * @memberof onnx.TensorShapeProto
+ * @instance
+ * @returns {Object.<string,*>} JSON object
+ */
+ TensorShapeProto.prototype.toJSON = function toJSON() {
+ return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
+ };
+
+ TensorShapeProto.Dimension = (function() {
+
+ /**
+ * Properties of a Dimension.
+ * @memberof onnx.TensorShapeProto
+ * @interface IDimension
+ * @property {number|Long|null} [dimValue] Dimension dimValue
+ * @property {string|null} [dimParam] Dimension dimParam
+ * @property {string|null} [denotation] Dimension denotation
+ */
+
+ /**
+ * Constructs a new Dimension.
+ * @memberof onnx.TensorShapeProto
+ * @classdesc Represents a Dimension.
+ * @implements IDimension
+ * @constructor
+ * @param {onnx.TensorShapeProto.IDimension=} [properties] Properties to set
+ */
+ function Dimension(properties) {
+ if (properties)
+ for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
+ if (properties[keys[i]] != null)
+ this[keys[i]] = properties[keys[i]];
+ }
+
+ /**
+ * Dimension dimValue.
+ * @member {number|Long} dimValue
+ * @memberof onnx.TensorShapeProto.Dimension
+ * @instance
+ */
+ Dimension.prototype.dimValue = $util.Long ? $util.Long.fromBits(0,0,false) : 0;
+
+ /**
+ * Dimension dimParam.
+ * @member {string} dimParam
+ * @memberof onnx.TensorShapeProto.Dimension
+ * @instance
+ */
+ Dimension.prototype.dimParam = "";
+
+ /**
+ * Dimension denotation.
+ * @member {string} denotation
+ * @memberof onnx.TensorShapeProto.Dimension
+ * @instance
+ */
+ Dimension.prototype.denotation = "";
+
+ // OneOf field names bound to virtual getters and setters
+ var $oneOfFields;
+
+ /**
+ * Dimension value.
+ * @member {"dimValue"|"dimParam"|undefined} value
+ * @memberof onnx.TensorShapeProto.Dimension
+ * @instance
+ */
+ Object.defineProperty(Dimension.prototype, "value", {
+ get: $util.oneOfGetter($oneOfFields = ["dimValue", "dimParam"]),
+ set: $util.oneOfSetter($oneOfFields)
+ });
+
+ /**
+ * Creates a new Dimension instance using the specified properties.
+ * @function create
+ * @memberof onnx.TensorShapeProto.Dimension
+ * @static
+ * @param {onnx.TensorShapeProto.IDimension=} [properties] Properties to set
+ * @returns {onnx.TensorShapeProto.Dimension} Dimension instance
+ */
+ Dimension.create = function create(properties) {
+ return new Dimension(properties);
+ };
+
+ /**
+ * Encodes the specified Dimension message. Does not implicitly {@link onnx.TensorShapeProto.Dimension.verify|verify} messages.
+ * @function encode
+ * @memberof onnx.TensorShapeProto.Dimension
+ * @static
+ * @param {onnx.TensorShapeProto.IDimension} message Dimension message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ Dimension.encode = function encode(message, writer) {
+ if (!writer)
+ writer = $Writer.create();
+ if (message.dimValue != null && message.hasOwnProperty("dimValue"))
+ writer.uint32(/* id 1, wireType 0 =*/8).int64(message.dimValue);
+ if (message.dimParam != null && message.hasOwnProperty("dimParam"))
+ writer.uint32(/* id 2, wireType 2 =*/18).string(message.dimParam);
+ if (message.denotation != null && message.hasOwnProperty("denotation"))
+ writer.uint32(/* id 3, wireType 2 =*/26).string(message.denotation);
+ return writer;
+ };
+
+ /**
+ * Encodes the specified Dimension message, length delimited. Does not implicitly {@link onnx.TensorShapeProto.Dimension.verify|verify} messages.
+ * @function encodeDelimited
+ * @memberof onnx.TensorShapeProto.Dimension
+ * @static
+ * @param {onnx.TensorShapeProto.IDimension} message Dimension message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ Dimension.encodeDelimited = function encodeDelimited(message, writer) {
+ return this.encode(message, writer).ldelim();
+ };
+
+ /**
+ * Decodes a Dimension message from the specified reader or buffer.
+ * @function decode
+ * @memberof onnx.TensorShapeProto.Dimension
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @param {number} [length] Message length if known beforehand
+ * @returns {onnx.TensorShapeProto.Dimension} Dimension
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ Dimension.decode = function decode(reader, length) {
+ if (!(reader instanceof $Reader))
+ reader = $Reader.create(reader);
+ var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.TensorShapeProto.Dimension();
+ while (reader.pos < end) {
+ var tag = reader.uint32();
+ switch (tag >>> 3) {
+ case 1:
+ message.dimValue = reader.int64();
+ break;
+ case 2:
+ message.dimParam = reader.string();
+ break;
+ case 3:
+ message.denotation = reader.string();
+ break;
+ default:
+ reader.skipType(tag & 7);
+ break;
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Decodes a Dimension message from the specified reader or buffer, length delimited.
+ * @function decodeDelimited
+ * @memberof onnx.TensorShapeProto.Dimension
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @returns {onnx.TensorShapeProto.Dimension} Dimension
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ Dimension.decodeDelimited = function decodeDelimited(reader) {
+ if (!(reader instanceof $Reader))
+ reader = new $Reader(reader);
+ return this.decode(reader, reader.uint32());
+ };
+
+ /**
+ * Verifies a Dimension message.
+ * @function verify
+ * @memberof onnx.TensorShapeProto.Dimension
+ * @static
+ * @param {Object.<string,*>} message Plain object to verify
+ * @returns {string|null} `null` if valid, otherwise the reason why it is not
+ */
+ Dimension.verify = function verify(message) {
+ if (typeof message !== "object" || message === null)
+ return "object expected";
+ var properties = {};
+ if (message.dimValue != null && message.hasOwnProperty("dimValue")) {
+ properties.value = 1;
+ if (!$util.isInteger(message.dimValue) && !(message.dimValue && $util.isInteger(message.dimValue.low) && $util.isInteger(message.dimValue.high)))
+ return "dimValue: integer|Long expected";
+ }
+ if (message.dimParam != null && message.hasOwnProperty("dimParam")) {
+ if (properties.value === 1)
+ return "value: multiple values";
+ properties.value = 1;
+ if (!$util.isString(message.dimParam))
+ return "dimParam: string expected";
+ }
+ if (message.denotation != null && message.hasOwnProperty("denotation"))
+ if (!$util.isString(message.denotation))
+ return "denotation: string expected";
+ return null;
+ };
+
+ /**
+ * Creates a Dimension message from a plain object. Also converts values to their respective internal types.
+ * @function fromObject
+ * @memberof onnx.TensorShapeProto.Dimension
+ * @static
+ * @param {Object.<string,*>} object Plain object
+ * @returns {onnx.TensorShapeProto.Dimension} Dimension
+ */
+ Dimension.fromObject = function fromObject(object) {
+ if (object instanceof $root.onnx.TensorShapeProto.Dimension)
+ return object;
+ var message = new $root.onnx.TensorShapeProto.Dimension();
+ if (object.dimValue != null)
+ if ($util.Long)
+ (message.dimValue = $util.Long.fromValue(object.dimValue)).unsigned = false;
+ else if (typeof object.dimValue === "string")
+ message.dimValue = parseInt(object.dimValue, 10);
+ else if (typeof object.dimValue === "number")
+ message.dimValue = object.dimValue;
+ else if (typeof object.dimValue === "object")
+ message.dimValue = new $util.LongBits(object.dimValue.low >>> 0, object.dimValue.high >>> 0).toNumber();
+ if (object.dimParam != null)
+ message.dimParam = String(object.dimParam);
+ if (object.denotation != null)
+ message.denotation = String(object.denotation);
+ return message;
+ };
+
+ /**
+ * Creates a plain object from a Dimension message. Also converts values to other types if specified.
+ * @function toObject
+ * @memberof onnx.TensorShapeProto.Dimension
+ * @static
+ * @param {onnx.TensorShapeProto.Dimension} message Dimension
+ * @param {$protobuf.IConversionOptions} [options] Conversion options
+ * @returns {Object.<string,*>} Plain object
+ */
+ Dimension.toObject = function toObject(message, options) {
+ if (!options)
+ options = {};
+ var object = {};
+ if (options.defaults)
+ object.denotation = "";
+ if (message.dimValue != null && message.hasOwnProperty("dimValue")) {
+ if (typeof message.dimValue === "number")
+ object.dimValue = options.longs === String ? String(message.dimValue) : message.dimValue;
+ else
+ object.dimValue = options.longs === String ? $util.Long.prototype.toString.call(message.dimValue) : options.longs === Number ? new $util.LongBits(message.dimValue.low >>> 0, message.dimValue.high >>> 0).toNumber() : message.dimValue;
+ if (options.oneofs)
+ object.value = "dimValue";
+ }
+ if (message.dimParam != null && message.hasOwnProperty("dimParam")) {
+ object.dimParam = message.dimParam;
+ if (options.oneofs)
+ object.value = "dimParam";
+ }
+ if (message.denotation != null && message.hasOwnProperty("denotation"))
+ object.denotation = message.denotation;
+ return object;
+ };
+
+ /**
+ * Converts this Dimension to JSON.
+ * @function toJSON
+ * @memberof onnx.TensorShapeProto.Dimension
+ * @instance
+ * @returns {Object.<string,*>} JSON object
+ */
+ Dimension.prototype.toJSON = function toJSON() {
+ return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
+ };
+
+ return Dimension;
+ })();
+
+ return TensorShapeProto;
+ })();
+
+ onnx.TypeProto = (function() {
+
+ /**
+ * Properties of a TypeProto.
+ * @memberof onnx
+ * @interface ITypeProto
+ * @property {onnx.TypeProto.ITensor|null} [tensorType] TypeProto tensorType
+ * @property {string|null} [denotation] TypeProto denotation
+ */
+
+ /**
+ * Constructs a new TypeProto.
+ * @memberof onnx
+ * @classdesc Represents a TypeProto.
+ * @implements ITypeProto
+ * @constructor
+ * @param {onnx.ITypeProto=} [properties] Properties to set
+ */
+ function TypeProto(properties) {
+ if (properties)
+ for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
+ if (properties[keys[i]] != null)
+ this[keys[i]] = properties[keys[i]];
+ }
+
+ /**
+ * TypeProto tensorType.
+ * @member {onnx.TypeProto.ITensor|null|undefined} tensorType
+ * @memberof onnx.TypeProto
+ * @instance
+ */
+ TypeProto.prototype.tensorType = null;
+
+ /**
+ * TypeProto denotation.
+ * @member {string} denotation
+ * @memberof onnx.TypeProto
+ * @instance
+ */
+ TypeProto.prototype.denotation = "";
+
+ // OneOf field names bound to virtual getters and setters
+ var $oneOfFields;
+
+ /**
+ * TypeProto value.
+ * @member {"tensorType"|undefined} value
+ * @memberof onnx.TypeProto
+ * @instance
+ */
+ Object.defineProperty(TypeProto.prototype, "value", {
+ get: $util.oneOfGetter($oneOfFields = ["tensorType"]),
+ set: $util.oneOfSetter($oneOfFields)
+ });
+
+ /**
+ * Creates a new TypeProto instance using the specified properties.
+ * @function create
+ * @memberof onnx.TypeProto
+ * @static
+ * @param {onnx.ITypeProto=} [properties] Properties to set
+ * @returns {onnx.TypeProto} TypeProto instance
+ */
+ TypeProto.create = function create(properties) {
+ return new TypeProto(properties);
+ };
+
+ /**
+ * Encodes the specified TypeProto message. Does not implicitly {@link onnx.TypeProto.verify|verify} messages.
+ * @function encode
+ * @memberof onnx.TypeProto
+ * @static
+ * @param {onnx.ITypeProto} message TypeProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ TypeProto.encode = function encode(message, writer) {
+ if (!writer)
+ writer = $Writer.create();
+ if (message.tensorType != null && message.hasOwnProperty("tensorType"))
+ $root.onnx.TypeProto.Tensor.encode(message.tensorType, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();
+ if (message.denotation != null && message.hasOwnProperty("denotation"))
+ writer.uint32(/* id 6, wireType 2 =*/50).string(message.denotation);
+ return writer;
+ };
+
+ /**
+ * Encodes the specified TypeProto message, length delimited. Does not implicitly {@link onnx.TypeProto.verify|verify} messages.
+ * @function encodeDelimited
+ * @memberof onnx.TypeProto
+ * @static
+ * @param {onnx.ITypeProto} message TypeProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ TypeProto.encodeDelimited = function encodeDelimited(message, writer) {
+ return this.encode(message, writer).ldelim();
+ };
+
+ /**
+ * Decodes a TypeProto message from the specified reader or buffer.
+ * @function decode
+ * @memberof onnx.TypeProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @param {number} [length] Message length if known beforehand
+ * @returns {onnx.TypeProto} TypeProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ TypeProto.decode = function decode(reader, length) {
+ if (!(reader instanceof $Reader))
+ reader = $Reader.create(reader);
+ var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.TypeProto();
+ while (reader.pos < end) {
+ var tag = reader.uint32();
+ switch (tag >>> 3) {
+ case 1:
+ message.tensorType = $root.onnx.TypeProto.Tensor.decode(reader, reader.uint32());
+ break;
+ case 6:
+ message.denotation = reader.string();
+ break;
+ default:
+ reader.skipType(tag & 7);
+ break;
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Decodes a TypeProto message from the specified reader or buffer, length delimited.
+ * @function decodeDelimited
+ * @memberof onnx.TypeProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @returns {onnx.TypeProto} TypeProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ TypeProto.decodeDelimited = function decodeDelimited(reader) {
+ if (!(reader instanceof $Reader))
+ reader = new $Reader(reader);
+ return this.decode(reader, reader.uint32());
+ };
+
+ /**
+ * Verifies a TypeProto message.
+ * @function verify
+ * @memberof onnx.TypeProto
+ * @static
+ * @param {Object.<string,*>} message Plain object to verify
+ * @returns {string|null} `null` if valid, otherwise the reason why it is not
+ */
+ TypeProto.verify = function verify(message) {
+ if (typeof message !== "object" || message === null)
+ return "object expected";
+ var properties = {};
+ if (message.tensorType != null && message.hasOwnProperty("tensorType")) {
+ properties.value = 1;
+ {
+ var error = $root.onnx.TypeProto.Tensor.verify(message.tensorType);
+ if (error)
+ return "tensorType." + error;
+ }
+ }
+ if (message.denotation != null && message.hasOwnProperty("denotation"))
+ if (!$util.isString(message.denotation))
+ return "denotation: string expected";
+ return null;
+ };
+
+ /**
+ * Creates a TypeProto message from a plain object. Also converts values to their respective internal types.
+ * @function fromObject
+ * @memberof onnx.TypeProto
+ * @static
+ * @param {Object.<string,*>} object Plain object
+ * @returns {onnx.TypeProto} TypeProto
+ */
+ TypeProto.fromObject = function fromObject(object) {
+ if (object instanceof $root.onnx.TypeProto)
+ return object;
+ var message = new $root.onnx.TypeProto();
+ if (object.tensorType != null) {
+ if (typeof object.tensorType !== "object")
+ throw TypeError(".onnx.TypeProto.tensorType: object expected");
+ message.tensorType = $root.onnx.TypeProto.Tensor.fromObject(object.tensorType);
+ }
+ if (object.denotation != null)
+ message.denotation = String(object.denotation);
+ return message;
+ };
+
+ /**
+ * Creates a plain object from a TypeProto message. Also converts values to other types if specified.
+ * @function toObject
+ * @memberof onnx.TypeProto
+ * @static
+ * @param {onnx.TypeProto} message TypeProto
+ * @param {$protobuf.IConversionOptions} [options] Conversion options
+ * @returns {Object.<string,*>} Plain object
+ */
+ TypeProto.toObject = function toObject(message, options) {
+ if (!options)
+ options = {};
+ var object = {};
+ if (options.defaults)
+ object.denotation = "";
+ if (message.tensorType != null && message.hasOwnProperty("tensorType")) {
+ object.tensorType = $root.onnx.TypeProto.Tensor.toObject(message.tensorType, options);
+ if (options.oneofs)
+ object.value = "tensorType";
+ }
+ if (message.denotation != null && message.hasOwnProperty("denotation"))
+ object.denotation = message.denotation;
+ return object;
+ };
+
+ /**
+ * Converts this TypeProto to JSON.
+ * @function toJSON
+ * @memberof onnx.TypeProto
+ * @instance
+ * @returns {Object.<string,*>} JSON object
+ */
+ TypeProto.prototype.toJSON = function toJSON() {
+ return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
+ };
+
+ TypeProto.Tensor = (function() {
+
+ /**
+ * Properties of a Tensor.
+ * @memberof onnx.TypeProto
+ * @interface ITensor
+ * @property {number|null} [elemType] Tensor elemType
+ * @property {onnx.ITensorShapeProto|null} [shape] Tensor shape
+ */
+
+ /**
+ * Constructs a new Tensor.
+ * @memberof onnx.TypeProto
+ * @classdesc Represents a Tensor.
+ * @implements ITensor
+ * @constructor
+ * @param {onnx.TypeProto.ITensor=} [properties] Properties to set
+ */
+ function Tensor(properties) {
+ if (properties)
+ for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
+ if (properties[keys[i]] != null)
+ this[keys[i]] = properties[keys[i]];
+ }
+
+ /**
+ * Tensor elemType.
+ * @member {number} elemType
+ * @memberof onnx.TypeProto.Tensor
+ * @instance
+ */
+ Tensor.prototype.elemType = 0;
+
+ /**
+ * Tensor shape.
+ * @member {onnx.ITensorShapeProto|null|undefined} shape
+ * @memberof onnx.TypeProto.Tensor
+ * @instance
+ */
+ Tensor.prototype.shape = null;
+
+ /**
+ * Creates a new Tensor instance using the specified properties.
+ * @function create
+ * @memberof onnx.TypeProto.Tensor
+ * @static
+ * @param {onnx.TypeProto.ITensor=} [properties] Properties to set
+ * @returns {onnx.TypeProto.Tensor} Tensor instance
+ */
+ Tensor.create = function create(properties) {
+ return new Tensor(properties);
+ };
+
+ /**
+ * Encodes the specified Tensor message. Does not implicitly {@link onnx.TypeProto.Tensor.verify|verify} messages.
+ * @function encode
+ * @memberof onnx.TypeProto.Tensor
+ * @static
+ * @param {onnx.TypeProto.ITensor} message Tensor message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ Tensor.encode = function encode(message, writer) {
+ if (!writer)
+ writer = $Writer.create();
+ if (message.elemType != null && message.hasOwnProperty("elemType"))
+ writer.uint32(/* id 1, wireType 0 =*/8).int32(message.elemType);
+ if (message.shape != null && message.hasOwnProperty("shape"))
+ $root.onnx.TensorShapeProto.encode(message.shape, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();
+ return writer;
+ };
+
+ /**
+ * Encodes the specified Tensor message, length delimited. Does not implicitly {@link onnx.TypeProto.Tensor.verify|verify} messages.
+ * @function encodeDelimited
+ * @memberof onnx.TypeProto.Tensor
+ * @static
+ * @param {onnx.TypeProto.ITensor} message Tensor message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ Tensor.encodeDelimited = function encodeDelimited(message, writer) {
+ return this.encode(message, writer).ldelim();
+ };
+
+ /**
+ * Decodes a Tensor message from the specified reader or buffer.
+ * @function decode
+ * @memberof onnx.TypeProto.Tensor
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @param {number} [length] Message length if known beforehand
+ * @returns {onnx.TypeProto.Tensor} Tensor
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ Tensor.decode = function decode(reader, length) {
+ if (!(reader instanceof $Reader))
+ reader = $Reader.create(reader);
+ var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.TypeProto.Tensor();
+ while (reader.pos < end) {
+ var tag = reader.uint32();
+ switch (tag >>> 3) {
+ case 1:
+ message.elemType = reader.int32();
+ break;
+ case 2:
+ message.shape = $root.onnx.TensorShapeProto.decode(reader, reader.uint32());
+ break;
+ default:
+ reader.skipType(tag & 7);
+ break;
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Decodes a Tensor message from the specified reader or buffer, length delimited.
+ * @function decodeDelimited
+ * @memberof onnx.TypeProto.Tensor
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @returns {onnx.TypeProto.Tensor} Tensor
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ Tensor.decodeDelimited = function decodeDelimited(reader) {
+ if (!(reader instanceof $Reader))
+ reader = new $Reader(reader);
+ return this.decode(reader, reader.uint32());
+ };
+
+ /**
+ * Verifies a Tensor message.
+ * @function verify
+ * @memberof onnx.TypeProto.Tensor
+ * @static
+ * @param {Object.<string,*>} message Plain object to verify
+ * @returns {string|null} `null` if valid, otherwise the reason why it is not
+ */
+ Tensor.verify = function verify(message) {
+ if (typeof message !== "object" || message === null)
+ return "object expected";
+ if (message.elemType != null && message.hasOwnProperty("elemType"))
+ if (!$util.isInteger(message.elemType))
+ return "elemType: integer expected";
+ if (message.shape != null && message.hasOwnProperty("shape")) {
+ var error = $root.onnx.TensorShapeProto.verify(message.shape);
+ if (error)
+ return "shape." + error;
+ }
+ return null;
+ };
+
+ /**
+ * Creates a Tensor message from a plain object. Also converts values to their respective internal types.
+ * @function fromObject
+ * @memberof onnx.TypeProto.Tensor
+ * @static
+ * @param {Object.<string,*>} object Plain object
+ * @returns {onnx.TypeProto.Tensor} Tensor
+ */
+ Tensor.fromObject = function fromObject(object) {
+ if (object instanceof $root.onnx.TypeProto.Tensor)
+ return object;
+ var message = new $root.onnx.TypeProto.Tensor();
+ if (object.elemType != null)
+ message.elemType = object.elemType | 0;
+ if (object.shape != null) {
+ if (typeof object.shape !== "object")
+ throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");
+ message.shape = $root.onnx.TensorShapeProto.fromObject(object.shape);
+ }
+ return message;
+ };
+
+ /**
+ * Creates a plain object from a Tensor message. Also converts values to other types if specified.
+ * @function toObject
+ * @memberof onnx.TypeProto.Tensor
+ * @static
+ * @param {onnx.TypeProto.Tensor} message Tensor
+ * @param {$protobuf.IConversionOptions} [options] Conversion options
+ * @returns {Object.<string,*>} Plain object
+ */
+ Tensor.toObject = function toObject(message, options) {
+ if (!options)
+ options = {};
+ var object = {};
+ if (options.defaults) {
+ object.elemType = 0;
+ object.shape = null;
+ }
+ if (message.elemType != null && message.hasOwnProperty("elemType"))
+ object.elemType = message.elemType;
+ if (message.shape != null && message.hasOwnProperty("shape"))
+ object.shape = $root.onnx.TensorShapeProto.toObject(message.shape, options);
+ return object;
+ };
+
+ /**
+ * Converts this Tensor to JSON.
+ * @function toJSON
+ * @memberof onnx.TypeProto.Tensor
+ * @instance
+ * @returns {Object.<string,*>} JSON object
+ */
+ Tensor.prototype.toJSON = function toJSON() {
+ return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
+ };
+
+ return Tensor;
+ })();
+
+ return TypeProto;
+ })();
+
+ onnx.OperatorSetIdProto = (function() {
+
+ /**
+ * Properties of an OperatorSetIdProto.
+ * @memberof onnx
+ * @interface IOperatorSetIdProto
+ * @property {string|null} [domain] OperatorSetIdProto domain
+ * @property {number|Long|null} [version] OperatorSetIdProto version
+ */
+
+ /**
+ * Constructs a new OperatorSetIdProto.
+ * @memberof onnx
+ * @classdesc Represents an OperatorSetIdProto.
+ * @implements IOperatorSetIdProto
+ * @constructor
+ * @param {onnx.IOperatorSetIdProto=} [properties] Properties to set
+ */
+ function OperatorSetIdProto(properties) {
+ if (properties)
+ for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
+ if (properties[keys[i]] != null)
+ this[keys[i]] = properties[keys[i]];
+ }
+
+ /**
+ * OperatorSetIdProto domain.
+ * @member {string} domain
+ * @memberof onnx.OperatorSetIdProto
+ * @instance
+ */
+ OperatorSetIdProto.prototype.domain = "";
+
+ /**
+ * OperatorSetIdProto version.
+ * @member {number|Long} version
+ * @memberof onnx.OperatorSetIdProto
+ * @instance
+ */
+ OperatorSetIdProto.prototype.version = $util.Long ? $util.Long.fromBits(0,0,false) : 0;
+
+ /**
+ * Creates a new OperatorSetIdProto instance using the specified properties.
+ * @function create
+ * @memberof onnx.OperatorSetIdProto
+ * @static
+ * @param {onnx.IOperatorSetIdProto=} [properties] Properties to set
+ * @returns {onnx.OperatorSetIdProto} OperatorSetIdProto instance
+ */
+ OperatorSetIdProto.create = function create(properties) {
+ return new OperatorSetIdProto(properties);
+ };
+
+ /**
+ * Encodes the specified OperatorSetIdProto message. Does not implicitly {@link onnx.OperatorSetIdProto.verify|verify} messages.
+ * @function encode
+ * @memberof onnx.OperatorSetIdProto
+ * @static
+ * @param {onnx.IOperatorSetIdProto} message OperatorSetIdProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ OperatorSetIdProto.encode = function encode(message, writer) {
+ if (!writer)
+ writer = $Writer.create();
+ if (message.domain != null && message.hasOwnProperty("domain"))
+ writer.uint32(/* id 1, wireType 2 =*/10).string(message.domain);
+ if (message.version != null && message.hasOwnProperty("version"))
+ writer.uint32(/* id 2, wireType 0 =*/16).int64(message.version);
+ return writer;
+ };
+
+ /**
+ * Encodes the specified OperatorSetIdProto message, length delimited. Does not implicitly {@link onnx.OperatorSetIdProto.verify|verify} messages.
+ * @function encodeDelimited
+ * @memberof onnx.OperatorSetIdProto
+ * @static
+ * @param {onnx.IOperatorSetIdProto} message OperatorSetIdProto message or plain object to encode
+ * @param {$protobuf.Writer} [writer] Writer to encode to
+ * @returns {$protobuf.Writer} Writer
+ */
+ OperatorSetIdProto.encodeDelimited = function encodeDelimited(message, writer) {
+ return this.encode(message, writer).ldelim();
+ };
+
+ /**
+ * Decodes an OperatorSetIdProto message from the specified reader or buffer.
+ * @function decode
+ * @memberof onnx.OperatorSetIdProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @param {number} [length] Message length if known beforehand
+ * @returns {onnx.OperatorSetIdProto} OperatorSetIdProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ OperatorSetIdProto.decode = function decode(reader, length) {
+ if (!(reader instanceof $Reader))
+ reader = $Reader.create(reader);
+ var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.OperatorSetIdProto();
+ while (reader.pos < end) {
+ var tag = reader.uint32();
+ switch (tag >>> 3) {
+ case 1:
+ message.domain = reader.string();
+ break;
+ case 2:
+ message.version = reader.int64();
+ break;
+ default:
+ reader.skipType(tag & 7);
+ break;
+ }
+ }
+ return message;
+ };
+
+ /**
+ * Decodes an OperatorSetIdProto message from the specified reader or buffer, length delimited.
+ * @function decodeDelimited
+ * @memberof onnx.OperatorSetIdProto
+ * @static
+ * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
+ * @returns {onnx.OperatorSetIdProto} OperatorSetIdProto
+ * @throws {Error} If the payload is not a reader or valid buffer
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
+ */
+ OperatorSetIdProto.decodeDelimited = function decodeDelimited(reader) {
+ if (!(reader instanceof $Reader))
+ reader = new $Reader(reader);
+ return this.decode(reader, reader.uint32());
+ };
+
+ /**
+ * Verifies an OperatorSetIdProto message.
+ * @function verify
+ * @memberof onnx.OperatorSetIdProto
+ * @static
+ * @param {Object.<string,*>} message Plain object to verify
+ * @returns {string|null} `null` if valid, otherwise the reason why it is not
+ */
+ OperatorSetIdProto.verify = function verify(message) {
+ if (typeof message !== "object" || message === null)
+ return "object expected";
+ if (message.domain != null && message.hasOwnProperty("domain"))
+ if (!$util.isString(message.domain))
+ return "domain: string expected";
+ if (message.version != null && message.hasOwnProperty("version"))
+ if (!$util.isInteger(message.version) && !(message.version && $util.isInteger(message.version.low) && $util.isInteger(message.version.high)))
+ return "version: integer|Long expected";
+ return null;
+ };
+
+ /**
+ * Creates an OperatorSetIdProto message from a plain object. Also converts values to their respective internal types.
+ * @function fromObject
+ * @memberof onnx.OperatorSetIdProto
+ * @static
+ * @param {Object.<string,*>} object Plain object
+ * @returns {onnx.OperatorSetIdProto} OperatorSetIdProto
+ */
+ OperatorSetIdProto.fromObject = function fromObject(object) {
+ if (object instanceof $root.onnx.OperatorSetIdProto)
+ return object;
+ var message = new $root.onnx.OperatorSetIdProto();
+ if (object.domain != null)
+ message.domain = String(object.domain);
+ if (object.version != null)
+ if ($util.Long)
+ (message.version = $util.Long.fromValue(object.version)).unsigned = false;
+ else if (typeof object.version === "string")
+ message.version = parseInt(object.version, 10);
+ else if (typeof object.version === "number")
+ message.version = object.version;
+ else if (typeof object.version === "object")
+ message.version = new $util.LongBits(object.version.low >>> 0, object.version.high >>> 0).toNumber();
+ return message;
+ };
+
+ /**
+ * Creates a plain object from an OperatorSetIdProto message. Also converts values to other types if specified.
+ * @function toObject
+ * @memberof onnx.OperatorSetIdProto
+ * @static
+ * @param {onnx.OperatorSetIdProto} message OperatorSetIdProto
+ * @param {$protobuf.IConversionOptions} [options] Conversion options
+ * @returns {Object.<string,*>} Plain object
+ */
+ OperatorSetIdProto.toObject = function toObject(message, options) {
+ if (!options)
+ options = {};
+ var object = {};
+ if (options.defaults) {
+ object.domain = "";
+ if ($util.Long) {
+ var long = new $util.Long(0, 0, false);
+ object.version = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
+ } else
+ object.version = options.longs === String ? "0" : 0;
+ }
+ if (message.domain != null && message.hasOwnProperty("domain"))
+ object.domain = message.domain;
+ if (message.version != null && message.hasOwnProperty("version"))
+ if (typeof message.version === "number")
+ object.version = options.longs === String ? String(message.version) : message.version;
+ else
+ object.version = options.longs === String ? $util.Long.prototype.toString.call(message.version) : options.longs === Number ? new $util.LongBits(message.version.low >>> 0, message.version.high >>> 0).toNumber() : message.version;
+ return object;
+ };
+
+ /**
+ * Converts this OperatorSetIdProto to JSON.
+ * @function toJSON
+ * @memberof onnx.OperatorSetIdProto
+ * @instance
+ * @returns {Object.<string,*>} JSON object
+ */
+ OperatorSetIdProto.prototype.toJSON = function toJSON() {
+ return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
+ };
+
+ return OperatorSetIdProto;
+ })();
+
+ return onnx;
+})();
+
+module.exports = $root;
+
+
+/***/ }),
+
+/***/ "./node_modules/protobufjs/minimal.js":
+/*!********************************************!*\
+ !*** ./node_modules/protobufjs/minimal.js ***!
+ \********************************************/
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+// minimal library entry point.
+
+
+module.exports = __webpack_require__(/*! ./src/index-minimal */ "./node_modules/protobufjs/src/index-minimal.js");
+
+
+/***/ }),
+
+/***/ "./node_modules/protobufjs/src/index-minimal.js":
+/*!******************************************************!*\
+ !*** ./node_modules/protobufjs/src/index-minimal.js ***!
+ \******************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+var protobuf = exports;
+
+/**
+ * Build type, one of `"full"`, `"light"` or `"minimal"`.
+ * @name build
+ * @type {string}
+ * @const
+ */
+protobuf.build = "minimal";
+
+// Serialization
+protobuf.Writer = __webpack_require__(/*! ./writer */ "./node_modules/protobufjs/src/writer.js");
+protobuf.BufferWriter = __webpack_require__(/*! ./writer_buffer */ "./node_modules/protobufjs/src/writer_buffer.js");
+protobuf.Reader = __webpack_require__(/*! ./reader */ "./node_modules/protobufjs/src/reader.js");
+protobuf.BufferReader = __webpack_require__(/*! ./reader_buffer */ "./node_modules/protobufjs/src/reader_buffer.js");
+
+// Utility
+protobuf.util = __webpack_require__(/*! ./util/minimal */ "./node_modules/protobufjs/src/util/minimal.js");
+protobuf.rpc = __webpack_require__(/*! ./rpc */ "./node_modules/protobufjs/src/rpc.js");
+protobuf.roots = __webpack_require__(/*! ./roots */ "./node_modules/protobufjs/src/roots.js");
+protobuf.configure = configure;
+
+/* istanbul ignore next */
+/**
+ * Reconfigures the library according to the environment.
+ * @returns {undefined}
+ */
+function configure() {
+ protobuf.util._configure();
+ protobuf.Writer._configure(protobuf.BufferWriter);
+ protobuf.Reader._configure(protobuf.BufferReader);
+}
+
+// Set up buffer utility according to the environment
+configure();
+
+
+/***/ }),
+
+/***/ "./node_modules/protobufjs/src/reader.js":
+/*!***********************************************!*\
+ !*** ./node_modules/protobufjs/src/reader.js ***!
+ \***********************************************/
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+module.exports = Reader;
+
+var util = __webpack_require__(/*! ./util/minimal */ "./node_modules/protobufjs/src/util/minimal.js");
+
+var BufferReader; // cyclic
+
+var LongBits = util.LongBits,
+ utf8 = util.utf8;
+
+/* istanbul ignore next */
+function indexOutOfRange(reader, writeLength) {
+ return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len);
+}
+
+/**
+ * Constructs a new reader instance using the specified buffer.
+ * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.
+ * @constructor
+ * @param {Uint8Array} buffer Buffer to read from
+ */
+function Reader(buffer) {
+
+ /**
+ * Read buffer.
+ * @type {Uint8Array}
+ */
+ this.buf = buffer;
+
+ /**
+ * Read buffer position.
+ * @type {number}
+ */
+ this.pos = 0;
+
+ /**
+ * Read buffer length.
+ * @type {number}
+ */
+ this.len = buffer.length;
+}
+
+var create_array = typeof Uint8Array !== "undefined"
+ ? function create_typed_array(buffer) {
+ if (buffer instanceof Uint8Array || Array.isArray(buffer))
+ return new Reader(buffer);
+ throw Error("illegal buffer");
+ }
+ /* istanbul ignore next */
+ : function create_array(buffer) {
+ if (Array.isArray(buffer))
+ return new Reader(buffer);
+ throw Error("illegal buffer");
+ };
+
+var create = function create() {
+ return util.Buffer
+ ? function create_buffer_setup(buffer) {
+ return (Reader.create = function create_buffer(buffer) {
+ return util.Buffer.isBuffer(buffer)
+ ? new BufferReader(buffer)
+ /* istanbul ignore next */
+ : create_array(buffer);
+ })(buffer);
+ }
+ /* istanbul ignore next */
+ : create_array;
+};
+
+/**
+ * Creates a new reader using the specified buffer.
+ * @function
+ * @param {Uint8Array|Buffer} buffer Buffer to read from
+ * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}
+ * @throws {Error} If `buffer` is not a valid buffer
+ */
+Reader.create = create();
+
+Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;
+
+/**
+ * Reads a varint as an unsigned 32 bit value.
+ * @function
+ * @returns {number} Value read
+ */
+Reader.prototype.uint32 = (function read_uint32_setup() {
+ var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)
+ return function read_uint32() {
+ value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;
+ value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;
+ value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;
+ value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;
+ value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;
+
+ /* istanbul ignore if */
+ if ((this.pos += 5) > this.len) {
+ this.pos = this.len;
+ throw indexOutOfRange(this, 10);
+ }
+ return value;
+ };
+})();
+
+/**
+ * Reads a varint as a signed 32 bit value.
+ * @returns {number} Value read
+ */
+Reader.prototype.int32 = function read_int32() {
+ return this.uint32() | 0;
+};
+
+/**
+ * Reads a zig-zag encoded varint as a signed 32 bit value.
+ * @returns {number} Value read
+ */
+Reader.prototype.sint32 = function read_sint32() {
+ var value = this.uint32();
+ return value >>> 1 ^ -(value & 1) | 0;
+};
+
+/* eslint-disable no-invalid-this */
+
+function readLongVarint() {
+ // tends to deopt with local vars for octet etc.
+ var bits = new LongBits(0, 0);
+ var i = 0;
+ if (this.len - this.pos > 4) { // fast route (lo)
+ for (; i < 4; ++i) {
+ // 1st..4th
+ bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
+ if (this.buf[this.pos++] < 128)
+ return bits;
+ }
+ // 5th
+ bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;
+ bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;
+ if (this.buf[this.pos++] < 128)
+ return bits;
+ i = 0;
+ } else {
+ for (; i < 3; ++i) {
+ /* istanbul ignore if */
+ if (this.pos >= this.len)
+ throw indexOutOfRange(this);
+ // 1st..3th
+ bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
+ if (this.buf[this.pos++] < 128)
+ return bits;
+ }
+ // 4th
+ bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;
+ return bits;
+ }
+ if (this.len - this.pos > 4) { // fast route (hi)
+ for (; i < 5; ++i) {
+ // 6th..10th
+ bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
+ if (this.buf[this.pos++] < 128)
+ return bits;
+ }
+ } else {
+ for (; i < 5; ++i) {
+ /* istanbul ignore if */
+ if (this.pos >= this.len)
+ throw indexOutOfRange(this);
+ // 6th..10th
+ bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
+ if (this.buf[this.pos++] < 128)
+ return bits;
+ }
+ }
+ /* istanbul ignore next */
+ throw Error("invalid varint encoding");
+}
+
+/* eslint-enable no-invalid-this */
+
+/**
+ * Reads a varint as a signed 64 bit value.
+ * @name Reader#int64
+ * @function
+ * @returns {Long} Value read
+ */
+
+/**
+ * Reads a varint as an unsigned 64 bit value.
+ * @name Reader#uint64
+ * @function
+ * @returns {Long} Value read
+ */
+
+/**
+ * Reads a zig-zag encoded varint as a signed 64 bit value.
+ * @name Reader#sint64
+ * @function
+ * @returns {Long} Value read
+ */
+
+/**
+ * Reads a varint as a boolean.
+ * @returns {boolean} Value read
+ */
+Reader.prototype.bool = function read_bool() {
+ return this.uint32() !== 0;
+};
+
+function readFixed32_end(buf, end) { // note that this uses `end`, not `pos`
+ return (buf[end - 4]
+ | buf[end - 3] << 8
+ | buf[end - 2] << 16
+ | buf[end - 1] << 24) >>> 0;
+}
+
+/**
+ * Reads fixed 32 bits as an unsigned 32 bit integer.
+ * @returns {number} Value read
+ */
+Reader.prototype.fixed32 = function read_fixed32() {
+
+ /* istanbul ignore if */
+ if (this.pos + 4 > this.len)
+ throw indexOutOfRange(this, 4);
+
+ return readFixed32_end(this.buf, this.pos += 4);
+};
+
+/**
+ * Reads fixed 32 bits as a signed 32 bit integer.
+ * @returns {number} Value read
+ */
+Reader.prototype.sfixed32 = function read_sfixed32() {
+
+ /* istanbul ignore if */
+ if (this.pos + 4 > this.len)
+ throw indexOutOfRange(this, 4);
+
+ return readFixed32_end(this.buf, this.pos += 4) | 0;
+};
+
+/* eslint-disable no-invalid-this */
+
+function readFixed64(/* this: Reader */) {
+
+ /* istanbul ignore if */
+ if (this.pos + 8 > this.len)
+ throw indexOutOfRange(this, 8);
+
+ return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));
+}
+
+/* eslint-enable no-invalid-this */
+
+/**
+ * Reads fixed 64 bits.
+ * @name Reader#fixed64
+ * @function
+ * @returns {Long} Value read
+ */
+
+/**
+ * Reads zig-zag encoded fixed 64 bits.
+ * @name Reader#sfixed64
+ * @function
+ * @returns {Long} Value read
+ */
+
+/**
+ * Reads a float (32 bit) as a number.
+ * @function
+ * @returns {number} Value read
+ */
+Reader.prototype.float = function read_float() {
+
+ /* istanbul ignore if */
+ if (this.pos + 4 > this.len)
+ throw indexOutOfRange(this, 4);
+
+ var value = util.float.readFloatLE(this.buf, this.pos);
+ this.pos += 4;
+ return value;
+};
+
+/**
+ * Reads a double (64 bit float) as a number.
+ * @function
+ * @returns {number} Value read
+ */
+Reader.prototype.double = function read_double() {
+
+ /* istanbul ignore if */
+ if (this.pos + 8 > this.len)
+ throw indexOutOfRange(this, 4);
+
+ var value = util.float.readDoubleLE(this.buf, this.pos);
+ this.pos += 8;
+ return value;
+};
+
+/**
+ * Reads a sequence of bytes preceeded by its length as a varint.
+ * @returns {Uint8Array} Value read
+ */
+Reader.prototype.bytes = function read_bytes() {
+ var length = this.uint32(),
+ start = this.pos,
+ end = this.pos + length;
+
+ /* istanbul ignore if */
+ if (end > this.len)
+ throw indexOutOfRange(this, length);
+
+ this.pos += length;
+ if (Array.isArray(this.buf)) // plain array
+ return this.buf.slice(start, end);
+ return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1
+ ? new this.buf.constructor(0)
+ : this._slice.call(this.buf, start, end);
+};
+
+/**
+ * Reads a string preceeded by its byte length as a varint.
+ * @returns {string} Value read
+ */
+Reader.prototype.string = function read_string() {
+ var bytes = this.bytes();
+ return utf8.read(bytes, 0, bytes.length);
+};
+
+/**
+ * Skips the specified number of bytes if specified, otherwise skips a varint.
+ * @param {number} [length] Length if known, otherwise a varint is assumed
+ * @returns {Reader} `this`
+ */
+Reader.prototype.skip = function skip(length) {
+ if (typeof length === "number") {
+ /* istanbul ignore if */
+ if (this.pos + length > this.len)
+ throw indexOutOfRange(this, length);
+ this.pos += length;
+ } else {
+ do {
+ /* istanbul ignore if */
+ if (this.pos >= this.len)
+ throw indexOutOfRange(this);
+ } while (this.buf[this.pos++] & 128);
+ }
+ return this;
+};
+
+/**
+ * Skips the next element of the specified wire type.
+ * @param {number} wireType Wire type received
+ * @returns {Reader} `this`
+ */
+Reader.prototype.skipType = function(wireType) {
+ switch (wireType) {
+ case 0:
+ this.skip();
+ break;
+ case 1:
+ this.skip(8);
+ break;
+ case 2:
+ this.skip(this.uint32());
+ break;
+ case 3:
+ while ((wireType = this.uint32() & 7) !== 4) {
+ this.skipType(wireType);
+ }
+ break;
+ case 5:
+ this.skip(4);
+ break;
+
+ /* istanbul ignore next */
+ default:
+ throw Error("invalid wire type " + wireType + " at offset " + this.pos);
+ }
+ return this;
+};
+
+Reader._configure = function(BufferReader_) {
+ BufferReader = BufferReader_;
+ Reader.create = create();
+ BufferReader._configure();
+
+ var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber";
+ util.merge(Reader.prototype, {
+
+ int64: function read_int64() {
+ return readLongVarint.call(this)[fn](false);
+ },
+
+ uint64: function read_uint64() {
+ return readLongVarint.call(this)[fn](true);
+ },
+
+ sint64: function read_sint64() {
+ return readLongVarint.call(this).zzDecode()[fn](false);
+ },
+
+ fixed64: function read_fixed64() {
+ return readFixed64.call(this)[fn](true);
+ },
+
+ sfixed64: function read_sfixed64() {
+ return readFixed64.call(this)[fn](false);
+ }
+
+ });
+};
+
+
+/***/ }),
+
+/***/ "./node_modules/protobufjs/src/reader_buffer.js":
+/*!******************************************************!*\
+ !*** ./node_modules/protobufjs/src/reader_buffer.js ***!
+ \******************************************************/
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+module.exports = BufferReader;
+
+// extends Reader
+var Reader = __webpack_require__(/*! ./reader */ "./node_modules/protobufjs/src/reader.js");
+(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;
+
+var util = __webpack_require__(/*! ./util/minimal */ "./node_modules/protobufjs/src/util/minimal.js");
+
+/**
+ * Constructs a new buffer reader instance.
+ * @classdesc Wire format reader using node buffers.
+ * @extends Reader
+ * @constructor
+ * @param {Buffer} buffer Buffer to read from
+ */
+function BufferReader(buffer) {
+ Reader.call(this, buffer);
+
+ /**
+ * Read buffer.
+ * @name BufferReader#buf
+ * @type {Buffer}
+ */
+}
+
+BufferReader._configure = function () {
+ /* istanbul ignore else */
+ if (util.Buffer)
+ BufferReader.prototype._slice = util.Buffer.prototype.slice;
+};
+
+
+/**
+ * @override
+ */
+BufferReader.prototype.string = function read_string_buffer() {
+ var len = this.uint32(); // modifies pos
+ return this.buf.utf8Slice
+ ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))
+ : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len));
+};
+
+/**
+ * Reads a sequence of bytes preceeded by its length as a varint.
+ * @name BufferReader#bytes
+ * @function
+ * @returns {Buffer} Value read
+ */
+
+BufferReader._configure();
+
+
+/***/ }),
+
+/***/ "./node_modules/protobufjs/src/roots.js":
+/*!**********************************************!*\
+ !*** ./node_modules/protobufjs/src/roots.js ***!
+ \**********************************************/
+/***/ ((module) => {
+
+"use strict";
+
+module.exports = {};
+
+/**
+ * Named roots.
+ * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).
+ * Can also be used manually to make roots available accross modules.
+ * @name roots
+ * @type {Object.<string,Root>}
+ * @example
+ * // pbjs -r myroot -o compiled.js ...
+ *
+ * // in another module:
+ * require("./compiled.js");
+ *
+ * // in any subsequent module:
+ * var root = protobuf.roots["myroot"];
+ */
+
+
+/***/ }),
+
+/***/ "./node_modules/protobufjs/src/rpc.js":
+/*!********************************************!*\
+ !*** ./node_modules/protobufjs/src/rpc.js ***!
+ \********************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+
+/**
+ * Streaming RPC helpers.
+ * @namespace
+ */
+var rpc = exports;
+
+/**
+ * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.
+ * @typedef RPCImpl
+ * @type {function}
+ * @param {Method|rpc.ServiceMethod<Message<{}>,Message<{}>>} method Reflected or static method being called
+ * @param {Uint8Array} requestData Request data
+ * @param {RPCImplCallback} callback Callback function
+ * @returns {undefined}
+ * @example
+ * function rpcImpl(method, requestData, callback) {
+ * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code
+ * throw Error("no such method");
+ * asynchronouslyObtainAResponse(requestData, function(err, responseData) {
+ * callback(err, responseData);
+ * });
+ * }
+ */
+
+/**
+ * Node-style callback as used by {@link RPCImpl}.
+ * @typedef RPCImplCallback
+ * @type {function}
+ * @param {Error|null} error Error, if any, otherwise `null`
+ * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error
+ * @returns {undefined}
+ */
+
+rpc.Service = __webpack_require__(/*! ./rpc/service */ "./node_modules/protobufjs/src/rpc/service.js");
+
+
+/***/ }),
+
+/***/ "./node_modules/protobufjs/src/rpc/service.js":
+/*!****************************************************!*\
+ !*** ./node_modules/protobufjs/src/rpc/service.js ***!
+ \****************************************************/
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+module.exports = Service;
+
+var util = __webpack_require__(/*! ../util/minimal */ "./node_modules/protobufjs/src/util/minimal.js");
+
+// Extends EventEmitter
+(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;
+
+/**
+ * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.
+ *
+ * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.
+ * @typedef rpc.ServiceMethodCallback
+ * @template TRes extends Message<TRes>
+ * @type {function}
+ * @param {Error|null} error Error, if any
+ * @param {TRes} [response] Response message
+ * @returns {undefined}
+ */
+
+/**
+ * A service method part of a {@link rpc.Service} as created by {@link Service.create}.
+ * @typedef rpc.ServiceMethod
+ * @template TReq extends Message<TReq>
+ * @template TRes extends Message<TRes>
+ * @type {function}
+ * @param {TReq|Properties<TReq>} request Request message or plain object
+ * @param {rpc.ServiceMethodCallback<TRes>} [callback] Node-style callback called with the error, if any, and the response message
+ * @returns {Promise<Message<TRes>>} Promise if `callback` has been omitted, otherwise `undefined`
+ */
+
+/**
+ * Constructs a new RPC service instance.
+ * @classdesc An RPC service as returned by {@link Service#create}.
+ * @exports rpc.Service
+ * @extends util.EventEmitter
+ * @constructor
+ * @param {RPCImpl} rpcImpl RPC implementation
+ * @param {boolean} [requestDelimited=false] Whether requests are length-delimited
+ * @param {boolean} [responseDelimited=false] Whether responses are length-delimited
+ */
+function Service(rpcImpl, requestDelimited, responseDelimited) {
+
+ if (typeof rpcImpl !== "function")
+ throw TypeError("rpcImpl must be a function");
+
+ util.EventEmitter.call(this);
+
+ /**
+ * RPC implementation. Becomes `null` once the service is ended.
+ * @type {RPCImpl|null}
+ */
+ this.rpcImpl = rpcImpl;
+
+ /**
+ * Whether requests are length-delimited.
+ * @type {boolean}
+ */
+ this.requestDelimited = Boolean(requestDelimited);
+
+ /**
+ * Whether responses are length-delimited.
+ * @type {boolean}
+ */
+ this.responseDelimited = Boolean(responseDelimited);
+}
+
+/**
+ * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.
+ * @param {Method|rpc.ServiceMethod<TReq,TRes>} method Reflected or static method
+ * @param {Constructor<TReq>} requestCtor Request constructor
+ * @param {Constructor<TRes>} responseCtor Response constructor
+ * @param {TReq|Properties<TReq>} request Request message or plain object
+ * @param {rpc.ServiceMethodCallback<TRes>} callback Service callback
+ * @returns {undefined}
+ * @template TReq extends Message<TReq>
+ * @template TRes extends Message<TRes>
+ */
+Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {
+
+ if (!request)
+ throw TypeError("request must be specified");
+
+ var self = this;
+ if (!callback)
+ return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);
+
+ if (!self.rpcImpl) {
+ setTimeout(function() { callback(Error("already ended")); }, 0);
+ return undefined;
+ }
+
+ try {
+ return self.rpcImpl(
+ method,
+ requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(),
+ function rpcCallback(err, response) {
+
+ if (err) {
+ self.emit("error", err, method);
+ return callback(err);
+ }
+
+ if (response === null) {
+ self.end(/* endedByRPC */ true);
+ return undefined;
+ }
+
+ if (!(response instanceof responseCtor)) {
+ try {
+ response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response);
+ } catch (err) {
+ self.emit("error", err, method);
+ return callback(err);
+ }
+ }
+
+ self.emit("data", response, method);
+ return callback(null, response);
+ }
+ );
+ } catch (err) {
+ self.emit("error", err, method);
+ setTimeout(function() { callback(err); }, 0);
+ return undefined;
+ }
+};
+
+/**
+ * Ends this service and emits the `end` event.
+ * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.
+ * @returns {rpc.Service} `this`
+ */
+Service.prototype.end = function end(endedByRPC) {
+ if (this.rpcImpl) {
+ if (!endedByRPC) // signal end to rpcImpl
+ this.rpcImpl(null, null, null);
+ this.rpcImpl = null;
+ this.emit("end").off();
+ }
+ return this;
+};
+
+
+/***/ }),
+
+/***/ "./node_modules/protobufjs/src/util/longbits.js":
+/*!******************************************************!*\
+ !*** ./node_modules/protobufjs/src/util/longbits.js ***!
+ \******************************************************/
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+module.exports = LongBits;
+
+var util = __webpack_require__(/*! ../util/minimal */ "./node_modules/protobufjs/src/util/minimal.js");
+
+/**
+ * Constructs new long bits.
+ * @classdesc Helper class for working with the low and high bits of a 64 bit value.
+ * @memberof util
+ * @constructor
+ * @param {number} lo Low 32 bits, unsigned
+ * @param {number} hi High 32 bits, unsigned
+ */
+function LongBits(lo, hi) {
+
+ // note that the casts below are theoretically unnecessary as of today, but older statically
+ // generated converter code might still call the ctor with signed 32bits. kept for compat.
+
+ /**
+ * Low bits.
+ * @type {number}
+ */
+ this.lo = lo >>> 0;
+
+ /**
+ * High bits.
+ * @type {number}
+ */
+ this.hi = hi >>> 0;
+}
+
+/**
+ * Zero bits.
+ * @memberof util.LongBits
+ * @type {util.LongBits}
+ */
+var zero = LongBits.zero = new LongBits(0, 0);
+
+zero.toNumber = function() { return 0; };
+zero.zzEncode = zero.zzDecode = function() { return this; };
+zero.length = function() { return 1; };
+
+/**
+ * Zero hash.
+ * @memberof util.LongBits
+ * @type {string}
+ */
+var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0";
+
+/**
+ * Constructs new long bits from the specified number.
+ * @param {number} value Value
+ * @returns {util.LongBits} Instance
+ */
+LongBits.fromNumber = function fromNumber(value) {
+ if (value === 0)
+ return zero;
+ var sign = value < 0;
+ if (sign)
+ value = -value;
+ var lo = value >>> 0,
+ hi = (value - lo) / 4294967296 >>> 0;
+ if (sign) {
+ hi = ~hi >>> 0;
+ lo = ~lo >>> 0;
+ if (++lo > 4294967295) {
+ lo = 0;
+ if (++hi > 4294967295)
+ hi = 0;
+ }
+ }
+ return new LongBits(lo, hi);
+};
+
+/**
+ * Constructs new long bits from a number, long or string.
+ * @param {Long|number|string} value Value
+ * @returns {util.LongBits} Instance
+ */
+LongBits.from = function from(value) {
+ if (typeof value === "number")
+ return LongBits.fromNumber(value);
+ if (util.isString(value)) {
+ /* istanbul ignore else */
+ if (util.Long)
+ value = util.Long.fromString(value);
+ else
+ return LongBits.fromNumber(parseInt(value, 10));
+ }
+ return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;
+};
+
+/**
+ * Converts this long bits to a possibly unsafe JavaScript number.
+ * @param {boolean} [unsigned=false] Whether unsigned or not
+ * @returns {number} Possibly unsafe number
+ */
+LongBits.prototype.toNumber = function toNumber(unsigned) {
+ if (!unsigned && this.hi >>> 31) {
+ var lo = ~this.lo + 1 >>> 0,
+ hi = ~this.hi >>> 0;
+ if (!lo)
+ hi = hi + 1 >>> 0;
+ return -(lo + hi * 4294967296);
+ }
+ return this.lo + this.hi * 4294967296;
+};
+
+/**
+ * Converts this long bits to a long.
+ * @param {boolean} [unsigned=false] Whether unsigned or not
+ * @returns {Long} Long
+ */
+LongBits.prototype.toLong = function toLong(unsigned) {
+ return util.Long
+ ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))
+ /* istanbul ignore next */
+ : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };
+};
+
+var charCodeAt = String.prototype.charCodeAt;
+
+/**
+ * Constructs new long bits from the specified 8 characters long hash.
+ * @param {string} hash Hash
+ * @returns {util.LongBits} Bits
+ */
+LongBits.fromHash = function fromHash(hash) {
+ if (hash === zeroHash)
+ return zero;
+ return new LongBits(
+ ( charCodeAt.call(hash, 0)
+ | charCodeAt.call(hash, 1) << 8
+ | charCodeAt.call(hash, 2) << 16
+ | charCodeAt.call(hash, 3) << 24) >>> 0
+ ,
+ ( charCodeAt.call(hash, 4)
+ | charCodeAt.call(hash, 5) << 8
+ | charCodeAt.call(hash, 6) << 16
+ | charCodeAt.call(hash, 7) << 24) >>> 0
+ );
+};
+
+/**
+ * Converts this long bits to a 8 characters long hash.
+ * @returns {string} Hash
+ */
+LongBits.prototype.toHash = function toHash() {
+ return String.fromCharCode(
+ this.lo & 255,
+ this.lo >>> 8 & 255,
+ this.lo >>> 16 & 255,
+ this.lo >>> 24 ,
+ this.hi & 255,
+ this.hi >>> 8 & 255,
+ this.hi >>> 16 & 255,
+ this.hi >>> 24
+ );
+};
+
+/**
+ * Zig-zag encodes this long bits.
+ * @returns {util.LongBits} `this`
+ */
+LongBits.prototype.zzEncode = function zzEncode() {
+ var mask = this.hi >> 31;
+ this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;
+ this.lo = ( this.lo << 1 ^ mask) >>> 0;
+ return this;
+};
+
+/**
+ * Zig-zag decodes this long bits.
+ * @returns {util.LongBits} `this`
+ */
+LongBits.prototype.zzDecode = function zzDecode() {
+ var mask = -(this.lo & 1);
+ this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;
+ this.hi = ( this.hi >>> 1 ^ mask) >>> 0;
+ return this;
+};
+
+/**
+ * Calculates the length of this longbits when encoded as a varint.
+ * @returns {number} Length
+ */
+LongBits.prototype.length = function length() {
+ var part0 = this.lo,
+ part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,
+ part2 = this.hi >>> 24;
+ return part2 === 0
+ ? part1 === 0
+ ? part0 < 16384
+ ? part0 < 128 ? 1 : 2
+ : part0 < 2097152 ? 3 : 4
+ : part1 < 16384
+ ? part1 < 128 ? 5 : 6
+ : part1 < 2097152 ? 7 : 8
+ : part2 < 128 ? 9 : 10;
+};
+
+
+/***/ }),
+
+/***/ "./node_modules/protobufjs/src/util/minimal.js":
+/*!*****************************************************!*\
+ !*** ./node_modules/protobufjs/src/util/minimal.js ***!
+ \*****************************************************/
+/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
+
+"use strict";
+
+var util = exports;
+
+// used to return a Promise where callback is omitted
+util.asPromise = __webpack_require__(/*! @protobufjs/aspromise */ "./node_modules/@protobufjs/aspromise/index.js");
+
+// converts to / from base64 encoded strings
+util.base64 = __webpack_require__(/*! @protobufjs/base64 */ "./node_modules/@protobufjs/base64/index.js");
+
+// base class of rpc.Service
+util.EventEmitter = __webpack_require__(/*! @protobufjs/eventemitter */ "./node_modules/@protobufjs/eventemitter/index.js");
+
+// float handling accross browsers
+util.float = __webpack_require__(/*! @protobufjs/float */ "./node_modules/@protobufjs/float/index.js");
+
+// requires modules optionally and hides the call from bundlers
+util.inquire = __webpack_require__(/*! @protobufjs/inquire */ "./node_modules/@protobufjs/inquire/index.js");
+
+// converts to / from utf8 encoded strings
+util.utf8 = __webpack_require__(/*! @protobufjs/utf8 */ "./node_modules/@protobufjs/utf8/index.js");
+
+// provides a node-like buffer pool in the browser
+util.pool = __webpack_require__(/*! @protobufjs/pool */ "./node_modules/@protobufjs/pool/index.js");
+
+// utility to work with the low and high bits of a 64 bit value
+util.LongBits = __webpack_require__(/*! ./longbits */ "./node_modules/protobufjs/src/util/longbits.js");
+
+/**
+ * Whether running within node or not.
+ * @memberof util
+ * @type {boolean}
+ */
+util.isNode = Boolean(typeof __webpack_require__.g !== "undefined"
+ && __webpack_require__.g
+ && __webpack_require__.g.process
+ && __webpack_require__.g.process.versions
+ && __webpack_require__.g.process.versions.node);
+
+/**
+ * Global object reference.
+ * @memberof util
+ * @type {Object}
+ */
+util.global = util.isNode && __webpack_require__.g
+ || typeof window !== "undefined" && window
+ || typeof self !== "undefined" && self
+ || this; // eslint-disable-line no-invalid-this
+
+/**
+ * An immuable empty array.
+ * @memberof util
+ * @type {Array.<*>}
+ * @const
+ */
+util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes
+
+/**
+ * An immutable empty object.
+ * @type {Object}
+ * @const
+ */
+util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes
+
+/**
+ * Tests if the specified value is an integer.
+ * @function
+ * @param {*} value Value to test
+ * @returns {boolean} `true` if the value is an integer
+ */
+util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {
+ return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
+};
+
+/**
+ * Tests if the specified value is a string.
+ * @param {*} value Value to test
+ * @returns {boolean} `true` if the value is a string
+ */
+util.isString = function isString(value) {
+ return typeof value === "string" || value instanceof String;
+};
+
+/**
+ * Tests if the specified value is a non-null object.
+ * @param {*} value Value to test
+ * @returns {boolean} `true` if the value is a non-null object
+ */
+util.isObject = function isObject(value) {
+ return value && typeof value === "object";
+};
+
+/**
+ * Checks if a property on a message is considered to be present.
+ * This is an alias of {@link util.isSet}.
+ * @function
+ * @param {Object} obj Plain object or message instance
+ * @param {string} prop Property name
+ * @returns {boolean} `true` if considered to be present, otherwise `false`
+ */
+util.isset =
+
+/**
+ * Checks if a property on a message is considered to be present.
+ * @param {Object} obj Plain object or message instance
+ * @param {string} prop Property name
+ * @returns {boolean} `true` if considered to be present, otherwise `false`
+ */
+util.isSet = function isSet(obj, prop) {
+ var value = obj[prop];
+ if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins
+ return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;
+ return false;
+};
+
+/**
+ * Any compatible Buffer instance.
+ * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.
+ * @interface Buffer
+ * @extends Uint8Array
+ */
+
+/**
+ * Node's Buffer class if available.
+ * @type {Constructor<Buffer>}
+ */
+util.Buffer = (function() {
+ try {
+ var Buffer = util.inquire("buffer").Buffer;
+ // refuse to use non-node buffers if not explicitly assigned (perf reasons):
+ return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;
+ } catch (e) {
+ /* istanbul ignore next */
+ return null;
+ }
+})();
+
+// Internal alias of or polyfull for Buffer.from.
+util._Buffer_from = null;
+
+// Internal alias of or polyfill for Buffer.allocUnsafe.
+util._Buffer_allocUnsafe = null;
+
+/**
+ * Creates a new buffer of whatever type supported by the environment.
+ * @param {number|number[]} [sizeOrArray=0] Buffer size or number array
+ * @returns {Uint8Array|Buffer} Buffer
+ */
+util.newBuffer = function newBuffer(sizeOrArray) {
+ /* istanbul ignore next */
+ return typeof sizeOrArray === "number"
+ ? util.Buffer
+ ? util._Buffer_allocUnsafe(sizeOrArray)
+ : new util.Array(sizeOrArray)
+ : util.Buffer
+ ? util._Buffer_from(sizeOrArray)
+ : typeof Uint8Array === "undefined"
+ ? sizeOrArray
+ : new Uint8Array(sizeOrArray);
+};
+
+/**
+ * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.
+ * @type {Constructor<Uint8Array>}
+ */
+util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array;
+
+/**
+ * Any compatible Long instance.
+ * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.
+ * @interface Long
+ * @property {number} low Low bits
+ * @property {number} high High bits
+ * @property {boolean} unsigned Whether unsigned or not
+ */
+
+/**
+ * Long.js's Long class if available.
+ * @type {Constructor<Long>}
+ */
+util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long
+ || /* istanbul ignore next */ util.global.Long
+ || util.inquire("long");
+
+/**
+ * Regular expression used to verify 2 bit (`bool`) map keys.
+ * @type {RegExp}
+ * @const
+ */
+util.key2Re = /^true|false|0|1$/;
+
+/**
+ * Regular expression used to verify 32 bit (`int32` etc.) map keys.
+ * @type {RegExp}
+ * @const
+ */
+util.key32Re = /^-?(?:0|[1-9][0-9]*)$/;
+
+/**
+ * Regular expression used to verify 64 bit (`int64` etc.) map keys.
+ * @type {RegExp}
+ * @const
+ */
+util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;
+
+/**
+ * Converts a number or long to an 8 characters long hash string.
+ * @param {Long|number} value Value to convert
+ * @returns {string} Hash
+ */
+util.longToHash = function longToHash(value) {
+ return value
+ ? util.LongBits.from(value).toHash()
+ : util.LongBits.zeroHash;
+};
+
+/**
+ * Converts an 8 characters long hash string to a long or number.
+ * @param {string} hash Hash
+ * @param {boolean} [unsigned=false] Whether unsigned or not
+ * @returns {Long|number} Original value
+ */
+util.longFromHash = function longFromHash(hash, unsigned) {
+ var bits = util.LongBits.fromHash(hash);
+ if (util.Long)
+ return util.Long.fromBits(bits.lo, bits.hi, unsigned);
+ return bits.toNumber(Boolean(unsigned));
+};
+
+/**
+ * Merges the properties of the source object into the destination object.
+ * @memberof util
+ * @param {Object.<string,*>} dst Destination object
+ * @param {Object.<string,*>} src Source object
+ * @param {boolean} [ifNotSet=false] Merges only if the key is not already set
+ * @returns {Object.<string,*>} Destination object
+ */
+function merge(dst, src, ifNotSet) { // used by converters
+ for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)
+ if (dst[keys[i]] === undefined || !ifNotSet)
+ dst[keys[i]] = src[keys[i]];
+ return dst;
+}
+
+util.merge = merge;
+
+/**
+ * Converts the first character of a string to lower case.
+ * @param {string} str String to convert
+ * @returns {string} Converted string
+ */
+util.lcFirst = function lcFirst(str) {
+ return str.charAt(0).toLowerCase() + str.substring(1);
+};
+
+/**
+ * Creates a custom error constructor.
+ * @memberof util
+ * @param {string} name Error name
+ * @returns {Constructor<Error>} Custom error constructor
+ */
+function newError(name) {
+
+ function CustomError(message, properties) {
+
+ if (!(this instanceof CustomError))
+ return new CustomError(message, properties);
+
+ // Error.call(this, message);
+ // ^ just returns a new error instance because the ctor can be called as a function
+
+ Object.defineProperty(this, "message", { get: function() { return message; } });
+
+ /* istanbul ignore next */
+ if (Error.captureStackTrace) // node
+ Error.captureStackTrace(this, CustomError);
+ else
+ Object.defineProperty(this, "stack", { value: new Error().stack || "" });
+
+ if (properties)
+ merge(this, properties);
+ }
+
+ (CustomError.prototype = Object.create(Error.prototype)).constructor = CustomError;
+
+ Object.defineProperty(CustomError.prototype, "name", { get: function() { return name; } });
+
+ CustomError.prototype.toString = function toString() {
+ return this.name + ": " + this.message;
+ };
+
+ return CustomError;
+}
+
+util.newError = newError;
+
+/**
+ * Constructs a new protocol error.
+ * @classdesc Error subclass indicating a protocol specifc error.
+ * @memberof util
+ * @extends Error
+ * @template T extends Message<T>
+ * @constructor
+ * @param {string} message Error message
+ * @param {Object.<string,*>} [properties] Additional properties
+ * @example
+ * try {
+ * MyMessage.decode(someBuffer); // throws if required fields are missing
+ * } catch (e) {
+ * if (e instanceof ProtocolError && e.instance)
+ * console.log("decoded so far: " + JSON.stringify(e.instance));
+ * }
+ */
+util.ProtocolError = newError("ProtocolError");
+
+/**
+ * So far decoded message instance.
+ * @name util.ProtocolError#instance
+ * @type {Message<T>}
+ */
+
+/**
+ * A OneOf getter as returned by {@link util.oneOfGetter}.
+ * @typedef OneOfGetter
+ * @type {function}
+ * @returns {string|undefined} Set field name, if any
+ */
+
+/**
+ * Builds a getter for a oneof's present field name.
+ * @param {string[]} fieldNames Field names
+ * @returns {OneOfGetter} Unbound getter
+ */
+util.oneOfGetter = function getOneOf(fieldNames) {
+ var fieldMap = {};
+ for (var i = 0; i < fieldNames.length; ++i)
+ fieldMap[fieldNames[i]] = 1;
+
+ /**
+ * @returns {string|undefined} Set field name, if any
+ * @this Object
+ * @ignore
+ */
+ return function() { // eslint-disable-line consistent-return
+ for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)
+ if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)
+ return keys[i];
+ };
+};
+
+/**
+ * A OneOf setter as returned by {@link util.oneOfSetter}.
+ * @typedef OneOfSetter
+ * @type {function}
+ * @param {string|undefined} value Field name
+ * @returns {undefined}
+ */
+
+/**
+ * Builds a setter for a oneof's present field name.
+ * @param {string[]} fieldNames Field names
+ * @returns {OneOfSetter} Unbound setter
+ */
+util.oneOfSetter = function setOneOf(fieldNames) {
+
+ /**
+ * @param {string} name Field name
+ * @returns {undefined}
+ * @this Object
+ * @ignore
+ */
+ return function(name) {
+ for (var i = 0; i < fieldNames.length; ++i)
+ if (fieldNames[i] !== name)
+ delete this[fieldNames[i]];
+ };
+};
+
+/**
+ * Default conversion options used for {@link Message#toJSON} implementations.
+ *
+ * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:
+ *
+ * - Longs become strings
+ * - Enums become string keys
+ * - Bytes become base64 encoded strings
+ * - (Sub-)Messages become plain objects
+ * - Maps become plain objects with all string keys
+ * - Repeated fields become arrays
+ * - NaN and Infinity for float and double fields become strings
+ *
+ * @type {IConversionOptions}
+ * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json
+ */
+util.toJSONOptions = {
+ longs: String,
+ enums: String,
+ bytes: String,
+ json: true
+};
+
+// Sets up buffer utility according to the environment (called in index-minimal)
+util._configure = function() {
+ var Buffer = util.Buffer;
+ /* istanbul ignore if */
+ if (!Buffer) {
+ util._Buffer_from = util._Buffer_allocUnsafe = null;
+ return;
+ }
+ // because node 4.x buffers are incompatible & immutable
+ // see: https://github.com/dcodeIO/protobuf.js/pull/665
+ util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||
+ /* istanbul ignore next */
+ function Buffer_from(value, encoding) {
+ return new Buffer(value, encoding);
+ };
+ util._Buffer_allocUnsafe = Buffer.allocUnsafe ||
+ /* istanbul ignore next */
+ function Buffer_allocUnsafe(size) {
+ return new Buffer(size);
+ };
+};
+
+
+/***/ }),
+
+/***/ "./node_modules/protobufjs/src/writer.js":
+/*!***********************************************!*\
+ !*** ./node_modules/protobufjs/src/writer.js ***!
+ \***********************************************/
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+module.exports = Writer;
+
+var util = __webpack_require__(/*! ./util/minimal */ "./node_modules/protobufjs/src/util/minimal.js");
+
+var BufferWriter; // cyclic
+
+var LongBits = util.LongBits,
+ base64 = util.base64,
+ utf8 = util.utf8;
+
+/**
+ * Constructs a new writer operation instance.
+ * @classdesc Scheduled writer operation.
+ * @constructor
+ * @param {function(*, Uint8Array, number)} fn Function to call
+ * @param {number} len Value byte length
+ * @param {*} val Value to write
+ * @ignore
+ */
+function Op(fn, len, val) {
+
+ /**
+ * Function to call.
+ * @type {function(Uint8Array, number, *)}
+ */
+ this.fn = fn;
+
+ /**
+ * Value byte length.
+ * @type {number}
+ */
+ this.len = len;
+
+ /**
+ * Next operation.
+ * @type {Writer.Op|undefined}
+ */
+ this.next = undefined;
+
+ /**
+ * Value to write.
+ * @type {*}
+ */
+ this.val = val; // type varies
+}
+
+/* istanbul ignore next */
+function noop() {} // eslint-disable-line no-empty-function
+
+/**
+ * Constructs a new writer state instance.
+ * @classdesc Copied writer state.
+ * @memberof Writer
+ * @constructor
+ * @param {Writer} writer Writer to copy state from
+ * @ignore
+ */
+function State(writer) {
+
+ /**
+ * Current head.
+ * @type {Writer.Op}
+ */
+ this.head = writer.head;
+
+ /**
+ * Current tail.
+ * @type {Writer.Op}
+ */
+ this.tail = writer.tail;
+
+ /**
+ * Current buffer length.
+ * @type {number}
+ */
+ this.len = writer.len;
+
+ /**
+ * Next state.
+ * @type {State|null}
+ */
+ this.next = writer.states;
+}
+
+/**
+ * Constructs a new writer instance.
+ * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.
+ * @constructor
+ */
+function Writer() {
+
+ /**
+ * Current length.
+ * @type {number}
+ */
+ this.len = 0;
+
+ /**
+ * Operations head.
+ * @type {Object}
+ */
+ this.head = new Op(noop, 0, 0);
+
+ /**
+ * Operations tail
+ * @type {Object}
+ */
+ this.tail = this.head;
+
+ /**
+ * Linked forked states.
+ * @type {Object|null}
+ */
+ this.states = null;
+
+ // When a value is written, the writer calculates its byte length and puts it into a linked
+ // list of operations to perform when finish() is called. This both allows us to allocate
+ // buffers of the exact required size and reduces the amount of work we have to do compared
+ // to first calculating over objects and then encoding over objects. In our case, the encoding
+ // part is just a linked list walk calling operations with already prepared values.
+}
+
+var create = function create() {
+ return util.Buffer
+ ? function create_buffer_setup() {
+ return (Writer.create = function create_buffer() {
+ return new BufferWriter();
+ })();
+ }
+ /* istanbul ignore next */
+ : function create_array() {
+ return new Writer();
+ };
+};
+
+/**
+ * Creates a new writer.
+ * @function
+ * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}
+ */
+Writer.create = create();
+
+/**
+ * Allocates a buffer of the specified size.
+ * @param {number} size Buffer size
+ * @returns {Uint8Array} Buffer
+ */
+Writer.alloc = function alloc(size) {
+ return new util.Array(size);
+};
+
+// Use Uint8Array buffer pool in the browser, just like node does with buffers
+/* istanbul ignore else */
+if (util.Array !== Array)
+ Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);
+
+/**
+ * Pushes a new operation to the queue.
+ * @param {function(Uint8Array, number, *)} fn Function to call
+ * @param {number} len Value byte length
+ * @param {number} val Value to write
+ * @returns {Writer} `this`
+ * @private
+ */
+Writer.prototype._push = function push(fn, len, val) {
+ this.tail = this.tail.next = new Op(fn, len, val);
+ this.len += len;
+ return this;
+};
+
+function writeByte(val, buf, pos) {
+ buf[pos] = val & 255;
+}
+
+function writeVarint32(val, buf, pos) {
+ while (val > 127) {
+ buf[pos++] = val & 127 | 128;
+ val >>>= 7;
+ }
+ buf[pos] = val;
+}
+
+/**
+ * Constructs a new varint writer operation instance.
+ * @classdesc Scheduled varint writer operation.
+ * @extends Op
+ * @constructor
+ * @param {number} len Value byte length
+ * @param {number} val Value to write
+ * @ignore
+ */
+function VarintOp(len, val) {
+ this.len = len;
+ this.next = undefined;
+ this.val = val;
+}
+
+VarintOp.prototype = Object.create(Op.prototype);
+VarintOp.prototype.fn = writeVarint32;
+
+/**
+ * Writes an unsigned 32 bit value as a varint.
+ * @param {number} value Value to write
+ * @returns {Writer} `this`
+ */
+Writer.prototype.uint32 = function write_uint32(value) {
+ // here, the call to this.push has been inlined and a varint specific Op subclass is used.
+ // uint32 is by far the most frequently used operation and benefits significantly from this.
+ this.len += (this.tail = this.tail.next = new VarintOp(
+ (value = value >>> 0)
+ < 128 ? 1
+ : value < 16384 ? 2
+ : value < 2097152 ? 3
+ : value < 268435456 ? 4
+ : 5,
+ value)).len;
+ return this;
+};
+
+/**
+ * Writes a signed 32 bit value as a varint.
+ * @function
+ * @param {number} value Value to write
+ * @returns {Writer} `this`
+ */
+Writer.prototype.int32 = function write_int32(value) {
+ return value < 0
+ ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec
+ : this.uint32(value);
+};
+
+/**
+ * Writes a 32 bit value as a varint, zig-zag encoded.
+ * @param {number} value Value to write
+ * @returns {Writer} `this`
+ */
+Writer.prototype.sint32 = function write_sint32(value) {
+ return this.uint32((value << 1 ^ value >> 31) >>> 0);
+};
+
+function writeVarint64(val, buf, pos) {
+ while (val.hi) {
+ buf[pos++] = val.lo & 127 | 128;
+ val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;
+ val.hi >>>= 7;
+ }
+ while (val.lo > 127) {
+ buf[pos++] = val.lo & 127 | 128;
+ val.lo = val.lo >>> 7;
+ }
+ buf[pos++] = val.lo;
+}
+
+/**
+ * Writes an unsigned 64 bit value as a varint.
+ * @param {Long|number|string} value Value to write
+ * @returns {Writer} `this`
+ * @throws {TypeError} If `value` is a string and no long library is present.
+ */
+Writer.prototype.uint64 = function write_uint64(value) {
+ var bits = LongBits.from(value);
+ return this._push(writeVarint64, bits.length(), bits);
+};
+
+/**
+ * Writes a signed 64 bit value as a varint.
+ * @function
+ * @param {Long|number|string} value Value to write
+ * @returns {Writer} `this`
+ * @throws {TypeError} If `value` is a string and no long library is present.
+ */
+Writer.prototype.int64 = Writer.prototype.uint64;
+
+/**
+ * Writes a signed 64 bit value as a varint, zig-zag encoded.
+ * @param {Long|number|string} value Value to write
+ * @returns {Writer} `this`
+ * @throws {TypeError} If `value` is a string and no long library is present.
+ */
+Writer.prototype.sint64 = function write_sint64(value) {
+ var bits = LongBits.from(value).zzEncode();
+ return this._push(writeVarint64, bits.length(), bits);
+};
+
+/**
+ * Writes a boolish value as a varint.
+ * @param {boolean} value Value to write
+ * @returns {Writer} `this`
+ */
+Writer.prototype.bool = function write_bool(value) {
+ return this._push(writeByte, 1, value ? 1 : 0);
+};
+
+function writeFixed32(val, buf, pos) {
+ buf[pos ] = val & 255;
+ buf[pos + 1] = val >>> 8 & 255;
+ buf[pos + 2] = val >>> 16 & 255;
+ buf[pos + 3] = val >>> 24;
+}
+
+/**
+ * Writes an unsigned 32 bit value as fixed 32 bits.
+ * @param {number} value Value to write
+ * @returns {Writer} `this`
+ */
+Writer.prototype.fixed32 = function write_fixed32(value) {
+ return this._push(writeFixed32, 4, value >>> 0);
+};
+
+/**
+ * Writes a signed 32 bit value as fixed 32 bits.
+ * @function
+ * @param {number} value Value to write
+ * @returns {Writer} `this`
+ */
+Writer.prototype.sfixed32 = Writer.prototype.fixed32;
+
+/**
+ * Writes an unsigned 64 bit value as fixed 64 bits.
+ * @param {Long|number|string} value Value to write
+ * @returns {Writer} `this`
+ * @throws {TypeError} If `value` is a string and no long library is present.
+ */
+Writer.prototype.fixed64 = function write_fixed64(value) {
+ var bits = LongBits.from(value);
+ return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);
+};
+
+/**
+ * Writes a signed 64 bit value as fixed 64 bits.
+ * @function
+ * @param {Long|number|string} value Value to write
+ * @returns {Writer} `this`
+ * @throws {TypeError} If `value` is a string and no long library is present.
+ */
+Writer.prototype.sfixed64 = Writer.prototype.fixed64;
+
+/**
+ * Writes a float (32 bit).
+ * @function
+ * @param {number} value Value to write
+ * @returns {Writer} `this`
+ */
+Writer.prototype.float = function write_float(value) {
+ return this._push(util.float.writeFloatLE, 4, value);
+};
+
+/**
+ * Writes a double (64 bit float).
+ * @function
+ * @param {number} value Value to write
+ * @returns {Writer} `this`
+ */
+Writer.prototype.double = function write_double(value) {
+ return this._push(util.float.writeDoubleLE, 8, value);
+};
+
+var writeBytes = util.Array.prototype.set
+ ? function writeBytes_set(val, buf, pos) {
+ buf.set(val, pos); // also works for plain array values
+ }
+ /* istanbul ignore next */
+ : function writeBytes_for(val, buf, pos) {
+ for (var i = 0; i < val.length; ++i)
+ buf[pos + i] = val[i];
+ };
+
+/**
+ * Writes a sequence of bytes.
+ * @param {Uint8Array|string} value Buffer or base64 encoded string to write
+ * @returns {Writer} `this`
+ */
+Writer.prototype.bytes = function write_bytes(value) {
+ var len = value.length >>> 0;
+ if (!len)
+ return this._push(writeByte, 1, 0);
+ if (util.isString(value)) {
+ var buf = Writer.alloc(len = base64.length(value));
+ base64.decode(value, buf, 0);
+ value = buf;
+ }
+ return this.uint32(len)._push(writeBytes, len, value);
+};
+
+/**
+ * Writes a string.
+ * @param {string} value Value to write
+ * @returns {Writer} `this`
+ */
+Writer.prototype.string = function write_string(value) {
+ var len = utf8.length(value);
+ return len
+ ? this.uint32(len)._push(utf8.write, len, value)
+ : this._push(writeByte, 1, 0);
+};
+
+/**
+ * Forks this writer's state by pushing it to a stack.
+ * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.
+ * @returns {Writer} `this`
+ */
+Writer.prototype.fork = function fork() {
+ this.states = new State(this);
+ this.head = this.tail = new Op(noop, 0, 0);
+ this.len = 0;
+ return this;
+};
+
+/**
+ * Resets this instance to the last state.
+ * @returns {Writer} `this`
+ */
+Writer.prototype.reset = function reset() {
+ if (this.states) {
+ this.head = this.states.head;
+ this.tail = this.states.tail;
+ this.len = this.states.len;
+ this.states = this.states.next;
+ } else {
+ this.head = this.tail = new Op(noop, 0, 0);
+ this.len = 0;
+ }
+ return this;
+};
+
+/**
+ * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.
+ * @returns {Writer} `this`
+ */
+Writer.prototype.ldelim = function ldelim() {
+ var head = this.head,
+ tail = this.tail,
+ len = this.len;
+ this.reset().uint32(len);
+ if (len) {
+ this.tail.next = head.next; // skip noop
+ this.tail = tail;
+ this.len += len;
+ }
+ return this;
+};
+
+/**
+ * Finishes the write operation.
+ * @returns {Uint8Array} Finished buffer
+ */
+Writer.prototype.finish = function finish() {
+ var head = this.head.next, // skip noop
+ buf = this.constructor.alloc(this.len),
+ pos = 0;
+ while (head) {
+ head.fn(head.val, buf, pos);
+ pos += head.len;
+ head = head.next;
+ }
+ // this.head = this.tail = null;
+ return buf;
+};
+
+Writer._configure = function(BufferWriter_) {
+ BufferWriter = BufferWriter_;
+ Writer.create = create();
+ BufferWriter._configure();
+};
+
+
+/***/ }),
+
+/***/ "./node_modules/protobufjs/src/writer_buffer.js":
+/*!******************************************************!*\
+ !*** ./node_modules/protobufjs/src/writer_buffer.js ***!
+ \******************************************************/
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+"use strict";
+
+module.exports = BufferWriter;
+
+// extends Writer
+var Writer = __webpack_require__(/*! ./writer */ "./node_modules/protobufjs/src/writer.js");
+(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;
+
+var util = __webpack_require__(/*! ./util/minimal */ "./node_modules/protobufjs/src/util/minimal.js");
+
+/**
+ * Constructs a new buffer writer instance.
+ * @classdesc Wire format writer using node buffers.
+ * @extends Writer
+ * @constructor
+ */
+function BufferWriter() {
+ Writer.call(this);
+}
+
+BufferWriter._configure = function () {
+ /**
+ * Allocates a buffer of the specified size.
+ * @function
+ * @param {number} size Buffer size
+ * @returns {Buffer} Buffer
+ */
+ BufferWriter.alloc = util._Buffer_allocUnsafe;
+
+ BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set"
+ ? function writeBytesBuffer_set(val, buf, pos) {
+ buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)
+ // also works for plain array values
+ }
+ /* istanbul ignore next */
+ : function writeBytesBuffer_copy(val, buf, pos) {
+ if (val.copy) // Buffer values
+ val.copy(buf, pos, 0, val.length);
+ else for (var i = 0; i < val.length;) // plain array values
+ buf[pos++] = val[i++];
+ };
+};
+
+
+/**
+ * @override
+ */
+BufferWriter.prototype.bytes = function write_bytes_buffer(value) {
+ if (util.isString(value))
+ value = util._Buffer_from(value, "base64");
+ var len = value.length >>> 0;
+ this.uint32(len);
+ if (len)
+ this._push(BufferWriter.writeBytesBuffer, len, value);
+ return this;
+};
+
+function writeStringBuffer(val, buf, pos) {
+ if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)
+ util.utf8.write(val, buf, pos);
+ else if (buf.utf8Write)
+ buf.utf8Write(val, pos);
+ else
+ buf.write(val, pos);
+}
+
+/**
+ * @override
+ */
+BufferWriter.prototype.string = function write_string_buffer(value) {
+ var len = util.Buffer.byteLength(value);
+ this.uint32(len);
+ if (len)
+ this._push(writeStringBuffer, len, value);
+ return this;
+};
+
+
+/**
+ * Finishes the write operation.
+ * @name BufferWriter#finish
+ * @function
+ * @returns {Buffer} Finished buffer
+ */
+
+BufferWriter._configure();
+
+
+/***/ }),
+
+/***/ "./lib/backend-onnxjs.ts":
+/*!*******************************!*\
+ !*** ./lib/backend-onnxjs.ts ***!
+ \*******************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.onnxjsBackend = void 0;
+const session_1 = __webpack_require__(/*! ./onnxjs/session */ "./lib/onnxjs/session.ts");
+const session_handler_1 = __webpack_require__(/*! ./onnxjs/session-handler */ "./lib/onnxjs/session-handler.ts");
+class OnnxjsBackend {
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
+ async init() { }
+ async createSessionHandler(pathOrBuffer, options) {
+ // NOTE: Session.Config(from onnx.js) is not compatible with InferenceSession.SessionOptions(from
+ // onnxruntime-common).
+ // In future we should remove Session.Config and use InferenceSession.SessionOptions.
+ // Currently we allow this to happen to make test runner work.
+ const session = new session_1.Session(options);
+ // typescript cannot merge method override correctly (so far in 4.2.3). need if-else to call the method.
+ if (typeof pathOrBuffer === 'string') {
+ await session.loadModel(pathOrBuffer);
+ }
+ else {
+ await session.loadModel(pathOrBuffer);
+ }
+ return new session_handler_1.OnnxjsSessionHandler(session);
+ }
+}
+exports.onnxjsBackend = new OnnxjsBackend();
+
+
+/***/ }),
+
+/***/ "./lib/backend-wasm.ts":
+/*!*****************************!*\
+ !*** ./lib/backend-wasm.ts ***!
+ \*****************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.wasmBackend = exports.initializeFlags = void 0;
+const onnxruntime_common_1 = __webpack_require__(/*! onnxruntime-common */ "../common/dist/lib/index.js");
+const os_1 = __webpack_require__(/*! os */ "?0757");
+const proxy_wrapper_1 = __webpack_require__(/*! ./wasm/proxy-wrapper */ "./lib/wasm/proxy-wrapper.ts");
+const session_handler_1 = __webpack_require__(/*! ./wasm/session-handler */ "./lib/wasm/session-handler.ts");
+/**
+ * This function initializes all flags for WebAssembly.
+ *
+ * Those flags are accessible from `ort.env.wasm`. Users are allow to set those flags before the first inference session
+ * being created, to override default value.
+ */
+const initializeFlags = () => {
+ if (typeof onnxruntime_common_1.env.wasm.initTimeout !== 'number' || onnxruntime_common_1.env.wasm.initTimeout < 0) {
+ onnxruntime_common_1.env.wasm.initTimeout = 0;
+ }
+ if (typeof onnxruntime_common_1.env.wasm.simd !== 'boolean') {
+ onnxruntime_common_1.env.wasm.simd = true;
+ }
+ if (typeof onnxruntime_common_1.env.wasm.proxy !== 'boolean') {
+ onnxruntime_common_1.env.wasm.proxy = false;
+ }
+ if (typeof onnxruntime_common_1.env.wasm.numThreads !== 'number' || !Number.isInteger(onnxruntime_common_1.env.wasm.numThreads) || onnxruntime_common_1.env.wasm.numThreads <= 0) {
+ const numCpuLogicalCores = typeof navigator === 'undefined' ? (0, os_1.cpus)().length : navigator.hardwareConcurrency;
+ onnxruntime_common_1.env.wasm.numThreads = Math.min(4, Math.ceil((numCpuLogicalCores || 1) / 2));
+ }
+};
+exports.initializeFlags = initializeFlags;
+class OnnxruntimeWebAssemblyBackend {
+ async init() {
+ // populate wasm flags
+ (0, exports.initializeFlags)();
+ // init wasm
+ await (0, proxy_wrapper_1.initWasm)();
+ }
+ async createSessionHandler(pathOrBuffer, options) {
+ const handler = new session_handler_1.OnnxruntimeWebAssemblySessionHandler();
+ await handler.loadModel(pathOrBuffer, options);
+ return Promise.resolve(handler);
+ }
+}
+exports.wasmBackend = new OnnxruntimeWebAssemblyBackend();
+
+
+/***/ }),
+
+/***/ "./lib/index.ts":
+/*!**********************!*\
+ !*** ./lib/index.ts ***!
+ \**********************/
+/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __exportStar = (this && this.__exportStar) || function(m, exports) {
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+/* eslint-disable @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports */
+// We use "require" instead of "import" here because import statement must be put in top level. Our current code does
+// not allow terser to tree-shaking code as expected because some codes are treated as having side effects.
+// So we import code inside the if-clause to allow terser remove the code safely.
+__exportStar(__webpack_require__(/*! onnxruntime-common */ "../common/dist/lib/index.js"), exports);
+const onnxruntime_common_1 = __webpack_require__(/*! onnxruntime-common */ "../common/dist/lib/index.js");
+if (true) {
+ const onnxjsBackend = (__webpack_require__(/*! ./backend-onnxjs */ "./lib/backend-onnxjs.ts").onnxjsBackend);
+ (0, onnxruntime_common_1.registerBackend)('webgl', onnxjsBackend, -10);
+}
+if (true) {
+ const wasmBackend = (__webpack_require__(/*! ./backend-wasm */ "./lib/backend-wasm.ts").wasmBackend);
+ (0, onnxruntime_common_1.registerBackend)('cpu', wasmBackend, 10);
+ (0, onnxruntime_common_1.registerBackend)('wasm', wasmBackend, 10);
+ (0, onnxruntime_common_1.registerBackend)('xnnpack', wasmBackend, 9);
+}
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/attribute-with-cache-key.ts":
+/*!************************************************!*\
+ !*** ./lib/onnxjs/attribute-with-cache-key.ts ***!
+ \************************************************/
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createAttributeWithCacheKey = void 0;
+class AttributeWithCacheKeyImpl {
+ constructor(attribute) {
+ Object.assign(this, attribute);
+ }
+ get cacheKey() {
+ if (!this._cacheKey) {
+ this._cacheKey =
+ Object.getOwnPropertyNames(this).sort().map(name => `${this[name]}`).join(';');
+ }
+ return this._cacheKey;
+ }
+}
+const createAttributeWithCacheKey = (attribute) => new AttributeWithCacheKeyImpl(attribute);
+exports.createAttributeWithCacheKey = createAttributeWithCacheKey;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/attribute.ts":
+/*!*********************************!*\
+ !*** ./lib/onnxjs/attribute.ts ***!
+ \*********************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Attribute = void 0;
+const onnx_proto_1 = __webpack_require__(/*! onnx-proto */ "./node_modules/onnx-proto/dist/onnx.js");
+const ort_generated_1 = __webpack_require__(/*! ./ort-schema/ort-generated */ "./lib/onnxjs/ort-schema/ort-generated.ts");
+const tensor_1 = __webpack_require__(/*! ./tensor */ "./lib/onnxjs/tensor.ts");
+const util_1 = __webpack_require__(/*! ./util */ "./lib/onnxjs/util.ts");
+var ortFbs = ort_generated_1.onnxruntime.experimental.fbs;
+class Attribute {
+ constructor(attributes) {
+ this._attributes = new Map();
+ if (attributes !== null && attributes !== undefined) {
+ for (const attr of attributes) {
+ if (attr instanceof onnx_proto_1.onnx.AttributeProto) {
+ this._attributes.set(attr.name, [Attribute.getValue(attr), Attribute.getType(attr)]);
+ }
+ else if (attr instanceof ortFbs.Attribute) {
+ this._attributes.set(attr.name(), [Attribute.getValue(attr), Attribute.getType(attr)]);
+ }
+ }
+ if (this._attributes.size < attributes.length) {
+ throw new Error('duplicated attribute names');
+ }
+ }
+ }
+ set(key, type, value) {
+ this._attributes.set(key, [value, type]);
+ }
+ delete(key) {
+ this._attributes.delete(key);
+ }
+ getFloat(key, defaultValue) {
+ return this.get(key, 'float', defaultValue);
+ }
+ getInt(key, defaultValue) {
+ return this.get(key, 'int', defaultValue);
+ }
+ getString(key, defaultValue) {
+ return this.get(key, 'string', defaultValue);
+ }
+ getTensor(key, defaultValue) {
+ return this.get(key, 'tensor', defaultValue);
+ }
+ getFloats(key, defaultValue) {
+ return this.get(key, 'floats', defaultValue);
+ }
+ getInts(key, defaultValue) {
+ return this.get(key, 'ints', defaultValue);
+ }
+ getStrings(key, defaultValue) {
+ return this.get(key, 'strings', defaultValue);
+ }
+ getTensors(key, defaultValue) {
+ return this.get(key, 'tensors', defaultValue);
+ }
+ get(key, type, defaultValue) {
+ const valueAndType = this._attributes.get(key);
+ if (valueAndType === undefined) {
+ if (defaultValue !== undefined) {
+ return defaultValue;
+ }
+ throw new Error(`required attribute not found: ${key}`);
+ }
+ if (valueAndType[1] !== type) {
+ throw new Error(`type mismatch: expected ${type} but got ${valueAndType[1]}`);
+ }
+ return valueAndType[0];
+ }
+ static getType(attr) {
+ const type = attr instanceof onnx_proto_1.onnx.AttributeProto ? (attr).type : attr.type();
+ switch (type) {
+ case onnx_proto_1.onnx.AttributeProto.AttributeType.FLOAT:
+ return 'float';
+ case onnx_proto_1.onnx.AttributeProto.AttributeType.INT:
+ return 'int';
+ case onnx_proto_1.onnx.AttributeProto.AttributeType.STRING:
+ return 'string';
+ case onnx_proto_1.onnx.AttributeProto.AttributeType.TENSOR:
+ return 'tensor';
+ case onnx_proto_1.onnx.AttributeProto.AttributeType.FLOATS:
+ return 'floats';
+ case onnx_proto_1.onnx.AttributeProto.AttributeType.INTS:
+ return 'ints';
+ case onnx_proto_1.onnx.AttributeProto.AttributeType.STRINGS:
+ return 'strings';
+ case onnx_proto_1.onnx.AttributeProto.AttributeType.TENSORS:
+ return 'tensors';
+ default:
+ throw new Error(`attribute type is not supported yet: ${onnx_proto_1.onnx.AttributeProto.AttributeType[type]}`);
+ }
+ }
+ static getValue(attr) {
+ const attrType = attr instanceof onnx_proto_1.onnx.AttributeProto ? attr.type : attr.type();
+ if (attrType === onnx_proto_1.onnx.AttributeProto.AttributeType.GRAPH || attrType === onnx_proto_1.onnx.AttributeProto.AttributeType.GRAPHS) {
+ throw new Error('graph attribute is not supported yet');
+ }
+ const value = this.getValueNoCheck(attr);
+ // cast LONG to number
+ if (attrType === onnx_proto_1.onnx.AttributeProto.AttributeType.INT && util_1.LongUtil.isLong(value)) {
+ return util_1.LongUtil.longToNumber(value);
+ }
+ // cast LONG[] to number[]
+ if (attrType === onnx_proto_1.onnx.AttributeProto.AttributeType.INTS) {
+ const arr = value;
+ const numberValue = new Array(arr.length);
+ for (let i = 0; i < arr.length; i++) {
+ const maybeLong = arr[i];
+ numberValue[i] = util_1.LongUtil.longToNumber(maybeLong);
+ }
+ return numberValue;
+ }
+ // cast onnx.TensorProto to onnxjs.Tensor
+ if (attrType === onnx_proto_1.onnx.AttributeProto.AttributeType.TENSOR) {
+ return attr instanceof onnx_proto_1.onnx.AttributeProto ? tensor_1.Tensor.fromProto(value) :
+ tensor_1.Tensor.fromOrtTensor(value);
+ }
+ // cast onnx.TensorProto[] to onnxjs.Tensor[]
+ if (attrType === onnx_proto_1.onnx.AttributeProto.AttributeType.TENSORS) {
+ if (attr instanceof onnx_proto_1.onnx.AttributeProto) {
+ const tensorProtos = value;
+ return tensorProtos.map(value => tensor_1.Tensor.fromProto(value));
+ }
+ else if (attr instanceof ortFbs.Attribute) {
+ const tensorProtos = value;
+ return tensorProtos.map(value => tensor_1.Tensor.fromOrtTensor(value));
+ }
+ }
+ // cast Uint8Array to string
+ if (attrType === onnx_proto_1.onnx.AttributeProto.AttributeType.STRING) {
+ // string in onnx attribute is of uint8array type, so we need to convert it to string below. While in ort format,
+ // string attributes are returned as string, so no conversion is needed.
+ if (attr instanceof onnx_proto_1.onnx.AttributeProto) {
+ const utf8String = value;
+ return (0, util_1.decodeUtf8String)(utf8String);
+ }
+ }
+ // cast Uint8Array[] to string[]
+ if (attrType === onnx_proto_1.onnx.AttributeProto.AttributeType.STRINGS) {
+ // strings in onnx attribute is returned as uint8array[], so we need to convert it to string[] below. While in ort
+ // format strings attributes are returned as string[], so no conversion is needed.
+ if (attr instanceof onnx_proto_1.onnx.AttributeProto) {
+ const utf8Strings = value;
+ return utf8Strings.map(util_1.decodeUtf8String);
+ }
+ }
+ return value;
+ }
+ static getValueNoCheck(attr) {
+ return attr instanceof (onnx_proto_1.onnx.AttributeProto) ? this.getValueNoCheckFromOnnxFormat(attr) :
+ this.getValueNoCheckFromOrtFormat(attr);
+ }
+ static getValueNoCheckFromOnnxFormat(attr) {
+ switch (attr.type) {
+ case onnx_proto_1.onnx.AttributeProto.AttributeType.FLOAT:
+ return attr.f;
+ case onnx_proto_1.onnx.AttributeProto.AttributeType.INT:
+ return attr.i;
+ case onnx_proto_1.onnx.AttributeProto.AttributeType.STRING:
+ return attr.s;
+ case onnx_proto_1.onnx.AttributeProto.AttributeType.TENSOR:
+ return attr.t;
+ case onnx_proto_1.onnx.AttributeProto.AttributeType.GRAPH:
+ return attr.g;
+ case onnx_proto_1.onnx.AttributeProto.AttributeType.FLOATS:
+ return attr.floats;
+ case onnx_proto_1.onnx.AttributeProto.AttributeType.INTS:
+ return attr.ints;
+ case onnx_proto_1.onnx.AttributeProto.AttributeType.STRINGS:
+ return attr.strings;
+ case onnx_proto_1.onnx.AttributeProto.AttributeType.TENSORS:
+ return attr.tensors;
+ case onnx_proto_1.onnx.AttributeProto.AttributeType.GRAPHS:
+ return attr.graphs;
+ default:
+ throw new Error(`unsupported attribute type: ${onnx_proto_1.onnx.AttributeProto.AttributeType[attr.type]}`);
+ }
+ }
+ static getValueNoCheckFromOrtFormat(attr) {
+ switch (attr.type()) {
+ case ortFbs.AttributeType.FLOAT:
+ return attr.f();
+ case ortFbs.AttributeType.INT:
+ return attr.i();
+ case ortFbs.AttributeType.STRING:
+ return attr.s();
+ case ortFbs.AttributeType.TENSOR:
+ return attr.t();
+ case ortFbs.AttributeType.GRAPH:
+ return attr.g();
+ case ortFbs.AttributeType.FLOATS:
+ return attr.floatsArray();
+ case ortFbs.AttributeType.INTS: {
+ const ints = [];
+ for (let i = 0; i < attr.intsLength(); i++) {
+ ints.push(attr.ints(i));
+ }
+ return ints;
+ }
+ case ortFbs.AttributeType.STRINGS: {
+ const strings = [];
+ for (let i = 0; i < attr.stringsLength(); i++) {
+ strings.push(attr.strings(i));
+ }
+ return strings;
+ }
+ case ortFbs.AttributeType.TENSORS: {
+ const tensors = [];
+ for (let i = 0; i < attr.tensorsLength(); i++) {
+ tensors.push(attr.tensors(i));
+ }
+ return tensors;
+ }
+ // case ortFbs.AttributeType.GRAPHS:
+ // TODO: Subgraph not supported yet.
+ // const graphs = [];
+ // for (let i = 0; i < attr.graphsLength(); i++) {
+ // graphs.push(attr.graphs(i)!);
+ // }
+ // return graphs;
+ default:
+ throw new Error(`unsupported attribute type: ${ortFbs.AttributeType[attr.type()]}`);
+ }
+ }
+}
+exports.Attribute = Attribute;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backend.ts":
+/*!*******************************!*\
+ !*** ./lib/onnxjs/backend.ts ***!
+ \*******************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.resolveBackend = exports.backend = void 0;
+const backend_webgl_1 = __webpack_require__(/*! ./backends/backend-webgl */ "./lib/onnxjs/backends/backend-webgl.ts");
+// caches all initialized backend instances
+const backendsCache = new Map();
+exports.backend = {
+ webgl: new backend_webgl_1.WebGLBackend(),
+};
+/**
+ * Resolve a reference to the backend. If a hint is specified, the corresponding
+ * backend will be used.
+ */
+async function resolveBackend(hint) {
+ if (!hint) {
+ return resolveBackend(['webgl']);
+ }
+ else {
+ const hints = typeof hint === 'string' ? [hint] : hint;
+ for (const backendHint of hints) {
+ const cache = backendsCache.get(backendHint);
+ if (cache) {
+ return cache;
+ }
+ const backend = await tryLoadBackend(backendHint);
+ if (backend) {
+ return backend;
+ }
+ }
+ }
+ throw new Error('no available backend to use');
+}
+exports.resolveBackend = resolveBackend;
+async function tryLoadBackend(backendHint) {
+ const backendObj = exports.backend;
+ if (typeof backendObj[backendHint] !== 'undefined' && isBackend(backendObj[backendHint])) {
+ const backend = backendObj[backendHint];
+ let init = backend.initialize();
+ if (typeof init === 'object' && 'then' in init) {
+ init = await init;
+ }
+ if (init) {
+ backendsCache.set(backendHint, backend);
+ return backend;
+ }
+ }
+ return undefined;
+}
+function isBackend(obj) {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const o = obj;
+ // check if an object is a Backend instance
+ if ('initialize' in o && typeof o.initialize === 'function' && // initialize()
+ 'createSessionHandler' in o && typeof o.createSessionHandler === 'function' && // createSessionHandler()
+ 'dispose' in o && typeof o.dispose === 'function' // dispose()
+ ) {
+ return true;
+ }
+ return false;
+}
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/backend-webgl.ts":
+/*!**********************************************!*\
+ !*** ./lib/onnxjs/backends/backend-webgl.ts ***!
+ \**********************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.WebGLBackend = void 0;
+const onnxruntime_common_1 = __webpack_require__(/*! onnxruntime-common */ "../common/dist/lib/index.js");
+const instrument_1 = __webpack_require__(/*! ../instrument */ "./lib/onnxjs/instrument.ts");
+const session_handler_1 = __webpack_require__(/*! ./webgl/session-handler */ "./lib/onnxjs/backends/webgl/session-handler.ts");
+const webgl_context_factory_1 = __webpack_require__(/*! ./webgl/webgl-context-factory */ "./lib/onnxjs/backends/webgl/webgl-context-factory.ts");
+/**
+ * WebGLBackend is the entry point for all WebGL opeartions
+ * When it starts it created the WebGLRenderingContext
+ * and other main framework components such as Program and Texture Managers
+ */
+class WebGLBackend {
+ get contextId() {
+ return onnxruntime_common_1.env.webgl.contextId;
+ }
+ set contextId(value) {
+ onnxruntime_common_1.env.webgl.contextId = value;
+ }
+ get matmulMaxBatchSize() {
+ return onnxruntime_common_1.env.webgl.matmulMaxBatchSize;
+ }
+ set matmulMaxBatchSize(value) {
+ onnxruntime_common_1.env.webgl.matmulMaxBatchSize = value;
+ }
+ get textureCacheMode() {
+ return onnxruntime_common_1.env.webgl.textureCacheMode;
+ }
+ set textureCacheMode(value) {
+ onnxruntime_common_1.env.webgl.textureCacheMode = value;
+ }
+ get pack() {
+ return onnxruntime_common_1.env.webgl.pack;
+ }
+ set pack(value) {
+ onnxruntime_common_1.env.webgl.pack = value;
+ }
+ get async() {
+ return onnxruntime_common_1.env.webgl.async;
+ }
+ set async(value) {
+ onnxruntime_common_1.env.webgl.async = value;
+ }
+ initialize() {
+ try {
+ this.glContext = (0, webgl_context_factory_1.createWebGLContext)(this.contextId);
+ if (typeof this.matmulMaxBatchSize !== 'number') {
+ this.matmulMaxBatchSize = 16;
+ }
+ if (typeof this.textureCacheMode !== 'string') {
+ this.textureCacheMode = 'full';
+ }
+ if (typeof this.pack !== 'boolean') {
+ this.pack = false;
+ }
+ if (typeof this.async !== 'boolean') {
+ this.async = false;
+ }
+ instrument_1.Logger.setWithEnv(onnxruntime_common_1.env);
+ instrument_1.Logger.verbose('WebGLBackend', `Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`);
+ return true;
+ }
+ catch (e) {
+ instrument_1.Logger.warning('WebGLBackend', `Unable to initialize WebGLBackend. ${e}`);
+ return false;
+ }
+ }
+ createSessionHandler(context) {
+ return new session_handler_1.WebGLSessionHandler(this, context);
+ }
+ dispose() {
+ this.glContext.dispose();
+ }
+}
+exports.WebGLBackend = WebGLBackend;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/glsl-coordinate-lib.ts":
+/*!**********************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/glsl-coordinate-lib.ts ***!
+ \**********************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.CoordsGlslLib = void 0;
+const util_1 = __webpack_require__(/*! ../../util */ "./lib/onnxjs/util.ts");
+const glsl_definitions_1 = __webpack_require__(/*! ./glsl-definitions */ "./lib/onnxjs/backends/webgl/glsl-definitions.ts");
+const glsl_source_1 = __webpack_require__(/*! ./glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const texture_layout_strategy_1 = __webpack_require__(/*! ./texture-layout-strategy */ "./lib/onnxjs/backends/webgl/texture-layout-strategy.ts");
+const utils_1 = __webpack_require__(/*! ./utils */ "./lib/onnxjs/backends/webgl/utils.ts");
+/**
+ * GLSL Library responsible for data types and routines for manipulating
+ * coordinates and mapping to/from tensor indices
+ */
+class CoordsGlslLib extends glsl_definitions_1.GlslLib {
+ constructor(context) {
+ super(context);
+ }
+ getFunctions() {
+ return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, this.offsetToCoords()), this.coordsToOffset()), this.toVec()), this.valueFrom()), this.getCommonUtilFuncs()), this.getInputsSamplingSnippets()), this.getOutputSamplingSnippet());
+ }
+ getCustomTypes() {
+ return {};
+ }
+ /**
+ * Produces a function that can map from
+ * 2D normalzied coordinates (s,t) to a flat offset
+ */
+ offsetToCoords() {
+ const funcName = 'offsetToCoords';
+ return {
+ offsetToCoords: new glsl_definitions_1.GlslLibRoutine(`
+ vec2 ${funcName}(int offset, int width, int height) {
+ int t = offset / width;
+ int s = offset - t*width;
+ vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height);
+ return coords;
+ }
+ `)
+ };
+ }
+ /**
+ * Produces a function that can map from
+ * 2D normalzied coordinates (s,t) to a flat offset
+ */
+ coordsToOffset() {
+ const funcName = 'coordsToOffset';
+ return {
+ coordsToOffset: new glsl_definitions_1.GlslLibRoutine(`
+ int ${funcName}(vec2 coords, int width, int height) {
+ float s = coords.s * float(width);
+ float t = coords.t * float(height);
+ int offset = int(t) * width + int(s);
+ return offset;
+ }
+ `)
+ };
+ }
+ /**
+ * Generates code for output sampler.
+ */
+ getOutputSamplingSnippet() {
+ const outputLayout = this.context.outputTextureLayout;
+ if (outputLayout.isPacked) {
+ return this.getPackedOutputSamplingSnippet(outputLayout);
+ }
+ else {
+ return this.getUnpackedOutputSamplingSnippet(outputLayout);
+ }
+ }
+ /**
+ * Generates code for packed output sampler.
+ */
+ getPackedOutputSamplingSnippet(outputLayout) {
+ const outShape = outputLayout.unpackedShape;
+ const outTexShape = [outputLayout.width, outputLayout.height];
+ const result = {};
+ const funcName = 'getOutputCoords';
+ switch (outShape.length) {
+ case 0:
+ result[funcName] = this.getOutputScalarCoords();
+ break;
+ case 1:
+ result[funcName] = this.getOutputPacked1DCoords(outShape, outTexShape);
+ break;
+ case 2:
+ result[funcName] = this.getOutputPacked2DCoords(outShape, outTexShape);
+ break;
+ case 3:
+ result[funcName] =
+ this.getOutputPacked3DCoords(outShape, outTexShape);
+ break;
+ default:
+ result[funcName] = this.getOutputPackedNDCoords(outShape, outTexShape);
+ }
+ const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
+ // TODO we need this to properly return a packed vec4 from kernels.
+ // Replace all '{glsl.output} = result' with 'setOutput(result)' in all kernels.
+ const floatTextureSetRGBASource = `
+ void setOutput(vec4 val) {
+ ${glsl.output} = val;
+ }
+ `;
+ const floatTextureSetRGBAFuncName = 'floatTextureSetRGBA';
+ result[floatTextureSetRGBAFuncName] = new glsl_definitions_1.GlslLibRoutine(floatTextureSetRGBASource);
+ return result;
+ }
+ /**
+ * Generates code for unpacked output sampler.
+ */
+ getUnpackedOutputSamplingSnippet(outputLayout) {
+ const outShape = outputLayout.unpackedShape;
+ const outTexShape = [outputLayout.width, outputLayout.height];
+ const result = {};
+ const funcName = 'getOutputCoords';
+ switch (outShape.length) {
+ case 0:
+ result[funcName] = this.getOutputScalarCoords();
+ break;
+ case 1:
+ result[funcName] = this.getOutputUnpacked1DCoords(outShape, outTexShape);
+ break;
+ case 2:
+ result[funcName] =
+ this.getOutputUnpacked2DCoords(outShape, outTexShape);
+ break;
+ case 3:
+ result[funcName] =
+ this.getOutputUnpacked3DCoords(outShape, outTexShape);
+ break;
+ case 4:
+ result[funcName] = this.getOutputUnpacked4DCoords(outShape, outTexShape);
+ break;
+ case 5:
+ result[funcName] = this.getOutputUnpacked5DCoords(outShape, outTexShape);
+ break;
+ case 6:
+ result[funcName] = this.getOutputUnpacked6DCoords(outShape, outTexShape);
+ break;
+ default:
+ throw new Error(`Unsupported output dimensionality: ${outShape.length}`);
+ }
+ const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
+ // TODO we need this to properly return a packed vec4 from kernels.
+ // Replace all '{glsl.output} = result' with 'setOutput(result)' in all kernels.
+ const floatTextureSetRSource = `
+ void setOutput(float val) {
+ ${glsl.output} = vec4(val, 0, 0, 0);
+ }
+ `;
+ const floatTextureSetRFuncName = 'floatTextureSetR';
+ result[floatTextureSetRFuncName] = new glsl_definitions_1.GlslLibRoutine(floatTextureSetRSource);
+ return result;
+ }
+ /**
+ * Scalar output coordinates.
+ */
+ getOutputScalarCoords() {
+ return new glsl_definitions_1.GlslLibRoutine(`
+ int getOutputCoords() {
+ return 0;
+ }
+ `);
+ }
+ /**
+ * 1D packed output coordinates.
+ */
+ getOutputPacked1DCoords(shape, texShape) {
+ const packedTexShape = texShape;
+ let source = '';
+ if (packedTexShape[0] === 1) {
+ source = `
+ int getOutputCoords() {
+ return 2 * int(TexCoords.y * ${packedTexShape[1]}.0);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source);
+ }
+ if (packedTexShape[1] === 1) {
+ source = `
+ int getOutputCoords() {
+ return 2 * int(TexCoords.x * ${packedTexShape[0]}.0);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source);
+ }
+ source = `
+ int getOutputCoords() {
+ ivec2 resTexRC = ivec2(TexCoords.xy *
+ vec2(${packedTexShape[0]}, ${packedTexShape[1]}));
+ return 2 * (resTexRC.y * ${packedTexShape[0]} + resTexRC.x);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source);
+ }
+ /**
+ * 2D packed output coordinates.
+ */
+ getOutputPacked2DCoords(shape, texShape) {
+ let source = '';
+ if (util_1.ArrayUtil.arraysEqual(shape, texShape)) {
+ source = `
+ ivec2 getOutputCoords() {
+ return 2 * ivec2(TexCoords.xy * vec2(${texShape[0]}, ${texShape[1]}));
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source);
+ }
+ const packedTexShape = texShape;
+ // texels needed to accommodate a logical row
+ const texelsInLogicalRow = Math.ceil(shape[1] / 2);
+ /**
+ * getOutputCoords
+ *
+ * resTexRC: The rows and columns of the texels. If you move over one
+ * texel to the right in the packed texture, you are moving over one column
+ * (not two).
+ *
+ * index: The texel index
+ */
+ source = `
+ ivec2 getOutputCoords() {
+ ivec2 resTexRC = ivec2(TexCoords.xy *
+ vec2(${packedTexShape[0]}, ${packedTexShape[1]}));
+
+ int index = resTexRC.y * ${packedTexShape[0]} + resTexRC.x;
+
+ // reverse r and c order for packed texture
+ int r = imod(index, ${texelsInLogicalRow}) * 2;
+ int c = 2 * (index / ${texelsInLogicalRow});
+
+ return ivec2(r, c);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source);
+ }
+ /**
+ * 3D packed output coordinates.
+ */
+ getOutputPacked3DCoords(shape, texShape) {
+ const packedTexShape = [texShape[0], texShape[1]];
+ const texelsInLogicalRow = Math.ceil(shape[2] / 2);
+ const texelsInBatch = texelsInLogicalRow * Math.ceil(shape[1] / 2);
+ const source = `
+ ivec3 getOutputCoords() {
+ ivec2 resTexRC = ivec2(TexCoords.xy *
+ vec2(${packedTexShape[0]}, ${packedTexShape[1]}));
+ int index = resTexRC.y * ${packedTexShape[0]} + resTexRC.x;
+
+ int b = index / ${texelsInBatch};
+ index -= b * ${texelsInBatch};
+
+ // reverse r and c order for packed texture
+ int r = imod(index, ${texelsInLogicalRow}) * 2;
+ int c = 2 * (index / ${texelsInLogicalRow});
+
+ return ivec3(b, r, c);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source);
+ }
+ /**
+ * ND packed output coordinates.
+ */
+ getOutputPackedNDCoords(shape, texShape) {
+ const packedTexShape = [texShape[0], texShape[1]];
+ const texelsInLogicalRow = Math.ceil(shape[shape.length - 1] / 2);
+ const texelsInBatch = texelsInLogicalRow * Math.ceil(shape[shape.length - 2] / 2);
+ let texelsInBatchN = texelsInBatch;
+ let batches = '';
+ let coords = 'b, r, c';
+ for (let b = 2; b < shape.length - 1; b++) {
+ texelsInBatchN *= shape[shape.length - b - 1];
+ batches = `
+ int b${b} = index / ${texelsInBatchN};
+ index -= b${b} * ${texelsInBatchN};
+ ` + batches;
+ coords = `b${b}, ` + coords;
+ }
+ const source = `
+ ivec${shape.length} getOutputCoords() {
+ ivec2 resTexRC = ivec2(TexCoords.xy *
+ vec2(${packedTexShape[0]}, ${packedTexShape[1]}));
+ int index = resTexRC.y * ${packedTexShape[0]} + resTexRC.x;
+
+ ${batches}
+
+ int b = index / ${texelsInBatch};
+ index -= b * ${texelsInBatch};
+
+ // reverse r and c order for packed texture
+ int r = imod(index, ${texelsInLogicalRow}) * 2;
+ int c = 2 * (index / ${texelsInLogicalRow});
+
+ return ivec${shape.length}(${coords});
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source);
+ }
+ /**
+ * Unpacked 1D output coordinates.
+ */
+ getOutputUnpacked1DCoords(shape, texShape) {
+ const source = `
+ int getOutputCoords() {
+ ivec2 resTexRC = ivec2(TexCoords.xy *
+ vec2(${texShape[0]}, ${texShape[1]}));
+ return resTexRC.y * ${texShape[0]} + resTexRC.x;
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source);
+ }
+ /**
+ * Unpacked 2D output coordinates.
+ */
+ getOutputUnpacked2DCoords(shape, texShape) {
+ const source = `
+ ivec2 getOutputCoords() {
+ ivec2 resTexRC = ivec2(TexCoords.xy *
+ vec2(${texShape[0]}, ${texShape[1]}));
+ int index = resTexRC.y * ${texShape[0]} + resTexRC.x;
+ int r = index / ${shape[1]};
+ int c = index - r * ${shape[1]};
+ return ivec2(r, c);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source);
+ }
+ /**
+ * Unpacked 3D output coordinates.
+ */
+ getOutputUnpacked3DCoords(shape, texShape) {
+ let source = '';
+ const rank = shape.length;
+ let strides = null;
+ if (rank < 2) {
+ strides = [];
+ }
+ strides = new Array(rank - 1);
+ strides[rank - 2] = shape[rank - 1];
+ for (let i = rank - 3; i >= 0; --i) {
+ strides[i] = strides[i + 1] * shape[i + 1];
+ }
+ const coordsToCompute = ['r', 'c', 'd'];
+ const coordsFromIndexSnippet = strides
+ .map((stride, i) => {
+ const line1 = `int ${coordsToCompute[i]} = index / ${stride}`;
+ const line2 = i === strides.length - 1 ?
+ `int ${coordsToCompute[i + 1]} = index - ${coordsToCompute[i]} * ${stride}` :
+ `index -= ${coordsToCompute[i]} * ${stride}`;
+ return `${line1}; ${line2};`;
+ })
+ .join('');
+ source = `
+ ivec3 getOutputCoords() {
+ ivec2 resTexRC = ivec2(TexCoords.xy *
+ vec2(${texShape[0]}, ${texShape[1]}));
+ int index = resTexRC.y * ${texShape[0]} + resTexRC.x;
+ ${coordsFromIndexSnippet}
+ return ivec3(r, c, d);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source);
+ }
+ /**
+ * Unpacked 4D output coordinates.
+ */
+ getOutputUnpacked4DCoords(shape, texShape) {
+ let source = '';
+ const rank = shape.length;
+ let strides = null;
+ if (rank < 2) {
+ strides = [];
+ }
+ strides = new Array(rank - 1);
+ strides[rank - 2] = shape[rank - 1];
+ for (let i = rank - 3; i >= 0; --i) {
+ strides[i] = strides[i + 1] * shape[i + 1];
+ }
+ const coordsToCompute = ['r', 'c', 'd', 'd2'];
+ const coordsFromIndexSnippet = strides
+ .map((stride, i) => {
+ const line1 = `int ${coordsToCompute[i]} = index / ${stride}`;
+ const line2 = i === strides.length - 1 ?
+ `int ${coordsToCompute[i + 1]} = index - ${coordsToCompute[i]} * ${stride}` :
+ `index -= ${coordsToCompute[i]} * ${stride}`;
+ return `${line1}; ${line2};`;
+ })
+ .join('');
+ source = `
+ ivec4 getOutputCoords() {
+ ivec2 resTexRC = ivec2(TexCoords.xy *
+ vec2(${texShape[0]}, ${texShape[1]}));
+ int index = resTexRC.y * ${texShape[0]} + resTexRC.x;
+ ${coordsFromIndexSnippet}
+ return ivec4(r, c, d, d2);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source);
+ }
+ /**
+ * Unpacked 5D output coordinates.
+ */
+ getOutputUnpacked5DCoords(shape, texShape) {
+ let source = '';
+ const rank = shape.length;
+ let strides = null;
+ if (rank < 2) {
+ strides = [];
+ }
+ strides = new Array(rank - 1);
+ strides[rank - 2] = shape[rank - 1];
+ for (let i = rank - 3; i >= 0; --i) {
+ strides[i] = strides[i + 1] * shape[i + 1];
+ }
+ const coordsToCompute = ['r', 'c', 'd', 'd2', 'd3'];
+ const coordsFromIndexSnippet = strides
+ .map((stride, i) => {
+ const line1 = `int ${coordsToCompute[i]} = index / ${stride}`;
+ const line2 = i === strides.length - 1 ?
+ `int ${coordsToCompute[i + 1]} = index - ${coordsToCompute[i]} * ${stride}` :
+ `index -= ${coordsToCompute[i]} * ${stride}`;
+ return `${line1}; ${line2};`;
+ })
+ .join('');
+ source = `
+ ivec5 getOutputCoords() {
+ ivec2 resTexRC = ivec2(TexCoords.xy *
+ vec2(${texShape[0]}, ${texShape[1]}));
+ int index = resTexRC.y * ${texShape[0]} + resTexRC.x;
+ ${coordsFromIndexSnippet}
+ return ivec5(r, c, d, d2, d3);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source);
+ }
+ /**
+ * Unpacked 6D output coordinates.
+ */
+ getOutputUnpacked6DCoords(shape, texShape) {
+ let source = '';
+ const rank = shape.length;
+ let strides = null;
+ if (rank < 2) {
+ strides = [];
+ }
+ strides = new Array(rank - 1);
+ strides[rank - 2] = shape[rank - 1];
+ for (let i = rank - 3; i >= 0; --i) {
+ strides[i] = strides[i + 1] * shape[i + 1];
+ }
+ const coordsToCompute = ['r', 'c', 'd', 'd2', 'd3', 'd4'];
+ const coordsFromIndexSnippet = strides
+ .map((stride, i) => {
+ const line1 = `int ${coordsToCompute[i]} = index / ${stride}`;
+ const line2 = i === strides.length - 1 ?
+ `int ${coordsToCompute[i + 1]} = index - ${coordsToCompute[i]} * ${stride}` :
+ `index -= ${coordsToCompute[i]} * ${stride}`;
+ return `${line1}; ${line2};`;
+ })
+ .join('');
+ source = `
+ ivec6 getOutputCoords() {
+ ivec2 resTexRC = ivec2(TexCoords.xy *
+ vec2(${texShape[0]}, ${texShape[1]}));
+ int index = resTexRC.y * ${texShape[0]} + resTexRC.x;
+ ${coordsFromIndexSnippet}
+ return ivec6(r, c, d, d2, d3, d4);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source);
+ }
+ /**
+ * Generates code for common UV coords computation utility functions.
+ */
+ getCommonUtilFuncs() {
+ const result = {};
+ let funcName = 'uvFromFlat';
+ result[funcName] = new glsl_definitions_1.GlslLibRoutine(`
+ vec2 uvFromFlat(int texNumR, int texNumC, int index) {
+ int texC = index / texNumR;
+ int texR = index - texC * texNumR;
+ // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to
+ // v.
+ return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC);
+ }
+ `);
+ funcName = 'packedUVfrom1D';
+ result[funcName] = new glsl_definitions_1.GlslLibRoutine(`
+ vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
+ int texelIndex = index / 2;
+ int texR = texelIndex / texNumC;
+ int texC = texelIndex - texR * texNumC;
+ return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
+ }
+ `);
+ funcName = 'packedUVfrom2D';
+ result[funcName] = new glsl_definitions_1.GlslLibRoutine(`
+ vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) {
+ int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
+ int texR = texelIndex / texNumC;
+ int texC = texelIndex - texR * texNumC;
+ return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
+ }
+ `);
+ funcName = 'packedUVfrom3D';
+ result[funcName] = new glsl_definitions_1.GlslLibRoutine(`
+ vec2 packedUVfrom3D(int texNumR, int texNumC,
+ int texelsInBatch, int texelsInLogicalRow, int b,
+ int row, int col) {
+ int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
+ int texR = index / texNumC;
+ int texC = index - texR * texNumC;
+ return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
+ }
+ `);
+ funcName = 'sampleTexture';
+ const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
+ result[funcName] = new glsl_definitions_1.GlslLibRoutine(`
+ float sampleTexture(sampler2D textureSampler, vec2 uv) {
+ return ${glsl.texture2D}(textureSampler, uv).r;
+ }`);
+ return result;
+ }
+ /**
+ * Constructing snippets for inputs
+ */
+ getInputsSamplingSnippets() {
+ const result = {};
+ const outputLayout = this.context.outputTextureLayout;
+ this.context.programInfo.inputNames.forEach((samplerName, i) => {
+ const inputLayout = this.context.inputTextureLayouts[i];
+ const funcName = (0, utils_1.generateShaderFuncNameFromInputSamplerName)(samplerName);
+ if (inputLayout.isPacked) {
+ result[funcName] = this.getPackedSamplerFromInput(funcName, samplerName, inputLayout);
+ }
+ else {
+ result[funcName] = this.getUnpackedSamplerFromInput(funcName, samplerName, inputLayout);
+ }
+ const outCoordFuncName = (0, utils_1.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(samplerName);
+ if (inputLayout.unpackedShape.length <= outputLayout.unpackedShape.length) {
+ if (inputLayout.isPacked) {
+ result[outCoordFuncName] =
+ this.getPackedSamplerAtOutputCoords(outCoordFuncName, inputLayout, outputLayout, samplerName);
+ }
+ else {
+ result[outCoordFuncName] =
+ this.getUnpackedSamplerAtOutputCoords(outCoordFuncName, inputLayout, outputLayout, samplerName);
+ }
+ }
+ });
+ return result;
+ }
+ /**
+ * Constructing snippets for output coordinates of samplers
+ */
+ getPackedSamplerAtOutputCoords(funcName, inputLayout, outputLayout, name) {
+ const inShape = inputLayout.unpackedShape;
+ const outShape = outputLayout.unpackedShape;
+ const texName = name;
+ const texFuncSnippet = (0, utils_1.generateShaderFuncNameFromInputSamplerName)(texName);
+ const inRank = inShape.length;
+ const outRank = outShape.length;
+ const broadcastDims = util_1.BroadcastUtil.getBroadcastDims(inShape, outShape);
+ const type = (0, utils_1.getCoordsDataType)(outRank);
+ const rankDiff = outRank - inRank;
+ let coordsSnippet;
+ const fields = (0, utils_1.getGlChannels)();
+ if (inRank === 0) {
+ coordsSnippet = '';
+ }
+ else if (outRank < 2 && broadcastDims.length >= 1) {
+ coordsSnippet = 'coords = 0;';
+ }
+ else {
+ coordsSnippet = broadcastDims.map(d => `coords.${fields[d + rankDiff]} = 0;`).join('\n');
+ }
+ let unpackedCoordsSnippet = '';
+ if (outRank < 2 && inRank > 0) {
+ unpackedCoordsSnippet = 'coords';
+ }
+ else {
+ unpackedCoordsSnippet = inShape.map((s, i) => `coords.${fields[i + rankDiff]}`).join(', ');
+ }
+ let output = 'return outputValue;';
+ const inSize = util_1.ShapeUtil.size(inShape);
+ const isInputScalar = inSize === 1;
+ const outSize = util_1.ShapeUtil.size(outShape);
+ const isOutputScalar = outSize === 1;
+ if (inRank === 1 && !isInputScalar && !isOutputScalar) {
+ output = `
+ return vec4(outputValue.xy, outputValue.xy);
+ `;
+ }
+ else if (isInputScalar && !isOutputScalar) {
+ if (outRank === 1) {
+ output = `
+ return vec4(outputValue.x, outputValue.x, 0., 0.);
+ `;
+ }
+ else {
+ output = `
+ return vec4(outputValue.x);
+ `;
+ }
+ }
+ else if (broadcastDims.length) {
+ const rows = inRank - 2;
+ const cols = inRank - 1;
+ if (broadcastDims.indexOf(rows) > -1 && broadcastDims.indexOf(cols) > -1) {
+ output = 'return vec4(outputValue.x);';
+ }
+ else if (broadcastDims.indexOf(rows) > -1) {
+ output = 'return vec4(outputValue.x, outputValue.y, ' +
+ 'outputValue.x, outputValue.y);';
+ }
+ else if (broadcastDims.indexOf(cols) > -1) {
+ output = 'return vec4(outputValue.xx, outputValue.zz);';
+ }
+ }
+ const swapLastDimsSnippet = `
+ int lastDim = coords.${fields[outRank - 1]};
+ coords.${fields[outRank - 1]} = coords.${fields[outRank - 2]};
+ coords.${fields[outRank - 2]} = lastDim;
+ `;
+ const source = `
+ vec4 ${funcName}() {
+ ${type} coords = getOutputCoords();
+ ${swapLastDimsSnippet}
+ ${coordsSnippet}
+ vec4 outputValue = ${texFuncSnippet}(${unpackedCoordsSnippet});
+ ${output}
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.getOutputCoords']);
+ }
+ /**
+ * Constructing snippets for unpacked output coordinates of samplers
+ */
+ getUnpackedSamplerAtOutputCoords(funcName, inputLayout, outputLayout, name) {
+ const outTexShape = [outputLayout.width, outputLayout.height];
+ const inTexShape = [inputLayout.width, inputLayout.height];
+ const inRank = inputLayout.unpackedShape.length;
+ const outRank = outputLayout.unpackedShape.length;
+ const inShape = inputLayout.unpackedShape;
+ const outShape = outputLayout.unpackedShape;
+ const texFuncSnippet = (0, utils_1.generateShaderFuncNameFromInputSamplerName)(name);
+ if (inRank === outRank && util_1.ArrayUtil.arraysEqual(inTexShape, outTexShape)) {
+ const source = `
+ float ${funcName}() {
+ return sampleTexture(${name}, TexCoords);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture']);
+ }
+ const type = (0, utils_1.getCoordsDataType)(outRank);
+ const broadcastDims = util_1.BroadcastUtil.getBroadcastDims(inShape, outShape);
+ const rankDiff = outRank - inRank;
+ let coordsSnippet;
+ const fields = (0, utils_1.getGlChannels)();
+ if (inRank === 0) {
+ coordsSnippet = '';
+ }
+ else if (outRank < 2 && broadcastDims.length >= 1) {
+ coordsSnippet = 'coords = 0;';
+ }
+ else {
+ coordsSnippet = broadcastDims.map(d => `coords.${fields[d + rankDiff]} = 0;`).join('\n');
+ }
+ let unpackedCoordsSnippet = '';
+ if (outRank < 2 && inRank > 0) {
+ unpackedCoordsSnippet = 'coords';
+ }
+ else {
+ unpackedCoordsSnippet = inputLayout.unpackedShape.map((s, i) => `coords.${fields[i + rankDiff]}`).join(', ');
+ }
+ const source = `
+ float ${funcName}() {
+ ${type} coords = getOutputCoords();
+ ${coordsSnippet}
+ return ${texFuncSnippet}(${unpackedCoordsSnippet});
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.getOutputCoords']);
+ }
+ /**
+ * Constructing snippets for packed operations.
+ */
+ getPackedSamplerFromInput(funcName, name, inputLayout) {
+ switch (inputLayout.unpackedShape.length) {
+ case 0:
+ return this.getPackedSamplerScalar(funcName, name);
+ case 1:
+ return this.getPackedSampler1D(funcName, name, inputLayout);
+ case 2:
+ return this.getPackedSampler2D(funcName, name, inputLayout);
+ case 3:
+ return this.getPackedSampler3D(funcName, name, inputLayout);
+ default:
+ return this.getPackedSamplerND(funcName, name, inputLayout);
+ }
+ }
+ /**
+ * Constructing snippets for unpacked operations.
+ */
+ getUnpackedSamplerFromInput(funcName, name, inputLayout) {
+ const shape = inputLayout.unpackedShape;
+ switch (shape.length) {
+ case 0:
+ return this.getUnpackedSamplerScalar(funcName, name, inputLayout);
+ case 1:
+ return this.getUnpackedSampler1D(funcName, name, inputLayout);
+ case 2:
+ return this.getUnpackedSampler2D(funcName, name, inputLayout);
+ case 3:
+ return this.getUnpackedSampler3D(funcName, name, inputLayout);
+ case 4:
+ return this.getUnpackedSampler4D(funcName, name, inputLayout);
+ case 5:
+ return this.getUnpackedSampler5D(funcName, name, inputLayout);
+ case 6:
+ return this.getUnpackedSampler6D(funcName, name, inputLayout);
+ default:
+ // TODO support more dimensionalities
+ throw new Error(`Unsupported dimension ${shape.length}-D`);
+ }
+ }
+ /**
+ * Packed scalar snippet.
+ */
+ getPackedSamplerScalar(funcName, name) {
+ const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
+ const source = `
+ vec4 ${funcName}() {
+ return ${glsl.texture2D}(${name}, halfCR);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source);
+ }
+ /**
+ * Packed 1D snippet.
+ */
+ getPackedSampler1D(funcName, name, inputLayout) {
+ const texShape = [inputLayout.width, inputLayout.height];
+ const packedTexShape = [texShape[1], texShape[0]];
+ const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
+ const packedSampler = `vec4 ${funcName}(int index) {
+ vec2 uv = packedUVfrom1D(
+ ${packedTexShape[0]}, ${packedTexShape[1]}, index);
+ return ${glsl.texture2D}(${name}, uv);
+ }`;
+ const source = packedSampler;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.packedUVfrom1D']);
+ }
+ /**
+ * Packed 2D snippet.
+ */
+ getPackedSampler2D(funcName, name, inputLayout) {
+ const shape = inputLayout.unpackedShape;
+ const texShape = [inputLayout.width, inputLayout.height];
+ const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
+ const texNumR = texShape[0];
+ const texNumC = texShape[1];
+ if (texShape != null && util_1.ArrayUtil.arraysEqual(shape, texShape)) {
+ const packedSampler = `vec4 ${funcName}(int row, int col) {
+ vec2 uv = (vec2(col, row) + halfCR) / vec2(${texNumC}.0, ${texNumR}.0);
+ return ${glsl.texture2D}(${name}, uv);
+ }`;
+ return new glsl_definitions_1.GlslLibRoutine(packedSampler);
+ }
+ const packedTexShape = texShape;
+ const valuesPerRow = Math.ceil(shape[1] / 2);
+ const packedSampler = `vec4 ${funcName}(int row, int col) {
+ vec2 uv = packedUVfrom2D(${packedTexShape[1]}, ${packedTexShape[0]}, ${valuesPerRow}, row, col);
+ return ${glsl.texture2D}(${name}, uv);
+ }`;
+ const source = packedSampler;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.packedUVfrom2D']);
+ }
+ /**
+ * Packed 3D snippet.
+ */
+ getPackedSampler3D(funcName, name, inputLayout) {
+ const shape = inputLayout.unpackedShape;
+ const texShape = [inputLayout.width, inputLayout.height];
+ const packedTexShape = [texShape[0], texShape[1]];
+ const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
+ if (shape[0] === 1) {
+ const squeezedShape = shape.slice(1);
+ const keptDims = [1, 2];
+ const newInputShape = (0, utils_1.squeezeInputShape)(shape, squeezedShape);
+ const params = ['b', 'row', 'col'];
+ // Deep copy of input texture layout.
+ const newInputLayout = JSON.parse(JSON.stringify(inputLayout));
+ newInputLayout.unpackedShape = newInputShape;
+ const samplerRoutine = this.getPackedSamplerFromInput(funcName, name, newInputLayout);
+ const packedSampler = `${samplerRoutine.routineBody}
+ vec4 ${funcName}(int b, int row, int col) {
+ return ${funcName}(${(0, utils_1.getSqueezedParams)(params, keptDims)});
+ } `;
+ const source = packedSampler;
+ return new glsl_definitions_1.GlslLibRoutine(source, samplerRoutine.dependencies);
+ }
+ const texNumR = packedTexShape[0];
+ const texNumC = packedTexShape[1];
+ const valuesPerRow = Math.ceil(shape[2] / 2);
+ const texelsInBatch = valuesPerRow * Math.ceil(shape[1] / 2);
+ const packedSampler = `vec4 ${funcName}(int b, int row, int col) {
+ vec2 uv = packedUVfrom3D(
+ ${texNumC}, ${texNumR}, ${texelsInBatch}, ${valuesPerRow}, b, row, col);
+ return ${glsl.texture2D}(${name}, uv);}`;
+ const source = packedSampler;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.packedUVfrom3D']);
+ }
+ /*
+ * Packed ND snippet.
+ */
+ getPackedSamplerND(funcName, name, inputLayout) {
+ const shape = inputLayout.unpackedShape;
+ const rank = shape.length;
+ const texShape = [inputLayout.width, inputLayout.height];
+ const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
+ const packedTexShape = [texShape[0], texShape[1]];
+ const texNumR = packedTexShape[1];
+ const texNumC = packedTexShape[0];
+ const valuesPerRow = Math.ceil(shape[rank - 1] / 2);
+ let texelsInBatch = valuesPerRow * Math.ceil(shape[rank - 2] / 2);
+ let params = 'int b, int row, int col';
+ let index = `b * ${texelsInBatch} + (row / 2) * ${valuesPerRow} + (col / 2)`;
+ for (let b = 2; b < rank - 1; b++) {
+ params = `int b${b}, ` + params;
+ texelsInBatch *= shape[rank - b - 1];
+ index = `b${b} * ${texelsInBatch} + ` + index;
+ }
+ const packedSampler = `vec4 ${funcName}(${params}) {
+ int index = ${index};
+ int texR = index / ${texNumC};
+ int texC = index - texR * ${texNumC};
+ vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${texNumC}, ${texNumR});
+ return ${glsl.texture2D}(${name}, uv);
+ }`;
+ const source = packedSampler;
+ return new glsl_definitions_1.GlslLibRoutine(source);
+ }
+ /**
+ * Unpacked scalar snippet.
+ */
+ getUnpackedSamplerScalar(funcName, name, inputLayout) {
+ const [texNumR, texNumC] = [inputLayout.width, inputLayout.height];
+ if (texNumR === 1 && texNumC === 1) {
+ const source = `
+ float ${funcName}() {
+ return sampleTexture(${name}, halfCR);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture']);
+ }
+ const source = `
+ float ${funcName}() {
+ int offset_${name} = coordsToOffset(TexCoords, ${texNumR}, ${texNumC});
+ vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, offset_${name});
+ return sampleTexture(${name}, uv);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.uvFromFlat', 'coordinates.sampleTexture', 'coordinates.coordsToOffset']);
+ }
+ /**
+ * Unpacked 1D snippet.
+ */
+ getUnpackedSampler1D(funcName, name, inputLayout) {
+ const tNumR = inputLayout.width;
+ const tNumC = inputLayout.height;
+ if (tNumC === 1 && tNumR === 1) {
+ const source = `
+ float ${funcName}(int index) {
+ return sampleTexture(${name}, halfCR);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture']);
+ }
+ if (tNumC === 1) {
+ const source = `
+ float ${funcName}(int index) {
+ vec2 uv = vec2((float(index) + 0.5) / ${tNumR}.0, 0.5);
+ return sampleTexture(${name}, uv);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture']);
+ }
+ if (tNumR === 1) {
+ const source = `
+ float ${funcName}(int index) {
+ vec2 uv = vec2(0.5, (float(index) + 0.5) / ${tNumC}.0);
+ return sampleTexture(${name}, uv);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture']);
+ }
+ const source = `
+ float ${funcName}(int index) {
+ vec2 uv = uvFromFlat(${tNumR}, ${tNumC}, index);
+ return sampleTexture(${name}, uv);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.uvFromFlat', 'coordinates.sampleTexture']);
+ }
+ /**
+ * Unpacked 2D snippet.
+ */
+ getUnpackedSampler2D(funcName, name, inputLayout) {
+ const shape = inputLayout.unpackedShape;
+ // TODO: modify row/col order for other dimensions.
+ const texShape = [inputLayout.height, inputLayout.width];
+ if (texShape != null && util_1.ArrayUtil.arraysEqual(shape, texShape)) {
+ const texNumR = texShape[1];
+ const texNumC = texShape[0];
+ const source = `
+ float ${funcName}(int row, int col) {
+ vec2 uv = (vec2(row, col) + halfCR) / vec2(${texNumR}.0, ${texNumC}.0);
+ return sampleTexture(${name}, uv);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture']);
+ }
+ const { newShape, keptDims } = (0, texture_layout_strategy_1.squeezeShape)(shape);
+ const squeezedShape = newShape;
+ if (squeezedShape.length < shape.length) {
+ const newInputShape = (0, utils_1.squeezeInputShape)(shape, squeezedShape);
+ // Deep copy of input texture layout.
+ const newInputLayout = JSON.parse(JSON.stringify(inputLayout));
+ newInputLayout.unpackedShape = newInputShape;
+ const params = ['col', 'row'];
+ const source = `
+ ${this.getUnpackedSamplerFromInput(funcName, name, newInputLayout).routineBody}
+ float ${funcName}(int row, int col) {
+ return ${funcName}(${(0, utils_1.getSqueezedParams)(params, keptDims)});
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture']);
+ }
+ const texNumR = texShape[1];
+ const texNumC = texShape[0];
+ if (texNumC === 1) {
+ const source = `
+ float ${funcName}(int row, int col) {
+ int offset_${name} = coordsToOffset(TexCoords, ${texNumR}, ${texNumC});
+ float index = dot(vec3(row, col, offset_${name}), vec3(${shape[1]}, 1, 1));
+ vec2 uv = vec2(0.5, (index + 0.5) / ${texNumR}.0);
+ return sampleTexture(${name}, uv);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture', 'coordinates.coordsToOffset']);
+ }
+ if (texNumR === 1) {
+ const source = `
+ float ${funcName}(int row, int col) {
+ int offset_${name} = coordsToOffset(TexCoords, ${texNumR}, ${texNumC});
+ float index = dot(vec3(row, col, offset_${name}), vec3(${shape[1]}, 1, 1));
+ vec2 uv = vec2((index + 0.5) / ${texNumC}.0, 0.5);
+ return sampleTexture(${name}, uv);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture', 'coordinates.coordsToOffset']);
+ }
+ const source = `
+ float ${funcName}(int row, int col) {
+ int index = col * ${shape[1]} + row;
+ vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
+ return sampleTexture(${name}, uv);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.uvFromFlat', 'coordinates.sampleTexture', 'coordinates.coordsToOffset']);
+ }
+ /**
+ * Unpacked 3D snippet.
+ */
+ getUnpackedSampler3D(funcName, name, inputLayout) {
+ const shape = inputLayout.unpackedShape;
+ const stride0 = shape[1] * shape[2];
+ const stride1 = shape[2];
+ const { newShape, keptDims } = (0, texture_layout_strategy_1.squeezeShape)(shape);
+ const squeezedShape = newShape;
+ if (squeezedShape.length < shape.length) {
+ const newInputShape = (0, utils_1.squeezeInputShape)(shape, squeezedShape);
+ const params = ['batch', 'col', 'row'];
+ // Deep copy of input texture layout.
+ const newInputLayout = JSON.parse(JSON.stringify(inputLayout));
+ newInputLayout.unpackedShape = newInputShape;
+ const routine = this.getUnpackedSamplerFromInput(funcName, name, newInputLayout);
+ // TODO: revisit the logic here to make it simpler
+ const revDims = keptDims.reverse();
+ const source = `
+ ${routine.routineBody}
+ float ${funcName}(int batch, int row, int col) {
+ return ${funcName}(${(0, utils_1.getSqueezedParams)(params, revDims)});
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, routine.dependencies);
+ }
+ const texNumR = inputLayout.width;
+ const texNumC = inputLayout.height;
+ const source = `
+ float ${funcName}(int depth, int row, int col) {
+ // Explicitly use integer operations as dot() only works on floats.
+ int index = depth * ${stride0} + col * ${stride1} + row;
+ vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
+ return sampleTexture(${name}, uv);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.uvFromFlat', 'coordinates.sampleTexture', 'coordinates.coordsToOffset']);
+ }
+ /**
+ * Unpacked 4D snippet.
+ */
+ getUnpackedSampler4D(funcName, name, inputLayout) {
+ const shape = inputLayout.unpackedShape;
+ const stride2 = shape[3];
+ const stride1 = shape[2] * stride2;
+ const stride0 = shape[1] * stride1;
+ //
+ // TODO: re-enable this shortcut once the index calculation bug is fixed.
+ //
+ // const {newShape, keptDims} = squeezeShape(shape as number[]);
+ // if (newShape.length < shape.length) {
+ // const newInputShape = squeezeInputShape(shape, newShape);
+ // const params = ['row', 'col', 'depth', 'depth2'];
+ // // Deep copy of input texture layout.
+ // const newInputLayout: TextureLayout = JSON.parse(JSON.stringify(inputLayout));
+ // newInputLayout.unpackedShape = newInputShape;
+ // const source = `
+ // ${this.getUnpackedSamplerFromInput(funcName, name, newInputLayout).routineBody}
+ // float ${funcName}(int row, int col, int depth, int depth2) {
+ // return ${funcName}(${getSqueezedParams(params, keptDims)});
+ // }
+ // `;
+ // return new GlslLibRoutine(
+ // source, ['coordinates.uvFromFlat', 'coordinates.sampleTexture', 'coordinates.coordsToOffset']);
+ // }
+ const texNumR = inputLayout.width;
+ const texNumC = inputLayout.height;
+ const source = `
+ float ${funcName}(int row, int col, int depth, int depth2) {
+ int index = row * ${stride0} + col * ${stride1} +
+ depth2 * ${stride2} + depth;
+ vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
+ return sampleTexture(${name}, uv);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.uvFromFlat', 'coordinates.sampleTexture']);
+ }
+ /**
+ * Unpacked 5D snippet.
+ */
+ getUnpackedSampler5D(funcName, name, inputLayout) {
+ const shape = inputLayout.unpackedShape;
+ const stride3 = shape[4];
+ const stride2 = shape[3] * stride3;
+ const stride1 = shape[2] * stride2;
+ const stride0 = shape[1] * stride1;
+ const { newShape, keptDims } = (0, texture_layout_strategy_1.squeezeShape)(shape);
+ if (newShape.length < shape.length) {
+ const newInputShape = (0, utils_1.squeezeInputShape)(shape, newShape);
+ const params = ['row', 'col', 'depth', 'depth2', 'depth3'];
+ // Deep copy of input texture layout.
+ const newInputLayout = JSON.parse(JSON.stringify(inputLayout));
+ newInputLayout.unpackedShape = newInputShape;
+ const source = `
+ ${this.getUnpackedSamplerFromInput(funcName, name, newInputLayout).routineBody}
+ float ${funcName}(int row, int col, int depth, int depth2, int depth3) {
+ return ${funcName}(${(0, utils_1.getSqueezedParams)(params, keptDims)});
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture', 'coordinates.uvFromFlat']);
+ }
+ const texNumR = inputLayout.width;
+ const texNumC = inputLayout.height;
+ const source = `
+ float ${funcName}(int row, int col, int depth, int depth2, int depth3) {
+ int index = row * ${stride0} + col * ${stride1} + depth * ${stride2} +
+ depth3 * ${stride3} + depth2;
+ vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
+ return sampleTexture(${name}, uv);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture', 'coordinates.uvFromFlat']);
+ }
+ /**
+ * Unpacked 6D snippet.
+ */
+ getUnpackedSampler6D(funcName, name, inputLayout) {
+ const shape = inputLayout.unpackedShape;
+ const stride4 = shape[5];
+ const stride3 = shape[4] * stride4;
+ const stride2 = shape[3] * stride3;
+ const stride1 = shape[2] * stride2;
+ const stride0 = shape[1] * stride1;
+ const { newShape, keptDims } = (0, texture_layout_strategy_1.squeezeShape)(shape);
+ if (newShape.length < shape.length) {
+ const newInputShape = (0, utils_1.squeezeInputShape)(shape, newShape);
+ const params = ['row', 'col', 'depth', 'depth2', 'depth3', 'depth4'];
+ // Deep copy of input texture layout.
+ const newInputLayout = JSON.parse(JSON.stringify(inputLayout));
+ newInputLayout.unpackedShape = newInputShape;
+ const source = `
+ ${this.getUnpackedSamplerFromInput(funcName, name, newInputLayout).routineBody}
+ float ${funcName}(int row, int col, int depth,
+ int depth2, int depth3, int depth4) {
+ return ${funcName}(${(0, utils_1.getSqueezedParams)(params, keptDims)});
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture', 'coordinates.uvFromFlat']);
+ }
+ const texNumR = inputLayout.width;
+ const texNumC = inputLayout.height;
+ const source = `
+ float ${funcName}(int row, int col, int depth,
+ int depth2, int depth3, int depth4) {
+ int index = row * ${stride0} + col * ${stride1} + depth * ${stride2} +
+ depth2 * ${stride3} + depth3 * ${stride4} + depth4;
+ vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
+ return sampleTexture(${name}, uv);
+ }
+ `;
+ return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.uvFromFlat', 'coordinates.sampleTexture', 'coordinates.coordsToOffset']);
+ }
+ /**
+ * This is the main function to map from the given texture coordiantes (s,t)
+ * to logical indices for the output
+ * There will only be one single variation of this
+ * Also see coordsToOffset and offsetToIndices for input-specific versions
+ */
+ toVec() {
+ const output = this.context.outputTextureLayout;
+ const rank = output.shape.length;
+ const strides = output.strides;
+ const xScale = output.width;
+ const yScale = output.height;
+ const stridesBlock = [];
+ for (let i = 0; i < rank - 1; ++i) {
+ stridesBlock.push(`
+ c[${i}] = offset / ${strides[i]};`);
+ stridesBlock.push(`
+ offset -= c[${i}] * ${strides[i]};`);
+ }
+ stridesBlock.push(`
+ c[${rank - 1}] = offset;`);
+ const body = `
+ void toVec(vec2 texCoords, out int c[${rank}]) {
+ int offset = coordsToOffset(texCoords, ${xScale}, ${yScale});
+ ${stridesBlock.join('')}
+ }
+ void toVec(int offset, out int c[${rank}]) {
+ ${stridesBlock.join('')}
+ }
+ `;
+ return { toVec: new glsl_definitions_1.GlslLibRoutine(body, ['coordinates.coordsToOffset']) };
+ }
+ /**
+ * These are value getter functions generated for each input
+ * Each function is hardwired to the name and dimensions of the input
+ * An '_T' variation is also produced which accesses values as if the
+ * input was transposed
+ */
+ valueFrom() {
+ const result = {};
+ this.context.programInfo.inputNames.forEach((name, i) => {
+ const layout = this.context.inputTextureLayouts[i];
+ const shape = layout.unpackedShape.length > 0 ? layout.unpackedShape : layout.shape;
+ const rank = shape.length;
+ let funcName = `_${name}`;
+ result[funcName] = new glsl_definitions_1.GlslLibRoutine(this.getValueFromSingle(name, rank, layout.width, layout.height, false), [`shapeUtils.indicesToOffset${funcName}`, 'coordinates.offsetToCoords', 'fragcolor.getColorAsFloat']);
+ funcName = funcName + '_T';
+ result[funcName] = new glsl_definitions_1.GlslLibRoutine(this.getValueFromSingle(name, rank, layout.width, layout.height, true), [`shapeUtils.indicesToOffset${funcName}`, 'coordinates.offsetToCoords', 'fragcolor.getColorAsFloat']);
+ });
+ return result;
+ }
+ /**
+ * Produces one value getter function for the name and rank given
+ * If a transpose is set proper offsetToCoords mapping will be used
+ * @param name name of the function
+ * @param rank rank of the input
+ * @param transpose whether or not should generate a transpose variation
+ */
+ getValueFromSingle(varName, rank, width, height, transpose) {
+ let name = `_${varName}`;
+ if (transpose) {
+ name = name + '_T';
+ }
+ const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
+ return `
+ float ${name}(int m[${rank}]) {
+ int offset = indicesToOffset${name}(m);
+ vec2 coords = offsetToCoords(offset, ${width}, ${height});
+ float value = getColorAsFloat(${glsl.texture2D}(${varName}, coords));
+ return value;
+ }
+ `;
+ }
+ /**
+ * Produces a packed value getter function for the name and rank given
+ * If a transpose is set proper offsetToCoords mapping will be used
+ * @param name name of the function
+ * @param rank rank of the input
+ * @param transpose whether or not should generate a transpose variation
+ */
+ getPackedValueFrom(varName, rank, width, height, transpose) {
+ let name = `_${varName}_Pack`;
+ if (transpose) {
+ name = name + '_T';
+ }
+ const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
+ return `
+ vec4 ${name}(int m[${rank}]) {
+ int offset = indicesToOffset_${varName}(m);
+ vec2 coords = offsetToCoords(offset, ${width}, ${height});
+ return ${glsl.texture2D}(${varName}, coords);
+ }
+ `;
+ }
+}
+exports.CoordsGlslLib = CoordsGlslLib;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/glsl-definitions.ts":
+/*!*******************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/glsl-definitions.ts ***!
+ \*******************************************************/
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.TopologicalSortGlslRoutines = exports.GlslLibRoutineNode = exports.GlslLibRoutine = exports.GlslLib = exports.GlslContext = exports.FunctionType = void 0;
+/* eslint-disable @typescript-eslint/naming-convention */
+var FunctionType;
+(function (FunctionType) {
+ FunctionType[FunctionType["ValueBased"] = 0] = "ValueBased";
+ FunctionType[FunctionType["Positional"] = 1] = "Positional";
+})(FunctionType = exports.FunctionType || (exports.FunctionType = {}));
+class GlslContext {
+ constructor(glContext, programInfo, inputTextureLayouts, outputTextureLayout) {
+ this.glContext = glContext;
+ this.programInfo = programInfo;
+ this.inputTextureLayouts = inputTextureLayouts;
+ this.outputTextureLayout = outputTextureLayout;
+ }
+}
+exports.GlslContext = GlslContext;
+class GlslLib {
+ constructor(context) {
+ this.context = context;
+ }
+}
+exports.GlslLib = GlslLib;
+// abstraction to represent a GLSL library routine and it's dependencies
+class GlslLibRoutine {
+ constructor(routineBody, dependencies) {
+ this.routineBody = routineBody;
+ this.dependencies = dependencies;
+ }
+}
+exports.GlslLibRoutine = GlslLibRoutine;
+// abstraction to represent a GLSL library routine and it's dependencies AS GRAPH Nodes
+// this level of abstraction is used to topologically sort routines before fragment shade inclusion
+class GlslLibRoutineNode {
+ constructor(name, routineBody, dependencies) {
+ this.name = name;
+ if (dependencies) {
+ this.dependencies = dependencies;
+ }
+ else {
+ this.dependencies = [];
+ }
+ if (routineBody) {
+ this.routineBody = routineBody;
+ }
+ }
+ addDependency(node) {
+ if (node) {
+ this.dependencies.push(node);
+ }
+ }
+}
+exports.GlslLibRoutineNode = GlslLibRoutineNode;
+// topologically sort GLSL library routines (graph nodes abstraction) before shader script inclusion
+class TopologicalSortGlslRoutines {
+ static returnOrderedNodes(nodes) {
+ if (!nodes || nodes.length === 0) {
+ return [];
+ }
+ if (nodes.length === 1) {
+ return nodes;
+ }
+ const cycleCheck = new Set();
+ const alreadyTraversed = new Set();
+ const result = new Array();
+ this.createOrderedNodes(nodes, cycleCheck, alreadyTraversed, result);
+ return result;
+ }
+ static createOrderedNodes(graphNodes, cycleCheck, alreadyTraversed, result) {
+ for (let i = 0; i < graphNodes.length; ++i) {
+ this.dfsTraverse(graphNodes[i], cycleCheck, alreadyTraversed, result);
+ }
+ }
+ static dfsTraverse(root, cycleCheck, alreadyTraversed, result) {
+ // if this root has already been traversed return
+ if (!root || alreadyTraversed.has(root.name)) {
+ return;
+ }
+ // cyclic dependency has been detected
+ if (cycleCheck.has(root.name)) {
+ throw new Error('Cyclic dependency detected. Can\'t topologically sort routines needed for shader.');
+ }
+ // hold this node to detect cycles if any
+ cycleCheck.add(root.name);
+ // traverse children in a dfs fashion
+ const dependencies = root.dependencies;
+ if (dependencies && dependencies.length > 0) {
+ for (let i = 0; i < dependencies.length; ++i) {
+ this.dfsTraverse(dependencies[i], cycleCheck, alreadyTraversed, result);
+ }
+ }
+ // add to result holder
+ result.push(root);
+ // mark this node as traversed so that we don't traverse from this again
+ alreadyTraversed.add(root.name);
+ // release the hold
+ cycleCheck.delete(root.name);
+ }
+}
+exports.TopologicalSortGlslRoutines = TopologicalSortGlslRoutines;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/glsl-encoding-lib.ts":
+/*!********************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/glsl-encoding-lib.ts ***!
+ \********************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.EncodingGlslLib = void 0;
+const glsl_definitions_1 = __webpack_require__(/*! ./glsl-definitions */ "./lib/onnxjs/backends/webgl/glsl-definitions.ts");
+/**
+ * This GLSL library handles routines converting
+ * float32 to/from Unsigned byte or float 16
+ */
+class EncodingGlslLib extends glsl_definitions_1.GlslLib {
+ constructor(context) {
+ super(context);
+ }
+ getFunctions() {
+ return Object.assign(Object.assign({}, this.encodeFloat32()), this.decodeFloat32());
+ }
+ getCustomTypes() {
+ return {};
+ }
+ encodeFloat32() {
+ return {
+ encode: new glsl_definitions_1.GlslLibRoutine(`highp vec4 encode(highp float f) {
+ return vec4(f, 0.0, 0.0, 0.0);
+ }
+ `)
+ };
+ }
+ decodeFloat32() {
+ return {
+ decode: new glsl_definitions_1.GlslLibRoutine(`highp float decode(highp vec4 rgba) {
+ return rgba.r;
+ }
+ `)
+ };
+ }
+ /**
+ * returns the routine to encode encode a 32bit float to a vec4 (of unsigned bytes)
+ * @credit: https://stackoverflow.com/questions/7059962/how-do-i-convert-a-vec4-rgba-value-to-a-float
+ */
+ encodeUint8() {
+ const endianness = EncodingGlslLib.isLittleEndian() ? 'rgba.rgba=rgba.abgr;' : '';
+ return {
+ encode: new glsl_definitions_1.GlslLibRoutine(`
+ highp vec4 encode(highp float f) {
+ highp float F = abs(f);
+ highp float Sign = step(0.0,-f);
+ highp float Exponent = floor(log2(F));
+ highp float Mantissa = (exp2(- Exponent) * F);
+ Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa));
+ highp vec4 rgba;
+ rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0));
+ rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0);
+ rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0)));
+ rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0)));
+ ${endianness}
+ rgba = rgba / 255.0; // values need to be normalized to [0,1]
+ return rgba;
+ }
+ `)
+ };
+ }
+ /**
+ * returns the routine to encode a vec4 of unsigned bytes to float32
+ * @credit: https://stackoverflow.com/questions/7059962/how-do-i-convert-a-vec4-rgba-value-to-a-float
+ */
+ decodeUint8() {
+ const endianness = EncodingGlslLib.isLittleEndian() ? 'rgba.rgba=rgba.abgr;' : '';
+ return {
+ decode: new glsl_definitions_1.GlslLibRoutine(`
+ highp float decode(highp vec4 rgba) {
+ rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255]
+ ${endianness}
+ highp float Sign = 1.0 - step(128.0,rgba[0])*2.0;
+ highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0;
+ highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000);
+ highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 ));
+ return Result;
+ }
+ `)
+ };
+ }
+ /**
+ * Determines if the machine is little endian or not
+ * @credit: https://gist.github.com/TooTallNate/4750953
+ */
+ static isLittleEndian() {
+ const b = new ArrayBuffer(4);
+ const a = new Uint32Array(b);
+ const c = new Uint8Array(b);
+ a[0] = 0xdeadbeef;
+ if (c[0] === 0xef) {
+ return true;
+ }
+ if (c[0] === 0xde) {
+ return false;
+ }
+ throw new Error('unknown endianness');
+ }
+}
+exports.EncodingGlslLib = EncodingGlslLib;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/glsl-fragcolor-lib.ts":
+/*!*********************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/glsl-fragcolor-lib.ts ***!
+ \*********************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.FragColorGlslLib = void 0;
+const glsl_definitions_1 = __webpack_require__(/*! ./glsl-definitions */ "./lib/onnxjs/backends/webgl/glsl-definitions.ts");
+const glsl_source_1 = __webpack_require__(/*! ./glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+/**
+ * This GLSL library handles routines around reading a texlet and writing to it
+ * Reading and writing could be more than just dealing with one channel
+ * It may require encoding/decoding to/from 4 channels into one
+ */
+class FragColorGlslLib extends glsl_definitions_1.GlslLib {
+ constructor(context) {
+ super(context);
+ }
+ getFunctions() {
+ return Object.assign(Object.assign({}, this.setFragColor()), this.getColorAsFloat());
+ }
+ getCustomTypes() {
+ return {};
+ }
+ setFragColor() {
+ const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
+ return {
+ setFragColor: new glsl_definitions_1.GlslLibRoutine(`
+ void setFragColor(float value) {
+ ${glsl.output} = encode(value);
+ }
+ `, ['encoding.encode'])
+ };
+ }
+ getColorAsFloat() {
+ return {
+ getColorAsFloat: new glsl_definitions_1.GlslLibRoutine(`
+ float getColorAsFloat(vec4 color) {
+ return decode(color);
+ }
+ `, ['encoding.decode'])
+ };
+ }
+}
+exports.FragColorGlslLib = FragColorGlslLib;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/glsl-function-inliner.ts":
+/*!************************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/glsl-function-inliner.ts ***!
+ \************************************************************/
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.replaceInlines = void 0;
+const INLINE_FUNC_DEF_REGEX = /@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm;
+const FUNC_CALL_REGEX = '(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;';
+/**
+ * GLSL preprocessor responsible for resolving @inline directives
+ */
+function replaceInlines(script) {
+ const inlineDefs = {};
+ let match;
+ while ((match = INLINE_FUNC_DEF_REGEX.exec(script)) !== null) {
+ const params = match[3]
+ .split(',')
+ .map(s => {
+ const tokens = s.trim().split(' ');
+ if (tokens && tokens.length === 2) {
+ return { type: tokens[0], name: tokens[1] };
+ }
+ return null;
+ })
+ .filter(v => v !== null);
+ inlineDefs[match[2]] = { params, body: match[4] };
+ }
+ for (const name in inlineDefs) {
+ const regexString = FUNC_CALL_REGEX.replace('__FUNC__', name);
+ const regex = new RegExp(regexString, 'gm');
+ while ((match = regex.exec(script)) !== null) {
+ const type = match[1];
+ const variable = match[2];
+ const params = match[3].split(',');
+ const declLine = (type) ? `${type} ${variable};` : '';
+ let newBody = inlineDefs[name].body;
+ let paramRedecLine = '';
+ inlineDefs[name].params.forEach((v, i) => {
+ if (v) {
+ paramRedecLine += `${v.type} ${v.name} = ${params[i]};\n`;
+ }
+ });
+ newBody = `${paramRedecLine}\n ${newBody}`;
+ newBody = newBody.replace('return', `${variable} = `);
+ const replacement = `
+ ${declLine}
+ {
+ ${newBody}
+ }
+ `;
+ script = script.replace(match[0], replacement);
+ }
+ }
+ script = script.replace(INLINE_FUNC_DEF_REGEX, '');
+ return script;
+}
+exports.replaceInlines = replaceInlines;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/glsl-preprocessor.ts":
+/*!********************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/glsl-preprocessor.ts ***!
+ \********************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.GlslPreprocessor = void 0;
+const glsl_definitions_1 = __webpack_require__(/*! ./glsl-definitions */ "./lib/onnxjs/backends/webgl/glsl-definitions.ts");
+const glsl_function_inliner_1 = __webpack_require__(/*! ./glsl-function-inliner */ "./lib/onnxjs/backends/webgl/glsl-function-inliner.ts");
+const glsl_registered_libs_1 = __webpack_require__(/*! ./glsl-registered-libs */ "./lib/onnxjs/backends/webgl/glsl-registered-libs.ts");
+const glsl_source_1 = __webpack_require__(/*! ./glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+/**
+ * Preprocessor for the additions to the GLSL language
+ * It deals with:
+ * @include directives
+ * @inline
+ * Loop unrolling (not implemented)
+ * Macro resolution (not implemented)
+ */
+class GlslPreprocessor {
+ constructor(glContext, programInfo, inputTextureLayouts, outputTextureLayout) {
+ this.libs = {};
+ this.glslLibRoutineDependencyGraph = {};
+ this.context = new glsl_definitions_1.GlslContext(glContext, programInfo, inputTextureLayouts, outputTextureLayout);
+ // construct GlslLibs
+ Object.keys(glsl_registered_libs_1.glslRegistry).forEach((name) => {
+ const lib = new glsl_registered_libs_1.glslRegistry[name](this.context);
+ this.libs[name] = lib;
+ });
+ // construct GlslRoutineDependencyGraph
+ const map = this.glslLibRoutineDependencyGraph;
+ for (const libName in this.libs) {
+ const lib = this.libs[libName];
+ const routinesInLib = lib.getFunctions();
+ for (const routine in routinesInLib) {
+ const key = libName + '.' + routine;
+ let currentNode;
+ if (map[key]) {
+ currentNode = map[key];
+ currentNode.routineBody = routinesInLib[routine].routineBody;
+ }
+ else {
+ currentNode = new glsl_definitions_1.GlslLibRoutineNode(key, routinesInLib[routine].routineBody);
+ map[key] = currentNode;
+ }
+ const dependencies = routinesInLib[routine].dependencies;
+ if (dependencies) {
+ for (let i = 0; i < dependencies.length; ++i) {
+ if (!map[dependencies[i]]) {
+ const node = new glsl_definitions_1.GlslLibRoutineNode(dependencies[i]);
+ map[dependencies[i]] = node;
+ currentNode.addDependency(node);
+ }
+ else {
+ currentNode.addDependency(map[dependencies[i]]);
+ }
+ }
+ }
+ }
+ }
+ }
+ preprocess() {
+ const programInfo = this.context.programInfo;
+ let source = programInfo.shaderSource;
+ // append main() function
+ if (!this.context.programInfo.hasMain) {
+ source = `${source}
+ ${(0, glsl_source_1.getDefaultFragShaderMain)(this.context.glContext.version, this.context.outputTextureLayout.shape.length)}`;
+ }
+ // replace inlines
+ source = (0, glsl_function_inliner_1.replaceInlines)(source);
+ // concat final source string
+ return `${(0, glsl_source_1.getFragShaderPreamble)(this.context.glContext.version)}
+ ${this.getUniforms(programInfo.inputNames, programInfo.variables)}
+ ${this.getImports(source)}
+ ${source}`;
+ }
+ getImports(script) {
+ const routinesIncluded = this.selectGlslLibRoutinesToBeIncluded(script);
+ if (routinesIncluded.length === 0) {
+ return '';
+ }
+ let routines = '';
+ for (let i = 0; i < routinesIncluded.length; ++i) {
+ if (routinesIncluded[i].routineBody) {
+ routines += routinesIncluded[i].routineBody + '\n';
+ }
+ else {
+ throw new Error(`Missing body for the Glsl Library routine: ${routinesIncluded[i].name}`);
+ }
+ }
+ return routines;
+ }
+ selectGlslLibRoutinesToBeIncluded(script) {
+ const nodes = [];
+ Object.keys(this.glslLibRoutineDependencyGraph).forEach(classAndRoutine => {
+ const routine = classAndRoutine.split('.')[1];
+ if (script.indexOf(routine) !== -1) {
+ nodes.push(this.glslLibRoutineDependencyGraph[classAndRoutine]);
+ }
+ });
+ return glsl_definitions_1.TopologicalSortGlslRoutines.returnOrderedNodes(nodes);
+ }
+ getUniforms(samplers, variables) {
+ const uniformLines = [];
+ if (samplers) {
+ for (const sampler of samplers) {
+ uniformLines.push(`uniform sampler2D ${sampler};`);
+ }
+ }
+ if (variables) {
+ for (const variable of variables) {
+ uniformLines.push(`uniform ${variable.type} ${variable.name}${variable.arrayLength ? `[${variable.arrayLength}]` : ''};`);
+ }
+ }
+ return uniformLines.join('\n');
+ }
+}
+exports.GlslPreprocessor = GlslPreprocessor;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/glsl-registered-libs.ts":
+/*!***********************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/glsl-registered-libs.ts ***!
+ \***********************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.glslRegistry = void 0;
+const glsl_coordinate_lib_1 = __webpack_require__(/*! ./glsl-coordinate-lib */ "./lib/onnxjs/backends/webgl/glsl-coordinate-lib.ts");
+const glsl_encoding_lib_1 = __webpack_require__(/*! ./glsl-encoding-lib */ "./lib/onnxjs/backends/webgl/glsl-encoding-lib.ts");
+const glsl_fragcolor_lib_1 = __webpack_require__(/*! ./glsl-fragcolor-lib */ "./lib/onnxjs/backends/webgl/glsl-fragcolor-lib.ts");
+const glsl_shape_utils_lib_1 = __webpack_require__(/*! ./glsl-shape-utils-lib */ "./lib/onnxjs/backends/webgl/glsl-shape-utils-lib.ts");
+const glsl_vec_lib_1 = __webpack_require__(/*! ./glsl-vec-lib */ "./lib/onnxjs/backends/webgl/glsl-vec-lib.ts");
+exports.glslRegistry = {
+ 'encoding': glsl_encoding_lib_1.EncodingGlslLib,
+ 'fragcolor': glsl_fragcolor_lib_1.FragColorGlslLib,
+ 'vec': glsl_vec_lib_1.VecGlslLib,
+ 'shapeUtils': glsl_shape_utils_lib_1.ShapeUtilsGlslLib,
+ 'coordinates': glsl_coordinate_lib_1.CoordsGlslLib,
+ // 'arrays': ArrayGlslSLib
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/glsl-shape-utils-lib.ts":
+/*!***********************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/glsl-shape-utils-lib.ts ***!
+ \***********************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ShapeUtilsGlslLib = void 0;
+const glsl_definitions_1 = __webpack_require__(/*! ./glsl-definitions */ "./lib/onnxjs/backends/webgl/glsl-definitions.ts");
+/**
+ * GLSL Library responsible for data types and routines for manipulating
+ * coordinates and mapping to/from tensor indices
+ */
+class ShapeUtilsGlslLib extends glsl_definitions_1.GlslLib {
+ constructor(context) {
+ super(context);
+ }
+ getFunctions() {
+ return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, this.bcastIndex()), this.bcastMatmulIndex()), this.offsetToIndices()), this.indicesToOffset()), this.incrementIndices());
+ }
+ getCustomTypes() {
+ return {};
+ }
+ bcastIndex() {
+ const outputRank = this.context.outputTextureLayout.shape.length;
+ const result = {};
+ this.context.programInfo.inputNames.forEach((name, i) => {
+ const shape = this.context.inputTextureLayouts[i].unpackedShape;
+ if (shape.length <= outputRank) {
+ const rank = shape.length;
+ const dimOffset = outputRank - rank;
+ const funcName = `bcastIndices_${name}`;
+ let block = '';
+ for (let i = 0; i < rank; ++i) {
+ block += `
+ realIndices[${i}] = int( mod(float(bcastedIndices[${dimOffset + i}]), ${shape[i]}.0) );
+ `;
+ }
+ const body = `
+ void ${funcName} (int bcastedIndices[${outputRank}], out int realIndices[${rank}]) {
+ ${block}
+ }
+ `;
+ result[funcName] = new glsl_definitions_1.GlslLibRoutine(body);
+ }
+ });
+ return result;
+ }
+ bcastMatmulIndex() {
+ const outputRank = this.context.outputTextureLayout.shape.length;
+ const result = {};
+ this.context.programInfo.inputNames.forEach((name, i) => {
+ const shape = this.context.inputTextureLayouts[i].shape;
+ if (!(shape.length < 2 || shape.length > outputRank)) {
+ const rank = shape.length;
+ const dimOffset = outputRank - rank;
+ const funcName = `bcastMatmulIndices_${name}`;
+ let block = '';
+ for (let i = 0; i < rank - 2; ++i) {
+ block += `
+ realIndices[${i}] = int( mod(float(bcastedIndices[${dimOffset + i}]), ${shape[i]}.0) );
+ `;
+ }
+ const body = `
+ void ${funcName}(int bcastedIndices[${outputRank}], out int realIndices[${rank}]) {
+ ${block}
+ realIndices[${rank - 1}] = bcastedIndices[${outputRank - 1}];
+ realIndices[${rank - 2}] = bcastedIndices[${outputRank - 2}];
+ }
+ `;
+ result[funcName] = new glsl_definitions_1.GlslLibRoutine(body);
+ }
+ });
+ return result;
+ }
+ indicesToOffset() {
+ const result = {};
+ this.context.programInfo.inputNames.forEach((name, i) => {
+ const shape = this.context.inputTextureLayouts[i].shape;
+ const strides = this.context.inputTextureLayouts[i].strides;
+ const rank = shape.length;
+ let funcName = `indicesToOffset_${name}`;
+ result[funcName] = new glsl_definitions_1.GlslLibRoutine(ShapeUtilsGlslLib.indexToOffsetSingle(funcName, rank, strides));
+ funcName = `indicesToOffset_${name}_T`;
+ result[funcName] =
+ new glsl_definitions_1.GlslLibRoutine(ShapeUtilsGlslLib.indexToOffsetSingle(funcName, rank, strides.slice().reverse()));
+ });
+ return result;
+ }
+ static indexToOffsetSingle(name, rank, strides) {
+ let block = '';
+ for (let i = rank - 1; i >= 0; --i) {
+ block += `
+ offset += indices[${i}] * ${strides[i]};
+ `;
+ }
+ return `
+ int ${name}(int indices[${rank}]) {
+ int offset = 0;
+ ${block}
+ return offset;
+ }
+ `;
+ }
+ offsetToIndices() {
+ const result = {};
+ this.context.programInfo.inputNames.forEach((name, i) => {
+ const shape = this.context.inputTextureLayouts[i].shape;
+ const strides = this.context.inputTextureLayouts[i].strides;
+ const rank = shape.length;
+ let funcName = `offsetToIndices_${name}`;
+ result[funcName] = new glsl_definitions_1.GlslLibRoutine(ShapeUtilsGlslLib.offsetToIndicesSingle(funcName, rank, strides));
+ funcName = `offsetToIndices_${name}_T`;
+ result[funcName] =
+ new glsl_definitions_1.GlslLibRoutine(ShapeUtilsGlslLib.offsetToIndicesSingle(funcName, rank, strides.slice().reverse()));
+ });
+ return result;
+ }
+ static offsetToIndicesSingle(name, rank, strides) {
+ const stridesBlock = [];
+ for (let i = 0; i < rank - 1; ++i) {
+ stridesBlock.push(`
+ indices[${i}] = offset / ${strides[i]};`);
+ stridesBlock.push(`
+ offset -= indices[${i}] * ${strides[i]};`);
+ }
+ stridesBlock.push(`
+ indices[${rank - 1}] = offset;`);
+ return `
+ void ${name}(int offset, out int indices[${rank}]) {
+ ${stridesBlock.join('')}
+ }
+ `;
+ }
+ incrementIndices() {
+ const result = {};
+ this.context.programInfo.inputNames.forEach((name, i) => {
+ const shape = this.context.inputTextureLayouts[i].shape;
+ const rank = shape.length;
+ const funcName = `incrementIndices_${name}`;
+ let shapeInit = '';
+ for (let i = 0; i < rank; ++i) {
+ shapeInit += `
+ shape[${i}] = ${shape[i]};`;
+ }
+ const body = `
+ void ${funcName}(int axis, out int indices[${rank}]) {
+ int shape[${rank}];
+ ${shapeInit};
+ for(int i = ${rank} -1 ; i >= 0; --i) {
+ if(i > axis) continue;
+ indices[i] += 1;
+ if(indices[i] < shape[i]) {
+ break;
+ }
+ indices[i] = 0;
+ }
+ }
+ `;
+ result[funcName] = new glsl_definitions_1.GlslLibRoutine(body);
+ });
+ return result;
+ }
+}
+exports.ShapeUtilsGlslLib = ShapeUtilsGlslLib;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/glsl-source.ts":
+/*!**************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/glsl-source.ts ***!
+ \**************************************************/
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getDefaultFragShaderMain = exports.getFragShaderPreamble = exports.getVertexShaderSource = exports.getGlsl = void 0;
+const GLSL_ES_2_0 = {
+ version: '',
+ attribute: 'attribute',
+ varyingVertex: 'varying',
+ varyingFrag: 'varying',
+ texture2D: 'texture2D',
+ output: 'gl_FragColor',
+ outputDeclaration: '',
+};
+const GLSL_ES_3_0 = {
+ version: '#version 300 es',
+ attribute: 'in',
+ varyingVertex: 'out',
+ varyingFrag: 'in',
+ texture2D: 'texture',
+ output: 'outputColor',
+ outputDeclaration: 'out vec4 outputColor;',
+};
+function getGlsl(version) {
+ return version === 1 ? GLSL_ES_2_0 : GLSL_ES_3_0;
+}
+exports.getGlsl = getGlsl;
+function getVertexShaderSource(version) {
+ const glsl = getGlsl(version);
+ return `${glsl.version}
+ precision highp float;
+ ${glsl.attribute} vec3 position;
+ ${glsl.attribute} vec2 textureCoord;
+
+ ${glsl.varyingVertex} vec2 TexCoords;
+
+ void main()
+ {
+ gl_Position = vec4(position, 1.0);
+ TexCoords = textureCoord;
+ }`;
+}
+exports.getVertexShaderSource = getVertexShaderSource;
+function getFragShaderPreamble(version) {
+ const glsl = getGlsl(version);
+ return `${glsl.version}
+ precision highp float;
+ precision highp int;
+ precision highp sampler2D;
+ ${glsl.varyingFrag} vec2 TexCoords;
+ ${glsl.outputDeclaration}
+ const vec2 halfCR = vec2(0.5, 0.5);
+
+ // Custom vector types to handle higher dimenalities.
+ struct ivec5
+ {
+ int x;
+ int y;
+ int z;
+ int w;
+ int u;
+ };
+
+ struct ivec6
+ {
+ int x;
+ int y;
+ int z;
+ int w;
+ int u;
+ int v;
+ };
+
+ int imod(int x, int y) {
+ return x - y * (x / y);
+ }
+
+ `;
+}
+exports.getFragShaderPreamble = getFragShaderPreamble;
+function getDefaultFragShaderMain(version, outputShapeLength) {
+ const glsl = getGlsl(version);
+ return `
+ void main() {
+ int indices[${outputShapeLength}];
+ toVec(TexCoords, indices);
+ vec4 result = vec4(process(indices));
+ ${glsl.output} = result;
+ }
+ `;
+}
+exports.getDefaultFragShaderMain = getDefaultFragShaderMain;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/glsl-vec-lib.ts":
+/*!***************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/glsl-vec-lib.ts ***!
+ \***************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.VecGlslLib = void 0;
+const glsl_definitions_1 = __webpack_require__(/*! ./glsl-definitions */ "./lib/onnxjs/backends/webgl/glsl-definitions.ts");
+/**
+ * GLSL Library responsible for vec routines
+ * Vec is an varible length int array. The length is fixed at the time of
+ * generating the library functions from the dimensions of the output.
+ */
+class VecGlslLib extends glsl_definitions_1.GlslLib {
+ constructor(context) {
+ super(context);
+ }
+ getCustomTypes() {
+ return {};
+ }
+ getFunctions() {
+ return Object.assign(Object.assign(Object.assign(Object.assign({}, this.binaryVecFunctions()), this.copyVec()), this.setVecItem()), this.getVecItem());
+ }
+ binaryVecFunctions() {
+ const outputLayout = this.context.outputTextureLayout;
+ const rank = outputLayout.shape.length;
+ const nameOp = { add: '+=', sub: '-=', mul: '*=', div: '/=' };
+ const result = {};
+ for (const name in nameOp) {
+ const fname = `${name}Vec`;
+ let assignmentBlock = '';
+ for (let i = 0; i < rank; ++i) {
+ assignmentBlock += `
+ dest[${i}] ${nameOp[name]} src[${i}];
+ `;
+ }
+ const body = `
+ void ${fname}(int src[${rank}], out int dest[${rank}]) {
+ ${assignmentBlock}
+ }
+ `;
+ result[fname] = new glsl_definitions_1.GlslLibRoutine(body);
+ }
+ return result;
+ }
+ copyVec() {
+ const outputLayout = this.context.outputTextureLayout;
+ const rank = outputLayout.shape.length;
+ let assignmentBlock = '';
+ for (let i = 0; i < rank; ++i) {
+ assignmentBlock += `
+ dest[${i}] = src[${i}];
+ `;
+ }
+ const body = `
+ void copyVec(int src[${rank}], out int dest[${rank}]) {
+ ${assignmentBlock}
+ }
+ `;
+ return { copyVec: new glsl_definitions_1.GlslLibRoutine(body) };
+ }
+ setVecItem() {
+ const outputLayout = this.context.outputTextureLayout;
+ const rank = outputLayout.shape.length;
+ let block = `
+ if(index < 0)
+ index =${rank} + index;
+ if (index == 0)
+ m[0] = value;
+ `;
+ for (let i = 1; i < rank - 1; ++i) {
+ block += `
+ else if (index == ${i})
+ m[${i}] = value;
+ `;
+ }
+ block += `
+ else
+ m[${rank - 1}] = value;
+ `;
+ const body = `
+ void setVecItem(out int m[${rank}], int index, int value) {
+ ${block}
+ }
+ `;
+ return { setVecItem: new glsl_definitions_1.GlslLibRoutine(body) };
+ }
+ getVecItem() {
+ const outputLayout = this.context.outputTextureLayout;
+ const rank = outputLayout.shape.length;
+ let block = `
+ if(index < 0)
+ index = ${rank} + index;
+ if (index == 0)
+ return m[0];
+ `;
+ for (let i = 1; i < rank - 1; ++i) {
+ block += `
+ else if (index == ${i})
+ return m[${i}];
+ `;
+ }
+ block += `
+ else
+ return m[${rank - 1}];
+ `;
+ const body = `
+ int getVecItem(int m[${rank}], int index) {
+ ${block}
+ }
+ `;
+ return { getVecItem: new glsl_definitions_1.GlslLibRoutine(body) };
+ }
+}
+exports.VecGlslLib = VecGlslLib;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/inference-handler.ts":
+/*!********************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/inference-handler.ts ***!
+ \********************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.WebGLInferenceHandler = void 0;
+const instrument_1 = __webpack_require__(/*! ../../instrument */ "./lib/onnxjs/instrument.ts");
+const tensor_1 = __webpack_require__(/*! ../../tensor */ "./lib/onnxjs/tensor.ts");
+const util_1 = __webpack_require__(/*! ../../util */ "./lib/onnxjs/util.ts");
+const pack_1 = __webpack_require__(/*! ./ops/pack */ "./lib/onnxjs/backends/webgl/ops/pack.ts");
+const reshape_packed_1 = __webpack_require__(/*! ./ops/reshape-packed */ "./lib/onnxjs/backends/webgl/ops/reshape-packed.ts");
+const uint8_encode_1 = __webpack_require__(/*! ./ops/uint8-encode */ "./lib/onnxjs/backends/webgl/ops/uint8-encode.ts");
+const unpack_1 = __webpack_require__(/*! ./ops/unpack */ "./lib/onnxjs/backends/webgl/ops/unpack.ts");
+const texture_layout_1 = __webpack_require__(/*! ./texture-layout */ "./lib/onnxjs/backends/webgl/texture-layout.ts");
+const types_1 = __webpack_require__(/*! ./types */ "./lib/onnxjs/backends/webgl/types.ts");
+const getProgramInfoUniqueKey = (programInfo, inputTextureDatas) => {
+ const inputs = inputTextureDatas.map(texture => `${texture.unpackedShape.join(',')};${texture.width}x${texture.height}`)
+ .join('_');
+ let key = programInfo.name;
+ if (programInfo.cacheHint) {
+ key += '[' + programInfo.cacheHint + ']';
+ }
+ key += ':' + inputs;
+ return key;
+};
+class WebGLInferenceHandler {
+ constructor(session) {
+ this.session = session;
+ this.packedTextureDataCache = new Map();
+ this.unpackedTextureDataCache = new Map();
+ }
+ /**
+ * @returns [width, height]
+ */
+ calculateTextureWidthAndHeight(shape, textureType) {
+ return (0, texture_layout_1.calculateTextureWidthAndHeight)(this.session.layoutStrategy, shape, textureType);
+ }
+ executeProgram(program, inputs) {
+ if (inputs.length < program.inputNames.length) {
+ throw new Error(`Input size mustn't be less than ${program.inputNames.length}.`);
+ }
+ if (program.inputNames.length !== program.inputTypes.length) {
+ throw new Error('input names size does not match input types');
+ }
+ // create texture info for input
+ const inputTextureDatas = [];
+ for (let i = 0; i < program.inputNames.length; ++i) {
+ inputTextureDatas[i] = this.getOrCreateTextureData(inputs[i], program.inputTypes[i]);
+ }
+ const key = getProgramInfoUniqueKey(program, inputTextureDatas);
+ let artifact = this.session.programManager.getArtifact(key);
+ const programInfo = artifact ?
+ artifact.programInfo :
+ (typeof program.get === 'function' ? program.get() :
+ program);
+ // create texture info for output
+ const outputTextureLayout = (0, texture_layout_1.createTextureLayoutFromTextureType)(this.session.layoutStrategy, programInfo.output.dims, programInfo.output.textureType);
+ const outputTextureData = this.createTextureData(outputTextureLayout, programInfo.output.type);
+ if (!artifact) {
+ artifact = this.session.programManager.build(programInfo, inputTextureDatas, outputTextureData);
+ this.session.programManager.setArtifact(key, artifact);
+ }
+ this.runProgram(artifact, inputTextureDatas, outputTextureData);
+ return outputTextureData;
+ }
+ run(program, inputs) {
+ const outputTextureData = this.executeProgram(program, inputs);
+ return outputTextureData.tensor;
+ }
+ runProgram(artifact, inputs, output) {
+ // input should match
+ for (let i = 0; i < inputs.length; ++i) {
+ if (!!inputs[i].isPacked !== (artifact.programInfo.inputTypes[i] === types_1.TextureType.packed)) {
+ throw new Error(`input[${i}] property packed inconsistent`);
+ }
+ }
+ // output should match
+ if (!!output.isPacked !== (artifact.programInfo.output.textureType === types_1.TextureType.packed)) {
+ throw new Error('output property packed inconsistent');
+ }
+ this.session.programManager.run(artifact, inputs, output);
+ }
+ /**
+ * Create a TextureData object from a tensor.
+ * Usage = Encoder.Usage.UploadOnly.
+ * If a related texture data is found in cache, returns it;
+ * Otherwise:
+ * Creates a new texture layout if not provided;
+ * Creates WebGLTexture with the layout;
+ * Upload tensor data to the texture;
+ * Creates a texture data object associated with the given tensor.
+ * @param tensor the tensor with data to upload
+ */
+ getOrCreateTextureData(tensor, textureType) {
+ let td = this.getTextureData(tensor.dataId, textureType === types_1.TextureType.packed);
+ if (!td) {
+ // check if we have texture data in different type
+ td = this.getTextureData(tensor.dataId, textureType !== types_1.TextureType.packed);
+ if (td) {
+ if (textureType === types_1.TextureType.packed) {
+ return this.pack(td);
+ }
+ else {
+ return this.unpack(td);
+ }
+ }
+ }
+ if (!td) {
+ const layout = (0, texture_layout_1.createTextureLayoutFromTextureType)(this.session.layoutStrategy, tensor.dims, textureType);
+ if (textureType === types_1.TextureType.packedLastDimension) {
+ const group = 1;
+ const channels = 4;
+ const shape = tensor.dims;
+ if (shape.length === 4) {
+ // pre-processing for kernel data of Conv.
+ //
+ // TODO: currently this is a hacking to overwrite Conv's weight. The correct way to do this should be:
+ // 1. implement texture based const-folding
+ // 2. create a WebGL program "preprocessConvWeight" to do the same work as below
+ // 3. run the program before dotProduct.
+ //
+ const adjustedKernelShape = [shape[0], Math.ceil((shape[1] * shape[2] * shape[3]) / channels)];
+ const adjustedLayout = (0, texture_layout_1.createTextureLayoutFromTextureType)(this.session.layoutStrategy, adjustedKernelShape, textureType);
+ let buffer = tensor.numberData;
+ if (shape[1] * shape[2] * shape[3] % channels !== 0) {
+ const numFeatureMaps = shape[0];
+ const oldRowSize = shape[1] * shape[2] * shape[3];
+ const newRowSize = Math.ceil(oldRowSize * group / channels) * channels;
+ const newSize = numFeatureMaps * newRowSize;
+ buffer = new Float32Array(newSize);
+ for (let f = 0; f < numFeatureMaps; ++f) {
+ const oldOffset = f * oldRowSize;
+ const newOffset = f * newRowSize + f % group * oldRowSize;
+ buffer.set(tensor.numberData.subarray(oldOffset, oldOffset + oldRowSize), newOffset);
+ }
+ }
+ return this.createTextureData(adjustedLayout, tensor.type, buffer, tensor, 1 /* Encoder.Usage.UploadOnly */);
+ }
+ }
+ if (textureType === types_1.TextureType.packed) {
+ const unpackedTextureLayout = (0, texture_layout_1.createTextureLayoutFromShape)(this.session.layoutStrategy, tensor.dims, 1, [], { reverseWH: true });
+ const unpackedTextureData = this.createTextureData(unpackedTextureLayout, tensor.type, tensor.numberData, tensor, 1 /* Encoder.Usage.UploadOnly */);
+ td = this.pack(unpackedTextureData);
+ }
+ else {
+ td = this.createTextureData(layout, tensor.type, tensor.numberData, tensor, 1 /* Encoder.Usage.UploadOnly */);
+ }
+ }
+ return td;
+ }
+ /**
+ * Create a TextureData object using the given data and bind to the given tensor.
+ * Usage = Encoder.Usage.UploadOnly.
+ * NOTE: this function is a hack for Conv implementation. should remove this function, after rewriting Conv
+ * implementation by Graph.Transformer
+ * @param dataType the tensor data type
+ * @param data the actual data to upload
+ * @param tensor the tensor to bind. tensor's data is ignored.
+ */
+ createTextureDataFromLayoutBindTensor(layout, dataType, data, tensor) {
+ return this.createTextureData(layout, dataType, data, tensor, 1 /* Encoder.Usage.UploadOnly */);
+ }
+ createTextureData(layout, dataType, data, tensor, usage) {
+ instrument_1.Logger.verbose('InferenceHandler', `Creating TextureData: layout:[${JSON.stringify(layout)}]`);
+ const texture = this.session.textureManager.createTextureFromLayout(dataType, layout, data, usage);
+ return this.createTextureDataFromTexture(layout, dataType, texture, tensor);
+ }
+ reshapeUnpacked(input, reshapedDims) {
+ const inputTD = this.getOrCreateTextureData(input, types_1.TextureType.unpacked);
+ const newTextureLayout = {
+ channels: inputTD.channels,
+ height: inputTD.height,
+ width: inputTD.width,
+ // handle reshaping into scalar Tensors
+ shape: reshapedDims.length !== 0 ? reshapedDims : [1],
+ strides: util_1.ShapeUtil.computeStrides(reshapedDims),
+ unpackedShape: reshapedDims,
+ };
+ const newTextureData = this.createTextureDataFromTexture(newTextureLayout, input.type, inputTD.texture);
+ return newTextureData.tensor;
+ }
+ reshapePacked(input, reshapedDims) {
+ const inputTD = this.getOrCreateTextureData(input, types_1.TextureType.packed);
+ // check if the reshape is 'cheap'
+ if ((0, reshape_packed_1.isReshapeCheap)(input.dims, reshapedDims)) {
+ const newTextureLayout = {
+ channels: inputTD.channels,
+ height: inputTD.height,
+ width: inputTD.width,
+ // handle reshaping into scalar Tensors
+ shape: reshapedDims.length !== 0 ? reshapedDims : [1],
+ strides: util_1.ShapeUtil.computeStrides(reshapedDims),
+ unpackedShape: reshapedDims,
+ isPacked: true
+ };
+ const newTextureData = this.createTextureDataFromTexture(newTextureLayout, input.type, inputTD.texture);
+ return newTextureData.tensor;
+ }
+ const squeezedInputShape = (0, reshape_packed_1.processDims3D)(input.dims);
+ const squeezedOutputShape = (0, reshape_packed_1.processDims3D)(reshapedDims);
+ const squeezedInputTensor = this.reshapePacked(input, squeezedInputShape);
+ const squeezedOutputTensor = this.run((0, reshape_packed_1.createPackedReshape3DProgramInfoLoader)(this, squeezedInputTensor, squeezedOutputShape), [squeezedInputTensor]);
+ const outputTensor = this.reshapePacked(squeezedOutputTensor, reshapedDims);
+ return outputTensor;
+ }
+ cast(input, type) {
+ const inputTD = this.getOrCreateTextureData(input, types_1.TextureType.unpacked);
+ const newTextureData = this.createTextureDataFromTexture(inputTD, type, inputTD.texture);
+ return newTextureData.tensor;
+ }
+ createTextureDataFromTexture(layout, dataType, texture, tensor, tensorId) {
+ const textureData = Object.assign(Object.assign({}, layout), { tensor: tensor ||
+ new tensor_1.Tensor(layout.unpackedShape, dataType, (_id) => this.readTexture(textureData), async (_id) => this.readTextureAsync(textureData), undefined, tensorId), texture });
+ this.setTextureData(textureData.tensor.dataId, textureData, layout.isPacked);
+ return textureData;
+ }
+ getTextureData(tensorId, isPacked = false) {
+ return this.session.isInitializer(tensorId) ? this.session.getTextureData(tensorId, isPacked) :
+ isPacked ? this.packedTextureDataCache.get(tensorId) :
+ this.unpackedTextureDataCache.get(tensorId);
+ }
+ setTextureData(tensorId, td, isPacked = false) {
+ if (this.session.isInitializer(tensorId)) {
+ this.session.setTextureData(tensorId, td, isPacked);
+ }
+ else {
+ (isPacked ? this.packedTextureDataCache : this.unpackedTextureDataCache).set(tensorId, td);
+ }
+ }
+ isTextureLayoutCached(tensor, isPacked = false) {
+ return !!this.getTextureData(tensor.dataId, isPacked);
+ }
+ dispose() {
+ this.session.textureManager.clearActiveTextures();
+ this.packedTextureDataCache.forEach(td => this.session.textureManager.releaseTexture(td));
+ this.packedTextureDataCache = new Map();
+ this.unpackedTextureDataCache.forEach(td => this.session.textureManager.releaseTexture(td));
+ this.unpackedTextureDataCache = new Map();
+ }
+ readTexture(textureData) {
+ if (textureData.isPacked) {
+ return this.readTexture(this.unpack(textureData));
+ }
+ if (!this.session.backend.glContext.isFloat32DownloadSupported) {
+ return this.session.textureManager.readUint8TextureAsFloat((0, uint8_encode_1.encodeAsUint8)(this, textureData));
+ }
+ return this.session.textureManager.readTexture(textureData, textureData.tensor.type, textureData.channels);
+ }
+ async readTextureAsync(textureData) {
+ if (textureData.isPacked) {
+ return this.readTextureAsync(this.unpack(textureData));
+ }
+ if (!this.session.backend.glContext.isFloat32DownloadSupported) {
+ return this.session.textureManager.readUint8TextureAsFloat((0, uint8_encode_1.encodeAsUint8)(this, textureData));
+ }
+ return this.session.textureManager.readTextureAsync(textureData, textureData.tensor.type, textureData.channels);
+ }
+ pack(input) {
+ const outputTextureData = this.executeProgram((0, pack_1.createPackProgramInfoLoader)(this, input.tensor), [input.tensor]);
+ return outputTextureData;
+ }
+ unpack(input) {
+ const outputTextureData = this.executeProgram((0, unpack_1.createUnpackProgramInfoLoader)(this, input.tensor), [input.tensor]);
+ return outputTextureData;
+ }
+}
+exports.WebGLInferenceHandler = WebGLInferenceHandler;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/op-resolve-rules.ts":
+/*!*******************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/op-resolve-rules.ts ***!
+ \*******************************************************/
+/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.WEBGL_OP_RESOLVE_RULES = void 0;
+const batch_normalization_1 = __webpack_require__(/*! ./ops/batch-normalization */ "./lib/onnxjs/backends/webgl/ops/batch-normalization.ts");
+const binaryOps = __importStar(__webpack_require__(/*! ./ops/binary-op */ "./lib/onnxjs/backends/webgl/ops/binary-op.ts"));
+const cast_1 = __webpack_require__(/*! ./ops/cast */ "./lib/onnxjs/backends/webgl/ops/cast.ts");
+const concat_1 = __webpack_require__(/*! ./ops/concat */ "./lib/onnxjs/backends/webgl/ops/concat.ts");
+const conv_1 = __webpack_require__(/*! ./ops/conv */ "./lib/onnxjs/backends/webgl/ops/conv.ts");
+const conv_transpose_1 = __webpack_require__(/*! ./ops/conv-transpose */ "./lib/onnxjs/backends/webgl/ops/conv-transpose.ts");
+const depth_to_space_1 = __webpack_require__(/*! ./ops/depth-to-space */ "./lib/onnxjs/backends/webgl/ops/depth-to-space.ts");
+const flatten_1 = __webpack_require__(/*! ./ops/flatten */ "./lib/onnxjs/backends/webgl/ops/flatten.ts");
+const gather_1 = __webpack_require__(/*! ./ops/gather */ "./lib/onnxjs/backends/webgl/ops/gather.ts");
+const gemm_1 = __webpack_require__(/*! ./ops/gemm */ "./lib/onnxjs/backends/webgl/ops/gemm.ts");
+const image_scaler_1 = __webpack_require__(/*! ./ops/image-scaler */ "./lib/onnxjs/backends/webgl/ops/image-scaler.ts");
+const instance_normalization_1 = __webpack_require__(/*! ./ops/instance-normalization */ "./lib/onnxjs/backends/webgl/ops/instance-normalization.ts");
+const matmul_1 = __webpack_require__(/*! ./ops/matmul */ "./lib/onnxjs/backends/webgl/ops/matmul.ts");
+const pad_1 = __webpack_require__(/*! ./ops/pad */ "./lib/onnxjs/backends/webgl/ops/pad.ts");
+const pool_1 = __webpack_require__(/*! ./ops/pool */ "./lib/onnxjs/backends/webgl/ops/pool.ts");
+const reduce_1 = __webpack_require__(/*! ./ops/reduce */ "./lib/onnxjs/backends/webgl/ops/reduce.ts");
+const reshape_1 = __webpack_require__(/*! ./ops/reshape */ "./lib/onnxjs/backends/webgl/ops/reshape.ts");
+const resize_packed_1 = __webpack_require__(/*! ./ops/resize-packed */ "./lib/onnxjs/backends/webgl/ops/resize-packed.ts");
+const shape_1 = __webpack_require__(/*! ./ops/shape */ "./lib/onnxjs/backends/webgl/ops/shape.ts");
+const slice_1 = __webpack_require__(/*! ./ops/slice */ "./lib/onnxjs/backends/webgl/ops/slice.ts");
+const softmax_1 = __webpack_require__(/*! ./ops/softmax */ "./lib/onnxjs/backends/webgl/ops/softmax.ts");
+const split_1 = __webpack_require__(/*! ./ops/split */ "./lib/onnxjs/backends/webgl/ops/split.ts");
+const squeeze_1 = __webpack_require__(/*! ./ops/squeeze */ "./lib/onnxjs/backends/webgl/ops/squeeze.ts");
+const sum_1 = __webpack_require__(/*! ./ops/sum */ "./lib/onnxjs/backends/webgl/ops/sum.ts");
+const tile_1 = __webpack_require__(/*! ./ops/tile */ "./lib/onnxjs/backends/webgl/ops/tile.ts");
+const transpose_1 = __webpack_require__(/*! ./ops/transpose */ "./lib/onnxjs/backends/webgl/ops/transpose.ts");
+const unaryOps = __importStar(__webpack_require__(/*! ./ops/unary-op */ "./lib/onnxjs/backends/webgl/ops/unary-op.ts"));
+const unsqueeze_1 = __webpack_require__(/*! ./ops/unsqueeze */ "./lib/onnxjs/backends/webgl/ops/unsqueeze.ts");
+const upsample_1 = __webpack_require__(/*! ./ops/upsample */ "./lib/onnxjs/backends/webgl/ops/upsample.ts");
+exports.WEBGL_OP_RESOLVE_RULES = [
+ ['Abs', '', '6+', unaryOps.abs],
+ ['Acos', '', '7+', unaryOps.acos],
+ ['Add', '', '7+', binaryOps.add],
+ ['And', '', '7+', binaryOps.and],
+ ['Asin', '', '7+', unaryOps.asin],
+ ['Atan', '', '7+', unaryOps.atan],
+ // TODO: support new attributes for AveragePool-10
+ ['AveragePool', '', '7+', pool_1.averagePool, pool_1.parseAveragePoolAttributes],
+ ['BatchNormalization', '', '7+', batch_normalization_1.batchNormalization, batch_normalization_1.parseBatchNormalizationAttributes],
+ ['Cast', '', '6+', cast_1.cast, cast_1.parseCastAttributes],
+ ['Ceil', '', '6+', unaryOps.ceil],
+ ['Clip', '', '6-10', unaryOps.clip, unaryOps.parseClipAttributes],
+ ['Clip', '', '11+', unaryOps.clipV11],
+ ['Concat', '', '4+', concat_1.concat, concat_1.parseConcatAttributes],
+ ['Conv', '', '1+', conv_1.conv, conv_1.parseConvAttributes],
+ ['ConvTranspose', '', '1+', conv_transpose_1.convTranspose, conv_transpose_1.parseConvTransposeAttributes],
+ ['Cos', '', '7+', unaryOps.cos],
+ ['Div', '', '7+', binaryOps.div],
+ ['Dropout', '', '7+', unaryOps.identity],
+ ['DepthToSpace', '', '1+', depth_to_space_1.depthToSpace, depth_to_space_1.parseDepthToSpaceAttributes],
+ ['Equal', '', '7+', binaryOps.equal],
+ ['Elu', '', '6+', unaryOps.elu, unaryOps.parseEluAttributes],
+ ['Exp', '', '6+', unaryOps.exp],
+ ['Flatten', '', '1+', flatten_1.flatten, flatten_1.parseFlattenAttributes],
+ ['Floor', '', '6+', unaryOps.floor],
+ ['FusedConv', 'com.microsoft', '1+', conv_1.conv, conv_1.parseConvAttributes],
+ ['Gather', '', '1+', gather_1.gather, gather_1.parseGatherAttributes],
+ ['Gemm', '', '7-10', gemm_1.gemm, gemm_1.parseGemmAttributesV7],
+ ['Gemm', '', '11+', gemm_1.gemm, gemm_1.parseGemmAttributesV11],
+ ['GlobalAveragePool', '', '1+', pool_1.globalAveragePool, pool_1.parseGlobalAveragePoolAttributes],
+ ['GlobalMaxPool', '', '1+', pool_1.globalMaxPool],
+ ['Greater', '', '7+', binaryOps.greater],
+ ['Identity', '', '1+', unaryOps.identity],
+ ['ImageScaler', '', '1+', image_scaler_1.imageScaler, image_scaler_1.parseImageScalerAttributes],
+ ['InstanceNormalization', '', '6+', instance_normalization_1.instanceNormalization, instance_normalization_1.parseInstanceNormalizationAttributes],
+ ['LeakyRelu', '', '6+', unaryOps.leakyRelu, unaryOps.parseLeakyReluAttributes],
+ ['Less', '', '7+', binaryOps.less],
+ ['Log', '', '6+', unaryOps.log],
+ ['MatMul', '', '1+', matmul_1.matMul, matmul_1.parseMatMulAttributes],
+ // TODO: support new attributes for MaxPool-8 and MaxPool-10
+ ['MaxPool', '', '1+', pool_1.maxPool, pool_1.parseMaxPoolAttributes],
+ ['Mul', '', '7+', binaryOps.mul],
+ ['Neg', '', '6+', unaryOps.neg],
+ ['Not', '', '1+', unaryOps.not],
+ ['Or', '', '7+', binaryOps.or],
+ ['Pad', '', '2-10', pad_1.padV2, pad_1.parsePadAttributesV2],
+ ['Pad', '', '11+', pad_1.padV11, pad_1.parsePadAttributesV11],
+ ['Pow', '', '7+', binaryOps.pow],
+ ['PRelu', '', '7+', binaryOps.pRelu],
+ ['ReduceLogSum', '', '1+', reduce_1.reduceLogSum, reduce_1.parseReduceAttributes],
+ ['ReduceMax', '', '1+', reduce_1.reduceMax, reduce_1.parseReduceAttributes],
+ ['ReduceMean', '', '1+', reduce_1.reduceMean, reduce_1.parseReduceAttributes],
+ ['ReduceMin', '', '1+', reduce_1.reduceMin, reduce_1.parseReduceAttributes],
+ ['ReduceProd', '', '1+', reduce_1.reduceProd, reduce_1.parseReduceAttributes],
+ ['ReduceSum', '', '1-12', reduce_1.reduceSum, reduce_1.parseReduceAttributes],
+ ['ReduceSumSquare', '', '1+', reduce_1.reduceLogSumSquare, reduce_1.parseReduceAttributes],
+ ['Relu', '', '6+', unaryOps.relu],
+ ['Reshape', '', '5+', reshape_1.reshape],
+ ['Resize', '', '10', resize_packed_1.resize, resize_packed_1.parseResizeAttributesV10],
+ ['Resize', '', '11+', resize_packed_1.resize, resize_packed_1.parseResizeAttributesV11],
+ ['Shape', '', '1+', shape_1.shape],
+ ['Sigmoid', '', '6+', unaryOps.sigmoid],
+ ['Sin', '', '7+', unaryOps.sin],
+ ['Slice', '', '10+', slice_1.sliceV10],
+ ['Slice', '', '1-9', slice_1.slice, slice_1.parseSliceAttributes],
+ // The "semantic" meaning of axis has changed in opset-13.
+ ['Softmax', '', '1-12', softmax_1.softmax, softmax_1.parseSoftmaxAttributes],
+ ['Softmax', '', '13+', softmax_1.softmaxV13, softmax_1.parseSoftmaxAttributesV13],
+ // 'Split' operator has an optional attribute 'split'
+ // this attribute determines how the specified axis of input data is split.
+ // When the attribute is missing, we need the count of number of outputs
+ // so that we can determine the 'split' attribute from the runtime input to the Operator
+ ['Split', '', '2-12', split_1.split, split_1.parseSplitAttributes],
+ ['Sqrt', '', '6+', unaryOps.sqrt],
+ ['Squeeze', '', '1-12', squeeze_1.squeeze, squeeze_1.parseSqueezeAttributes],
+ ['Squeeze', '', '13+', squeeze_1.squeezeV13],
+ ['Sub', '', '7+', binaryOps.sub],
+ ['Sum', '', '6+', sum_1.sum],
+ ['Tan', '', '7+', unaryOps.tan],
+ ['Tanh', '', '6+', unaryOps.tanh],
+ ['Tile', '', '6+', tile_1.tile],
+ ['Transpose', '', '1+', transpose_1.transpose, transpose_1.parseTransposeAttributes],
+ ['Upsample', '', '7-8', upsample_1.upsample, upsample_1.parseUpsampleAttributesV7],
+ ['Upsample', '', '9', upsample_1.upsample, upsample_1.parseUpsampleAttributesV9],
+ ['Unsqueeze', '', '1-12', unsqueeze_1.unsqueeze, unsqueeze_1.parseUnsqueezeAttributes],
+ ['Unsqueeze', '', '13+', unsqueeze_1.unsqueezeV13],
+ ['Xor', '', '7+', binaryOps.xor],
+];
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/batch-normalization.ts":
+/*!**************************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/batch-normalization.ts ***!
+ \**************************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseBatchNormalizationAttributes = exports.batchNormalization = void 0;
+const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const batchNormalizationProgramMetadata = {
+ name: 'BatchNormalization',
+ inputNames: ['A', 'Scale', 'B', 'Mean', 'Variance'],
+ inputTypes: [types_1.TextureType.unpacked, types_1.TextureType.unpacked, types_1.TextureType.unpacked, types_1.TextureType.unpacked, types_1.TextureType.unpacked]
+};
+const batchNormalization = (inferenceHandler, inputs, attributes) => {
+ validateInputs(inputs);
+ const output = inferenceHandler.run(Object.assign(Object.assign({}, batchNormalizationProgramMetadata), { cacheHint: attributes.cacheKey, get: () => createBatchNormalizationProgramInfo(inferenceHandler, inputs, attributes) }), inputs);
+ return [output];
+};
+exports.batchNormalization = batchNormalization;
+const parseBatchNormalizationAttributes = (node) => {
+ const epsilon = node.attributes.getFloat('epsilon', 1e-5);
+ const momentum = node.attributes.getFloat('momentum', 0.9);
+ const spatial = node.attributes.getInt('spatial', 1);
+ return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ epsilon, momentum, spatial });
+};
+exports.parseBatchNormalizationAttributes = parseBatchNormalizationAttributes;
+const createBatchNormalizationProgramInfo = (inferenceHandler, inputs, attributes) => {
+ const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
+ const rank = inputs[0].dims.length;
+ const [scaleWidth, scaleHeight] = inferenceHandler.calculateTextureWidthAndHeight(inputs[1].dims, types_1.TextureType.unpacked);
+ const shaderSource = `
+ float process(int[${rank}] indices) {
+ vec2 position = offsetToCoords(indices[1], ${scaleWidth}, ${scaleHeight});
+ float scale = getColorAsFloat(${glsl.texture2D}(Scale, position));
+ float mean = getColorAsFloat(${glsl.texture2D}(Mean, position));
+ float variance = getColorAsFloat(${glsl.texture2D}(Variance, position));
+ float b = getColorAsFloat(${glsl.texture2D}(B, position));
+
+ return scale * ( (_A(indices) - mean) / sqrt(variance + float(${attributes.epsilon})) ) + b;
+ }`;
+ return Object.assign(Object.assign({}, batchNormalizationProgramMetadata), { output: { dims: inputs[0].dims, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource });
+};
+const validateInputs = (inputs) => {
+ if (!inputs || inputs.length !== 5) {
+ throw new Error('BatchNormalization requires 5 inputs.');
+ }
+ const X = inputs[0];
+ const scale = inputs[1];
+ const B = inputs[2];
+ const mean = inputs[3];
+ const var_ = inputs[4];
+ // input should atleast have three dimensions - N,C,dim1,...,dimn
+ // other inputs can have only one dimensions
+ if (X.dims.length < 3 || scale.dims.length !== 1 || B.dims.length !== 1 || mean.dims.length !== 1 ||
+ var_.dims.length !== 1) {
+ throw new Error('invalid input shape.');
+ }
+ if (scale.dims[0] !== X.dims[1] || B.dims[0] !== X.dims[1] || mean.dims[0] !== X.dims[1] ||
+ var_.dims[0] !== X.dims[1]) {
+ throw new Error('invalid input shape.');
+ }
+ if ((X.type !== 'float32' && X.type !== 'float64') || (scale.type !== 'float32' && scale.type !== 'float64') ||
+ (B.type !== 'float32' && B.type !== 'float64') || (mean.type !== 'float32' && mean.type !== 'float64') ||
+ (var_.type !== 'float32' && var_.type !== 'float64')) {
+ throw new Error('invalid input tensor types.');
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/binary-op.ts":
+/*!****************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/binary-op.ts ***!
+ \****************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.xor = exports.sub = exports.pRelu = exports.pow = exports.or = exports.mul = exports.less = exports.greater = exports.equal = exports.div = exports.and = exports.add = exports.glslPRelu = exports.glslPow = exports.glslXor = exports.glslOr = exports.glslAnd = exports.glslLess = exports.glslGreater = exports.glslEqual = exports.glslSub = exports.glslMul = exports.glslDiv = exports.glslAdd = void 0;
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const glsl_definitions_1 = __webpack_require__(/*! ../glsl-definitions */ "./lib/onnxjs/backends/webgl/glsl-definitions.ts");
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+function glslAdd() {
+ const name = 'add_';
+ const body = `
+ float ${name}(float a, float b) {
+ return a + b;
+ }
+ vec4 ${name}(vec4 v1, vec4 v2) {
+ return v1 + v2;
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslAdd = glslAdd;
+function glslDiv() {
+ const name = 'div_';
+ const body = `
+ float ${name}(float a, float b) {
+ return a / b;
+ }
+ vec4 ${name}(vec4 v1, vec4 v2) {
+ return v1 / v2;
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslDiv = glslDiv;
+function glslMul() {
+ const name = 'mul_';
+ const body = `
+ float ${name}(float a, float b) {
+ return a * b;
+ }
+ vec4 ${name}(vec4 v1, vec4 v2) {
+ return v1 * v2;
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslMul = glslMul;
+function glslSub() {
+ const name = 'sub_';
+ const body = `
+ float ${name}(float a, float b) {
+ return a - b;
+ }
+ vec4 ${name}(vec4 v1, vec4 v2) {
+ return v1 - v2;
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslSub = glslSub;
+function glslEqual() {
+ const name = 'equal_';
+ const body = `
+ float ${name}(float a, float b) {
+ return float(a == b);
+ }
+ vec4 ${name}(vec4 v1, vec4 v2) {
+ return vec4(equal(v1, v2));
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslEqual = glslEqual;
+function glslGreater() {
+ const name = 'greater_';
+ const body = `
+ float ${name}(float a, float b) {
+ return float(a > b);
+ }
+ vec4 ${name}(vec4 v1, vec4 v2) {
+ return vec4( v1.r > v2.r ,
+ v1.g > v2.g,
+ v1.b > v2.b,
+ v1.a > v2.a );
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslGreater = glslGreater;
+function glslLess() {
+ const name = 'less_';
+ const body = `
+ float ${name}(float a, float b) {
+ return float(a < b);
+ }
+ vec4 ${name}(vec4 v1, vec4 v2) {
+ return vec4( v1.r < v2.r ,
+ v1.g < v2.g,
+ v1.b < v2.b,
+ v1.a < v2.a );
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslLess = glslLess;
+function glslAnd() {
+ const name = 'and_';
+ const body = `
+ float ${name}(float a, float b) {
+ return float( bool(a) && bool(b) );
+ }
+ vec4 ${name}(vec4 v1, vec4 v2) {
+ bvec4 b1 = bvec4(v1);
+ bvec4 b2 = bvec4(v2);
+ return vec4( b1.r && b2.r ,
+ b1.g && b2.g,
+ b1.b && b2.b,
+ b1.a && b2.a );
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslAnd = glslAnd;
+function glslOr() {
+ const name = 'or_';
+ const body = `
+ float ${name}(float a, float b) {
+ return float( bool(a) || bool(b) );
+ }
+ vec4 ${name}(vec4 v1, vec4 v2) {
+ bvec4 b1 = bvec4(v1);
+ bvec4 b2 = bvec4(v2);
+ return vec4( b1.r || b2.r ,
+ b1.g || b2.g,
+ b1.b || b2.b,
+ b1.a || b2.a );
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslOr = glslOr;
+function glslXor() {
+ const name = 'xor_';
+ const body = `
+ float ${name}(float a, float b) {
+ return float( bool(a) ^^ bool(b) );
+ }
+ vec4 ${name}(vec4 v1, vec4 v2) {
+ bvec4 b1 = bvec4(v1);
+ bvec4 b2 = bvec4(v2);
+ return vec4( b1.r ^^ b2.r ,
+ b1.g ^^ b2.g,
+ b1.b ^^ b2.b,
+ b1.a ^^ b2.a );
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslXor = glslXor;
+function glslPow() {
+ return glslBuiltinBinary('pow');
+}
+exports.glslPow = glslPow;
+function glslPRelu() {
+ const name = 'prelu_';
+ const body = `
+ float ${name}(float a, float b) {
+ return a < 0.0 ? a * b: a;
+ }
+ vec4 ${name}(vec4 v1, vec4 v2) {
+ return vec4(
+ v1.r < 0.0 ? v1.r * v2.r: v1.r,
+ v1.g < 0.0 ? v1.g * v2.g: v1.g,
+ v1.b < 0.0 ? v1.b * v2.b: v1.b,
+ v1.a < 0.0 ? v1.a * v2.a: v1.a
+ );
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslPRelu = glslPRelu;
+function glslBuiltinBinary(fname) {
+ const name = `${fname}_`;
+ const body = `
+ float ${name}(float a, float b) {
+ return ${fname}(a, b);
+ }
+ vec4 ${name}(vec4 v1, vec4 v2) {
+ return ${fname}(v1, v2);
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+const createBinaryProgramInfoLoader = (handler, inputs, glslFunc, outputTensorType = inputs[0].type, cacheKey) => {
+ const textureType = handler.session.pack ? types_1.TextureType.packed : types_1.TextureType.unpacked;
+ return {
+ name: glslFunc.name,
+ inputNames: ['A', 'B'],
+ inputTypes: [textureType, textureType],
+ cacheHint: cacheKey,
+ get: () => createBinaryProgramInfo(handler, inputs, glslFunc, outputTensorType)
+ };
+};
+const createBinaryProgramInfo = (handler, inputs, glslFunc, outputTensorType = inputs[0].type) => {
+ const textureType = handler.session.pack ? types_1.TextureType.packed : types_1.TextureType.unpacked;
+ const isBroadcast = !util_1.ShapeUtil.areEqual(inputs[0].dims, inputs[1].dims);
+ let outputShape = inputs[0].dims;
+ const usePackedTexture = handler.session.pack;
+ if (isBroadcast) {
+ const calculatedShape = util_1.BroadcastUtil.calcShape(inputs[0].dims, inputs[1].dims, false);
+ if (!calculatedShape) {
+ throw new Error('Can\'t perform binary op on the given tensors');
+ }
+ outputShape = calculatedShape;
+ const outputRank = outputShape.length;
+ const aRank = inputs[0].dims.length !== 0 ? inputs[0].dims.length : 1;
+ const bRank = inputs[1].dims.length !== 0 ? inputs[1].dims.length : 1;
+ const aBcast = inputs[0].dims.length !== 0 ? 'bcastIndices_A(indices, aindices);' : 'aindices[0] = 0;';
+ const bBcast = inputs[1].dims.length !== 0 ? 'bcastIndices_B(indices, bindices);' : 'bindices[0] = 0;';
+ const glsl = (0, glsl_source_1.getGlsl)(handler.session.backend.glContext.version);
+ const shaderSource = usePackedTexture ? `
+ ${glslFunc.body}
+ void main() {
+ vec4 a = getAAtOutCoords();
+ vec4 b = getBAtOutCoords();
+ vec4 result = ${glslFunc.name}(a, b);
+ ${glsl.output} = result;
+ }` :
+ `
+ ${glslFunc.body}
+ float process(int indices[${outputRank}]) {
+ int aindices[${aRank}];
+ int bindices[${bRank}];
+ ${aBcast}
+ ${bBcast}
+ return ${glslFunc.name}(_A(aindices), _B(bindices));
+ }`;
+ return {
+ name: glslFunc.name,
+ inputNames: ['A', 'B'],
+ inputTypes: [textureType, textureType],
+ output: { dims: outputShape, type: outputTensorType, textureType },
+ shaderSource,
+ hasMain: usePackedTexture
+ };
+ }
+ const glsl = (0, glsl_source_1.getGlsl)(handler.session.backend.glContext.version);
+ const shaderSource = `
+ ${glslFunc.body}
+ void main() {
+ vec4 v1 = ${glsl.texture2D}(A, TexCoords);
+ vec4 v2 = ${glsl.texture2D}(B, TexCoords);
+ vec4 result = ${glslFunc.name}(v1, v2);
+ ${glsl.output} = result;
+ }
+ `;
+ return {
+ name: glslFunc.name,
+ inputNames: ['A', 'B'],
+ inputTypes: [textureType, textureType],
+ output: { dims: inputs[0].dims, type: outputTensorType, textureType },
+ shaderSource,
+ hasMain: true
+ };
+};
+const add = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslAdd()), inputs)];
+exports.add = add;
+const and = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslAnd(), 'bool'), inputs)];
+exports.and = and;
+const div = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslDiv()), inputs)];
+exports.div = div;
+const equal = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslEqual(), 'bool'), inputs)];
+exports.equal = equal;
+const greater = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslGreater(), 'bool'), inputs)];
+exports.greater = greater;
+const less = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslLess(), 'bool'), inputs)];
+exports.less = less;
+const mul = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslMul()), inputs)];
+exports.mul = mul;
+const or = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslOr(), 'bool'), inputs)];
+exports.or = or;
+const pow = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslPow()), inputs)];
+exports.pow = pow;
+const pRelu = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslPRelu()), inputs)];
+exports.pRelu = pRelu;
+const sub = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslSub()), inputs)];
+exports.sub = sub;
+const xor = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslXor(), 'bool'), inputs)];
+exports.xor = xor;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/cast.ts":
+/*!***********************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/cast.ts ***!
+ \***********************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseCastAttributes = exports.cast = void 0;
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const cast = (handler, inputs, to) => {
+ validateInputs(inputs);
+ return [handler.cast(inputs[0], to)];
+};
+exports.cast = cast;
+const parseCastAttributes = (node) => util_1.ProtoUtil.tensorDataTypeFromProto(node.attributes.getInt('to'));
+exports.parseCastAttributes = parseCastAttributes;
+const validateInputs = (inputs) => {
+ if (!inputs || inputs.length !== 1) {
+ throw new Error('Cast requires 1 input.');
+ }
+ if (inputs[0].type === 'string') {
+ throw new Error('Invalid input type.');
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/concat-packed.ts":
+/*!********************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/concat-packed.ts ***!
+ \********************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createPackedConcatProgramInfoLoader = void 0;
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const utils_1 = __webpack_require__(/*! ../utils */ "./lib/onnxjs/backends/webgl/utils.ts");
+const packing_utils_1 = __webpack_require__(/*! ./packing-utils */ "./lib/onnxjs/backends/webgl/ops/packing-utils.ts");
+const createPackedConcatProgramMetadata = (inputCount, cacheHint) => ({
+ name: 'Concat (packed)',
+ inputNames: Array.from({ length: inputCount }, (v, i) => `X${i}`),
+ inputTypes: Array(inputCount).fill(types_1.TextureType.packed),
+ cacheHint
+});
+const createPackedConcatProgramInfo = (handler, metadata, inputs, axis) => {
+ const inputShape = inputs[0].dims.slice();
+ if (axis >= inputShape.length || axis < (-1 * inputShape.length)) {
+ throw new Error('axis specified for concat doesn\'t match input dimensionality');
+ }
+ if (axis < 0) {
+ axis = inputShape.length + axis;
+ }
+ // ensure all of the non-concatenated axes match each other
+ // calculate the shape of the output tensor while we do that
+ const outputShape = inputShape.slice(0);
+ for (let i = 1; i < inputs.length; i++) {
+ const dataNShape = inputs[i].dims.slice();
+ for (let axisIndex = 0; axisIndex < inputShape.length; axisIndex++) {
+ // add to the placeholder for computing output shape
+ if (axisIndex === axis) {
+ outputShape[axis] += dataNShape[axisIndex];
+ }
+ // ensure all non-cancatenated axes match each other
+ else if (inputShape[axisIndex] !== dataNShape[axisIndex]) {
+ throw new Error('non concat dimensions must match');
+ }
+ }
+ }
+ const rank = outputShape.length;
+ const coords = (0, packing_utils_1.getChannels)('coords', rank);
+ const dtype = (0, utils_1.getCoordsDataType)(rank);
+ const unpackChannel = (0, packing_utils_1.unpackFromChannel)();
+ const shapes = inputs.map(i => i.dims);
+ const channels = (0, utils_1.getGlChannels)(rank);
+ const offsets = new Array(shapes.length - 1);
+ offsets[0] = shapes[0][axis];
+ for (let i = 1; i < offsets.length; i++) {
+ offsets[i] = offsets[i - 1] + shapes[i][axis];
+ }
+ const channel = channels[axis];
+ const lastChannels = channels.slice(-2);
+ const allChannels = channels.join();
+ let getValueSnippet = `if (${channel} < ${offsets[0]}) {
+ return getChannel(
+ getX0(${allChannels}), vec2(${lastChannels.join()}));
+ }`;
+ for (let i = 1; i < offsets.length; i++) {
+ const shift = offsets[i - 1];
+ getValueSnippet += `
+ if (${channel} < ${offsets[i]} && ${channel} >= ${offsets[i - 1]}) {
+ return getChannel(
+ getX${i}(${getShiftedChannelsSnippet(channels, channel, shift)}),
+ vec2(${getShiftedChannelsSnippet(lastChannels, channel, shift)}));
+ }`;
+ }
+ const lastIndex = offsets.length;
+ const shift = offsets[offsets.length - 1];
+ getValueSnippet += `
+ return getChannel(
+ getX${lastIndex}(${getShiftedChannelsSnippet(channels, channel, shift)}),
+ vec2(${getShiftedChannelsSnippet(lastChannels, channel, shift)}));`;
+ const glsl = (0, glsl_source_1.getGlsl)(handler.session.backend.glContext.version);
+ const shaderSource = `
+ ${unpackChannel}
+ float getValue(${channels.map(x => 'int ' + x)}) {
+ ${getValueSnippet}
+ }
+
+ void main() {
+ ${dtype} coords = getOutputCoords();
+ int lastDim = coords.${channels[rank - 1]};
+ coords.${channels[rank - 1]} = coords.${channels[rank - 2]};
+ coords.${channels[rank - 2]} = lastDim;
+
+ vec4 result = vec4(getValue(${coords}), 0., 0., 0.);
+
+ ${coords[rank - 1]} = ${coords[rank - 1]} + 1;
+ if (${coords[rank - 1]} < ${outputShape[rank - 1]}) {
+ result.g = getValue(${coords});
+ }
+
+ ${coords[rank - 2]} = ${coords[rank - 2]} + 1;
+ if (${coords[rank - 2]} < ${outputShape[rank - 2]}) {
+ result.a = getValue(${coords});
+ }
+
+ ${coords[rank - 1]} = ${coords[rank - 1]} - 1;
+ if (${coords[rank - 2]} < ${outputShape[rank - 2]} &&
+ ${coords[rank - 1]} < ${outputShape[rank - 1]}) {
+ result.b = getValue(${coords});
+ }
+ ${glsl.output} = result;
+ }
+ `;
+ return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.packed }, shaderSource, hasMain: true });
+};
+const createPackedConcatProgramInfoLoader = (handler, inputs, attributes) => {
+ const metadata = createPackedConcatProgramMetadata(inputs.length, attributes.cacheKey);
+ return Object.assign(Object.assign({}, metadata), { get: () => createPackedConcatProgramInfo(handler, metadata, inputs, attributes.axis) });
+};
+exports.createPackedConcatProgramInfoLoader = createPackedConcatProgramInfoLoader;
+const getShiftedChannelsSnippet = (channels, channel, shift) => {
+ const channelIdx = channels.indexOf(channel);
+ const res = channels.map((c, idx) => {
+ if (idx === channelIdx) {
+ return `${c} - ${shift}`;
+ }
+ else {
+ return c;
+ }
+ });
+ return res.join();
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/concat.ts":
+/*!*************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/concat.ts ***!
+ \*************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseConcatAttributes = exports.concat = void 0;
+const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const concat_packed_1 = __webpack_require__(/*! ./concat-packed */ "./lib/onnxjs/backends/webgl/ops/concat-packed.ts");
+const concat = (inferenceHandler, inputs, attributes) => {
+ validateInputs(inputs);
+ if (inferenceHandler.session.pack && inputs[0].dims.length > 1) {
+ const output = inferenceHandler.run((0, concat_packed_1.createPackedConcatProgramInfoLoader)(inferenceHandler, inputs, attributes), inputs);
+ return [output];
+ }
+ else {
+ const output = inferenceHandler.run(createUnpackedConcatProgramInfoLoader(inferenceHandler, inputs, attributes), inputs);
+ return [output];
+ }
+};
+exports.concat = concat;
+const createUnpackedConcatProgramMetadata = (inputCount, cacheHint) => ({
+ name: 'Concat',
+ inputNames: Array.from({ length: inputCount }, (v, i) => `X${i}`),
+ inputTypes: Array(inputCount).fill(types_1.TextureType.unpacked),
+ cacheHint
+});
+const createUnpackedConcatProgramInfo = (handler, metadata, inputs, axis) => {
+ const inputShape = inputs[0].dims.slice();
+ if (axis >= inputShape.length || axis < (-1 * inputShape.length)) {
+ throw new Error('axis specified for concat doesn\'t match input dimensionality');
+ }
+ if (axis < 0) {
+ axis = inputShape.length + axis;
+ }
+ // ensure all of the non-concatenated axes match each other
+ // calculate the shape of the output tensor while we do that
+ const outputShape = inputShape.slice(0);
+ for (let i = 1; i < inputs.length; i++) {
+ const dataNShape = inputs[i].dims.slice();
+ for (let axisIndex = 0; axisIndex < inputShape.length; axisIndex++) {
+ // add to the placeholder for computing output shape
+ if (axisIndex === axis) {
+ outputShape[axis] += dataNShape[axisIndex];
+ }
+ // ensure all non-cancatenated axes match each other
+ else if (inputShape[axisIndex] !== dataNShape[axisIndex]) {
+ throw new Error('non concat dimensions must match');
+ }
+ }
+ }
+ const rank = outputShape.length;
+ const sizeInConcatAxis = new Array(inputs.length);
+ let previousSum = 0;
+ for (let i = 0; i < sizeInConcatAxis.length; ++i) {
+ previousSum += inputs[i].dims[axis];
+ sizeInConcatAxis[i] = previousSum;
+ }
+ let getTextureIndexWhereDataResidesMethod = '';
+ // in most cases linear search is sufficient, as in most scenarios, only 2 tensors are concatenated
+ if (inputs.length < 5) {
+ getTextureIndexWhereDataResidesMethod = getTextureIndexWhereDataResidesLinearSearch(sizeInConcatAxis);
+ }
+ else {
+ getTextureIndexWhereDataResidesMethod = getTextureIndexWhereDataResidesBinarySearch(sizeInConcatAxis);
+ }
+ const fetchDataFromCorrectTextureMethod = getFetchDataFromCorrectTextureMethod(inputs.length, rank);
+ const getSizeInConcatAxisValueFromIndexMethod = getGetSizeInConcatAxisValueFromIndexMethod(sizeInConcatAxis);
+ const shaderSource = `
+ ${fetchDataFromCorrectTextureMethod}
+ ${getSizeInConcatAxisValueFromIndexMethod}
+ ${getTextureIndexWhereDataResidesMethod}
+ float process(int indices[${rank}]) {
+ int textureIndex = getTextureWhereDataResides (indices[${axis}]);
+
+ if(textureIndex != 0) {
+ indices[${axis}] = indices[${axis}] - int(getSizeInConcatAxisValueFromIndex(textureIndex-int(1)));
+ }
+
+ return fetchDataFromCorrectTexture(textureIndex, indices);
+ }`;
+ return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource });
+};
+const createUnpackedConcatProgramInfoLoader = (handler, inputs, attributes) => {
+ const metadata = createUnpackedConcatProgramMetadata(inputs.length, attributes.cacheKey);
+ return Object.assign(Object.assign({}, metadata), { get: () => createUnpackedConcatProgramInfo(handler, metadata, inputs, attributes.axis) });
+};
+const getTextureIndexWhereDataResidesLinearSearch = (sizeInConcatAxis) => {
+ const searchAxis = sizeInConcatAxis.map((size, i) => `if(index<${size}) {return ${i};}
+`);
+ return `int getTextureWhereDataResides(int index) {
+ ${searchAxis.join('')}
+ }`;
+};
+// TODO: Implement BinarySearch in GLSL
+const getTextureIndexWhereDataResidesBinarySearch = (sizeInConcatAxis) => getTextureIndexWhereDataResidesLinearSearch(sizeInConcatAxis);
+const getFetchDataFromCorrectTextureMethod = (numberOfTensors, tensorRank) => {
+ const codeLines = [`float fetchDataFromCorrectTexture(int textureIndex, int indices[${tensorRank}]) {`];
+ for (let i = 0; i < numberOfTensors; ++i) {
+ if (i === 0) {
+ codeLines.push('\t' +
+ `if (textureIndex == ${i}) { return _X${i}(indices); }`);
+ }
+ else if (i === numberOfTensors - 1) {
+ codeLines.push('\t' +
+ `else { return _X${i}(indices); }`);
+ }
+ else {
+ codeLines.push('\t' +
+ `else if (textureIndex == ${i}) { return _X${i}(indices); }`);
+ }
+ }
+ codeLines.push('\t' +
+ '}');
+ return codeLines.join('\n');
+};
+const getGetSizeInConcatAxisValueFromIndexMethod = (sizeInConcatAxis) => {
+ const codeLines = ['int getSizeInConcatAxisValueFromIndex(int index) {'];
+ for (let i = 0; i < sizeInConcatAxis.length; ++i) {
+ if (i === 0) {
+ codeLines.push('\t' +
+ `if (index == ${i}) { return ${sizeInConcatAxis[i]}; }`);
+ }
+ else if (i === sizeInConcatAxis.length - 1) {
+ codeLines.push('\t' +
+ `else { return ${sizeInConcatAxis[i]}; }`);
+ }
+ else {
+ codeLines.push('\t' +
+ `else if (index == ${i}) { return ${sizeInConcatAxis[i]}; }`);
+ }
+ }
+ codeLines.push('\t' +
+ '}');
+ return codeLines.join('\n');
+};
+const parseConcatAttributes = (node) => (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ axis: node.attributes.getInt('axis') });
+exports.parseConcatAttributes = parseConcatAttributes;
+const validateInputs = (inputs) => {
+ if (!inputs || inputs.length < 1) {
+ throw new Error('too few inputs');
+ }
+ const inputType = inputs[0].type;
+ const inputDimensionality = inputs[0].dims.length;
+ // TODO: Support string concat
+ if (inputType === 'string') {
+ throw new Error('string tensor is not supported yet');
+ }
+ for (const input of inputs) {
+ // make sure types of all inputs match
+ if (input.type !== inputType) {
+ throw new Error('input tensors should be one type');
+ }
+ // make sure the dimensionality of all inputs are the same
+ if (input.dims.length !== inputDimensionality) {
+ throw new Error('input tensors should have the same shape');
+ }
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/conv-grouped.ts":
+/*!*******************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/conv-grouped.ts ***!
+ \*******************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createUnpackedGroupedConvProgramInfoLoader = void 0;
+const instrument_1 = __webpack_require__(/*! ../../../instrument */ "./lib/onnxjs/instrument.ts");
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const conv_1 = __webpack_require__(/*! ./conv */ "./lib/onnxjs/backends/webgl/ops/conv.ts");
+const fuse_utils_1 = __webpack_require__(/*! ./fuse-utils */ "./lib/onnxjs/backends/webgl/ops/fuse-utils.ts");
+const createUnpackedGroupedConvProgramMetadata = (hasBias, cacheHint) => ({
+ name: 'GroupedConv',
+ inputNames: hasBias ? ['X', 'W', 'Bias'] : ['X', 'W'],
+ inputTypes: hasBias ? [types_1.TextureType.unpacked, types_1.TextureType.unpacked, types_1.TextureType.unpacked] :
+ [types_1.TextureType.unpacked, types_1.TextureType.unpacked],
+ cacheHint
+});
+const createUnpackedGroupedConvProgramInfo = (inferenceHandler, inputs, metadata, attributes) => {
+ const hasBias = inputs.length > 2;
+ const processBias = hasBias ? 'value += getBias(output_channel);' : '';
+ const xShape = inputs[0].dims.slice();
+ const wShape = inputs[1].dims.slice();
+ const outputChannelsPerGroup = wShape[0] / attributes.group;
+ instrument_1.Logger.verbose('GroupedConv', `autpPad:${attributes.autoPad}, dilations:${attributes.dilations}, group:${attributes.group}, kernelShape:${attributes.kernelShape}, pads:${attributes.pads}, strides:${attributes.strides}`);
+ const outputShape = (0, conv_1.calculateOutputShape)(xShape, wShape, attributes.dilations, attributes.pads, attributes.strides);
+ const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
+ const { activationFunction, applyActivation } = (0, fuse_utils_1.getActivationSnippet)(attributes);
+ const shaderSource = `
+ const ivec2 strides = ivec2(${attributes.strides[0]}, ${attributes.strides[1]});
+ const ivec2 pads = ivec2(${attributes.pads[0]}, ${attributes.pads[1]});
+ ${activationFunction}
+ void main() {
+ ivec4 coords = getOutputCoords();
+ int batch = coords.x;
+ int output_channel = coords.y;
+ ivec2 xRCCorner = coords.zw * strides - pads;
+ int group_id = output_channel / ${outputChannelsPerGroup};
+
+ float value = 0.0;
+ for (int wInChannel = 0; wInChannel < ${wShape[1]}; wInChannel++) {
+ int input_channel = group_id * ${wShape[1]} + wInChannel;
+ for (int wHeight = 0; wHeight < ${wShape[2]}; wHeight++) {
+ int xHeight = xRCCorner.x + wHeight * ${attributes.dilations[0]};
+
+ if (xHeight < 0 || xHeight >= ${xShape[2]}) {
+ continue;
+ }
+
+ for (int wWidth = 0; wWidth < ${wShape[3]}; wWidth++) {
+ int xWidth = xRCCorner.y + wWidth * ${attributes.dilations[1]};
+ if (xWidth < 0 || xWidth >= ${xShape[3]}) {
+ continue;
+ }
+
+ float xVal = getX(batch, input_channel, xWidth, xHeight);
+ float wVal = getW(output_channel, wInChannel, wWidth, wHeight);
+ value += xVal*wVal;
+ }
+ }
+ }
+ ${processBias}
+ ${applyActivation}
+ ${glsl.output} = vec4(value, .0, .0, .0);
+ }
+`;
+ return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource, hasMain: true });
+};
+const createUnpackedGroupedConvProgramInfoLoader = (inferenceHandler, inputs, attributes) => {
+ const metadata = createUnpackedGroupedConvProgramMetadata(inputs.length > 2, attributes.cacheKey);
+ return Object.assign(Object.assign({}, metadata), { get: () => createUnpackedGroupedConvProgramInfo(inferenceHandler, inputs, metadata, attributes) });
+};
+exports.createUnpackedGroupedConvProgramInfoLoader = createUnpackedGroupedConvProgramInfoLoader;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/conv-pack.ts":
+/*!****************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/conv-pack.ts ***!
+ \****************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.conv2DPacked = exports.conv2DPackedPointwise = void 0;
+const conv_1 = __webpack_require__(/*! ./conv */ "./lib/onnxjs/backends/webgl/ops/conv.ts");
+const im2col_pack_1 = __webpack_require__(/*! ./im2col-pack */ "./lib/onnxjs/backends/webgl/ops/im2col-pack.ts");
+const matmul_pack_1 = __webpack_require__(/*! ./matmul-pack */ "./lib/onnxjs/backends/webgl/ops/matmul-pack.ts");
+const conv2DPackedPointwise = (inferenceHandler, inputs, attributes) => {
+ const xshape = inputs[0].dims;
+ const kshape = inputs[1].dims;
+ const outputShape = (0, conv_1.calculateOutputShape)(xshape, kshape, attributes.dilations, attributes.pads, attributes.strides);
+ const reshapedX = inferenceHandler.reshapePacked(inputs[0], [xshape[1], xshape[2] * xshape[3]]);
+ const reshapedK = inferenceHandler.reshapePacked(inputs[1], [kshape[0], kshape[1]]);
+ const matmulInputs = inputs.length > 2 ? [reshapedK, reshapedX, inputs[2]] : [reshapedK, reshapedX];
+ const matmulOutput = inferenceHandler.run((0, matmul_pack_1.createPackedMatmulProgramInfoLoader)(inferenceHandler, matmulInputs, attributes), matmulInputs);
+ return inferenceHandler.reshapePacked(matmulOutput, outputShape);
+};
+exports.conv2DPackedPointwise = conv2DPackedPointwise;
+const conv2DPacked = (inferenceHandler, inputs, attributes) => {
+ const xshape = inputs[0].dims;
+ const kshape = inputs[1].dims;
+ const outputShape = (0, conv_1.calculateOutputShape)(xshape, kshape, attributes.dilations, attributes.pads, attributes.strides);
+ // run im2col
+ const im2colOutput = inferenceHandler.run((0, im2col_pack_1.createPackedIm2ColProgramInfoLoader)(inferenceHandler, inputs[0], inputs[1], outputShape, attributes), [inputs[0]]);
+ // reshape kernel
+ const kernelReshaped = inferenceHandler.reshapePacked(inputs[1], [kshape[0], kshape[1] * kshape[2] * kshape[3]]);
+ // run matmul
+ const matmulInputs = (inputs.length === 3) ? [kernelReshaped, im2colOutput, inputs[2]] : [kernelReshaped, im2colOutput];
+ const matmulOutput = inferenceHandler.run((0, matmul_pack_1.createPackedMatmulProgramInfoLoader)(inferenceHandler, matmulInputs, attributes), matmulInputs);
+ // reshape output
+ const outputReshaped = inferenceHandler.reshapePacked(matmulOutput, outputShape);
+ return outputReshaped;
+};
+exports.conv2DPacked = conv2DPacked;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/conv-transpose.ts":
+/*!*********************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/conv-transpose.ts ***!
+ \*********************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseConvTransposeAttributes = exports.convTranspose = void 0;
+const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const fuse_utils_1 = __webpack_require__(/*! ./fuse-utils */ "./lib/onnxjs/backends/webgl/ops/fuse-utils.ts");
+const computeTotalPad = (inDim, stride, adj, kernel, dilation, outSize) => (inDim - 1) * stride + adj + (kernel - 1) * dilation + 1 - outSize;
+const distributePadding = (totalPad, autoPad, pads, head, tail) => {
+ const smallPad = Math.floor(totalPad / 2);
+ if (autoPad === 'SAME_UPPER') {
+ pads[head] = smallPad;
+ pads[tail] = totalPad - smallPad;
+ }
+ else if (autoPad === 'SAME_LOWER') {
+ pads[head] = totalPad - smallPad;
+ pads[tail] = smallPad;
+ }
+};
+const calculateOutputShapeAndPads = (inputShape, kernelShape, dilations, autoPad, pads, strides, outputPadding, outputShape) => {
+ const spatialRank = inputShape.length - 2;
+ const updateShape = outputShape.length === 0;
+ for (let i = 0; i < spatialRank; ++i) {
+ const outSize = updateShape ? inputShape[i + 2] * strides[i] : outputShape[i];
+ const totalPad = computeTotalPad(inputShape[i + 2], strides[i], pads[i], kernelShape[i], dilations[i], outSize);
+ distributePadding(totalPad, autoPad, pads, i, i + spatialRank);
+ if (updateShape) {
+ outputShape.push(strides[i] * (inputShape[i + 2] - 1) + outputPadding[i] + (kernelShape[i] - 1) * dilations[i] + 1 -
+ pads[i] - pads[i + spatialRank]);
+ }
+ }
+};
+const convTranspose = (inferenceHandler, inputs, attributes) => {
+ validateInputs(inputs, attributes); // currently will fail if not convTranspose2D
+ return convTranspose2d(inferenceHandler, inputs, attributes);
+};
+exports.convTranspose = convTranspose;
+const convTranspose2d = (inferenceHandler, inputs, attributes) => {
+ const adjustedAttributes = getAdjustedConvTransposeAttributes(attributes, inputs);
+ return [convTranspose2DUnpacked(inferenceHandler, inputs, adjustedAttributes)];
+};
+const createConvTransposeProgramMetadata = (hasBias, cacheHint) => ({
+ name: 'ConvTranspose',
+ inputNames: hasBias ? ['X', 'W', 'B'] : ['X', 'W'],
+ inputTypes: hasBias ? [types_1.TextureType.unpacked, types_1.TextureType.unpacked, types_1.TextureType.unpacked] :
+ [types_1.TextureType.unpacked, types_1.TextureType.unpacked],
+ cacheHint
+});
+const createUnpackedConvTransposeProgramInfo = (inferenceHandler, inputs, metadata, attributes) => {
+ const hasBias = inputs.length > 2;
+ const valueInit = hasBias ? 'getB(output_channel)' : '0.0';
+ const xShape = inputs[0].dims;
+ const wShape = inputs[1].dims;
+ const outputChannelsPerGroup = wShape[1];
+ const inputChannelsPerGroup = wShape[0] / attributes.group;
+ const outputShape = [inputs[0].dims[0], inputs[1].dims[1] * attributes.group, ...attributes.outputShape];
+ const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
+ const { activationFunction, applyActivation } = (0, fuse_utils_1.getActivationSnippet)(attributes);
+ const shaderSource = `
+ const ivec2 strides = ivec2(${attributes.strides[0]}, ${attributes.strides[1]});
+ const ivec2 pads = ivec2(${attributes.pads[0]}, ${attributes.pads[1]});
+ ${activationFunction}
+ void main() {
+ ivec4 coords = getOutputCoords();
+ int batch = coords.x;
+ int output_channel = coords.y;
+
+ ivec2 loc = coords.zw + pads;
+
+ int group_id = output_channel / ${outputChannelsPerGroup};
+ int wOutChannel = output_channel - group_id * ${outputChannelsPerGroup};
+
+ float value = ${valueInit};
+ for (int inChannelOffset = 0; inChannelOffset < ${inputChannelsPerGroup}; inChannelOffset++) {
+ int input_channel = group_id * ${inputChannelsPerGroup} + inChannelOffset;
+ for (int wWOff = 0; wWOff < ${wShape[2]}; wWOff++) {
+ for (int wHOff = 0; wHOff < ${wShape[3]}; wHOff++) {
+ ivec2 wOff = ivec2(wWOff * ${attributes.dilations[0]}, wHOff * ${attributes.dilations[1]});
+ ivec2 wLoc = loc - wOff;
+ ivec2 wLocIn = wLoc / strides;
+ if (
+ wLocIn * strides == wLoc &&
+ wLocIn.x >= 0 && wLocIn.x < ${xShape[2]} &&
+ wLocIn.y >= 0 && wLocIn.y < ${xShape[3]}
+ ) {
+ float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x);
+ float wVal = getW(input_channel, wOutChannel, wHOff, wWOff);
+ value += xVal * wVal;
+ }
+ }
+ }
+ }
+ ${applyActivation}
+ ${glsl.output} = vec4(value, .0, .0, .0);
+ }
+`;
+ return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource, hasMain: true });
+};
+const createUnpackedConvTransposeProgramInfoLoader = (inferenceHandler, inputs, attributes) => {
+ const metadata = createConvTransposeProgramMetadata(inputs.length > 2, attributes.cacheKey);
+ return Object.assign(Object.assign({}, metadata), { get: () => createUnpackedConvTransposeProgramInfo(inferenceHandler, inputs, metadata, attributes) });
+};
+const convTranspose2DUnpacked = (inferenceHandler, inputs, attributes) => {
+ const result = inferenceHandler.run(createUnpackedConvTransposeProgramInfoLoader(inferenceHandler, inputs, attributes), inputs);
+ return result;
+};
+const getAdjustedConvTransposeAttributes = (attributes, inputs) => {
+ const kernelShape = attributes.kernelShape.slice();
+ // if kernelShape is not specified in the attributes of this op, infer it from the weight tensor dims
+ if (attributes.kernelShape.length === 0) {
+ for (let i = 2; i < inputs[1].dims.length; ++i) {
+ kernelShape.push(inputs[1].dims[i]);
+ }
+ }
+ const pads = attributes.pads.slice();
+ const outputShape = attributes.outputShape.slice();
+ const inputShape = inputs[0].dims;
+ // If outputShape is not specified in the attributes of this op, infer it from the parameters
+ // Similarly, automatically infer pads if not specified
+ calculateOutputShapeAndPads(inputShape, kernelShape, attributes.dilations, attributes.autoPad, pads, attributes.strides, attributes.outputPadding, outputShape);
+ // always return a new object so does not modify the original attributes
+ const newAttributes = Object.assign({}, attributes);
+ Object.assign(newAttributes, { kernelShape, pads, outputShape, cacheKey: attributes.cacheKey });
+ return newAttributes;
+};
+const parseConvTransposeAttributes = (node) => {
+ const attributes = node.attributes;
+ const activationAttributes = (0, fuse_utils_1.parseInternalActivationAttributes)(attributes);
+ // TODO : Make this generic enough to compute default attributes for multi-dimensional conv
+ const autoPad = attributes.getString('auto_pad', 'NOTSET');
+ const dilations = attributes.getInts('dilations', [1, 1]);
+ const group = attributes.getInt('group', 1);
+ const kernelShape = attributes.getInts('kernel_shape', []);
+ const outputPadding = attributes.getInts('output_padding', [0, 0]);
+ const outputShape = attributes.getInts('output_shape', []);
+ const pads = attributes.getInts('pads', [0, 0, 0, 0]);
+ const strides = attributes.getInts('strides', [1, 1]);
+ return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)(Object.assign({ autoPad, dilations, group, kernelShape, outputPadding, outputShape, pads, strides }, activationAttributes));
+};
+exports.parseConvTransposeAttributes = parseConvTransposeAttributes;
+const validateInputs = (inputs, attributes) => {
+ // Refer to the below link for all input checks
+ // https://github.com/onnx/onnx/blob/main/docs/Operators.md#Conv
+ if (!inputs || (inputs.length !== 2 && inputs.length !== 3)) {
+ throw new Error('Conv requires 2 or 3 inputs');
+ }
+ // TODO : Need to add support for multi-dimensional conv
+ if (inputs[0].dims.length !== 4 || inputs[1].dims.length !== 4) {
+ throw new Error('currently only support 2-dimensional conv');
+ }
+ // FILTER_IN_CHANNEL should be equal to DATA_CHANNEL
+ const dataChannel = inputs[0].dims[1];
+ const filterInChannel = inputs[1].dims[0];
+ if (dataChannel !== filterInChannel) {
+ throw new Error('FILTER_IN_CHANNEL should be equal to DATA_CHANNEL');
+ }
+ const featureMaps = inputs[1].dims[1] * attributes.group;
+ // if bias is provided it should be 1D and the number of elements should be equal to the number of feature maps
+ if (inputs.length === 3 && (inputs[2].dims.length !== 1 || inputs[2].dims[0] !== featureMaps)) {
+ throw new Error('invalid bias');
+ }
+ const spatialRank = inputs[0].dims.length - 2;
+ // wrong dilations dimension
+ if (attributes.dilations.length !== spatialRank) {
+ throw new Error(`dilations should be ${spatialRank}D`);
+ }
+ // Wrong strides dimension
+ if (attributes.strides.length !== spatialRank) {
+ throw new Error(`strides should be ${spatialRank}D`);
+ }
+ // Wrong pads dimension
+ if (attributes.pads.length !== spatialRank * 2) {
+ throw new Error(`pads should be ${spatialRank * 2}D`);
+ }
+ // Wrong output padding dimension
+ if (attributes.outputPadding.length !== spatialRank) {
+ throw new Error(`output_padding should be ${spatialRank}D`);
+ }
+ // if kernelShape is specified, it's data length must be 2 less than dims length of the weights tensor
+ // (the first 2 dims are batch_size and channels)
+ if (attributes.kernelShape.length !== 0 && attributes.kernelShape.length !== inputs[1].dims.length - 2) {
+ throw new Error('invalid kernel shape');
+ }
+ // as with kernelShape, must have same number of spatial dims as input
+ if (attributes.outputShape.length !== 0 && attributes.outputShape.length !== inputs[0].dims.length - 2) {
+ throw new Error('invalid output shape');
+ }
+ // TODO : Need to add support for float64
+ if (inputs[0].type !== 'float32' || inputs[1].type !== 'float32') {
+ throw new Error('ConvTranspose input(X,W) should be float tensor');
+ }
+ if (inputs.length === 3 && inputs[2].type !== 'float32') {
+ throw new Error('ConvTranspose input(bias) should be float tensor');
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/conv.ts":
+/*!***********************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/conv.ts ***!
+ \***********************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseConvAttributes = exports.conv = exports.calculateOutputShape = void 0;
+const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const conv_grouped_1 = __webpack_require__(/*! ./conv-grouped */ "./lib/onnxjs/backends/webgl/ops/conv-grouped.ts");
+const conv_pack_1 = __webpack_require__(/*! ./conv-pack */ "./lib/onnxjs/backends/webgl/ops/conv-pack.ts");
+const dot_product_1 = __webpack_require__(/*! ./dot-product */ "./lib/onnxjs/backends/webgl/ops/dot-product.ts");
+const fuse_utils_1 = __webpack_require__(/*! ./fuse-utils */ "./lib/onnxjs/backends/webgl/ops/fuse-utils.ts");
+const im2col_1 = __webpack_require__(/*! ./im2col */ "./lib/onnxjs/backends/webgl/ops/im2col.ts");
+const matmul_1 = __webpack_require__(/*! ./matmul */ "./lib/onnxjs/backends/webgl/ops/matmul.ts");
+const calculateOutputShape = (inputShape, kernelShape, dilations, adjustPads, strides) => {
+ const batchSize = inputShape[0];
+ const inputSpatialShape = inputShape.slice(2);
+ const spatialRank = inputSpatialShape.length;
+ const outChannels = kernelShape[0];
+ const kernelSpatialShape = kernelShape.slice(2);
+ const dilatedKernelShape = kernelSpatialShape.map((v, i) => v + (v - 1) * (dilations[i] - 1));
+ const inputSpatialShapeWithPad = inputSpatialShape.map((v, i) => v + adjustPads[i] + adjustPads[i + spatialRank]);
+ const outputSpatialShape = inputSpatialShapeWithPad.map((v, i) => Math.floor((v - dilatedKernelShape[i] + strides[i]) / strides[i]));
+ const outputShape = [batchSize, outChannels].concat(...outputSpatialShape);
+ return outputShape;
+};
+exports.calculateOutputShape = calculateOutputShape;
+const conv = (inferenceHandler, inputs, attributes) => {
+ validateInputs(inputs, attributes); // currently will fail if not conv2D
+ return conv2d(inferenceHandler, inputs, attributes);
+};
+exports.conv = conv;
+const conv2d = (inferenceHandler, inputs, attributes) => {
+ const adjustedAttributes = getAdjustedConvAttributes(attributes, inputs);
+ const packMode = inferenceHandler.session.pack;
+ const isPointwise = adjustedAttributes.kernelShape[0] === 1 && adjustedAttributes.kernelShape[1] === 1;
+ if (adjustedAttributes.group > 1) {
+ const result = inferenceHandler.run((0, conv_grouped_1.createUnpackedGroupedConvProgramInfoLoader)(inferenceHandler, inputs, adjustedAttributes), inputs);
+ return [result];
+ }
+ else if (isPointwise && packMode) {
+ return [conv2DUnpackedPointwise(inferenceHandler, inputs, adjustedAttributes)];
+ }
+ else if (packMode && inputs[0].dims.length === 4 && inputs[0].dims[0] === 1 && !isPointwise) {
+ return [(0, conv_pack_1.conv2DPacked)(inferenceHandler, inputs, adjustedAttributes)];
+ }
+ else {
+ return [conv2DUnpacked(inferenceHandler, inputs, adjustedAttributes)];
+ }
+};
+const conv2DUnpackedPointwise = (inferenceHandler, inputs, attributes) => {
+ const xshape = inputs[0].dims;
+ const kshape = inputs[1].dims;
+ const outputShape = (0, exports.calculateOutputShape)(xshape, kshape, attributes.dilations, attributes.pads, attributes.strides);
+ const reshapedX = inferenceHandler.reshapeUnpacked(inputs[0], [xshape[1], xshape[2] * xshape[3]]);
+ const reshapedK = inferenceHandler.reshapeUnpacked(inputs[1], [kshape[0], kshape[1]]);
+ const matmulInputs = inputs.length > 2 ? [reshapedK, reshapedX, inputs[2]] : [reshapedK, reshapedX];
+ const matmulOutput = inferenceHandler.run((0, matmul_1.createMatmulProgramInfoLoader)(matmulInputs, attributes), matmulInputs);
+ return inferenceHandler.reshapeUnpacked(matmulOutput, outputShape);
+};
+const conv2DUnpacked = (inferenceHandler, inputs, attributes) => {
+ const xshape = inputs[0].dims;
+ const kshape = inputs[1].dims;
+ const outputShape = (0, exports.calculateOutputShape)(xshape, kshape, attributes.dilations, attributes.pads, attributes.strides);
+ const xIm2Col = inferenceHandler.run((0, im2col_1.createIm2ColProgramInfoLoader)(inferenceHandler, inputs[0], inputs[1], outputShape, attributes), [inputs[0]]);
+ const dotProductInputs = inputs.length === 3 ? [xIm2Col, inputs[1], inputs[2]] : [xIm2Col, inputs[1]];
+ const output = inferenceHandler.run((0, dot_product_1.createDotProductProgramInfoLoader)(inferenceHandler, inputs, outputShape, attributes), dotProductInputs);
+ return output;
+};
+const getAdjustedConvAttributes = (attributes, inputs) => {
+ const kernelShape = attributes.kernelShape.slice();
+ // if kernelShape is not specified in the attributes of this op, infer it from the weight tensor dims
+ if (attributes.kernelShape.length === 0) {
+ for (let i = 2; i < inputs[1].dims.length; ++i) {
+ kernelShape.push(inputs[1].dims[i]);
+ }
+ }
+ const pads = attributes.pads.slice();
+ util_1.PoolConvUtil.adjustPadsBasedOnAutoPad(inputs[0].dims, attributes.strides, attributes.dilations, kernelShape, pads, attributes.autoPad);
+ // always return a new object so does not modify the original attributes
+ const newAttributes = Object.assign({}, attributes);
+ Object.assign(newAttributes, { kernelShape, pads, cacheKey: attributes.cacheKey });
+ return newAttributes;
+};
+const parseConvAttributes = (node) => {
+ const attributes = node.attributes;
+ const activationAttributes = (0, fuse_utils_1.parseInternalActivationAttributes)(attributes);
+ // TODO : Make this generic enough to compute default attributes for multi-dimensional conv
+ const autoPad = attributes.getString('auto_pad', 'NOTSET');
+ const dilations = attributes.getInts('dilations', [1, 1]);
+ const group = attributes.getInt('group', 1);
+ const kernelShape = attributes.getInts('kernel_shape', []);
+ const pads = attributes.getInts('pads', [0, 0, 0, 0]);
+ const strides = attributes.getInts('strides', [1, 1]);
+ return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)(Object.assign({ autoPad, dilations, group, kernelShape, pads, strides }, activationAttributes));
+};
+exports.parseConvAttributes = parseConvAttributes;
+const validateInputs = (inputs, attributes) => {
+ // Refer to the below link for all input checks
+ // https://github.com/onnx/onnx/blob/main/docs/Operators.md#Conv
+ if (!inputs || (inputs.length !== 2 && inputs.length !== 3)) {
+ throw new Error('Conv requires 2 or 3 inputs');
+ }
+ // TODO : Need to add support for multi-dimensional conv
+ if (inputs[0].dims.length !== 4 || inputs[1].dims.length !== 4) {
+ throw new Error('currently only support 2-dimensional conv');
+ }
+ // FILTER_IN_CHANNEL should be equal to DATA_CHANNEL
+ const dataChannel = inputs[0].dims[1];
+ const filterInChannel = inputs[1].dims[1] * attributes.group;
+ if (dataChannel !== filterInChannel) {
+ throw new Error('FILTER_IN_CHANNEL should be equal to DATA_CHANNEL');
+ }
+ // if bias is provided it should be 1D and the number of elements should be equal to the number of feature maps
+ if (inputs.length === 3 && (inputs[2].dims.length !== 1 || inputs[1].dims[0] !== inputs[2].dims[0])) {
+ throw new Error('invalid bias');
+ }
+ const spatialRank = inputs[0].dims.length - 2;
+ // wrong dilations dimension
+ if (attributes.dilations.length !== spatialRank) {
+ throw new Error(`dilations should be ${spatialRank}D`);
+ }
+ // Wrong strides dimension
+ if (attributes.strides.length !== spatialRank) {
+ throw new Error(`strides should be ${spatialRank}D`);
+ }
+ // Wrong pads dimension
+ if (attributes.pads.length !== spatialRank * 2) {
+ throw new Error(`pads should be ${spatialRank * 2}D`);
+ }
+ // if kernelShape is specified, it's data length must be 2 less than dims length of the weights tensor
+ // (the first 2 dims are batch_size and channels)
+ if (attributes.kernelShape.length !== 0 && attributes.kernelShape.length !== inputs[1].dims.length - 2) {
+ throw new Error('invalid kernel shape');
+ }
+ // TODO : Need to add support for float64
+ if (inputs[0].type !== 'float32' || inputs[1].type !== 'float32') {
+ throw new Error('Conv input(X,W) should be float tensor');
+ }
+ if (inputs.length === 3 && inputs[2].type !== 'float32') {
+ throw new Error('Conv input(bias) should be float tensor');
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/depth-to-space.ts":
+/*!*********************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/depth-to-space.ts ***!
+ \*********************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseDepthToSpaceAttributes = exports.depthToSpace = void 0;
+const transpose_1 = __webpack_require__(/*! ./transpose */ "./lib/onnxjs/backends/webgl/ops/transpose.ts");
+const depthToSpace = (inferenceHandler, inputs, attributes) => {
+ validateInputs(inputs);
+ const blocksize = attributes.blocksize;
+ const blocksizeSqr = blocksize * blocksize;
+ const transposePerm = attributes.mode === 'DCR' ? [0, 3, 4, 1, 5, 2] : [0, 1, 4, 2, 5, 3];
+ const firstReshapeShape = attributes.mode === 'DCR' ?
+ [
+ inputs[0].dims[0], blocksize, blocksize, inputs[0].dims[1] / blocksizeSqr, inputs[0].dims[2],
+ inputs[0].dims[3]
+ ] :
+ [
+ inputs[0].dims[0], inputs[0].dims[1] / blocksizeSqr, blocksize, blocksize, inputs[0].dims[2],
+ inputs[0].dims[3]
+ ];
+ // const transpose = new WebGLTranspose();
+ // const attributes = new Attribute(undefined);
+ // attributes.set('perm', 'ints', transposePerm);
+ // transpose.initialize(attributes);
+ // First reshape
+ const firstReshapedTensor = inferenceHandler.reshapeUnpacked(inputs[0], firstReshapeShape);
+ // transpose
+ const transposeAttributes = { perm: transposePerm, cacheKey: `${transposePerm}` };
+ const [transposeOutput] = (0, transpose_1.transpose)(inferenceHandler, [firstReshapedTensor], transposeAttributes);
+ // Second reshape
+ const secondReshapeShape = [
+ inputs[0].dims[0], inputs[0].dims[1] / blocksizeSqr, inputs[0].dims[2] * blocksize,
+ inputs[0].dims[3] * blocksize
+ ];
+ const result = inferenceHandler.reshapeUnpacked(transposeOutput, secondReshapeShape);
+ return [result];
+};
+exports.depthToSpace = depthToSpace;
+const parseDepthToSpaceAttributes = (node) => {
+ // processing node attributes
+ const blocksize = node.attributes.getInt('blocksize');
+ if (blocksize < 1) {
+ throw new Error(`blocksize must be >= 1, but got : ${blocksize} for DepthToSpace`);
+ }
+ const mode = node.attributes.getString('mode', 'DCR');
+ if (mode !== 'DCR' && mode !== 'CRD') {
+ throw new Error(`unrecognized mode: ${mode} for DepthToSpace`);
+ }
+ return { mode, blocksize };
+};
+exports.parseDepthToSpaceAttributes = parseDepthToSpaceAttributes;
+const validateInputs = (inputs) => {
+ if (inputs.length !== 1) {
+ throw new Error(`DepthToSpace expect 1 inputs, but got ${inputs.length}`);
+ }
+ // Input has to be a 4-D tensor
+ // TODO: Support string depth-to-space.
+ if (inputs[0].type === 'string' || inputs[0].dims.length !== 4) {
+ throw new TypeError('DepthToSpace input should be a 4-D numeric tensor');
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/dot-product.ts":
+/*!******************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/dot-product.ts ***!
+ \******************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createDotProductProgramInfoLoader = void 0;
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const fuse_utils_1 = __webpack_require__(/*! ./fuse-utils */ "./lib/onnxjs/backends/webgl/ops/fuse-utils.ts");
+const im2col_1 = __webpack_require__(/*! ./im2col */ "./lib/onnxjs/backends/webgl/ops/im2col.ts");
+const createDotProductProgramMetadata = (hasBias, attributes) => ({
+ name: 'ConvDotProduct',
+ inputNames: hasBias ? ['Im2Col', 'K', 'B'] : ['Im2Col', 'K'],
+ inputTypes: hasBias ? [types_1.TextureType.unpacked, types_1.TextureType.packedLastDimension, types_1.TextureType.unpacked] :
+ [types_1.TextureType.unpacked, types_1.TextureType.packedLastDimension],
+ cacheKey: attributes.activationCacheKey
+});
+const createDotProductProgramInfo = (inferenceHandler, metadata, inputs, outputShape, attributes) => {
+ const xshape = inputs[0].dims;
+ const kshape = inputs[1].dims;
+ const adjustedKernelShape = [kshape[0], Math.ceil((xshape[1] * kshape[2] * kshape[3]) / 4)];
+ const im2colShape = (0, im2col_1.calculateIm2ColDims)(xshape, kshape, outputShape);
+ const [kWidth, kHeight] = inferenceHandler.calculateTextureWidthAndHeight(adjustedKernelShape, types_1.TextureType.packedLastDimension);
+ const im2colStrides = util_1.ShapeUtil.computeStrides(im2colShape);
+ const [im2colWidth, im2colHeight] = inferenceHandler.calculateTextureWidthAndHeight(im2colShape, types_1.TextureType.packedLastDimension);
+ const rank = outputShape.length;
+ const initValue = (inputs.length < 3) ? '0.0' : '_B(b)';
+ const sharedDim = Math.ceil(xshape[1] * kshape[2] * kshape[3] / 4);
+ const { activationFunction, applyActivation } = (0, fuse_utils_1.getActivationSnippet)(attributes);
+ const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
+ const shaderSource = `
+${activationFunction}
+float process(int indices[${rank}]) {
+ int b[1];
+ b[0] = indices[1];
+ int im2col[4];
+ im2col[0] = indices[0];
+ im2col[1] = indices[2];
+ im2col[2] = indices[3];
+ int im2colOffset = im2col[0] * ${im2colStrides[0]} + im2col[1] * ${im2colStrides[1]} + im2col[2] * ${im2colStrides[2]};
+ int kernelOffset = indices[1] * ${adjustedKernelShape[1]};
+ float value = ${initValue};
+ for (int i = 0; i < ${sharedDim}; ++i) {
+ vec2 im2colCoords = offsetToCoords(im2colOffset, ${im2colWidth}, ${im2colHeight});
+ vec2 kernelCoords = offsetToCoords(kernelOffset, ${kWidth}, ${kHeight});
+ value += dot(${glsl.texture2D}(Im2Col, im2colCoords), ${glsl.texture2D}(K, kernelCoords));
+ ++im2colOffset;
+ ++kernelOffset;
+ }
+ ${applyActivation}
+ return value;
+}`;
+ return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource });
+};
+const createDotProductProgramInfoLoader = (inferenceHandler, inputs, outputShape, attributes) => {
+ const metadata = createDotProductProgramMetadata(inputs.length > 2, attributes);
+ return Object.assign(Object.assign({}, metadata), { get: () => createDotProductProgramInfo(inferenceHandler, metadata, inputs, outputShape, attributes) });
+};
+exports.createDotProductProgramInfoLoader = createDotProductProgramInfoLoader;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/flatten.ts":
+/*!**************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/flatten.ts ***!
+ \**************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseFlattenAttributes = exports.flatten = void 0;
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const flatten = (inferenceHandler, inputs, axis) => {
+ validateInputs(inputs, axis);
+ const outputDims = util_1.ShapeUtil.flattenShape(inputs[0].dims, axis);
+ return [inferenceHandler.reshapeUnpacked(inputs[0], outputDims)];
+};
+exports.flatten = flatten;
+const parseFlattenAttributes = (node) => node.attributes.getInt('axis', 1); // default axis is 1
+exports.parseFlattenAttributes = parseFlattenAttributes;
+const validateInputs = (inputs, axis) => {
+ if (!inputs || inputs.length !== 1) {
+ throw new Error('Flatten requires 1 input.');
+ }
+ const r = inputs[0].dims.length;
+ if (r === 0) {
+ throw new Error('scalar tensor is not supported.');
+ }
+ if (axis < -r || axis > r) {
+ throw new Error('Invalid axis');
+ }
+ // TODO: Support string type
+ if (inputs[0].type === 'string') {
+ throw new Error('string tensor is not supported.');
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/fuse-utils.ts":
+/*!*****************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/fuse-utils.ts ***!
+ \*****************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseInternalActivationAttributes = exports.getActivationSnippet = void 0;
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const unary_op_1 = __webpack_require__(/*! ./unary-op */ "./lib/onnxjs/backends/webgl/ops/unary-op.ts");
+function getActivationSnippet(attributes) {
+ let func;
+ switch (attributes.activation) {
+ case 'Relu':
+ func = (0, unary_op_1.glslRelu)();
+ break;
+ case 'Sigmoid':
+ func = (0, unary_op_1.glslSigmoid)();
+ break;
+ case 'Clip':
+ func = (0, unary_op_1.glslClip)(attributes.clipMin, attributes.clipMax);
+ break;
+ // TODO: adding other activations that can be fused.
+ default:
+ return { activationFunction: '', applyActivation: '' };
+ }
+ const activationName = func.name;
+ const activationFunction = func.body;
+ const applyActivation = `value = ${activationName}_(value);`;
+ return { activationFunction, applyActivation };
+}
+exports.getActivationSnippet = getActivationSnippet;
+const parseInternalActivationAttributes = (attributes) => {
+ const activation = attributes.getString('activation', '');
+ if (activation === 'Clip') {
+ const [clipMin, clipMax] = attributes.getFloats('activation_params', [util_1.MIN_CLIP, util_1.MAX_CLIP]);
+ return { activation, clipMax, clipMin, activationCacheKey: `${activation}:${clipMin},${clipMax}` };
+ }
+ return { activation, activationCacheKey: activation };
+};
+exports.parseInternalActivationAttributes = parseInternalActivationAttributes;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/gather.ts":
+/*!*************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/gather.ts ***!
+ \*************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseGatherAttributes = exports.gather = void 0;
+const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
+const operators_1 = __webpack_require__(/*! ../../../operators */ "./lib/onnxjs/operators.ts");
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const gather = (inferenceHandler, inputs, attributes) => {
+ validateInputs(inputs, attributes.axis);
+ const output = inferenceHandler.run(createGatherProgramInfoLoader(inferenceHandler, inputs, attributes), inputs);
+ return [output];
+};
+exports.gather = gather;
+const parseGatherAttributes = (node) => (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ axis: node.attributes.getInt('axis', 0) });
+exports.parseGatherAttributes = parseGatherAttributes;
+const gatherProgramMetadata = {
+ name: 'Gather',
+ inputNames: ['A', 'B'],
+ inputTypes: [types_1.TextureType.unpacked, types_1.TextureType.unpacked],
+};
+const createGatherProgramInfo = (handler, metadata, inputs, axis) => {
+ const inputShape = inputs[0].dims.slice();
+ const indexDataShape = inputs[1].dims.slice();
+ const outputShape = new Array(inputShape.length + indexDataShape.length - 1);
+ axis = util_1.ShapeUtil.normalizeAxis(axis, inputShape.length);
+ const indexCopyOps = [];
+ for (let i = 0; i < outputShape.length; i++) {
+ // outputShape is divided into three parts: A, B, C
+ // |0 axis| axis + indexDataShape.length | end|
+ // | A | B | C |
+ //
+ // inputIdx: [A, inputs[1][B], C]
+ if (i < axis) { // A
+ outputShape[i] = inputShape[i];
+ indexCopyOps.push(`inputIdx[${i}] = outputIdx[${i}];`);
+ }
+ else {
+ if (i < axis + indexDataShape.length) { // B
+ outputShape[i] = indexDataShape[i - axis];
+ indexCopyOps.push(`indexDataIdx[${i - axis}] = outputIdx[${i}];`);
+ }
+ else { // C
+ outputShape[i] = inputShape[i - indexDataShape.length + 1]; // skip 1 for axis
+ indexCopyOps.push(`inputIdx[${i - indexDataShape.length + 1}] = outputIdx[${i}];`);
+ }
+ }
+ }
+ const orank = outputShape.length || 1;
+ const irank = inputShape.length;
+ const iDrank = indexDataShape.length || 1;
+ const shaderSource = `
+ float process(int outputIdx[${orank}]) {
+ int inputIdx[${irank}];
+ int indexDataIdx[${iDrank}];
+ indexDataIdx[0] = 0;
+ ${indexCopyOps.join('\n ')}
+ int idx = int(_B(indexDataIdx));
+ inputIdx[${axis}] = idx < 0 ? idx + ${inputShape[axis]} : idx;
+ return _A(inputIdx);
+ }`;
+ return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource });
+};
+const createGatherProgramInfoLoader = (handler, inputs, attributes) => {
+ const metadata = Object.assign(Object.assign({}, gatherProgramMetadata), { cacheHint: attributes.cacheKey });
+ return Object.assign(Object.assign({}, metadata), { get: () => createGatherProgramInfo(handler, metadata, inputs, attributes.axis) });
+};
+const validateInputs = (inputs, axis) => {
+ if (!inputs || inputs.length !== 2) {
+ throw new Error('Gather requires 2 inputs.');
+ }
+ const tensorRank = inputs[0].dims.length;
+ if (tensorRank < 1) {
+ throw new Error('Invalid input shape.');
+ }
+ if (axis < -tensorRank || axis > tensorRank - 1) {
+ throw new Error('Invalid axis.');
+ }
+ if (operators_1.NUMBER_TYPES.indexOf(inputs[0].type) === -1) {
+ throw new Error('Invaid input type.');
+ }
+ if (inputs[1].type !== 'int32' && inputs[1].type !== 'int16') {
+ throw new Error('Invaid input type.');
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/gemm.ts":
+/*!***********************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/gemm.ts ***!
+ \***********************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseGemmAttributesV11 = exports.parseGemmAttributesV7 = exports.gemm = void 0;
+const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const gemm = (inferenceHandler, inputs, attributes) => {
+ validateInputs(inputs, attributes);
+ const output = inferenceHandler.run(createGemmProgramInfoLoader(inputs, attributes), inputs);
+ return [output];
+};
+exports.gemm = gemm;
+const parseGemmAttributes = (node, isOptionalC) => {
+ const transA = node.attributes.getInt('transA', 0) !== 0;
+ const transB = node.attributes.getInt('transB', 0) !== 0;
+ const alpha = node.attributes.getFloat('alpha', 1.0);
+ const beta = node.attributes.getFloat('beta', 1.0);
+ return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ transA, transB, alpha, beta, isOptionalC });
+};
+const parseGemmAttributesV7 = (node) => parseGemmAttributes(node, false);
+exports.parseGemmAttributesV7 = parseGemmAttributesV7;
+const parseGemmAttributesV11 = (node) => parseGemmAttributes(node, true);
+exports.parseGemmAttributesV11 = parseGemmAttributesV11;
+const createGemmProgramInfoLoader = (inputs, attributes) => {
+ const metadata = {
+ name: 'Gemm',
+ inputNames: inputs.length === 3 ? ['A', 'B', 'C'] : ['A', 'B'],
+ inputTypes: inputs.length === 3 ? [types_1.TextureType.unpacked, types_1.TextureType.unpacked, types_1.TextureType.unpacked] :
+ [types_1.TextureType.unpacked, types_1.TextureType.unpacked],
+ key: attributes.cacheKey
+ };
+ return Object.assign(Object.assign({}, metadata), { get: () => createGemmProgramInfo(metadata, inputs, attributes) });
+};
+const createGemmProgramInfo = (metadata, inputs, attributes) => {
+ const aShape = inputs[0].dims.slice();
+ const bShape = inputs[1].dims.slice();
+ const [M, N] = util_1.GemmUtil.getShapeOfGemmResult(aShape, attributes.transA, bShape, attributes.transB, inputs.length === 3 ? inputs[2].dims : undefined);
+ const outputShape = [M, N];
+ if (!outputShape) {
+ throw new Error('Can\'t use gemm on the given tensors');
+ }
+ let sharedDim = aShape[aShape.length - 1];
+ let line = '';
+ if (attributes.transA) {
+ sharedDim = aShape[0];
+ }
+ if (attributes.transA && attributes.transB) {
+ line = 'value += _A_T(a) * _B_T(b);';
+ }
+ else if (attributes.transA && !attributes.transB) {
+ line = 'value += _A_T(a) * _B(b);';
+ }
+ else if (!attributes.transA && attributes.transB) {
+ line = 'value += _A(a) * _B_T(b);';
+ }
+ else if (!attributes.transA && !attributes.transB) {
+ line = 'value += _A(a) * _B(b);';
+ }
+ const rank = outputShape.length;
+ const declareC = inputs.length === 3 ? `int c[${inputs[2].dims.length}];` : '';
+ const broadcastC = inputs.length === 3 ? 'bcastIndices_C(indices, c);' : '';
+ const calculateC = inputs.length === 3 ? 'value += beta * _C(c);' : '';
+ const shaderSource = `
+ float process(int indices[${rank}]) {
+ int a[${rank}];
+ int b[${rank}];
+ ${declareC}
+
+ copyVec(indices, a);
+ copyVec(indices, b);
+ ${broadcastC}
+
+ float value = 0.0;
+ for (int k=0; k<${sharedDim}; ++k) {
+ a[${rank - 1}] = k;
+ b[${rank - 2}] = k;
+ ${line}
+ }
+
+ value = value * alpha;
+ ${calculateC}
+ return value;
+ }`;
+ return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, variables: [
+ { name: 'alpha', type: 'float', data: attributes.alpha }, { name: 'beta', type: 'float', data: attributes.beta }
+ ], shaderSource });
+};
+const validateInputs = (inputs, attributes) => {
+ if (!inputs) {
+ throw new Error('Input is missing');
+ }
+ if (attributes.isOptionalC && (inputs.length < 2 || inputs.length > 3)) {
+ throw new Error('Invaid input shape.');
+ }
+ if (!attributes.isOptionalC && inputs.length !== 3) {
+ throw new Error('Gemm requires 3 inputs');
+ }
+ // 'C' can be of dimensionality 1 or 2 only
+ if (inputs.length === 3 && inputs[2].dims.length !== 1 && inputs[2].dims.length !== 2) {
+ throw new Error('Invalid input shape of C');
+ }
+ if ((inputs[0].type !== 'float32' && inputs[0].type !== 'float64') ||
+ (inputs[1].type !== 'float32' && inputs[1].type !== 'float64') ||
+ (inputs.length === 3 && inputs[2].type !== 'float32' && inputs[2].type !== 'float64')) {
+ throw new Error('Invalid input type.');
+ }
+ if ((inputs[0].type !== inputs[1].type) || (inputs.length === 3 && inputs[0].type !== inputs[2].type)) {
+ throw new Error('Input types are mismatched');
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/im2col-pack.ts":
+/*!******************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/im2col-pack.ts ***!
+ \******************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createPackedIm2ColProgramInfoLoader = void 0;
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const packing_utils_1 = __webpack_require__(/*! ./packing-utils */ "./lib/onnxjs/backends/webgl/ops/packing-utils.ts");
+const createPackedIm2ColProgramMetadata = (cacheHint) => ({
+ name: 'Im2Col (packed)',
+ inputNames: ['A'],
+ inputTypes: [types_1.TextureType.packed],
+ cacheHint,
+});
+const createPackedIm2ColProgramInfo = (inferenceHandler, metadata, x, w, outputShape, attributes) => {
+ const xshape = x.dims;
+ const wshape = w.dims;
+ const rowDim = 2;
+ const colDim = 3;
+ const rank = outputShape.length;
+ const im2colShape = [wshape[1] * wshape[2] * wshape[3], outputShape[2] * outputShape[3]];
+ const kernelSize = wshape[2] * wshape[3];
+ const unpackChannel = (0, packing_utils_1.unpackFromChannel)();
+ const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
+ let unrolled = '';
+ for (let row = 0; row <= 1; row++) {
+ for (let col = 0; col <= 1; col++) {
+ unrolled += `
+ blockIndex = rc.x + ${col};
+ pos = rc.y + ${row};
+
+ if(blockIndex < ${im2colShape[1]} && pos < ${im2colShape[0]}) {
+ offsetY = int(blockIndex / (${outputShape[rank - 1]})) * ${attributes.strides[0]} -
+ ${attributes.pads[0]};
+ d0 = offsetY + ${attributes.dilations[0]} * (imod(pos, ${kernelSize}) / ${wshape[2]});
+
+ if(d0 < ${xshape[rowDim]} && d0 >= 0) {
+ offsetX = imod(blockIndex, ${outputShape[rank - 1]}) * ${attributes.strides[1]} -
+ ${attributes.pads[1]};
+ d1 = offsetX + ${attributes.dilations[1]} * imod(imod(pos, ${kernelSize}), ${wshape[2]});
+
+ if(d1 < ${xshape[colDim]} && d1 >= 0) {
+
+ ch = int(float(pos)/ ${kernelSize}.);
+ innerDims = vec2(d0, d1);
+ result[${row * 2 + col}] = getChannel(
+ getA(0, ch, int(innerDims.x),
+ int(innerDims.y)), innerDims);
+ }
+ }
+ }
+
+ `;
+ }
+ }
+ const shaderSource = `
+ ${unpackChannel}
+
+ void main() {
+ ivec2 rc = getOutputCoords();
+ vec4 result = vec4(0.0);
+ int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
+ vec2 innerDims;
+ ${unrolled}
+ ${glsl.output} = result;
+ }
+ `;
+ return Object.assign(Object.assign({}, metadata), { output: { dims: im2colShape, type: x.type, textureType: types_1.TextureType.packed }, shaderSource, hasMain: true });
+};
+const createPackedIm2ColProgramInfoLoader = (inferenceHandler, x, w, outputShape, attributes) => {
+ const metadata = createPackedIm2ColProgramMetadata(attributes.cacheKey);
+ return Object.assign(Object.assign({}, metadata), { get: () => createPackedIm2ColProgramInfo(inferenceHandler, metadata, x, w, outputShape, attributes) });
+};
+exports.createPackedIm2ColProgramInfoLoader = createPackedIm2ColProgramInfoLoader;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/im2col.ts":
+/*!*************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/im2col.ts ***!
+ \*************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.calculateIm2ColDims = exports.createIm2ColProgramInfoLoader = void 0;
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const createIm2ColProgramMetadata = (cacheHint) => ({
+ name: 'Im2Col',
+ inputNames: ['X'],
+ inputTypes: [types_1.TextureType.unpacked],
+ cacheHint,
+});
+const createIm2ColProgramInfo = (inferenceHandler, metadata, x, w, outputShape, attributes) => {
+ const xshape = x.dims;
+ const wshape = w.dims;
+ const rank = outputShape.length;
+ const im2colDims = (0, exports.calculateIm2ColDims)(xshape, wshape, outputShape, 4);
+ const shaderSource = `
+ const int XC = ${xshape[1]};
+ const int XH = ${xshape[2]};
+ const int XW = ${xshape[3]};
+ const int KH = ${attributes.kernelShape[0]};
+ const int KW = ${attributes.kernelShape[1]};
+ const int dilationH = ${attributes.dilations[0]};
+ const int dilationW = ${attributes.dilations[1]};
+ const int strideH = ${attributes.strides[0]};
+ const int strideW = ${attributes.strides[1]};
+ const int padH = ${attributes.pads[0]};
+ const int padW = ${attributes.pads[1]};
+ const int KHKW = KH*KW;
+ const int XCKHKW = XC * KHKW;
+ const int outputChannels = 4;
+ vec4 process(int indices[${rank}]) {
+ int b = indices[0]; // batch size
+ int oh = indices[1] * strideH - padH; //output height
+ int ow = indices[2] * strideW - padW; //output width
+ int p = indices[3] * outputChannels; //patch
+ vec4 value = vec4(0.0);
+ for(int i=0; i < outputChannels; ++i) {
+ if(p < XCKHKW) {
+ int patchC = p / KHKW;
+ int patchH = (p - patchC*KHKW) / KW;
+ int patchW = (p - patchC*KHKW) - patchH * KW;
+ int xh2 = oh + patchH * dilationH;
+ int xw2 = ow + patchW * dilationW;
+ int x[${xshape.length}];
+ x[0] = b;
+ x[1] = patchC;
+ x[2] = xh2;
+ x[3] = xw2;
+ if(xh2 >= 0 &&
+ xh2 < XH &&
+ xw2 >= 0 &&
+ xw2 < XW) {
+ value[i] = _X(x);
+ }
+ }
+ ++p;
+ }
+ return value;
+ }
+ `;
+ return Object.assign(Object.assign({}, metadata), { output: { dims: im2colDims, type: x.type, textureType: types_1.TextureType.packedLastDimension }, shaderSource });
+};
+const createIm2ColProgramInfoLoader = (inferenceHandler, x, w, outputShape, attributes) => {
+ const metadata = createIm2ColProgramMetadata(attributes.cacheKey);
+ return Object.assign(Object.assign({}, metadata), { get: () => createIm2ColProgramInfo(inferenceHandler, metadata, x, w, outputShape, attributes) });
+};
+exports.createIm2ColProgramInfoLoader = createIm2ColProgramInfoLoader;
+const calculateIm2ColDims = (inputShape, kernelShape, outputShape, channels = 4) => [outputShape[0], outputShape[2], outputShape[3],
+ Math.ceil(inputShape[1] * kernelShape[2] * kernelShape[3] / channels)];
+exports.calculateIm2ColDims = calculateIm2ColDims;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/image-scaler.ts":
+/*!*******************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/image-scaler.ts ***!
+ \*******************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseImageScalerAttributes = exports.imageScaler = void 0;
+const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const imageScaler = (inferenceHandler, inputs, attributes) => {
+ validateInputs(inputs);
+ const output = inferenceHandler.run(createImageScalerProgramInfoLoader(inferenceHandler, inputs, attributes), inputs);
+ return [output];
+};
+exports.imageScaler = imageScaler;
+const parseImageScalerAttributes = (node) => {
+ const scale = node.attributes.getFloat('scale');
+ const bias = node.attributes.getFloats('bias');
+ return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ scale, bias });
+};
+exports.parseImageScalerAttributes = parseImageScalerAttributes;
+const imageScalerProgramMetadata = {
+ name: 'ImageScaler',
+ inputNames: ['X'],
+ inputTypes: [types_1.TextureType.unpacked],
+};
+const createImageScalerProgramInfo = (handler, metadata, inputs, attributes) => {
+ const outputShape = inputs[0].dims.slice();
+ const rank = outputShape.length;
+ const getBiasMethod = createGetBiasMethod(attributes.bias.length);
+ const shaderSource = `
+ ${getBiasMethod}
+ float process(int indices[${rank}]) {
+ return _X(indices) * scale + getBias(bias, indices[1]);
+ }`;
+ return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, variables: [
+ { name: 'bias', type: 'float', arrayLength: attributes.bias.length, data: attributes.bias },
+ { name: 'scale', type: 'float', data: attributes.scale }
+ ], shaderSource });
+};
+const createImageScalerProgramInfoLoader = (handler, inputs, attributes) => {
+ const metadata = Object.assign(Object.assign({}, imageScalerProgramMetadata), { cacheHint: attributes.cacheKey });
+ return Object.assign(Object.assign({}, metadata), { get: () => createImageScalerProgramInfo(handler, metadata, inputs, attributes) });
+};
+const createGetBiasMethod = (numChannels) => {
+ const codeLines = [`float getBias(float bias[${numChannels}], int channel) {`];
+ for (let i = 0; i < numChannels; ++i) {
+ if (i === 0) {
+ codeLines.push('\t' +
+ `if (channel == ${i}) { return bias[${i}]; }`);
+ }
+ else if (i === numChannels - 1) {
+ codeLines.push('\t' +
+ `else { return bias[${i}]; }`);
+ }
+ else {
+ codeLines.push('\t' +
+ `else if (channel == ${i}) { return bias[${i}]; }`);
+ }
+ }
+ codeLines.push('\t' +
+ '}');
+ return codeLines.join('\n');
+};
+const validateInputs = (inputs) => {
+ if (!inputs || inputs.length !== 1) {
+ throw new Error('ImageScaler requires 1 input.');
+ }
+ if (inputs[0].dims.length !== 4) {
+ throw new Error('Invalid input shape.');
+ }
+ if (inputs[0].type !== 'float32' && inputs[0].type !== 'float64') {
+ throw new Error('Invalid input type.');
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/instance-normalization.ts":
+/*!*****************************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/instance-normalization.ts ***!
+ \*****************************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseInstanceNormalizationAttributes = exports.instanceNormalization = void 0;
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const instanceNormalization = (inferenceHandler, inputs, epsilon) => {
+ validateInputs(inputs);
+ const meanAndVariance = inferenceHandler.run(createMeanAndVarianceProgramInfoLoader(inputs[0]), inputs);
+ const output = inferenceHandler.run(createComputeOutputProgramInfoLoader(inferenceHandler, inputs[0], epsilon, meanAndVariance.dims), [inputs[0], meanAndVariance, inputs[1], inputs[2]]);
+ return [output];
+};
+exports.instanceNormalization = instanceNormalization;
+const parseInstanceNormalizationAttributes = (node) => node.attributes.getFloat('epsilon', 1e-5);
+exports.parseInstanceNormalizationAttributes = parseInstanceNormalizationAttributes;
+const meanAndVarianceProgramMetadata = {
+ name: 'InstanceNormalization_MeanAndVariance',
+ inputNames: ['X'],
+ inputTypes: [types_1.TextureType.unpacked],
+};
+const createMeanAndVarianceProgramInfo = (metadata, input) => {
+ const xDims = input.dims.slice();
+ const channel = xDims[1];
+ const channelSize = xDims[2] * xDims[3];
+ const outputShape = [xDims[0], channel];
+ const shaderSource = `
+ vec4 process(int[2] indices) {
+ vec4 v = vec4(0.0);
+ int a[4];
+ a[0] = indices[0];
+ a[1] = indices[1];
+ float temp = 0.0;
+ for(int a2=0; a2<${xDims[2]}; a2++) {
+ a[2] = a2;
+ for(int a3=0; a3<${xDims[3]}; a3++) {
+ a[3] = a3;
+ float x = _X(a);
+ temp += x;
+ }
+ }
+ float mean = temp / float(${channelSize});
+ temp = 0.0;
+ for(int a2=0; a2<${xDims[2]}; a2++) {
+ a[2] = a2;
+ for(int a3=0; a3<${xDims[3]}; a3++) {
+ a[3] = a3;
+ float x = _X(a);
+ temp += (x - mean) * (x - mean);
+ }
+ }
+ v.r = mean;
+ v.g = temp / float(${channelSize});
+
+ return v;
+ }`;
+ return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: input.type, textureType: types_1.TextureType.packedLastDimension }, shaderSource });
+};
+const createMeanAndVarianceProgramInfoLoader = (input) => (Object.assign(Object.assign({}, meanAndVarianceProgramMetadata), { get: () => createMeanAndVarianceProgramInfo(meanAndVarianceProgramMetadata, input) }));
+const computeOutputProgramMetadata = {
+ name: 'InstanceNormalization_ComputeOutput',
+ inputNames: ['X', 'MeanAndVariance', 'Scale', 'B'],
+ inputTypes: [types_1.TextureType.unpacked, types_1.TextureType.packedLastDimension, types_1.TextureType.unpacked, types_1.TextureType.unpacked],
+};
+const createComputeOutputProgramInfo = (inferenceHandler, metadata, input, epsilon, meanAndVarianceShape) => {
+ const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
+ const [textureWidth, textureHeight] = inferenceHandler.calculateTextureWidthAndHeight(meanAndVarianceShape, types_1.TextureType.packedLastDimension);
+ const [meanAndVarianceWidth, meanAndVarianceHeight] = [textureWidth / 4, textureHeight];
+ const shaderSource = `
+ vec4 get_MeanAndVariance(int[2] mv) {
+ int offset = indicesToOffset_MeanAndVariance(mv);
+ vec2 coords = offsetToCoords(offset, ${meanAndVarianceWidth}, ${meanAndVarianceHeight});
+ return ${glsl.texture2D}(MeanAndVariance, coords);
+ }
+
+ float process(int[4] indices) {
+ int mv[2];
+ mv[0] = indices[0];
+ mv[1] = indices[1];
+ vec4 mean_and_variance = get_MeanAndVariance(mv);
+ float mean = mean_and_variance.r;
+ float variance = mean_and_variance.g;
+
+ int sb[1];
+ sb[0] = indices[1];
+ float scale = _Scale(sb);
+ float b = _B(sb);
+
+ return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b;
+ }`;
+ return Object.assign(Object.assign({}, metadata), { output: { dims: input.dims, type: input.type, textureType: types_1.TextureType.unpacked }, variables: [{ name: 'epsilon', type: 'float', data: epsilon }], shaderSource });
+};
+const createComputeOutputProgramInfoLoader = (inferenceHandler, input, epsilon, meanAndVarianceShape) => {
+ const metadata = Object.assign(Object.assign({}, computeOutputProgramMetadata), { cacheHint: `${epsilon}` });
+ return Object.assign(Object.assign({}, metadata), { get: () => createComputeOutputProgramInfo(inferenceHandler, metadata, input, epsilon, meanAndVarianceShape) });
+};
+const validateInputs = (inputs) => {
+ if (!inputs || inputs.length !== 3) {
+ throw new Error('InstanceNormalization requires 3 inputs.');
+ }
+ const X = inputs[0];
+ const scale = inputs[1];
+ const B = inputs[2];
+ // input should at least have three dimensions - N,C,dim1,...,dimn
+ // other inputs can have only one dimensions
+ if (X.dims.length < 3 || scale.dims.length !== 1 || B.dims.length !== 1) {
+ throw new Error('Invalid input shape.');
+ }
+ if (scale.dims[0] !== X.dims[1] || B.dims[0] !== X.dims[1]) {
+ throw new Error('Input shapes are mismatched.');
+ }
+ if ((X.type !== 'float32' && X.type !== 'float64') || (scale.type !== 'float32' && scale.type !== 'float64') ||
+ (B.type !== 'float32' && B.type !== 'float64')) {
+ throw new Error('Invalid input type.');
+ }
+ if (inputs[0].dims.length !== 4) {
+ throw new Error('Only support 4-D input shape.');
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/matmul-pack.ts":
+/*!******************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/matmul-pack.ts ***!
+ \******************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createPackedMatmulProgramInfoLoader = void 0;
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const utils_1 = __webpack_require__(/*! ../utils */ "./lib/onnxjs/backends/webgl/utils.ts");
+const fuse_utils_1 = __webpack_require__(/*! ./fuse-utils */ "./lib/onnxjs/backends/webgl/ops/fuse-utils.ts");
+const matmul_1 = __webpack_require__(/*! ./matmul */ "./lib/onnxjs/backends/webgl/ops/matmul.ts");
+const createPackedMatmulProgramMetadata = (hasBias, cacheHint) => ({
+ name: 'MatMul (packed)',
+ inputNames: hasBias ? ['A', 'B', 'Bias'] : ['A', 'B'],
+ inputTypes: hasBias ? [types_1.TextureType.packed, types_1.TextureType.packed, types_1.TextureType.packed] :
+ [types_1.TextureType.packed, types_1.TextureType.packed],
+ cacheHint
+});
+const createPackedMatmulProgramInfo = (inferenceHandler, metadata, inputs, activationAttributes) => {
+ const hasBias = inputs.length > 2;
+ const processBias = hasBias ? 'value += getBiasForMatmul();' : '';
+ const aShape = inputs[0].dims;
+ const bShape = inputs[1].dims;
+ const outputShape = util_1.BroadcastUtil.calcShape(aShape, bShape, true);
+ const isBroadcast = !util_1.ShapeUtil.areEqual(inputs[0].dims, inputs[1].dims);
+ if (!outputShape) {
+ throw new Error('Can\'t use matmul on the given tensors');
+ }
+ const sharedDim = aShape[aShape.length - 1];
+ const sharedDimIndex = Math.ceil(sharedDim / 2);
+ const aRank = aShape.length;
+ const bRank = bShape.length;
+ const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
+ const coordsDataType = (0, utils_1.getCoordsDataType)(outputShape.length);
+ const outRank = outputShape.length;
+ const allGlChannels = (0, utils_1.getGlChannels)();
+ const { activationFunction, applyActivation } = (0, fuse_utils_1.getActivationSnippet)(activationAttributes);
+ const getBiasForMatmulSnippet = hasBias ? `${(0, matmul_1.getBiasForMatmul)(coordsDataType, allGlChannels, inputs[2].dims, outputShape, true)}` : '';
+ const getBcastedSamplerForMatmulSnippet = isBroadcast ? `${getBcastSamplerForMatmul(coordsDataType, allGlChannels, inputs, outputShape)}` : '';
+ const getSamplerAInLoopSnippet = isBroadcast ? 'getAAtOutCoordsMatmul(i)' : `getA(${getA(allGlChannels, aRank)})`;
+ const getSamplerBInLoopSnippet = isBroadcast ? 'getBAtOutCoordsMatmul(i)' : `getB(${getB(allGlChannels, bRank)})`;
+ const getOutputCoordsSnippet = isBroadcast ? '' : `${coordsDataType} rc =
+ getOutputCoords(); int lastDim = rc.${allGlChannels[outRank - 1]}; rc.${allGlChannels[outRank - 1]} =
+ rc.${allGlChannels[outRank - 2]}; rc.${allGlChannels[outRank - 2]} = lastDim;
+ `;
+ const shaderSource = `
+ ${getBcastedSamplerForMatmulSnippet}
+ ${getBiasForMatmulSnippet}
+ ${activationFunction}
+ void main() {
+ ${getOutputCoordsSnippet}
+
+ vec4 value = vec4(0);
+ for (int i = 0; i < ${sharedDimIndex}; i++) {
+ vec4 a = ${getSamplerAInLoopSnippet};
+ vec4 b = ${getSamplerBInLoopSnippet};
+
+ value += (a.rrbb * b.rgrg);
+ value += (a.ggaa * b.baba);
+ }
+ ${processBias}
+ ${applyActivation}
+ ${glsl.output} = value;
+ }`;
+ return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.packed }, shaderSource, hasMain: true });
+};
+const createPackedMatmulProgramInfoLoader = (inferenceHandler, inputs, activationAttributes) => {
+ const metadata = createPackedMatmulProgramMetadata(inputs.length > 2, activationAttributes.activationCacheKey);
+ return Object.assign(Object.assign({}, metadata), { get: () => createPackedMatmulProgramInfo(inferenceHandler, metadata, inputs, activationAttributes) });
+};
+exports.createPackedMatmulProgramInfoLoader = createPackedMatmulProgramInfoLoader;
+function getBcastSamplerForMatmul(coordsDataType, allGlChannels, inputs, outShape) {
+ let unpackedACoordsSnippet = [];
+ let unpackedBCoordsSnippet = [];
+ const inAShape = inputs[0].dims;
+ const inBShape = inputs[1].dims;
+ const inARank = inAShape.length;
+ const inBRank = inBShape.length;
+ const outRank = outShape.length;
+ const rankADiff = outRank - inARank;
+ const rankBDiff = outRank - inBRank;
+ unpackedACoordsSnippet = inAShape.map((s, i) => `coords.${allGlChannels[i + rankADiff]}`);
+ unpackedACoordsSnippet[inARank - 1] = 'i*2';
+ unpackedACoordsSnippet.join(', ');
+ unpackedBCoordsSnippet = inBShape.map((s, i) => `coords.${allGlChannels[i + rankBDiff]}`);
+ unpackedBCoordsSnippet[inBRank - 2] = 'i*2';
+ unpackedBCoordsSnippet.join(', ');
+ const broadcastADims = util_1.BroadcastUtil.getBroadcastDims(inAShape, outShape);
+ const broadcastBDims = util_1.BroadcastUtil.getBroadcastDims(inBShape, outShape);
+ const coordsASnippet = broadcastADims.map(d => `coords.${allGlChannels[d + rankADiff]} = 0;`).join('\n');
+ const coordsBSnippet = broadcastBDims.map(d => `coords.${allGlChannels[d + rankBDiff]} = 0;`).join('\n');
+ const swapDimSnippet = `int lastDim = coords.${allGlChannels[outRank - 1]};
+ coords.${allGlChannels[outRank - 1]} = coords.${allGlChannels[outRank - 2]};
+ coords.${allGlChannels[outRank - 2]} = lastDim;`;
+ const getBcastSamplerMatmulSource = `
+vec4 getAAtOutCoordsMatmul(int i) {
+ ${coordsDataType} coords = getOutputCoords();
+ ${swapDimSnippet}
+ ${coordsASnippet}
+ vec4 outputValue = getA(${unpackedACoordsSnippet});
+ return outputValue;
+}
+
+vec4 getBAtOutCoordsMatmul(int i) {
+ ${coordsDataType} coords = getOutputCoords();
+ ${swapDimSnippet}
+ ${coordsBSnippet}
+ vec4 outputValue = getB(${unpackedBCoordsSnippet});
+ return outputValue;
+}`;
+ return getBcastSamplerMatmulSource;
+}
+function getA(allGlChannels, rank) {
+ let res = '';
+ for (let i = 0; i < rank - 2; i++) {
+ res += `rc.${allGlChannels[i]}, `;
+ }
+ res += `rc.${allGlChannels[rank - 2]}, ` +
+ 'i*2';
+ return res;
+}
+function getB(allGlChannels, rank) {
+ let res = '';
+ for (let i = 0; i < rank - 2; i++) {
+ res += `rc.${allGlChannels[i]}, `;
+ }
+ res += 'i*2, ' +
+ `rc.${allGlChannels[rank - 1]}`;
+ return res;
+}
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/matmul.ts":
+/*!*************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/matmul.ts ***!
+ \*************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getBiasForMatmul = exports.createMatmulProgramInfoLoader = exports.parseMatMulAttributes = exports.matMul = void 0;
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const utils_1 = __webpack_require__(/*! ../utils */ "./lib/onnxjs/backends/webgl/utils.ts");
+const fuse_utils_1 = __webpack_require__(/*! ./fuse-utils */ "./lib/onnxjs/backends/webgl/ops/fuse-utils.ts");
+const matmul_pack_1 = __webpack_require__(/*! ./matmul-pack */ "./lib/onnxjs/backends/webgl/ops/matmul-pack.ts");
+const matMul = (inferenceHandler, inputs, attributes) => {
+ validateInputs(inputs);
+ if (inferenceHandler.session.pack) {
+ return [inferenceHandler.run((0, matmul_pack_1.createPackedMatmulProgramInfoLoader)(inferenceHandler, inputs, attributes), inputs)];
+ }
+ else {
+ return [inferenceHandler.run(createMatmulProgramInfoLoader(inputs, attributes), inputs)];
+ }
+};
+exports.matMul = matMul;
+const parseMatMulAttributes = (node) => (0, fuse_utils_1.parseInternalActivationAttributes)(node.attributes);
+exports.parseMatMulAttributes = parseMatMulAttributes;
+const createMatmulProgramMetadata = (hasBias, cacheHint) => ({
+ name: 'MatMul',
+ inputNames: hasBias ? ['A', 'B', 'Bias'] : ['A', 'B'],
+ inputTypes: hasBias ? [types_1.TextureType.unpacked, types_1.TextureType.unpacked, types_1.TextureType.unpacked] :
+ [types_1.TextureType.unpacked, types_1.TextureType.unpacked],
+ cacheHint
+});
+function createMatmulProgramInfo(metadata, inputs, activationAttributes) {
+ const aShape = inputs[0].dims;
+ const bShape = inputs[1].dims;
+ const outputShape = util_1.BroadcastUtil.calcShape(aShape, bShape, true);
+ if (!outputShape) {
+ throw new Error('Can\'t use matmul on the given tensors');
+ }
+ const coordsDataType = (0, utils_1.getCoordsDataType)(outputShape.length);
+ const allGlChannels = (0, utils_1.getGlChannels)();
+ const { activationFunction, applyActivation } = (0, fuse_utils_1.getActivationSnippet)(activationAttributes);
+ const hasBias = inputs.length > 2;
+ const processBias = hasBias ? 'value += getBiasForMatmul();' : '';
+ const getBiasForMatmulSnippet = hasBias ? `${getBiasForMatmul(coordsDataType, allGlChannels, inputs[2].dims, outputShape, false)}` : '';
+ const rank = outputShape.length;
+ const arank = aShape.length;
+ const brank = bShape.length;
+ const sharedDim = aShape[aShape.length - 1];
+ const shaderSource = `
+ ${activationFunction}
+ ${getBiasForMatmulSnippet}
+ float process(int indices[${rank}]) {
+ int a[${arank}];
+ int b[${brank}];
+ bcastMatmulIndices_A(indices, a);
+ bcastMatmulIndices_B(indices, b);
+
+ float value;
+ for (int k=0; k<${sharedDim}; ++k) {
+ a[${arank - 1}] = k;
+ b[${brank - 2}] = k;
+ value += _A(a) * _B(b);
+ }
+ ${processBias}
+ ${applyActivation}
+ return value;
+ }`;
+ return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource });
+}
+function createMatmulProgramInfoLoader(inputs, activationAttributes) {
+ const metadata = createMatmulProgramMetadata(inputs.length > 2, activationAttributes.activationCacheKey);
+ return Object.assign(Object.assign({}, metadata), { get: () => createMatmulProgramInfo(metadata, inputs, activationAttributes) });
+}
+exports.createMatmulProgramInfoLoader = createMatmulProgramInfoLoader;
+const validateInputs = (inputs) => {
+ if (!inputs || inputs.length !== 2) {
+ throw new Error('MatMul requires 2 inputs.');
+ }
+ if (inputs[0].dims[inputs[0].dims.length - 1] !== inputs[1].dims[inputs[1].dims.length - 2]) {
+ throw new Error('shared dimension does not match.');
+ }
+ if ((inputs[0].type !== 'float32' && inputs[0].type !== 'float64') ||
+ (inputs[1].type !== 'float32' && inputs[1].type !== 'float64')) {
+ throw new Error('inputs should be float type');
+ }
+ if (inputs[0].type !== inputs[1].type) {
+ throw new Error('inputs types should match');
+ }
+};
+function getBiasForMatmul(coordsDataType, allGlChannels, inShape, outShape, isPacked) {
+ let unpackedCoordsSnippet = '';
+ const inRank = inShape.length;
+ const outRank = outShape.length;
+ const rankDiff = outRank - inRank;
+ if (outRank < 2 && inRank > 0) {
+ unpackedCoordsSnippet = 'coords';
+ }
+ else {
+ unpackedCoordsSnippet = inShape.map((s, i) => `coords.${allGlChannels[i + rankDiff]}`).join(', ');
+ }
+ const broadcastDims = util_1.BroadcastUtil.getBroadcastDims(inShape, outShape);
+ const coordsSnippet = broadcastDims.map(d => `coords.${allGlChannels[d + rankDiff]} = 0;`).join('\n');
+ const inSize = util_1.ShapeUtil.size(inShape);
+ const isInputScalar = inSize === 1;
+ let output = 'vec4(outputValue.xx, outputValue.yy)';
+ if (isInputScalar) {
+ output = 'vec4(outputValue.x)';
+ }
+ const getBiasForMatmulSource = isPacked ? `
+vec4 getBiasForMatmul() {
+ ${coordsDataType} coords = getOutputCoords();
+ ${coordsSnippet}
+ vec4 outputValue = getBias(${unpackedCoordsSnippet});
+ return ${output};
+}` :
+ `
+float getBiasForMatmul() {
+ ${coordsDataType} coords = getOutputCoords();
+ ${coordsSnippet}
+ return getBias(coords.x);
+}`;
+ return getBiasForMatmulSource;
+}
+exports.getBiasForMatmul = getBiasForMatmul;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/pack.ts":
+/*!***********************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/pack.ts ***!
+ \***********************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createPackProgramInfoLoader = void 0;
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const utils_1 = __webpack_require__(/*! ../utils */ "./lib/onnxjs/backends/webgl/utils.ts");
+const packing_utils_1 = __webpack_require__(/*! ./packing-utils */ "./lib/onnxjs/backends/webgl/ops/packing-utils.ts");
+const packProgramMetadata = {
+ name: 'pack',
+ inputNames: ['A'],
+ inputTypes: [types_1.TextureType.unpackedReversed]
+};
+const createPackProgramInfo = (handler, input) => {
+ const glsl = (0, glsl_source_1.getGlsl)(handler.session.backend.glContext.version);
+ const inputShape = input.dims;
+ const inputRank = inputShape.length;
+ // createTextureLayoutFromShape won't change output rank. Need to verify by running tests
+ const outputRank = input.dims.length;
+ const coordsDataType = (0, utils_1.getCoordsDataType)(outputRank);
+ const channels = (0, packing_utils_1.getChannels)('rc', outputRank);
+ const setup = getSetup(outputRank, channels, inputShape[inputShape.length - 2], inputShape[inputShape.length - 1]);
+ let reversedInputWH;
+ if (inputRank === 0) {
+ reversedInputWH = [1, 1];
+ }
+ else if (inputRank === 1) {
+ reversedInputWH = [inputShape[0], 1];
+ }
+ else {
+ reversedInputWH = [inputShape[outputRank - 1], inputShape[outputRank - 2]];
+ }
+ const outOfBoundsCondition = getOutOfBoundsCondition(outputRank, reversedInputWH, channels);
+ const output = getOutput(inputShape, channels);
+ const shaderSource = `
+ void main() {
+ ${coordsDataType} rc = getOutputCoords();
+
+ if(${outOfBoundsCondition}) {
+ ${glsl.output} = vec4(0);
+ } else {
+ ${setup}
+
+ ${glsl.output} = vec4(${output});
+ }
+ }
+ `;
+ return Object.assign(Object.assign({}, packProgramMetadata), { hasMain: true, output: { dims: input.dims, type: input.type, textureType: types_1.TextureType.packed }, shaderSource });
+};
+const createPackProgramInfoLoader = (handler, input) => (Object.assign(Object.assign({}, packProgramMetadata), { get: () => createPackProgramInfo(handler, input) }));
+exports.createPackProgramInfoLoader = createPackProgramInfoLoader;
+/**
+ * check output coordinate location and return false if it is outside input's width/height boundary
+ */
+function getOutOfBoundsCondition(rank, shape, dims) {
+ if (rank === 0) {
+ return 'false';
+ }
+ if (rank === 1) {
+ return `rc > ${shape[0]}`;
+ }
+ let cond = '';
+ for (let i = rank - 2; i < rank; i++) {
+ cond += `${dims[i]} >= ${shape[i - rank + 2]}`;
+ if (i < rank - 1) {
+ cond += '||';
+ }
+ }
+ return cond;
+}
+/**
+ * code snippet to sample input texture with output coordiantes
+ */
+function getOutput(shape, dims) {
+ const rank = shape.length;
+ if (rank === 0) {
+ return 'getA(), 0, 0, 0';
+ }
+ if (rank === 1) {
+ return `getA(rc),
+ rc + 1 >= ${shape[0]} ? 0. : getA(rc + 1),
+ 0, 0`;
+ }
+ const coord00 = 'r, c';
+ const coord01 = 'r, cp1';
+ const coord10 = 'rp1, c';
+ const coord11 = 'rp1, cp1';
+ let D = '';
+ if (rank > 2) {
+ for (let i = 0; i < rank - 2; ++i) {
+ D = D + `${dims[i]},`;
+ }
+ }
+ return `getA(${D}${coord00}),
+ rEdge ? 0. : getA(${D}${coord10}),
+ cEdge ? 0. : getA(${D}${coord01}),
+ rEdge || cEdge ? 0. : getA(${D}${coord11})`;
+}
+/**
+ * code snippet to setup 4 coordinates and edge conditions
+ */
+function getSetup(rank, dims, rows, cols) {
+ if (rank === 0 || rank === 1) {
+ return '';
+ }
+ // rank >= 2 for width+height pack.
+ else {
+ const setup = `
+ int r = ${dims[rank - 2]};
+ int c = ${dims[rank - 1]};
+ int rp1 = ${dims[rank - 2]} + 1;
+ int cp1 = ${dims[rank - 1]} + 1;
+ bool rEdge = rp1 >= ${cols};
+ bool cEdge = cp1 >= ${rows};
+ `;
+ return setup;
+ }
+}
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/packing-utils.ts":
+/*!********************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/packing-utils.ts ***!
+ \********************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.unpackFromChannel = exports.getChannels = exports.getVecChannels = void 0;
+const utils_1 = __webpack_require__(/*! ../utils */ "./lib/onnxjs/backends/webgl/utils.ts");
+function getVecChannels(name, rank) {
+ return (0, utils_1.getGlChannels)(rank).map(d => `${name}.${d}`);
+}
+exports.getVecChannels = getVecChannels;
+function getChannels(name, rank) {
+ if (rank === 1) {
+ return [name];
+ }
+ return getVecChannels(name, rank);
+}
+exports.getChannels = getChannels;
+function unpackFromChannel() {
+ return `
+ float getChannel(vec4 frag, int dim) {
+ int modCoord = imod(dim, 2);
+ return modCoord == 0 ? frag.r : frag.g;
+ }
+
+ float getChannel(vec4 frag, vec2 innerDims) {
+ vec2 modCoord = mod(innerDims, 2.);
+ return modCoord.x == 0. ?
+ (modCoord.y == 0. ? frag.r : frag.g) :
+ (modCoord.y == 0. ? frag.b : frag.a);
+ }
+ `;
+}
+exports.unpackFromChannel = unpackFromChannel;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/pad.ts":
+/*!**********************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/pad.ts ***!
+ \**********************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parsePadAttributesV11 = exports.padV11 = exports.parsePadAttributesV2 = exports.padV2 = void 0;
+const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const padProgramMetadata = {
+ name: 'Pad',
+ inputNames: ['A'],
+ inputTypes: [types_1.TextureType.unpacked],
+};
+const padV2 = (inferenceHandler, inputs, attributes) => {
+ validateInputsV2(inputs);
+ const output = inferenceHandler.run(Object.assign(Object.assign({}, padProgramMetadata), { cacheHint: attributes.cacheKey, get: () => createPadProgramInfo(inferenceHandler, inputs[0], attributes) }), inputs);
+ return [output];
+};
+exports.padV2 = padV2;
+const parsePadAttributesV2 = (node) => {
+ const mode = node.attributes.getString('mode', 'constant');
+ const value = node.attributes.getFloat('value', 0.0);
+ const pads = node.attributes.getInts('pads');
+ return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ mode, value, pads });
+};
+exports.parsePadAttributesV2 = parsePadAttributesV2;
+const padV11 = (inferenceHandler, inputs, mode) => {
+ validateInputsV11(inputs);
+ const attrubutes = generatePadAttributesFromInputs(inferenceHandler, inputs, mode);
+ return (0, exports.padV2)(inferenceHandler, [inputs[0]], attrubutes);
+};
+exports.padV11 = padV11;
+const parsePadAttributesV11 = (node) => node.attributes.getString('mode', 'constant');
+exports.parsePadAttributesV11 = parsePadAttributesV11;
+const generatePadAttributesFromInputs = (inferenceHandler, inputs, mode) => {
+ if (!inferenceHandler.session.isInitializer(inputs[1].dataId) ||
+ (inputs.length >= 3 && !inferenceHandler.session.isInitializer(inputs[2].dataId))) {
+ throw new Error('dynamic pad attributes are not allowed');
+ }
+ const pads = Array.from(inputs[1].integerData);
+ const value = (inputs.length >= 3) ? inputs[2].floatData[0] : 0.0;
+ return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ mode, pads, value });
+};
+const createPadProgramInfo = (inferenceHandler, input, attributes) => {
+ const outputShape = util_1.ShapeUtil.padShape(input.dims.slice(), attributes.pads);
+ const rank = outputShape.length;
+ const padFunction = getPadFunction(inferenceHandler, input, attributes);
+ const shaderSource = `
+ ${padFunction}
+ float process(int[${rank}] indices) {
+ return padA(indices);
+ }`;
+ return {
+ name: 'Pad',
+ inputNames: ['A'],
+ inputTypes: [types_1.TextureType.unpacked],
+ output: { dims: outputShape, type: input.type, textureType: types_1.TextureType.unpacked },
+ shaderSource
+ };
+};
+const validateInputsV2 = (inputs) => {
+ if (!inputs || inputs.length !== 1) {
+ throw new Error('Pad requires 1 input');
+ }
+ if (inputs[0].type !== 'float32' && inputs[0].type !== 'float64') {
+ throw new Error('Invalid input type.');
+ }
+};
+const validateInputsV11 = (inputs) => {
+ if (!inputs || (inputs.length !== 2 && inputs.length !== 3)) {
+ throw new Error('Pad requires 2 or 3 inputs');
+ }
+ if (inputs[1].type !== 'int32') {
+ throw new Error('Invalid input type.');
+ }
+ if (inputs.length >= 3 && inputs[2].type === 'string') {
+ throw new Error('Invalid input type.');
+ }
+};
+const getPadFunction = (inferenceHandler, input, attributes) => {
+ const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
+ const [width, height] = inferenceHandler.calculateTextureWidthAndHeight(input.dims, types_1.TextureType.unpacked);
+ const strides = util_1.ShapeUtil.computeStrides(input.dims);
+ switch (attributes.mode) {
+ case 'constant':
+ return getPadConstant(glsl, input.dims, strides, width, height, attributes.pads, attributes.value);
+ case 'reflect':
+ return getPadReflect(glsl, input.dims, strides, width, height, attributes.pads);
+ case 'edge':
+ return getPadEdge(glsl, input.dims, strides, width, height, attributes.pads);
+ default:
+ throw new Error('Invalid mode');
+ }
+};
+const getPadConstant = (glsl, shape, strides, width, height, pads, value) => {
+ const rank = shape.length;
+ let block = '';
+ for (let i = rank - 1; i >= 0; --i) {
+ block += `
+ k = m[${i}] - ${pads[i]};
+ if (k < 0) return constant;
+ if (k >= ${shape[i]}) return constant;
+ offset += k * ${strides[i]};
+ `;
+ }
+ return `
+ float padA(int m[${rank}]) {
+ const float constant = float(${value});
+ int offset = 0;
+ int k = 0;
+ ${block}
+ vec2 coords = offsetToCoords(offset, ${width}, ${height});
+ float value = getColorAsFloat(${glsl.texture2D}(A, coords));
+ return value;
+ }
+ `;
+};
+const getPadReflect = (glsl, shape, strides, width, height, pads) => {
+ const rank = shape.length;
+ let block = '';
+ for (let i = rank - 1; i >= 0; --i) {
+ block += `
+ k = m[${i}] - ${pads[i]};
+ if (k < 0) { k = -k; }
+ {
+ const int _2n_1 = ${2 * (shape[i] - 1)};
+ k = int( mod( float(k), float(_2n_1) ) ) ;
+ if(k >= ${shape[i]}) { k = _2n_1 - k; }
+ }
+ offset += k * ${strides[i]};
+ `;
+ }
+ return `
+ float padA(int m[${rank}]) {
+ int offset = 0;
+ int k = 0;
+ ${block}
+ vec2 coords = offsetToCoords(offset, ${width}, ${height});
+ float value = getColorAsFloat(${glsl.texture2D}(A, coords));
+ return value;
+ }
+ `;
+};
+const getPadEdge = (glsl, shape, strides, width, height, pads) => {
+ const rank = shape.length;
+ let block = '';
+ for (let i = rank - 1; i >= 0; --i) {
+ block += `
+ k = m[${i}] - ${pads[i]};
+ if (k < 0) k = 0;
+ if (k >= ${shape[i]}) k = ${shape[i] - 1};
+ offset += k * ${strides[i]};
+ `;
+ }
+ return `
+ float padA(int m[${rank}]) {
+ int offset = 0;
+ int k = 0;
+ ${block}
+ vec2 coords = offsetToCoords(offset, ${width}, ${height});
+ float value = getColorAsFloat(${glsl.texture2D}(A, coords));
+ return value;
+ }
+ `;
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/pool.ts":
+/*!***********************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/pool.ts ***!
+ \***********************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.globalMaxPool = exports.parseMaxPoolAttributes = exports.maxPool = exports.parseGlobalAveragePoolAttributes = exports.globalAveragePool = exports.parseAveragePoolAttributes = exports.averagePool = void 0;
+const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const averagePool = (inferenceHandler, inputs, attributes) => {
+ validateInputs(inputs);
+ const metadata = { name: 'AveragePool', inputNames: ['X'], inputTypes: [types_1.TextureType.unpacked], cacheHint: attributes.cacheKey };
+ const output = inferenceHandler.run(Object.assign(Object.assign({}, metadata), { get: () => createAveragePoolProgramInfo(inputs, metadata, false, attributes) }), inputs);
+ return [output];
+};
+exports.averagePool = averagePool;
+const parseAveragePoolAttributes = (node) => {
+ const autoPad = node.attributes.getString('auto_pad', 'NOTSET');
+ const ceilMode = node.attributes.getInt('ceil_mode', 0);
+ const countIncludePad = (node.attributes.getInt('count_include_pad', 0) === 0 ? false : true);
+ const kernelShape = node.attributes.getInts('kernel_shape');
+ const strides = node.attributes.getInts('strides', []);
+ const pads = node.attributes.getInts('pads', []);
+ // TODO: support attribute 'ceil_mode'
+ if (ceilMode !== 0) {
+ throw new Error('using ceil() in shape computation is not yet supported for AveragePool');
+ }
+ return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ autoPad, ceilMode, countIncludePad, kernelShape, strides, pads });
+};
+exports.parseAveragePoolAttributes = parseAveragePoolAttributes;
+const createAveragePoolProgramInfo = (inputs, metadata, isGlobalOperator, attributes) => {
+ const [adjustedAttributes, outputShape] = getAdjustedPoolAttributesAndOutputShape(inputs, attributes, isGlobalOperator);
+ const kernelSize = util_1.ShapeUtil.size(adjustedAttributes.kernelShape);
+ const op1 = 'value += _X(x);';
+ let op2 = '';
+ if (adjustedAttributes.countIncludePad) {
+ op2 += `value /= float(${kernelSize});`;
+ }
+ else {
+ op2 += `value /= float(${kernelSize} - pad);`;
+ }
+ const poolingCode = generatePoolingCode(inputs[0].dims, adjustedAttributes, op1, op2, '0.0');
+ const shaderSource = `
+ ${poolingCode}
+ `;
+ return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource });
+};
+const globalAveragePool = (inferenceHandler, inputs, attributes) => {
+ validateInputs(inputs);
+ const metadata = {
+ name: 'GlobalAveragePool',
+ inputNames: ['X'],
+ inputTypes: [types_1.TextureType.unpacked],
+ cacheHint: `${attributes.countIncludePad}`
+ };
+ const output = inferenceHandler.run(Object.assign(Object.assign({}, metadata), { get: () => createAveragePoolProgramInfo(inputs, metadata, true, attributes) }), inputs);
+ return [output];
+};
+exports.globalAveragePool = globalAveragePool;
+const parseGlobalAveragePoolAttributes = (node) => {
+ const countIncludePad = (node.attributes.getInt('count_include_pad', 0) === 0 ? false : true);
+ return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ autoPad: '', ceilMode: 0, countIncludePad, kernelShape: [], strides: [], pads: [] });
+};
+exports.parseGlobalAveragePoolAttributes = parseGlobalAveragePoolAttributes;
+const maxPool = (inferenceHandler, inputs, attributes) => {
+ validateInputs(inputs);
+ const metadata = { name: 'MaxPool', inputNames: ['X'], inputTypes: [types_1.TextureType.unpacked], cacheHint: attributes.cacheKey };
+ const output = inferenceHandler.run(Object.assign(Object.assign({}, metadata), { get: () => createMaxPoolProgramInfo(inputs, metadata, false, attributes) }), inputs);
+ return [output];
+};
+exports.maxPool = maxPool;
+const parseMaxPoolAttributes = (node) => {
+ const autoPad = node.attributes.getString('auto_pad', 'NOTSET');
+ const ceilMode = node.attributes.getInt('ceil_mode', 0);
+ const kernelShape = node.attributes.getInts('kernel_shape');
+ const strides = node.attributes.getInts('strides', []);
+ const pads = node.attributes.getInts('pads', []);
+ const storageOrder = node.attributes.getInt('storage_order', 0);
+ const dilations = node.attributes.getInts('dilations', []);
+ // TODO: support attribute 'ceil_mode' and 'storage_order'
+ if (storageOrder !== 0) {
+ throw new Error('column major storage order is not yet supported for MaxPool');
+ }
+ if (ceilMode !== 0) {
+ throw new Error('using ceil() in shape computation is not yet supported for MaxPool');
+ }
+ return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ autoPad, ceilMode, countIncludePad: false, kernelShape, strides, pads, storageOrder, dilations });
+};
+exports.parseMaxPoolAttributes = parseMaxPoolAttributes;
+const createMaxPoolProgramInfo = (inputs, metadata, isGlobalOperator, attributes) => {
+ const [adjustedAttributes, outputShape] = getAdjustedPoolAttributesAndOutputShape(inputs, attributes, isGlobalOperator);
+ const op1 = `
+ value = max(_X(x), value);
+ `;
+ const op2 = '';
+ const poolingCode = generatePoolingCode(inputs[0].dims, adjustedAttributes, op1, op2, '-1e5');
+ const shaderSource = `
+ ${poolingCode}
+ `;
+ return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource });
+};
+const getAdjustedPoolAttributesAndOutputShape = (inputs, attributes, isGlobalOperator) => {
+ const inputShape = inputs[0].dims.slice();
+ const hasDilations = Object.hasOwnProperty.call(attributes, 'dilations');
+ const kernelShape = attributes.kernelShape.slice();
+ const strides = attributes.strides.slice();
+ const dilations = hasDilations ? attributes.dilations.slice() : [];
+ const pads = attributes.pads.slice();
+ util_1.PoolConvUtil.adjustPoolAttributes(isGlobalOperator, inputShape, kernelShape, strides, dilations, pads);
+ const outputShape = util_1.PoolConvUtil.computePoolOutputShape(isGlobalOperator, inputShape, strides, dilations, kernelShape, pads, attributes.autoPad);
+ const newAttributes = Object.assign({}, attributes);
+ if (hasDilations) {
+ Object.assign(newAttributes, { kernelShape, strides, pads, dilations, cacheKey: attributes.cacheKey });
+ }
+ else {
+ Object.assign(newAttributes, { kernelShape, strides, pads, cacheKey: attributes.cacheKey });
+ }
+ return [newAttributes, outputShape];
+};
+const globalMaxPoolAttributes = {
+ autoPad: '',
+ ceilMode: 0,
+ countIncludePad: false,
+ kernelShape: [],
+ strides: [],
+ pads: [],
+ storageOrder: 0,
+ dilations: [],
+ cacheKey: ''
+};
+const globalMaxPoolMetadata = {
+ name: 'GlobalMaxPool',
+ inputNames: ['X'],
+ inputTypes: [types_1.TextureType.unpacked]
+};
+const globalMaxPool = (inferenceHandler, inputs) => {
+ validateInputs(inputs);
+ const output = inferenceHandler.run(Object.assign(Object.assign({}, globalMaxPoolMetadata), { get: () => createMaxPoolProgramInfo(inputs, globalMaxPoolMetadata, true, globalMaxPoolAttributes) }), inputs);
+ return [output];
+};
+exports.globalMaxPool = globalMaxPool;
+const validateInputs = (inputs) => {
+ if (!inputs || inputs.length !== 1) {
+ throw new Error('Pool ops requires 1 input.');
+ }
+ if (inputs[0].type !== 'float32' && inputs[0].type !== 'float64') {
+ throw new Error('Invalid input type.');
+ }
+};
+const generatePoolingCode = (inputDims, attributes, op1, op2, start) => {
+ const rank = inputDims.length;
+ if (attributes.kernelShape.length <= 2) {
+ const kw = attributes.kernelShape[attributes.kernelShape.length - 1];
+ const sw = attributes.strides[attributes.strides.length - 1];
+ const pwStart = attributes.pads[attributes.pads.length / 2 - 1];
+ const pwEnd = attributes.pads[attributes.pads.length - 1];
+ const dimW = inputDims[rank - 1];
+ let codeW = '';
+ let codeH = '';
+ let codeHEnd = '';
+ if (pwStart + pwEnd !== 0) {
+ codeW = `
+ for (int i = 0; i < ${kw}; i++) {
+ x[${rank} - 1] = indices[${rank} - 1] * ${sw} - ${pwStart} + i;
+ if (x[${rank} - 1] < 0 || x[${rank} - 1] >= ${dimW}) {
+ pad++;
+ continue;
+ }
+ ${op1}
+ }`;
+ }
+ else {
+ codeW = `
+ for (int i = 0; i < ${kw}; i++) {
+ x[${rank} - 1] = indices[${rank} - 1] * ${sw} - ${pwStart} + i;
+ ${op1}
+ }`;
+ }
+ if (attributes.kernelShape.length === 2) {
+ const kh = attributes.kernelShape[attributes.kernelShape.length - 2];
+ const sh = attributes.strides[attributes.strides.length - 2];
+ const phStart = attributes.pads[attributes.pads.length / 2 - 2];
+ const phEnd = attributes.pads[attributes.pads.length - 2];
+ const dimH = inputDims[rank - 2];
+ if (phStart + phEnd !== 0) {
+ codeH = `
+ for (int j = 0; j < ${kh}; j++) {
+ x[${rank} - 2] = indices[${rank} - 2] * ${sh} - ${phStart} + j;
+ if (x[${rank} - 2] < 0 || x[${rank} - 2] >= ${dimH}) {
+ pad+= ${kw};
+ continue;
+ }
+ `;
+ }
+ else {
+ codeH = `
+ for (int j = 0; j < ${kh}; j++) {
+ x[${rank} - 2] = indices[${rank} - 2] * ${sh} - ${phStart} + j;
+ `;
+ }
+ codeHEnd = `
+ }
+ `;
+ }
+ const poolingCode = `
+ float process(int indices[${rank}]) {
+ int x[${rank}];
+ copyVec(indices, x);
+
+ float value = ${start};
+ int pad = 0;
+ ${codeH}
+ ${codeW}
+ ${codeHEnd}
+ ${op2}
+ return value;
+ }
+ `;
+ return poolingCode;
+ }
+ else {
+ const kernelSize = util_1.ShapeUtil.size(attributes.kernelShape);
+ const kernelStrides = util_1.ShapeUtil.computeStrides(attributes.kernelShape);
+ const stridesRank = kernelStrides.length;
+ const padsRank = attributes.pads.length;
+ const offsetToIndicesFunction = offsetToIndices(stridesRank);
+ const copyInputDims = copyArray(inputDims, 'inputDims');
+ const copyPads = copyArray(attributes.pads, 'pads');
+ const copyKernelStrides = copyArray(kernelStrides, 'kernelStrides');
+ const copyStrides = copyArray(attributes.strides, 'strides');
+ const hasPads = attributes.pads.reduce((sum, cur) => sum + cur);
+ let padCode = '';
+ if (hasPads) {
+ padCode = `
+ if (x[j] >= inputDims[j] || x[j] < 0) {
+ pad++;
+ isPad = true;
+ break;
+ }
+ }
+ if (!isPad) {
+ ${op1}
+ }`;
+ }
+ else {
+ padCode = `
+ }
+ ${op1}
+ `;
+ }
+ const poolingCode = `
+ ${offsetToIndicesFunction}
+ float process(int indices[${rank}]) {
+ int x[${rank}];
+ copyVec(indices, x);
+ int offset[${stridesRank}];
+ int pads[${padsRank}];
+ int inputDims[${rank}];
+ int kernelStrides[${stridesRank}];
+ int strides[${stridesRank}];
+ ${copyPads}
+ ${copyInputDims}
+ ${copyStrides}
+ ${copyKernelStrides}
+
+ float value = ${start};
+ int pad = 0;
+ bool isPad = false;
+ for (int i = 0; i < ${kernelSize}; i++) {
+ offsetToIndices(i, kernelStrides, offset);
+ isPad = false;
+ for (int j = ${rank} - ${stridesRank}; j < ${rank}; j++) {
+ x[j] = indices[j] * strides[j - ${rank} + ${stridesRank}]
+ + offset[j - ${rank} + ${stridesRank}] - pads[j - 2];
+ ${padCode}
+ }
+ ${op2}
+
+ return value;
+ }
+ `;
+ return poolingCode;
+ }
+};
+const copyArray = (array, arrayName) => {
+ let block = '';
+ for (let i = 0; i < array.length; i++) {
+ block += `
+ ${arrayName}[${i}] = ${array[i]};
+ `;
+ }
+ return block;
+};
+const offsetToIndices = (rank) => `
+ void offsetToIndices(int offset, int[${rank}] strides, out int[${rank}] indices) {
+ if (${rank} == 0) {
+ return;
+ }
+ for (int i = 0; i < ${rank} - 1; ++i) {
+ indices[i] = offset / strides[i];
+ offset -= indices[i] * strides[i];
+ }
+ indices[${rank} - 1] = offset;
+ }`;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/reduce.ts":
+/*!*************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/reduce.ts ***!
+ \*************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.reduceLogSumSquare = exports.reduceLogSum = exports.reduceProd = exports.reduceMin = exports.reduceMax = exports.reduceMean = exports.reduceSum = exports.parseReduceAttributes = void 0;
+const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
+const operators_1 = __webpack_require__(/*! ../../../operators */ "./lib/onnxjs/operators.ts");
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const reduce = (inferenceHandler, inputs, attributes, name, reduceOp) => {
+ validateInputs(inputs);
+ const reduceProgramMetadata = {
+ name,
+ inputNames: ['A'],
+ inputTypes: [types_1.TextureType.unpacked],
+ };
+ const output = inferenceHandler.run(Object.assign(Object.assign({}, reduceProgramMetadata), { cacheHint: attributes.cacheKey, get: () => createReduceProgramInfo(inferenceHandler, inputs, attributes, name, reduceOp, reduceProgramMetadata) }), inputs);
+ return [output];
+};
+const parseReduceAttributes = (node) => {
+ const axes = node.attributes.getInts('axes', []);
+ const keepDims = node.attributes.getInt('keepdims', 1) === 1;
+ return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ axes, keepDims });
+};
+exports.parseReduceAttributes = parseReduceAttributes;
+const createReduceProgramInfo = (handler, inputs, attributes, name, reduceOp, reduceProgramMetadata) => {
+ const outputShape = [];
+ const iRank = inputs[0].dims.length || 1;
+ const idxCopy = []; // copy output indexes to input indexes
+ const axes = util_1.ShapeUtil.normalizeAxes(attributes.axes, inputs[0].dims.length);
+ const ops = reduceOp(inputs, axes);
+ let reduceOps = ops[1];
+ for (let k = 0; k < inputs[0].dims.length; k++) {
+ // if this axis is reduced
+ if (axes.indexOf(k) >= 0 || axes.length === 0) {
+ if (attributes.keepDims) {
+ outputShape.push(1);
+ } // else { remove the axis from outputShape; }
+ // loop over the d-th axis
+ reduceOps = `
+ for(int j${k} = 0; j${k} < ${inputs[0].dims[k]}; j${k}++) {
+ inputIdx[${k}] = j${k};
+ ${reduceOps}
+ }`;
+ }
+ else {
+ idxCopy.push(`inputIdx[${k}] = outputIdx[${outputShape.length}];`);
+ outputShape.push(inputs[0].dims[k]);
+ }
+ }
+ const oRank = outputShape.length || 1;
+ const shaderSource = `
+ float process(int outputIdx[${oRank}]) {
+ float value; // final result
+ int inputIdx[${iRank}]; // addressing input data
+ ${idxCopy.join('\n')}
+ ${ops[0]} // init ops for reduce max/min
+ ${reduceOps}
+ ${ops[2]} // final computation for reduce mean
+ return value;
+ }`;
+ return Object.assign(Object.assign({}, reduceProgramMetadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource });
+};
+const validateInputs = (inputs) => {
+ if (!inputs || inputs.length !== 1) {
+ throw new Error('Reduce op requires 1 input.');
+ }
+ if (operators_1.NUMBER_TYPES.indexOf(inputs[0].type) === -1) {
+ throw new Error('Invalid input type.');
+ }
+};
+const reduceSum = (inferenceHandler, inputs, attributes) => {
+ const reduceOp = () => ['value = 0.0;', 'value += _A(inputIdx);', ''];
+ return reduce(inferenceHandler, inputs, attributes, 'ReduceSum', reduceOp);
+};
+exports.reduceSum = reduceSum;
+const reduceMean = (inferenceHandler, inputs, attributes) => {
+ const reduceOp = (inputs, axes) => {
+ let size = 1.0;
+ for (let k = 0; k < inputs[0].dims.length; k++) {
+ if (axes.indexOf(k) >= 0 || axes.length === 0) {
+ size *= inputs[0].dims[k];
+ }
+ }
+ return ['value = 0.0;', 'value += _A(inputIdx);', `value /= ${size}.;`]; // ensure real number with `.`
+ };
+ return reduce(inferenceHandler, inputs, attributes, 'ReduceMean', reduceOp);
+};
+exports.reduceMean = reduceMean;
+const reduceMax = (inferenceHandler, inputs, attributes) => {
+ const reduceOp = (inputs, axes) => {
+ const idxZero = [];
+ for (let k = 0; k < inputs[0].dims.length; k++) {
+ if (axes.indexOf(k) >= 0 || axes.length === 0) {
+ idxZero.push(`inputIdx[${k}] = 0;`); // first element
+ }
+ }
+ return [`${idxZero.join('\n')}\nvalue = _A(inputIdx);`, 'value = max(value, _A(inputIdx));', ''];
+ };
+ return reduce(inferenceHandler, inputs, attributes, 'ReduceMax', reduceOp);
+};
+exports.reduceMax = reduceMax;
+const reduceMin = (inferenceHandler, inputs, attributes) => {
+ const reduceOp = (inputs, axes) => {
+ const idxZero = [];
+ for (let k = 0; k < inputs[0].dims.length; k++) {
+ if (axes.indexOf(k) >= 0 || axes.length === 0) {
+ idxZero.push(`inputIdx[${k}] = 0;`); // first element
+ }
+ }
+ return [`${idxZero.join('\n')}\nvalue = _A(inputIdx);`, 'value = min(value, _A(inputIdx));', ''];
+ };
+ return reduce(inferenceHandler, inputs, attributes, 'ReduceMin', reduceOp);
+};
+exports.reduceMin = reduceMin;
+const reduceProd = (inferenceHandler, inputs, attributes) => {
+ const reduceOp = () => ['value = 1.0;', 'value *= _A(inputIdx);', ''];
+ return reduce(inferenceHandler, inputs, attributes, 'ReduceProd', reduceOp);
+};
+exports.reduceProd = reduceProd;
+const reduceLogSum = (inferenceHandler, inputs, attributes) => {
+ const reduceOp = () => ['value = 0.0;', 'value += _A(inputIdx);', 'value = log(value);'];
+ return reduce(inferenceHandler, inputs, attributes, 'ReduceLogSum', reduceOp);
+};
+exports.reduceLogSum = reduceLogSum;
+const reduceLogSumSquare = (inferenceHandler, inputs, attributes) => {
+ const reduceOp = () => ['float t; value = 0.0;', 't = _A(inputIdx); value += t * t;', ''];
+ return reduce(inferenceHandler, inputs, attributes, 'ReduceLogSumSquare', reduceOp);
+};
+exports.reduceLogSumSquare = reduceLogSumSquare;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/reshape-packed.ts":
+/*!*********************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/reshape-packed.ts ***!
+ \*********************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isReshapeCheap = exports.processDims3D = exports.createPackedReshape3DProgramInfoLoader = void 0;
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const packing_utils_1 = __webpack_require__(/*! ./packing-utils */ "./lib/onnxjs/backends/webgl/ops/packing-utils.ts");
+const createPackedReshape3DProgramMetadata = (outputShape3D) => ({ name: 'Reshape (packed)', inputTypes: [types_1.TextureType.packed], inputNames: ['A'], cacheHint: `${outputShape3D}` });
+const createPackedReshape3DProgramInfo = (handler, input3D, metadata, outputShape3D) => {
+ const inputShape3D = input3D.dims;
+ const squeezedOutputShape = outputShape3D;
+ let mainLoop = '';
+ for (let i = 0; i < 4; i++) {
+ let outputCoords = '';
+ switch (i) {
+ case 0:
+ outputCoords = 'outputCoords = rc;';
+ break;
+ case 1:
+ outputCoords = 'outputCoords = ivec3(rc.x, rc.y+1, rc.z);';
+ break;
+ case 2:
+ outputCoords = 'outputCoords = ivec3(rc.x, rc.y, rc.z+1);';
+ break;
+ case 3:
+ outputCoords = 'outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);';
+ break;
+ default:
+ throw new Error();
+ }
+ mainLoop += `
+ ${outputCoords}
+ ${i > 0 ? 'if(outputCoords.y < rows && outputCoords.z < cols){' : ''}
+ int flattenedIndex = getFlattenedIndex(outputCoords);
+
+ ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex);
+ vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z));
+
+ result[${i}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims);
+
+ ${i > 0 ? '}' : ''}
+ `;
+ }
+ const glsl = (0, glsl_source_1.getGlsl)(handler.session.backend.glContext.version);
+ const shaderSource = `
+ ${getReshapedInputCoords(inputShape3D)}
+ ${getFlattenedIndexFrom3D(squeezedOutputShape)}
+ ${(0, packing_utils_1.unpackFromChannel)()}
+
+ void main() {
+ ivec3 rc = getOutputCoords();
+
+ vec4 result = vec4(0.0);
+
+ ivec3 outputCoords;
+ int rows = ${squeezedOutputShape[2]};
+ int cols = ${squeezedOutputShape[1]};
+
+ ${mainLoop}
+ ${glsl.output} = result;
+ }
+ `;
+ return Object.assign(Object.assign({}, metadata), { output: { dims: squeezedOutputShape, type: input3D.type, textureType: types_1.TextureType.packed }, shaderSource, hasMain: true });
+};
+const createPackedReshape3DProgramInfoLoader = (handler, input3D, outputShape3D) => {
+ const metadata = createPackedReshape3DProgramMetadata(outputShape3D);
+ return Object.assign(Object.assign({}, metadata), { get: () => createPackedReshape3DProgramInfo(handler, input3D, metadata, outputShape3D) });
+};
+exports.createPackedReshape3DProgramInfoLoader = createPackedReshape3DProgramInfoLoader;
+function processDims3D(shape) {
+ if (shape.length === 0) {
+ return [1, 1, 1];
+ }
+ // TODO: squeeze other shapes to 2D case
+ let batch = 1;
+ for (let i = 0; i < shape.length - 2; ++i) {
+ batch *= shape[i];
+ }
+ return [batch, shape.length > 1 ? shape[shape.length - 2] : 1, shape[shape.length - 1]];
+}
+exports.processDims3D = processDims3D;
+// For packed reshape, we need to re-arrange texel data for output shape.
+// Our pack is designed to pack a 2x2 tile in last h and w dimension, so
+// for the reshaped new tensor, we just need to re-arrange the last h and
+// w dimension. For any shape that is not in 3D, i.e. [batch, W, H], we
+// first convert it to 3D by collapsing other dimension to batch dim, then
+// process with the last two dimensions.
+// Note: we only need the shape tensor to calculate output shape, so the
+// content in shape tensor is never uploaded to GPU. It is always kept in CPU.
+// TODO: optimize the algorithm -- in some cases, if the last two dims are
+// the same between input shape and output shape, the packed reshape can be
+// treated as no-op.
+function isReshapeCheap(dims, reshapedDims) {
+ let isCheapReshape = false;
+ if (dims.length === 0 || reshapedDims.length === 0) { // scalar
+ isCheapReshape = true;
+ }
+ else if (dims.length < 2 || reshapedDims.length < 2) { // 1D
+ isCheapReshape = dims[dims.length - 1] === reshapedDims[reshapedDims.length - 1];
+ }
+ else { // 2D +
+ isCheapReshape = dims[dims.length - 1] === reshapedDims[reshapedDims.length - 1] &&
+ dims[dims.length - 2] === reshapedDims[reshapedDims.length - 2];
+ }
+ return isCheapReshape;
+}
+exports.isReshapeCheap = isReshapeCheap;
+function getReshapedInputCoords(shape) {
+ const strides = util_1.ShapeUtil.computeStrides(shape);
+ const coords = ['b', 'r', 'c'];
+ const index = 'index';
+ const coordsFromIndexSnippet = strides
+ .map((stride, i) => {
+ const line1 = `int ${coords[i]} = ${index} / ${stride}`;
+ const line2 = i === strides.length - 1 ?
+ `int ${coords[i + 1]} = ${index} - ${coords[i]} * ${stride}` :
+ `index -= ${coords[i]} * ${stride}`;
+ return `${line1}; ${line2};`;
+ })
+ .join('');
+ return `
+ ivec3 inputCoordsFromReshapedOutCoords(int index) {
+ ${coordsFromIndexSnippet}
+ return ivec3(b, r, c);
+ }
+ `;
+}
+function getFlattenedIndexFrom3D(shape) {
+ const strides = util_1.ShapeUtil.computeStrides(shape);
+ return `
+ int getFlattenedIndex(ivec3 coords) {
+ // reverse y, z order
+ return coords.x * ${strides[0]} + coords.z * ${strides[1]} + coords.y;
+ }
+`;
+}
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/reshape.ts":
+/*!**************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/reshape.ts ***!
+ \**************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.reshape = void 0;
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const reshape = (handler, inputs) => {
+ const reshapedDims = util_1.ShapeUtil.calculateReshapedDims(inputs[0].dims, inputs[1].integerData);
+ if (handler.session.pack) {
+ return [handler.reshapePacked(inputs[0], reshapedDims)];
+ }
+ else {
+ return [handler.reshapeUnpacked(inputs[0], reshapedDims)];
+ }
+};
+exports.reshape = reshape;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/resize-packed.ts":
+/*!********************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/resize-packed.ts ***!
+ \********************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseResizeAttributesV11 = exports.parseResizeAttributesV10 = exports.resize = void 0;
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const utils_1 = __webpack_require__(/*! ../utils */ "./lib/onnxjs/backends/webgl/utils.ts");
+const packing_utils_1 = __webpack_require__(/*! ./packing-utils */ "./lib/onnxjs/backends/webgl/ops/packing-utils.ts");
+const upsample_1 = __webpack_require__(/*! ./upsample */ "./lib/onnxjs/backends/webgl/ops/upsample.ts");
+const resizeProgramMetadata = {
+ name: 'Resize',
+ inputNames: ['A'],
+ inputTypes: [types_1.TextureType.packed]
+};
+const resize = (inferenceHandler, inputs, attributes) => {
+ (0, upsample_1.validateInputs)(inputs, attributes);
+ const output = inferenceHandler.run(Object.assign(Object.assign({}, resizeProgramMetadata), { cacheHint: attributes.cacheKey, get: () => createPackedResizeProgramInfo(inferenceHandler, inputs, attributes) }), inputs);
+ return [output];
+};
+exports.resize = resize;
+const parseResizeAttributesV10 = (node) => (0, upsample_1.parseUpsampleAttributes)(node, 10);
+exports.parseResizeAttributesV10 = parseResizeAttributesV10;
+const parseResizeAttributesV11 = (node) => (0, upsample_1.parseUpsampleAttributes)(node, 11);
+exports.parseResizeAttributesV11 = parseResizeAttributesV11;
+const createPackedResizeProgramInfo = (inferenceHandler, inputs, attributes) => {
+ const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
+ const [scales, outputShape] = prepareInputs(inputs, attributes);
+ const isSame = scales.every((s) => s === 1) && attributes.coordinateTransformMode !== 'tf_crop_and_resize';
+ if (isSame) {
+ return Object.assign(Object.assign({}, resizeProgramMetadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.packed }, hasMain: true, shaderSource: `void main() {
+ vec4 v = ${glsl.texture2D}(X, TexCoords);
+ ${glsl.output} = v;
+ }` });
+ }
+ const dim = outputShape.length;
+ if (dim < 2) {
+ throw new Error(`output dimension should be at least 2, but got ${dim}`);
+ }
+ const outputHeight = outputShape[dim - 2];
+ const outputWidth = outputShape[dim - 1];
+ const inputShape = inputs[0].dims;
+ if (dim !== inputShape.length) {
+ throw new Error(`output dimension should match input ${inputShape.length}, but got ${dim}`);
+ }
+ const inputHeight = inputShape[dim - 2];
+ const inputWidth = inputShape[dim - 1];
+ const scalesHeight = scales[dim - 2];
+ const scalesWidth = scales[dim - 1];
+ let getSourceFracIndex = '';
+ if (attributes.mode !== 'linear') {
+ // TODO: support other modes
+ throw new Error(`resize (packed) does not support mode: '${attributes.mode}'`);
+ }
+ switch (attributes.coordinateTransformMode) {
+ case 'asymmetric':
+ getSourceFracIndex = `
+ vec4 getSourceFracIndex(ivec4 coords) {
+ return vec4(coords) / scaleWHWH;
+ }
+ `;
+ break;
+ case 'half_pixel':
+ getSourceFracIndex = `
+ vec4 getSourceFracIndex(ivec4 coords) {
+ return (vec4(coords) + 0.5) / scaleWHWH - 0.5;
+ }
+ `;
+ break;
+ case 'pytorch_half_pixel':
+ getSourceFracIndex = `
+ vec4 getSourceFracIndex(ivec4 coords) {
+ vec4 fcoords = vec4(coords);
+ return vec4(
+ ${outputWidth}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0,
+ ${outputHeight}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0,
+ ${outputWidth}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0,
+ ${outputHeight}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0
+ );
+ }
+ `;
+ break;
+ case 'align_corners':
+ getSourceFracIndex = `
+ vec4 getSourceFracIndex(ivec4 coords) {
+ vec4 resized = vec4(${outputWidth}.0 - 1.0, ${outputHeight}.0 - 1.0, ${outputWidth}.0 - 1.0,
+ ${outputHeight}.0 - 1.0);
+ vec4 original = vec4(${inputWidth}.0 - 1.0, ${inputHeight}.0 - 1.0, ${inputWidth}.0 - 1.0,
+ ${inputHeight}.0 - 1.0);
+ vec4 new_scale = original / resized;
+ return vec4(coords) * new_scale;
+ }
+ `;
+ break;
+ default:
+ // TODO:supporting other coordinateTransformModes
+ throw new Error(`resize (packed) does not support coordinateTransformMode: \
+ '${attributes.coordinateTransformMode}'`);
+ }
+ const coordsDataType = (0, utils_1.getCoordsDataType)(dim);
+ const unpackChannel = (0, packing_utils_1.unpackFromChannel)();
+ const shaderSource = `
+ const vec2 inputWH = vec2(${inputHeight}.0, ${inputWidth}.0);
+ const vec4 scaleWHWH = vec4(float(${scalesHeight}), float(${scalesWidth}), float(${scalesHeight}), float(${scalesWidth}));
+ ${unpackChannel}
+ ${getSourceFracIndex}
+ float getAValue(int x10, int r, int c, int d) {
+ return getChannel(getA(x10, r, c, d), vec2(c, d));
+ }
+ void main() {
+ ${coordsDataType} rc = getOutputCoords();
+
+ int batch = rc[0];
+ int depth = rc[1];
+
+ // retrieve the 4 coordinates that is used in the 4 packed output values.
+ ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1);
+
+ // calculate the source index in fraction
+ vec4 sourceFrac = getSourceFracIndex(coords);
+
+ // get the lower and upper bound of the 4 values that will be packed into one texel.
+ ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy)));
+ ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw)));
+ ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy)));
+ ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw)));
+
+ bool hasNextRow = rc.w < ${outputHeight - 1};
+ bool hasNextCol = rc.z < ${outputWidth - 1};
+
+ // pack x00, x01, x10, x11's top-left corner into one vec4 structure
+ vec4 topLeft = vec4(
+ getAValue(batch, depth, x00.x, x00.y),
+ hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0,
+ hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0,
+ (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0);
+
+ // pack x00, x01, x10, x11's top-right corner into one vec4 structure
+ vec4 topRight = vec4(
+ getAValue(batch, depth, x00.x, x00.w),
+ hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0,
+ hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0,
+ (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0);
+
+ // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure
+ vec4 bottomLeft = vec4(
+ getAValue(batch, depth, x00.z, x00.y),
+ hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0,
+ hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0,
+ (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0);
+
+ // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure
+ vec4 bottomRight = vec4(
+ getAValue(batch, depth, x00.z, x00.w),
+ hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0,
+ hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0,
+ (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0);
+
+ // calculate the interpolation fraction on u and v direction
+ vec4 frac = vec4(sourceFrac) - floor(sourceFrac);
+ vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0));
+
+ vec4 top = mix(topLeft, topRight, clampFrac.ywyw);
+ vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw);
+ vec4 newValue = mix(top, bottom, clampFrac.xxzz);
+
+ ${glsl.output} = vec4(newValue);
+ }
+ `;
+ return Object.assign(Object.assign({}, resizeProgramMetadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.packed }, hasMain: true, shaderSource });
+};
+const prepareInputs = (inputs, attributes) => {
+ const x = inputs[0];
+ const xDims = x.dims;
+ let scales = attributes.scales;
+ let outputSizes;
+ if (scales.length === 0) {
+ const scalesTensor = inputs[attributes.scalesInputIdx];
+ if (scalesTensor && scalesTensor.size !== 0) {
+ if (inputs[attributes.sizesInputIdx]) {
+ throw new Error('Only one of scales or sizes must be provided as input.');
+ }
+ scales = parseScalesData(scalesTensor, attributes.mode, attributes.isResize);
+ }
+ else {
+ const sizesTensor = inputs[attributes.sizesInputIdx];
+ if (!sizesTensor || sizesTensor.size === 0) {
+ throw new Error('Either scales or sizes MUST be provided as input.');
+ }
+ outputSizes = Array.from(sizesTensor.integerData);
+ scales = parseScalesDataFromOutputSize(outputSizes, xDims, attributes.mode, attributes.isResize);
+ }
+ }
+ else {
+ if (inputs[attributes.sizesInputIdx]) {
+ throw new Error('Only one of scales or sizes must be provided as input.');
+ }
+ }
+ const yDims = outputSizes || (xDims.map((dim, i) => Math.floor(dim * scales[i])));
+ return [scales, yDims];
+};
+const parseScalesData = (scale, mode, isResize) => {
+ const scales = Array.from(scale.floatData);
+ (0, upsample_1.scalesValidation)(scales, mode, isResize);
+ return scales;
+};
+const parseScalesDataFromOutputSize = (yDims, xDims, mode, isResize) => {
+ const length = xDims.length;
+ const scales = new Array(length);
+ for (let i = 0, end = length; i < end; i++) {
+ if (xDims[i] === 0) {
+ if (yDims[i] !== 0) {
+ throw new Error('Input dim is zero but required output dim is non-zero.');
+ }
+ scales[i] = 1;
+ }
+ else {
+ scales[i] = yDims[i] / xDims[i];
+ }
+ }
+ (0, upsample_1.scalesValidation)(scales, mode, isResize);
+ return scales;
+};
+// roi data is not used yet. but leave here for future usage.
+// const getRoi = (inputs: Tensor[], attributes: UpsampleAttributes) : number[] => {
+// let roi: number[] = [];
+// if (attributes.needRoiInput) {
+// if (attributes.roiInputIdx <= 0) {
+// throw new Error('Invalid roi input index.');
+// }
+// const roiTensor = inputs[attributes.roiInputIdx];
+// roi = roiTensor.size > 0 ? Array.from(roiTensor.floatData) : [];
+// } else {
+// roi = new Array(inputs[0].dims.length * 2).fill(0);
+// }
+// return roi;
+// };
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/shape.ts":
+/*!************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/shape.ts ***!
+ \************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.shape = void 0;
+const tensor_1 = __webpack_require__(/*! ../../../tensor */ "./lib/onnxjs/tensor.ts");
+const shape = (inferenceHandler, inputs) => {
+ validateInputs(inputs);
+ return [new tensor_1.Tensor([inputs[0].dims.length], 'int32', undefined, undefined, new Int32Array(inputs[0].dims))];
+};
+exports.shape = shape;
+const validateInputs = (inputs) => {
+ if (!inputs || inputs.length !== 1) {
+ throw new Error('Shape requires 1 input.');
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/slice.ts":
+/*!************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/slice.ts ***!
+ \************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.sliceV10 = exports.parseSliceAttributes = exports.slice = void 0;
+const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
+const operators_1 = __webpack_require__(/*! ../../../operators */ "./lib/onnxjs/operators.ts");
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const sliceProgramMetadata = {
+ name: 'Slice',
+ inputNames: ['A'],
+ inputTypes: [types_1.TextureType.unpacked]
+};
+const slice = (inferenceHandler, inputs, attributes) => {
+ validateInputs(inputs);
+ const output = inferenceHandler.run(Object.assign(Object.assign({}, sliceProgramMetadata), { cacheHint: attributes.cacheKey, get: () => createSliceProgramInfo(inferenceHandler, inputs[0], attributes) }), inputs);
+ return [output];
+};
+exports.slice = slice;
+const parseSliceAttributes = (node) => {
+ const starts = node.attributes.getInts('starts');
+ const ends = node.attributes.getInts('ends');
+ const axes = node.attributes.getInts('axes', []);
+ return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ starts, ends, axes });
+};
+exports.parseSliceAttributes = parseSliceAttributes;
+const createSliceProgramInfo = (inferenceHandler, input, attributes) => {
+ const axes = (attributes.axes.length === 0) ? input.dims.slice(0).map((val, i) => i) : attributes.axes;
+ const normalizedAxes = util_1.ShapeUtil.normalizeAxes(axes, input.dims.length);
+ const starts = attributes.starts.map((start, i) => {
+ if (start > input.dims[normalizedAxes[i]] - 1) {
+ return input.dims[normalizedAxes[i]];
+ }
+ return util_1.ShapeUtil.normalizeAxis(start, input.dims[normalizedAxes[i]]);
+ });
+ const ends = attributes.ends.map((end, i) => {
+ if (end > input.dims[normalizedAxes[i]] - 1) {
+ return input.dims[normalizedAxes[i]];
+ }
+ return util_1.ShapeUtil.normalizeAxis(end, input.dims[normalizedAxes[i]]);
+ });
+ const outputShape = input.dims.slice();
+ const sliceOps = [];
+ for (let i = 0; i < normalizedAxes.length; i++) {
+ outputShape[normalizedAxes[i]] = ends[i] - starts[i];
+ if (starts[i] > 0) {
+ sliceOps.push(`outputIdx[${normalizedAxes[i]}] += ${starts[i]};`);
+ } // else { sliceOps.push(`outputIdx[${normalizedAxes[i]}] += 0;`); }
+ }
+ const rank = outputShape.length;
+ const shaderSource = `
+ float process(int outputIdx[${rank}]) {
+ ${sliceOps.join('\n ')}
+ return _A(outputIdx);
+ }`;
+ return Object.assign(Object.assign({}, sliceProgramMetadata), { output: { dims: outputShape, type: input.type, textureType: types_1.TextureType.unpacked }, shaderSource });
+};
+const validateInputs = (inputs) => {
+ if (!inputs || inputs.length !== 1) {
+ throw new Error('Slice requires 1 input.');
+ }
+ if (operators_1.NUMBER_TYPES.indexOf(inputs[0].type) === -1) {
+ throw new Error('Invalid input type.');
+ }
+};
+const sliceV10 = (inferenceHandler, inputs) => {
+ validateInputsV10(inputs);
+ const attributes = generateSliceAttributesFromInputs(inferenceHandler, inputs);
+ const output = inferenceHandler.run(Object.assign(Object.assign({}, sliceProgramMetadata), { cacheHint: attributes.cacheKey, get: () => createSliceProgramInfo(inferenceHandler, inputs[0], attributes) }), [inputs[0]]);
+ return [output];
+};
+exports.sliceV10 = sliceV10;
+const generateSliceAttributesFromInputs = (inferenceHandler, inputs) => {
+ if (!inferenceHandler.session.isInitializer(inputs[1].dataId) ||
+ !inferenceHandler.session.isInitializer(inputs[2].dataId) ||
+ (inputs.length >= 4 && !inferenceHandler.session.isInitializer(inputs[3].dataId)) ||
+ (inputs.length >= 5 && !inferenceHandler.session.isInitializer(inputs[4].dataId))) {
+ throw new Error('dynamic slice attributes are not allowed');
+ }
+ if (inputs.length >= 5 && inputs[4].integerData.some((i) => i !== 1)) {
+ throw new Error('currently non-1 steps is not supported for Slice');
+ }
+ const starts = Array.from(inputs[1].integerData);
+ const ends = Array.from(inputs[2].integerData);
+ const axes = inputs.length >= 4 ? Array.from(inputs[3].integerData) : [];
+ const cacheKey = `${axes};${starts};${ends}`;
+ return { starts, ends, axes, cacheKey };
+};
+const validateInputsV10 = (inputs) => {
+ if (!inputs || inputs.length < 3 || inputs.length > 5) {
+ throw new Error('Invalid input number.');
+ }
+ if (inputs[1].type !== 'int32' || inputs[1].dims.length !== 1) {
+ throw new Error('Invalid input type.');
+ }
+ if (inputs[2].type !== 'int32' || inputs[2].dims.length !== 1) {
+ throw new Error('Invalid input type.');
+ }
+ if (inputs.length >= 4 && (inputs[3].type !== 'int32' || inputs[3].dims.length !== 1)) {
+ throw new Error('Invalid input type.');
+ }
+ if (inputs.length >= 5 && (inputs[4].type !== 'int32' || inputs[4].dims.length !== 1)) {
+ throw new Error('Invalid input type.');
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/softmax.ts":
+/*!**************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/softmax.ts ***!
+ \**************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.softmaxV13 = exports.parseSoftmaxAttributesV13 = exports.parseSoftmaxAttributes = exports.softmax = void 0;
+const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const transpose_1 = __webpack_require__(/*! ./transpose */ "./lib/onnxjs/backends/webgl/ops/transpose.ts");
+const softmaxComputeMaxProgramMetadata = {
+ name: 'SoftmaxComputeMax',
+ inputNames: ['A'],
+ inputTypes: [types_1.TextureType.unpacked],
+};
+const softmaxComputeScaleProgramMetadata = {
+ name: 'SoftmaxComputeScale',
+ inputNames: ['A', 'Max'],
+ inputTypes: [types_1.TextureType.unpacked, types_1.TextureType.unpacked],
+};
+const softmaxProgramMetadata = {
+ name: 'SoftMax',
+ inputNames: ['A', 'Max', 'Norm'],
+ inputTypes: [types_1.TextureType.unpacked, types_1.TextureType.unpacked, types_1.TextureType.unpacked],
+};
+const softmax = (inferenceHandler, inputs, attributes) => {
+ validateInputs(inputs);
+ const inputShape = inputs[0].dims.slice();
+ const axis = util_1.ShapeUtil.normalizeAxis(attributes.axis, inputShape.length);
+ const logicalRowCount = util_1.ShapeUtil.sizeToDimension(inputShape, axis);
+ const featureCount = util_1.ShapeUtil.sizeFromDimension(inputShape, axis);
+ const output = computeSoftmax(inferenceHandler, inputs, attributes, logicalRowCount, featureCount);
+ return output;
+};
+exports.softmax = softmax;
+const parseSoftmaxAttributes = (node) => (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ axis: node.attributes.getInt('axis', 1) });
+exports.parseSoftmaxAttributes = parseSoftmaxAttributes;
+const parseSoftmaxAttributesV13 = (node) => (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ axis: node.attributes.getInt('axis', -1) });
+exports.parseSoftmaxAttributesV13 = parseSoftmaxAttributesV13;
+// The "semantic" meaning of axis has changed in opset-13.
+// Please compare: https://github.com/onnx/onnx/blob/main/docs/Operators.md#Softmax
+// with https://github.com/onnx/onnx/blob/main/docs/Changelog.md#Softmax-11 for detailed explanations
+// To account for the opset-13 behavior, our plan will be to transpose the "axis" dim to the innermost dim
+// and perform softmax and then reverse the transpose. We can skip the transposing aspect if the axis is already
+// the innermost dim
+const softmaxV13 = (inferenceHandler, inputs, attributes) => {
+ validateInputs(inputs);
+ const inputShape = inputs[0].dims.slice();
+ const axis = util_1.ShapeUtil.normalizeAxis(attributes.axis, inputShape.length);
+ const rank = inputShape.length;
+ const isTransposeRequired = (axis !== rank - 1) ? true : false;
+ const transposedInputShape = [];
+ let perm = [];
+ let transposedInputs = [];
+ let transposeAttribute;
+ if (isTransposeRequired) {
+ perm = Array.from({ length: rank }).map((_, i) => i);
+ // swap the innermost dim with the dim corresponding to axis
+ perm[axis] = rank - 1;
+ perm[rank - 1] = axis;
+ perm.map(p => transposedInputShape.push(inputShape[p]));
+ transposeAttribute = (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ perm });
+ transposedInputs = (0, transpose_1.transpose)(inferenceHandler, inputs, transposeAttribute);
+ }
+ const logicalRowCount = isTransposeRequired ? util_1.ShapeUtil.sizeToDimension(transposedInputShape, rank - 1) :
+ util_1.ShapeUtil.sizeToDimension(inputShape, rank - 1);
+ const featureCount = isTransposeRequired ? util_1.ShapeUtil.sizeFromDimension(transposedInputShape, rank - 1) :
+ util_1.ShapeUtil.sizeFromDimension(inputShape, rank - 1);
+ const output = computeSoftmax(inferenceHandler, isTransposeRequired ? transposedInputs : inputs, attributes, logicalRowCount, featureCount);
+ if (isTransposeRequired) {
+ const reversedOutput = (0, transpose_1.transpose)(inferenceHandler, output, transposeAttribute);
+ return reversedOutput;
+ }
+ else {
+ return output;
+ }
+};
+exports.softmaxV13 = softmaxV13;
+const computeSoftmax = (inferenceHandler, inputs, attributes, logicalRowCount, featureCount) => {
+ const computeMaxProgramInfo = createComputeMaxProgramInfo(inferenceHandler, inputs[0], logicalRowCount, featureCount, [logicalRowCount]);
+ const max = inferenceHandler.run(Object.assign(Object.assign({}, softmaxComputeMaxProgramMetadata), { cacheHint: attributes.cacheKey, get: () => computeMaxProgramInfo }), inputs);
+ const computeScaleProgramInfo = createComputScaleProgramInfo(inferenceHandler, inputs[0], logicalRowCount, featureCount, computeMaxProgramInfo.output.dims, [logicalRowCount]);
+ const scale = inferenceHandler.run(Object.assign(Object.assign({}, softmaxComputeScaleProgramMetadata), { cacheHint: attributes.cacheKey, get: () => computeScaleProgramInfo }), [inputs[0], max]);
+ const softMaxProgramInfo = createSoftMaxProgramInfo(inferenceHandler, inputs[0], logicalRowCount, featureCount, computeMaxProgramInfo.output.dims, computeScaleProgramInfo.output.dims);
+ const output = inferenceHandler.run(Object.assign(Object.assign({}, softmaxProgramMetadata), { cacheHint: attributes.cacheKey, get: () => softMaxProgramInfo }), [inputs[0], max, scale]);
+ return [output];
+};
+/**
+ * Create a texture that contains the maximum value of each of the 'N' rows
+ */
+const createComputeMaxProgramInfo = (inferenceHandler, input, logicalRowCount, featureCount, outputShape) => {
+ const [textureWidth, textureHeight] = inferenceHandler.calculateTextureWidthAndHeight(input.dims, types_1.TextureType.unpacked);
+ const rank = outputShape.length;
+ if (logicalRowCount < 1 || featureCount < 1) {
+ throw new Error('Logical row count N and feature count D must be greater than or equal to 1');
+ }
+ if (outputShape.length !== 1) {
+ throw new Error('Dimensionality of the output should be 1');
+ }
+ if (outputShape[0] !== logicalRowCount) {
+ throw new Error('Shape of the output should be equal to logical row count');
+ }
+ const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
+ const shaderSource = `
+ float process(int[${rank}] indices) {
+ int logical_row_start_offset = indices[0] * ${featureCount};
+
+ float max = getColorAsFloat(${glsl.texture2D}(A, offsetToCoords(logical_row_start_offset, ${textureWidth},
+ ${textureHeight} )));
+ for(int i=1; i<${featureCount}; ++i)
+ {
+ float current = getColorAsFloat(${glsl.texture2D}(A, offsetToCoords(logical_row_start_offset + i,
+ ${textureWidth}, ${textureHeight})));
+ if(current > max)
+ max = current;
+ }
+
+ return max;
+ }`;
+ return Object.assign(Object.assign({}, softmaxComputeMaxProgramMetadata), { output: { dims: outputShape, type: input.type, textureType: types_1.TextureType.unpacked }, shaderSource });
+};
+/**
+ * Create a texture that contains the normalization factor for each of the 'N' rows
+ */
+const createComputScaleProgramInfo = (inferenceHandler, input, logicalRowCount, featureCount, maxElementPerLogicalRow, outputShape) => {
+ const [textureWidth, textureHeight] = inferenceHandler.calculateTextureWidthAndHeight(input.dims, types_1.TextureType.unpacked);
+ const rank = outputShape.length;
+ if (logicalRowCount < 1 || featureCount < 1) {
+ throw new Error('Logical row count N and feature count D must be greater than or equal to 1');
+ }
+ if (outputShape.length !== 1) {
+ throw new Error('Dimensionality of the output should be 1');
+ }
+ if (outputShape[0] !== logicalRowCount) {
+ throw new Error('Shape of the output should be equal to logical row count');
+ }
+ if (maxElementPerLogicalRow.length !== 1) {
+ throw new Error('Dimensionality of the intermediate results should be 1');
+ }
+ if (maxElementPerLogicalRow[0] !== logicalRowCount) {
+ throw new Error('Shape of the intermediate results should be equal to logical row count');
+ }
+ const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
+ const shaderSource = `
+ float process(int[${rank}] indices) {
+ int logical_row_start_offset = indices[0] * ${featureCount};
+
+ float norm_factor = 0.0;
+ float max = _Max(indices);
+ for(int i=0; i<${featureCount}; ++i)
+ {
+ norm_factor += exp(getColorAsFloat(${glsl.texture2D}(A, offsetToCoords(logical_row_start_offset + i,
+ ${textureWidth}, ${textureHeight}))) - max);
+ }
+
+ return norm_factor;
+ }`;
+ return Object.assign(Object.assign({}, softmaxComputeScaleProgramMetadata), { output: { dims: outputShape, type: input.type, textureType: types_1.TextureType.unpacked }, shaderSource });
+};
+const createSoftMaxProgramInfo = (inferenceHandler, input, logicalRowCount, featureCount, maxElementPerLogicalRow, normalizationPerLogicalRow) => {
+ const [textureWidth, textureHeight] = inferenceHandler.calculateTextureWidthAndHeight(input.dims, types_1.TextureType.unpacked);
+ const rank = input.dims.length;
+ if (logicalRowCount < 1 || featureCount < 1) {
+ throw new Error('Logical row count N and feature count D must be greater than or equal to 1');
+ }
+ if (maxElementPerLogicalRow.length !== 1 || normalizationPerLogicalRow.length !== 1) {
+ throw new Error('Dimensionality of the intermediate results should be 1');
+ }
+ if (maxElementPerLogicalRow[0] !== logicalRowCount || normalizationPerLogicalRow[0] !== logicalRowCount) {
+ throw new Error('Shape of the intermediate results should be equal to logical row count');
+ }
+ const shaderSource = `
+ float process(int[${rank}] indices) {
+
+ // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords)
+ int offset = coordsToOffset(TexCoords, ${textureWidth}, ${textureHeight});
+
+ //determine the logical row for this index
+ int logical_row_index[1];
+ logical_row_index[0] = offset / ${featureCount};
+
+ float norm_factor = _Norm(logical_row_index);
+
+ // avoid possible division by 0
+ // if norm_facor is 0, all elements are zero
+ // if so, return 0
+ if(norm_factor == 0.0)
+ return 0.0;
+
+ return exp(_A(indices) - _Max(logical_row_index)) / norm_factor;
+ }`;
+ return Object.assign(Object.assign({}, softmaxProgramMetadata), { output: { dims: input.dims, type: input.type, textureType: types_1.TextureType.unpacked }, shaderSource });
+};
+const validateInputs = (inputs) => {
+ if (!inputs || inputs.length !== 1) {
+ throw new Error('Softmax requires 1 input.');
+ }
+ if (inputs[0].type !== 'float32' && inputs[0].type !== 'float64') {
+ throw new Error('Invalid input type');
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/split.ts":
+/*!************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/split.ts ***!
+ \************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseSplitAttributes = exports.split = void 0;
+const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const splitProgramMetadata = {
+ name: 'Split',
+ inputNames: ['A'],
+ inputTypes: [types_1.TextureType.unpacked],
+};
+const split = (inferenceHandler, inputs, attributes) => {
+ validateInputs(inputs);
+ const axis = util_1.ShapeUtil.normalizeAxis(attributes.axis, inputs[0].dims.length);
+ const count = getProgramCount(inferenceHandler, inputs, axis, attributes);
+ const output = [];
+ for (let i = 0; i < count; ++i) {
+ output.push(inferenceHandler.run(Object.assign(Object.assign({}, splitProgramMetadata), { cacheHint: `${attributes.cacheKey};${i}`, get: () => createSplitProgramInfo(inferenceHandler, inputs[0], attributes, axis, i) }), inputs));
+ }
+ return output;
+};
+exports.split = split;
+const parseSplitAttributes = (node) => {
+ const axis = node.attributes.getInt('axis', 0);
+ const split = node.attributes.getInts('split', []);
+ const numOutputs = node.outputs.length;
+ return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ axis, split, numOutputs });
+};
+exports.parseSplitAttributes = parseSplitAttributes;
+const getProgramCount = (inferenceHandler, inputs, axis, attributes) => {
+ const [, offsets] = util_1.SplitUtil.splitShape(inputs[0].dims, axis, attributes.split, attributes.numOutputs);
+ return offsets.length;
+};
+const createSplitProgramInfo = (inferenceHandler, input, attributes, axis, index) => {
+ const [shapes, offsets] = util_1.SplitUtil.splitShape(input.dims, axis, attributes.split, attributes.numOutputs);
+ const offset = offsets[index];
+ const outputShape = shapes[index];
+ const rank = outputShape.length;
+ const shaderSource = `
+ float process(int indices[${rank}]) {
+ indices[${axis}] += ${offset};
+ return _A(indices);
+ }
+ `;
+ return Object.assign(Object.assign({}, splitProgramMetadata), { cacheHint: `${attributes.cacheKey}:${index}`, output: { dims: outputShape, type: input.type, textureType: types_1.TextureType.unpacked }, shaderSource });
+};
+const validateInputs = (inputs) => {
+ if (!inputs || inputs.length !== 1) {
+ throw new Error('Split requires one input.');
+ }
+ if (inputs[0].type !== 'int8' && inputs[0].type !== 'uint8' && inputs[0].type !== 'int16' &&
+ inputs[0].type !== 'uint16' && inputs[0].type !== 'int32' && inputs[0].type !== 'uint32' &&
+ inputs[0].type !== 'float32' && inputs[0].type !== 'float64' && inputs[0].type !== 'bool') {
+ throw new Error('Invalid input type.');
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/squeeze.ts":
+/*!**************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/squeeze.ts ***!
+ \**************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseSqueezeAttributes = exports.squeezeV13 = exports.squeeze = void 0;
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const squeeze = (inferenceHandler, inputs, axes) => {
+ validateInputs(inputs);
+ const outputShape = util_1.ShapeUtil.squeezeShape(inputs[0].dims, axes);
+ const output = inferenceHandler.reshapeUnpacked(inputs[0], outputShape);
+ return [output];
+};
+exports.squeeze = squeeze;
+const squeezeV13 = (inferenceHandler, inputs) => {
+ validateInputsV13(inputs);
+ return (0, exports.squeeze)(inferenceHandler, [inputs[0]], Array.from(inputs[1].integerData));
+};
+exports.squeezeV13 = squeezeV13;
+const parseSqueezeAttributes = (node) => node.attributes.getInts('axes');
+exports.parseSqueezeAttributes = parseSqueezeAttributes;
+const validateInputs = (inputs) => {
+ if (!inputs || inputs.length !== 1) {
+ throw new Error('Squeeze requires 1 input.');
+ }
+ if (inputs[0].type === 'string') {
+ throw new Error('invalid input tensor types.');
+ }
+};
+const validateInputsV13 = (inputs) => {
+ if (!inputs || inputs.length !== 2) {
+ throw new Error('Squeeze requires 2 inputs.');
+ }
+ if (inputs[1].type !== 'int32') {
+ throw new Error('Invalid input type.');
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/sum.ts":
+/*!**********************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/sum.ts ***!
+ \**********************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.sum = void 0;
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const sum = (inferenceHandler, inputs) => {
+ validateInputs(inputs);
+ const sumProgramMetadata = {
+ name: 'Sum',
+ inputNames: inputs.map((v, i) => `X${i}`),
+ inputTypes: new Array(inputs.length).fill(types_1.TextureType.unpacked)
+ };
+ const output = inferenceHandler.run(Object.assign(Object.assign({}, sumProgramMetadata), { get: () => createSumProgramInfo(inferenceHandler, inputs, sumProgramMetadata) }), inputs);
+ return [output];
+};
+exports.sum = sum;
+const createSumProgramInfo = (inferenceHandler, inputs, sumProgramMetadata) => {
+ const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
+ const outputShape = inputs[0].dims.slice();
+ const sumLine = inputs.map((v, i) => `${glsl.texture2D}(X${i},TexCoords)`).join(' + ');
+ const shaderSource = `
+ void main() {
+ vec4 result = ${sumLine};
+ ${glsl.output} = result;
+ }
+ `;
+ return Object.assign(Object.assign({}, sumProgramMetadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, hasMain: true, shaderSource });
+};
+const validateInputs = (inputs) => {
+ if (!inputs || inputs.length === 0) {
+ throw new Error('Sum requires inputs.');
+ }
+ const length = inputs[0].dims.length;
+ for (let i = 1; i < inputs.length; i++) {
+ if (length !== inputs[i].dims.length) {
+ throw new Error('Input shapes are mismatched.');
+ }
+ for (let j = 0; j < length; j++) {
+ if (inputs[0].dims[j] !== inputs[i].dims[j]) {
+ throw new Error('Input shapes are not matched.');
+ }
+ }
+ }
+ if (inputs[0].type !== 'float32' && inputs[0].type !== 'float64') {
+ throw new Error('Invalid input type.');
+ }
+ for (let i = 1; i < inputs.length; i++) {
+ if (inputs[0].type !== inputs[i].type) {
+ throw new Error('Input types are not matched.');
+ }
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/tile.ts":
+/*!***********************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/tile.ts ***!
+ \***********************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.tile = void 0;
+const operators_1 = __webpack_require__(/*! ../../../operators */ "./lib/onnxjs/operators.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const tile = (inferenceHandler, inputs) => {
+ validateInputs(inputs);
+ const tileProgramMetadata = {
+ name: 'Tile',
+ inputNames: ['A'],
+ inputTypes: [types_1.TextureType.unpacked],
+ };
+ const output = inferenceHandler.run(Object.assign(Object.assign({}, tileProgramMetadata), { get: () => createTileProgramInfo(inferenceHandler, inputs, tileProgramMetadata) }), inputs);
+ return [output];
+};
+exports.tile = tile;
+const createTileProgramInfo = (handler, inputs, tileProgramMetadata) => {
+ const inputShape = inputs[0].dims.slice();
+ const outputShape = new Array(inputShape.length);
+ const tileOps = [];
+ for (let i = 0; i < inputShape.length; i++) {
+ outputShape[i] = inputShape[i] * inputs[1].numberData[i];
+ tileOps.push(`inputIdx[${i}] = int(mod(float(outputIdx[${i}]), ${inputShape[i]}.));`);
+ }
+ const rank = outputShape.length;
+ const shaderSource = `
+ float process(int outputIdx[${rank}]) {
+ int inputIdx[${rank}];
+ ${tileOps.join('\n')}
+ return _A(inputIdx);
+ }
+ `;
+ return Object.assign(Object.assign({}, tileProgramMetadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource });
+};
+const validateInputs = (inputs) => {
+ if (!inputs || inputs.length !== 2) {
+ throw new Error('Tile requires 2 input.');
+ }
+ if (inputs[1].dims.length !== 1) {
+ throw new Error('The second input shape must 1 dimension.');
+ }
+ if (inputs[1].dims[0] !== inputs[0].dims.length) {
+ throw new Error('Invalid input shape.');
+ }
+ if (operators_1.NUMBER_TYPES.indexOf(inputs[0].type) === -1) {
+ throw new Error('Invalid input type.');
+ }
+ if (inputs[1].type !== 'int32' && inputs[1].type !== 'int16') {
+ throw new Error('Invalid repeat type.');
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/transpose.ts":
+/*!****************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/transpose.ts ***!
+ \****************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseTransposeAttributes = exports.transpose = void 0;
+const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const transposeProgramMetadata = {
+ name: 'Transpose',
+ inputNames: ['A'],
+ inputTypes: [types_1.TextureType.unpacked]
+};
+const transpose = (inferenceHandler, inputs, attributes) => {
+ validateInputs(inputs);
+ const output = inferenceHandler.run(Object.assign(Object.assign({}, transposeProgramMetadata), { cacheHint: attributes.cacheKey, get: () => createTransposeProgramInfo(inferenceHandler, inputs[0], attributes.perm) }), inputs);
+ return [output];
+};
+exports.transpose = transpose;
+const parseTransposeAttributes = (node) => (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ perm: node.attributes.getInts('perm', []) });
+exports.parseTransposeAttributes = parseTransposeAttributes;
+const createTransposeProgramInfo = (inferenceHandler, input, perm) => {
+ const inputShape = input.dims;
+ perm = getAdjustedPerm(inputShape, perm);
+ const unpackedOutputShape = getOutputShape(inputShape, perm);
+ const rank = inputShape.length;
+ // A dims=[${inputs[0].dims.toString()}]
+ // out Dims=[${unpackedOutputShape.toString()}]
+ // based on perm=[${perm.toString()}]
+ const shaderSource = `
+ ${getPermFunctionBody('perm', perm, rank)}
+ float process(int indices[${rank}]) {
+ int a[${rank}];
+ perm(a, indices);
+ return _A(a);
+ }`;
+ return Object.assign(Object.assign({}, transposeProgramMetadata), { output: { dims: unpackedOutputShape, type: input.type, textureType: types_1.TextureType.unpacked }, shaderSource });
+};
+const getAdjustedPerm = (inputShape, perm) => {
+ if (perm && perm.length !== inputShape.length) {
+ perm = [...(inputShape.keys())].reverse();
+ }
+ return perm;
+};
+const getOutputShape = (inputShape, perm) => {
+ perm = getAdjustedPerm(inputShape, perm);
+ return util_1.ShapeUtil.sortBasedOnPerm(inputShape, perm);
+};
+const getPermFunctionBody = (name, perm, rank) => {
+ const reverseFunc = [];
+ reverseFunc.push(`void ${name}(out int a[${rank}], int src[${rank}]) {`);
+ for (let i = 0; i < rank; ++i) {
+ reverseFunc.push(`\ta[${perm[i]}]=src[${i}];`);
+ }
+ reverseFunc.push('\t}');
+ return reverseFunc.join('\n');
+};
+const validateInputs = (inputs) => {
+ if (!inputs || inputs.length !== 1) {
+ throw new Error('Transpose requires 1 input.');
+ }
+ if (inputs[0].type !== 'float32' && inputs[0].type !== 'float64') {
+ throw new Error('input should be float tensor');
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/uint8-encode.ts":
+/*!*******************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/uint8-encode.ts ***!
+ \*******************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.encodeAsUint8 = void 0;
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const encodeAsUint8 = (inferenceHandler, input) => {
+ const outputShape = input.shape;
+ const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
+ /**
+ * https://github.com/tensorflow/tfjs-core/blob/master/src/kernels/webgl/encode_float_gpu.ts
+ */
+ const shaderSource = `
+ const float FLOAT_MAX = 1.70141184e38;
+ const float FLOAT_MIN = 1.17549435e-38;
+
+ bool isNaN(float val) {
+ return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true;
+ }
+
+ highp vec4 encodeAsUint8(highp float v) {
+ if (isNaN(v)) {
+ return vec4(255, 255, 255, 255);
+ }
+
+ highp float av = abs(v);
+
+ if(av < FLOAT_MIN) {
+ return vec4(0.0, 0.0, 0.0, 0.0);
+ } else if(v > FLOAT_MAX) {
+ return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
+ } else if(v < -FLOAT_MAX) {
+ return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
+ }
+
+ highp vec4 c = vec4(0,0,0,0);
+
+ highp float e = floor(log2(av));
+ highp float m = exp2(fract(log2(av))) - 1.0;
+
+ c[2] = floor(128.0 * m);
+ m -= c[2] / 128.0;
+ c[1] = floor(32768.0 * m);
+ m -= c[1] / 32768.0;
+ c[0] = floor(8388608.0 * m);
+
+ highp float ebias = e + 127.0;
+ c[3] = floor(ebias / 2.0);
+ ebias -= c[3] * 2.0;
+ c[2] += floor(ebias) * 128.0;
+
+ c[3] += 128.0 * step(0.0, -v);
+
+ return c / 255.0;
+ }
+
+ void main() {
+ float value = ${glsl.texture2D}(X,TexCoords).r;
+ ${glsl.output} = encodeAsUint8(value);
+ }`;
+ const programInfo = {
+ name: 'Uint8Encode',
+ inputTypes: [types_1.TextureType.unpacked],
+ inputNames: ['X'],
+ output: { dims: outputShape, type: input.tensor.type, textureType: types_1.TextureType.downloadUint8AsFloat },
+ shaderSource,
+ hasMain: true
+ };
+ return inferenceHandler.executeProgram(programInfo, [input.tensor]);
+};
+exports.encodeAsUint8 = encodeAsUint8;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/unary-op.ts":
+/*!***************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/unary-op.ts ***!
+ \***************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.tanh = exports.tan = exports.sqrt = exports.sin = exports.sigmoid = exports.relu = exports.not = exports.neg = exports.log = exports.parseLeakyReluAttributes = exports.leakyRelu = exports.identity = exports.floor = exports.exp = exports.parseEluAttributes = exports.elu = exports.cos = exports.ceil = exports.clipV11 = exports.parseClipAttributes = exports.clip = exports.atan = exports.asin = exports.acos = exports.abs = exports.glslTanh = exports.glslTan = exports.glslSqrt = exports.glslSigmoid = exports.glslRelu = exports.glslSin = exports.glslNot = exports.glslNeg = exports.glslLog = exports.glslLeakyRelu = exports.glslIdentity = exports.glslClip = exports.glslFloor = exports.glslExp = exports.glslElu = exports.glslCos = exports.glslCeil = exports.glslAtan = exports.glslAsin = exports.glslAcos = exports.glslAbs = void 0;
+const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const glsl_definitions_1 = __webpack_require__(/*! ../glsl-definitions */ "./lib/onnxjs/backends/webgl/glsl-definitions.ts");
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+function glslAbs() {
+ return glslBuiltinUnary('abs');
+}
+exports.glslAbs = glslAbs;
+function glslAcos() {
+ return glslBuiltinUnary('acos');
+}
+exports.glslAcos = glslAcos;
+function glslAsin() {
+ return glslBuiltinUnary('asin');
+}
+exports.glslAsin = glslAsin;
+function glslAtan() {
+ return glslBuiltinUnary('atan');
+}
+exports.glslAtan = glslAtan;
+function glslCeil() {
+ return glslBuiltinUnary('ceil');
+}
+exports.glslCeil = glslCeil;
+function glslCos() {
+ return glslBuiltinUnary('cos');
+}
+exports.glslCos = glslCos;
+function glslElu(alpha) {
+ const name = 'elu';
+ const body = `
+ const float alpha = float(${alpha});
+
+ float ${name}_(float a) {
+ return a >= 0.0 ? a: (exp(a) - 1.0) * alpha;
+ }
+ vec4 ${name}_(vec4 v) {
+ return vec4(${name}_(v.x), ${name}_(v.y), ${name}_(v.z), ${name}_(v.w));
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslElu = glslElu;
+function glslExp() {
+ return glslBuiltinUnary('exp');
+}
+exports.glslExp = glslExp;
+function glslFloor() {
+ return glslBuiltinUnary('floor');
+}
+exports.glslFloor = glslFloor;
+function glslClip(min, max) {
+ const name = 'clip';
+ const body = `
+ const float min = float(${min});
+ const float max = float(${max});
+
+ float ${name}_(float a) {
+ return clamp(a, min, max);
+ }
+ vec4 ${name}_(vec4 v) {
+ return clamp(v, min, max);
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslClip = glslClip;
+function glslIdentity() {
+ const name = 'indentity';
+ const body = `
+ float ${name}_(float a) {
+ return a;
+ }
+ vec4 ${name}_(vec4 v) {
+ return v;
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslIdentity = glslIdentity;
+function glslLeakyRelu(alpha) {
+ const name = 'leakyRelu';
+ const body = `
+ const float alpha = float(${alpha});
+
+ float ${name}_(float a) {
+ return a < 0.0 ? a * alpha : a;
+ }
+ vec4 ${name}_(vec4 v) {
+ return vec4(${name}_(v.x), ${name}_(v.y), ${name}_(v.z), ${name}_(v.w));
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslLeakyRelu = glslLeakyRelu;
+function glslLog() {
+ return glslBuiltinUnary('log');
+}
+exports.glslLog = glslLog;
+function glslNeg() {
+ const name = 'neg';
+ const body = `
+ float ${name}_(float a) {
+ return -a;
+ }
+ vec4 ${name}_(vec4 v) {
+ return -v;
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslNeg = glslNeg;
+function glslNot() {
+ const name = 'not';
+ const body = `
+ float ${name}_(float a) {
+ return float( ! bool(a) );
+ }
+ bool ${name}_(bool a) {
+ return !a;
+ }
+ vec4 ${name}_(vec4 v) {
+ return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w));
+ }
+ bvec4 ${name}_(bvec4 v) {
+ return bvec4(!v.x, !v.y, !v.z, !v.w);
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslNot = glslNot;
+function glslSin() {
+ return glslBuiltinUnary('sin');
+}
+exports.glslSin = glslSin;
+function glslRelu() {
+ const name = 'relu';
+ const body = `
+ float ${name}_(float a) {
+ return max( a, 0.0 );
+ }
+ vec4 ${name}_(vec4 v) {
+ return max( v, 0.0 );
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslRelu = glslRelu;
+function glslSigmoid() {
+ const name = 'sigmoid';
+ const body = `
+ float ${name}_(float a) {
+ return 1.0 / (1.0 + exp(-a));
+ }
+ vec4 ${name}_(vec4 v) {
+ return 1.0 / (1.0 + exp(-v));
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslSigmoid = glslSigmoid;
+function glslSqrt() {
+ return glslBuiltinUnary('sqrt');
+}
+exports.glslSqrt = glslSqrt;
+function glslTan() {
+ return glslBuiltinUnary('tan');
+}
+exports.glslTan = glslTan;
+function glslTanh() {
+ const name = 'tanh';
+ const body = `
+ float ${name}_(float a) {
+ a = clamp(a, -10., 10.);
+ a = exp(2.*a);
+ return (a - 1.) / (a + 1.);
+ }
+ vec4 ${name}_(vec4 v) {
+ v = clamp(v, -10., 10.);
+ v = exp(2.*v);
+ return (v - 1.) / (v + 1.);
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+exports.glslTanh = glslTanh;
+function glslBuiltinUnary(name) {
+ const body = `
+ float ${name}_(float a) {
+ return ${name}(a);
+ }
+ vec4 ${name}_(vec4 v) {
+ return ${name}(v);
+ }
+ `;
+ return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
+}
+/////
+/////
+/////
+const createElementwiseProgramInfo = (handler, metadata, input, glslFunc) => {
+ const textureType = handler.session.pack ? types_1.TextureType.packed : types_1.TextureType.unpacked;
+ const glsl = (0, glsl_source_1.getGlsl)(handler.session.backend.glContext.version);
+ return Object.assign(Object.assign({}, metadata), { output: { dims: input.dims, type: input.type, textureType }, shaderSource: `
+ ${glslFunc.body}
+ void main() {
+ vec4 v = ${glsl.texture2D}(A, TexCoords);
+ v = ${glslFunc.name}_(v);
+ ${glsl.output} = v;
+ }
+ `, hasMain: true });
+};
+const createElementwiseProgramInfoLoader = (handler, input, glslFunc, cacheKey) => {
+ const textureType = handler.session.pack ? types_1.TextureType.packed : types_1.TextureType.unpacked;
+ const metadata = { name: glslFunc.name, inputTypes: [textureType], inputNames: ['A'], cacheHint: cacheKey };
+ return Object.assign(Object.assign({}, metadata), { get: () => createElementwiseProgramInfo(handler, metadata, input, glslFunc) });
+};
+const abs = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslAbs()), inputs)];
+exports.abs = abs;
+const acos = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslAcos()), inputs)];
+exports.acos = acos;
+const asin = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslAsin()), inputs)];
+exports.asin = asin;
+const atan = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslAtan()), inputs)];
+exports.atan = atan;
+const clip = (handler, inputs, attributes) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslClip(attributes.min, attributes.max), attributes.cacheKey), inputs)];
+exports.clip = clip;
+const parseClipAttributes = (node) => (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ min: node.attributes.getFloat('min', util_1.MIN_CLIP), max: node.attributes.getFloat('max', util_1.MAX_CLIP) });
+exports.parseClipAttributes = parseClipAttributes;
+const clipV11 = (handler, inputs) => {
+ const attributes = generateClipAttributesFromInputs(handler, inputs);
+ return (0, exports.clip)(handler, [inputs[0]], attributes);
+};
+exports.clipV11 = clipV11;
+const generateClipAttributesFromInputs = (handler, inputs) => {
+ if (inputs.length >= 3 &&
+ (!handler.session.isInitializer(inputs[1].dataId) || !handler.session.isInitializer(inputs[2].dataId))) {
+ throw new Error('dynamic clip attributes are not allowed');
+ }
+ const min = (inputs.length >= 3) ? inputs[1].numberData[0] : util_1.MIN_CLIP;
+ const max = (inputs.length >= 3) ? inputs[2].numberData[0] : util_1.MAX_CLIP;
+ return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ min, max });
+};
+const ceil = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslCeil()), inputs)];
+exports.ceil = ceil;
+const cos = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslCos()), inputs)];
+exports.cos = cos;
+const elu = (handler, inputs, attributes) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslElu(attributes.alpha), attributes.cacheKey), inputs)];
+exports.elu = elu;
+const parseEluAttributes = (node) => (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ alpha: node.attributes.getFloat('alpha', 1.0) });
+exports.parseEluAttributes = parseEluAttributes;
+const exp = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslExp()), inputs)];
+exports.exp = exp;
+const floor = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslFloor()), inputs)];
+exports.floor = floor;
+const identity = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslIdentity()), inputs)];
+exports.identity = identity;
+const leakyRelu = (handler, inputs, attributes) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslLeakyRelu(attributes.alpha), attributes.cacheKey), inputs)];
+exports.leakyRelu = leakyRelu;
+const parseLeakyReluAttributes = (node) => (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ alpha: node.attributes.getFloat('alpha', 0.01) });
+exports.parseLeakyReluAttributes = parseLeakyReluAttributes;
+const log = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslLog()), inputs)];
+exports.log = log;
+const neg = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslNeg()), inputs)];
+exports.neg = neg;
+const not = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslNot()), inputs)];
+exports.not = not;
+const relu = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslRelu()), inputs)];
+exports.relu = relu;
+const sigmoid = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslSigmoid()), inputs)];
+exports.sigmoid = sigmoid;
+const sin = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslSin()), inputs)];
+exports.sin = sin;
+const sqrt = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslSqrt()), inputs)];
+exports.sqrt = sqrt;
+const tan = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslTan()), inputs)];
+exports.tan = tan;
+const tanh = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslTanh()), inputs)];
+exports.tanh = tanh;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/unpack.ts":
+/*!*************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/unpack.ts ***!
+ \*************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createUnpackProgramInfoLoader = exports.createUnpackProgramInfo = void 0;
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const utils_1 = __webpack_require__(/*! ../utils */ "./lib/onnxjs/backends/webgl/utils.ts");
+const packing_utils_1 = __webpack_require__(/*! ./packing-utils */ "./lib/onnxjs/backends/webgl/ops/packing-utils.ts");
+const unpackProgramMetadata = {
+ name: 'unpack',
+ inputNames: ['A'],
+ inputTypes: [types_1.TextureType.packed]
+};
+const createUnpackProgramInfo = (handler, input) => {
+ const rank = input.dims.length;
+ const channels = (0, packing_utils_1.getChannels)('rc', rank);
+ const innerDims = channels.slice(-2);
+ const coordsDataType = (0, utils_1.getCoordsDataType)(rank);
+ const unpackChannel = (0, packing_utils_1.unpackFromChannel)();
+ const isScalar = (input.dims.length === 0);
+ const sourceCoords = isScalar ? '' : getSourceCoords(rank, channels);
+ const coords = rank <= 1 ? 'rc' : `vec2(${innerDims.join(',')})`;
+ const glsl = (0, glsl_source_1.getGlsl)(handler.session.backend.glContext.version);
+ const shaderSource = `
+ ${unpackChannel}
+ void main() {
+ ${coordsDataType} rc = getOutputCoords();
+
+ // Sample the texture with the coords to get the rgba channel value.
+ vec4 packedInput = getA(${sourceCoords});
+
+ ${glsl.output} = vec4(getChannel(packedInput, ${coords}), 0, 0, 0);
+ }
+ `;
+ return Object.assign(Object.assign({}, unpackProgramMetadata), { hasMain: true, output: { dims: input.dims, type: input.type, textureType: types_1.TextureType.unpacked }, shaderSource });
+};
+exports.createUnpackProgramInfo = createUnpackProgramInfo;
+const createUnpackProgramInfoLoader = (handler, input) => (Object.assign(Object.assign({}, unpackProgramMetadata), { get: () => (0, exports.createUnpackProgramInfo)(handler, input) }));
+exports.createUnpackProgramInfoLoader = createUnpackProgramInfoLoader;
+function getSourceCoords(rank, dims) {
+ if (rank === 1) {
+ return 'rc';
+ }
+ let coords = '';
+ for (let i = 0; i < rank; i++) {
+ coords += dims[i];
+ if (i < rank - 1) {
+ coords += ',';
+ }
+ }
+ return coords;
+}
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/unsqueeze.ts":
+/*!****************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/unsqueeze.ts ***!
+ \****************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseUnsqueezeAttributes = exports.unsqueezeV13 = exports.unsqueeze = void 0;
+const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
+const unsqueeze = (inferenceHandler, inputs, axes) => {
+ validateInputs(inputs);
+ const outputShape = util_1.ShapeUtil.unsqueezeShape(inputs[0].dims, axes);
+ const output = inferenceHandler.reshapeUnpacked(inputs[0], outputShape);
+ return [output];
+};
+exports.unsqueeze = unsqueeze;
+const unsqueezeV13 = (inferenceHandler, inputs) => {
+ validateInputsV13(inputs);
+ return (0, exports.unsqueeze)(inferenceHandler, [inputs[0]], Array.from(inputs[1].integerData));
+};
+exports.unsqueezeV13 = unsqueezeV13;
+const parseUnsqueezeAttributes = (node) => node.attributes.getInts('axes');
+exports.parseUnsqueezeAttributes = parseUnsqueezeAttributes;
+const validateInputs = (inputs) => {
+ if (!inputs || inputs.length !== 1) {
+ throw new Error('Unsqueeze requires 1 input.');
+ }
+ if (inputs[0].type === 'string') {
+ throw new Error('invalid input tensor types.');
+ }
+};
+const validateInputsV13 = (inputs) => {
+ if (!inputs || inputs.length !== 2) {
+ throw new Error('Unsqueeze requires 2 inputs.');
+ }
+ if (inputs[1].type !== 'int32') {
+ throw new Error('Invalid input type.');
+ }
+};
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/ops/upsample.ts":
+/*!***************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/ops/upsample.ts ***!
+ \***************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.scalesValidation = exports.validateInputs = exports.parseUpsampleAttributes = exports.parseUpsampleAttributesV9 = exports.parseUpsampleAttributesV7 = exports.upsample = void 0;
+const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
+const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
+const upsampleProgramMetadata = {
+ name: 'Upsample',
+ inputNames: ['X'],
+ inputTypes: [types_1.TextureType.unpacked],
+};
+const upsample = (inferenceHandler, inputs, attributes) => {
+ (0, exports.validateInputs)(inputs, attributes);
+ const output = inferenceHandler.run(Object.assign(Object.assign({}, upsampleProgramMetadata), { cacheHint: attributes.cacheKey, get: () => createUpsampleProgramInfo(inferenceHandler, inputs, attributes) }), inputs);
+ return [output];
+};
+exports.upsample = upsample;
+const parseUpsampleAttributesV7 = (node) => (0, exports.parseUpsampleAttributes)(node, 7);
+exports.parseUpsampleAttributesV7 = parseUpsampleAttributesV7;
+const parseUpsampleAttributesV9 = (node) => (0, exports.parseUpsampleAttributes)(node, 9);
+exports.parseUpsampleAttributesV9 = parseUpsampleAttributesV9;
+const parseUpsampleAttributes = (node, opset) => {
+ const isResize = (opset >= 10);
+ // processing node attributes
+ const mode = node.attributes.getString('mode', 'nearest');
+ if (mode !== 'nearest' && mode !== 'linear' && (opset < 11 || mode !== 'cubic')) {
+ throw new Error(`unrecognized mode: ${mode}`);
+ }
+ let scales = [];
+ if (opset < 9) {
+ scales = node.attributes.getFloats('scales');
+ (0, exports.scalesValidation)(scales, mode, isResize);
+ }
+ const extrapolationValue = node.attributes.getFloat('extrapolation_value', 0.0);
+ const coordinateTransformMode = opset > 10 ? node.attributes.getString('coordinate_transformation_mode', 'half_pixel') : 'asymmetric';
+ if ([
+ 'asymmetric', 'pytorch_half_pixel', 'tf_half_pixel_for_nn', 'align_corners', 'tf_crop_and_resize', 'half_pixel'
+ ].indexOf(coordinateTransformMode) === -1) {
+ throw new Error(`coordinate_transform_mode '${coordinateTransformMode}' is not supported`);
+ }
+ const needRoiInput = (coordinateTransformMode === 'tf_crop_and_resize');
+ const useExtrapolation = needRoiInput;
+ const nearestMode = (mode === 'nearest' && opset >= 11) ? node.attributes.getString('nearest_mode', 'round_prefer_floor') : '';
+ if (['round_prefer_floor', 'round_prefer_ceil', 'floor', 'ceil', ''].indexOf(nearestMode) === -1) {
+ throw new Error(`nearest_mode '${nearestMode}' is not supported`);
+ }
+ const cubicCoefficientA = node.attributes.getFloat('cubic_coeff_a', -0.75);
+ const excludeOutside = node.attributes.getInt('exclude_outside', 0) !== 0;
+ if (excludeOutside && mode !== 'cubic') {
+ throw new Error('exclude_outside can be set to 1 only when mode is CUBIC.');
+ }
+ const useNearest2xOptimization = (opset < 11) ? true : (mode === 'nearest' && coordinateTransformMode === 'asymmetric' && nearestMode === 'floor');
+ let roiInputIdx = 0;
+ let scalesInputIdx = 0;
+ let sizesInputIdx = 0;
+ if (opset > 10) {
+ // handle when roiInput is not given
+ if (node.inputs.length > 2) {
+ roiInputIdx = 1;
+ scalesInputIdx = 2;
+ sizesInputIdx = 3;
+ }
+ else {
+ scalesInputIdx = 1;
+ sizesInputIdx = 2;
+ }
+ }
+ else if (opset === 9) {
+ scalesInputIdx = 1;
+ }
+ return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({
+ opset,
+ isResize,
+ mode,
+ scales,
+ extrapolationValue,
+ coordinateTransformMode,
+ useExtrapolation,
+ needRoiInput,
+ nearestMode,
+ cubicCoefficientA,
+ excludeOutside,
+ useNearest2xOptimization,
+ roiInputIdx,
+ scalesInputIdx,
+ sizesInputIdx
+ });
+};
+exports.parseUpsampleAttributes = parseUpsampleAttributes;
+const createUpsampleProgramInfo = (inferenceHandler, inputs, attributes) => {
+ const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
+ const [inputWidth, inputHeight] = inferenceHandler.calculateTextureWidthAndHeight(inputs[0].dims, types_1.TextureType.unpacked);
+ const outputShape = inputs[0].dims.map((dim, i) => Math.floor(dim * attributes.scales[i]));
+ const [outputWidth, outputHeight] = inferenceHandler.calculateTextureWidthAndHeight(outputShape, types_1.TextureType.unpacked);
+ const dim = outputShape.length;
+ const outputPitches = new Array(dim);
+ const inputPitches = new Array(dim);
+ let precalculatedPitches = `
+ int output_pitches[${dim}];
+ int input_pitches[${dim}];
+ `;
+ for (let d = dim - 1; d >= 0; d--) {
+ outputPitches[d] = (d === dim - 1) ? 1 : outputPitches[d + 1] * outputShape[d + 1];
+ inputPitches[d] = (d === dim - 1) ? 1 : inputPitches[d + 1] * inputs[0].dims[d + 1];
+ precalculatedPitches += `
+ output_pitches[${d}] = ${outputPitches[d]};
+ input_pitches[${d}] = ${inputPitches[d]};
+ `;
+ }
+ const getInputFloatFunction = `
+ float getInputFloat(int index) {
+ vec2 coords = offsetToCoords(index, ${inputWidth}, ${inputHeight});
+ float value = getColorAsFloat(${glsl.texture2D}(X, coords));
+ return value;
+ }
+ `;
+ const shaderSource = attributes.mode === 'nearest' ?
+ // nearest
+ `
+ ${getInputFloatFunction}
+ float process(int indices[${dim}]) {
+ int input_index = 0;
+ int output_index = coordsToOffset(TexCoords, ${outputWidth}, ${outputHeight});
+
+ ${precalculatedPitches}
+
+ int d, m;
+ for (int dim = 0; dim < ${dim}; ++dim) {
+ d = output_index / output_pitches[dim];
+ m = output_index - d * output_pitches[dim];
+ output_index = m;
+
+ if (scales[dim] != 1 && d > 0) {
+ int d2 = d / scales[dim];
+ m = d - d2 * scales[dim];
+ d = d2;
+ }
+ input_index += input_pitches[dim] * d;
+ }
+
+ return getInputFloat(input_index);
+ }` :
+ dim === 4 ?
+ // bilinear 4D
+ `
+ ${getInputFloatFunction}
+ float process(int indices[4]) {
+ int input_index = 0;
+ int output_index = coordsToOffset(TexCoords, ${outputWidth}, ${outputHeight});
+
+ ${precalculatedPitches}
+
+ int m;
+ int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3;
+ index_of_dim0 = output_index / output_pitches[0];
+ m = output_index - index_of_dim0 * output_pitches[0];
+ index_of_dim1 = m / output_pitches[1];
+ m = m - index_of_dim1 * output_pitches[1];
+ index_of_dim2 = m / output_pitches[2];
+ m = m - index_of_dim2 * output_pitches[2];
+ index_of_dim3 = m;
+
+ int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset;
+ index_of_input_dim2 = index_of_dim2 / scales[2];
+ y_offset = index_of_dim2 - index_of_input_dim2 * scales[2];
+ index_of_input_dim3 = index_of_dim3 / scales[3];
+ x_offset = index_of_dim3 - index_of_input_dim3 * scales[3];
+
+ input_index = index_of_dim0 * input_pitches[0] +
+ index_of_dim1 * input_pitches[1] +
+ index_of_input_dim2 * input_pitches[2] +
+ index_of_input_dim3;
+
+ float x00 = getInputFloat(input_index);
+ float x10, x01, x11;
+
+ bool end_of_dim2 = false;
+ if (index_of_input_dim2 == (${inputs[0].dims[2]} - 1)) {
+ // It's the end in dimension 2
+ x01 = x00;
+ end_of_dim2 = true;
+ } else {
+ x01 = getInputFloat(input_index + input_pitches[2]);
+ }
+
+ if (index_of_input_dim3 == (input_pitches[2] - 1)) {
+ // It's the end in dimension 3
+ x10 = x00;
+ x11 = x01;
+ }
+ else {
+ x10 = getInputFloat(input_index + 1);
+ x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1);
+ }
+
+ float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]);
+ float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]);
+ return y0 + float(x_offset) * (y1 - y0) / float(scales[3]);
+ }` :
+ // bilinear 2D
+ `
+ ${getInputFloatFunction}
+ float process(int indices[2]) {
+ int input_index = 0;
+ int output_index = coordsToOffset(TexCoords, ${outputWidth}, ${outputHeight});
+
+ ${precalculatedPitches}
+
+ int m;
+ int index_of_dim0, index_of_dim1;
+ index_of_dim0 = output_index / output_pitches[0];
+ m = output_index - index_of_dim0 * output_pitches[0];
+ index_of_dim1 = m;
+
+ int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset;
+ index_of_input_dim0 = index_of_dim0 / scales[0];
+ y_offset = index_of_dim0 - index_of_input_dim0 * scales[0];
+ index_of_input_dim1 = index_of_dim1 / scales[1];
+ x_offset = index_of_dim1 - index_of_input_dim1 * scales[1];
+
+ input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1;
+
+ float x00 = getInputFloat(input_index);
+ float x10, x01, x11;
+
+ bool end_of_dim0 = false;
+ if (index_of_input_dim0 == (${inputs[0].dims[0]} - 1)) {
+ // It's the end in dimension 0
+ x01 = x00;
+ end_of_dim0 = true;
+ } else {
+ x01 = getInputFloat(input_index + input_pitches[0]);
+ }
+
+ if (index_of_input_dim1 == (input_pitches[0] - 1)) {
+ // It's the end in dimension 1
+ x10 = x00;
+ x11 = x01;
+ }
+ else {
+ x10 = getInputFloat(input_index + 1);
+ x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1);
+ }
+
+ float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]);
+ float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]);
+ return y0 + float(x_offset) * (y1 - y0) / float(scales[1]);
+ }`;
+ return Object.assign(Object.assign({}, upsampleProgramMetadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource, variables: [{
+ name: 'scales',
+ type: 'int',
+ arrayLength: attributes.scales.length,
+ data: attributes.scales.map(x => Math.ceil(x))
+ }] });
+};
+const validateInputs = (inputs, attribute) => {
+ if (!inputs || (attribute.opset < 9 && inputs.length !== 1) ||
+ (attribute.opset >= 9 && attribute.opset < 11 && inputs.length !== 2) ||
+ (attribute.opset >= 11 && inputs.length < 2)) {
+ throw new Error('invalid inputs.');
+ }
+ if (attribute.scales.length > 0 && inputs[0].dims.length !== attribute.scales.length) {
+ throw new Error('Invalid input shape.');
+ }
+ if (inputs[0].type === 'string') {
+ throw new Error('Invalid input tensor types.');
+ }
+};
+exports.validateInputs = validateInputs;
+const scalesValidation = (scales, mode, isResize) => {
+ if (!isResize) {
+ for (const scale of scales) {
+ if (scale < 1) {
+ throw new Error('Scale value should be greater than or equal to 1.');
+ }
+ }
+ }
+ else {
+ for (const scale of scales) {
+ if (scale <= 0) {
+ throw new Error('Scale value should be greater than 0.');
+ }
+ }
+ }
+ if (mode === 'linear' || mode === 'cubic') {
+ if (scales.length !== 2 && (scales.length !== 4 || scales[0] !== 1 || scales[1] !== 1)) {
+ throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') \
+ or 4-D inputs with the corresponding outermost 2 scale values being 1 \
+ in the ${isResize ? 'Resize' : 'Upsample'} opeartor.`);
+ }
+ }
+};
+exports.scalesValidation = scalesValidation;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/program-manager.ts":
+/*!******************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/program-manager.ts ***!
+ \******************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ProgramManager = void 0;
+const onnxruntime_common_1 = __webpack_require__(/*! onnxruntime-common */ "../common/dist/lib/index.js");
+const instrument_1 = __webpack_require__(/*! ../../instrument */ "./lib/onnxjs/instrument.ts");
+const glsl_preprocessor_1 = __webpack_require__(/*! ./glsl-preprocessor */ "./lib/onnxjs/backends/webgl/glsl-preprocessor.ts");
+const glsl_source_1 = __webpack_require__(/*! ./glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
+/**
+ * ProgramManager is the main class behind running computations
+ * It builds ProgramInfo's into Artifacts
+ * It compiles given ProgramInfo's into WebGL Prorams (cached as Artifacts)
+ * Uses the artifact to run the computation by calling Draw on
+ * the WebGL drawing buffer
+ * ProgramManager automatically maps (binds) input variables to their
+ * corresponding Location's in the binary program
+ */
+class ProgramManager {
+ constructor(profiler, glContext, textureLayoutStrategy) {
+ this.profiler = profiler;
+ this.glContext = glContext;
+ this.textureLayoutStrategy = textureLayoutStrategy;
+ this.repo = new Map();
+ this.attributesBound = false;
+ }
+ getArtifact(key) {
+ return this.repo.get(key);
+ }
+ setArtifact(key, artifact) {
+ this.repo.set(key, artifact);
+ }
+ run(buildArtifact, inputs, output) {
+ var _a;
+ this.profiler.event('op', `ProgramManager.run ${(_a = buildArtifact.programInfo.name) !== null && _a !== void 0 ? _a : 'unknown kernel'}`, () => {
+ var _a;
+ const gl = this.glContext.gl;
+ const program = buildArtifact.program;
+ gl.useProgram(program);
+ try {
+ this.bindOutput(output);
+ if (!this.attributesBound) {
+ this.bindAttributes(buildArtifact.attribLocations);
+ }
+ this.bindUniforms(buildArtifact.uniformLocations, (_a = buildArtifact.programInfo.variables) !== null && _a !== void 0 ? _a : [], inputs);
+ }
+ catch (err) {
+ instrument_1.Logger.error('ProgramManager', buildArtifact.programInfo.shaderSource);
+ throw err;
+ }
+ this.profiler.event('backend', 'GlContext.draw()', () => {
+ this.glContext.draw();
+ });
+ }, this.glContext);
+ }
+ dispose() {
+ if (this.vertexShader) {
+ this.glContext.deleteShader(this.vertexShader);
+ }
+ this.repo.forEach(a => this.glContext.deleteProgram(a.program));
+ }
+ build(programInfo, inputTextureLayouts, outputTextureLayout) {
+ return this.profiler.event('backend', 'ProgramManager.build', () => {
+ const preprocessor = new glsl_preprocessor_1.GlslPreprocessor(this.glContext, programInfo, inputTextureLayouts, outputTextureLayout);
+ const fragScript = preprocessor.preprocess();
+ const program = this.compile(fragScript);
+ const artifact = {
+ programInfo,
+ program,
+ uniformLocations: this.getUniformLocations(program, preprocessor.context.programInfo.inputNames, preprocessor.context.programInfo.variables),
+ attribLocations: this.getAttribLocations(program)
+ };
+ return artifact;
+ });
+ }
+ compile(fragShaderScript) {
+ if (!this.vertexShader) {
+ instrument_1.Logger.verbose('ProrgramManager', 'Compiling and caching Vertex shader for the first time');
+ const vertexShaderScript = (0, glsl_source_1.getVertexShaderSource)(this.glContext.version);
+ this.vertexShader = this.glContext.compileShader(vertexShaderScript, this.glContext.gl.VERTEX_SHADER);
+ }
+ if (onnxruntime_common_1.env.debug) {
+ instrument_1.Logger.verbose('ProrgramManager', `FragShader:
+${fragShaderScript}
+`);
+ }
+ const fragShader = this.glContext.compileShader(fragShaderScript, this.glContext.gl.FRAGMENT_SHADER);
+ const program = this.glContext.createProgram(this.vertexShader, fragShader);
+ this.glContext.deleteShader(fragShader);
+ return program;
+ }
+ bindOutput(td) {
+ const width = td.width;
+ const height = td.height;
+ instrument_1.Logger.verbose('ProrgramManager', `Binding output texture to Framebuffer: w/h=${width}/${height}, shape=${td.shape}, type=${td.tensor.type}`);
+ this.glContext.attachFramebuffer(td.texture, width, height);
+ }
+ bindAttributes(attribLocations) {
+ const positionHandle = attribLocations.position;
+ const textureCoordHandle = attribLocations.textureCoord;
+ this.glContext.setVertexAttributes(positionHandle, textureCoordHandle);
+ this.attributesBound = true;
+ }
+ bindUniforms(uniformLocations, variables, textures) {
+ var _a;
+ const gl = this.glContext.gl;
+ let texturePosition = 0;
+ for (const { name, type, location, arrayLength } of uniformLocations) {
+ const value = (_a = variables.find(v => v.name === name)) === null || _a === void 0 ? void 0 : _a.data;
+ if (type !== 'sampler2D' && !value) {
+ throw new Error(`variable '${name}' does not have data defined in program info`);
+ }
+ switch (type) {
+ case 'sampler2D':
+ this.bindTexture(textures[texturePosition], location, texturePosition);
+ texturePosition++;
+ break;
+ case 'float':
+ if (arrayLength) {
+ gl.uniform1fv(location, value);
+ }
+ else {
+ gl.uniform1f(location, value);
+ }
+ break;
+ case 'int':
+ if (arrayLength) {
+ gl.uniform1iv(location, value);
+ }
+ else {
+ gl.uniform1i(location, value);
+ }
+ break;
+ default:
+ throw new Error(`Uniform not implemented: ${type}`);
+ }
+ }
+ }
+ bindTexture(td, uniformHandle, position) {
+ this.glContext.bindTextureToUniform(td.texture, position, uniformHandle);
+ }
+ getAttribLocations(program) {
+ return {
+ position: this.getAttribLocation(program, 'position'),
+ textureCoord: this.getAttribLocation(program, 'textureCoord')
+ };
+ }
+ getUniformLocations(program, samplers, variables) {
+ const uniformLocations = [];
+ if (samplers) {
+ for (const sampler of samplers) {
+ uniformLocations.push({ name: sampler, type: 'sampler2D', location: this.getUniformLocation(program, sampler) });
+ }
+ }
+ if (variables) {
+ for (const variable of variables) {
+ uniformLocations.push(Object.assign(Object.assign({}, variable), { location: this.getUniformLocation(program, variable.name) }));
+ }
+ }
+ return uniformLocations;
+ }
+ getUniformLocation(program, name) {
+ const gl = this.glContext.gl;
+ const reference = gl.getUniformLocation(program, name);
+ if (reference === null) {
+ throw new Error(`Uniform ${name} not found.`);
+ }
+ return reference;
+ }
+ getAttribLocation(program, name) {
+ const gl = this.glContext.gl;
+ const attributeLocation = gl.getAttribLocation(program, name);
+ return attributeLocation;
+ }
+}
+exports.ProgramManager = ProgramManager;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/session-handler.ts":
+/*!******************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/session-handler.ts ***!
+ \******************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.WebGLSessionHandler = void 0;
+const instrument_1 = __webpack_require__(/*! ../../instrument */ "./lib/onnxjs/instrument.ts");
+const opset_1 = __webpack_require__(/*! ../../opset */ "./lib/onnxjs/opset.ts");
+const inference_handler_1 = __webpack_require__(/*! ./inference-handler */ "./lib/onnxjs/backends/webgl/inference-handler.ts");
+const op_resolve_rules_1 = __webpack_require__(/*! ./op-resolve-rules */ "./lib/onnxjs/backends/webgl/op-resolve-rules.ts");
+const program_manager_1 = __webpack_require__(/*! ./program-manager */ "./lib/onnxjs/backends/webgl/program-manager.ts");
+const texture_layout_strategy_1 = __webpack_require__(/*! ./texture-layout-strategy */ "./lib/onnxjs/backends/webgl/texture-layout-strategy.ts");
+const texture_manager_1 = __webpack_require__(/*! ./texture-manager */ "./lib/onnxjs/backends/webgl/texture-manager.ts");
+class WebGLSessionHandler {
+ constructor(backend, context) {
+ this.backend = backend;
+ this.context = context;
+ this.layoutStrategy = new texture_layout_strategy_1.PreferLogicalStrategy(backend.glContext.maxTextureSize);
+ this.programManager = new program_manager_1.ProgramManager(this.context.profiler, backend.glContext, this.layoutStrategy);
+ this.textureManager = new texture_manager_1.TextureManager(backend.glContext, this.layoutStrategy, this.context.profiler, { reuseTextures: backend.textureCacheMode === 'full' });
+ this.packedTextureDataCache = new Map();
+ this.unpackedTextureDataCache = new Map();
+ this.pack = backend.pack;
+ this.pack2unpackMap = new Map();
+ this.unpack2packMap = new Map();
+ }
+ createInferenceHandler() {
+ return new inference_handler_1.WebGLInferenceHandler(this);
+ }
+ onGraphInitialized(graph) {
+ const initializers = graph.getValues().filter(v => v.from === -1 && v.tensor).map(v => v.tensor.dataId);
+ this.initializers = new Set(initializers);
+ }
+ isInitializer(tensorId) {
+ return this.initializers ? this.initializers.has(tensorId) : false;
+ }
+ addInitializer(tensorId) {
+ this.initializers.add(tensorId);
+ }
+ getTextureData(tensorId, isPacked) {
+ if (isPacked) {
+ return this.packedTextureDataCache.get(tensorId);
+ }
+ else {
+ return this.unpackedTextureDataCache.get(tensorId);
+ }
+ }
+ setTextureData(tensorId, textureData, isPacked = false) {
+ instrument_1.Logger.verbose('WebGLSessionHandler', 'Storing Texture data in cache');
+ if (isPacked) {
+ this.packedTextureDataCache.set(tensorId, textureData);
+ }
+ else {
+ this.unpackedTextureDataCache.set(tensorId, textureData);
+ }
+ }
+ dispose() {
+ this.programManager.dispose();
+ this.textureManager.clearActiveTextures();
+ this.packedTextureDataCache.forEach(td => this.textureManager.releaseTexture(td, true));
+ this.packedTextureDataCache = new Map();
+ this.unpackedTextureDataCache.forEach(td => this.textureManager.releaseTexture(td, true));
+ this.unpackedTextureDataCache = new Map();
+ }
+ resolve(node, opsets, graph) {
+ const op = (0, opset_1.resolveOperator)(node, opsets, op_resolve_rules_1.WEBGL_OP_RESOLVE_RULES);
+ return { impl: op.opImpl, context: op.opInit ? op.opInit(node, graph) : node };
+ }
+}
+exports.WebGLSessionHandler = WebGLSessionHandler;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/texture-data-encoder.ts":
+/*!***********************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/texture-data-encoder.ts ***!
+ \***********************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Uint8DataEncoder = exports.RGBAFloatDataEncoder = exports.RedFloat32DataEncoder = void 0;
+const instrument_1 = __webpack_require__(/*! ../../instrument */ "./lib/onnxjs/instrument.ts");
+/**
+ * WebGL2 data encoder
+ * Uses R32F as the format for texlet
+ */
+class RedFloat32DataEncoder {
+ constructor(gl, channels = 1) {
+ if (channels === 1) {
+ this.internalFormat = gl.R32F;
+ this.format = gl.RED;
+ this.textureType = gl.FLOAT;
+ this.channelSize = channels;
+ }
+ else if (channels === 4) {
+ this.internalFormat = gl.RGBA32F;
+ this.format = gl.RGBA;
+ this.textureType = gl.FLOAT;
+ this.channelSize = channels;
+ }
+ else {
+ throw new Error(`Invalid number of channels: ${channels}`);
+ }
+ }
+ encode(src, textureSize) {
+ let result;
+ let source;
+ if (src.constructor !== Float32Array) {
+ instrument_1.Logger.warning('Encoder', 'data was not of type Float32; creating new Float32Array');
+ source = new Float32Array(src);
+ }
+ if (textureSize * this.channelSize > src.length) {
+ instrument_1.Logger.warning('Encoder', 'Source data too small. Allocating larger array');
+ source = src;
+ result = this.allocate(textureSize * this.channelSize);
+ source.forEach((v, i) => result[i] = v);
+ }
+ else {
+ source = src;
+ result = source;
+ }
+ return result;
+ }
+ allocate(size) {
+ return new Float32Array(size * 4);
+ }
+ decode(buffer, dataSize) {
+ if (this.channelSize === 1) {
+ const filteredData = buffer.filter((value, index) => index % 4 === 0).subarray(0, dataSize);
+ return filteredData;
+ }
+ return buffer.subarray(0, dataSize);
+ }
+}
+exports.RedFloat32DataEncoder = RedFloat32DataEncoder;
+/**
+ * Data encoder for WebGL 1 with support for floating point texture
+ */
+class RGBAFloatDataEncoder {
+ constructor(gl, channels = 1, textureType) {
+ if (channels !== 1 && channels !== 4) {
+ throw new Error(`Invalid number of channels: ${channels}`);
+ }
+ this.internalFormat = gl.RGBA;
+ this.format = gl.RGBA;
+ this.channelSize = channels;
+ this.textureType = textureType || gl.FLOAT;
+ }
+ encode(src, textureSize) {
+ let dest = src;
+ if (this.channelSize === 1) {
+ instrument_1.Logger.verbose('Encoder', 'Exploding into a larger array');
+ dest = this.allocate(textureSize);
+ src.forEach((v, i) => dest[i * 4] = v);
+ }
+ return dest;
+ }
+ allocate(size) {
+ return new Float32Array(size * 4);
+ }
+ decode(buffer, dataSize) {
+ if (this.channelSize === 1) {
+ const filteredData = buffer.filter((value, index) => index % 4 === 0).subarray(0, dataSize);
+ return filteredData;
+ }
+ return buffer.subarray(0, dataSize);
+ }
+}
+exports.RGBAFloatDataEncoder = RGBAFloatDataEncoder;
+class Uint8DataEncoder {
+ constructor(gl, channels = 1) {
+ this.channelSize = 4;
+ if (channels === 1) {
+ this.internalFormat = gl.ALPHA;
+ this.format = gl.ALPHA; // not tested
+ this.textureType = gl.UNSIGNED_BYTE;
+ this.channelSize = channels;
+ }
+ else if (channels === 4) {
+ this.internalFormat = gl.RGBA;
+ this.format = gl.RGBA;
+ this.textureType = gl.UNSIGNED_BYTE;
+ this.channelSize = channels;
+ }
+ else {
+ throw new Error(`Invalid number of channels: ${channels}`);
+ }
+ }
+ encode(src, _textureSize) {
+ return new Uint8Array(src.buffer, src.byteOffset, src.byteLength);
+ }
+ allocate(size) {
+ return new Uint8Array(size * this.channelSize);
+ }
+ decode(buffer, dataSize) {
+ if (buffer instanceof Uint8Array) {
+ return buffer.subarray(0, dataSize);
+ }
+ throw new Error(`Invalid array type: ${buffer.constructor}`);
+ }
+}
+exports.Uint8DataEncoder = Uint8DataEncoder;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/texture-layout-strategy.ts":
+/*!**************************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/texture-layout-strategy.ts ***!
+ \**************************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getBatchDim = exports.sizeToSquarishShape = exports.getRowsCols = exports.sizeFromShape = exports.isInt = exports.parseAxisParam = exports.squeezeShape = exports.PreferLogicalStrategy = exports.AlwaysKeepOriginalSizeStrategy = void 0;
+const instrument_1 = __webpack_require__(/*! ../../instrument */ "./lib/onnxjs/instrument.ts");
+const util_1 = __webpack_require__(/*! ../../util */ "./lib/onnxjs/util.ts");
+/**
+ * This strategy try to find the minimal max(W,H) that fulfills (W * H == totalSize)
+ */
+class AlwaysKeepOriginalSizeStrategy {
+ constructor(maxTextureSize) {
+ this.maxTextureSize = maxTextureSize;
+ }
+ computeTextureWH(shape, prefs) {
+ // scalar tensor
+ if (shape.length === 0) {
+ return [1, 1];
+ }
+ const maxTextureSize = this.maxTextureSize;
+ if (prefs && prefs.breakAxis !== undefined) {
+ // check to see if dims fit
+ const wsize = prefs.breakAxis >= shape.length ? 1 : shape.slice(prefs.breakAxis).reduce((a, b) => a * b);
+ const hsize = prefs.breakAxis <= 0 ? 1 : shape.slice(0, prefs.breakAxis).reduce((a, b) => a * b);
+ if (wsize > maxTextureSize || hsize > maxTextureSize) {
+ // ignore preferences
+ // continue with default layout
+ instrument_1.Logger.verbose('TextureLayout', `Given width/height preferences were unattainable: shape:${shape}, breakAxis:${prefs.breakAxis}`);
+ }
+ else {
+ return [wsize, hsize];
+ }
+ }
+ const totalSize = shape.reduce((a, b) => a * b);
+ let width = Math.floor(Math.sqrt(totalSize));
+ for (; width < maxTextureSize && width < totalSize; width++) {
+ if (totalSize % width === 0) {
+ break;
+ }
+ }
+ if (width >= maxTextureSize || totalSize % width !== 0) {
+ throw new Error(`The given dimensions are outside this GPU's boundaries: ${shape}`);
+ }
+ return [width, totalSize / width];
+ }
+}
+exports.AlwaysKeepOriginalSizeStrategy = AlwaysKeepOriginalSizeStrategy;
+class PreferLogicalStrategy {
+ constructor(maxTextureSize) {
+ this.maxTextureSize = maxTextureSize;
+ }
+ computeTextureWH(shape, prefs) {
+ const wh = this.computeTexture(shape, prefs);
+ if (prefs && prefs.isPacked) {
+ wh[0] /= 2;
+ wh[1] /= 2;
+ }
+ if (prefs && prefs.reverseWH) {
+ return [wh[1], wh[0]];
+ }
+ return wh;
+ }
+ computeTexture(shape, prefs) {
+ const isPacked = prefs && prefs.isPacked;
+ // scalar tensor
+ if (shape.length === 0) {
+ return isPacked ? [2, 2] : [1, 1];
+ }
+ let maxTextureSize = this.maxTextureSize;
+ if (prefs && prefs.breakAxis !== undefined) {
+ // check to see if dims fit
+ const wsize = prefs.breakAxis >= shape.length ? 1 : shape.slice(prefs.breakAxis).reduce((a, b) => a * b);
+ const hsize = prefs.breakAxis <= 0 ? 1 : shape.slice(0, prefs.breakAxis).reduce((a, b) => a * b);
+ if (wsize > maxTextureSize || hsize > maxTextureSize) {
+ // ignore preferences
+ // continue with default layout
+ instrument_1.Logger.verbose('TextureLayout', `Given width/height preferences were unattainable: shape:${shape}, breakAxis:${prefs.breakAxis}`);
+ }
+ else {
+ return [wsize, hsize];
+ }
+ }
+ let logShape = shape.slice(0);
+ if (isPacked) {
+ maxTextureSize = maxTextureSize * 2;
+ // This logic ensures we accurately count the number of packed texels needed
+ // to accommodate the tensor. We can only pack values in the same texel if
+ // they are from adjacent pairs of rows/cols within the same batch. So if a
+ // tensor has 3 rows, we pretend it has 4 rows in order to account for the
+ // fact that the texels containing the third row are half empty.
+ logShape = logShape.map((d, i) => i >= logShape.length - 2 ? (logShape[i] % 2 === 0 ? logShape[i] : logShape[i] + 1) : logShape[i]);
+ // Packed texture height is at least 2 (the channel height of a single
+ // texel).
+ if (logShape.length === 1) {
+ logShape = [2, logShape[0]];
+ }
+ }
+ // If logical shape is 2, we don't squeeze, since we want to match physical.
+ if (logShape.length !== 2) {
+ const squeezeResult = squeezeShape(logShape);
+ logShape = squeezeResult.newShape;
+ }
+ const size = sizeFromShape(logShape);
+ if (logShape.length <= 1 && size <= maxTextureSize) {
+ return [1, size];
+ }
+ else if (logShape.length === 2 && logShape[0] <= maxTextureSize && logShape[1] <= maxTextureSize) {
+ return logShape;
+ }
+ else if (logShape.length === 3 && logShape[0] * logShape[1] <= maxTextureSize && logShape[2] <= maxTextureSize) {
+ return [logShape[0] * logShape[1], logShape[2]];
+ }
+ else if (logShape.length === 3 && logShape[0] <= maxTextureSize && logShape[1] * logShape[2] <= maxTextureSize) {
+ return [logShape[0], logShape[1] * logShape[2]];
+ }
+ else if (logShape.length === 4 && logShape[0] * logShape[1] * logShape[2] <= maxTextureSize &&
+ logShape[3] <= maxTextureSize) {
+ return [logShape[0] * logShape[1] * logShape[2], logShape[3]];
+ }
+ else if (logShape.length === 4 && logShape[0] <= maxTextureSize &&
+ logShape[1] * logShape[2] * logShape[3] <= maxTextureSize) {
+ return [logShape[0], logShape[1] * logShape[2] * logShape[3]];
+ }
+ else {
+ if (isPacked) {
+ // For packed textures size equals the number of channels required to
+ // accommodate the texture data. However in order to squarify such that
+ // inner dimensions stay even, we rewrite size to equal the number of
+ // texels. Then in the return statement we rehydrate the squarified
+ // dimensions to channel units.
+ return sizeToSquarishShape(size / 4).map(d => d * 2);
+ }
+ return sizeToSquarishShape(size);
+ }
+ }
+}
+exports.PreferLogicalStrategy = PreferLogicalStrategy;
+function squeezeShape(shape, axis) {
+ const newShape = [];
+ const keptDims = [];
+ const isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0;
+ const axes = (axis == null || isEmptyArray) ? null : parseAxisParam(axis, shape).sort();
+ let j = 0;
+ for (let i = 0; i < shape.length; ++i) {
+ if (axes != null) {
+ if (axes[j] === i && shape[i] !== 1) {
+ throw new Error(`Can't squeeze axis ${i} since its dim '${shape[i]}' is not 1`);
+ }
+ if ((axes[j] == null || axes[j] > i) && shape[i] === 1) {
+ newShape.push(shape[i]);
+ keptDims.push(i);
+ }
+ if (axes[j] <= i) {
+ j++;
+ }
+ }
+ if (shape[i] !== 1) {
+ newShape.push(shape[i]);
+ keptDims.push(i);
+ }
+ }
+ return { newShape, keptDims };
+}
+exports.squeezeShape = squeezeShape;
+function parseAxisParam(axis, shape) {
+ const rank = shape.length;
+ // Normalize input
+ axis = axis == null ? shape.map((s, i) => i) : [].concat(axis);
+ // Check for valid range
+ (0, util_1.assert)(axis.every(ax => ax >= -rank && ax < rank), () => `All values in axis param must be in range [-${rank}, ${rank}) but ` +
+ `got axis ${axis}`);
+ // Check for only integers
+ (0, util_1.assert)(axis.every(isInt), () => 'All values in axis param must be integers but ' +
+ `got axis ${axis}`);
+ // Handle negative axis.
+ return axis.map(a => a < 0 ? rank + a : a);
+}
+exports.parseAxisParam = parseAxisParam;
+function isInt(a) {
+ return a % 1 === 0;
+}
+exports.isInt = isInt;
+function sizeFromShape(shape) {
+ if (shape.length === 0) {
+ // Scalar.
+ return 1;
+ }
+ let size = shape[0];
+ for (let i = 1; i < shape.length; i++) {
+ size *= shape[i];
+ }
+ return size;
+}
+exports.sizeFromShape = sizeFromShape;
+function getRowsCols(shape) {
+ if (shape.length === 0) {
+ throw Error('Cannot get rows and columns of an empty shape array.');
+ }
+ return [shape.length > 1 ? shape[shape.length - 2] : 1, shape[shape.length - 1]];
+}
+exports.getRowsCols = getRowsCols;
+function sizeToSquarishShape(size) {
+ const width = Math.ceil(Math.sqrt(size));
+ return [width, Math.ceil(size / width)];
+}
+exports.sizeToSquarishShape = sizeToSquarishShape;
+function getBatchDim(shape, dimsToSkip = 2) {
+ return sizeFromShape(shape.slice(0, shape.length - dimsToSkip));
+}
+exports.getBatchDim = getBatchDim;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/texture-layout.ts":
+/*!*****************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/texture-layout.ts ***!
+ \*****************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createTextureLayoutFromShape = exports.calculateTextureWidthAndHeight = exports.createTextureLayoutFromTextureType = void 0;
+const util_1 = __webpack_require__(/*! ../../util */ "./lib/onnxjs/util.ts");
+const types_1 = __webpack_require__(/*! ./types */ "./lib/onnxjs/backends/webgl/types.ts");
+const createTextureLayoutFromTextureType = (textureLayoutStrategy, shape, textureType) => {
+ const channel = (textureType === types_1.TextureType.unpacked || textureType === types_1.TextureType.unpackedReversed) ? 1 : 4;
+ const isPacked = textureType === types_1.TextureType.packed;
+ const reverseWH = (textureType === types_1.TextureType.unpackedReversed || textureType === types_1.TextureType.packed);
+ const breakAxis = textureType === types_1.TextureType.packedLastDimension ? shape.length - 1 : undefined;
+ const unpackedShape = textureType === types_1.TextureType.packedLastDimension ?
+ shape.map((d, i) => i === shape.length - 1 ? d * 4 : d) :
+ undefined;
+ return (0, exports.createTextureLayoutFromShape)(textureLayoutStrategy, shape, channel, unpackedShape, { isPacked, reverseWH, breakAxis });
+};
+exports.createTextureLayoutFromTextureType = createTextureLayoutFromTextureType;
+const calculateTextureWidthAndHeight = (textureLayoutStrategy, shape, textureType) => {
+ const layout = (0, exports.createTextureLayoutFromTextureType)(textureLayoutStrategy, shape, textureType);
+ return [layout.width, layout.height];
+};
+exports.calculateTextureWidthAndHeight = calculateTextureWidthAndHeight;
+/**
+ * Create a TextureLayout object from shape.
+ */
+const createTextureLayoutFromShape = (textureLayoutStrategy, shape, channels = 1, unpackedShape, prefs) => {
+ const isPacked = !!(prefs && prefs.isPacked);
+ const [width, height] = textureLayoutStrategy.computeTextureWH(isPacked ? unpackedShape || shape : shape, prefs);
+ const rank = shape.length;
+ let inferredDims = shape.slice(0);
+ if (rank === 0) {
+ inferredDims = [1];
+ }
+ if (channels === 1) {
+ // unpackedShape will take `shape` and not `inferredDims` so as to create a scalar Tensor if need be
+ unpackedShape = shape;
+ }
+ else if (isPacked) {
+ if (channels !== 4) {
+ throw new Error('a packed texture must be 4-channel');
+ }
+ unpackedShape = shape;
+ if (rank > 0) {
+ inferredDims[rank - 1] = Math.ceil(inferredDims[rank - 1] / 2);
+ }
+ if (rank > 1) {
+ inferredDims[rank - 2] = Math.ceil(inferredDims[rank - 2] / 2);
+ }
+ }
+ else if (!unpackedShape) {
+ throw new Error('Unpacked shape is needed when using channels > 1');
+ }
+ return {
+ width,
+ height,
+ channels,
+ isPacked,
+ shape: inferredDims,
+ strides: util_1.ShapeUtil.computeStrides(inferredDims),
+ unpackedShape,
+ reversedWH: (prefs && prefs.reverseWH)
+ };
+};
+exports.createTextureLayoutFromShape = createTextureLayoutFromShape;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/texture-manager.ts":
+/*!******************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/texture-manager.ts ***!
+ \******************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.TextureManager = void 0;
+const instrument_1 = __webpack_require__(/*! ../../instrument */ "./lib/onnxjs/instrument.ts");
+/**
+ * TextureManager is the mainly responsible for caching Textures
+ * Textures are cached in 2 levels:
+ * 1. the texures which are associated with a dataId (from Tensor)
+ * Caching these is crucial to performance. These are In-use Textures
+ * 2. textures which are not in use by any current ProgramInfo/Tensor
+ * These are called Free Textures
+ * TextureManager is also used to help creating textures. For this it
+ * uses WebGLContext and TextureLayoutStrategy
+ */
+class TextureManager {
+ constructor(glContext, layoutStrategy, profiler, config) {
+ this.glContext = glContext;
+ this.layoutStrategy = layoutStrategy;
+ this.profiler = profiler;
+ this.config = config;
+ this.pendingRead = new Map();
+ if (config.reuseTextures) {
+ this.inUseTextures = new Map();
+ this.idleTextures = new Map();
+ this.textureLookup = new Map();
+ }
+ }
+ createTextureFromLayout(dataType, layout, data, usage) {
+ const textureDataType = this.toEncoderType(dataType);
+ const encoder = this.glContext.getEncoder(textureDataType, layout.channels || 1, usage);
+ if (layout.isPacked && usage === 1 /* Encoder.Usage.UploadOnly */) {
+ throw new Error('not implemented');
+ }
+ const width = layout.width;
+ const height = layout.height;
+ let key;
+ let inUseTextures;
+ if (this.config.reuseTextures) {
+ key = `${width}x${height}_${encoder.format}_${encoder.internalFormat}_${encoder.textureType}`;
+ inUseTextures = this.inUseTextures.get(key);
+ if (!inUseTextures) {
+ inUseTextures = [];
+ this.inUseTextures.set(key, inUseTextures);
+ }
+ const idleTextures = this.idleTextures.get(key);
+ if (idleTextures && idleTextures.length > 0) {
+ const texture = idleTextures.pop();
+ inUseTextures.push(texture);
+ if (usage === 1 /* Encoder.Usage.UploadOnly */) {
+ this.glContext.updateTexture(texture, width, height, encoder, this.toTextureData(dataType, data));
+ }
+ return texture;
+ }
+ }
+ instrument_1.Logger.verbose('TextureManager', `Creating new texture of size ${layout.width}x${layout.height}`);
+ const texture = this.glContext.allocateTexture(width, height, encoder, this.toTextureData(dataType, data));
+ if (this.config.reuseTextures) {
+ inUseTextures.push(texture);
+ this.textureLookup.set(texture, key);
+ }
+ return texture;
+ }
+ readTexture(td, dataType, channels) {
+ if (!channels) {
+ channels = 1;
+ }
+ return this.profiler.event('backend', 'TextureManager.readTexture', () => {
+ const dataSize = td.shape.reduce((a, b) => a * b) * channels;
+ const data = this.glContext.readTexture(td.texture, td.width, td.height, dataSize, this.toEncoderType(dataType), channels);
+ return this.toTensorData(dataType, data);
+ });
+ }
+ async readTextureAsync(td, dataType, channels) {
+ const dataId = td.tensor.dataId;
+ if (!channels) {
+ channels = 1;
+ }
+ if (this.pendingRead.has(dataId)) {
+ const subscribers = this.pendingRead.get(dataId);
+ return new Promise(resolve => subscribers === null || subscribers === void 0 ? void 0 : subscribers.push(resolve));
+ }
+ return this.profiler.event('backend', 'TextureManager.readTextureAsync', async () => {
+ this.pendingRead.set(dataId, []);
+ const dataSize = td.shape.reduce((a, b) => a * b) * channels;
+ // add a fence waiting for the data to be ready
+ await this.glContext.createAndWaitForFence();
+ const data = this.glContext.readTexture(td.texture, td.width, td.height, dataSize, this.toEncoderType(dataType), channels);
+ const tensorData = this.toTensorData(dataType, data);
+ const subscribers = this.pendingRead.get(dataId);
+ this.pendingRead.delete(dataId);
+ subscribers === null || subscribers === void 0 ? void 0 : subscribers.forEach(resolve => resolve(tensorData));
+ return tensorData;
+ });
+ }
+ readUint8TextureAsFloat(td) {
+ return this.profiler.event('backend', 'TextureManager.readUint8TextureAsFloat', () => {
+ const dataSize = td.shape.reduce((a, b) => a * b);
+ const data = this.glContext.readTexture(td.texture, td.width, td.height, dataSize * 4, 'byte', 4);
+ return new Float32Array(data.buffer, data.byteOffset, dataSize);
+ });
+ }
+ releaseTexture(textureData, deleteTexture) {
+ let key;
+ if (this.config.reuseTextures) {
+ key = this.textureLookup.get(textureData.texture);
+ if (key) {
+ if (deleteTexture) {
+ this.textureLookup.delete(key);
+ }
+ const inUseTextures = this.inUseTextures.get(key);
+ if (inUseTextures) {
+ const index = inUseTextures.indexOf(textureData.texture);
+ if (index !== -1) {
+ inUseTextures.splice(index, 1);
+ let idleTextures = this.idleTextures.get(key);
+ if (!idleTextures) {
+ idleTextures = [];
+ this.idleTextures.set(key, idleTextures);
+ }
+ idleTextures.push(textureData.texture);
+ }
+ }
+ }
+ }
+ if (!key || deleteTexture) {
+ instrument_1.Logger.verbose('TextureManager', `Deleting texture of size ${textureData.width}x${textureData.height}`);
+ this.glContext.deleteTexture(textureData.texture);
+ }
+ }
+ toTensorData(dataType, data) {
+ switch (dataType) {
+ case 'int16':
+ return data instanceof Int16Array ? data : Int16Array.from(data);
+ case 'int32':
+ return data instanceof Int32Array ? data : Int32Array.from(data);
+ case 'int8':
+ return data instanceof Int8Array ? data : Int8Array.from(data);
+ case 'uint16':
+ return data instanceof Uint16Array ? data : Uint16Array.from(data);
+ case 'uint32':
+ return data instanceof Uint32Array ? data : Uint32Array.from(data);
+ case 'uint8':
+ case 'bool':
+ return data instanceof Uint8Array ? data : Uint8Array.from(data);
+ case 'float32':
+ return data instanceof Float32Array ? data : Float32Array.from(data);
+ case 'float64':
+ return data instanceof Float64Array ? data : Float64Array.from(data);
+ default:
+ throw new Error(`TensorData type ${dataType} is not supported`);
+ }
+ }
+ toTextureData(dataType, data) {
+ if (!data) {
+ return undefined;
+ }
+ return (data instanceof Float32Array) ? data : new Float32Array(data);
+ /*
+ switch (dataType) {
+ case 'int16':
+ case 'int32':
+ case 'uint16':
+ case 'uint32':
+ return (data.constructor === Uint32Array) ? data as Uint32Array : new Uint32Array(data);
+ case 'int8':
+ case 'uint8':
+ case 'bool':
+ return (data.constructor === Uint8Array) ? data as Uint8Array : new Uint8Array(data);
+ case 'float32':
+ case 'float64':
+ return (data.constructor === Float32Array) ? data as Float32Array : new Float32Array(data);
+ default:
+ throw new Error(`TensorData type ${dataType} is not supported`);
+ }
+ */
+ }
+ toEncoderType(_dataType) {
+ return 'float';
+ // switch (dataType) {
+ // case 'int16':
+ // case 'int32':
+ // case 'uint16':
+ // case 'uint32':
+ // return 'int';
+ // case 'uint8':
+ // case 'bool':
+ // return 'byte';
+ // case 'float32':
+ // case 'float64':
+ // return 'float';
+ // default:
+ // throw new Error(`TensorData type ${dataType} is not supported`);
+ // }
+ }
+ clearActiveTextures() {
+ this.glContext.clearActiveTextures();
+ }
+}
+exports.TextureManager = TextureManager;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/types.ts":
+/*!********************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/types.ts ***!
+ \********************************************/
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.TextureType = void 0;
+var TextureType;
+(function (TextureType) {
+ TextureType[TextureType["unpacked"] = 0] = "unpacked";
+ TextureType[TextureType["unpackedReversed"] = 1] = "unpackedReversed";
+ TextureType[TextureType["packed"] = 2] = "packed";
+ TextureType[TextureType["downloadUint8AsFloat"] = 3] = "downloadUint8AsFloat";
+ TextureType[TextureType["packedLastDimension"] = 4] = "packedLastDimension"; // <-- ONLY used in old ONNX.js Conv implementation for input W (deprecated)
+})(TextureType = exports.TextureType || (exports.TextureType = {}));
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/utils.ts":
+/*!********************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/utils.ts ***!
+ \********************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getGlChannels = exports.getCoordsDataType = exports.getSqueezedParams = exports.squeezeInputShape = exports.generateShaderFuncNameFromInputSamplerNameAtOutCoords = exports.generateShaderFuncNameFromInputSamplerName = exports.repeatedTry = exports.getPackedShape = void 0;
+const util_1 = __webpack_require__(/*! ../../util */ "./lib/onnxjs/util.ts");
+/**
+ * Given a non RGBA shape calculate the R version
+ * It is assumed that the dimensions are multiples of given channels
+ * NOTE: it is always the last dim that gets packed.
+ * @param unpackedShape original shape to create a packed version from
+ */
+function getPackedShape(unpackedShape) {
+ const len = unpackedShape.length;
+ return unpackedShape.slice(0, len - 1).concat(unpackedShape[len - 1] / 4);
+}
+exports.getPackedShape = getPackedShape;
+async function repeatedTry(checkFn, delayFn = (_counter) => 0, maxCounter) {
+ return new Promise((resolve, reject) => {
+ let tryCount = 0;
+ const tryFn = () => {
+ if (checkFn()) {
+ resolve();
+ return;
+ }
+ tryCount++;
+ const nextBackoff = delayFn(tryCount);
+ if (maxCounter != null && tryCount >= maxCounter) {
+ reject();
+ return;
+ }
+ setTimeout(tryFn, nextBackoff);
+ };
+ tryFn();
+ });
+}
+exports.repeatedTry = repeatedTry;
+/**
+ * Generates the function name from an input sampler name.
+ * @param samplerName Name of the sampler.
+ */
+function generateShaderFuncNameFromInputSamplerName(samplerName) {
+ (0, util_1.assert)(typeof samplerName !== 'undefined' && samplerName.length !== 0, () => 'empty string found for sampler name');
+ return 'get' + samplerName.charAt(0).toUpperCase() + samplerName.slice(1);
+}
+exports.generateShaderFuncNameFromInputSamplerName = generateShaderFuncNameFromInputSamplerName;
+/**
+ * Generates the function name from an input sampler name at output coordinates.
+ * @param samplerName Name of the sampler.
+ */
+function generateShaderFuncNameFromInputSamplerNameAtOutCoords(samplerName) {
+ (0, util_1.assert)(typeof samplerName !== 'undefined' && samplerName.length !== 0, () => 'empty string found for sampler name');
+ return 'get' + samplerName.charAt(0).toUpperCase() + samplerName.slice(1) + 'AtOutCoords';
+}
+exports.generateShaderFuncNameFromInputSamplerNameAtOutCoords = generateShaderFuncNameFromInputSamplerNameAtOutCoords;
+/** Returns a new input shape (a copy) that has a squeezed logical shape. */
+function squeezeInputShape(inputShape, squeezedShape) {
+ // Deep copy.
+ let newInputShape = JSON.parse(JSON.stringify(inputShape));
+ newInputShape = squeezedShape;
+ return newInputShape;
+}
+exports.squeezeInputShape = squeezeInputShape;
+/** Returns a list of squeezed parameters for shader functions */
+function getSqueezedParams(params, keptDims) {
+ return keptDims.map(d => params[d]).join(', ');
+}
+exports.getSqueezedParams = getSqueezedParams;
+/** Returns the data type for different ranks. */
+function getCoordsDataType(rank) {
+ if (rank <= 1) {
+ return 'int';
+ }
+ else if (rank === 2) {
+ return 'ivec2';
+ }
+ else if (rank === 3) {
+ return 'ivec3';
+ }
+ else if (rank === 4) {
+ return 'ivec4';
+ }
+ else if (rank === 5) {
+ return 'ivec5';
+ }
+ else if (rank === 6) {
+ return 'ivec6';
+ }
+ else {
+ throw Error(`GPU for rank ${rank} is not yet supported`);
+ }
+}
+exports.getCoordsDataType = getCoordsDataType;
+function getGlChannels(rank = 6) {
+ return ['x', 'y', 'z', 'w', 'u', 'v'].slice(0, rank);
+}
+exports.getGlChannels = getGlChannels;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/webgl-context-factory.ts":
+/*!************************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/webgl-context-factory.ts ***!
+ \************************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createNewWebGLContext = exports.createWebGLContext = void 0;
+const instrument_1 = __webpack_require__(/*! ../../instrument */ "./lib/onnxjs/instrument.ts");
+const webgl_context_1 = __webpack_require__(/*! ./webgl-context */ "./lib/onnxjs/backends/webgl/webgl-context.ts");
+const cache = {};
+/**
+ * This factory function creates proper WebGLRenderingContext based on
+ * the current browsers capabilities
+ * The order is from higher/most recent versions to most basic
+ */
+function createWebGLContext(contextId) {
+ let context;
+ if ((!contextId || contextId === 'webgl2') && 'webgl2' in cache) {
+ context = cache.webgl2;
+ }
+ else if ((!contextId || contextId === 'webgl') && 'webgl' in cache) {
+ context = cache.webgl;
+ }
+ context = context || createNewWebGLContext(contextId);
+ contextId = contextId || context.version === 1 ? 'webgl' : 'webgl2';
+ const gl = context.gl;
+ cache[contextId] = context;
+ if (gl.isContextLost()) {
+ delete cache[contextId];
+ return createWebGLContext(contextId);
+ }
+ gl.disable(gl.DEPTH_TEST);
+ gl.disable(gl.STENCIL_TEST);
+ gl.disable(gl.BLEND);
+ gl.disable(gl.DITHER);
+ gl.disable(gl.POLYGON_OFFSET_FILL);
+ gl.disable(gl.SAMPLE_COVERAGE);
+ gl.enable(gl.SCISSOR_TEST);
+ gl.enable(gl.CULL_FACE);
+ gl.cullFace(gl.BACK);
+ return context;
+}
+exports.createWebGLContext = createWebGLContext;
+function createNewWebGLContext(contextId) {
+ const canvas = createCanvas();
+ const contextAttributes = {
+ alpha: false,
+ depth: false,
+ antialias: false,
+ stencil: false,
+ preserveDrawingBuffer: false,
+ premultipliedAlpha: false,
+ failIfMajorPerformanceCaveat: false
+ };
+ let gl;
+ const ca = contextAttributes;
+ if (!contextId || contextId === 'webgl2') {
+ gl = canvas.getContext('webgl2', ca);
+ if (gl) {
+ try {
+ return new webgl_context_1.WebGLContext(gl, 2);
+ }
+ catch (err) {
+ instrument_1.Logger.warning('GlContextFactory', `failed to create WebGLContext using contextId 'webgl2'. Error: ${err}`);
+ }
+ }
+ }
+ if (!contextId || contextId === 'webgl') {
+ gl = canvas.getContext('webgl', ca) || canvas.getContext('experimental-webgl', ca);
+ if (gl) {
+ try {
+ return new webgl_context_1.WebGLContext(gl, 1);
+ }
+ catch (err) {
+ instrument_1.Logger.warning('GlContextFactory', `failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${err}`);
+ }
+ }
+ }
+ throw new Error('WebGL is not supported');
+}
+exports.createNewWebGLContext = createNewWebGLContext;
+function createCanvas() {
+ if (typeof document === 'undefined') {
+ if (typeof OffscreenCanvas === 'undefined') {
+ throw new TypeError('failed to create canvas: OffscreenCanvas is not supported');
+ }
+ return new OffscreenCanvas(1, 1);
+ }
+ const canvas = document.createElement('canvas');
+ canvas.width = 1;
+ canvas.height = 1;
+ return canvas;
+}
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/backends/webgl/webgl-context.ts":
+/*!****************************************************!*\
+ !*** ./lib/onnxjs/backends/webgl/webgl-context.ts ***!
+ \****************************************************/
+/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.WebGLContext = exports.linearSearchLastTrue = void 0;
+const onnxruntime_common_1 = __webpack_require__(/*! onnxruntime-common */ "../common/dist/lib/index.js");
+const DataEncoders = __importStar(__webpack_require__(/*! ./texture-data-encoder */ "./lib/onnxjs/backends/webgl/texture-data-encoder.ts"));
+const utils_1 = __webpack_require__(/*! ./utils */ "./lib/onnxjs/backends/webgl/utils.ts");
+function linearSearchLastTrue(arr) {
+ let i = 0;
+ for (; i < arr.length; ++i) {
+ const isDone = arr[i]();
+ if (!isDone) {
+ break;
+ }
+ }
+ return i - 1;
+}
+exports.linearSearchLastTrue = linearSearchLastTrue;
+/**
+ * Abstraction and wrapper around WebGLRenderingContext and its operations
+ */
+class WebGLContext {
+ constructor(gl, version) {
+ this.frameBufferBound = false;
+ this.itemsToPoll = [];
+ this.gl = gl;
+ this.version = version;
+ this.getExtensions();
+ this.vertexbuffer = this.createVertexbuffer();
+ this.framebuffer = this.createFramebuffer();
+ this.queryVitalParameters();
+ }
+ allocateTexture(width, height, encoder, data) {
+ const gl = this.gl;
+ // create the texture
+ const texture = gl.createTexture();
+ // bind the texture so the following methods effect this texture.
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ const buffer = data ? encoder.encode(data, width * height) : null;
+ gl.texImage2D(gl.TEXTURE_2D, 0, // Level of detail.
+ encoder.internalFormat, width, height, 0, // Always 0 in OpenGL ES.
+ encoder.format, encoder.textureType, buffer);
+ this.checkError();
+ return texture;
+ }
+ updateTexture(texture, width, height, encoder, data) {
+ const gl = this.gl;
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ const buffer = encoder.encode(data, width * height);
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, // level
+ 0, // xoffset
+ 0, // yoffset
+ width, height, encoder.format, encoder.textureType, buffer);
+ this.checkError();
+ }
+ attachFramebuffer(texture, width, height) {
+ const gl = this.gl;
+ // Make it the target for framebuffer operations - including rendering.
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); // 0, we aren't using MIPMAPs
+ this.checkError();
+ gl.viewport(0, 0, width, height);
+ gl.scissor(0, 0, width, height);
+ }
+ readTexture(texture, width, height, dataSize, dataType, channels) {
+ const gl = this.gl;
+ if (!channels) {
+ channels = 1;
+ }
+ if (!this.frameBufferBound) {
+ this.attachFramebuffer(texture, width, height);
+ }
+ const encoder = this.getEncoder(dataType, channels);
+ const buffer = encoder.allocate(width * height);
+ // bind texture to framebuffer
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); // 0, we aren't using MIPMAPs
+ // TODO: Check if framebuffer is ready
+ gl.readPixels(0, 0, width, height, gl.RGBA, encoder.textureType, buffer);
+ this.checkError();
+ // unbind FB
+ return encoder.decode(buffer, dataSize);
+ }
+ isFramebufferReady() {
+ // TODO: Implement logic to check if the framebuffer is ready
+ return true;
+ }
+ getActiveTexture() {
+ const gl = this.gl;
+ const n = gl.getParameter(this.gl.ACTIVE_TEXTURE);
+ return `TEXTURE${(n - gl.TEXTURE0)}`;
+ }
+ getTextureBinding() {
+ return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D);
+ }
+ getFramebufferBinding() {
+ return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING);
+ }
+ setVertexAttributes(positionHandle, textureCoordHandle) {
+ const gl = this.gl;
+ gl.vertexAttribPointer(positionHandle, 3, gl.FLOAT, false, 20, 0);
+ gl.enableVertexAttribArray(positionHandle);
+ if (textureCoordHandle !== -1) {
+ gl.vertexAttribPointer(textureCoordHandle, 2, gl.FLOAT, false, 20, 12);
+ gl.enableVertexAttribArray(textureCoordHandle);
+ }
+ this.checkError();
+ }
+ createProgram(vertexShader, fragShader) {
+ const gl = this.gl;
+ const program = gl.createProgram();
+ // the program consists of our shaders
+ gl.attachShader(program, vertexShader);
+ gl.attachShader(program, fragShader);
+ gl.linkProgram(program);
+ return program;
+ }
+ compileShader(shaderSource, shaderType) {
+ const gl = this.gl;
+ const shader = gl.createShader(shaderType);
+ if (!shader) {
+ throw new Error(`createShader() returned null with type ${shaderType}`);
+ }
+ gl.shaderSource(shader, shaderSource);
+ gl.compileShader(shader);
+ if (gl.getShaderParameter(shader, gl.COMPILE_STATUS) === false) {
+ throw new Error(`Failed to compile shader: ${gl.getShaderInfoLog(shader)}
+Shader source:
+${shaderSource}`);
+ }
+ return shader;
+ }
+ deleteShader(shader) {
+ this.gl.deleteShader(shader);
+ }
+ bindTextureToUniform(texture, position, uniformHandle) {
+ const gl = this.gl;
+ gl.activeTexture(gl.TEXTURE0 + position);
+ this.checkError();
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ this.checkError();
+ gl.uniform1i(uniformHandle, position);
+ this.checkError();
+ }
+ draw() {
+ this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 4);
+ this.checkError();
+ }
+ checkError() {
+ if (onnxruntime_common_1.env.debug) {
+ const gl = this.gl;
+ const error = gl.getError();
+ let label = '';
+ switch (error) {
+ case (gl.NO_ERROR):
+ return;
+ case (gl.INVALID_ENUM):
+ label = 'INVALID_ENUM';
+ break;
+ case (gl.INVALID_VALUE):
+ label = 'INVALID_VALUE';
+ break;
+ case (gl.INVALID_OPERATION):
+ label = 'INVALID_OPERATION';
+ break;
+ case (gl.INVALID_FRAMEBUFFER_OPERATION):
+ label = 'INVALID_FRAMEBUFFER_OPERATION';
+ break;
+ case (gl.OUT_OF_MEMORY):
+ label = 'OUT_OF_MEMORY';
+ break;
+ case (gl.CONTEXT_LOST_WEBGL):
+ label = 'CONTEXT_LOST_WEBGL';
+ break;
+ default:
+ label = `Unknown WebGL Error: ${error.toString(16)}`;
+ }
+ throw new Error(label);
+ }
+ }
+ deleteTexture(texture) {
+ this.gl.deleteTexture(texture);
+ }
+ deleteProgram(program) {
+ this.gl.deleteProgram(program);
+ }
+ getEncoder(dataType, channels, usage = 0 /* Encoder.Usage.Default */) {
+ if (this.version === 2) {
+ return new DataEncoders.RedFloat32DataEncoder(this.gl, channels);
+ }
+ switch (dataType) {
+ case 'float':
+ if (usage === 1 /* Encoder.Usage.UploadOnly */ || this.isRenderFloat32Supported) {
+ return new DataEncoders.RGBAFloatDataEncoder(this.gl, channels);
+ }
+ else {
+ return new DataEncoders.RGBAFloatDataEncoder(this.gl, channels, this.textureHalfFloatExtension.HALF_FLOAT_OES);
+ }
+ case 'int':
+ throw new Error('not implemented');
+ case 'byte':
+ return new DataEncoders.Uint8DataEncoder(this.gl, channels);
+ default:
+ throw new Error(`Invalid dataType: ${dataType}`);
+ }
+ }
+ clearActiveTextures() {
+ const gl = this.gl;
+ for (let unit = 0; unit < this.maxTextureImageUnits; ++unit) {
+ gl.activeTexture(gl.TEXTURE0 + unit);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ }
+ }
+ dispose() {
+ if (this.disposed) {
+ return;
+ }
+ const gl = this.gl;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.deleteFramebuffer(this.framebuffer);
+ gl.bindBuffer(gl.ARRAY_BUFFER, null);
+ gl.deleteBuffer(this.vertexbuffer);
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
+ gl.finish();
+ this.disposed = true;
+ }
+ createDefaultGeometry() {
+ // Sets of x,y,z(=0),s,t coordinates.
+ return new Float32Array([
+ -1.0, 1.0, 0.0, 0.0, 1.0,
+ -1.0, -1.0, 0.0, 0.0, 0.0,
+ 1.0, 1.0, 0.0, 1.0, 1.0,
+ 1.0, -1.0, 0.0, 1.0, 0.0 // lower right
+ ]);
+ }
+ createVertexbuffer() {
+ const gl = this.gl;
+ const buffer = gl.createBuffer();
+ if (!buffer) {
+ throw new Error('createBuffer() returned null');
+ }
+ const geometry = this.createDefaultGeometry();
+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
+ gl.bufferData(gl.ARRAY_BUFFER, geometry, gl.STATIC_DRAW);
+ this.checkError();
+ return buffer;
+ }
+ createFramebuffer() {
+ const fb = this.gl.createFramebuffer();
+ if (!fb) {
+ throw new Error('createFramebuffer returned null');
+ }
+ return fb;
+ }
+ queryVitalParameters() {
+ const gl = this.gl;
+ this.isFloatTextureAttachableToFrameBuffer = this.checkFloatTextureAttachableToFrameBuffer();
+ this.isRenderFloat32Supported = this.checkRenderFloat32();
+ this.isFloat32DownloadSupported = this.checkFloat32Download();
+ if (this.version === 1 && !this.textureHalfFloatExtension && !this.isRenderFloat32Supported) {
+ throw new Error('both float32 and float16 TextureType are not supported');
+ }
+ this.isBlendSupported = !this.isRenderFloat32Supported || this.checkFloat32Blend();
+ // this.maxCombinedTextureImageUnits = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
+ this.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
+ this.maxTextureImageUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
+ // this.maxCubeMapTextureSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
+ // this.shadingLanguageVersion = gl.getParameter(gl.SHADING_LANGUAGE_VERSION);
+ // this.webglVendor = gl.getParameter(gl.VENDOR);
+ // this.webglVersion = gl.getParameter(gl.VERSION);
+ if (this.version === 2) {
+ // this.max3DTextureSize = gl.getParameter(WebGL2RenderingContext.MAX_3D_TEXTURE_SIZE);
+ // this.maxArrayTextureLayers = gl.getParameter(WebGL2RenderingContext.MAX_ARRAY_TEXTURE_LAYERS);
+ // this.maxColorAttachments = gl.getParameter(WebGL2RenderingContext.MAX_COLOR_ATTACHMENTS);
+ // this.maxDrawBuffers = gl.getParameter(WebGL2RenderingContext.MAX_DRAW_BUFFERS);
+ }
+ }
+ getExtensions() {
+ if (this.version === 2) {
+ this.colorBufferFloatExtension = this.gl.getExtension('EXT_color_buffer_float');
+ this.disjointTimerQueryWebgl2Extension = this.gl.getExtension('EXT_disjoint_timer_query_webgl2');
+ }
+ else {
+ this.textureFloatExtension = this.gl.getExtension('OES_texture_float');
+ this.textureHalfFloatExtension = this.gl.getExtension('OES_texture_half_float');
+ }
+ }
+ checkFloatTextureAttachableToFrameBuffer() {
+ // test whether Float32 texture is supported:
+ // STEP.1 create a float texture
+ const gl = this.gl;
+ const texture = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ const internalFormat = this.version === 2 ? gl.RGBA32F : gl.RGBA;
+ gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, 1, 1, 0, gl.RGBA, gl.FLOAT, null);
+ // STEP.2 bind a frame buffer
+ const frameBuffer = gl.createFramebuffer();
+ gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
+ // STEP.3 attach texture to framebuffer
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
+ // STEP.4 test whether framebuffer is complete
+ const isComplete = gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.deleteTexture(texture);
+ gl.deleteFramebuffer(frameBuffer);
+ return isComplete;
+ }
+ checkRenderFloat32() {
+ if (this.version === 2) {
+ if (!this.colorBufferFloatExtension) {
+ return false;
+ }
+ }
+ else {
+ if (!this.textureFloatExtension) {
+ return false;
+ }
+ }
+ return this.isFloatTextureAttachableToFrameBuffer;
+ }
+ checkFloat32Download() {
+ if (this.version === 2) {
+ if (!this.colorBufferFloatExtension) {
+ return false;
+ }
+ }
+ else {
+ if (!this.textureFloatExtension) {
+ return false;
+ }
+ if (!this.gl.getExtension('WEBGL_color_buffer_float')) {
+ return false;
+ }
+ }
+ return this.isFloatTextureAttachableToFrameBuffer;
+ }
+ /**
+ * Check whether GL_BLEND is supported
+ */
+ checkFloat32Blend() {
+ // it looks like currently (2019-05-08) there is no easy way to detect whether BLEND is supported
+ // https://github.com/microsoft/onnxjs/issues/145
+ const gl = this.gl;
+ let texture;
+ let frameBuffer;
+ let vertexShader;
+ let fragmentShader;
+ let program;
+ try {
+ texture = gl.createTexture();
+ frameBuffer = gl.createFramebuffer();
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ const internalFormat = this.version === 2 ? gl.RGBA32F : gl.RGBA;
+ gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, 1, 1, 0, gl.RGBA, gl.FLOAT, null);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
+ gl.enable(gl.BLEND);
+ vertexShader = gl.createShader(gl.VERTEX_SHADER);
+ if (!vertexShader) {
+ return false;
+ }
+ gl.shaderSource(vertexShader, 'void main(){}');
+ gl.compileShader(vertexShader);
+ fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
+ if (!fragmentShader) {
+ return false;
+ }
+ gl.shaderSource(fragmentShader, 'precision highp float;void main(){gl_FragColor=vec4(0.5);}');
+ gl.compileShader(fragmentShader);
+ program = gl.createProgram();
+ if (!program) {
+ return false;
+ }
+ gl.attachShader(program, vertexShader);
+ gl.attachShader(program, fragmentShader);
+ gl.linkProgram(program);
+ gl.useProgram(program);
+ gl.drawArrays(gl.POINTS, 0, 1);
+ return gl.getError() === gl.NO_ERROR;
+ }
+ finally {
+ gl.disable(gl.BLEND);
+ if (program) {
+ gl.deleteProgram(program);
+ }
+ if (vertexShader) {
+ gl.deleteShader(vertexShader);
+ }
+ if (fragmentShader) {
+ gl.deleteShader(fragmentShader);
+ }
+ if (frameBuffer) {
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.deleteFramebuffer(frameBuffer);
+ }
+ if (texture) {
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.deleteTexture(texture);
+ }
+ }
+ }
+ beginTimer() {
+ if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) {
+ const gl2 = this.gl;
+ const ext = this.disjointTimerQueryWebgl2Extension;
+ const query = gl2.createQuery();
+ gl2.beginQuery(ext.TIME_ELAPSED_EXT, query);
+ return query;
+ }
+ else {
+ // TODO: add webgl 1 handling.
+ throw new Error('WebGL1 profiling currently not supported.');
+ }
+ }
+ endTimer() {
+ if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) {
+ const gl2 = this.gl;
+ const ext = this.disjointTimerQueryWebgl2Extension;
+ gl2.endQuery(ext.TIME_ELAPSED_EXT);
+ return;
+ }
+ else {
+ // TODO: add webgl 1 handling.
+ throw new Error('WebGL1 profiling currently not supported');
+ }
+ }
+ isTimerResultAvailable(query) {
+ let available = false, disjoint = false;
+ if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) {
+ const gl2 = this.gl;
+ const ext = this.disjointTimerQueryWebgl2Extension;
+ available = gl2.getQueryParameter(query, gl2.QUERY_RESULT_AVAILABLE);
+ disjoint = gl2.getParameter(ext.GPU_DISJOINT_EXT);
+ }
+ else {
+ // TODO: add webgl 1 handling.
+ throw new Error('WebGL1 profiling currently not supported');
+ }
+ return available && !disjoint;
+ }
+ getTimerResult(query) {
+ let timeElapsed = 0;
+ if (this.version === 2) {
+ const gl2 = this.gl;
+ timeElapsed = gl2.getQueryParameter(query, gl2.QUERY_RESULT);
+ gl2.deleteQuery(query);
+ }
+ else {
+ // TODO: add webgl 1 handling.
+ throw new Error('WebGL1 profiling currently not supported');
+ }
+ // return miliseconds
+ return timeElapsed / 1000000;
+ }
+ async waitForQueryAndGetTime(query) {
+ await (0, utils_1.repeatedTry)(() => this.isTimerResultAvailable(query));
+ return this.getTimerResult(query);
+ }
+ async createAndWaitForFence() {
+ const fenceContext = this.createFence(this.gl);
+ return this.pollFence(fenceContext);
+ }
+ createFence(gl) {
+ let isFencePassed;
+ const gl2 = gl;
+ const query = gl2.fenceSync(gl2.SYNC_GPU_COMMANDS_COMPLETE, 0);
+ gl.flush();
+ if (query === null) {
+ isFencePassed = () => true;
+ }
+ else {
+ isFencePassed = () => {
+ const status = gl2.clientWaitSync(query, 0, 0);
+ return status === gl2.ALREADY_SIGNALED || status === gl2.CONDITION_SATISFIED;
+ };
+ }
+ return { query, isFencePassed };
+ }
+ async pollFence(fenceContext) {
+ return new Promise(resolve => {
+ void this.addItemToPoll(() => fenceContext.isFencePassed(), () => resolve());
+ });
+ }
+ pollItems() {
+ // Find the last query that has finished.
+ const index = linearSearchLastTrue(this.itemsToPoll.map(x => x.isDoneFn));
+ for (let i = 0; i <= index; ++i) {
+ const { resolveFn } = this.itemsToPoll[i];
+ resolveFn();
+ }
+ this.itemsToPoll = this.itemsToPoll.slice(index + 1);
+ }
+ async addItemToPoll(isDoneFn, resolveFn) {
+ this.itemsToPoll.push({ isDoneFn, resolveFn });
+ if (this.itemsToPoll.length > 1) {
+ // We already have a running loop that polls.
+ return;
+ }
+ // Start a new loop that polls.
+ await (0, utils_1.repeatedTry)(() => {
+ this.pollItems();
+ // End the loop if no more items to poll.
+ return this.itemsToPoll.length === 0;
+ });
+ }
+}
+exports.WebGLContext = WebGLContext;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/execution-plan.ts":
+/*!**************************************!*\
+ !*** ./lib/onnxjs/execution-plan.ts ***!
+ \**************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ExecutionPlan = void 0;
+const instrument_1 = __webpack_require__(/*! ./instrument */ "./lib/onnxjs/instrument.ts");
+class KernelOp {
+ constructor(op, node) {
+ this.op = op;
+ this.node = node;
+ }
+}
+class ExecutionPlan {
+ constructor(graph, ops, profiler) {
+ this.graph = graph;
+ this.profiler = profiler;
+ this.initialize(ops);
+ }
+ initialize(ops) {
+ this.profiler.event('session', 'ExecutionPlan.initialize', () => {
+ const graphNodes = this.graph.getNodes();
+ if (graphNodes.length !== ops.length) {
+ throw new Error('The size of nodes and OPs do not match.');
+ }
+ this._ops = ops.map((op, i) => new KernelOp(op, graphNodes[i]));
+ this.reset();
+ // look for starter node(s)
+ this._starter = [];
+ this._ops.forEach((op, i) => {
+ let resolved = true;
+ for (const input of op.node.inputs) {
+ if (!this._values[input] // not an initialized input
+ && this.graph.getInputIndices().indexOf(input) === -1 // not model input
+ ) {
+ resolved = false;
+ break;
+ }
+ }
+ if (resolved) {
+ this._starter.push(i);
+ }
+ });
+ });
+ }
+ reset() {
+ this._values = this.graph.getValues().map(i => i.tensor);
+ }
+ async execute(sessionHandler, modelInputs) {
+ return this.profiler.event('session', 'ExecutionPlan.execute', async () => {
+ // reset mediem result
+ this.reset();
+ // create inference handler
+ const inferenceHandler = sessionHandler.createInferenceHandler();
+ // populate inputs value
+ const graphInputs = this.graph.getInputIndices();
+ if (modelInputs.length !== graphInputs.length) {
+ throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${modelInputs.length} expected: ${graphInputs.length}`);
+ }
+ modelInputs.forEach((input, i) => {
+ const index = graphInputs[i];
+ this._values[index] = input;
+ });
+ // prepare running sequence
+ const sequence = this._starter.slice(0);
+ // execution iterations
+ const graphValues = this.graph.getValues();
+ const graphNodes = this.graph.getNodes();
+ let rear = 0;
+ while (rear < sequence.length) {
+ const thisOpIndex = sequence[rear++];
+ const thisOp = this._ops[thisOpIndex];
+ // check input
+ const inputList = thisOp.node.inputs.map(i => this._values[i]);
+ if (inputList.indexOf(undefined) !== -1) {
+ throw new Error(`unresolved input detected: op: ${thisOp.node}`);
+ }
+ // run
+ const inputTensors = inputList;
+ instrument_1.Logger.verbose('ExecPlan', `Runing op:${thisOp.node.name} (${inputTensors.map((t, i) => `'${thisOp.node.inputs[i]}': ${t.type}[${t.dims.join(',')}]`).join(', ')})`);
+ const outputList = await this.profiler.event('node', thisOp.node.name, async () => thisOp.op.impl(inferenceHandler, inputTensors, thisOp.op.context));
+ // check output
+ if (outputList.length !== thisOp.node.outputs.length) {
+ throw new Error('the size of output does not match model definition.');
+ }
+ // fill value
+ outputList.forEach((output, i) => {
+ const j = thisOp.node.outputs[i];
+ if (this._values[j]) {
+ throw new Error(`output [${j}] already has value: op:${thisOp.node.name}`);
+ }
+ this._values[j] = output;
+ });
+ // resolve downstream nodes
+ const downstreamNodes = new Set();
+ outputList.forEach((output, i) => {
+ const j = thisOp.node.outputs[i];
+ for (const currentDownstreamNodeIndex of graphValues[j].to) {
+ const currentDownstreamNode = graphNodes[currentDownstreamNodeIndex];
+ let resolved = true;
+ for (const k of currentDownstreamNode.inputs) {
+ if (!this._values[k]) {
+ resolved = false;
+ break;
+ }
+ }
+ if (resolved) {
+ downstreamNodes.add(currentDownstreamNodeIndex);
+ }
+ }
+ });
+ sequence.push(...downstreamNodes);
+ }
+ const output = [];
+ for (let i = 0; i < this.graph.getOutputIndices().length; i++) {
+ const outputIndex = this.graph.getOutputIndices()[i];
+ const outputTensor = this._values[outputIndex];
+ if (outputTensor === undefined) {
+ throw new Error(`required output [${outputIndex}] does not have value`);
+ }
+ if (outputIndex === 0) {
+ await outputTensor.getData();
+ }
+ else {
+ // eslint-disable-next-line no-unused-expressions
+ outputTensor.data;
+ }
+ output.push(outputTensor);
+ }
+ instrument_1.Logger.verbose('ExecPlan', 'disposing of inferenceHandler');
+ inferenceHandler.dispose();
+ return output;
+ });
+ }
+}
+exports.ExecutionPlan = ExecutionPlan;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/graph.ts":
+/*!*****************************!*\
+ !*** ./lib/onnxjs/graph.ts ***!
+ \*****************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Graph = void 0;
+const onnx_proto_1 = __webpack_require__(/*! onnx-proto */ "./node_modules/onnx-proto/dist/onnx.js");
+const attribute_1 = __webpack_require__(/*! ./attribute */ "./lib/onnxjs/attribute.ts");
+const ort_generated_1 = __webpack_require__(/*! ./ort-schema/ort-generated */ "./lib/onnxjs/ort-schema/ort-generated.ts");
+const tensor_1 = __webpack_require__(/*! ./tensor */ "./lib/onnxjs/tensor.ts");
+const util_1 = __webpack_require__(/*! ./util */ "./lib/onnxjs/util.ts");
+var ortFbs = ort_generated_1.onnxruntime.experimental.fbs;
+// eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/no-redeclare
+exports.Graph = {
+ /**
+ * construct a graph from a graph protobuf type
+ */
+ from: (graphProto, initializer) => new GraphImpl(graphProto, initializer),
+};
+class Value {
+ constructor(valueInfo) {
+ this._from = undefined;
+ this._to = [];
+ this.tensor = undefined;
+ this.type = undefined;
+ if (valueInfo) {
+ this.type = util_1.ProtoUtil.tensorValueTypeFromProto(valueInfo.type.tensorType);
+ }
+ }
+ get from() {
+ return this._from;
+ }
+ get to() {
+ return this._to;
+ }
+}
+class Node {
+ constructor(_nodeProto, name) {
+ if (_nodeProto instanceof onnx_proto_1.onnx.NodeProto) {
+ this.name = _nodeProto.name;
+ this.opType = _nodeProto.opType;
+ this.attributes = new attribute_1.Attribute(_nodeProto.attribute);
+ }
+ else if (_nodeProto instanceof ortFbs.Node) {
+ this.name = name !== null && name !== void 0 ? name : _nodeProto.name();
+ this.opType = _nodeProto.opType();
+ this.attributes = new attribute_1.Attribute(util_1.ProtoUtil.tensorAttributesFromORTFormat(_nodeProto));
+ }
+ this.inputs = [];
+ this.outputs = [];
+ this.executeNode = true;
+ }
+}
+class GraphImpl {
+ constructor(graph, graphInitializer) {
+ if (!graph) {
+ throw new TypeError('graph is empty');
+ }
+ // build the graph - will throw exceptions if something fatal is detected
+ this.buildGraph(graph);
+ // execute any transformation logic for the graph (if applicable)
+ this.transformGraph(graphInitializer);
+ // check for cycles and other inconsistencies - will throw exceptions if something fatal is detected
+ this.checkIsAcyclic();
+ }
+ getInputIndices() {
+ return this._allInputIndices;
+ }
+ getInputNames() {
+ return this._allInputNames;
+ }
+ getOutputIndices() {
+ return this._allOutputIndices;
+ }
+ getOutputNames() {
+ return this._allOutputNames;
+ }
+ getValues() {
+ return this._allData;
+ }
+ getNodes() {
+ return this._nodes;
+ }
+ buildGraph(graph) {
+ // build the graph - will throw exceptions if something fatal is detected
+ if (graph instanceof onnx_proto_1.onnx.GraphProto) {
+ this.buildGraphFromOnnxFormat(graph);
+ }
+ else if (graph instanceof ortFbs.Graph) {
+ this.buildGraphFromOrtFormat(graph);
+ }
+ else {
+ throw new TypeError('Graph type is not supported.');
+ }
+ }
+ buildGraphFromOnnxFormat(graph) {
+ const dataIndices = new Map();
+ this._allData = [];
+ this._allInputIndices = [];
+ this._allInputNames = [];
+ this._allOutputIndices = [];
+ this._allOutputNames = [];
+ this._nodes = [];
+ const nodesIndices = new Map();
+ // scan all inputs
+ if (!graph.input) {
+ throw new Error('missing information in graph: input');
+ }
+ const inputValueNames = [];
+ for (const i of graph.input) {
+ if (dataIndices.has(i.name)) {
+ throw new Error(`duplicated input name: ${i.name}`);
+ }
+ const currentIndex = this._allData.push(new Value(i)) - 1;
+ dataIndices.set(i.name, currentIndex);
+ inputValueNames.push(i.name);
+ }
+ // scan all initializers
+ if (!graph.initializer) {
+ throw new Error('missing information in graph: initializer');
+ }
+ for (const i of graph.initializer) {
+ let index = dataIndices.get(i.name);
+ if (index === undefined) {
+ const value = new Value();
+ value.type = {
+ shape: { dims: util_1.ProtoUtil.tensorDimsFromProto(i.dims) },
+ tensorType: util_1.ProtoUtil.tensorDataTypeFromProto(i.dataType)
+ };
+ index = this._allData.push(value) - 1;
+ dataIndices.set(i.name, index);
+ }
+ this._allData[index]._from = -1;
+ this._allData[index].tensor = tensor_1.Tensor.fromProto(i);
+ }
+ // filter out input indices
+ for (let i = 0; i < this._allData.length; i++) {
+ if (!this._allData[i].tensor) {
+ this._allInputIndices.push(i);
+ this._allInputNames.push(inputValueNames[i]);
+ }
+ }
+ // scan all outputs
+ if (!graph.output) {
+ throw new Error('missing information in graph: output');
+ }
+ for (const i of graph.output) {
+ if (dataIndices.has(i.name)) {
+ throw new Error(`duplicated output name: ${i.name}`);
+ }
+ const currentIndex = this._allData.push(new Value(i)) - 1;
+ dataIndices.set(i.name, currentIndex);
+ this._allOutputIndices.push(currentIndex);
+ this._allOutputNames.push(i.name);
+ }
+ // scan all nodes
+ if (!graph.node) {
+ throw new Error('missing information in graph: node');
+ }
+ for (const nodeProto of graph.node) {
+ if (!nodeProto.name) {
+ // assign a name to the node if it doesn't have one
+ for (let pick = 0;; pick++) {
+ const name = `unnamed_${nodeProto.opType}_${pick}`;
+ if (!nodesIndices.has(name)) {
+ nodeProto.name = name;
+ break;
+ }
+ }
+ }
+ if (nodesIndices.has(nodeProto.name)) {
+ throw new Error(`duplicated node name: ${nodeProto.name}`);
+ }
+ const currentIndex = this._nodes.push(new Node(nodeProto)) - 1;
+ nodesIndices.set(nodeProto.name, currentIndex);
+ }
+ // scan node's outputs
+ for (let i = 0; i < this._nodes.length; i++) {
+ const node = this._nodes[i];
+ const nodeProto = graph.node[i];
+ if (!nodeProto.output) {
+ throw new Error(`missing output for node: ${nodeProto.name}`);
+ }
+ for (const output of nodeProto.output) {
+ let dataIndex = dataIndices.get(output);
+ if (typeof dataIndex === 'undefined') {
+ dataIndex = this._allData.push(new Value()) - 1;
+ dataIndices.set(output, dataIndex);
+ }
+ node.outputs.push(dataIndex);
+ if (this._allData[dataIndex]._from !== undefined) {
+ throw new Error(`multiple nodes output to one data value: ${dataIndex}`);
+ }
+ this._allData[dataIndex]._from = i;
+ // for the 'Constant' operator, just create a new edge in the graph corresponding to the 'output' of the
+ // operator and ignore the node from the graph
+ if (nodeProto.opType === 'Constant') {
+ if (!nodeProto.attribute || nodeProto.attribute.length !== 1 || !nodeProto.attribute[0].t) {
+ throw new Error('missing attributes or missing tensor value in attributes for this Constant operator');
+ }
+ if (!nodeProto.output || nodeProto.output.length !== 1) {
+ throw new Error('missing output or incorrect number of outputs for this Constant operator');
+ }
+ node.outputs.pop();
+ node.executeNode = false;
+ this._allData[dataIndex]._from = -1;
+ this._allData[dataIndex].tensor = tensor_1.Tensor.fromProto(nodeProto.attribute[0].t);
+ }
+ }
+ }
+ // scan node's inputs
+ for (let i = 0; i < this._nodes.length; i++) {
+ const node = this._nodes[i];
+ const nodeProto = graph.node[i];
+ if (!nodeProto.input) {
+ throw new Error(`missing input for node: ${nodeProto.name}`);
+ }
+ for (const input of nodeProto.input) {
+ const dataIndex = dataIndices.get(input);
+ if (typeof dataIndex === 'undefined') {
+ // handle exception when opset > 9 and roi not given
+ if (input === '' && nodeProto.input.length === 3 && nodeProto.opType === 'Resize') {
+ continue;
+ }
+ throw new Error(`unrecognized input '${input}' for node: ${nodeProto.name}`);
+ }
+ node.inputs.push(dataIndex);
+ this._allData[dataIndex]._to.push(i);
+ }
+ }
+ return true;
+ }
+ buildGraphFromOrtFormat(graph) {
+ var _a, _b, _c;
+ const dataIndices = new Map();
+ this._allData = [];
+ this._allInputIndices = [];
+ this._allInputNames = [];
+ this._allOutputIndices = [];
+ this._allOutputNames = [];
+ this._nodes = [];
+ const nodesIndices = new Map();
+ // scan all inputs
+ const inputValueNames = [];
+ for (let i = 0; i < graph.inputsLength(); i++) {
+ const inputName = graph.inputs(i);
+ if (dataIndices.has(inputName)) {
+ throw new Error(`duplicated input name: ${inputName}`);
+ }
+ // Find the input typeInfo from nodeargs
+ for (let j = 0; j < graph.nodeArgsLength(); j++) {
+ if (((_a = graph.nodeArgs(j)) === null || _a === void 0 ? void 0 : _a.name()) === inputName) {
+ const value = new Value();
+ const valueType = (_c = (_b = graph.nodeArgs(j)) === null || _b === void 0 ? void 0 : _b.type()) === null || _c === void 0 ? void 0 : _c.valueType();
+ if (valueType !== ortFbs.TypeInfoValue.tensor_type) {
+ throw new Error('Unexpected value type for the nodeArg.');
+ }
+ const valueInfo = graph.nodeArgs(j).type().value(new ortFbs.TensorTypeAndShape());
+ const type = util_1.ProtoUtil.tensorDataTypeFromProto(valueInfo.elemType());
+ const shape = valueInfo.shape();
+ const dims = [];
+ for (let k = 0; k < shape.dimLength(); k++) {
+ dims.push(util_1.LongUtil.longToNumber(shape.dim(k).value().dimValue()));
+ }
+ value.type = { shape: { dims }, tensorType: type };
+ const currentIndex = this._allData.push(value) - 1;
+ dataIndices.set(inputName, currentIndex);
+ inputValueNames.push(inputName);
+ }
+ }
+ }
+ // check initializers
+ for (let i = 0; i < graph.initializersLength(); i++) {
+ const initializer = graph.initializers(i);
+ let index = dataIndices.get(initializer.name());
+ if (index === undefined) {
+ const value = new Value();
+ const dims = util_1.ProtoUtil.tensorDimsFromORTFormat(initializer);
+ const type = util_1.ProtoUtil.tensorDataTypeFromProto(initializer.dataType());
+ value.type = { shape: { dims }, tensorType: type };
+ index = this._allData.push(value) - 1;
+ dataIndices.set(initializer.name(), index);
+ }
+ this._allData[index]._from = -1;
+ this._allData[index].tensor = tensor_1.Tensor.fromOrtTensor(initializer);
+ }
+ // filter out input indices
+ for (let i = 0; i < this._allData.length; i++) {
+ if (!this._allData[i].tensor) {
+ this._allInputIndices.push(i);
+ this._allInputNames.push(inputValueNames[i]);
+ }
+ }
+ // scan all outputs
+ for (let i = 0; i < graph.outputsLength(); i++) {
+ const outputName = graph.outputs(i);
+ if (dataIndices.has(outputName)) {
+ throw new Error(`duplicated output name: ${outputName}`);
+ }
+ const currentIndex = this._allData.push(new Value()) - 1;
+ dataIndices.set(outputName, currentIndex);
+ this._allOutputIndices.push(currentIndex);
+ this._allOutputNames.push(outputName);
+ }
+ // scan all nodes
+ if (!graph.nodes) {
+ throw new Error('missing information in graph: node');
+ }
+ for (let i = 0; i < graph.nodesLength(); i++) {
+ const nodeProto = graph.nodes(i);
+ let name = nodeProto.name();
+ if (!name) {
+ // assign a name to the node if it doesn't have one
+ for (let pick = 0;; pick++) {
+ name = `unnamed_${nodeProto.opType()}_${pick}`;
+ if (!nodesIndices.has(name)) {
+ // an unique name is found. break.
+ break;
+ }
+ }
+ }
+ if (nodesIndices.has(name)) {
+ throw new Error(`duplicated node name: ${name}`);
+ }
+ const currentIndex = this._nodes.push(new Node(nodeProto, name)) - 1;
+ nodesIndices.set(name, currentIndex);
+ }
+ // scan node's outputs
+ for (let i = 0; i < this._nodes.length; i++) {
+ const node = this._nodes[i];
+ const nodeProto = graph.nodes(i);
+ if (nodeProto == null) {
+ throw new Error(`No node exists at index ${i}`);
+ }
+ if ((nodeProto === null || nodeProto === void 0 ? void 0 : nodeProto.outputsLength()) === 0) {
+ throw new Error(`missing output for node: ${nodeProto.name}`);
+ }
+ for (let j = 0; j < (nodeProto === null || nodeProto === void 0 ? void 0 : nodeProto.outputsLength()); j++) {
+ const output = nodeProto === null || nodeProto === void 0 ? void 0 : nodeProto.outputs(j);
+ let dataIndex = dataIndices.get(output);
+ if (typeof dataIndex === 'undefined') {
+ dataIndex = this._allData.push(new Value()) - 1;
+ dataIndices.set(output, dataIndex);
+ }
+ node.outputs.push(dataIndex);
+ if (this._allData[dataIndex]._from !== undefined) {
+ throw new Error(`multiple nodes output to one data value: ${dataIndex}`);
+ }
+ this._allData[dataIndex]._from = i;
+ // for the 'Constant' operator, just create a new edge in the graph corresponding to the 'output' of the
+ // operator and ignore the node from the graph
+ if (nodeProto.opType() === 'Constant') {
+ if (nodeProto.attributesLength() !== 1 || !nodeProto.attributes(0).t()) {
+ throw new Error('missing attributes or missing tensor value in attributes for this Constant operator');
+ }
+ if (nodeProto.outputsLength() !== 1) {
+ throw new Error('missing output or incorrect number of outputs for this Constant operator');
+ }
+ node.outputs.pop();
+ node.executeNode = false;
+ this._allData[dataIndex]._from = -1;
+ this._allData[dataIndex].tensor = tensor_1.Tensor.fromOrtTensor(nodeProto.attributes(0).t());
+ }
+ }
+ }
+ // scan node's inputs
+ for (let i = 0; i < this._nodes.length; i++) {
+ const node = this._nodes[i];
+ const nodeProto = graph.nodes(i);
+ if (nodeProto.inputsLength() === 0) {
+ throw new Error(`missing input for node: ${nodeProto.name}`);
+ }
+ for (let j = 0; j < nodeProto.inputsLength(); j++) {
+ const input = nodeProto.inputs(j);
+ const dataIndex = dataIndices.get(input);
+ if (typeof dataIndex === 'undefined') {
+ throw new Error(`unrecognized input '${input}' for node: ${nodeProto.name()}`);
+ }
+ node.inputs.push(dataIndex);
+ this._allData[dataIndex]._to.push(i);
+ }
+ }
+ }
+ checkIsAcyclic() {
+ // go through the graph and check for cycles or other fatal inconsistencies
+ const starters = new Set();
+ this._allInputIndices.forEach(i => {
+ const data = this._allData[i];
+ data._to.forEach(j => {
+ starters.add(j);
+ });
+ });
+ // Iterative DFS to check for cycles
+ const nodesStack = Array.from(starters);
+ const nodesState = new Array(this._nodes.length).fill('white');
+ while (nodesStack.length > 0) {
+ const nodeIndex = nodesStack.pop();
+ // this node has now been processed completely. Mark this node 'black' to denote this.
+ if (nodesState[nodeIndex] === 'gray') {
+ nodesState[nodeIndex] = 'black';
+ }
+ else {
+ // this node is under processing stage. mark this node 'gray' to denote this.
+ nodesStack.push(nodeIndex);
+ nodesState[nodeIndex] = 'gray';
+ this._nodes[nodeIndex].outputs.forEach((outgoingEdgeIndex) => {
+ const data = this._allData[outgoingEdgeIndex];
+ if (typeof data.tensor !== 'undefined') {
+ throw new Error('node outputs should not be initialized');
+ }
+ if (data._from !== nodeIndex) {
+ throw new Error('from property of the Value object doesn\'t match index of Node being processed');
+ }
+ data._to.forEach((downstreamNodeIndex) => {
+ // back edge found - cyclic
+ if (nodesState[downstreamNodeIndex] === 'gray') {
+ throw new Error('model graph is cyclic');
+ }
+ // tree edge found - continue processing by adding it to stack
+ else if (nodesState[downstreamNodeIndex] === 'white') {
+ nodesStack.push(downstreamNodeIndex);
+ }
+ });
+ });
+ }
+ }
+ }
+ transformGraph(graphInitializer) {
+ // apply common transform
+ this.removeAllIdentityNodes();
+ this.removeAllDropoutNodes();
+ this.fuseConvActivationNodes();
+ // apply initializer specific transform
+ if (graphInitializer) {
+ graphInitializer.transformGraph(this);
+ }
+ // finalize graph
+ this.finalizeGraph();
+ }
+ /**
+ * finalize the graph.
+ *
+ * this function should be called after all the transformation completed.
+ * this function removes all unnecessary nodes and values from the graph
+ */
+ finalizeGraph() {
+ let offset = 0;
+ // delete all nodes that are not being executed
+ for (let i = 0; i < this._nodes.length; i++) {
+ if (!this._nodes[i].executeNode) {
+ // delete this node and shift all subsequent nodes up
+ offset++;
+ // delete all output values
+ this._nodes[i].outputs.forEach(ind => {
+ this._allData[ind]._from = -2;
+ });
+ this._nodes.splice(i, 1);
+ i--;
+ continue;
+ }
+ if (offset > 0) {
+ // update the value table
+ this._nodes[i].inputs.forEach(value => {
+ const ind = this._allData[value]._to.indexOf(i + offset);
+ if (ind !== -1) {
+ this._allData[value]._to[ind] = i;
+ }
+ });
+ this._nodes[i].outputs.forEach(value => {
+ if (this._allData[value]._from && this._allData[value]._from === i + offset) {
+ this._allData[value]._from = i;
+ }
+ });
+ }
+ }
+ offset = 0;
+ // delete all values that are not being referenced
+ for (let i = 0; i < this._allData.length; i++) {
+ // if current value is neither linked to next node, nor an output value, remove it.
+ if (this._allData[i].from === -2 && this._allOutputIndices.indexOf(i + offset) === -1) {
+ offset++;
+ this._allData.splice(i, 1);
+ i--;
+ continue;
+ }
+ if (offset > 0) {
+ let ind = -1;
+ // if current value is neither an input value nor an initializer, find the node it's
+ // coming from and update the corresponding node output
+ if (this._allData[i].from !== undefined && this._allData[i].from !== -1) {
+ ind = this._nodes[this._allData[i].from].outputs.indexOf(i + offset);
+ if (ind !== -1) {
+ this._nodes[this._allData[i].from].outputs[ind] = i;
+ }
+ }
+ else {
+ // if current value is an input value, update its reference in inputIndices
+ ind = this._allInputIndices.indexOf(i + offset);
+ if (ind !== -1) {
+ this._allInputIndices[ind] = i;
+ }
+ }
+ // find the node that the current value is linking to and update its input reference
+ this._allData[i].to.forEach(node => {
+ ind = this._nodes[node].inputs.indexOf(i + offset);
+ if (ind !== -1) {
+ this._nodes[node].inputs[ind] = i;
+ }
+ });
+ if (this._allData[i].to.length === 0) {
+ // if current value is a graph output, update its reference in outputIndices
+ ind = this._allOutputIndices.indexOf(i + offset);
+ if (ind !== -1) {
+ this._allOutputIndices[ind] = i;
+ }
+ }
+ }
+ }
+ }
+ /**
+ * Delete the specifed node. Assume the node has one incoming input and the first output connected to other nodes.
+ * An input validation must be done before calling this function.
+ * @param nodeIndex The index of node to be deleted
+ */
+ deleteNode(nodeIndex) {
+ const node = this._nodes[nodeIndex];
+ if (node.outputs.length > 1) {
+ for (let i = 1; i < node.outputs.length; i++) {
+ if (this._allData[node.outputs[i]].to.length > 0) {
+ throw new Error('Node deletion with more than one output connected to other nodes is not supported. ');
+ }
+ }
+ }
+ // this node wil not be executed
+ node.executeNode = false;
+ const inputValueIndex = node.inputs[0];
+ const outputValueIndex = node.outputs[0];
+ const nodesConsumingOutput = this._allData[outputValueIndex].to;
+ // remove this node from the to property of the input Value
+ const delIndex = this._allData[inputValueIndex].to.indexOf(nodeIndex);
+ // should not happen
+ if (delIndex === -1) {
+ throw new Error('The Value object doesn\'t have the current Node in it\'s \'to\' property ');
+ }
+ this._allData[inputValueIndex].to.splice(delIndex, 1);
+ // clear node indices consuming this output Value
+ this._allData[outputValueIndex]._to = [];
+ // if the output of this node is a graph output, adjust the index appropriately
+ const index = this._allOutputIndices.indexOf(outputValueIndex);
+ if (index !== -1) {
+ this._allOutputIndices[index] = inputValueIndex;
+ }
+ // override the inputs for nodes consuming this node's output with the input to this node
+ if (nodesConsumingOutput && nodesConsumingOutput.length > 0) {
+ for (const nodeIndex of nodesConsumingOutput) {
+ const replaceIndex = this._nodes[nodeIndex].inputs.indexOf(outputValueIndex);
+ // should not happen
+ if (replaceIndex === -1) {
+ throw new Error('The Node object doesn\'t have the output Value in it\'s \'inputs\' property ');
+ }
+ this._nodes[nodeIndex].inputs[replaceIndex] = inputValueIndex;
+ this._allData[inputValueIndex].to.push(nodeIndex);
+ }
+ }
+ }
+ removeAllDropoutNodes() {
+ let nodeIndex = 0;
+ for (const node of this._nodes) {
+ // weed out 'Dropout' nodes so that no time is wasted in execution
+ if (node.opType === 'Dropout') {
+ // the node should have exactly 1 input and 1 or 2 outputs
+ if (node.inputs.length !== 1) {
+ throw new Error('Dropout nodes should only contain one input. ');
+ }
+ if (node.outputs.length !== 1 && node.outputs.length !== 2) {
+ throw new Error('Dropout nodes should contain either 1 or 2 output(s)');
+ }
+ // the second output should not be referenced by any other node
+ if (node.outputs.length === 2 && this._allData[node.outputs[1]]._to.length !== 0) {
+ throw new Error('Dropout nodes\'s second output should not be referenced by other nodes');
+ }
+ this.deleteNode(nodeIndex);
+ }
+ nodeIndex++;
+ }
+ }
+ removeAllIdentityNodes() {
+ let nodeIndex = 0;
+ for (const node of this._nodes) {
+ // weed out 'Identity' nodes so that no time is wasted in execution
+ if (node.opType === 'Identity') {
+ this.deleteNode(nodeIndex);
+ }
+ nodeIndex++;
+ }
+ }
+ isActivation(n) {
+ switch (n.opType) {
+ // TODO: add other activation methods
+ case 'Relu':
+ case 'Sigmoid':
+ case 'Clip':
+ return true;
+ default:
+ return false;
+ }
+ }
+ fuseConvActivationNodes() {
+ for (const node of this._nodes) {
+ if (node.opType === 'Conv') {
+ const next = this._allData[node.outputs[0]]._to;
+ if (next.length === 1 && this.isActivation(this._nodes[next[0]])) {
+ const child = this._nodes[next[0]];
+ if (child.opType === 'Clip') {
+ if (child.inputs.length === 1) {
+ try {
+ node.attributes.set('activation_params', 'floats', [child.attributes.getFloat('min'), child.attributes.getFloat('max')]);
+ }
+ catch (e) {
+ node.attributes.set('activation_params', 'floats', [util_1.MIN_CLIP, util_1.MAX_CLIP]);
+ }
+ }
+ else if (child.inputs.length >= 3 && this._allData[child.inputs[1]].tensor !== undefined &&
+ this._allData[child.inputs[2]].tensor !== undefined) {
+ node.attributes.set('activation_params', 'floats', [
+ this._allData[child.inputs[1]].tensor.floatData[0], this._allData[child.inputs[2]].tensor.floatData[0]
+ ]);
+ }
+ else {
+ // Skip fusion with clip node since clip min and clip max are not coming from initializer
+ continue;
+ }
+ }
+ node.attributes.set('activation', 'string', (child.opType));
+ this.deleteNode(next[0]);
+ }
+ }
+ }
+ }
+}
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/instrument.ts":
+/*!**********************************!*\
+ !*** ./lib/onnxjs/instrument.ts ***!
+ \**********************************/
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.now = exports.Profiler = exports.Logger = void 0;
+class NoOpLoggerProvider {
+ log(_severity, _content, _category) {
+ // do nothing
+ }
+}
+class ConsoleLoggerProvider {
+ log(severity, content, category) {
+ // eslint-disable-next-line no-console
+ console.log(`${this.color(severity)} ${category ? '\x1b[35m' + category + '\x1b[0m ' : ''}${content}`);
+ }
+ color(severity) {
+ switch (severity) {
+ case 'verbose':
+ return '\x1b[34;40mv\x1b[0m';
+ case 'info':
+ return '\x1b[32mi\x1b[0m';
+ case 'warning':
+ return '\x1b[30;43mw\x1b[0m';
+ case 'error':
+ return '\x1b[31;40me\x1b[0m';
+ case 'fatal':
+ return '\x1b[101mf\x1b[0m';
+ default:
+ throw new Error(`unsupported severity: ${severity}`);
+ }
+ }
+}
+const SEVERITY_VALUE = {
+ verbose: 1000,
+ info: 2000,
+ warning: 4000,
+ error: 5000,
+ fatal: 6000
+};
+const LOGGER_PROVIDER_MAP = {
+ ['none']: new NoOpLoggerProvider(),
+ ['console']: new ConsoleLoggerProvider()
+};
+const LOGGER_DEFAULT_CONFIG = {
+ provider: 'console',
+ minimalSeverity: 'warning',
+ logDateTime: true,
+ logSourceLocation: false
+};
+let LOGGER_CONFIG_MAP = { ['']: LOGGER_DEFAULT_CONFIG };
+function log(arg0, arg1, arg2, arg3) {
+ if (arg1 === undefined) {
+ // log(category: string): Logger.CategorizedLogger;
+ return createCategorizedLogger(arg0);
+ }
+ else if (arg2 === undefined) {
+ // log(severity, content);
+ logInternal(arg0, arg1, 1);
+ }
+ else if (typeof arg2 === 'number' && arg3 === undefined) {
+ // log(severity, content, stack)
+ logInternal(arg0, arg1, arg2);
+ }
+ else if (typeof arg2 === 'string' && arg3 === undefined) {
+ // log(severity, category, content)
+ logInternal(arg0, arg2, 1, arg1);
+ }
+ else if (typeof arg2 === 'string' && typeof arg3 === 'number') {
+ // log(severity, category, content, stack)
+ logInternal(arg0, arg2, arg3, arg1);
+ }
+ else {
+ throw new TypeError('input is valid');
+ }
+}
+function createCategorizedLogger(category) {
+ return {
+ verbose: log.verbose.bind(null, category),
+ info: log.info.bind(null, category),
+ warning: log.warning.bind(null, category),
+ error: log.error.bind(null, category),
+ fatal: log.fatal.bind(null, category)
+ };
+}
+// NOTE: argument 'category' is put the last parameter beacause typescript
+// doesn't allow optional argument put in front of required argument. This
+// order is different from a usual logging API.
+function logInternal(severity, content, stack, category) {
+ const config = LOGGER_CONFIG_MAP[category || ''] || LOGGER_CONFIG_MAP[''];
+ if (SEVERITY_VALUE[severity] < SEVERITY_VALUE[config.minimalSeverity]) {
+ return;
+ }
+ if (config.logDateTime) {
+ content = `${new Date().toISOString()}|${content}`;
+ }
+ if (config.logSourceLocation) {
+ // TODO: calculate source location from 'stack'
+ }
+ LOGGER_PROVIDER_MAP[config.provider].log(severity, content, category);
+}
+// eslint-disable-next-line @typescript-eslint/no-namespace
+(function (log) {
+ function verbose(arg0, arg1) {
+ log('verbose', arg0, arg1);
+ }
+ log.verbose = verbose;
+ function info(arg0, arg1) {
+ log('info', arg0, arg1);
+ }
+ log.info = info;
+ function warning(arg0, arg1) {
+ log('warning', arg0, arg1);
+ }
+ log.warning = warning;
+ function error(arg0, arg1) {
+ log('error', arg0, arg1);
+ }
+ log.error = error;
+ function fatal(arg0, arg1) {
+ log('fatal', arg0, arg1);
+ }
+ log.fatal = fatal;
+ function reset(config) {
+ LOGGER_CONFIG_MAP = {};
+ set('', config || {});
+ }
+ log.reset = reset;
+ function set(category, config) {
+ if (category === '*') {
+ reset(config);
+ }
+ else {
+ const previousConfig = LOGGER_CONFIG_MAP[category] || LOGGER_DEFAULT_CONFIG;
+ LOGGER_CONFIG_MAP[category] = {
+ provider: config.provider || previousConfig.provider,
+ minimalSeverity: config.minimalSeverity || previousConfig.minimalSeverity,
+ logDateTime: (config.logDateTime === undefined) ? previousConfig.logDateTime : config.logDateTime,
+ logSourceLocation: (config.logSourceLocation === undefined) ? previousConfig.logSourceLocation :
+ config.logSourceLocation
+ };
+ }
+ // TODO: we want to support wildcard or regex?
+ }
+ log.set = set;
+ function setWithEnv(env) {
+ const config = {};
+ if (env.logLevel) {
+ config.minimalSeverity = env.logLevel;
+ }
+ set('', config);
+ }
+ log.setWithEnv = setWithEnv;
+})(log || (log = {}));
+// eslint-disable-next-line @typescript-eslint/no-redeclare, @typescript-eslint/naming-convention
+exports.Logger = log;
+// TODO
+// class WebGLEvent implements Profiler.Event {}
+class Event {
+ constructor(category, name, startTime, endCallback, timer, ctx) {
+ this.category = category;
+ this.name = name;
+ this.startTime = startTime;
+ this.endCallback = endCallback;
+ this.timer = timer;
+ this.ctx = ctx;
+ }
+ end() {
+ return this.endCallback(this);
+ }
+ async checkTimer() {
+ if (this.ctx === undefined || this.timer === undefined) {
+ throw new Error('No webgl timer found');
+ }
+ else {
+ this.ctx.endTimer();
+ return this.ctx.waitForQueryAndGetTime(this.timer);
+ }
+ }
+}
+class EventRecord {
+ constructor(category, name, startTime, endTime) {
+ this.category = category;
+ this.name = name;
+ this.startTime = startTime;
+ this.endTime = endTime;
+ }
+}
+class Profiler {
+ static create(config) {
+ if (config === undefined) {
+ return new this();
+ }
+ return new this(config.maxNumberEvents, config.flushBatchSize, config.flushIntervalInMilliseconds);
+ }
+ constructor(maxNumberEvents, flushBatchSize, flushIntervalInMilliseconds) {
+ this._started = false;
+ this._flushPointer = 0;
+ this._started = false;
+ this._maxNumberEvents = maxNumberEvents === undefined ? 10000 : maxNumberEvents;
+ this._flushBatchSize = flushBatchSize === undefined ? 10 : flushBatchSize;
+ this._flushIntervalInMilliseconds = flushIntervalInMilliseconds === undefined ? 5000 : flushIntervalInMilliseconds;
+ }
+ // start profiling
+ start() {
+ this._started = true;
+ this._timingEvents = [];
+ this._flushTime = (0, exports.now)();
+ this._flushPointer = 0;
+ }
+ // stop profiling
+ stop() {
+ this._started = false;
+ for (; this._flushPointer < this._timingEvents.length; this._flushPointer++) {
+ this.logOneEvent(this._timingEvents[this._flushPointer]);
+ }
+ }
+ event(category, name, func, ctx) {
+ const event = this._started ? this.begin(category, name, ctx) : undefined;
+ let isPromise = false;
+ const res = func();
+ // we consider a then-able object is a promise
+ if (res && typeof res.then === 'function') {
+ isPromise = true;
+ return new Promise((resolve, reject) => {
+ res
+ .then(async (value) => {
+ if (event) {
+ await event.end();
+ }
+ resolve(value);
+ }, async (reason) => {
+ if (event) {
+ await event.end();
+ }
+ reject(reason);
+ });
+ });
+ }
+ if (!isPromise && event) {
+ const eventRes = event.end();
+ if (eventRes && typeof eventRes.then === 'function') {
+ return new Promise((resolve, reject) => {
+ (eventRes).then(() => {
+ resolve(res);
+ }, (reason) => {
+ reject(reason);
+ });
+ });
+ }
+ }
+ return res;
+ }
+ // begin an event
+ begin(category, name, ctx) {
+ if (!this._started) {
+ throw new Error('profiler is not started yet');
+ }
+ if (ctx === undefined) {
+ const startTime = (0, exports.now)();
+ this.flush(startTime);
+ return new Event(category, name, startTime, e => this.endSync(e));
+ }
+ else {
+ const timer = ctx.beginTimer();
+ return new Event(category, name, 0, async (e) => this.end(e), timer, ctx);
+ }
+ }
+ // end the specific event
+ async end(event) {
+ const endTime = await event.checkTimer();
+ if (this._timingEvents.length < this._maxNumberEvents) {
+ this._timingEvents.push(new EventRecord(event.category, event.name, event.startTime, endTime));
+ this.flush(endTime);
+ }
+ }
+ endSync(event) {
+ const endTime = (0, exports.now)();
+ if (this._timingEvents.length < this._maxNumberEvents) {
+ this._timingEvents.push(new EventRecord(event.category, event.name, event.startTime, endTime));
+ this.flush(endTime);
+ }
+ }
+ logOneEvent(event) {
+ exports.Logger.verbose(`Profiler.${event.category}`, `${(event.endTime - event.startTime).toFixed(2)}ms on event '${event.name}' at ${event.endTime.toFixed(2)}`);
+ }
+ flush(currentTime) {
+ if (this._timingEvents.length - this._flushPointer >= this._flushBatchSize ||
+ currentTime - this._flushTime >= this._flushIntervalInMilliseconds) {
+ // should flush when either batch size accumlated or interval elepsed
+ for (const previousPointer = this._flushPointer; this._flushPointer < previousPointer + this._flushBatchSize &&
+ this._flushPointer < this._timingEvents.length; this._flushPointer++) {
+ this.logOneEvent(this._timingEvents[this._flushPointer]);
+ }
+ this._flushTime = (0, exports.now)();
+ }
+ }
+ get started() {
+ return this._started;
+ }
+}
+exports.Profiler = Profiler;
+/**
+ * returns a number to represent the current timestamp in a resolution as high as possible.
+ */
+exports.now = (typeof performance !== 'undefined' && performance.now) ? () => performance.now() : Date.now;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/model.ts":
+/*!*****************************!*\
+ !*** ./lib/onnxjs/model.ts ***!
+ \*****************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Model = void 0;
+const flatbuffers_1 = __webpack_require__(/*! flatbuffers */ "./node_modules/flatbuffers/js/flatbuffers.mjs");
+const onnx_proto_1 = __webpack_require__(/*! onnx-proto */ "./node_modules/onnx-proto/dist/onnx.js");
+const graph_1 = __webpack_require__(/*! ./graph */ "./lib/onnxjs/graph.ts");
+const ort_generated_1 = __webpack_require__(/*! ./ort-schema/ort-generated */ "./lib/onnxjs/ort-schema/ort-generated.ts");
+const util_1 = __webpack_require__(/*! ./util */ "./lib/onnxjs/util.ts");
+var ortFbs = ort_generated_1.onnxruntime.experimental.fbs;
+class Model {
+ // empty model
+ constructor() { }
+ load(buf, graphInitializer, isOrtFormat) {
+ if (!isOrtFormat) {
+ // isOrtFormat === false || isOrtFormat === undefined
+ try {
+ this.loadFromOnnxFormat(buf, graphInitializer);
+ return;
+ }
+ catch (e) {
+ if (isOrtFormat !== undefined) {
+ throw e;
+ }
+ }
+ }
+ this.loadFromOrtFormat(buf, graphInitializer);
+ }
+ loadFromOnnxFormat(buf, graphInitializer) {
+ const modelProto = onnx_proto_1.onnx.ModelProto.decode(buf);
+ const irVersion = util_1.LongUtil.longToNumber(modelProto.irVersion);
+ if (irVersion < 3) {
+ throw new Error('only support ONNX model with IR_VERSION>=3');
+ }
+ this._opsets =
+ modelProto.opsetImport.map(i => ({ domain: i.domain, version: util_1.LongUtil.longToNumber(i.version) }));
+ this._graph = graph_1.Graph.from(modelProto.graph, graphInitializer);
+ }
+ loadFromOrtFormat(buf, graphInitializer) {
+ const fb = new flatbuffers_1.flatbuffers.ByteBuffer(buf);
+ const ortModel = ortFbs.InferenceSession.getRootAsInferenceSession(fb).model();
+ const irVersion = util_1.LongUtil.longToNumber(ortModel.irVersion());
+ if (irVersion < 3) {
+ throw new Error('only support ONNX model with IR_VERSION>=3');
+ }
+ this._opsets = [];
+ for (let i = 0; i < ortModel.opsetImportLength(); i++) {
+ const opsetId = ortModel.opsetImport(i);
+ this._opsets.push({ domain: opsetId === null || opsetId === void 0 ? void 0 : opsetId.domain(), version: util_1.LongUtil.longToNumber(opsetId.version()) });
+ }
+ this._graph = graph_1.Graph.from(ortModel.graph(), graphInitializer);
+ }
+ get graph() {
+ return this._graph;
+ }
+ get opsets() {
+ return this._opsets;
+ }
+}
+exports.Model = Model;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/operators.ts":
+/*!*********************************!*\
+ !*** ./lib/onnxjs/operators.ts ***!
+ \*********************************/
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.FLOAT_TYPES = exports.INT_TYPES = exports.NUMBER_TYPES = void 0;
+exports.NUMBER_TYPES = ['float32', 'float64', 'int32', 'int16', 'int8', 'uint16', 'uint32', 'uint8'];
+exports.INT_TYPES = ['int32', 'int16', 'int8', 'uint16', 'uint32', 'uint8'];
+exports.FLOAT_TYPES = ['float32', 'float64'];
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/opset.ts":
+/*!*****************************!*\
+ !*** ./lib/onnxjs/opset.ts ***!
+ \*****************************/
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.resolveOperator = void 0;
+function resolveOperator(node, opsets, rules) {
+ for (const rule of rules) {
+ const opType = rule[0];
+ const domain = rule[1];
+ const versionSelector = rule[2];
+ const opImpl = rule[3];
+ const opInit = rule[4];
+ if (node.opType === opType) { // operator type matches
+ for (const opset of opsets) {
+ // opset '' and 'ai.onnx' are considered the same.
+ if (opset.domain === domain || (opset.domain === 'ai.onnx' && domain === '')) { // opset domain found
+ if (matchSelector(opset.version, versionSelector)) {
+ return { opImpl, opInit };
+ }
+ }
+ }
+ }
+ }
+ throw new TypeError(`cannot resolve operator '${node.opType}' with opsets: ${opsets.map(set => `${set.domain || 'ai.onnx'} v${set.version}`).join(', ')}`);
+}
+exports.resolveOperator = resolveOperator;
+function matchSelector(version, selector) {
+ if (selector.endsWith('+')) {
+ // minimum version match ('7+' expects version>=7)
+ const rangeStart = Number.parseInt(selector.substring(0, selector.length - 1), 10);
+ return !isNaN(rangeStart) && rangeStart <= version;
+ }
+ else if (selector.split('-').length === 2) {
+ // range match ('6-8' expects 6<=version<=8)
+ const pair = selector.split('-');
+ const rangeStart = Number.parseInt(pair[0], 10);
+ const rangeEnd = Number.parseInt(pair[1], 10);
+ return !isNaN(rangeStart) && !isNaN(rangeEnd) && rangeStart <= version && version <= rangeEnd;
+ }
+ else {
+ // exact match ('7' expects version===7)
+ return Number.parseInt(selector, 10) === version;
+ }
+}
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/ort-schema/ort-generated.ts":
+/*!************************************************!*\
+ !*** ./lib/onnxjs/ort-schema/ort-generated.ts ***!
+ \************************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// automatically generated by the FlatBuffers compiler, do not modify
+/* eslint-disable */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.onnxruntime = void 0;
+const flatbuffers_1 = __webpack_require__(/*! flatbuffers */ "./node_modules/flatbuffers/js/flatbuffers.mjs");
+/**
+ * @enum {number}
+ */
+var onnxruntime;
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ let AttributeType;
+ (function (AttributeType) {
+ AttributeType[AttributeType["UNDEFINED"] = 0] = "UNDEFINED";
+ AttributeType[AttributeType["FLOAT"] = 1] = "FLOAT";
+ AttributeType[AttributeType["INT"] = 2] = "INT";
+ AttributeType[AttributeType["STRING"] = 3] = "STRING";
+ AttributeType[AttributeType["TENSOR"] = 4] = "TENSOR";
+ AttributeType[AttributeType["GRAPH"] = 5] = "GRAPH";
+ AttributeType[AttributeType["FLOATS"] = 6] = "FLOATS";
+ AttributeType[AttributeType["INTS"] = 7] = "INTS";
+ AttributeType[AttributeType["STRINGS"] = 8] = "STRINGS";
+ AttributeType[AttributeType["TENSORS"] = 9] = "TENSORS";
+ AttributeType[AttributeType["GRAPHS"] = 10] = "GRAPHS";
+ AttributeType[AttributeType["SPARSE_TENSOR"] = 11] = "SPARSE_TENSOR";
+ AttributeType[AttributeType["SPARSE_TENSORS"] = 12] = "SPARSE_TENSORS";
+ })(AttributeType = fbs.AttributeType || (fbs.AttributeType = {}));
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @enum {number}
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ let DimensionValueType;
+ (function (DimensionValueType) {
+ DimensionValueType[DimensionValueType["UNKNOWN"] = 0] = "UNKNOWN";
+ DimensionValueType[DimensionValueType["VALUE"] = 1] = "VALUE";
+ DimensionValueType[DimensionValueType["PARAM"] = 2] = "PARAM";
+ })(DimensionValueType = fbs.DimensionValueType || (fbs.DimensionValueType = {}));
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @enum {number}
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ let TensorDataType;
+ (function (TensorDataType) {
+ TensorDataType[TensorDataType["UNDEFINED"] = 0] = "UNDEFINED";
+ TensorDataType[TensorDataType["FLOAT"] = 1] = "FLOAT";
+ TensorDataType[TensorDataType["UINT8"] = 2] = "UINT8";
+ TensorDataType[TensorDataType["INT8"] = 3] = "INT8";
+ TensorDataType[TensorDataType["UINT16"] = 4] = "UINT16";
+ TensorDataType[TensorDataType["INT16"] = 5] = "INT16";
+ TensorDataType[TensorDataType["INT32"] = 6] = "INT32";
+ TensorDataType[TensorDataType["INT64"] = 7] = "INT64";
+ TensorDataType[TensorDataType["STRING"] = 8] = "STRING";
+ TensorDataType[TensorDataType["BOOL"] = 9] = "BOOL";
+ TensorDataType[TensorDataType["FLOAT16"] = 10] = "FLOAT16";
+ TensorDataType[TensorDataType["DOUBLE"] = 11] = "DOUBLE";
+ TensorDataType[TensorDataType["UINT32"] = 12] = "UINT32";
+ TensorDataType[TensorDataType["UINT64"] = 13] = "UINT64";
+ TensorDataType[TensorDataType["COMPLEX64"] = 14] = "COMPLEX64";
+ TensorDataType[TensorDataType["COMPLEX128"] = 15] = "COMPLEX128";
+ TensorDataType[TensorDataType["BFLOAT16"] = 16] = "BFLOAT16";
+ })(TensorDataType = fbs.TensorDataType || (fbs.TensorDataType = {}));
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @enum {number}
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ let NodeType;
+ (function (NodeType) {
+ NodeType[NodeType["Primitive"] = 0] = "Primitive";
+ NodeType[NodeType["Fused"] = 1] = "Fused";
+ })(NodeType = fbs.NodeType || (fbs.NodeType = {}));
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @enum {number}
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ let TypeInfoValue;
+ (function (TypeInfoValue) {
+ TypeInfoValue[TypeInfoValue["NONE"] = 0] = "NONE";
+ TypeInfoValue[TypeInfoValue["tensor_type"] = 1] = "tensor_type";
+ TypeInfoValue[TypeInfoValue["sequence_type"] = 2] = "sequence_type";
+ TypeInfoValue[TypeInfoValue["map_type"] = 3] = "map_type";
+ })(TypeInfoValue = fbs.TypeInfoValue || (fbs.TypeInfoValue = {}));
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class Shape {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns Shape
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param Shape= obj
+ * @returns Shape
+ */
+ static getRootAsShape(bb, obj) {
+ return (obj || new Shape()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param Shape= obj
+ * @returns Shape
+ */
+ static getSizePrefixedRootAsShape(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Shape()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param number index
+ * @param onnxruntime.experimental.fbs.Dimension= obj
+ * @returns onnxruntime.experimental.fbs.Dimension
+ */
+ dim(index, obj) {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? (obj || new onnxruntime.experimental.fbs.Dimension())
+ .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
+ null;
+ }
+ /**
+ * @returns number
+ */
+ dimLength() {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startShape(builder) {
+ builder.startObject(1);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset dimOffset
+ */
+ static addDim(builder, dimOffset) {
+ builder.addFieldOffset(0, dimOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Offset> data
+ * @returns flatbuffers.Offset
+ */
+ static createDimVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startDimVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endShape(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ static createShape(builder, dimOffset) {
+ Shape.startShape(builder);
+ Shape.addDim(builder, dimOffset);
+ return Shape.endShape(builder);
+ }
+ }
+ fbs.Shape = Shape;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class Dimension {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns Dimension
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param Dimension= obj
+ * @returns Dimension
+ */
+ static getRootAsDimension(bb, obj) {
+ return (obj || new Dimension()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param Dimension= obj
+ * @returns Dimension
+ */
+ static getSizePrefixedRootAsDimension(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Dimension()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param onnxruntime.experimental.fbs.DimensionValue= obj
+ * @returns onnxruntime.experimental.fbs.DimensionValue|null
+ */
+ value(obj) {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? (obj || new onnxruntime.experimental.fbs.DimensionValue())
+ .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
+ null;
+ }
+ denotation(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startDimension(builder) {
+ builder.startObject(2);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset valueOffset
+ */
+ static addValue(builder, valueOffset) {
+ builder.addFieldOffset(0, valueOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset denotationOffset
+ */
+ static addDenotation(builder, denotationOffset) {
+ builder.addFieldOffset(1, denotationOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endDimension(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ static createDimension(builder, valueOffset, denotationOffset) {
+ Dimension.startDimension(builder);
+ Dimension.addValue(builder, valueOffset);
+ Dimension.addDenotation(builder, denotationOffset);
+ return Dimension.endDimension(builder);
+ }
+ }
+ fbs.Dimension = Dimension;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class DimensionValue {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns DimensionValue
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param DimensionValue= obj
+ * @returns DimensionValue
+ */
+ static getRootAsDimensionValue(bb, obj) {
+ return (obj || new DimensionValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param DimensionValue= obj
+ * @returns DimensionValue
+ */
+ static getSizePrefixedRootAsDimensionValue(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new DimensionValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @returns onnxruntime.experimental.fbs.DimensionValueType
+ */
+ dimType() {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? /** */ (this.bb.readInt8(this.bb_pos + offset)) :
+ onnxruntime.experimental.fbs.DimensionValueType.UNKNOWN;
+ }
+ /**
+ * @returns flatbuffers.Long
+ */
+ dimValue() {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
+ }
+ dimParam(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startDimensionValue(builder) {
+ builder.startObject(3);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param onnxruntime.experimental.fbs.DimensionValueType dimType
+ */
+ static addDimType(builder, dimType) {
+ builder.addFieldInt8(0, dimType, onnxruntime.experimental.fbs.DimensionValueType.UNKNOWN);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Long dimValue
+ */
+ static addDimValue(builder, dimValue) {
+ builder.addFieldInt64(1, dimValue, builder.createLong(0, 0));
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset dimParamOffset
+ */
+ static addDimParam(builder, dimParamOffset) {
+ builder.addFieldOffset(2, dimParamOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endDimensionValue(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ static createDimensionValue(builder, dimType, dimValue, dimParamOffset) {
+ DimensionValue.startDimensionValue(builder);
+ DimensionValue.addDimType(builder, dimType);
+ DimensionValue.addDimValue(builder, dimValue);
+ DimensionValue.addDimParam(builder, dimParamOffset);
+ return DimensionValue.endDimensionValue(builder);
+ }
+ }
+ fbs.DimensionValue = DimensionValue;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class TensorTypeAndShape {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns TensorTypeAndShape
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param TensorTypeAndShape= obj
+ * @returns TensorTypeAndShape
+ */
+ static getRootAsTensorTypeAndShape(bb, obj) {
+ return (obj || new TensorTypeAndShape()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param TensorTypeAndShape= obj
+ * @returns TensorTypeAndShape
+ */
+ static getSizePrefixedRootAsTensorTypeAndShape(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new TensorTypeAndShape()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @returns onnxruntime.experimental.fbs.TensorDataType
+ */
+ elemType() {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? /** */ (this.bb.readInt32(this.bb_pos + offset)) :
+ onnxruntime.experimental.fbs.TensorDataType.UNDEFINED;
+ }
+ /**
+ * @param onnxruntime.experimental.fbs.Shape= obj
+ * @returns onnxruntime.experimental.fbs.Shape|null
+ */
+ shape(obj) {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? (obj || new onnxruntime.experimental.fbs.Shape())
+ .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
+ null;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startTensorTypeAndShape(builder) {
+ builder.startObject(2);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param onnxruntime.experimental.fbs.TensorDataType elemType
+ */
+ static addElemType(builder, elemType) {
+ builder.addFieldInt32(0, elemType, onnxruntime.experimental.fbs.TensorDataType.UNDEFINED);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset shapeOffset
+ */
+ static addShape(builder, shapeOffset) {
+ builder.addFieldOffset(1, shapeOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endTensorTypeAndShape(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ static createTensorTypeAndShape(builder, elemType, shapeOffset) {
+ TensorTypeAndShape.startTensorTypeAndShape(builder);
+ TensorTypeAndShape.addElemType(builder, elemType);
+ TensorTypeAndShape.addShape(builder, shapeOffset);
+ return TensorTypeAndShape.endTensorTypeAndShape(builder);
+ }
+ }
+ fbs.TensorTypeAndShape = TensorTypeAndShape;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class MapType {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns MapType
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param MapType= obj
+ * @returns MapType
+ */
+ static getRootAsMapType(bb, obj) {
+ return (obj || new MapType()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param MapType= obj
+ * @returns MapType
+ */
+ static getSizePrefixedRootAsMapType(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new MapType()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @returns onnxruntime.experimental.fbs.TensorDataType
+ */
+ keyType() {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? /** */ (this.bb.readInt32(this.bb_pos + offset)) :
+ onnxruntime.experimental.fbs.TensorDataType.UNDEFINED;
+ }
+ /**
+ * @param onnxruntime.experimental.fbs.TypeInfo= obj
+ * @returns onnxruntime.experimental.fbs.TypeInfo|null
+ */
+ valueType(obj) {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? (obj || new onnxruntime.experimental.fbs.TypeInfo())
+ .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
+ null;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startMapType(builder) {
+ builder.startObject(2);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param onnxruntime.experimental.fbs.TensorDataType keyType
+ */
+ static addKeyType(builder, keyType) {
+ builder.addFieldInt32(0, keyType, onnxruntime.experimental.fbs.TensorDataType.UNDEFINED);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset valueTypeOffset
+ */
+ static addValueType(builder, valueTypeOffset) {
+ builder.addFieldOffset(1, valueTypeOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endMapType(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ static createMapType(builder, keyType, valueTypeOffset) {
+ MapType.startMapType(builder);
+ MapType.addKeyType(builder, keyType);
+ MapType.addValueType(builder, valueTypeOffset);
+ return MapType.endMapType(builder);
+ }
+ }
+ fbs.MapType = MapType;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class SequenceType {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns SequenceType
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param SequenceType= obj
+ * @returns SequenceType
+ */
+ static getRootAsSequenceType(bb, obj) {
+ return (obj || new SequenceType()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param SequenceType= obj
+ * @returns SequenceType
+ */
+ static getSizePrefixedRootAsSequenceType(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new SequenceType()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param onnxruntime.experimental.fbs.TypeInfo= obj
+ * @returns onnxruntime.experimental.fbs.TypeInfo|null
+ */
+ elemType(obj) {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? (obj || new onnxruntime.experimental.fbs.TypeInfo())
+ .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
+ null;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startSequenceType(builder) {
+ builder.startObject(1);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset elemTypeOffset
+ */
+ static addElemType(builder, elemTypeOffset) {
+ builder.addFieldOffset(0, elemTypeOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endSequenceType(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ static createSequenceType(builder, elemTypeOffset) {
+ SequenceType.startSequenceType(builder);
+ SequenceType.addElemType(builder, elemTypeOffset);
+ return SequenceType.endSequenceType(builder);
+ }
+ }
+ fbs.SequenceType = SequenceType;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class EdgeEnd {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns EdgeEnd
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @returns number
+ */
+ nodeIndex() {
+ return this.bb.readUint32(this.bb_pos);
+ }
+ /**
+ * @returns number
+ */
+ srcArgIndex() {
+ return this.bb.readInt32(this.bb_pos + 4);
+ }
+ /**
+ * @returns number
+ */
+ dstArgIndex() {
+ return this.bb.readInt32(this.bb_pos + 8);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number node_index
+ * @param number src_arg_index
+ * @param number dst_arg_index
+ * @returns flatbuffers.Offset
+ */
+ static createEdgeEnd(builder, node_index, src_arg_index, dst_arg_index) {
+ builder.prep(4, 12);
+ builder.writeInt32(dst_arg_index);
+ builder.writeInt32(src_arg_index);
+ builder.writeInt32(node_index);
+ return builder.offset();
+ }
+ }
+ fbs.EdgeEnd = EdgeEnd;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class NodeEdge {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns NodeEdge
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param NodeEdge= obj
+ * @returns NodeEdge
+ */
+ static getRootAsNodeEdge(bb, obj) {
+ return (obj || new NodeEdge()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param NodeEdge= obj
+ * @returns NodeEdge
+ */
+ static getSizePrefixedRootAsNodeEdge(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new NodeEdge()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @returns number
+ */
+ nodeIndex() {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param number index
+ * @param onnxruntime.experimental.fbs.EdgeEnd= obj
+ * @returns onnxruntime.experimental.fbs.EdgeEnd
+ */
+ inputEdges(index, obj) {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? (obj || new onnxruntime.experimental.fbs.EdgeEnd())
+ .__init(this.bb.__vector(this.bb_pos + offset) + index * 12, this.bb) :
+ null;
+ }
+ /**
+ * @returns number
+ */
+ inputEdgesLength() {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param number index
+ * @param onnxruntime.experimental.fbs.EdgeEnd= obj
+ * @returns onnxruntime.experimental.fbs.EdgeEnd
+ */
+ outputEdges(index, obj) {
+ let offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? (obj || new onnxruntime.experimental.fbs.EdgeEnd())
+ .__init(this.bb.__vector(this.bb_pos + offset) + index * 12, this.bb) :
+ null;
+ }
+ /**
+ * @returns number
+ */
+ outputEdgesLength() {
+ let offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startNodeEdge(builder) {
+ builder.startObject(3);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number nodeIndex
+ */
+ static addNodeIndex(builder, nodeIndex) {
+ builder.addFieldInt32(0, nodeIndex, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset inputEdgesOffset
+ */
+ static addInputEdges(builder, inputEdgesOffset) {
+ builder.addFieldOffset(1, inputEdgesOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startInputEdgesVector(builder, numElems) {
+ builder.startVector(12, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset outputEdgesOffset
+ */
+ static addOutputEdges(builder, outputEdgesOffset) {
+ builder.addFieldOffset(2, outputEdgesOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startOutputEdgesVector(builder, numElems) {
+ builder.startVector(12, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endNodeEdge(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ static createNodeEdge(builder, nodeIndex, inputEdgesOffset, outputEdgesOffset) {
+ NodeEdge.startNodeEdge(builder);
+ NodeEdge.addNodeIndex(builder, nodeIndex);
+ NodeEdge.addInputEdges(builder, inputEdgesOffset);
+ NodeEdge.addOutputEdges(builder, outputEdgesOffset);
+ return NodeEdge.endNodeEdge(builder);
+ }
+ }
+ fbs.NodeEdge = NodeEdge;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class Node {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns Node
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param Node= obj
+ * @returns Node
+ */
+ static getRootAsNode(bb, obj) {
+ return (obj || new Node()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param Node= obj
+ * @returns Node
+ */
+ static getSizePrefixedRootAsNode(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Node()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ name(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ docString(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ domain(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ /**
+ * @returns number
+ */
+ sinceVersion() {
+ let offset = this.bb.__offset(this.bb_pos, 10);
+ return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @returns number
+ */
+ index() {
+ let offset = this.bb.__offset(this.bb_pos, 12);
+ return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
+ }
+ opType(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 14);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ /**
+ * @returns onnxruntime.experimental.fbs.NodeType
+ */
+ type() {
+ let offset = this.bb.__offset(this.bb_pos, 16);
+ return offset ? /** */ (this.bb.readInt32(this.bb_pos + offset)) :
+ onnxruntime.experimental.fbs.NodeType.Primitive;
+ }
+ executionProviderType(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 18);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ inputs(index, optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 20);
+ return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
+ }
+ /**
+ * @returns number
+ */
+ inputsLength() {
+ let offset = this.bb.__offset(this.bb_pos, 20);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ outputs(index, optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 22);
+ return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
+ }
+ /**
+ * @returns number
+ */
+ outputsLength() {
+ let offset = this.bb.__offset(this.bb_pos, 22);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param number index
+ * @param onnxruntime.experimental.fbs.Attribute= obj
+ * @returns onnxruntime.experimental.fbs.Attribute
+ */
+ attributes(index, obj) {
+ let offset = this.bb.__offset(this.bb_pos, 24);
+ return offset ? (obj || new onnxruntime.experimental.fbs.Attribute())
+ .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
+ null;
+ }
+ /**
+ * @returns number
+ */
+ attributesLength() {
+ let offset = this.bb.__offset(this.bb_pos, 24);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param number index
+ * @returns number
+ */
+ inputArgCounts(index) {
+ let offset = this.bb.__offset(this.bb_pos, 26);
+ return offset ? this.bb.readInt32(this.bb.__vector(this.bb_pos + offset) + index * 4) : 0;
+ }
+ /**
+ * @returns number
+ */
+ inputArgCountsLength() {
+ let offset = this.bb.__offset(this.bb_pos, 26);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @returns Int32Array
+ */
+ inputArgCountsArray() {
+ let offset = this.bb.__offset(this.bb_pos, 26);
+ return offset ?
+ new Int32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) :
+ null;
+ }
+ implicitInputs(index, optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 28);
+ return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
+ }
+ /**
+ * @returns number
+ */
+ implicitInputsLength() {
+ let offset = this.bb.__offset(this.bb_pos, 28);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startNode(builder) {
+ builder.startObject(13);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset nameOffset
+ */
+ static addName(builder, nameOffset) {
+ builder.addFieldOffset(0, nameOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset docStringOffset
+ */
+ static addDocString(builder, docStringOffset) {
+ builder.addFieldOffset(1, docStringOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset domainOffset
+ */
+ static addDomain(builder, domainOffset) {
+ builder.addFieldOffset(2, domainOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number sinceVersion
+ */
+ static addSinceVersion(builder, sinceVersion) {
+ builder.addFieldInt32(3, sinceVersion, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number index
+ */
+ static addIndex(builder, index) {
+ builder.addFieldInt32(4, index, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset opTypeOffset
+ */
+ static addOpType(builder, opTypeOffset) {
+ builder.addFieldOffset(5, opTypeOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param onnxruntime.experimental.fbs.NodeType type
+ */
+ static addType(builder, type) {
+ builder.addFieldInt32(6, type, onnxruntime.experimental.fbs.NodeType.Primitive);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset executionProviderTypeOffset
+ */
+ static addExecutionProviderType(builder, executionProviderTypeOffset) {
+ builder.addFieldOffset(7, executionProviderTypeOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset inputsOffset
+ */
+ static addInputs(builder, inputsOffset) {
+ builder.addFieldOffset(8, inputsOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Offset> data
+ * @returns flatbuffers.Offset
+ */
+ static createInputsVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startInputsVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset outputsOffset
+ */
+ static addOutputs(builder, outputsOffset) {
+ builder.addFieldOffset(9, outputsOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Offset> data
+ * @returns flatbuffers.Offset
+ */
+ static createOutputsVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startOutputsVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset attributesOffset
+ */
+ static addAttributes(builder, attributesOffset) {
+ builder.addFieldOffset(10, attributesOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Offset> data
+ * @returns flatbuffers.Offset
+ */
+ static createAttributesVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startAttributesVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset inputArgCountsOffset
+ */
+ static addInputArgCounts(builder, inputArgCountsOffset) {
+ builder.addFieldOffset(11, inputArgCountsOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<number> data
+ * @returns flatbuffers.Offset
+ */
+ static createInputArgCountsVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt32(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startInputArgCountsVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset implicitInputsOffset
+ */
+ static addImplicitInputs(builder, implicitInputsOffset) {
+ builder.addFieldOffset(12, implicitInputsOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Offset> data
+ * @returns flatbuffers.Offset
+ */
+ static createImplicitInputsVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startImplicitInputsVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endNode(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ static createNode(builder, nameOffset, docStringOffset, domainOffset, sinceVersion, index, opTypeOffset, type, executionProviderTypeOffset, inputsOffset, outputsOffset, attributesOffset, inputArgCountsOffset, implicitInputsOffset) {
+ Node.startNode(builder);
+ Node.addName(builder, nameOffset);
+ Node.addDocString(builder, docStringOffset);
+ Node.addDomain(builder, domainOffset);
+ Node.addSinceVersion(builder, sinceVersion);
+ Node.addIndex(builder, index);
+ Node.addOpType(builder, opTypeOffset);
+ Node.addType(builder, type);
+ Node.addExecutionProviderType(builder, executionProviderTypeOffset);
+ Node.addInputs(builder, inputsOffset);
+ Node.addOutputs(builder, outputsOffset);
+ Node.addAttributes(builder, attributesOffset);
+ Node.addInputArgCounts(builder, inputArgCountsOffset);
+ Node.addImplicitInputs(builder, implicitInputsOffset);
+ return Node.endNode(builder);
+ }
+ }
+ fbs.Node = Node;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class ValueInfo {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns ValueInfo
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param ValueInfo= obj
+ * @returns ValueInfo
+ */
+ static getRootAsValueInfo(bb, obj) {
+ return (obj || new ValueInfo()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param ValueInfo= obj
+ * @returns ValueInfo
+ */
+ static getSizePrefixedRootAsValueInfo(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new ValueInfo()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ name(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ docString(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ /**
+ * @param onnxruntime.experimental.fbs.TypeInfo= obj
+ * @returns onnxruntime.experimental.fbs.TypeInfo|null
+ */
+ type(obj) {
+ let offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? (obj || new onnxruntime.experimental.fbs.TypeInfo())
+ .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
+ null;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startValueInfo(builder) {
+ builder.startObject(3);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset nameOffset
+ */
+ static addName(builder, nameOffset) {
+ builder.addFieldOffset(0, nameOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset docStringOffset
+ */
+ static addDocString(builder, docStringOffset) {
+ builder.addFieldOffset(1, docStringOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset typeOffset
+ */
+ static addType(builder, typeOffset) {
+ builder.addFieldOffset(2, typeOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endValueInfo(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ static createValueInfo(builder, nameOffset, docStringOffset, typeOffset) {
+ ValueInfo.startValueInfo(builder);
+ ValueInfo.addName(builder, nameOffset);
+ ValueInfo.addDocString(builder, docStringOffset);
+ ValueInfo.addType(builder, typeOffset);
+ return ValueInfo.endValueInfo(builder);
+ }
+ }
+ fbs.ValueInfo = ValueInfo;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class TypeInfo {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns TypeInfo
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param TypeInfo= obj
+ * @returns TypeInfo
+ */
+ static getRootAsTypeInfo(bb, obj) {
+ return (obj || new TypeInfo()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param TypeInfo= obj
+ * @returns TypeInfo
+ */
+ static getSizePrefixedRootAsTypeInfo(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new TypeInfo()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ denotation(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ /**
+ * @returns onnxruntime.experimental.fbs.TypeInfoValue
+ */
+ valueType() {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? /** */ (this.bb.readUint8(this.bb_pos + offset)) :
+ onnxruntime.experimental.fbs.TypeInfoValue.NONE;
+ }
+ /**
+ * @param flatbuffers.Table obj
+ * @returns ?flatbuffers.Table
+ */
+ value(obj) {
+ let offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.__union(obj, this.bb_pos + offset) : null;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startTypeInfo(builder) {
+ builder.startObject(3);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset denotationOffset
+ */
+ static addDenotation(builder, denotationOffset) {
+ builder.addFieldOffset(0, denotationOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param onnxruntime.experimental.fbs.TypeInfoValue valueType
+ */
+ static addValueType(builder, valueType) {
+ builder.addFieldInt8(1, valueType, onnxruntime.experimental.fbs.TypeInfoValue.NONE);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset valueOffset
+ */
+ static addValue(builder, valueOffset) {
+ builder.addFieldOffset(2, valueOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endTypeInfo(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ static createTypeInfo(builder, denotationOffset, valueType, valueOffset) {
+ TypeInfo.startTypeInfo(builder);
+ TypeInfo.addDenotation(builder, denotationOffset);
+ TypeInfo.addValueType(builder, valueType);
+ TypeInfo.addValue(builder, valueOffset);
+ return TypeInfo.endTypeInfo(builder);
+ }
+ }
+ fbs.TypeInfo = TypeInfo;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class OperatorSetId {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns OperatorSetId
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param OperatorSetId= obj
+ * @returns OperatorSetId
+ */
+ static getRootAsOperatorSetId(bb, obj) {
+ return (obj || new OperatorSetId()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param OperatorSetId= obj
+ * @returns OperatorSetId
+ */
+ static getSizePrefixedRootAsOperatorSetId(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new OperatorSetId()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ domain(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ /**
+ * @returns flatbuffers.Long
+ */
+ version() {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startOperatorSetId(builder) {
+ builder.startObject(2);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset domainOffset
+ */
+ static addDomain(builder, domainOffset) {
+ builder.addFieldOffset(0, domainOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Long version
+ */
+ static addVersion(builder, version) {
+ builder.addFieldInt64(1, version, builder.createLong(0, 0));
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endOperatorSetId(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ static createOperatorSetId(builder, domainOffset, version) {
+ OperatorSetId.startOperatorSetId(builder);
+ OperatorSetId.addDomain(builder, domainOffset);
+ OperatorSetId.addVersion(builder, version);
+ return OperatorSetId.endOperatorSetId(builder);
+ }
+ }
+ fbs.OperatorSetId = OperatorSetId;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class Tensor {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns Tensor
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param Tensor= obj
+ * @returns Tensor
+ */
+ static getRootAsTensor(bb, obj) {
+ return (obj || new Tensor()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param Tensor= obj
+ * @returns Tensor
+ */
+ static getSizePrefixedRootAsTensor(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Tensor()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ name(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ docString(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ /**
+ * @param number index
+ * @returns flatbuffers.Long
+ */
+ dims(index) {
+ let offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.readInt64(this.bb.__vector(this.bb_pos + offset) + index * 8) :
+ this.bb.createLong(0, 0);
+ }
+ /**
+ * @returns number
+ */
+ dimsLength() {
+ let offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @returns onnxruntime.experimental.fbs.TensorDataType
+ */
+ dataType() {
+ let offset = this.bb.__offset(this.bb_pos, 10);
+ return offset ? /** */ (this.bb.readInt32(this.bb_pos + offset)) :
+ onnxruntime.experimental.fbs.TensorDataType.UNDEFINED;
+ }
+ /**
+ * @param number index
+ * @returns number
+ */
+ rawData(index) {
+ let offset = this.bb.__offset(this.bb_pos, 12);
+ return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
+ }
+ /**
+ * @returns number
+ */
+ rawDataLength() {
+ let offset = this.bb.__offset(this.bb_pos, 12);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @returns Uint8Array
+ */
+ rawDataArray() {
+ let offset = this.bb.__offset(this.bb_pos, 12);
+ return offset ?
+ new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) :
+ null;
+ }
+ stringData(index, optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 14);
+ return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
+ }
+ /**
+ * @returns number
+ */
+ stringDataLength() {
+ let offset = this.bb.__offset(this.bb_pos, 14);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startTensor(builder) {
+ builder.startObject(6);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset nameOffset
+ */
+ static addName(builder, nameOffset) {
+ builder.addFieldOffset(0, nameOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset docStringOffset
+ */
+ static addDocString(builder, docStringOffset) {
+ builder.addFieldOffset(1, docStringOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset dimsOffset
+ */
+ static addDims(builder, dimsOffset) {
+ builder.addFieldOffset(2, dimsOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Long> data
+ * @returns flatbuffers.Offset
+ */
+ static createDimsVector(builder, data) {
+ builder.startVector(8, data.length, 8);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt64(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startDimsVector(builder, numElems) {
+ builder.startVector(8, numElems, 8);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param onnxruntime.experimental.fbs.TensorDataType dataType
+ */
+ static addDataType(builder, dataType) {
+ builder.addFieldInt32(3, dataType, onnxruntime.experimental.fbs.TensorDataType.UNDEFINED);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset rawDataOffset
+ */
+ static addRawData(builder, rawDataOffset) {
+ builder.addFieldOffset(4, rawDataOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<number> data
+ * @returns flatbuffers.Offset
+ */
+ static createRawDataVector(builder, data) {
+ builder.startVector(1, data.length, 1);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt8(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startRawDataVector(builder, numElems) {
+ builder.startVector(1, numElems, 1);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset stringDataOffset
+ */
+ static addStringData(builder, stringDataOffset) {
+ builder.addFieldOffset(5, stringDataOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Offset> data
+ * @returns flatbuffers.Offset
+ */
+ static createStringDataVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startStringDataVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endTensor(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ static createTensor(builder, nameOffset, docStringOffset, dimsOffset, dataType, rawDataOffset, stringDataOffset) {
+ Tensor.startTensor(builder);
+ Tensor.addName(builder, nameOffset);
+ Tensor.addDocString(builder, docStringOffset);
+ Tensor.addDims(builder, dimsOffset);
+ Tensor.addDataType(builder, dataType);
+ Tensor.addRawData(builder, rawDataOffset);
+ Tensor.addStringData(builder, stringDataOffset);
+ return Tensor.endTensor(builder);
+ }
+ }
+ fbs.Tensor = Tensor;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class SparseTensor {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns SparseTensor
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param SparseTensor= obj
+ * @returns SparseTensor
+ */
+ static getRootAsSparseTensor(bb, obj) {
+ return (obj || new SparseTensor()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param SparseTensor= obj
+ * @returns SparseTensor
+ */
+ static getSizePrefixedRootAsSparseTensor(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new SparseTensor()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param onnxruntime.experimental.fbs.Tensor= obj
+ * @returns onnxruntime.experimental.fbs.Tensor|null
+ */
+ values(obj) {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? (obj || new onnxruntime.experimental.fbs.Tensor())
+ .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
+ null;
+ }
+ /**
+ * @param onnxruntime.experimental.fbs.Tensor= obj
+ * @returns onnxruntime.experimental.fbs.Tensor|null
+ */
+ indices(obj) {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? (obj || new onnxruntime.experimental.fbs.Tensor())
+ .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
+ null;
+ }
+ /**
+ * @param number index
+ * @returns flatbuffers.Long
+ */
+ dims(index) {
+ let offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.readInt64(this.bb.__vector(this.bb_pos + offset) + index * 8) :
+ this.bb.createLong(0, 0);
+ }
+ /**
+ * @returns number
+ */
+ dimsLength() {
+ let offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startSparseTensor(builder) {
+ builder.startObject(3);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset valuesOffset
+ */
+ static addValues(builder, valuesOffset) {
+ builder.addFieldOffset(0, valuesOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset indicesOffset
+ */
+ static addIndices(builder, indicesOffset) {
+ builder.addFieldOffset(1, indicesOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset dimsOffset
+ */
+ static addDims(builder, dimsOffset) {
+ builder.addFieldOffset(2, dimsOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Long> data
+ * @returns flatbuffers.Offset
+ */
+ static createDimsVector(builder, data) {
+ builder.startVector(8, data.length, 8);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt64(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startDimsVector(builder, numElems) {
+ builder.startVector(8, numElems, 8);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endSparseTensor(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ static createSparseTensor(builder, valuesOffset, indicesOffset, dimsOffset) {
+ SparseTensor.startSparseTensor(builder);
+ SparseTensor.addValues(builder, valuesOffset);
+ SparseTensor.addIndices(builder, indicesOffset);
+ SparseTensor.addDims(builder, dimsOffset);
+ return SparseTensor.endSparseTensor(builder);
+ }
+ }
+ fbs.SparseTensor = SparseTensor;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class Attribute {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns Attribute
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param Attribute= obj
+ * @returns Attribute
+ */
+ static getRootAsAttribute(bb, obj) {
+ return (obj || new Attribute()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param Attribute= obj
+ * @returns Attribute
+ */
+ static getSizePrefixedRootAsAttribute(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Attribute()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ name(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ docString(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ /**
+ * @returns onnxruntime.experimental.fbs.AttributeType
+ */
+ type() {
+ let offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? /** */ (this.bb.readInt32(this.bb_pos + offset)) :
+ onnxruntime.experimental.fbs.AttributeType.UNDEFINED;
+ }
+ /**
+ * @returns number
+ */
+ f() {
+ let offset = this.bb.__offset(this.bb_pos, 10);
+ return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0;
+ }
+ /**
+ * @returns flatbuffers.Long
+ */
+ i() {
+ let offset = this.bb.__offset(this.bb_pos, 12);
+ return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
+ }
+ s(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 14);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ /**
+ * @param onnxruntime.experimental.fbs.Tensor= obj
+ * @returns onnxruntime.experimental.fbs.Tensor|null
+ */
+ t(obj) {
+ let offset = this.bb.__offset(this.bb_pos, 16);
+ return offset ? (obj || new onnxruntime.experimental.fbs.Tensor())
+ .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
+ null;
+ }
+ /**
+ * @param onnxruntime.experimental.fbs.Graph= obj
+ * @returns onnxruntime.experimental.fbs.Graph|null
+ */
+ g(obj) {
+ let offset = this.bb.__offset(this.bb_pos, 18);
+ return offset ? (obj || new onnxruntime.experimental.fbs.Graph())
+ .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
+ null;
+ }
+ /**
+ * @param number index
+ * @returns number
+ */
+ floats(index) {
+ let offset = this.bb.__offset(this.bb_pos, 20);
+ return offset ? this.bb.readFloat32(this.bb.__vector(this.bb_pos + offset) + index * 4) : 0;
+ }
+ /**
+ * @returns number
+ */
+ floatsLength() {
+ let offset = this.bb.__offset(this.bb_pos, 20);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @returns Float32Array
+ */
+ floatsArray() {
+ let offset = this.bb.__offset(this.bb_pos, 20);
+ return offset ?
+ new Float32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) :
+ null;
+ }
+ /**
+ * @param number index
+ * @returns flatbuffers.Long
+ */
+ ints(index) {
+ let offset = this.bb.__offset(this.bb_pos, 22);
+ return offset ? this.bb.readInt64(this.bb.__vector(this.bb_pos + offset) + index * 8) :
+ this.bb.createLong(0, 0);
+ }
+ /**
+ * @returns number
+ */
+ intsLength() {
+ let offset = this.bb.__offset(this.bb_pos, 22);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ strings(index, optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 24);
+ return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
+ }
+ /**
+ * @returns number
+ */
+ stringsLength() {
+ let offset = this.bb.__offset(this.bb_pos, 24);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param number index
+ * @param onnxruntime.experimental.fbs.Tensor= obj
+ * @returns onnxruntime.experimental.fbs.Tensor
+ */
+ tensors(index, obj) {
+ let offset = this.bb.__offset(this.bb_pos, 26);
+ return offset ? (obj || new onnxruntime.experimental.fbs.Tensor())
+ .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
+ null;
+ }
+ /**
+ * @returns number
+ */
+ tensorsLength() {
+ let offset = this.bb.__offset(this.bb_pos, 26);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param number index
+ * @param onnxruntime.experimental.fbs.Graph= obj
+ * @returns onnxruntime.experimental.fbs.Graph
+ */
+ graphs(index, obj) {
+ let offset = this.bb.__offset(this.bb_pos, 28);
+ return offset ? (obj || new onnxruntime.experimental.fbs.Graph())
+ .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
+ null;
+ }
+ /**
+ * @returns number
+ */
+ graphsLength() {
+ let offset = this.bb.__offset(this.bb_pos, 28);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startAttribute(builder) {
+ builder.startObject(13);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset nameOffset
+ */
+ static addName(builder, nameOffset) {
+ builder.addFieldOffset(0, nameOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset docStringOffset
+ */
+ static addDocString(builder, docStringOffset) {
+ builder.addFieldOffset(1, docStringOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param onnxruntime.experimental.fbs.AttributeType type
+ */
+ static addType(builder, type) {
+ builder.addFieldInt32(2, type, onnxruntime.experimental.fbs.AttributeType.UNDEFINED);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number f
+ */
+ static addF(builder, f) {
+ builder.addFieldFloat32(3, f, 0.0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Long i
+ */
+ static addI(builder, i) {
+ builder.addFieldInt64(4, i, builder.createLong(0, 0));
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset sOffset
+ */
+ static addS(builder, sOffset) {
+ builder.addFieldOffset(5, sOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset tOffset
+ */
+ static addT(builder, tOffset) {
+ builder.addFieldOffset(6, tOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset gOffset
+ */
+ static addG(builder, gOffset) {
+ builder.addFieldOffset(7, gOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset floatsOffset
+ */
+ static addFloats(builder, floatsOffset) {
+ builder.addFieldOffset(8, floatsOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<number> data
+ * @returns flatbuffers.Offset
+ */
+ static createFloatsVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addFloat32(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startFloatsVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset intsOffset
+ */
+ static addInts(builder, intsOffset) {
+ builder.addFieldOffset(9, intsOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Long> data
+ * @returns flatbuffers.Offset
+ */
+ static createIntsVector(builder, data) {
+ builder.startVector(8, data.length, 8);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt64(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startIntsVector(builder, numElems) {
+ builder.startVector(8, numElems, 8);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset stringsOffset
+ */
+ static addStrings(builder, stringsOffset) {
+ builder.addFieldOffset(10, stringsOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Offset> data
+ * @returns flatbuffers.Offset
+ */
+ static createStringsVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startStringsVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset tensorsOffset
+ */
+ static addTensors(builder, tensorsOffset) {
+ builder.addFieldOffset(11, tensorsOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Offset> data
+ * @returns flatbuffers.Offset
+ */
+ static createTensorsVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startTensorsVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset graphsOffset
+ */
+ static addGraphs(builder, graphsOffset) {
+ builder.addFieldOffset(12, graphsOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Offset> data
+ * @returns flatbuffers.Offset
+ */
+ static createGraphsVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startGraphsVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endAttribute(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ static createAttribute(builder, nameOffset, docStringOffset, type, f, i, sOffset, tOffset, gOffset, floatsOffset, intsOffset, stringsOffset, tensorsOffset, graphsOffset) {
+ Attribute.startAttribute(builder);
+ Attribute.addName(builder, nameOffset);
+ Attribute.addDocString(builder, docStringOffset);
+ Attribute.addType(builder, type);
+ Attribute.addF(builder, f);
+ Attribute.addI(builder, i);
+ Attribute.addS(builder, sOffset);
+ Attribute.addT(builder, tOffset);
+ Attribute.addG(builder, gOffset);
+ Attribute.addFloats(builder, floatsOffset);
+ Attribute.addInts(builder, intsOffset);
+ Attribute.addStrings(builder, stringsOffset);
+ Attribute.addTensors(builder, tensorsOffset);
+ Attribute.addGraphs(builder, graphsOffset);
+ return Attribute.endAttribute(builder);
+ }
+ }
+ fbs.Attribute = Attribute;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class Graph {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns Graph
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param Graph= obj
+ * @returns Graph
+ */
+ static getRootAsGraph(bb, obj) {
+ return (obj || new Graph()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param Graph= obj
+ * @returns Graph
+ */
+ static getSizePrefixedRootAsGraph(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Graph()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param number index
+ * @param onnxruntime.experimental.fbs.Tensor= obj
+ * @returns onnxruntime.experimental.fbs.Tensor
+ */
+ initializers(index, obj) {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? (obj || new onnxruntime.experimental.fbs.Tensor())
+ .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
+ null;
+ }
+ /**
+ * @returns number
+ */
+ initializersLength() {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param number index
+ * @param onnxruntime.experimental.fbs.ValueInfo= obj
+ * @returns onnxruntime.experimental.fbs.ValueInfo
+ */
+ nodeArgs(index, obj) {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? (obj || new onnxruntime.experimental.fbs.ValueInfo())
+ .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
+ null;
+ }
+ /**
+ * @returns number
+ */
+ nodeArgsLength() {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param number index
+ * @param onnxruntime.experimental.fbs.Node= obj
+ * @returns onnxruntime.experimental.fbs.Node
+ */
+ nodes(index, obj) {
+ let offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? (obj || new onnxruntime.experimental.fbs.Node())
+ .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
+ null;
+ }
+ /**
+ * @returns number
+ */
+ nodesLength() {
+ let offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @returns number
+ */
+ maxNodeIndex() {
+ let offset = this.bb.__offset(this.bb_pos, 10);
+ return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param number index
+ * @param onnxruntime.experimental.fbs.NodeEdge= obj
+ * @returns onnxruntime.experimental.fbs.NodeEdge
+ */
+ nodeEdges(index, obj) {
+ let offset = this.bb.__offset(this.bb_pos, 12);
+ return offset ? (obj || new onnxruntime.experimental.fbs.NodeEdge())
+ .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
+ null;
+ }
+ /**
+ * @returns number
+ */
+ nodeEdgesLength() {
+ let offset = this.bb.__offset(this.bb_pos, 12);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ inputs(index, optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 14);
+ return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
+ }
+ /**
+ * @returns number
+ */
+ inputsLength() {
+ let offset = this.bb.__offset(this.bb_pos, 14);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ outputs(index, optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 16);
+ return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
+ }
+ /**
+ * @returns number
+ */
+ outputsLength() {
+ let offset = this.bb.__offset(this.bb_pos, 16);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param number index
+ * @param onnxruntime.experimental.fbs.SparseTensor= obj
+ * @returns onnxruntime.experimental.fbs.SparseTensor
+ */
+ sparseInitializers(index, obj) {
+ let offset = this.bb.__offset(this.bb_pos, 18);
+ return offset ? (obj || new onnxruntime.experimental.fbs.SparseTensor())
+ .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
+ null;
+ }
+ /**
+ * @returns number
+ */
+ sparseInitializersLength() {
+ let offset = this.bb.__offset(this.bb_pos, 18);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startGraph(builder) {
+ builder.startObject(8);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset initializersOffset
+ */
+ static addInitializers(builder, initializersOffset) {
+ builder.addFieldOffset(0, initializersOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Offset> data
+ * @returns flatbuffers.Offset
+ */
+ static createInitializersVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startInitializersVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset nodeArgsOffset
+ */
+ static addNodeArgs(builder, nodeArgsOffset) {
+ builder.addFieldOffset(1, nodeArgsOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Offset> data
+ * @returns flatbuffers.Offset
+ */
+ static createNodeArgsVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startNodeArgsVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset nodesOffset
+ */
+ static addNodes(builder, nodesOffset) {
+ builder.addFieldOffset(2, nodesOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Offset> data
+ * @returns flatbuffers.Offset
+ */
+ static createNodesVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startNodesVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number maxNodeIndex
+ */
+ static addMaxNodeIndex(builder, maxNodeIndex) {
+ builder.addFieldInt32(3, maxNodeIndex, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset nodeEdgesOffset
+ */
+ static addNodeEdges(builder, nodeEdgesOffset) {
+ builder.addFieldOffset(4, nodeEdgesOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Offset> data
+ * @returns flatbuffers.Offset
+ */
+ static createNodeEdgesVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startNodeEdgesVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset inputsOffset
+ */
+ static addInputs(builder, inputsOffset) {
+ builder.addFieldOffset(5, inputsOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Offset> data
+ * @returns flatbuffers.Offset
+ */
+ static createInputsVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startInputsVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset outputsOffset
+ */
+ static addOutputs(builder, outputsOffset) {
+ builder.addFieldOffset(6, outputsOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Offset> data
+ * @returns flatbuffers.Offset
+ */
+ static createOutputsVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startOutputsVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset sparseInitializersOffset
+ */
+ static addSparseInitializers(builder, sparseInitializersOffset) {
+ builder.addFieldOffset(7, sparseInitializersOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Offset> data
+ * @returns flatbuffers.Offset
+ */
+ static createSparseInitializersVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startSparseInitializersVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endGraph(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ static createGraph(builder, initializersOffset, nodeArgsOffset, nodesOffset, maxNodeIndex, nodeEdgesOffset, inputsOffset, outputsOffset, sparseInitializersOffset) {
+ Graph.startGraph(builder);
+ Graph.addInitializers(builder, initializersOffset);
+ Graph.addNodeArgs(builder, nodeArgsOffset);
+ Graph.addNodes(builder, nodesOffset);
+ Graph.addMaxNodeIndex(builder, maxNodeIndex);
+ Graph.addNodeEdges(builder, nodeEdgesOffset);
+ Graph.addInputs(builder, inputsOffset);
+ Graph.addOutputs(builder, outputsOffset);
+ Graph.addSparseInitializers(builder, sparseInitializersOffset);
+ return Graph.endGraph(builder);
+ }
+ }
+ fbs.Graph = Graph;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class Model {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns Model
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param Model= obj
+ * @returns Model
+ */
+ static getRootAsModel(bb, obj) {
+ return (obj || new Model()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param Model= obj
+ * @returns Model
+ */
+ static getSizePrefixedRootAsModel(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Model()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @returns flatbuffers.Long
+ */
+ irVersion() {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
+ }
+ /**
+ * @param number index
+ * @param onnxruntime.experimental.fbs.OperatorSetId= obj
+ * @returns onnxruntime.experimental.fbs.OperatorSetId
+ */
+ opsetImport(index, obj) {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? (obj || new onnxruntime.experimental.fbs.OperatorSetId())
+ .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
+ null;
+ }
+ /**
+ * @returns number
+ */
+ opsetImportLength() {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ producerName(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ producerVersion(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 10);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ domain(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 12);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ /**
+ * @returns flatbuffers.Long
+ */
+ modelVersion() {
+ let offset = this.bb.__offset(this.bb_pos, 14);
+ return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
+ }
+ docString(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 16);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ /**
+ * @param onnxruntime.experimental.fbs.Graph= obj
+ * @returns onnxruntime.experimental.fbs.Graph|null
+ */
+ graph(obj) {
+ let offset = this.bb.__offset(this.bb_pos, 18);
+ return offset ? (obj || new onnxruntime.experimental.fbs.Graph())
+ .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
+ null;
+ }
+ graphDocString(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 20);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startModel(builder) {
+ builder.startObject(9);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Long irVersion
+ */
+ static addIrVersion(builder, irVersion) {
+ builder.addFieldInt64(0, irVersion, builder.createLong(0, 0));
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset opsetImportOffset
+ */
+ static addOpsetImport(builder, opsetImportOffset) {
+ builder.addFieldOffset(1, opsetImportOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Offset> data
+ * @returns flatbuffers.Offset
+ */
+ static createOpsetImportVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startOpsetImportVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset producerNameOffset
+ */
+ static addProducerName(builder, producerNameOffset) {
+ builder.addFieldOffset(2, producerNameOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset producerVersionOffset
+ */
+ static addProducerVersion(builder, producerVersionOffset) {
+ builder.addFieldOffset(3, producerVersionOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset domainOffset
+ */
+ static addDomain(builder, domainOffset) {
+ builder.addFieldOffset(4, domainOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Long modelVersion
+ */
+ static addModelVersion(builder, modelVersion) {
+ builder.addFieldInt64(5, modelVersion, builder.createLong(0, 0));
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset docStringOffset
+ */
+ static addDocString(builder, docStringOffset) {
+ builder.addFieldOffset(6, docStringOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset graphOffset
+ */
+ static addGraph(builder, graphOffset) {
+ builder.addFieldOffset(7, graphOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset graphDocStringOffset
+ */
+ static addGraphDocString(builder, graphDocStringOffset) {
+ builder.addFieldOffset(8, graphDocStringOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endModel(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ static createModel(builder, irVersion, opsetImportOffset, producerNameOffset, producerVersionOffset, domainOffset, modelVersion, docStringOffset, graphOffset, graphDocStringOffset) {
+ Model.startModel(builder);
+ Model.addIrVersion(builder, irVersion);
+ Model.addOpsetImport(builder, opsetImportOffset);
+ Model.addProducerName(builder, producerNameOffset);
+ Model.addProducerVersion(builder, producerVersionOffset);
+ Model.addDomain(builder, domainOffset);
+ Model.addModelVersion(builder, modelVersion);
+ Model.addDocString(builder, docStringOffset);
+ Model.addGraph(builder, graphOffset);
+ Model.addGraphDocString(builder, graphDocStringOffset);
+ return Model.endModel(builder);
+ }
+ }
+ fbs.Model = Model;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class KernelCreateInfos {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns KernelCreateInfos
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param KernelCreateInfos= obj
+ * @returns KernelCreateInfos
+ */
+ static getRootAsKernelCreateInfos(bb, obj) {
+ return (obj || new KernelCreateInfos()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param KernelCreateInfos= obj
+ * @returns KernelCreateInfos
+ */
+ static getSizePrefixedRootAsKernelCreateInfos(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new KernelCreateInfos()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param number index
+ * @returns number
+ */
+ nodeIndices(index) {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.readUint32(this.bb.__vector(this.bb_pos + offset) + index * 4) : 0;
+ }
+ /**
+ * @returns number
+ */
+ nodeIndicesLength() {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @returns Uint32Array
+ */
+ nodeIndicesArray() {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ?
+ new Uint32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) :
+ null;
+ }
+ /**
+ * @param number index
+ * @returns flatbuffers.Long
+ */
+ kernelDefHashes(index) {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.readUint64(this.bb.__vector(this.bb_pos + offset) + index * 8) :
+ this.bb.createLong(0, 0);
+ }
+ /**
+ * @returns number
+ */
+ kernelDefHashesLength() {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startKernelCreateInfos(builder) {
+ builder.startObject(2);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset nodeIndicesOffset
+ */
+ static addNodeIndices(builder, nodeIndicesOffset) {
+ builder.addFieldOffset(0, nodeIndicesOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<number> data
+ * @returns flatbuffers.Offset
+ */
+ static createNodeIndicesVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt32(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startNodeIndicesVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset kernelDefHashesOffset
+ */
+ static addKernelDefHashes(builder, kernelDefHashesOffset) {
+ builder.addFieldOffset(1, kernelDefHashesOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Long> data
+ * @returns flatbuffers.Offset
+ */
+ static createKernelDefHashesVector(builder, data) {
+ builder.startVector(8, data.length, 8);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt64(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startKernelDefHashesVector(builder, numElems) {
+ builder.startVector(8, numElems, 8);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endKernelCreateInfos(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ static createKernelCreateInfos(builder, nodeIndicesOffset, kernelDefHashesOffset) {
+ KernelCreateInfos.startKernelCreateInfos(builder);
+ KernelCreateInfos.addNodeIndices(builder, nodeIndicesOffset);
+ KernelCreateInfos.addKernelDefHashes(builder, kernelDefHashesOffset);
+ return KernelCreateInfos.endKernelCreateInfos(builder);
+ }
+ }
+ fbs.KernelCreateInfos = KernelCreateInfos;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class SubGraphSessionState {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns SubGraphSessionState
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param SubGraphSessionState= obj
+ * @returns SubGraphSessionState
+ */
+ static getRootAsSubGraphSessionState(bb, obj) {
+ return (obj || new SubGraphSessionState()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param SubGraphSessionState= obj
+ * @returns SubGraphSessionState
+ */
+ static getSizePrefixedRootAsSubGraphSessionState(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new SubGraphSessionState()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ graphId(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ /**
+ * @param onnxruntime.experimental.fbs.SessionState= obj
+ * @returns onnxruntime.experimental.fbs.SessionState|null
+ */
+ sessionState(obj) {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? (obj || new onnxruntime.experimental.fbs.SessionState())
+ .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
+ null;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startSubGraphSessionState(builder) {
+ builder.startObject(2);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset graphIdOffset
+ */
+ static addGraphId(builder, graphIdOffset) {
+ builder.addFieldOffset(0, graphIdOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset sessionStateOffset
+ */
+ static addSessionState(builder, sessionStateOffset) {
+ builder.addFieldOffset(1, sessionStateOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endSubGraphSessionState(builder) {
+ let offset = builder.endObject();
+ builder.requiredField(offset, 4); // graph_id
+ return offset;
+ }
+ static createSubGraphSessionState(builder, graphIdOffset, sessionStateOffset) {
+ SubGraphSessionState.startSubGraphSessionState(builder);
+ SubGraphSessionState.addGraphId(builder, graphIdOffset);
+ SubGraphSessionState.addSessionState(builder, sessionStateOffset);
+ return SubGraphSessionState.endSubGraphSessionState(builder);
+ }
+ }
+ fbs.SubGraphSessionState = SubGraphSessionState;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class SessionState {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns SessionState
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param SessionState= obj
+ * @returns SessionState
+ */
+ static getRootAsSessionState(bb, obj) {
+ return (obj || new SessionState()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param SessionState= obj
+ * @returns SessionState
+ */
+ static getSizePrefixedRootAsSessionState(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new SessionState()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param onnxruntime.experimental.fbs.KernelCreateInfos= obj
+ * @returns onnxruntime.experimental.fbs.KernelCreateInfos|null
+ */
+ kernels(obj) {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? (obj || new onnxruntime.experimental.fbs.KernelCreateInfos())
+ .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
+ null;
+ }
+ /**
+ * @param number index
+ * @param onnxruntime.experimental.fbs.SubGraphSessionState= obj
+ * @returns onnxruntime.experimental.fbs.SubGraphSessionState
+ */
+ subGraphSessionStates(index, obj) {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? (obj || new onnxruntime.experimental.fbs.SubGraphSessionState())
+ .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
+ null;
+ }
+ /**
+ * @returns number
+ */
+ subGraphSessionStatesLength() {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startSessionState(builder) {
+ builder.startObject(2);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset kernelsOffset
+ */
+ static addKernels(builder, kernelsOffset) {
+ builder.addFieldOffset(0, kernelsOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset subGraphSessionStatesOffset
+ */
+ static addSubGraphSessionStates(builder, subGraphSessionStatesOffset) {
+ builder.addFieldOffset(1, subGraphSessionStatesOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param Array.<flatbuffers.Offset> data
+ * @returns flatbuffers.Offset
+ */
+ static createSubGraphSessionStatesVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param number numElems
+ */
+ static startSubGraphSessionStatesVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endSessionState(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ static createSessionState(builder, kernelsOffset, subGraphSessionStatesOffset) {
+ SessionState.startSessionState(builder);
+ SessionState.addKernels(builder, kernelsOffset);
+ SessionState.addSubGraphSessionStates(builder, subGraphSessionStatesOffset);
+ return SessionState.endSessionState(builder);
+ }
+ }
+ fbs.SessionState = SessionState;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+/**
+ * @constructor
+ */
+(function (onnxruntime) {
+ var experimental;
+ (function (experimental) {
+ var fbs;
+ (function (fbs) {
+ class InferenceSession {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ /**
+ * @param number i
+ * @param flatbuffers.ByteBuffer bb
+ * @returns InferenceSession
+ */
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param InferenceSession= obj
+ * @returns InferenceSession
+ */
+ static getRootAsInferenceSession(bb, obj) {
+ return (obj || new InferenceSession()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @param InferenceSession= obj
+ * @returns InferenceSession
+ */
+ static getSizePrefixedRootAsInferenceSession(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new InferenceSession()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ /**
+ * @param flatbuffers.ByteBuffer bb
+ * @returns boolean
+ */
+ static bufferHasIdentifier(bb) {
+ return bb.__has_identifier('ORTM');
+ }
+ ortVersion(optionalEncoding) {
+ let offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ /**
+ * @param onnxruntime.experimental.fbs.Model= obj
+ * @returns onnxruntime.experimental.fbs.Model|null
+ */
+ model(obj) {
+ let offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? (obj || new onnxruntime.experimental.fbs.Model())
+ .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
+ null;
+ }
+ /**
+ * @param onnxruntime.experimental.fbs.SessionState= obj
+ * @returns onnxruntime.experimental.fbs.SessionState|null
+ */
+ sessionState(obj) {
+ let offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? (obj || new onnxruntime.experimental.fbs.SessionState())
+ .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
+ null;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ */
+ static startInferenceSession(builder) {
+ builder.startObject(3);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset ortVersionOffset
+ */
+ static addOrtVersion(builder, ortVersionOffset) {
+ builder.addFieldOffset(0, ortVersionOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset modelOffset
+ */
+ static addModel(builder, modelOffset) {
+ builder.addFieldOffset(1, modelOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset sessionStateOffset
+ */
+ static addSessionState(builder, sessionStateOffset) {
+ builder.addFieldOffset(2, sessionStateOffset, 0);
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @returns flatbuffers.Offset
+ */
+ static endInferenceSession(builder) {
+ let offset = builder.endObject();
+ return offset;
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset offset
+ */
+ static finishInferenceSessionBuffer(builder, offset) {
+ builder.finish(offset, 'ORTM');
+ }
+ /**
+ * @param flatbuffers.Builder builder
+ * @param flatbuffers.Offset offset
+ */
+ static finishSizePrefixedInferenceSessionBuffer(builder, offset) {
+ builder.finish(offset, 'ORTM', true);
+ }
+ static createInferenceSession(builder, ortVersionOffset, modelOffset, sessionStateOffset) {
+ InferenceSession.startInferenceSession(builder);
+ InferenceSession.addOrtVersion(builder, ortVersionOffset);
+ InferenceSession.addModel(builder, modelOffset);
+ InferenceSession.addSessionState(builder, sessionStateOffset);
+ return InferenceSession.endInferenceSession(builder);
+ }
+ }
+ fbs.InferenceSession = InferenceSession;
+ })(fbs = experimental.fbs || (experimental.fbs = {}));
+ })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
+})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/session-handler.ts":
+/*!***************************************!*\
+ !*** ./lib/onnxjs/session-handler.ts ***!
+ \***************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.OnnxjsSessionHandler = void 0;
+const onnxruntime_common_1 = __webpack_require__(/*! onnxruntime-common */ "../common/dist/lib/index.js");
+const tensor_1 = __webpack_require__(/*! ./tensor */ "./lib/onnxjs/tensor.ts");
+class OnnxjsSessionHandler {
+ constructor(session) {
+ this.session = session;
+ this.inputNames = this.session.inputNames;
+ this.outputNames = this.session.outputNames;
+ }
+ async dispose() { }
+ async run(feeds, _fetches, _options) {
+ const inputMap = new Map();
+ for (const name in feeds) {
+ if (Object.hasOwnProperty.call(feeds, name)) {
+ const feed = feeds[name];
+ inputMap.set(name, new tensor_1.Tensor(feed.dims, feed.type, undefined, undefined, feed.data));
+ }
+ }
+ const outputMap = await this.session.run(inputMap);
+ const output = {};
+ outputMap.forEach((tensor, name) => {
+ output[name] = new onnxruntime_common_1.Tensor(tensor.type, tensor.data, tensor.dims);
+ });
+ return output;
+ }
+ startProfiling() {
+ this.session.startProfiling();
+ }
+ endProfiling() {
+ this.session.endProfiling();
+ }
+}
+exports.OnnxjsSessionHandler = OnnxjsSessionHandler;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/session.ts":
+/*!*******************************!*\
+ !*** ./lib/onnxjs/session.ts ***!
+ \*******************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Session = void 0;
+const fs_1 = __webpack_require__(/*! fs */ "?6c45");
+const util_1 = __webpack_require__(/*! util */ "?b3a2");
+const backend_1 = __webpack_require__(/*! ./backend */ "./lib/onnxjs/backend.ts");
+const execution_plan_1 = __webpack_require__(/*! ./execution-plan */ "./lib/onnxjs/execution-plan.ts");
+const instrument_1 = __webpack_require__(/*! ./instrument */ "./lib/onnxjs/instrument.ts");
+const model_1 = __webpack_require__(/*! ./model */ "./lib/onnxjs/model.ts");
+class Session {
+ constructor(config = {}) {
+ this._initialized = false;
+ this.backendHint = config.backendHint;
+ this.profiler = instrument_1.Profiler.create(config.profiler);
+ this.context = { profiler: this.profiler, graphInputTypes: [], graphInputDims: [] };
+ }
+ get inputNames() {
+ return this._model.graph.getInputNames();
+ }
+ get outputNames() {
+ return this._model.graph.getOutputNames();
+ }
+ startProfiling() {
+ this.profiler.start();
+ }
+ endProfiling() {
+ this.profiler.stop();
+ }
+ async loadModel(arg, byteOffset, length) {
+ await this.profiler.event('session', 'Session.loadModel', async () => {
+ // resolve backend and session handler
+ const backend = await (0, backend_1.resolveBackend)(this.backendHint);
+ this.sessionHandler = backend.createSessionHandler(this.context);
+ this._model = new model_1.Model();
+ if (typeof arg === 'string') {
+ const isOrtFormat = arg.endsWith('.ort');
+ if (typeof fetch === 'undefined') {
+ // node
+ const buf = await (0, util_1.promisify)(fs_1.readFile)(arg);
+ this.initialize(buf, isOrtFormat);
+ }
+ else {
+ // browser
+ const response = await fetch(arg);
+ const buf = await response.arrayBuffer();
+ this.initialize(new Uint8Array(buf), isOrtFormat);
+ }
+ }
+ else if (!ArrayBuffer.isView(arg)) {
+ // load model from ArrayBuffer
+ const arr = new Uint8Array(arg, byteOffset || 0, length || arg.byteLength);
+ this.initialize(arr);
+ }
+ else {
+ // load model from Uint8array
+ this.initialize(arg);
+ }
+ });
+ }
+ initialize(modelProtoBlob, isOrtFormat) {
+ if (this._initialized) {
+ throw new Error('already initialized');
+ }
+ this.profiler.event('session', 'Session.initialize', () => {
+ // load graph
+ const graphInitializer = this.sessionHandler.transformGraph ? this.sessionHandler : undefined;
+ this._model.load(modelProtoBlob, graphInitializer, isOrtFormat);
+ // graph is completely initialzied at this stage , let the interested handlers know
+ if (this.sessionHandler.onGraphInitialized) {
+ this.sessionHandler.onGraphInitialized(this._model.graph);
+ }
+ // initialize each operator in the graph
+ this.initializeOps(this._model.graph);
+ // instantiate an ExecutionPlan object to be used by the Session object
+ this._executionPlan = new execution_plan_1.ExecutionPlan(this._model.graph, this._ops, this.profiler);
+ });
+ this._initialized = true;
+ }
+ async run(inputs) {
+ if (!this._initialized) {
+ throw new Error('session not initialized yet');
+ }
+ return this.profiler.event('session', 'Session.run', async () => {
+ const inputTensors = this.normalizeAndValidateInputs(inputs);
+ const outputTensors = await this._executionPlan.execute(this.sessionHandler, inputTensors);
+ return this.createOutput(outputTensors);
+ });
+ }
+ normalizeAndValidateInputs(inputs) {
+ const modelInputNames = this._model.graph.getInputNames();
+ // normalize inputs
+ // inputs: Tensor[]
+ if (Array.isArray(inputs)) {
+ if (inputs.length !== modelInputNames.length) {
+ throw new Error(`incorrect input array length: expected ${modelInputNames.length} but got ${inputs.length}`);
+ }
+ }
+ // convert map to array
+ // inputs: Map<string, Tensor>
+ else {
+ if (inputs.size !== modelInputNames.length) {
+ throw new Error(`incorrect input map size: expected ${modelInputNames.length} but got ${inputs.size}`);
+ }
+ const sortedInputs = new Array(inputs.size);
+ let sortedInputsIndex = 0;
+ for (let i = 0; i < modelInputNames.length; ++i) {
+ const tensor = inputs.get(modelInputNames[i]);
+ if (!tensor) {
+ throw new Error(`missing input tensor for: '${name}'`);
+ }
+ sortedInputs[sortedInputsIndex++] = tensor;
+ }
+ inputs = sortedInputs;
+ }
+ // validate dims requirements
+ // First session run - graph input data is not cached for the session
+ if (!this.context.graphInputTypes || this.context.graphInputTypes.length === 0 || !this.context.graphInputDims ||
+ this.context.graphInputDims.length === 0) {
+ const modelInputIndices = this._model.graph.getInputIndices();
+ const modelValues = this._model.graph.getValues();
+ const graphInputDims = new Array(modelInputIndices.length);
+ for (let i = 0; i < modelInputIndices.length; ++i) {
+ const graphInput = modelValues[modelInputIndices[i]];
+ graphInputDims[i] = graphInput.type.shape.dims;
+ // cached for second and subsequent runs.
+ // Some parts of the framework works on the assumption that the graph and types and shapes are static
+ this.context.graphInputTypes.push(graphInput.type.tensorType);
+ this.context.graphInputDims.push(inputs[i].dims);
+ }
+ this.validateInputTensorDims(graphInputDims, inputs, true);
+ }
+ // Second and subsequent session runs - graph input data is cached for the session
+ else {
+ this.validateInputTensorDims(this.context.graphInputDims, inputs, false);
+ }
+ // validate types requirement
+ this.validateInputTensorTypes(this.context.graphInputTypes, inputs);
+ return inputs;
+ }
+ validateInputTensorTypes(graphInputTypes, givenInputs) {
+ for (let i = 0; i < givenInputs.length; i++) {
+ const expectedType = graphInputTypes[i];
+ const actualType = givenInputs[i].type;
+ if (expectedType !== actualType) {
+ throw new Error(`input tensor[${i}] check failed: expected type '${expectedType}' but got ${actualType}`);
+ }
+ }
+ }
+ validateInputTensorDims(graphInputDims, givenInputs, noneDimSupported) {
+ for (let i = 0; i < givenInputs.length; i++) {
+ const expectedDims = graphInputDims[i];
+ const actualDims = givenInputs[i].dims;
+ if (!this.compareTensorDims(expectedDims, actualDims, noneDimSupported)) {
+ throw new Error(`input tensor[${i}] check failed: expected shape '[${expectedDims.join(',')}]' but got [${actualDims.join(',')}]`);
+ }
+ }
+ }
+ compareTensorDims(expectedDims, actualDims, noneDimSupported) {
+ if (expectedDims.length !== actualDims.length) {
+ return false;
+ }
+ for (let i = 0; i < expectedDims.length; ++i) {
+ if (expectedDims[i] !== actualDims[i] && (!noneDimSupported || expectedDims[i] !== 0)) {
+ // data shape mis-match AND not a 'None' dimension.
+ return false;
+ }
+ }
+ return true;
+ }
+ createOutput(outputTensors) {
+ const modelOutputNames = this._model.graph.getOutputNames();
+ if (outputTensors.length !== modelOutputNames.length) {
+ throw new Error('expected number of outputs do not match number of generated outputs');
+ }
+ const output = new Map();
+ for (let i = 0; i < modelOutputNames.length; ++i) {
+ output.set(modelOutputNames[i], outputTensors[i]);
+ }
+ return output;
+ }
+ initializeOps(graph) {
+ const nodes = graph.getNodes();
+ this._ops = new Array(nodes.length);
+ for (let i = 0; i < nodes.length; i++) {
+ this._ops[i] = this.sessionHandler.resolve(nodes[i], this._model.opsets, graph);
+ }
+ }
+}
+exports.Session = Session;
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/tensor.ts":
+/*!******************************!*\
+ !*** ./lib/onnxjs/tensor.ts ***!
+ \******************************/
+/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Tensor = void 0;
+const guid_typescript_1 = __webpack_require__(/*! guid-typescript */ "./node_modules/guid-typescript/dist/guid.js");
+const long_1 = __importDefault(__webpack_require__(/*! long */ "./node_modules/long/src/long.js"));
+const onnx_proto_1 = __webpack_require__(/*! onnx-proto */ "./node_modules/onnx-proto/dist/onnx.js");
+const ort_generated_1 = __webpack_require__(/*! ./ort-schema/ort-generated */ "./lib/onnxjs/ort-schema/ort-generated.ts");
+const util_1 = __webpack_require__(/*! ./util */ "./lib/onnxjs/util.ts");
+var ortFbs = ort_generated_1.onnxruntime.experimental.fbs;
+class Tensor {
+ /**
+ * get the underlying tensor data
+ */
+ get data() {
+ if (this.cache === undefined) {
+ const data = this.dataProvider(this.dataId);
+ if (data.length !== this.size) {
+ throw new Error('Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.');
+ }
+ this.cache = data;
+ }
+ return this.cache;
+ }
+ /**
+ * get the underlying string tensor data. Should only use when type is STRING
+ */
+ get stringData() {
+ if (this.type !== 'string') {
+ throw new TypeError('data type is not string');
+ }
+ return this.data;
+ }
+ /**
+ * get the underlying integer tensor data. Should only use when type is one of the following: (UINT8, INT8, UINT16,
+ * INT16, INT32, UINT32, BOOL)
+ */
+ get integerData() {
+ switch (this.type) {
+ case 'uint8':
+ case 'int8':
+ case 'uint16':
+ case 'int16':
+ case 'int32':
+ case 'uint32':
+ case 'bool':
+ return this.data;
+ default:
+ throw new TypeError('data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)');
+ }
+ }
+ /**
+ * get the underlying float tensor data. Should only use when type is one of the following: (FLOAT, DOUBLE)
+ */
+ get floatData() {
+ switch (this.type) {
+ case 'float32':
+ case 'float64':
+ return this.data;
+ default:
+ throw new TypeError('data type is not float (float32, float64)');
+ }
+ }
+ /**
+ * get the underlying number tensor data. Should only use when type is one of the following: (UINT8, INT8, UINT16,
+ * INT16, INT32, UINT32, BOOL, FLOAT, DOUBLE)
+ */
+ get numberData() {
+ if (this.type !== 'string') {
+ return this.data;
+ }
+ throw new TypeError('type cannot be non-number (string)');
+ }
+ /**
+ * get value of an element at the given indices
+ */
+ get(indices) {
+ return this.data[util_1.ShapeUtil.indicesToOffset(indices, this.strides)];
+ }
+ /**
+ * set value of an element at the given indices
+ */
+ set(indices, value) {
+ this.data[util_1.ShapeUtil.indicesToOffset(indices, this.strides)] = value;
+ }
+ /**
+ * get the underlying tensor data asynchronously
+ */
+ async getData() {
+ if (this.cache === undefined) {
+ this.cache = await this.asyncDataProvider(this.dataId);
+ }
+ return this.cache;
+ }
+ /**
+ * get the strides for each dimension
+ */
+ get strides() {
+ if (!this._strides) {
+ this._strides = util_1.ShapeUtil.computeStrides(this.dims);
+ }
+ return this._strides;
+ }
+ constructor(
+ /**
+ * get the dimensions of the tensor
+ */
+ dims,
+ /**
+ * get the type of the tensor
+ */
+ type, dataProvider, asyncDataProvider, cache,
+ /**
+ * get the data ID that used to map to a tensor data
+ */
+ dataId = guid_typescript_1.Guid.create()) {
+ this.dims = dims;
+ this.type = type;
+ this.dataProvider = dataProvider;
+ this.asyncDataProvider = asyncDataProvider;
+ this.cache = cache;
+ this.dataId = dataId;
+ this.size = util_1.ShapeUtil.validateDimsAndCalcSize(dims);
+ const size = this.size;
+ const empty = (dataProvider === undefined && asyncDataProvider === undefined && cache === undefined);
+ if (cache !== undefined) {
+ if (cache.length !== size) {
+ throw new RangeError('Input dims doesn\'t match data length.');
+ }
+ }
+ if (type === 'string') {
+ if (cache !== undefined && (!Array.isArray(cache) || !cache.every(i => typeof i === 'string'))) {
+ throw new TypeError('cache should be a string array');
+ }
+ if (empty) {
+ this.cache = new Array(size);
+ }
+ }
+ else {
+ if (cache !== undefined) {
+ const constructor = dataviewConstructor(type);
+ if (!(cache instanceof constructor)) {
+ throw new TypeError(`cache should be type ${constructor.name}`);
+ }
+ }
+ if (empty) {
+ const buf = new ArrayBuffer(size * sizeof(type));
+ this.cache = createView(buf, type);
+ }
+ }
+ }
+ /**
+ * Construct new Tensor from a ONNX Tensor object
+ * @param tensorProto the ONNX Tensor
+ */
+ static fromProto(tensorProto) {
+ if (!tensorProto) {
+ throw new Error('cannot construct Value from an empty tensor');
+ }
+ const type = util_1.ProtoUtil.tensorDataTypeFromProto(tensorProto.dataType);
+ const dims = util_1.ProtoUtil.tensorDimsFromProto(tensorProto.dims);
+ const value = new Tensor(dims, type);
+ if (type === 'string') {
+ // When it's STRING type, the value should always be stored in field
+ // 'stringData'
+ tensorProto.stringData.forEach((str, i) => {
+ value.data[i] = (0, util_1.decodeUtf8String)(str);
+ });
+ }
+ else if (tensorProto.rawData && typeof tensorProto.rawData.byteLength === 'number' &&
+ tensorProto.rawData.byteLength > 0) {
+ // NOT considering segment for now (IMPORTANT)
+ // populate value from rawData
+ const dataDest = value.data;
+ const dataSource = new DataView(tensorProto.rawData.buffer, tensorProto.rawData.byteOffset, tensorProto.rawData.byteLength);
+ const elementSize = sizeofProto(tensorProto.dataType);
+ const length = tensorProto.rawData.byteLength / elementSize;
+ if (tensorProto.rawData.byteLength % elementSize !== 0) {
+ throw new Error('invalid buffer length');
+ }
+ if (dataDest.length !== length) {
+ throw new Error('buffer length mismatch');
+ }
+ for (let i = 0; i < length; i++) {
+ const n = readProto(dataSource, tensorProto.dataType, i * elementSize);
+ dataDest[i] = n;
+ }
+ }
+ else {
+ // populate value from array
+ let array;
+ switch (tensorProto.dataType) {
+ case onnx_proto_1.onnx.TensorProto.DataType.FLOAT:
+ array = tensorProto.floatData;
+ break;
+ case onnx_proto_1.onnx.TensorProto.DataType.INT32:
+ case onnx_proto_1.onnx.TensorProto.DataType.INT16:
+ case onnx_proto_1.onnx.TensorProto.DataType.UINT16:
+ case onnx_proto_1.onnx.TensorProto.DataType.INT8:
+ case onnx_proto_1.onnx.TensorProto.DataType.UINT8:
+ case onnx_proto_1.onnx.TensorProto.DataType.BOOL:
+ array = tensorProto.int32Data;
+ break;
+ case onnx_proto_1.onnx.TensorProto.DataType.INT64:
+ array = tensorProto.int64Data;
+ break;
+ case onnx_proto_1.onnx.TensorProto.DataType.DOUBLE:
+ array = tensorProto.doubleData;
+ break;
+ case onnx_proto_1.onnx.TensorProto.DataType.UINT32:
+ case onnx_proto_1.onnx.TensorProto.DataType.UINT64:
+ array = tensorProto.uint64Data;
+ break;
+ default:
+ // should never run here
+ throw new Error('unspecific error');
+ }
+ if (array === null || array === undefined) {
+ throw new Error('failed to populate data from a tensorproto value');
+ }
+ const data = value.data;
+ if (data.length !== array.length) {
+ throw new Error('array length mismatch');
+ }
+ for (let i = 0; i < array.length; i++) {
+ const element = array[i];
+ if (long_1.default.isLong(element)) {
+ data[i] = longToNumber(element, tensorProto.dataType);
+ }
+ else {
+ data[i] = element;
+ }
+ }
+ }
+ return value;
+ }
+ /**
+ * Construct new Tensor from raw data
+ * @param data the raw data object. Should be a string array for 'string' tensor, and the corresponding typed array
+ * for other types of tensor.
+ * @param dims the dimensions of the tensor
+ * @param type the type of the tensor
+ */
+ static fromData(data, dims, type) {
+ return new Tensor(dims, type, undefined, undefined, data);
+ }
+ static fromOrtTensor(ortTensor) {
+ if (!ortTensor) {
+ throw new Error('cannot construct Value from an empty tensor');
+ }
+ const dims = util_1.ProtoUtil.tensorDimsFromORTFormat(ortTensor);
+ const type = util_1.ProtoUtil.tensorDataTypeFromProto(ortTensor.dataType());
+ const value = new Tensor(dims, type);
+ if (type === 'string') {
+ // When it's STRING type, the value should always be stored in field
+ // 'stringData'
+ for (let i = 0; i < ortTensor.stringDataLength(); i++) {
+ value.data[i] = ortTensor.stringData(i);
+ }
+ }
+ else if (ortTensor.rawDataArray() && typeof ortTensor.rawDataLength() === 'number' && ortTensor.rawDataLength() > 0) {
+ // NOT considering segment for now (IMPORTANT)
+ // populate value from rawData
+ const dataDest = value.data;
+ const dataSource = new DataView(ortTensor.rawDataArray().buffer, ortTensor.rawDataArray().byteOffset, ortTensor.rawDataLength());
+ const elementSize = sizeofProto(ortTensor.dataType());
+ const length = ortTensor.rawDataLength() / elementSize;
+ if (ortTensor.rawDataLength() % elementSize !== 0) {
+ throw new Error('invalid buffer length');
+ }
+ if (dataDest.length !== length) {
+ throw new Error('buffer length mismatch');
+ }
+ for (let i = 0; i < length; i++) {
+ const n = readProto(dataSource, ortTensor.dataType(), i * elementSize);
+ dataDest[i] = n;
+ }
+ }
+ return value;
+ }
+}
+exports.Tensor = Tensor;
+function sizeof(type) {
+ switch (type) {
+ case 'bool':
+ case 'int8':
+ case 'uint8':
+ return 1;
+ case 'int16':
+ case 'uint16':
+ return 2;
+ case 'int32':
+ case 'uint32':
+ case 'float32':
+ return 4;
+ case 'float64':
+ return 8;
+ default:
+ throw new Error(`cannot calculate sizeof() on type ${type}`);
+ }
+}
+function sizeofProto(type) {
+ switch (type) {
+ case onnx_proto_1.onnx.TensorProto.DataType.UINT8:
+ case onnx_proto_1.onnx.TensorProto.DataType.INT8:
+ case onnx_proto_1.onnx.TensorProto.DataType.BOOL:
+ return 1;
+ case onnx_proto_1.onnx.TensorProto.DataType.UINT16:
+ case onnx_proto_1.onnx.TensorProto.DataType.INT16:
+ return 2;
+ case onnx_proto_1.onnx.TensorProto.DataType.FLOAT:
+ case onnx_proto_1.onnx.TensorProto.DataType.INT32:
+ case onnx_proto_1.onnx.TensorProto.DataType.UINT32:
+ return 4;
+ case onnx_proto_1.onnx.TensorProto.DataType.INT64:
+ case onnx_proto_1.onnx.TensorProto.DataType.DOUBLE:
+ case onnx_proto_1.onnx.TensorProto.DataType.UINT64:
+ return 8;
+ default:
+ throw new Error(`cannot calculate sizeof() on type ${onnx_proto_1.onnx.TensorProto.DataType[type]}`);
+ }
+}
+function createView(dataBuffer, type) {
+ return new (dataviewConstructor(type))(dataBuffer);
+}
+function dataviewConstructor(type) {
+ switch (type) {
+ case 'bool':
+ case 'uint8':
+ return Uint8Array;
+ case 'int8':
+ return Int8Array;
+ case 'int16':
+ return Int16Array;
+ case 'uint16':
+ return Uint16Array;
+ case 'int32':
+ return Int32Array;
+ case 'uint32':
+ return Uint32Array;
+ case 'float32':
+ return Float32Array;
+ case 'float64':
+ return Float64Array;
+ default:
+ // should never run to here
+ throw new Error('unspecified error');
+ }
+}
+// convert a long number to a 32-bit integer (cast-down)
+function longToNumber(i, type) {
+ // INT64, UINT32, UINT64
+ if (type === onnx_proto_1.onnx.TensorProto.DataType.INT64 || type === ortFbs.TensorDataType.INT64) {
+ if (i.greaterThanOrEqual(2147483648) || i.lessThan(-2147483648)) {
+ throw new TypeError('int64 is not supported');
+ }
+ }
+ else if (type === onnx_proto_1.onnx.TensorProto.DataType.UINT32 || type === ortFbs.TensorDataType.UINT32 ||
+ type === onnx_proto_1.onnx.TensorProto.DataType.UINT64 || type === ortFbs.TensorDataType.UINT64) {
+ if (i.greaterThanOrEqual(4294967296) || i.lessThan(0)) {
+ throw new TypeError('uint64 is not supported');
+ }
+ }
+ else {
+ throw new TypeError(`not a LONG type: ${onnx_proto_1.onnx.TensorProto.DataType[type]}`);
+ }
+ return i.toNumber();
+}
+// read one value from TensorProto
+function readProto(view, type, byteOffset) {
+ switch (type) {
+ case onnx_proto_1.onnx.TensorProto.DataType.BOOL:
+ case onnx_proto_1.onnx.TensorProto.DataType.UINT8:
+ return view.getUint8(byteOffset);
+ case onnx_proto_1.onnx.TensorProto.DataType.INT8:
+ return view.getInt8(byteOffset);
+ case onnx_proto_1.onnx.TensorProto.DataType.UINT16:
+ return view.getUint16(byteOffset, true);
+ case onnx_proto_1.onnx.TensorProto.DataType.INT16:
+ return view.getInt16(byteOffset, true);
+ case onnx_proto_1.onnx.TensorProto.DataType.FLOAT:
+ return view.getFloat32(byteOffset, true);
+ case onnx_proto_1.onnx.TensorProto.DataType.INT32:
+ return view.getInt32(byteOffset, true);
+ case onnx_proto_1.onnx.TensorProto.DataType.UINT32:
+ return view.getUint32(byteOffset, true);
+ case onnx_proto_1.onnx.TensorProto.DataType.INT64:
+ return longToNumber(long_1.default.fromBits(view.getUint32(byteOffset, true), view.getUint32(byteOffset + 4, true), false), type);
+ case onnx_proto_1.onnx.TensorProto.DataType.DOUBLE:
+ return view.getFloat64(byteOffset, true);
+ case onnx_proto_1.onnx.TensorProto.DataType.UINT64:
+ return longToNumber(long_1.default.fromBits(view.getUint32(byteOffset, true), view.getUint32(byteOffset + 4, true), true), type);
+ default:
+ throw new Error(`cannot read from DataView for type ${onnx_proto_1.onnx.TensorProto.DataType[type]}`);
+ }
+}
+
+
+/***/ }),
+
+/***/ "./lib/onnxjs/util.ts":
+/*!****************************!*\
+ !*** ./lib/onnxjs/util.ts ***!
+ \****************************/
+/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.decodeUtf8String = exports.MAX_CLIP = exports.MIN_CLIP = exports.PoolConvUtil = exports.ReduceUtil = exports.SplitUtil = exports.MathUtil = exports.ShapeUtil = exports.LongUtil = exports.ProtoUtil = exports.GemmUtil = exports.arrayCopyHelper = exports.BroadcastUtil = exports.MatMulUtil = exports.ArrayUtil = exports.assert = exports.checkInputsShape = void 0;
+const flatbuffers_1 = __webpack_require__(/*! flatbuffers */ "./node_modules/flatbuffers/js/flatbuffers.mjs");
+const long_1 = __importDefault(__webpack_require__(/*! long */ "./node_modules/long/src/long.js"));
+const onnx_proto_1 = __webpack_require__(/*! onnx-proto */ "./node_modules/onnx-proto/dist/onnx.js");
+const tensor_1 = __webpack_require__(/*! ./tensor */ "./lib/onnxjs/tensor.ts");
+// check the inputs shape before running an OP.
+// return true when the inputs pass the check
+// return false when the inputs do not fit the requirement
+// throw exception when fatal error or not implemented
+function checkInputsShape(inputs, ...expectedDimensions) {
+ if (!inputs || inputs.length !== expectedDimensions.length) {
+ return false;
+ }
+ for (let i = 0; i < inputs.length; i++) {
+ if (!inputs[i].dims || inputs[i].dims.length !== expectedDimensions[i]) {
+ return false;
+ }
+ }
+ return true;
+}
+exports.checkInputsShape = checkInputsShape;
+// Evaluates the given expression and asserts error message if condition is unmet.
+function assert(expr, msg) {
+ if (!expr) {
+ throw new Error(typeof msg === 'string' ? msg : msg());
+ }
+}
+exports.assert = assert;
+class ArrayUtil {
+ /**
+ * Verifies if 2 input arrays contain the same elements.
+ * @param n1 Array 1
+ * @param n2 Array 2
+ * @returns Whether these 2 are equal
+ */
+ static arraysEqual(n1, n2) {
+ if (n1.length !== n2.length) {
+ return false;
+ }
+ for (let i = 0; i < n1.length; i++) {
+ if (n1[i] !== n2[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
+exports.ArrayUtil = ArrayUtil;
+class MatMulUtil {
+ /**
+ * Fix the input shapes for MatMul operation if they need fixing
+ * @param dimsA The shape of tensor A. Should be an array of positive integers
+ * @param dimsB The shape of tensor B. Should be an array of positive integers
+ * @returns A tuple containing the preprocessed input shapes as required by ONNX specifications
+ */
+ static preprocessInputShapes(dimsA, dimsB) {
+ // If the first argument is 1-D, it is promoted to a matrix by prepending
+ // a 1 to its dimensions. After matrix multiplication the prepended 1 is
+ // removed.
+ const a = (dimsA.length === 1) ? [1, dimsA[0]] : dimsA;
+ // If the second argument is 1-D, it is promoted to a matrix by appending
+ // a 1 to its dimensions. After matrix multiplication the appended 1 is
+ // removed.
+ const b = (dimsB.length === 1) ? [dimsB[0], 1] : dimsB;
+ return [a, b];
+ }
+ /**
+ * Fix the output shape computed for MatMul operation if it needs fixing
+ * @param outputShape The computed outputShape. Should be an array (atleast of length 2) of positive integers.
+ * This will be mutated.
+ * @param aRank The rank of tensor A.
+ * @param bRank The rank of tensor B.
+ */
+ static postprocessOutputShape(outputShape, aRank, bRank) {
+ // Remove prepended dimension if first input is 1d
+ if (aRank === 1) {
+ // outputShape = outputShape.slice(0, outputShape.length - 2).concat(outputShape.slice(outputShape.length - 1));
+ outputShape.splice(outputShape.length - 2, 1);
+ }
+ // Remove appended dimension if second input is 1d
+ if (bRank === 1) {
+ outputShape.pop();
+ }
+ }
+ /**
+ * Calculate the expected shape when matrix multiplication
+ * @param a The shape of tensor A. Should be a tuple of 2 positive integers
+ * @param b The shape of tensor B. Should be a tuple of 2 positive integers
+ * @returns The expected shape of the result, or undefined if N/A
+ */
+ static calcMatMulShape(a, b) {
+ return (a[1] !== b[0]) ? undefined : [a[0], b[1]];
+ }
+}
+exports.MatMulUtil = MatMulUtil;
+class BroadcastUtil {
+ /**
+ * Calculate the expected shape when broadcasting 2 tensors
+ * @param a The shape of tensor A. Should be an array of positive integers
+ * @param b The shape of tensor B. Should be an array of positive integers
+ * @param isMatMul Whether the operation is MatMul
+ * @returns The expected shape of the result, or undefined if N/A
+ */
+ static calcShape(adims, bdims, isMatMul = false) {
+ const arank = adims.length;
+ const brank = bdims.length;
+ if (arank === 0) {
+ return bdims;
+ }
+ if (brank === 0) {
+ return adims;
+ }
+ const crank = Math.max(adims.length, bdims.length);
+ const cdims = new Array(crank);
+ // calculate the last 2 dimension if it is MatMul
+ if (isMatMul) {
+ if (arank < 2 || brank < 2) {
+ return undefined;
+ }
+ const cShapeMatMul = MatMulUtil.calcMatMulShape([adims[arank - 2], adims[arank - 1]], [bdims[brank - 2], bdims[brank - 1]]);
+ if (cShapeMatMul === undefined) {
+ return undefined;
+ }
+ [cdims[crank - 2], cdims[crank - 1]] = cShapeMatMul;
+ }
+ for (let i = isMatMul ? 3 : 1; i <= crank; i++) {
+ const aLen = arank - i < 0 ? 1 : adims[arank - i];
+ const bLen = brank - i < 0 ? 1 : bdims[brank - i];
+ if (aLen !== bLen && aLen > 1 && bLen > 1) {
+ return undefined;
+ }
+ cdims[crank - i] = Math.max(aLen, bLen);
+ }
+ return cdims;
+ }
+ /**
+ * Given the indices of a broadcasted tensor, calculate the original indices
+ * @param broadcastedIndices The given indices of the broadcasted tensor.
+ * @param originalShape The original shape of the tensor before broadcas
+ * @returns The calculated indices that maps to the original tensor.
+ */
+ static index(broadcastedIndices, originalShape) {
+ // NOTE 1: we assume the parameter broadcastedIndices is valid. ie. it should have the same
+ // length as the broadcasted shape, and for each dimension the index should
+ // not be out of range.
+ const originalIndices = new Array(originalShape.length);
+ BroadcastUtil.fillIndex(broadcastedIndices, originalShape, originalIndices);
+ return originalIndices;
+ }
+ /**
+ * Given the indices of a broadcasted tensor, calculate the original indices
+ * @param broadcastedIndices The given indices of the broadcasted tensor.
+ * @param originalShape The original shape of the tensor before broadcast
+ * @param originalIndices The mapping of broadcastedIndices to the originalIndices (output parameter - will be
+ * mutated).
+ */
+ static fillIndex(broadcastedIndices, originalShape, originalIndices) {
+ // NOTE 1: we assume the parameter broadcastedIndices is valid. ie. it should have the same length as the
+ // broadcasted shape, and for each dimension the index should not be out of range.
+ // NOTE 2: we assume the parameter originalIndices has the same length as the originalShape
+ const dimOffset = broadcastedIndices.length - originalShape.length;
+ for (let i = 0; i < originalShape.length; i++) {
+ originalIndices[i] = broadcastedIndices[dimOffset + i] % originalShape[i];
+ }
+ }
+ /**
+ * Perform the broadcasting operation on the specific operator
+ * @param a The input tensor A
+ * @param b The input tensor B
+ * @param op The operator lambda function
+ * @param inplace Whether to write the result back to A.
+ * @returns The result tensor, or undefined if input not broadcastable.
+ */
+ static calc(a, b, op, inplace, resultType) {
+ const outputShape = BroadcastUtil.calcShape(a.dims, b.dims);
+ if (outputShape) {
+ if (inplace && !ShapeUtil.areEqual(outputShape, a.dims)) {
+ // B is not broadcastable to A, failed to calculate inplace.
+ return undefined;
+ }
+ const size = ShapeUtil.size(outputShape);
+ const c = inplace ? a : new tensor_1.Tensor(outputShape, resultType || a.type);
+ // both inputs are scalars
+ if (outputShape.length === 0) {
+ c.set([], op(a.get([]), b.get([])));
+ }
+ // atleast one input is a non-scalar
+ else {
+ const outputIndices = new Array(outputShape.length);
+ const originalIndicesA = new Array(a.dims.length);
+ const originalIndicesB = new Array(b.dims.length);
+ let valA = 0;
+ let valB = 0;
+ let isAScalar = false;
+ let isBScalar = false;
+ if (a.dims.length === 0) {
+ valA = a.get([]);
+ isAScalar = true;
+ }
+ if (b.dims.length === 0) {
+ valB = b.get([]);
+ isBScalar = true;
+ }
+ let rest;
+ for (let i = 0; i < size; i++) {
+ // traversal indices
+ rest = i;
+ for (let j = outputShape.length - 1; j >= 0; j--) {
+ outputIndices[j] = rest % outputShape[j];
+ rest = Math.floor(rest / outputShape[j]);
+ }
+ if (!isAScalar) {
+ // map outputIndices (which is actually broadcasted) to the originalIndices
+ BroadcastUtil.fillIndex(outputIndices, a.dims, originalIndicesA);
+ valA = a.get(originalIndicesA);
+ }
+ if (!isBScalar) {
+ BroadcastUtil.fillIndex(outputIndices, b.dims, originalIndicesB);
+ valB = b.get(originalIndicesB);
+ }
+ c.set(outputIndices, op(valA, valB));
+ }
+ }
+ return c;
+ }
+ return undefined;
+ }
+ /**
+ * Determine if a shape is unidirectional broadcastable to another shape
+ * @param shape The input shape
+ * @param finalShape The desired shape after broadcasting
+ */
+ static isValidBroadcast(shape, finalShape) {
+ // align shape to the right
+ const inputRank = shape.length;
+ const finalRank = finalShape.length;
+ if (inputRank > finalRank) {
+ return false;
+ }
+ for (let i = 1; i <= inputRank; i++) {
+ if (shape[inputRank - i] !== 1 && shape[inputRank - i] !== finalShape[finalRank - i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+ /**
+ * Determine the broadcasted dims in input shape based on the given output shape.
+ * Note that this function only returns the broadcasted dims.
+ * @param inputShape The input shape
+ * @param outputShape The output shape
+ * @returns The broadcasted dims in input shape.
+ */
+ static getBroadcastDims(inputShape, outputShape) {
+ const inRank = inputShape.length;
+ const dims = [];
+ for (let i = 0; i < inRank; i++) {
+ const dim = inRank - 1 - i;
+ const a = inputShape[dim] || 1;
+ const b = outputShape[outputShape.length - 1 - i] || 1;
+ if (b > 1 && a === 1) {
+ dims.unshift(dim);
+ }
+ }
+ return dims;
+ }
+}
+exports.BroadcastUtil = BroadcastUtil;
+// copy array helper
+// mimics memcpy as much as possible
+function arrayCopyHelper(target, source, targetIndex, sourceIndex, blockSize) {
+ if (sourceIndex < 0 || sourceIndex >= source.length) {
+ throw new Error('sourceIndex out of bounds');
+ }
+ if (targetIndex < 0 || targetIndex >= target.length) {
+ throw new Error('targetIndex out of bounds');
+ }
+ if (sourceIndex + blockSize > source.length) {
+ throw new Error('source indices to be copied are outside bounds');
+ }
+ if (targetIndex + blockSize > target.length) {
+ throw new Error('target array is too small to hold result');
+ }
+ for (let offset = 0; offset < blockSize; offset++) {
+ target[targetIndex + offset] = source[sourceIndex + offset];
+ }
+}
+exports.arrayCopyHelper = arrayCopyHelper;
+class GemmUtil {
+ // will make sure input shapes are compatible for this op
+ // and return back the shape of the output in the form of a tuple
+ // will throw exception if the input shapes are not compatible
+ static getShapeOfGemmResult(leftShape, transLeft, rightShape, transRight, biasShape) {
+ if (leftShape.length !== 2 || rightShape.length !== 2) {
+ throw new Error('shape need to be of size 2');
+ }
+ let M;
+ let K;
+ let N;
+ if (transLeft) {
+ M = leftShape[1];
+ K = leftShape[0];
+ }
+ else {
+ M = leftShape[0];
+ K = leftShape[1];
+ }
+ let kDim = -1;
+ if (transRight) {
+ N = rightShape[0];
+ kDim = 1;
+ }
+ else {
+ N = rightShape[1];
+ kDim = 0;
+ }
+ if (rightShape[kDim] !== K) {
+ throw new Error('dimension mismatch');
+ }
+ if (M <= 0 || N <= 0 || K <= 0) {
+ throw new Error('invalid shape specified');
+ }
+ if (biasShape && !BroadcastUtil.isValidBroadcast(biasShape, [M, N])) {
+ throw new Error('gemm: invalid bias shape for broadcast');
+ }
+ return [M, N, K];
+ }
+}
+exports.GemmUtil = GemmUtil;
+class ProtoUtil {
+ static tensorDataTypeFromProto(typeProto) {
+ switch (typeProto) {
+ case onnx_proto_1.onnx.TensorProto.DataType.INT8:
+ return 'int8';
+ case onnx_proto_1.onnx.TensorProto.DataType.UINT8:
+ return 'uint8';
+ case onnx_proto_1.onnx.TensorProto.DataType.BOOL:
+ return 'bool';
+ case onnx_proto_1.onnx.TensorProto.DataType.INT16:
+ return 'int16';
+ case onnx_proto_1.onnx.TensorProto.DataType.UINT16:
+ return 'uint16';
+ case onnx_proto_1.onnx.TensorProto.DataType.INT32:
+ return 'int32';
+ case onnx_proto_1.onnx.TensorProto.DataType.UINT32:
+ return 'uint32';
+ case onnx_proto_1.onnx.TensorProto.DataType.FLOAT:
+ return 'float32';
+ case onnx_proto_1.onnx.TensorProto.DataType.DOUBLE:
+ return 'float64';
+ case onnx_proto_1.onnx.TensorProto.DataType.STRING:
+ return 'string';
+ // For INT64/UINT64, reduce their value to 32-bits.
+ // Should throw exception when overflow
+ case onnx_proto_1.onnx.TensorProto.DataType.INT64:
+ return 'int32';
+ case onnx_proto_1.onnx.TensorProto.DataType.UINT64:
+ return 'uint32';
+ default:
+ throw new Error(`unsupported data type: ${onnx_proto_1.onnx.TensorProto.DataType[typeProto]}`);
+ }
+ }
+ static tensorDataTypeStringToEnum(type) {
+ switch (type) {
+ case 'int8':
+ return onnx_proto_1.onnx.TensorProto.DataType.INT8;
+ case 'uint8':
+ return onnx_proto_1.onnx.TensorProto.DataType.UINT8;
+ case 'bool':
+ return onnx_proto_1.onnx.TensorProto.DataType.BOOL;
+ case 'int16':
+ return onnx_proto_1.onnx.TensorProto.DataType.INT16;
+ case 'uint16':
+ return onnx_proto_1.onnx.TensorProto.DataType.UINT16;
+ case 'int32':
+ return onnx_proto_1.onnx.TensorProto.DataType.INT32;
+ case 'uint32':
+ return onnx_proto_1.onnx.TensorProto.DataType.UINT32;
+ case 'float32':
+ return onnx_proto_1.onnx.TensorProto.DataType.FLOAT;
+ case 'float64':
+ return onnx_proto_1.onnx.TensorProto.DataType.DOUBLE;
+ case 'string':
+ return onnx_proto_1.onnx.TensorProto.DataType.STRING;
+ case 'int64':
+ return onnx_proto_1.onnx.TensorProto.DataType.INT64;
+ case 'uint64':
+ return onnx_proto_1.onnx.TensorProto.DataType.UINT64;
+ default:
+ throw new Error(`unsupported data type: ${type}`);
+ }
+ }
+ static tensorDimsFromProto(dims) {
+ // get rid of Long type for dims
+ return dims.map(d => long_1.default.isLong(d) ? d.toNumber() : d);
+ }
+ static tensorValueTypeFromProto(valueType) {
+ return {
+ tensorType: ProtoUtil.tensorDataTypeFromProto(valueType.elemType),
+ shape: { dims: ProtoUtil.tensorDimsFromProto(valueType.shape.dim.map(d => d.dimValue)) }
+ };
+ }
+ static tensorDimsFromORTFormat(tensor) {
+ const dims = [];
+ for (let i = 0; i < tensor.dimsLength(); i++) {
+ dims.push(LongUtil.longToNumber(tensor.dims(i)));
+ }
+ return dims;
+ }
+ static tensorAttributesFromORTFormat(node) {
+ const attributes = [];
+ for (let i = 0; i < node.attributesLength(); i++) {
+ attributes.push(node.attributes(i));
+ }
+ return attributes;
+ }
+}
+exports.ProtoUtil = ProtoUtil;
+class LongUtil {
+ // This function is called to get a number from long type of data for attribute, dim, and ir version,
+ // which values are signed integers.
+ // To make it more generic, add an optional paramter to convert to a unsigned number.
+ static longToNumber(n, unsigned) {
+ if (long_1.default.isLong(n)) {
+ return n.toNumber();
+ }
+ else if (n instanceof flatbuffers_1.flatbuffers.Long) {
+ return long_1.default.fromValue({ low: n.low, high: n.high, unsigned: unsigned !== null && unsigned !== void 0 ? unsigned : false }).toNumber();
+ }
+ return n;
+ }
+ static isLong(n) {
+ return long_1.default.isLong(n) || n instanceof flatbuffers_1.flatbuffers.Long;
+ }
+}
+exports.LongUtil = LongUtil;
+class ShapeUtil {
+ static size(dims) {
+ return ShapeUtil.getSizeFromDimensionRange(dims, 0, dims.length);
+ }
+ // `axis` inclusive
+ static sizeFromDimension(dims, axis) {
+ if (axis < 0 || axis > dims.length) {
+ throw new Error(`invalid dimension of ${axis} for sizeFromDimension as Tensor has ${dims.length} dimensions.`);
+ }
+ return ShapeUtil.getSizeFromDimensionRange(dims, axis, dims.length);
+ }
+ // `axis` exclusive
+ static sizeToDimension(dims, axis) {
+ if (axis < 0 || axis > dims.length) {
+ throw new Error(`invalid dimension of ${axis} for sizeToDimension as Tensor has ${dims.length} dimensions.`);
+ }
+ return ShapeUtil.getSizeFromDimensionRange(dims, 0, axis);
+ }
+ static getSizeFromDimensionRange(dims, start, end) {
+ let size = 1;
+ for (let i = start; i < end; i++) {
+ // safety check as this method is called by multiple other methods requiring size.
+ // size cannot be 0 or negative.
+ if (dims[i] <= 0) {
+ throw new Error(
+ // eslint-disable-next-line max-len
+ 'cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them.');
+ }
+ size *= dims[i];
+ }
+ return size;
+ }
+ static computeStrides(dims) {
+ const rank = dims.length;
+ if (rank === 0) {
+ return [];
+ }
+ else if (rank === 1) {
+ return [1];
+ }
+ const strides = new Array(rank);
+ strides[rank - 1] = 1;
+ strides[rank - 2] = dims[rank - 1];
+ for (let i = rank - 3; i >= 0; --i) {
+ strides[i] = strides[i + 1] * dims[i + 1];
+ }
+ return strides;
+ }
+ static transpose(dims) {
+ const copy = dims.slice();
+ return copy.reverse();
+ }
+ static indicesToOffset(indices, strides, axis) {
+ if (axis === undefined) {
+ axis = indices.length;
+ }
+ let offset = 0;
+ for (let i = 0; i < axis; ++i) {
+ offset += strides[i] * indices[i];
+ }
+ return offset;
+ }
+ static offsetToIndices(offset, strides) {
+ const rank = strides.length;
+ if (rank === 0) {
+ return [];
+ }
+ else if (rank === 1) {
+ return [offset * strides[0]];
+ }
+ const indices = new Array(strides.length);
+ for (let i = 0; i < indices.length - 1; ++i) {
+ indices[i] = Math.floor(offset / strides[i]);
+ offset -= indices[i] * strides[i];
+ }
+ indices[indices.length - 1] = offset;
+ return indices;
+ }
+ /**
+ * normailze axis of range [-r, r) into [0, r).
+ */
+ static normalizeAxis(axis, tensorRank) {
+ if (axis < -tensorRank && axis >= tensorRank) {
+ throw new Error('unsupported axis for this operation.');
+ }
+ return axis < 0 ? axis + tensorRank : axis;
+ }
+ static normalizeAxes(axes, tensorRank) {
+ return axes.map(x => this.normalizeAxis(x, tensorRank));
+ }
+ // Increment an index into a tensor (in lexicographic
+ // ordering), wrapping around the specified upper_bound.
+ /**
+ * Increment an index into a tensor (in lexicographic ordering), wrapping around the specified upper_bound.
+ * @param index Given index to increment (Will be mutated)
+ * @param dims The dimensions of the tensor for which the given index corresponds to
+ * @param axisToIncrementOn The 1-indexed axis to increment on. If undefined, axisToIncrementOn == rank
+ */
+ static incrementIndex(index, dims, axisToIncrementOn) {
+ if (dims.length === 0 || index.length === 0) {
+ throw new Error('Index incrementing unsupported for scalar Tensor');
+ }
+ if (axisToIncrementOn === undefined) {
+ axisToIncrementOn = dims.length;
+ }
+ else {
+ if (axisToIncrementOn <= 0 || axisToIncrementOn > dims.length) {
+ throw new Error('Incorrect axis to increment on');
+ }
+ }
+ for (let k = axisToIncrementOn - 1; k >= 0; --k) {
+ index[k]++;
+ if (index[k] < dims[k]) {
+ break;
+ }
+ index[k] = 0;
+ }
+ }
+ /**
+ * Produces a new dimensions array based on the values in the 'originalDimensions' and 'shape' array
+ * Used in Reshape
+ * @param originalDims Original Shape array
+ * @param shapeHints array containing values to compute the new dimensions
+ * For example:
+ * originalDims = [2,2] and shapeHints = [0,-1] will return [2,2]
+ * originalDims = [2,2] and shapeHints = [4] will return [4]
+ * originalDims = [2,2] and shapeHints = [5] will throw an exception
+ * https://github.com/onnx/onnx/blob/main/docs/Operators.md#Reshape
+ */
+ static calculateReshapedDims(originalDims, shapeHints) {
+ // reshape to a Scalar Tensor
+ if (shapeHints.length === 0) {
+ if (originalDims.length === 0 || ShapeUtil.size(originalDims) === 1) {
+ return [];
+ }
+ else {
+ throw new Error('cannot reshape to a scalar Tensor');
+ }
+ }
+ const nDims = shapeHints.length;
+ const reshapedDims = new Array(nDims);
+ let unknownDimension = -1;
+ let newTensorSize = 1;
+ for (let i = 0; i < nDims; i++) {
+ if (shapeHints[i] < -1) {
+ throw new Error('a dimension in shape hints cannot be less than -1');
+ }
+ if (shapeHints[i] === -1) {
+ if (unknownDimension !== -1) {
+ throw new Error('at most one dimension in shape hints can be -1');
+ }
+ unknownDimension = i;
+ }
+ else {
+ if (shapeHints[i] === 0) {
+ if (i >= originalDims.length) {
+ throw new Error('the dimension with value zero exceeds the dimension size of the input tensor');
+ }
+ reshapedDims[i] = originalDims[i];
+ }
+ else {
+ reshapedDims[i] = shapeHints[i];
+ }
+ newTensorSize *= reshapedDims[i];
+ }
+ }
+ const oldTensorSize = ShapeUtil.size(originalDims);
+ if (unknownDimension !== -1) {
+ if (oldTensorSize % newTensorSize !== 0) {
+ throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${originalDims}] Output shape: [${shapeHints}]`);
+ }
+ reshapedDims[unknownDimension] = oldTensorSize / newTensorSize;
+ }
+ // validate sizes from originalDims and reshapedDims match
+ else {
+ if (newTensorSize !== oldTensorSize) {
+ throw new Error('reshapedDims and originalDims don\'t have matching sizes');
+ }
+ }
+ return reshapedDims;
+ }
+ /**
+ * Sorts a given array based on the indices in the Perm array
+ * Used in Transpose
+ * @param a Array to be sorted such as dims or strides
+ * @param perm Perm given; if null a will be reversed
+ */
+ static sortBasedOnPerm(a, perm) {
+ if (perm) {
+ return perm.map((v) => a[v]);
+ }
+ else {
+ return a.slice().reverse();
+ }
+ }
+ /**
+ * Pads a given shape according to the padding values
+ * @param dims shape of the Tensor to be padded
+ * @param pad pad values
+ */
+ static padShape(dims, pad) {
+ const rank = dims.length;
+ return dims.map((v, i) => v + pad[i] + pad[i + rank]);
+ }
+ /**
+ * Determines if the two shapes are identical
+ * @param shape1
+ * @param shape2
+ */
+ static areEqual(shape1, shape2) {
+ if (shape1.length !== shape2.length) {
+ return false;
+ }
+ return shape1.every((v, i) => v === shape2[i]);
+ }
+ /**
+ * Validates if the given `dims` or `shape` is valid in ONNX.js context and returns data size
+ * @param dims - input `dims` that needs to be checked
+ */
+ static validateDimsAndCalcSize(dims) {
+ if (dims.length > 6) {
+ throw new TypeError('Only rank 0 to 6 is supported for tensor shape.');
+ }
+ let size = 1;
+ for (const n of dims) {
+ if (!Number.isInteger(n)) {
+ throw new TypeError(`Invalid shape: ${n} is not an integer`);
+ }
+ if (n < 0 || n > 2147483647) {
+ throw new TypeError(`Invalid shape: length ${n} is not allowed`);
+ }
+ size *= n;
+ }
+ return size;
+ }
+ /**
+ * Determines the shape of output tensor y = flatten(x, axis)
+ * @param dims - shape of input tensor
+ * @param axis - flatten axis, in the range [-r, r]
+ */
+ static flattenShape(dims, axis) {
+ if (axis < 0) {
+ axis += dims.length;
+ }
+ const total = dims.reduce((x, y) => x * y, 1);
+ const right = dims.slice(axis).reduce((x, y) => x * y, 1);
+ const outputDims = [total / right, right];
+ return outputDims;
+ }
+ /**
+ * Determines the shape of output tensor y = squeeze(x, axes)
+ * @param dims - shape of input tensor
+ * @param axes - squeeze axes
+ */
+ static squeezeShape(dims, axes) {
+ const outputDims = new Array();
+ // sanity check
+ axes = ShapeUtil.normalizeAxes(axes, dims.length);
+ for (let i = 0; i < dims.length; i++) {
+ const inSqueezeList = axes.indexOf(i) >= 0;
+ if (inSqueezeList && dims[i] !== 1) {
+ throw new Error('squeeze an axis of size different than 1');
+ }
+ if ((axes.length === 0 && dims[i] > 1) || (axes.length > 0 && !inSqueezeList)) {
+ outputDims.push(dims[i]);
+ }
+ }
+ return outputDims;
+ }
+ /**
+ * Determines the shape of output tensor y = unsqueeze(x, axes)
+ * @param dims - shape of input tensor
+ * @param axes - unsqueeze axes
+ */
+ static unsqueezeShape(dims, axes) {
+ const outputDims = new Array(dims.length + axes.length);
+ // initialize the array elements to 0
+ outputDims.fill(0);
+ // set all axes indices to 1 in outputDims and check for duplicates
+ for (let i = 0; i < axes.length; i++) {
+ const axis = ShapeUtil.normalizeAxis(axes[i], outputDims.length);
+ if (axis >= outputDims.length) {
+ throw new Error('\'axes\' has an out of range axis');
+ }
+ if (outputDims[axis] !== 0) {
+ throw new Error('\'axes\' has a duplicate axis');
+ }
+ outputDims[axis] = 1;
+ }
+ // fill in the zero entries of outputDims with the input tensor's shape
+ let inputDimsIterator = 0;
+ for (let i = 0; i < outputDims.length; i++) {
+ if (outputDims[i] === 0) {
+ outputDims[i] = dims[inputDimsIterator++];
+ }
+ }
+ // sanity check assertion. 'inputDimsIterator'
+ // should be equal to the length of 'dims'
+ if (inputDimsIterator !== dims.length) {
+ throw new Error('the unsqueezed dimension could not be established');
+ }
+ return outputDims;
+ }
+}
+exports.ShapeUtil = ShapeUtil;
+// bunch of helper methods that do a variety of math operations
+class MathUtil {
+ // y = (x*x) + y
+ static sqr(target, source, targetIndex, sourceIndex, blockSize) {
+ if (sourceIndex < 0 || sourceIndex >= source.length) {
+ throw new Error('sourceIndex out of bounds');
+ }
+ if (targetIndex < 0 || targetIndex >= target.length) {
+ throw new Error('targetIndex out of bounds');
+ }
+ if (sourceIndex + blockSize > source.length) {
+ throw new Error('source indices to be copied are outside bounds');
+ }
+ if (targetIndex + blockSize > target.length) {
+ throw new Error('target array is too small to hold result');
+ }
+ for (let offset = 0; offset < blockSize; offset++) {
+ target[targetIndex + offset] += Math.pow(source[sourceIndex + offset], 2);
+ }
+ }
+ // y = ax + y
+ static axpy(target, source, targetIndex, sourceIndex, blockSize, alpha) {
+ if (sourceIndex < 0 || sourceIndex >= source.length) {
+ throw new Error('sourceIndex out of bounds');
+ }
+ if (targetIndex < 0 || targetIndex >= target.length) {
+ throw new Error('targetIndex out of bounds');
+ }
+ if (sourceIndex + blockSize > source.length) {
+ throw new Error('source indices to be copied are outside bounds');
+ }
+ if (targetIndex + blockSize > target.length) {
+ throw new Error('target array is too small to hold result');
+ }
+ for (let offset = 0; offset < blockSize; offset++) {
+ target[targetIndex + offset] += (alpha * source[sourceIndex + offset]);
+ }
+ }
+ // y = pow(x, b)
+ static powx(target, source, targetIndex, sourceIndex, blockSize, b) {
+ if (sourceIndex < 0 || sourceIndex >= source.length) {
+ throw new Error('sourceIndex out of bounds');
+ }
+ if (targetIndex < 0 || targetIndex >= target.length) {
+ throw new Error('targetIndex out of bounds');
+ }
+ if (sourceIndex + blockSize > source.length) {
+ throw new Error('source indices to be copied are outside bounds');
+ }
+ if (targetIndex + blockSize > target.length) {
+ throw new Error('target array is too small to hold result');
+ }
+ for (let offset = 0; offset < blockSize; offset++) {
+ target[targetIndex + offset] = Math.pow(source[sourceIndex + offset], b);
+ }
+ }
+ // y = x * y
+ static mul(target, source, targetIndex, sourceIndex, blockSize) {
+ if (sourceIndex < 0 || sourceIndex >= source.length) {
+ throw new Error('sourceIndex out of bounds');
+ }
+ if (targetIndex < 0 || targetIndex >= target.length) {
+ throw new Error('targetIndex out of bounds');
+ }
+ if (sourceIndex + blockSize > source.length) {
+ throw new Error('source indices to be copied are outside bounds');
+ }
+ if (targetIndex + blockSize > target.length) {
+ throw new Error('target array is too small to hold result');
+ }
+ for (let offset = 0; offset < blockSize; offset++) {
+ target[targetIndex + offset] = (source[sourceIndex + offset] * target[targetIndex + offset]);
+ }
+ }
+}
+exports.MathUtil = MathUtil;
+class SplitUtil {
+ /**
+ * Calculates new Shapes from existing one and the splits given along the axis provides
+ * @param dims Shape of the Tensor to be splitted into two or more Shapes
+ * @param axis The dimension along which the Tensor will be split
+ * @param splits Offsets for the start of each split
+ */
+ static splitShape(dims, axis, split, numOutputs) {
+ if (split.length === 0) {
+ if (!numOutputs) {
+ throw new Error('need to know number of outputs when the \'split\' attribute is not specified');
+ }
+ SplitUtil.determineSplit(dims[axis], numOutputs, split);
+ }
+ const shapes = [];
+ const offsets = [0];
+ for (let i = 0; i < split.length; ++i) {
+ if (i !== 0) {
+ offsets.push(offsets[i - 1] + split[i - 1]);
+ }
+ const shape = dims.slice();
+ shape[axis] = split[i];
+ shapes.push(shape);
+ }
+ return [shapes, offsets];
+ }
+ static determineSplit(numElementsAlongAxis, numOutputs, split) {
+ // If 'split' is not specified by the user, we need to partition the number of elements equally among the outputs
+ if (numElementsAlongAxis % numOutputs !== 0) {
+ throw new Error('cannot split tensor to equal sized parts');
+ }
+ for (let i = 0; i < numOutputs; ++i) {
+ split.push(numElementsAlongAxis / numOutputs);
+ }
+ }
+}
+exports.SplitUtil = SplitUtil;
+class ReduceUtil {
+ /**
+ * Perform reduce operations on the specific operator
+ * @param a Input tensor data
+ * @param axes The dimensions along which the Tensor will be reduced
+ * @param keepdims If set to true, the axes which are reduced are left in the
+ * result as dimensions with size one.
+ * @param op1 The operation to be performed on each element in the tensor
+ * @param op2 The operation to be performed between elements in the tensor
+ */
+ static calcReduce(a, axes, keepdims, op1, op2) {
+ const dims = a.dims.slice(0);
+ // if axes is not set, perform reduce on all axes
+ if (axes.length === 0) {
+ dims.forEach((d, ind) => axes.push(ind));
+ }
+ // get a temporary broadcastable output shape
+ const outputDims = ReduceUtil.calcReduceShape(dims, axes, true);
+ // loop through the output and calculate result one by one
+ const size = ShapeUtil.size(outputDims);
+ const y = new tensor_1.Tensor(outputDims, a.type);
+ const strides = ShapeUtil.computeStrides(outputDims);
+ const inputStrides = ShapeUtil.computeStrides(dims);
+ const indicesY = new Array(dims.length);
+ for (let i = 0; i < size; i++) {
+ const indices = ShapeUtil.offsetToIndices(i, strides);
+ // map index
+ BroadcastUtil.fillIndex(indices, dims, indicesY);
+ y.set(indices, ReduceUtil.calcReduceByAxis(a.numberData, axes, dims, 0, ShapeUtil.indicesToOffset(indicesY, inputStrides), op1, op2));
+ }
+ if (keepdims) {
+ return y;
+ }
+ else {
+ // keepdims == 0, calculate the expected shape
+ return new tensor_1.Tensor(ReduceUtil.calcReduceShape(dims, axes, keepdims), y.type, undefined, undefined, y.data, y.dataId);
+ }
+ }
+ /**
+ * Perform reduce operations on the specific operator on specific axes
+ * @param a Input tensor data
+ * @param axes The dimensions along which the Tensor will be reduced
+ * @param dims The input dimension.
+ * @param curAxisInd Index in axes specifying the current dimension along
+ * which the tensor will be reduced
+ * @param pos The current index of element to perform operation
+ * @param op1 The operation to be performed on each element in the tensor
+ * @param op2 The operation to be performed between elements in the tensor
+ */
+ static calcReduceByAxis(input, axes, dims, curAxisInd, pos, op1, op2) {
+ let res = 0;
+ if (curAxisInd >= axes.length) {
+ return op1(input[pos]);
+ }
+ const axis = axes[curAxisInd];
+ const step = axis >= dims.length ? 1 : ShapeUtil.size(dims.slice(axis + 1));
+ for (let i = 0; i < dims[axis]; i++) {
+ res = i === 0 ? ReduceUtil.calcReduceByAxis(input, axes, dims, curAxisInd + 1, pos, op1, op2) :
+ op2(res, ReduceUtil.calcReduceByAxis(input, axes, dims, curAxisInd + 1, pos, op1, op2));
+ pos += step;
+ }
+ return res;
+ }
+ /**
+ * Calculate the expected shape of a reduce operation
+ * @param dims The input tensor dimension
+ * @param axes The dimensions along which the Tensor will be reduced
+ * @param keepdims If set to true, the axes which are reduced are left in the
+ * result as dimensions with size one.
+ */
+ static calcReduceShape(dims, axes, keepDims) {
+ const outputDims = dims.slice();
+ for (let i = 0; i < axes.length; i++) {
+ if (keepDims) {
+ outputDims[axes[i]] = 1;
+ }
+ else {
+ outputDims[axes[i]] = 0;
+ }
+ }
+ return outputDims.filter(dim => dim !== 0);
+ }
+}
+exports.ReduceUtil = ReduceUtil;
+class PoolConvUtil {
+ /**
+ * Adjust the kernel, strides, pads to correct rank. Set to default value if not present
+ * @param isGlobalOperator If true, perform global pooling.
+ * @param inputDims The input tensor dimension.
+ * @param kernelShape The size of the kernel along each axis.
+ * @param strides Stride along each axis.
+ * @param dilations Dilation along each axis.
+ * @param pads Padding for the beginning and ending along each axis.
+ */
+ static adjustPoolAttributes(isGlobalOperator, inputDims, kernelShape, strides, dilations, pads) {
+ if (!isGlobalOperator && kernelShape.length !== inputDims.length - 2) {
+ throw new Error('length of specified kernel shapes should be 2 less than length of input dimensions');
+ }
+ if (isGlobalOperator) {
+ // adjust kernel shape to cover the input dims
+ for (let dim = 0; dim < inputDims.length - 2; dim++) {
+ if (dim >= kernelShape.length) {
+ kernelShape.push(inputDims[dim + 2]);
+ }
+ else {
+ kernelShape[dim] = inputDims[dim + 2];
+ }
+ }
+ }
+ // adjust strides length to match kernel shape length
+ for (let dim = 0; dim < kernelShape.length; dim++) {
+ if (dim < strides.length) {
+ if (strides[dim] < 0) {
+ throw new Error('strides should be greater than or equal to 1');
+ }
+ }
+ else {
+ strides.push(1);
+ }
+ }
+ // adjust dilation value
+ for (let dim = 0; dim < kernelShape.length; dim++) {
+ if (dim < dilations.length) {
+ if (dilations[dim] < 0) {
+ throw new Error('dilations should be greater than or equal to 1');
+ }
+ }
+ else {
+ dilations.push(1);
+ }
+ }
+ // adjust pads length to match 2 * kernel shape length
+ for (let dim = 0; dim < kernelShape.length * 2; dim++) {
+ if (dim < pads.length) {
+ if (pads[dim] < 0) {
+ throw new Error('pad should be greater than or equal to 1');
+ }
+ }
+ else {
+ pads.push(0);
+ }
+ }
+ // sanity checks for values in kernel shapes and pads
+ for (let dim = 0; dim < kernelShape.length; dim++) {
+ if (kernelShape[dim] <= 0) {
+ throw new Error('kernel shapes need to be greater than 0');
+ }
+ if (pads[dim] >= kernelShape[dim] || pads[dim + kernelShape.length] >= kernelShape[dim]) {
+ throw new Error('pads should be smaller than kernel');
+ }
+ }
+ }
+ // adjust pad values based on 'autoPad' attribute
+ static adjustPadsBasedOnAutoPad(inputDims, strides, dilations, kernelShape, pads, autoPad) {
+ if (!autoPad) {
+ return;
+ }
+ if (pads.length !== 2 * (inputDims.length - 2)) {
+ throw new Error('length of pads should be twice the length of data dimensions');
+ }
+ if (strides.length !== (inputDims.length - 2)) {
+ throw new Error('length of strides should be the length of data dimensions');
+ }
+ if (kernelShape.length !== (inputDims.length - 2)) {
+ throw new Error('length of kernel shapes should be the length of data dimensions');
+ }
+ for (let dim = 0; dim < inputDims.length - 2; dim++) {
+ PoolConvUtil.adjustPadAndReturnShape(inputDims[dim + 2], strides[dim], dilations[dim], kernelShape[dim], pads, dim, dim + inputDims.length - 2, autoPad);
+ }
+ }
+ /**
+ * Calculate the output shape for Pool ops based on input attributes. (Should be used only for Pool ops)
+ * @param isGlobalOperator If true, perform global pooling.
+ * @param inputDims The input tensor dimension. (inputs[0].dims)
+ * @param strides Stride along each axis.
+ * @param dilations Dilation along each axis.
+ * @param kernelShape The size of the kernel along each axis.
+ * @param pads Padding for the beginning and ending along each axis.
+ * @param autoPad DEPRECATED attribute supported for legacy models. Specifies how to implicitly calculate pads in each
+ * dimension. Can take values NOTSET, SAME_UPPER, SAME_LOWER, or VALID.
+ */
+ static computePoolOutputShape(isGlobalOperator, inputDims, strides, dilations, kernelShape, pads, autoPad) {
+ if (inputDims.length <= 0) {
+ throw new Error('input shape must be of size greater than 0');
+ }
+ // Add batch size and number of channels of output
+ const outputDims = [inputDims[0], inputDims[1]];
+ PoolConvUtil.computeShapeHelper(isGlobalOperator, inputDims, outputDims, strides, dilations, kernelShape, pads, autoPad);
+ return outputDims;
+ }
+ /**
+ * Calculate the output shape for Conv op based on input attributes. (Should be used only for Conv op)
+ * @param inputDims The input tensor dimension. (inputs[0].dims)
+ * @param filterDims The filter tensor dimension. (inputs[1].dims)
+ * @param strides Stride along each axis.
+ * @param kernelShape The size of the kernel along each axis.
+ * @param pads Padding for the beginning and ending along each axis.
+ * @param autoPad DEPRECATED attribute supported for legacy models. Specifies how to implicitly calculate pads in each
+ * dimension. Can take values NOTSET, SAME_UPPER, SAME_LOWER, or VALID.
+ */
+ static computeConvOutputShape(inputDims, filterDims, strides, dilations, kernelShape, pads, autoPad) {
+ if (inputDims.length <= 0 || filterDims.length <= 0) {
+ throw new Error('invalid input tensor dims or invalid filter tensor dims');
+ }
+ // Add batch size and number of channels of output
+ const outputDims = [inputDims[0], filterDims[0]];
+ PoolConvUtil.computeShapeHelper(false, inputDims, outputDims, strides, dilations, kernelShape, pads, autoPad);
+ return outputDims;
+ }
+ // will compute output shapes for data dimensions ONLY (i.e.) no batch size and channels
+ // called by computePoolOutputShape() and computeConvOutputShape()
+ // adjust pads based on 'autoPad' attribute prior to shape computation
+ static computeShapeHelper(isGlobalOperator, inputDims, outputDims, strides, dilations, kernelShape, pads, autoPad) {
+ if (isGlobalOperator) {
+ for (let dim = 0; dim < inputDims.length - 2; dim++) {
+ outputDims.push(1);
+ }
+ }
+ else {
+ for (let dim = 0; dim < inputDims.length - 2; dim++) {
+ outputDims.push(PoolConvUtil.adjustPadAndReturnShape(inputDims[dim + 2], strides[dim], dilations[dim], kernelShape[dim], pads, dim, dim + inputDims.length - 2, autoPad));
+ }
+ }
+ }
+ // helper for computeShapeHelper() and adjustPadsBasedOnAutoPad()
+ // adjusts pad value for given 'autoPad' string and computes output shape along a particular dimension
+ static adjustPadAndReturnShape(inSize, stride, dilation, kernel, pads, padHeadIndex, padTailIndex, autoPad) {
+ const dkernel = dilation * (kernel - 1) + 1;
+ if (autoPad && autoPad !== 'NOTSET') {
+ switch (autoPad) {
+ case 'VALID':
+ pads[padHeadIndex] = 0;
+ pads[padTailIndex] = 0;
+ return Math.floor(((inSize - dkernel) / stride) + 1);
+ case 'SAME_LOWER':
+ case 'SAME_UPPER':
+ if (dilation !== 1) {
+ throw new Error('Dilation not supported for SAME_UPPER or SAME_LOWER');
+ }
+ else {
+ const legacyTargetSize = (inSize + stride - 1) / stride;
+ const padNeeded = (legacyTargetSize - 1) * stride + kernel - inSize;
+ pads[padHeadIndex] =
+ (autoPad === 'SAME_LOWER') ? Math.floor((padNeeded + 1) / 2) : Math.floor(padNeeded / 2);
+ pads[padTailIndex] = padNeeded - pads[padHeadIndex];
+ return Math.floor(((inSize + padNeeded - kernel) / stride) + 1);
+ }
+ default:
+ throw new Error('Unsupported AutoPad type');
+ }
+ }
+ else {
+ return Math.floor(((inSize + pads[padHeadIndex] + pads[padTailIndex] - dkernel) / stride) + 1);
+ }
+ }
+}
+exports.PoolConvUtil = PoolConvUtil;
+exports.MIN_CLIP = -3.4028234663852886e+38;
+exports.MAX_CLIP = 3.4028234663852886e+38;
+function decodeUtf8String(buffer) {
+ return new TextDecoder().decode(buffer);
+}
+exports.decodeUtf8String = decodeUtf8String;
+
+
+/***/ }),
+
+/***/ "./lib/wasm/options-utils.ts":
+/*!***********************************!*\
+ !*** ./lib/wasm/options-utils.ts ***!
+ \***********************************/
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.iterateExtraOptions = void 0;
+const iterateExtraOptions = (options, prefix, seen, handler) => {
+ if (typeof options == 'object' && options !== null) {
+ if (seen.has(options)) {
+ throw new Error('Circular reference in options');
+ }
+ else {
+ seen.add(options);
+ }
+ }
+ Object.entries(options).forEach(([key, value]) => {
+ const name = (prefix) ? prefix + key : key;
+ if (typeof value === 'object') {
+ (0, exports.iterateExtraOptions)(value, name + '.', seen, handler);
+ }
+ else if (typeof value === 'string' || typeof value === 'number') {
+ handler(name, value.toString());
+ }
+ else if (typeof value === 'boolean') {
+ handler(name, (value) ? '1' : '0');
+ }
+ else {
+ throw new Error(`Can't handle extra config type: ${typeof value}`);
+ }
+ });
+};
+exports.iterateExtraOptions = iterateExtraOptions;
+
+
+/***/ }),
+
+/***/ "./lib/wasm/proxy-wrapper.ts":
+/*!***********************************!*\
+ !*** ./lib/wasm/proxy-wrapper.ts ***!
+ \***********************************/
+/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+var _a;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.endProfiling = exports.run = exports.releaseSession = exports.createSession = exports.createSessionFinalize = exports.createSessionAllocate = exports.initOrt = exports.initWasm = void 0;
+const onnxruntime_common_1 = __webpack_require__(/*! onnxruntime-common */ "../common/dist/lib/index.js");
+const core = __importStar(__webpack_require__(/*! ./wasm-core-impl */ "./lib/wasm/wasm-core-impl.ts"));
+const wasm_factory_1 = __webpack_require__(/*! ./wasm-factory */ "./lib/wasm/wasm-factory.ts");
+const isProxy = () => !!onnxruntime_common_1.env.wasm.proxy && typeof document !== 'undefined';
+let proxyWorker;
+let initializing = false;
+let initialized = false;
+let aborted = false;
+let initWasmCallbacks;
+let initOrtCallbacks;
+const createSessionAllocateCallbacks = [];
+const createSessionFinalizeCallbacks = [];
+const createSessionCallbacks = [];
+const releaseSessionCallbacks = [];
+const runCallbacks = [];
+const endProfilingCallbacks = [];
+const ensureWorker = () => {
+ if (initializing || !initialized || aborted || !proxyWorker) {
+ throw new Error('worker not ready');
+ }
+};
+const onProxyWorkerMessage = (ev) => {
+ switch (ev.data.type) {
+ case 'init-wasm':
+ initializing = false;
+ if (ev.data.err) {
+ aborted = true;
+ initWasmCallbacks[1](ev.data.err);
+ }
+ else {
+ initialized = true;
+ initWasmCallbacks[0]();
+ }
+ break;
+ case 'init-ort':
+ if (ev.data.err) {
+ initOrtCallbacks[1](ev.data.err);
+ }
+ else {
+ initOrtCallbacks[0]();
+ }
+ break;
+ case 'create_allocate':
+ if (ev.data.err) {
+ createSessionAllocateCallbacks.shift()[1](ev.data.err);
+ }
+ else {
+ createSessionAllocateCallbacks.shift()[0](ev.data.out);
+ }
+ break;
+ case 'create_finalize':
+ if (ev.data.err) {
+ createSessionFinalizeCallbacks.shift()[1](ev.data.err);
+ }
+ else {
+ createSessionFinalizeCallbacks.shift()[0](ev.data.out);
+ }
+ break;
+ case 'create':
+ if (ev.data.err) {
+ createSessionCallbacks.shift()[1](ev.data.err);
+ }
+ else {
+ createSessionCallbacks.shift()[0](ev.data.out);
+ }
+ break;
+ case 'release':
+ if (ev.data.err) {
+ releaseSessionCallbacks.shift()[1](ev.data.err);
+ }
+ else {
+ releaseSessionCallbacks.shift()[0]();
+ }
+ break;
+ case 'run':
+ if (ev.data.err) {
+ runCallbacks.shift()[1](ev.data.err);
+ }
+ else {
+ runCallbacks.shift()[0](ev.data.out);
+ }
+ break;
+ case 'end-profiling':
+ if (ev.data.err) {
+ endProfilingCallbacks.shift()[1](ev.data.err);
+ }
+ else {
+ endProfilingCallbacks.shift()[0]();
+ }
+ break;
+ default:
+ }
+};
+const scriptSrc = typeof document !== 'undefined' ? (_a = document === null || document === void 0 ? void 0 : document.currentScript) === null || _a === void 0 ? void 0 : _a.src : undefined;
+const initWasm = async () => {
+ if ( true && isProxy()) {
+ if (initialized) {
+ return;
+ }
+ if (initializing) {
+ throw new Error('multiple calls to \'initWasm()\' detected.');
+ }
+ if (aborted) {
+ throw new Error('previous call to \'initWasm()\' failed.');
+ }
+ initializing = true;
+ // overwrite wasm filepaths
+ if (onnxruntime_common_1.env.wasm.wasmPaths === undefined) {
+ if (scriptSrc && scriptSrc.indexOf('blob:') !== 0) {
+ onnxruntime_common_1.env.wasm.wasmPaths = scriptSrc.substr(0, +(scriptSrc).lastIndexOf('/') + 1);
+ }
+ }
+ return new Promise((resolve, reject) => {
+ proxyWorker === null || proxyWorker === void 0 ? void 0 : proxyWorker.terminate();
+ // eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports
+ proxyWorker = (__webpack_require__(/*! worker-loader?inline=no-fallback!./proxy-worker/main */ "./node_modules/worker-loader/dist/cjs.js?inline=no-fallback!./lib/wasm/proxy-worker/main.ts")["default"])();
+ proxyWorker.onmessage = onProxyWorkerMessage;
+ initWasmCallbacks = [resolve, reject];
+ const message = { type: 'init-wasm', in: onnxruntime_common_1.env.wasm };
+ proxyWorker.postMessage(message);
+ });
+ }
+ else {
+ return (0, wasm_factory_1.initializeWebAssembly)(onnxruntime_common_1.env.wasm);
+ }
+};
+exports.initWasm = initWasm;
+const initOrt = async (numThreads, loggingLevel) => {
+ if ( true && isProxy()) {
+ ensureWorker();
+ return new Promise((resolve, reject) => {
+ initOrtCallbacks = [resolve, reject];
+ const message = { type: 'init-ort', in: { numThreads, loggingLevel } };
+ proxyWorker.postMessage(message);
+ });
+ }
+ else {
+ core.initOrt(numThreads, loggingLevel);
+ }
+};
+exports.initOrt = initOrt;
+const createSessionAllocate = async (model) => {
+ if ( true && isProxy()) {
+ ensureWorker();
+ return new Promise((resolve, reject) => {
+ createSessionAllocateCallbacks.push([resolve, reject]);
+ const message = { type: 'create_allocate', in: { model } };
+ proxyWorker.postMessage(message, [model.buffer]);
+ });
+ }
+ else {
+ return core.createSessionAllocate(model);
+ }
+};
+exports.createSessionAllocate = createSessionAllocate;
+const createSessionFinalize = async (modeldata, options) => {
+ if ( true && isProxy()) {
+ ensureWorker();
+ return new Promise((resolve, reject) => {
+ createSessionFinalizeCallbacks.push([resolve, reject]);
+ const message = { type: 'create_finalize', in: { modeldata, options } };
+ proxyWorker.postMessage(message);
+ });
+ }
+ else {
+ return core.createSessionFinalize(modeldata, options);
+ }
+};
+exports.createSessionFinalize = createSessionFinalize;
+const createSession = async (model, options) => {
+ if ( true && isProxy()) {
+ ensureWorker();
+ return new Promise((resolve, reject) => {
+ createSessionCallbacks.push([resolve, reject]);
+ const message = { type: 'create', in: { model, options } };
+ proxyWorker.postMessage(message, [model.buffer]);
+ });
+ }
+ else {
+ return core.createSession(model, options);
+ }
+};
+exports.createSession = createSession;
+const releaseSession = async (sessionId) => {
+ if ( true && isProxy()) {
+ ensureWorker();
+ return new Promise((resolve, reject) => {
+ releaseSessionCallbacks.push([resolve, reject]);
+ const message = { type: 'release', in: sessionId };
+ proxyWorker.postMessage(message);
+ });
+ }
+ else {
+ core.releaseSession(sessionId);
+ }
+};
+exports.releaseSession = releaseSession;
+const run = async (sessionId, inputIndices, inputs, outputIndices, options) => {
+ if ( true && isProxy()) {
+ ensureWorker();
+ return new Promise((resolve, reject) => {
+ runCallbacks.push([resolve, reject]);
+ const message = { type: 'run', in: { sessionId, inputIndices, inputs, outputIndices, options } };
+ proxyWorker.postMessage(message, core.extractTransferableBuffers(inputs));
+ });
+ }
+ else {
+ return core.run(sessionId, inputIndices, inputs, outputIndices, options);
+ }
+};
+exports.run = run;
+const endProfiling = async (sessionId) => {
+ if ( true && isProxy()) {
+ ensureWorker();
+ return new Promise((resolve, reject) => {
+ endProfilingCallbacks.push([resolve, reject]);
+ const message = { type: 'end-profiling', in: sessionId };
+ proxyWorker.postMessage(message);
+ });
+ }
+ else {
+ core.endProfiling(sessionId);
+ }
+};
+exports.endProfiling = endProfiling;
+
+
+/***/ }),
+
+/***/ "./lib/wasm/run-options.ts":
+/*!*********************************!*\
+ !*** ./lib/wasm/run-options.ts ***!
+ \*********************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.setRunOptions = void 0;
+const options_utils_1 = __webpack_require__(/*! ./options-utils */ "./lib/wasm/options-utils.ts");
+const string_utils_1 = __webpack_require__(/*! ./string-utils */ "./lib/wasm/string-utils.ts");
+const wasm_factory_1 = __webpack_require__(/*! ./wasm-factory */ "./lib/wasm/wasm-factory.ts");
+const setRunOptions = (options) => {
+ const wasm = (0, wasm_factory_1.getInstance)();
+ let runOptionsHandle = 0;
+ const allocs = [];
+ const runOptions = options || {};
+ try {
+ if ((options === null || options === void 0 ? void 0 : options.logSeverityLevel) === undefined) {
+ runOptions.logSeverityLevel = 2; // Default to warning
+ }
+ else if (typeof options.logSeverityLevel !== 'number' || !Number.isInteger(options.logSeverityLevel) ||
+ options.logSeverityLevel < 0 || options.logSeverityLevel > 4) {
+ throw new Error(`log serverity level is not valid: ${options.logSeverityLevel}`);
+ }
+ if ((options === null || options === void 0 ? void 0 : options.logVerbosityLevel) === undefined) {
+ runOptions.logVerbosityLevel = 0; // Default to 0
+ }
+ else if (typeof options.logVerbosityLevel !== 'number' || !Number.isInteger(options.logVerbosityLevel)) {
+ throw new Error(`log verbosity level is not valid: ${options.logVerbosityLevel}`);
+ }
+ if ((options === null || options === void 0 ? void 0 : options.terminate) === undefined) {
+ runOptions.terminate = false;
+ }
+ let tagDataOffset = 0;
+ if ((options === null || options === void 0 ? void 0 : options.tag) !== undefined) {
+ tagDataOffset = (0, string_utils_1.allocWasmString)(options.tag, allocs);
+ }
+ runOptionsHandle = wasm._OrtCreateRunOptions(runOptions.logSeverityLevel, runOptions.logVerbosityLevel, !!runOptions.terminate, tagDataOffset);
+ if (runOptionsHandle === 0) {
+ throw new Error('Can\'t create run options');
+ }
+ if ((options === null || options === void 0 ? void 0 : options.extra) !== undefined) {
+ (0, options_utils_1.iterateExtraOptions)(options.extra, '', new WeakSet(), (key, value) => {
+ const keyDataOffset = (0, string_utils_1.allocWasmString)(key, allocs);
+ const valueDataOffset = (0, string_utils_1.allocWasmString)(value, allocs);
+ if (wasm._OrtAddRunConfigEntry(runOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {
+ throw new Error(`Can't set a run config entry: ${key} - ${value}`);
+ }
+ });
+ }
+ return [runOptionsHandle, allocs];
+ }
+ catch (e) {
+ if (runOptionsHandle !== 0) {
+ wasm._OrtReleaseRunOptions(runOptionsHandle);
+ }
+ allocs.forEach(wasm._free);
+ throw e;
+ }
+};
+exports.setRunOptions = setRunOptions;
+
+
+/***/ }),
+
+/***/ "./lib/wasm/session-handler.ts":
+/*!*************************************!*\
+ !*** ./lib/wasm/session-handler.ts ***!
+ \*************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.OnnxruntimeWebAssemblySessionHandler = void 0;
+const fs_1 = __webpack_require__(/*! fs */ "?295d");
+const onnxruntime_common_1 = __webpack_require__(/*! onnxruntime-common */ "../common/dist/lib/index.js");
+const util_1 = __webpack_require__(/*! util */ "?cf98");
+const proxy_wrapper_1 = __webpack_require__(/*! ./proxy-wrapper */ "./lib/wasm/proxy-wrapper.ts");
+let ortInit;
+const getLogLevel = (logLevel) => {
+ switch (logLevel) {
+ case 'verbose':
+ return 0;
+ case 'info':
+ return 1;
+ case 'warning':
+ return 2;
+ case 'error':
+ return 3;
+ case 'fatal':
+ return 4;
+ default:
+ throw new Error(`unsupported logging level: ${logLevel}`);
+ }
+};
+class OnnxruntimeWebAssemblySessionHandler {
+ async createSessionAllocate(path) {
+ // fetch model from url and move to wasm heap. The arraybufffer that held the http
+ // response is freed once we return
+ const response = await fetch(path);
+ const arrayBuffer = await response.arrayBuffer();
+ return (0, proxy_wrapper_1.createSessionAllocate)(new Uint8Array(arrayBuffer));
+ }
+ async loadModel(pathOrBuffer, options) {
+ if (!ortInit) {
+ await (0, proxy_wrapper_1.initOrt)(onnxruntime_common_1.env.wasm.numThreads, getLogLevel(onnxruntime_common_1.env.logLevel));
+ ortInit = true;
+ }
+ if (typeof pathOrBuffer === 'string') {
+ if (typeof fetch === 'undefined') {
+ // node
+ const model = await (0, util_1.promisify)(fs_1.readFile)(pathOrBuffer);
+ [this.sessionId, this.inputNames, this.outputNames] = await (0, proxy_wrapper_1.createSession)(model, options);
+ }
+ else {
+ // browser
+ // fetch model and move to wasm heap.
+ const modelData = await this.createSessionAllocate(pathOrBuffer);
+ // create the session
+ [this.sessionId, this.inputNames, this.outputNames] = await (0, proxy_wrapper_1.createSessionFinalize)(modelData, options);
+ }
+ }
+ else {
+ [this.sessionId, this.inputNames, this.outputNames] = await (0, proxy_wrapper_1.createSession)(pathOrBuffer, options);
+ }
+ }
+ async dispose() {
+ return (0, proxy_wrapper_1.releaseSession)(this.sessionId);
+ }
+ async run(feeds, fetches, options) {
+ const inputArray = [];
+ const inputIndices = [];
+ Object.entries(feeds).forEach(kvp => {
+ const name = kvp[0];
+ const tensor = kvp[1];
+ const index = this.inputNames.indexOf(name);
+ if (index === -1) {
+ throw new Error(`invalid input '${name}'`);
+ }
+ inputArray.push(tensor);
+ inputIndices.push(index);
+ });
+ const outputIndices = [];
+ Object.entries(fetches).forEach(kvp => {
+ const name = kvp[0];
+ // TODO: support pre-allocated output
+ const index = this.outputNames.indexOf(name);
+ if (index === -1) {
+ throw new Error(`invalid output '${name}'`);
+ }
+ outputIndices.push(index);
+ });
+ const outputs = await (0, proxy_wrapper_1.run)(this.sessionId, inputIndices, inputArray.map(t => [t.type, t.dims, t.data]), outputIndices, options);
+ const result = {};
+ for (let i = 0; i < outputs.length; i++) {
+ result[this.outputNames[outputIndices[i]]] = new onnxruntime_common_1.Tensor(outputs[i][0], outputs[i][2], outputs[i][1]);
+ }
+ return result;
+ }
+ startProfiling() {
+ // TODO: implement profiling
+ }
+ endProfiling() {
+ void (0, proxy_wrapper_1.endProfiling)(this.sessionId);
+ }
+}
+exports.OnnxruntimeWebAssemblySessionHandler = OnnxruntimeWebAssemblySessionHandler;
+
+
+/***/ }),
+
+/***/ "./lib/wasm/session-options.ts":
+/*!*************************************!*\
+ !*** ./lib/wasm/session-options.ts ***!
+ \*************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.setSessionOptions = void 0;
+const options_utils_1 = __webpack_require__(/*! ./options-utils */ "./lib/wasm/options-utils.ts");
+const string_utils_1 = __webpack_require__(/*! ./string-utils */ "./lib/wasm/string-utils.ts");
+const wasm_factory_1 = __webpack_require__(/*! ./wasm-factory */ "./lib/wasm/wasm-factory.ts");
+const getGraphOptimzationLevel = (graphOptimizationLevel) => {
+ switch (graphOptimizationLevel) {
+ case 'disabled':
+ return 0;
+ case 'basic':
+ return 1;
+ case 'extended':
+ return 2;
+ case 'all':
+ return 99;
+ default:
+ throw new Error(`unsupported graph optimization level: ${graphOptimizationLevel}`);
+ }
+};
+const getExecutionMode = (executionMode) => {
+ switch (executionMode) {
+ case 'sequential':
+ return 0;
+ case 'parallel':
+ return 1;
+ default:
+ throw new Error(`unsupported execution mode: ${executionMode}`);
+ }
+};
+const appendDefaultOptions = (options) => {
+ if (!options.extra) {
+ options.extra = {};
+ }
+ if (!options.extra.session) {
+ options.extra.session = {};
+ }
+ const session = options.extra.session;
+ if (!session.use_ort_model_bytes_directly) {
+ // eslint-disable-next-line camelcase
+ session.use_ort_model_bytes_directly = '1';
+ }
+};
+const setExecutionProviders = (sessionOptionsHandle, executionProviders, allocs) => {
+ for (const ep of executionProviders) {
+ let epName = typeof ep === 'string' ? ep : ep.name;
+ // check EP name
+ switch (epName) {
+ case 'xnnpack':
+ epName = 'XNNPACK';
+ break;
+ case 'wasm':
+ case 'cpu':
+ continue;
+ default:
+ throw new Error(`not supported EP: ${epName}`);
+ }
+ const epNameDataOffset = (0, string_utils_1.allocWasmString)(epName, allocs);
+ if ((0, wasm_factory_1.getInstance)()._OrtAppendExecutionProvider(sessionOptionsHandle, epNameDataOffset) !== 0) {
+ throw new Error(`Can't append execution provider: ${epName}`);
+ }
+ }
+};
+const setSessionOptions = (options) => {
+ const wasm = (0, wasm_factory_1.getInstance)();
+ let sessionOptionsHandle = 0;
+ const allocs = [];
+ const sessionOptions = options || {};
+ appendDefaultOptions(sessionOptions);
+ try {
+ if ((options === null || options === void 0 ? void 0 : options.graphOptimizationLevel) === undefined) {
+ sessionOptions.graphOptimizationLevel = 'all';
+ }
+ const graphOptimizationLevel = getGraphOptimzationLevel(sessionOptions.graphOptimizationLevel);
+ if ((options === null || options === void 0 ? void 0 : options.enableCpuMemArena) === undefined) {
+ sessionOptions.enableCpuMemArena = true;
+ }
+ if ((options === null || options === void 0 ? void 0 : options.enableMemPattern) === undefined) {
+ sessionOptions.enableMemPattern = true;
+ }
+ if ((options === null || options === void 0 ? void 0 : options.executionMode) === undefined) {
+ sessionOptions.executionMode = 'sequential';
+ }
+ const executionMode = getExecutionMode(sessionOptions.executionMode);
+ let logIdDataOffset = 0;
+ if ((options === null || options === void 0 ? void 0 : options.logId) !== undefined) {
+ logIdDataOffset = (0, string_utils_1.allocWasmString)(options.logId, allocs);
+ }
+ if ((options === null || options === void 0 ? void 0 : options.logSeverityLevel) === undefined) {
+ sessionOptions.logSeverityLevel = 2; // Default to warning
+ }
+ else if (typeof options.logSeverityLevel !== 'number' || !Number.isInteger(options.logSeverityLevel) ||
+ options.logSeverityLevel < 0 || options.logSeverityLevel > 4) {
+ throw new Error(`log serverity level is not valid: ${options.logSeverityLevel}`);
+ }
+ if ((options === null || options === void 0 ? void 0 : options.logVerbosityLevel) === undefined) {
+ sessionOptions.logVerbosityLevel = 0; // Default to 0
+ }
+ else if (typeof options.logVerbosityLevel !== 'number' || !Number.isInteger(options.logVerbosityLevel)) {
+ throw new Error(`log verbosity level is not valid: ${options.logVerbosityLevel}`);
+ }
+ if ((options === null || options === void 0 ? void 0 : options.enableProfiling) === undefined) {
+ sessionOptions.enableProfiling = false;
+ }
+ sessionOptionsHandle = wasm._OrtCreateSessionOptions(graphOptimizationLevel, !!sessionOptions.enableCpuMemArena, !!sessionOptions.enableMemPattern, executionMode, !!sessionOptions.enableProfiling, 0, logIdDataOffset, sessionOptions.logSeverityLevel, sessionOptions.logVerbosityLevel);
+ if (sessionOptionsHandle === 0) {
+ throw new Error('Can\'t create session options');
+ }
+ if (options === null || options === void 0 ? void 0 : options.executionProviders) {
+ setExecutionProviders(sessionOptionsHandle, options.executionProviders, allocs);
+ }
+ if ((options === null || options === void 0 ? void 0 : options.extra) !== undefined) {
+ (0, options_utils_1.iterateExtraOptions)(options.extra, '', new WeakSet(), (key, value) => {
+ const keyDataOffset = (0, string_utils_1.allocWasmString)(key, allocs);
+ const valueDataOffset = (0, string_utils_1.allocWasmString)(value, allocs);
+ if (wasm._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {
+ throw new Error(`Can't set a session config entry: ${key} - ${value}`);
+ }
+ });
+ }
+ return [sessionOptionsHandle, allocs];
+ }
+ catch (e) {
+ if (sessionOptionsHandle !== 0) {
+ wasm._OrtReleaseSessionOptions(sessionOptionsHandle);
+ }
+ allocs.forEach(wasm._free);
+ throw e;
+ }
+};
+exports.setSessionOptions = setSessionOptions;
+
+
+/***/ }),
+
+/***/ "./lib/wasm/string-utils.ts":
+/*!**********************************!*\
+ !*** ./lib/wasm/string-utils.ts ***!
+ \**********************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.allocWasmString = void 0;
+const wasm_factory_1 = __webpack_require__(/*! ./wasm-factory */ "./lib/wasm/wasm-factory.ts");
+const allocWasmString = (data, allocs) => {
+ const wasm = (0, wasm_factory_1.getInstance)();
+ const dataLength = wasm.lengthBytesUTF8(data) + 1;
+ const dataOffset = wasm._malloc(dataLength);
+ wasm.stringToUTF8(data, dataOffset, dataLength);
+ allocs.push(dataOffset);
+ return dataOffset;
+};
+exports.allocWasmString = allocWasmString;
+
+
+/***/ }),
+
+/***/ "./lib/wasm/wasm-core-impl.ts":
+/*!************************************!*\
+ !*** ./lib/wasm/wasm-core-impl.ts ***!
+ \************************************/
+/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
+
+"use strict";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.extractTransferableBuffers = exports.endProfiling = exports.run = exports.releaseSession = exports.createSession = exports.createSessionFinalize = exports.createSessionAllocate = exports.initOrt = void 0;
+const run_options_1 = __webpack_require__(/*! ./run-options */ "./lib/wasm/run-options.ts");
+const session_options_1 = __webpack_require__(/*! ./session-options */ "./lib/wasm/session-options.ts");
+const string_utils_1 = __webpack_require__(/*! ./string-utils */ "./lib/wasm/string-utils.ts");
+const wasm_factory_1 = __webpack_require__(/*! ./wasm-factory */ "./lib/wasm/wasm-factory.ts");
+/**
+ * initialize ORT environment.
+ * @param numThreads SetGlobalIntraOpNumThreads(numThreads)
+ * @param loggingLevel CreateEnv(static_cast<OrtLoggingLevel>(logging_level))
+ */
+const initOrt = (numThreads, loggingLevel) => {
+ const errorCode = (0, wasm_factory_1.getInstance)()._OrtInit(numThreads, loggingLevel);
+ if (errorCode !== 0) {
+ throw new Error(`Can't initialize onnxruntime. error code = ${errorCode}`);
+ }
+};
+exports.initOrt = initOrt;
+const activeSessions = new Map();
+/**
+ * create an instance of InferenceSession.
+ * @returns the metadata of InferenceSession. 0-value handle for failure.
+ */
+const createSessionAllocate = (model) => {
+ const wasm = (0, wasm_factory_1.getInstance)();
+ const modelDataOffset = wasm._malloc(model.byteLength);
+ wasm.HEAPU8.set(model, modelDataOffset);
+ return [modelDataOffset, model.byteLength];
+};
+exports.createSessionAllocate = createSessionAllocate;
+const createSessionFinalize = (modelData, options) => {
+ const wasm = (0, wasm_factory_1.getInstance)();
+ let sessionHandle = 0;
+ let sessionOptionsHandle = 0;
+ let allocs = [];
+ try {
+ [sessionOptionsHandle, allocs] = (0, session_options_1.setSessionOptions)(options);
+ sessionHandle = wasm._OrtCreateSession(modelData[0], modelData[1], sessionOptionsHandle);
+ if (sessionHandle === 0) {
+ throw new Error('Can\'t create a session');
+ }
+ }
+ finally {
+ wasm._free(modelData[0]);
+ wasm._OrtReleaseSessionOptions(sessionOptionsHandle);
+ allocs.forEach(wasm._free);
+ }
+ const inputCount = wasm._OrtGetInputCount(sessionHandle);
+ const outputCount = wasm._OrtGetOutputCount(sessionHandle);
+ const inputNames = [];
+ const inputNamesUTF8Encoded = [];
+ const outputNames = [];
+ const outputNamesUTF8Encoded = [];
+ for (let i = 0; i < inputCount; i++) {
+ const name = wasm._OrtGetInputName(sessionHandle, i);
+ if (name === 0) {
+ throw new Error('Can\'t get an input name');
+ }
+ inputNamesUTF8Encoded.push(name);
+ inputNames.push(wasm.UTF8ToString(name));
+ }
+ for (let i = 0; i < outputCount; i++) {
+ const name = wasm._OrtGetOutputName(sessionHandle, i);
+ if (name === 0) {
+ throw new Error('Can\'t get an output name');
+ }
+ outputNamesUTF8Encoded.push(name);
+ outputNames.push(wasm.UTF8ToString(name));
+ }
+ activeSessions.set(sessionHandle, [sessionHandle, inputNamesUTF8Encoded, outputNamesUTF8Encoded]);
+ return [sessionHandle, inputNames, outputNames];
+};
+exports.createSessionFinalize = createSessionFinalize;
+/**
+ * create an instance of InferenceSession.
+ * @returns the metadata of InferenceSession. 0-value handle for failure.
+ */
+const createSession = (model, options) => {
+ const modelData = (0, exports.createSessionAllocate)(model);
+ return (0, exports.createSessionFinalize)(modelData, options);
+};
+exports.createSession = createSession;
+const releaseSession = (sessionId) => {
+ const wasm = (0, wasm_factory_1.getInstance)();
+ const session = activeSessions.get(sessionId);
+ if (!session) {
+ throw new Error('invalid session id');
+ }
+ const sessionHandle = session[0];
+ const inputNamesUTF8Encoded = session[1];
+ const outputNamesUTF8Encoded = session[2];
+ inputNamesUTF8Encoded.forEach(wasm._OrtFree);
+ outputNamesUTF8Encoded.forEach(wasm._OrtFree);
+ wasm._OrtReleaseSession(sessionHandle);
+ activeSessions.delete(sessionId);
+};
+exports.releaseSession = releaseSession;
+const tensorDataTypeStringToEnum = (type) => {
+ switch (type) {
+ case 'int8':
+ return 3 /* DataType.int8 */;
+ case 'uint8':
+ return 2 /* DataType.uint8 */;
+ case 'bool':
+ return 9 /* DataType.bool */;
+ case 'int16':
+ return 5 /* DataType.int16 */;
+ case 'uint16':
+ return 4 /* DataType.uint16 */;
+ case 'int32':
+ return 6 /* DataType.int32 */;
+ case 'uint32':
+ return 12 /* DataType.uint32 */;
+ case 'float32':
+ return 1 /* DataType.float */;
+ case 'float64':
+ return 11 /* DataType.double */;
+ case 'string':
+ return 8 /* DataType.string */;
+ case 'int64':
+ return 7 /* DataType.int64 */;
+ case 'uint64':
+ return 13 /* DataType.uint64 */;
+ default:
+ throw new Error(`unsupported data type: ${type}`);
+ }
+};
+const tensorDataTypeEnumToString = (typeProto) => {
+ switch (typeProto) {
+ case 3 /* DataType.int8 */:
+ return 'int8';
+ case 2 /* DataType.uint8 */:
+ return 'uint8';
+ case 9 /* DataType.bool */:
+ return 'bool';
+ case 5 /* DataType.int16 */:
+ return 'int16';
+ case 4 /* DataType.uint16 */:
+ return 'uint16';
+ case 6 /* DataType.int32 */:
+ return 'int32';
+ case 12 /* DataType.uint32 */:
+ return 'uint32';
+ case 1 /* DataType.float */:
+ return 'float32';
+ case 11 /* DataType.double */:
+ return 'float64';
+ case 8 /* DataType.string */:
+ return 'string';
+ case 7 /* DataType.int64 */:
+ return 'int64';
+ case 13 /* DataType.uint64 */:
+ return 'uint64';
+ default:
+ throw new Error(`unsupported data type: ${typeProto}`);
+ }
+};
+const numericTensorTypeToTypedArray = (type) => {
+ switch (type) {
+ case 'float32':
+ return Float32Array;
+ case 'uint8':
+ return Uint8Array;
+ case 'int8':
+ return Int8Array;
+ case 'uint16':
+ return Uint16Array;
+ case 'int16':
+ return Int16Array;
+ case 'int32':
+ return Int32Array;
+ case 'bool':
+ return Uint8Array;
+ case 'float64':
+ return Float64Array;
+ case 'uint32':
+ return Uint32Array;
+ case 'int64':
+ return BigInt64Array;
+ case 'uint64':
+ return BigUint64Array;
+ default:
+ throw new Error(`unsupported type: ${type}`);
+ }
+};
+/**
+ * perform inference run
+ */
+const run = (sessionId, inputIndices, inputs, outputIndices, options) => {
+ const wasm = (0, wasm_factory_1.getInstance)();
+ const session = activeSessions.get(sessionId);
+ if (!session) {
+ throw new Error('invalid session id');
+ }
+ const sessionHandle = session[0];
+ const inputNamesUTF8Encoded = session[1];
+ const outputNamesUTF8Encoded = session[2];
+ const inputCount = inputIndices.length;
+ const outputCount = outputIndices.length;
+ let runOptionsHandle = 0;
+ let runOptionsAllocs = [];
+ const inputValues = [];
+ const inputAllocs = [];
+ try {
+ [runOptionsHandle, runOptionsAllocs] = (0, run_options_1.setRunOptions)(options);
+ // create input tensors
+ for (let i = 0; i < inputCount; i++) {
+ const dataType = inputs[i][0];
+ const dims = inputs[i][1];
+ const data = inputs[i][2];
+ let dataOffset;
+ let dataByteLength;
+ if (Array.isArray(data)) {
+ // string tensor
+ dataByteLength = 4 * data.length;
+ dataOffset = wasm._malloc(dataByteLength);
+ inputAllocs.push(dataOffset);
+ let dataIndex = dataOffset / 4;
+ for (let i = 0; i < data.length; i++) {
+ if (typeof data[i] !== 'string') {
+ throw new TypeError(`tensor data at index ${i} is not a string`);
+ }
+ wasm.HEAPU32[dataIndex++] = (0, string_utils_1.allocWasmString)(data[i], inputAllocs);
+ }
+ }
+ else {
+ dataByteLength = data.byteLength;
+ dataOffset = wasm._malloc(dataByteLength);
+ inputAllocs.push(dataOffset);
+ wasm.HEAPU8.set(new Uint8Array(data.buffer, data.byteOffset, dataByteLength), dataOffset);
+ }
+ const stack = wasm.stackSave();
+ const dimsOffset = wasm.stackAlloc(4 * dims.length);
+ try {
+ let dimIndex = dimsOffset / 4;
+ dims.forEach(d => wasm.HEAP32[dimIndex++] = d);
+ const tensor = wasm._OrtCreateTensor(tensorDataTypeStringToEnum(dataType), dataOffset, dataByteLength, dimsOffset, dims.length);
+ if (tensor === 0) {
+ throw new Error('Can\'t create a tensor');
+ }
+ inputValues.push(tensor);
+ }
+ finally {
+ wasm.stackRestore(stack);
+ }
+ }
+ const beforeRunStack = wasm.stackSave();
+ const inputValuesOffset = wasm.stackAlloc(inputCount * 4);
+ const inputNamesOffset = wasm.stackAlloc(inputCount * 4);
+ const outputValuesOffset = wasm.stackAlloc(outputCount * 4);
+ const outputNamesOffset = wasm.stackAlloc(outputCount * 4);
+ try {
+ let inputValuesIndex = inputValuesOffset / 4;
+ let inputNamesIndex = inputNamesOffset / 4;
+ let outputValuesIndex = outputValuesOffset / 4;
+ let outputNamesIndex = outputNamesOffset / 4;
+ for (let i = 0; i < inputCount; i++) {
+ wasm.HEAPU32[inputValuesIndex++] = inputValues[i];
+ wasm.HEAPU32[inputNamesIndex++] = inputNamesUTF8Encoded[inputIndices[i]];
+ }
+ for (let i = 0; i < outputCount; i++) {
+ wasm.HEAPU32[outputValuesIndex++] = 0;
+ wasm.HEAPU32[outputNamesIndex++] = outputNamesUTF8Encoded[outputIndices[i]];
+ }
+ // support RunOptions
+ let errorCode = wasm._OrtRun(sessionHandle, inputNamesOffset, inputValuesOffset, inputCount, outputNamesOffset, outputCount, outputValuesOffset, runOptionsHandle);
+ const output = [];
+ if (errorCode === 0) {
+ for (let i = 0; i < outputCount; i++) {
+ const tensor = wasm.HEAPU32[outputValuesOffset / 4 + i];
+ const beforeGetTensorDataStack = wasm.stackSave();
+ // stack allocate 4 pointer value
+ const tensorDataOffset = wasm.stackAlloc(4 * 4);
+ let type, dataOffset = 0;
+ try {
+ errorCode = wasm._OrtGetTensorData(tensor, tensorDataOffset, tensorDataOffset + 4, tensorDataOffset + 8, tensorDataOffset + 12);
+ if (errorCode !== 0) {
+ throw new Error(`Can't access output tensor data. error code = ${errorCode}`);
+ }
+ let tensorDataIndex = tensorDataOffset / 4;
+ const dataType = wasm.HEAPU32[tensorDataIndex++];
+ dataOffset = wasm.HEAPU32[tensorDataIndex++];
+ const dimsOffset = wasm.HEAPU32[tensorDataIndex++];
+ const dimsLength = wasm.HEAPU32[tensorDataIndex++];
+ const dims = [];
+ for (let i = 0; i < dimsLength; i++) {
+ dims.push(wasm.HEAPU32[dimsOffset / 4 + i]);
+ }
+ wasm._OrtFree(dimsOffset);
+ const size = dims.length === 0 ? 1 : dims.reduce((a, b) => a * b);
+ type = tensorDataTypeEnumToString(dataType);
+ if (type === 'string') {
+ const stringData = [];
+ let dataIndex = dataOffset / 4;
+ for (let i = 0; i < size; i++) {
+ const offset = wasm.HEAPU32[dataIndex++];
+ const maxBytesToRead = i === size - 1 ? undefined : wasm.HEAPU32[dataIndex] - offset;
+ stringData.push(wasm.UTF8ToString(offset, maxBytesToRead));
+ }
+ output.push([type, dims, stringData]);
+ }
+ else {
+ const typedArrayConstructor = numericTensorTypeToTypedArray(type);
+ const data = new typedArrayConstructor(size);
+ new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
+ .set(wasm.HEAPU8.subarray(dataOffset, dataOffset + data.byteLength));
+ output.push([type, dims, data]);
+ }
+ }
+ finally {
+ wasm.stackRestore(beforeGetTensorDataStack);
+ if (type === 'string' && dataOffset) {
+ wasm._free(dataOffset);
+ }
+ wasm._OrtReleaseTensor(tensor);
+ }
+ }
+ }
+ if (errorCode === 0) {
+ return output;
+ }
+ else {
+ throw new Error(`failed to call OrtRun(). error code = ${errorCode}.`);
+ }
+ }
+ finally {
+ wasm.stackRestore(beforeRunStack);
+ }
+ }
+ finally {
+ inputValues.forEach(wasm._OrtReleaseTensor);
+ inputAllocs.forEach(wasm._free);
+ wasm._OrtReleaseRunOptions(runOptionsHandle);
+ runOptionsAllocs.forEach(wasm._free);
+ }
+};
+exports.run = run;
+/**
+ * end profiling
+ */
+const endProfiling = (sessionId) => {
+ const wasm = (0, wasm_factory_1.getInstance)();
+ const session = activeSessions.get(sessionId);
+ if (!session) {
+ throw new Error('invalid session id');
+ }
+ const sessionHandle = session[0];
+ // profile file name is not used yet, but it must be freed.
+ const profileFileName = wasm._OrtEndProfiling(sessionHandle);
+ if (profileFileName === 0) {
+ throw new Error('Can\'t get an profile file name');
+ }
+ wasm._OrtFree(profileFileName);
+};
+exports.endProfiling = endProfiling;
+const extractTransferableBuffers = (tensors) => {
+ const buffers = [];
+ for (const tensor of tensors) {
+ const data = tensor[2];
+ if (!Array.isArray(data) && data.buffer) {
+ buffers.push(data.buffer);
+ }
+ }
+ return buffers;
+};
+exports.extractTransferableBuffers = extractTransferableBuffers;
+
+
+/***/ }),
+
+/***/ "./lib/wasm/wasm-factory.ts":
+/*!**********************************!*\
+ !*** ./lib/wasm/wasm-factory.ts ***!
+ \**********************************/
+/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
+
+"use strict";
+var __dirname = "/";
+
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.dispose = exports.getInstance = exports.initializeWebAssembly = void 0;
+const path = __importStar(__webpack_require__(/*! path */ "?7aa5"));
+const ort_wasm_js_1 = __importDefault(__webpack_require__(/*! ./binding/ort-wasm.js */ "./lib/wasm/binding/ort-wasm.js"));
+const ortWasmFactoryThreaded =
+// eslint-disable-next-line @typescript-eslint/no-require-imports
+ true ? __webpack_require__(/*! ./binding/ort-wasm-threaded.js */ "./lib/wasm/binding/ort-wasm-threaded.js") : 0;
+let wasm;
+let initialized = false;
+let initializing = false;
+let aborted = false;
+const isMultiThreadSupported = () => {
+ try {
+ // If 'SharedArrayBuffer' is not available, WebAssembly threads will not work.
+ if (typeof SharedArrayBuffer === 'undefined') {
+ return false;
+ }
+ // Test for transferability of SABs (for browsers. needed for Firefox)
+ // https://groups.google.com/forum/#!msg/mozilla.dev.platform/IHkBZlHETpA/dwsMNchWEQAJ
+ if (typeof MessageChannel !== 'undefined') {
+ new MessageChannel().port1.postMessage(new SharedArrayBuffer(1));
+ }
+ // Test for WebAssembly threads capability (for both browsers and Node.js)
+ // This typed array is a WebAssembly program containing threaded instructions.
+ return WebAssembly.validate(new Uint8Array([
+ 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5,
+ 4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11
+ ]));
+ }
+ catch (e) {
+ return false;
+ }
+};
+const isSimdSupported = () => {
+ try {
+ // Test for WebAssembly SIMD capability (for both browsers and Node.js)
+ // This typed array is a WebAssembly program containing SIMD instructions.
+ // The binary data is generated from the following code by wat2wasm:
+ //
+ // (module
+ // (type $t0 (func))
+ // (func $f0 (type $t0)
+ // (drop
+ // (i32x4.dot_i16x8_s
+ // (i8x16.splat
+ // (i32.const 0))
+ // (v128.const i32x4 0x00000000 0x00000000 0x00000000 0x00000000)))))
+ return WebAssembly.validate(new Uint8Array([
+ 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 30, 1, 28, 0, 65, 0,
+ 253, 15, 253, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 253, 186, 1, 26, 11
+ ]));
+ }
+ catch (e) {
+ return false;
+ }
+};
+const getWasmFileName = (useSimd, useThreads) => {
+ if (useThreads) {
+ return useSimd ? 'ort-wasm-simd-threaded.wasm' : 'ort-wasm-threaded.wasm';
+ }
+ else {
+ return useSimd ? 'ort-wasm-simd.wasm' : 'ort-wasm.wasm';
+ }
+};
+const initializeWebAssembly = async (flags) => {
+ if (initialized) {
+ return Promise.resolve();
+ }
+ if (initializing) {
+ throw new Error('multiple calls to \'initializeWebAssembly()\' detected.');
+ }
+ if (aborted) {
+ throw new Error('previous call to \'initializeWebAssembly()\' failed.');
+ }
+ initializing = true;
+ // wasm flags are already initialized
+ const timeout = flags.initTimeout;
+ const numThreads = flags.numThreads;
+ const simd = flags.simd;
+ const useThreads = numThreads > 1 && isMultiThreadSupported();
+ const useSimd = simd && isSimdSupported();
+ const wasmPrefixOverride = typeof flags.wasmPaths === 'string' ? flags.wasmPaths : undefined;
+ const wasmFileName = getWasmFileName(false, useThreads);
+ const wasmOverrideFileName = getWasmFileName(useSimd, useThreads);
+ const wasmPathOverride = typeof flags.wasmPaths === 'object' ? flags.wasmPaths[wasmOverrideFileName] : undefined;
+ let isTimeout = false;
+ const tasks = [];
+ // promise for timeout
+ if (timeout > 0) {
+ tasks.push(new Promise((resolve) => {
+ setTimeout(() => {
+ isTimeout = true;
+ resolve();
+ }, timeout);
+ }));
+ }
+ // promise for module initialization
+ tasks.push(new Promise((resolve, reject) => {
+ const factory = useThreads ? ortWasmFactoryThreaded : ort_wasm_js_1.default;
+ const config = {
+ locateFile: (fileName, scriptDirectory) => {
+ if ( true && useThreads && fileName.endsWith('.worker.js') &&
+ typeof Blob !== 'undefined') {
+ return URL.createObjectURL(new Blob([
+ // This require() function is handled by webpack to load file content of the corresponding .worker.js
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ __webpack_require__(/*! ./binding/ort-wasm-threaded.worker.js */ "./lib/wasm/binding/ort-wasm-threaded.worker.js")
+ ], { type: 'text/javascript' }));
+ }
+ if (fileName === wasmFileName) {
+ const prefix = wasmPrefixOverride !== null && wasmPrefixOverride !== void 0 ? wasmPrefixOverride : scriptDirectory;
+ return wasmPathOverride !== null && wasmPathOverride !== void 0 ? wasmPathOverride : prefix + wasmOverrideFileName;
+ }
+ return scriptDirectory + fileName;
+ }
+ };
+ if ( true && useThreads) {
+ if (typeof Blob === 'undefined') {
+ config.mainScriptUrlOrBlob = path.join(__dirname, 'ort-wasm-threaded.js');
+ }
+ else {
+ const scriptSourceCode = `var ortWasmThreaded=(function(){var _scriptDir;return ${factory.toString()}})();`;
+ config.mainScriptUrlOrBlob = new Blob([scriptSourceCode], { type: 'text/javascript' });
+ }
+ }
+ factory(config).then(
+ // wasm module initialized successfully
+ module => {
+ initializing = false;
+ initialized = true;
+ wasm = module;
+ resolve();
+ },
+ // wasm module failed to initialize
+ (what) => {
+ initializing = false;
+ aborted = true;
+ reject(what);
+ });
+ }));
+ await Promise.race(tasks);
+ if (isTimeout) {
+ throw new Error(`WebAssembly backend initializing failed due to timeout: ${timeout}ms`);
+ }
+};
+exports.initializeWebAssembly = initializeWebAssembly;
+const getInstance = () => {
+ if (initialized && wasm) {
+ return wasm;
+ }
+ throw new Error('WebAssembly is not initialized yet.');
+};
+exports.getInstance = getInstance;
+const dispose = () => {
+ var _a;
+ if (initialized && !initializing && !aborted) {
+ initializing = true;
+ (_a = wasm.PThread) === null || _a === void 0 ? void 0 : _a.terminateAllThreads();
+ wasm = undefined;
+ initializing = false;
+ initialized = false;
+ aborted = true;
+ }
+};
+exports.dispose = dispose;
+
+
+/***/ }),
+
+/***/ "./node_modules/worker-loader/dist/cjs.js?inline=no-fallback!./lib/wasm/proxy-worker/main.ts":
+/*!***************************************************************************************************!*\
+ !*** ./node_modules/worker-loader/dist/cjs.js?inline=no-fallback!./lib/wasm/proxy-worker/main.ts ***!
+ \***************************************************************************************************/
+/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "default": () => (/* binding */ Worker_fn)
+/* harmony export */ });
+/* harmony import */ var _node_modules_worker_loader_dist_runtime_inline_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! !!../../../node_modules/worker-loader/dist/runtime/inline.js */ "./node_modules/worker-loader/dist/runtime/inline.js");
+/* harmony import */ var _node_modules_worker_loader_dist_runtime_inline_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_worker_loader_dist_runtime_inline_js__WEBPACK_IMPORTED_MODULE_0__);
+
+
+
+function Worker_fn() {
+ return _node_modules_worker_loader_dist_runtime_inline_js__WEBPACK_IMPORTED_MODULE_0___default()("/*!\n* ONNX Runtime Web v1.14.0\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\n/******/ (() => { // webpackBootstrap\n/******/ \tvar __webpack_modules__ = ({\n\n/***/ \"./lib/wasm/binding/ort-wasm-threaded.js\":\n/*!***********************************************!*\\\n !*** ./lib/wasm/binding/ort-wasm-threaded.js ***!\n \\***********************************************/\n/***/ ((module, __unused_webpack_exports, __webpack_require__) => {\n\nvar __filename = \"/index.js\";\nvar __dirname = \"/\";\n\r\nvar ortWasmThreaded = (() => {\r\n var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;\r\n if (true) _scriptDir = _scriptDir || __filename;\r\n return (\r\nfunction(ortWasmThreaded) {\r\n ortWasmThreaded = ortWasmThreaded || {};\r\n\r\n\r\nfunction d(){m.buffer!=n&&p(m.buffer);return aa}function q(){m.buffer!=n&&p(m.buffer);return ba}function r(){m.buffer!=n&&p(m.buffer);return ca}function v(){m.buffer!=n&&p(m.buffer);return da}function ea(){m.buffer!=n&&p(m.buffer);return fa}var x;x||(x=typeof ortWasmThreaded !== 'undefined' ? ortWasmThreaded : {});var ha,ia;x.ready=new Promise(function(a,b){ha=a;ia=b});\r\nvar ja=Object.assign({},x),ka=\"./this.program\",la=(a,b)=>{throw b;},ma=\"object\"==typeof window,y=\"function\"==typeof importScripts,B=\"object\"==typeof process&&\"object\"==typeof process.versions&&\"string\"==typeof process.versions.node,C=x.ENVIRONMENT_IS_PTHREAD||!1,D=\"\";function na(a){return x.locateFile?x.locateFile(a,D):D+a}var oa,pa,qa,fs,ra,sa;\r\nif(B){D=y?(__webpack_require__(/*! path */ \"?75c6\").dirname)(D)+\"/\":__dirname+\"/\";sa=()=>{ra||(fs=__webpack_require__(/*! fs */ \"?63c8\"),ra=__webpack_require__(/*! path */ \"?75c6\"))};oa=function(b,c){sa();b=ra.normalize(b);return fs.readFileSync(b,c?void 0:\"utf8\")};qa=b=>{b=oa(b,!0);b.buffer||(b=new Uint8Array(b));return b};pa=(b,c,e)=>{sa();b=ra.normalize(b);fs.readFile(b,function(f,h){f?e(f):c(h.buffer)})};1<process.argv.length&&(ka=process.argv[1].replace(/\\\\/g,\"/\"));process.argv.slice(2);process.on(\"uncaughtException\",function(b){if(!(b instanceof E))throw b;});process.on(\"unhandledRejection\",\r\nfunction(b){throw b;});la=(b,c)=>{if(F())throw process.exitCode=b,c;c instanceof E||G(\"exiting due to exception: \"+c);process.exit(b)};x.inspect=function(){return\"[Emscripten Module object]\"};let a;try{a=__webpack_require__(/*! worker_threads */ \"?c6f7\")}catch(b){throw console.error('The \"worker_threads\" module is not supported in this node.js build - perhaps a newer version is needed?'),b;}__webpack_require__.g.Worker=a.Worker}else if(ma||y)y?D=self.location.href:\"undefined\"!=typeof document&&document.currentScript&&(D=document.currentScript.src),\r\n_scriptDir&&(D=_scriptDir),0!==D.indexOf(\"blob:\")?D=D.substr(0,D.replace(/[?#].*/,\"\").lastIndexOf(\"/\")+1):D=\"\",B||(oa=a=>{var b=new XMLHttpRequest;b.open(\"GET\",a,!1);b.send(null);return b.responseText},y&&(qa=a=>{var b=new XMLHttpRequest;b.open(\"GET\",a,!1);b.responseType=\"arraybuffer\";b.send(null);return new Uint8Array(b.response)}),pa=(a,b,c)=>{var e=new XMLHttpRequest;e.open(\"GET\",a,!0);e.responseType=\"arraybuffer\";e.onload=()=>{200==e.status||0==e.status&&e.response?b(e.response):c()};e.onerror=\r\nc;e.send(null)});B&&\"undefined\"==typeof performance&&(__webpack_require__.g.performance=(__webpack_require__(/*! perf_hooks */ \"?674f\").performance));var ta=console.log.bind(console),ua=console.warn.bind(console);B&&(sa(),ta=a=>fs.writeSync(1,a+\"\\n\"),ua=a=>fs.writeSync(2,a+\"\\n\"));var va=x.print||ta,G=x.printErr||ua;Object.assign(x,ja);ja=null;x.thisProgram&&(ka=x.thisProgram);x.quit&&(la=x.quit);var H;x.wasmBinary&&(H=x.wasmBinary);var noExitRuntime=x.noExitRuntime||!1;\"object\"!=typeof WebAssembly&&I(\"no native wasm support detected\");\r\nvar m,wa,xa=!1,ya=\"undefined\"!=typeof TextDecoder?new TextDecoder(\"utf8\"):void 0;\r\nfunction za(a,b,c){b>>>=0;var e=b+c;for(c=b;a[c]&&!(c>=e);)++c;if(16<c-b&&a.buffer&&ya)return ya.decode(a.buffer instanceof SharedArrayBuffer?a.slice(b,c):a.subarray(b,c));for(e=\"\";b<c;){var f=a[b++];if(f&128){var h=a[b++]&63;if(192==(f&224))e+=String.fromCharCode((f&31)<<6|h);else{var k=a[b++]&63;f=224==(f&240)?(f&15)<<12|h<<6|k:(f&7)<<18|h<<12|k<<6|a[b++]&63;65536>f?e+=String.fromCharCode(f):(f-=65536,e+=String.fromCharCode(55296|f>>10,56320|f&1023))}}else e+=String.fromCharCode(f)}return e}\r\nfunction Aa(a,b){return(a>>>=0)?za(q(),a,b):\"\"}\r\nfunction Ba(a,b,c,e){c>>>=0;if(!(0<e))return 0;var f=c;e=c+e-1;for(var h=0;h<a.length;++h){var k=a.charCodeAt(h);if(55296<=k&&57343>=k){var l=a.charCodeAt(++h);k=65536+((k&1023)<<10)|l&1023}if(127>=k){if(c>=e)break;b[c++>>>0]=k}else{if(2047>=k){if(c+1>=e)break;b[c++>>>0]=192|k>>6}else{if(65535>=k){if(c+2>=e)break;b[c++>>>0]=224|k>>12}else{if(c+3>=e)break;b[c++>>>0]=240|k>>18;b[c++>>>0]=128|k>>12&63}b[c++>>>0]=128|k>>6&63}b[c++>>>0]=128|k&63}}b[c>>>0]=0;return c-f}\r\nfunction Ca(a){for(var b=0,c=0;c<a.length;++c){var e=a.charCodeAt(c);127>=e?b++:2047>=e?b+=2:55296<=e&&57343>=e?(b+=4,++c):b+=3}return b}var n,aa,ba,ca,da,fa;C&&(n=x.buffer);function p(a){n=a;x.HEAP8=aa=new Int8Array(a);x.HEAP16=new Int16Array(a);x.HEAP32=ca=new Int32Array(a);x.HEAPU8=ba=new Uint8Array(a);x.HEAPU16=new Uint16Array(a);x.HEAPU32=da=new Uint32Array(a);x.HEAPF32=new Float32Array(a);x.HEAPF64=fa=new Float64Array(a)}var Da=x.INITIAL_MEMORY||16777216;\r\nif(C)m=x.wasmMemory,n=x.buffer;else if(x.wasmMemory)m=x.wasmMemory;else if(m=new WebAssembly.Memory({initial:Da/65536,maximum:65536,shared:!0}),!(m.buffer instanceof SharedArrayBuffer))throw G(\"requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag\"),B&&console.log(\"(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)\"),\r\nError(\"bad memory\");m&&(n=m.buffer);Da=n.byteLength;p(n);var Ea,Fa=[],Ga=[],Ha=[],Ia=[],Ja=0;function F(){return noExitRuntime||0<Ja}function Ka(){var a=x.preRun.shift();Fa.unshift(a)}var L=0,La=null,M=null;function I(a){if(C)postMessage({cmd:\"onAbort\",arg:a});else if(x.onAbort)x.onAbort(a);a=\"Aborted(\"+a+\")\";G(a);xa=!0;a=new WebAssembly.RuntimeError(a+\". Build with -sASSERTIONS for more info.\");ia(a);throw a;}function Ma(){return O.startsWith(\"data:application/octet-stream;base64,\")}var O;O=\"ort-wasm-threaded.wasm\";\r\nMa()||(O=na(O));function Na(){var a=O;try{if(a==O&&H)return new Uint8Array(H);if(qa)return qa(a);throw\"both async and sync fetching of the wasm failed\";}catch(b){I(b)}}\r\nfunction Oa(){if(!H&&(ma||y)){if(\"function\"==typeof fetch&&!O.startsWith(\"file://\"))return fetch(O,{credentials:\"same-origin\"}).then(function(a){if(!a.ok)throw\"failed to load wasm binary file at '\"+O+\"'\";return a.arrayBuffer()}).catch(function(){return Na()});if(pa)return new Promise(function(a,b){pa(O,function(c){a(new Uint8Array(c))},b)})}return Promise.resolve().then(function(){return Na()})}var Pa={};\r\nfunction E(a){this.name=\"ExitStatus\";this.message=\"Program terminated with exit(\"+a+\")\";this.status=a}function Qa(a){(a=P.Vb[a])||I();P.mc(a)}function Ra(a){var b=P.Cc();if(!b)return 6;P.ac.push(b);P.Vb[a.Ub]=b;b.Ub=a.Ub;var c={cmd:\"run\",start_routine:a.Ic,arg:a.zc,pthread_ptr:a.Ub};b.$b=()=>{c.time=performance.now();b.postMessage(c,a.Nc)};b.loaded&&(b.$b(),delete b.$b);return 0}function Sa(a){if(C)return Q(1,1,a);if(!F()){P.oc();if(x.onExit)x.onExit(a);xa=!0}la(a,new E(a))}\r\nfunction Ta(a,b){if(!b&&C)throw Ua(a),\"unwind\";F()||C||(Va(),R(Ha),Wa(0),Xa[1].length&&Ya(1,10),Xa[2].length&&Ya(2,10),P.oc());Sa(a)}\r\nvar P={Yb:[],ac:[],qc:[],Vb:{},fc:function(){C&&P.Ec()},Pc:function(){},Ec:function(){P.receiveObjectTransfer=P.Gc;P.threadInitTLS=P.pc;P.setExitStatus=P.nc;noExitRuntime=!1},nc:function(){},oc:function(){for(var a of Object.values(P.Vb))P.mc(a);for(a of P.Yb)a.terminate();P.Yb=[]},mc:function(a){var b=a.Ub;delete P.Vb[b];P.Yb.push(a);P.ac.splice(P.ac.indexOf(a),1);a.Ub=0;Za(b)},Gc:function(){},pc:function(){P.qc.forEach(a=>a())},Fc:function(a,b){a.onmessage=c=>{c=c.data;var e=c.cmd;a.Ub&&(P.Bc=a.Ub);\r\nif(c.targetThread&&c.targetThread!=$a()){var f=P.Vb[c.Qc];f?f.postMessage(c,c.transferList):G('Internal error! Worker sent a message \"'+e+'\" to target pthread '+c.targetThread+\", but that thread no longer exists!\")}else if(\"processProxyingQueue\"===e)ab(c.queue);else if(\"spawnThread\"===e)Ra(c);else if(\"cleanupThread\"===e)Qa(c.thread);else if(\"killThread\"===e)c=c.thread,e=P.Vb[c],delete P.Vb[c],e.terminate(),Za(c),P.ac.splice(P.ac.indexOf(e),1),e.Ub=0;else if(\"cancelThread\"===e)P.Vb[c.thread].postMessage({cmd:\"cancel\"});\r\nelse if(\"loaded\"===e)a.loaded=!0,b&&b(a),a.$b&&(a.$b(),delete a.$b);else if(\"print\"===e)va(\"Thread \"+c.threadId+\": \"+c.text);else if(\"printErr\"===e)G(\"Thread \"+c.threadId+\": \"+c.text);else if(\"alert\"===e)alert(\"Thread \"+c.threadId+\": \"+c.text);else if(\"setimmediate\"===c.target)a.postMessage(c);else if(\"onAbort\"===e){if(x.onAbort)x.onAbort(c.arg)}else e&&G(\"worker sent an unknown command \"+e);P.Bc=void 0};a.onerror=c=>{G(\"worker sent an error! \"+c.filename+\":\"+c.lineno+\": \"+c.message);throw c;};B&&\r\n(a.on(\"message\",function(c){a.onmessage({data:c})}),a.on(\"error\",function(c){a.onerror(c)}),a.on(\"detachedExit\",function(){}));a.postMessage({cmd:\"load\",urlOrBlob:x.mainScriptUrlOrBlob||_scriptDir,wasmMemory:m,wasmModule:wa})},yc:function(){var a=na(\"ort-wasm-threaded.worker.js\");P.Yb.push(new Worker(a))},Cc:function(){0==P.Yb.length&&(P.yc(),P.Fc(P.Yb[0]));return P.Yb.pop()}};x.PThread=P;function R(a){for(;0<a.length;)a.shift()(x)}function bb(a){var b=S();a=a();U(b);return a}\r\nx.establishStackSpace=function(){var a=$a(),b=r()[a+44>>2>>>0];a=r()[a+48>>2>>>0];cb(b,b-a);U(b)};function Ua(a){if(C)return Q(2,0,a);try{Ta(a)}catch(b){b instanceof E||\"unwind\"==b||la(1,b)}}var db=[];function V(a){var b=db[a];b||(a>=db.length&&(db.length=a+1),db[a]=b=Ea.get(a));return b}x.invokeEntryPoint=function(a,b){a=V(a)(b);F()?P.nc(a):eb(a)};function fb(a,b){d().set(a,b>>>0)}var gb=[],hb=0,W=0;\r\nfunction X(a){this.Zb=a;this.Sb=a-24;this.xc=function(b){v()[this.Sb+4>>2>>>0]=b};this.bc=function(){return v()[this.Sb+4>>2>>>0]};this.wc=function(b){v()[this.Sb+8>>2>>>0]=b};this.Dc=function(){return v()[this.Sb+8>>2>>>0]};this.rc=function(){r()[this.Sb>>2>>>0]=0};this.hc=function(b){b=b?1:0;d()[this.Sb+12>>0>>>0]=b};this.uc=function(){return 0!=d()[this.Sb+12>>0>>>0]};this.ic=function(b){b=b?1:0;d()[this.Sb+13>>0>>>0]=b};this.kc=function(){return 0!=d()[this.Sb+13>>0>>>0]};this.fc=function(b,c){this.cc(0);\r\nthis.xc(b);this.wc(c);this.rc();this.hc(!1);this.ic(!1)};this.sc=function(){Atomics.add(r(),this.Sb>>2,1)};this.Hc=function(){return 1===Atomics.sub(r(),this.Sb>>2,1)};this.cc=function(b){v()[this.Sb+16>>2>>>0]=b};this.tc=function(){return v()[this.Sb+16>>2>>>0]};this.vc=function(){if(ib(this.bc()))return v()[this.Zb>>2>>>0];var b=this.tc();return 0!==b?b:this.Zb}}function jb(a){return kb((new X(a)).Sb)}function lb(a,b,c,e){return C?Q(3,1,a,b,c,e):mb(a,b,c,e)}\r\nfunction mb(a,b,c,e){if(\"undefined\"==typeof SharedArrayBuffer)return G(\"Current environment does not support SharedArrayBuffer, pthreads are not available!\"),6;var f=[];if(C&&0===f.length)return lb(a,b,c,e);a={Ic:c,Ub:a,zc:e,Nc:f};return C?(a.Oc=\"spawnThread\",postMessage(a,f),0):Ra(a)}function nb(a,b,c){return C?Q(4,1,a,b,c):0}function ob(a,b){if(C)return Q(5,1,a,b)}function pb(a,b){if(C)return Q(6,1,a,b)}function qb(a,b,c){if(C)return Q(7,1,a,b,c)}function rb(a,b,c){return C?Q(8,1,a,b,c):0}\r\nfunction sb(a,b){if(C)return Q(9,1,a,b)}function tb(a,b,c){if(C)return Q(10,1,a,b,c)}function ub(a,b,c,e){if(C)return Q(11,1,a,b,c,e)}function vb(a,b,c,e){if(C)return Q(12,1,a,b,c,e)}function wb(a,b,c,e){if(C)return Q(13,1,a,b,c,e)}function xb(a){if(C)return Q(14,1,a)}function yb(a,b){if(C)return Q(15,1,a,b)}function zb(a,b,c){if(C)return Q(16,1,a,b,c)}function ab(a){Atomics.store(r(),a>>2,1);$a()&&Ab(a);Atomics.compareExchange(r(),a>>2,1,0)}x.executeNotifiedProxyingQueue=ab;\r\nfunction Bb(a){return v()[a>>>2]+4294967296*r()[a+4>>>2]}function Cb(a,b,c,e,f,h){return C?Q(17,1,a,b,c,e,f,h):-52}function Db(a,b,c,e,f,h){if(C)return Q(18,1,a,b,c,e,f,h)}function Eb(a){var b=Ca(a)+1,c=Fb(b);c&&Ba(a,d(),c,b);return c}\r\nfunction Gb(a,b,c){function e(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:\"GMT\"}if(C)return Q(19,1,a,b,c);var f=(new Date).getFullYear(),h=new Date(f,0,1),k=new Date(f,6,1);f=h.getTimezoneOffset();var l=k.getTimezoneOffset(),u=Math.max(f,l);r()[a>>2>>>0]=60*u;r()[b>>2>>>0]=Number(f!=l);a=e(h);b=e(k);a=Eb(a);b=Eb(b);l<f?(v()[c>>2>>>0]=a,v()[c+4>>2>>>0]=b):(v()[c>>2>>>0]=b,v()[c+4>>2>>>0]=a)}function Hb(a,b,c){Hb.Ac||(Hb.Ac=!0,Gb(a,b,c))}var Ib,Jb;\r\nJb=B?()=>{var a=process.hrtime();return 1E3*a[0]+a[1]/1E6}:C?()=>performance.now()-x.__performance_now_clock_drift:()=>performance.now();function Q(a,b){var c=arguments.length-2,e=arguments;return bb(()=>{for(var f=Kb(8*c),h=f>>3,k=0;k<c;k++){var l=e[2+k];ea()[h+k>>>0]=l}return Lb(a,c,f,b)})}var Mb=[],Nb={};\r\nfunction Ob(){if(!Pb){var a={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\",_:ka||\"./this.program\"},b;for(b in Nb)void 0===Nb[b]?delete a[b]:a[b]=Nb[b];var c=[];for(b in a)c.push(b+\"=\"+a[b]);Pb=c}return Pb}var Pb;\r\nfunction Qb(a,b){if(C)return Q(20,1,a,b);var c=0;Ob().forEach(function(e,f){var h=b+c;f=v()[a+4*f>>2>>>0]=h;for(h=0;h<e.length;++h)d()[f++>>0>>>0]=e.charCodeAt(h);d()[f>>0>>>0]=0;c+=e.length+1});return 0}function Rb(a,b){if(C)return Q(21,1,a,b);var c=Ob();v()[a>>2>>>0]=c.length;var e=0;c.forEach(function(f){e+=f.length+1});v()[b>>2>>>0]=e;return 0}function Sb(a){return C?Q(22,1,a):52}function Tb(a,b,c,e){return C?Q(23,1,a,b,c,e):52}function Ub(a,b,c,e,f){return C?Q(24,1,a,b,c,e,f):70}\r\nvar Xa=[null,[],[]];function Ya(a,b){var c=Xa[a];0===b||10===b?((1===a?va:G)(za(c,0)),c.length=0):c.push(b)}function Vb(a,b,c,e){if(C)return Q(25,1,a,b,c,e);for(var f=0,h=0;h<c;h++){var k=v()[b>>2>>>0],l=v()[b+4>>2>>>0];b+=8;for(var u=0;u<l;u++)Ya(a,q()[k+u>>>0]);f+=l}v()[e>>2>>>0]=f;return 0}var Y=0;\r\nfunction Wb(){if(\"object\"==typeof crypto&&\"function\"==typeof crypto.getRandomValues){var a=new Uint8Array(1);return()=>{crypto.getRandomValues(a);return a[0]}}if(B)try{var b=__webpack_require__(Object(function webpackMissingModule() { var e = new Error(\"Cannot find module 'crypto'\"); e.code = 'MODULE_NOT_FOUND'; throw e; }()));return()=>b.randomBytes(1)[0]}catch(c){}return()=>I(\"randomDevice\")}function Xb(a,b){Xb.lc||(Xb.lc=Wb());for(var c=0;c<b;c++)d()[a+c>>0>>>0]=Xb.lc();return 0}function Yb(a){return 0===a%4&&(0!==a%100||0===a%400)}var Zb=[31,29,31,30,31,30,31,31,30,31,30,31],$b=[31,28,31,30,31,30,31,31,30,31,30,31];\r\nfunction ac(a){var b=Array(Ca(a)+1);Ba(a,b,0,b.length);return b}\r\nfunction bc(a,b,c,e){function f(g,w,z){for(g=\"number\"==typeof g?g.toString():g||\"\";g.length<w;)g=z[0]+g;return g}function h(g,w){return f(g,w,\"0\")}function k(g,w){function z(T){return 0>T?-1:0<T?1:0}var N;0===(N=z(g.getFullYear()-w.getFullYear()))&&0===(N=z(g.getMonth()-w.getMonth()))&&(N=z(g.getDate()-w.getDate()));return N}function l(g){switch(g.getDay()){case 0:return new Date(g.getFullYear()-1,11,29);case 1:return g;case 2:return new Date(g.getFullYear(),0,3);case 3:return new Date(g.getFullYear(),\r\n0,2);case 4:return new Date(g.getFullYear(),0,1);case 5:return new Date(g.getFullYear()-1,11,31);case 6:return new Date(g.getFullYear()-1,11,30)}}function u(g){var w=g.Wb;for(g=new Date((new Date(g.Xb+1900,0,1)).getTime());0<w;){var z=g.getMonth(),N=(Yb(g.getFullYear())?Zb:$b)[z];if(w>N-g.getDate())w-=N-g.getDate()+1,g.setDate(1),11>z?g.setMonth(z+1):(g.setMonth(0),g.setFullYear(g.getFullYear()+1));else{g.setDate(g.getDate()+w);break}}z=new Date(g.getFullYear()+1,0,4);w=l(new Date(g.getFullYear(),\r\n0,4));z=l(z);return 0>=k(w,g)?0>=k(z,g)?g.getFullYear()+1:g.getFullYear():g.getFullYear()-1}var t=r()[e+40>>2>>>0];e={Lc:r()[e>>2>>>0],Kc:r()[e+4>>2>>>0],dc:r()[e+8>>2>>>0],jc:r()[e+12>>2>>>0],ec:r()[e+16>>2>>>0],Xb:r()[e+20>>2>>>0],Tb:r()[e+24>>2>>>0],Wb:r()[e+28>>2>>>0],Rc:r()[e+32>>2>>>0],Jc:r()[e+36>>2>>>0],Mc:t?Aa(t):\"\"};c=Aa(c);t={\"%c\":\"%a %b %d %H:%M:%S %Y\",\"%D\":\"%m/%d/%y\",\"%F\":\"%Y-%m-%d\",\"%h\":\"%b\",\"%r\":\"%I:%M:%S %p\",\"%R\":\"%H:%M\",\"%T\":\"%H:%M:%S\",\"%x\":\"%m/%d/%y\",\"%X\":\"%H:%M:%S\",\"%Ec\":\"%c\",\"%EC\":\"%C\",\r\n\"%Ex\":\"%m/%d/%y\",\"%EX\":\"%H:%M:%S\",\"%Ey\":\"%y\",\"%EY\":\"%Y\",\"%Od\":\"%d\",\"%Oe\":\"%e\",\"%OH\":\"%H\",\"%OI\":\"%I\",\"%Om\":\"%m\",\"%OM\":\"%M\",\"%OS\":\"%S\",\"%Ou\":\"%u\",\"%OU\":\"%U\",\"%OV\":\"%V\",\"%Ow\":\"%w\",\"%OW\":\"%W\",\"%Oy\":\"%y\"};for(var A in t)c=c.replace(new RegExp(A,\"g\"),t[A]);var K=\"Sunday Monday Tuesday Wednesday Thursday Friday Saturday\".split(\" \"),J=\"January February March April May June July August September October November December\".split(\" \");t={\"%a\":function(g){return K[g.Tb].substring(0,3)},\"%A\":function(g){return K[g.Tb]},\r\n\"%b\":function(g){return J[g.ec].substring(0,3)},\"%B\":function(g){return J[g.ec]},\"%C\":function(g){return h((g.Xb+1900)/100|0,2)},\"%d\":function(g){return h(g.jc,2)},\"%e\":function(g){return f(g.jc,2,\" \")},\"%g\":function(g){return u(g).toString().substring(2)},\"%G\":function(g){return u(g)},\"%H\":function(g){return h(g.dc,2)},\"%I\":function(g){g=g.dc;0==g?g=12:12<g&&(g-=12);return h(g,2)},\"%j\":function(g){for(var w=0,z=0;z<=g.ec-1;w+=(Yb(g.Xb+1900)?Zb:$b)[z++]);return h(g.jc+w,3)},\"%m\":function(g){return h(g.ec+\r\n1,2)},\"%M\":function(g){return h(g.Kc,2)},\"%n\":function(){return\"\\n\"},\"%p\":function(g){return 0<=g.dc&&12>g.dc?\"AM\":\"PM\"},\"%S\":function(g){return h(g.Lc,2)},\"%t\":function(){return\"\\t\"},\"%u\":function(g){return g.Tb||7},\"%U\":function(g){return h(Math.floor((g.Wb+7-g.Tb)/7),2)},\"%V\":function(g){var w=Math.floor((g.Wb+7-(g.Tb+6)%7)/7);2>=(g.Tb+371-g.Wb-2)%7&&w++;if(w)53==w&&(z=(g.Tb+371-g.Wb)%7,4==z||3==z&&Yb(g.Xb)||(w=1));else{w=52;var z=(g.Tb+7-g.Wb-1)%7;(4==z||5==z&&Yb(g.Xb%400-1))&&w++}return h(w,\r\n2)},\"%w\":function(g){return g.Tb},\"%W\":function(g){return h(Math.floor((g.Wb+7-(g.Tb+6)%7)/7),2)},\"%y\":function(g){return(g.Xb+1900).toString().substring(2)},\"%Y\":function(g){return g.Xb+1900},\"%z\":function(g){g=g.Jc;var w=0<=g;g=Math.abs(g)/60;return(w?\"+\":\"-\")+String(\"0000\"+(g/60*100+g%60)).slice(-4)},\"%Z\":function(g){return g.Mc},\"%%\":function(){return\"%\"}};c=c.replace(/%%/g,\"\\x00\\x00\");for(A in t)c.includes(A)&&(c=c.replace(new RegExp(A,\"g\"),t[A](e)));c=c.replace(/\\0\\0/g,\"%\");A=ac(c);if(A.length>\r\nb)return 0;fb(A,a);return A.length-1}P.fc();\r\nvar cc=[null,Sa,Ua,lb,nb,ob,pb,qb,rb,sb,tb,ub,vb,wb,xb,yb,zb,Cb,Db,Gb,Qb,Rb,Sb,Tb,Ub,Vb],Pc={b:function(a){return Fb(a+24)+24},n:function(a){a=new X(a);a.uc()||(a.hc(!0),hb--);a.ic(!1);gb.push(a);a.sc();return a.vc()},ma:function(a){G(\"Unexpected exception thrown, this is not properly supported - aborting\");xa=!0;throw a;},x:function(){Z(0);var a=gb.pop();if(a.Hc()&&!a.kc()){var b=a.Dc();b&&V(b)(a.Zb);jb(a.Zb)}W=0},e:function(){var a=W;if(!a)return Y=0;var b=new X(a);b.cc(a);var c=b.bc();if(!c)return Y=\r\n0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;if(dc(h,c,b.Sb+16))return Y=h,a}Y=c;return a},l:function(){var a=W;if(!a)return Y=0;var b=new X(a);b.cc(a);var c=b.bc();if(!c)return Y=0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;if(dc(h,c,b.Sb+16))return Y=h,a}Y=c;return a},h:function(){var a=W;if(!a)return Y=0;var b=new X(a);b.cc(a);var c=b.bc();if(!c)return Y=0,a;for(var e=Array.prototype.slice.call(arguments),\r\nf=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;if(dc(h,c,b.Sb+16))return Y=h,a}Y=c;return a},t:jb,M:function(){var a=gb.pop();a||I(\"no exception to throw\");var b=a.Zb;a.kc()||(gb.push(a),a.ic(!0),a.hc(!1),hb++);W=b;throw b;},c:function(a,b,c){(new X(a)).fc(b,c);W=a;hb++;throw a;},pa:function(){return hb},Fa:function(a){ec(a,!y,1,!ma);P.pc()},T:function(a){C?postMessage({cmd:\"cleanupThread\",thread:a}):Qa(a)},xa:mb,j:function(a){W||(W=a);throw a;},H:nb,Ma:ob,ua:pb,wa:qb,oa:rb,Ka:sb,Ca:tb,Ja:ub,\r\nV:vb,va:wb,sa:xb,La:yb,ta:zb,Ta:function(){},X:function(){I(\"To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking\")},Ua:function(){I(\"To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking\")},W:function(){return Date.now()},ya:function(){return 2097152},Oa:function(){return!0},za:function(a,b,c,e){if(a==b)setTimeout(()=>ab(e));else if(C)postMessage({targetThread:a,cmd:\"processProxyingQueue\",\r\nqueue:e});else{a=P.Vb[a];if(!a)return;a.postMessage({cmd:\"processProxyingQueue\",queue:e})}return 1},Ea:function(){return-1},Pa:function(a,b){a=new Date(1E3*Bb(a));r()[b>>2>>>0]=a.getUTCSeconds();r()[b+4>>2>>>0]=a.getUTCMinutes();r()[b+8>>2>>>0]=a.getUTCHours();r()[b+12>>2>>>0]=a.getUTCDate();r()[b+16>>2>>>0]=a.getUTCMonth();r()[b+20>>2>>>0]=a.getUTCFullYear()-1900;r()[b+24>>2>>>0]=a.getUTCDay();a=(a.getTime()-Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0))/864E5|0;r()[b+28>>2>>>0]=a},Qa:function(a,b){a=\r\nnew Date(1E3*Bb(a));r()[b>>2>>>0]=a.getSeconds();r()[b+4>>2>>>0]=a.getMinutes();r()[b+8>>2>>>0]=a.getHours();r()[b+12>>2>>>0]=a.getDate();r()[b+16>>2>>>0]=a.getMonth();r()[b+20>>2>>>0]=a.getFullYear()-1900;r()[b+24>>2>>>0]=a.getDay();var c=new Date(a.getFullYear(),0,1),e=(a.getTime()-c.getTime())/864E5|0;r()[b+28>>2>>>0]=e;r()[b+36>>2>>>0]=-(60*a.getTimezoneOffset());e=(new Date(a.getFullYear(),6,1)).getTimezoneOffset();c=c.getTimezoneOffset();a=(e!=c&&a.getTimezoneOffset()==Math.min(c,e))|0;r()[b+\r\n32>>2>>>0]=a},Ra:function(a){var b=new Date(r()[a+20>>2>>>0]+1900,r()[a+16>>2>>>0],r()[a+12>>2>>>0],r()[a+8>>2>>>0],r()[a+4>>2>>>0],r()[a>>2>>>0],0),c=r()[a+32>>2>>>0],e=b.getTimezoneOffset(),f=new Date(b.getFullYear(),0,1),h=(new Date(b.getFullYear(),6,1)).getTimezoneOffset(),k=f.getTimezoneOffset(),l=Math.min(k,h);0>c?r()[a+32>>2>>>0]=Number(h!=k&&l==e):0<c!=(l==e)&&(h=Math.max(k,h),b.setTime(b.getTime()+6E4*((0<c?l:h)-e)));r()[a+24>>2>>>0]=b.getDay();c=(b.getTime()-f.getTime())/864E5|0;r()[a+28>>\r\n2>>>0]=c;r()[a>>2>>>0]=b.getSeconds();r()[a+4>>2>>>0]=b.getMinutes();r()[a+8>>2>>>0]=b.getHours();r()[a+12>>2>>>0]=b.getDate();r()[a+16>>2>>>0]=b.getMonth();return b.getTime()/1E3|0},Aa:Cb,Ba:Db,Sa:Hb,y:function(){I(\"\")},U:function(){if(!B&&!y){var a=\"Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread\";Ib||(Ib={});Ib[a]||(Ib[a]=1,B&&(a=\"warning: \"+a),G(a))}},ra:function(){return 4294901760},B:Jb,Ia:function(a,b,\r\nc){q().copyWithin(a>>>0,b>>>0,b+c>>>0)},F:function(){return B?(__webpack_require__(/*! os */ \"?aedb\").cpus)().length:navigator.hardwareConcurrency},Da:function(a,b,c){Mb.length=b;c>>=3;for(var e=0;e<b;e++)Mb[e]=ea()[c+e>>>0];return(0>a?Pa[-a-1]:cc[a]).apply(null,Mb)},qa:function(a){var b=q().length;a>>>=0;if(a<=b||4294901760<a)return!1;for(var c=1;4>=c;c*=2){var e=b*(1+.2/c);e=Math.min(e,a+100663296);var f=Math;e=Math.max(a,e);f=f.min.call(f,4294901760,e+(65536-e%65536)%65536);a:{try{m.grow(f-n.byteLength+65535>>>16);p(m.buffer);\r\nvar h=1;break a}catch(k){}h=void 0}if(h)return!0}return!1},Na:function(){throw\"unwind\";},Ga:Qb,Ha:Rb,J:Ta,I:Sb,S:Tb,ga:Ub,R:Vb,d:function(){return Y},na:Xb,ia:fc,ja:gc,K:hc,f:ic,P:jc,Q:kc,k:lc,p:mc,q:nc,N:oc,s:pc,w:qc,L:rc,E:sc,aa:tc,_:uc,Z:vc,ca:wc,$:xc,ba:yc,Y:zc,g:Ac,r:Bc,i:Cc,ha:Dc,m:Ec,v:Fc,u:Gc,O:Hc,A:Ic,ka:Jc,C:Kc,D:Lc,fa:Mc,da:Nc,ea:Oc,o:function(a){return a},a:m||x.wasmMemory,G:function(a){Y=a},la:bc,z:function(a,b,c,e){return bc(a,b,c,e)}};\r\n(function(){function a(f,h){x.asm=f.exports;P.qc.push(x.asm.sb);Ea=x.asm.ub;Ga.unshift(x.asm.Va);wa=h;C||(L--,x.monitorRunDependencies&&x.monitorRunDependencies(L),0==L&&(null!==La&&(clearInterval(La),La=null),M&&(f=M,M=null,f())))}function b(f){a(f.instance,f.module)}function c(f){return Oa().then(function(h){return WebAssembly.instantiate(h,e)}).then(function(h){return h}).then(f,function(h){G(\"failed to asynchronously prepare wasm: \"+h);I(h)})}var e={a:Pc};C||(L++,x.monitorRunDependencies&&x.monitorRunDependencies(L));\r\nif(x.instantiateWasm)try{return x.instantiateWasm(e,a)}catch(f){return G(\"Module.instantiateWasm callback failed with error: \"+f),!1}(function(){return H||\"function\"!=typeof WebAssembly.instantiateStreaming||Ma()||O.startsWith(\"file://\")||B||\"function\"!=typeof fetch?c(b):fetch(O,{credentials:\"same-origin\"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(b,function(h){G(\"wasm streaming compile failed: \"+h);G(\"falling back to ArrayBuffer instantiation\");return c(b)})})})().catch(ia);\r\nreturn{}})();x.___wasm_call_ctors=function(){return(x.___wasm_call_ctors=x.asm.Va).apply(null,arguments)};x._OrtInit=function(){return(x._OrtInit=x.asm.Wa).apply(null,arguments)};x._OrtCreateSessionOptions=function(){return(x._OrtCreateSessionOptions=x.asm.Xa).apply(null,arguments)};x._OrtAppendExecutionProvider=function(){return(x._OrtAppendExecutionProvider=x.asm.Ya).apply(null,arguments)};x._OrtAddSessionConfigEntry=function(){return(x._OrtAddSessionConfigEntry=x.asm.Za).apply(null,arguments)};\r\nx._OrtReleaseSessionOptions=function(){return(x._OrtReleaseSessionOptions=x.asm._a).apply(null,arguments)};x._OrtCreateSession=function(){return(x._OrtCreateSession=x.asm.$a).apply(null,arguments)};x._OrtReleaseSession=function(){return(x._OrtReleaseSession=x.asm.ab).apply(null,arguments)};x._OrtGetInputCount=function(){return(x._OrtGetInputCount=x.asm.bb).apply(null,arguments)};x._OrtGetOutputCount=function(){return(x._OrtGetOutputCount=x.asm.cb).apply(null,arguments)};\r\nx._OrtGetInputName=function(){return(x._OrtGetInputName=x.asm.db).apply(null,arguments)};x._OrtGetOutputName=function(){return(x._OrtGetOutputName=x.asm.eb).apply(null,arguments)};x._OrtFree=function(){return(x._OrtFree=x.asm.fb).apply(null,arguments)};x._OrtCreateTensor=function(){return(x._OrtCreateTensor=x.asm.gb).apply(null,arguments)};x._OrtGetTensorData=function(){return(x._OrtGetTensorData=x.asm.hb).apply(null,arguments)};\r\nx._OrtReleaseTensor=function(){return(x._OrtReleaseTensor=x.asm.ib).apply(null,arguments)};x._OrtCreateRunOptions=function(){return(x._OrtCreateRunOptions=x.asm.jb).apply(null,arguments)};x._OrtAddRunConfigEntry=function(){return(x._OrtAddRunConfigEntry=x.asm.kb).apply(null,arguments)};x._OrtReleaseRunOptions=function(){return(x._OrtReleaseRunOptions=x.asm.lb).apply(null,arguments)};x._OrtRun=function(){return(x._OrtRun=x.asm.mb).apply(null,arguments)};\r\nx._OrtEndProfiling=function(){return(x._OrtEndProfiling=x.asm.nb).apply(null,arguments)};var $a=x._pthread_self=function(){return($a=x._pthread_self=x.asm.ob).apply(null,arguments)},Fb=x._malloc=function(){return(Fb=x._malloc=x.asm.pb).apply(null,arguments)},kb=x._free=function(){return(kb=x._free=x.asm.qb).apply(null,arguments)},Wa=x._fflush=function(){return(Wa=x._fflush=x.asm.rb).apply(null,arguments)};x.__emscripten_tls_init=function(){return(x.__emscripten_tls_init=x.asm.sb).apply(null,arguments)};\r\nvar Va=x.___funcs_on_exit=function(){return(Va=x.___funcs_on_exit=x.asm.tb).apply(null,arguments)},ec=x.__emscripten_thread_init=function(){return(ec=x.__emscripten_thread_init=x.asm.vb).apply(null,arguments)};x.__emscripten_thread_crashed=function(){return(x.__emscripten_thread_crashed=x.asm.wb).apply(null,arguments)};\r\nvar Lb=x._emscripten_run_in_main_runtime_thread_js=function(){return(Lb=x._emscripten_run_in_main_runtime_thread_js=x.asm.xb).apply(null,arguments)},Ab=x.__emscripten_proxy_execute_task_queue=function(){return(Ab=x.__emscripten_proxy_execute_task_queue=x.asm.yb).apply(null,arguments)},Za=x.__emscripten_thread_free_data=function(){return(Za=x.__emscripten_thread_free_data=x.asm.zb).apply(null,arguments)},eb=x.__emscripten_thread_exit=function(){return(eb=x.__emscripten_thread_exit=x.asm.Ab).apply(null,\r\narguments)},Z=x._setThrew=function(){return(Z=x._setThrew=x.asm.Bb).apply(null,arguments)},cb=x._emscripten_stack_set_limits=function(){return(cb=x._emscripten_stack_set_limits=x.asm.Cb).apply(null,arguments)},S=x.stackSave=function(){return(S=x.stackSave=x.asm.Db).apply(null,arguments)},U=x.stackRestore=function(){return(U=x.stackRestore=x.asm.Eb).apply(null,arguments)},Kb=x.stackAlloc=function(){return(Kb=x.stackAlloc=x.asm.Fb).apply(null,arguments)},dc=x.___cxa_can_catch=function(){return(dc=x.___cxa_can_catch=\r\nx.asm.Gb).apply(null,arguments)},ib=x.___cxa_is_pointer_type=function(){return(ib=x.___cxa_is_pointer_type=x.asm.Hb).apply(null,arguments)},Qc=x.dynCall_j=function(){return(Qc=x.dynCall_j=x.asm.Ib).apply(null,arguments)},Rc=x.dynCall_iiiiij=function(){return(Rc=x.dynCall_iiiiij=x.asm.Jb).apply(null,arguments)},Sc=x.dynCall_jii=function(){return(Sc=x.dynCall_jii=x.asm.Kb).apply(null,arguments)},Tc=x.dynCall_viiiiij=function(){return(Tc=x.dynCall_viiiiij=x.asm.Lb).apply(null,arguments)},Uc=x.dynCall_vjji=\r\nfunction(){return(Uc=x.dynCall_vjji=x.asm.Mb).apply(null,arguments)},Vc=x.dynCall_viiijjjii=function(){return(Vc=x.dynCall_viiijjjii=x.asm.Nb).apply(null,arguments)},Wc=x.dynCall_iij=function(){return(Wc=x.dynCall_iij=x.asm.Ob).apply(null,arguments)},Xc=x.dynCall_ji=function(){return(Xc=x.dynCall_ji=x.asm.Pb).apply(null,arguments)},Yc=x.dynCall_iiiiiij=function(){return(Yc=x.dynCall_iiiiiij=x.asm.Qb).apply(null,arguments)},Zc=x.dynCall_iiij=function(){return(Zc=x.dynCall_iiij=x.asm.Rb).apply(null,\r\narguments)};function ic(a,b){var c=S();try{return V(a)(b)}catch(e){U(c);if(e!==e+0)throw e;Z(1,0)}}function Bc(a,b){var c=S();try{V(a)(b)}catch(e){U(c);if(e!==e+0)throw e;Z(1,0)}}function Cc(a,b,c){var e=S();try{V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function lc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function mc(a,b,c,e){var f=S();try{return V(a)(b,c,e)}catch(h){U(f);if(h!==h+0)throw h;Z(1,0)}}\r\nfunction qc(a,b,c,e,f,h,k){var l=S();try{return V(a)(b,c,e,f,h,k)}catch(u){U(l);if(u!==u+0)throw u;Z(1,0)}}function Ac(a){var b=S();try{V(a)()}catch(c){U(b);if(c!==c+0)throw c;Z(1,0)}}function pc(a,b,c,e,f,h){var k=S();try{return V(a)(b,c,e,f,h)}catch(l){U(k);if(l!==l+0)throw l;Z(1,0)}}function nc(a,b,c,e,f){var h=S();try{return V(a)(b,c,e,f)}catch(k){U(h);if(k!==k+0)throw k;Z(1,0)}}function Ec(a,b,c,e){var f=S();try{V(a)(b,c,e)}catch(h){U(f);if(h!==h+0)throw h;Z(1,0)}}\r\nfunction Gc(a,b,c,e,f,h){var k=S();try{V(a)(b,c,e,f,h)}catch(l){U(k);if(l!==l+0)throw l;Z(1,0)}}function Fc(a,b,c,e,f){var h=S();try{V(a)(b,c,e,f)}catch(k){U(h);if(k!==k+0)throw k;Z(1,0)}}function Ic(a,b,c,e,f,h,k,l){var u=S();try{V(a)(b,c,e,f,h,k,l)}catch(t){U(u);if(t!==t+0)throw t;Z(1,0)}}function kc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function jc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}\r\nfunction Jc(a,b,c,e,f,h,k,l,u){var t=S();try{V(a)(b,c,e,f,h,k,l,u)}catch(A){U(t);if(A!==A+0)throw A;Z(1,0)}}function Hc(a,b,c,e,f,h,k){var l=S();try{V(a)(b,c,e,f,h,k)}catch(u){U(l);if(u!==u+0)throw u;Z(1,0)}}function oc(a,b,c,e,f,h){var k=S();try{return V(a)(b,c,e,f,h)}catch(l){U(k);if(l!==l+0)throw l;Z(1,0)}}function rc(a,b,c,e,f,h,k,l){var u=S();try{return V(a)(b,c,e,f,h,k,l)}catch(t){U(u);if(t!==t+0)throw t;Z(1,0)}}\r\nfunction sc(a,b,c,e,f,h,k,l,u,t,A,K){var J=S();try{return V(a)(b,c,e,f,h,k,l,u,t,A,K)}catch(g){U(J);if(g!==g+0)throw g;Z(1,0)}}function Kc(a,b,c,e,f,h,k,l,u,t,A){var K=S();try{V(a)(b,c,e,f,h,k,l,u,t,A)}catch(J){U(K);if(J!==J+0)throw J;Z(1,0)}}function Lc(a,b,c,e,f,h,k,l,u,t,A,K,J,g,w,z){var N=S();try{V(a)(b,c,e,f,h,k,l,u,t,A,K,J,g,w,z)}catch(T){U(N);if(T!==T+0)throw T;Z(1,0)}}function hc(a){var b=S();try{return V(a)()}catch(c){U(b);if(c!==c+0)throw c;Z(1,0)}}\r\nfunction gc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function fc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function Dc(a,b,c,e){var f=S();try{V(a)(b,c,e)}catch(h){U(f);if(h!==h+0)throw h;Z(1,0)}}function Mc(a,b,c,e,f,h,k,l){var u=S();try{Tc(a,b,c,e,f,h,k,l)}catch(t){U(u);if(t!==t+0)throw t;Z(1,0)}}function Oc(a,b,c,e,f,h){var k=S();try{Uc(a,b,c,e,f,h)}catch(l){U(k);if(l!==l+0)throw l;Z(1,0)}}\r\nfunction Nc(a,b,c,e,f,h,k,l,u,t,A,K){var J=S();try{Vc(a,b,c,e,f,h,k,l,u,t,A,K)}catch(g){U(J);if(g!==g+0)throw g;Z(1,0)}}function wc(a,b,c,e){var f=S();try{return Wc(a,b,c,e)}catch(h){U(f);if(h!==h+0)throw h;Z(1,0)}}function yc(a,b){var c=S();try{return Xc(a,b)}catch(e){U(c);if(e!==e+0)throw e;Z(1,0)}}function tc(a,b,c,e,f,h,k,l){var u=S();try{return Yc(a,b,c,e,f,h,k,l)}catch(t){U(u);if(t!==t+0)throw t;Z(1,0)}}function xc(a){var b=S();try{return Qc(a)}catch(c){U(b);if(c!==c+0)throw c;Z(1,0)}}\r\nfunction uc(a,b,c,e,f,h,k){var l=S();try{return Rc(a,b,c,e,f,h,k)}catch(u){U(l);if(u!==u+0)throw u;Z(1,0)}}function vc(a,b,c,e,f){var h=S();try{return Zc(a,b,c,e,f)}catch(k){U(h);if(k!==k+0)throw k;Z(1,0)}}function zc(a,b,c){var e=S();try{return Sc(a,b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}x.UTF8ToString=Aa;x.stringToUTF8=function(a,b,c){return Ba(a,q(),b,c)};x.lengthBytesUTF8=Ca;x.keepRuntimeAlive=F;x.wasmMemory=m;x.stackSave=S;x.stackRestore=U;x.stackAlloc=Kb;x.ExitStatus=E;x.PThread=P;var $c;\r\nM=function ad(){$c||bd();$c||(M=ad)};\r\nfunction bd(){function a(){if(!$c&&($c=!0,x.calledRun=!0,!xa)){C||R(Ga);ha(x);if(x.onRuntimeInitialized)x.onRuntimeInitialized();if(!C){if(x.postRun)for(\"function\"==typeof x.postRun&&(x.postRun=[x.postRun]);x.postRun.length;){var b=x.postRun.shift();Ia.unshift(b)}R(Ia)}}}if(!(0<L))if(C)ha(x),C||R(Ga),postMessage({cmd:\"loaded\"});else{if(x.preRun)for(\"function\"==typeof x.preRun&&(x.preRun=[x.preRun]);x.preRun.length;)Ka();R(Fa);0<L||(x.setStatus?(x.setStatus(\"Running...\"),setTimeout(function(){setTimeout(function(){x.setStatus(\"\")},\r\n1);a()},1)):a())}}if(x.preInit)for(\"function\"==typeof x.preInit&&(x.preInit=[x.preInit]);0<x.preInit.length;)x.preInit.pop()();bd();\r\n\r\n\r\n return ortWasmThreaded.ready\r\n}\r\n);\r\n})();\r\nif (true)\r\n module.exports = ortWasmThreaded;\r\nelse {}\r\n\n\n/***/ }),\n\n/***/ \"./lib/wasm/binding/ort-wasm.js\":\n/*!**************************************!*\\\n !*** ./lib/wasm/binding/ort-wasm.js ***!\n \\**************************************/\n/***/ ((module, __unused_webpack_exports, __webpack_require__) => {\n\nvar __filename = \"/index.js\";\nvar __dirname = \"/\";\n\r\nvar ortWasm = (() => {\r\n var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;\r\n if (true) _scriptDir = _scriptDir || __filename;\r\n return (\r\nfunction(ortWasm) {\r\n ortWasm = ortWasm || {};\r\n\r\n\r\nvar d;d||(d=typeof ortWasm !== 'undefined' ? ortWasm : {});var aa,ba;d.ready=new Promise(function(a,b){aa=a;ba=b});var ca=Object.assign({},d),da=\"./this.program\",ea=(a,b)=>{throw b;},fa=\"object\"==typeof window,m=\"function\"==typeof importScripts,p=\"object\"==typeof process&&\"object\"==typeof process.versions&&\"string\"==typeof process.versions.node,q=\"\",ha,r,v,fs,y,ia;\r\nif(p)q=m?(__webpack_require__(/*! path */ \"?75c6\").dirname)(q)+\"/\":__dirname+\"/\",ia=()=>{y||(fs=__webpack_require__(/*! fs */ \"?63c8\"),y=__webpack_require__(/*! path */ \"?75c6\"))},ha=function(a,b){ia();a=y.normalize(a);return fs.readFileSync(a,b?void 0:\"utf8\")},v=a=>{a=ha(a,!0);a.buffer||(a=new Uint8Array(a));return a},r=(a,b,c)=>{ia();a=y.normalize(a);fs.readFile(a,function(e,f){e?c(e):b(f.buffer)})},1<process.argv.length&&(da=process.argv[1].replace(/\\\\/g,\"/\")),process.argv.slice(2),process.on(\"uncaughtException\",function(a){if(!(a instanceof ja))throw a;}),process.on(\"unhandledRejection\",\r\nfunction(a){throw a;}),ea=(a,b)=>{if(noExitRuntime||0<ka)throw process.exitCode=a,b;b instanceof ja||z(\"exiting due to exception: \"+b);process.exit(a)},d.inspect=function(){return\"[Emscripten Module object]\"};else if(fa||m)m?q=self.location.href:\"undefined\"!=typeof document&&document.currentScript&&(q=document.currentScript.src),_scriptDir&&(q=_scriptDir),0!==q.indexOf(\"blob:\")?q=q.substr(0,q.replace(/[?#].*/,\"\").lastIndexOf(\"/\")+1):q=\"\",ha=a=>{var b=new XMLHttpRequest;b.open(\"GET\",a,!1);b.send(null);\r\nreturn b.responseText},m&&(v=a=>{var b=new XMLHttpRequest;b.open(\"GET\",a,!1);b.responseType=\"arraybuffer\";b.send(null);return new Uint8Array(b.response)}),r=(a,b,c)=>{var e=new XMLHttpRequest;e.open(\"GET\",a,!0);e.responseType=\"arraybuffer\";e.onload=()=>{200==e.status||0==e.status&&e.response?b(e.response):c()};e.onerror=c;e.send(null)};var la=d.print||console.log.bind(console),z=d.printErr||console.warn.bind(console);Object.assign(d,ca);ca=null;d.thisProgram&&(da=d.thisProgram);d.quit&&(ea=d.quit);\r\nvar A;d.wasmBinary&&(A=d.wasmBinary);var noExitRuntime=d.noExitRuntime||!1;\"object\"!=typeof WebAssembly&&B(\"no native wasm support detected\");var ma,D=!1,na=\"undefined\"!=typeof TextDecoder?new TextDecoder(\"utf8\"):void 0;\r\nfunction oa(a,b,c){b>>>=0;var e=b+c;for(c=b;a[c]&&!(c>=e);)++c;if(16<c-b&&a.buffer&&na)return na.decode(a.subarray(b,c));for(e=\"\";b<c;){var f=a[b++];if(f&128){var h=a[b++]&63;if(192==(f&224))e+=String.fromCharCode((f&31)<<6|h);else{var k=a[b++]&63;f=224==(f&240)?(f&15)<<12|h<<6|k:(f&7)<<18|h<<12|k<<6|a[b++]&63;65536>f?e+=String.fromCharCode(f):(f-=65536,e+=String.fromCharCode(55296|f>>10,56320|f&1023))}}else e+=String.fromCharCode(f)}return e}function pa(a,b){return(a>>>=0)?oa(G,a,b):\"\"}\r\nfunction qa(a,b,c,e){c>>>=0;if(!(0<e))return 0;var f=c;e=c+e-1;for(var h=0;h<a.length;++h){var k=a.charCodeAt(h);if(55296<=k&&57343>=k){var l=a.charCodeAt(++h);k=65536+((k&1023)<<10)|l&1023}if(127>=k){if(c>=e)break;b[c++>>>0]=k}else{if(2047>=k){if(c+1>=e)break;b[c++>>>0]=192|k>>6}else{if(65535>=k){if(c+2>=e)break;b[c++>>>0]=224|k>>12}else{if(c+3>=e)break;b[c++>>>0]=240|k>>18;b[c++>>>0]=128|k>>12&63}b[c++>>>0]=128|k>>6&63}b[c++>>>0]=128|k&63}}b[c>>>0]=0;return c-f}\r\nfunction ra(a){for(var b=0,c=0;c<a.length;++c){var e=a.charCodeAt(c);127>=e?b++:2047>=e?b+=2:55296<=e&&57343>=e?(b+=4,++c):b+=3}return b}var sa,H,G,I,J;function ta(){var a=ma.buffer;sa=a;d.HEAP8=H=new Int8Array(a);d.HEAP16=new Int16Array(a);d.HEAP32=I=new Int32Array(a);d.HEAPU8=G=new Uint8Array(a);d.HEAPU16=new Uint16Array(a);d.HEAPU32=J=new Uint32Array(a);d.HEAPF32=new Float32Array(a);d.HEAPF64=new Float64Array(a)}var ua,va=[],wa=[],xa=[],ya=[],ka=0;\r\nfunction za(){var a=d.preRun.shift();va.unshift(a)}var K=0,Aa=null,L=null;function B(a){if(d.onAbort)d.onAbort(a);a=\"Aborted(\"+a+\")\";z(a);D=!0;a=new WebAssembly.RuntimeError(a+\". Build with -sASSERTIONS for more info.\");ba(a);throw a;}function Ba(){return N.startsWith(\"data:application/octet-stream;base64,\")}var N;N=\"ort-wasm.wasm\";if(!Ba()){var Ca=N;N=d.locateFile?d.locateFile(Ca,q):q+Ca}\r\nfunction Da(){var a=N;try{if(a==N&&A)return new Uint8Array(A);if(v)return v(a);throw\"both async and sync fetching of the wasm failed\";}catch(b){B(b)}}\r\nfunction Ea(){if(!A&&(fa||m)){if(\"function\"==typeof fetch&&!N.startsWith(\"file://\"))return fetch(N,{credentials:\"same-origin\"}).then(function(a){if(!a.ok)throw\"failed to load wasm binary file at '\"+N+\"'\";return a.arrayBuffer()}).catch(function(){return Da()});if(r)return new Promise(function(a,b){r(N,function(c){a(new Uint8Array(c))},b)})}return Promise.resolve().then(function(){return Da()})}function ja(a){this.name=\"ExitStatus\";this.message=\"Program terminated with exit(\"+a+\")\";this.status=a}\r\nfunction O(a){for(;0<a.length;)a.shift()(d)}var P=[],Q=0,R=0;\r\nfunction S(a){this.Db=a;this.zb=a-24;this.Ub=function(b){J[this.zb+4>>2>>>0]=b};this.Eb=function(){return J[this.zb+4>>2>>>0]};this.Sb=function(b){J[this.zb+8>>2>>>0]=b};this.Wb=function(){return J[this.zb+8>>2>>>0]};this.Tb=function(){I[this.zb>>2>>>0]=0};this.Ib=function(b){H[this.zb+12>>0>>>0]=b?1:0};this.Pb=function(){return 0!=H[this.zb+12>>0>>>0]};this.Jb=function(b){H[this.zb+13>>0>>>0]=b?1:0};this.Lb=function(){return 0!=H[this.zb+13>>0>>>0]};this.Rb=function(b,c){this.Fb(0);this.Ub(b);this.Sb(c);\r\nthis.Tb();this.Ib(!1);this.Jb(!1)};this.Nb=function(){I[this.zb>>2>>>0]+=1};this.Xb=function(){var b=I[this.zb>>2>>>0];I[this.zb>>2>>>0]=b-1;return 1===b};this.Fb=function(b){J[this.zb+16>>2>>>0]=b};this.Ob=function(){return J[this.zb+16>>2>>>0]};this.Qb=function(){if(Fa(this.Eb()))return J[this.Db>>2>>>0];var b=this.Ob();return 0!==b?b:this.Db}}function Ga(a){return Ha((new S(a)).zb)}var T=[];function U(a){var b=T[a];b||(a>=T.length&&(T.length=a+1),T[a]=b=ua.get(a));return b}\r\nfunction Ia(a){var b=ra(a)+1,c=Ja(b);c&&qa(a,H,c,b);return c}function Ka(a,b,c){function e(n){return(n=n.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?n[1]:\"GMT\"}var f=(new Date).getFullYear(),h=new Date(f,0,1),k=new Date(f,6,1);f=h.getTimezoneOffset();var l=k.getTimezoneOffset();I[a>>2>>>0]=60*Math.max(f,l);I[b>>2>>>0]=Number(f!=l);a=e(h);b=e(k);a=Ia(a);b=Ia(b);l<f?(J[c>>2>>>0]=a,J[c+4>>2>>>0]=b):(J[c>>2>>>0]=b,J[c+4>>2>>>0]=a)}function La(a,b,c){La.Vb||(La.Vb=!0,Ka(a,b,c))}var Ma={};\r\nfunction Na(){if(!Oa){var a={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\",_:da||\"./this.program\"},b;for(b in Ma)void 0===Ma[b]?delete a[b]:a[b]=Ma[b];var c=[];for(b in a)c.push(b+\"=\"+a[b]);Oa=c}return Oa}var Oa,Pa=[null,[],[]];function Qa(a,b){var c=Pa[a];0===b||10===b?((1===a?la:z)(oa(c,0)),c.length=0):c.push(b)}var V=0;\r\nfunction Ra(){if(\"object\"==typeof crypto&&\"function\"==typeof crypto.getRandomValues){var a=new Uint8Array(1);return()=>{crypto.getRandomValues(a);return a[0]}}if(p)try{var b=__webpack_require__(Object(function webpackMissingModule() { var e = new Error(\"Cannot find module 'crypto'\"); e.code = 'MODULE_NOT_FOUND'; throw e; }()));return()=>b.randomBytes(1)[0]}catch(c){}return()=>B(\"randomDevice\")}function W(a,b){W.Mb||(W.Mb=Ra());for(var c=0;c<b;c++)H[a+c>>0>>>0]=W.Mb();return 0}function Sa(a){return 0===a%4&&(0!==a%100||0===a%400)}var Ta=[31,29,31,30,31,30,31,31,30,31,30,31],Ua=[31,28,31,30,31,30,31,31,30,31,30,31];\r\nfunction Va(a){var b=Array(ra(a)+1);qa(a,b,0,b.length);return b}\r\nfunction Wa(a,b,c,e){function f(g,u,w){for(g=\"number\"==typeof g?g.toString():g||\"\";g.length<u;)g=w[0]+g;return g}function h(g,u){return f(g,u,\"0\")}function k(g,u){function w(M){return 0>M?-1:0<M?1:0}var F;0===(F=w(g.getFullYear()-u.getFullYear()))&&0===(F=w(g.getMonth()-u.getMonth()))&&(F=w(g.getDate()-u.getDate()));return F}function l(g){switch(g.getDay()){case 0:return new Date(g.getFullYear()-1,11,29);case 1:return g;case 2:return new Date(g.getFullYear(),0,3);case 3:return new Date(g.getFullYear(),\r\n0,2);case 4:return new Date(g.getFullYear(),0,1);case 5:return new Date(g.getFullYear()-1,11,31);case 6:return new Date(g.getFullYear()-1,11,30)}}function n(g){var u=g.Bb;for(g=new Date((new Date(g.Cb+1900,0,1)).getTime());0<u;){var w=g.getMonth(),F=(Sa(g.getFullYear())?Ta:Ua)[w];if(u>F-g.getDate())u-=F-g.getDate()+1,g.setDate(1),11>w?g.setMonth(w+1):(g.setMonth(0),g.setFullYear(g.getFullYear()+1));else{g.setDate(g.getDate()+u);break}}w=new Date(g.getFullYear()+1,0,4);u=l(new Date(g.getFullYear(),\r\n0,4));w=l(w);return 0>=k(u,g)?0>=k(w,g)?g.getFullYear()+1:g.getFullYear():g.getFullYear()-1}var t=I[e+40>>2>>>0];e={$b:I[e>>2>>>0],Zb:I[e+4>>2>>>0],Gb:I[e+8>>2>>>0],Kb:I[e+12>>2>>>0],Hb:I[e+16>>2>>>0],Cb:I[e+20>>2>>>0],Ab:I[e+24>>2>>>0],Bb:I[e+28>>2>>>0],bc:I[e+32>>2>>>0],Yb:I[e+36>>2>>>0],ac:t?pa(t):\"\"};c=pa(c);t={\"%c\":\"%a %b %d %H:%M:%S %Y\",\"%D\":\"%m/%d/%y\",\"%F\":\"%Y-%m-%d\",\"%h\":\"%b\",\"%r\":\"%I:%M:%S %p\",\"%R\":\"%H:%M\",\"%T\":\"%H:%M:%S\",\"%x\":\"%m/%d/%y\",\"%X\":\"%H:%M:%S\",\"%Ec\":\"%c\",\"%EC\":\"%C\",\"%Ex\":\"%m/%d/%y\",\r\n\"%EX\":\"%H:%M:%S\",\"%Ey\":\"%y\",\"%EY\":\"%Y\",\"%Od\":\"%d\",\"%Oe\":\"%e\",\"%OH\":\"%H\",\"%OI\":\"%I\",\"%Om\":\"%m\",\"%OM\":\"%M\",\"%OS\":\"%S\",\"%Ou\":\"%u\",\"%OU\":\"%U\",\"%OV\":\"%V\",\"%Ow\":\"%w\",\"%OW\":\"%W\",\"%Oy\":\"%y\"};for(var x in t)c=c.replace(new RegExp(x,\"g\"),t[x]);var E=\"Sunday Monday Tuesday Wednesday Thursday Friday Saturday\".split(\" \"),C=\"January February March April May June July August September October November December\".split(\" \");t={\"%a\":function(g){return E[g.Ab].substring(0,3)},\"%A\":function(g){return E[g.Ab]},\"%b\":function(g){return C[g.Hb].substring(0,\r\n3)},\"%B\":function(g){return C[g.Hb]},\"%C\":function(g){return h((g.Cb+1900)/100|0,2)},\"%d\":function(g){return h(g.Kb,2)},\"%e\":function(g){return f(g.Kb,2,\" \")},\"%g\":function(g){return n(g).toString().substring(2)},\"%G\":function(g){return n(g)},\"%H\":function(g){return h(g.Gb,2)},\"%I\":function(g){g=g.Gb;0==g?g=12:12<g&&(g-=12);return h(g,2)},\"%j\":function(g){for(var u=0,w=0;w<=g.Hb-1;u+=(Sa(g.Cb+1900)?Ta:Ua)[w++]);return h(g.Kb+u,3)},\"%m\":function(g){return h(g.Hb+1,2)},\"%M\":function(g){return h(g.Zb,\r\n2)},\"%n\":function(){return\"\\n\"},\"%p\":function(g){return 0<=g.Gb&&12>g.Gb?\"AM\":\"PM\"},\"%S\":function(g){return h(g.$b,2)},\"%t\":function(){return\"\\t\"},\"%u\":function(g){return g.Ab||7},\"%U\":function(g){return h(Math.floor((g.Bb+7-g.Ab)/7),2)},\"%V\":function(g){var u=Math.floor((g.Bb+7-(g.Ab+6)%7)/7);2>=(g.Ab+371-g.Bb-2)%7&&u++;if(u)53==u&&(w=(g.Ab+371-g.Bb)%7,4==w||3==w&&Sa(g.Cb)||(u=1));else{u=52;var w=(g.Ab+7-g.Bb-1)%7;(4==w||5==w&&Sa(g.Cb%400-1))&&u++}return h(u,2)},\"%w\":function(g){return g.Ab},\"%W\":function(g){return h(Math.floor((g.Bb+\r\n7-(g.Ab+6)%7)/7),2)},\"%y\":function(g){return(g.Cb+1900).toString().substring(2)},\"%Y\":function(g){return g.Cb+1900},\"%z\":function(g){g=g.Yb;var u=0<=g;g=Math.abs(g)/60;return(u?\"+\":\"-\")+String(\"0000\"+(g/60*100+g%60)).slice(-4)},\"%Z\":function(g){return g.ac},\"%%\":function(){return\"%\"}};c=c.replace(/%%/g,\"\\x00\\x00\");for(x in t)c.includes(x)&&(c=c.replace(new RegExp(x,\"g\"),t[x](e)));c=c.replace(/\\0\\0/g,\"%\");x=Va(c);if(x.length>b)return 0;H.set(x,a>>>0);return x.length-1}\r\nvar Jb={a:function(a){return Ja(a+24)+24},m:function(a){a=new S(a);a.Pb()||(a.Ib(!0),Q--);a.Jb(!1);P.push(a);a.Nb();return a.Qb()},ia:function(a){z(\"Unexpected exception thrown, this is not properly supported - aborting\");D=!0;throw a;},w:function(){X(0);var a=P.pop();if(a.Xb()&&!a.Lb()){var b=a.Wb();b&&U(b)(a.Db);Ga(a.Db)}R=0},d:function(){var a=R;if(!a)return V=0;var b=new S(a);b.Fb(a);var c=b.Eb();if(!c)return V=0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];\r\nif(0===h||h===c)break;if(Xa(h,c,b.zb+16))return V=h,a}V=c;return a},k:function(){var a=R;if(!a)return V=0;var b=new S(a);b.Fb(a);var c=b.Eb();if(!c)return V=0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;if(Xa(h,c,b.zb+16))return V=h,a}V=c;return a},g:function(){var a=R;if(!a)return V=0;var b=new S(a);b.Fb(a);var c=b.Eb();if(!c)return V=0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;\r\nif(Xa(h,c,b.zb+16))return V=h,a}V=c;return a},s:Ga,L:function(){var a=P.pop();a||B(\"no exception to throw\");var b=a.Db;a.Lb()||(P.push(a),a.Jb(!0),a.Ib(!1),Q++);R=b;throw b;},b:function(a,b,c){(new S(a)).Rb(b,c);R=a;Q++;throw a;},la:function(){return Q},i:function(a){R||(R=a);throw a;},H:function(){return 0},Ba:function(){},pa:function(){},ra:function(){},ka:function(){return 0},za:function(){},ua:function(){},ya:function(){},R:function(){},qa:function(){},na:function(){},Aa:function(){},oa:function(){},\r\nHa:function(){},Ja:function(){B(\"To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking\")},Ia:function(){B(\"To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking\")},S:function(){return Date.now()},Ca:function(){return!0},Da:function(a,b){a=new Date(1E3*(J[a>>>2]+4294967296*I[a+4>>>2]));I[b>>2>>>0]=a.getUTCSeconds();I[b+4>>2>>>0]=a.getUTCMinutes();I[b+8>>2>>>0]=a.getUTCHours();I[b+12>>2>>>\r\n0]=a.getUTCDate();I[b+16>>2>>>0]=a.getUTCMonth();I[b+20>>2>>>0]=a.getUTCFullYear()-1900;I[b+24>>2>>>0]=a.getUTCDay();I[b+28>>2>>>0]=(a.getTime()-Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0))/864E5|0},Ea:function(a,b){a=new Date(1E3*(J[a>>>2]+4294967296*I[a+4>>>2]));I[b>>2>>>0]=a.getSeconds();I[b+4>>2>>>0]=a.getMinutes();I[b+8>>2>>>0]=a.getHours();I[b+12>>2>>>0]=a.getDate();I[b+16>>2>>>0]=a.getMonth();I[b+20>>2>>>0]=a.getFullYear()-1900;I[b+24>>2>>>0]=a.getDay();var c=new Date(a.getFullYear(),0,1);I[b+\r\n28>>2>>>0]=(a.getTime()-c.getTime())/864E5|0;I[b+36>>2>>>0]=-(60*a.getTimezoneOffset());var e=(new Date(a.getFullYear(),6,1)).getTimezoneOffset();c=c.getTimezoneOffset();I[b+32>>2>>>0]=(e!=c&&a.getTimezoneOffset()==Math.min(c,e))|0},Fa:function(a){var b=new Date(I[a+20>>2>>>0]+1900,I[a+16>>2>>>0],I[a+12>>2>>>0],I[a+8>>2>>>0],I[a+4>>2>>>0],I[a>>2>>>0],0),c=I[a+32>>2>>>0],e=b.getTimezoneOffset(),f=new Date(b.getFullYear(),0,1),h=(new Date(b.getFullYear(),6,1)).getTimezoneOffset(),k=f.getTimezoneOffset(),\r\nl=Math.min(k,h);0>c?I[a+32>>2>>>0]=Number(h!=k&&l==e):0<c!=(l==e)&&(h=Math.max(k,h),b.setTime(b.getTime()+6E4*((0<c?l:h)-e)));I[a+24>>2>>>0]=b.getDay();I[a+28>>2>>>0]=(b.getTime()-f.getTime())/864E5|0;I[a>>2>>>0]=b.getSeconds();I[a+4>>2>>>0]=b.getMinutes();I[a+8>>2>>>0]=b.getHours();I[a+12>>2>>>0]=b.getDate();I[a+16>>2>>>0]=b.getMonth();return b.getTime()/1E3|0},sa:function(){return-52},ta:function(){},Ga:La,B:function(){B(\"\")},ma:function(){return 4294901760},I:p?()=>{var a=process.hrtime();return 1E3*\r\na[0]+a[1]/1E6}:()=>performance.now(),xa:function(a,b,c){G.copyWithin(a>>>0,b>>>0,b+c>>>0)},G:function(a){var b=G.length;a>>>=0;if(4294901760<a)return!1;for(var c=1;4>=c;c*=2){var e=b*(1+.2/c);e=Math.min(e,a+100663296);var f=Math;e=Math.max(a,e);f=f.min.call(f,4294901760,e+(65536-e%65536)%65536);a:{try{ma.grow(f-sa.byteLength+65535>>>16);ta();var h=1;break a}catch(k){}h=void 0}if(h)return!0}return!1},va:function(a,b){var c=0;Na().forEach(function(e,f){var h=b+c;f=J[a+4*f>>2>>>0]=h;for(h=0;h<e.length;++h)H[f++>>\r\n0>>>0]=e.charCodeAt(h);H[f>>0>>>0]=0;c+=e.length+1});return 0},wa:function(a,b){var c=Na();J[a>>2>>>0]=c.length;var e=0;c.forEach(function(f){e+=f.length+1});J[b>>2>>>0]=e;return 0},ba:function(a){noExitRuntime||0<ka||(Ya(),O(xa),Za(0),Pa[1].length&&Qa(1,10),Pa[2].length&&Qa(2,10));if(!(noExitRuntime||0<ka)){if(d.onExit)d.onExit(a);D=!0}ea(a,new ja(a))},E:function(){return 52},Q:function(){return 52},ca:function(){return 70},P:function(a,b,c,e){for(var f=0,h=0;h<c;h++){var k=J[b>>2>>>0],l=J[b+4>>\r\n2>>>0];b+=8;for(var n=0;n<l;n++)Qa(a,G[k+n>>>0]);f+=l}J[e>>2>>>0]=f;return 0},c:function(){return V},ja:W,ea:$a,fa:ab,J:bb,e:cb,N:db,O:eb,j:fb,o:gb,p:hb,M:ib,r:jb,v:kb,K:lb,D:mb,X:nb,V:ob,U:pb,Z:qb,W:rb,Y:sb,T:tb,f:ub,q:vb,h:wb,da:xb,l:yb,t:zb,u:Ab,x:Bb,z:Cb,ga:Db,A:Eb,C:Fb,aa:Gb,_:Hb,$:Ib,n:function(a){return a},F:function(a){V=a},ha:Wa,y:function(a,b,c,e){return Wa(a,b,c,e)}};\r\n(function(){function a(f){d.asm=f.exports;ma=d.asm.Ka;ta();ua=d.asm.ib;wa.unshift(d.asm.La);K--;d.monitorRunDependencies&&d.monitorRunDependencies(K);0==K&&(null!==Aa&&(clearInterval(Aa),Aa=null),L&&(f=L,L=null,f()))}function b(f){a(f.instance)}function c(f){return Ea().then(function(h){return WebAssembly.instantiate(h,e)}).then(function(h){return h}).then(f,function(h){z(\"failed to asynchronously prepare wasm: \"+h);B(h)})}var e={a:Jb};K++;d.monitorRunDependencies&&d.monitorRunDependencies(K);if(d.instantiateWasm)try{return d.instantiateWasm(e,\r\na)}catch(f){return z(\"Module.instantiateWasm callback failed with error: \"+f),!1}(function(){return A||\"function\"!=typeof WebAssembly.instantiateStreaming||Ba()||N.startsWith(\"file://\")||p||\"function\"!=typeof fetch?c(b):fetch(N,{credentials:\"same-origin\"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(b,function(h){z(\"wasm streaming compile failed: \"+h);z(\"falling back to ArrayBuffer instantiation\");return c(b)})})})().catch(ba);return{}})();\r\nd.___wasm_call_ctors=function(){return(d.___wasm_call_ctors=d.asm.La).apply(null,arguments)};d._OrtInit=function(){return(d._OrtInit=d.asm.Ma).apply(null,arguments)};d._OrtCreateSessionOptions=function(){return(d._OrtCreateSessionOptions=d.asm.Na).apply(null,arguments)};d._OrtAppendExecutionProvider=function(){return(d._OrtAppendExecutionProvider=d.asm.Oa).apply(null,arguments)};d._OrtAddSessionConfigEntry=function(){return(d._OrtAddSessionConfigEntry=d.asm.Pa).apply(null,arguments)};\r\nd._OrtReleaseSessionOptions=function(){return(d._OrtReleaseSessionOptions=d.asm.Qa).apply(null,arguments)};d._OrtCreateSession=function(){return(d._OrtCreateSession=d.asm.Ra).apply(null,arguments)};d._OrtReleaseSession=function(){return(d._OrtReleaseSession=d.asm.Sa).apply(null,arguments)};d._OrtGetInputCount=function(){return(d._OrtGetInputCount=d.asm.Ta).apply(null,arguments)};d._OrtGetOutputCount=function(){return(d._OrtGetOutputCount=d.asm.Ua).apply(null,arguments)};\r\nd._OrtGetInputName=function(){return(d._OrtGetInputName=d.asm.Va).apply(null,arguments)};d._OrtGetOutputName=function(){return(d._OrtGetOutputName=d.asm.Wa).apply(null,arguments)};d._OrtFree=function(){return(d._OrtFree=d.asm.Xa).apply(null,arguments)};d._OrtCreateTensor=function(){return(d._OrtCreateTensor=d.asm.Ya).apply(null,arguments)};d._OrtGetTensorData=function(){return(d._OrtGetTensorData=d.asm.Za).apply(null,arguments)};\r\nd._OrtReleaseTensor=function(){return(d._OrtReleaseTensor=d.asm._a).apply(null,arguments)};d._OrtCreateRunOptions=function(){return(d._OrtCreateRunOptions=d.asm.$a).apply(null,arguments)};d._OrtAddRunConfigEntry=function(){return(d._OrtAddRunConfigEntry=d.asm.ab).apply(null,arguments)};d._OrtReleaseRunOptions=function(){return(d._OrtReleaseRunOptions=d.asm.bb).apply(null,arguments)};d._OrtRun=function(){return(d._OrtRun=d.asm.cb).apply(null,arguments)};\r\nd._OrtEndProfiling=function(){return(d._OrtEndProfiling=d.asm.db).apply(null,arguments)};\r\nvar Ja=d._malloc=function(){return(Ja=d._malloc=d.asm.eb).apply(null,arguments)},Ha=d._free=function(){return(Ha=d._free=d.asm.fb).apply(null,arguments)},Za=d._fflush=function(){return(Za=d._fflush=d.asm.gb).apply(null,arguments)},Ya=d.___funcs_on_exit=function(){return(Ya=d.___funcs_on_exit=d.asm.hb).apply(null,arguments)},X=d._setThrew=function(){return(X=d._setThrew=d.asm.jb).apply(null,arguments)},Y=d.stackSave=function(){return(Y=d.stackSave=d.asm.kb).apply(null,arguments)},Z=d.stackRestore=\r\nfunction(){return(Z=d.stackRestore=d.asm.lb).apply(null,arguments)},Kb=d.stackAlloc=function(){return(Kb=d.stackAlloc=d.asm.mb).apply(null,arguments)},Xa=d.___cxa_can_catch=function(){return(Xa=d.___cxa_can_catch=d.asm.nb).apply(null,arguments)},Fa=d.___cxa_is_pointer_type=function(){return(Fa=d.___cxa_is_pointer_type=d.asm.ob).apply(null,arguments)},Lb=d.dynCall_j=function(){return(Lb=d.dynCall_j=d.asm.pb).apply(null,arguments)},Mb=d.dynCall_iiiiij=function(){return(Mb=d.dynCall_iiiiij=d.asm.qb).apply(null,\r\narguments)},Nb=d.dynCall_jii=function(){return(Nb=d.dynCall_jii=d.asm.rb).apply(null,arguments)},Ob=d.dynCall_viiiiij=function(){return(Ob=d.dynCall_viiiiij=d.asm.sb).apply(null,arguments)},Pb=d.dynCall_vjji=function(){return(Pb=d.dynCall_vjji=d.asm.tb).apply(null,arguments)},Qb=d.dynCall_viiijjjii=function(){return(Qb=d.dynCall_viiijjjii=d.asm.ub).apply(null,arguments)},Rb=d.dynCall_iij=function(){return(Rb=d.dynCall_iij=d.asm.vb).apply(null,arguments)},Sb=d.dynCall_ji=function(){return(Sb=d.dynCall_ji=\r\nd.asm.wb).apply(null,arguments)},Tb=d.dynCall_iiiiiij=function(){return(Tb=d.dynCall_iiiiiij=d.asm.xb).apply(null,arguments)},Ub=d.dynCall_iiij=function(){return(Ub=d.dynCall_iiij=d.asm.yb).apply(null,arguments)};function cb(a,b){var c=Y();try{return U(a)(b)}catch(e){Z(c);if(e!==e+0)throw e;X(1,0)}}function vb(a,b){var c=Y();try{U(a)(b)}catch(e){Z(c);if(e!==e+0)throw e;X(1,0)}}function wb(a,b,c){var e=Y();try{U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}\r\nfunction fb(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function gb(a,b,c,e){var f=Y();try{return U(a)(b,c,e)}catch(h){Z(f);if(h!==h+0)throw h;X(1,0)}}function kb(a,b,c,e,f,h,k){var l=Y();try{return U(a)(b,c,e,f,h,k)}catch(n){Z(l);if(n!==n+0)throw n;X(1,0)}}function ub(a){var b=Y();try{U(a)()}catch(c){Z(b);if(c!==c+0)throw c;X(1,0)}}function jb(a,b,c,e,f,h){var k=Y();try{return U(a)(b,c,e,f,h)}catch(l){Z(k);if(l!==l+0)throw l;X(1,0)}}\r\nfunction hb(a,b,c,e,f){var h=Y();try{return U(a)(b,c,e,f)}catch(k){Z(h);if(k!==k+0)throw k;X(1,0)}}function yb(a,b,c,e){var f=Y();try{U(a)(b,c,e)}catch(h){Z(f);if(h!==h+0)throw h;X(1,0)}}function Ab(a,b,c,e,f,h){var k=Y();try{U(a)(b,c,e,f,h)}catch(l){Z(k);if(l!==l+0)throw l;X(1,0)}}function zb(a,b,c,e,f){var h=Y();try{U(a)(b,c,e,f)}catch(k){Z(h);if(k!==k+0)throw k;X(1,0)}}function Bb(a,b,c,e,f,h,k){var l=Y();try{U(a)(b,c,e,f,h,k)}catch(n){Z(l);if(n!==n+0)throw n;X(1,0)}}\r\nfunction Cb(a,b,c,e,f,h,k,l){var n=Y();try{U(a)(b,c,e,f,h,k,l)}catch(t){Z(n);if(t!==t+0)throw t;X(1,0)}}function eb(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function db(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function Db(a,b,c,e,f,h,k,l,n){var t=Y();try{U(a)(b,c,e,f,h,k,l,n)}catch(x){Z(t);if(x!==x+0)throw x;X(1,0)}}function ib(a,b,c,e,f,h){var k=Y();try{return U(a)(b,c,e,f,h)}catch(l){Z(k);if(l!==l+0)throw l;X(1,0)}}\r\nfunction lb(a,b,c,e,f,h,k,l){var n=Y();try{return U(a)(b,c,e,f,h,k,l)}catch(t){Z(n);if(t!==t+0)throw t;X(1,0)}}function mb(a,b,c,e,f,h,k,l,n,t,x,E){var C=Y();try{return U(a)(b,c,e,f,h,k,l,n,t,x,E)}catch(g){Z(C);if(g!==g+0)throw g;X(1,0)}}function Eb(a,b,c,e,f,h,k,l,n,t,x){var E=Y();try{U(a)(b,c,e,f,h,k,l,n,t,x)}catch(C){Z(E);if(C!==C+0)throw C;X(1,0)}}function Fb(a,b,c,e,f,h,k,l,n,t,x,E,C,g,u,w){var F=Y();try{U(a)(b,c,e,f,h,k,l,n,t,x,E,C,g,u,w)}catch(M){Z(F);if(M!==M+0)throw M;X(1,0)}}\r\nfunction bb(a){var b=Y();try{return U(a)()}catch(c){Z(b);if(c!==c+0)throw c;X(1,0)}}function ab(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function $a(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function xb(a,b,c,e){var f=Y();try{U(a)(b,c,e)}catch(h){Z(f);if(h!==h+0)throw h;X(1,0)}}function Gb(a,b,c,e,f,h,k,l){var n=Y();try{Ob(a,b,c,e,f,h,k,l)}catch(t){Z(n);if(t!==t+0)throw t;X(1,0)}}\r\nfunction Ib(a,b,c,e,f,h){var k=Y();try{Pb(a,b,c,e,f,h)}catch(l){Z(k);if(l!==l+0)throw l;X(1,0)}}function Hb(a,b,c,e,f,h,k,l,n,t,x,E){var C=Y();try{Qb(a,b,c,e,f,h,k,l,n,t,x,E)}catch(g){Z(C);if(g!==g+0)throw g;X(1,0)}}function qb(a,b,c,e){var f=Y();try{return Rb(a,b,c,e)}catch(h){Z(f);if(h!==h+0)throw h;X(1,0)}}function sb(a,b){var c=Y();try{return Sb(a,b)}catch(e){Z(c);if(e!==e+0)throw e;X(1,0)}}\r\nfunction nb(a,b,c,e,f,h,k,l){var n=Y();try{return Tb(a,b,c,e,f,h,k,l)}catch(t){Z(n);if(t!==t+0)throw t;X(1,0)}}function rb(a){var b=Y();try{return Lb(a)}catch(c){Z(b);if(c!==c+0)throw c;X(1,0)}}function ob(a,b,c,e,f,h,k){var l=Y();try{return Mb(a,b,c,e,f,h,k)}catch(n){Z(l);if(n!==n+0)throw n;X(1,0)}}function pb(a,b,c,e,f){var h=Y();try{return Ub(a,b,c,e,f)}catch(k){Z(h);if(k!==k+0)throw k;X(1,0)}}function tb(a,b,c){var e=Y();try{return Nb(a,b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}\r\nd.UTF8ToString=pa;d.stringToUTF8=function(a,b,c){return qa(a,G,b,c)};d.lengthBytesUTF8=ra;d.stackSave=Y;d.stackRestore=Z;d.stackAlloc=Kb;var Vb;L=function Wb(){Vb||Xb();Vb||(L=Wb)};\r\nfunction Xb(){function a(){if(!Vb&&(Vb=!0,d.calledRun=!0,!D)){O(wa);aa(d);if(d.onRuntimeInitialized)d.onRuntimeInitialized();if(d.postRun)for(\"function\"==typeof d.postRun&&(d.postRun=[d.postRun]);d.postRun.length;){var b=d.postRun.shift();ya.unshift(b)}O(ya)}}if(!(0<K)){if(d.preRun)for(\"function\"==typeof d.preRun&&(d.preRun=[d.preRun]);d.preRun.length;)za();O(va);0<K||(d.setStatus?(d.setStatus(\"Running...\"),setTimeout(function(){setTimeout(function(){d.setStatus(\"\")},1);a()},1)):a())}}\r\nif(d.preInit)for(\"function\"==typeof d.preInit&&(d.preInit=[d.preInit]);0<d.preInit.length;)d.preInit.pop()();Xb();\r\n\r\n\r\n return ortWasm.ready\r\n}\r\n);\r\n})();\r\nif (true)\r\n module.exports = ortWasm;\r\nelse {}\r\n\n\n/***/ }),\n\n/***/ \"./lib/wasm/options-utils.ts\":\n/*!***********************************!*\\\n !*** ./lib/wasm/options-utils.ts ***!\n \\***********************************/\n/***/ ((__unused_webpack_module, exports) => {\n\n\"use strict\";\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.iterateExtraOptions = void 0;\nconst iterateExtraOptions = (options, prefix, seen, handler) => {\n if (typeof options == 'object' && options !== null) {\n if (seen.has(options)) {\n throw new Error('Circular reference in options');\n }\n else {\n seen.add(options);\n }\n }\n Object.entries(options).forEach(([key, value]) => {\n const name = (prefix) ? prefix + key : key;\n if (typeof value === 'object') {\n (0, exports.iterateExtraOptions)(value, name + '.', seen, handler);\n }\n else if (typeof value === 'string' || typeof value === 'number') {\n handler(name, value.toString());\n }\n else if (typeof value === 'boolean') {\n handler(name, (value) ? '1' : '0');\n }\n else {\n throw new Error(`Can't handle extra config type: ${typeof value}`);\n }\n });\n};\nexports.iterateExtraOptions = iterateExtraOptions;\n\n\n/***/ }),\n\n/***/ \"./lib/wasm/run-options.ts\":\n/*!*********************************!*\\\n !*** ./lib/wasm/run-options.ts ***!\n \\*********************************/\n/***/ ((__unused_webpack_module, exports, __webpack_require__) => {\n\n\"use strict\";\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.setRunOptions = void 0;\nconst options_utils_1 = __webpack_require__(/*! ./options-utils */ \"./lib/wasm/options-utils.ts\");\nconst string_utils_1 = __webpack_require__(/*! ./string-utils */ \"./lib/wasm/string-utils.ts\");\nconst wasm_factory_1 = __webpack_require__(/*! ./wasm-factory */ \"./lib/wasm/wasm-factory.ts\");\nconst setRunOptions = (options) => {\n const wasm = (0, wasm_factory_1.getInstance)();\n let runOptionsHandle = 0;\n const allocs = [];\n const runOptions = options || {};\n try {\n if ((options === null || options === void 0 ? void 0 : options.logSeverityLevel) === undefined) {\n runOptions.logSeverityLevel = 2; // Default to warning\n }\n else if (typeof options.logSeverityLevel !== 'number' || !Number.isInteger(options.logSeverityLevel) ||\n options.logSeverityLevel < 0 || options.logSeverityLevel > 4) {\n throw new Error(`log serverity level is not valid: ${options.logSeverityLevel}`);\n }\n if ((options === null || options === void 0 ? void 0 : options.logVerbosityLevel) === undefined) {\n runOptions.logVerbosityLevel = 0; // Default to 0\n }\n else if (typeof options.logVerbosityLevel !== 'number' || !Number.isInteger(options.logVerbosityLevel)) {\n throw new Error(`log verbosity level is not valid: ${options.logVerbosityLevel}`);\n }\n if ((options === null || options === void 0 ? void 0 : options.terminate) === undefined) {\n runOptions.terminate = false;\n }\n let tagDataOffset = 0;\n if ((options === null || options === void 0 ? void 0 : options.tag) !== undefined) {\n tagDataOffset = (0, string_utils_1.allocWasmString)(options.tag, allocs);\n }\n runOptionsHandle = wasm._OrtCreateRunOptions(runOptions.logSeverityLevel, runOptions.logVerbosityLevel, !!runOptions.terminate, tagDataOffset);\n if (runOptionsHandle === 0) {\n throw new Error('Can\\'t create run options');\n }\n if ((options === null || options === void 0 ? void 0 : options.extra) !== undefined) {\n (0, options_utils_1.iterateExtraOptions)(options.extra, '', new WeakSet(), (key, value) => {\n const keyDataOffset = (0, string_utils_1.allocWasmString)(key, allocs);\n const valueDataOffset = (0, string_utils_1.allocWasmString)(value, allocs);\n if (wasm._OrtAddRunConfigEntry(runOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n throw new Error(`Can't set a run config entry: ${key} - ${value}`);\n }\n });\n }\n return [runOptionsHandle, allocs];\n }\n catch (e) {\n if (runOptionsHandle !== 0) {\n wasm._OrtReleaseRunOptions(runOptionsHandle);\n }\n allocs.forEach(wasm._free);\n throw e;\n }\n};\nexports.setRunOptions = setRunOptions;\n\n\n/***/ }),\n\n/***/ \"./lib/wasm/session-options.ts\":\n/*!*************************************!*\\\n !*** ./lib/wasm/session-options.ts ***!\n \\*************************************/\n/***/ ((__unused_webpack_module, exports, __webpack_require__) => {\n\n\"use strict\";\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.setSessionOptions = void 0;\nconst options_utils_1 = __webpack_require__(/*! ./options-utils */ \"./lib/wasm/options-utils.ts\");\nconst string_utils_1 = __webpack_require__(/*! ./string-utils */ \"./lib/wasm/string-utils.ts\");\nconst wasm_factory_1 = __webpack_require__(/*! ./wasm-factory */ \"./lib/wasm/wasm-factory.ts\");\nconst getGraphOptimzationLevel = (graphOptimizationLevel) => {\n switch (graphOptimizationLevel) {\n case 'disabled':\n return 0;\n case 'basic':\n return 1;\n case 'extended':\n return 2;\n case 'all':\n return 99;\n default:\n throw new Error(`unsupported graph optimization level: ${graphOptimizationLevel}`);\n }\n};\nconst getExecutionMode = (executionMode) => {\n switch (executionMode) {\n case 'sequential':\n return 0;\n case 'parallel':\n return 1;\n default:\n throw new Error(`unsupported execution mode: ${executionMode}`);\n }\n};\nconst appendDefaultOptions = (options) => {\n if (!options.extra) {\n options.extra = {};\n }\n if (!options.extra.session) {\n options.extra.session = {};\n }\n const session = options.extra.session;\n if (!session.use_ort_model_bytes_directly) {\n // eslint-disable-next-line camelcase\n session.use_ort_model_bytes_directly = '1';\n }\n};\nconst setExecutionProviders = (sessionOptionsHandle, executionProviders, allocs) => {\n for (const ep of executionProviders) {\n let epName = typeof ep === 'string' ? ep : ep.name;\n // check EP name\n switch (epName) {\n case 'xnnpack':\n epName = 'XNNPACK';\n break;\n case 'wasm':\n case 'cpu':\n continue;\n default:\n throw new Error(`not supported EP: ${epName}`);\n }\n const epNameDataOffset = (0, string_utils_1.allocWasmString)(epName, allocs);\n if ((0, wasm_factory_1.getInstance)()._OrtAppendExecutionProvider(sessionOptionsHandle, epNameDataOffset) !== 0) {\n throw new Error(`Can't append execution provider: ${epName}`);\n }\n }\n};\nconst setSessionOptions = (options) => {\n const wasm = (0, wasm_factory_1.getInstance)();\n let sessionOptionsHandle = 0;\n const allocs = [];\n const sessionOptions = options || {};\n appendDefaultOptions(sessionOptions);\n try {\n if ((options === null || options === void 0 ? void 0 : options.graphOptimizationLevel) === undefined) {\n sessionOptions.graphOptimizationLevel = 'all';\n }\n const graphOptimizationLevel = getGraphOptimzationLevel(sessionOptions.graphOptimizationLevel);\n if ((options === null || options === void 0 ? void 0 : options.enableCpuMemArena) === undefined) {\n sessionOptions.enableCpuMemArena = true;\n }\n if ((options === null || options === void 0 ? void 0 : options.enableMemPattern) === undefined) {\n sessionOptions.enableMemPattern = true;\n }\n if ((options === null || options === void 0 ? void 0 : options.executionMode) === undefined) {\n sessionOptions.executionMode = 'sequential';\n }\n const executionMode = getExecutionMode(sessionOptions.executionMode);\n let logIdDataOffset = 0;\n if ((options === null || options === void 0 ? void 0 : options.logId) !== undefined) {\n logIdDataOffset = (0, string_utils_1.allocWasmString)(options.logId, allocs);\n }\n if ((options === null || options === void 0 ? void 0 : options.logSeverityLevel) === undefined) {\n sessionOptions.logSeverityLevel = 2; // Default to warning\n }\n else if (typeof options.logSeverityLevel !== 'number' || !Number.isInteger(options.logSeverityLevel) ||\n options.logSeverityLevel < 0 || options.logSeverityLevel > 4) {\n throw new Error(`log serverity level is not valid: ${options.logSeverityLevel}`);\n }\n if ((options === null || options === void 0 ? void 0 : options.logVerbosityLevel) === undefined) {\n sessionOptions.logVerbosityLevel = 0; // Default to 0\n }\n else if (typeof options.logVerbosityLevel !== 'number' || !Number.isInteger(options.logVerbosityLevel)) {\n throw new Error(`log verbosity level is not valid: ${options.logVerbosityLevel}`);\n }\n if ((options === null || options === void 0 ? void 0 : options.enableProfiling) === undefined) {\n sessionOptions.enableProfiling = false;\n }\n sessionOptionsHandle = wasm._OrtCreateSessionOptions(graphOptimizationLevel, !!sessionOptions.enableCpuMemArena, !!sessionOptions.enableMemPattern, executionMode, !!sessionOptions.enableProfiling, 0, logIdDataOffset, sessionOptions.logSeverityLevel, sessionOptions.logVerbosityLevel);\n if (sessionOptionsHandle === 0) {\n throw new Error('Can\\'t create session options');\n }\n if (options === null || options === void 0 ? void 0 : options.executionProviders) {\n setExecutionProviders(sessionOptionsHandle, options.executionProviders, allocs);\n }\n if ((options === null || options === void 0 ? void 0 : options.extra) !== undefined) {\n (0, options_utils_1.iterateExtraOptions)(options.extra, '', new WeakSet(), (key, value) => {\n const keyDataOffset = (0, string_utils_1.allocWasmString)(key, allocs);\n const valueDataOffset = (0, string_utils_1.allocWasmString)(value, allocs);\n if (wasm._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n throw new Error(`Can't set a session config entry: ${key} - ${value}`);\n }\n });\n }\n return [sessionOptionsHandle, allocs];\n }\n catch (e) {\n if (sessionOptionsHandle !== 0) {\n wasm._OrtReleaseSessionOptions(sessionOptionsHandle);\n }\n allocs.forEach(wasm._free);\n throw e;\n }\n};\nexports.setSessionOptions = setSessionOptions;\n\n\n/***/ }),\n\n/***/ \"./lib/wasm/string-utils.ts\":\n/*!**********************************!*\\\n !*** ./lib/wasm/string-utils.ts ***!\n \\**********************************/\n/***/ ((__unused_webpack_module, exports, __webpack_require__) => {\n\n\"use strict\";\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.allocWasmString = void 0;\nconst wasm_factory_1 = __webpack_require__(/*! ./wasm-factory */ \"./lib/wasm/wasm-factory.ts\");\nconst allocWasmString = (data, allocs) => {\n const wasm = (0, wasm_factory_1.getInstance)();\n const dataLength = wasm.lengthBytesUTF8(data) + 1;\n const dataOffset = wasm._malloc(dataLength);\n wasm.stringToUTF8(data, dataOffset, dataLength);\n allocs.push(dataOffset);\n return dataOffset;\n};\nexports.allocWasmString = allocWasmString;\n\n\n/***/ }),\n\n/***/ \"./lib/wasm/wasm-core-impl.ts\":\n/*!************************************!*\\\n !*** ./lib/wasm/wasm-core-impl.ts ***!\n \\************************************/\n/***/ ((__unused_webpack_module, exports, __webpack_require__) => {\n\n\"use strict\";\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.extractTransferableBuffers = exports.endProfiling = exports.run = exports.releaseSession = exports.createSession = exports.createSessionFinalize = exports.createSessionAllocate = exports.initOrt = void 0;\nconst run_options_1 = __webpack_require__(/*! ./run-options */ \"./lib/wasm/run-options.ts\");\nconst session_options_1 = __webpack_require__(/*! ./session-options */ \"./lib/wasm/session-options.ts\");\nconst string_utils_1 = __webpack_require__(/*! ./string-utils */ \"./lib/wasm/string-utils.ts\");\nconst wasm_factory_1 = __webpack_require__(/*! ./wasm-factory */ \"./lib/wasm/wasm-factory.ts\");\n/**\n * initialize ORT environment.\n * @param numThreads SetGlobalIntraOpNumThreads(numThreads)\n * @param loggingLevel CreateEnv(static_cast<OrtLoggingLevel>(logging_level))\n */\nconst initOrt = (numThreads, loggingLevel) => {\n const errorCode = (0, wasm_factory_1.getInstance)()._OrtInit(numThreads, loggingLevel);\n if (errorCode !== 0) {\n throw new Error(`Can't initialize onnxruntime. error code = ${errorCode}`);\n }\n};\nexports.initOrt = initOrt;\nconst activeSessions = new Map();\n/**\n * create an instance of InferenceSession.\n * @returns the metadata of InferenceSession. 0-value handle for failure.\n */\nconst createSessionAllocate = (model) => {\n const wasm = (0, wasm_factory_1.getInstance)();\n const modelDataOffset = wasm._malloc(model.byteLength);\n wasm.HEAPU8.set(model, modelDataOffset);\n return [modelDataOffset, model.byteLength];\n};\nexports.createSessionAllocate = createSessionAllocate;\nconst createSessionFinalize = (modelData, options) => {\n const wasm = (0, wasm_factory_1.getInstance)();\n let sessionHandle = 0;\n let sessionOptionsHandle = 0;\n let allocs = [];\n try {\n [sessionOptionsHandle, allocs] = (0, session_options_1.setSessionOptions)(options);\n sessionHandle = wasm._OrtCreateSession(modelData[0], modelData[1], sessionOptionsHandle);\n if (sessionHandle === 0) {\n throw new Error('Can\\'t create a session');\n }\n }\n finally {\n wasm._free(modelData[0]);\n wasm._OrtReleaseSessionOptions(sessionOptionsHandle);\n allocs.forEach(wasm._free);\n }\n const inputCount = wasm._OrtGetInputCount(sessionHandle);\n const outputCount = wasm._OrtGetOutputCount(sessionHandle);\n const inputNames = [];\n const inputNamesUTF8Encoded = [];\n const outputNames = [];\n const outputNamesUTF8Encoded = [];\n for (let i = 0; i < inputCount; i++) {\n const name = wasm._OrtGetInputName(sessionHandle, i);\n if (name === 0) {\n throw new Error('Can\\'t get an input name');\n }\n inputNamesUTF8Encoded.push(name);\n inputNames.push(wasm.UTF8ToString(name));\n }\n for (let i = 0; i < outputCount; i++) {\n const name = wasm._OrtGetOutputName(sessionHandle, i);\n if (name === 0) {\n throw new Error('Can\\'t get an output name');\n }\n outputNamesUTF8Encoded.push(name);\n outputNames.push(wasm.UTF8ToString(name));\n }\n activeSessions.set(sessionHandle, [sessionHandle, inputNamesUTF8Encoded, outputNamesUTF8Encoded]);\n return [sessionHandle, inputNames, outputNames];\n};\nexports.createSessionFinalize = createSessionFinalize;\n/**\n * create an instance of InferenceSession.\n * @returns the metadata of InferenceSession. 0-value handle for failure.\n */\nconst createSession = (model, options) => {\n const modelData = (0, exports.createSessionAllocate)(model);\n return (0, exports.createSessionFinalize)(modelData, options);\n};\nexports.createSession = createSession;\nconst releaseSession = (sessionId) => {\n const wasm = (0, wasm_factory_1.getInstance)();\n const session = activeSessions.get(sessionId);\n if (!session) {\n throw new Error('invalid session id');\n }\n const sessionHandle = session[0];\n const inputNamesUTF8Encoded = session[1];\n const outputNamesUTF8Encoded = session[2];\n inputNamesUTF8Encoded.forEach(wasm._OrtFree);\n outputNamesUTF8Encoded.forEach(wasm._OrtFree);\n wasm._OrtReleaseSession(sessionHandle);\n activeSessions.delete(sessionId);\n};\nexports.releaseSession = releaseSession;\nconst tensorDataTypeStringToEnum = (type) => {\n switch (type) {\n case 'int8':\n return 3 /* DataType.int8 */;\n case 'uint8':\n return 2 /* DataType.uint8 */;\n case 'bool':\n return 9 /* DataType.bool */;\n case 'int16':\n return 5 /* DataType.int16 */;\n case 'uint16':\n return 4 /* DataType.uint16 */;\n case 'int32':\n return 6 /* DataType.int32 */;\n case 'uint32':\n return 12 /* DataType.uint32 */;\n case 'float32':\n return 1 /* DataType.float */;\n case 'float64':\n return 11 /* DataType.double */;\n case 'string':\n return 8 /* DataType.string */;\n case 'int64':\n return 7 /* DataType.int64 */;\n case 'uint64':\n return 13 /* DataType.uint64 */;\n default:\n throw new Error(`unsupported data type: ${type}`);\n }\n};\nconst tensorDataTypeEnumToString = (typeProto) => {\n switch (typeProto) {\n case 3 /* DataType.int8 */:\n return 'int8';\n case 2 /* DataType.uint8 */:\n return 'uint8';\n case 9 /* DataType.bool */:\n return 'bool';\n case 5 /* DataType.int16 */:\n return 'int16';\n case 4 /* DataType.uint16 */:\n return 'uint16';\n case 6 /* DataType.int32 */:\n return 'int32';\n case 12 /* DataType.uint32 */:\n return 'uint32';\n case 1 /* DataType.float */:\n return 'float32';\n case 11 /* DataType.double */:\n return 'float64';\n case 8 /* DataType.string */:\n return 'string';\n case 7 /* DataType.int64 */:\n return 'int64';\n case 13 /* DataType.uint64 */:\n return 'uint64';\n default:\n throw new Error(`unsupported data type: ${typeProto}`);\n }\n};\nconst numericTensorTypeToTypedArray = (type) => {\n switch (type) {\n case 'float32':\n return Float32Array;\n case 'uint8':\n return Uint8Array;\n case 'int8':\n return Int8Array;\n case 'uint16':\n return Uint16Array;\n case 'int16':\n return Int16Array;\n case 'int32':\n return Int32Array;\n case 'bool':\n return Uint8Array;\n case 'float64':\n return Float64Array;\n case 'uint32':\n return Uint32Array;\n case 'int64':\n return BigInt64Array;\n case 'uint64':\n return BigUint64Array;\n default:\n throw new Error(`unsupported type: ${type}`);\n }\n};\n/**\n * perform inference run\n */\nconst run = (sessionId, inputIndices, inputs, outputIndices, options) => {\n const wasm = (0, wasm_factory_1.getInstance)();\n const session = activeSessions.get(sessionId);\n if (!session) {\n throw new Error('invalid session id');\n }\n const sessionHandle = session[0];\n const inputNamesUTF8Encoded = session[1];\n const outputNamesUTF8Encoded = session[2];\n const inputCount = inputIndices.length;\n const outputCount = outputIndices.length;\n let runOptionsHandle = 0;\n let runOptionsAllocs = [];\n const inputValues = [];\n const inputAllocs = [];\n try {\n [runOptionsHandle, runOptionsAllocs] = (0, run_options_1.setRunOptions)(options);\n // create input tensors\n for (let i = 0; i < inputCount; i++) {\n const dataType = inputs[i][0];\n const dims = inputs[i][1];\n const data = inputs[i][2];\n let dataOffset;\n let dataByteLength;\n if (Array.isArray(data)) {\n // string tensor\n dataByteLength = 4 * data.length;\n dataOffset = wasm._malloc(dataByteLength);\n inputAllocs.push(dataOffset);\n let dataIndex = dataOffset / 4;\n for (let i = 0; i < data.length; i++) {\n if (typeof data[i] !== 'string') {\n throw new TypeError(`tensor data at index ${i} is not a string`);\n }\n wasm.HEAPU32[dataIndex++] = (0, string_utils_1.allocWasmString)(data[i], inputAllocs);\n }\n }\n else {\n dataByteLength = data.byteLength;\n dataOffset = wasm._malloc(dataByteLength);\n inputAllocs.push(dataOffset);\n wasm.HEAPU8.set(new Uint8Array(data.buffer, data.byteOffset, dataByteLength), dataOffset);\n }\n const stack = wasm.stackSave();\n const dimsOffset = wasm.stackAlloc(4 * dims.length);\n try {\n let dimIndex = dimsOffset / 4;\n dims.forEach(d => wasm.HEAP32[dimIndex++] = d);\n const tensor = wasm._OrtCreateTensor(tensorDataTypeStringToEnum(dataType), dataOffset, dataByteLength, dimsOffset, dims.length);\n if (tensor === 0) {\n throw new Error('Can\\'t create a tensor');\n }\n inputValues.push(tensor);\n }\n finally {\n wasm.stackRestore(stack);\n }\n }\n const beforeRunStack = wasm.stackSave();\n const inputValuesOffset = wasm.stackAlloc(inputCount * 4);\n const inputNamesOffset = wasm.stackAlloc(inputCount * 4);\n const outputValuesOffset = wasm.stackAlloc(outputCount * 4);\n const outputNamesOffset = wasm.stackAlloc(outputCount * 4);\n try {\n let inputValuesIndex = inputValuesOffset / 4;\n let inputNamesIndex = inputNamesOffset / 4;\n let outputValuesIndex = outputValuesOffset / 4;\n let outputNamesIndex = outputNamesOffset / 4;\n for (let i = 0; i < inputCount; i++) {\n wasm.HEAPU32[inputValuesIndex++] = inputValues[i];\n wasm.HEAPU32[inputNamesIndex++] = inputNamesUTF8Encoded[inputIndices[i]];\n }\n for (let i = 0; i < outputCount; i++) {\n wasm.HEAPU32[outputValuesIndex++] = 0;\n wasm.HEAPU32[outputNamesIndex++] = outputNamesUTF8Encoded[outputIndices[i]];\n }\n // support RunOptions\n let errorCode = wasm._OrtRun(sessionHandle, inputNamesOffset, inputValuesOffset, inputCount, outputNamesOffset, outputCount, outputValuesOffset, runOptionsHandle);\n const output = [];\n if (errorCode === 0) {\n for (let i = 0; i < outputCount; i++) {\n const tensor = wasm.HEAPU32[outputValuesOffset / 4 + i];\n const beforeGetTensorDataStack = wasm.stackSave();\n // stack allocate 4 pointer value\n const tensorDataOffset = wasm.stackAlloc(4 * 4);\n let type, dataOffset = 0;\n try {\n errorCode = wasm._OrtGetTensorData(tensor, tensorDataOffset, tensorDataOffset + 4, tensorDataOffset + 8, tensorDataOffset + 12);\n if (errorCode !== 0) {\n throw new Error(`Can't access output tensor data. error code = ${errorCode}`);\n }\n let tensorDataIndex = tensorDataOffset / 4;\n const dataType = wasm.HEAPU32[tensorDataIndex++];\n dataOffset = wasm.HEAPU32[tensorDataIndex++];\n const dimsOffset = wasm.HEAPU32[tensorDataIndex++];\n const dimsLength = wasm.HEAPU32[tensorDataIndex++];\n const dims = [];\n for (let i = 0; i < dimsLength; i++) {\n dims.push(wasm.HEAPU32[dimsOffset / 4 + i]);\n }\n wasm._OrtFree(dimsOffset);\n const size = dims.length === 0 ? 1 : dims.reduce((a, b) => a * b);\n type = tensorDataTypeEnumToString(dataType);\n if (type === 'string') {\n const stringData = [];\n let dataIndex = dataOffset / 4;\n for (let i = 0; i < size; i++) {\n const offset = wasm.HEAPU32[dataIndex++];\n const maxBytesToRead = i === size - 1 ? undefined : wasm.HEAPU32[dataIndex] - offset;\n stringData.push(wasm.UTF8ToString(offset, maxBytesToRead));\n }\n output.push([type, dims, stringData]);\n }\n else {\n const typedArrayConstructor = numericTensorTypeToTypedArray(type);\n const data = new typedArrayConstructor(size);\n new Uint8Array(data.buffer, data.byteOffset, data.byteLength)\n .set(wasm.HEAPU8.subarray(dataOffset, dataOffset + data.byteLength));\n output.push([type, dims, data]);\n }\n }\n finally {\n wasm.stackRestore(beforeGetTensorDataStack);\n if (type === 'string' && dataOffset) {\n wasm._free(dataOffset);\n }\n wasm._OrtReleaseTensor(tensor);\n }\n }\n }\n if (errorCode === 0) {\n return output;\n }\n else {\n throw new Error(`failed to call OrtRun(). error code = ${errorCode}.`);\n }\n }\n finally {\n wasm.stackRestore(beforeRunStack);\n }\n }\n finally {\n inputValues.forEach(wasm._OrtReleaseTensor);\n inputAllocs.forEach(wasm._free);\n wasm._OrtReleaseRunOptions(runOptionsHandle);\n runOptionsAllocs.forEach(wasm._free);\n }\n};\nexports.run = run;\n/**\n * end profiling\n */\nconst endProfiling = (sessionId) => {\n const wasm = (0, wasm_factory_1.getInstance)();\n const session = activeSessions.get(sessionId);\n if (!session) {\n throw new Error('invalid session id');\n }\n const sessionHandle = session[0];\n // profile file name is not used yet, but it must be freed.\n const profileFileName = wasm._OrtEndProfiling(sessionHandle);\n if (profileFileName === 0) {\n throw new Error('Can\\'t get an profile file name');\n }\n wasm._OrtFree(profileFileName);\n};\nexports.endProfiling = endProfiling;\nconst extractTransferableBuffers = (tensors) => {\n const buffers = [];\n for (const tensor of tensors) {\n const data = tensor[2];\n if (!Array.isArray(data) && data.buffer) {\n buffers.push(data.buffer);\n }\n }\n return buffers;\n};\nexports.extractTransferableBuffers = extractTransferableBuffers;\n\n\n/***/ }),\n\n/***/ \"./lib/wasm/wasm-factory.ts\":\n/*!**********************************!*\\\n !*** ./lib/wasm/wasm-factory.ts ***!\n \\**********************************/\n/***/ (function(__unused_webpack_module, exports, __webpack_require__) {\n\n\"use strict\";\nvar __dirname = \"/\";\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.dispose = exports.getInstance = exports.initializeWebAssembly = void 0;\nconst path = __importStar(__webpack_require__(/*! path */ \"?7aa5\"));\nconst ort_wasm_js_1 = __importDefault(__webpack_require__(/*! ./binding/ort-wasm.js */ \"./lib/wasm/binding/ort-wasm.js\"));\nconst ortWasmFactoryThreaded = \n// eslint-disable-next-line @typescript-eslint/no-require-imports\n true ? __webpack_require__(/*! ./binding/ort-wasm-threaded.js */ \"./lib/wasm/binding/ort-wasm-threaded.js\") : 0;\nlet wasm;\nlet initialized = false;\nlet initializing = false;\nlet aborted = false;\nconst isMultiThreadSupported = () => {\n try {\n // If 'SharedArrayBuffer' is not available, WebAssembly threads will not work.\n if (typeof SharedArrayBuffer === 'undefined') {\n return false;\n }\n // Test for transferability of SABs (for browsers. needed for Firefox)\n // https://groups.google.com/forum/#!msg/mozilla.dev.platform/IHkBZlHETpA/dwsMNchWEQAJ\n if (typeof MessageChannel !== 'undefined') {\n new MessageChannel().port1.postMessage(new SharedArrayBuffer(1));\n }\n // Test for WebAssembly threads capability (for both browsers and Node.js)\n // This typed array is a WebAssembly program containing threaded instructions.\n return WebAssembly.validate(new Uint8Array([\n 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5,\n 4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11\n ]));\n }\n catch (e) {\n return false;\n }\n};\nconst isSimdSupported = () => {\n try {\n // Test for WebAssembly SIMD capability (for both browsers and Node.js)\n // This typed array is a WebAssembly program containing SIMD instructions.\n // The binary data is generated from the following code by wat2wasm:\n //\n // (module\n // (type $t0 (func))\n // (func $f0 (type $t0)\n // (drop\n // (i32x4.dot_i16x8_s\n // (i8x16.splat\n // (i32.const 0))\n // (v128.const i32x4 0x00000000 0x00000000 0x00000000 0x00000000)))))\n return WebAssembly.validate(new Uint8Array([\n 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 30, 1, 28, 0, 65, 0,\n 253, 15, 253, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 253, 186, 1, 26, 11\n ]));\n }\n catch (e) {\n return false;\n }\n};\nconst getWasmFileName = (useSimd, useThreads) => {\n if (useThreads) {\n return useSimd ? 'ort-wasm-simd-threaded.wasm' : 'ort-wasm-threaded.wasm';\n }\n else {\n return useSimd ? 'ort-wasm-simd.wasm' : 'ort-wasm.wasm';\n }\n};\nconst initializeWebAssembly = async (flags) => {\n if (initialized) {\n return Promise.resolve();\n }\n if (initializing) {\n throw new Error('multiple calls to \\'initializeWebAssembly()\\' detected.');\n }\n if (aborted) {\n throw new Error('previous call to \\'initializeWebAssembly()\\' failed.');\n }\n initializing = true;\n // wasm flags are already initialized\n const timeout = flags.initTimeout;\n const numThreads = flags.numThreads;\n const simd = flags.simd;\n const useThreads = numThreads > 1 && isMultiThreadSupported();\n const useSimd = simd && isSimdSupported();\n const wasmPrefixOverride = typeof flags.wasmPaths === 'string' ? flags.wasmPaths : undefined;\n const wasmFileName = getWasmFileName(false, useThreads);\n const wasmOverrideFileName = getWasmFileName(useSimd, useThreads);\n const wasmPathOverride = typeof flags.wasmPaths === 'object' ? flags.wasmPaths[wasmOverrideFileName] : undefined;\n let isTimeout = false;\n const tasks = [];\n // promise for timeout\n if (timeout > 0) {\n tasks.push(new Promise((resolve) => {\n setTimeout(() => {\n isTimeout = true;\n resolve();\n }, timeout);\n }));\n }\n // promise for module initialization\n tasks.push(new Promise((resolve, reject) => {\n const factory = useThreads ? ortWasmFactoryThreaded : ort_wasm_js_1.default;\n const config = {\n locateFile: (fileName, scriptDirectory) => {\n if ( true && useThreads && fileName.endsWith('.worker.js') &&\n typeof Blob !== 'undefined') {\n return URL.createObjectURL(new Blob([\n // This require() function is handled by webpack to load file content of the corresponding .worker.js\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n __webpack_require__(/*! ./binding/ort-wasm-threaded.worker.js */ \"./lib/wasm/binding/ort-wasm-threaded.worker.js\")\n ], { type: 'text/javascript' }));\n }\n if (fileName === wasmFileName) {\n const prefix = wasmPrefixOverride !== null && wasmPrefixOverride !== void 0 ? wasmPrefixOverride : scriptDirectory;\n return wasmPathOverride !== null && wasmPathOverride !== void 0 ? wasmPathOverride : prefix + wasmOverrideFileName;\n }\n return scriptDirectory + fileName;\n }\n };\n if ( true && useThreads) {\n if (typeof Blob === 'undefined') {\n config.mainScriptUrlOrBlob = path.join(__dirname, 'ort-wasm-threaded.js');\n }\n else {\n const scriptSourceCode = `var ortWasmThreaded=(function(){var _scriptDir;return ${factory.toString()}})();`;\n config.mainScriptUrlOrBlob = new Blob([scriptSourceCode], { type: 'text/javascript' });\n }\n }\n factory(config).then(\n // wasm module initialized successfully\n module => {\n initializing = false;\n initialized = true;\n wasm = module;\n resolve();\n }, \n // wasm module failed to initialize\n (what) => {\n initializing = false;\n aborted = true;\n reject(what);\n });\n }));\n await Promise.race(tasks);\n if (isTimeout) {\n throw new Error(`WebAssembly backend initializing failed due to timeout: ${timeout}ms`);\n }\n};\nexports.initializeWebAssembly = initializeWebAssembly;\nconst getInstance = () => {\n if (initialized && wasm) {\n return wasm;\n }\n throw new Error('WebAssembly is not initialized yet.');\n};\nexports.getInstance = getInstance;\nconst dispose = () => {\n var _a;\n if (initialized && !initializing && !aborted) {\n initializing = true;\n (_a = wasm.PThread) === null || _a === void 0 ? void 0 : _a.terminateAllThreads();\n wasm = undefined;\n initializing = false;\n initialized = false;\n aborted = true;\n }\n};\nexports.dispose = dispose;\n\n\n/***/ }),\n\n/***/ \"./lib/wasm/binding/ort-wasm-threaded.worker.js\":\n/*!******************************************************!*\\\n !*** ./lib/wasm/binding/ort-wasm-threaded.worker.js ***!\n \\******************************************************/\n/***/ ((module) => {\n\n\"use strict\";\nmodule.exports = \"\\\"use strict\\\";var Module={};var ENVIRONMENT_IS_NODE=typeof process==\\\"object\\\"&&typeof process.versions==\\\"object\\\"&&typeof process.versions.node==\\\"string\\\";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require(\\\"worker_threads\\\");var parentPort=nodeWorkerThreads.parentPort;parentPort.on(\\\"message\\\",data=>onmessage({data:data}));var fs=require(\\\"fs\\\");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,\\\"utf8\\\"))},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}var initializedJS=false;var pendingNotifiedProxyingQueues=[];function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(\\\" \\\");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+\\\"\\\\n\\\");return}console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(\\\" \\\");postMessage({cmd:\\\"alert\\\",text:text,threadId:Module[\\\"_pthread_self\\\"]()})}var err=threadPrintErr;self.alert=threadAlert;Module[\\\"instantiateWasm\\\"]=(info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module[\\\"wasmModule\\\"],info);receiveInstance(instance);Module[\\\"wasmModule\\\"]=null;return instance.exports};self.onunhandledrejection=e=>{throw e.reason??e};self.onmessage=e=>{try{if(e.data.cmd===\\\"load\\\"){Module[\\\"wasmModule\\\"]=e.data.wasmModule;Module[\\\"wasmMemory\\\"]=e.data.wasmMemory;Module[\\\"buffer\\\"]=Module[\\\"wasmMemory\\\"].buffer;Module[\\\"ENVIRONMENT_IS_PTHREAD\\\"]=true;if(typeof e.data.urlOrBlob==\\\"string\\\"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}ortWasmThreaded(Module).then(function(instance){Module=instance})}else if(e.data.cmd===\\\"run\\\"){Module[\\\"__performance_now_clock_drift\\\"]=performance.now()-e.data.time;Module[\\\"__emscripten_thread_init\\\"](e.data.pthread_ptr,/*isMainBrowserThread=*/0,/*isMainRuntimeThread=*/0,/*canBlock=*/1);Module[\\\"establishStackSpace\\\"]();Module[\\\"PThread\\\"].receiveObjectTransfer(e.data);Module[\\\"PThread\\\"].threadInitTLS();if(!initializedJS){pendingNotifiedProxyingQueues.forEach(queue=>{Module[\\\"executeNotifiedProxyingQueue\\\"](queue)});pendingNotifiedProxyingQueues=[];initializedJS=true}try{Module[\\\"invokeEntryPoint\\\"](e.data.start_routine,e.data.arg)}catch(ex){if(ex!=\\\"unwind\\\"){if(ex instanceof Module[\\\"ExitStatus\\\"]){if(Module[\\\"keepRuntimeAlive\\\"]()){}else{Module[\\\"__emscripten_thread_exit\\\"](ex.status)}}else{throw ex}}}}else if(e.data.cmd===\\\"cancel\\\"){if(Module[\\\"_pthread_self\\\"]()){Module[\\\"__emscripten_thread_exit\\\"](-1)}}else if(e.data.target===\\\"setimmediate\\\"){}else if(e.data.cmd===\\\"processProxyingQueue\\\"){if(initializedJS){Module[\\\"executeNotifiedProxyingQueue\\\"](e.data.queue)}else{pendingNotifiedProxyingQueues.push(e.data.queue)}}else{err(\\\"worker.js received unknown command \\\"+e.data.cmd);err(e.data)}}catch(ex){err(\\\"worker.js onmessage() captured an uncaught exception: \\\"+ex);if(ex&&ex.stack)err(ex.stack);if(Module[\\\"__emscripten_thread_crashed\\\"]){Module[\\\"__emscripten_thread_crashed\\\"]()}throw ex}};\\r\\n\";\n\n/***/ }),\n\n/***/ \"?63c8\":\n/*!********************!*\\\n !*** fs (ignored) ***!\n \\********************/\n/***/ (() => {\n\n/* (ignored) */\n\n/***/ }),\n\n/***/ \"?aedb\":\n/*!********************!*\\\n !*** os (ignored) ***!\n \\********************/\n/***/ (() => {\n\n/* (ignored) */\n\n/***/ }),\n\n/***/ \"?75c6\":\n/*!**********************!*\\\n !*** path (ignored) ***!\n \\**********************/\n/***/ (() => {\n\n/* (ignored) */\n\n/***/ }),\n\n/***/ \"?674f\":\n/*!****************************!*\\\n !*** perf_hooks (ignored) ***!\n \\****************************/\n/***/ (() => {\n\n/* (ignored) */\n\n/***/ }),\n\n/***/ \"?c6f7\":\n/*!********************************!*\\\n !*** worker_threads (ignored) ***!\n \\********************************/\n/***/ (() => {\n\n/* (ignored) */\n\n/***/ }),\n\n/***/ \"?7aa5\":\n/*!**********************!*\\\n !*** path (ignored) ***!\n \\**********************/\n/***/ (() => {\n\n/* (ignored) */\n\n/***/ })\n\n/******/ \t});\n/************************************************************************/\n/******/ \t// The module cache\n/******/ \tvar __webpack_module_cache__ = {};\n/******/ \t\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/ \t\t// Check if module is in cache\n/******/ \t\tvar cachedModule = __webpack_module_cache__[moduleId];\n/******/ \t\tif (cachedModule !== undefined) {\n/******/ \t\t\treturn cachedModule.exports;\n/******/ \t\t}\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = __webpack_module_cache__[moduleId] = {\n/******/ \t\t\t// no module.id needed\n/******/ \t\t\t// no module.loaded needed\n/******/ \t\t\texports: {}\n/******/ \t\t};\n/******/ \t\n/******/ \t\t// Execute the module function\n/******/ \t\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n/******/ \t\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/ \t\n/************************************************************************/\n/******/ \t/* webpack/runtime/global */\n/******/ \t(() => {\n/******/ \t\t__webpack_require__.g = (function() {\n/******/ \t\t\tif (typeof globalThis === 'object') return globalThis;\n/******/ \t\t\ttry {\n/******/ \t\t\t\treturn this || new Function('return this')();\n/******/ \t\t\t} catch (e) {\n/******/ \t\t\t\tif (typeof window === 'object') return window;\n/******/ \t\t\t}\n/******/ \t\t})();\n/******/ \t})();\n/******/ \t\n/************************************************************************/\nvar __webpack_exports__ = {};\n// This entry need to be wrapped in an IIFE because it need to be in strict mode.\n(() => {\n\"use strict\";\nvar exports = __webpack_exports__;\n/*!*****************************************************************************************************!*\\\n !*** ./node_modules/ts-loader/index.js??ruleSet[1].rules[0].use[0]!./lib/wasm/proxy-worker/main.ts ***!\n \\*****************************************************************************************************/\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst wasm_core_impl_1 = __webpack_require__(/*! ../wasm-core-impl */ \"./lib/wasm/wasm-core-impl.ts\");\nconst wasm_factory_1 = __webpack_require__(/*! ../wasm-factory */ \"./lib/wasm/wasm-factory.ts\");\nself.onmessage = (ev) => {\n switch (ev.data.type) {\n case 'init-wasm':\n (0, wasm_factory_1.initializeWebAssembly)(ev.data.in)\n .then(() => postMessage({ type: 'init-wasm' }), err => postMessage({ type: 'init-wasm', err }));\n break;\n case 'init-ort':\n try {\n const { numThreads, loggingLevel } = ev.data.in;\n (0, wasm_core_impl_1.initOrt)(numThreads, loggingLevel);\n postMessage({ type: 'init-ort' });\n }\n catch (err) {\n postMessage({ type: 'init-ort', err });\n }\n break;\n case 'create_allocate':\n try {\n const { model } = ev.data.in;\n const modeldata = (0, wasm_core_impl_1.createSessionAllocate)(model);\n postMessage({ type: 'create_allocate', out: modeldata });\n }\n catch (err) {\n postMessage({ type: 'create_allocate', err });\n }\n break;\n case 'create_finalize':\n try {\n const { modeldata, options } = ev.data.in;\n const sessionMetadata = (0, wasm_core_impl_1.createSessionFinalize)(modeldata, options);\n postMessage({ type: 'create_finalize', out: sessionMetadata });\n }\n catch (err) {\n postMessage({ type: 'create_finalize', err });\n }\n break;\n case 'create':\n try {\n const { model, options } = ev.data.in;\n const sessionMetadata = (0, wasm_core_impl_1.createSession)(model, options);\n postMessage({ type: 'create', out: sessionMetadata });\n }\n catch (err) {\n postMessage({ type: 'create', err });\n }\n break;\n case 'release':\n try {\n const handler = ev.data.in;\n (0, wasm_core_impl_1.releaseSession)(handler);\n postMessage({ type: 'release' });\n }\n catch (err) {\n postMessage({ type: 'release', err });\n }\n break;\n case 'run':\n try {\n const { sessionId, inputIndices, inputs, outputIndices, options } = ev.data.in;\n const outputs = (0, wasm_core_impl_1.run)(sessionId, inputIndices, inputs, outputIndices, options);\n postMessage({ type: 'run', out: outputs }, (0, wasm_core_impl_1.extractTransferableBuffers)(outputs));\n }\n catch (err) {\n postMessage({ type: 'run', err });\n }\n break;\n case 'end-profiling':\n try {\n const handler = ev.data.in;\n (0, wasm_core_impl_1.endProfiling)(handler);\n postMessage({ type: 'end-profiling' });\n }\n catch (err) {\n postMessage({ type: 'end-profiling', err });\n }\n break;\n default:\n }\n};\n\n})();\n\n/******/ })()\n;\n", "Worker", undefined, undefined);
+}
+
+
+/***/ }),
+
+/***/ "./node_modules/worker-loader/dist/runtime/inline.js":
+/*!***********************************************************!*\
+ !*** ./node_modules/worker-loader/dist/runtime/inline.js ***!
+ \***********************************************************/
+/***/ ((module) => {
+
+"use strict";
+
+
+/* eslint-env browser */
+
+/* eslint-disable no-undef, no-use-before-define, new-cap */
+module.exports = function (content, workerConstructor, workerOptions, url) {
+ var globalScope = self || window;
+
+ try {
+ try {
+ var blob;
+
+ try {
+ // New API
+ blob = new globalScope.Blob([content]);
+ } catch (e) {
+ // BlobBuilder = Deprecated, but widely implemented
+ var BlobBuilder = globalScope.BlobBuilder || globalScope.WebKitBlobBuilder || globalScope.MozBlobBuilder || globalScope.MSBlobBuilder;
+ blob = new BlobBuilder();
+ blob.append(content);
+ blob = blob.getBlob();
+ }
+
+ var URL = globalScope.URL || globalScope.webkitURL;
+ var objectURL = URL.createObjectURL(blob);
+ var worker = new globalScope[workerConstructor](objectURL, workerOptions);
+ URL.revokeObjectURL(objectURL);
+ return worker;
+ } catch (e) {
+ return new globalScope[workerConstructor]("data:application/javascript,".concat(encodeURIComponent(content)), workerOptions);
+ }
+ } catch (e) {
+ if (!url) {
+ throw Error("Inline worker is not supported");
+ }
+
+ return new globalScope[workerConstructor](url, workerOptions);
+ }
+};
+
+/***/ }),
+
+/***/ "./lib/wasm/binding/ort-wasm-threaded.worker.js":
+/*!******************************************************!*\
+ !*** ./lib/wasm/binding/ort-wasm-threaded.worker.js ***!
+ \******************************************************/
+/***/ ((module) => {
+
+"use strict";
+module.exports = "\"use strict\";var Module={};var ENVIRONMENT_IS_NODE=typeof process==\"object\"&&typeof process.versions==\"object\"&&typeof process.versions.node==\"string\";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require(\"worker_threads\");var parentPort=nodeWorkerThreads.parentPort;parentPort.on(\"message\",data=>onmessage({data:data}));var fs=require(\"fs\");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,\"utf8\"))},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}var initializedJS=false;var pendingNotifiedProxyingQueues=[];function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(\" \");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+\"\\n\");return}console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(\" \");postMessage({cmd:\"alert\",text:text,threadId:Module[\"_pthread_self\"]()})}var err=threadPrintErr;self.alert=threadAlert;Module[\"instantiateWasm\"]=(info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module[\"wasmModule\"],info);receiveInstance(instance);Module[\"wasmModule\"]=null;return instance.exports};self.onunhandledrejection=e=>{throw e.reason??e};self.onmessage=e=>{try{if(e.data.cmd===\"load\"){Module[\"wasmModule\"]=e.data.wasmModule;Module[\"wasmMemory\"]=e.data.wasmMemory;Module[\"buffer\"]=Module[\"wasmMemory\"].buffer;Module[\"ENVIRONMENT_IS_PTHREAD\"]=true;if(typeof e.data.urlOrBlob==\"string\"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}ortWasmThreaded(Module).then(function(instance){Module=instance})}else if(e.data.cmd===\"run\"){Module[\"__performance_now_clock_drift\"]=performance.now()-e.data.time;Module[\"__emscripten_thread_init\"](e.data.pthread_ptr,/*isMainBrowserThread=*/0,/*isMainRuntimeThread=*/0,/*canBlock=*/1);Module[\"establishStackSpace\"]();Module[\"PThread\"].receiveObjectTransfer(e.data);Module[\"PThread\"].threadInitTLS();if(!initializedJS){pendingNotifiedProxyingQueues.forEach(queue=>{Module[\"executeNotifiedProxyingQueue\"](queue)});pendingNotifiedProxyingQueues=[];initializedJS=true}try{Module[\"invokeEntryPoint\"](e.data.start_routine,e.data.arg)}catch(ex){if(ex!=\"unwind\"){if(ex instanceof Module[\"ExitStatus\"]){if(Module[\"keepRuntimeAlive\"]()){}else{Module[\"__emscripten_thread_exit\"](ex.status)}}else{throw ex}}}}else if(e.data.cmd===\"cancel\"){if(Module[\"_pthread_self\"]()){Module[\"__emscripten_thread_exit\"](-1)}}else if(e.data.target===\"setimmediate\"){}else if(e.data.cmd===\"processProxyingQueue\"){if(initializedJS){Module[\"executeNotifiedProxyingQueue\"](e.data.queue)}else{pendingNotifiedProxyingQueues.push(e.data.queue)}}else{err(\"worker.js received unknown command \"+e.data.cmd);err(e.data)}}catch(ex){err(\"worker.js onmessage() captured an uncaught exception: \"+ex);if(ex&&ex.stack)err(ex.stack);if(Module[\"__emscripten_thread_crashed\"]){Module[\"__emscripten_thread_crashed\"]()}throw ex}};\r\n";
+
+/***/ }),
+
+/***/ "?6c45":
+/*!********************!*\
+ !*** fs (ignored) ***!
+ \********************/
+/***/ (() => {
+
+/* (ignored) */
+
+/***/ }),
+
+/***/ "?b3a2":
+/*!**********************!*\
+ !*** util (ignored) ***!
+ \**********************/
+/***/ (() => {
+
+/* (ignored) */
+
+/***/ }),
+
+/***/ "?63c8":
+/*!********************!*\
+ !*** fs (ignored) ***!
+ \********************/
+/***/ (() => {
+
+/* (ignored) */
+
+/***/ }),
+
+/***/ "?aedb":
+/*!********************!*\
+ !*** os (ignored) ***!
+ \********************/
+/***/ (() => {
+
+/* (ignored) */
+
+/***/ }),
+
+/***/ "?75c6":
+/*!**********************!*\
+ !*** path (ignored) ***!
+ \**********************/
+/***/ (() => {
+
+/* (ignored) */
+
+/***/ }),
+
+/***/ "?674f":
+/*!****************************!*\
+ !*** perf_hooks (ignored) ***!
+ \****************************/
+/***/ (() => {
+
+/* (ignored) */
+
+/***/ }),
+
+/***/ "?c6f7":
+/*!********************************!*\
+ !*** worker_threads (ignored) ***!
+ \********************************/
+/***/ (() => {
+
+/* (ignored) */
+
+/***/ }),
+
+/***/ "?295d":
+/*!********************!*\
+ !*** fs (ignored) ***!
+ \********************/
+/***/ (() => {
+
+/* (ignored) */
+
+/***/ }),
+
+/***/ "?7aa5":
+/*!**********************!*\
+ !*** path (ignored) ***!
+ \**********************/
+/***/ (() => {
+
+/* (ignored) */
+
+/***/ }),
+
+/***/ "?cf98":
+/*!**********************!*\
+ !*** util (ignored) ***!
+ \**********************/
+/***/ (() => {
+
+/* (ignored) */
+
+/***/ }),
+
+/***/ "?0757":
+/*!********************!*\
+ !*** os (ignored) ***!
+ \********************/
+/***/ (() => {
+
+/* (ignored) */
+
+/***/ }),
+
+/***/ "./node_modules/flatbuffers/js/flatbuffers.mjs":
+/*!*****************************************************!*\
+ !*** ./node_modules/flatbuffers/js/flatbuffers.mjs ***!
+ \*****************************************************/
+/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ "flatbuffers": () => (/* binding */ flatbuffers)
+/* harmony export */ });
+/// @file
+/// @addtogroup flatbuffers_javascript_api
+/// @{
+/// @cond FLATBUFFERS_INTERNAL
+
+/**
+ * @fileoverview
+ *
+ * Need to suppress 'global this' error so the Node.js export line doesn't cause
+ * closure compile to error out.
+ * @suppress {globalThis}
+ */
+
+/**
+ * @const
+ * @namespace
+ */
+var flatbuffers = {};
+
+/**
+ * @typedef {number}
+ */
+flatbuffers.Offset;
+
+/**
+ * @typedef {{
+ * bb: flatbuffers.ByteBuffer,
+ * bb_pos: number
+ * }}
+ */
+flatbuffers.Table;
+
+/**
+ * @type {number}
+ * @const
+ */
+flatbuffers.SIZEOF_SHORT = 2;
+
+/**
+ * @type {number}
+ * @const
+ */
+flatbuffers.SIZEOF_INT = 4;
+
+/**
+ * @type {number}
+ * @const
+ */
+flatbuffers.FILE_IDENTIFIER_LENGTH = 4;
+
+/**
+ * @type {number}
+ * @const
+ */
+flatbuffers.SIZE_PREFIX_LENGTH = 4;
+
+/**
+ * @enum {number}
+ */
+flatbuffers.Encoding = {
+ UTF8_BYTES: 1,
+ UTF16_STRING: 2
+};
+
+/**
+ * @type {Int32Array}
+ * @const
+ */
+flatbuffers.int32 = new Int32Array(2);
+
+/**
+ * @type {Float32Array}
+ * @const
+ */
+flatbuffers.float32 = new Float32Array(flatbuffers.int32.buffer);
+
+/**
+ * @type {Float64Array}
+ * @const
+ */
+flatbuffers.float64 = new Float64Array(flatbuffers.int32.buffer);
+
+/**
+ * @type {boolean}
+ * @const
+ */
+flatbuffers.isLittleEndian = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1;
+
+////////////////////////////////////////////////////////////////////////////////
+
+/**
+ * @constructor
+ * @param {number} low
+ * @param {number} high
+ */
+flatbuffers.Long = function(low, high) {
+ /**
+ * @type {number}
+ * @const
+ */
+ this.low = low | 0;
+
+ /**
+ * @type {number}
+ * @const
+ */
+ this.high = high | 0;
+};
+
+/**
+ * @param {number} low
+ * @param {number} high
+ * @returns {!flatbuffers.Long}
+ */
+flatbuffers.Long.create = function(low, high) {
+ // Special-case zero to avoid GC overhead for default values
+ return low == 0 && high == 0 ? flatbuffers.Long.ZERO : new flatbuffers.Long(low, high);
+};
+
+/**
+ * @returns {number}
+ */
+flatbuffers.Long.prototype.toFloat64 = function() {
+ return (this.low >>> 0) + this.high * 0x100000000;
+};
+
+/**
+ * @param {flatbuffers.Long} other
+ * @returns {boolean}
+ */
+flatbuffers.Long.prototype.equals = function(other) {
+ return this.low == other.low && this.high == other.high;
+};
+
+/**
+ * @type {!flatbuffers.Long}
+ * @const
+ */
+flatbuffers.Long.ZERO = new flatbuffers.Long(0, 0);
+
+/// @endcond
+////////////////////////////////////////////////////////////////////////////////
+/**
+ * Create a FlatBufferBuilder.
+ *
+ * @constructor
+ * @param {number=} opt_initial_size
+ */
+flatbuffers.Builder = function(opt_initial_size) {
+ if (!opt_initial_size) {
+ var initial_size = 1024;
+ } else {
+ var initial_size = opt_initial_size;
+ }
+
+ /**
+ * @type {flatbuffers.ByteBuffer}
+ * @private
+ */
+ this.bb = flatbuffers.ByteBuffer.allocate(initial_size);
+
+ /**
+ * Remaining space in the ByteBuffer.
+ *
+ * @type {number}
+ * @private
+ */
+ this.space = initial_size;
+
+ /**
+ * Minimum alignment encountered so far.
+ *
+ * @type {number}
+ * @private
+ */
+ this.minalign = 1;
+
+ /**
+ * The vtable for the current table.
+ *
+ * @type {Array.<number>}
+ * @private
+ */
+ this.vtable = null;
+
+ /**
+ * The amount of fields we're actually using.
+ *
+ * @type {number}
+ * @private
+ */
+ this.vtable_in_use = 0;
+
+ /**
+ * Whether we are currently serializing a table.
+ *
+ * @type {boolean}
+ * @private
+ */
+ this.isNested = false;
+
+ /**
+ * Starting offset of the current struct/table.
+ *
+ * @type {number}
+ * @private
+ */
+ this.object_start = 0;
+
+ /**
+ * List of offsets of all vtables.
+ *
+ * @type {Array.<number>}
+ * @private
+ */
+ this.vtables = [];
+
+ /**
+ * For the current vector being built.
+ *
+ * @type {number}
+ * @private
+ */
+ this.vector_num_elems = 0;
+
+ /**
+ * False omits default values from the serialized data
+ *
+ * @type {boolean}
+ * @private
+ */
+ this.force_defaults = false;
+};
+
+flatbuffers.Builder.prototype.clear = function() {
+ this.bb.clear();
+ this.space = this.bb.capacity();
+ this.minalign = 1;
+ this.vtable = null;
+ this.vtable_in_use = 0;
+ this.isNested = false;
+ this.object_start = 0;
+ this.vtables = [];
+ this.vector_num_elems = 0;
+ this.force_defaults = false;
+};
+
+/**
+ * In order to save space, fields that are set to their default value
+ * don't get serialized into the buffer. Forcing defaults provides a
+ * way to manually disable this optimization.
+ *
+ * @param {boolean} forceDefaults true always serializes default values
+ */
+flatbuffers.Builder.prototype.forceDefaults = function(forceDefaults) {
+ this.force_defaults = forceDefaults;
+};
+
+/**
+ * Get the ByteBuffer representing the FlatBuffer. Only call this after you've
+ * called finish(). The actual data starts at the ByteBuffer's current position,
+ * not necessarily at 0.
+ *
+ * @returns {flatbuffers.ByteBuffer}
+ */
+flatbuffers.Builder.prototype.dataBuffer = function() {
+ return this.bb;
+};
+
+/**
+ * Get the bytes representing the FlatBuffer. Only call this after you've
+ * called finish().
+ *
+ * @returns {!Uint8Array}
+ */
+flatbuffers.Builder.prototype.asUint8Array = function() {
+ return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset());
+};
+
+/// @cond FLATBUFFERS_INTERNAL
+/**
+ * Prepare to write an element of `size` after `additional_bytes` have been
+ * written, e.g. if you write a string, you need to align such the int length
+ * field is aligned to 4 bytes, and the string data follows it directly. If all
+ * you need to do is alignment, `additional_bytes` will be 0.
+ *
+ * @param {number} size This is the of the new element to write
+ * @param {number} additional_bytes The padding size
+ */
+flatbuffers.Builder.prototype.prep = function(size, additional_bytes) {
+ // Track the biggest thing we've ever aligned to.
+ if (size > this.minalign) {
+ this.minalign = size;
+ }
+
+ // Find the amount of alignment needed such that `size` is properly
+ // aligned after `additional_bytes`
+ var align_size = ((~(this.bb.capacity() - this.space + additional_bytes)) + 1) & (size - 1);
+
+ // Reallocate the buffer if needed.
+ while (this.space < align_size + size + additional_bytes) {
+ var old_buf_size = this.bb.capacity();
+ this.bb = flatbuffers.Builder.growByteBuffer(this.bb);
+ this.space += this.bb.capacity() - old_buf_size;
+ }
+
+ this.pad(align_size);
+};
+
+/**
+ * @param {number} byte_size
+ */
+flatbuffers.Builder.prototype.pad = function(byte_size) {
+ for (var i = 0; i < byte_size; i++) {
+ this.bb.writeInt8(--this.space, 0);
+ }
+};
+
+/**
+ * @param {number} value
+ */
+flatbuffers.Builder.prototype.writeInt8 = function(value) {
+ this.bb.writeInt8(this.space -= 1, value);
+};
+
+/**
+ * @param {number} value
+ */
+flatbuffers.Builder.prototype.writeInt16 = function(value) {
+ this.bb.writeInt16(this.space -= 2, value);
+};
+
+/**
+ * @param {number} value
+ */
+flatbuffers.Builder.prototype.writeInt32 = function(value) {
+ this.bb.writeInt32(this.space -= 4, value);
+};
+
+/**
+ * @param {flatbuffers.Long} value
+ */
+flatbuffers.Builder.prototype.writeInt64 = function(value) {
+ this.bb.writeInt64(this.space -= 8, value);
+};
+
+/**
+ * @param {number} value
+ */
+flatbuffers.Builder.prototype.writeFloat32 = function(value) {
+ this.bb.writeFloat32(this.space -= 4, value);
+};
+
+/**
+ * @param {number} value
+ */
+flatbuffers.Builder.prototype.writeFloat64 = function(value) {
+ this.bb.writeFloat64(this.space -= 8, value);
+};
+/// @endcond
+
+/**
+ * Add an `int8` to the buffer, properly aligned, and grows the buffer (if necessary).
+ * @param {number} value The `int8` to add the the buffer.
+ */
+flatbuffers.Builder.prototype.addInt8 = function(value) {
+ this.prep(1, 0);
+ this.writeInt8(value);
+};
+
+/**
+ * Add an `int16` to the buffer, properly aligned, and grows the buffer (if necessary).
+ * @param {number} value The `int16` to add the the buffer.
+ */
+flatbuffers.Builder.prototype.addInt16 = function(value) {
+ this.prep(2, 0);
+ this.writeInt16(value);
+};
+
+/**
+ * Add an `int32` to the buffer, properly aligned, and grows the buffer (if necessary).
+ * @param {number} value The `int32` to add the the buffer.
+ */
+flatbuffers.Builder.prototype.addInt32 = function(value) {
+ this.prep(4, 0);
+ this.writeInt32(value);
+};
+
+/**
+ * Add an `int64` to the buffer, properly aligned, and grows the buffer (if necessary).
+ * @param {flatbuffers.Long} value The `int64` to add the the buffer.
+ */
+flatbuffers.Builder.prototype.addInt64 = function(value) {
+ this.prep(8, 0);
+ this.writeInt64(value);
+};
+
+/**
+ * Add a `float32` to the buffer, properly aligned, and grows the buffer (if necessary).
+ * @param {number} value The `float32` to add the the buffer.
+ */
+flatbuffers.Builder.prototype.addFloat32 = function(value) {
+ this.prep(4, 0);
+ this.writeFloat32(value);
+};
+
+/**
+ * Add a `float64` to the buffer, properly aligned, and grows the buffer (if necessary).
+ * @param {number} value The `float64` to add the the buffer.
+ */
+flatbuffers.Builder.prototype.addFloat64 = function(value) {
+ this.prep(8, 0);
+ this.writeFloat64(value);
+};
+
+/// @cond FLATBUFFERS_INTERNAL
+/**
+ * @param {number} voffset
+ * @param {number} value
+ * @param {number} defaultValue
+ */
+flatbuffers.Builder.prototype.addFieldInt8 = function(voffset, value, defaultValue) {
+ if (this.force_defaults || value != defaultValue) {
+ this.addInt8(value);
+ this.slot(voffset);
+ }
+};
+
+/**
+ * @param {number} voffset
+ * @param {number} value
+ * @param {number} defaultValue
+ */
+flatbuffers.Builder.prototype.addFieldInt16 = function(voffset, value, defaultValue) {
+ if (this.force_defaults || value != defaultValue) {
+ this.addInt16(value);
+ this.slot(voffset);
+ }
+};
+
+/**
+ * @param {number} voffset
+ * @param {number} value
+ * @param {number} defaultValue
+ */
+flatbuffers.Builder.prototype.addFieldInt32 = function(voffset, value, defaultValue) {
+ if (this.force_defaults || value != defaultValue) {
+ this.addInt32(value);
+ this.slot(voffset);
+ }
+};
+
+/**
+ * @param {number} voffset
+ * @param {flatbuffers.Long} value
+ * @param {flatbuffers.Long} defaultValue
+ */
+flatbuffers.Builder.prototype.addFieldInt64 = function(voffset, value, defaultValue) {
+ if (this.force_defaults || !value.equals(defaultValue)) {
+ this.addInt64(value);
+ this.slot(voffset);
+ }
+};
+
+/**
+ * @param {number} voffset
+ * @param {number} value
+ * @param {number} defaultValue
+ */
+flatbuffers.Builder.prototype.addFieldFloat32 = function(voffset, value, defaultValue) {
+ if (this.force_defaults || value != defaultValue) {
+ this.addFloat32(value);
+ this.slot(voffset);
+ }
+};
+
+/**
+ * @param {number} voffset
+ * @param {number} value
+ * @param {number} defaultValue
+ */
+flatbuffers.Builder.prototype.addFieldFloat64 = function(voffset, value, defaultValue) {
+ if (this.force_defaults || value != defaultValue) {
+ this.addFloat64(value);
+ this.slot(voffset);
+ }
+};
+
+/**
+ * @param {number} voffset
+ * @param {flatbuffers.Offset} value
+ * @param {flatbuffers.Offset} defaultValue
+ */
+flatbuffers.Builder.prototype.addFieldOffset = function(voffset, value, defaultValue) {
+ if (this.force_defaults || value != defaultValue) {
+ this.addOffset(value);
+ this.slot(voffset);
+ }
+};
+
+/**
+ * Structs are stored inline, so nothing additional is being added. `d` is always 0.
+ *
+ * @param {number} voffset
+ * @param {flatbuffers.Offset} value
+ * @param {flatbuffers.Offset} defaultValue
+ */
+flatbuffers.Builder.prototype.addFieldStruct = function(voffset, value, defaultValue) {
+ if (value != defaultValue) {
+ this.nested(value);
+ this.slot(voffset);
+ }
+};
+
+/**
+ * Structures are always stored inline, they need to be created right
+ * where they're used. You'll get this assertion failure if you
+ * created it elsewhere.
+ *
+ * @param {flatbuffers.Offset} obj The offset of the created object
+ */
+flatbuffers.Builder.prototype.nested = function(obj) {
+ if (obj != this.offset()) {
+ throw new Error('FlatBuffers: struct must be serialized inline.');
+ }
+};
+
+/**
+ * Should not be creating any other object, string or vector
+ * while an object is being constructed
+ */
+flatbuffers.Builder.prototype.notNested = function() {
+ if (this.isNested) {
+ throw new Error('FlatBuffers: object serialization must not be nested.');
+ }
+};
+
+/**
+ * Set the current vtable at `voffset` to the current location in the buffer.
+ *
+ * @param {number} voffset
+ */
+flatbuffers.Builder.prototype.slot = function(voffset) {
+ this.vtable[voffset] = this.offset();
+};
+
+/**
+ * @returns {flatbuffers.Offset} Offset relative to the end of the buffer.
+ */
+flatbuffers.Builder.prototype.offset = function() {
+ return this.bb.capacity() - this.space;
+};
+
+/**
+ * Doubles the size of the backing ByteBuffer and copies the old data towards
+ * the end of the new buffer (since we build the buffer backwards).
+ *
+ * @param {flatbuffers.ByteBuffer} bb The current buffer with the existing data
+ * @returns {!flatbuffers.ByteBuffer} A new byte buffer with the old data copied
+ * to it. The data is located at the end of the buffer.
+ *
+ * uint8Array.set() formally takes {Array<number>|ArrayBufferView}, so to pass
+ * it a uint8Array we need to suppress the type check:
+ * @suppress {checkTypes}
+ */
+flatbuffers.Builder.growByteBuffer = function(bb) {
+ var old_buf_size = bb.capacity();
+
+ // Ensure we don't grow beyond what fits in an int.
+ if (old_buf_size & 0xC0000000) {
+ throw new Error('FlatBuffers: cannot grow buffer beyond 2 gigabytes.');
+ }
+
+ var new_buf_size = old_buf_size << 1;
+ var nbb = flatbuffers.ByteBuffer.allocate(new_buf_size);
+ nbb.setPosition(new_buf_size - old_buf_size);
+ nbb.bytes().set(bb.bytes(), new_buf_size - old_buf_size);
+ return nbb;
+};
+/// @endcond
+
+/**
+ * Adds on offset, relative to where it will be written.
+ *
+ * @param {flatbuffers.Offset} offset The offset to add.
+ */
+flatbuffers.Builder.prototype.addOffset = function(offset) {
+ this.prep(flatbuffers.SIZEOF_INT, 0); // Ensure alignment is already done.
+ this.writeInt32(this.offset() - offset + flatbuffers.SIZEOF_INT);
+};
+
+/// @cond FLATBUFFERS_INTERNAL
+/**
+ * Start encoding a new object in the buffer. Users will not usually need to
+ * call this directly. The FlatBuffers compiler will generate helper methods
+ * that call this method internally.
+ *
+ * @param {number} numfields
+ */
+flatbuffers.Builder.prototype.startObject = function(numfields) {
+ this.notNested();
+ if (this.vtable == null) {
+ this.vtable = [];
+ }
+ this.vtable_in_use = numfields;
+ for (var i = 0; i < numfields; i++) {
+ this.vtable[i] = 0; // This will push additional elements as needed
+ }
+ this.isNested = true;
+ this.object_start = this.offset();
+};
+
+/**
+ * Finish off writing the object that is under construction.
+ *
+ * @returns {flatbuffers.Offset} The offset to the object inside `dataBuffer`
+ */
+flatbuffers.Builder.prototype.endObject = function() {
+ if (this.vtable == null || !this.isNested) {
+ throw new Error('FlatBuffers: endObject called without startObject');
+ }
+
+ this.addInt32(0);
+ var vtableloc = this.offset();
+
+ // Trim trailing zeroes.
+ var i = this.vtable_in_use - 1;
+ for (; i >= 0 && this.vtable[i] == 0; i--) {}
+ var trimmed_size = i + 1;
+
+ // Write out the current vtable.
+ for (; i >= 0; i--) {
+ // Offset relative to the start of the table.
+ this.addInt16(this.vtable[i] != 0 ? vtableloc - this.vtable[i] : 0);
+ }
+
+ var standard_fields = 2; // The fields below:
+ this.addInt16(vtableloc - this.object_start);
+ var len = (trimmed_size + standard_fields) * flatbuffers.SIZEOF_SHORT;
+ this.addInt16(len);
+
+ // Search for an existing vtable that matches the current one.
+ var existing_vtable = 0;
+ var vt1 = this.space;
+outer_loop:
+ for (i = 0; i < this.vtables.length; i++) {
+ var vt2 = this.bb.capacity() - this.vtables[i];
+ if (len == this.bb.readInt16(vt2)) {
+ for (var j = flatbuffers.SIZEOF_SHORT; j < len; j += flatbuffers.SIZEOF_SHORT) {
+ if (this.bb.readInt16(vt1 + j) != this.bb.readInt16(vt2 + j)) {
+ continue outer_loop;
+ }
+ }
+ existing_vtable = this.vtables[i];
+ break;
+ }
+ }
+
+ if (existing_vtable) {
+ // Found a match:
+ // Remove the current vtable.
+ this.space = this.bb.capacity() - vtableloc;
+
+ // Point table to existing vtable.
+ this.bb.writeInt32(this.space, existing_vtable - vtableloc);
+ } else {
+ // No match:
+ // Add the location of the current vtable to the list of vtables.
+ this.vtables.push(this.offset());
+
+ // Point table to current vtable.
+ this.bb.writeInt32(this.bb.capacity() - vtableloc, this.offset() - vtableloc);
+ }
+
+ this.isNested = false;
+ return vtableloc;
+};
+/// @endcond
+
+/**
+ * Finalize a buffer, poiting to the given `root_table`.
+ *
+ * @param {flatbuffers.Offset} root_table
+ * @param {string=} opt_file_identifier
+ * @param {boolean=} opt_size_prefix
+ */
+flatbuffers.Builder.prototype.finish = function(root_table, opt_file_identifier, opt_size_prefix) {
+ var size_prefix = opt_size_prefix ? flatbuffers.SIZE_PREFIX_LENGTH : 0;
+ if (opt_file_identifier) {
+ var file_identifier = opt_file_identifier;
+ this.prep(this.minalign, flatbuffers.SIZEOF_INT +
+ flatbuffers.FILE_IDENTIFIER_LENGTH + size_prefix);
+ if (file_identifier.length != flatbuffers.FILE_IDENTIFIER_LENGTH) {
+ throw new Error('FlatBuffers: file identifier must be length ' +
+ flatbuffers.FILE_IDENTIFIER_LENGTH);
+ }
+ for (var i = flatbuffers.FILE_IDENTIFIER_LENGTH - 1; i >= 0; i--) {
+ this.writeInt8(file_identifier.charCodeAt(i));
+ }
+ }
+ this.prep(this.minalign, flatbuffers.SIZEOF_INT + size_prefix);
+ this.addOffset(root_table);
+ if (size_prefix) {
+ this.addInt32(this.bb.capacity() - this.space);
+ }
+ this.bb.setPosition(this.space);
+};
+
+/**
+ * Finalize a size prefixed buffer, pointing to the given `root_table`.
+ *
+ * @param {flatbuffers.Offset} root_table
+ * @param {string=} opt_file_identifier
+ */
+flatbuffers.Builder.prototype.finishSizePrefixed = function (root_table, opt_file_identifier) {
+ this.finish(root_table, opt_file_identifier, true);
+};
+
+/// @cond FLATBUFFERS_INTERNAL
+/**
+ * This checks a required field has been set in a given table that has
+ * just been constructed.
+ *
+ * @param {flatbuffers.Offset} table
+ * @param {number} field
+ */
+flatbuffers.Builder.prototype.requiredField = function(table, field) {
+ var table_start = this.bb.capacity() - table;
+ var vtable_start = table_start - this.bb.readInt32(table_start);
+ var ok = this.bb.readInt16(vtable_start + field) != 0;
+
+ // If this fails, the caller will show what field needs to be set.
+ if (!ok) {
+ throw new Error('FlatBuffers: field ' + field + ' must be set');
+ }
+};
+
+/**
+ * Start a new array/vector of objects. Users usually will not call
+ * this directly. The FlatBuffers compiler will create a start/end
+ * method for vector types in generated code.
+ *
+ * @param {number} elem_size The size of each element in the array
+ * @param {number} num_elems The number of elements in the array
+ * @param {number} alignment The alignment of the array
+ */
+flatbuffers.Builder.prototype.startVector = function(elem_size, num_elems, alignment) {
+ this.notNested();
+ this.vector_num_elems = num_elems;
+ this.prep(flatbuffers.SIZEOF_INT, elem_size * num_elems);
+ this.prep(alignment, elem_size * num_elems); // Just in case alignment > int.
+};
+
+/**
+ * Finish off the creation of an array and all its elements. The array must be
+ * created with `startVector`.
+ *
+ * @returns {flatbuffers.Offset} The offset at which the newly created array
+ * starts.
+ */
+flatbuffers.Builder.prototype.endVector = function() {
+ this.writeInt32(this.vector_num_elems);
+ return this.offset();
+};
+/// @endcond
+
+/**
+ * Encode the string `s` in the buffer using UTF-8. If a Uint8Array is passed
+ * instead of a string, it is assumed to contain valid UTF-8 encoded data.
+ *
+ * @param {string|Uint8Array} s The string to encode
+ * @return {flatbuffers.Offset} The offset in the buffer where the encoded string starts
+ */
+flatbuffers.Builder.prototype.createString = function(s) {
+ if (s instanceof Uint8Array) {
+ var utf8 = s;
+ } else {
+ var utf8 = [];
+ var i = 0;
+
+ while (i < s.length) {
+ var codePoint;
+
+ // Decode UTF-16
+ var a = s.charCodeAt(i++);
+ if (a < 0xD800 || a >= 0xDC00) {
+ codePoint = a;
+ } else {
+ var b = s.charCodeAt(i++);
+ codePoint = (a << 10) + b + (0x10000 - (0xD800 << 10) - 0xDC00);
+ }
+
+ // Encode UTF-8
+ if (codePoint < 0x80) {
+ utf8.push(codePoint);
+ } else {
+ if (codePoint < 0x800) {
+ utf8.push(((codePoint >> 6) & 0x1F) | 0xC0);
+ } else {
+ if (codePoint < 0x10000) {
+ utf8.push(((codePoint >> 12) & 0x0F) | 0xE0);
+ } else {
+ utf8.push(
+ ((codePoint >> 18) & 0x07) | 0xF0,
+ ((codePoint >> 12) & 0x3F) | 0x80);
+ }
+ utf8.push(((codePoint >> 6) & 0x3F) | 0x80);
+ }
+ utf8.push((codePoint & 0x3F) | 0x80);
+ }
+ }
+ }
+
+ this.addInt8(0);
+ this.startVector(1, utf8.length, 1);
+ this.bb.setPosition(this.space -= utf8.length);
+ for (var i = 0, offset = this.space, bytes = this.bb.bytes(); i < utf8.length; i++) {
+ bytes[offset++] = utf8[i];
+ }
+ return this.endVector();
+};
+
+/**
+ * A helper function to avoid generated code depending on this file directly.
+ *
+ * @param {number} low
+ * @param {number} high
+ * @returns {!flatbuffers.Long}
+ */
+flatbuffers.Builder.prototype.createLong = function(low, high) {
+ return flatbuffers.Long.create(low, high);
+};
+////////////////////////////////////////////////////////////////////////////////
+/// @cond FLATBUFFERS_INTERNAL
+/**
+ * Create a new ByteBuffer with a given array of bytes (`Uint8Array`).
+ *
+ * @constructor
+ * @param {Uint8Array} bytes
+ */
+flatbuffers.ByteBuffer = function(bytes) {
+ /**
+ * @type {Uint8Array}
+ * @private
+ */
+ this.bytes_ = bytes;
+
+ /**
+ * @type {number}
+ * @private
+ */
+ this.position_ = 0;
+};
+
+/**
+ * Create and allocate a new ByteBuffer with a given size.
+ *
+ * @param {number} byte_size
+ * @returns {!flatbuffers.ByteBuffer}
+ */
+flatbuffers.ByteBuffer.allocate = function(byte_size) {
+ return new flatbuffers.ByteBuffer(new Uint8Array(byte_size));
+};
+
+flatbuffers.ByteBuffer.prototype.clear = function() {
+ this.position_ = 0;
+};
+
+/**
+ * Get the underlying `Uint8Array`.
+ *
+ * @returns {Uint8Array}
+ */
+flatbuffers.ByteBuffer.prototype.bytes = function() {
+ return this.bytes_;
+};
+
+/**
+ * Get the buffer's position.
+ *
+ * @returns {number}
+ */
+flatbuffers.ByteBuffer.prototype.position = function() {
+ return this.position_;
+};
+
+/**
+ * Set the buffer's position.
+ *
+ * @param {number} position
+ */
+flatbuffers.ByteBuffer.prototype.setPosition = function(position) {
+ this.position_ = position;
+};
+
+/**
+ * Get the buffer's capacity.
+ *
+ * @returns {number}
+ */
+flatbuffers.ByteBuffer.prototype.capacity = function() {
+ return this.bytes_.length;
+};
+
+/**
+ * @param {number} offset
+ * @returns {number}
+ */
+flatbuffers.ByteBuffer.prototype.readInt8 = function(offset) {
+ return this.readUint8(offset) << 24 >> 24;
+};
+
+/**
+ * @param {number} offset
+ * @returns {number}
+ */
+flatbuffers.ByteBuffer.prototype.readUint8 = function(offset) {
+ return this.bytes_[offset];
+};
+
+/**
+ * @param {number} offset
+ * @returns {number}
+ */
+flatbuffers.ByteBuffer.prototype.readInt16 = function(offset) {
+ return this.readUint16(offset) << 16 >> 16;
+};
+
+/**
+ * @param {number} offset
+ * @returns {number}
+ */
+flatbuffers.ByteBuffer.prototype.readUint16 = function(offset) {
+ return this.bytes_[offset] | this.bytes_[offset + 1] << 8;
+};
+
+/**
+ * @param {number} offset
+ * @returns {number}
+ */
+flatbuffers.ByteBuffer.prototype.readInt32 = function(offset) {
+ return this.bytes_[offset] | this.bytes_[offset + 1] << 8 | this.bytes_[offset + 2] << 16 | this.bytes_[offset + 3] << 24;
+};
+
+/**
+ * @param {number} offset
+ * @returns {number}
+ */
+flatbuffers.ByteBuffer.prototype.readUint32 = function(offset) {
+ return this.readInt32(offset) >>> 0;
+};
+
+/**
+ * @param {number} offset
+ * @returns {!flatbuffers.Long}
+ */
+flatbuffers.ByteBuffer.prototype.readInt64 = function(offset) {
+ return new flatbuffers.Long(this.readInt32(offset), this.readInt32(offset + 4));
+};
+
+/**
+ * @param {number} offset
+ * @returns {!flatbuffers.Long}
+ */
+flatbuffers.ByteBuffer.prototype.readUint64 = function(offset) {
+ return new flatbuffers.Long(this.readUint32(offset), this.readUint32(offset + 4));
+};
+
+/**
+ * @param {number} offset
+ * @returns {number}
+ */
+flatbuffers.ByteBuffer.prototype.readFloat32 = function(offset) {
+ flatbuffers.int32[0] = this.readInt32(offset);
+ return flatbuffers.float32[0];
+};
+
+/**
+ * @param {number} offset
+ * @returns {number}
+ */
+flatbuffers.ByteBuffer.prototype.readFloat64 = function(offset) {
+ flatbuffers.int32[flatbuffers.isLittleEndian ? 0 : 1] = this.readInt32(offset);
+ flatbuffers.int32[flatbuffers.isLittleEndian ? 1 : 0] = this.readInt32(offset + 4);
+ return flatbuffers.float64[0];
+};
+
+/**
+ * @param {number} offset
+ * @param {number|boolean} value
+ */
+flatbuffers.ByteBuffer.prototype.writeInt8 = function(offset, value) {
+ this.bytes_[offset] = /** @type {number} */(value);
+};
+
+/**
+ * @param {number} offset
+ * @param {number} value
+ */
+flatbuffers.ByteBuffer.prototype.writeUint8 = function(offset, value) {
+ this.bytes_[offset] = value;
+};
+
+/**
+ * @param {number} offset
+ * @param {number} value
+ */
+flatbuffers.ByteBuffer.prototype.writeInt16 = function(offset, value) {
+ this.bytes_[offset] = value;
+ this.bytes_[offset + 1] = value >> 8;
+};
+
+/**
+ * @param {number} offset
+ * @param {number} value
+ */
+flatbuffers.ByteBuffer.prototype.writeUint16 = function(offset, value) {
+ this.bytes_[offset] = value;
+ this.bytes_[offset + 1] = value >> 8;
+};
+
+/**
+ * @param {number} offset
+ * @param {number} value
+ */
+flatbuffers.ByteBuffer.prototype.writeInt32 = function(offset, value) {
+ this.bytes_[offset] = value;
+ this.bytes_[offset + 1] = value >> 8;
+ this.bytes_[offset + 2] = value >> 16;
+ this.bytes_[offset + 3] = value >> 24;
+};
+
+/**
+ * @param {number} offset
+ * @param {number} value
+ */
+flatbuffers.ByteBuffer.prototype.writeUint32 = function(offset, value) {
+ this.bytes_[offset] = value;
+ this.bytes_[offset + 1] = value >> 8;
+ this.bytes_[offset + 2] = value >> 16;
+ this.bytes_[offset + 3] = value >> 24;
+};
+
+/**
+ * @param {number} offset
+ * @param {flatbuffers.Long} value
+ */
+flatbuffers.ByteBuffer.prototype.writeInt64 = function(offset, value) {
+ this.writeInt32(offset, value.low);
+ this.writeInt32(offset + 4, value.high);
+};
+
+/**
+ * @param {number} offset
+ * @param {flatbuffers.Long} value
+ */
+flatbuffers.ByteBuffer.prototype.writeUint64 = function(offset, value) {
+ this.writeUint32(offset, value.low);
+ this.writeUint32(offset + 4, value.high);
+};
+
+/**
+ * @param {number} offset
+ * @param {number} value
+ */
+flatbuffers.ByteBuffer.prototype.writeFloat32 = function(offset, value) {
+ flatbuffers.float32[0] = value;
+ this.writeInt32(offset, flatbuffers.int32[0]);
+};
+
+/**
+ * @param {number} offset
+ * @param {number} value
+ */
+flatbuffers.ByteBuffer.prototype.writeFloat64 = function(offset, value) {
+ flatbuffers.float64[0] = value;
+ this.writeInt32(offset, flatbuffers.int32[flatbuffers.isLittleEndian ? 0 : 1]);
+ this.writeInt32(offset + 4, flatbuffers.int32[flatbuffers.isLittleEndian ? 1 : 0]);
+};
+
+/**
+ * Return the file identifier. Behavior is undefined for FlatBuffers whose
+ * schema does not include a file_identifier (likely points at padding or the
+ * start of a the root vtable).
+ * @returns {string}
+ */
+flatbuffers.ByteBuffer.prototype.getBufferIdentifier = function() {
+ if (this.bytes_.length < this.position_ + flatbuffers.SIZEOF_INT +
+ flatbuffers.FILE_IDENTIFIER_LENGTH) {
+ throw new Error(
+ 'FlatBuffers: ByteBuffer is too short to contain an identifier.');
+ }
+ var result = "";
+ for (var i = 0; i < flatbuffers.FILE_IDENTIFIER_LENGTH; i++) {
+ result += String.fromCharCode(
+ this.readInt8(this.position_ + flatbuffers.SIZEOF_INT + i));
+ }
+ return result;
+};
+
+/**
+ * Look up a field in the vtable, return an offset into the object, or 0 if the
+ * field is not present.
+ *
+ * @param {number} bb_pos
+ * @param {number} vtable_offset
+ * @returns {number}
+ */
+flatbuffers.ByteBuffer.prototype.__offset = function(bb_pos, vtable_offset) {
+ var vtable = bb_pos - this.readInt32(bb_pos);
+ return vtable_offset < this.readInt16(vtable) ? this.readInt16(vtable + vtable_offset) : 0;
+};
+
+/**
+ * Initialize any Table-derived type to point to the union at the given offset.
+ *
+ * @param {flatbuffers.Table} t
+ * @param {number} offset
+ * @returns {flatbuffers.Table}
+ */
+flatbuffers.ByteBuffer.prototype.__union = function(t, offset) {
+ t.bb_pos = offset + this.readInt32(offset);
+ t.bb = this;
+ return t;
+};
+
+/**
+ * Create a JavaScript string from UTF-8 data stored inside the FlatBuffer.
+ * This allocates a new string and converts to wide chars upon each access.
+ *
+ * To avoid the conversion to UTF-16, pass flatbuffers.Encoding.UTF8_BYTES as
+ * the "optionalEncoding" argument. This is useful for avoiding conversion to
+ * and from UTF-16 when the data will just be packaged back up in another
+ * FlatBuffer later on.
+ *
+ * @param {number} offset
+ * @param {flatbuffers.Encoding=} opt_encoding Defaults to UTF16_STRING
+ * @returns {string|!Uint8Array}
+ */
+flatbuffers.ByteBuffer.prototype.__string = function(offset, opt_encoding) {
+ offset += this.readInt32(offset);
+
+ var length = this.readInt32(offset);
+ var result = '';
+ var i = 0;
+
+ offset += flatbuffers.SIZEOF_INT;
+
+ if (opt_encoding === flatbuffers.Encoding.UTF8_BYTES) {
+ return this.bytes_.subarray(offset, offset + length);
+ }
+
+ while (i < length) {
+ var codePoint;
+
+ // Decode UTF-8
+ var a = this.readUint8(offset + i++);
+ if (a < 0xC0) {
+ codePoint = a;
+ } else {
+ var b = this.readUint8(offset + i++);
+ if (a < 0xE0) {
+ codePoint =
+ ((a & 0x1F) << 6) |
+ (b & 0x3F);
+ } else {
+ var c = this.readUint8(offset + i++);
+ if (a < 0xF0) {
+ codePoint =
+ ((a & 0x0F) << 12) |
+ ((b & 0x3F) << 6) |
+ (c & 0x3F);
+ } else {
+ var d = this.readUint8(offset + i++);
+ codePoint =
+ ((a & 0x07) << 18) |
+ ((b & 0x3F) << 12) |
+ ((c & 0x3F) << 6) |
+ (d & 0x3F);
+ }
+ }
+ }
+
+ // Encode UTF-16
+ if (codePoint < 0x10000) {
+ result += String.fromCharCode(codePoint);
+ } else {
+ codePoint -= 0x10000;
+ result += String.fromCharCode(
+ (codePoint >> 10) + 0xD800,
+ (codePoint & ((1 << 10) - 1)) + 0xDC00);
+ }
+ }
+
+ return result;
+};
+
+/**
+ * Retrieve the relative offset stored at "offset"
+ * @param {number} offset
+ * @returns {number}
+ */
+flatbuffers.ByteBuffer.prototype.__indirect = function(offset) {
+ return offset + this.readInt32(offset);
+};
+
+/**
+ * Get the start of data of a vector whose offset is stored at "offset" in this object.
+ *
+ * @param {number} offset
+ * @returns {number}
+ */
+flatbuffers.ByteBuffer.prototype.__vector = function(offset) {
+ return offset + this.readInt32(offset) + flatbuffers.SIZEOF_INT; // data starts after the length
+};
+
+/**
+ * Get the length of a vector whose offset is stored at "offset" in this object.
+ *
+ * @param {number} offset
+ * @returns {number}
+ */
+flatbuffers.ByteBuffer.prototype.__vector_len = function(offset) {
+ return this.readInt32(offset + this.readInt32(offset));
+};
+
+/**
+ * @param {string} ident
+ * @returns {boolean}
+ */
+flatbuffers.ByteBuffer.prototype.__has_identifier = function(ident) {
+ if (ident.length != flatbuffers.FILE_IDENTIFIER_LENGTH) {
+ throw new Error('FlatBuffers: file identifier must be length ' +
+ flatbuffers.FILE_IDENTIFIER_LENGTH);
+ }
+ for (var i = 0; i < flatbuffers.FILE_IDENTIFIER_LENGTH; i++) {
+ if (ident.charCodeAt(i) != this.readInt8(this.position_ + flatbuffers.SIZEOF_INT + i)) {
+ return false;
+ }
+ }
+ return true;
+};
+
+/**
+ * A helper function to avoid generated code depending on this file directly.
+ *
+ * @param {number} low
+ * @param {number} high
+ * @returns {!flatbuffers.Long}
+ */
+flatbuffers.ByteBuffer.prototype.createLong = function(low, high) {
+ return flatbuffers.Long.create(low, high);
+};
+
+// Exports for Node.js and RequireJS
+
+
+/// @endcond
+/// @}
+
+
+/***/ })
+
+/******/ });
+/************************************************************************/
+/******/ // The module cache
+/******/ var __webpack_module_cache__ = {};
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/ // Check if module is in cache
+/******/ var cachedModule = __webpack_module_cache__[moduleId];
+/******/ if (cachedModule !== undefined) {
+/******/ return cachedModule.exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = __webpack_module_cache__[moduleId] = {
+/******/ // no module.id needed
+/******/ // no module.loaded needed
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/************************************************************************/
+/******/ /* webpack/runtime/compat get default export */
+/******/ (() => {
+/******/ // getDefaultExport function for compatibility with non-harmony modules
+/******/ __webpack_require__.n = (module) => {
+/******/ var getter = module && module.__esModule ?
+/******/ () => (module['default']) :
+/******/ () => (module);
+/******/ __webpack_require__.d(getter, { a: getter });
+/******/ return getter;
+/******/ };
+/******/ })();
+/******/
+/******/ /* webpack/runtime/define property getters */
+/******/ (() => {
+/******/ // define getter functions for harmony exports
+/******/ __webpack_require__.d = (exports, definition) => {
+/******/ for(var key in definition) {
+/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
+/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
+/******/ }
+/******/ }
+/******/ };
+/******/ })();
+/******/
+/******/ /* webpack/runtime/global */
+/******/ (() => {
+/******/ __webpack_require__.g = (function() {
+/******/ if (typeof globalThis === 'object') return globalThis;
+/******/ try {
+/******/ return this || new Function('return this')();
+/******/ } catch (e) {
+/******/ if (typeof window === 'object') return window;
+/******/ }
+/******/ })();
+/******/ })();
+/******/
+/******/ /* webpack/runtime/hasOwnProperty shorthand */
+/******/ (() => {
+/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
+/******/ })();
+/******/
+/******/ /* webpack/runtime/make namespace object */
+/******/ (() => {
+/******/ // define __esModule on exports
+/******/ __webpack_require__.r = (exports) => {
+/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
+/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
+/******/ }
+/******/ Object.defineProperty(exports, '__esModule', { value: true });
+/******/ };
+/******/ })();
+/******/
+/************************************************************************/
+/******/
+/******/ // startup
+/******/ // Load entry module and return exports
+/******/ // This entry module is referenced by other modules so it can't be inlined
+/******/ var __webpack_exports__ = __webpack_require__("./lib/index.ts");
+/******/
+/******/ return __webpack_exports__;
+/******/ })()
+;
+});