/*!
 * ONNX Runtime Web v1.18.0
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
"use strict";
var ort = (() => {
  var __create = Object.create;
  var __defProp = Object.defineProperty;
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  var __getOwnPropNames = Object.getOwnPropertyNames;
  var __getProtoOf = Object.getPrototypeOf;
  var __hasOwnProp = Object.prototype.hasOwnProperty;
  var __esm = (fn, res) => function __init() {
    return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
  };
  var __commonJS = (cb, mod2) => function __require() {
    return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
  };
  var __export = (target, all) => {
    for (var name2 in all)
      __defProp(target, name2, { get: all[name2], enumerable: true });
  };
  var __copyProps = (to, from, except, desc) => {
    if (from && typeof from === "object" || typeof from === "function") {
      for (let key of __getOwnPropNames(from))
        if (!__hasOwnProp.call(to, key) && key !== except)
          __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
    }
    return to;
  };
  var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
    // If the importer is in node compatibility mode or this is not an ESM
    // file that has been converted to a CommonJS file using a Babel-
    // compatible transform (i.e. "__esModule" has not been set), then set
    // "default" to the CommonJS "module.exports" for node compatibility.
    isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
    mod2
  ));
  var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);

  // common/dist/esm/backend-impl.js
  var backends, backendsSortedByPriority, registerBackend, tryResolveAndInitializeBackend, resolveBackendAndExecutionProviders;
  var init_backend_impl = __esm({
    "common/dist/esm/backend-impl.js"() {
      "use strict";
      backends = /* @__PURE__ */ new Map();
      backendsSortedByPriority = [];
      registerBackend = (name2, backend2, priority) => {
        if (backend2 && typeof backend2.init === "function" && typeof backend2.createInferenceSessionHandler === "function") {
          const currentBackend = backends.get(name2);
          if (currentBackend === void 0) {
            backends.set(name2, { backend: backend2, priority });
          } else if (currentBackend.priority > priority) {
            return;
          } else if (currentBackend.priority === priority) {
            if (currentBackend.backend !== backend2) {
              throw new Error(`cannot register backend "${name2}" using priority ${priority}`);
            }
          }
          if (priority >= 0) {
            const i = backendsSortedByPriority.indexOf(name2);
            if (i !== -1) {
              backendsSortedByPriority.splice(i, 1);
            }
            for (let i2 = 0; i2 < backendsSortedByPriority.length; i2++) {
              if (backends.get(backendsSortedByPriority[i2]).priority <= priority) {
                backendsSortedByPriority.splice(i2, 0, name2);
                return;
              }
            }
            backendsSortedByPriority.push(name2);
          }
          return;
        }
        throw new TypeError("not a valid backend");
      };
      tryResolveAndInitializeBackend = async (backendName) => {
        const backendInfo = backends.get(backendName);
        if (!backendInfo) {
          return "backend not found.";
        }
        if (backendInfo.initialized) {
          return backendInfo.backend;
        } else if (backendInfo.aborted) {
          return backendInfo.error;
        } else {
          const isInitializing = !!backendInfo.initPromise;
          try {
            if (!isInitializing) {
              backendInfo.initPromise = backendInfo.backend.init(backendName);
            }
            await backendInfo.initPromise;
            backendInfo.initialized = true;
            return backendInfo.backend;
          } catch (e) {
            if (!isInitializing) {
              backendInfo.error = `${e}`;
              backendInfo.aborted = true;
            }
            return backendInfo.error;
          } finally {
            delete backendInfo.initPromise;
          }
        }
      };
      resolveBackendAndExecutionProviders = async (options) => {
        const eps = options.executionProviders || [];
        const backendHints = eps.map((i) => typeof i === "string" ? i : i.name);
        const backendNames = backendHints.length === 0 ? backendsSortedByPriority : backendHints;
        let backend2;
        const errors = [];
        const availableBackendNames = /* @__PURE__ */ new Set();
        for (const backendName of backendNames) {
          const resolveResult = await tryResolveAndInitializeBackend(backendName);
          if (typeof resolveResult === "string") {
            errors.push({ name: backendName, err: resolveResult });
          } else {
            if (!backend2) {
              backend2 = resolveResult;
            }
            if (backend2 === resolveResult) {
              availableBackendNames.add(backendName);
            }
          }
        }
        if (!backend2) {
          throw new Error(`no available backend found. ERR: ${errors.map((e) => `[${e.name}] ${e.err}`).join(", ")}`);
        }
        for (const { name: name2, err } of errors) {
          if (backendHints.includes(name2)) {
            console.warn(`removing requested execution provider "${name2}" from session options because it is not available: ${err}`);
          }
        }
        const filteredEps = eps.filter((i) => availableBackendNames.has(typeof i === "string" ? i : i.name));
        return [
          backend2,
          new Proxy(options, {
            get: (target, prop) => {
              if (prop === "executionProviders") {
                return filteredEps;
              }
              return Reflect.get(target, prop);
            }
          })
        ];
      };
    }
  });

  // common/dist/esm/backend.js
  var init_backend = __esm({
    "common/dist/esm/backend.js"() {
      "use strict";
      init_backend_impl();
    }
  });

  // common/dist/esm/version.js
  var version;
  var init_version = __esm({
    "common/dist/esm/version.js"() {
      "use strict";
      version = "1.18.0";
    }
  });

  // common/dist/esm/env-impl.js
  var logLevelValue, env;
  var init_env_impl = __esm({
    "common/dist/esm/env-impl.js"() {
      "use strict";
      init_version();
      logLevelValue = "warning";
      env = {
        wasm: {},
        webgl: {},
        webgpu: {},
        versions: { common: version },
        set logLevel(value) {
          if (value === void 0) {
            return;
          }
          if (typeof value !== "string" || ["verbose", "info", "warning", "error", "fatal"].indexOf(value) === -1) {
            throw new Error(`Unsupported logging level: ${value}`);
          }
          logLevelValue = value;
        },
        get logLevel() {
          return logLevelValue;
        }
      };
      Object.defineProperty(env, "logLevel", { enumerable: true });
    }
  });

  // common/dist/esm/env.js
  var env2;
  var init_env = __esm({
    "common/dist/esm/env.js"() {
      "use strict";
      init_env_impl();
      env2 = env;
    }
  });

  // common/dist/esm/tensor-conversion-impl.js
  var tensorToDataURL, tensorToImageData;
  var init_tensor_conversion_impl = __esm({
    "common/dist/esm/tensor-conversion-impl.js"() {
      "use strict";
      tensorToDataURL = (tensor, options) => {
        const canvas = typeof document !== "undefined" ? document.createElement("canvas") : new OffscreenCanvas(1, 1);
        canvas.width = tensor.dims[3];
        canvas.height = tensor.dims[2];
        const pixels2DContext = canvas.getContext("2d");
        if (pixels2DContext != null) {
          let width;
          let height;
          if (options?.tensorLayout !== void 0 && options.tensorLayout === "NHWC") {
            width = tensor.dims[2];
            height = tensor.dims[3];
          } else {
            width = tensor.dims[3];
            height = tensor.dims[2];
          }
          const inputformat = options?.format !== void 0 ? options.format : "RGB";
          const norm = options?.norm;
          let normMean;
          let normBias;
          if (norm === void 0 || norm.mean === void 0) {
            normMean = [255, 255, 255, 255];
          } else {
            if (typeof norm.mean === "number") {
              normMean = [norm.mean, norm.mean, norm.mean, norm.mean];
            } else {
              normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 0];
              if (norm.mean[3] !== void 0) {
                normMean[3] = norm.mean[3];
              }
            }
          }
          if (norm === void 0 || norm.bias === void 0) {
            normBias = [0, 0, 0, 0];
          } else {
            if (typeof norm.bias === "number") {
              normBias = [norm.bias, norm.bias, norm.bias, norm.bias];
            } else {
              normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];
              if (norm.bias[3] !== void 0) {
                normBias[3] = norm.bias[3];
              }
            }
          }
          const stride = height * width;
          let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;
          if (inputformat === "RGBA") {
            rTensorPointer = 0;
            gTensorPointer = stride;
            bTensorPointer = stride * 2;
            aTensorPointer = stride * 3;
          } else if (inputformat === "RGB") {
            rTensorPointer = 0;
            gTensorPointer = stride;
            bTensorPointer = stride * 2;
          } else if (inputformat === "RBG") {
            rTensorPointer = 0;
            bTensorPointer = stride;
            gTensorPointer = stride * 2;
          }
          for (let i = 0; i < height; i++) {
            for (let j = 0; j < width; j++) {
              const R = (tensor.data[rTensorPointer++] - normBias[0]) * normMean[0];
              const G = (tensor.data[gTensorPointer++] - normBias[1]) * normMean[1];
              const B = (tensor.data[bTensorPointer++] - normBias[2]) * normMean[2];
              const A = aTensorPointer === -1 ? 255 : (tensor.data[aTensorPointer++] - normBias[3]) * normMean[3];
              pixels2DContext.fillStyle = "rgba(" + R + "," + G + "," + B + "," + A + ")";
              pixels2DContext.fillRect(j, i, 1, 1);
            }
          }
          if ("toDataURL" in canvas) {
            return canvas.toDataURL();
          } else {
            throw new Error("toDataURL is not supported");
          }
        } else {
          throw new Error("Can not access image data");
        }
      };
      tensorToImageData = (tensor, options) => {
        const pixels2DContext = typeof document !== "undefined" ? document.createElement("canvas").getContext("2d") : new OffscreenCanvas(1, 1).getContext("2d");
        let image;
        if (pixels2DContext != null) {
          let width;
          let height;
          let channels;
          if (options?.tensorLayout !== void 0 && options.tensorLayout === "NHWC") {
            width = tensor.dims[2];
            height = tensor.dims[1];
            channels = tensor.dims[3];
          } else {
            width = tensor.dims[3];
            height = tensor.dims[2];
            channels = tensor.dims[1];
          }
          const inputformat = options !== void 0 ? options.format !== void 0 ? options.format : "RGB" : "RGB";
          const norm = options?.norm;
          let normMean;
          let normBias;
          if (norm === void 0 || norm.mean === void 0) {
            normMean = [255, 255, 255, 255];
          } else {
            if (typeof norm.mean === "number") {
              normMean = [norm.mean, norm.mean, norm.mean, norm.mean];
            } else {
              normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 255];
              if (norm.mean[3] !== void 0) {
                normMean[3] = norm.mean[3];
              }
            }
          }
          if (norm === void 0 || norm.bias === void 0) {
            normBias = [0, 0, 0, 0];
          } else {
            if (typeof norm.bias === "number") {
              normBias = [norm.bias, norm.bias, norm.bias, norm.bias];
            } else {
              normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];
              if (norm.bias[3] !== void 0) {
                normBias[3] = norm.bias[3];
              }
            }
          }
          const stride = height * width;
          if (options !== void 0) {
            if (options.format !== void 0 && (channels === 4 && options.format !== "RGBA") || channels === 3 && (options.format !== "RGB" && options.format !== "BGR")) {
              throw new Error("Tensor format doesn't match input tensor dims");
            }
          }
          const step = 4;
          let rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;
          let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;
          if (inputformat === "RGBA") {
            rTensorPointer = 0;
            gTensorPointer = stride;
            bTensorPointer = stride * 2;
            aTensorPointer = stride * 3;
          } else if (inputformat === "RGB") {
            rTensorPointer = 0;
            gTensorPointer = stride;
            bTensorPointer = stride * 2;
          } else if (inputformat === "RBG") {
            rTensorPointer = 0;
            bTensorPointer = stride;
            gTensorPointer = stride * 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] = (tensor.data[rTensorPointer++] - normBias[0]) * normMean[0];
            image.data[gImagePointer] = (tensor.data[gTensorPointer++] - normBias[1]) * normMean[1];
            image.data[bImagePointer] = (tensor.data[bTensorPointer++] - normBias[2]) * normMean[2];
            image.data[aImagePointer] = aTensorPointer === -1 ? 255 : (tensor.data[aTensorPointer++] - normBias[3]) * normMean[3];
          }
        } else {
          throw new Error("Can not access image data");
        }
        return image;
      };
    }
  });

  // common/dist/esm/tensor-factory-impl.js
  var bufferToTensor, tensorFromImage, tensorFromTexture, tensorFromGpuBuffer, tensorFromPinnedBuffer;
  var init_tensor_factory_impl = __esm({
    "common/dist/esm/tensor-factory-impl.js"() {
      "use strict";
      init_tensor_impl();
      bufferToTensor = (buffer, options) => {
        if (buffer === void 0) {
          throw new Error("Image buffer must be defined");
        }
        if (options.height === void 0 || options.width === void 0) {
          throw new Error("Image height and width must be defined");
        }
        if (options.tensorLayout === "NHWC") {
          throw new Error("NHWC Tensor layout is not supported yet");
        }
        const { height, width } = options;
        const norm = options.norm ?? { mean: 255, bias: 0 };
        let normMean;
        let normBias;
        if (typeof norm.mean === "number") {
          normMean = [norm.mean, norm.mean, norm.mean, norm.mean];
        } else {
          normMean = [norm.mean[0], norm.mean[1], norm.mean[2], norm.mean[3] ?? 255];
        }
        if (typeof norm.bias === "number") {
          normBias = [norm.bias, norm.bias, norm.bias, norm.bias];
        } else {
          normBias = [norm.bias[0], norm.bias[1], norm.bias[2], norm.bias[3] ?? 0];
        }
        const inputformat = options.format !== void 0 ? options.format : "RGBA";
        const outputformat = options.tensorFormat !== void 0 ? options.tensorFormat !== void 0 ? options.tensorFormat : "RGB" : "RGB";
        const stride = height * width;
        const float32Data = outputformat === "RGBA" ? new Float32Array(stride * 4) : new Float32Array(stride * 3);
        let step = 4, rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;
        let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;
        if (inputformat === "RGB") {
          step = 3;
          rImagePointer = 0;
          gImagePointer = 1;
          bImagePointer = 2;
          aImagePointer = -1;
        }
        if (outputformat === "RGBA") {
          aTensorPointer = stride * 3;
        } else if (outputformat === "RBG") {
          rTensorPointer = 0;
          bTensorPointer = stride;
          gTensorPointer = stride * 2;
        } else if (outputformat === "BGR") {
          bTensorPointer = 0;
          gTensorPointer = stride;
          rTensorPointer = stride * 2;
        }
        for (let i = 0; i < stride; i++, rImagePointer += step, bImagePointer += step, gImagePointer += step, aImagePointer += step) {
          float32Data[rTensorPointer++] = (buffer[rImagePointer] + normBias[0]) / normMean[0];
          float32Data[gTensorPointer++] = (buffer[gImagePointer] + normBias[1]) / normMean[1];
          float32Data[bTensorPointer++] = (buffer[bImagePointer] + normBias[2]) / normMean[2];
          if (aTensorPointer !== -1 && aImagePointer !== -1) {
            float32Data[aTensorPointer++] = (buffer[aImagePointer] + normBias[3]) / normMean[3];
          }
        }
        const outputTensor = outputformat === "RGBA" ? new Tensor("float32", float32Data, [1, 4, height, width]) : new Tensor("float32", float32Data, [1, 3, height, width]);
        return outputTensor;
      };
      tensorFromImage = async (image, options) => {
        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 isString = typeof image === "string";
        let data;
        let bufferToTensorOptions = options ?? {};
        const createCanvas2 = () => {
          if (typeof document !== "undefined") {
            return document.createElement("canvas");
          } else if (typeof OffscreenCanvas !== "undefined") {
            return new OffscreenCanvas(1, 1);
          } else {
            throw new Error("Canvas is not supported");
          }
        };
        const createCanvasContext = (canvas) => {
          if (canvas instanceof HTMLCanvasElement) {
            return canvas.getContext("2d");
          } else if (canvas instanceof OffscreenCanvas) {
            return canvas.getContext("2d");
          } else {
            return null;
          }
        };
        if (isHTMLImageEle) {
          const canvas = createCanvas2();
          canvas.width = image.width;
          canvas.height = image.height;
          const pixels2DContext = createCanvasContext(canvas);
          if (pixels2DContext != null) {
            let height = image.height;
            let width = image.width;
            if (options !== void 0 && options.resizedHeight !== void 0 && options.resizedWidth !== void 0) {
              height = options.resizedHeight;
              width = options.resizedWidth;
            }
            if (options !== void 0) {
              bufferToTensorOptions = options;
              if (options.tensorFormat !== void 0) {
                throw new Error("Image input config format must be RGBA for HTMLImageElement");
              } else {
                bufferToTensorOptions.tensorFormat = "RGBA";
              }
              bufferToTensorOptions.height = height;
              bufferToTensorOptions.width = width;
            } else {
              bufferToTensorOptions.tensorFormat = "RGBA";
              bufferToTensorOptions.height = height;
              bufferToTensorOptions.width = width;
            }
            pixels2DContext.drawImage(image, 0, 0);
            data = pixels2DContext.getImageData(0, 0, width, height).data;
          } else {
            throw new Error("Can not access image data");
          }
        } else if (isImageDataEle) {
          let height;
          let width;
          if (options !== void 0 && options.resizedWidth !== void 0 && options.resizedHeight !== void 0) {
            height = options.resizedHeight;
            width = options.resizedWidth;
          } else {
            height = image.height;
            width = image.width;
          }
          if (options !== void 0) {
            bufferToTensorOptions = options;
          }
          bufferToTensorOptions.format = "RGBA";
          bufferToTensorOptions.height = height;
          bufferToTensorOptions.width = width;
          if (options !== void 0) {
            const tempCanvas = createCanvas2();
            tempCanvas.width = width;
            tempCanvas.height = height;
            const pixels2DContext = createCanvasContext(tempCanvas);
            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) {
          if (options === void 0) {
            throw new Error("Please provide image config with format for Imagebitmap");
          }
          const canvas = createCanvas2();
          canvas.width = image.width;
          canvas.height = image.height;
          const pixels2DContext = createCanvasContext(canvas);
          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;
            bufferToTensorOptions.height = height;
            bufferToTensorOptions.width = width;
            return bufferToTensor(data, bufferToTensorOptions);
          } else {
            throw new Error("Can not access image data");
          }
        } else if (isString) {
          return new Promise((resolve, reject) => {
            const canvas = createCanvas2();
            const context = createCanvasContext(canvas);
            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);
              bufferToTensorOptions.height = canvas.height;
              bufferToTensorOptions.width = canvas.width;
              resolve(bufferToTensor(img.data, bufferToTensorOptions));
            };
          });
        } else {
          throw new Error("Input data provided is not supported - aborted tensor creation");
        }
        if (data !== void 0) {
          return bufferToTensor(data, bufferToTensorOptions);
        } else {
          throw new Error("Input data provided is not supported - aborted tensor creation");
        }
      };
      tensorFromTexture = (texture, options) => {
        const { width, height, download, dispose } = options;
        const dims = [1, height, width, 4];
        return new Tensor({ location: "texture", type: "float32", texture, dims, download, dispose });
      };
      tensorFromGpuBuffer = (gpuBuffer, options) => {
        const { dataType, dims, download, dispose } = options;
        return new Tensor({ location: "gpu-buffer", type: dataType ?? "float32", gpuBuffer, dims, download, dispose });
      };
      tensorFromPinnedBuffer = (type, buffer, dims) => new Tensor({ location: "cpu-pinned", type, data: buffer, dims: dims ?? [buffer.length] });
    }
  });

  // common/dist/esm/tensor-impl-type-mapping.js
  var NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP, NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP, isTypedArrayChecked, checkTypedArray;
  var init_tensor_impl_type_mapping = __esm({
    "common/dist/esm/tensor-impl-type-mapping.js"() {
      "use strict";
      NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = /* @__PURE__ */ new Map([
        ["float32", Float32Array],
        ["uint8", Uint8Array],
        ["int8", Int8Array],
        ["uint16", Uint16Array],
        ["int16", Int16Array],
        ["int32", Int32Array],
        ["bool", Uint8Array],
        ["float64", Float64Array],
        ["uint32", Uint32Array]
      ]);
      NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = /* @__PURE__ */ new Map([
        [Float32Array, "float32"],
        [Uint8Array, "uint8"],
        [Int8Array, "int8"],
        [Uint16Array, "uint16"],
        [Int16Array, "int16"],
        [Int32Array, "int32"],
        [Float64Array, "float64"],
        [Uint32Array, "uint32"]
      ]);
      isTypedArrayChecked = false;
      checkTypedArray = () => {
        if (!isTypedArrayChecked) {
          isTypedArrayChecked = true;
          const isBigInt64ArrayAvailable = typeof BigInt64Array !== "undefined" && BigInt64Array.from;
          const isBigUint64ArrayAvailable = typeof BigUint64Array !== "undefined" && BigUint64Array.from;
          const isFloat16ArrayAvailable = typeof Float16Array !== "undefined" && Float16Array.from;
          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");
          }
          if (isFloat16ArrayAvailable) {
            NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("float16", Float16Array);
            NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(Float16Array, "float16");
          } else {
            NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("float16", Uint16Array);
          }
        }
      };
    }
  });

  // common/dist/esm/tensor-utils-impl.js
  var calculateSize, tensorReshape;
  var init_tensor_utils_impl = __esm({
    "common/dist/esm/tensor-utils-impl.js"() {
      "use strict";
      init_tensor_impl();
      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;
      };
      tensorReshape = (tensor, dims) => {
        switch (tensor.location) {
          case "cpu":
            return new Tensor(tensor.type, tensor.data, dims);
          case "cpu-pinned":
            return new Tensor({
              location: "cpu-pinned",
              data: tensor.data,
              type: tensor.type,
              dims
            });
          case "texture":
            return new Tensor({
              location: "texture",
              texture: tensor.texture,
              type: tensor.type,
              dims
            });
          case "gpu-buffer":
            return new Tensor({
              location: "gpu-buffer",
              gpuBuffer: tensor.gpuBuffer,
              type: tensor.type,
              dims
            });
          default:
            throw new Error(`tensorReshape: tensor location ${tensor.location} is not supported`);
        }
      };
    }
  });

  // common/dist/esm/tensor-impl.js
  var Tensor;
  var init_tensor_impl = __esm({
    "common/dist/esm/tensor-impl.js"() {
      "use strict";
      init_tensor_conversion_impl();
      init_tensor_factory_impl();
      init_tensor_impl_type_mapping();
      init_tensor_utils_impl();
      Tensor = class {
        /**
         * implementation.
         */
        constructor(arg0, arg1, arg2) {
          checkTypedArray();
          let type;
          let dims;
          if (typeof arg0 === "object" && "location" in arg0) {
            this.dataLocation = arg0.location;
            type = arg0.type;
            dims = arg0.dims;
            switch (arg0.location) {
              case "cpu-pinned": {
                const expectedTypedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(type);
                if (!expectedTypedArrayConstructor) {
                  throw new TypeError(`unsupported type "${type}" to create tensor from pinned buffer`);
                }
                if (!(arg0.data instanceof expectedTypedArrayConstructor)) {
                  throw new TypeError(`buffer should be of type ${expectedTypedArrayConstructor.name}`);
                }
                this.cpuData = arg0.data;
                break;
              }
              case "texture": {
                if (type !== "float32") {
                  throw new TypeError(`unsupported type "${type}" to create tensor from texture`);
                }
                this.gpuTextureData = arg0.texture;
                this.downloader = arg0.download;
                this.disposer = arg0.dispose;
                break;
              }
              case "gpu-buffer": {
                if (type !== "float32" && type !== "float16" && type !== "int32" && type !== "int64" && type !== "uint32" && type !== "uint8" && type !== "bool") {
                  throw new TypeError(`unsupported type "${type}" to create tensor from gpu buffer`);
                }
                this.gpuBufferData = arg0.gpuBuffer;
                this.downloader = arg0.download;
                this.disposer = arg0.dispose;
                break;
              }
              default:
                throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`);
            }
          } else {
            let data;
            let maybeDims;
            if (typeof arg0 === "string") {
              type = arg0;
              maybeDims = arg2;
              if (arg0 === "string") {
                if (!Array.isArray(arg1)) {
                  throw new TypeError("A string tensor's data must be a string array.");
                }
                data = arg1;
              } else {
                const typedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(arg0);
                if (typedArrayConstructor === void 0) {
                  throw new TypeError(`Unsupported tensor type: ${arg0}.`);
                }
                if (Array.isArray(arg1)) {
                  if (arg0 === "float16" && typedArrayConstructor === Uint16Array) {
                    throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");
                  } else if (arg0 === "uint64" || arg0 === "int64") {
                    data = typedArrayConstructor.from(arg1, BigInt);
                  } else {
                    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 {
              maybeDims = arg1;
              if (Array.isArray(arg0)) {
                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";
                  data = Uint8Array.from(arg0);
                } else {
                  throw new TypeError(`Invalid element type of data array: ${firstElementType}.`);
                }
              } else {
                const mappedType = NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(arg0.constructor);
                if (mappedType === void 0) {
                  throw new TypeError(`Unsupported type for tensor data: ${arg0.constructor}.`);
                }
                type = mappedType;
                data = arg0;
              }
            }
            if (maybeDims === void 0) {
              maybeDims = [data.length];
            } else if (!Array.isArray(maybeDims)) {
              throw new TypeError("A tensor's dims must be a number array");
            }
            dims = maybeDims;
            this.cpuData = data;
            this.dataLocation = "cpu";
          }
          const size = calculateSize(dims);
          if (this.cpuData && size !== this.cpuData.length) {
            throw new Error(`Tensor's size(${size}) does not match data length(${this.cpuData.length}).`);
          }
          this.type = type;
          this.dims = dims;
          this.size = size;
        }
        // #endregion
        // #region factory
        static async fromImage(image, options) {
          return tensorFromImage(image, options);
        }
        static fromTexture(texture, options) {
          return tensorFromTexture(texture, options);
        }
        static fromGpuBuffer(gpuBuffer, options) {
          return tensorFromGpuBuffer(gpuBuffer, options);
        }
        static fromPinnedBuffer(type, buffer, dims) {
          return tensorFromPinnedBuffer(type, buffer, dims);
        }
        // #endregion
        // #region conversions
        toDataURL(options) {
          return tensorToDataURL(this, options);
        }
        toImageData(options) {
          return tensorToImageData(this, options);
        }
        // #endregion
        // #region properties
        get data() {
          this.ensureValid();
          if (!this.cpuData) {
            throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");
          }
          return this.cpuData;
        }
        get location() {
          return this.dataLocation;
        }
        get texture() {
          this.ensureValid();
          if (!this.gpuTextureData) {
            throw new Error("The data is not stored as a WebGL texture.");
          }
          return this.gpuTextureData;
        }
        get gpuBuffer() {
          this.ensureValid();
          if (!this.gpuBufferData) {
            throw new Error("The data is not stored as a WebGPU buffer.");
          }
          return this.gpuBufferData;
        }
        // #endregion
        // #region methods
        async getData(releaseData) {
          this.ensureValid();
          switch (this.dataLocation) {
            case "cpu":
            case "cpu-pinned":
              return this.data;
            case "texture":
            case "gpu-buffer": {
              if (!this.downloader) {
                throw new Error("The current tensor is not created with a specified data downloader.");
              }
              if (this.isDownloading) {
                throw new Error("The current tensor is being downloaded.");
              }
              try {
                this.isDownloading = true;
                const data = await this.downloader();
                this.downloader = void 0;
                this.dataLocation = "cpu";
                this.cpuData = data;
                if (releaseData && this.disposer) {
                  this.disposer();
                  this.disposer = void 0;
                }
                return data;
              } finally {
                this.isDownloading = false;
              }
            }
            default:
              throw new Error(`cannot get data from location: ${this.dataLocation}`);
          }
        }
        dispose() {
          if (this.isDownloading) {
            throw new Error("The current tensor is being downloaded.");
          }
          if (this.disposer) {
            this.disposer();
            this.disposer = void 0;
          }
          this.cpuData = void 0;
          this.gpuTextureData = void 0;
          this.gpuBufferData = void 0;
          this.downloader = void 0;
          this.isDownloading = void 0;
          this.dataLocation = "none";
        }
        // #endregion
        // #region tensor utilities
        ensureValid() {
          if (this.dataLocation === "none") {
            throw new Error("The tensor is disposed.");
          }
        }
        reshape(dims) {
          this.ensureValid();
          if (this.downloader || this.disposer) {
            throw new Error("Cannot reshape a tensor that owns GPU resource.");
          }
          return tensorReshape(this, dims);
        }
      };
    }
  });

  // common/dist/esm/tensor.js
  var Tensor2;
  var init_tensor = __esm({
    "common/dist/esm/tensor.js"() {
      "use strict";
      init_tensor_impl();
      Tensor2 = Tensor;
    }
  });

  // common/dist/esm/trace.js
  var TRACE, TRACE_FUNC, TRACE_FUNC_BEGIN, TRACE_FUNC_END;
  var init_trace = __esm({
    "common/dist/esm/trace.js"() {
      "use strict";
      init_env_impl();
      TRACE = (deviceType, label) => {
        if (typeof env.trace === "undefined" ? !env.wasm.trace : !env.trace) {
          return;
        }
        console.timeStamp(`${deviceType}::ORT::${label}`);
      };
      TRACE_FUNC = (msg, extraMsg) => {
        const stack = new Error().stack?.split(/\r\n|\r|\n/g) || [];
        let hasTraceFunc = false;
        for (let i = 0; i < stack.length; i++) {
          if (hasTraceFunc && !stack[i].includes("TRACE_FUNC")) {
            let label = `FUNC_${msg}::${stack[i].trim().split(" ")[1]}`;
            if (extraMsg) {
              label += `::${extraMsg}`;
            }
            TRACE("CPU", label);
            return;
          }
          if (stack[i].includes("TRACE_FUNC")) {
            hasTraceFunc = true;
          }
        }
      };
      TRACE_FUNC_BEGIN = (extraMsg) => {
        if (typeof env.trace === "undefined" ? !env.wasm.trace : !env.trace) {
          return;
        }
        TRACE_FUNC("BEGIN", extraMsg);
      };
      TRACE_FUNC_END = (extraMsg) => {
        if (typeof env.trace === "undefined" ? !env.wasm.trace : !env.trace) {
          return;
        }
        TRACE_FUNC("END", extraMsg);
      };
    }
  });

  // common/dist/esm/inference-session-impl.js
  var InferenceSession;
  var init_inference_session_impl = __esm({
    "common/dist/esm/inference-session-impl.js"() {
      "use strict";
      init_backend_impl();
      init_tensor();
      init_trace();
      InferenceSession = class _InferenceSession {
        constructor(handler) {
          this.handler = handler;
        }
        async run(feeds, arg1, arg2) {
          TRACE_FUNC_BEGIN();
          const fetches = {};
          let options = {};
          if (typeof feeds !== "object" || feeds === null || feeds instanceof Tensor2 || 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;
          if (typeof arg1 === "object") {
            if (arg1 === null) {
              throw new TypeError("Unexpected argument[1]: cannot be null.");
            }
            if (arg1 instanceof Tensor2) {
              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;
              for (const name2 of arg1) {
                if (typeof name2 !== "string") {
                  throw new TypeError("'fetches' must be a string array or an object.");
                }
                if (this.outputNames.indexOf(name2) === -1) {
                  throw new RangeError(`'fetches' contains invalid output name: ${name2}.`);
                }
                fetches[name2] = null;
              }
              if (typeof arg2 === "object" && arg2 !== null) {
                options = arg2;
              } else if (typeof arg2 !== "undefined") {
                throw new TypeError("'options' must be an object.");
              }
            } else {
              let isFetches = false;
              const arg1Keys = Object.getOwnPropertyNames(arg1);
              for (const name2 of this.outputNames) {
                if (arg1Keys.indexOf(name2) !== -1) {
                  const v = arg1[name2];
                  if (v === null || v instanceof Tensor2) {
                    isFetches = true;
                    isFetchesEmpty = false;
                    fetches[name2] = 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'.");
          }
          for (const name2 of this.inputNames) {
            if (typeof feeds[name2] === "undefined") {
              throw new Error(`input '${name2}' is missing in 'feeds'.`);
            }
          }
          if (isFetchesEmpty) {
            for (const name2 of this.outputNames) {
              fetches[name2] = null;
            }
          }
          const results = await this.handler.run(feeds, fetches, options);
          const returnValue = {};
          for (const key in results) {
            if (Object.hasOwnProperty.call(results, key)) {
              const result = results[key];
              if (result instanceof Tensor2) {
                returnValue[key] = result;
              } else {
                returnValue[key] = new Tensor2(result.type, result.data, result.dims);
              }
            }
          }
          TRACE_FUNC_END();
          return returnValue;
        }
        async release() {
          return this.handler.dispose();
        }
        static async create(arg0, arg1, arg2, arg3) {
          TRACE_FUNC_BEGIN();
          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'.");
          }
          const [backend2, optionsWithValidatedEPs] = await resolveBackendAndExecutionProviders(options);
          const handler = await backend2.createInferenceSessionHandler(filePathOrUint8Array, optionsWithValidatedEPs);
          TRACE_FUNC_END();
          return new _InferenceSession(handler);
        }
        startProfiling() {
          this.handler.startProfiling();
        }
        endProfiling() {
          this.handler.endProfiling();
        }
        get inputNames() {
          return this.handler.inputNames;
        }
        get outputNames() {
          return this.handler.outputNames;
        }
      };
    }
  });

  // common/dist/esm/inference-session.js
  var InferenceSession2;
  var init_inference_session = __esm({
    "common/dist/esm/inference-session.js"() {
      "use strict";
      init_inference_session_impl();
      InferenceSession2 = InferenceSession;
    }
  });

  // common/dist/esm/tensor-conversion.js
  var init_tensor_conversion = __esm({
    "common/dist/esm/tensor-conversion.js"() {
      "use strict";
    }
  });

  // common/dist/esm/tensor-factory.js
  var init_tensor_factory = __esm({
    "common/dist/esm/tensor-factory.js"() {
      "use strict";
    }
  });

  // common/dist/esm/onnx-model.js
  var init_onnx_model = __esm({
    "common/dist/esm/onnx-model.js"() {
      "use strict";
    }
  });

  // common/dist/esm/onnx-value.js
  var init_onnx_value = __esm({
    "common/dist/esm/onnx-value.js"() {
      "use strict";
    }
  });

  // common/dist/esm/training-session-impl.js
  var noBackendErrMsg, TrainingSession;
  var init_training_session_impl = __esm({
    "common/dist/esm/training-session-impl.js"() {
      "use strict";
      init_backend_impl();
      init_tensor();
      noBackendErrMsg = "Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";
      TrainingSession = class _TrainingSession {
        constructor(handler, hasOptimizerModel, hasEvalModel) {
          this.handler = handler;
          this.hasOptimizerModel = hasOptimizerModel;
          this.hasEvalModel = hasEvalModel;
        }
        get trainingInputNames() {
          return this.handler.inputNames;
        }
        get trainingOutputNames() {
          return this.handler.outputNames;
        }
        get evalInputNames() {
          if (this.hasEvalModel) {
            return this.handler.evalInputNames;
          } else {
            throw new Error("This training session has no evalModel loaded.");
          }
        }
        get evalOutputNames() {
          if (this.hasEvalModel) {
            return this.handler.evalOutputNames;
          } else {
            throw new Error("This training session has no evalModel loaded.");
          }
        }
        static async create(trainingOptions, sessionOptions) {
          const evalModel = trainingOptions.evalModel || "";
          const optimizerModel = trainingOptions.optimizerModel || "";
          const options = sessionOptions || {};
          const [backend2, optionsWithValidatedEPs] = await resolveBackendAndExecutionProviders(options);
          if (backend2.createTrainingSessionHandler) {
            const handler = await backend2.createTrainingSessionHandler(trainingOptions.checkpointState, trainingOptions.trainModel, evalModel, optimizerModel, optionsWithValidatedEPs);
            return new _TrainingSession(handler, !!trainingOptions.optimizerModel, !!trainingOptions.evalModel);
          } else {
            throw new Error(noBackendErrMsg);
          }
        }
        /**
         * Helper function for runTrainStep and future runStep methods that handles the type-narrowing conversion from
         * the given parameters to SessionHandler.FetchesType and RunOptions.
         *
         * @param inputNames the feeds object is checked that they contain all input names in the provided list of input
         * names.
         * @param outputNames the fetches object is checked that their keys match up with valid names in the list of output
         * names.
         * @param feeds the required input
         * @param arg1 narrowed & converted into the SessionHandler.FetchesType or RunOptions object
         * @param arg2 optional RunOptions object.
         * @returns
         */
        typeNarrowingForRunStep(inputNames, outputNames, feeds, arg1, arg2) {
          const fetches = {};
          let options = {};
          if (typeof feeds !== "object" || feeds === null || feeds instanceof Tensor2 || 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;
          if (typeof arg1 === "object") {
            if (arg1 === null) {
              throw new TypeError("Unexpected argument[1]: cannot be null.");
            }
            if (arg1 instanceof Tensor2) {
              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;
              for (const name2 of arg1) {
                if (typeof name2 !== "string") {
                  throw new TypeError("'fetches' must be a string array or an object.");
                }
                if (outputNames.indexOf(name2) === -1) {
                  throw new RangeError(`'fetches' contains invalid output name: ${name2}.`);
                }
                fetches[name2] = null;
              }
              if (typeof arg2 === "object" && arg2 !== null) {
                options = arg2;
              } else if (typeof arg2 !== "undefined") {
                throw new TypeError("'options' must be an object.");
              }
            } else {
              let isFetches = false;
              const arg1Keys = Object.getOwnPropertyNames(arg1);
              for (const name2 of outputNames) {
                if (arg1Keys.indexOf(name2) !== -1) {
                  const v = arg1[name2];
                  if (v === null || v instanceof Tensor2) {
                    isFetches = true;
                    isFetchesEmpty = false;
                    fetches[name2] = 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'.");
          }
          for (const name2 of inputNames) {
            if (typeof feeds[name2] === "undefined") {
              throw new Error(`input '${name2}' is missing in 'feeds'.`);
            }
          }
          if (isFetchesEmpty) {
            for (const name2 of outputNames) {
              fetches[name2] = null;
            }
          }
          return [fetches, options];
        }
        /**
         * Helper method for runTrainStep and any other runStep methods. Takes the ReturnType result from the SessionHandler
         * and changes it into a map of Tensors.
         *
         * @param results
         * @returns
         */
        convertHandlerReturnTypeToMapOfTensors(results) {
          const returnValue = {};
          for (const key in results) {
            if (Object.hasOwnProperty.call(results, key)) {
              const result = results[key];
              if (result instanceof Tensor2) {
                returnValue[key] = result;
              } else {
                returnValue[key] = new Tensor2(result.type, result.data, result.dims);
              }
            }
          }
          return returnValue;
        }
        async lazyResetGrad() {
          await this.handler.lazyResetGrad();
        }
        async runTrainStep(feeds, arg1, arg2) {
          const [fetches, options] = this.typeNarrowingForRunStep(this.trainingInputNames, this.trainingOutputNames, feeds, arg1, arg2);
          const results = await this.handler.runTrainStep(feeds, fetches, options);
          return this.convertHandlerReturnTypeToMapOfTensors(results);
        }
        async runOptimizerStep(options) {
          if (this.hasOptimizerModel) {
            await this.handler.runOptimizerStep(options || {});
          } else {
            throw new Error("This TrainingSession has no OptimizerModel loaded.");
          }
        }
        async runEvalStep(feeds, arg1, arg2) {
          if (this.hasEvalModel) {
            const [fetches, options] = this.typeNarrowingForRunStep(this.evalInputNames, this.evalOutputNames, feeds, arg1, arg2);
            const results = await this.handler.runEvalStep(feeds, fetches, options);
            return this.convertHandlerReturnTypeToMapOfTensors(results);
          } else {
            throw new Error("This TrainingSession has no EvalModel loaded.");
          }
        }
        async getParametersSize(trainableOnly = true) {
          return this.handler.getParametersSize(trainableOnly);
        }
        async loadParametersBuffer(array, trainableOnly = true) {
          const paramsSize = await this.getParametersSize(trainableOnly);
          if (array.length !== 4 * paramsSize) {
            throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");
          }
          return this.handler.loadParametersBuffer(array, trainableOnly);
        }
        async getContiguousParameters(trainableOnly = true) {
          return this.handler.getContiguousParameters(trainableOnly);
        }
        async release() {
          return this.handler.dispose();
        }
      };
    }
  });

  // common/dist/esm/training-session.js
  var TrainingSession2;
  var init_training_session = __esm({
    "common/dist/esm/training-session.js"() {
      "use strict";
      init_training_session_impl();
      TrainingSession2 = TrainingSession;
    }
  });

  // common/dist/esm/index.js
  var esm_exports = {};
  __export(esm_exports, {
    InferenceSession: () => InferenceSession2,
    TRACE: () => TRACE,
    TRACE_FUNC_BEGIN: () => TRACE_FUNC_BEGIN,
    TRACE_FUNC_END: () => TRACE_FUNC_END,
    Tensor: () => Tensor2,
    TrainingSession: () => TrainingSession2,
    env: () => env2,
    registerBackend: () => registerBackend
  });
  var init_esm = __esm({
    "common/dist/esm/index.js"() {
      "use strict";
      init_backend();
      init_env();
      init_inference_session();
      init_tensor();
      init_tensor_conversion();
      init_tensor_factory();
      init_trace();
      init_onnx_model();
      init_onnx_value();
      init_training_session();
    }
  });

  // nodejs-ignore:node:fs/promises
  var readFile;
  var init_promises = __esm({
    "nodejs-ignore:node:fs/promises"() {
      readFile = void 0;
    }
  });

  // web/lib/onnxjs/instrument.ts
  function log(arg0, arg1, arg2, arg3) {
    if (arg1 === void 0) {
      return createCategorizedLogger(arg0);
    } else if (arg2 === void 0) {
      logInternal(arg0, arg1, 1);
    } else if (typeof arg2 === "number" && arg3 === void 0) {
      logInternal(arg0, arg1, arg2);
    } else if (typeof arg2 === "string" && arg3 === void 0) {
      logInternal(arg0, arg2, 1, arg1);
    } else if (typeof arg2 === "string" && typeof arg3 === "number") {
      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)
    };
  }
  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 = `${(/* @__PURE__ */ new Date()).toISOString()}|${content}`;
    }
    if (config.logSourceLocation) {
    }
    LOGGER_PROVIDER_MAP[config.provider].log(severity, content, category);
  }
  var NoOpLoggerProvider, ConsoleLoggerProvider, SEVERITY_VALUE, LOGGER_PROVIDER_MAP, LOGGER_DEFAULT_CONFIG, LOGGER_CONFIG_MAP, Logger, Event, EventRecord, Profiler, now;
  var init_instrument = __esm({
    "web/lib/onnxjs/instrument.ts"() {
      "use strict";
      NoOpLoggerProvider = class {
        log(_severity, _content, _category) {
        }
      };
      ConsoleLoggerProvider = class {
        log(severity, content, category) {
          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}`);
          }
        }
      };
      SEVERITY_VALUE = {
        verbose: 1e3,
        info: 2e3,
        warning: 4e3,
        error: 5e3,
        fatal: 6e3
      };
      LOGGER_PROVIDER_MAP = {
        ["none"]: new NoOpLoggerProvider(),
        ["console"]: new ConsoleLoggerProvider()
      };
      LOGGER_DEFAULT_CONFIG = {
        provider: "console",
        minimalSeverity: "warning",
        logDateTime: true,
        logSourceLocation: false
      };
      LOGGER_CONFIG_MAP = { [""]: LOGGER_DEFAULT_CONFIG };
      ((log3) => {
        function verbose(arg0, arg1) {
          log3("verbose", arg0, arg1);
        }
        log3.verbose = verbose;
        function info(arg0, arg1) {
          log3("info", arg0, arg1);
        }
        log3.info = info;
        function warning(arg0, arg1) {
          log3("warning", arg0, arg1);
        }
        log3.warning = warning;
        function error(arg0, arg1) {
          log3("error", arg0, arg1);
        }
        log3.error = error;
        function fatal(arg0, arg1) {
          log3("fatal", arg0, arg1);
        }
        log3.fatal = fatal;
        function reset(config) {
          LOGGER_CONFIG_MAP = {};
          set("", config || {});
        }
        log3.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 === void 0 ? previousConfig.logDateTime : config.logDateTime,
              logSourceLocation: config.logSourceLocation === void 0 ? previousConfig.logSourceLocation : config.logSourceLocation
            };
          }
        }
        log3.set = set;
        function setWithEnv(env3) {
          const config = {};
          if (env3.logLevel) {
            config.minimalSeverity = env3.logLevel;
          }
          set("", config);
        }
        log3.setWithEnv = setWithEnv;
      })(log || (log = {}));
      Logger = log;
      Event = class {
        constructor(category, name2, startTime, endCallback, timer, ctx) {
          this.category = category;
          this.name = name2;
          this.startTime = startTime;
          this.endCallback = endCallback;
          this.timer = timer;
          this.ctx = ctx;
        }
        async end() {
          return this.endCallback(this);
        }
        async checkTimer() {
          if (this.ctx === void 0 || this.timer === void 0) {
            throw new Error("No webgl timer found");
          } else {
            this.ctx.endTimer();
            return this.ctx.waitForQueryAndGetTime(this.timer);
          }
        }
      };
      EventRecord = class {
        constructor(category, name2, startTime, endTime) {
          this.category = category;
          this.name = name2;
          this.startTime = startTime;
          this.endTime = endTime;
        }
      };
      Profiler = class {
        constructor(maxNumberEvents, flushBatchSize, flushIntervalInMilliseconds) {
          this._started = false;
          this._flushPointer = 0;
          this._started = false;
          this._maxNumberEvents = maxNumberEvents === void 0 ? 1e4 : maxNumberEvents;
          this._flushBatchSize = flushBatchSize === void 0 ? 10 : flushBatchSize;
          this._flushIntervalInMilliseconds = flushIntervalInMilliseconds === void 0 ? 5e3 : flushIntervalInMilliseconds;
        }
        static create(config) {
          if (config === void 0) {
            return new this();
          }
          return new this(config.maxNumberEvents, config.flushBatchSize, config.flushIntervalInMilliseconds);
        }
        // start profiling
        start() {
          this._started = true;
          this._timingEvents = [];
          this._flushTime = 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, name2, func, ctx) {
          const event = this._started ? this.begin(category, name2, ctx) : void 0;
          let isPromise = false;
          const res = func();
          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, name2, ctx) {
          if (!this._started) {
            throw new Error("profiler is not started yet");
          }
          if (ctx === void 0) {
            const startTime = now();
            this.flush(startTime);
            return new Event(category, name2, startTime, (e) => this.endSync(e));
          } else {
            const timer = ctx.beginTimer();
            return new Event(category, name2, 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 = now();
          if (this._timingEvents.length < this._maxNumberEvents) {
            this._timingEvents.push(new EventRecord(event.category, event.name, event.startTime, endTime));
            this.flush(endTime);
          }
        }
        logOneEvent(event) {
          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) {
            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 = now();
          }
        }
        get started() {
          return this._started;
        }
      };
      now = typeof performance !== "undefined" && performance.now ? () => performance.now() : Date.now;
    }
  });

  // web/lib/onnxjs/opset.ts
  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) {
        for (const opset of opsets) {
          if (opset.domain === domain || opset.domain === "ai.onnx" && domain === "") {
            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(", ")}`);
  }
  function matchSelector(version3, selector) {
    if (selector.endsWith("+")) {
      const rangeStart = Number.parseInt(selector.substring(0, selector.length - 1), 10);
      return !isNaN(rangeStart) && rangeStart <= version3;
    } else if (selector.split("-").length === 2) {
      const pair = selector.split("-");
      const rangeStart = Number.parseInt(pair[0], 10);
      const rangeEnd = Number.parseInt(pair[1], 10);
      return !isNaN(rangeStart) && !isNaN(rangeEnd) && rangeStart <= version3 && version3 <= rangeEnd;
    } else {
      return Number.parseInt(selector, 10) === version3;
    }
  }
  var init_opset = __esm({
    "web/lib/onnxjs/opset.ts"() {
      "use strict";
    }
  });

  // web/node_modules/guid-typescript/dist/guid.js
  var require_guid = __commonJS({
    "web/node_modules/guid-typescript/dist/guid.js"(exports2) {
      "use strict";
      exports2.__esModule = true;
      var Guid2 = (
        /** @class */
        function() {
          function Guid3(guid) {
            if (!guid) {
              throw new TypeError("Invalid argument; `value` has no value.");
            }
            this.value = Guid3.EMPTY;
            if (guid && Guid3.isGuid(guid)) {
              this.value = guid;
            }
          }
          Guid3.isGuid = function(guid) {
            var value = guid.toString();
            return guid && (guid instanceof Guid3 || Guid3.validator.test(value));
          };
          Guid3.create = function() {
            return new Guid3([Guid3.gen(2), Guid3.gen(1), Guid3.gen(1), Guid3.gen(1), Guid3.gen(3)].join("-"));
          };
          Guid3.createEmpty = function() {
            return new Guid3("emptyguid");
          };
          Guid3.parse = function(guid) {
            return new Guid3(guid);
          };
          Guid3.raw = function() {
            return [Guid3.gen(2), Guid3.gen(1), Guid3.gen(1), Guid3.gen(1), Guid3.gen(3)].join("-");
          };
          Guid3.gen = function(count) {
            var out = "";
            for (var i = 0; i < count; i++) {
              out += ((1 + Math.random()) * 65536 | 0).toString(16).substring(1);
            }
            return out;
          };
          Guid3.prototype.equals = function(other) {
            return Guid3.isGuid(other) && this.value === other.toString();
          };
          Guid3.prototype.isEmpty = function() {
            return this.value === Guid3.EMPTY;
          };
          Guid3.prototype.toString = function() {
            return this.value;
          };
          Guid3.prototype.toJSON = function() {
            return {
              value: this.value
            };
          };
          Guid3.validator = new RegExp("^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$", "i");
          Guid3.EMPTY = "00000000-0000-0000-0000-000000000000";
          return Guid3;
        }()
      );
      exports2.Guid = Guid2;
    }
  });

  // web/node_modules/long/index.js
  function Long(low, high, unsigned) {
    this.low = low | 0;
    this.high = high | 0;
    this.unsigned = !!unsigned;
  }
  function isLong(obj) {
    return (obj && obj["__isLong__"]) === true;
  }
  function ctz32(value) {
    var c = Math.clz32(value & -value);
    return value ? 31 - c : c;
  }
  function fromInt(value, unsigned) {
    var obj, cachedObj, cache2;
    if (unsigned) {
      value >>>= 0;
      if (cache2 = 0 <= value && value < 256) {
        cachedObj = UINT_CACHE[value];
        if (cachedObj)
          return cachedObj;
      }
      obj = fromBits(value, 0, true);
      if (cache2)
        UINT_CACHE[value] = obj;
      return obj;
    } else {
      value |= 0;
      if (cache2 = -128 <= value && value < 128) {
        cachedObj = INT_CACHE[value];
        if (cachedObj)
          return cachedObj;
      }
      obj = fromBits(value, value < 0 ? -1 : 0, false);
      if (cache2)
        INT_CACHE[value] = obj;
      return obj;
    }
  }
  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);
  }
  function fromBits(lowBits, highBits, unsigned) {
    return new Long(lowBits, highBits, unsigned);
  }
  function fromString(str, unsigned, radix) {
    if (str.length === 0)
      throw Error("empty string");
    if (typeof unsigned === "number") {
      radix = unsigned;
      unsigned = false;
    } else {
      unsigned = !!unsigned;
    }
    if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
      return unsigned ? UZERO : ZERO;
    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();
    }
    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;
  }
  function fromValue(val, unsigned) {
    if (typeof val === "number")
      return fromNumber(val, unsigned);
    if (typeof val === "string")
      return fromString(val, unsigned);
    return fromBits(val.low, val.high, typeof unsigned === "boolean" ? unsigned : val.unsigned);
  }
  var wasm, INT_CACHE, UINT_CACHE, pow_dbl, TWO_PWR_16_DBL, TWO_PWR_24_DBL, TWO_PWR_32_DBL, TWO_PWR_64_DBL, TWO_PWR_63_DBL, TWO_PWR_24, ZERO, UZERO, ONE, UONE, NEG_ONE, MAX_VALUE, MAX_UNSIGNED_VALUE, MIN_VALUE, LongPrototype, long_default;
  var init_long = __esm({
    "web/node_modules/long/index.js"() {
      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) {
      }
      Long.prototype.__isLong__;
      Object.defineProperty(Long.prototype, "__isLong__", { value: true });
      Long.isLong = isLong;
      INT_CACHE = {};
      UINT_CACHE = {};
      Long.fromInt = fromInt;
      Long.fromNumber = fromNumber;
      Long.fromBits = fromBits;
      pow_dbl = Math.pow;
      Long.fromString = fromString;
      Long.fromValue = fromValue;
      TWO_PWR_16_DBL = 1 << 16;
      TWO_PWR_24_DBL = 1 << 24;
      TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
      TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
      TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
      TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
      ZERO = fromInt(0);
      Long.ZERO = ZERO;
      UZERO = fromInt(0, true);
      Long.UZERO = UZERO;
      ONE = fromInt(1);
      Long.ONE = ONE;
      UONE = fromInt(1, true);
      Long.UONE = UONE;
      NEG_ONE = fromInt(-1);
      Long.NEG_ONE = NEG_ONE;
      MAX_VALUE = fromBits(4294967295 | 0, 2147483647 | 0, false);
      Long.MAX_VALUE = MAX_VALUE;
      MAX_UNSIGNED_VALUE = fromBits(4294967295 | 0, 4294967295 | 0, true);
      Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
      MIN_VALUE = fromBits(0, 2147483648 | 0, false);
      Long.MIN_VALUE = MIN_VALUE;
      LongPrototype = Long.prototype;
      LongPrototype.toInt = function toInt() {
        return this.unsigned ? this.low >>> 0 : this.low;
      };
      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);
      };
      LongPrototype.toString = function toString(radix) {
        radix = radix || 10;
        if (radix < 2 || 36 < radix)
          throw RangeError("radix");
        if (this.isZero())
          return "0";
        if (this.isNegative()) {
          if (this.eq(MIN_VALUE)) {
            var radixLong = fromNumber(radix), div2 = this.div(radixLong), rem1 = div2.mul(radixLong).sub(this);
            return div2.toString(radix) + rem1.toInt().toString(radix);
          } else
            return "-" + this.neg().toString(radix);
        }
        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;
          }
        }
      };
      LongPrototype.getHighBits = function getHighBits() {
        return this.high;
      };
      LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
        return this.high >>> 0;
      };
      LongPrototype.getLowBits = function getLowBits() {
        return this.low;
      };
      LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
        return this.low >>> 0;
      };
      LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
        if (this.isNegative())
          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;
      };
      LongPrototype.isZero = function isZero() {
        return this.high === 0 && this.low === 0;
      };
      LongPrototype.eqz = LongPrototype.isZero;
      LongPrototype.isNegative = function isNegative() {
        return !this.unsigned && this.high < 0;
      };
      LongPrototype.isPositive = function isPositive() {
        return this.unsigned || this.high >= 0;
      };
      LongPrototype.isOdd = function isOdd() {
        return (this.low & 1) === 1;
      };
      LongPrototype.isEven = function isEven() {
        return (this.low & 1) === 0;
      };
      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;
      };
      LongPrototype.eq = LongPrototype.equals;
      LongPrototype.notEquals = function notEquals(other) {
        return !this.eq(
          /* validates */
          other
        );
      };
      LongPrototype.neq = LongPrototype.notEquals;
      LongPrototype.ne = LongPrototype.notEquals;
      LongPrototype.lessThan = function lessThan(other) {
        return this.comp(
          /* validates */
          other
        ) < 0;
      };
      LongPrototype.lt = LongPrototype.lessThan;
      LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
        return this.comp(
          /* validates */
          other
        ) <= 0;
      };
      LongPrototype.lte = LongPrototype.lessThanOrEqual;
      LongPrototype.le = LongPrototype.lessThanOrEqual;
      LongPrototype.greaterThan = function greaterThan(other) {
        return this.comp(
          /* validates */
          other
        ) > 0;
      };
      LongPrototype.gt = LongPrototype.greaterThan;
      LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
        return this.comp(
          /* validates */
          other
        ) >= 0;
      };
      LongPrototype.gte = LongPrototype.greaterThanOrEqual;
      LongPrototype.ge = LongPrototype.greaterThanOrEqual;
      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;
        if (!this.unsigned)
          return this.sub(other).isNegative() ? -1 : 1;
        return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1;
      };
      LongPrototype.comp = LongPrototype.compare;
      LongPrototype.negate = function negate() {
        if (!this.unsigned && this.eq(MIN_VALUE))
          return MIN_VALUE;
        return this.not().add(ONE);
      };
      LongPrototype.neg = LongPrototype.negate;
      LongPrototype.add = function add(addend) {
        if (!isLong(addend))
          addend = fromValue(addend);
        var a48 = this.high >>> 16;
        var a32 = this.high & 65535;
        var a16 = this.low >>> 16;
        var a00 = this.low & 65535;
        var b48 = addend.high >>> 16;
        var b32 = addend.high & 65535;
        var b16 = addend.low >>> 16;
        var b00 = addend.low & 65535;
        var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
        c00 += a00 + b00;
        c16 += c00 >>> 16;
        c00 &= 65535;
        c16 += a16 + b16;
        c32 += c16 >>> 16;
        c16 &= 65535;
        c32 += a32 + b32;
        c48 += c32 >>> 16;
        c32 &= 65535;
        c48 += a48 + b48;
        c48 &= 65535;
        return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
      };
      LongPrototype.subtract = function subtract(subtrahend) {
        if (!isLong(subtrahend))
          subtrahend = fromValue(subtrahend);
        return this.add(subtrahend.neg());
      };
      LongPrototype.sub = LongPrototype.subtract;
      LongPrototype.multiply = function multiply(multiplier) {
        if (this.isZero())
          return this;
        if (!isLong(multiplier))
          multiplier = fromValue(multiplier);
        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 this.unsigned ? UZERO : 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 (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
          return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
        var a48 = this.high >>> 16;
        var a32 = this.high & 65535;
        var a16 = this.low >>> 16;
        var a00 = this.low & 65535;
        var b48 = multiplier.high >>> 16;
        var b32 = multiplier.high & 65535;
        var b16 = multiplier.low >>> 16;
        var b00 = multiplier.low & 65535;
        var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
        c00 += a00 * b00;
        c16 += c00 >>> 16;
        c00 &= 65535;
        c16 += a16 * b00;
        c32 += c16 >>> 16;
        c16 &= 65535;
        c16 += a00 * b16;
        c32 += c16 >>> 16;
        c16 &= 65535;
        c32 += a32 * b00;
        c48 += c32 >>> 16;
        c32 &= 65535;
        c32 += a16 * b16;
        c48 += c32 >>> 16;
        c32 &= 65535;
        c32 += a00 * b32;
        c48 += c32 >>> 16;
        c32 &= 65535;
        c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
        c48 &= 65535;
        return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
      };
      LongPrototype.mul = LongPrototype.multiply;
      LongPrototype.divide = function divide(divisor) {
        if (!isLong(divisor))
          divisor = fromValue(divisor);
        if (divisor.isZero())
          throw Error("division by zero");
        if (wasm) {
          if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) {
            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) {
          if (this.eq(MIN_VALUE)) {
            if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
              return MIN_VALUE;
            else if (divisor.eq(MIN_VALUE))
              return ONE;
            else {
              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 {
          if (!divisor.unsigned)
            divisor = divisor.toUnsigned();
          if (divisor.gt(this))
            return UZERO;
          if (divisor.gt(this.shru(1)))
            return UONE;
          res = UZERO;
        }
        rem = this;
        while (rem.gte(divisor)) {
          approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
          var log22 = Math.ceil(Math.log(approx) / Math.LN2), delta = log22 <= 48 ? 1 : pow_dbl(2, log22 - 48), approxRes = fromNumber(approx), approxRem = approxRes.mul(divisor);
          while (approxRem.isNegative() || approxRem.gt(rem)) {
            approx -= delta;
            approxRes = fromNumber(approx, this.unsigned);
            approxRem = approxRes.mul(divisor);
          }
          if (approxRes.isZero())
            approxRes = ONE;
          res = res.add(approxRes);
          rem = rem.sub(approxRem);
        }
        return res;
      };
      LongPrototype.div = LongPrototype.divide;
      LongPrototype.modulo = function modulo(divisor) {
        if (!isLong(divisor))
          divisor = fromValue(divisor);
        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));
      };
      LongPrototype.mod = LongPrototype.modulo;
      LongPrototype.rem = LongPrototype.modulo;
      LongPrototype.not = function not() {
        return fromBits(~this.low, ~this.high, this.unsigned);
      };
      LongPrototype.countLeadingZeros = function countLeadingZeros() {
        return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32;
      };
      LongPrototype.clz = LongPrototype.countLeadingZeros;
      LongPrototype.countTrailingZeros = function countTrailingZeros() {
        return this.low ? ctz32(this.low) : ctz32(this.high) + 32;
      };
      LongPrototype.ctz = LongPrototype.countTrailingZeros;
      LongPrototype.and = function and(other) {
        if (!isLong(other))
          other = fromValue(other);
        return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
      };
      LongPrototype.or = function or(other) {
        if (!isLong(other))
          other = fromValue(other);
        return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
      };
      LongPrototype.xor = function xor(other) {
        if (!isLong(other))
          other = fromValue(other);
        return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
      };
      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);
      };
      LongPrototype.shl = LongPrototype.shiftLeft;
      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);
      };
      LongPrototype.shr = LongPrototype.shiftRight;
      LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
        if (isLong(numBits))
          numBits = numBits.toInt();
        if ((numBits &= 63) === 0)
          return this;
        if (numBits < 32)
          return fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >>> numBits, this.unsigned);
        if (numBits === 32)
          return fromBits(this.high, 0, this.unsigned);
        return fromBits(this.high >>> numBits - 32, 0, this.unsigned);
      };
      LongPrototype.shru = LongPrototype.shiftRightUnsigned;
      LongPrototype.shr_u = LongPrototype.shiftRightUnsigned;
      LongPrototype.rotateLeft = function rotateLeft(numBits) {
        var b;
        if (isLong(numBits))
          numBits = numBits.toInt();
        if ((numBits &= 63) === 0)
          return this;
        if (numBits === 32)
          return fromBits(this.high, this.low, this.unsigned);
        if (numBits < 32) {
          b = 32 - numBits;
          return fromBits(this.low << numBits | this.high >>> b, this.high << numBits | this.low >>> b, this.unsigned);
        }
        numBits -= 32;
        b = 32 - numBits;
        return fromBits(this.high << numBits | this.low >>> b, this.low << numBits | this.high >>> b, this.unsigned);
      };
      LongPrototype.rotl = LongPrototype.rotateLeft;
      LongPrototype.rotateRight = function rotateRight(numBits) {
        var b;
        if (isLong(numBits))
          numBits = numBits.toInt();
        if ((numBits &= 63) === 0)
          return this;
        if (numBits === 32)
          return fromBits(this.high, this.low, this.unsigned);
        if (numBits < 32) {
          b = 32 - numBits;
          return fromBits(this.high << b | this.low >>> numBits, this.low << b | this.high >>> numBits, this.unsigned);
        }
        numBits -= 32;
        b = 32 - numBits;
        return fromBits(this.low << b | this.high >>> numBits, this.high << b | this.low >>> numBits, this.unsigned);
      };
      LongPrototype.rotr = LongPrototype.rotateRight;
      LongPrototype.toSigned = function toSigned() {
        if (!this.unsigned)
          return this;
        return fromBits(this.low, this.high, false);
      };
      LongPrototype.toUnsigned = function toUnsigned() {
        if (this.unsigned)
          return this;
        return fromBits(this.low, this.high, true);
      };
      LongPrototype.toBytes = function toBytes(le) {
        return le ? this.toBytesLE() : this.toBytesBE();
      };
      LongPrototype.toBytesLE = function toBytesLE() {
        var hi = this.high, lo = this.low;
        return [
          lo & 255,
          lo >>> 8 & 255,
          lo >>> 16 & 255,
          lo >>> 24,
          hi & 255,
          hi >>> 8 & 255,
          hi >>> 16 & 255,
          hi >>> 24
        ];
      };
      LongPrototype.toBytesBE = function toBytesBE() {
        var hi = this.high, lo = this.low;
        return [
          hi >>> 24,
          hi >>> 16 & 255,
          hi >>> 8 & 255,
          hi & 255,
          lo >>> 24,
          lo >>> 16 & 255,
          lo >>> 8 & 255,
          lo & 255
        ];
      };
      Long.fromBytes = function fromBytes(bytes, unsigned, le) {
        return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
      };
      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
        );
      };
      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
        );
      };
      long_default = Long;
    }
  });

  // web/node_modules/flatbuffers/js/flatbuffers.mjs
  var flatbuffers;
  var init_flatbuffers = __esm({
    "web/node_modules/flatbuffers/js/flatbuffers.mjs"() {
      flatbuffers = {};
      flatbuffers.Offset;
      flatbuffers.Table;
      flatbuffers.SIZEOF_SHORT = 2;
      flatbuffers.SIZEOF_INT = 4;
      flatbuffers.FILE_IDENTIFIER_LENGTH = 4;
      flatbuffers.SIZE_PREFIX_LENGTH = 4;
      flatbuffers.Encoding = {
        UTF8_BYTES: 1,
        UTF16_STRING: 2
      };
      flatbuffers.int32 = new Int32Array(2);
      flatbuffers.float32 = new Float32Array(flatbuffers.int32.buffer);
      flatbuffers.float64 = new Float64Array(flatbuffers.int32.buffer);
      flatbuffers.isLittleEndian = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1;
      flatbuffers.Long = function(low, high) {
        this.low = low | 0;
        this.high = high | 0;
      };
      flatbuffers.Long.create = function(low, high) {
        return low == 0 && high == 0 ? flatbuffers.Long.ZERO : new flatbuffers.Long(low, high);
      };
      flatbuffers.Long.prototype.toFloat64 = function() {
        return (this.low >>> 0) + this.high * 4294967296;
      };
      flatbuffers.Long.prototype.equals = function(other) {
        return this.low == other.low && this.high == other.high;
      };
      flatbuffers.Long.ZERO = new flatbuffers.Long(0, 0);
      flatbuffers.Builder = function(opt_initial_size) {
        if (!opt_initial_size) {
          var initial_size = 1024;
        } else {
          var initial_size = opt_initial_size;
        }
        this.bb = flatbuffers.ByteBuffer.allocate(initial_size);
        this.space = initial_size;
        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;
      };
      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;
      };
      flatbuffers.Builder.prototype.forceDefaults = function(forceDefaults) {
        this.force_defaults = forceDefaults;
      };
      flatbuffers.Builder.prototype.dataBuffer = function() {
        return this.bb;
      };
      flatbuffers.Builder.prototype.asUint8Array = function() {
        return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset());
      };
      flatbuffers.Builder.prototype.prep = function(size, additional_bytes) {
        if (size > this.minalign) {
          this.minalign = size;
        }
        var align_size = ~(this.bb.capacity() - this.space + additional_bytes) + 1 & size - 1;
        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);
      };
      flatbuffers.Builder.prototype.pad = function(byte_size) {
        for (var i = 0; i < byte_size; i++) {
          this.bb.writeInt8(--this.space, 0);
        }
      };
      flatbuffers.Builder.prototype.writeInt8 = function(value) {
        this.bb.writeInt8(this.space -= 1, value);
      };
      flatbuffers.Builder.prototype.writeInt16 = function(value) {
        this.bb.writeInt16(this.space -= 2, value);
      };
      flatbuffers.Builder.prototype.writeInt32 = function(value) {
        this.bb.writeInt32(this.space -= 4, value);
      };
      flatbuffers.Builder.prototype.writeInt64 = function(value) {
        this.bb.writeInt64(this.space -= 8, value);
      };
      flatbuffers.Builder.prototype.writeFloat32 = function(value) {
        this.bb.writeFloat32(this.space -= 4, value);
      };
      flatbuffers.Builder.prototype.writeFloat64 = function(value) {
        this.bb.writeFloat64(this.space -= 8, value);
      };
      flatbuffers.Builder.prototype.addInt8 = function(value) {
        this.prep(1, 0);
        this.writeInt8(value);
      };
      flatbuffers.Builder.prototype.addInt16 = function(value) {
        this.prep(2, 0);
        this.writeInt16(value);
      };
      flatbuffers.Builder.prototype.addInt32 = function(value) {
        this.prep(4, 0);
        this.writeInt32(value);
      };
      flatbuffers.Builder.prototype.addInt64 = function(value) {
        this.prep(8, 0);
        this.writeInt64(value);
      };
      flatbuffers.Builder.prototype.addFloat32 = function(value) {
        this.prep(4, 0);
        this.writeFloat32(value);
      };
      flatbuffers.Builder.prototype.addFloat64 = function(value) {
        this.prep(8, 0);
        this.writeFloat64(value);
      };
      flatbuffers.Builder.prototype.addFieldInt8 = function(voffset, value, defaultValue) {
        if (this.force_defaults || value != defaultValue) {
          this.addInt8(value);
          this.slot(voffset);
        }
      };
      flatbuffers.Builder.prototype.addFieldInt16 = function(voffset, value, defaultValue) {
        if (this.force_defaults || value != defaultValue) {
          this.addInt16(value);
          this.slot(voffset);
        }
      };
      flatbuffers.Builder.prototype.addFieldInt32 = function(voffset, value, defaultValue) {
        if (this.force_defaults || value != defaultValue) {
          this.addInt32(value);
          this.slot(voffset);
        }
      };
      flatbuffers.Builder.prototype.addFieldInt64 = function(voffset, value, defaultValue) {
        if (this.force_defaults || !value.equals(defaultValue)) {
          this.addInt64(value);
          this.slot(voffset);
        }
      };
      flatbuffers.Builder.prototype.addFieldFloat32 = function(voffset, value, defaultValue) {
        if (this.force_defaults || value != defaultValue) {
          this.addFloat32(value);
          this.slot(voffset);
        }
      };
      flatbuffers.Builder.prototype.addFieldFloat64 = function(voffset, value, defaultValue) {
        if (this.force_defaults || value != defaultValue) {
          this.addFloat64(value);
          this.slot(voffset);
        }
      };
      flatbuffers.Builder.prototype.addFieldOffset = function(voffset, value, defaultValue) {
        if (this.force_defaults || value != defaultValue) {
          this.addOffset(value);
          this.slot(voffset);
        }
      };
      flatbuffers.Builder.prototype.addFieldStruct = function(voffset, value, defaultValue) {
        if (value != defaultValue) {
          this.nested(value);
          this.slot(voffset);
        }
      };
      flatbuffers.Builder.prototype.nested = function(obj) {
        if (obj != this.offset()) {
          throw new Error("FlatBuffers: struct must be serialized inline.");
        }
      };
      flatbuffers.Builder.prototype.notNested = function() {
        if (this.isNested) {
          throw new Error("FlatBuffers: object serialization must not be nested.");
        }
      };
      flatbuffers.Builder.prototype.slot = function(voffset) {
        this.vtable[voffset] = this.offset();
      };
      flatbuffers.Builder.prototype.offset = function() {
        return this.bb.capacity() - this.space;
      };
      flatbuffers.Builder.growByteBuffer = function(bb) {
        var old_buf_size = bb.capacity();
        if (old_buf_size & 3221225472) {
          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;
      };
      flatbuffers.Builder.prototype.addOffset = function(offset) {
        this.prep(flatbuffers.SIZEOF_INT, 0);
        this.writeInt32(this.offset() - offset + flatbuffers.SIZEOF_INT);
      };
      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.isNested = true;
        this.object_start = this.offset();
      };
      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();
        var i = this.vtable_in_use - 1;
        for (; i >= 0 && this.vtable[i] == 0; i--) {
        }
        var trimmed_size = i + 1;
        for (; i >= 0; i--) {
          this.addInt16(this.vtable[i] != 0 ? vtableloc - this.vtable[i] : 0);
        }
        var standard_fields = 2;
        this.addInt16(vtableloc - this.object_start);
        var len = (trimmed_size + standard_fields) * flatbuffers.SIZEOF_SHORT;
        this.addInt16(len);
        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) {
          this.space = this.bb.capacity() - vtableloc;
          this.bb.writeInt32(this.space, existing_vtable - vtableloc);
        } else {
          this.vtables.push(this.offset());
          this.bb.writeInt32(this.bb.capacity() - vtableloc, this.offset() - vtableloc);
        }
        this.isNested = false;
        return vtableloc;
      };
      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);
      };
      flatbuffers.Builder.prototype.finishSizePrefixed = function(root_table, opt_file_identifier) {
        this.finish(root_table, opt_file_identifier, true);
      };
      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 (!ok) {
          throw new Error("FlatBuffers: field " + field + " must be set");
        }
      };
      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);
      };
      flatbuffers.Builder.prototype.endVector = function() {
        this.writeInt32(this.vector_num_elems);
        return this.offset();
      };
      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;
            var a = s.charCodeAt(i++);
            if (a < 55296 || a >= 56320) {
              codePoint = a;
            } else {
              var b = s.charCodeAt(i++);
              codePoint = (a << 10) + b + (65536 - (55296 << 10) - 56320);
            }
            if (codePoint < 128) {
              utf8.push(codePoint);
            } else {
              if (codePoint < 2048) {
                utf8.push(codePoint >> 6 & 31 | 192);
              } else {
                if (codePoint < 65536) {
                  utf8.push(codePoint >> 12 & 15 | 224);
                } else {
                  utf8.push(
                    codePoint >> 18 & 7 | 240,
                    codePoint >> 12 & 63 | 128
                  );
                }
                utf8.push(codePoint >> 6 & 63 | 128);
              }
              utf8.push(codePoint & 63 | 128);
            }
          }
        }
        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();
      };
      flatbuffers.Builder.prototype.createLong = function(low, high) {
        return flatbuffers.Long.create(low, high);
      };
      flatbuffers.ByteBuffer = function(bytes) {
        this.bytes_ = bytes;
        this.position_ = 0;
      };
      flatbuffers.ByteBuffer.allocate = function(byte_size) {
        return new flatbuffers.ByteBuffer(new Uint8Array(byte_size));
      };
      flatbuffers.ByteBuffer.prototype.clear = function() {
        this.position_ = 0;
      };
      flatbuffers.ByteBuffer.prototype.bytes = function() {
        return this.bytes_;
      };
      flatbuffers.ByteBuffer.prototype.position = function() {
        return this.position_;
      };
      flatbuffers.ByteBuffer.prototype.setPosition = function(position) {
        this.position_ = position;
      };
      flatbuffers.ByteBuffer.prototype.capacity = function() {
        return this.bytes_.length;
      };
      flatbuffers.ByteBuffer.prototype.readInt8 = function(offset) {
        return this.readUint8(offset) << 24 >> 24;
      };
      flatbuffers.ByteBuffer.prototype.readUint8 = function(offset) {
        return this.bytes_[offset];
      };
      flatbuffers.ByteBuffer.prototype.readInt16 = function(offset) {
        return this.readUint16(offset) << 16 >> 16;
      };
      flatbuffers.ByteBuffer.prototype.readUint16 = function(offset) {
        return this.bytes_[offset] | this.bytes_[offset + 1] << 8;
      };
      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;
      };
      flatbuffers.ByteBuffer.prototype.readUint32 = function(offset) {
        return this.readInt32(offset) >>> 0;
      };
      flatbuffers.ByteBuffer.prototype.readInt64 = function(offset) {
        return new flatbuffers.Long(this.readInt32(offset), this.readInt32(offset + 4));
      };
      flatbuffers.ByteBuffer.prototype.readUint64 = function(offset) {
        return new flatbuffers.Long(this.readUint32(offset), this.readUint32(offset + 4));
      };
      flatbuffers.ByteBuffer.prototype.readFloat32 = function(offset) {
        flatbuffers.int32[0] = this.readInt32(offset);
        return flatbuffers.float32[0];
      };
      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];
      };
      flatbuffers.ByteBuffer.prototype.writeInt8 = function(offset, value) {
        this.bytes_[offset] = /** @type {number} */
        value;
      };
      flatbuffers.ByteBuffer.prototype.writeUint8 = function(offset, value) {
        this.bytes_[offset] = value;
      };
      flatbuffers.ByteBuffer.prototype.writeInt16 = function(offset, value) {
        this.bytes_[offset] = value;
        this.bytes_[offset + 1] = value >> 8;
      };
      flatbuffers.ByteBuffer.prototype.writeUint16 = function(offset, value) {
        this.bytes_[offset] = value;
        this.bytes_[offset + 1] = value >> 8;
      };
      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;
      };
      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;
      };
      flatbuffers.ByteBuffer.prototype.writeInt64 = function(offset, value) {
        this.writeInt32(offset, value.low);
        this.writeInt32(offset + 4, value.high);
      };
      flatbuffers.ByteBuffer.prototype.writeUint64 = function(offset, value) {
        this.writeUint32(offset, value.low);
        this.writeUint32(offset + 4, value.high);
      };
      flatbuffers.ByteBuffer.prototype.writeFloat32 = function(offset, value) {
        flatbuffers.float32[0] = value;
        this.writeInt32(offset, flatbuffers.int32[0]);
      };
      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]);
      };
      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;
      };
      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;
      };
      flatbuffers.ByteBuffer.prototype.__union = function(t, offset) {
        t.bb_pos = offset + this.readInt32(offset);
        t.bb = this;
        return t;
      };
      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;
          var a = this.readUint8(offset + i++);
          if (a < 192) {
            codePoint = a;
          } else {
            var b = this.readUint8(offset + i++);
            if (a < 224) {
              codePoint = (a & 31) << 6 | b & 63;
            } else {
              var c = this.readUint8(offset + i++);
              if (a < 240) {
                codePoint = (a & 15) << 12 | (b & 63) << 6 | c & 63;
              } else {
                var d = this.readUint8(offset + i++);
                codePoint = (a & 7) << 18 | (b & 63) << 12 | (c & 63) << 6 | d & 63;
              }
            }
          }
          if (codePoint < 65536) {
            result += String.fromCharCode(codePoint);
          } else {
            codePoint -= 65536;
            result += String.fromCharCode(
              (codePoint >> 10) + 55296,
              (codePoint & (1 << 10) - 1) + 56320
            );
          }
        }
        return result;
      };
      flatbuffers.ByteBuffer.prototype.__indirect = function(offset) {
        return offset + this.readInt32(offset);
      };
      flatbuffers.ByteBuffer.prototype.__vector = function(offset) {
        return offset + this.readInt32(offset) + flatbuffers.SIZEOF_INT;
      };
      flatbuffers.ByteBuffer.prototype.__vector_len = function(offset) {
        return this.readInt32(offset + this.readInt32(offset));
      };
      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;
      };
      flatbuffers.ByteBuffer.prototype.createLong = function(low, high) {
        return flatbuffers.Long.create(low, high);
      };
    }
  });

  // web/lib/onnxjs/ort-schema/flatbuffers/ort-generated.ts
  var onnxruntime;
  var init_ort_generated = __esm({
    "web/lib/onnxjs/ort-schema/flatbuffers/ort-generated.ts"() {
      "use strict";
      init_flatbuffers();
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            let AttributeType;
            ((AttributeType2) => {
              AttributeType2[AttributeType2["UNDEFINED"] = 0] = "UNDEFINED";
              AttributeType2[AttributeType2["FLOAT"] = 1] = "FLOAT";
              AttributeType2[AttributeType2["INT"] = 2] = "INT";
              AttributeType2[AttributeType2["STRING"] = 3] = "STRING";
              AttributeType2[AttributeType2["TENSOR"] = 4] = "TENSOR";
              AttributeType2[AttributeType2["GRAPH"] = 5] = "GRAPH";
              AttributeType2[AttributeType2["FLOATS"] = 6] = "FLOATS";
              AttributeType2[AttributeType2["INTS"] = 7] = "INTS";
              AttributeType2[AttributeType2["STRINGS"] = 8] = "STRINGS";
              AttributeType2[AttributeType2["TENSORS"] = 9] = "TENSORS";
              AttributeType2[AttributeType2["GRAPHS"] = 10] = "GRAPHS";
              AttributeType2[AttributeType2["SPARSE_TENSOR"] = 11] = "SPARSE_TENSOR";
              AttributeType2[AttributeType2["SPARSE_TENSORS"] = 12] = "SPARSE_TENSORS";
            })(AttributeType = fbs2.AttributeType || (fbs2.AttributeType = {}));
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            let DimensionValueType;
            ((DimensionValueType2) => {
              DimensionValueType2[DimensionValueType2["UNKNOWN"] = 0] = "UNKNOWN";
              DimensionValueType2[DimensionValueType2["VALUE"] = 1] = "VALUE";
              DimensionValueType2[DimensionValueType2["PARAM"] = 2] = "PARAM";
            })(DimensionValueType = fbs2.DimensionValueType || (fbs2.DimensionValueType = {}));
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            let TensorDataType;
            ((TensorDataType2) => {
              TensorDataType2[TensorDataType2["UNDEFINED"] = 0] = "UNDEFINED";
              TensorDataType2[TensorDataType2["FLOAT"] = 1] = "FLOAT";
              TensorDataType2[TensorDataType2["UINT8"] = 2] = "UINT8";
              TensorDataType2[TensorDataType2["INT8"] = 3] = "INT8";
              TensorDataType2[TensorDataType2["UINT16"] = 4] = "UINT16";
              TensorDataType2[TensorDataType2["INT16"] = 5] = "INT16";
              TensorDataType2[TensorDataType2["INT32"] = 6] = "INT32";
              TensorDataType2[TensorDataType2["INT64"] = 7] = "INT64";
              TensorDataType2[TensorDataType2["STRING"] = 8] = "STRING";
              TensorDataType2[TensorDataType2["BOOL"] = 9] = "BOOL";
              TensorDataType2[TensorDataType2["FLOAT16"] = 10] = "FLOAT16";
              TensorDataType2[TensorDataType2["DOUBLE"] = 11] = "DOUBLE";
              TensorDataType2[TensorDataType2["UINT32"] = 12] = "UINT32";
              TensorDataType2[TensorDataType2["UINT64"] = 13] = "UINT64";
              TensorDataType2[TensorDataType2["COMPLEX64"] = 14] = "COMPLEX64";
              TensorDataType2[TensorDataType2["COMPLEX128"] = 15] = "COMPLEX128";
              TensorDataType2[TensorDataType2["BFLOAT16"] = 16] = "BFLOAT16";
              TensorDataType2[TensorDataType2["FLOAT8E4M3FN"] = 17] = "FLOAT8E4M3FN";
              TensorDataType2[TensorDataType2["FLOAT8E4M3FNUZ"] = 18] = "FLOAT8E4M3FNUZ";
              TensorDataType2[TensorDataType2["FLOAT8E5M2"] = 19] = "FLOAT8E5M2";
              TensorDataType2[TensorDataType2["FLOAT8E5M2FNUZ"] = 20] = "FLOAT8E5M2FNUZ";
            })(TensorDataType = fbs2.TensorDataType || (fbs2.TensorDataType = {}));
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            let NodeType;
            ((NodeType2) => {
              NodeType2[NodeType2["Primitive"] = 0] = "Primitive";
              NodeType2[NodeType2["Fused"] = 1] = "Fused";
            })(NodeType = fbs2.NodeType || (fbs2.NodeType = {}));
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            let TypeInfoValue;
            ((TypeInfoValue2) => {
              TypeInfoValue2[TypeInfoValue2["NONE"] = 0] = "NONE";
              TypeInfoValue2[TypeInfoValue2["tensor_type"] = 1] = "tensor_type";
              TypeInfoValue2[TypeInfoValue2["sequence_type"] = 2] = "sequence_type";
              TypeInfoValue2[TypeInfoValue2["map_type"] = 3] = "map_type";
            })(TypeInfoValue = fbs2.TypeInfoValue || (fbs2.TypeInfoValue = {}));
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            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.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 onnxruntime2.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);
              }
            }
            fbs2.Shape = Shape;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            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.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 onnxruntime2.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);
              }
            }
            fbs2.Dimension = Dimension;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            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.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)
                ) : 0 /* 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, 0 /* 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);
              }
            }
            fbs2.DimensionValue = DimensionValue;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            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.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)
                ) : 0 /* 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 onnxruntime2.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, 0 /* 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);
              }
            }
            fbs2.TensorTypeAndShape = TensorTypeAndShape;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            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.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)
                ) : 0 /* 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 onnxruntime2.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, 0 /* 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);
              }
            }
            fbs2.MapType = MapType;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            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.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 onnxruntime2.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);
              }
            }
            fbs2.SequenceType = SequenceType;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            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();
              }
            }
            fbs2.EdgeEnd = EdgeEnd;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            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.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 onnxruntime2.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 onnxruntime2.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);
              }
            }
            fbs2.NodeEdge = NodeEdge;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            class Node2 {
              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 Node2()).__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.SIZE_PREFIX_LENGTH);
                return (obj || new Node2()).__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)
                ) : 0 /* 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 onnxruntime2.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, 0 /* 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) {
                Node2.startNode(builder);
                Node2.addName(builder, nameOffset);
                Node2.addDocString(builder, docStringOffset);
                Node2.addDomain(builder, domainOffset);
                Node2.addSinceVersion(builder, sinceVersion);
                Node2.addIndex(builder, index);
                Node2.addOpType(builder, opTypeOffset);
                Node2.addType(builder, type);
                Node2.addExecutionProviderType(builder, executionProviderTypeOffset);
                Node2.addInputs(builder, inputsOffset);
                Node2.addOutputs(builder, outputsOffset);
                Node2.addAttributes(builder, attributesOffset);
                Node2.addInputArgCounts(builder, inputArgCountsOffset);
                Node2.addImplicitInputs(builder, implicitInputsOffset);
                return Node2.endNode(builder);
              }
            }
            fbs2.Node = Node2;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            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.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 onnxruntime2.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);
              }
            }
            fbs2.ValueInfo = ValueInfo;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            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.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)
                ) : 0 /* 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, 0 /* 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);
              }
            }
            fbs2.TypeInfo = TypeInfo;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            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.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, version3) {
                builder.addFieldInt64(1, version3, builder.createLong(0, 0));
              }
              /**
               * @param flatbuffers.Builder builder
               * @returns flatbuffers.Offset
               */
              static endOperatorSetId(builder) {
                let offset = builder.endObject();
                return offset;
              }
              static createOperatorSetId(builder, domainOffset, version3) {
                OperatorSetId.startOperatorSetId(builder);
                OperatorSetId.addDomain(builder, domainOffset);
                OperatorSetId.addVersion(builder, version3);
                return OperatorSetId.endOperatorSetId(builder);
              }
            }
            fbs2.OperatorSetId = OperatorSetId;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            class Tensor4 {
              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 Tensor4()).__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.SIZE_PREFIX_LENGTH);
                return (obj || new Tensor4()).__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)
                ) : 0 /* 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, 0 /* 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) {
                Tensor4.startTensor(builder);
                Tensor4.addName(builder, nameOffset);
                Tensor4.addDocString(builder, docStringOffset);
                Tensor4.addDims(builder, dimsOffset);
                Tensor4.addDataType(builder, dataType);
                Tensor4.addRawData(builder, rawDataOffset);
                Tensor4.addStringData(builder, stringDataOffset);
                return Tensor4.endTensor(builder);
              }
            }
            fbs2.Tensor = Tensor4;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            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.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 onnxruntime2.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 onnxruntime2.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);
              }
            }
            fbs2.SparseTensor = SparseTensor;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            class Attribute2 {
              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 Attribute2()).__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.SIZE_PREFIX_LENGTH);
                return (obj || new Attribute2()).__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)
                ) : 0 /* UNDEFINED */;
              }
              /**
               * @returns number
               */
              f() {
                let offset = this.bb.__offset(this.bb_pos, 10);
                return offset ? this.bb.readFloat32(this.bb_pos + offset) : 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 onnxruntime2.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 onnxruntime2.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 onnxruntime2.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 onnxruntime2.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, 0 /* UNDEFINED */);
              }
              /**
               * @param flatbuffers.Builder builder
               * @param number f
               */
              static addF(builder, f) {
                builder.addFieldFloat32(3, f, 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) {
                Attribute2.startAttribute(builder);
                Attribute2.addName(builder, nameOffset);
                Attribute2.addDocString(builder, docStringOffset);
                Attribute2.addType(builder, type);
                Attribute2.addF(builder, f);
                Attribute2.addI(builder, i);
                Attribute2.addS(builder, sOffset);
                Attribute2.addT(builder, tOffset);
                Attribute2.addG(builder, gOffset);
                Attribute2.addFloats(builder, floatsOffset);
                Attribute2.addInts(builder, intsOffset);
                Attribute2.addStrings(builder, stringsOffset);
                Attribute2.addTensors(builder, tensorsOffset);
                Attribute2.addGraphs(builder, graphsOffset);
                return Attribute2.endAttribute(builder);
              }
            }
            fbs2.Attribute = Attribute2;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            class Graph2 {
              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 Graph2()).__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.SIZE_PREFIX_LENGTH);
                return (obj || new Graph2()).__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 onnxruntime2.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 onnxruntime2.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 onnxruntime2.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 onnxruntime2.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 onnxruntime2.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) {
                Graph2.startGraph(builder);
                Graph2.addInitializers(builder, initializersOffset);
                Graph2.addNodeArgs(builder, nodeArgsOffset);
                Graph2.addNodes(builder, nodesOffset);
                Graph2.addMaxNodeIndex(builder, maxNodeIndex);
                Graph2.addNodeEdges(builder, nodeEdgesOffset);
                Graph2.addInputs(builder, inputsOffset);
                Graph2.addOutputs(builder, outputsOffset);
                Graph2.addSparseInitializers(builder, sparseInitializersOffset);
                return Graph2.endGraph(builder);
              }
            }
            fbs2.Graph = Graph2;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            class Model2 {
              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 Model2()).__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.SIZE_PREFIX_LENGTH);
                return (obj || new Model2()).__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 onnxruntime2.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 onnxruntime2.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) {
                Model2.startModel(builder);
                Model2.addIrVersion(builder, irVersion);
                Model2.addOpsetImport(builder, opsetImportOffset);
                Model2.addProducerName(builder, producerNameOffset);
                Model2.addProducerVersion(builder, producerVersionOffset);
                Model2.addDomain(builder, domainOffset);
                Model2.addModelVersion(builder, modelVersion);
                Model2.addDocString(builder, docStringOffset);
                Model2.addGraph(builder, graphOffset);
                Model2.addGraphDocString(builder, graphDocStringOffset);
                return Model2.endModel(builder);
              }
            }
            fbs2.Model = Model2;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            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.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);
              }
            }
            fbs2.KernelCreateInfos = KernelCreateInfos;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            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.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 onnxruntime2.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);
                return offset;
              }
              static createSubGraphSessionState(builder, graphIdOffset, sessionStateOffset) {
                SubGraphSessionState.startSubGraphSessionState(builder);
                SubGraphSessionState.addGraphId(builder, graphIdOffset);
                SubGraphSessionState.addSessionState(builder, sessionStateOffset);
                return SubGraphSessionState.endSubGraphSessionState(builder);
              }
            }
            fbs2.SubGraphSessionState = SubGraphSessionState;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            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.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 onnxruntime2.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 onnxruntime2.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);
              }
            }
            fbs2.SessionState = SessionState;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
      ((onnxruntime2) => {
        let experimental;
        ((experimental2) => {
          let fbs;
          ((fbs2) => {
            class InferenceSession7 {
              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 InferenceSession7()).__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.SIZE_PREFIX_LENGTH);
                return (obj || new InferenceSession7()).__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 onnxruntime2.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 onnxruntime2.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) {
                InferenceSession7.startInferenceSession(builder);
                InferenceSession7.addOrtVersion(builder, ortVersionOffset);
                InferenceSession7.addModel(builder, modelOffset);
                InferenceSession7.addSessionState(builder, sessionStateOffset);
                return InferenceSession7.endInferenceSession(builder);
              }
            }
            fbs2.InferenceSession = InferenceSession7;
          })(fbs = experimental2.fbs || (experimental2.fbs = {}));
        })(experimental = onnxruntime2.experimental || (onnxruntime2.experimental = {}));
      })(onnxruntime || (onnxruntime = {}));
    }
  });

  // web/node_modules/@protobufjs/aspromise/index.js
  var require_aspromise = __commonJS({
    "web/node_modules/@protobufjs/aspromise/index.js"(exports2, module2) {
      "use strict";
      module2.exports = asPromise;
      function asPromise(fn, ctx) {
        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) {
            if (pending) {
              pending = false;
              if (err)
                reject(err);
              else {
                var params2 = new Array(arguments.length - 1), offset2 = 0;
                while (offset2 < params2.length)
                  params2[offset2++] = arguments[offset2];
                resolve.apply(null, params2);
              }
            }
          };
          try {
            fn.apply(ctx || null, params);
          } catch (err) {
            if (pending) {
              pending = false;
              reject(err);
            }
          }
        });
      }
    }
  });

  // web/node_modules/@protobufjs/base64/index.js
  var require_base64 = __commonJS({
    "web/node_modules/@protobufjs/base64/index.js"(exports2) {
      "use strict";
      var base64 = exports2;
      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;
      };
      var b64 = new Array(64);
      var s64 = new Array(123);
      for (i = 0; i < 64; )
        s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;
      var i;
      base64.encode = function encode(buffer, start, end) {
        var parts = null, chunk = [];
        var i2 = 0, j = 0, t;
        while (start < end) {
          var b = buffer[start++];
          switch (j) {
            case 0:
              chunk[i2++] = b64[b >> 2];
              t = (b & 3) << 4;
              j = 1;
              break;
            case 1:
              chunk[i2++] = b64[t | b >> 4];
              t = (b & 15) << 2;
              j = 2;
              break;
            case 2:
              chunk[i2++] = b64[t | b >> 6];
              chunk[i2++] = b64[b & 63];
              j = 0;
              break;
          }
          if (i2 > 8191) {
            (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
            i2 = 0;
          }
        }
        if (j) {
          chunk[i2++] = b64[t];
          chunk[i2++] = 61;
          if (j === 1)
            chunk[i2++] = 61;
        }
        if (parts) {
          if (i2)
            parts.push(String.fromCharCode.apply(String, chunk.slice(0, i2)));
          return parts.join("");
        }
        return String.fromCharCode.apply(String, chunk.slice(0, i2));
      };
      var invalidEncoding = "invalid encoding";
      base64.decode = function decode(string, buffer, offset) {
        var start = offset;
        var j = 0, t;
        for (var i2 = 0; i2 < string.length; ) {
          var c = string.charCodeAt(i2++);
          if (c === 61 && j > 1)
            break;
          if ((c = s64[c]) === void 0)
            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;
      };
      base64.test = function test(string) {
        return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);
      };
    }
  });

  // web/node_modules/@protobufjs/eventemitter/index.js
  var require_eventemitter = __commonJS({
    "web/node_modules/@protobufjs/eventemitter/index.js"(exports2, module2) {
      "use strict";
      module2.exports = EventEmitter;
      function EventEmitter() {
        this._listeners = {};
      }
      EventEmitter.prototype.on = function on(evt, fn, ctx) {
        (this._listeners[evt] || (this._listeners[evt] = [])).push({
          fn,
          ctx: ctx || this
        });
        return this;
      };
      EventEmitter.prototype.off = function off(evt, fn) {
        if (evt === void 0)
          this._listeners = {};
        else {
          if (fn === void 0)
            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;
      };
      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;
      };
    }
  });

  // web/node_modules/@protobufjs/float/index.js
  var require_float = __commonJS({
    "web/node_modules/@protobufjs/float/index.js"(exports2, module2) {
      "use strict";
      module2.exports = factory(factory);
      function factory(exports3) {
        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];
            }
            exports3.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;
            exports3.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];
            }
            exports3.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;
            exports3.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;
          })();
        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 > 34028234663852886e22)
                writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);
              else if (val < 11754943508222875e-54)
                writeUint((sign << 31 | Math.round(val / 1401298464324817e-60)) >>> 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);
              }
            }
            exports3.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);
            exports3.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 ? sign * 1401298464324817e-60 * mantissa : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);
            }
            exports3.readFloatLE = readFloat_ieee754.bind(null, readUintLE);
            exports3.readFloatBE = readFloat_ieee754.bind(null, readUintBE);
          })();
        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];
            }
            exports3.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;
            exports3.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];
            }
            exports3.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;
            exports3.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;
          })();
        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 > 17976931348623157e292) {
                writeUint(0, buf, pos + off0);
                writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);
              } else {
                var mantissa;
                if (val < 22250738585072014e-324) {
                  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);
                }
              }
            }
            exports3.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);
            exports3.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 ? sign * 5e-324 * mantissa : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);
            }
            exports3.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);
            exports3.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);
          })();
        return exports3;
      }
      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;
      }
    }
  });

  // web/node_modules/@protobufjs/inquire/index.js
  var require_inquire = __commonJS({
    "web/node_modules/@protobufjs/inquire/index.js"(exports, module) {
      "use strict";
      module.exports = inquire;
      function inquire(moduleName) {
        try {
          var mod = eval("quire".replace(/^/, "re"))(moduleName);
          if (mod && (mod.length || Object.keys(mod).length))
            return mod;
        } catch (e) {
        }
        return null;
      }
    }
  });

  // web/node_modules/@protobufjs/utf8/index.js
  var require_utf8 = __commonJS({
    "web/node_modules/@protobufjs/utf8/index.js"(exports2) {
      "use strict";
      var utf8 = exports2;
      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 & 64512) === 55296 && (string.charCodeAt(i + 1) & 64512) === 56320) {
            ++i;
            len += 4;
          } else
            len += 3;
        }
        return len;
      };
      utf8.read = function utf8_read(buffer, start, end) {
        var len = end - start;
        if (len < 1)
          return "";
        var parts = null, chunk = [], i = 0, t;
        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) - 65536;
            chunk[i++] = 55296 + (t >> 10);
            chunk[i++] = 56320 + (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));
      };
      utf8.write = function utf8_write(string, buffer, offset) {
        var start = offset, c1, c2;
        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 & 64512) === 55296 && ((c2 = string.charCodeAt(i + 1)) & 64512) === 56320) {
            c1 = 65536 + ((c1 & 1023) << 10) + (c2 & 1023);
            ++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;
      };
    }
  });

  // web/node_modules/@protobufjs/pool/index.js
  var require_pool = __commonJS({
    "web/node_modules/@protobufjs/pool/index.js"(exports2, module2) {
      "use strict";
      module2.exports = pool;
      function pool(alloc, slice2, size) {
        var SIZE = size || 8192;
        var MAX = SIZE >>> 1;
        var slab = null;
        var offset = SIZE;
        return function pool_alloc(size2) {
          if (size2 < 1 || size2 > MAX)
            return alloc(size2);
          if (offset + size2 > SIZE) {
            slab = alloc(SIZE);
            offset = 0;
          }
          var buf = slice2.call(slab, offset, offset += size2);
          if (offset & 7)
            offset = (offset | 7) + 1;
          return buf;
        };
      }
    }
  });

  // web/node_modules/protobufjs/src/util/longbits.js
  var require_longbits = __commonJS({
    "web/node_modules/protobufjs/src/util/longbits.js"(exports2, module2) {
      "use strict";
      module2.exports = LongBits;
      var util = require_minimal();
      function LongBits(lo, hi) {
        this.lo = lo >>> 0;
        this.hi = hi >>> 0;
      }
      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;
      };
      var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0";
      LongBits.fromNumber = function fromNumber2(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);
      };
      LongBits.from = function from(value) {
        if (typeof value === "number")
          return LongBits.fromNumber(value);
        if (util.isString(value)) {
          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;
      };
      LongBits.prototype.toNumber = function toNumber2(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;
      };
      LongBits.prototype.toLong = function toLong(unsigned) {
        return util.Long ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };
      };
      var charCodeAt = String.prototype.charCodeAt;
      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
        );
      };
      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
        );
      };
      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;
      };
      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;
      };
      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;
      };
    }
  });

  // web/node_modules/protobufjs/src/util/minimal.js
  var require_minimal = __commonJS({
    "web/node_modules/protobufjs/src/util/minimal.js"(exports2) {
      "use strict";
      var util = exports2;
      util.asPromise = require_aspromise();
      util.base64 = require_base64();
      util.EventEmitter = require_eventemitter();
      util.float = require_float();
      util.inquire = require_inquire();
      util.utf8 = require_utf8();
      util.pool = require_pool();
      util.LongBits = require_longbits();
      util.isNode = Boolean(typeof global !== "undefined" && global && global.process && global.process.versions && global.process.versions.node);
      util.global = util.isNode && global || typeof window !== "undefined" && window || typeof self !== "undefined" && self || exports2;
      util.emptyArray = Object.freeze ? Object.freeze([]) : (
        /* istanbul ignore next */
        []
      );
      util.emptyObject = Object.freeze ? Object.freeze({}) : (
        /* istanbul ignore next */
        {}
      );
      util.isInteger = Number.isInteger || /* istanbul ignore next */
      function isInteger(value) {
        return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
      };
      util.isString = function isString(value) {
        return typeof value === "string" || value instanceof String;
      };
      util.isObject = function isObject(value) {
        return value && typeof value === "object";
      };
      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))
          return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;
        return false;
      };
      util.Buffer = function() {
        try {
          var Buffer2 = util.inquire("buffer").Buffer;
          return Buffer2.prototype.utf8Write ? Buffer2 : (
            /* istanbul ignore next */
            null
          );
        } catch (e) {
          return null;
        }
      }();
      util._Buffer_from = null;
      util._Buffer_allocUnsafe = null;
      util.newBuffer = function newBuffer(sizeOrArray) {
        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);
      };
      util.Array = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
      util.Long = /* istanbul ignore next */
      util.global.dcodeIO && /* istanbul ignore next */
      util.global.dcodeIO.Long || /* istanbul ignore next */
      util.global.Long || util.inquire("long");
      util.key2Re = /^true|false|0|1$/;
      util.key32Re = /^-?(?:0|[1-9][0-9]*)$/;
      util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;
      util.longToHash = function longToHash(value) {
        return value ? util.LongBits.from(value).toHash() : util.LongBits.zeroHash;
      };
      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));
      };
      function merge(dst, src, ifNotSet) {
        for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)
          if (dst[keys[i]] === void 0 || !ifNotSet)
            dst[keys[i]] = src[keys[i]];
        return dst;
      }
      util.merge = merge;
      util.lcFirst = function lcFirst(str) {
        return str.charAt(0).toLowerCase() + str.substring(1);
      };
      function newError(name2) {
        function CustomError(message, properties) {
          if (!(this instanceof CustomError))
            return new CustomError(message, properties);
          Object.defineProperty(this, "message", { get: function() {
            return message;
          } });
          if (Error.captureStackTrace)
            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: {
            value: CustomError,
            writable: true,
            enumerable: false,
            configurable: true
          },
          name: {
            get: function get() {
              return name2;
            },
            set: void 0,
            enumerable: false,
            // configurable: false would accurately preserve the behavior of
            // the original, but I'm guessing that was not intentional.
            // For an actual error subclass, this property would
            // be configurable.
            configurable: true
          },
          toString: {
            value: function value() {
              return this.name + ": " + this.message;
            },
            writable: true,
            enumerable: false,
            configurable: true
          }
        });
        return CustomError;
      }
      util.newError = newError;
      util.ProtocolError = newError("ProtocolError");
      util.oneOfGetter = function getOneOf(fieldNames) {
        var fieldMap = {};
        for (var i = 0; i < fieldNames.length; ++i)
          fieldMap[fieldNames[i]] = 1;
        return function() {
          for (var keys = Object.keys(this), i2 = keys.length - 1; i2 > -1; --i2)
            if (fieldMap[keys[i2]] === 1 && this[keys[i2]] !== void 0 && this[keys[i2]] !== null)
              return keys[i2];
        };
      };
      util.oneOfSetter = function setOneOf(fieldNames) {
        return function(name2) {
          for (var i = 0; i < fieldNames.length; ++i)
            if (fieldNames[i] !== name2)
              delete this[fieldNames[i]];
        };
      };
      util.toJSONOptions = {
        longs: String,
        enums: String,
        bytes: String,
        json: true
      };
      util._configure = function() {
        var Buffer2 = util.Buffer;
        if (!Buffer2) {
          util._Buffer_from = util._Buffer_allocUnsafe = null;
          return;
        }
        util._Buffer_from = Buffer2.from !== Uint8Array.from && Buffer2.from || /* istanbul ignore next */
        function Buffer_from(value, encoding) {
          return new Buffer2(value, encoding);
        };
        util._Buffer_allocUnsafe = Buffer2.allocUnsafe || /* istanbul ignore next */
        function Buffer_allocUnsafe(size) {
          return new Buffer2(size);
        };
      };
    }
  });

  // web/node_modules/protobufjs/src/writer.js
  var require_writer = __commonJS({
    "web/node_modules/protobufjs/src/writer.js"(exports2, module2) {
      "use strict";
      module2.exports = Writer;
      var util = require_minimal();
      var BufferWriter;
      var LongBits = util.LongBits;
      var base64 = util.base64;
      var utf8 = util.utf8;
      function Op(fn, len, val) {
        this.fn = fn;
        this.len = len;
        this.next = void 0;
        this.val = val;
      }
      function noop() {
      }
      function State(writer) {
        this.head = writer.head;
        this.tail = writer.tail;
        this.len = writer.len;
        this.next = writer.states;
      }
      function Writer() {
        this.len = 0;
        this.head = new Op(noop, 0, 0);
        this.tail = this.head;
        this.states = null;
      }
      var create = function create2() {
        return util.Buffer ? function create_buffer_setup() {
          return (Writer.create = function create_buffer() {
            return new BufferWriter();
          })();
        } : function create_array() {
          return new Writer();
        };
      };
      Writer.create = create();
      Writer.alloc = function alloc(size) {
        return new util.Array(size);
      };
      if (util.Array !== Array)
        Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);
      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;
      }
      function VarintOp(len, val) {
        this.len = len;
        this.next = void 0;
        this.val = val;
      }
      VarintOp.prototype = Object.create(Op.prototype);
      VarintOp.prototype.fn = writeVarint32;
      Writer.prototype.uint32 = function write_uint32(value) {
        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;
      };
      Writer.prototype.int32 = function write_int32(value) {
        return value < 0 ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) : this.uint32(value);
      };
      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;
      }
      Writer.prototype.uint64 = function write_uint64(value) {
        var bits = LongBits.from(value);
        return this._push(writeVarint64, bits.length(), bits);
      };
      Writer.prototype.int64 = Writer.prototype.uint64;
      Writer.prototype.sint64 = function write_sint64(value) {
        var bits = LongBits.from(value).zzEncode();
        return this._push(writeVarint64, bits.length(), bits);
      };
      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;
      }
      Writer.prototype.fixed32 = function write_fixed32(value) {
        return this._push(writeFixed32, 4, value >>> 0);
      };
      Writer.prototype.sfixed32 = Writer.prototype.fixed32;
      Writer.prototype.fixed64 = function write_fixed64(value) {
        var bits = LongBits.from(value);
        return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);
      };
      Writer.prototype.sfixed64 = Writer.prototype.fixed64;
      Writer.prototype.float = function write_float(value) {
        return this._push(util.float.writeFloatLE, 4, value);
      };
      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);
      } : function writeBytes_for(val, buf, pos) {
        for (var i = 0; i < val.length; ++i)
          buf[pos + i] = val[i];
      };
      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);
      };
      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);
      };
      Writer.prototype.fork = function fork() {
        this.states = new State(this);
        this.head = this.tail = new Op(noop, 0, 0);
        this.len = 0;
        return 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;
      };
      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;
          this.tail = tail;
          this.len += len;
        }
        return this;
      };
      Writer.prototype.finish = function finish() {
        var head = this.head.next, buf = this.constructor.alloc(this.len), pos = 0;
        while (head) {
          head.fn(head.val, buf, pos);
          pos += head.len;
          head = head.next;
        }
        return buf;
      };
      Writer._configure = function(BufferWriter_) {
        BufferWriter = BufferWriter_;
        Writer.create = create();
        BufferWriter._configure();
      };
    }
  });

  // web/node_modules/protobufjs/src/writer_buffer.js
  var require_writer_buffer = __commonJS({
    "web/node_modules/protobufjs/src/writer_buffer.js"(exports2, module2) {
      "use strict";
      module2.exports = BufferWriter;
      var Writer = require_writer();
      (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;
      var util = require_minimal();
      function BufferWriter() {
        Writer.call(this);
      }
      BufferWriter._configure = function() {
        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);
        } : function writeBytesBuffer_copy(val, buf, pos) {
          if (val.copy)
            val.copy(buf, pos, 0, val.length);
          else
            for (var i = 0; i < val.length; )
              buf[pos++] = val[i++];
        };
      };
      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)
          util.utf8.write(val, buf, pos);
        else if (buf.utf8Write)
          buf.utf8Write(val, pos);
        else
          buf.write(val, pos);
      }
      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;
      };
      BufferWriter._configure();
    }
  });

  // web/node_modules/protobufjs/src/reader.js
  var require_reader = __commonJS({
    "web/node_modules/protobufjs/src/reader.js"(exports2, module2) {
      "use strict";
      module2.exports = Reader;
      var util = require_minimal();
      var BufferReader;
      var LongBits = util.LongBits;
      var utf8 = util.utf8;
      function indexOutOfRange(reader, writeLength) {
        return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len);
      }
      function Reader(buffer) {
        this.buf = buffer;
        this.pos = 0;
        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");
      } : function create_array2(buffer) {
        if (Array.isArray(buffer))
          return new Reader(buffer);
        throw Error("illegal buffer");
      };
      var create = function create2() {
        return util.Buffer ? function create_buffer_setup(buffer) {
          return (Reader.create = function create_buffer(buffer2) {
            return util.Buffer.isBuffer(buffer2) ? new BufferReader(buffer2) : create_array(buffer2);
          })(buffer);
        } : create_array;
      };
      Reader.create = create();
      Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */
      util.Array.prototype.slice;
      Reader.prototype.uint32 = function read_uint32_setup() {
        var value = 4294967295;
        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;
          if ((this.pos += 5) > this.len) {
            this.pos = this.len;
            throw indexOutOfRange(this, 10);
          }
          return value;
        };
      }();
      Reader.prototype.int32 = function read_int32() {
        return this.uint32() | 0;
      };
      Reader.prototype.sint32 = function read_sint32() {
        var value = this.uint32();
        return value >>> 1 ^ -(value & 1) | 0;
      };
      function readLongVarint() {
        var bits = new LongBits(0, 0);
        var i = 0;
        if (this.len - this.pos > 4) {
          for (; i < 4; ++i) {
            bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
            if (this.buf[this.pos++] < 128)
              return bits;
          }
          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) {
            if (this.pos >= this.len)
              throw indexOutOfRange(this);
            bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
            if (this.buf[this.pos++] < 128)
              return bits;
          }
          bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;
          return bits;
        }
        if (this.len - this.pos > 4) {
          for (; i < 5; ++i) {
            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) {
            if (this.pos >= this.len)
              throw indexOutOfRange(this);
            bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
            if (this.buf[this.pos++] < 128)
              return bits;
          }
        }
        throw Error("invalid varint encoding");
      }
      Reader.prototype.bool = function read_bool() {
        return this.uint32() !== 0;
      };
      function readFixed32_end(buf, end) {
        return (buf[end - 4] | buf[end - 3] << 8 | buf[end - 2] << 16 | buf[end - 1] << 24) >>> 0;
      }
      Reader.prototype.fixed32 = function read_fixed32() {
        if (this.pos + 4 > this.len)
          throw indexOutOfRange(this, 4);
        return readFixed32_end(this.buf, this.pos += 4);
      };
      Reader.prototype.sfixed32 = function read_sfixed32() {
        if (this.pos + 4 > this.len)
          throw indexOutOfRange(this, 4);
        return readFixed32_end(this.buf, this.pos += 4) | 0;
      };
      function readFixed64() {
        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));
      }
      Reader.prototype.float = function read_float() {
        if (this.pos + 4 > this.len)
          throw indexOutOfRange(this, 4);
        var value = util.float.readFloatLE(this.buf, this.pos);
        this.pos += 4;
        return value;
      };
      Reader.prototype.double = function read_double() {
        if (this.pos + 8 > this.len)
          throw indexOutOfRange(this, 4);
        var value = util.float.readDoubleLE(this.buf, this.pos);
        this.pos += 8;
        return value;
      };
      Reader.prototype.bytes = function read_bytes() {
        var length = this.uint32(), start = this.pos, end = this.pos + length;
        if (end > this.len)
          throw indexOutOfRange(this, length);
        this.pos += length;
        if (Array.isArray(this.buf))
          return this.buf.slice(start, end);
        if (start === end) {
          var nativeBuffer = util.Buffer;
          return nativeBuffer ? nativeBuffer.alloc(0) : new this.buf.constructor(0);
        }
        return this._slice.call(this.buf, start, end);
      };
      Reader.prototype.string = function read_string() {
        var bytes = this.bytes();
        return utf8.read(bytes, 0, bytes.length);
      };
      Reader.prototype.skip = function skip(length) {
        if (typeof length === "number") {
          if (this.pos + length > this.len)
            throw indexOutOfRange(this, length);
          this.pos += length;
        } else {
          do {
            if (this.pos >= this.len)
              throw indexOutOfRange(this);
          } while (this.buf[this.pos++] & 128);
        }
        return 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;
          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);
          }
        });
      };
    }
  });

  // web/node_modules/protobufjs/src/reader_buffer.js
  var require_reader_buffer = __commonJS({
    "web/node_modules/protobufjs/src/reader_buffer.js"(exports2, module2) {
      "use strict";
      module2.exports = BufferReader;
      var Reader = require_reader();
      (BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;
      var util = require_minimal();
      function BufferReader(buffer) {
        Reader.call(this, buffer);
      }
      BufferReader._configure = function() {
        if (util.Buffer)
          BufferReader.prototype._slice = util.Buffer.prototype.slice;
      };
      BufferReader.prototype.string = function read_string_buffer() {
        var len = this.uint32();
        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));
      };
      BufferReader._configure();
    }
  });

  // web/node_modules/protobufjs/src/rpc/service.js
  var require_service = __commonJS({
    "web/node_modules/protobufjs/src/rpc/service.js"(exports2, module2) {
      "use strict";
      module2.exports = Service;
      var util = require_minimal();
      (Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;
      function Service(rpcImpl, requestDelimited, responseDelimited) {
        if (typeof rpcImpl !== "function")
          throw TypeError("rpcImpl must be a function");
        util.EventEmitter.call(this);
        this.rpcImpl = rpcImpl;
        this.requestDelimited = Boolean(requestDelimited);
        this.responseDelimited = Boolean(responseDelimited);
      }
      Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {
        if (!request)
          throw TypeError("request must be specified");
        var self2 = this;
        if (!callback)
          return util.asPromise(rpcCall, self2, method, requestCtor, responseCtor, request);
        if (!self2.rpcImpl) {
          setTimeout(function() {
            callback(Error("already ended"));
          }, 0);
          return void 0;
        }
        try {
          return self2.rpcImpl(
            method,
            requestCtor[self2.requestDelimited ? "encodeDelimited" : "encode"](request).finish(),
            function rpcCallback(err, response) {
              if (err) {
                self2.emit("error", err, method);
                return callback(err);
              }
              if (response === null) {
                self2.end(
                  /* endedByRPC */
                  true
                );
                return void 0;
              }
              if (!(response instanceof responseCtor)) {
                try {
                  response = responseCtor[self2.responseDelimited ? "decodeDelimited" : "decode"](response);
                } catch (err2) {
                  self2.emit("error", err2, method);
                  return callback(err2);
                }
              }
              self2.emit("data", response, method);
              return callback(null, response);
            }
          );
        } catch (err) {
          self2.emit("error", err, method);
          setTimeout(function() {
            callback(err);
          }, 0);
          return void 0;
        }
      };
      Service.prototype.end = function end(endedByRPC) {
        if (this.rpcImpl) {
          if (!endedByRPC)
            this.rpcImpl(null, null, null);
          this.rpcImpl = null;
          this.emit("end").off();
        }
        return this;
      };
    }
  });

  // web/node_modules/protobufjs/src/rpc.js
  var require_rpc = __commonJS({
    "web/node_modules/protobufjs/src/rpc.js"(exports2) {
      "use strict";
      var rpc = exports2;
      rpc.Service = require_service();
    }
  });

  // web/node_modules/protobufjs/src/roots.js
  var require_roots = __commonJS({
    "web/node_modules/protobufjs/src/roots.js"(exports2, module2) {
      "use strict";
      module2.exports = {};
    }
  });

  // web/node_modules/protobufjs/src/index-minimal.js
  var require_index_minimal = __commonJS({
    "web/node_modules/protobufjs/src/index-minimal.js"(exports2) {
      "use strict";
      var protobuf = exports2;
      protobuf.build = "minimal";
      protobuf.Writer = require_writer();
      protobuf.BufferWriter = require_writer_buffer();
      protobuf.Reader = require_reader();
      protobuf.BufferReader = require_reader_buffer();
      protobuf.util = require_minimal();
      protobuf.rpc = require_rpc();
      protobuf.roots = require_roots();
      protobuf.configure = configure;
      function configure() {
        protobuf.util._configure();
        protobuf.Writer._configure(protobuf.BufferWriter);
        protobuf.Reader._configure(protobuf.BufferReader);
      }
      configure();
    }
  });

  // web/node_modules/protobufjs/minimal.js
  var require_minimal2 = __commonJS({
    "web/node_modules/protobufjs/minimal.js"(exports2, module2) {
      "use strict";
      module2.exports = require_index_minimal();
    }
  });

  // web/lib/onnxjs/ort-schema/protobuf/onnx.js
  var require_onnx = __commonJS({
    "web/lib/onnxjs/ort-schema/protobuf/onnx.js"(exports2, module2) {
      "use strict";
      var $protobuf = require_minimal2();
      var $Reader = $protobuf.Reader;
      var $Writer = $protobuf.Writer;
      var $util = $protobuf.util;
      var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {});
      $root.onnx = function() {
        var onnx6 = {};
        onnx6.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_2019_3_18"] = 5;
          values[valuesById[6] = "IR_VERSION_2019_9_19"] = 6;
          values[valuesById[7] = "IR_VERSION_2020_5_8"] = 7;
          values[valuesById[8] = "IR_VERSION_2021_7_30"] = 8;
          values[valuesById[9] = "IR_VERSION"] = 9;
          return values;
        }();
        onnx6.AttributeProto = function() {
          function AttributeProto(properties) {
            this.floats = [];
            this.ints = [];
            this.strings = [];
            this.tensors = [];
            this.graphs = [];
            this.sparseTensors = [];
            this.typeProtos = [];
            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.prototype.name = "";
          AttributeProto.prototype.refAttrName = "";
          AttributeProto.prototype.docString = "";
          AttributeProto.prototype.type = 0;
          AttributeProto.prototype.f = 0;
          AttributeProto.prototype.i = $util.Long ? $util.Long.fromBits(0, 0, false) : 0;
          AttributeProto.prototype.s = $util.newBuffer([]);
          AttributeProto.prototype.t = null;
          AttributeProto.prototype.g = null;
          AttributeProto.prototype.sparseTensor = null;
          AttributeProto.prototype.tp = null;
          AttributeProto.prototype.floats = $util.emptyArray;
          AttributeProto.prototype.ints = $util.emptyArray;
          AttributeProto.prototype.strings = $util.emptyArray;
          AttributeProto.prototype.tensors = $util.emptyArray;
          AttributeProto.prototype.graphs = $util.emptyArray;
          AttributeProto.prototype.sparseTensors = $util.emptyArray;
          AttributeProto.prototype.typeProtos = $util.emptyArray;
          AttributeProto.create = function create(properties) {
            return new AttributeProto(properties);
          };
          AttributeProto.encode = function encode(message, writer) {
            if (!writer)
              writer = $Writer.create();
            if (message.name != null && Object.hasOwnProperty.call(message, "name"))
              writer.uint32(
                /* id 1, wireType 2 =*/
                10
              ).string(message.name);
            if (message.f != null && Object.hasOwnProperty.call(message, "f"))
              writer.uint32(
                /* id 2, wireType 5 =*/
                21
              ).float(message.f);
            if (message.i != null && Object.hasOwnProperty.call(message, "i"))
              writer.uint32(
                /* id 3, wireType 0 =*/
                24
              ).int64(message.i);
            if (message.s != null && Object.hasOwnProperty.call(message, "s"))
              writer.uint32(
                /* id 4, wireType 2 =*/
                34
              ).bytes(message.s);
            if (message.t != null && Object.hasOwnProperty.call(message, "t"))
              $root.onnx.TensorProto.encode(message.t, writer.uint32(
                /* id 5, wireType 2 =*/
                42
              ).fork()).ldelim();
            if (message.g != null && Object.hasOwnProperty.call(message, "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 && Object.hasOwnProperty.call(message, "docString"))
              writer.uint32(
                /* id 13, wireType 2 =*/
                106
              ).string(message.docString);
            if (message.tp != null && Object.hasOwnProperty.call(message, "tp"))
              $root.onnx.TypeProto.encode(message.tp, writer.uint32(
                /* id 14, wireType 2 =*/
                114
              ).fork()).ldelim();
            if (message.typeProtos != null && message.typeProtos.length)
              for (var i = 0; i < message.typeProtos.length; ++i)
                $root.onnx.TypeProto.encode(message.typeProtos[i], writer.uint32(
                  /* id 15, wireType 2 =*/
                  122
                ).fork()).ldelim();
            if (message.type != null && Object.hasOwnProperty.call(message, "type"))
              writer.uint32(
                /* id 20, wireType 0 =*/
                160
              ).int32(message.type);
            if (message.refAttrName != null && Object.hasOwnProperty.call(message, "refAttrName"))
              writer.uint32(
                /* id 21, wireType 2 =*/
                170
              ).string(message.refAttrName);
            if (message.sparseTensor != null && Object.hasOwnProperty.call(message, "sparseTensor"))
              $root.onnx.SparseTensorProto.encode(message.sparseTensor, writer.uint32(
                /* id 22, wireType 2 =*/
                178
              ).fork()).ldelim();
            if (message.sparseTensors != null && message.sparseTensors.length)
              for (var i = 0; i < message.sparseTensors.length; ++i)
                $root.onnx.SparseTensorProto.encode(message.sparseTensors[i], writer.uint32(
                  /* id 23, wireType 2 =*/
                  186
                ).fork()).ldelim();
            return writer;
          };
          AttributeProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
          };
          AttributeProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
              reader = $Reader.create(reader);
            var end = length === void 0 ? 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 22: {
                  message.sparseTensor = $root.onnx.SparseTensorProto.decode(reader, reader.uint32());
                  break;
                }
                case 14: {
                  message.tp = $root.onnx.TypeProto.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;
                }
                case 23: {
                  if (!(message.sparseTensors && message.sparseTensors.length))
                    message.sparseTensors = [];
                  message.sparseTensors.push($root.onnx.SparseTensorProto.decode(reader, reader.uint32()));
                  break;
                }
                case 15: {
                  if (!(message.typeProtos && message.typeProtos.length))
                    message.typeProtos = [];
                  message.typeProtos.push($root.onnx.TypeProto.decode(reader, reader.uint32()));
                  break;
                }
                default:
                  reader.skipType(tag & 7);
                  break;
              }
            }
            return message;
          };
          AttributeProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
              reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
          };
          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 11:
                case 13:
                case 6:
                case 7:
                case 8:
                case 9:
                case 10:
                case 12:
                case 14:
                  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.sparseTensor != null && message.hasOwnProperty("sparseTensor")) {
              var error = $root.onnx.SparseTensorProto.verify(message.sparseTensor);
              if (error)
                return "sparseTensor." + error;
            }
            if (message.tp != null && message.hasOwnProperty("tp")) {
              var error = $root.onnx.TypeProto.verify(message.tp);
              if (error)
                return "tp." + 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;
              }
            }
            if (message.sparseTensors != null && message.hasOwnProperty("sparseTensors")) {
              if (!Array.isArray(message.sparseTensors))
                return "sparseTensors: array expected";
              for (var i = 0; i < message.sparseTensors.length; ++i) {
                var error = $root.onnx.SparseTensorProto.verify(message.sparseTensors[i]);
                if (error)
                  return "sparseTensors." + error;
              }
            }
            if (message.typeProtos != null && message.hasOwnProperty("typeProtos")) {
              if (!Array.isArray(message.typeProtos))
                return "typeProtos: array expected";
              for (var i = 0; i < message.typeProtos.length; ++i) {
                var error = $root.onnx.TypeProto.verify(message.typeProtos[i]);
                if (error)
                  return "typeProtos." + error;
              }
            }
            return null;
          };
          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) {
              default:
                if (typeof object.type === "number") {
                  message.type = object.type;
                  break;
                }
                break;
              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 "SPARSE_TENSOR":
              case 11:
                message.type = 11;
                break;
              case "TYPE_PROTO":
              case 13:
                message.type = 13;
                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;
              case "SPARSE_TENSORS":
              case 12:
                message.type = 12;
                break;
              case "TYPE_PROTOS":
              case 14:
                message.type = 14;
                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 >= 0)
                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.sparseTensor != null) {
              if (typeof object.sparseTensor !== "object")
                throw TypeError(".onnx.AttributeProto.sparseTensor: object expected");
              message.sparseTensor = $root.onnx.SparseTensorProto.fromObject(object.sparseTensor);
            }
            if (object.tp != null) {
              if (typeof object.tp !== "object")
                throw TypeError(".onnx.AttributeProto.tp: object expected");
              message.tp = $root.onnx.TypeProto.fromObject(object.tp);
            }
            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 >= 0)
                  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]);
              }
            }
            if (object.sparseTensors) {
              if (!Array.isArray(object.sparseTensors))
                throw TypeError(".onnx.AttributeProto.sparseTensors: array expected");
              message.sparseTensors = [];
              for (var i = 0; i < object.sparseTensors.length; ++i) {
                if (typeof object.sparseTensors[i] !== "object")
                  throw TypeError(".onnx.AttributeProto.sparseTensors: object expected");
                message.sparseTensors[i] = $root.onnx.SparseTensorProto.fromObject(object.sparseTensors[i]);
              }
            }
            if (object.typeProtos) {
              if (!Array.isArray(object.typeProtos))
                throw TypeError(".onnx.AttributeProto.typeProtos: array expected");
              message.typeProtos = [];
              for (var i = 0; i < object.typeProtos.length; ++i) {
                if (typeof object.typeProtos[i] !== "object")
                  throw TypeError(".onnx.AttributeProto.typeProtos: object expected");
                message.typeProtos[i] = $root.onnx.TypeProto.fromObject(object.typeProtos[i]);
              }
            }
            return message;
          };
          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 = [];
              object.typeProtos = [];
              object.sparseTensors = [];
            }
            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.tp = null;
              object.type = options.enums === String ? "UNDEFINED" : 0;
              object.refAttrName = "";
              object.sparseTensor = null;
            }
            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.tp != null && message.hasOwnProperty("tp"))
              object.tp = $root.onnx.TypeProto.toObject(message.tp, options);
            if (message.typeProtos && message.typeProtos.length) {
              object.typeProtos = [];
              for (var j = 0; j < message.typeProtos.length; ++j)
                object.typeProtos[j] = $root.onnx.TypeProto.toObject(message.typeProtos[j], options);
            }
            if (message.type != null && message.hasOwnProperty("type"))
              object.type = options.enums === String ? $root.onnx.AttributeProto.AttributeType[message.type] === void 0 ? message.type : $root.onnx.AttributeProto.AttributeType[message.type] : message.type;
            if (message.refAttrName != null && message.hasOwnProperty("refAttrName"))
              object.refAttrName = message.refAttrName;
            if (message.sparseTensor != null && message.hasOwnProperty("sparseTensor"))
              object.sparseTensor = $root.onnx.SparseTensorProto.toObject(message.sparseTensor, options);
            if (message.sparseTensors && message.sparseTensors.length) {
              object.sparseTensors = [];
              for (var j = 0; j < message.sparseTensors.length; ++j)
                object.sparseTensors[j] = $root.onnx.SparseTensorProto.toObject(message.sparseTensors[j], options);
            }
            return object;
          };
          AttributeProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
          };
          AttributeProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
            if (typeUrlPrefix === void 0) {
              typeUrlPrefix = "type.googleapis.com";
            }
            return typeUrlPrefix + "/onnx.AttributeProto";
          };
          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[11] = "SPARSE_TENSOR"] = 11;
            values[valuesById[13] = "TYPE_PROTO"] = 13;
            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;
            values[valuesById[12] = "SPARSE_TENSORS"] = 12;
            values[valuesById[14] = "TYPE_PROTOS"] = 14;
            return values;
          }();
          return AttributeProto;
        }();
        onnx6.ValueInfoProto = function() {
          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.prototype.name = "";
          ValueInfoProto.prototype.type = null;
          ValueInfoProto.prototype.docString = "";
          ValueInfoProto.create = function create(properties) {
            return new ValueInfoProto(properties);
          };
          ValueInfoProto.encode = function encode(message, writer) {
            if (!writer)
              writer = $Writer.create();
            if (message.name != null && Object.hasOwnProperty.call(message, "name"))
              writer.uint32(
                /* id 1, wireType 2 =*/
                10
              ).string(message.name);
            if (message.type != null && Object.hasOwnProperty.call(message, "type"))
              $root.onnx.TypeProto.encode(message.type, writer.uint32(
                /* id 2, wireType 2 =*/
                18
              ).fork()).ldelim();
            if (message.docString != null && Object.hasOwnProperty.call(message, "docString"))
              writer.uint32(
                /* id 3, wireType 2 =*/
                26
              ).string(message.docString);
            return writer;
          };
          ValueInfoProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
          };
          ValueInfoProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
              reader = $Reader.create(reader);
            var end = length === void 0 ? 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;
          };
          ValueInfoProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
              reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
          };
          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;
          };
          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;
          };
          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;
          };
          ValueInfoProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
          };
          ValueInfoProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
            if (typeUrlPrefix === void 0) {
              typeUrlPrefix = "type.googleapis.com";
            }
            return typeUrlPrefix + "/onnx.ValueInfoProto";
          };
          return ValueInfoProto;
        }();
        onnx6.NodeProto = function() {
          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.prototype.input = $util.emptyArray;
          NodeProto.prototype.output = $util.emptyArray;
          NodeProto.prototype.name = "";
          NodeProto.prototype.opType = "";
          NodeProto.prototype.domain = "";
          NodeProto.prototype.attribute = $util.emptyArray;
          NodeProto.prototype.docString = "";
          NodeProto.create = function create(properties) {
            return new NodeProto(properties);
          };
          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 && Object.hasOwnProperty.call(message, "name"))
              writer.uint32(
                /* id 3, wireType 2 =*/
                26
              ).string(message.name);
            if (message.opType != null && Object.hasOwnProperty.call(message, "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 && Object.hasOwnProperty.call(message, "docString"))
              writer.uint32(
                /* id 6, wireType 2 =*/
                50
              ).string(message.docString);
            if (message.domain != null && Object.hasOwnProperty.call(message, "domain"))
              writer.uint32(
                /* id 7, wireType 2 =*/
                58
              ).string(message.domain);
            return writer;
          };
          NodeProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
          };
          NodeProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
              reader = $Reader.create(reader);
            var end = length === void 0 ? 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;
          };
          NodeProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
              reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
          };
          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;
          };
          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;
          };
          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;
          };
          NodeProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
          };
          NodeProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
            if (typeUrlPrefix === void 0) {
              typeUrlPrefix = "type.googleapis.com";
            }
            return typeUrlPrefix + "/onnx.NodeProto";
          };
          return NodeProto;
        }();
        onnx6.TrainingInfoProto = function() {
          function TrainingInfoProto(properties) {
            this.initializationBinding = [];
            this.updateBinding = [];
            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]];
            }
          }
          TrainingInfoProto.prototype.initialization = null;
          TrainingInfoProto.prototype.algorithm = null;
          TrainingInfoProto.prototype.initializationBinding = $util.emptyArray;
          TrainingInfoProto.prototype.updateBinding = $util.emptyArray;
          TrainingInfoProto.create = function create(properties) {
            return new TrainingInfoProto(properties);
          };
          TrainingInfoProto.encode = function encode(message, writer) {
            if (!writer)
              writer = $Writer.create();
            if (message.initialization != null && Object.hasOwnProperty.call(message, "initialization"))
              $root.onnx.GraphProto.encode(message.initialization, writer.uint32(
                /* id 1, wireType 2 =*/
                10
              ).fork()).ldelim();
            if (message.algorithm != null && Object.hasOwnProperty.call(message, "algorithm"))
              $root.onnx.GraphProto.encode(message.algorithm, writer.uint32(
                /* id 2, wireType 2 =*/
                18
              ).fork()).ldelim();
            if (message.initializationBinding != null && message.initializationBinding.length)
              for (var i = 0; i < message.initializationBinding.length; ++i)
                $root.onnx.StringStringEntryProto.encode(message.initializationBinding[i], writer.uint32(
                  /* id 3, wireType 2 =*/
                  26
                ).fork()).ldelim();
            if (message.updateBinding != null && message.updateBinding.length)
              for (var i = 0; i < message.updateBinding.length; ++i)
                $root.onnx.StringStringEntryProto.encode(message.updateBinding[i], writer.uint32(
                  /* id 4, wireType 2 =*/
                  34
                ).fork()).ldelim();
            return writer;
          };
          TrainingInfoProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
          };
          TrainingInfoProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
              reader = $Reader.create(reader);
            var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.onnx.TrainingInfoProto();
            while (reader.pos < end) {
              var tag = reader.uint32();
              switch (tag >>> 3) {
                case 1: {
                  message.initialization = $root.onnx.GraphProto.decode(reader, reader.uint32());
                  break;
                }
                case 2: {
                  message.algorithm = $root.onnx.GraphProto.decode(reader, reader.uint32());
                  break;
                }
                case 3: {
                  if (!(message.initializationBinding && message.initializationBinding.length))
                    message.initializationBinding = [];
                  message.initializationBinding.push($root.onnx.StringStringEntryProto.decode(reader, reader.uint32()));
                  break;
                }
                case 4: {
                  if (!(message.updateBinding && message.updateBinding.length))
                    message.updateBinding = [];
                  message.updateBinding.push($root.onnx.StringStringEntryProto.decode(reader, reader.uint32()));
                  break;
                }
                default:
                  reader.skipType(tag & 7);
                  break;
              }
            }
            return message;
          };
          TrainingInfoProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
              reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
          };
          TrainingInfoProto.verify = function verify(message) {
            if (typeof message !== "object" || message === null)
              return "object expected";
            if (message.initialization != null && message.hasOwnProperty("initialization")) {
              var error = $root.onnx.GraphProto.verify(message.initialization);
              if (error)
                return "initialization." + error;
            }
            if (message.algorithm != null && message.hasOwnProperty("algorithm")) {
              var error = $root.onnx.GraphProto.verify(message.algorithm);
              if (error)
                return "algorithm." + error;
            }
            if (message.initializationBinding != null && message.hasOwnProperty("initializationBinding")) {
              if (!Array.isArray(message.initializationBinding))
                return "initializationBinding: array expected";
              for (var i = 0; i < message.initializationBinding.length; ++i) {
                var error = $root.onnx.StringStringEntryProto.verify(message.initializationBinding[i]);
                if (error)
                  return "initializationBinding." + error;
              }
            }
            if (message.updateBinding != null && message.hasOwnProperty("updateBinding")) {
              if (!Array.isArray(message.updateBinding))
                return "updateBinding: array expected";
              for (var i = 0; i < message.updateBinding.length; ++i) {
                var error = $root.onnx.StringStringEntryProto.verify(message.updateBinding[i]);
                if (error)
                  return "updateBinding." + error;
              }
            }
            return null;
          };
          TrainingInfoProto.fromObject = function fromObject(object) {
            if (object instanceof $root.onnx.TrainingInfoProto)
              return object;
            var message = new $root.onnx.TrainingInfoProto();
            if (object.initialization != null) {
              if (typeof object.initialization !== "object")
                throw TypeError(".onnx.TrainingInfoProto.initialization: object expected");
              message.initialization = $root.onnx.GraphProto.fromObject(object.initialization);
            }
            if (object.algorithm != null) {
              if (typeof object.algorithm !== "object")
                throw TypeError(".onnx.TrainingInfoProto.algorithm: object expected");
              message.algorithm = $root.onnx.GraphProto.fromObject(object.algorithm);
            }
            if (object.initializationBinding) {
              if (!Array.isArray(object.initializationBinding))
                throw TypeError(".onnx.TrainingInfoProto.initializationBinding: array expected");
              message.initializationBinding = [];
              for (var i = 0; i < object.initializationBinding.length; ++i) {
                if (typeof object.initializationBinding[i] !== "object")
                  throw TypeError(".onnx.TrainingInfoProto.initializationBinding: object expected");
                message.initializationBinding[i] = $root.onnx.StringStringEntryProto.fromObject(object.initializationBinding[i]);
              }
            }
            if (object.updateBinding) {
              if (!Array.isArray(object.updateBinding))
                throw TypeError(".onnx.TrainingInfoProto.updateBinding: array expected");
              message.updateBinding = [];
              for (var i = 0; i < object.updateBinding.length; ++i) {
                if (typeof object.updateBinding[i] !== "object")
                  throw TypeError(".onnx.TrainingInfoProto.updateBinding: object expected");
                message.updateBinding[i] = $root.onnx.StringStringEntryProto.fromObject(object.updateBinding[i]);
              }
            }
            return message;
          };
          TrainingInfoProto.toObject = function toObject(message, options) {
            if (!options)
              options = {};
            var object = {};
            if (options.arrays || options.defaults) {
              object.initializationBinding = [];
              object.updateBinding = [];
            }
            if (options.defaults) {
              object.initialization = null;
              object.algorithm = null;
            }
            if (message.initialization != null && message.hasOwnProperty("initialization"))
              object.initialization = $root.onnx.GraphProto.toObject(message.initialization, options);
            if (message.algorithm != null && message.hasOwnProperty("algorithm"))
              object.algorithm = $root.onnx.GraphProto.toObject(message.algorithm, options);
            if (message.initializationBinding && message.initializationBinding.length) {
              object.initializationBinding = [];
              for (var j = 0; j < message.initializationBinding.length; ++j)
                object.initializationBinding[j] = $root.onnx.StringStringEntryProto.toObject(message.initializationBinding[j], options);
            }
            if (message.updateBinding && message.updateBinding.length) {
              object.updateBinding = [];
              for (var j = 0; j < message.updateBinding.length; ++j)
                object.updateBinding[j] = $root.onnx.StringStringEntryProto.toObject(message.updateBinding[j], options);
            }
            return object;
          };
          TrainingInfoProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
          };
          TrainingInfoProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
            if (typeUrlPrefix === void 0) {
              typeUrlPrefix = "type.googleapis.com";
            }
            return typeUrlPrefix + "/onnx.TrainingInfoProto";
          };
          return TrainingInfoProto;
        }();
        onnx6.ModelProto = function() {
          function ModelProto(properties) {
            this.opsetImport = [];
            this.metadataProps = [];
            this.trainingInfo = [];
            this.functions = [];
            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.prototype.irVersion = $util.Long ? $util.Long.fromBits(0, 0, false) : 0;
          ModelProto.prototype.opsetImport = $util.emptyArray;
          ModelProto.prototype.producerName = "";
          ModelProto.prototype.producerVersion = "";
          ModelProto.prototype.domain = "";
          ModelProto.prototype.modelVersion = $util.Long ? $util.Long.fromBits(0, 0, false) : 0;
          ModelProto.prototype.docString = "";
          ModelProto.prototype.graph = null;
          ModelProto.prototype.metadataProps = $util.emptyArray;
          ModelProto.prototype.trainingInfo = $util.emptyArray;
          ModelProto.prototype.functions = $util.emptyArray;
          ModelProto.create = function create(properties) {
            return new ModelProto(properties);
          };
          ModelProto.encode = function encode(message, writer) {
            if (!writer)
              writer = $Writer.create();
            if (message.irVersion != null && Object.hasOwnProperty.call(message, "irVersion"))
              writer.uint32(
                /* id 1, wireType 0 =*/
                8
              ).int64(message.irVersion);
            if (message.producerName != null && Object.hasOwnProperty.call(message, "producerName"))
              writer.uint32(
                /* id 2, wireType 2 =*/
                18
              ).string(message.producerName);
            if (message.producerVersion != null && Object.hasOwnProperty.call(message, "producerVersion"))
              writer.uint32(
                /* id 3, wireType 2 =*/
                26
              ).string(message.producerVersion);
            if (message.domain != null && Object.hasOwnProperty.call(message, "domain"))
              writer.uint32(
                /* id 4, wireType 2 =*/
                34
              ).string(message.domain);
            if (message.modelVersion != null && Object.hasOwnProperty.call(message, "modelVersion"))
              writer.uint32(
                /* id 5, wireType 0 =*/
                40
              ).int64(message.modelVersion);
            if (message.docString != null && Object.hasOwnProperty.call(message, "docString"))
              writer.uint32(
                /* id 6, wireType 2 =*/
                50
              ).string(message.docString);
            if (message.graph != null && Object.hasOwnProperty.call(message, "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();
            if (message.trainingInfo != null && message.trainingInfo.length)
              for (var i = 0; i < message.trainingInfo.length; ++i)
                $root.onnx.TrainingInfoProto.encode(message.trainingInfo[i], writer.uint32(
                  /* id 20, wireType 2 =*/
                  162
                ).fork()).ldelim();
            if (message.functions != null && message.functions.length)
              for (var i = 0; i < message.functions.length; ++i)
                $root.onnx.FunctionProto.encode(message.functions[i], writer.uint32(
                  /* id 25, wireType 2 =*/
                  202
                ).fork()).ldelim();
            return writer;
          };
          ModelProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
          };
          ModelProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
              reader = $Reader.create(reader);
            var end = length === void 0 ? 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;
                }
                case 20: {
                  if (!(message.trainingInfo && message.trainingInfo.length))
                    message.trainingInfo = [];
                  message.trainingInfo.push($root.onnx.TrainingInfoProto.decode(reader, reader.uint32()));
                  break;
                }
                case 25: {
                  if (!(message.functions && message.functions.length))
                    message.functions = [];
                  message.functions.push($root.onnx.FunctionProto.decode(reader, reader.uint32()));
                  break;
                }
                default:
                  reader.skipType(tag & 7);
                  break;
              }
            }
            return message;
          };
          ModelProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
              reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
          };
          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;
              }
            }
            if (message.trainingInfo != null && message.hasOwnProperty("trainingInfo")) {
              if (!Array.isArray(message.trainingInfo))
                return "trainingInfo: array expected";
              for (var i = 0; i < message.trainingInfo.length; ++i) {
                var error = $root.onnx.TrainingInfoProto.verify(message.trainingInfo[i]);
                if (error)
                  return "trainingInfo." + error;
              }
            }
            if (message.functions != null && message.hasOwnProperty("functions")) {
              if (!Array.isArray(message.functions))
                return "functions: array expected";
              for (var i = 0; i < message.functions.length; ++i) {
                var error = $root.onnx.FunctionProto.verify(message.functions[i]);
                if (error)
                  return "functions." + error;
              }
            }
            return null;
          };
          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]);
              }
            }
            if (object.trainingInfo) {
              if (!Array.isArray(object.trainingInfo))
                throw TypeError(".onnx.ModelProto.trainingInfo: array expected");
              message.trainingInfo = [];
              for (var i = 0; i < object.trainingInfo.length; ++i) {
                if (typeof object.trainingInfo[i] !== "object")
                  throw TypeError(".onnx.ModelProto.trainingInfo: object expected");
                message.trainingInfo[i] = $root.onnx.TrainingInfoProto.fromObject(object.trainingInfo[i]);
              }
            }
            if (object.functions) {
              if (!Array.isArray(object.functions))
                throw TypeError(".onnx.ModelProto.functions: array expected");
              message.functions = [];
              for (var i = 0; i < object.functions.length; ++i) {
                if (typeof object.functions[i] !== "object")
                  throw TypeError(".onnx.ModelProto.functions: object expected");
                message.functions[i] = $root.onnx.FunctionProto.fromObject(object.functions[i]);
              }
            }
            return message;
          };
          ModelProto.toObject = function toObject(message, options) {
            if (!options)
              options = {};
            var object = {};
            if (options.arrays || options.defaults) {
              object.opsetImport = [];
              object.metadataProps = [];
              object.trainingInfo = [];
              object.functions = [];
            }
            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);
            }
            if (message.trainingInfo && message.trainingInfo.length) {
              object.trainingInfo = [];
              for (var j = 0; j < message.trainingInfo.length; ++j)
                object.trainingInfo[j] = $root.onnx.TrainingInfoProto.toObject(message.trainingInfo[j], options);
            }
            if (message.functions && message.functions.length) {
              object.functions = [];
              for (var j = 0; j < message.functions.length; ++j)
                object.functions[j] = $root.onnx.FunctionProto.toObject(message.functions[j], options);
            }
            return object;
          };
          ModelProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
          };
          ModelProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
            if (typeUrlPrefix === void 0) {
              typeUrlPrefix = "type.googleapis.com";
            }
            return typeUrlPrefix + "/onnx.ModelProto";
          };
          return ModelProto;
        }();
        onnx6.StringStringEntryProto = function() {
          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.prototype.key = "";
          StringStringEntryProto.prototype.value = "";
          StringStringEntryProto.create = function create(properties) {
            return new StringStringEntryProto(properties);
          };
          StringStringEntryProto.encode = function encode(message, writer) {
            if (!writer)
              writer = $Writer.create();
            if (message.key != null && Object.hasOwnProperty.call(message, "key"))
              writer.uint32(
                /* id 1, wireType 2 =*/
                10
              ).string(message.key);
            if (message.value != null && Object.hasOwnProperty.call(message, "value"))
              writer.uint32(
                /* id 2, wireType 2 =*/
                18
              ).string(message.value);
            return writer;
          };
          StringStringEntryProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
          };
          StringStringEntryProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
              reader = $Reader.create(reader);
            var end = length === void 0 ? 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;
          };
          StringStringEntryProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
              reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
          };
          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;
          };
          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;
          };
          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;
          };
          StringStringEntryProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
          };
          StringStringEntryProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
            if (typeUrlPrefix === void 0) {
              typeUrlPrefix = "type.googleapis.com";
            }
            return typeUrlPrefix + "/onnx.StringStringEntryProto";
          };
          return StringStringEntryProto;
        }();
        onnx6.TensorAnnotation = function() {
          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.prototype.tensorName = "";
          TensorAnnotation.prototype.quantParameterTensorNames = $util.emptyArray;
          TensorAnnotation.create = function create(properties) {
            return new TensorAnnotation(properties);
          };
          TensorAnnotation.encode = function encode(message, writer) {
            if (!writer)
              writer = $Writer.create();
            if (message.tensorName != null && Object.hasOwnProperty.call(message, "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;
          };
          TensorAnnotation.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
          };
          TensorAnnotation.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
              reader = $Reader.create(reader);
            var end = length === void 0 ? 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;
          };
          TensorAnnotation.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
              reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
          };
          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;
          };
          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;
          };
          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;
          };
          TensorAnnotation.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
          };
          TensorAnnotation.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
            if (typeUrlPrefix === void 0) {
              typeUrlPrefix = "type.googleapis.com";
            }
            return typeUrlPrefix + "/onnx.TensorAnnotation";
          };
          return TensorAnnotation;
        }();
        onnx6.GraphProto = function() {
          function GraphProto(properties) {
            this.node = [];
            this.initializer = [];
            this.sparseInitializer = [];
            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.prototype.node = $util.emptyArray;
          GraphProto.prototype.name = "";
          GraphProto.prototype.initializer = $util.emptyArray;
          GraphProto.prototype.sparseInitializer = $util.emptyArray;
          GraphProto.prototype.docString = "";
          GraphProto.prototype.input = $util.emptyArray;
          GraphProto.prototype.output = $util.emptyArray;
          GraphProto.prototype.valueInfo = $util.emptyArray;
          GraphProto.prototype.quantizationAnnotation = $util.emptyArray;
          GraphProto.create = function create(properties) {
            return new GraphProto(properties);
          };
          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 && Object.hasOwnProperty.call(message, "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 && Object.hasOwnProperty.call(message, "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();
            if (message.sparseInitializer != null && message.sparseInitializer.length)
              for (var i = 0; i < message.sparseInitializer.length; ++i)
                $root.onnx.SparseTensorProto.encode(message.sparseInitializer[i], writer.uint32(
                  /* id 15, wireType 2 =*/
                  122
                ).fork()).ldelim();
            return writer;
          };
          GraphProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
          };
          GraphProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
              reader = $Reader.create(reader);
            var end = length === void 0 ? 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 15: {
                  if (!(message.sparseInitializer && message.sparseInitializer.length))
                    message.sparseInitializer = [];
                  message.sparseInitializer.push($root.onnx.SparseTensorProto.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;
          };
          GraphProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
              reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
          };
          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.sparseInitializer != null && message.hasOwnProperty("sparseInitializer")) {
              if (!Array.isArray(message.sparseInitializer))
                return "sparseInitializer: array expected";
              for (var i = 0; i < message.sparseInitializer.length; ++i) {
                var error = $root.onnx.SparseTensorProto.verify(message.sparseInitializer[i]);
                if (error)
                  return "sparseInitializer." + 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;
          };
          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.sparseInitializer) {
              if (!Array.isArray(object.sparseInitializer))
                throw TypeError(".onnx.GraphProto.sparseInitializer: array expected");
              message.sparseInitializer = [];
              for (var i = 0; i < object.sparseInitializer.length; ++i) {
                if (typeof object.sparseInitializer[i] !== "object")
                  throw TypeError(".onnx.GraphProto.sparseInitializer: object expected");
                message.sparseInitializer[i] = $root.onnx.SparseTensorProto.fromObject(object.sparseInitializer[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;
          };
          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 = [];
              object.sparseInitializer = [];
            }
            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);
            }
            if (message.sparseInitializer && message.sparseInitializer.length) {
              object.sparseInitializer = [];
              for (var j = 0; j < message.sparseInitializer.length; ++j)
                object.sparseInitializer[j] = $root.onnx.SparseTensorProto.toObject(message.sparseInitializer[j], options);
            }
            return object;
          };
          GraphProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
          };
          GraphProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
            if (typeUrlPrefix === void 0) {
              typeUrlPrefix = "type.googleapis.com";
            }
            return typeUrlPrefix + "/onnx.GraphProto";
          };
          return GraphProto;
        }();
        onnx6.TensorProto = function() {
          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.prototype.dims = $util.emptyArray;
          TensorProto.prototype.dataType = 0;
          TensorProto.prototype.segment = null;
          TensorProto.prototype.floatData = $util.emptyArray;
          TensorProto.prototype.int32Data = $util.emptyArray;
          TensorProto.prototype.stringData = $util.emptyArray;
          TensorProto.prototype.int64Data = $util.emptyArray;
          TensorProto.prototype.name = "";
          TensorProto.prototype.docString = "";
          TensorProto.prototype.rawData = $util.newBuffer([]);
          TensorProto.prototype.externalData = $util.emptyArray;
          TensorProto.prototype.dataLocation = 0;
          TensorProto.prototype.doubleData = $util.emptyArray;
          TensorProto.prototype.uint64Data = $util.emptyArray;
          TensorProto.create = function create(properties) {
            return new TensorProto(properties);
          };
          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 && Object.hasOwnProperty.call(message, "dataType"))
              writer.uint32(
                /* id 2, wireType 0 =*/
                16
              ).int32(message.dataType);
            if (message.segment != null && Object.hasOwnProperty.call(message, "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 && Object.hasOwnProperty.call(message, "name"))
              writer.uint32(
                /* id 8, wireType 2 =*/
                66
              ).string(message.name);
            if (message.rawData != null && Object.hasOwnProperty.call(message, "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 && Object.hasOwnProperty.call(message, "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 && Object.hasOwnProperty.call(message, "dataLocation"))
              writer.uint32(
                /* id 14, wireType 0 =*/
                112
              ).int32(message.dataLocation);
            return writer;
          };
          TensorProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
          };
          TensorProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
              reader = $Reader.create(reader);
            var end = length === void 0 ? 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;
          };
          TensorProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
              reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
          };
          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;
          };
          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 >= 0)
                  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 >= 0)
                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) {
              default:
                if (typeof object.dataLocation === "number") {
                  message.dataLocation = object.dataLocation;
                  break;
                }
                break;
              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;
          };
          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] === void 0 ? message.dataLocation : $root.onnx.TensorProto.DataLocation[message.dataLocation] : message.dataLocation;
            return object;
          };
          TensorProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
          };
          TensorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
            if (typeUrlPrefix === void 0) {
              typeUrlPrefix = "type.googleapis.com";
            }
            return typeUrlPrefix + "/onnx.TensorProto";
          };
          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;
            values[valuesById[17] = "FLOAT8E4M3FN"] = 17;
            values[valuesById[18] = "FLOAT8E4M3FNUZ"] = 18;
            values[valuesById[19] = "FLOAT8E5M2"] = 19;
            values[valuesById[20] = "FLOAT8E5M2FNUZ"] = 20;
            return values;
          }();
          TensorProto.Segment = function() {
            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.prototype.begin = $util.Long ? $util.Long.fromBits(0, 0, false) : 0;
            Segment.prototype.end = $util.Long ? $util.Long.fromBits(0, 0, false) : 0;
            Segment.create = function create(properties) {
              return new Segment(properties);
            };
            Segment.encode = function encode(message, writer) {
              if (!writer)
                writer = $Writer.create();
              if (message.begin != null && Object.hasOwnProperty.call(message, "begin"))
                writer.uint32(
                  /* id 1, wireType 0 =*/
                  8
                ).int64(message.begin);
              if (message.end != null && Object.hasOwnProperty.call(message, "end"))
                writer.uint32(
                  /* id 2, wireType 0 =*/
                  16
                ).int64(message.end);
              return writer;
            };
            Segment.encodeDelimited = function encodeDelimited(message, writer) {
              return this.encode(message, writer).ldelim();
            };
            Segment.decode = function decode(reader, length) {
              if (!(reader instanceof $Reader))
                reader = $Reader.create(reader);
              var end = length === void 0 ? 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;
            };
            Segment.decodeDelimited = function decodeDelimited(reader) {
              if (!(reader instanceof $Reader))
                reader = new $Reader(reader);
              return this.decode(reader, reader.uint32());
            };
            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;
            };
            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;
            };
            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;
            };
            Segment.prototype.toJSON = function toJSON() {
              return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
            };
            Segment.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
              if (typeUrlPrefix === void 0) {
                typeUrlPrefix = "type.googleapis.com";
              }
              return typeUrlPrefix + "/onnx.TensorProto.Segment";
            };
            return Segment;
          }();
          TensorProto.DataLocation = function() {
            var valuesById = {}, values = Object.create(valuesById);
            values[valuesById[0] = "DEFAULT"] = 0;
            values[valuesById[1] = "EXTERNAL"] = 1;
            return values;
          }();
          return TensorProto;
        }();
        onnx6.SparseTensorProto = function() {
          function SparseTensorProto(properties) {
            this.dims = [];
            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]];
            }
          }
          SparseTensorProto.prototype.values = null;
          SparseTensorProto.prototype.indices = null;
          SparseTensorProto.prototype.dims = $util.emptyArray;
          SparseTensorProto.create = function create(properties) {
            return new SparseTensorProto(properties);
          };
          SparseTensorProto.encode = function encode(message, writer) {
            if (!writer)
              writer = $Writer.create();
            if (message.values != null && Object.hasOwnProperty.call(message, "values"))
              $root.onnx.TensorProto.encode(message.values, writer.uint32(
                /* id 1, wireType 2 =*/
                10
              ).fork()).ldelim();
            if (message.indices != null && Object.hasOwnProperty.call(message, "indices"))
              $root.onnx.TensorProto.encode(message.indices, writer.uint32(
                /* id 2, wireType 2 =*/
                18
              ).fork()).ldelim();
            if (message.dims != null && message.dims.length) {
              writer.uint32(
                /* id 3, wireType 2 =*/
                26
              ).fork();
              for (var i = 0; i < message.dims.length; ++i)
                writer.int64(message.dims[i]);
              writer.ldelim();
            }
            return writer;
          };
          SparseTensorProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
          };
          SparseTensorProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
              reader = $Reader.create(reader);
            var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.onnx.SparseTensorProto();
            while (reader.pos < end) {
              var tag = reader.uint32();
              switch (tag >>> 3) {
                case 1: {
                  message.values = $root.onnx.TensorProto.decode(reader, reader.uint32());
                  break;
                }
                case 2: {
                  message.indices = $root.onnx.TensorProto.decode(reader, reader.uint32());
                  break;
                }
                case 3: {
                  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;
                }
                default:
                  reader.skipType(tag & 7);
                  break;
              }
            }
            return message;
          };
          SparseTensorProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
              reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
          };
          SparseTensorProto.verify = function verify(message) {
            if (typeof message !== "object" || message === null)
              return "object expected";
            if (message.values != null && message.hasOwnProperty("values")) {
              var error = $root.onnx.TensorProto.verify(message.values);
              if (error)
                return "values." + error;
            }
            if (message.indices != null && message.hasOwnProperty("indices")) {
              var error = $root.onnx.TensorProto.verify(message.indices);
              if (error)
                return "indices." + error;
            }
            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";
            }
            return null;
          };
          SparseTensorProto.fromObject = function fromObject(object) {
            if (object instanceof $root.onnx.SparseTensorProto)
              return object;
            var message = new $root.onnx.SparseTensorProto();
            if (object.values != null) {
              if (typeof object.values !== "object")
                throw TypeError(".onnx.SparseTensorProto.values: object expected");
              message.values = $root.onnx.TensorProto.fromObject(object.values);
            }
            if (object.indices != null) {
              if (typeof object.indices !== "object")
                throw TypeError(".onnx.SparseTensorProto.indices: object expected");
              message.indices = $root.onnx.TensorProto.fromObject(object.indices);
            }
            if (object.dims) {
              if (!Array.isArray(object.dims))
                throw TypeError(".onnx.SparseTensorProto.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();
            }
            return message;
          };
          SparseTensorProto.toObject = function toObject(message, options) {
            if (!options)
              options = {};
            var object = {};
            if (options.arrays || options.defaults)
              object.dims = [];
            if (options.defaults) {
              object.values = null;
              object.indices = null;
            }
            if (message.values != null && message.hasOwnProperty("values"))
              object.values = $root.onnx.TensorProto.toObject(message.values, options);
            if (message.indices != null && message.hasOwnProperty("indices"))
              object.indices = $root.onnx.TensorProto.toObject(message.indices, options);
            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];
            }
            return object;
          };
          SparseTensorProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
          };
          SparseTensorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
            if (typeUrlPrefix === void 0) {
              typeUrlPrefix = "type.googleapis.com";
            }
            return typeUrlPrefix + "/onnx.SparseTensorProto";
          };
          return SparseTensorProto;
        }();
        onnx6.TensorShapeProto = function() {
          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.prototype.dim = $util.emptyArray;
          TensorShapeProto.create = function create(properties) {
            return new TensorShapeProto(properties);
          };
          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;
          };
          TensorShapeProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
          };
          TensorShapeProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
              reader = $Reader.create(reader);
            var end = length === void 0 ? 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;
          };
          TensorShapeProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
              reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
          };
          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;
          };
          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;
          };
          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;
          };
          TensorShapeProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
          };
          TensorShapeProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
            if (typeUrlPrefix === void 0) {
              typeUrlPrefix = "type.googleapis.com";
            }
            return typeUrlPrefix + "/onnx.TensorShapeProto";
          };
          TensorShapeProto.Dimension = function() {
            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.prototype.dimValue = null;
            Dimension.prototype.dimParam = null;
            Dimension.prototype.denotation = "";
            var $oneOfFields;
            Object.defineProperty(Dimension.prototype, "value", {
              get: $util.oneOfGetter($oneOfFields = ["dimValue", "dimParam"]),
              set: $util.oneOfSetter($oneOfFields)
            });
            Dimension.create = function create(properties) {
              return new Dimension(properties);
            };
            Dimension.encode = function encode(message, writer) {
              if (!writer)
                writer = $Writer.create();
              if (message.dimValue != null && Object.hasOwnProperty.call(message, "dimValue"))
                writer.uint32(
                  /* id 1, wireType 0 =*/
                  8
                ).int64(message.dimValue);
              if (message.dimParam != null && Object.hasOwnProperty.call(message, "dimParam"))
                writer.uint32(
                  /* id 2, wireType 2 =*/
                  18
                ).string(message.dimParam);
              if (message.denotation != null && Object.hasOwnProperty.call(message, "denotation"))
                writer.uint32(
                  /* id 3, wireType 2 =*/
                  26
                ).string(message.denotation);
              return writer;
            };
            Dimension.encodeDelimited = function encodeDelimited(message, writer) {
              return this.encode(message, writer).ldelim();
            };
            Dimension.decode = function decode(reader, length) {
              if (!(reader instanceof $Reader))
                reader = $Reader.create(reader);
              var end = length === void 0 ? 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;
            };
            Dimension.decodeDelimited = function decodeDelimited(reader) {
              if (!(reader instanceof $Reader))
                reader = new $Reader(reader);
              return this.decode(reader, reader.uint32());
            };
            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;
            };
            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;
            };
            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;
            };
            Dimension.prototype.toJSON = function toJSON() {
              return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
            };
            Dimension.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
              if (typeUrlPrefix === void 0) {
                typeUrlPrefix = "type.googleapis.com";
              }
              return typeUrlPrefix + "/onnx.TensorShapeProto.Dimension";
            };
            return Dimension;
          }();
          return TensorShapeProto;
        }();
        onnx6.TypeProto = function() {
          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.prototype.tensorType = null;
          TypeProto.prototype.sequenceType = null;
          TypeProto.prototype.mapType = null;
          TypeProto.prototype.optionalType = null;
          TypeProto.prototype.sparseTensorType = null;
          TypeProto.prototype.denotation = "";
          var $oneOfFields;
          Object.defineProperty(TypeProto.prototype, "value", {
            get: $util.oneOfGetter($oneOfFields = ["tensorType", "sequenceType", "mapType", "optionalType", "sparseTensorType"]),
            set: $util.oneOfSetter($oneOfFields)
          });
          TypeProto.create = function create(properties) {
            return new TypeProto(properties);
          };
          TypeProto.encode = function encode(message, writer) {
            if (!writer)
              writer = $Writer.create();
            if (message.tensorType != null && Object.hasOwnProperty.call(message, "tensorType"))
              $root.onnx.TypeProto.Tensor.encode(message.tensorType, writer.uint32(
                /* id 1, wireType 2 =*/
                10
              ).fork()).ldelim();
            if (message.sequenceType != null && Object.hasOwnProperty.call(message, "sequenceType"))
              $root.onnx.TypeProto.Sequence.encode(message.sequenceType, writer.uint32(
                /* id 4, wireType 2 =*/
                34
              ).fork()).ldelim();
            if (message.mapType != null && Object.hasOwnProperty.call(message, "mapType"))
              $root.onnx.TypeProto.Map.encode(message.mapType, writer.uint32(
                /* id 5, wireType 2 =*/
                42
              ).fork()).ldelim();
            if (message.denotation != null && Object.hasOwnProperty.call(message, "denotation"))
              writer.uint32(
                /* id 6, wireType 2 =*/
                50
              ).string(message.denotation);
            if (message.sparseTensorType != null && Object.hasOwnProperty.call(message, "sparseTensorType"))
              $root.onnx.TypeProto.SparseTensor.encode(message.sparseTensorType, writer.uint32(
                /* id 8, wireType 2 =*/
                66
              ).fork()).ldelim();
            if (message.optionalType != null && Object.hasOwnProperty.call(message, "optionalType"))
              $root.onnx.TypeProto.Optional.encode(message.optionalType, writer.uint32(
                /* id 9, wireType 2 =*/
                74
              ).fork()).ldelim();
            return writer;
          };
          TypeProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
          };
          TypeProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
              reader = $Reader.create(reader);
            var end = length === void 0 ? 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 4: {
                  message.sequenceType = $root.onnx.TypeProto.Sequence.decode(reader, reader.uint32());
                  break;
                }
                case 5: {
                  message.mapType = $root.onnx.TypeProto.Map.decode(reader, reader.uint32());
                  break;
                }
                case 9: {
                  message.optionalType = $root.onnx.TypeProto.Optional.decode(reader, reader.uint32());
                  break;
                }
                case 8: {
                  message.sparseTensorType = $root.onnx.TypeProto.SparseTensor.decode(reader, reader.uint32());
                  break;
                }
                case 6: {
                  message.denotation = reader.string();
                  break;
                }
                default:
                  reader.skipType(tag & 7);
                  break;
              }
            }
            return message;
          };
          TypeProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
              reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
          };
          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.sequenceType != null && message.hasOwnProperty("sequenceType")) {
              if (properties.value === 1)
                return "value: multiple values";
              properties.value = 1;
              {
                var error = $root.onnx.TypeProto.Sequence.verify(message.sequenceType);
                if (error)
                  return "sequenceType." + error;
              }
            }
            if (message.mapType != null && message.hasOwnProperty("mapType")) {
              if (properties.value === 1)
                return "value: multiple values";
              properties.value = 1;
              {
                var error = $root.onnx.TypeProto.Map.verify(message.mapType);
                if (error)
                  return "mapType." + error;
              }
            }
            if (message.optionalType != null && message.hasOwnProperty("optionalType")) {
              if (properties.value === 1)
                return "value: multiple values";
              properties.value = 1;
              {
                var error = $root.onnx.TypeProto.Optional.verify(message.optionalType);
                if (error)
                  return "optionalType." + error;
              }
            }
            if (message.sparseTensorType != null && message.hasOwnProperty("sparseTensorType")) {
              if (properties.value === 1)
                return "value: multiple values";
              properties.value = 1;
              {
                var error = $root.onnx.TypeProto.SparseTensor.verify(message.sparseTensorType);
                if (error)
                  return "sparseTensorType." + error;
              }
            }
            if (message.denotation != null && message.hasOwnProperty("denotation")) {
              if (!$util.isString(message.denotation))
                return "denotation: string expected";
            }
            return null;
          };
          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.sequenceType != null) {
              if (typeof object.sequenceType !== "object")
                throw TypeError(".onnx.TypeProto.sequenceType: object expected");
              message.sequenceType = $root.onnx.TypeProto.Sequence.fromObject(object.sequenceType);
            }
            if (object.mapType != null) {
              if (typeof object.mapType !== "object")
                throw TypeError(".onnx.TypeProto.mapType: object expected");
              message.mapType = $root.onnx.TypeProto.Map.fromObject(object.mapType);
            }
            if (object.optionalType != null) {
              if (typeof object.optionalType !== "object")
                throw TypeError(".onnx.TypeProto.optionalType: object expected");
              message.optionalType = $root.onnx.TypeProto.Optional.fromObject(object.optionalType);
            }
            if (object.sparseTensorType != null) {
              if (typeof object.sparseTensorType !== "object")
                throw TypeError(".onnx.TypeProto.sparseTensorType: object expected");
              message.sparseTensorType = $root.onnx.TypeProto.SparseTensor.fromObject(object.sparseTensorType);
            }
            if (object.denotation != null)
              message.denotation = String(object.denotation);
            return message;
          };
          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.sequenceType != null && message.hasOwnProperty("sequenceType")) {
              object.sequenceType = $root.onnx.TypeProto.Sequence.toObject(message.sequenceType, options);
              if (options.oneofs)
                object.value = "sequenceType";
            }
            if (message.mapType != null && message.hasOwnProperty("mapType")) {
              object.mapType = $root.onnx.TypeProto.Map.toObject(message.mapType, options);
              if (options.oneofs)
                object.value = "mapType";
            }
            if (message.denotation != null && message.hasOwnProperty("denotation"))
              object.denotation = message.denotation;
            if (message.sparseTensorType != null && message.hasOwnProperty("sparseTensorType")) {
              object.sparseTensorType = $root.onnx.TypeProto.SparseTensor.toObject(message.sparseTensorType, options);
              if (options.oneofs)
                object.value = "sparseTensorType";
            }
            if (message.optionalType != null && message.hasOwnProperty("optionalType")) {
              object.optionalType = $root.onnx.TypeProto.Optional.toObject(message.optionalType, options);
              if (options.oneofs)
                object.value = "optionalType";
            }
            return object;
          };
          TypeProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
          };
          TypeProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
            if (typeUrlPrefix === void 0) {
              typeUrlPrefix = "type.googleapis.com";
            }
            return typeUrlPrefix + "/onnx.TypeProto";
          };
          TypeProto.Tensor = function() {
            function Tensor4(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]];
              }
            }
            Tensor4.prototype.elemType = 0;
            Tensor4.prototype.shape = null;
            Tensor4.create = function create(properties) {
              return new Tensor4(properties);
            };
            Tensor4.encode = function encode(message, writer) {
              if (!writer)
                writer = $Writer.create();
              if (message.elemType != null && Object.hasOwnProperty.call(message, "elemType"))
                writer.uint32(
                  /* id 1, wireType 0 =*/
                  8
                ).int32(message.elemType);
              if (message.shape != null && Object.hasOwnProperty.call(message, "shape"))
                $root.onnx.TensorShapeProto.encode(message.shape, writer.uint32(
                  /* id 2, wireType 2 =*/
                  18
                ).fork()).ldelim();
              return writer;
            };
            Tensor4.encodeDelimited = function encodeDelimited(message, writer) {
              return this.encode(message, writer).ldelim();
            };
            Tensor4.decode = function decode(reader, length) {
              if (!(reader instanceof $Reader))
                reader = $Reader.create(reader);
              var end = length === void 0 ? 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;
            };
            Tensor4.decodeDelimited = function decodeDelimited(reader) {
              if (!(reader instanceof $Reader))
                reader = new $Reader(reader);
              return this.decode(reader, reader.uint32());
            };
            Tensor4.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;
            };
            Tensor4.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;
            };
            Tensor4.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;
            };
            Tensor4.prototype.toJSON = function toJSON() {
              return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
            };
            Tensor4.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
              if (typeUrlPrefix === void 0) {
                typeUrlPrefix = "type.googleapis.com";
              }
              return typeUrlPrefix + "/onnx.TypeProto.Tensor";
            };
            return Tensor4;
          }();
          TypeProto.Sequence = function() {
            function Sequence(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]];
              }
            }
            Sequence.prototype.elemType = null;
            Sequence.create = function create(properties) {
              return new Sequence(properties);
            };
            Sequence.encode = function encode(message, writer) {
              if (!writer)
                writer = $Writer.create();
              if (message.elemType != null && Object.hasOwnProperty.call(message, "elemType"))
                $root.onnx.TypeProto.encode(message.elemType, writer.uint32(
                  /* id 1, wireType 2 =*/
                  10
                ).fork()).ldelim();
              return writer;
            };
            Sequence.encodeDelimited = function encodeDelimited(message, writer) {
              return this.encode(message, writer).ldelim();
            };
            Sequence.decode = function decode(reader, length) {
              if (!(reader instanceof $Reader))
                reader = $Reader.create(reader);
              var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.onnx.TypeProto.Sequence();
              while (reader.pos < end) {
                var tag = reader.uint32();
                switch (tag >>> 3) {
                  case 1: {
                    message.elemType = $root.onnx.TypeProto.decode(reader, reader.uint32());
                    break;
                  }
                  default:
                    reader.skipType(tag & 7);
                    break;
                }
              }
              return message;
            };
            Sequence.decodeDelimited = function decodeDelimited(reader) {
              if (!(reader instanceof $Reader))
                reader = new $Reader(reader);
              return this.decode(reader, reader.uint32());
            };
            Sequence.verify = function verify(message) {
              if (typeof message !== "object" || message === null)
                return "object expected";
              if (message.elemType != null && message.hasOwnProperty("elemType")) {
                var error = $root.onnx.TypeProto.verify(message.elemType);
                if (error)
                  return "elemType." + error;
              }
              return null;
            };
            Sequence.fromObject = function fromObject(object) {
              if (object instanceof $root.onnx.TypeProto.Sequence)
                return object;
              var message = new $root.onnx.TypeProto.Sequence();
              if (object.elemType != null) {
                if (typeof object.elemType !== "object")
                  throw TypeError(".onnx.TypeProto.Sequence.elemType: object expected");
                message.elemType = $root.onnx.TypeProto.fromObject(object.elemType);
              }
              return message;
            };
            Sequence.toObject = function toObject(message, options) {
              if (!options)
                options = {};
              var object = {};
              if (options.defaults)
                object.elemType = null;
              if (message.elemType != null && message.hasOwnProperty("elemType"))
                object.elemType = $root.onnx.TypeProto.toObject(message.elemType, options);
              return object;
            };
            Sequence.prototype.toJSON = function toJSON() {
              return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
            };
            Sequence.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
              if (typeUrlPrefix === void 0) {
                typeUrlPrefix = "type.googleapis.com";
              }
              return typeUrlPrefix + "/onnx.TypeProto.Sequence";
            };
            return Sequence;
          }();
          TypeProto.Map = function() {
            function Map2(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]];
              }
            }
            Map2.prototype.keyType = 0;
            Map2.prototype.valueType = null;
            Map2.create = function create(properties) {
              return new Map2(properties);
            };
            Map2.encode = function encode(message, writer) {
              if (!writer)
                writer = $Writer.create();
              if (message.keyType != null && Object.hasOwnProperty.call(message, "keyType"))
                writer.uint32(
                  /* id 1, wireType 0 =*/
                  8
                ).int32(message.keyType);
              if (message.valueType != null && Object.hasOwnProperty.call(message, "valueType"))
                $root.onnx.TypeProto.encode(message.valueType, writer.uint32(
                  /* id 2, wireType 2 =*/
                  18
                ).fork()).ldelim();
              return writer;
            };
            Map2.encodeDelimited = function encodeDelimited(message, writer) {
              return this.encode(message, writer).ldelim();
            };
            Map2.decode = function decode(reader, length) {
              if (!(reader instanceof $Reader))
                reader = $Reader.create(reader);
              var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.onnx.TypeProto.Map();
              while (reader.pos < end) {
                var tag = reader.uint32();
                switch (tag >>> 3) {
                  case 1: {
                    message.keyType = reader.int32();
                    break;
                  }
                  case 2: {
                    message.valueType = $root.onnx.TypeProto.decode(reader, reader.uint32());
                    break;
                  }
                  default:
                    reader.skipType(tag & 7);
                    break;
                }
              }
              return message;
            };
            Map2.decodeDelimited = function decodeDelimited(reader) {
              if (!(reader instanceof $Reader))
                reader = new $Reader(reader);
              return this.decode(reader, reader.uint32());
            };
            Map2.verify = function verify(message) {
              if (typeof message !== "object" || message === null)
                return "object expected";
              if (message.keyType != null && message.hasOwnProperty("keyType")) {
                if (!$util.isInteger(message.keyType))
                  return "keyType: integer expected";
              }
              if (message.valueType != null && message.hasOwnProperty("valueType")) {
                var error = $root.onnx.TypeProto.verify(message.valueType);
                if (error)
                  return "valueType." + error;
              }
              return null;
            };
            Map2.fromObject = function fromObject(object) {
              if (object instanceof $root.onnx.TypeProto.Map)
                return object;
              var message = new $root.onnx.TypeProto.Map();
              if (object.keyType != null)
                message.keyType = object.keyType | 0;
              if (object.valueType != null) {
                if (typeof object.valueType !== "object")
                  throw TypeError(".onnx.TypeProto.Map.valueType: object expected");
                message.valueType = $root.onnx.TypeProto.fromObject(object.valueType);
              }
              return message;
            };
            Map2.toObject = function toObject(message, options) {
              if (!options)
                options = {};
              var object = {};
              if (options.defaults) {
                object.keyType = 0;
                object.valueType = null;
              }
              if (message.keyType != null && message.hasOwnProperty("keyType"))
                object.keyType = message.keyType;
              if (message.valueType != null && message.hasOwnProperty("valueType"))
                object.valueType = $root.onnx.TypeProto.toObject(message.valueType, options);
              return object;
            };
            Map2.prototype.toJSON = function toJSON() {
              return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
            };
            Map2.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
              if (typeUrlPrefix === void 0) {
                typeUrlPrefix = "type.googleapis.com";
              }
              return typeUrlPrefix + "/onnx.TypeProto.Map";
            };
            return Map2;
          }();
          TypeProto.Optional = function() {
            function Optional(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]];
              }
            }
            Optional.prototype.elemType = null;
            Optional.create = function create(properties) {
              return new Optional(properties);
            };
            Optional.encode = function encode(message, writer) {
              if (!writer)
                writer = $Writer.create();
              if (message.elemType != null && Object.hasOwnProperty.call(message, "elemType"))
                $root.onnx.TypeProto.encode(message.elemType, writer.uint32(
                  /* id 1, wireType 2 =*/
                  10
                ).fork()).ldelim();
              return writer;
            };
            Optional.encodeDelimited = function encodeDelimited(message, writer) {
              return this.encode(message, writer).ldelim();
            };
            Optional.decode = function decode(reader, length) {
              if (!(reader instanceof $Reader))
                reader = $Reader.create(reader);
              var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.onnx.TypeProto.Optional();
              while (reader.pos < end) {
                var tag = reader.uint32();
                switch (tag >>> 3) {
                  case 1: {
                    message.elemType = $root.onnx.TypeProto.decode(reader, reader.uint32());
                    break;
                  }
                  default:
                    reader.skipType(tag & 7);
                    break;
                }
              }
              return message;
            };
            Optional.decodeDelimited = function decodeDelimited(reader) {
              if (!(reader instanceof $Reader))
                reader = new $Reader(reader);
              return this.decode(reader, reader.uint32());
            };
            Optional.verify = function verify(message) {
              if (typeof message !== "object" || message === null)
                return "object expected";
              if (message.elemType != null && message.hasOwnProperty("elemType")) {
                var error = $root.onnx.TypeProto.verify(message.elemType);
                if (error)
                  return "elemType." + error;
              }
              return null;
            };
            Optional.fromObject = function fromObject(object) {
              if (object instanceof $root.onnx.TypeProto.Optional)
                return object;
              var message = new $root.onnx.TypeProto.Optional();
              if (object.elemType != null) {
                if (typeof object.elemType !== "object")
                  throw TypeError(".onnx.TypeProto.Optional.elemType: object expected");
                message.elemType = $root.onnx.TypeProto.fromObject(object.elemType);
              }
              return message;
            };
            Optional.toObject = function toObject(message, options) {
              if (!options)
                options = {};
              var object = {};
              if (options.defaults)
                object.elemType = null;
              if (message.elemType != null && message.hasOwnProperty("elemType"))
                object.elemType = $root.onnx.TypeProto.toObject(message.elemType, options);
              return object;
            };
            Optional.prototype.toJSON = function toJSON() {
              return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
            };
            Optional.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
              if (typeUrlPrefix === void 0) {
                typeUrlPrefix = "type.googleapis.com";
              }
              return typeUrlPrefix + "/onnx.TypeProto.Optional";
            };
            return Optional;
          }();
          TypeProto.SparseTensor = function() {
            function SparseTensor(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]];
              }
            }
            SparseTensor.prototype.elemType = 0;
            SparseTensor.prototype.shape = null;
            SparseTensor.create = function create(properties) {
              return new SparseTensor(properties);
            };
            SparseTensor.encode = function encode(message, writer) {
              if (!writer)
                writer = $Writer.create();
              if (message.elemType != null && Object.hasOwnProperty.call(message, "elemType"))
                writer.uint32(
                  /* id 1, wireType 0 =*/
                  8
                ).int32(message.elemType);
              if (message.shape != null && Object.hasOwnProperty.call(message, "shape"))
                $root.onnx.TensorShapeProto.encode(message.shape, writer.uint32(
                  /* id 2, wireType 2 =*/
                  18
                ).fork()).ldelim();
              return writer;
            };
            SparseTensor.encodeDelimited = function encodeDelimited(message, writer) {
              return this.encode(message, writer).ldelim();
            };
            SparseTensor.decode = function decode(reader, length) {
              if (!(reader instanceof $Reader))
                reader = $Reader.create(reader);
              var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.onnx.TypeProto.SparseTensor();
              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;
            };
            SparseTensor.decodeDelimited = function decodeDelimited(reader) {
              if (!(reader instanceof $Reader))
                reader = new $Reader(reader);
              return this.decode(reader, reader.uint32());
            };
            SparseTensor.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;
            };
            SparseTensor.fromObject = function fromObject(object) {
              if (object instanceof $root.onnx.TypeProto.SparseTensor)
                return object;
              var message = new $root.onnx.TypeProto.SparseTensor();
              if (object.elemType != null)
                message.elemType = object.elemType | 0;
              if (object.shape != null) {
                if (typeof object.shape !== "object")
                  throw TypeError(".onnx.TypeProto.SparseTensor.shape: object expected");
                message.shape = $root.onnx.TensorShapeProto.fromObject(object.shape);
              }
              return message;
            };
            SparseTensor.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;
            };
            SparseTensor.prototype.toJSON = function toJSON() {
              return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
            };
            SparseTensor.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
              if (typeUrlPrefix === void 0) {
                typeUrlPrefix = "type.googleapis.com";
              }
              return typeUrlPrefix + "/onnx.TypeProto.SparseTensor";
            };
            return SparseTensor;
          }();
          return TypeProto;
        }();
        onnx6.OperatorSetIdProto = function() {
          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.prototype.domain = "";
          OperatorSetIdProto.prototype.version = $util.Long ? $util.Long.fromBits(0, 0, false) : 0;
          OperatorSetIdProto.create = function create(properties) {
            return new OperatorSetIdProto(properties);
          };
          OperatorSetIdProto.encode = function encode(message, writer) {
            if (!writer)
              writer = $Writer.create();
            if (message.domain != null && Object.hasOwnProperty.call(message, "domain"))
              writer.uint32(
                /* id 1, wireType 2 =*/
                10
              ).string(message.domain);
            if (message.version != null && Object.hasOwnProperty.call(message, "version"))
              writer.uint32(
                /* id 2, wireType 0 =*/
                16
              ).int64(message.version);
            return writer;
          };
          OperatorSetIdProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
          };
          OperatorSetIdProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
              reader = $Reader.create(reader);
            var end = length === void 0 ? 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;
          };
          OperatorSetIdProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
              reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
          };
          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;
          };
          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;
          };
          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;
          };
          OperatorSetIdProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
          };
          OperatorSetIdProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
            if (typeUrlPrefix === void 0) {
              typeUrlPrefix = "type.googleapis.com";
            }
            return typeUrlPrefix + "/onnx.OperatorSetIdProto";
          };
          return OperatorSetIdProto;
        }();
        onnx6.OperatorStatus = function() {
          var valuesById = {}, values = Object.create(valuesById);
          values[valuesById[0] = "EXPERIMENTAL"] = 0;
          values[valuesById[1] = "STABLE"] = 1;
          return values;
        }();
        onnx6.FunctionProto = function() {
          function FunctionProto(properties) {
            this.input = [];
            this.output = [];
            this.attribute = [];
            this.attributeProto = [];
            this.node = [];
            this.opsetImport = [];
            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]];
            }
          }
          FunctionProto.prototype.name = "";
          FunctionProto.prototype.input = $util.emptyArray;
          FunctionProto.prototype.output = $util.emptyArray;
          FunctionProto.prototype.attribute = $util.emptyArray;
          FunctionProto.prototype.attributeProto = $util.emptyArray;
          FunctionProto.prototype.node = $util.emptyArray;
          FunctionProto.prototype.docString = "";
          FunctionProto.prototype.opsetImport = $util.emptyArray;
          FunctionProto.prototype.domain = "";
          FunctionProto.create = function create(properties) {
            return new FunctionProto(properties);
          };
          FunctionProto.encode = function encode(message, writer) {
            if (!writer)
              writer = $Writer.create();
            if (message.name != null && Object.hasOwnProperty.call(message, "name"))
              writer.uint32(
                /* id 1, wireType 2 =*/
                10
              ).string(message.name);
            if (message.input != null && message.input.length)
              for (var i = 0; i < message.input.length; ++i)
                writer.uint32(
                  /* id 4, wireType 2 =*/
                  34
                ).string(message.input[i]);
            if (message.output != null && message.output.length)
              for (var i = 0; i < message.output.length; ++i)
                writer.uint32(
                  /* id 5, wireType 2 =*/
                  42
                ).string(message.output[i]);
            if (message.attribute != null && message.attribute.length)
              for (var i = 0; i < message.attribute.length; ++i)
                writer.uint32(
                  /* id 6, wireType 2 =*/
                  50
                ).string(message.attribute[i]);
            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 7, wireType 2 =*/
                  58
                ).fork()).ldelim();
            if (message.docString != null && Object.hasOwnProperty.call(message, "docString"))
              writer.uint32(
                /* id 8, wireType 2 =*/
                66
              ).string(message.docString);
            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 9, wireType 2 =*/
                  74
                ).fork()).ldelim();
            if (message.domain != null && Object.hasOwnProperty.call(message, "domain"))
              writer.uint32(
                /* id 10, wireType 2 =*/
                82
              ).string(message.domain);
            if (message.attributeProto != null && message.attributeProto.length)
              for (var i = 0; i < message.attributeProto.length; ++i)
                $root.onnx.AttributeProto.encode(message.attributeProto[i], writer.uint32(
                  /* id 11, wireType 2 =*/
                  90
                ).fork()).ldelim();
            return writer;
          };
          FunctionProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
          };
          FunctionProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
              reader = $Reader.create(reader);
            var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.onnx.FunctionProto();
            while (reader.pos < end) {
              var tag = reader.uint32();
              switch (tag >>> 3) {
                case 1: {
                  message.name = reader.string();
                  break;
                }
                case 4: {
                  if (!(message.input && message.input.length))
                    message.input = [];
                  message.input.push(reader.string());
                  break;
                }
                case 5: {
                  if (!(message.output && message.output.length))
                    message.output = [];
                  message.output.push(reader.string());
                  break;
                }
                case 6: {
                  if (!(message.attribute && message.attribute.length))
                    message.attribute = [];
                  message.attribute.push(reader.string());
                  break;
                }
                case 11: {
                  if (!(message.attributeProto && message.attributeProto.length))
                    message.attributeProto = [];
                  message.attributeProto.push($root.onnx.AttributeProto.decode(reader, reader.uint32()));
                  break;
                }
                case 7: {
                  if (!(message.node && message.node.length))
                    message.node = [];
                  message.node.push($root.onnx.NodeProto.decode(reader, reader.uint32()));
                  break;
                }
                case 8: {
                  message.docString = reader.string();
                  break;
                }
                case 9: {
                  if (!(message.opsetImport && message.opsetImport.length))
                    message.opsetImport = [];
                  message.opsetImport.push($root.onnx.OperatorSetIdProto.decode(reader, reader.uint32()));
                  break;
                }
                case 10: {
                  message.domain = reader.string();
                  break;
                }
                default:
                  reader.skipType(tag & 7);
                  break;
              }
            }
            return message;
          };
          FunctionProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
              reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
          };
          FunctionProto.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.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.attribute != null && message.hasOwnProperty("attribute")) {
              if (!Array.isArray(message.attribute))
                return "attribute: array expected";
              for (var i = 0; i < message.attribute.length; ++i)
                if (!$util.isString(message.attribute[i]))
                  return "attribute: string[] expected";
            }
            if (message.attributeProto != null && message.hasOwnProperty("attributeProto")) {
              if (!Array.isArray(message.attributeProto))
                return "attributeProto: array expected";
              for (var i = 0; i < message.attributeProto.length; ++i) {
                var error = $root.onnx.AttributeProto.verify(message.attributeProto[i]);
                if (error)
                  return "attributeProto." + error;
              }
            }
            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.docString != null && message.hasOwnProperty("docString")) {
              if (!$util.isString(message.docString))
                return "docString: string 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.domain != null && message.hasOwnProperty("domain")) {
              if (!$util.isString(message.domain))
                return "domain: string expected";
            }
            return null;
          };
          FunctionProto.fromObject = function fromObject(object) {
            if (object instanceof $root.onnx.FunctionProto)
              return object;
            var message = new $root.onnx.FunctionProto();
            if (object.name != null)
              message.name = String(object.name);
            if (object.input) {
              if (!Array.isArray(object.input))
                throw TypeError(".onnx.FunctionProto.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.FunctionProto.output: array expected");
              message.output = [];
              for (var i = 0; i < object.output.length; ++i)
                message.output[i] = String(object.output[i]);
            }
            if (object.attribute) {
              if (!Array.isArray(object.attribute))
                throw TypeError(".onnx.FunctionProto.attribute: array expected");
              message.attribute = [];
              for (var i = 0; i < object.attribute.length; ++i)
                message.attribute[i] = String(object.attribute[i]);
            }
            if (object.attributeProto) {
              if (!Array.isArray(object.attributeProto))
                throw TypeError(".onnx.FunctionProto.attributeProto: array expected");
              message.attributeProto = [];
              for (var i = 0; i < object.attributeProto.length; ++i) {
                if (typeof object.attributeProto[i] !== "object")
                  throw TypeError(".onnx.FunctionProto.attributeProto: object expected");
                message.attributeProto[i] = $root.onnx.AttributeProto.fromObject(object.attributeProto[i]);
              }
            }
            if (object.node) {
              if (!Array.isArray(object.node))
                throw TypeError(".onnx.FunctionProto.node: array expected");
              message.node = [];
              for (var i = 0; i < object.node.length; ++i) {
                if (typeof object.node[i] !== "object")
                  throw TypeError(".onnx.FunctionProto.node: object expected");
                message.node[i] = $root.onnx.NodeProto.fromObject(object.node[i]);
              }
            }
            if (object.docString != null)
              message.docString = String(object.docString);
            if (object.opsetImport) {
              if (!Array.isArray(object.opsetImport))
                throw TypeError(".onnx.FunctionProto.opsetImport: array expected");
              message.opsetImport = [];
              for (var i = 0; i < object.opsetImport.length; ++i) {
                if (typeof object.opsetImport[i] !== "object")
                  throw TypeError(".onnx.FunctionProto.opsetImport: object expected");
                message.opsetImport[i] = $root.onnx.OperatorSetIdProto.fromObject(object.opsetImport[i]);
              }
            }
            if (object.domain != null)
              message.domain = String(object.domain);
            return message;
          };
          FunctionProto.toObject = function toObject(message, options) {
            if (!options)
              options = {};
            var object = {};
            if (options.arrays || options.defaults) {
              object.input = [];
              object.output = [];
              object.attribute = [];
              object.node = [];
              object.opsetImport = [];
              object.attributeProto = [];
            }
            if (options.defaults) {
              object.name = "";
              object.docString = "";
              object.domain = "";
            }
            if (message.name != null && message.hasOwnProperty("name"))
              object.name = message.name;
            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.attribute && message.attribute.length) {
              object.attribute = [];
              for (var j = 0; j < message.attribute.length; ++j)
                object.attribute[j] = message.attribute[j];
            }
            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.docString != null && message.hasOwnProperty("docString"))
              object.docString = message.docString;
            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.domain != null && message.hasOwnProperty("domain"))
              object.domain = message.domain;
            if (message.attributeProto && message.attributeProto.length) {
              object.attributeProto = [];
              for (var j = 0; j < message.attributeProto.length; ++j)
                object.attributeProto[j] = $root.onnx.AttributeProto.toObject(message.attributeProto[j], options);
            }
            return object;
          };
          FunctionProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
          };
          FunctionProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
            if (typeUrlPrefix === void 0) {
              typeUrlPrefix = "type.googleapis.com";
            }
            return typeUrlPrefix + "/onnx.FunctionProto";
          };
          return FunctionProto;
        }();
        return onnx6;
      }();
      module2.exports = $root;
    }
  });

  // web/lib/onnxjs/util.ts
  function assert(expr, msg) {
    if (!expr) {
      throw new Error(typeof msg === "string" ? msg : msg());
    }
  }
  function decodeUtf8String(buffer) {
    return new TextDecoder().decode(buffer);
  }
  var import_onnx, ArrayUtil, MatMulUtil, BroadcastUtil, GemmUtil, ProtoUtil, LongUtil, ShapeUtil, SplitUtil, PoolConvUtil, MIN_CLIP, MAX_CLIP;
  var init_util = __esm({
    "web/lib/onnxjs/util.ts"() {
      "use strict";
      init_flatbuffers();
      init_long();
      import_onnx = __toESM(require_onnx());
      init_tensor2();
      ArrayUtil = class {
        /**
         * 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;
        }
      };
      MatMulUtil = class {
        /**
         * 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) {
          const a = dimsA.length === 1 ? [1, dimsA[0]] : dimsA;
          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) {
          if (aRank === 1) {
            outputShape.splice(outputShape.length - 2, 1);
          }
          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] ? void 0 : [a[0], b[1]];
        }
      };
      BroadcastUtil = 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);
          if (isMatMul) {
            if (arank < 2 || brank < 2) {
              return void 0;
            }
            const cShapeMatMul = MatMulUtil.calcMatMulShape([adims[arank - 2], adims[arank - 1]], [bdims[brank - 2], bdims[brank - 1]]);
            if (cShapeMatMul === void 0) {
              return void 0;
            }
            [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 void 0;
            }
            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) {
          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) {
          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)) {
              return void 0;
            }
            const size = ShapeUtil.size(outputShape);
            const c = inplace ? a : new Tensor3(outputShape, resultType || a.type);
            if (outputShape.length === 0) {
              c.set([], op(a.get([]), b.get([])));
            } 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++) {
                rest = i;
                for (let j = outputShape.length - 1; j >= 0; j--) {
                  outputIndices[j] = rest % outputShape[j];
                  rest = Math.floor(rest / outputShape[j]);
                }
                if (!isAScalar) {
                  _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 void 0;
        }
        /**
         * Determine if a shape is unidirectional broadcastable to another shape
         * @param shape The input shape
         * @param finalShape The desired shape after broadcasting
         */
        static isValidBroadcast(shape2, finalShape) {
          const inputRank = shape2.length;
          const finalRank = finalShape.length;
          if (inputRank > finalRank) {
            return false;
          }
          for (let i = 1; i <= inputRank; i++) {
            if (shape2[inputRank - i] !== 1 && shape2[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;
        }
      };
      GemmUtil = class {
        // 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];
        }
      };
      ProtoUtil = class _ProtoUtil {
        static tensorDataTypeFromProto(typeProto) {
          switch (typeProto) {
            case import_onnx.onnx.TensorProto.DataType.INT8:
              return "int8";
            case import_onnx.onnx.TensorProto.DataType.UINT8:
              return "uint8";
            case import_onnx.onnx.TensorProto.DataType.BOOL:
              return "bool";
            case import_onnx.onnx.TensorProto.DataType.INT16:
              return "int16";
            case import_onnx.onnx.TensorProto.DataType.UINT16:
              return "uint16";
            case import_onnx.onnx.TensorProto.DataType.INT32:
              return "int32";
            case import_onnx.onnx.TensorProto.DataType.UINT32:
              return "uint32";
            case import_onnx.onnx.TensorProto.DataType.FLOAT:
              return "float32";
            case import_onnx.onnx.TensorProto.DataType.DOUBLE:
              return "float64";
            case import_onnx.onnx.TensorProto.DataType.STRING:
              return "string";
            case import_onnx.onnx.TensorProto.DataType.INT64:
              return "int32";
            case import_onnx.onnx.TensorProto.DataType.UINT64:
              return "uint32";
            default:
              throw new Error(`unsupported data type: ${import_onnx.onnx.TensorProto.DataType[typeProto]}`);
          }
        }
        static tensorDataTypeStringToEnum(type) {
          switch (type) {
            case "int8":
              return import_onnx.onnx.TensorProto.DataType.INT8;
            case "uint8":
              return import_onnx.onnx.TensorProto.DataType.UINT8;
            case "bool":
              return import_onnx.onnx.TensorProto.DataType.BOOL;
            case "int16":
              return import_onnx.onnx.TensorProto.DataType.INT16;
            case "uint16":
              return import_onnx.onnx.TensorProto.DataType.UINT16;
            case "int32":
              return import_onnx.onnx.TensorProto.DataType.INT32;
            case "uint32":
              return import_onnx.onnx.TensorProto.DataType.UINT32;
            case "float32":
              return import_onnx.onnx.TensorProto.DataType.FLOAT;
            case "float64":
              return import_onnx.onnx.TensorProto.DataType.DOUBLE;
            case "string":
              return import_onnx.onnx.TensorProto.DataType.STRING;
            case "int64":
              return import_onnx.onnx.TensorProto.DataType.INT64;
            case "uint64":
              return import_onnx.onnx.TensorProto.DataType.UINT64;
            default:
              throw new Error(`unsupported data type: ${type}`);
          }
        }
        static tensorDimsFromProto(dims) {
          return dims.map((d) => long_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;
        }
      };
      LongUtil = class {
        // 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_default.isLong(n)) {
            return n.toNumber();
          } else if (n instanceof flatbuffers.Long) {
            return long_default.fromValue({ low: n.low, high: n.high, unsigned: unsigned ?? false }).toNumber();
          }
          return n;
        }
        static isLong(n) {
          return long_default.isLong(n) || n instanceof flatbuffers.Long;
        }
      };
      ShapeUtil = 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++) {
            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 === void 0) {
            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 === void 0) {
            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) {
          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;
          } 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();
          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);
          outputDims.fill(0);
          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;
          }
          let inputDimsIterator = 0;
          for (let i = 0; i < outputDims.length; i++) {
            if (outputDims[i] === 0) {
              outputDims[i] = dims[inputDimsIterator++];
            }
          }
          if (inputDimsIterator !== dims.length) {
            throw new Error("the unsqueezed dimension could not be established");
          }
          return outputDims;
        }
      };
      SplitUtil = 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, split2, numOutputs) {
          if (split2.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, split2);
          }
          const shapes = [];
          const offsets = [0];
          for (let i = 0; i < split2.length; ++i) {
            if (i !== 0) {
              offsets.push(offsets[i - 1] + split2[i - 1]);
            }
            const shape2 = dims.slice();
            shape2[axis] = split2[i];
            shapes.push(shape2);
          }
          return [shapes, offsets];
        }
        static determineSplit(numElementsAlongAxis, numOutputs, split2) {
          if (numElementsAlongAxis % numOutputs !== 0) {
            throw new Error("cannot split tensor to equal sized parts");
          }
          for (let i = 0; i < numOutputs; ++i) {
            split2.push(numElementsAlongAxis / numOutputs);
          }
        }
      };
      PoolConvUtil = 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) {
            for (let dim = 0; dim < inputDims.length - 2; dim++) {
              if (dim >= kernelShape.length) {
                kernelShape.push(inputDims[dim + 2]);
              } else {
                kernelShape[dim] = inputDims[dim + 2];
              }
            }
          }
          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);
            }
          }
          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);
            }
          }
          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);
            }
          }
          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");
          }
          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");
          }
          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);
          }
        }
      };
      MIN_CLIP = -34028234663852886e22;
      MAX_CLIP = 34028234663852886e22;
    }
  });

  // web/lib/onnxjs/tensor.ts
  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 import_onnx2.onnx.TensorProto.DataType.UINT8:
      case import_onnx2.onnx.TensorProto.DataType.INT8:
      case import_onnx2.onnx.TensorProto.DataType.BOOL:
        return 1;
      case import_onnx2.onnx.TensorProto.DataType.UINT16:
      case import_onnx2.onnx.TensorProto.DataType.INT16:
        return 2;
      case import_onnx2.onnx.TensorProto.DataType.FLOAT:
      case import_onnx2.onnx.TensorProto.DataType.INT32:
      case import_onnx2.onnx.TensorProto.DataType.UINT32:
        return 4;
      case import_onnx2.onnx.TensorProto.DataType.INT64:
      case import_onnx2.onnx.TensorProto.DataType.DOUBLE:
      case import_onnx2.onnx.TensorProto.DataType.UINT64:
        return 8;
      default:
        throw new Error(`cannot calculate sizeof() on type ${import_onnx2.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 "int64":
        return BigInt64Array;
      case "float32":
        return Float32Array;
      case "float64":
        return Float64Array;
      default:
        throw new Error("unspecified error");
    }
  }
  function longToNumber(i, type) {
    if (type === import_onnx2.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 === import_onnx2.onnx.TensorProto.DataType.UINT32 || type === ortFbs.TensorDataType.UINT32 || type === import_onnx2.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: ${import_onnx2.onnx.TensorProto.DataType[type]}`);
    }
    return i.toNumber();
  }
  function readProto(view, type, byteOffset) {
    switch (type) {
      case import_onnx2.onnx.TensorProto.DataType.BOOL:
      case import_onnx2.onnx.TensorProto.DataType.UINT8:
        return view.getUint8(byteOffset);
      case import_onnx2.onnx.TensorProto.DataType.INT8:
        return view.getInt8(byteOffset);
      case import_onnx2.onnx.TensorProto.DataType.UINT16:
        return view.getUint16(byteOffset, true);
      case import_onnx2.onnx.TensorProto.DataType.INT16:
        return view.getInt16(byteOffset, true);
      case import_onnx2.onnx.TensorProto.DataType.FLOAT:
        return view.getFloat32(byteOffset, true);
      case import_onnx2.onnx.TensorProto.DataType.INT32:
        return view.getInt32(byteOffset, true);
      case import_onnx2.onnx.TensorProto.DataType.UINT32:
        return view.getUint32(byteOffset, true);
      case import_onnx2.onnx.TensorProto.DataType.INT64:
        return longToNumber(
          long_default.fromBits(view.getUint32(byteOffset, true), view.getUint32(byteOffset + 4, true), false),
          type
        );
      case import_onnx2.onnx.TensorProto.DataType.DOUBLE:
        return view.getFloat64(byteOffset, true);
      case import_onnx2.onnx.TensorProto.DataType.UINT64:
        return longToNumber(
          long_default.fromBits(view.getUint32(byteOffset, true), view.getUint32(byteOffset + 4, true), true),
          type
        );
      default:
        throw new Error(`cannot read from DataView for type ${import_onnx2.onnx.TensorProto.DataType[type]}`);
    }
  }
  var import_guid_typescript, import_onnx2, ortFbs, Tensor3;
  var init_tensor2 = __esm({
    "web/lib/onnxjs/tensor.ts"() {
      "use strict";
      import_guid_typescript = __toESM(require_guid());
      init_long();
      init_ort_generated();
      import_onnx2 = __toESM(require_onnx());
      init_util();
      ortFbs = onnxruntime.experimental.fbs;
      Tensor3 = class _Tensor {
        constructor(dims, type, dataProvider, asyncDataProvider, cache2, dataId = import_guid_typescript.Guid.create()) {
          this.dims = dims;
          this.type = type;
          this.dataProvider = dataProvider;
          this.asyncDataProvider = asyncDataProvider;
          this.cache = cache2;
          this.dataId = dataId;
          this.size = ShapeUtil.validateDimsAndCalcSize(dims);
          const size = this.size;
          const empty = dataProvider === void 0 && asyncDataProvider === void 0 && cache2 === void 0;
          if (cache2 !== void 0) {
            if (cache2.length !== size) {
              throw new RangeError("Input dims doesn't match data length.");
            }
          }
          if (type === "string") {
            if (cache2 !== void 0 && (!Array.isArray(cache2) || !cache2.every((i) => typeof i === "string"))) {
              throw new TypeError("cache should be a string array");
            }
            if (empty) {
              this.cache = new Array(size);
            }
          } else {
            if (cache2 !== void 0) {
              const constructor = dataviewConstructor(type);
              if (!(cache2 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);
            }
          }
        }
        /**
         * get the underlying tensor data
         */
        get data() {
          if (this.cache === void 0) {
            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[ShapeUtil.indicesToOffset(indices, this.strides)];
        }
        /**
         * set value of an element at the given indices
         */
        set(indices, value) {
          this.data[ShapeUtil.indicesToOffset(indices, this.strides)] = value;
        }
        /**
         * get the underlying tensor data asynchronously
         */
        async getData() {
          if (this.cache === void 0) {
            this.cache = await this.asyncDataProvider(this.dataId);
          }
          return this.cache;
        }
        /**
         * get the strides for each dimension
         */
        get strides() {
          if (!this._strides) {
            this._strides = ShapeUtil.computeStrides(this.dims);
          }
          return this._strides;
        }
        /**
         * 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 = ProtoUtil.tensorDataTypeFromProto(tensorProto.dataType);
          const dims = ProtoUtil.tensorDimsFromProto(tensorProto.dims);
          const value = new _Tensor(dims, type);
          if (type === "string") {
            tensorProto.stringData.forEach((str, i) => {
              value.data[i] = decodeUtf8String(str);
            });
          } else if (tensorProto.rawData && typeof tensorProto.rawData.byteLength === "number" && tensorProto.rawData.byteLength > 0) {
            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 {
            let array;
            switch (tensorProto.dataType) {
              case import_onnx2.onnx.TensorProto.DataType.FLOAT:
                array = tensorProto.floatData;
                break;
              case import_onnx2.onnx.TensorProto.DataType.INT32:
              case import_onnx2.onnx.TensorProto.DataType.INT16:
              case import_onnx2.onnx.TensorProto.DataType.UINT16:
              case import_onnx2.onnx.TensorProto.DataType.INT8:
              case import_onnx2.onnx.TensorProto.DataType.UINT8:
              case import_onnx2.onnx.TensorProto.DataType.BOOL:
                array = tensorProto.int32Data;
                break;
              case import_onnx2.onnx.TensorProto.DataType.INT64:
                array = tensorProto.int64Data;
                break;
              case import_onnx2.onnx.TensorProto.DataType.DOUBLE:
                array = tensorProto.doubleData;
                break;
              case import_onnx2.onnx.TensorProto.DataType.UINT32:
              case import_onnx2.onnx.TensorProto.DataType.UINT64:
                array = tensorProto.uint64Data;
                break;
              default:
                throw new Error("unspecific error");
            }
            if (array === null || array === void 0) {
              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_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, void 0, void 0, data);
        }
        static fromOrtTensor(ortTensor) {
          if (!ortTensor) {
            throw new Error("cannot construct Value from an empty tensor");
          }
          const dims = ProtoUtil.tensorDimsFromORTFormat(ortTensor);
          const type = ProtoUtil.tensorDataTypeFromProto(ortTensor.dataType());
          const value = new _Tensor(dims, type);
          if (type === "string") {
            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) {
            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;
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/glsl-source.ts
  function getGlsl(version3) {
    return version3 === 1 ? GLSL_ES_2_0 : GLSL_ES_3_0;
  }
  function getVertexShaderSource(version3) {
    const glsl = getGlsl(version3);
    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;
      }`;
  }
  function getFragShaderPreamble(version3) {
    const glsl = getGlsl(version3);
    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);
    }

    `;
  }
  function getDefaultFragShaderMain(version3, outputShapeLength) {
    const glsl = getGlsl(version3);
    return `
  void main() {
    int indices[${outputShapeLength}];
    toVec(TexCoords, indices);
    vec4 result = vec4(process(indices));
    ${glsl.output} = result;
  }
  `;
  }
  var GLSL_ES_2_0, GLSL_ES_3_0;
  var init_glsl_source = __esm({
    "web/lib/onnxjs/backends/webgl/glsl-source.ts"() {
      "use strict";
      GLSL_ES_2_0 = {
        version: "",
        attribute: "attribute",
        varyingVertex: "varying",
        varyingFrag: "varying",
        texture2D: "texture2D",
        output: "gl_FragColor",
        outputDeclaration: ""
      };
      GLSL_ES_3_0 = {
        version: "#version 300 es",
        attribute: "in",
        varyingVertex: "out",
        varyingFrag: "in",
        texture2D: "texture",
        output: "outputColor",
        outputDeclaration: "out vec4 outputColor;"
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/types.ts
  var init_types = __esm({
    "web/lib/onnxjs/backends/webgl/types.ts"() {
      "use strict";
    }
  });

  // web/lib/onnxjs/backends/webgl/utils.ts
  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();
    });
  }
  function generateShaderFuncNameFromInputSamplerName(samplerName) {
    assert(typeof samplerName !== "undefined" && samplerName.length !== 0, () => "empty string found for sampler name");
    return "get" + samplerName.charAt(0).toUpperCase() + samplerName.slice(1);
  }
  function generateShaderFuncNameFromInputSamplerNameAtOutCoords(samplerName) {
    assert(typeof samplerName !== "undefined" && samplerName.length !== 0, () => "empty string found for sampler name");
    return "get" + samplerName.charAt(0).toUpperCase() + samplerName.slice(1) + "AtOutCoords";
  }
  function squeezeInputShape(inputShape, squeezedShape) {
    let newInputShape = JSON.parse(JSON.stringify(inputShape));
    newInputShape = squeezedShape;
    return newInputShape;
  }
  function getSqueezedParams(params, keptDims) {
    return keptDims.map((d) => params[d]).join(", ");
  }
  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`);
    }
  }
  function getGlChannels(rank = 6) {
    return ["x", "y", "z", "w", "u", "v"].slice(0, rank);
  }
  var init_utils = __esm({
    "web/lib/onnxjs/backends/webgl/utils.ts"() {
      "use strict";
      init_util();
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/packing-utils.ts
  function getVecChannels(name2, rank) {
    return getGlChannels(rank).map((d) => `${name2}.${d}`);
  }
  function getChannels(name2, rank) {
    if (rank === 1) {
      return [name2];
    }
    return getVecChannels(name2, rank);
  }
  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);
    }
  `;
  }
  var init_packing_utils = __esm({
    "web/lib/onnxjs/backends/webgl/ops/packing-utils.ts"() {
      "use strict";
      init_utils();
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/pack.ts
  function getOutOfBoundsCondition(rank, shape2, dims) {
    if (rank === 0) {
      return "false";
    }
    if (rank === 1) {
      return `rc > ${shape2[0]}`;
    }
    let cond = "";
    for (let i = rank - 2; i < rank; i++) {
      cond += `${dims[i]} >= ${shape2[i - rank + 2]}`;
      if (i < rank - 1) {
        cond += "||";
      }
    }
    return cond;
  }
  function getOutput(shape2, dims) {
    const rank = shape2.length;
    if (rank === 0) {
      return "getA(), 0, 0, 0";
    }
    if (rank === 1) {
      return `getA(rc),
            rc + 1 >= ${shape2[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})`;
  }
  function getSetup(rank, dims, rows, cols) {
    if (rank === 0 || rank === 1) {
      return "";
    } 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;
    }
  }
  var packProgramMetadata, createPackProgramInfo, createPackProgramInfoLoader;
  var init_pack = __esm({
    "web/lib/onnxjs/backends/webgl/ops/pack.ts"() {
      "use strict";
      init_glsl_source();
      init_types();
      init_utils();
      init_packing_utils();
      packProgramMetadata = {
        name: "pack",
        inputNames: ["A"],
        inputTypes: [1 /* unpackedReversed */]
      };
      createPackProgramInfo = (handler, input) => {
        const glsl = getGlsl(handler.session.backend.glContext.version);
        const inputShape = input.dims;
        const inputRank = inputShape.length;
        const outputRank = input.dims.length;
        const coordsDataType = getCoordsDataType(outputRank);
        const channels = 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 {
          ...packProgramMetadata,
          hasMain: true,
          output: { dims: input.dims, type: input.type, textureType: 2 /* packed */ },
          shaderSource
        };
      };
      createPackProgramInfoLoader = (handler, input) => ({ ...packProgramMetadata, get: () => createPackProgramInfo(handler, input) });
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/reshape-packed.ts
  function processDims3D(shape2) {
    if (shape2.length === 0) {
      return [1, 1, 1];
    }
    let batch = 1;
    for (let i = 0; i < shape2.length - 2; ++i) {
      batch *= shape2[i];
    }
    return [batch, shape2.length > 1 ? shape2[shape2.length - 2] : 1, shape2[shape2.length - 1]];
  }
  function isReshapeCheap(dims, reshapedDims) {
    let isCheapReshape = false;
    if (dims.length === 0 || reshapedDims.length === 0) {
      isCheapReshape = true;
    } else if (dims.length < 2 || reshapedDims.length < 2) {
      isCheapReshape = dims[dims.length - 1] === reshapedDims[reshapedDims.length - 1];
    } else {
      isCheapReshape = dims[dims.length - 1] === reshapedDims[reshapedDims.length - 1] && dims[dims.length - 2] === reshapedDims[reshapedDims.length - 2];
    }
    return isCheapReshape;
  }
  function getReshapedInputCoords(shape2) {
    const strides = ShapeUtil.computeStrides(shape2);
    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(shape2) {
    const strides = ShapeUtil.computeStrides(shape2);
    return `
  int getFlattenedIndex(ivec3 coords) {
    // reverse y, z order
    return coords.x * ${strides[0]} + coords.z * ${strides[1]} + coords.y;
  }
`;
  }
  var createPackedReshape3DProgramMetadata, createPackedReshape3DProgramInfo, createPackedReshape3DProgramInfoLoader;
  var init_reshape_packed = __esm({
    "web/lib/onnxjs/backends/webgl/ops/reshape-packed.ts"() {
      "use strict";
      init_util();
      init_glsl_source();
      init_types();
      init_packing_utils();
      createPackedReshape3DProgramMetadata = (outputShape3D) => ({ name: "Reshape (packed)", inputTypes: [2 /* packed */], inputNames: ["A"], cacheHint: `${outputShape3D}` });
      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 = getGlsl(handler.session.backend.glContext.version);
        const shaderSource = `
      ${getReshapedInputCoords(inputShape3D)}
      ${getFlattenedIndexFrom3D(squeezedOutputShape)}
      ${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 {
          ...metadata,
          output: { dims: squeezedOutputShape, type: input3D.type, textureType: 2 /* packed */ },
          shaderSource,
          hasMain: true
        };
      };
      createPackedReshape3DProgramInfoLoader = (handler, input3D, outputShape3D) => {
        const metadata = createPackedReshape3DProgramMetadata(outputShape3D);
        return { ...metadata, get: () => createPackedReshape3DProgramInfo(handler, input3D, metadata, outputShape3D) };
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/uint8-encode.ts
  var encodeAsUint8;
  var init_uint8_encode = __esm({
    "web/lib/onnxjs/backends/webgl/ops/uint8-encode.ts"() {
      "use strict";
      init_glsl_source();
      init_types();
      encodeAsUint8 = (inferenceHandler, input) => {
        const outputShape = input.shape;
        const glsl = getGlsl(inferenceHandler.session.backend.glContext.version);
        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: [0 /* unpacked */],
          inputNames: ["X"],
          output: { dims: outputShape, type: input.tensor.type, textureType: 3 /* downloadUint8AsFloat */ },
          shaderSource,
          hasMain: true
        };
        return inferenceHandler.executeProgram(programInfo, [input.tensor]);
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/unpack.ts
  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;
  }
  var unpackProgramMetadata, createUnpackProgramInfo, createUnpackProgramInfoLoader;
  var init_unpack = __esm({
    "web/lib/onnxjs/backends/webgl/ops/unpack.ts"() {
      "use strict";
      init_glsl_source();
      init_types();
      init_utils();
      init_packing_utils();
      unpackProgramMetadata = {
        name: "unpack",
        inputNames: ["A"],
        inputTypes: [2 /* packed */]
      };
      createUnpackProgramInfo = (handler, input) => {
        const rank = input.dims.length;
        const channels = getChannels("rc", rank);
        const innerDims = channels.slice(-2);
        const coordsDataType = getCoordsDataType(rank);
        const unpackChannel = unpackFromChannel();
        const isScalar = input.dims.length === 0;
        const sourceCoords = isScalar ? "" : getSourceCoords(rank, channels);
        const coords = rank <= 1 ? "rc" : `vec2(${innerDims.join(",")})`;
        const glsl = 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 {
          ...unpackProgramMetadata,
          hasMain: true,
          output: { dims: input.dims, type: input.type, textureType: 0 /* unpacked */ },
          shaderSource
        };
      };
      createUnpackProgramInfoLoader = (handler, input) => ({ ...unpackProgramMetadata, get: () => createUnpackProgramInfo(handler, input) });
    }
  });

  // web/lib/onnxjs/backends/webgl/texture-data-encoder.ts
  var RedFloat32DataEncoder, RGBAFloatDataEncoder, Uint8DataEncoder;
  var init_texture_data_encoder = __esm({
    "web/lib/onnxjs/backends/webgl/texture-data-encoder.ts"() {
      "use strict";
      init_instrument();
      RedFloat32DataEncoder = class {
        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) {
            Logger.warning("Encoder", "data was not of type Float32; creating new Float32Array");
            source = new Float32Array(src);
          }
          if (textureSize * this.channelSize > src.length) {
            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);
        }
      };
      RGBAFloatDataEncoder = class {
        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) {
            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);
        }
      };
      Uint8DataEncoder = class {
        constructor(gl, channels = 1) {
          this.channelSize = 4;
          if (channels === 1) {
            this.internalFormat = gl.ALPHA;
            this.format = gl.ALPHA;
            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}`);
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/texture-layout.ts
  var createTextureLayoutFromTextureType, calculateTextureWidthAndHeight, createTextureLayoutFromShape;
  var init_texture_layout = __esm({
    "web/lib/onnxjs/backends/webgl/texture-layout.ts"() {
      "use strict";
      init_util();
      init_types();
      createTextureLayoutFromTextureType = (textureLayoutStrategy, shape2, textureType) => {
        const channel = textureType === 0 /* unpacked */ || textureType === 1 /* unpackedReversed */ ? 1 : 4;
        const isPacked = textureType === 2 /* packed */;
        const reverseWH = textureType === 1 /* unpackedReversed */ || textureType === 2 /* packed */;
        const breakAxis = textureType === 4 /* packedLastDimension */ ? shape2.length - 1 : void 0;
        const unpackedShape = textureType === 4 /* packedLastDimension */ ? shape2.map((d, i) => i === shape2.length - 1 ? d * 4 : d) : void 0;
        return createTextureLayoutFromShape(
          textureLayoutStrategy,
          shape2,
          channel,
          unpackedShape,
          { isPacked, reverseWH, breakAxis }
        );
      };
      calculateTextureWidthAndHeight = (textureLayoutStrategy, shape2, textureType) => {
        const layout = createTextureLayoutFromTextureType(textureLayoutStrategy, shape2, textureType);
        return [layout.width, layout.height];
      };
      createTextureLayoutFromShape = (textureLayoutStrategy, shape2, channels = 1, unpackedShape, prefs) => {
        const isPacked = !!(prefs && prefs.isPacked);
        const [width, height] = textureLayoutStrategy.computeTextureWH(isPacked ? unpackedShape || shape2 : shape2, prefs);
        const rank = shape2.length;
        let inferredDims = shape2.slice(0);
        if (rank === 0) {
          inferredDims = [1];
        }
        if (channels === 1) {
          unpackedShape = shape2;
        } else if (isPacked) {
          if (channels !== 4) {
            throw new Error("a packed texture must be 4-channel");
          }
          unpackedShape = shape2;
          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: ShapeUtil.computeStrides(inferredDims),
          unpackedShape,
          reversedWH: prefs && prefs.reverseWH
        };
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/inference-handler.ts
  var getProgramInfoUniqueKey, WebGLInferenceHandler;
  var init_inference_handler = __esm({
    "web/lib/onnxjs/backends/webgl/inference-handler.ts"() {
      "use strict";
      init_instrument();
      init_tensor2();
      init_util();
      init_pack();
      init_reshape_packed();
      init_uint8_encode();
      init_unpack();
      init_texture_data_encoder();
      init_texture_layout();
      init_types();
      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;
      };
      WebGLInferenceHandler = class {
        constructor(session) {
          this.session = session;
          this.packedTextureDataCache = /* @__PURE__ */ new Map();
          this.unpackedTextureDataCache = /* @__PURE__ */ new Map();
        }
        /**
         * @returns [width, height]
         */
        calculateTextureWidthAndHeight(shape2, textureType) {
          return calculateTextureWidthAndHeight(this.session.layoutStrategy, shape2, 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");
          }
          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;
          const outputTextureLayout = 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) {
          for (let i = 0; i < inputs.length; ++i) {
            if (!!inputs[i].isPacked !== (artifact.programInfo.inputTypes[i] === 2 /* packed */)) {
              throw new Error(`input[${i}] property packed inconsistent`);
            }
          }
          if (!!output.isPacked !== (artifact.programInfo.output.textureType === 2 /* packed */)) {
            throw new Error("output property packed inconsistent");
          }
          this.session.programManager.run(artifact, inputs, output);
        }
        /**
         * Create a TextureData object from a tensor.
         * Usage = EncoderUsage.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 === 2 /* packed */);
          if (!td) {
            td = this.getTextureData(tensor.dataId, textureType !== 2 /* packed */);
            if (td) {
              if (textureType === 2 /* packed */) {
                return this.pack(td);
              } else {
                return this.unpack(td);
              }
            }
          }
          if (!td) {
            const layout = createTextureLayoutFromTextureType(this.session.layoutStrategy, tensor.dims, textureType);
            if (textureType === 4 /* packedLastDimension */) {
              const group = 1;
              const channels = 4;
              const shape2 = tensor.dims;
              if (shape2.length === 4) {
                const adjustedKernelShape = [shape2[0], Math.ceil(shape2[1] * shape2[2] * shape2[3] / channels)];
                const adjustedLayout = createTextureLayoutFromTextureType(this.session.layoutStrategy, adjustedKernelShape, textureType);
                let buffer = tensor.numberData;
                if (shape2[1] * shape2[2] * shape2[3] % channels !== 0) {
                  const numFeatureMaps = shape2[0];
                  const oldRowSize = shape2[1] * shape2[2] * shape2[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 /* UploadOnly */);
              }
            }
            if (textureType === 2 /* packed */) {
              const unpackedTextureLayout = createTextureLayoutFromShape(this.session.layoutStrategy, tensor.dims, 1, [], { reverseWH: true });
              const unpackedTextureData = this.createTextureData(
                unpackedTextureLayout,
                tensor.type,
                tensor.numberData,
                tensor,
                1 /* UploadOnly */
              );
              td = this.pack(unpackedTextureData);
            } else {
              td = this.createTextureData(layout, tensor.type, tensor.numberData, tensor, 1 /* UploadOnly */);
            }
          }
          return td;
        }
        /**
         * Create a TextureData object using the given data and bind to the given tensor.
         * Usage = EncoderUsage.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 /* UploadOnly */);
        }
        createTextureData(layout, dataType, data, tensor, usage) {
          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, 0 /* unpacked */);
          const newTextureLayout = {
            channels: inputTD.channels,
            height: inputTD.height,
            width: inputTD.width,
            // handle reshaping into scalar Tensors
            shape: reshapedDims.length !== 0 ? reshapedDims : [1],
            strides: 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, 2 /* packed */);
          if (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: ShapeUtil.computeStrides(reshapedDims),
              unpackedShape: reshapedDims,
              isPacked: true
            };
            const newTextureData = this.createTextureDataFromTexture(newTextureLayout, input.type, inputTD.texture);
            return newTextureData.tensor;
          }
          const squeezedInputShape = processDims3D(input.dims);
          const squeezedOutputShape = processDims3D(reshapedDims);
          const squeezedInputTensor = this.reshapePacked(input, squeezedInputShape);
          const squeezedOutputTensor = this.run(
            createPackedReshape3DProgramInfoLoader(this, squeezedInputTensor, squeezedOutputShape),
            [squeezedInputTensor]
          );
          const outputTensor = this.reshapePacked(squeezedOutputTensor, reshapedDims);
          return outputTensor;
        }
        cast(input, type) {
          const inputTD = this.getOrCreateTextureData(input, 0 /* unpacked */);
          const newTextureData = this.createTextureDataFromTexture(inputTD, type, inputTD.texture);
          return newTextureData.tensor;
        }
        createTextureDataFromTexture(layout, dataType, texture, tensor, tensorId) {
          const textureData = {
            ...layout,
            tensor: tensor || new Tensor3(
              layout.unpackedShape,
              dataType,
              (_id) => this.readTexture(textureData),
              async (_id) => this.readTextureAsync(textureData),
              void 0,
              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 = /* @__PURE__ */ new Map();
          this.unpackedTextureDataCache.forEach((td) => this.session.textureManager.releaseTexture(td));
          this.unpackedTextureDataCache = /* @__PURE__ */ new Map();
        }
        readTexture(textureData) {
          if (textureData.isPacked) {
            return this.readTexture(this.unpack(textureData));
          }
          if (!this.session.backend.glContext.isFloat32DownloadSupported) {
            return this.session.textureManager.readUint8TextureAsFloat(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(encodeAsUint8(this, textureData));
          }
          return this.session.textureManager.readTextureAsync(textureData, textureData.tensor.type, textureData.channels);
        }
        pack(input) {
          const outputTextureData = this.executeProgram(createPackProgramInfoLoader(this, input.tensor), [input.tensor]);
          return outputTextureData;
        }
        unpack(input) {
          const outputTextureData = this.executeProgram(createUnpackProgramInfoLoader(this, input.tensor), [input.tensor]);
          return outputTextureData;
        }
      };
    }
  });

  // web/lib/onnxjs/attribute-with-cache-key.ts
  var AttributeWithCacheKeyImpl, createAttributeWithCacheKey;
  var init_attribute_with_cache_key = __esm({
    "web/lib/onnxjs/attribute-with-cache-key.ts"() {
      "use strict";
      AttributeWithCacheKeyImpl = class {
        constructor(attribute) {
          Object.assign(this, attribute);
        }
        get cacheKey() {
          if (!this.key) {
            this.key = Object.getOwnPropertyNames(this).sort().map((name2) => `${this[name2]}`).join(";");
          }
          return this.key;
        }
      };
      createAttributeWithCacheKey = (attribute) => new AttributeWithCacheKeyImpl(attribute);
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/batch-normalization.ts
  var batchNormalizationProgramMetadata, batchNormalization, parseBatchNormalizationAttributes, createBatchNormalizationProgramInfo, validateInputs;
  var init_batch_normalization = __esm({
    "web/lib/onnxjs/backends/webgl/ops/batch-normalization.ts"() {
      "use strict";
      init_attribute_with_cache_key();
      init_glsl_source();
      init_types();
      batchNormalizationProgramMetadata = {
        name: "BatchNormalization",
        inputNames: ["A", "Scale", "B", "Mean", "Variance"],
        inputTypes: [0 /* unpacked */, 0 /* unpacked */, 0 /* unpacked */, 0 /* unpacked */, 0 /* unpacked */]
      };
      batchNormalization = (inferenceHandler, inputs, attributes) => {
        validateInputs(inputs);
        const output = inferenceHandler.run(
          {
            ...batchNormalizationProgramMetadata,
            cacheHint: attributes.cacheKey,
            get: () => createBatchNormalizationProgramInfo(inferenceHandler, inputs, attributes)
          },
          inputs
        );
        return [output];
      };
      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 createAttributeWithCacheKey({ epsilon, momentum, spatial });
      };
      createBatchNormalizationProgramInfo = (inferenceHandler, inputs, attributes) => {
        const glsl = getGlsl(inferenceHandler.session.backend.glContext.version);
        const rank = inputs[0].dims.length;
        const [scaleWidth, scaleHeight] = inferenceHandler.calculateTextureWidthAndHeight(inputs[1].dims, 0 /* 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 {
          ...batchNormalizationProgramMetadata,
          output: { dims: inputs[0].dims, type: inputs[0].type, textureType: 0 /* unpacked */ },
          shaderSource
        };
      };
      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];
        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.");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/glsl-definitions.ts
  var GlslContext, GlslLib, GlslLibRoutine, GlslLibRoutineNode, TopologicalSortGlslRoutines;
  var init_glsl_definitions = __esm({
    "web/lib/onnxjs/backends/webgl/glsl-definitions.ts"() {
      "use strict";
      GlslContext = class {
        constructor(glContext, programInfo, inputTextureLayouts, outputTextureLayout) {
          this.glContext = glContext;
          this.programInfo = programInfo;
          this.inputTextureLayouts = inputTextureLayouts;
          this.outputTextureLayout = outputTextureLayout;
        }
      };
      GlslLib = class {
        constructor(context) {
          this.context = context;
        }
      };
      GlslLibRoutine = class {
        constructor(routineBody, dependencies) {
          this.routineBody = routineBody;
          this.dependencies = dependencies;
        }
      };
      GlslLibRoutineNode = class {
        constructor(name2, routineBody, dependencies) {
          this.name = name2;
          if (dependencies) {
            this.dependencies = dependencies;
          } else {
            this.dependencies = [];
          }
          if (routineBody) {
            this.routineBody = routineBody;
          }
        }
        addDependency(node) {
          if (node) {
            this.dependencies.push(node);
          }
        }
      };
      TopologicalSortGlslRoutines = class {
        static returnOrderedNodes(nodes) {
          if (!nodes || nodes.length === 0) {
            return [];
          }
          if (nodes.length === 1) {
            return nodes;
          }
          const cycleCheck = /* @__PURE__ */ new Set();
          const alreadyTraversed = /* @__PURE__ */ 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 (!root || alreadyTraversed.has(root.name)) {
            return;
          }
          if (cycleCheck.has(root.name)) {
            throw new Error("Cyclic dependency detected. Can't topologically sort routines needed for shader.");
          }
          cycleCheck.add(root.name);
          const dependencies = root.dependencies;
          if (dependencies && dependencies.length > 0) {
            for (let i = 0; i < dependencies.length; ++i) {
              this.dfsTraverse(dependencies[i], cycleCheck, alreadyTraversed, result);
            }
          }
          result.push(root);
          alreadyTraversed.add(root.name);
          cycleCheck.delete(root.name);
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/binary-op.ts
  function glslAdd() {
    const name2 = "add_";
    const body = `
  float ${name2}(float a, float b) {
    return a + b;
  }
  vec4 ${name2}(vec4 v1, vec4 v2) {
    return v1 + v2;
  }
  `;
    return { body, name: name2, type: 0 /* ValueBased */ };
  }
  function glslDiv() {
    const name2 = "div_";
    const body = `
  float ${name2}(float a, float b) {
    return a / b;
  }
  vec4 ${name2}(vec4 v1, vec4 v2) {
    return v1 / v2;
  }
  `;
    return { body, name: name2, type: 0 /* ValueBased */ };
  }
  function glslMul() {
    const name2 = "mul_";
    const body = `
  float ${name2}(float a, float b) {
    return a * b;
  }
  vec4 ${name2}(vec4 v1, vec4 v2) {
    return v1 * v2;
  }
  `;
    return { body, name: name2, type: 0 /* ValueBased */ };
  }
  function glslSub() {
    const name2 = "sub_";
    const body = `
  float ${name2}(float a, float b) {
    return a - b;
  }
  vec4 ${name2}(vec4 v1, vec4 v2) {
    return v1 - v2;
  }
  `;
    return { body, name: name2, type: 0 /* ValueBased */ };
  }
  function glslEqual() {
    const name2 = "equal_";
    const body = `
  float ${name2}(float a, float b) {
    return float(a == b);
  }
  vec4 ${name2}(vec4 v1, vec4 v2) {
    return vec4(equal(v1, v2));
  }
  `;
    return { body, name: name2, type: 0 /* ValueBased */ };
  }
  function glslGreater() {
    const name2 = "greater_";
    const body = `
  float ${name2}(float a, float b) {
    return float(a > b);
  }
  vec4 ${name2}(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: name2, type: 0 /* ValueBased */ };
  }
  function glslLess() {
    const name2 = "less_";
    const body = `
  float ${name2}(float a, float b) {
    return float(a < b);
  }
  vec4 ${name2}(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: name2, type: 0 /* ValueBased */ };
  }
  function glslAnd() {
    const name2 = "and_";
    const body = `
  float ${name2}(float a, float b) {
    return float( bool(a) && bool(b) );
  }
  vec4 ${name2}(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: name2, type: 0 /* ValueBased */ };
  }
  function glslOr() {
    const name2 = "or_";
    const body = `
  float ${name2}(float a, float b) {
    return float( bool(a) || bool(b) );
  }
  vec4 ${name2}(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: name2, type: 0 /* ValueBased */ };
  }
  function glslXor() {
    const name2 = "xor_";
    const body = `
  float ${name2}(float a, float b) {
    return float( bool(a) ^^ bool(b) );
  }
  vec4 ${name2}(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: name2, type: 0 /* ValueBased */ };
  }
  function glslPow() {
    return glslBuiltinBinary("pow");
  }
  function glslPRelu() {
    const name2 = "prelu_";
    const body = `
  float ${name2}(float a, float b) {
    return a < 0.0 ? a * b: a;
  }
  vec4 ${name2}(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: name2, type: 0 /* ValueBased */ };
  }
  function glslBuiltinBinary(fname) {
    const name2 = `${fname}_`;
    const body = `
  float ${name2}(float a, float b) {
    return ${fname}(a, b);
  }
  vec4 ${name2}(vec4 v1, vec4 v2) {
    return ${fname}(v1, v2);
  }
  `;
    return { body, name: name2, type: 0 /* ValueBased */ };
  }
  var createBinaryProgramInfoLoader, createBinaryProgramInfo, add2, and2, div, equal, greater, less, mul, or2, pow, pRelu, sub, xor2;
  var init_binary_op = __esm({
    "web/lib/onnxjs/backends/webgl/ops/binary-op.ts"() {
      "use strict";
      init_util();
      init_glsl_definitions();
      init_glsl_source();
      init_types();
      createBinaryProgramInfoLoader = (handler, inputs, glslFunc, outputTensorType = inputs[0].type, cacheKey) => {
        const textureType = handler.session.pack ? 2 /* packed */ : 0 /* unpacked */;
        return {
          name: glslFunc.name,
          inputNames: ["A", "B"],
          inputTypes: [textureType, textureType],
          cacheHint: cacheKey,
          get: () => createBinaryProgramInfo(handler, inputs, glslFunc, outputTensorType)
        };
      };
      createBinaryProgramInfo = (handler, inputs, glslFunc, outputTensorType = inputs[0].type) => {
        const textureType = handler.session.pack ? 2 /* packed */ : 0 /* unpacked */;
        const isBroadcast = !ShapeUtil.areEqual(inputs[0].dims, inputs[1].dims);
        let outputShape = inputs[0].dims;
        const usePackedTexture = handler.session.pack;
        if (isBroadcast) {
          const calculatedShape = 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 glsl2 = getGlsl(handler.session.backend.glContext.version);
          const shaderSource2 = usePackedTexture ? `
      ${glslFunc.body}
      void main() {
        vec4 a = getAAtOutCoords();
        vec4 b = getBAtOutCoords();
        vec4 result = ${glslFunc.name}(a, b);
        ${glsl2.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: shaderSource2,
            hasMain: usePackedTexture
          };
        }
        const glsl = 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
        };
      };
      add2 = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslAdd()), inputs)];
      and2 = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslAnd(), "bool"), inputs)];
      div = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslDiv()), inputs)];
      equal = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslEqual(), "bool"), inputs)];
      greater = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslGreater(), "bool"), inputs)];
      less = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslLess(), "bool"), inputs)];
      mul = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslMul()), inputs)];
      or2 = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslOr(), "bool"), inputs)];
      pow = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslPow()), inputs)];
      pRelu = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslPRelu()), inputs)];
      sub = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslSub()), inputs)];
      xor2 = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslXor(), "bool"), inputs)];
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/cast.ts
  var cast, parseCastAttributes, validateInputs2;
  var init_cast = __esm({
    "web/lib/onnxjs/backends/webgl/ops/cast.ts"() {
      "use strict";
      init_util();
      cast = (handler, inputs, to) => {
        validateInputs2(inputs);
        return [handler.cast(inputs[0], to)];
      };
      parseCastAttributes = (node) => ProtoUtil.tensorDataTypeFromProto(node.attributes.getInt("to"));
      validateInputs2 = (inputs) => {
        if (!inputs || inputs.length !== 1) {
          throw new Error("Cast requires 1 input.");
        }
        if (inputs[0].type === "string") {
          throw new Error("Invalid input type.");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/concat-packed.ts
  var createPackedConcatProgramMetadata, createPackedConcatProgramInfo, createPackedConcatProgramInfoLoader, getShiftedChannelsSnippet;
  var init_concat_packed = __esm({
    "web/lib/onnxjs/backends/webgl/ops/concat-packed.ts"() {
      "use strict";
      init_glsl_source();
      init_types();
      init_utils();
      init_packing_utils();
      createPackedConcatProgramMetadata = (inputCount, cacheHint) => ({
        name: "Concat (packed)",
        inputNames: Array.from({ length: inputCount }, (_v, i) => `X${i}`),
        inputTypes: Array(inputCount).fill(2 /* packed */),
        cacheHint
      });
      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;
        }
        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++) {
            if (axisIndex === axis) {
              outputShape[axis] += dataNShape[axisIndex];
            } else if (inputShape[axisIndex] !== dataNShape[axisIndex]) {
              throw new Error("non concat dimensions must match");
            }
          }
        }
        const rank = outputShape.length;
        const coords = getChannels("coords", rank);
        const dtype = getCoordsDataType(rank);
        const unpackChannel = unpackFromChannel();
        const shapes = inputs.map((i) => i.dims);
        const channels = 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 shift2 = offsets[i - 1];
          getValueSnippet += `
            if (${channel} < ${offsets[i]}  && ${channel} >= ${offsets[i - 1]}) {
              return getChannel(
                getX${i}(${getShiftedChannelsSnippet(channels, channel, shift2)}),
                vec2(${getShiftedChannelsSnippet(lastChannels, channel, shift2)}));
            }`;
        }
        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 = 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 {
          ...metadata,
          output: { dims: outputShape, type: inputs[0].type, textureType: 2 /* packed */ },
          shaderSource,
          hasMain: true
        };
      };
      createPackedConcatProgramInfoLoader = (handler, inputs, attributes) => {
        const metadata = createPackedConcatProgramMetadata(inputs.length, attributes.cacheKey);
        return { ...metadata, get: () => createPackedConcatProgramInfo(handler, metadata, inputs, attributes.axis) };
      };
      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();
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/concat.ts
  var concat, createUnpackedConcatProgramMetadata, createUnpackedConcatProgramInfo, createUnpackedConcatProgramInfoLoader, getTextureIndexWhereDataResidesLinearSearch, getTextureIndexWhereDataResidesBinarySearch, getFetchDataFromCorrectTextureMethod, getGetSizeInConcatAxisValueFromIndexMethod, parseConcatAttributes, validateInputs3;
  var init_concat = __esm({
    "web/lib/onnxjs/backends/webgl/ops/concat.ts"() {
      "use strict";
      init_attribute_with_cache_key();
      init_types();
      init_concat_packed();
      concat = (inferenceHandler, inputs, attributes) => {
        validateInputs3(inputs);
        if (inferenceHandler.session.pack && inputs[0].dims.length > 1) {
          const output = inferenceHandler.run(createPackedConcatProgramInfoLoader(inferenceHandler, inputs, attributes), inputs);
          return [output];
        } else {
          const output = inferenceHandler.run(createUnpackedConcatProgramInfoLoader(inferenceHandler, inputs, attributes), inputs);
          return [output];
        }
      };
      createUnpackedConcatProgramMetadata = (inputCount, cacheHint) => ({
        name: "Concat",
        inputNames: Array.from({ length: inputCount }, (_v, i) => `X${i}`),
        inputTypes: Array(inputCount).fill(0 /* unpacked */),
        cacheHint
      });
      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;
        }
        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++) {
            if (axisIndex === axis) {
              outputShape[axis] += dataNShape[axisIndex];
            } 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 = "";
        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 {
          ...metadata,
          output: { dims: outputShape, type: inputs[0].type, textureType: 0 /* unpacked */ },
          shaderSource
        };
      };
      createUnpackedConcatProgramInfoLoader = (handler, inputs, attributes) => {
        const metadata = createUnpackedConcatProgramMetadata(inputs.length, attributes.cacheKey);
        return { ...metadata, get: () => createUnpackedConcatProgramInfo(handler, metadata, inputs, attributes.axis) };
      };
      getTextureIndexWhereDataResidesLinearSearch = (sizeInConcatAxis) => {
        const searchAxis = sizeInConcatAxis.map((size, i) => `if(index<${size}) {return ${i};}
`);
        return `int getTextureWhereDataResides(int index) {
      ${searchAxis.join("")}
    }`;
      };
      getTextureIndexWhereDataResidesBinarySearch = (sizeInConcatAxis) => getTextureIndexWhereDataResidesLinearSearch(sizeInConcatAxis);
      getFetchDataFromCorrectTextureMethod = (numberOfTensors, tensorRank) => {
        const codeLines = [`float fetchDataFromCorrectTexture(int textureIndex, int indices[${tensorRank}]) {`];
        for (let i = 0; i < numberOfTensors; ++i) {
          if (i === 0) {
            codeLines.push(
              `	if (textureIndex == ${i}) { return _X${i}(indices); }`
            );
          } else if (i === numberOfTensors - 1) {
            codeLines.push(
              `	else { return _X${i}(indices); }`
            );
          } else {
            codeLines.push(
              `	else if (textureIndex == ${i}) { return _X${i}(indices); }`
            );
          }
        }
        codeLines.push(
          "	}"
        );
        return codeLines.join("\n");
      };
      getGetSizeInConcatAxisValueFromIndexMethod = (sizeInConcatAxis) => {
        const codeLines = ["int getSizeInConcatAxisValueFromIndex(int index) {"];
        for (let i = 0; i < sizeInConcatAxis.length; ++i) {
          if (i === 0) {
            codeLines.push(
              `	if (index == ${i}) { return ${sizeInConcatAxis[i]}; }`
            );
          } else if (i === sizeInConcatAxis.length - 1) {
            codeLines.push(
              `	else { return ${sizeInConcatAxis[i]}; }`
            );
          } else {
            codeLines.push(
              `	else if (index == ${i}) { return ${sizeInConcatAxis[i]}; }`
            );
          }
        }
        codeLines.push(
          "	}"
        );
        return codeLines.join("\n");
      };
      parseConcatAttributes = (node) => createAttributeWithCacheKey({ axis: node.attributes.getInt("axis") });
      validateInputs3 = (inputs) => {
        if (!inputs || inputs.length < 1) {
          throw new Error("too few inputs");
        }
        const inputType = inputs[0].type;
        const inputDimensionality = inputs[0].dims.length;
        if (inputType === "string") {
          throw new Error("string tensor is not supported yet");
        }
        for (const input of inputs) {
          if (input.type !== inputType) {
            throw new Error("input tensors should be one type");
          }
          if (input.dims.length !== inputDimensionality) {
            throw new Error("input tensors should have the same shape");
          }
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/unary-op.ts
  function glslAbs() {
    return glslBuiltinUnary("abs");
  }
  function glslAcos() {
    return glslBuiltinUnary("acos");
  }
  function glslAsin() {
    return glslBuiltinUnary("asin");
  }
  function glslAtan() {
    return glslBuiltinUnary("atan");
  }
  function glslCeil() {
    return glslBuiltinUnary("ceil");
  }
  function glslCos() {
    return glslBuiltinUnary("cos");
  }
  function glslElu(alpha) {
    const name2 = "elu";
    const body = `
  const float alpha = float(${alpha});

  float ${name2}_(float a) {
    return a >= 0.0 ? a: (exp(a) - 1.0) * alpha;
  }
  vec4 ${name2}_(vec4 v) {
    return vec4(${name2}_(v.x), ${name2}_(v.y), ${name2}_(v.z), ${name2}_(v.w));
  }
  `;
    return { body, name: name2, type: 0 /* ValueBased */ };
  }
  function glslExp() {
    return glslBuiltinUnary("exp");
  }
  function glslFloor() {
    return glslBuiltinUnary("floor");
  }
  function glslClip(min, max) {
    const name2 = "clip";
    const body = `
  const float min = float(${min});
  const float max = float(${max});

  float ${name2}_(float a) {
    return clamp(a, min, max);
  }
  vec4 ${name2}_(vec4 v) {
    return clamp(v, min, max);
  }
  `;
    return { body, name: name2, type: 0 /* ValueBased */ };
  }
  function glslIdentity() {
    const name2 = "indentity";
    const body = `
  float ${name2}_(float a) {
    return a;
  }
  vec4 ${name2}_(vec4 v) {
    return v;
  }
  `;
    return { body, name: name2, type: 0 /* ValueBased */ };
  }
  function glslLeakyRelu(alpha) {
    const name2 = "leakyRelu";
    const body = `
  const float alpha = float(${alpha});

  float ${name2}_(float a) {
    return a < 0.0 ? a * alpha : a;
  }
  vec4 ${name2}_(vec4 v) {
    return vec4(${name2}_(v.x), ${name2}_(v.y), ${name2}_(v.z), ${name2}_(v.w));
  }
  `;
    return { body, name: name2, type: 0 /* ValueBased */ };
  }
  function glslLog() {
    return glslBuiltinUnary("log");
  }
  function glslNeg() {
    const name2 = "neg";
    const body = `
  float ${name2}_(float a) {
    return -a;
  }
  vec4 ${name2}_(vec4 v) {
    return -v;
  }
  `;
    return { body, name: name2, type: 0 /* ValueBased */ };
  }
  function glslNot() {
    const name2 = "not";
    const body = `
  float ${name2}_(float a) {
    return float( ! bool(a) );
  }
  bool ${name2}_(bool a) {
    return !a;
  }
  vec4 ${name2}_(vec4 v) {
    return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w));
  }
  bvec4 ${name2}_(bvec4 v) {
    return bvec4(!v.x, !v.y, !v.z, !v.w);
  }
  `;
    return { body, name: name2, type: 0 /* ValueBased */ };
  }
  function glslSin() {
    return glslBuiltinUnary("sin");
  }
  function glslRelu() {
    const name2 = "relu";
    const body = `
  float ${name2}_(float a) {
    return max( a, 0.0 );
  }
  vec4 ${name2}_(vec4 v) {
    return max( v, 0.0 );
  }
  `;
    return { body, name: name2, type: 0 /* ValueBased */ };
  }
  function glslSigmoid() {
    const name2 = "sigmoid";
    const body = `
  float ${name2}_(float a) {
    return 1.0 / (1.0 + exp(-a));
  }
  vec4 ${name2}_(vec4 v) {
    return 1.0 / (1.0 + exp(-v));
  }
  `;
    return { body, name: name2, type: 0 /* ValueBased */ };
  }
  function glslSqrt() {
    return glslBuiltinUnary("sqrt");
  }
  function glslTan() {
    return glslBuiltinUnary("tan");
  }
  function glslTanh() {
    const name2 = "tanh";
    const body = `
  float ${name2}_(float a) {
    a = clamp(a, -10., 10.);
    a = exp(2.*a);
    return (a - 1.) / (a + 1.);
  }
  vec4 ${name2}_(vec4 v) {
    v = clamp(v, -10., 10.);
    v = exp(2.*v);
    return (v - 1.) / (v + 1.);
  }
  `;
    return { body, name: name2, type: 0 /* ValueBased */ };
  }
  function glslBuiltinUnary(name2) {
    const body = `
  float ${name2}_(float a) {
    return ${name2}(a);
  }
  vec4 ${name2}_(vec4 v) {
    return ${name2}(v);
  }
  `;
    return { body, name: name2, type: 0 /* ValueBased */ };
  }
  var createElementwiseProgramInfo, createElementwiseProgramInfoLoader, abs, acos, asin, atan, clip, parseClipAttributes, clipV11, generateClipAttributesFromInputs, ceil, cos, elu, parseEluAttributes, exp, floor, identity, leakyRelu, parseLeakyReluAttributes, log2, neg, not2, relu, sigmoid, sin, sqrt, tan, tanh;
  var init_unary_op = __esm({
    "web/lib/onnxjs/backends/webgl/ops/unary-op.ts"() {
      "use strict";
      init_attribute_with_cache_key();
      init_util();
      init_glsl_definitions();
      init_glsl_source();
      init_types();
      createElementwiseProgramInfo = (handler, metadata, input, glslFunc) => {
        const textureType = handler.session.pack ? 2 /* packed */ : 0 /* unpacked */;
        const glsl = getGlsl(handler.session.backend.glContext.version);
        return {
          ...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
        };
      };
      createElementwiseProgramInfoLoader = (handler, input, glslFunc, cacheKey) => {
        const textureType = handler.session.pack ? 2 /* packed */ : 0 /* unpacked */;
        const metadata = { name: glslFunc.name, inputTypes: [textureType], inputNames: ["A"], cacheHint: cacheKey };
        return { ...metadata, get: () => createElementwiseProgramInfo(handler, metadata, input, glslFunc) };
      };
      abs = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslAbs()), inputs)];
      acos = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslAcos()), inputs)];
      asin = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslAsin()), inputs)];
      atan = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslAtan()), inputs)];
      clip = (handler, inputs, attributes) => [handler.run(
        createElementwiseProgramInfoLoader(
          handler,
          inputs[0],
          glslClip(attributes.min, attributes.max),
          attributes.cacheKey
        ),
        inputs
      )];
      parseClipAttributes = (node) => createAttributeWithCacheKey(
        { min: node.attributes.getFloat("min", MIN_CLIP), max: node.attributes.getFloat("max", MAX_CLIP) }
      );
      clipV11 = (handler, inputs) => {
        const attributes = generateClipAttributesFromInputs(handler, inputs);
        return clip(handler, [inputs[0]], attributes);
      };
      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] : MIN_CLIP;
        const max = inputs.length >= 3 ? inputs[2].numberData[0] : MAX_CLIP;
        return createAttributeWithCacheKey({ min, max });
      };
      ceil = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslCeil()), inputs)];
      cos = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslCos()), inputs)];
      elu = (handler, inputs, attributes) => [handler.run(
        createElementwiseProgramInfoLoader(handler, inputs[0], glslElu(attributes.alpha), attributes.cacheKey),
        inputs
      )];
      parseEluAttributes = (node) => createAttributeWithCacheKey({ alpha: node.attributes.getFloat("alpha", 1) });
      exp = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslExp()), inputs)];
      floor = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslFloor()), inputs)];
      identity = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslIdentity()), inputs)];
      leakyRelu = (handler, inputs, attributes) => [handler.run(
        createElementwiseProgramInfoLoader(handler, inputs[0], glslLeakyRelu(attributes.alpha), attributes.cacheKey),
        inputs
      )];
      parseLeakyReluAttributes = (node) => createAttributeWithCacheKey({ alpha: node.attributes.getFloat("alpha", 0.01) });
      log2 = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslLog()), inputs)];
      neg = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslNeg()), inputs)];
      not2 = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslNot()), inputs)];
      relu = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslRelu()), inputs)];
      sigmoid = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslSigmoid()), inputs)];
      sin = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslSin()), inputs)];
      sqrt = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslSqrt()), inputs)];
      tan = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslTan()), inputs)];
      tanh = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslTanh()), inputs)];
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/fuse-utils.ts
  function getActivationSnippet(attributes) {
    let func;
    switch (attributes.activation) {
      case "Relu":
        func = glslRelu();
        break;
      case "Sigmoid":
        func = glslSigmoid();
        break;
      case "Clip":
        func = glslClip(attributes.clipMin, attributes.clipMax);
        break;
      default:
        return { activationFunction: "", applyActivation: "" };
    }
    const activationName = func.name;
    const activationFunction = func.body;
    const applyActivation = `value = ${activationName}_(value);`;
    return { activationFunction, applyActivation };
  }
  var parseInternalActivationAttributes;
  var init_fuse_utils = __esm({
    "web/lib/onnxjs/backends/webgl/ops/fuse-utils.ts"() {
      "use strict";
      init_util();
      init_unary_op();
      parseInternalActivationAttributes = (attributes) => {
        const activation = attributes.getString("activation", "");
        if (activation === "Clip") {
          const [clipMin, clipMax] = attributes.getFloats("activation_params", [MIN_CLIP, MAX_CLIP]);
          return { activation, clipMax, clipMin, activationCacheKey: `${activation}:${clipMin},${clipMax}` };
        }
        return { activation, activationCacheKey: activation };
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/conv-grouped.ts
  var createUnpackedGroupedConvProgramMetadata, createUnpackedGroupedConvProgramInfo, createUnpackedGroupedConvProgramInfoLoader;
  var init_conv_grouped = __esm({
    "web/lib/onnxjs/backends/webgl/ops/conv-grouped.ts"() {
      "use strict";
      init_instrument();
      init_glsl_source();
      init_types();
      init_conv();
      init_fuse_utils();
      createUnpackedGroupedConvProgramMetadata = (hasBias, cacheHint) => ({
        name: "GroupedConv",
        inputNames: hasBias ? ["X", "W", "Bias"] : ["X", "W"],
        inputTypes: hasBias ? [0 /* unpacked */, 0 /* unpacked */, 0 /* unpacked */] : [0 /* unpacked */, 0 /* unpacked */],
        cacheHint
      });
      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;
        Logger.verbose(
          "GroupedConv",
          `autpPad:${attributes.autoPad}, dilations:${attributes.dilations}, group:${attributes.group}, kernelShape:${attributes.kernelShape}, pads:${attributes.pads}, strides:${attributes.strides}`
        );
        const outputShape = calculateOutputShape(xShape, wShape, attributes.dilations, attributes.pads, attributes.strides);
        const glsl = getGlsl(inferenceHandler.session.backend.glContext.version);
        const { activationFunction, applyActivation } = 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 {
          ...metadata,
          output: { dims: outputShape, type: inputs[0].type, textureType: 0 /* unpacked */ },
          shaderSource,
          hasMain: true
        };
      };
      createUnpackedGroupedConvProgramInfoLoader = (inferenceHandler, inputs, attributes) => {
        const metadata = createUnpackedGroupedConvProgramMetadata(inputs.length > 2, attributes.cacheKey);
        return {
          ...metadata,
          get: () => createUnpackedGroupedConvProgramInfo(inferenceHandler, inputs, metadata, attributes)
        };
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/im2col-pack.ts
  var createPackedIm2ColProgramMetadata, createPackedIm2ColProgramInfo, createPackedIm2ColProgramInfoLoader;
  var init_im2col_pack = __esm({
    "web/lib/onnxjs/backends/webgl/ops/im2col-pack.ts"() {
      "use strict";
      init_glsl_source();
      init_types();
      init_packing_utils();
      createPackedIm2ColProgramMetadata = (cacheHint) => ({
        name: "Im2Col (packed)",
        inputNames: ["A"],
        inputTypes: [2 /* packed */],
        cacheHint
      });
      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 = unpackFromChannel();
        const glsl = 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 {
          ...metadata,
          output: { dims: im2colShape, type: x.type, textureType: 2 /* packed */ },
          shaderSource,
          hasMain: true
        };
      };
      createPackedIm2ColProgramInfoLoader = (inferenceHandler, x, w, outputShape, attributes) => {
        const metadata = createPackedIm2ColProgramMetadata(attributes.cacheKey);
        return {
          ...metadata,
          get: () => createPackedIm2ColProgramInfo(inferenceHandler, metadata, x, w, outputShape, attributes)
        };
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/matmul.ts
  function createMatmulProgramInfo(metadata, inputs, activationAttributes) {
    const aShape = inputs[0].dims;
    const bShape = inputs[1].dims;
    const outputShape = BroadcastUtil.calcShape(aShape, bShape, true);
    if (!outputShape) {
      throw new Error("Can't use matmul on the given tensors");
    }
    const coordsDataType = getCoordsDataType(outputShape.length);
    const allGlChannels = getGlChannels();
    const { activationFunction, applyActivation } = 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 {
      ...metadata,
      output: { dims: outputShape, type: inputs[0].type, textureType: 0 /* unpacked */ },
      shaderSource
    };
  }
  function createMatmulProgramInfoLoader(inputs, activationAttributes) {
    const metadata = createMatmulProgramMetadata(inputs.length > 2, activationAttributes.activationCacheKey);
    return { ...metadata, get: () => createMatmulProgramInfo(metadata, inputs, activationAttributes) };
  }
  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 = BroadcastUtil.getBroadcastDims(inShape, outShape);
    const coordsSnippet = broadcastDims.map((d) => `coords.${allGlChannels[d + rankDiff]} = 0;`).join("\n");
    const inSize = 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;
  }
  var matMul, parseMatMulAttributes, createMatmulProgramMetadata, validateInputs4;
  var init_matmul = __esm({
    "web/lib/onnxjs/backends/webgl/ops/matmul.ts"() {
      "use strict";
      init_util();
      init_types();
      init_utils();
      init_fuse_utils();
      init_matmul_pack();
      matMul = (inferenceHandler, inputs, attributes) => {
        validateInputs4(inputs);
        if (inferenceHandler.session.pack) {
          return [inferenceHandler.run(
            createPackedMatmulProgramInfoLoader(inferenceHandler, inputs, attributes),
            inputs
          )];
        } else {
          return [inferenceHandler.run(createMatmulProgramInfoLoader(inputs, attributes), inputs)];
        }
      };
      parseMatMulAttributes = (node) => parseInternalActivationAttributes(node.attributes);
      createMatmulProgramMetadata = (hasBias, cacheHint) => ({
        name: "MatMul",
        inputNames: hasBias ? ["A", "B", "Bias"] : ["A", "B"],
        inputTypes: hasBias ? [0 /* unpacked */, 0 /* unpacked */, 0 /* unpacked */] : [0 /* unpacked */, 0 /* unpacked */],
        cacheHint
      });
      validateInputs4 = (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");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/matmul-pack.ts
  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 = BroadcastUtil.getBroadcastDims(inAShape, outShape);
    const broadcastBDims = 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;
  }
  var createPackedMatmulProgramMetadata, createPackedMatmulProgramInfo, createPackedMatmulProgramInfoLoader;
  var init_matmul_pack = __esm({
    "web/lib/onnxjs/backends/webgl/ops/matmul-pack.ts"() {
      "use strict";
      init_util();
      init_glsl_source();
      init_types();
      init_utils();
      init_fuse_utils();
      init_matmul();
      createPackedMatmulProgramMetadata = (hasBias, cacheHint) => ({
        name: "MatMul (packed)",
        inputNames: hasBias ? ["A", "B", "Bias"] : ["A", "B"],
        inputTypes: hasBias ? [2 /* packed */, 2 /* packed */, 2 /* packed */] : [2 /* packed */, 2 /* packed */],
        cacheHint
      });
      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 = BroadcastUtil.calcShape(aShape, bShape, true);
        const isBroadcast = !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 = getGlsl(inferenceHandler.session.backend.glContext.version);
        const coordsDataType = getCoordsDataType(outputShape.length);
        const outRank = outputShape.length;
        const allGlChannels = getGlChannels();
        const { activationFunction, applyActivation } = getActivationSnippet(activationAttributes);
        const getBiasForMatmulSnippet = hasBias ? `${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 {
          ...metadata,
          output: { dims: outputShape, type: inputs[0].type, textureType: 2 /* packed */ },
          shaderSource,
          hasMain: true
        };
      };
      createPackedMatmulProgramInfoLoader = (inferenceHandler, inputs, activationAttributes) => {
        const metadata = createPackedMatmulProgramMetadata(inputs.length > 2, activationAttributes.activationCacheKey);
        return {
          ...metadata,
          get: () => createPackedMatmulProgramInfo(inferenceHandler, metadata, inputs, activationAttributes)
        };
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/conv-pack.ts
  var conv2DPacked;
  var init_conv_pack = __esm({
    "web/lib/onnxjs/backends/webgl/ops/conv-pack.ts"() {
      "use strict";
      init_conv();
      init_im2col_pack();
      init_matmul_pack();
      conv2DPacked = (inferenceHandler, inputs, attributes) => {
        const xshape = inputs[0].dims;
        const kshape = inputs[1].dims;
        const outputShape = calculateOutputShape(xshape, kshape, attributes.dilations, attributes.pads, attributes.strides);
        const im2colOutput = inferenceHandler.run(
          createPackedIm2ColProgramInfoLoader(inferenceHandler, inputs[0], inputs[1], outputShape, attributes),
          [inputs[0]]
        );
        const kernelReshaped = inferenceHandler.reshapePacked(inputs[1], [kshape[0], kshape[1] * kshape[2] * kshape[3]]);
        const matmulInputs = inputs.length === 3 ? [kernelReshaped, im2colOutput, inputs[2]] : [kernelReshaped, im2colOutput];
        const matmulOutput = inferenceHandler.run(
          createPackedMatmulProgramInfoLoader(inferenceHandler, matmulInputs, attributes),
          matmulInputs
        );
        const outputReshaped = inferenceHandler.reshapePacked(matmulOutput, outputShape);
        return outputReshaped;
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/im2col.ts
  var createIm2ColProgramMetadata, createIm2ColProgramInfo, createIm2ColProgramInfoLoader, calculateIm2ColDims;
  var init_im2col = __esm({
    "web/lib/onnxjs/backends/webgl/ops/im2col.ts"() {
      "use strict";
      init_types();
      createIm2ColProgramMetadata = (cacheHint) => ({
        name: "Im2Col",
        inputNames: ["X"],
        inputTypes: [0 /* unpacked */],
        cacheHint
      });
      createIm2ColProgramInfo = (_inferenceHandler, metadata, x, w, outputShape, attributes) => {
        const xshape = x.dims;
        const wshape = w.dims;
        const rank = outputShape.length;
        const im2colDims = 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 {
          ...metadata,
          output: { dims: im2colDims, type: x.type, textureType: 4 /* packedLastDimension */ },
          shaderSource
        };
      };
      createIm2ColProgramInfoLoader = (inferenceHandler, x, w, outputShape, attributes) => {
        const metadata = createIm2ColProgramMetadata(attributes.cacheKey);
        return {
          ...metadata,
          get: () => createIm2ColProgramInfo(inferenceHandler, metadata, x, w, outputShape, attributes)
        };
      };
      calculateIm2ColDims = (inputShape, kernelShape, outputShape, channels = 4) => [
        outputShape[0],
        outputShape[2],
        outputShape[3],
        Math.ceil(inputShape[1] * kernelShape[2] * kernelShape[3] / channels)
      ];
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/dot-product.ts
  var createDotProductProgramMetadata, createDotProductProgramInfo, createDotProductProgramInfoLoader;
  var init_dot_product = __esm({
    "web/lib/onnxjs/backends/webgl/ops/dot-product.ts"() {
      "use strict";
      init_util();
      init_glsl_source();
      init_types();
      init_fuse_utils();
      init_im2col();
      createDotProductProgramMetadata = (hasBias, attributes) => ({
        name: "ConvDotProduct",
        inputNames: hasBias ? ["Im2Col", "K", "B"] : ["Im2Col", "K"],
        inputTypes: hasBias ? [0 /* unpacked */, 4 /* packedLastDimension */, 0 /* unpacked */] : [0 /* unpacked */, 4 /* packedLastDimension */],
        cacheKey: attributes.activationCacheKey
      });
      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 = calculateIm2ColDims(xshape, kshape, outputShape);
        const [kWidth, kHeight] = inferenceHandler.calculateTextureWidthAndHeight(adjustedKernelShape, 4 /* packedLastDimension */);
        const im2colStrides = ShapeUtil.computeStrides(im2colShape);
        const [im2colWidth, im2colHeight] = inferenceHandler.calculateTextureWidthAndHeight(im2colShape, 4 /* 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 } = getActivationSnippet(attributes);
        const glsl = 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 {
          ...metadata,
          output: { dims: outputShape, type: inputs[0].type, textureType: 0 /* unpacked */ },
          shaderSource
        };
      };
      createDotProductProgramInfoLoader = (inferenceHandler, inputs, outputShape, attributes) => {
        const metadata = createDotProductProgramMetadata(inputs.length > 2, attributes);
        return {
          ...metadata,
          get: () => createDotProductProgramInfo(inferenceHandler, metadata, inputs, outputShape, attributes)
        };
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/conv.ts
  var calculateOutputShape, conv, conv2d, conv2DUnpackedPointwise, conv2DUnpacked, getAdjustedConvAttributes, parseConvAttributes, validateInputs5;
  var init_conv = __esm({
    "web/lib/onnxjs/backends/webgl/ops/conv.ts"() {
      "use strict";
      init_attribute_with_cache_key();
      init_util();
      init_conv_grouped();
      init_conv_pack();
      init_dot_product();
      init_fuse_utils();
      init_im2col();
      init_matmul();
      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;
      };
      conv = (inferenceHandler, inputs, attributes) => {
        validateInputs5(inputs, attributes);
        return conv2d(inferenceHandler, inputs, attributes);
      };
      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(
            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 [conv2DPacked(inferenceHandler, inputs, adjustedAttributes)];
        } else {
          return [conv2DUnpacked(inferenceHandler, inputs, adjustedAttributes)];
        }
      };
      conv2DUnpackedPointwise = (inferenceHandler, inputs, attributes) => {
        const xshape = inputs[0].dims;
        const kshape = inputs[1].dims;
        const outputShape = 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(createMatmulProgramInfoLoader(matmulInputs, attributes), matmulInputs);
        return inferenceHandler.reshapeUnpacked(matmulOutput, outputShape);
      };
      conv2DUnpacked = (inferenceHandler, inputs, attributes) => {
        const xshape = inputs[0].dims;
        const kshape = inputs[1].dims;
        const outputShape = calculateOutputShape(xshape, kshape, attributes.dilations, attributes.pads, attributes.strides);
        const xIm2Col = inferenceHandler.run(
          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(
          createDotProductProgramInfoLoader(inferenceHandler, inputs, outputShape, attributes),
          dotProductInputs
        );
        return output;
      };
      getAdjustedConvAttributes = (attributes, inputs) => {
        const kernelShape = attributes.kernelShape.slice();
        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();
        PoolConvUtil.adjustPadsBasedOnAutoPad(
          inputs[0].dims,
          attributes.strides,
          attributes.dilations,
          kernelShape,
          pads,
          attributes.autoPad
        );
        const newAttributes = Object.assign({}, attributes);
        Object.assign(newAttributes, { kernelShape, pads, cacheKey: attributes.cacheKey });
        return newAttributes;
      };
      parseConvAttributes = (node) => {
        const attributes = node.attributes;
        const activationAttributes = parseInternalActivationAttributes(attributes);
        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 createAttributeWithCacheKey({ autoPad, dilations, group, kernelShape, pads, strides, ...activationAttributes });
      };
      validateInputs5 = (inputs, attributes) => {
        if (!inputs || inputs.length !== 2 && inputs.length !== 3) {
          throw new Error("Conv requires 2 or 3 inputs");
        }
        if (inputs[0].dims.length !== 4 || inputs[1].dims.length !== 4) {
          throw new Error("currently only support 2-dimensional conv");
        }
        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 (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;
        if (attributes.dilations.length !== spatialRank) {
          throw new Error(`dilations should be ${spatialRank}D`);
        }
        if (attributes.strides.length !== spatialRank) {
          throw new Error(`strides should be ${spatialRank}D`);
        }
        if (attributes.pads.length !== spatialRank * 2) {
          throw new Error(`pads should be ${spatialRank * 2}D`);
        }
        if (attributes.kernelShape.length !== 0 && attributes.kernelShape.length !== inputs[1].dims.length - 2) {
          throw new Error("invalid kernel shape");
        }
        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");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/conv-transpose.ts
  var computeTotalPad, distributePadding, calculateOutputShapeAndPads, convTranspose, convTranspose2d, createConvTransposeProgramMetadata, createUnpackedConvTransposeProgramInfo, createUnpackedConvTransposeProgramInfoLoader, convTranspose2DUnpacked, getAdjustedConvTransposeAttributes, parseConvTransposeAttributes, validateInputs6;
  var init_conv_transpose = __esm({
    "web/lib/onnxjs/backends/webgl/ops/conv-transpose.ts"() {
      "use strict";
      init_attribute_with_cache_key();
      init_glsl_source();
      init_types();
      init_fuse_utils();
      computeTotalPad = (inDim, stride, adj, kernel, dilation, outSize) => (inDim - 1) * stride + adj + (kernel - 1) * dilation + 1 - outSize;
      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;
        }
      };
      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]
            );
          }
        }
      };
      convTranspose = (inferenceHandler, inputs, attributes) => {
        validateInputs6(inputs, attributes);
        return convTranspose2d(inferenceHandler, inputs, attributes);
      };
      convTranspose2d = (inferenceHandler, inputs, attributes) => {
        const adjustedAttributes = getAdjustedConvTransposeAttributes(attributes, inputs);
        return [convTranspose2DUnpacked(inferenceHandler, inputs, adjustedAttributes)];
      };
      createConvTransposeProgramMetadata = (hasBias, cacheHint) => ({
        name: "ConvTranspose",
        inputNames: hasBias ? ["X", "W", "B"] : ["X", "W"],
        inputTypes: hasBias ? [0 /* unpacked */, 0 /* unpacked */, 0 /* unpacked */] : [0 /* unpacked */, 0 /* unpacked */],
        cacheHint
      });
      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 = getGlsl(inferenceHandler.session.backend.glContext.version);
        const { activationFunction, applyActivation } = 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 {
          ...metadata,
          output: { dims: outputShape, type: inputs[0].type, textureType: 0 /* unpacked */ },
          shaderSource,
          hasMain: true
        };
      };
      createUnpackedConvTransposeProgramInfoLoader = (inferenceHandler, inputs, attributes) => {
        const metadata = createConvTransposeProgramMetadata(inputs.length > 2, attributes.cacheKey);
        return {
          ...metadata,
          get: () => createUnpackedConvTransposeProgramInfo(inferenceHandler, inputs, metadata, attributes)
        };
      };
      convTranspose2DUnpacked = (inferenceHandler, inputs, attributes) => {
        const result = inferenceHandler.run(
          createUnpackedConvTransposeProgramInfoLoader(inferenceHandler, inputs, attributes),
          inputs
        );
        return result;
      };
      getAdjustedConvTransposeAttributes = (attributes, inputs) => {
        const kernelShape = attributes.kernelShape.slice();
        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;
        calculateOutputShapeAndPads(
          inputShape,
          kernelShape,
          attributes.dilations,
          attributes.autoPad,
          pads,
          attributes.strides,
          attributes.outputPadding,
          outputShape
        );
        const newAttributes = Object.assign({}, attributes);
        Object.assign(newAttributes, { kernelShape, pads, outputShape, cacheKey: attributes.cacheKey });
        return newAttributes;
      };
      parseConvTransposeAttributes = (node) => {
        const attributes = node.attributes;
        const activationAttributes = parseInternalActivationAttributes(attributes);
        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 createAttributeWithCacheKey(
          { autoPad, dilations, group, kernelShape, outputPadding, outputShape, pads, strides, ...activationAttributes }
        );
      };
      validateInputs6 = (inputs, attributes) => {
        if (!inputs || inputs.length !== 2 && inputs.length !== 3) {
          throw new Error("Conv requires 2 or 3 inputs");
        }
        if (inputs[0].dims.length !== 4 || inputs[1].dims.length !== 4) {
          throw new Error("currently only support 2-dimensional conv");
        }
        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 (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;
        if (attributes.dilations.length !== spatialRank) {
          throw new Error(`dilations should be ${spatialRank}D`);
        }
        if (attributes.strides.length !== spatialRank) {
          throw new Error(`strides should be ${spatialRank}D`);
        }
        if (attributes.pads.length !== spatialRank * 2) {
          throw new Error(`pads should be ${spatialRank * 2}D`);
        }
        if (attributes.outputPadding.length !== spatialRank) {
          throw new Error(`output_padding should be ${spatialRank}D`);
        }
        if (attributes.kernelShape.length !== 0 && attributes.kernelShape.length !== inputs[1].dims.length - 2) {
          throw new Error("invalid kernel shape");
        }
        if (attributes.outputShape.length !== 0 && attributes.outputShape.length !== inputs[0].dims.length - 2) {
          throw new Error("invalid output shape");
        }
        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");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/transpose.ts
  var transposeProgramMetadata, transpose, parseTransposeAttributes, createTransposeProgramInfo, getAdjustedPerm, getOutputShape, getPermFunctionBody, validateInputs7;
  var init_transpose = __esm({
    "web/lib/onnxjs/backends/webgl/ops/transpose.ts"() {
      "use strict";
      init_attribute_with_cache_key();
      init_util();
      init_types();
      transposeProgramMetadata = {
        name: "Transpose",
        inputNames: ["A"],
        inputTypes: [0 /* unpacked */]
      };
      transpose = (inferenceHandler, inputs, attributes) => {
        validateInputs7(inputs);
        const output = inferenceHandler.run(
          {
            ...transposeProgramMetadata,
            cacheHint: attributes.cacheKey,
            get: () => createTransposeProgramInfo(inferenceHandler, inputs[0], attributes.perm)
          },
          inputs
        );
        return [output];
      };
      parseTransposeAttributes = (node) => createAttributeWithCacheKey({ perm: node.attributes.getInts("perm", []) });
      createTransposeProgramInfo = (_inferenceHandler, input, perm) => {
        const inputShape = input.dims;
        perm = getAdjustedPerm(inputShape, perm);
        const unpackedOutputShape = getOutputShape(inputShape, perm);
        const rank = inputShape.length;
        const shaderSource = `
      ${getPermFunctionBody("perm", perm, rank)}
      float process(int indices[${rank}]) {
        int a[${rank}];
        perm(a, indices);
        return _A(a);
      }`;
        return {
          ...transposeProgramMetadata,
          output: { dims: unpackedOutputShape, type: input.type, textureType: 0 /* unpacked */ },
          shaderSource
        };
      };
      getAdjustedPerm = (inputShape, perm) => {
        if (perm && perm.length !== inputShape.length) {
          perm = [...inputShape.keys()].reverse();
        }
        return perm;
      };
      getOutputShape = (inputShape, perm) => {
        perm = getAdjustedPerm(inputShape, perm);
        return ShapeUtil.sortBasedOnPerm(inputShape, perm);
      };
      getPermFunctionBody = (name2, perm, rank) => {
        const reverseFunc = [];
        reverseFunc.push(`void ${name2}(out int a[${rank}], int src[${rank}]) {`);
        for (let i = 0; i < rank; ++i) {
          reverseFunc.push(`	a[${perm[i]}]=src[${i}];`);
        }
        reverseFunc.push("	}");
        return reverseFunc.join("\n");
      };
      validateInputs7 = (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");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/depth-to-space.ts
  var depthToSpace, parseDepthToSpaceAttributes, validateInputs8;
  var init_depth_to_space = __esm({
    "web/lib/onnxjs/backends/webgl/ops/depth-to-space.ts"() {
      "use strict";
      init_transpose();
      depthToSpace = (inferenceHandler, inputs, attributes) => {
        validateInputs8(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 firstReshapedTensor = inferenceHandler.reshapeUnpacked(inputs[0], firstReshapeShape);
        const transposeAttributes = { perm: transposePerm, cacheKey: `${transposePerm}` };
        const [transposeOutput] = transpose(inferenceHandler, [firstReshapedTensor], transposeAttributes);
        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];
      };
      parseDepthToSpaceAttributes = (node) => {
        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 };
      };
      validateInputs8 = (inputs) => {
        if (inputs.length !== 1) {
          throw new Error(`DepthToSpace expect 1 inputs, but got ${inputs.length}`);
        }
        if (inputs[0].type === "string" || inputs[0].dims.length !== 4) {
          throw new TypeError("DepthToSpace input should be a 4-D numeric tensor");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/flatten.ts
  var flatten, parseFlattenAttributes, validateInputs9;
  var init_flatten = __esm({
    "web/lib/onnxjs/backends/webgl/ops/flatten.ts"() {
      "use strict";
      init_util();
      flatten = (inferenceHandler, inputs, axis) => {
        validateInputs9(inputs, axis);
        const outputDims = ShapeUtil.flattenShape(inputs[0].dims, axis);
        return [inferenceHandler.reshapeUnpacked(inputs[0], outputDims)];
      };
      parseFlattenAttributes = (node) => node.attributes.getInt("axis", 1);
      validateInputs9 = (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");
        }
        if (inputs[0].type === "string") {
          throw new Error("string tensor is not supported.");
        }
      };
    }
  });

  // web/lib/onnxjs/operators.ts
  var NUMBER_TYPES;
  var init_operators = __esm({
    "web/lib/onnxjs/operators.ts"() {
      "use strict";
      NUMBER_TYPES = ["float32", "float64", "int32", "int16", "int8", "uint16", "uint32", "uint8"];
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/gather.ts
  var gather, parseGatherAttributes, gatherProgramMetadata, createGatherProgramInfo, createGatherProgramInfoLoader, validateInputs10;
  var init_gather = __esm({
    "web/lib/onnxjs/backends/webgl/ops/gather.ts"() {
      "use strict";
      init_attribute_with_cache_key();
      init_operators();
      init_util();
      init_types();
      gather = (inferenceHandler, inputs, attributes) => {
        validateInputs10(inputs, attributes.axis);
        const output = inferenceHandler.run(createGatherProgramInfoLoader(inferenceHandler, inputs, attributes), inputs);
        return [output];
      };
      parseGatherAttributes = (node) => createAttributeWithCacheKey({ axis: node.attributes.getInt("axis", 0) });
      gatherProgramMetadata = {
        name: "Gather",
        inputNames: ["A", "B"],
        inputTypes: [0 /* unpacked */, 0 /* unpacked */]
      };
      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 = ShapeUtil.normalizeAxis(axis, inputShape.length);
        const indexCopyOps = [];
        for (let i = 0; i < outputShape.length; i++) {
          if (i < axis) {
            outputShape[i] = inputShape[i];
            indexCopyOps.push(`inputIdx[${i}] = outputIdx[${i}];`);
          } else {
            if (i < axis + indexDataShape.length) {
              outputShape[i] = indexDataShape[i - axis];
              indexCopyOps.push(`indexDataIdx[${i - axis}] = outputIdx[${i}];`);
            } else {
              outputShape[i] = inputShape[i - indexDataShape.length + 1];
              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 {
          ...metadata,
          output: { dims: outputShape, type: inputs[0].type, textureType: 0 /* unpacked */ },
          shaderSource
        };
      };
      createGatherProgramInfoLoader = (handler, inputs, attributes) => {
        const metadata = { ...gatherProgramMetadata, cacheHint: attributes.cacheKey };
        return { ...metadata, get: () => createGatherProgramInfo(handler, metadata, inputs, attributes.axis) };
      };
      validateInputs10 = (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 (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.");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/gemm.ts
  var gemm, parseGemmAttributes, parseGemmAttributesV7, parseGemmAttributesV11, createGemmProgramInfoLoader, createGemmProgramInfo, validateInputs11;
  var init_gemm = __esm({
    "web/lib/onnxjs/backends/webgl/ops/gemm.ts"() {
      "use strict";
      init_attribute_with_cache_key();
      init_util();
      init_types();
      gemm = (inferenceHandler, inputs, attributes) => {
        validateInputs11(inputs, attributes);
        const output = inferenceHandler.run(createGemmProgramInfoLoader(inputs, attributes), inputs);
        return [output];
      };
      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);
        const beta = node.attributes.getFloat("beta", 1);
        return createAttributeWithCacheKey({ transA, transB, alpha, beta, isOptionalC });
      };
      parseGemmAttributesV7 = (node) => parseGemmAttributes(node, false);
      parseGemmAttributesV11 = (node) => parseGemmAttributes(node, true);
      createGemmProgramInfoLoader = (inputs, attributes) => {
        const metadata = {
          name: "Gemm",
          inputNames: inputs.length === 3 ? ["A", "B", "C"] : ["A", "B"],
          inputTypes: inputs.length === 3 ? [0 /* unpacked */, 0 /* unpacked */, 0 /* unpacked */] : [0 /* unpacked */, 0 /* unpacked */],
          key: attributes.cacheKey
        };
        return { ...metadata, get: () => createGemmProgramInfo(metadata, inputs, attributes) };
      };
      createGemmProgramInfo = (metadata, inputs, attributes) => {
        const aShape = inputs[0].dims.slice();
        const bShape = inputs[1].dims.slice();
        const [M, N] = GemmUtil.getShapeOfGemmResult(
          aShape,
          attributes.transA,
          bShape,
          attributes.transB,
          inputs.length === 3 ? inputs[2].dims : void 0
        );
        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 {
          ...metadata,
          output: { dims: outputShape, type: inputs[0].type, textureType: 0 /* unpacked */ },
          variables: [
            { name: "alpha", type: "float", data: attributes.alpha },
            { name: "beta", type: "float", data: attributes.beta }
          ],
          shaderSource
        };
      };
      validateInputs11 = (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");
        }
        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");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/image-scaler.ts
  var imageScaler, parseImageScalerAttributes, imageScalerProgramMetadata, createImageScalerProgramInfo, createImageScalerProgramInfoLoader, createGetBiasMethod, validateInputs12;
  var init_image_scaler = __esm({
    "web/lib/onnxjs/backends/webgl/ops/image-scaler.ts"() {
      "use strict";
      init_attribute_with_cache_key();
      init_types();
      imageScaler = (inferenceHandler, inputs, attributes) => {
        validateInputs12(inputs);
        const output = inferenceHandler.run(createImageScalerProgramInfoLoader(inferenceHandler, inputs, attributes), inputs);
        return [output];
      };
      parseImageScalerAttributes = (node) => {
        const scale = node.attributes.getFloat("scale");
        const bias = node.attributes.getFloats("bias");
        return createAttributeWithCacheKey({ scale, bias });
      };
      imageScalerProgramMetadata = {
        name: "ImageScaler",
        inputNames: ["X"],
        inputTypes: [0 /* unpacked */]
      };
      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 {
          ...metadata,
          output: { dims: outputShape, type: inputs[0].type, textureType: 0 /* unpacked */ },
          variables: [
            { name: "bias", type: "float", arrayLength: attributes.bias.length, data: attributes.bias },
            { name: "scale", type: "float", data: attributes.scale }
          ],
          shaderSource
        };
      };
      createImageScalerProgramInfoLoader = (handler, inputs, attributes) => {
        const metadata = { ...imageScalerProgramMetadata, cacheHint: attributes.cacheKey };
        return { ...metadata, get: () => createImageScalerProgramInfo(handler, metadata, inputs, attributes) };
      };
      createGetBiasMethod = (numChannels) => {
        const codeLines = [`float getBias(float bias[${numChannels}], int channel) {`];
        for (let i = 0; i < numChannels; ++i) {
          if (i === 0) {
            codeLines.push(
              `	if (channel == ${i}) { return bias[${i}]; }`
            );
          } else if (i === numChannels - 1) {
            codeLines.push(
              `	else { return bias[${i}]; }`
            );
          } else {
            codeLines.push(
              `	else if (channel == ${i}) { return bias[${i}]; }`
            );
          }
        }
        codeLines.push(
          "	}"
        );
        return codeLines.join("\n");
      };
      validateInputs12 = (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.");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/instance-normalization.ts
  var instanceNormalization, parseInstanceNormalizationAttributes, meanAndVarianceProgramMetadata, createMeanAndVarianceProgramInfo, createMeanAndVarianceProgramInfoLoader, computeOutputProgramMetadata, createComputeOutputProgramInfo, createComputeOutputProgramInfoLoader, validateInputs13;
  var init_instance_normalization = __esm({
    "web/lib/onnxjs/backends/webgl/ops/instance-normalization.ts"() {
      "use strict";
      init_glsl_source();
      init_types();
      instanceNormalization = (inferenceHandler, inputs, epsilon) => {
        validateInputs13(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];
      };
      parseInstanceNormalizationAttributes = (node) => node.attributes.getFloat("epsilon", 1e-5);
      meanAndVarianceProgramMetadata = {
        name: "InstanceNormalization_MeanAndVariance",
        inputNames: ["X"],
        inputTypes: [0 /* unpacked */]
      };
      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 {
          ...metadata,
          output: { dims: outputShape, type: input.type, textureType: 4 /* packedLastDimension */ },
          shaderSource
        };
      };
      createMeanAndVarianceProgramInfoLoader = (input) => ({
        ...meanAndVarianceProgramMetadata,
        get: () => createMeanAndVarianceProgramInfo(meanAndVarianceProgramMetadata, input)
      });
      computeOutputProgramMetadata = {
        name: "InstanceNormalization_ComputeOutput",
        inputNames: ["X", "MeanAndVariance", "Scale", "B"],
        inputTypes: [0 /* unpacked */, 4 /* packedLastDimension */, 0 /* unpacked */, 0 /* unpacked */]
      };
      createComputeOutputProgramInfo = (inferenceHandler, metadata, input, epsilon, meanAndVarianceShape) => {
        const glsl = getGlsl(inferenceHandler.session.backend.glContext.version);
        const [textureWidth, textureHeight] = inferenceHandler.calculateTextureWidthAndHeight(meanAndVarianceShape, 4 /* 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 {
          ...metadata,
          output: { dims: input.dims, type: input.type, textureType: 0 /* unpacked */ },
          variables: [{ name: "epsilon", type: "float", data: epsilon }],
          shaderSource
        };
      };
      createComputeOutputProgramInfoLoader = (inferenceHandler, input, epsilon, meanAndVarianceShape) => {
        const metadata = { ...computeOutputProgramMetadata, cacheHint: `${epsilon}` };
        return {
          ...metadata,
          get: () => createComputeOutputProgramInfo(inferenceHandler, metadata, input, epsilon, meanAndVarianceShape)
        };
      };
      validateInputs13 = (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];
        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.");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/lrn.ts
  function createLrnProgramInfo(inputs, attributes) {
    const C = inputs[0].dims[1];
    const rank = inputs[0].dims.length;
    const from = -Math.floor((attributes.size - 1) / 2);
    const to = Math.ceil((attributes.size - 1) / 2);
    const alpha = `float(${attributes.alpha}) / float(${attributes.size})`;
    const bias = `float(${attributes.bias})`;
    const beta = `float(${attributes.beta})`;
    const shaderSource = `
    float process(int indices[${rank}]) {
        int c = indices[1];
        float x = _X(indices);
        float square_sum = 0.0;

        for (int i = ${from}; i <= ${to}; i++) {
          int idx = c + i;
          if (c >= 0 && c < ${C}) {
            indices[1] = idx;
            float j = _X(indices);
            square_sum += j * j;
          }
        }
        return x / pow(${bias} + ${alpha} * square_sum, ${beta});
    }`;
    return {
      ...lrnProgramMetadata,
      cacheHint: attributes.cacheKey,
      output: { dims: inputs[0].dims, type: inputs[0].type, textureType: 0 /* unpacked */ },
      shaderSource
    };
  }
  function createLrnProgramInfoLoader(inputs, attributes) {
    return { ...lrnProgramMetadata, cacheHint: attributes.cacheKey, get: () => createLrnProgramInfo(inputs, attributes) };
  }
  var lrn, parseLrnAttributes, lrnProgramMetadata, validateInputs14;
  var init_lrn = __esm({
    "web/lib/onnxjs/backends/webgl/ops/lrn.ts"() {
      "use strict";
      init_attribute_with_cache_key();
      init_types();
      lrn = (inferenceHandler, inputs, attributes) => {
        validateInputs14(inputs);
        return [inferenceHandler.run(createLrnProgramInfoLoader(inputs, attributes), inputs)];
      };
      parseLrnAttributes = (node) => {
        const alpha = node.attributes.getFloat("alpha", 1e-4);
        const beta = node.attributes.getFloat("beta", 0.75);
        const bias = node.attributes.getFloat("bias", 1);
        const size = node.attributes.getInt("size");
        return createAttributeWithCacheKey({ alpha, beta, bias, size });
      };
      lrnProgramMetadata = {
        name: "LRN",
        inputNames: ["X"],
        inputTypes: [0 /* unpacked */]
      };
      validateInputs14 = (inputs) => {
        if (!inputs || inputs.length !== 1) {
          throw new Error("LRN requires 1 input.");
        }
        if (inputs[0].dims.length !== 4) {
          throw new Error('currently only support LRN for input with "NCHW" format');
        }
        if (inputs[0].type !== "float32") {
          throw new Error("input should be float type");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/pad.ts
  var padProgramMetadata, padV2, parsePadAttributesV2, padV11, parsePadAttributesV11, generatePadAttributesFromInputs, createPadProgramInfo, validateInputsV2, validateInputsV11, getPadFunction, getPadConstant, getPadReflect, getPadEdge;
  var init_pad = __esm({
    "web/lib/onnxjs/backends/webgl/ops/pad.ts"() {
      "use strict";
      init_attribute_with_cache_key();
      init_util();
      init_glsl_source();
      init_types();
      padProgramMetadata = {
        name: "Pad",
        inputNames: ["A"],
        inputTypes: [0 /* unpacked */]
      };
      padV2 = (inferenceHandler, inputs, attributes) => {
        validateInputsV2(inputs);
        const output = inferenceHandler.run(
          {
            ...padProgramMetadata,
            cacheHint: attributes.cacheKey,
            get: () => createPadProgramInfo(inferenceHandler, inputs[0], attributes)
          },
          inputs
        );
        return [output];
      };
      parsePadAttributesV2 = (node) => {
        const mode = node.attributes.getString("mode", "constant");
        const value = node.attributes.getFloat("value", 0);
        const pads = node.attributes.getInts("pads");
        return createAttributeWithCacheKey({ mode, value, pads });
      };
      padV11 = (inferenceHandler, inputs, mode) => {
        validateInputsV11(inputs);
        const attrubutes = generatePadAttributesFromInputs(inferenceHandler, inputs, mode);
        return padV2(inferenceHandler, [inputs[0]], attrubutes);
      };
      parsePadAttributesV11 = (node) => node.attributes.getString("mode", "constant");
      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;
        return createAttributeWithCacheKey({ mode, pads, value });
      };
      createPadProgramInfo = (inferenceHandler, input, attributes) => {
        const outputShape = 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: [0 /* unpacked */],
          output: { dims: outputShape, type: input.type, textureType: 0 /* unpacked */ },
          shaderSource
        };
      };
      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.");
        }
      };
      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.");
        }
      };
      getPadFunction = (inferenceHandler, input, attributes) => {
        const glsl = getGlsl(inferenceHandler.session.backend.glContext.version);
        const [width, height] = inferenceHandler.calculateTextureWidthAndHeight(input.dims, 0 /* unpacked */);
        const strides = 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");
        }
      };
      getPadConstant = (glsl, shape2, strides, width, height, pads, value) => {
        const rank = shape2.length;
        let block = "";
        for (let i = rank - 1; i >= 0; --i) {
          block += `
        k = m[${i}] - ${pads[i]};
        if (k < 0)  return constant;
        if (k >= ${shape2[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;
      }
      `;
      };
      getPadReflect = (glsl, shape2, strides, width, height, pads) => {
        const rank = shape2.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 * (shape2[i] - 1)};
          k = int( mod( float(k), float(_2n_1) ) ) ;
          if(k >= ${shape2[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;
      }
      `;
      };
      getPadEdge = (glsl, shape2, strides, width, height, pads) => {
        const rank = shape2.length;
        let block = "";
        for (let i = rank - 1; i >= 0; --i) {
          block += `
        k = m[${i}] - ${pads[i]};
        if (k < 0)  k = 0;
        if (k >= ${shape2[i]}) k = ${shape2[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;
      }
      `;
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/pool.ts
  var averagePool, parseAveragePoolAttributes, createAveragePoolProgramInfo, globalAveragePool, parseGlobalAveragePoolAttributes, maxPool, parseMaxPoolAttributes, createMaxPoolProgramInfo, getAdjustedPoolAttributesAndOutputShape, globalMaxPoolAttributes, globalMaxPoolMetadata, globalMaxPool, validateInputs15, generatePoolingCode, copyArray, offsetToIndices;
  var init_pool = __esm({
    "web/lib/onnxjs/backends/webgl/ops/pool.ts"() {
      "use strict";
      init_attribute_with_cache_key();
      init_util();
      init_types();
      averagePool = (inferenceHandler, inputs, attributes) => {
        validateInputs15(inputs);
        const metadata = { name: "AveragePool", inputNames: ["X"], inputTypes: [0 /* unpacked */], cacheHint: attributes.cacheKey };
        const output = inferenceHandler.run(
          { ...metadata, get: () => createAveragePoolProgramInfo(inputs, metadata, false, attributes) },
          inputs
        );
        return [output];
      };
      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", []);
        if (ceilMode !== 0) {
          throw new Error("using ceil() in shape computation is not yet supported for AveragePool");
        }
        return createAttributeWithCacheKey({ autoPad, ceilMode, countIncludePad, kernelShape, strides, pads });
      };
      createAveragePoolProgramInfo = (inputs, metadata, isGlobalOperator, attributes) => {
        const [adjustedAttributes, outputShape] = getAdjustedPoolAttributesAndOutputShape(inputs, attributes, isGlobalOperator);
        const kernelSize = 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 {
          ...metadata,
          output: { dims: outputShape, type: inputs[0].type, textureType: 0 /* unpacked */ },
          shaderSource
        };
      };
      globalAveragePool = (inferenceHandler, inputs, attributes) => {
        validateInputs15(inputs);
        const metadata = {
          name: "GlobalAveragePool",
          inputNames: ["X"],
          inputTypes: [0 /* unpacked */],
          cacheHint: `${attributes.countIncludePad}`
        };
        const output = inferenceHandler.run(
          { ...metadata, get: () => createAveragePoolProgramInfo(inputs, metadata, true, attributes) },
          inputs
        );
        return [output];
      };
      parseGlobalAveragePoolAttributes = (node) => {
        const countIncludePad = node.attributes.getInt("count_include_pad", 0) === 0 ? false : true;
        return createAttributeWithCacheKey(
          { autoPad: "", ceilMode: 0, countIncludePad, kernelShape: [], strides: [], pads: [] }
        );
      };
      maxPool = (inferenceHandler, inputs, attributes) => {
        validateInputs15(inputs);
        const metadata = { name: "MaxPool", inputNames: ["X"], inputTypes: [0 /* unpacked */], cacheHint: attributes.cacheKey };
        const output = inferenceHandler.run(
          { ...metadata, get: () => createMaxPoolProgramInfo(inputs, metadata, false, attributes) },
          inputs
        );
        return [output];
      };
      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", []);
        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 createAttributeWithCacheKey(
          { autoPad, ceilMode, countIncludePad: false, kernelShape, strides, pads, storageOrder, dilations }
        );
      };
      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 {
          ...metadata,
          output: { dims: outputShape, type: inputs[0].type, textureType: 0 /* unpacked */ },
          shaderSource
        };
      };
      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();
        PoolConvUtil.adjustPoolAttributes(isGlobalOperator, inputShape, kernelShape, strides, dilations, pads);
        const outputShape = 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];
      };
      globalMaxPoolAttributes = {
        autoPad: "",
        ceilMode: 0,
        countIncludePad: false,
        kernelShape: [],
        strides: [],
        pads: [],
        storageOrder: 0,
        dilations: [],
        cacheKey: ""
      };
      globalMaxPoolMetadata = {
        name: "GlobalMaxPool",
        inputNames: ["X"],
        inputTypes: [0 /* unpacked */]
      };
      globalMaxPool = (inferenceHandler, inputs) => {
        validateInputs15(inputs);
        const output = inferenceHandler.run(
          {
            ...globalMaxPoolMetadata,
            get: () => createMaxPoolProgramInfo(inputs, globalMaxPoolMetadata, true, globalMaxPoolAttributes)
          },
          inputs
        );
        return [output];
      };
      validateInputs15 = (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.");
        }
      };
      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 = ShapeUtil.size(attributes.kernelShape);
          const kernelStrides = 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((sum2, cur) => sum2 + 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;
        }
      };
      copyArray = (array, arrayName) => {
        let block = "";
        for (let i = 0; i < array.length; i++) {
          block += `
      ${arrayName}[${i}] = ${array[i]};
    `;
        }
        return block;
      };
      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;
  }`;
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/reduce.ts
  var reduce, parseReduceAttributes, createReduceProgramInfo, validateInputs16, reduceSum, reduceMean, reduceMax, reduceMin, reduceProd, reduceLogSum, reduceLogSumSquare;
  var init_reduce = __esm({
    "web/lib/onnxjs/backends/webgl/ops/reduce.ts"() {
      "use strict";
      init_attribute_with_cache_key();
      init_operators();
      init_util();
      init_types();
      reduce = (inferenceHandler, inputs, attributes, name2, reduceOp) => {
        validateInputs16(inputs);
        const reduceProgramMetadata = {
          name: name2,
          inputNames: ["A"],
          inputTypes: [0 /* unpacked */]
        };
        const output = inferenceHandler.run(
          {
            ...reduceProgramMetadata,
            cacheHint: attributes.cacheKey,
            get: () => createReduceProgramInfo(inferenceHandler, inputs, attributes, name2, reduceOp, reduceProgramMetadata)
          },
          inputs
        );
        return [output];
      };
      parseReduceAttributes = (node) => {
        const axes = node.attributes.getInts("axes", []);
        const keepDims = node.attributes.getInt("keepdims", 1) === 1;
        return createAttributeWithCacheKey({ axes, keepDims });
      };
      createReduceProgramInfo = (_handler, inputs, attributes, _name, reduceOp, reduceProgramMetadata) => {
        const outputShape = [];
        const iRank = inputs[0].dims.length || 1;
        const idxCopy = [];
        const axes = 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 (axes.indexOf(k) >= 0 || axes.length === 0) {
            if (attributes.keepDims) {
              outputShape.push(1);
            }
            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 {
          ...reduceProgramMetadata,
          output: { dims: outputShape, type: inputs[0].type, textureType: 0 /* unpacked */ },
          shaderSource
        };
      };
      validateInputs16 = (inputs) => {
        if (!inputs || inputs.length !== 1) {
          throw new Error("Reduce op requires 1 input.");
        }
        if (NUMBER_TYPES.indexOf(inputs[0].type) === -1) {
          throw new Error("Invalid input type.");
        }
      };
      reduceSum = (inferenceHandler, inputs, attributes) => {
        const reduceOp = () => ["value = 0.0;", "value += _A(inputIdx);", ""];
        return reduce(inferenceHandler, inputs, attributes, "ReduceSum", reduceOp);
      };
      reduceMean = (inferenceHandler, inputs, attributes) => {
        const reduceOp = (inputs2, axes) => {
          let size = 1;
          for (let k = 0; k < inputs2[0].dims.length; k++) {
            if (axes.indexOf(k) >= 0 || axes.length === 0) {
              size *= inputs2[0].dims[k];
            }
          }
          return ["value = 0.0;", "value += _A(inputIdx);", `value /= ${size}.;`];
        };
        return reduce(inferenceHandler, inputs, attributes, "ReduceMean", reduceOp);
      };
      reduceMax = (inferenceHandler, inputs, attributes) => {
        const reduceOp = (inputs2, axes) => {
          const idxZero = [];
          for (let k = 0; k < inputs2[0].dims.length; k++) {
            if (axes.indexOf(k) >= 0 || axes.length === 0) {
              idxZero.push(`inputIdx[${k}] = 0;`);
            }
          }
          return [`${idxZero.join("\n")}
value = _A(inputIdx);`, "value = max(value, _A(inputIdx));", ""];
        };
        return reduce(inferenceHandler, inputs, attributes, "ReduceMax", reduceOp);
      };
      reduceMin = (inferenceHandler, inputs, attributes) => {
        const reduceOp = (inputs2, axes) => {
          const idxZero = [];
          for (let k = 0; k < inputs2[0].dims.length; k++) {
            if (axes.indexOf(k) >= 0 || axes.length === 0) {
              idxZero.push(`inputIdx[${k}] = 0;`);
            }
          }
          return [`${idxZero.join("\n")}
value = _A(inputIdx);`, "value = min(value, _A(inputIdx));", ""];
        };
        return reduce(inferenceHandler, inputs, attributes, "ReduceMin", reduceOp);
      };
      reduceProd = (inferenceHandler, inputs, attributes) => {
        const reduceOp = () => ["value = 1.0;", "value *= _A(inputIdx);", ""];
        return reduce(inferenceHandler, inputs, attributes, "ReduceProd", reduceOp);
      };
      reduceLogSum = (inferenceHandler, inputs, attributes) => {
        const reduceOp = () => ["value = 0.0;", "value += _A(inputIdx);", "value = log(value);"];
        return reduce(inferenceHandler, inputs, attributes, "ReduceLogSum", reduceOp);
      };
      reduceLogSumSquare = (inferenceHandler, inputs, attributes) => {
        const reduceOp = () => ["float t; value = 0.0;", "t = _A(inputIdx); value += t * t;", ""];
        return reduce(inferenceHandler, inputs, attributes, "ReduceLogSumSquare", reduceOp);
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/reshape.ts
  var reshape;
  var init_reshape = __esm({
    "web/lib/onnxjs/backends/webgl/ops/reshape.ts"() {
      "use strict";
      init_util();
      reshape = (handler, inputs) => {
        const reshapedDims = 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)];
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/upsample.ts
  var upsampleProgramMetadata, upsample, parseUpsampleAttributesV7, parseUpsampleAttributesV9, parseUpsampleAttributes, createUpsampleProgramInfo, validateInputs17, scalesValidation;
  var init_upsample = __esm({
    "web/lib/onnxjs/backends/webgl/ops/upsample.ts"() {
      "use strict";
      init_attribute_with_cache_key();
      init_glsl_source();
      init_types();
      upsampleProgramMetadata = {
        name: "Upsample",
        inputNames: ["X"],
        inputTypes: [0 /* unpacked */]
      };
      upsample = (inferenceHandler, inputs, attributes) => {
        validateInputs17(inputs, attributes);
        const output = inferenceHandler.run(
          {
            ...upsampleProgramMetadata,
            cacheHint: attributes.cacheKey,
            get: () => createUpsampleProgramInfo(inferenceHandler, inputs, attributes)
          },
          inputs
        );
        return [output];
      };
      parseUpsampleAttributesV7 = (node) => parseUpsampleAttributes(node, 7);
      parseUpsampleAttributesV9 = (node) => parseUpsampleAttributes(node, 9);
      parseUpsampleAttributes = (node, opset) => {
        const isResize = opset >= 10;
        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");
          scalesValidation(scales, mode, isResize);
        }
        const extrapolationValue = node.attributes.getFloat("extrapolation_value", 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) {
          if (node.inputs.length > 2) {
            roiInputIdx = 1;
            scalesInputIdx = 2;
            sizesInputIdx = 3;
          } else {
            scalesInputIdx = 1;
            sizesInputIdx = 2;
          }
        } else if (opset === 9) {
          scalesInputIdx = 1;
        }
        return createAttributeWithCacheKey({
          opset,
          isResize,
          mode,
          scales,
          extrapolationValue,
          coordinateTransformMode,
          useExtrapolation,
          needRoiInput,
          nearestMode,
          cubicCoefficientA,
          excludeOutside,
          useNearest2xOptimization,
          roiInputIdx,
          scalesInputIdx,
          sizesInputIdx
        });
      };
      createUpsampleProgramInfo = (inferenceHandler, inputs, attributes) => {
        const glsl = getGlsl(inferenceHandler.session.backend.glContext.version);
        const [inputWidth, inputHeight] = inferenceHandler.calculateTextureWidthAndHeight(inputs[0].dims, 0 /* unpacked */);
        const outputShape = inputs[0].dims.map((dim2, i) => Math.floor(dim2 * attributes.scales[i]));
        const [outputWidth, outputHeight] = inferenceHandler.calculateTextureWidthAndHeight(outputShape, 0 /* 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 {
          ...upsampleProgramMetadata,
          output: { dims: outputShape, type: inputs[0].type, textureType: 0 /* unpacked */ },
          shaderSource,
          variables: [{
            name: "scales",
            type: "int",
            arrayLength: attributes.scales.length,
            data: attributes.scales.map((x) => Math.ceil(x))
          }]
        };
      };
      validateInputs17 = (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.");
        }
      };
      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.`);
          }
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/resize-packed.ts
  var resizeProgramMetadata, resize, parseResizeAttributesV10, parseResizeAttributesV11, createPackedResizeProgramInfo, prepareInputs, parseScalesData, parseScalesDataFromOutputSize;
  var init_resize_packed = __esm({
    "web/lib/onnxjs/backends/webgl/ops/resize-packed.ts"() {
      "use strict";
      init_glsl_source();
      init_types();
      init_utils();
      init_packing_utils();
      init_upsample();
      resizeProgramMetadata = {
        name: "Resize",
        inputNames: ["A"],
        inputTypes: [2 /* packed */]
      };
      resize = (inferenceHandler, inputs, attributes) => {
        validateInputs17(inputs, attributes);
        const output = inferenceHandler.run(
          {
            ...resizeProgramMetadata,
            cacheHint: attributes.cacheKey,
            get: () => createPackedResizeProgramInfo(inferenceHandler, inputs, attributes)
          },
          inputs
        );
        return [output];
      };
      parseResizeAttributesV10 = (node) => parseUpsampleAttributes(node, 10);
      parseResizeAttributesV11 = (node) => parseUpsampleAttributes(node, 11);
      createPackedResizeProgramInfo = (inferenceHandler, inputs, attributes) => {
        const glsl = 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 {
            ...resizeProgramMetadata,
            output: { dims: outputShape, type: inputs[0].type, textureType: 2 /* 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") {
          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:
            throw new Error(`resize (packed) does not support coordinateTransformMode:                                 '${attributes.coordinateTransformMode}'`);
        }
        const coordsDataType = getCoordsDataType(dim);
        const unpackChannel = 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 {
          ...resizeProgramMetadata,
          output: { dims: outputShape, type: inputs[0].type, textureType: 2 /* packed */ },
          hasMain: true,
          shaderSource
        };
      };
      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];
      };
      parseScalesData = (scale, mode, isResize) => {
        const scales = Array.from(scale.floatData);
        scalesValidation(scales, mode, isResize);
        return scales;
      };
      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];
          }
        }
        scalesValidation(scales, mode, isResize);
        return scales;
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/shape.ts
  var shape, validateInputs18;
  var init_shape = __esm({
    "web/lib/onnxjs/backends/webgl/ops/shape.ts"() {
      "use strict";
      init_tensor2();
      shape = (_inferenceHandler, inputs) => {
        validateInputs18(inputs);
        return [new Tensor3([inputs[0].dims.length], "int32", void 0, void 0, new Int32Array(inputs[0].dims))];
      };
      validateInputs18 = (inputs) => {
        if (!inputs || inputs.length !== 1) {
          throw new Error("Shape requires 1 input.");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/slice.ts
  var sliceProgramMetadata, slice, parseSliceAttributes, createSliceProgramInfo, validateInputs19, sliceV10, generateSliceAttributesFromInputs, validateInputsV10;
  var init_slice = __esm({
    "web/lib/onnxjs/backends/webgl/ops/slice.ts"() {
      "use strict";
      init_attribute_with_cache_key();
      init_operators();
      init_util();
      init_types();
      sliceProgramMetadata = {
        name: "Slice",
        inputNames: ["A"],
        inputTypes: [0 /* unpacked */]
      };
      slice = (inferenceHandler, inputs, attributes) => {
        validateInputs19(inputs);
        const output = inferenceHandler.run(
          {
            ...sliceProgramMetadata,
            cacheHint: attributes.cacheKey,
            get: () => createSliceProgramInfo(inferenceHandler, inputs[0], attributes)
          },
          inputs
        );
        return [output];
      };
      parseSliceAttributes = (node) => {
        const starts = node.attributes.getInts("starts");
        const ends = node.attributes.getInts("ends");
        const axes = node.attributes.getInts("axes", []);
        return createAttributeWithCacheKey({ starts, ends, axes });
      };
      createSliceProgramInfo = (_inferenceHandler, input, attributes) => {
        const axes = attributes.axes.length === 0 ? input.dims.slice(0).map((_val, i) => i) : attributes.axes;
        const normalizedAxes = 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 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 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]};`);
          }
        }
        const rank = outputShape.length;
        const shaderSource = `
      float process(int outputIdx[${rank}]) {
        ${sliceOps.join("\n      ")}
        return _A(outputIdx);
      }`;
        return {
          ...sliceProgramMetadata,
          output: { dims: outputShape, type: input.type, textureType: 0 /* unpacked */ },
          shaderSource
        };
      };
      validateInputs19 = (inputs) => {
        if (!inputs || inputs.length !== 1) {
          throw new Error("Slice requires 1 input.");
        }
        if (NUMBER_TYPES.indexOf(inputs[0].type) === -1) {
          throw new Error("Invalid input type.");
        }
      };
      sliceV10 = (inferenceHandler, inputs) => {
        validateInputsV10(inputs);
        const attributes = generateSliceAttributesFromInputs(inferenceHandler, inputs);
        const output = inferenceHandler.run(
          {
            ...sliceProgramMetadata,
            cacheHint: attributes.cacheKey,
            get: () => createSliceProgramInfo(inferenceHandler, inputs[0], attributes)
          },
          [inputs[0]]
        );
        return [output];
      };
      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 };
      };
      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.");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/softmax.ts
  var softmaxComputeMaxProgramMetadata, softmaxComputeScaleProgramMetadata, softmaxProgramMetadata, softmax, parseSoftmaxAttributes, parseSoftmaxAttributesV13, softmaxV13, computeSoftmax, createComputeMaxProgramInfo, createComputScaleProgramInfo, createSoftMaxProgramInfo, validateInputs20;
  var init_softmax = __esm({
    "web/lib/onnxjs/backends/webgl/ops/softmax.ts"() {
      "use strict";
      init_attribute_with_cache_key();
      init_util();
      init_glsl_source();
      init_types();
      init_transpose();
      softmaxComputeMaxProgramMetadata = {
        name: "SoftmaxComputeMax",
        inputNames: ["A"],
        inputTypes: [0 /* unpacked */]
      };
      softmaxComputeScaleProgramMetadata = {
        name: "SoftmaxComputeScale",
        inputNames: ["A", "Max"],
        inputTypes: [0 /* unpacked */, 0 /* unpacked */]
      };
      softmaxProgramMetadata = {
        name: "SoftMax",
        inputNames: ["A", "Max", "Norm"],
        inputTypes: [0 /* unpacked */, 0 /* unpacked */, 0 /* unpacked */]
      };
      softmax = (inferenceHandler, inputs, attributes) => {
        validateInputs20(inputs);
        const inputShape = inputs[0].dims.slice();
        const axis = ShapeUtil.normalizeAxis(attributes.axis, inputShape.length);
        const logicalRowCount = ShapeUtil.sizeToDimension(inputShape, axis);
        const featureCount = ShapeUtil.sizeFromDimension(inputShape, axis);
        const output = computeSoftmax(inferenceHandler, inputs, attributes, logicalRowCount, featureCount);
        return output;
      };
      parseSoftmaxAttributes = (node) => createAttributeWithCacheKey({ axis: node.attributes.getInt("axis", 1) });
      parseSoftmaxAttributesV13 = (node) => createAttributeWithCacheKey({ axis: node.attributes.getInt("axis", -1) });
      softmaxV13 = (inferenceHandler, inputs, attributes) => {
        validateInputs20(inputs);
        const inputShape = inputs[0].dims.slice();
        const axis = 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);
          perm[axis] = rank - 1;
          perm[rank - 1] = axis;
          perm.map((p) => transposedInputShape.push(inputShape[p]));
          transposeAttribute = createAttributeWithCacheKey({ perm });
          transposedInputs = transpose(inferenceHandler, inputs, transposeAttribute);
        }
        const logicalRowCount = isTransposeRequired ? ShapeUtil.sizeToDimension(transposedInputShape, rank - 1) : ShapeUtil.sizeToDimension(inputShape, rank - 1);
        const featureCount = isTransposeRequired ? ShapeUtil.sizeFromDimension(transposedInputShape, rank - 1) : ShapeUtil.sizeFromDimension(inputShape, rank - 1);
        const output = computeSoftmax(
          inferenceHandler,
          isTransposeRequired ? transposedInputs : inputs,
          attributes,
          logicalRowCount,
          featureCount
        );
        if (isTransposeRequired) {
          const reversedOutput = transpose(inferenceHandler, output, transposeAttribute);
          return reversedOutput;
        } else {
          return output;
        }
      };
      computeSoftmax = (inferenceHandler, inputs, attributes, logicalRowCount, featureCount) => {
        const computeMaxProgramInfo = createComputeMaxProgramInfo(inferenceHandler, inputs[0], logicalRowCount, featureCount, [logicalRowCount]);
        const max = inferenceHandler.run(
          { ...softmaxComputeMaxProgramMetadata, cacheHint: attributes.cacheKey, get: () => computeMaxProgramInfo },
          inputs
        );
        const computeScaleProgramInfo = createComputScaleProgramInfo(
          inferenceHandler,
          inputs[0],
          logicalRowCount,
          featureCount,
          computeMaxProgramInfo.output.dims,
          [logicalRowCount]
        );
        const scale = inferenceHandler.run(
          { ...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(
          { ...softmaxProgramMetadata, cacheHint: attributes.cacheKey, get: () => softMaxProgramInfo },
          [inputs[0], max, scale]
        );
        return [output];
      };
      createComputeMaxProgramInfo = (inferenceHandler, input, logicalRowCount, featureCount, outputShape) => {
        const [textureWidth, textureHeight] = inferenceHandler.calculateTextureWidthAndHeight(input.dims, 0 /* 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 = 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 {
          ...softmaxComputeMaxProgramMetadata,
          output: { dims: outputShape, type: input.type, textureType: 0 /* unpacked */ },
          shaderSource
        };
      };
      createComputScaleProgramInfo = (inferenceHandler, input, logicalRowCount, featureCount, maxElementPerLogicalRow, outputShape) => {
        const [textureWidth, textureHeight] = inferenceHandler.calculateTextureWidthAndHeight(input.dims, 0 /* 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 = 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 {
          ...softmaxComputeScaleProgramMetadata,
          output: { dims: outputShape, type: input.type, textureType: 0 /* unpacked */ },
          shaderSource
        };
      };
      createSoftMaxProgramInfo = (inferenceHandler, input, logicalRowCount, featureCount, maxElementPerLogicalRow, normalizationPerLogicalRow) => {
        const [textureWidth, textureHeight] = inferenceHandler.calculateTextureWidthAndHeight(input.dims, 0 /* 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 {
          ...softmaxProgramMetadata,
          output: { dims: input.dims, type: input.type, textureType: 0 /* unpacked */ },
          shaderSource
        };
      };
      validateInputs20 = (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");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/split.ts
  var splitProgramMetadata, split, parseSplitAttributes, getProgramCount, createSplitProgramInfo, validateInputs21;
  var init_split = __esm({
    "web/lib/onnxjs/backends/webgl/ops/split.ts"() {
      "use strict";
      init_attribute_with_cache_key();
      init_util();
      init_types();
      splitProgramMetadata = {
        name: "Split",
        inputNames: ["A"],
        inputTypes: [0 /* unpacked */]
      };
      split = (inferenceHandler, inputs, attributes) => {
        validateInputs21(inputs);
        const axis = 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(
            {
              ...splitProgramMetadata,
              cacheHint: `${attributes.cacheKey};${i}`,
              get: () => createSplitProgramInfo(inferenceHandler, inputs[0], attributes, axis, i)
            },
            inputs
          ));
        }
        return output;
      };
      parseSplitAttributes = (node) => {
        const axis = node.attributes.getInt("axis", 0);
        const split2 = node.attributes.getInts("split", []);
        const numOutputs = node.outputs.length;
        return createAttributeWithCacheKey({ axis, split: split2, numOutputs });
      };
      getProgramCount = (_inferenceHandler, inputs, axis, attributes) => {
        const [, offsets] = SplitUtil.splitShape(inputs[0].dims, axis, attributes.split, attributes.numOutputs);
        return offsets.length;
      };
      createSplitProgramInfo = (_inferenceHandler, input, attributes, axis, index) => {
        const [shapes, offsets] = 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 {
          ...splitProgramMetadata,
          cacheHint: `${attributes.cacheKey}:${index}`,
          output: { dims: outputShape, type: input.type, textureType: 0 /* unpacked */ },
          shaderSource
        };
      };
      validateInputs21 = (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.");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/squeeze.ts
  var squeeze, squeezeV13, parseSqueezeAttributes, validateInputs22, validateInputsV13;
  var init_squeeze = __esm({
    "web/lib/onnxjs/backends/webgl/ops/squeeze.ts"() {
      "use strict";
      init_util();
      squeeze = (inferenceHandler, inputs, axes) => {
        validateInputs22(inputs);
        const outputShape = ShapeUtil.squeezeShape(inputs[0].dims, axes);
        const output = inferenceHandler.reshapeUnpacked(inputs[0], outputShape);
        return [output];
      };
      squeezeV13 = (inferenceHandler, inputs) => {
        validateInputsV13(inputs);
        return squeeze(inferenceHandler, [inputs[0]], Array.from(inputs[1].integerData));
      };
      parseSqueezeAttributes = (node) => node.attributes.getInts("axes");
      validateInputs22 = (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.");
        }
      };
      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.");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/sum.ts
  var sum, createSumProgramInfo, validateInputs23;
  var init_sum = __esm({
    "web/lib/onnxjs/backends/webgl/ops/sum.ts"() {
      "use strict";
      init_glsl_source();
      init_types();
      sum = (inferenceHandler, inputs) => {
        validateInputs23(inputs);
        const sumProgramMetadata = {
          name: "Sum",
          inputNames: inputs.map((_v, i) => `X${i}`),
          inputTypes: new Array(inputs.length).fill(0 /* unpacked */)
        };
        const output = inferenceHandler.run(
          { ...sumProgramMetadata, get: () => createSumProgramInfo(inferenceHandler, inputs, sumProgramMetadata) },
          inputs
        );
        return [output];
      };
      createSumProgramInfo = (inferenceHandler, inputs, sumProgramMetadata) => {
        const glsl = 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 {
          ...sumProgramMetadata,
          output: { dims: outputShape, type: inputs[0].type, textureType: 0 /* unpacked */ },
          hasMain: true,
          shaderSource
        };
      };
      validateInputs23 = (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.");
          }
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/tile.ts
  var tile, createTileProgramInfo, validateInputs24;
  var init_tile = __esm({
    "web/lib/onnxjs/backends/webgl/ops/tile.ts"() {
      "use strict";
      init_operators();
      init_types();
      tile = (inferenceHandler, inputs) => {
        validateInputs24(inputs);
        const tileProgramMetadata = {
          name: "Tile",
          inputNames: ["A"],
          inputTypes: [0 /* unpacked */]
        };
        const output = inferenceHandler.run(
          { ...tileProgramMetadata, get: () => createTileProgramInfo(inferenceHandler, inputs, tileProgramMetadata) },
          inputs
        );
        return [output];
      };
      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 {
          ...tileProgramMetadata,
          output: { dims: outputShape, type: inputs[0].type, textureType: 0 /* unpacked */ },
          shaderSource
        };
      };
      validateInputs24 = (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 (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.");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/ops/unsqueeze.ts
  var unsqueeze, unsqueezeV13, parseUnsqueezeAttributes, validateInputs25, validateInputsV132;
  var init_unsqueeze = __esm({
    "web/lib/onnxjs/backends/webgl/ops/unsqueeze.ts"() {
      "use strict";
      init_util();
      unsqueeze = (inferenceHandler, inputs, axes) => {
        validateInputs25(inputs);
        const outputShape = ShapeUtil.unsqueezeShape(inputs[0].dims, axes);
        const output = inferenceHandler.reshapeUnpacked(inputs[0], outputShape);
        return [output];
      };
      unsqueezeV13 = (inferenceHandler, inputs) => {
        validateInputsV132(inputs);
        return unsqueeze(inferenceHandler, [inputs[0]], Array.from(inputs[1].integerData));
      };
      parseUnsqueezeAttributes = (node) => node.attributes.getInts("axes");
      validateInputs25 = (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.");
        }
      };
      validateInputsV132 = (inputs) => {
        if (!inputs || inputs.length !== 2) {
          throw new Error("Unsqueeze requires 2 inputs.");
        }
        if (inputs[1].type !== "int32") {
          throw new Error("Invalid input type.");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/op-resolve-rules.ts
  var WEBGL_OP_RESOLVE_RULES;
  var init_op_resolve_rules = __esm({
    "web/lib/onnxjs/backends/webgl/op-resolve-rules.ts"() {
      "use strict";
      init_batch_normalization();
      init_binary_op();
      init_cast();
      init_concat();
      init_conv();
      init_conv_transpose();
      init_depth_to_space();
      init_flatten();
      init_gather();
      init_gemm();
      init_image_scaler();
      init_instance_normalization();
      init_lrn();
      init_matmul();
      init_pad();
      init_pool();
      init_reduce();
      init_reshape();
      init_resize_packed();
      init_shape();
      init_slice();
      init_softmax();
      init_split();
      init_squeeze();
      init_sum();
      init_tile();
      init_transpose();
      init_unary_op();
      init_unsqueeze();
      init_upsample();
      WEBGL_OP_RESOLVE_RULES = [
        ["Abs", "", "6+", abs],
        ["Acos", "", "7+", acos],
        ["Add", "", "7+", add2],
        ["And", "", "7+", and2],
        ["Asin", "", "7+", asin],
        ["Atan", "", "7+", atan],
        // TODO: support new attributes for AveragePool-10
        ["AveragePool", "", "7+", averagePool, parseAveragePoolAttributes],
        ["BatchNormalization", "", "7+", batchNormalization, parseBatchNormalizationAttributes],
        ["Cast", "", "6+", cast, parseCastAttributes],
        ["Ceil", "", "6+", ceil],
        ["Clip", "", "6-10", clip, parseClipAttributes],
        ["Clip", "", "11+", clipV11],
        ["Concat", "", "4+", concat, parseConcatAttributes],
        ["Conv", "", "1+", conv, parseConvAttributes],
        ["ConvTranspose", "", "1+", convTranspose, parseConvTransposeAttributes],
        ["Cos", "", "7+", cos],
        ["Div", "", "7+", div],
        ["Dropout", "", "7+", identity],
        ["DepthToSpace", "", "1+", depthToSpace, parseDepthToSpaceAttributes],
        ["Equal", "", "7+", equal],
        ["Elu", "", "6+", elu, parseEluAttributes],
        ["Exp", "", "6+", exp],
        ["Flatten", "", "1+", flatten, parseFlattenAttributes],
        ["Floor", "", "6+", floor],
        ["FusedConv", "com.microsoft", "1+", conv, parseConvAttributes],
        ["Gather", "", "1+", gather, parseGatherAttributes],
        ["Gemm", "", "7-10", gemm, parseGemmAttributesV7],
        ["Gemm", "", "11+", gemm, parseGemmAttributesV11],
        ["GlobalAveragePool", "", "1+", globalAveragePool, parseGlobalAveragePoolAttributes],
        ["GlobalMaxPool", "", "1+", globalMaxPool],
        ["Greater", "", "7+", greater],
        ["Identity", "", "1+", identity],
        ["ImageScaler", "", "1+", imageScaler, parseImageScalerAttributes],
        ["InstanceNormalization", "", "6+", instanceNormalization, parseInstanceNormalizationAttributes],
        ["LeakyRelu", "", "6+", leakyRelu, parseLeakyReluAttributes],
        ["Less", "", "7+", less],
        ["LRN", "", "1+", lrn, parseLrnAttributes],
        ["Log", "", "6+", log2],
        ["MatMul", "", "1+", matMul, parseMatMulAttributes],
        // TODO: support new attributes for MaxPool-8 and MaxPool-10
        ["MaxPool", "", "1+", maxPool, parseMaxPoolAttributes],
        ["Mul", "", "7+", mul],
        ["Neg", "", "6+", neg],
        ["Not", "", "1+", not2],
        ["Or", "", "7+", or2],
        ["Pad", "", "2-10", padV2, parsePadAttributesV2],
        ["Pad", "", "11+", padV11, parsePadAttributesV11],
        ["Pow", "", "7+", pow],
        ["PRelu", "", "7+", pRelu],
        ["ReduceLogSum", "", "1+", reduceLogSum, parseReduceAttributes],
        ["ReduceMax", "", "1+", reduceMax, parseReduceAttributes],
        ["ReduceMean", "", "1+", reduceMean, parseReduceAttributes],
        ["ReduceMin", "", "1+", reduceMin, parseReduceAttributes],
        ["ReduceProd", "", "1+", reduceProd, parseReduceAttributes],
        ["ReduceSum", "", "1-12", reduceSum, parseReduceAttributes],
        ["ReduceSumSquare", "", "1+", reduceLogSumSquare, parseReduceAttributes],
        ["Relu", "", "6+", relu],
        ["Reshape", "", "5+", reshape],
        ["Resize", "", "10", resize, parseResizeAttributesV10],
        ["Resize", "", "11+", resize, parseResizeAttributesV11],
        ["Shape", "", "1+", shape],
        ["Sigmoid", "", "6+", sigmoid],
        ["Sin", "", "7+", sin],
        ["Slice", "", "10+", sliceV10],
        // TODO: support 'steps' for Slice-10
        ["Slice", "", "1-9", slice, parseSliceAttributes],
        // The "semantic" meaning of axis has changed in opset-13.
        ["Softmax", "", "1-12", softmax, parseSoftmaxAttributes],
        ["Softmax", "", "13+", softmaxV13, 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, parseSplitAttributes],
        ["Sqrt", "", "6+", sqrt],
        ["Squeeze", "", "1-12", squeeze, parseSqueezeAttributes],
        ["Squeeze", "", "13+", squeezeV13],
        ["Sub", "", "7+", sub],
        ["Sum", "", "6+", sum],
        ["Tan", "", "7+", tan],
        ["Tanh", "", "6+", tanh],
        ["Tile", "", "6+", tile],
        ["Transpose", "", "1+", transpose, parseTransposeAttributes],
        ["Upsample", "", "7-8", upsample, parseUpsampleAttributesV7],
        ["Upsample", "", "9", upsample, parseUpsampleAttributesV9],
        ["Unsqueeze", "", "1-12", unsqueeze, parseUnsqueezeAttributes],
        ["Unsqueeze", "", "13+", unsqueezeV13],
        ["Xor", "", "7+", xor2]
      ];
    }
  });

  // web/lib/onnxjs/backends/webgl/glsl-function-inliner.ts
  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 name2 in inlineDefs) {
      const regexString = FUNC_CALL_REGEX.replace("__FUNC__", name2);
      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[name2].body;
        let paramRedecLine = "";
        inlineDefs[name2].params.forEach((v, i) => {
          if (v) {
            paramRedecLine += `${v.type} ${v.name} = ${params[i]};
`;
          }
        });
        newBody = `${paramRedecLine}
 ${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;
  }
  var INLINE_FUNC_DEF_REGEX, FUNC_CALL_REGEX;
  var init_glsl_function_inliner = __esm({
    "web/lib/onnxjs/backends/webgl/glsl-function-inliner.ts"() {
      "use strict";
      INLINE_FUNC_DEF_REGEX = /@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm;
      FUNC_CALL_REGEX = "(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;";
    }
  });

  // web/lib/onnxjs/backends/webgl/texture-layout-strategy.ts
  function squeezeShape(shape2, axis) {
    const newShape = [];
    const keptDims = [];
    const isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0;
    const axes = axis == null || isEmptyArray ? null : parseAxisParam(axis, shape2).sort();
    let j = 0;
    for (let i = 0; i < shape2.length; ++i) {
      if (axes != null) {
        if (axes[j] === i && shape2[i] !== 1) {
          throw new Error(`Can't squeeze axis ${i} since its dim '${shape2[i]}' is not 1`);
        }
        if ((axes[j] == null || axes[j] > i) && shape2[i] === 1) {
          newShape.push(shape2[i]);
          keptDims.push(i);
        }
        if (axes[j] <= i) {
          j++;
        }
      }
      if (shape2[i] !== 1) {
        newShape.push(shape2[i]);
        keptDims.push(i);
      }
    }
    return { newShape, keptDims };
  }
  function parseAxisParam(axis, shape2) {
    const rank = shape2.length;
    axis = axis == null ? shape2.map((_s, i) => i) : [].concat(axis);
    assert(
      axis.every((ax) => ax >= -rank && ax < rank),
      () => `All values in axis param must be in range [-${rank}, ${rank}) but got axis ${axis}`
    );
    assert(
      axis.every(isInt),
      () => `All values in axis param must be integers but got axis ${axis}`
    );
    return axis.map((a) => a < 0 ? rank + a : a);
  }
  function isInt(a) {
    return a % 1 === 0;
  }
  function sizeFromShape(shape2) {
    if (shape2.length === 0) {
      return 1;
    }
    let size = shape2[0];
    for (let i = 1; i < shape2.length; i++) {
      size *= shape2[i];
    }
    return size;
  }
  function sizeToSquarishShape(size) {
    const width = Math.ceil(Math.sqrt(size));
    return [width, Math.ceil(size / width)];
  }
  var PreferLogicalStrategy;
  var init_texture_layout_strategy = __esm({
    "web/lib/onnxjs/backends/webgl/texture-layout-strategy.ts"() {
      "use strict";
      init_instrument();
      init_util();
      PreferLogicalStrategy = class {
        constructor(maxTextureSize) {
          this.maxTextureSize = maxTextureSize;
        }
        computeTextureWH(shape2, prefs) {
          const wh = this.computeTexture(shape2, prefs);
          if (prefs && prefs.isPacked) {
            wh[0] /= 2;
            wh[1] /= 2;
          }
          if (prefs && prefs.reverseWH) {
            return [wh[1], wh[0]];
          }
          return wh;
        }
        computeTexture(shape2, prefs) {
          const isPacked = prefs && prefs.isPacked;
          if (shape2.length === 0) {
            return isPacked ? [2, 2] : [1, 1];
          }
          let maxTextureSize = this.maxTextureSize;
          if (prefs && prefs.breakAxis !== void 0) {
            const wsize = prefs.breakAxis >= shape2.length ? 1 : shape2.slice(prefs.breakAxis).reduce((a, b) => a * b);
            const hsize = prefs.breakAxis <= 0 ? 1 : shape2.slice(0, prefs.breakAxis).reduce((a, b) => a * b);
            if (wsize > maxTextureSize || hsize > maxTextureSize) {
              Logger.verbose(
                "TextureLayout",
                `Given width/height preferences were unattainable: shape:${shape2}, breakAxis:${prefs.breakAxis}`
              );
            } else {
              return [wsize, hsize];
            }
          }
          let logShape = shape2.slice(0);
          if (isPacked) {
            maxTextureSize = maxTextureSize * 2;
            logShape = logShape.map(
              (_d, i) => i >= logShape.length - 2 ? logShape[i] % 2 === 0 ? logShape[i] : logShape[i] + 1 : logShape[i]
            );
            if (logShape.length === 1) {
              logShape = [2, logShape[0]];
            }
          }
          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) {
              return sizeToSquarishShape(size / 4).map((d) => d * 2);
            }
            return sizeToSquarishShape(size);
          }
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/glsl-coordinate-lib.ts
  var CoordsGlslLib;
  var init_glsl_coordinate_lib = __esm({
    "web/lib/onnxjs/backends/webgl/glsl-coordinate-lib.ts"() {
      "use strict";
      init_util();
      init_glsl_definitions();
      init_glsl_source();
      init_texture_layout_strategy();
      init_utils();
      CoordsGlslLib = class extends GlslLib {
        constructor(context) {
          super(context);
        }
        getFunctions() {
          return {
            ...this.offsetToCoords(),
            ...this.coordsToOffset(),
            ...this.toVec(),
            ...this.valueFrom(),
            // TODO return these only when packing is enabled.
            ...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 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 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 = getGlsl(this.context.glContext.version);
          const floatTextureSetRGBASource = `
      void setOutput(vec4 val) {
        ${glsl.output} = val;
      }
    `;
          const floatTextureSetRGBAFuncName = "floatTextureSetRGBA";
          result[floatTextureSetRGBAFuncName] = new 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 = getGlsl(this.context.glContext.version);
          const floatTextureSetRSource = `
        void setOutput(float val) {
          ${glsl.output} = vec4(val, 0, 0, 0);
        }
    `;
          const floatTextureSetRFuncName = "floatTextureSetR";
          result[floatTextureSetRFuncName] = new GlslLibRoutine(floatTextureSetRSource);
          return result;
        }
        /**
         * Scalar output coordinates.
         */
        getOutputScalarCoords() {
          return new 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 GlslLibRoutine(source);
          }
          if (packedTexShape[1] === 1) {
            source = `
          int getOutputCoords() {
            return 2 * int(TexCoords.x * ${packedTexShape[0]}.0);
          }
        `;
            return new 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 GlslLibRoutine(source);
        }
        /**
         * 2D packed output coordinates.
         */
        getOutputPacked2DCoords(shape2, texShape) {
          let source = "";
          if (ArrayUtil.arraysEqual(shape2, texShape)) {
            source = `
        ivec2 getOutputCoords() {
          return 2 * ivec2(TexCoords.xy * vec2(${texShape[0]}, ${texShape[1]}));
        }
      `;
            return new GlslLibRoutine(source);
          }
          const packedTexShape = texShape;
          const texelsInLogicalRow = Math.ceil(shape2[1] / 2);
          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 GlslLibRoutine(source);
        }
        /**
         * 3D packed output coordinates.
         */
        getOutputPacked3DCoords(shape2, texShape) {
          const packedTexShape = [texShape[0], texShape[1]];
          const texelsInLogicalRow = Math.ceil(shape2[2] / 2);
          const texelsInBatch = texelsInLogicalRow * Math.ceil(shape2[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 GlslLibRoutine(source);
        }
        /**
         * ND packed output coordinates.
         */
        getOutputPackedNDCoords(shape2, texShape) {
          const packedTexShape = [texShape[0], texShape[1]];
          const texelsInLogicalRow = Math.ceil(shape2[shape2.length - 1] / 2);
          const texelsInBatch = texelsInLogicalRow * Math.ceil(shape2[shape2.length - 2] / 2);
          let texelsInBatchN = texelsInBatch;
          let batches = "";
          let coords = "b, r, c";
          for (let b = 2; b < shape2.length - 1; b++) {
            texelsInBatchN *= shape2[shape2.length - b - 1];
            batches = `
      int b${b} = index / ${texelsInBatchN};
      index -= b${b} * ${texelsInBatchN};
    ` + batches;
            coords = `b${b}, ` + coords;
          }
          const source = `
      ivec${shape2.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${shape2.length}(${coords});
      }
    `;
          return new 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 GlslLibRoutine(source);
        }
        /**
         * Unpacked 2D output coordinates.
         */
        getOutputUnpacked2DCoords(shape2, 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 / ${shape2[1]};
          int c = index - r * ${shape2[1]};
          return ivec2(r, c);
        }
      `;
          return new GlslLibRoutine(source);
        }
        /**
         * Unpacked 3D output coordinates.
         */
        getOutputUnpacked3DCoords(shape2, texShape) {
          let source = "";
          const rank = shape2.length;
          let strides = null;
          if (rank < 2) {
            strides = [];
          }
          strides = new Array(rank - 1);
          strides[rank - 2] = shape2[rank - 1];
          for (let i = rank - 3; i >= 0; --i) {
            strides[i] = strides[i + 1] * shape2[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 GlslLibRoutine(source);
        }
        /**
         * Unpacked 4D output coordinates.
         */
        getOutputUnpacked4DCoords(shape2, texShape) {
          let source = "";
          const rank = shape2.length;
          let strides = null;
          if (rank < 2) {
            strides = [];
          }
          strides = new Array(rank - 1);
          strides[rank - 2] = shape2[rank - 1];
          for (let i = rank - 3; i >= 0; --i) {
            strides[i] = strides[i + 1] * shape2[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 GlslLibRoutine(source);
        }
        /**
         * Unpacked 5D output coordinates.
         */
        getOutputUnpacked5DCoords(shape2, texShape) {
          let source = "";
          const rank = shape2.length;
          let strides = null;
          if (rank < 2) {
            strides = [];
          }
          strides = new Array(rank - 1);
          strides[rank - 2] = shape2[rank - 1];
          for (let i = rank - 3; i >= 0; --i) {
            strides[i] = strides[i + 1] * shape2[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 GlslLibRoutine(source);
        }
        /**
         * Unpacked 6D output coordinates.
         */
        getOutputUnpacked6DCoords(shape2, texShape) {
          let source = "";
          const rank = shape2.length;
          let strides = null;
          if (rank < 2) {
            strides = [];
          }
          strides = new Array(rank - 1);
          strides[rank - 2] = shape2[rank - 1];
          for (let i = rank - 3; i >= 0; --i) {
            strides[i] = strides[i + 1] * shape2[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 GlslLibRoutine(source);
        }
        /**
         * Generates code for common UV coords computation utility functions.
         */
        getCommonUtilFuncs() {
          const result = {};
          let funcName = "uvFromFlat";
          result[funcName] = new 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 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 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 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 = getGlsl(this.context.glContext.version);
          result[funcName] = new 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 = generateShaderFuncNameFromInputSamplerName(samplerName);
            if (inputLayout.isPacked) {
              result[funcName] = this.getPackedSamplerFromInput(funcName, samplerName, inputLayout);
            } else {
              result[funcName] = this.getUnpackedSamplerFromInput(funcName, samplerName, inputLayout);
            }
            const outCoordFuncName = 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, name2) {
          const inShape = inputLayout.unpackedShape;
          const outShape = outputLayout.unpackedShape;
          const texName = name2;
          const texFuncSnippet = generateShaderFuncNameFromInputSamplerName(texName);
          const inRank = inShape.length;
          const outRank = outShape.length;
          const broadcastDims = BroadcastUtil.getBroadcastDims(inShape, outShape);
          const type = getCoordsDataType(outRank);
          const rankDiff = outRank - inRank;
          let coordsSnippet;
          const fields = 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 = ShapeUtil.size(inShape);
          const isInputScalar = inSize === 1;
          const outSize = 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 GlslLibRoutine(source, ["coordinates.getOutputCoords"]);
        }
        /**
         * Constructing snippets for unpacked output coordinates of samplers
         */
        getUnpackedSamplerAtOutputCoords(funcName, inputLayout, outputLayout, name2) {
          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 = generateShaderFuncNameFromInputSamplerName(name2);
          if (inRank === outRank && ArrayUtil.arraysEqual(inTexShape, outTexShape)) {
            const source2 = `
          float ${funcName}() {
            return sampleTexture(${name2}, TexCoords);
          }
        `;
            return new GlslLibRoutine(source2, ["coordinates.sampleTexture"]);
          }
          const type = getCoordsDataType(outRank);
          const broadcastDims = BroadcastUtil.getBroadcastDims(inShape, outShape);
          const rankDiff = outRank - inRank;
          let coordsSnippet;
          const fields = 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 GlslLibRoutine(source, ["coordinates.getOutputCoords"]);
        }
        /**
         * Constructing snippets for packed operations.
         */
        getPackedSamplerFromInput(funcName, name2, inputLayout) {
          switch (inputLayout.unpackedShape.length) {
            case 0:
              return this.getPackedSamplerScalar(funcName, name2);
            case 1:
              return this.getPackedSampler1D(funcName, name2, inputLayout);
            case 2:
              return this.getPackedSampler2D(funcName, name2, inputLayout);
            case 3:
              return this.getPackedSampler3D(funcName, name2, inputLayout);
            default:
              return this.getPackedSamplerND(funcName, name2, inputLayout);
          }
        }
        /**
         * Constructing snippets for unpacked operations.
         */
        getUnpackedSamplerFromInput(funcName, name2, inputLayout) {
          const shape2 = inputLayout.unpackedShape;
          switch (shape2.length) {
            case 0:
              return this.getUnpackedSamplerScalar(funcName, name2, inputLayout);
            case 1:
              return this.getUnpackedSampler1D(funcName, name2, inputLayout);
            case 2:
              return this.getUnpackedSampler2D(funcName, name2, inputLayout);
            case 3:
              return this.getUnpackedSampler3D(funcName, name2, inputLayout);
            case 4:
              return this.getUnpackedSampler4D(funcName, name2, inputLayout);
            case 5:
              return this.getUnpackedSampler5D(funcName, name2, inputLayout);
            case 6:
              return this.getUnpackedSampler6D(funcName, name2, inputLayout);
            default:
              throw new Error(`Unsupported dimension ${shape2.length}-D`);
          }
        }
        /**
         * Packed scalar snippet.
         */
        getPackedSamplerScalar(funcName, name2) {
          const glsl = getGlsl(this.context.glContext.version);
          const source = `
          vec4 ${funcName}() {
            return ${glsl.texture2D}(${name2}, halfCR);
          }
        `;
          return new GlslLibRoutine(source);
        }
        /**
         * Packed 1D snippet.
         */
        getPackedSampler1D(funcName, name2, inputLayout) {
          const texShape = [inputLayout.width, inputLayout.height];
          const packedTexShape = [texShape[1], texShape[0]];
          const glsl = getGlsl(this.context.glContext.version);
          const packedSampler = `vec4 ${funcName}(int index) {
      vec2 uv = packedUVfrom1D(
      ${packedTexShape[0]}, ${packedTexShape[1]}, index);
      return ${glsl.texture2D}(${name2}, uv);
    }`;
          const source = packedSampler;
          return new GlslLibRoutine(source, ["coordinates.packedUVfrom1D"]);
        }
        /**
         * Packed 2D snippet.
         */
        getPackedSampler2D(funcName, name2, inputLayout) {
          const shape2 = inputLayout.unpackedShape;
          const texShape = [inputLayout.width, inputLayout.height];
          const glsl = getGlsl(this.context.glContext.version);
          const texNumR = texShape[0];
          const texNumC = texShape[1];
          if (texShape != null && ArrayUtil.arraysEqual(shape2, texShape)) {
            const packedSampler2 = `vec4 ${funcName}(int row, int col) {
        vec2 uv = (vec2(col, row) + halfCR) / vec2(${texNumC}.0, ${texNumR}.0);
        return ${glsl.texture2D}(${name2}, uv);
      }`;
            return new GlslLibRoutine(packedSampler2);
          }
          const packedTexShape = texShape;
          const valuesPerRow = Math.ceil(shape2[1] / 2);
          const packedSampler = `vec4 ${funcName}(int row, int col) {
      vec2 uv = packedUVfrom2D(${packedTexShape[1]}, ${packedTexShape[0]}, ${valuesPerRow}, row, col);
      return ${glsl.texture2D}(${name2}, uv);
    }`;
          const source = packedSampler;
          return new GlslLibRoutine(source, ["coordinates.packedUVfrom2D"]);
        }
        /**
         * Packed 3D snippet.
         */
        getPackedSampler3D(funcName, name2, inputLayout) {
          const shape2 = inputLayout.unpackedShape;
          const texShape = [inputLayout.width, inputLayout.height];
          const packedTexShape = [texShape[0], texShape[1]];
          const glsl = getGlsl(this.context.glContext.version);
          if (shape2[0] === 1) {
            const squeezedShape = shape2.slice(1);
            const keptDims = [1, 2];
            const newInputShape = squeezeInputShape(shape2, squeezedShape);
            const params = ["b", "row", "col"];
            const newInputLayout = JSON.parse(JSON.stringify(inputLayout));
            newInputLayout.unpackedShape = newInputShape;
            const samplerRoutine = this.getPackedSamplerFromInput(funcName, name2, newInputLayout);
            const packedSampler2 = `${samplerRoutine.routineBody}
      vec4 ${funcName}(int b, int row, int col) {
        return ${funcName}(${getSqueezedParams(params, keptDims)});
      } `;
            const source2 = packedSampler2;
            return new GlslLibRoutine(source2, samplerRoutine.dependencies);
          }
          const texNumR = packedTexShape[0];
          const texNumC = packedTexShape[1];
          const valuesPerRow = Math.ceil(shape2[2] / 2);
          const texelsInBatch = valuesPerRow * Math.ceil(shape2[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}(${name2}, uv);}`;
          const source = packedSampler;
          return new GlslLibRoutine(source, ["coordinates.packedUVfrom3D"]);
        }
        /*
         * Packed ND snippet.
         */
        getPackedSamplerND(funcName, name2, inputLayout) {
          const shape2 = inputLayout.unpackedShape;
          const rank = shape2.length;
          const texShape = [inputLayout.width, inputLayout.height];
          const glsl = getGlsl(this.context.glContext.version);
          const packedTexShape = [texShape[0], texShape[1]];
          const texNumR = packedTexShape[1];
          const texNumC = packedTexShape[0];
          const valuesPerRow = Math.ceil(shape2[rank - 1] / 2);
          let texelsInBatch = valuesPerRow * Math.ceil(shape2[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 *= shape2[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}(${name2}, uv);
    }`;
          const source = packedSampler;
          return new GlslLibRoutine(source);
        }
        /**
         * Unpacked scalar snippet.
         */
        getUnpackedSamplerScalar(funcName, name2, inputLayout) {
          const [texNumR, texNumC] = [inputLayout.width, inputLayout.height];
          if (texNumR === 1 && texNumC === 1) {
            const source2 = `
          float ${funcName}() {
            return sampleTexture(${name2}, halfCR);
          }
        `;
            return new GlslLibRoutine(source2, ["coordinates.sampleTexture"]);
          }
          const source = `
        float ${funcName}() {
          int offset_${name2} = coordsToOffset(TexCoords, ${texNumR}, ${texNumC});
          vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, offset_${name2});
          return sampleTexture(${name2}, uv);
        }
      `;
          return new GlslLibRoutine(
            source,
            ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]
          );
        }
        /**
         * Unpacked 1D snippet.
         */
        getUnpackedSampler1D(funcName, name2, inputLayout) {
          const tNumR = inputLayout.width;
          const tNumC = inputLayout.height;
          if (tNumC === 1 && tNumR === 1) {
            const source2 = `
        float ${funcName}(int index) {
          return sampleTexture(${name2}, halfCR);
        }
      `;
            return new GlslLibRoutine(source2, ["coordinates.sampleTexture"]);
          }
          if (tNumC === 1) {
            const source2 = `
          float ${funcName}(int index) {
            vec2 uv = vec2((float(index) + 0.5) / ${tNumR}.0, 0.5);
            return sampleTexture(${name2}, uv);
          }
        `;
            return new GlslLibRoutine(source2, ["coordinates.sampleTexture"]);
          }
          if (tNumR === 1) {
            const source2 = `
          float ${funcName}(int index) {
            vec2 uv = vec2(0.5, (float(index) + 0.5) / ${tNumC}.0);
            return sampleTexture(${name2}, uv);
          }
        `;
            return new GlslLibRoutine(source2, ["coordinates.sampleTexture"]);
          }
          const source = `
        float ${funcName}(int index) {
          vec2 uv = uvFromFlat(${tNumR}, ${tNumC}, index);
          return sampleTexture(${name2}, uv);
        }
      `;
          return new GlslLibRoutine(source, ["coordinates.uvFromFlat", "coordinates.sampleTexture"]);
        }
        /**
         * Unpacked 2D snippet.
         */
        getUnpackedSampler2D(funcName, name2, inputLayout) {
          const shape2 = inputLayout.unpackedShape;
          const texShape = [inputLayout.height, inputLayout.width];
          if (texShape != null && ArrayUtil.arraysEqual(shape2, texShape)) {
            const texNumR2 = texShape[1];
            const texNumC2 = texShape[0];
            const source2 = `
          float ${funcName}(int row, int col) {
            vec2 uv = (vec2(row, col) + halfCR) / vec2(${texNumR2}.0, ${texNumC2}.0);
            return sampleTexture(${name2}, uv);
          }
        `;
            return new GlslLibRoutine(source2, ["coordinates.sampleTexture"]);
          }
          const { newShape, keptDims } = squeezeShape(shape2);
          const squeezedShape = newShape;
          if (squeezedShape.length < shape2.length) {
            const newInputShape = squeezeInputShape(shape2, squeezedShape);
            const newInputLayout = JSON.parse(JSON.stringify(inputLayout));
            newInputLayout.unpackedShape = newInputShape;
            const params = ["col", "row"];
            const source2 = `
          ${this.getUnpackedSamplerFromInput(funcName, name2, newInputLayout).routineBody}
          float ${funcName}(int row, int col) {
            return ${funcName}(${getSqueezedParams(params, keptDims)});
          }
        `;
            return new GlslLibRoutine(source2, ["coordinates.sampleTexture"]);
          }
          const texNumR = texShape[1];
          const texNumC = texShape[0];
          if (texNumC === 1) {
            const source2 = `
          float ${funcName}(int row, int col) {
            int offset_${name2} = coordsToOffset(TexCoords, ${texNumR}, ${texNumC});
            float index = dot(vec3(row, col, offset_${name2}), vec3(${shape2[1]}, 1, 1));
            vec2 uv = vec2(0.5, (index + 0.5) / ${texNumR}.0);
            return sampleTexture(${name2}, uv);
          }
        `;
            return new GlslLibRoutine(source2, ["coordinates.sampleTexture", "coordinates.coordsToOffset"]);
          }
          if (texNumR === 1) {
            const source2 = `
          float ${funcName}(int row, int col) {
            int offset_${name2} = coordsToOffset(TexCoords, ${texNumR}, ${texNumC});
            float index = dot(vec3(row, col, offset_${name2}), vec3(${shape2[1]}, 1, 1));
            vec2 uv = vec2((index + 0.5) / ${texNumC}.0, 0.5);
            return sampleTexture(${name2}, uv);
          }
        `;
            return new GlslLibRoutine(source2, ["coordinates.sampleTexture", "coordinates.coordsToOffset"]);
          }
          const source = `
        float ${funcName}(int row, int col) {
          int index = col * ${shape2[1]} + row;
          vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
          return sampleTexture(${name2}, uv);
        }
      `;
          return new GlslLibRoutine(
            source,
            ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]
          );
        }
        /**
         * Unpacked 3D snippet.
         */
        getUnpackedSampler3D(funcName, name2, inputLayout) {
          const shape2 = inputLayout.unpackedShape;
          const stride0 = shape2[1] * shape2[2];
          const stride1 = shape2[2];
          const { newShape, keptDims } = squeezeShape(shape2);
          const squeezedShape = newShape;
          if (squeezedShape.length < shape2.length) {
            const newInputShape = squeezeInputShape(shape2, squeezedShape);
            const params = ["batch", "col", "row"];
            const newInputLayout = JSON.parse(JSON.stringify(inputLayout));
            newInputLayout.unpackedShape = newInputShape;
            const routine = this.getUnpackedSamplerFromInput(funcName, name2, newInputLayout);
            const revDims = keptDims.reverse();
            const source2 = `
          ${routine.routineBody}
          float ${funcName}(int batch, int row, int col) {
            return ${funcName}(${getSqueezedParams(params, revDims)});
          }
        `;
            return new GlslLibRoutine(source2, 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(${name2}, uv);
          }
      `;
          return new GlslLibRoutine(
            source,
            ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]
          );
        }
        /**
         * Unpacked 4D snippet.
         */
        getUnpackedSampler4D(funcName, name2, inputLayout) {
          const shape2 = inputLayout.unpackedShape;
          const stride2 = shape2[3];
          const stride1 = shape2[2] * stride2;
          const stride0 = shape2[1] * stride1;
          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(${name2}, uv);
        }
      `;
          return new GlslLibRoutine(source, ["coordinates.uvFromFlat", "coordinates.sampleTexture"]);
        }
        /**
         * Unpacked 5D snippet.
         */
        getUnpackedSampler5D(funcName, name2, inputLayout) {
          const shape2 = inputLayout.unpackedShape;
          const stride3 = shape2[4];
          const stride2 = shape2[3] * stride3;
          const stride1 = shape2[2] * stride2;
          const stride0 = shape2[1] * stride1;
          const { newShape, keptDims } = squeezeShape(shape2);
          if (newShape.length < shape2.length) {
            const newInputShape = squeezeInputShape(shape2, newShape);
            const params = ["row", "col", "depth", "depth2", "depth3"];
            const newInputLayout = JSON.parse(JSON.stringify(inputLayout));
            newInputLayout.unpackedShape = newInputShape;
            const source2 = `
          ${this.getUnpackedSamplerFromInput(funcName, name2, newInputLayout).routineBody}
          float ${funcName}(int row, int col, int depth, int depth2, int depth3) {
            return ${funcName}(${getSqueezedParams(params, keptDims)});
          }
        `;
            return new GlslLibRoutine(source2, ["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(${name2}, uv);
        }
      `;
          return new GlslLibRoutine(source, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]);
        }
        /**
         * Unpacked 6D snippet.
         */
        getUnpackedSampler6D(funcName, name2, inputLayout) {
          const shape2 = inputLayout.unpackedShape;
          const stride4 = shape2[5];
          const stride3 = shape2[4] * stride4;
          const stride2 = shape2[3] * stride3;
          const stride1 = shape2[2] * stride2;
          const stride0 = shape2[1] * stride1;
          const { newShape, keptDims } = squeezeShape(shape2);
          if (newShape.length < shape2.length) {
            const newInputShape = squeezeInputShape(shape2, newShape);
            const params = ["row", "col", "depth", "depth2", "depth3", "depth4"];
            const newInputLayout = JSON.parse(JSON.stringify(inputLayout));
            newInputLayout.unpackedShape = newInputShape;
            const source2 = `
            ${this.getUnpackedSamplerFromInput(funcName, name2, newInputLayout).routineBody}
            float ${funcName}(int row, int col, int depth,
              int depth2, int depth3, int depth4) {
              return ${funcName}(${getSqueezedParams(params, keptDims)});
            }
          `;
            return new GlslLibRoutine(source2, ["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(${name2}, uv);
          }
        `;
          return new 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 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((name2, i) => {
            const layout = this.context.inputTextureLayouts[i];
            const shape2 = layout.unpackedShape.length > 0 ? layout.unpackedShape : layout.shape;
            const rank = shape2.length;
            let funcName = `_${name2}`;
            result[funcName] = new GlslLibRoutine(
              this.getValueFromSingle(name2, rank, layout.width, layout.height, false),
              [`shapeUtils.indicesToOffset${funcName}`, "coordinates.offsetToCoords", "fragcolor.getColorAsFloat"]
            );
            funcName = funcName + "_T";
            result[funcName] = new GlslLibRoutine(
              this.getValueFromSingle(name2, 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, transpose2) {
          let name2 = `_${varName}`;
          if (transpose2) {
            name2 = name2 + "_T";
          }
          const glsl = getGlsl(this.context.glContext.version);
          return `
        float ${name2}(int m[${rank}]) {
          int offset = indicesToOffset${name2}(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, transpose2) {
          let name2 = `_${varName}_Pack`;
          if (transpose2) {
            name2 = name2 + "_T";
          }
          const glsl = getGlsl(this.context.glContext.version);
          return `
        vec4 ${name2}(int m[${rank}]) {
          int offset = indicesToOffset_${varName}(m);
          vec2 coords = offsetToCoords(offset, ${width}, ${height});
          return ${glsl.texture2D}(${varName}, coords);
        }
        `;
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/glsl-encoding-lib.ts
  var EncodingGlslLib;
  var init_glsl_encoding_lib = __esm({
    "web/lib/onnxjs/backends/webgl/glsl-encoding-lib.ts"() {
      "use strict";
      init_glsl_definitions();
      EncodingGlslLib = class _EncodingGlslLib extends GlslLib {
        constructor(context) {
          super(context);
        }
        getFunctions() {
          return { ...this.encodeFloat32(), ...this.decodeFloat32() };
        }
        getCustomTypes() {
          return {};
        }
        encodeFloat32() {
          return {
            encode: new GlslLibRoutine(`highp vec4 encode(highp float f) {
        return vec4(f, 0.0, 0.0, 0.0);
      }
        `)
          };
        }
        decodeFloat32() {
          return {
            decode: new 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 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 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] = 3735928559;
          if (c[0] === 239) {
            return true;
          }
          if (c[0] === 222) {
            return false;
          }
          throw new Error("unknown endianness");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/glsl-fragcolor-lib.ts
  var FragColorGlslLib;
  var init_glsl_fragcolor_lib = __esm({
    "web/lib/onnxjs/backends/webgl/glsl-fragcolor-lib.ts"() {
      "use strict";
      init_glsl_definitions();
      init_glsl_source();
      FragColorGlslLib = class extends GlslLib {
        constructor(context) {
          super(context);
        }
        getFunctions() {
          return { ...this.setFragColor(), ...this.getColorAsFloat() };
        }
        getCustomTypes() {
          return {};
        }
        setFragColor() {
          const glsl = getGlsl(this.context.glContext.version);
          return {
            setFragColor: new GlslLibRoutine(
              `
        void setFragColor(float value) {
            ${glsl.output} = encode(value);
        }
        `,
              ["encoding.encode"]
            )
          };
        }
        getColorAsFloat() {
          return {
            getColorAsFloat: new GlslLibRoutine(
              `
        float getColorAsFloat(vec4 color) {
            return decode(color);
        }
        `,
              ["encoding.decode"]
            )
          };
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/glsl-shape-utils-lib.ts
  var ShapeUtilsGlslLib;
  var init_glsl_shape_utils_lib = __esm({
    "web/lib/onnxjs/backends/webgl/glsl-shape-utils-lib.ts"() {
      "use strict";
      init_glsl_definitions();
      ShapeUtilsGlslLib = class _ShapeUtilsGlslLib extends GlslLib {
        constructor(context) {
          super(context);
        }
        getFunctions() {
          return {
            ...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((name2, i) => {
            const shape2 = this.context.inputTextureLayouts[i].unpackedShape;
            if (shape2.length <= outputRank) {
              const rank = shape2.length;
              const dimOffset = outputRank - rank;
              const funcName = `bcastIndices_${name2}`;
              let block = "";
              for (let i2 = 0; i2 < rank; ++i2) {
                block += `
          realIndices[${i2}] = int( mod(float(bcastedIndices[${dimOffset + i2}]), ${shape2[i2]}.0) );
          `;
              }
              const body = `
        void ${funcName} (int bcastedIndices[${outputRank}], out int realIndices[${rank}]) {
          ${block}
        }
        `;
              result[funcName] = new GlslLibRoutine(body);
            }
          });
          return result;
        }
        bcastMatmulIndex() {
          const outputRank = this.context.outputTextureLayout.shape.length;
          const result = {};
          this.context.programInfo.inputNames.forEach((name2, i) => {
            const shape2 = this.context.inputTextureLayouts[i].shape;
            if (!(shape2.length < 2 || shape2.length > outputRank)) {
              const rank = shape2.length;
              const dimOffset = outputRank - rank;
              const funcName = `bcastMatmulIndices_${name2}`;
              let block = "";
              for (let i2 = 0; i2 < rank - 2; ++i2) {
                block += `
          realIndices[${i2}] = int( mod(float(bcastedIndices[${dimOffset + i2}]), ${shape2[i2]}.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 GlslLibRoutine(body);
            }
          });
          return result;
        }
        indicesToOffset() {
          const result = {};
          this.context.programInfo.inputNames.forEach((name2, i) => {
            const shape2 = this.context.inputTextureLayouts[i].shape;
            const strides = this.context.inputTextureLayouts[i].strides;
            const rank = shape2.length;
            let funcName = `indicesToOffset_${name2}`;
            result[funcName] = new GlslLibRoutine(_ShapeUtilsGlslLib.indexToOffsetSingle(funcName, rank, strides));
            funcName = `indicesToOffset_${name2}_T`;
            result[funcName] = new GlslLibRoutine(_ShapeUtilsGlslLib.indexToOffsetSingle(funcName, rank, strides.slice().reverse()));
          });
          return result;
        }
        static indexToOffsetSingle(name2, rank, strides) {
          let block = "";
          for (let i = rank - 1; i >= 0; --i) {
            block += `
        offset += indices[${i}] * ${strides[i]};
        `;
          }
          return `
      int ${name2}(int indices[${rank}]) {
        int offset = 0;
        ${block}
        return offset;
      }
      `;
        }
        offsetToIndices() {
          const result = {};
          this.context.programInfo.inputNames.forEach((name2, i) => {
            const shape2 = this.context.inputTextureLayouts[i].shape;
            const strides = this.context.inputTextureLayouts[i].strides;
            const rank = shape2.length;
            let funcName = `offsetToIndices_${name2}`;
            result[funcName] = new GlslLibRoutine(_ShapeUtilsGlslLib.offsetToIndicesSingle(funcName, rank, strides));
            funcName = `offsetToIndices_${name2}_T`;
            result[funcName] = new GlslLibRoutine(_ShapeUtilsGlslLib.offsetToIndicesSingle(funcName, rank, strides.slice().reverse()));
          });
          return result;
        }
        static offsetToIndicesSingle(name2, 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 ${name2}(int offset, out int indices[${rank}]) {
        ${stridesBlock.join("")}
      }
      `;
        }
        incrementIndices() {
          const result = {};
          this.context.programInfo.inputNames.forEach((name2, i) => {
            const shape2 = this.context.inputTextureLayouts[i].shape;
            const rank = shape2.length;
            const funcName = `incrementIndices_${name2}`;
            let shapeInit = "";
            for (let i2 = 0; i2 < rank; ++i2) {
              shapeInit += `
        shape[${i2}] = ${shape2[i2]};`;
            }
            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 GlslLibRoutine(body);
          });
          return result;
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/glsl-vec-lib.ts
  var VecGlslLib;
  var init_glsl_vec_lib = __esm({
    "web/lib/onnxjs/backends/webgl/glsl-vec-lib.ts"() {
      "use strict";
      init_glsl_definitions();
      VecGlslLib = class extends GlslLib {
        constructor(context) {
          super(context);
        }
        getCustomTypes() {
          return {};
        }
        getFunctions() {
          return { ...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 name2 in nameOp) {
            const fname = `${name2}Vec`;
            let assignmentBlock = "";
            for (let i = 0; i < rank; ++i) {
              assignmentBlock += `
          dest[${i}] ${nameOp[name2]} src[${i}];
          `;
            }
            const body = `
        void ${fname}(int src[${rank}], out int dest[${rank}]) {
          ${assignmentBlock}
        }
        `;
            result[fname] = new 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 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 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 GlslLibRoutine(body) };
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/glsl-registered-libs.ts
  var glslRegistry;
  var init_glsl_registered_libs = __esm({
    "web/lib/onnxjs/backends/webgl/glsl-registered-libs.ts"() {
      "use strict";
      init_glsl_coordinate_lib();
      init_glsl_encoding_lib();
      init_glsl_fragcolor_lib();
      init_glsl_shape_utils_lib();
      init_glsl_vec_lib();
      glslRegistry = {
        "encoding": EncodingGlslLib,
        "fragcolor": FragColorGlslLib,
        "vec": VecGlslLib,
        "shapeUtils": ShapeUtilsGlslLib,
        "coordinates": CoordsGlslLib
        //  'arrays': ArrayGlslSLib
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/glsl-preprocessor.ts
  var GlslPreprocessor;
  var init_glsl_preprocessor = __esm({
    "web/lib/onnxjs/backends/webgl/glsl-preprocessor.ts"() {
      "use strict";
      init_glsl_definitions();
      init_glsl_function_inliner();
      init_glsl_registered_libs();
      init_glsl_source();
      GlslPreprocessor = class {
        constructor(glContext, programInfo, inputTextureLayouts, outputTextureLayout) {
          this.libs = {};
          this.glslLibRoutineDependencyGraph = {};
          this.context = new GlslContext(glContext, programInfo, inputTextureLayouts, outputTextureLayout);
          Object.keys(glslRegistry).forEach((name2) => {
            const lib = new glslRegistry[name2](this.context);
            this.libs[name2] = lib;
          });
          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 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 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;
          if (!this.context.programInfo.hasMain) {
            source = `${source}
      ${getDefaultFragShaderMain(this.context.glContext.version, this.context.outputTextureLayout.shape.length)}`;
          }
          source = replaceInlines(source);
          return `${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 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");
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/program-manager.ts
  var ProgramManager;
  var init_program_manager = __esm({
    "web/lib/onnxjs/backends/webgl/program-manager.ts"() {
      "use strict";
      init_esm();
      init_instrument();
      init_glsl_preprocessor();
      init_glsl_source();
      ProgramManager = class {
        constructor(profiler, glContext, textureLayoutStrategy) {
          this.profiler = profiler;
          this.glContext = glContext;
          this.textureLayoutStrategy = textureLayoutStrategy;
          this.repo = /* @__PURE__ */ new Map();
          this.attributesBound = false;
        }
        getArtifact(key) {
          return this.repo.get(key);
        }
        setArtifact(key, artifact) {
          this.repo.set(key, artifact);
        }
        run(buildArtifact, inputs, output) {
          this.profiler.event("op", `ProgramManager.run ${buildArtifact.programInfo.name ?? "unknown kernel"}`, () => {
            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, buildArtifact.programInfo.variables ?? [], inputs);
            } catch (err) {
              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 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) {
            Logger.verbose("ProrgramManager", "Compiling and caching Vertex shader for the first time");
            const vertexShaderScript = getVertexShaderSource(this.glContext.version);
            this.vertexShader = this.glContext.compileShader(vertexShaderScript, this.glContext.gl.VERTEX_SHADER);
          }
          if (env2.debug) {
            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;
          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) {
          const gl = this.glContext.gl;
          let texturePosition = 0;
          for (const { name: name2, type, location, arrayLength } of uniformLocations) {
            const value = variables.find((v) => v.name === name2)?.data;
            if (type !== "sampler2D" && !value) {
              throw new Error(`variable '${name2}' 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({ ...variable, location: this.getUniformLocation(program, variable.name) });
            }
          }
          return uniformLocations;
        }
        getUniformLocation(program, name2) {
          const gl = this.glContext.gl;
          const reference = gl.getUniformLocation(program, name2);
          if (reference === null) {
            throw new Error(`Uniform ${name2} not found.`);
          }
          return reference;
        }
        getAttribLocation(program, name2) {
          const gl = this.glContext.gl;
          const attributeLocation = gl.getAttribLocation(program, name2);
          return attributeLocation;
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/texture-manager.ts
  var TextureManager;
  var init_texture_manager = __esm({
    "web/lib/onnxjs/backends/webgl/texture-manager.ts"() {
      "use strict";
      init_instrument();
      init_texture_data_encoder();
      TextureManager = class {
        constructor(glContext, layoutStrategy, profiler, config) {
          this.glContext = glContext;
          this.layoutStrategy = layoutStrategy;
          this.profiler = profiler;
          this.config = config;
          this.pendingRead = /* @__PURE__ */ new Map();
          if (config.reuseTextures) {
            this.inUseTextures = /* @__PURE__ */ new Map();
            this.idleTextures = /* @__PURE__ */ new Map();
            this.textureLookup = /* @__PURE__ */ 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 /* 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 texture2 = idleTextures.pop();
              inUseTextures.push(texture2);
              if (usage === 1 /* UploadOnly */) {
                this.glContext.updateTexture(texture2, width, height, encoder, this.toTextureData(dataType, data));
              }
              return texture2;
            }
          }
          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?.push(resolve));
          }
          return this.profiler.event("backend", "TextureManager.readTextureAsync", async () => {
            this.pendingRead.set(dataId, []);
            const dataSize = td.shape.reduce((a, b) => a * b) * channels;
            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?.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) {
            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 void 0;
          }
          return data instanceof Float32Array ? data : new Float32Array(data);
        }
        toEncoderType(_dataType) {
          return "float";
        }
        clearActiveTextures() {
          this.glContext.clearActiveTextures();
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/session-handler.ts
  var WebGLSessionHandler;
  var init_session_handler = __esm({
    "web/lib/onnxjs/backends/webgl/session-handler.ts"() {
      "use strict";
      init_instrument();
      init_opset();
      init_inference_handler();
      init_op_resolve_rules();
      init_program_manager();
      init_texture_layout_strategy();
      init_texture_manager();
      WebGLSessionHandler = class {
        constructor(backend2, context) {
          this.backend = backend2;
          this.context = context;
          this.layoutStrategy = new PreferLogicalStrategy(backend2.glContext.maxTextureSize);
          this.programManager = new ProgramManager(this.context.profiler, backend2.glContext, this.layoutStrategy);
          this.textureManager = new TextureManager(
            backend2.glContext,
            this.layoutStrategy,
            this.context.profiler,
            { reuseTextures: backend2.textureCacheMode === "full" }
          );
          this.packedTextureDataCache = /* @__PURE__ */ new Map();
          this.unpackedTextureDataCache = /* @__PURE__ */ new Map();
          this.pack = backend2.pack;
          this.pack2unpackMap = /* @__PURE__ */ new Map();
          this.unpack2packMap = /* @__PURE__ */ new Map();
        }
        createInferenceHandler() {
          return new 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) {
          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 = /* @__PURE__ */ new Map();
          this.unpackedTextureDataCache.forEach((td) => this.textureManager.releaseTexture(td, true));
          this.unpackedTextureDataCache = /* @__PURE__ */ new Map();
        }
        resolve(node, opsets, graph) {
          const op = resolveOperator(node, opsets, WEBGL_OP_RESOLVE_RULES);
          return { impl: op.opImpl, context: op.opInit ? op.opInit(node, graph) : node };
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/webgl-context.ts
  function linearSearchLastTrue(arr) {
    let i = 0;
    for (; i < arr.length; ++i) {
      const isDone = arr[i]();
      if (!isDone) {
        break;
      }
    }
    return i - 1;
  }
  var WebGLContext;
  var init_webgl_context = __esm({
    "web/lib/onnxjs/backends/webgl/webgl-context.ts"() {
      "use strict";
      init_esm();
      init_texture_data_encoder();
      init_texture_data_encoder();
      init_utils();
      WebGLContext = class {
        constructor(gl, version3) {
          this.frameBufferBound = false;
          this.itemsToPoll = [];
          this.gl = gl;
          this.version = version3;
          this.getExtensions();
          this.vertexbuffer = this.createVertexbuffer();
          this.framebuffer = this.createFramebuffer();
          this.queryVitalParameters();
        }
        allocateTexture(width, height, encoder, data) {
          const gl = this.gl;
          const texture = gl.createTexture();
          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;
          gl.bindTexture(gl.TEXTURE_2D, texture);
          gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
          gl.framebufferTexture2D(
            gl.FRAMEBUFFER,
            gl.COLOR_ATTACHMENT0,
            gl.TEXTURE_2D,
            texture,
            0
          );
          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);
          gl.bindTexture(gl.TEXTURE_2D, texture);
          gl.framebufferTexture2D(
            gl.FRAMEBUFFER,
            gl.COLOR_ATTACHMENT0,
            gl.TEXTURE_2D,
            texture,
            0
          );
          gl.readPixels(0, 0, width, height, gl.RGBA, encoder.textureType, buffer);
          this.checkError();
          return encoder.decode(buffer, dataSize);
        }
        isFramebufferReady() {
          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();
          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 (env2.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 /* Default */) {
          if (this.version === 2) {
            return new RedFloat32DataEncoder(this.gl, channels);
          }
          switch (dataType) {
            case "float":
              if (usage === 1 /* UploadOnly */ || this.isRenderFloat32Supported) {
                return new RGBAFloatDataEncoder(this.gl, channels);
              } else {
                return new RGBAFloatDataEncoder(
                  this.gl,
                  channels,
                  this.textureHalfFloatExtension.HALF_FLOAT_OES
                );
              }
            case "int":
              throw new Error("not implemented");
            case "byte":
              return new 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() {
          return new Float32Array([
            -1,
            1,
            0,
            0,
            1,
            // upper left
            -1,
            -1,
            0,
            0,
            0,
            // lower left
            1,
            1,
            0,
            1,
            1,
            // upper right
            1,
            -1,
            0,
            1,
            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.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
          this.maxTextureImageUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
          if (this.version === 2) {
          }
        }
        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() {
          const gl = this.gl;
          const texture = gl.createTexture();
          gl.bindTexture(gl.TEXTURE_2D, texture);
          const internalFormat = this.version === 2 ? gl.RGBA32F : gl.RGBA;
          gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, 1, 1, 0, gl.RGBA, gl.FLOAT, null);
          const frameBuffer = gl.createFramebuffer();
          gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
          gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
          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() {
          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);
            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 {
            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 {
            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 {
            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 {
            throw new Error("WebGL1 profiling currently not supported");
          }
          return timeElapsed / 1e6;
        }
        async waitForQueryAndGetTime(query) {
          await 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() {
          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) {
            return;
          }
          await repeatedTry(() => {
            this.pollItems();
            return this.itemsToPoll.length === 0;
          });
        }
      };
    }
  });

  // web/lib/onnxjs/backends/webgl/webgl-context-factory.ts
  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;
    }
    if (!context) {
      try {
        const offscreenCanvas = createOffscreenCanvas();
        context = createNewWebGLContext(offscreenCanvas, contextId);
      } catch (e) {
        const canvas = createCanvas();
        context = createNewWebGLContext(canvas, 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;
  }
  function createNewWebGLContext(canvas, contextId) {
    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 WebGLContext(gl, 2);
        } catch (err) {
          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 WebGLContext(gl, 1);
        } catch (err) {
          Logger.warning(
            "GlContextFactory",
            `failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${err}`
          );
        }
      }
    }
    throw new Error("WebGL is not supported");
  }
  function createCanvas() {
    if (typeof document === "undefined") {
      throw new TypeError("failed to create canvas: document is not supported");
    }
    const canvas = document.createElement("canvas");
    canvas.width = 1;
    canvas.height = 1;
    return canvas;
  }
  function createOffscreenCanvas() {
    if (typeof OffscreenCanvas === "undefined") {
      throw new TypeError("failed to create offscreen canvas: OffscreenCanvas is not supported");
    }
    return new OffscreenCanvas(1, 1);
  }
  var cache;
  var init_webgl_context_factory = __esm({
    "web/lib/onnxjs/backends/webgl/webgl-context-factory.ts"() {
      "use strict";
      init_instrument();
      init_webgl_context();
      cache = {};
    }
  });

  // web/lib/onnxjs/backends/backend-webgl.ts
  var WebGLBackend;
  var init_backend_webgl = __esm({
    "web/lib/onnxjs/backends/backend-webgl.ts"() {
      "use strict";
      init_esm();
      init_instrument();
      init_session_handler();
      init_webgl_context_factory();
      WebGLBackend = class {
        get contextId() {
          return env2.webgl.contextId;
        }
        set contextId(value) {
          env2.webgl.contextId = value;
        }
        get matmulMaxBatchSize() {
          return env2.webgl.matmulMaxBatchSize;
        }
        set matmulMaxBatchSize(value) {
          env2.webgl.matmulMaxBatchSize = value;
        }
        get textureCacheMode() {
          return env2.webgl.textureCacheMode;
        }
        set textureCacheMode(value) {
          env2.webgl.textureCacheMode = value;
        }
        get pack() {
          return env2.webgl.pack;
        }
        set pack(value) {
          env2.webgl.pack = value;
        }
        get async() {
          return env2.webgl.async;
        }
        set async(value) {
          env2.webgl.async = value;
        }
        initialize() {
          try {
            this.glContext = 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;
            }
            Logger.setWithEnv(env2);
            if (!env2.webgl.context) {
              Object.defineProperty(env2.webgl, "context", { value: this.glContext.gl });
            }
            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) {
            Logger.warning("WebGLBackend", `Unable to initialize WebGLBackend. ${e}`);
            return false;
          }
        }
        createSessionHandler(context) {
          return new WebGLSessionHandler(this, context);
        }
        dispose() {
          this.glContext.dispose();
        }
      };
    }
  });

  // web/lib/onnxjs/backend.ts
  async function resolveBackend(hint) {
    if (!hint) {
      return resolveBackend(["webgl"]);
    } else {
      const hints = typeof hint === "string" ? [hint] : hint;
      for (const backendHint of hints) {
        const cache2 = backendsCache.get(backendHint);
        if (cache2) {
          return cache2;
        }
        const backend2 = await tryLoadBackend(backendHint);
        if (backend2) {
          return backend2;
        }
      }
    }
    throw new Error("no available backend to use");
  }
  async function tryLoadBackend(backendHint) {
    const backendObj = backend;
    if (typeof backendObj[backendHint] !== "undefined" && isBackend(backendObj[backendHint])) {
      const backend2 = backendObj[backendHint];
      let init = backend2.initialize();
      if (typeof init === "object" && "then" in init) {
        init = await init;
      }
      if (init) {
        backendsCache.set(backendHint, backend2);
        return backend2;
      }
    }
    return void 0;
  }
  function isBackend(obj) {
    const o = obj;
    if ("initialize" in o && typeof o.initialize === "function" && // initialize()
    "createSessionHandler" in o && typeof o.createSessionHandler === "function" && // createSessionHandler()
    "dispose" in o && typeof o.dispose === "function") {
      return true;
    }
    return false;
  }
  var backendsCache, backend;
  var init_backend2 = __esm({
    "web/lib/onnxjs/backend.ts"() {
      "use strict";
      init_backend_webgl();
      backendsCache = /* @__PURE__ */ new Map();
      backend = {
        webgl: new WebGLBackend()
      };
    }
  });

  // web/lib/onnxjs/execution-plan.ts
  var KernelOp, ExecutionPlan;
  var init_execution_plan = __esm({
    "web/lib/onnxjs/execution-plan.ts"() {
      "use strict";
      init_instrument();
      KernelOp = class {
        constructor(op, node) {
          this.op = op;
          this.node = node;
        }
      };
      ExecutionPlan = class {
        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();
            this._starter = [];
            this._ops.forEach((op, i) => {
              let resolved = true;
              for (const input of op.node.inputs) {
                if (!this._values[input] && this.graph.getInputIndices().indexOf(input) === -1) {
                  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 () => {
            this.reset();
            const inferenceHandler = sessionHandler.createInferenceHandler();
            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;
            });
            const sequence = this._starter.slice(0);
            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];
              const inputList = thisOp.node.inputs.map((i) => this._values[i]);
              if (inputList.indexOf(void 0) !== -1) {
                throw new Error(`unresolved input detected: op: ${thisOp.node}`);
              }
              const inputTensors = inputList;
              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)
              );
              if (outputList.length !== thisOp.node.outputs.length) {
                throw new Error("the size of output does not match model definition.");
              }
              outputList.forEach((output2, 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] = output2;
              });
              const downstreamNodes = /* @__PURE__ */ 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 === void 0) {
                throw new Error(`required output [${outputIndex}] does not have value`);
              }
              if (outputIndex === 0) {
                await outputTensor.getData();
              } else {
                outputTensor.data;
              }
              output.push(outputTensor);
            }
            Logger.verbose("ExecPlan", "disposing of inferenceHandler");
            inferenceHandler.dispose();
            return output;
          });
        }
      };
    }
  });

  // web/lib/onnxjs/attribute.ts
  var import_onnx3, ortFbs2, Attribute;
  var init_attribute = __esm({
    "web/lib/onnxjs/attribute.ts"() {
      "use strict";
      init_ort_generated();
      import_onnx3 = __toESM(require_onnx());
      init_tensor2();
      init_util();
      ortFbs2 = onnxruntime.experimental.fbs;
      Attribute = class _Attribute {
        constructor(attributes) {
          this._attributes = /* @__PURE__ */ new Map();
          if (attributes !== null && attributes !== void 0) {
            for (const attr of attributes) {
              if (attr instanceof import_onnx3.onnx.AttributeProto) {
                this._attributes.set(attr.name, [_Attribute.getValue(attr), _Attribute.getType(attr)]);
              } else if (attr instanceof ortFbs2.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 === void 0) {
            if (defaultValue !== void 0) {
              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 import_onnx3.onnx.AttributeProto ? attr.type : attr.type();
          switch (type) {
            case import_onnx3.onnx.AttributeProto.AttributeType.FLOAT:
              return "float";
            case import_onnx3.onnx.AttributeProto.AttributeType.INT:
              return "int";
            case import_onnx3.onnx.AttributeProto.AttributeType.STRING:
              return "string";
            case import_onnx3.onnx.AttributeProto.AttributeType.TENSOR:
              return "tensor";
            case import_onnx3.onnx.AttributeProto.AttributeType.FLOATS:
              return "floats";
            case import_onnx3.onnx.AttributeProto.AttributeType.INTS:
              return "ints";
            case import_onnx3.onnx.AttributeProto.AttributeType.STRINGS:
              return "strings";
            case import_onnx3.onnx.AttributeProto.AttributeType.TENSORS:
              return "tensors";
            default:
              throw new Error(`attribute type is not supported yet: ${import_onnx3.onnx.AttributeProto.AttributeType[type]}`);
          }
        }
        static getValue(attr) {
          const attrType = attr instanceof import_onnx3.onnx.AttributeProto ? attr.type : attr.type();
          if (attrType === import_onnx3.onnx.AttributeProto.AttributeType.GRAPH || attrType === import_onnx3.onnx.AttributeProto.AttributeType.GRAPHS) {
            throw new Error("graph attribute is not supported yet");
          }
          const value = this.getValueNoCheck(attr);
          if (attrType === import_onnx3.onnx.AttributeProto.AttributeType.INT && LongUtil.isLong(value)) {
            return LongUtil.longToNumber(value);
          }
          if (attrType === import_onnx3.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] = LongUtil.longToNumber(maybeLong);
            }
            return numberValue;
          }
          if (attrType === import_onnx3.onnx.AttributeProto.AttributeType.TENSOR) {
            return attr instanceof import_onnx3.onnx.AttributeProto ? Tensor3.fromProto(value) : Tensor3.fromOrtTensor(value);
          }
          if (attrType === import_onnx3.onnx.AttributeProto.AttributeType.TENSORS) {
            if (attr instanceof import_onnx3.onnx.AttributeProto) {
              const tensorProtos = value;
              return tensorProtos.map((value2) => Tensor3.fromProto(value2));
            } else if (attr instanceof ortFbs2.Attribute) {
              const tensorProtos = value;
              return tensorProtos.map((value2) => Tensor3.fromOrtTensor(value2));
            }
          }
          if (attrType === import_onnx3.onnx.AttributeProto.AttributeType.STRING) {
            if (attr instanceof import_onnx3.onnx.AttributeProto) {
              const utf8String = value;
              return decodeUtf8String(utf8String);
            }
          }
          if (attrType === import_onnx3.onnx.AttributeProto.AttributeType.STRINGS) {
            if (attr instanceof import_onnx3.onnx.AttributeProto) {
              const utf8Strings = value;
              return utf8Strings.map(decodeUtf8String);
            }
          }
          return value;
        }
        static getValueNoCheck(attr) {
          return attr instanceof import_onnx3.onnx.AttributeProto ? this.getValueNoCheckFromOnnxFormat(attr) : this.getValueNoCheckFromOrtFormat(attr);
        }
        static getValueNoCheckFromOnnxFormat(attr) {
          switch (attr.type) {
            case import_onnx3.onnx.AttributeProto.AttributeType.FLOAT:
              return attr.f;
            case import_onnx3.onnx.AttributeProto.AttributeType.INT:
              return attr.i;
            case import_onnx3.onnx.AttributeProto.AttributeType.STRING:
              return attr.s;
            case import_onnx3.onnx.AttributeProto.AttributeType.TENSOR:
              return attr.t;
            case import_onnx3.onnx.AttributeProto.AttributeType.GRAPH:
              return attr.g;
            case import_onnx3.onnx.AttributeProto.AttributeType.FLOATS:
              return attr.floats;
            case import_onnx3.onnx.AttributeProto.AttributeType.INTS:
              return attr.ints;
            case import_onnx3.onnx.AttributeProto.AttributeType.STRINGS:
              return attr.strings;
            case import_onnx3.onnx.AttributeProto.AttributeType.TENSORS:
              return attr.tensors;
            case import_onnx3.onnx.AttributeProto.AttributeType.GRAPHS:
              return attr.graphs;
            default:
              throw new Error(`unsupported attribute type: ${import_onnx3.onnx.AttributeProto.AttributeType[attr.type]}`);
          }
        }
        static getValueNoCheckFromOrtFormat(attr) {
          switch (attr.type()) {
            case ortFbs2.AttributeType.FLOAT:
              return attr.f();
            case ortFbs2.AttributeType.INT:
              return attr.i();
            case ortFbs2.AttributeType.STRING:
              return attr.s();
            case ortFbs2.AttributeType.TENSOR:
              return attr.t();
            case ortFbs2.AttributeType.GRAPH:
              return attr.g();
            case ortFbs2.AttributeType.FLOATS:
              return attr.floatsArray();
            case ortFbs2.AttributeType.INTS: {
              const ints = [];
              for (let i = 0; i < attr.intsLength(); i++) {
                ints.push(attr.ints(i));
              }
              return ints;
            }
            case ortFbs2.AttributeType.STRINGS: {
              const strings = [];
              for (let i = 0; i < attr.stringsLength(); i++) {
                strings.push(attr.strings(i));
              }
              return strings;
            }
            case ortFbs2.AttributeType.TENSORS: {
              const tensors = [];
              for (let i = 0; i < attr.tensorsLength(); i++) {
                tensors.push(attr.tensors(i));
              }
              return tensors;
            }
            default:
              throw new Error(`unsupported attribute type: ${ortFbs2.AttributeType[attr.type()]}`);
          }
        }
      };
    }
  });

  // web/lib/onnxjs/graph.ts
  var import_onnx4, ortFbs3, Graph, Value, Node, GraphImpl;
  var init_graph = __esm({
    "web/lib/onnxjs/graph.ts"() {
      "use strict";
      init_attribute();
      init_ort_generated();
      import_onnx4 = __toESM(require_onnx());
      init_tensor2();
      init_util();
      ortFbs3 = onnxruntime.experimental.fbs;
      Graph = {
        /**
         * construct a graph from a graph protobuf type
         */
        from: (graphProto, initializer) => new GraphImpl(graphProto, initializer)
      };
      Value = class {
        constructor(valueInfo) {
          this._from = void 0;
          this._to = [];
          this.tensor = void 0;
          this.type = void 0;
          if (valueInfo) {
            this.type = ProtoUtil.tensorValueTypeFromProto(valueInfo.type.tensorType);
          }
        }
        // -1 represent from initializer
        get from() {
          return this._from;
        }
        get to() {
          return this._to;
        }
      };
      Node = class {
        constructor(_nodeProto, name2) {
          if (_nodeProto instanceof import_onnx4.onnx.NodeProto) {
            this.name = _nodeProto.name;
            this.opType = _nodeProto.opType;
            this.attributes = new Attribute(_nodeProto.attribute);
          } else if (_nodeProto instanceof ortFbs3.Node) {
            this.name = name2 ?? _nodeProto.name();
            this.opType = _nodeProto.opType();
            this.attributes = new Attribute(ProtoUtil.tensorAttributesFromORTFormat(_nodeProto));
          }
          this.inputs = [];
          this.outputs = [];
          this.executeNode = true;
        }
      };
      GraphImpl = class {
        constructor(graph, graphInitializer) {
          if (!graph) {
            throw new TypeError("graph is empty");
          }
          this.buildGraph(graph);
          this.transformGraph(graphInitializer);
          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) {
          if (graph instanceof import_onnx4.onnx.GraphProto) {
            this.buildGraphFromOnnxFormat(graph);
          } else if (graph instanceof ortFbs3.Graph) {
            this.buildGraphFromOrtFormat(graph);
          } else {
            throw new TypeError("Graph type is not supported.");
          }
        }
        buildGraphFromOnnxFormat(graph) {
          const dataIndices = /* @__PURE__ */ new Map();
          this._allData = [];
          this._allInputIndices = [];
          this._allInputNames = [];
          this._allOutputIndices = [];
          this._allOutputNames = [];
          this._nodes = [];
          const nodesIndices = /* @__PURE__ */ new Map();
          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);
          }
          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 === void 0) {
              const value = new Value();
              value.type = {
                shape: { dims: ProtoUtil.tensorDimsFromProto(i.dims) },
                tensorType: ProtoUtil.tensorDataTypeFromProto(i.dataType)
              };
              index = this._allData.push(value) - 1;
              dataIndices.set(i.name, index);
            }
            this._allData[index]._from = -1;
            this._allData[index].tensor = Tensor3.fromProto(i);
          }
          for (let i = 0; i < this._allData.length; i++) {
            if (!this._allData[i].tensor) {
              this._allInputIndices.push(i);
              this._allInputNames.push(inputValueNames[i]);
            }
          }
          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);
          }
          if (!graph.node) {
            throw new Error("missing information in graph: node");
          }
          for (const nodeProto of graph.node) {
            if (!nodeProto.name) {
              for (let pick = 0; ; pick++) {
                const name2 = `unnamed_${nodeProto.opType}_${pick}`;
                if (!nodesIndices.has(name2)) {
                  nodeProto.name = name2;
                  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);
          }
          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 !== void 0) {
                throw new Error(`multiple nodes output to one data value: ${dataIndex}`);
              }
              this._allData[dataIndex]._from = i;
              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 = Tensor3.fromProto(nodeProto.attribute[0].t);
              }
            }
          }
          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") {
                if (input === "" && (nodeProto.input.length === 3 || nodeProto.input.length === 4) && 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) {
          const dataIndices = /* @__PURE__ */ new Map();
          this._allData = [];
          this._allInputIndices = [];
          this._allInputNames = [];
          this._allOutputIndices = [];
          this._allOutputNames = [];
          this._nodes = [];
          const nodesIndices = /* @__PURE__ */ new Map();
          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}`);
            }
            for (let j = 0; j < graph.nodeArgsLength(); j++) {
              if (graph.nodeArgs(j)?.name() === inputName) {
                const value = new Value();
                const valueType = graph.nodeArgs(j)?.type()?.valueType();
                if (valueType !== ortFbs3.TypeInfoValue.tensor_type) {
                  throw new Error("Unexpected value type for the nodeArg.");
                }
                const valueInfo = graph.nodeArgs(j).type().value(new ortFbs3.TensorTypeAndShape());
                const type = ProtoUtil.tensorDataTypeFromProto(valueInfo.elemType());
                const shape2 = valueInfo.shape();
                const dims = [];
                for (let k = 0; k < shape2.dimLength(); k++) {
                  dims.push(LongUtil.longToNumber(shape2.dim(k).value().dimValue()));
                }
                value.type = { shape: { dims }, tensorType: type };
                const currentIndex = this._allData.push(value) - 1;
                dataIndices.set(inputName, currentIndex);
                inputValueNames.push(inputName);
              }
            }
          }
          for (let i = 0; i < graph.initializersLength(); i++) {
            const initializer = graph.initializers(i);
            let index = dataIndices.get(initializer.name());
            if (index === void 0) {
              const value = new Value();
              const dims = ProtoUtil.tensorDimsFromORTFormat(initializer);
              const type = 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 = Tensor3.fromOrtTensor(initializer);
          }
          for (let i = 0; i < this._allData.length; i++) {
            if (!this._allData[i].tensor) {
              this._allInputIndices.push(i);
              this._allInputNames.push(inputValueNames[i]);
            }
          }
          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);
          }
          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 name2 = nodeProto.name();
            if (!name2) {
              for (let pick = 0; ; pick++) {
                name2 = `unnamed_${nodeProto.opType()}_${pick}`;
                if (!nodesIndices.has(name2)) {
                  break;
                }
              }
            }
            if (nodesIndices.has(name2)) {
              throw new Error(`duplicated node name: ${name2}`);
            }
            const currentIndex = this._nodes.push(new Node(nodeProto, name2)) - 1;
            nodesIndices.set(name2, currentIndex);
          }
          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?.outputsLength() === 0) {
              throw new Error(`missing output for node: ${nodeProto.name}`);
            }
            for (let j = 0; j < nodeProto?.outputsLength(); j++) {
              const output = 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 !== void 0) {
                throw new Error(`multiple nodes output to one data value: ${dataIndex}`);
              }
              this._allData[dataIndex]._from = i;
              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 = Tensor3.fromOrtTensor(nodeProto.attributes(0).t());
              }
            }
          }
          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() {
          const starters = /* @__PURE__ */ new Set();
          this._allInputIndices.forEach((i) => {
            const data = this._allData[i];
            data._to.forEach((j) => {
              starters.add(j);
            });
          });
          const nodesStack = Array.from(starters);
          const nodesState = new Array(this._nodes.length).fill("white");
          while (nodesStack.length > 0) {
            const nodeIndex = nodesStack.pop();
            if (nodesState[nodeIndex] === "gray") {
              nodesState[nodeIndex] = "black";
            } else {
              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) => {
                  if (nodesState[downstreamNodeIndex] === "gray") {
                    throw new Error("model graph is cyclic");
                  } else if (nodesState[downstreamNodeIndex] === "white") {
                    nodesStack.push(downstreamNodeIndex);
                  }
                });
              });
            }
          }
        }
        transformGraph(graphInitializer) {
          this.removeAllIdentityNodes();
          this.removeAllDropoutNodes();
          this.fuseConvActivationNodes();
          if (graphInitializer) {
            graphInitializer.transformGraph(this);
          }
          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;
          const newIndices = new Array(this._nodes.length, 0);
          let nodePossition = 0;
          for (let i = 0; i < this._nodes.length; i++) {
            newIndices[i] = nodePossition;
            if (this._nodes[i].executeNode) {
              if (nodePossition !== i) {
                this._nodes[nodePossition] = this._nodes[i];
              }
              nodePossition++;
            } else {
              this._nodes[i].outputs.forEach((ind) => {
                this._allData[ind]._from = -2;
              });
            }
          }
          this._nodes.splice(nodePossition, this._nodes.length - nodePossition);
          for (let i = 0; i < this._allData.length; i++) {
            const currentData = this._allData[i];
            if (currentData._from !== void 0 && currentData._from !== -1 && currentData._from !== -2) {
              currentData._from = newIndices[currentData._from];
            }
            for (let j = 0; j < currentData._to.length; j++) {
              if (currentData._to[j] >= 0) {
                currentData._to[j] = newIndices[currentData._to[j]];
              } else {
                throw new Error("Trying to update a removed node");
              }
            }
          }
          offset = 0;
          for (let i = 0; i < this._allData.length; i++) {
            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 (this._allData[i].from !== void 0 && 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 {
                ind = this._allInputIndices.indexOf(i + offset);
                if (ind !== -1) {
                  this._allInputIndices[ind] = i;
                }
              }
              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) {
                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. ");
              }
            }
          }
          node.executeNode = false;
          const inputValueIndex = node.inputs[0];
          const outputValueIndex = node.outputs[0];
          const nodesConsumingOutput = this._allData[outputValueIndex].to;
          for (let i = 0; i < node.inputs.length; i++) {
            const delIndex = this._allData[node.inputs[i]].to.indexOf(nodeIndex);
            if (delIndex === -1) {
              throw new Error("The Value object doesn't have the current Node in it's 'to' property ");
            }
            this._allData[node.inputs[i]].to.splice(delIndex, 1);
          }
          this._allData[outputValueIndex]._to = [];
          const index = this._allOutputIndices.indexOf(outputValueIndex);
          if (index !== -1) {
            this._allOutputIndices[index] = inputValueIndex;
          }
          if (nodesConsumingOutput && nodesConsumingOutput.length > 0) {
            for (const nodeIndex2 of nodesConsumingOutput) {
              const replaceIndex = this._nodes[nodeIndex2].inputs.indexOf(outputValueIndex);
              if (replaceIndex === -1) {
                throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");
              }
              this._nodes[nodeIndex2].inputs[replaceIndex] = inputValueIndex;
              this._allData[inputValueIndex].to.push(nodeIndex2);
            }
          }
        }
        removeAllDropoutNodes() {
          let nodeIndex = 0;
          for (const node of this._nodes) {
            if (node.opType === "Dropout") {
              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)");
              }
              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) {
            if (node.opType === "Identity") {
              this.deleteNode(nodeIndex);
            }
            nodeIndex++;
          }
        }
        isActivation(n) {
          switch (n.opType) {
            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", [MIN_CLIP, MAX_CLIP]);
                    }
                  } else if (child.inputs.length >= 3 && this._allData[child.inputs[1]].tensor !== void 0 && this._allData[child.inputs[2]].tensor !== void 0) {
                    node.attributes.set("activation_params", "floats", [
                      this._allData[child.inputs[1]].tensor.floatData[0],
                      this._allData[child.inputs[2]].tensor.floatData[0]
                    ]);
                  } else {
                    continue;
                  }
                }
                node.attributes.set("activation", "string", child.opType);
                this.deleteNode(next[0]);
              }
            }
          }
        }
      };
    }
  });

  // web/lib/onnxjs/model.ts
  var import_onnx5, ortFbs4, Model;
  var init_model = __esm({
    "web/lib/onnxjs/model.ts"() {
      "use strict";
      init_flatbuffers();
      init_graph();
      init_ort_generated();
      import_onnx5 = __toESM(require_onnx());
      init_util();
      ortFbs4 = onnxruntime.experimental.fbs;
      Model = class {
        // empty model
        constructor() {
        }
        load(buf, graphInitializer, isOrtFormat) {
          let onnxError;
          if (!isOrtFormat) {
            try {
              this.loadFromOnnxFormat(buf, graphInitializer);
              return;
            } catch (e) {
              if (isOrtFormat !== void 0) {
                throw e;
              }
              onnxError = e;
            }
          }
          try {
            this.loadFromOrtFormat(buf, graphInitializer);
          } catch (e) {
            if (isOrtFormat !== void 0) {
              throw e;
            }
            throw new Error(`Failed to load model as ONNX format: ${onnxError}
as ORT format: ${e}`);
          }
        }
        loadFromOnnxFormat(buf, graphInitializer) {
          const modelProto = import_onnx5.onnx.ModelProto.decode(buf);
          const irVersion = 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: LongUtil.longToNumber(i.version) }));
          this._graph = Graph.from(modelProto.graph, graphInitializer);
        }
        loadFromOrtFormat(buf, graphInitializer) {
          const fb = new flatbuffers.ByteBuffer(buf);
          const ortModel = ortFbs4.InferenceSession.getRootAsInferenceSession(fb).model();
          const irVersion = 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?.domain(), version: LongUtil.longToNumber(opsetId.version()) });
          }
          this._graph = Graph.from(ortModel.graph(), graphInitializer);
        }
        get graph() {
          return this._graph;
        }
        get opsets() {
          return this._opsets;
        }
      };
    }
  });

  // web/lib/onnxjs/session.ts
  var Session;
  var init_session = __esm({
    "web/lib/onnxjs/session.ts"() {
      "use strict";
      init_promises();
      init_backend2();
      init_execution_plan();
      init_instrument();
      init_model();
      Session = class {
        constructor(config = {}) {
          this._initialized = false;
          this.backendHint = config.backendHint;
          this.profiler = 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 () => {
            const backend2 = await resolveBackend(this.backendHint);
            this.sessionHandler = backend2.createSessionHandler(this.context);
            this._model = new Model();
            if (typeof arg === "string") {
              const isOrtFormat = arg.endsWith(".ort");
              if (typeof process !== "undefined" && process.versions && process.versions.node) {
                const buf = await readFile(arg);
                this.initialize(buf, isOrtFormat);
              } else {
                const response = await fetch(arg);
                const buf = await response.arrayBuffer();
                this.initialize(new Uint8Array(buf), isOrtFormat);
              }
            } else if (!ArrayBuffer.isView(arg)) {
              const arr = new Uint8Array(arg, byteOffset || 0, length || arg.byteLength);
              this.initialize(arr);
            } else {
              this.initialize(arg);
            }
          });
        }
        initialize(modelProtoBlob, isOrtFormat) {
          if (this._initialized) {
            throw new Error("already initialized");
          }
          this.profiler.event("session", "Session.initialize", () => {
            const graphInitializer = this.sessionHandler.transformGraph ? this.sessionHandler : void 0;
            this._model.load(modelProtoBlob, graphInitializer, isOrtFormat);
            if (this.sessionHandler.onGraphInitialized) {
              this.sessionHandler.onGraphInitialized(this._model.graph);
            }
            this.initializeOps(this._model.graph);
            this._executionPlan = new 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();
          if (Array.isArray(inputs)) {
            if (inputs.length !== modelInputNames.length) {
              throw new Error(`incorrect input array length: expected ${modelInputNames.length} but got ${inputs.length}`);
            }
          } 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;
          }
          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;
              this.context.graphInputTypes.push(graphInput.type.tensorType);
              this.context.graphInputDims.push(inputs[i].dims);
            }
            this.validateInputTensorDims(graphInputDims, inputs, true);
          } else {
            this.validateInputTensorDims(this.context.graphInputDims, inputs, false);
          }
          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)) {
              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 = /* @__PURE__ */ 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);
          }
        }
      };
    }
  });

  // web/lib/onnxjs/session-handler-inference.ts
  var OnnxjsSessionHandler;
  var init_session_handler_inference = __esm({
    "web/lib/onnxjs/session-handler-inference.ts"() {
      "use strict";
      init_esm();
      init_tensor2();
      OnnxjsSessionHandler = class {
        constructor(session) {
          this.session = session;
          this.inputNames = this.session.inputNames;
          this.outputNames = this.session.outputNames;
        }
        async dispose() {
        }
        async run(feeds, _fetches, _options) {
          const inputMap = /* @__PURE__ */ new Map();
          for (const name2 in feeds) {
            if (Object.hasOwnProperty.call(feeds, name2)) {
              const feed = feeds[name2];
              inputMap.set(
                name2,
                new Tensor3(
                  feed.dims,
                  feed.type,
                  void 0,
                  void 0,
                  feed.data
                )
              );
            }
          }
          const outputMap = await this.session.run(inputMap);
          const output = {};
          outputMap.forEach((tensor, name2) => {
            output[name2] = new Tensor2(tensor.type, tensor.data, tensor.dims);
          });
          return output;
        }
        startProfiling() {
          this.session.startProfiling();
        }
        endProfiling() {
          this.session.endProfiling();
        }
      };
    }
  });

  // web/lib/backend-onnxjs.ts
  var backend_onnxjs_exports = {};
  __export(backend_onnxjs_exports, {
    onnxjsBackend: () => onnxjsBackend
  });
  var OnnxjsBackend, onnxjsBackend;
  var init_backend_onnxjs = __esm({
    "web/lib/backend-onnxjs.ts"() {
      "use strict";
      init_session();
      init_session_handler_inference();
      OnnxjsBackend = class {
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        async init() {
        }
        async createInferenceSessionHandler(pathOrBuffer, options) {
          const session = new Session(options);
          if (typeof pathOrBuffer === "string") {
            await session.loadModel(pathOrBuffer);
          } else {
            await session.loadModel(pathOrBuffer);
          }
          return new OnnxjsSessionHandler(session);
        }
      };
      onnxjsBackend = new OnnxjsBackend();
    }
  });

  // nodejs-ignore:node:os
  var cpus;
  var init_node_os = __esm({
    "nodejs-ignore:node:os"() {
      cpus = void 0;
    }
  });

  // nodejs-ignore:node:path
  var join;
  var init_node_path = __esm({
    "nodejs-ignore:node:path"() {
      join = void 0;
    }
  });

  // nodejs-ignore:fs
  var fs_exports = {};
  __export(fs_exports, {
    createReadStream: () => createReadStream,
    readFile: () => readFile2,
    readFileSync: () => readFileSync
  });
  var readFile2, readFileSync, createReadStream;
  var init_fs = __esm({
    "nodejs-ignore:fs"() {
      readFile2 = void 0;
      readFileSync = void 0;
      createReadStream = void 0;
    }
  });

  // nodejs-ignore:path
  var path_exports = {};
  __export(path_exports, {
    join: () => join2
  });
  var join2;
  var init_path = __esm({
    "nodejs-ignore:path"() {
      join2 = void 0;
    }
  });

  // web/lib/wasm/binding/ort-wasm.js
  var require_ort_wasm = __commonJS({
    "web/lib/wasm/binding/ort-wasm.js"(exports2, module2) {
      "use strict";
      var ortWasm = (() => {
        var _scriptDir = typeof document != "undefined" ? document.currentScript?.src : void 0;
        if (typeof __filename != "undefined")
          _scriptDir ||= __filename;
        return function(moduleArg = {}) {
          var f = moduleArg, k, l, readyPromise = new Promise((a, b) => {
            k = a;
            l = b;
          }), u = Object.assign({}, f), v = "./this.program", aa = "object" == typeof window, w = "function" == typeof importScripts, ba = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, z = "", A, B, C;
          if (ba) {
            var fs = (init_fs(), __toCommonJS(fs_exports)), D = (init_path(), __toCommonJS(path_exports));
            z = w ? D.dirname(z) + "/" : __dirname + "/";
            A = (a, b) => {
              a = E(a) ? new URL(a) : D.normalize(a);
              return fs.readFileSync(a, b ? void 0 : "utf8");
            };
            C = (a) => {
              a = A(a, true);
              a.buffer || (a = new Uint8Array(a));
              return a;
            };
            B = (a, b, c, e = true) => {
              a = E(a) ? new URL(a) : D.normalize(a);
              fs.readFile(a, e ? void 0 : "utf8", (g, h) => {
                g ? c(g) : b(e ? h.buffer : h);
              });
            };
            !f.thisProgram && 1 < process.argv.length && (v = process.argv[1].replace(/\\/g, "/"));
            process.argv.slice(2);
          } else if (aa || w)
            w ? z = self.location.href : "undefined" != typeof document && document.currentScript && (z = document.currentScript.src), _scriptDir && (z = _scriptDir), z.startsWith("blob:") ? z = "" : z = z.substr(0, z.replace(/[?#].*/, "").lastIndexOf("/") + 1), A = (a) => {
              var b = new XMLHttpRequest();
              b.open("GET", a, false);
              b.send(null);
              return b.responseText;
            }, w && (C = (a) => {
              var b = new XMLHttpRequest();
              b.open("GET", a, false);
              b.responseType = "arraybuffer";
              b.send(null);
              return new Uint8Array(b.response);
            }), B = (a, b, c) => {
              var e = new XMLHttpRequest();
              e.open("GET", a, true);
              e.responseType = "arraybuffer";
              e.onload = () => {
                200 == e.status || 0 == e.status && e.response ? b(e.response) : c();
              };
              e.onerror = c;
              e.send(null);
            };
          var ca = console.log.bind(console), F = console.error.bind(console);
          Object.assign(f, u);
          u = null;
          var G, da = false, H, I, J, K, ea;
          function fa() {
            var a = G.buffer;
            f.HEAP8 = H = new Int8Array(a);
            f.HEAP16 = new Int16Array(a);
            f.HEAPU8 = I = new Uint8Array(a);
            f.HEAPU16 = new Uint16Array(a);
            f.HEAP32 = J = new Int32Array(a);
            f.HEAPU32 = K = new Uint32Array(a);
            f.HEAPF32 = new Float32Array(a);
            f.HEAPF64 = ea = new Float64Array(a);
          }
          var L = [], M = [], ha = [], N = 0, O = null, P = null;
          function ia(a) {
            a = "Aborted(" + a + ")";
            F(a);
            da = true;
            a = new WebAssembly.RuntimeError(a + ". Build with -sASSERTIONS for more info.");
            l(a);
            throw a;
          }
          var ja = (a) => a.startsWith("data:application/octet-stream;base64,"), E = (a) => a.startsWith("file://"), Q;
          Q = "ort-wasm.wasm";
          if (!ja(Q)) {
            var ka = Q;
            Q = f.locateFile ? f.locateFile(ka, z) : z + ka;
          }
          function la(a) {
            if (C)
              return C(a);
            throw "both async and sync fetching of the wasm failed";
          }
          function ma(a) {
            if (aa || w) {
              if ("function" == typeof fetch && !E(a))
                return fetch(a, { credentials: "same-origin" }).then((b) => {
                  if (!b.ok)
                    throw `failed to load wasm binary file at '${a}'`;
                  return b.arrayBuffer();
                }).catch(() => la(a));
              if (B)
                return new Promise((b, c) => {
                  B(a, (e) => b(new Uint8Array(e)), c);
                });
            }
            return Promise.resolve().then(() => la(a));
          }
          function na(a, b, c) {
            return ma(a).then((e) => WebAssembly.instantiate(e, b)).then(c, (e) => {
              F(`failed to asynchronously prepare wasm: ${e}`);
              ia(e);
            });
          }
          function oa(a, b) {
            var c = Q;
            return "function" != typeof WebAssembly.instantiateStreaming || ja(c) || E(c) || ba || "function" != typeof fetch ? na(c, a, b) : fetch(c, { credentials: "same-origin" }).then((e) => WebAssembly.instantiateStreaming(e, a).then(b, function(g) {
              F(`wasm streaming compile failed: ${g}`);
              F("falling back to ArrayBuffer instantiation");
              return na(c, a, b);
            }));
          }
          var R, pa = { 798088: (a, b, c, e) => {
            if ("undefined" == typeof f || !f.ya)
              return 1;
            a = S(a >>> 0);
            a.startsWith("./") && (a = a.substring(2));
            a = f.ya.get(a);
            if (!a)
              return 2;
            b >>>= 0;
            c >>>= 0;
            if (b + c > a.byteLength)
              return 3;
            try {
              return I.set(a.subarray(b, b + c), e >>> 0 >>> 0), 0;
            } catch {
              return 4;
            }
          } };
          class qa {
            constructor(a) {
              this.wa = a - 24;
            }
          }
          var ra = 0, sa = 0, ta = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0, ua = (a, b, c) => {
            b >>>= 0;
            var e = b + c;
            for (c = b; a[c] && !(c >= e); )
              ++c;
            if (16 < c - b && a.buffer && ta)
              return ta.decode(a.subarray(b, c));
            for (e = ""; b < c; ) {
              var g = a[b++];
              if (g & 128) {
                var h = a[b++] & 63;
                if (192 == (g & 224))
                  e += String.fromCharCode((g & 31) << 6 | h);
                else {
                  var m = a[b++] & 63;
                  g = 224 == (g & 240) ? (g & 15) << 12 | h << 6 | m : (g & 7) << 18 | h << 12 | m << 6 | a[b++] & 63;
                  65536 > g ? e += String.fromCharCode(g) : (g -= 65536, e += String.fromCharCode(55296 | g >> 10, 56320 | g & 1023));
                }
              } else
                e += String.fromCharCode(g);
            }
            return e;
          }, S = (a, b) => (a >>>= 0) ? ua(I, a, b) : "", va = (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;
          }, T = (a, b, c, e) => {
            c >>>= 0;
            if (!(0 < e))
              return 0;
            var g = c;
            e = c + e - 1;
            for (var h = 0; h < a.length; ++h) {
              var m = a.charCodeAt(h);
              if (55296 <= m && 57343 >= m) {
                var q = a.charCodeAt(++h);
                m = 65536 + ((m & 1023) << 10) | q & 1023;
              }
              if (127 >= m) {
                if (c >= e)
                  break;
                b[c++ >>> 0] = m;
              } else {
                if (2047 >= m) {
                  if (c + 1 >= e)
                    break;
                  b[c++ >>> 0] = 192 | m >> 6;
                } else {
                  if (65535 >= m) {
                    if (c + 2 >= e)
                      break;
                    b[c++ >>> 0] = 224 | m >> 12;
                  } else {
                    if (c + 3 >= e)
                      break;
                    b[c++ >>> 0] = 240 | m >> 18;
                    b[c++ >>> 0] = 128 | m >> 12 & 63;
                  }
                  b[c++ >>> 0] = 128 | m >> 6 & 63;
                }
                b[c++ >>> 0] = 128 | m & 63;
              }
            }
            b[c >>> 0] = 0;
            return c - g;
          }, U = (a) => 0 === a % 4 && (0 !== a % 100 || 0 === a % 400), za = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], Aa = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], V = [], W = {}, Ba = () => {
            if (!X) {
              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", _: v || "./this.program" }, b;
              for (b in W)
                void 0 === W[b] ? delete a[b] : a[b] = W[b];
              var c = [];
              for (b in a)
                c.push(`${b}=${a[b]}`);
              X = c;
            }
            return X;
          }, X, Ca = [null, [], []], Da = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], Ea = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
          function Fa(a) {
            var b = Array(va(a) + 1);
            T(a, b, 0, b.length);
            return b;
          }
          function Ga(a, b, c, e) {
            function g(d, n, p) {
              for (d = "number" == typeof d ? d.toString() : d || ""; d.length < n; )
                d = p[0] + d;
              return d;
            }
            function h(d, n) {
              return g(d, n, "0");
            }
            function m(d, n) {
              function p(wa) {
                return 0 > wa ? -1 : 0 < wa ? 1 : 0;
              }
              var y;
              0 === (y = p(d.getFullYear() - n.getFullYear())) && 0 === (y = p(d.getMonth() - n.getMonth())) && (y = p(d.getDate() - n.getDate()));
              return y;
            }
            function q(d) {
              switch (d.getDay()) {
                case 0:
                  return new Date(d.getFullYear() - 1, 11, 29);
                case 1:
                  return d;
                case 2:
                  return new Date(d.getFullYear(), 0, 3);
                case 3:
                  return new Date(
                    d.getFullYear(),
                    0,
                    2
                  );
                case 4:
                  return new Date(d.getFullYear(), 0, 1);
                case 5:
                  return new Date(d.getFullYear() - 1, 11, 31);
                case 6:
                  return new Date(d.getFullYear() - 1, 11, 30);
              }
            }
            function x(d) {
              var n = d.sa;
              for (d = new Date(new Date(d.ta + 1900, 0, 1).getTime()); 0 < n; ) {
                var p = d.getMonth(), y = (U(d.getFullYear()) ? Da : Ea)[p];
                if (n > y - d.getDate())
                  n -= y - d.getDate() + 1, d.setDate(1), 11 > p ? d.setMonth(p + 1) : (d.setMonth(0), d.setFullYear(d.getFullYear() + 1));
                else {
                  d.setDate(d.getDate() + n);
                  break;
                }
              }
              p = new Date(d.getFullYear() + 1, 0, 4);
              n = q(new Date(
                d.getFullYear(),
                0,
                4
              ));
              p = q(p);
              return 0 >= m(n, d) ? 0 >= m(p, d) ? d.getFullYear() + 1 : d.getFullYear() : d.getFullYear() - 1;
            }
            a >>>= 0;
            b >>>= 0;
            c >>>= 0;
            e >>>= 0;
            var r = K[e + 40 >>> 2 >>> 0];
            e = { Ba: J[e >>> 2 >>> 0], Aa: J[e + 4 >>> 2 >>> 0], ua: J[e + 8 >>> 2 >>> 0], xa: J[e + 12 >>> 2 >>> 0], va: J[e + 16 >>> 2 >>> 0], ta: J[e + 20 >>> 2 >>> 0], na: J[e + 24 >>> 2 >>> 0], sa: J[e + 28 >>> 2 >>> 0], Da: J[e + 32 >>> 2 >>> 0], za: J[e + 36 >>> 2 >>> 0], Ca: r ? S(r) : "" };
            c = S(c);
            r = {
              "%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 t in r)
              c = c.replace(new RegExp(t, "g"), r[t]);
            var xa = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), ya = "January February March April May June July August September October November December".split(" ");
            r = {
              "%a": (d) => xa[d.na].substring(0, 3),
              "%A": (d) => xa[d.na],
              "%b": (d) => ya[d.va].substring(0, 3),
              "%B": (d) => ya[d.va],
              "%C": (d) => h((d.ta + 1900) / 100 | 0, 2),
              "%d": (d) => h(d.xa, 2),
              "%e": (d) => g(d.xa, 2, " "),
              "%g": (d) => x(d).toString().substring(2),
              "%G": x,
              "%H": (d) => h(d.ua, 2),
              "%I": (d) => {
                d = d.ua;
                0 == d ? d = 12 : 12 < d && (d -= 12);
                return h(d, 2);
              },
              "%j": (d) => {
                for (var n = 0, p = 0; p <= d.va - 1; n += (U(d.ta + 1900) ? Da : Ea)[p++])
                  ;
                return h(d.xa + n, 3);
              },
              "%m": (d) => h(d.va + 1, 2),
              "%M": (d) => h(d.Aa, 2),
              "%n": () => "\n",
              "%p": (d) => 0 <= d.ua && 12 > d.ua ? "AM" : "PM",
              "%S": (d) => h(d.Ba, 2),
              "%t": () => "	",
              "%u": (d) => d.na || 7,
              "%U": (d) => h(Math.floor((d.sa + 7 - d.na) / 7), 2),
              "%V": (d) => {
                var n = Math.floor((d.sa + 7 - (d.na + 6) % 7) / 7);
                2 >= (d.na + 371 - d.sa - 2) % 7 && n++;
                if (n)
                  53 == n && (p = (d.na + 371 - d.sa) % 7, 4 == p || 3 == p && U(d.ta) || (n = 1));
                else {
                  n = 52;
                  var p = (d.na + 7 - d.sa - 1) % 7;
                  (4 == p || 5 == p && U(d.ta % 400 - 1)) && n++;
                }
                return h(n, 2);
              },
              "%w": (d) => d.na,
              "%W": (d) => h(Math.floor((d.sa + 7 - (d.na + 6) % 7) / 7), 2),
              "%y": (d) => (d.ta + 1900).toString().substring(2),
              "%Y": (d) => d.ta + 1900,
              "%z": (d) => {
                d = d.za;
                var n = 0 <= d;
                d = Math.abs(d) / 60;
                return (n ? "+" : "-") + String("0000" + (d / 60 * 100 + d % 60)).slice(-4);
              },
              "%Z": (d) => d.Ca,
              "%%": () => "%"
            };
            c = c.replace(/%%/g, "\0\0");
            for (t in r)
              c.includes(t) && (c = c.replace(new RegExp(t, "g"), r[t](e)));
            c = c.replace(/\0\0/g, "%");
            t = Fa(c);
            if (t.length > b)
              return 0;
            H.set(t, a >>> 0);
            return t.length - 1;
          }
          var Ia = { a: function(a, b, c) {
            a >>>= 0;
            var e = new qa(a);
            K[e.wa + 16 >>> 2 >>> 0] = 0;
            K[e.wa + 4 >>> 2 >>> 0] = b >>> 0;
            K[e.wa + 8 >>> 2 >>> 0] = c >>> 0;
            ra = a;
            sa++;
            throw ra;
          }, e: function() {
            return 0;
          }, H: function() {
          }, x: function() {
          }, z: function() {
          }, J: function() {
            return 0;
          }, F: function() {
          }, A: function() {
          }, E: function() {
          }, g: function() {
          }, y: function() {
          }, v: function() {
          }, G: function() {
          }, w: function() {
          }, k: () => 1, I: function(a, b, c) {
            b >>>= 0;
            return I.copyWithin(a >>> 0 >>> 0, b >>> 0, b + (c >>> 0) >>> 0);
          }, n: function(a, b, c) {
            a = b + 2097152 >>> 0 < 4194305 - !!a ? (a >>> 0) + 4294967296 * b : NaN;
            c >>>= 0;
            a = new Date(1e3 * a);
            J[c >>> 2 >>> 0] = a.getUTCSeconds();
            J[c + 4 >>> 2 >>> 0] = a.getUTCMinutes();
            J[c + 8 >>> 2 >>> 0] = a.getUTCHours();
            J[c + 12 >>> 2 >>> 0] = a.getUTCDate();
            J[c + 16 >>> 2 >>> 0] = a.getUTCMonth();
            J[c + 20 >>> 2 >>> 0] = a.getUTCFullYear() - 1900;
            J[c + 24 >>> 2 >>> 0] = a.getUTCDay();
            J[c + 28 >>> 2 >>> 0] = (a.getTime() - Date.UTC(a.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0;
          }, o: function(a, b, c) {
            a = b + 2097152 >>> 0 < 4194305 - !!a ? (a >>> 0) + 4294967296 * b : NaN;
            c >>>= 0;
            a = new Date(1e3 * a);
            J[c >>> 2 >>> 0] = a.getSeconds();
            J[c + 4 >>> 2 >>> 0] = a.getMinutes();
            J[c + 8 >>> 2 >>> 0] = a.getHours();
            J[c + 12 >>> 2 >>> 0] = a.getDate();
            J[c + 16 >>> 2 >>> 0] = a.getMonth();
            J[c + 20 >>> 2 >>> 0] = a.getFullYear() - 1900;
            J[c + 24 >>> 2 >>> 0] = a.getDay();
            J[c + 28 >>> 2 >>> 0] = (U(a.getFullYear()) ? za : Aa)[a.getMonth()] + a.getDate() - 1 | 0;
            J[c + 36 >>> 2 >>> 0] = -(60 * a.getTimezoneOffset());
            b = new Date(a.getFullYear(), 6, 1).getTimezoneOffset();
            var e = new Date(a.getFullYear(), 0, 1).getTimezoneOffset();
            J[c + 32 >>> 2 >>> 0] = (b != e && a.getTimezoneOffset() == Math.min(e, b)) | 0;
          }, p: function(a) {
            a >>>= 0;
            var b = new Date(
              J[a + 20 >>> 2 >>> 0] + 1900,
              J[a + 16 >>> 2 >>> 0],
              J[a + 12 >>> 2 >>> 0],
              J[a + 8 >>> 2 >>> 0],
              J[a + 4 >>> 2 >>> 0],
              J[a >>> 2 >>> 0],
              0
            ), c = J[a + 32 >>> 2 >>> 0], e = b.getTimezoneOffset(), g = new Date(b.getFullYear(), 6, 1).getTimezoneOffset(), h = new Date(b.getFullYear(), 0, 1).getTimezoneOffset(), m = Math.min(h, g);
            0 > c ? J[a + 32 >>> 2 >>> 0] = Number(g != h && m == e) : 0 < c != (m == e) && (g = Math.max(h, g), b.setTime(b.getTime() + 6e4 * ((0 < c ? m : g) - e)));
            J[a + 24 >>> 2 >>> 0] = b.getDay();
            J[a + 28 >>> 2 >>> 0] = (U(b.getFullYear()) ? za : Aa)[b.getMonth()] + b.getDate() - 1 | 0;
            J[a >>> 2 >>> 0] = b.getSeconds();
            J[a + 4 >>> 2 >>> 0] = b.getMinutes();
            J[a + 8 >>> 2 >>> 0] = b.getHours();
            J[a + 12 >>> 2 >>> 0] = b.getDate();
            J[a + 16 >>> 2 >>> 0] = b.getMonth();
            J[a + 20 >>> 2 >>> 0] = b.getYear();
            a = b.getTime();
            a = isNaN(a) ? -1 : a / 1e3;
            Ha((R = a, 1 <= +Math.abs(R) ? 0 < R ? +Math.floor(R / 4294967296) >>> 0 : ~~+Math.ceil((R - +(~~R >>> 0)) / 4294967296) >>> 0 : 0));
            return a >>> 0;
          }, l: function() {
            return -52;
          }, m: function() {
          }, t: function(a, b, c, e) {
            c >>>= 0;
            e >>>= 0;
            var g = (/* @__PURE__ */ new Date()).getFullYear(), h = new Date(g, 0, 1), m = new Date(g, 6, 1);
            g = h.getTimezoneOffset();
            var q = m.getTimezoneOffset();
            K[a >>> 0 >>> 2 >>> 0] = 60 * Math.max(g, q);
            J[b >>> 0 >>> 2 >>> 0] = Number(g != q);
            a = (x) => x.toLocaleTimeString(void 0, { hour12: false, timeZoneName: "short" }).split(" ")[1];
            h = a(h);
            m = a(m);
            q < g ? (T(h, I, c, 17), T(m, I, e, 17)) : (T(h, I, e, 17), T(m, I, c, 17));
          }, d: () => {
            ia("");
          }, B: function(a, b, c) {
            a >>>= 0;
            b >>>= 0;
            c >>>= 0;
            V.length = 0;
            for (var e; e = I[b++ >>> 0]; ) {
              var g = 105 != e;
              g &= 112 != e;
              c += g && c % 8 ? 4 : 0;
              V.push(112 == e ? K[c >>> 2 >>> 0] : 105 == e ? J[c >>> 2 >>> 0] : ea[c >>> 3 >>> 0]);
              c += g ? 8 : 4;
            }
            return pa[a](...V);
          }, h: () => Date.now(), u: function() {
            return 4294901760;
          }, b: () => performance.now(), s: function(a) {
            a >>>= 0;
            var b = I.length;
            if (4294901760 < a)
              return false;
            for (var c = 1; 4 >= c; c *= 2) {
              var e = b * (1 + 0.2 / c);
              e = Math.min(e, a + 100663296);
              var g = Math;
              e = Math.max(a, e);
              a: {
                g = (g.min.call(g, 4294901760, e + (65536 - e % 65536) % 65536) - G.buffer.byteLength + 65535) / 65536;
                try {
                  G.grow(g);
                  fa();
                  var h = 1;
                  break a;
                } catch (m) {
                }
                h = void 0;
              }
              if (h)
                return true;
            }
            return false;
          }, C: function(a, b) {
            a >>>= 0;
            b >>>= 0;
            var c = 0;
            Ba().forEach((e, g) => {
              var h = b + c;
              g = K[a + 4 * g >>> 2 >>> 0] = h;
              for (h = 0; h < e.length; ++h)
                H[g++ >>> 0] = e.charCodeAt(h);
              H[g >>> 0] = 0;
              c += e.length + 1;
            });
            return 0;
          }, D: function(a, b) {
            a >>>= 0;
            b >>>= 0;
            var c = Ba();
            K[a >>> 2 >>> 0] = c.length;
            var e = 0;
            c.forEach((g) => e += g.length + 1);
            K[b >>> 2 >>> 0] = e;
            return 0;
          }, f: () => 52, j: function() {
            return 52;
          }, q: function() {
            return 70;
          }, i: function(a, b, c, e) {
            b >>>= 0;
            c >>>= 0;
            e >>>= 0;
            for (var g = 0, h = 0; h < c; h++) {
              var m = K[b >>> 2 >>> 0], q = K[b + 4 >>> 2 >>> 0];
              b += 8;
              for (var x = 0; x < q; x++) {
                var r = I[m + x >>> 0], t = Ca[a];
                0 === r || 10 === r ? ((1 === a ? ca : F)(ua(t, 0)), t.length = 0) : t.push(r);
              }
              g += q;
            }
            K[e >>> 2 >>> 0] = g;
            return 0;
          }, r: Ga, c: function(a, b, c, e) {
            return Ga(a >>> 0, b >>> 0, c >>> 0, e >>> 0);
          } }, Y = function() {
            function a(c) {
              Y = c.exports;
              Y = Ja();
              G = Y.K;
              fa();
              M.unshift(Y.L);
              N--;
              0 == N && (null !== O && (clearInterval(O), O = null), P && (c = P, P = null, c()));
              return Y;
            }
            var b = { a: Ia };
            N++;
            if (f.instantiateWasm)
              try {
                return f.instantiateWasm(b, a);
              } catch (c) {
                F(`Module.instantiateWasm callback failed with error: ${c}`), l(c);
              }
            oa(b, function(c) {
              a(c.instance);
            }).catch(l);
            return {};
          }();
          f._OrtInit = (a, b) => (f._OrtInit = Y.M)(a, b);
          f._OrtGetLastError = (a, b) => (f._OrtGetLastError = Y.N)(a, b);
          f._OrtCreateSessionOptions = (a, b, c, e, g, h, m, q, x, r) => (f._OrtCreateSessionOptions = Y.O)(a, b, c, e, g, h, m, q, x, r);
          f._OrtAppendExecutionProvider = (a, b) => (f._OrtAppendExecutionProvider = Y.P)(a, b);
          f._OrtAddFreeDimensionOverride = (a, b, c) => (f._OrtAddFreeDimensionOverride = Y.Q)(a, b, c);
          f._OrtAddSessionConfigEntry = (a, b, c) => (f._OrtAddSessionConfigEntry = Y.R)(a, b, c);
          f._OrtReleaseSessionOptions = (a) => (f._OrtReleaseSessionOptions = Y.S)(a);
          f._OrtCreateSession = (a, b, c) => (f._OrtCreateSession = Y.T)(a, b, c);
          f._OrtReleaseSession = (a) => (f._OrtReleaseSession = Y.U)(a);
          f._OrtGetInputOutputCount = (a, b, c) => (f._OrtGetInputOutputCount = Y.V)(a, b, c);
          f._OrtGetInputName = (a, b) => (f._OrtGetInputName = Y.W)(a, b);
          f._OrtGetOutputName = (a, b) => (f._OrtGetOutputName = Y.X)(a, b);
          f._OrtFree = (a) => (f._OrtFree = Y.Y)(a);
          f._OrtCreateTensor = (a, b, c, e, g, h) => (f._OrtCreateTensor = Y.Z)(a, b, c, e, g, h);
          f._OrtGetTensorData = (a, b, c, e, g) => (f._OrtGetTensorData = Y._)(a, b, c, e, g);
          f._OrtReleaseTensor = (a) => (f._OrtReleaseTensor = Y.$)(a);
          f._OrtCreateRunOptions = (a, b, c, e) => (f._OrtCreateRunOptions = Y.aa)(a, b, c, e);
          f._OrtAddRunConfigEntry = (a, b, c) => (f._OrtAddRunConfigEntry = Y.ba)(a, b, c);
          f._OrtReleaseRunOptions = (a) => (f._OrtReleaseRunOptions = Y.ca)(a);
          f._OrtCreateBinding = (a) => (f._OrtCreateBinding = Y.da)(a);
          f._OrtBindInput = (a, b, c) => (f._OrtBindInput = Y.ea)(a, b, c);
          f._OrtBindOutput = (a, b, c, e) => (f._OrtBindOutput = Y.fa)(a, b, c, e);
          f._OrtClearBoundOutputs = (a) => (f._OrtClearBoundOutputs = Y.ga)(a);
          f._OrtReleaseBinding = (a) => (f._OrtReleaseBinding = Y.ha)(a);
          f._OrtRunWithBinding = (a, b, c, e, g) => (f._OrtRunWithBinding = Y.ia)(a, b, c, e, g);
          f._OrtRun = (a, b, c, e, g, h, m, q) => (f._OrtRun = Y.ja)(a, b, c, e, g, h, m, q);
          f._OrtEndProfiling = (a) => (f._OrtEndProfiling = Y.ka)(a);
          f._malloc = (a) => (f._malloc = Y.la)(a);
          f._free = (a) => (f._free = Y.ma)(a);
          var Ha = (a) => (Ha = Y.oa)(a), Ka = (a) => (Ka = Y.pa)(a), La = (a) => (La = Y.qa)(a), Ma = () => (Ma = Y.ra)();
          function Ja() {
            var a = Y;
            a = Object.assign({}, a);
            var b = (c) => (e) => c(e) >>> 0;
            a.la = b(a.la);
            a.qa = b(a.qa);
            a.ra = ((c) => () => c() >>> 0)(a.ra);
            return a;
          }
          f.stackSave = () => Ma();
          f.stackRestore = (a) => Ka(a);
          f.stackAlloc = (a) => La(a);
          f.UTF8ToString = S;
          f.stringToUTF8 = (a, b, c) => T(a, I, b, c);
          f.lengthBytesUTF8 = va;
          var Z;
          P = function Na() {
            Z || Oa();
            Z || (P = Na);
          };
          function Oa() {
            if (!(0 < N)) {
              if (f.preRun)
                for ("function" == typeof f.preRun && (f.preRun = [f.preRun]); f.preRun.length; ) {
                  var a = f.preRun.shift();
                  L.unshift(a);
                }
              for (; 0 < L.length; )
                L.shift()(f);
              if (!(0 < N || Z || (Z = true, f.calledRun = true, da))) {
                for (; 0 < M.length; )
                  M.shift()(f);
                for (k(f); 0 < ha.length; )
                  ha.shift()(f);
              }
            }
          }
          Oa();
          return readyPromise;
        };
      })();
      if (typeof exports2 === "object" && typeof module2 === "object")
        module2.exports = ortWasm;
      else if (typeof define === "function" && define["amd"])
        define([], () => ortWasm);
    }
  });

  // nodejs-ignore:worker_threads
  var require_worker_threads = __commonJS({
    "nodejs-ignore:worker_threads"() {
    }
  });

  // nodejs-ignore:perf_hooks
  var require_perf_hooks = __commonJS({
    "nodejs-ignore:perf_hooks"() {
    }
  });

  // nodejs-ignore:os
  var os_exports = {};
  __export(os_exports, {
    cpus: () => cpus2
  });
  var cpus2;
  var init_os = __esm({
    "nodejs-ignore:os"() {
      cpus2 = void 0;
    }
  });

  // web/lib/wasm/binding/ort-wasm-threaded.js
  var require_ort_wasm_threaded = __commonJS({
    "web/lib/wasm/binding/ort-wasm-threaded.js"(exports2, module2) {
      "use strict";
      var ortWasmThreaded = (() => {
        var _scriptDir = typeof document != "undefined" ? document.currentScript?.src : void 0;
        if (typeof __filename != "undefined")
          _scriptDir ||= __filename;
        return function(moduleArg = {}) {
          function aa() {
            e.buffer != l.buffer && m();
            return l;
          }
          function n() {
            e.buffer != l.buffer && m();
            return ba;
          }
          function p() {
            e.buffer != l.buffer && m();
            return ca;
          }
          function r() {
            e.buffer != l.buffer && m();
            return da;
          }
          function ea() {
            e.buffer != l.buffer && m();
            return fa;
          }
          var v = moduleArg, ha, x, readyPromise = new Promise((a, b) => {
            ha = a;
            x = b;
          }), ia = Object.assign({}, v), ja = "./this.program", z = (a, b) => {
            throw b;
          }, ka = "object" == typeof window, A = "function" == typeof importScripts, B = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, D = v.ENVIRONMENT_IS_PTHREAD || false, E = "";
          function la(a) {
            return v.locateFile ? v.locateFile(a, E) : E + a;
          }
          var ma, G, H;
          if (B) {
            var fs = (init_fs(), __toCommonJS(fs_exports)), na = (init_path(), __toCommonJS(path_exports));
            E = A ? na.dirname(E) + "/" : __dirname + "/";
            ma = (a, b) => {
              a = I(a) ? new URL(a) : na.normalize(a);
              return fs.readFileSync(a, b ? void 0 : "utf8");
            };
            H = (a) => {
              a = ma(a, true);
              a.buffer || (a = new Uint8Array(a));
              return a;
            };
            G = (a, b, c, d = true) => {
              a = I(a) ? new URL(a) : na.normalize(a);
              fs.readFile(a, d ? void 0 : "utf8", (h, g) => {
                h ? c(h) : b(d ? g.buffer : g);
              });
            };
            !v.thisProgram && 1 < process.argv.length && (ja = process.argv[1].replace(/\\/g, "/"));
            process.argv.slice(2);
            z = (a, b) => {
              process.exitCode = a;
              throw b;
            };
            global.Worker = require_worker_threads().Worker;
          } else if (ka || A)
            A ? E = self.location.href : "undefined" != typeof document && document.currentScript && (E = document.currentScript.src), typeof _scriptDir !== "undefined" && _scriptDir && (E = _scriptDir), E.startsWith("blob:") ? E = "" : E = E.substr(0, E.replace(/[?#].*/, "").lastIndexOf("/") + 1), B || (ma = (a) => {
              var b = new XMLHttpRequest();
              b.open("GET", a, false);
              b.send(null);
              return b.responseText;
            }, A && (H = (a) => {
              var b = new XMLHttpRequest();
              b.open("GET", a, false);
              b.responseType = "arraybuffer";
              b.send(null);
              return new Uint8Array(b.response);
            }), G = (a, b, c) => {
              var d = new XMLHttpRequest();
              d.open("GET", a, true);
              d.responseType = "arraybuffer";
              d.onload = () => {
                200 == d.status || 0 == d.status && d.response ? b(d.response) : c();
              };
              d.onerror = c;
              d.send(null);
            });
          B && "undefined" == typeof performance && (global.performance = require_perf_hooks().performance);
          var oa = console.log.bind(console), pa = console.error.bind(console);
          B && (oa = (...a) => fs.writeSync(1, a.join(" ") + "\n"), pa = (...a) => fs.writeSync(2, a.join(" ") + "\n"));
          var qa = oa, J = pa;
          Object.assign(v, ia);
          ia = null;
          var e, ra, K = false, L, l, ba, ca, da, fa;
          function m() {
            var a = e.buffer;
            v.HEAP8 = l = new Int8Array(a);
            v.HEAP16 = new Int16Array(a);
            v.HEAPU8 = ba = new Uint8Array(a);
            v.HEAPU16 = new Uint16Array(a);
            v.HEAP32 = ca = new Int32Array(a);
            v.HEAPU32 = da = new Uint32Array(a);
            v.HEAPF32 = new Float32Array(a);
            v.HEAPF64 = fa = new Float64Array(a);
          }
          var sa = 16777216;
          if (D)
            e = v.wasmMemory;
          else if (v.wasmMemory)
            e = v.wasmMemory;
          else if (e = new WebAssembly.Memory({ initial: sa / 65536, maximum: 65536, shared: true }), !(e.buffer instanceof SharedArrayBuffer))
            throw J("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 && J("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"), Error("bad memory");
          m();
          sa = e.buffer.byteLength;
          var ta = [], ua = [], va = [], M = 0, wa = null, N = null;
          function xa() {
            M--;
            if (0 == M && (null !== wa && (clearInterval(wa), wa = null), N)) {
              var a = N;
              N = null;
              a();
            }
          }
          function ya(a) {
            a = "Aborted(" + a + ")";
            J(a);
            K = true;
            L = 1;
            a = new WebAssembly.RuntimeError(a + ". Build with -sASSERTIONS for more info.");
            x(a);
            throw a;
          }
          var za = (a) => a.startsWith("data:application/octet-stream;base64,"), I = (a) => a.startsWith("file://"), O;
          O = "ort-wasm-threaded.wasm";
          za(O) || (O = la(O));
          function Aa(a) {
            if (H)
              return H(a);
            throw "both async and sync fetching of the wasm failed";
          }
          function Ba(a) {
            if (ka || A) {
              if ("function" == typeof fetch && !I(a))
                return fetch(a, { credentials: "same-origin" }).then((b) => {
                  if (!b.ok)
                    throw `failed to load wasm binary file at '${a}'`;
                  return b.arrayBuffer();
                }).catch(() => Aa(a));
              if (G)
                return new Promise((b, c) => {
                  G(a, (d) => b(new Uint8Array(d)), c);
                });
            }
            return Promise.resolve().then(() => Aa(a));
          }
          function Ca(a, b, c) {
            return Ba(a).then((d) => WebAssembly.instantiate(d, b)).then(c, (d) => {
              J(`failed to asynchronously prepare wasm: ${d}`);
              ya(d);
            });
          }
          function Da(a, b) {
            var c = O;
            return "function" != typeof WebAssembly.instantiateStreaming || za(c) || I(c) || B || "function" != typeof fetch ? Ca(c, a, b) : fetch(c, { credentials: "same-origin" }).then((d) => WebAssembly.instantiateStreaming(d, a).then(b, function(h) {
              J(`wasm streaming compile failed: ${h}`);
              J("falling back to ArrayBuffer instantiation");
              return Ca(c, a, b);
            }));
          }
          var P, Ea = { 799444: (a, b, c, d) => {
            if ("undefined" == typeof v || !v.bb)
              return 1;
            a = Q(a >>> 0);
            a.startsWith("./") && (a = a.substring(2));
            a = v.bb.get(a);
            if (!a)
              return 2;
            b >>>= 0;
            c >>>= 0;
            d >>>= 0;
            if (b + c > a.byteLength)
              return 3;
            try {
              return n().set(a.subarray(b, b + c), d >>> 0), 0;
            } catch {
              return 4;
            }
          } };
          function R(a) {
            this.name = "ExitStatus";
            this.message = `Program terminated with exit(${a})`;
            this.status = a;
          }
          var Fa = (a) => {
            a.terminate();
            a.onmessage = () => {
            };
          }, Ha = (a) => {
            0 == S.Oa.length && (Ga(), S.Xa(S.Oa[0]));
            var b = S.Oa.pop();
            if (!b)
              return 6;
            S.Pa.push(b);
            S.La[a.Na] = b;
            b.Na = a.Na;
            var c = { cmd: "run", start_routine: a.gb, arg: a.cb, pthread_ptr: a.Na };
            B && b.unref();
            b.postMessage(c, a.mb);
            return 0;
          }, T = 0, Ja = (a) => {
            var b = Ia();
            a = a();
            U(b);
            return a;
          }, V = (a, b, ...c) => Ja(() => {
            for (var d = c.length, h = Ka(8 * d), g = h >>> 3, k = 0; k < c.length; k++) {
              var t = c[k];
              ea()[g + k >>> 0] = t;
            }
            return La(a, 0, d, h, b);
          });
          function Ma(a) {
            if (D)
              return V(0, 1, a);
            L = a;
            0 < T || (S.hb(), v.onExit?.(a), K = true);
            z(a, new R(a));
          }
          var Oa = (a) => {
            L = a;
            if (D)
              throw Na(a), "unwind";
            Ma(a);
          };
          function Pa() {
            for (var a = v.numThreads; a--; )
              Ga();
            ta.unshift(() => {
              M++;
              Qa(() => xa());
            });
          }
          function Ga() {
            var a = la("ort-wasm-threaded.worker.js");
            a = new Worker(a);
            S.Oa.push(a);
          }
          function Qa(a) {
            D ? a() : Promise.all(S.Oa.map(S.Xa)).then(a);
          }
          var S = { Oa: [], Pa: [], ab: [], La: {}, Va() {
            D ? (S.receiveObjectTransfer = S.fb, S.threadInitTLS = S.$a, S.setExitStatus = S.Za) : Pa();
          }, Za: (a) => L = a, pb: ["$terminateWorker"], hb: () => {
            for (var a of S.Pa)
              Fa(a);
            for (a of S.Oa)
              Fa(a);
            S.Oa = [];
            S.Pa = [];
            S.La = [];
          }, Ya: (a) => {
            var b = a.Na;
            delete S.La[b];
            S.Oa.push(a);
            S.Pa.splice(S.Pa.indexOf(a), 1);
            a.Na = 0;
            Ra(b);
          }, fb() {
          }, $a() {
            S.ab.forEach((a) => a());
          }, Xa: (a) => new Promise((b) => {
            a.onmessage = (g) => {
              g = g.data;
              var k = g.cmd;
              if (g.targetThread && g.targetThread != W()) {
                var t = S.La[g.targetThread];
                t ? t.postMessage(g, g.transferList) : J(`Internal error! Worker sent a message "${k}" to target pthread ${g.targetThread}, but that thread no longer exists!`);
              } else if ("checkMailbox" === k)
                Sa();
              else if ("spawnThread" === k)
                Ha(g);
              else if ("cleanupThread" === k)
                S.Ya(S.La[g.thread]);
              else if ("killThread" === k)
                g = g.thread, k = S.La[g], delete S.La[g], Fa(k), Ra(g), S.Pa.splice(S.Pa.indexOf(k), 1), k.Na = 0;
              else if ("cancelThread" === k)
                S.La[g.thread].postMessage({ cmd: "cancel" });
              else if ("loaded" === k)
                a.loaded = true, B && !a.Na && a.unref(), b(a);
              else if ("alert" === k)
                alert(`Thread ${g.threadId}: ${g.text}`);
              else if ("setimmediate" === g.target)
                a.postMessage(g);
              else if ("callHandler" === k)
                v[g.handler](...g.args);
              else
                k && J(`worker sent an unknown command ${k}`);
            };
            a.onerror = (g) => {
              J(`${"worker sent an error!"} ${g.filename}:${g.lineno}: ${g.message}`);
              throw g;
            };
            B && (a.on("message", (g) => a.onmessage({ data: g })), a.on("error", (g) => a.onerror(g)));
            var c = [], d = ["onExit"], h;
            for (h of d)
              v.hasOwnProperty(h) && c.push(h);
            a.postMessage({ cmd: "load", handlers: c, urlOrBlob: v.mainScriptUrlOrBlob || _scriptDir, wasmMemory: e, wasmModule: ra });
          }) };
          v.PThread = S;
          var Ta = (a) => {
            for (; 0 < a.length; )
              a.shift()(v);
          };
          v.establishStackSpace = () => {
            var a = W(), b = r()[a + 52 >>> 2 >>> 0];
            a = r()[a + 56 >>> 2 >>> 0];
            Ua(b, b - a);
            U(b);
          };
          function Na(a) {
            if (D)
              return V(1, 0, a);
            Oa(a);
          }
          var Va = [], Wa;
          v.invokeEntryPoint = (a, b) => {
            T = 0;
            var c = Va[a];
            c || (a >= Va.length && (Va.length = a + 1), Va[a] = c = Wa.get(a));
            a = c(b);
            0 < T ? S.Za(a) : Xa(a);
          };
          class Ya {
            constructor(a) {
              this.Ua = a - 24;
            }
            Va(a, b) {
              r()[this.Ua + 16 >>> 2 >>> 0] = 0;
              r()[this.Ua + 4 >>> 2 >>> 0] = a;
              r()[this.Ua + 8 >>> 2 >>> 0] = b;
            }
          }
          var Za = 0, $a = 0;
          function ab(a, b, c, d) {
            return D ? V(2, 1, a, b, c, d) : bb(a, b, c, d);
          }
          function bb(a, b, c, d) {
            a >>>= 0;
            b >>>= 0;
            c >>>= 0;
            d >>>= 0;
            if ("undefined" == typeof SharedArrayBuffer)
              return J("Current environment does not support SharedArrayBuffer, pthreads are not available!"), 6;
            var h = [];
            if (D && 0 === h.length)
              return ab(a, b, c, d);
            a = { gb: c, Na: a, cb: d, mb: h };
            return D ? (a.ob = "spawnThread", postMessage(a, h), 0) : Ha(a);
          }
          var cb = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0, db = (a, b, c) => {
            b >>>= 0;
            var d = b + c;
            for (c = b; a[c] && !(c >= d); )
              ++c;
            if (16 < c - b && a.buffer && cb)
              return cb.decode(a.buffer instanceof SharedArrayBuffer ? a.slice(b, c) : a.subarray(b, c));
            for (d = ""; b < c; ) {
              var h = a[b++];
              if (h & 128) {
                var g = a[b++] & 63;
                if (192 == (h & 224))
                  d += String.fromCharCode((h & 31) << 6 | g);
                else {
                  var k = a[b++] & 63;
                  h = 224 == (h & 240) ? (h & 15) << 12 | g << 6 | k : (h & 7) << 18 | g << 12 | k << 6 | a[b++] & 63;
                  65536 > h ? d += String.fromCharCode(h) : (h -= 65536, d += String.fromCharCode(55296 | h >> 10, 56320 | h & 1023));
                }
              } else
                d += String.fromCharCode(h);
            }
            return d;
          }, Q = (a, b) => (a >>>= 0) ? db(n(), a, b) : "";
          function eb(a, b, c) {
            return D ? V(3, 1, a, b, c) : 0;
          }
          function fb(a, b) {
            if (D)
              return V(4, 1, a, b);
          }
          var gb = (a) => {
            for (var b = 0, c = 0; c < a.length; ++c) {
              var d = a.charCodeAt(c);
              127 >= d ? b++ : 2047 >= d ? b += 2 : 55296 <= d && 57343 >= d ? (b += 4, ++c) : b += 3;
            }
            return b;
          }, hb = (a, b, c, d) => {
            c >>>= 0;
            if (!(0 < d))
              return 0;
            var h = c;
            d = c + d - 1;
            for (var g = 0; g < a.length; ++g) {
              var k = a.charCodeAt(g);
              if (55296 <= k && 57343 >= k) {
                var t = a.charCodeAt(++g);
                k = 65536 + ((k & 1023) << 10) | t & 1023;
              }
              if (127 >= k) {
                if (c >= d)
                  break;
                b[c++ >>> 0] = k;
              } else {
                if (2047 >= k) {
                  if (c + 1 >= d)
                    break;
                  b[c++ >>> 0] = 192 | k >> 6;
                } else {
                  if (65535 >= k) {
                    if (c + 2 >= d)
                      break;
                    b[c++ >>> 0] = 224 | k >> 12;
                  } else {
                    if (c + 3 >= d)
                      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 - h;
          }, X = (a, b, c) => hb(a, n(), b, c);
          function ib(a, b) {
            if (D)
              return V(5, 1, a, b);
          }
          function jb(a, b, c) {
            if (D)
              return V(6, 1, a, b, c);
          }
          function kb(a, b, c) {
            return D ? V(7, 1, a, b, c) : 0;
          }
          function lb(a, b) {
            if (D)
              return V(8, 1, a, b);
          }
          function mb(a, b, c) {
            if (D)
              return V(9, 1, a, b, c);
          }
          function nb(a, b, c, d) {
            if (D)
              return V(10, 1, a, b, c, d);
          }
          function ob(a, b, c, d) {
            if (D)
              return V(11, 1, a, b, c, d);
          }
          function pb(a, b, c, d) {
            if (D)
              return V(12, 1, a, b, c, d);
          }
          function qb(a) {
            if (D)
              return V(13, 1, a);
          }
          function rb(a, b) {
            if (D)
              return V(14, 1, a, b);
          }
          function sb(a, b, c) {
            if (D)
              return V(15, 1, a, b, c);
          }
          function tb(a) {
            a >>>= 0;
            "function" === typeof Atomics.nb && (Atomics.nb(p(), a >>> 2, a).value.then(Sa), a += 128, Atomics.store(p(), a >>> 2, 1));
          }
          v.__emscripten_thread_mailbox_await = tb;
          var Sa = () => {
            var a = W();
            if (a && (tb(a), a = ub, !K))
              try {
                if (a(), !(0 < T))
                  try {
                    D ? Xa(L) : Oa(L);
                  } catch (b) {
                    b instanceof R || "unwind" == b || z(1, b);
                  }
              } catch (b) {
                b instanceof R || "unwind" == b || z(1, b);
              }
          };
          v.checkMailbox = Sa;
          var vb = [], Y = (a) => 0 === a % 4 && (0 !== a % 100 || 0 === a % 400), wb = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], xb = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
          function yb(a, b, c, d, h, g, k, t) {
            return D ? V(16, 1, a, b, c, d, h, g, k, t) : -52;
          }
          function zb(a, b, c, d, h, g, k) {
            if (D)
              return V(17, 1, a, b, c, d, h, g, k);
          }
          var Ab = [], Bb = {}, Db = () => {
            if (!Cb) {
              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", _: ja || "./this.program" }, b;
              for (b in Bb)
                void 0 === Bb[b] ? delete a[b] : a[b] = Bb[b];
              var c = [];
              for (b in a)
                c.push(`${b}=${a[b]}`);
              Cb = c;
            }
            return Cb;
          }, Cb;
          function Eb(a, b) {
            if (D)
              return V(18, 1, a, b);
            a >>>= 0;
            b >>>= 0;
            var c = 0;
            Db().forEach((d, h) => {
              var g = b + c;
              h = r()[a + 4 * h >>> 2 >>> 0] = g;
              for (g = 0; g < d.length; ++g)
                aa()[h++ >>> 0] = d.charCodeAt(g);
              aa()[h >>> 0] = 0;
              c += d.length + 1;
            });
            return 0;
          }
          function Ib(a, b) {
            if (D)
              return V(19, 1, a, b);
            a >>>= 0;
            b >>>= 0;
            var c = Db();
            r()[a >>> 2 >>> 0] = c.length;
            var d = 0;
            c.forEach((h) => d += h.length + 1);
            r()[b >>> 2 >>> 0] = d;
            return 0;
          }
          function Jb(a) {
            return D ? V(20, 1, a) : 52;
          }
          function Kb(a, b, c, d) {
            return D ? V(21, 1, a, b, c, d) : 52;
          }
          function Lb(a, b, c, d, h) {
            return D ? V(22, 1, a, b, c, d, h) : 70;
          }
          var Mb = [null, [], []];
          function Nb(a, b, c, d) {
            if (D)
              return V(23, 1, a, b, c, d);
            b >>>= 0;
            c >>>= 0;
            d >>>= 0;
            for (var h = 0, g = 0; g < c; g++) {
              var k = r()[b >>> 2 >>> 0], t = r()[b + 4 >>> 2 >>> 0];
              b += 8;
              for (var C = 0; C < t; C++) {
                var w = n()[k + C >>> 0], y = Mb[a];
                0 === w || 10 === w ? ((1 === a ? qa : J)(db(y, 0)), y.length = 0) : y.push(w);
              }
              h += t;
            }
            r()[d >>> 2 >>> 0] = h;
            return 0;
          }
          var Ob = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], Pb = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
          function Qb(a) {
            var b = Array(gb(a) + 1);
            hb(a, b, 0, b.length);
            return b;
          }
          var Rb = (a, b) => {
            aa().set(a, b >>> 0);
          };
          function Sb(a, b, c, d) {
            function h(f, q, u) {
              for (f = "number" == typeof f ? f.toString() : f || ""; f.length < q; )
                f = u[0] + f;
              return f;
            }
            function g(f, q) {
              return h(f, q, "0");
            }
            function k(f, q) {
              function u(Fb) {
                return 0 > Fb ? -1 : 0 < Fb ? 1 : 0;
              }
              var F;
              0 === (F = u(f.getFullYear() - q.getFullYear())) && 0 === (F = u(f.getMonth() - q.getMonth())) && (F = u(f.getDate() - q.getDate()));
              return F;
            }
            function t(f) {
              switch (f.getDay()) {
                case 0:
                  return new Date(f.getFullYear() - 1, 11, 29);
                case 1:
                  return f;
                case 2:
                  return new Date(f.getFullYear(), 0, 3);
                case 3:
                  return new Date(
                    f.getFullYear(),
                    0,
                    2
                  );
                case 4:
                  return new Date(f.getFullYear(), 0, 1);
                case 5:
                  return new Date(f.getFullYear() - 1, 11, 31);
                case 6:
                  return new Date(f.getFullYear() - 1, 11, 30);
              }
            }
            function C(f) {
              var q = f.Qa;
              for (f = new Date(new Date(f.Ra + 1900, 0, 1).getTime()); 0 < q; ) {
                var u = f.getMonth(), F = (Y(f.getFullYear()) ? Ob : Pb)[u];
                if (q > F - f.getDate())
                  q -= F - f.getDate() + 1, f.setDate(1), 11 > u ? f.setMonth(u + 1) : (f.setMonth(0), f.setFullYear(f.getFullYear() + 1));
                else {
                  f.setDate(f.getDate() + q);
                  break;
                }
              }
              u = new Date(f.getFullYear() + 1, 0, 4);
              q = t(new Date(
                f.getFullYear(),
                0,
                4
              ));
              u = t(u);
              return 0 >= k(q, f) ? 0 >= k(u, f) ? f.getFullYear() + 1 : f.getFullYear() : f.getFullYear() - 1;
            }
            a >>>= 0;
            b >>>= 0;
            c >>>= 0;
            d >>>= 0;
            var w = r()[d + 40 >>> 2 >>> 0];
            d = { kb: p()[d >>> 2 >>> 0], jb: p()[d + 4 >>> 2 >>> 0], Sa: p()[d + 8 >>> 2 >>> 0], Wa: p()[d + 12 >>> 2 >>> 0], Ta: p()[d + 16 >>> 2 >>> 0], Ra: p()[d + 20 >>> 2 >>> 0], Ma: p()[d + 24 >>> 2 >>> 0], Qa: p()[d + 28 >>> 2 >>> 0], qb: p()[d + 32 >>> 2 >>> 0], ib: p()[d + 36 >>> 2 >>> 0], lb: w ? Q(w) : "" };
            c = Q(c);
            w = {
              "%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 y in w)
              c = c.replace(new RegExp(y, "g"), w[y]);
            var Gb = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), Hb = "January February March April May June July August September October November December".split(" ");
            w = {
              "%a": (f) => Gb[f.Ma].substring(0, 3),
              "%A": (f) => Gb[f.Ma],
              "%b": (f) => Hb[f.Ta].substring(0, 3),
              "%B": (f) => Hb[f.Ta],
              "%C": (f) => g((f.Ra + 1900) / 100 | 0, 2),
              "%d": (f) => g(f.Wa, 2),
              "%e": (f) => h(f.Wa, 2, " "),
              "%g": (f) => C(f).toString().substring(2),
              "%G": C,
              "%H": (f) => g(f.Sa, 2),
              "%I": (f) => {
                f = f.Sa;
                0 == f ? f = 12 : 12 < f && (f -= 12);
                return g(f, 2);
              },
              "%j": (f) => {
                for (var q = 0, u = 0; u <= f.Ta - 1; q += (Y(f.Ra + 1900) ? Ob : Pb)[u++])
                  ;
                return g(f.Wa + q, 3);
              },
              "%m": (f) => g(f.Ta + 1, 2),
              "%M": (f) => g(f.jb, 2),
              "%n": () => "\n",
              "%p": (f) => 0 <= f.Sa && 12 > f.Sa ? "AM" : "PM",
              "%S": (f) => g(f.kb, 2),
              "%t": () => "	",
              "%u": (f) => f.Ma || 7,
              "%U": (f) => g(Math.floor((f.Qa + 7 - f.Ma) / 7), 2),
              "%V": (f) => {
                var q = Math.floor((f.Qa + 7 - (f.Ma + 6) % 7) / 7);
                2 >= (f.Ma + 371 - f.Qa - 2) % 7 && q++;
                if (q)
                  53 == q && (u = (f.Ma + 371 - f.Qa) % 7, 4 == u || 3 == u && Y(f.Ra) || (q = 1));
                else {
                  q = 52;
                  var u = (f.Ma + 7 - f.Qa - 1) % 7;
                  (4 == u || 5 == u && Y(f.Ra % 400 - 1)) && q++;
                }
                return g(q, 2);
              },
              "%w": (f) => f.Ma,
              "%W": (f) => g(Math.floor((f.Qa + 7 - (f.Ma + 6) % 7) / 7), 2),
              "%y": (f) => (f.Ra + 1900).toString().substring(2),
              "%Y": (f) => f.Ra + 1900,
              "%z": (f) => {
                f = f.ib;
                var q = 0 <= f;
                f = Math.abs(f) / 60;
                return (q ? "+" : "-") + String("0000" + (f / 60 * 100 + f % 60)).slice(-4);
              },
              "%Z": (f) => f.lb,
              "%%": () => "%"
            };
            c = c.replace(
              /%%/g,
              "\0\0"
            );
            for (y in w)
              c.includes(y) && (c = c.replace(new RegExp(y, "g"), w[y](d)));
            c = c.replace(/\0\0/g, "%");
            y = Qb(c);
            if (y.length > b)
              return 0;
            Rb(y, a);
            return y.length - 1;
          }
          S.Va();
          var Tb = [Ma, Na, ab, eb, fb, ib, jb, kb, lb, mb, nb, ob, pb, qb, rb, sb, yb, zb, Eb, Ib, Jb, Kb, Lb, Nb], Wb = {
            b: function(a, b, c) {
              a >>>= 0;
              new Ya(a).Va(b >>> 0, c >>> 0);
              Za = a;
              $a++;
              throw Za;
            },
            L: function(a) {
              Ub(a >>> 0, !A, 1, !ka, 131072, false);
              S.$a();
            },
            j: function(a) {
              a >>>= 0;
              D ? postMessage({ cmd: "cleanupThread", thread: a }) : S.Ya(S.La[a]);
            },
            H: bb,
            h: eb,
            S: fb,
            D: ib,
            F: jb,
            T: kb,
            Q: lb,
            J: mb,
            P: nb,
            n: ob,
            E: pb,
            B: qb,
            R: rb,
            C: sb,
            p: () => 1,
            z: function(a, b) {
              a >>>= 0;
              a == b >>> 0 ? setTimeout(Sa) : D ? postMessage({ targetThread: a, cmd: "checkMailbox" }) : (a = S.La[a]) && a.postMessage({ cmd: "checkMailbox" });
            },
            I: function(a, b, c, d, h) {
              b >>>= 0;
              c >>>= 0;
              vb.length = d;
              h = h >>> 0 >>> 3;
              for (var g = 0; g < d; g++)
                vb[g] = ea()[h + g >>> 0];
              a = b ? Ea[b] : Tb[a];
              S.eb = c;
              c = a(...vb);
              S.eb = 0;
              return c;
            },
            K: tb,
            o: function(a) {
              B && S.La[a >>> 0].ref();
            },
            s: function(a, b, c) {
              a = b + 2097152 >>> 0 < 4194305 - !!a ? (a >>> 0) + 4294967296 * b : NaN;
              c >>>= 0;
              a = new Date(1e3 * a);
              p()[c >>> 2 >>> 0] = a.getUTCSeconds();
              p()[c + 4 >>> 2 >>> 0] = a.getUTCMinutes();
              p()[c + 8 >>> 2 >>> 0] = a.getUTCHours();
              p()[c + 12 >>> 2 >>> 0] = a.getUTCDate();
              p()[c + 16 >>> 2 >>> 0] = a.getUTCMonth();
              p()[c + 20 >>> 2 >>> 0] = a.getUTCFullYear() - 1900;
              p()[c + 24 >>> 2 >>> 0] = a.getUTCDay();
              a = (a.getTime() - Date.UTC(a.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0;
              p()[c + 28 >>> 2 >>> 0] = a;
            },
            t: function(a, b, c) {
              a = b + 2097152 >>> 0 < 4194305 - !!a ? (a >>> 0) + 4294967296 * b : NaN;
              c >>>= 0;
              a = new Date(1e3 * a);
              p()[c >>> 2 >>> 0] = a.getSeconds();
              p()[c + 4 >>> 2 >>> 0] = a.getMinutes();
              p()[c + 8 >>> 2 >>> 0] = a.getHours();
              p()[c + 12 >>> 2 >>> 0] = a.getDate();
              p()[c + 16 >>> 2 >>> 0] = a.getMonth();
              p()[c + 20 >>> 2 >>> 0] = a.getFullYear() - 1900;
              p()[c + 24 >>> 2 >>> 0] = a.getDay();
              b = (Y(a.getFullYear()) ? wb : xb)[a.getMonth()] + a.getDate() - 1 | 0;
              p()[c + 28 >>> 2 >>> 0] = b;
              p()[c + 36 >>> 2 >>> 0] = -(60 * a.getTimezoneOffset());
              b = new Date(a.getFullYear(), 6, 1).getTimezoneOffset();
              var d = new Date(a.getFullYear(), 0, 1).getTimezoneOffset();
              a = (b != d && a.getTimezoneOffset() == Math.min(d, b)) | 0;
              p()[c + 32 >>> 2 >>> 0] = a;
            },
            u: function(a) {
              a >>>= 0;
              var b = new Date(p()[a + 20 >>> 2 >>> 0] + 1900, p()[a + 16 >>> 2 >>> 0], p()[a + 12 >>> 2 >>> 0], p()[a + 8 >>> 2 >>> 0], p()[a + 4 >>> 2 >>> 0], p()[a >>> 2 >>> 0], 0), c = p()[a + 32 >>> 2 >>> 0], d = b.getTimezoneOffset(), h = new Date(b.getFullYear(), 6, 1).getTimezoneOffset(), g = new Date(
                b.getFullYear(),
                0,
                1
              ).getTimezoneOffset(), k = Math.min(g, h);
              0 > c ? p()[a + 32 >>> 2 >>> 0] = Number(h != g && k == d) : 0 < c != (k == d) && (h = Math.max(g, h), b.setTime(b.getTime() + 6e4 * ((0 < c ? k : h) - d)));
              p()[a + 24 >>> 2 >>> 0] = b.getDay();
              c = (Y(b.getFullYear()) ? wb : xb)[b.getMonth()] + b.getDate() - 1 | 0;
              p()[a + 28 >>> 2 >>> 0] = c;
              p()[a >>> 2 >>> 0] = b.getSeconds();
              p()[a + 4 >>> 2 >>> 0] = b.getMinutes();
              p()[a + 8 >>> 2 >>> 0] = b.getHours();
              p()[a + 12 >>> 2 >>> 0] = b.getDate();
              p()[a + 16 >>> 2 >>> 0] = b.getMonth();
              p()[a + 20 >>> 2 >>> 0] = b.getYear();
              a = b.getTime();
              a = isNaN(a) ? -1 : a / 1e3;
              Vb((P = a, 1 <= +Math.abs(P) ? 0 < P ? +Math.floor(P / 4294967296) >>> 0 : ~~+Math.ceil((P - +(~~P >>> 0)) / 4294967296) >>> 0 : 0));
              return a >>> 0;
            },
            q: yb,
            r: zb,
            y: function(a, b, c, d) {
              a >>>= 0;
              b >>>= 0;
              c >>>= 0;
              d >>>= 0;
              var h = (/* @__PURE__ */ new Date()).getFullYear(), g = new Date(h, 0, 1), k = new Date(h, 6, 1);
              h = g.getTimezoneOffset();
              var t = k.getTimezoneOffset(), C = Math.max(h, t);
              r()[a >>> 2 >>> 0] = 60 * C;
              p()[b >>> 2 >>> 0] = Number(h != t);
              a = (w) => w.toLocaleTimeString(void 0, { hour12: false, timeZoneName: "short" }).split(" ")[1];
              g = a(g);
              k = a(k);
              t < h ? (X(g, c, 17), X(k, d, 17)) : (X(g, d, 17), X(k, c, 17));
            },
            c: () => {
              ya("");
            },
            O: function(a, b, c) {
              a >>>= 0;
              b >>>= 0;
              c >>>= 0;
              Ab.length = 0;
              for (var d; d = n()[b++ >>> 0]; ) {
                var h = 105 != d;
                h &= 112 != d;
                c += h && c % 8 ? 4 : 0;
                Ab.push(112 == d ? r()[c >>> 2 >>> 0] : 105 == d ? p()[c >>> 2 >>> 0] : ea()[c >>> 3 >>> 0]);
                c += h ? 8 : 4;
              }
              return Ea[a](...Ab);
            },
            k: () => {
            },
            i: () => Date.now(),
            U: () => {
              T += 1;
              throw "unwind";
            },
            A: function() {
              return 4294901760;
            },
            e: () => performance.timeOrigin + performance.now(),
            f: () => B ? (init_os(), __toCommonJS(os_exports)).cpus().length : navigator.hardwareConcurrency,
            x: function(a) {
              a >>>= 0;
              var b = n().length;
              if (a <= b || 4294901760 < a)
                return false;
              for (var c = 1; 4 >= c; c *= 2) {
                var d = b * (1 + 0.2 / c);
                d = Math.min(d, a + 100663296);
                var h = Math;
                d = Math.max(a, d);
                a: {
                  h = (h.min.call(h, 4294901760, d + (65536 - d % 65536) % 65536) - e.buffer.byteLength + 65535) / 65536;
                  try {
                    e.grow(h);
                    m();
                    var g = 1;
                    break a;
                  } catch (k) {
                  }
                  g = void 0;
                }
                if (g)
                  return true;
              }
              return false;
            },
            M: Eb,
            N: Ib,
            G: Oa,
            g: Jb,
            m: Kb,
            v: Lb,
            l: Nb,
            a: e || v.wasmMemory,
            w: Sb,
            d: function(a, b, c, d) {
              return Sb(a >>> 0, b >>> 0, c >>> 0, d >>> 0);
            }
          }, Z = function() {
            function a(c, d) {
              Z = c.exports;
              Z = Xb();
              S.ab.push(Z.ya);
              Wa = Z.za;
              ua.unshift(Z.V);
              ra = d;
              xa();
              return Z;
            }
            var b = { a: Wb };
            M++;
            if (v.instantiateWasm)
              try {
                return v.instantiateWasm(
                  b,
                  a
                );
              } catch (c) {
                J(`Module.instantiateWasm callback failed with error: ${c}`), x(c);
              }
            Da(b, function(c) {
              a(c.instance, c.module);
            }).catch(x);
            return {};
          }();
          v._OrtInit = (a, b) => (v._OrtInit = Z.W)(a, b);
          v._OrtGetLastError = (a, b) => (v._OrtGetLastError = Z.X)(a, b);
          v._OrtCreateSessionOptions = (a, b, c, d, h, g, k, t, C, w) => (v._OrtCreateSessionOptions = Z.Y)(a, b, c, d, h, g, k, t, C, w);
          v._OrtAppendExecutionProvider = (a, b) => (v._OrtAppendExecutionProvider = Z.Z)(a, b);
          v._OrtAddFreeDimensionOverride = (a, b, c) => (v._OrtAddFreeDimensionOverride = Z._)(a, b, c);
          v._OrtAddSessionConfigEntry = (a, b, c) => (v._OrtAddSessionConfigEntry = Z.$)(a, b, c);
          v._OrtReleaseSessionOptions = (a) => (v._OrtReleaseSessionOptions = Z.aa)(a);
          v._OrtCreateSession = (a, b, c) => (v._OrtCreateSession = Z.ba)(a, b, c);
          v._OrtReleaseSession = (a) => (v._OrtReleaseSession = Z.ca)(a);
          v._OrtGetInputOutputCount = (a, b, c) => (v._OrtGetInputOutputCount = Z.da)(a, b, c);
          v._OrtGetInputName = (a, b) => (v._OrtGetInputName = Z.ea)(a, b);
          v._OrtGetOutputName = (a, b) => (v._OrtGetOutputName = Z.fa)(a, b);
          v._OrtFree = (a) => (v._OrtFree = Z.ga)(a);
          v._OrtCreateTensor = (a, b, c, d, h, g) => (v._OrtCreateTensor = Z.ha)(a, b, c, d, h, g);
          v._OrtGetTensorData = (a, b, c, d, h) => (v._OrtGetTensorData = Z.ia)(a, b, c, d, h);
          v._OrtReleaseTensor = (a) => (v._OrtReleaseTensor = Z.ja)(a);
          v._OrtCreateRunOptions = (a, b, c, d) => (v._OrtCreateRunOptions = Z.ka)(a, b, c, d);
          v._OrtAddRunConfigEntry = (a, b, c) => (v._OrtAddRunConfigEntry = Z.la)(a, b, c);
          v._OrtReleaseRunOptions = (a) => (v._OrtReleaseRunOptions = Z.ma)(a);
          v._OrtCreateBinding = (a) => (v._OrtCreateBinding = Z.na)(a);
          v._OrtBindInput = (a, b, c) => (v._OrtBindInput = Z.oa)(a, b, c);
          v._OrtBindOutput = (a, b, c, d) => (v._OrtBindOutput = Z.pa)(a, b, c, d);
          v._OrtClearBoundOutputs = (a) => (v._OrtClearBoundOutputs = Z.qa)(a);
          v._OrtReleaseBinding = (a) => (v._OrtReleaseBinding = Z.ra)(a);
          v._OrtRunWithBinding = (a, b, c, d, h) => (v._OrtRunWithBinding = Z.sa)(a, b, c, d, h);
          v._OrtRun = (a, b, c, d, h, g, k, t) => (v._OrtRun = Z.ta)(a, b, c, d, h, g, k, t);
          v._OrtEndProfiling = (a) => (v._OrtEndProfiling = Z.ua)(a);
          var W = v._pthread_self = () => (W = v._pthread_self = Z.va)();
          v._malloc = (a) => (v._malloc = Z.wa)(a);
          v._free = (a) => (v._free = Z.xa)(a);
          v.__emscripten_tls_init = () => (v.__emscripten_tls_init = Z.ya)();
          var Ub = v.__emscripten_thread_init = (a, b, c, d, h, g) => (Ub = v.__emscripten_thread_init = Z.Aa)(a, b, c, d, h, g);
          v.__emscripten_thread_crashed = () => (v.__emscripten_thread_crashed = Z.Ba)();
          var La = (a, b, c, d, h) => (La = Z.Ca)(a, b, c, d, h), Ra = (a) => (Ra = Z.Da)(a), Xa = v.__emscripten_thread_exit = (a) => (Xa = v.__emscripten_thread_exit = Z.Ea)(a), ub = () => (ub = Z.Fa)(), Vb = (a) => (Vb = Z.Ga)(a), Ua = (a, b) => (Ua = Z.Ha)(a, b), U = (a) => (U = Z.Ia)(a), Ka = (a) => (Ka = Z.Ja)(a), Ia = () => (Ia = Z.Ka)();
          function Xb() {
            var a = Z;
            a = Object.assign({}, a);
            var b = (d) => () => d() >>> 0, c = (d) => (h) => d(h) >>> 0;
            a.va = b(a.va);
            a.wa = c(a.wa);
            a.emscripten_main_runtime_thread_id = b(a.emscripten_main_runtime_thread_id);
            a.Ja = c(a.Ja);
            a.Ka = b(a.Ka);
            return a;
          }
          v.wasmMemory = e;
          v.stackSave = () => Ia();
          v.stackRestore = (a) => U(a);
          v.stackAlloc = (a) => Ka(a);
          v.keepRuntimeAlive = () => 0 < T;
          v.UTF8ToString = Q;
          v.stringToUTF8 = X;
          v.lengthBytesUTF8 = gb;
          v.ExitStatus = R;
          v.PThread = S;
          var Yb;
          N = function Zb() {
            Yb || $b();
            Yb || (N = Zb);
          };
          function $b() {
            if (!(0 < M))
              if (D)
                ha(v), D || Ta(ua), startWorker(v);
              else {
                if (v.preRun)
                  for ("function" == typeof v.preRun && (v.preRun = [v.preRun]); v.preRun.length; )
                    ta.unshift(v.preRun.shift());
                Ta(ta);
                0 < M || Yb || (Yb = true, v.calledRun = true, K || (D || Ta(ua), ha(v), D || Ta(va)));
              }
          }
          $b();
          return readyPromise;
        };
      })();
      if (typeof exports2 === "object" && typeof module2 === "object")
        module2.exports = ortWasmThreaded;
      else if (typeof define === "function" && define["amd"])
        define([], () => ortWasmThreaded);
    }
  });

  // web/lib/wasm/binding/ort-wasm-threaded.worker.js
  var require_ort_wasm_threaded_worker = __commonJS({
    "web/lib/wasm/binding/ort-wasm-threaded.worker.js"(exports2, module2) {
      module2.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");var vm=require("vm");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:f=>vm.runInThisContext(fs.readFileSync(f,"utf8"),{filename:f}),postMessage:msg=>parentPort.postMessage(msg),performance:global.performance||{now:Date.now}})}var initializedJS=false;function threadPrintErr(...args){var text=args.join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+"\\n");return}console.error(text)}function threadAlert(...args){var text=args.join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=(info,receiveInstance)=>{var module=Module["wasmModule"];Module["wasmModule"]=null;var instance=new WebAssembly.Instance(module,info);return receiveInstance(instance)};self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let messageQueue=[];self.onmessage=e=>messageQueue.push(e);self.startWorker=instance=>{Module=instance;postMessage({"cmd":"loaded"});for(let msg of messageQueue){handleMessage(msg)}self.onmessage=handleMessage};Module["wasmModule"]=e.data.wasmModule;for(const handler of e.data.handlers){Module[handler]=(...args)=>{postMessage({cmd:"callHandler",handler:handler,args:args})}}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)}else if(e.data.cmd==="run"){Module["__emscripten_thread_init"](e.data.pthread_ptr,/*is_main=*/0,/*is_runtime=*/0,/*can_block=*/1);Module["__emscripten_thread_mailbox_await"](e.data.pthread_ptr);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInitTLS();if(!initializedJS){initializedJS=true}try{Module["invokeEntryPoint"](e.data.start_routine,e.data.arg)}catch(ex){if(ex!="unwind"){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==="checkMailbox"){if(initializedJS){Module["checkMailbox"]()}}else if(e.data.cmd){err(`worker.js received unknown command ${e.data.cmd}`);err(e.data)}}catch(ex){Module["__emscripten_thread_crashed"]?.();throw ex}}self.onmessage=handleMessage;\n';
    }
  });

  // web/lib/wasm/wasm-factory.ts
  var ortWasmFactory, ortWasmFactoryThreaded, wasm2, initialized, initializing, aborted, isMultiThreadSupported, isSimdSupported, getWasmFileName, initializeWebAssembly, getInstance;
  var init_wasm_factory = __esm({
    "web/lib/wasm/wasm-factory.ts"() {
      "use strict";
      init_node_path();
      if (false) {
        ortWasmFactory = null;
      } else {
        ortWasmFactory = true ? require_ort_wasm() : null;
      }
      ortWasmFactoryThreaded = true ? true ? require_ort_wasm_threaded() : null : ortWasmFactory;
      initialized = false;
      initializing = false;
      aborted = false;
      isMultiThreadSupported = (numThreads) => {
        if (numThreads === 1) {
          return false;
        }
        if (typeof SharedArrayBuffer === "undefined") {
          if (typeof self !== "undefined" && !self.crossOriginIsolated) {
            console.warn(
              "env.wasm.numThreads is set to " + numThreads + ", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."
            );
          }
          return false;
        }
        if (typeof process !== "undefined" && process.versions && process.versions.node) {
          console.warn(
            "env.wasm.numThreads is set to " + numThreads + ", however, currently onnxruntime-web does not support multi-threads in Node.js. Please consider using onnxruntime-node for performance critical scenarios."
          );
        }
        try {
          if (typeof MessageChannel !== "undefined") {
            new MessageChannel().port1.postMessage(new SharedArrayBuffer(1));
          }
          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;
        }
      };
      isSimdSupported = () => {
        try {
          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;
        }
      };
      getWasmFileName = (useSimd, useThreads) => {
        if (useSimd) {
          if (false) {
            return "ort-training-wasm-simd.wasm";
          }
          return useThreads ? "ort-wasm-simd-threaded.wasm" : "ort-wasm-simd.wasm";
        } else {
          return useThreads ? "ort-wasm-threaded.wasm" : "ort-wasm.wasm";
        }
      };
      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;
        const timeout = flags.initTimeout;
        const numThreads = flags.numThreads;
        const simd = flags.simd;
        const useThreads = isMultiThreadSupported(numThreads);
        const useSimd = simd && isSimdSupported();
        const wasmPaths = flags.wasmPaths;
        const wasmPrefixOverride = typeof wasmPaths === "string" ? wasmPaths : void 0;
        const wasmFileName = getWasmFileName(useSimd, useThreads);
        const wasmPathOverride = typeof wasmPaths === "object" ? wasmPaths[wasmFileName] : void 0;
        let isTimeout = false;
        const tasks = [];
        if (timeout > 0) {
          tasks.push(new Promise((resolve) => {
            setTimeout(() => {
              isTimeout = true;
              resolve();
            }, timeout);
          }));
        }
        tasks.push(new Promise((resolve, reject) => {
          const factory = useThreads ? ortWasmFactoryThreaded : ortWasmFactory;
          const config = {
            locateFile: (fileName, scriptDirectory) => {
              if (useThreads && fileName.endsWith(".worker.js") && typeof Blob !== "undefined") {
                return URL.createObjectURL(new Blob(
                  [
                    // This require() function is handled by esbuild plugin to load file content as string.
                    // eslint-disable-next-line @typescript-eslint/no-require-imports
                    require_ort_wasm_threaded_worker()
                  ],
                  { type: "text/javascript" }
                ));
              }
              if (fileName.endsWith(".wasm")) {
                if (wasmPathOverride) {
                  return wasmPathOverride;
                }
                const prefix = wasmPrefixOverride ?? scriptDirectory;
                if (false) {
                  if (wasmFileName === "ort-wasm-simd.wasm") {
                    return prefix + "ort-wasm-simd.jsep.wasm";
                  } else if (wasmFileName === "ort-wasm-simd-threaded.wasm") {
                    return prefix + "ort-wasm-simd-threaded.jsep.wasm";
                  }
                }
                return prefix + wasmFileName;
              }
              return scriptDirectory + fileName;
            }
          };
          if (useThreads) {
            config.numThreads = numThreads;
            if (typeof Blob === "undefined") {
              config.mainScriptUrlOrBlob = join(__dirname, "ort-wasm-threaded.js");
            } else {
              const scriptSourceCode = `var ortWasmThreaded=${factory.toString()};`;
              config.mainScriptUrlOrBlob = new Blob([scriptSourceCode], { type: "text/javascript" });
            }
          }
          factory(config).then(
            // wasm module initialized successfully
            (module2) => {
              initializing = false;
              initialized = true;
              wasm2 = module2;
              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`);
        }
      };
      getInstance = () => {
        if (initialized && wasm2) {
          return wasm2;
        }
        throw new Error("WebAssembly is not initialized yet.");
      };
    }
  });

  // web/lib/wasm/wasm-utils.ts
  var allocWasmString, iterateExtraOptions, checkLastError;
  var init_wasm_utils = __esm({
    "web/lib/wasm/wasm-utils.ts"() {
      "use strict";
      init_wasm_factory();
      allocWasmString = (data, allocs) => {
        const wasm3 = getInstance();
        const dataLength = wasm3.lengthBytesUTF8(data) + 1;
        const dataOffset = wasm3._malloc(dataLength);
        wasm3.stringToUTF8(data, dataOffset, dataLength);
        allocs.push(dataOffset);
        return dataOffset;
      };
      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 name2 = prefix ? prefix + key : key;
          if (typeof value === "object") {
            iterateExtraOptions(value, name2 + ".", seen, handler);
          } else if (typeof value === "string" || typeof value === "number") {
            handler(name2, value.toString());
          } else if (typeof value === "boolean") {
            handler(name2, value ? "1" : "0");
          } else {
            throw new Error(`Can't handle extra config type: ${typeof value}`);
          }
        });
      };
      checkLastError = (message) => {
        const wasm3 = getInstance();
        const stack = wasm3.stackSave();
        try {
          const paramsOffset = wasm3.stackAlloc(8);
          wasm3._OrtGetLastError(paramsOffset, paramsOffset + 4);
          const errorCode = wasm3.HEAP32[paramsOffset / 4];
          const errorMessagePointer = wasm3.HEAPU32[paramsOffset / 4 + 1];
          const errorMessage = errorMessagePointer ? wasm3.UTF8ToString(errorMessagePointer) : "";
          throw new Error(`${message} ERROR_CODE: ${errorCode}, ERROR_MESSAGE: ${errorMessage}`);
        } finally {
          wasm3.stackRestore(stack);
        }
      };
    }
  });

  // web/lib/wasm/run-options.ts
  var setRunOptions;
  var init_run_options = __esm({
    "web/lib/wasm/run-options.ts"() {
      "use strict";
      init_wasm_factory();
      init_wasm_utils();
      setRunOptions = (options) => {
        const wasm3 = getInstance();
        let runOptionsHandle = 0;
        const allocs = [];
        const runOptions = options || {};
        try {
          if (options?.logSeverityLevel === void 0) {
            runOptions.logSeverityLevel = 2;
          } 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?.logVerbosityLevel === void 0) {
            runOptions.logVerbosityLevel = 0;
          } else if (typeof options.logVerbosityLevel !== "number" || !Number.isInteger(options.logVerbosityLevel)) {
            throw new Error(`log verbosity level is not valid: ${options.logVerbosityLevel}`);
          }
          if (options?.terminate === void 0) {
            runOptions.terminate = false;
          }
          let tagDataOffset = 0;
          if (options?.tag !== void 0) {
            tagDataOffset = allocWasmString(options.tag, allocs);
          }
          runOptionsHandle = wasm3._OrtCreateRunOptions(
            runOptions.logSeverityLevel,
            runOptions.logVerbosityLevel,
            !!runOptions.terminate,
            tagDataOffset
          );
          if (runOptionsHandle === 0) {
            checkLastError("Can't create run options.");
          }
          if (options?.extra !== void 0) {
            iterateExtraOptions(options.extra, "", /* @__PURE__ */ new WeakSet(), (key, value) => {
              const keyDataOffset = allocWasmString(key, allocs);
              const valueDataOffset = allocWasmString(value, allocs);
              if (wasm3._OrtAddRunConfigEntry(runOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {
                checkLastError(`Can't set a run config entry: ${key} - ${value}.`);
              }
            });
          }
          return [runOptionsHandle, allocs];
        } catch (e) {
          if (runOptionsHandle !== 0) {
            wasm3._OrtReleaseRunOptions(runOptionsHandle);
          }
          allocs.forEach((alloc) => wasm3._free(alloc));
          throw e;
        }
      };
    }
  });

  // web/lib/wasm/session-options.ts
  var getGraphOptimzationLevel, getExecutionMode, appendDefaultOptions, setExecutionProviders, setSessionOptions;
  var init_session_options = __esm({
    "web/lib/wasm/session-options.ts"() {
      "use strict";
      init_wasm_factory();
      init_wasm_utils();
      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}`);
        }
      };
      getExecutionMode = (executionMode) => {
        switch (executionMode) {
          case "sequential":
            return 0;
          case "parallel":
            return 1;
          default:
            throw new Error(`unsupported execution mode: ${executionMode}`);
        }
      };
      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) {
          session.use_ort_model_bytes_directly = "1";
        }
        if (options.executionProviders && options.executionProviders.some((ep) => (typeof ep === "string" ? ep : ep.name) === "webgpu")) {
          options.enableMemPattern = false;
        }
      };
      setExecutionProviders = (sessionOptionsHandle, executionProviders, allocs) => {
        for (const ep of executionProviders) {
          let epName = typeof ep === "string" ? ep : ep.name;
          switch (epName) {
            case "webnn":
              epName = "WEBNN";
              if (typeof ep !== "string") {
                const webnnOptions = ep;
                if (webnnOptions?.deviceType) {
                  const keyDataOffset = allocWasmString("deviceType", allocs);
                  const valueDataOffset = allocWasmString(webnnOptions.deviceType, allocs);
                  if (getInstance()._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {
                    checkLastError(`Can't set a session config entry: 'deviceType' - ${webnnOptions.deviceType}.`);
                  }
                }
                if (webnnOptions?.numThreads) {
                  let numThreads = webnnOptions.numThreads;
                  if (typeof numThreads != "number" || !Number.isInteger(numThreads) || numThreads < 0) {
                    numThreads = 0;
                  }
                  const keyDataOffset = allocWasmString("numThreads", allocs);
                  const valueDataOffset = allocWasmString(numThreads.toString(), allocs);
                  if (getInstance()._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {
                    checkLastError(`Can't set a session config entry: 'numThreads' - ${webnnOptions.numThreads}.`);
                  }
                }
                if (webnnOptions?.powerPreference) {
                  const keyDataOffset = allocWasmString("powerPreference", allocs);
                  const valueDataOffset = allocWasmString(webnnOptions.powerPreference, allocs);
                  if (getInstance()._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {
                    checkLastError(
                      `Can't set a session config entry: 'powerPreference' - ${webnnOptions.powerPreference}.`
                    );
                  }
                }
              }
              break;
            case "webgpu":
              epName = "JS";
              if (typeof ep !== "string") {
                const webgpuOptions = ep;
                if (webgpuOptions?.preferredLayout) {
                  if (webgpuOptions.preferredLayout !== "NCHW" && webgpuOptions.preferredLayout !== "NHWC") {
                    throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${webgpuOptions.preferredLayout}`);
                  }
                  const keyDataOffset = allocWasmString("preferredLayout", allocs);
                  const valueDataOffset = allocWasmString(webgpuOptions.preferredLayout, allocs);
                  if (getInstance()._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {
                    checkLastError(
                      `Can't set a session config entry: 'preferredLayout' - ${webgpuOptions.preferredLayout}.`
                    );
                  }
                }
              }
              break;
            case "wasm":
            case "cpu":
              continue;
            default:
              throw new Error(`not supported execution provider: ${epName}`);
          }
          const epNameDataOffset = allocWasmString(epName, allocs);
          if (getInstance()._OrtAppendExecutionProvider(sessionOptionsHandle, epNameDataOffset) !== 0) {
            checkLastError(`Can't append execution provider: ${epName}.`);
          }
        }
      };
      setSessionOptions = (options) => {
        const wasm3 = getInstance();
        let sessionOptionsHandle = 0;
        const allocs = [];
        const sessionOptions = options || {};
        appendDefaultOptions(sessionOptions);
        try {
          const graphOptimizationLevel = getGraphOptimzationLevel(sessionOptions.graphOptimizationLevel ?? "all");
          const executionMode = getExecutionMode(sessionOptions.executionMode ?? "sequential");
          const logIdDataOffset = typeof sessionOptions.logId === "string" ? allocWasmString(sessionOptions.logId, allocs) : 0;
          const logSeverityLevel = sessionOptions.logSeverityLevel ?? 2;
          if (!Number.isInteger(logSeverityLevel) || logSeverityLevel < 0 || logSeverityLevel > 4) {
            throw new Error(`log serverity level is not valid: ${logSeverityLevel}`);
          }
          const logVerbosityLevel = sessionOptions.logVerbosityLevel ?? 0;
          if (!Number.isInteger(logVerbosityLevel) || logVerbosityLevel < 0 || logVerbosityLevel > 4) {
            throw new Error(`log verbosity level is not valid: ${logVerbosityLevel}`);
          }
          const optimizedModelFilePathOffset = typeof sessionOptions.optimizedModelFilePath === "string" ? allocWasmString(sessionOptions.optimizedModelFilePath, allocs) : 0;
          sessionOptionsHandle = wasm3._OrtCreateSessionOptions(
            graphOptimizationLevel,
            !!sessionOptions.enableCpuMemArena,
            !!sessionOptions.enableMemPattern,
            executionMode,
            !!sessionOptions.enableProfiling,
            0,
            logIdDataOffset,
            logSeverityLevel,
            logVerbosityLevel,
            optimizedModelFilePathOffset
          );
          if (sessionOptionsHandle === 0) {
            checkLastError("Can't create session options.");
          }
          if (sessionOptions.executionProviders) {
            setExecutionProviders(sessionOptionsHandle, sessionOptions.executionProviders, allocs);
          }
          if (sessionOptions.enableGraphCapture !== void 0) {
            if (typeof sessionOptions.enableGraphCapture !== "boolean") {
              throw new Error(`enableGraphCapture must be a boolean value: ${sessionOptions.enableGraphCapture}`);
            }
            const keyDataOffset = allocWasmString("enableGraphCapture", allocs);
            const valueDataOffset = allocWasmString(sessionOptions.enableGraphCapture.toString(), allocs);
            if (wasm3._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {
              checkLastError(
                `Can't set a session config entry: 'enableGraphCapture' - ${sessionOptions.enableGraphCapture}.`
              );
            }
          }
          if (sessionOptions.freeDimensionOverrides) {
            for (const [name2, value] of Object.entries(sessionOptions.freeDimensionOverrides)) {
              if (typeof name2 !== "string") {
                throw new Error(`free dimension override name must be a string: ${name2}`);
              }
              if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
                throw new Error(`free dimension override value must be a non-negative integer: ${value}`);
              }
              const nameOffset = allocWasmString(name2, allocs);
              if (wasm3._OrtAddFreeDimensionOverride(sessionOptionsHandle, nameOffset, value) !== 0) {
                checkLastError(`Can't set a free dimension override: ${name2} - ${value}.`);
              }
            }
          }
          if (sessionOptions.extra !== void 0) {
            iterateExtraOptions(sessionOptions.extra, "", /* @__PURE__ */ new WeakSet(), (key, value) => {
              const keyDataOffset = allocWasmString(key, allocs);
              const valueDataOffset = allocWasmString(value, allocs);
              if (wasm3._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {
                checkLastError(`Can't set a session config entry: ${key} - ${value}.`);
              }
            });
          }
          return [sessionOptionsHandle, allocs];
        } catch (e) {
          if (sessionOptionsHandle !== 0) {
            wasm3._OrtReleaseSessionOptions(sessionOptionsHandle);
          }
          allocs.forEach((alloc) => wasm3._free(alloc));
          throw e;
        }
      };
    }
  });

  // web/lib/wasm/wasm-common.ts
  var tensorDataTypeStringToEnum, tensorDataTypeEnumToString, getTensorElementSize, tensorTypeToTypedArrayConstructor, logLevelStringToEnum, isGpuBufferSupportedType, dataLocationStringToEnum;
  var init_wasm_common = __esm({
    "web/lib/wasm/wasm-common.ts"() {
      "use strict";
      tensorDataTypeStringToEnum = (type) => {
        switch (type) {
          case "int8":
            return 3 /* int8 */;
          case "uint8":
            return 2 /* uint8 */;
          case "bool":
            return 9 /* bool */;
          case "int16":
            return 5 /* int16 */;
          case "uint16":
            return 4 /* uint16 */;
          case "int32":
            return 6 /* int32 */;
          case "uint32":
            return 12 /* uint32 */;
          case "float16":
            return 10 /* float16 */;
          case "float32":
            return 1 /* float */;
          case "float64":
            return 11 /* double */;
          case "string":
            return 8 /* string */;
          case "int64":
            return 7 /* int64 */;
          case "uint64":
            return 13 /* uint64 */;
          default:
            throw new Error(`unsupported data type: ${type}`);
        }
      };
      tensorDataTypeEnumToString = (typeProto) => {
        switch (typeProto) {
          case 3 /* int8 */:
            return "int8";
          case 2 /* uint8 */:
            return "uint8";
          case 9 /* bool */:
            return "bool";
          case 5 /* int16 */:
            return "int16";
          case 4 /* uint16 */:
            return "uint16";
          case 6 /* int32 */:
            return "int32";
          case 12 /* uint32 */:
            return "uint32";
          case 10 /* float16 */:
            return "float16";
          case 1 /* float */:
            return "float32";
          case 11 /* double */:
            return "float64";
          case 8 /* string */:
            return "string";
          case 7 /* int64 */:
            return "int64";
          case 13 /* uint64 */:
            return "uint64";
          default:
            throw new Error(`unsupported data type: ${typeProto}`);
        }
      };
      getTensorElementSize = (dateType) => [void 0, 4, 1, 1, 2, 2, 4, 8, void 0, 1, 2, 8, 4, 8, void 0, void 0, void 0][dateType];
      tensorTypeToTypedArrayConstructor = (type) => {
        switch (type) {
          case "float16":
            return typeof Float16Array !== "undefined" && Float16Array.from ? Float16Array : Uint16Array;
          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}`);
        }
      };
      logLevelStringToEnum = (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}`);
        }
      };
      isGpuBufferSupportedType = (type) => type === "float32" || type === "float16" || type === "int32" || type === "int64" || type === "uint32" || type === "uint8" || type === "bool";
      dataLocationStringToEnum = (location) => {
        switch (location) {
          case "none":
            return 0;
          case "cpu":
            return 1;
          case "cpu-pinned":
            return 2;
          case "texture":
            return 3;
          case "gpu-buffer":
            return 4;
          default:
            throw new Error(`unsupported data location: ${location}`);
        }
      };
    }
  });

  // web/lib/wasm/wasm-utils-load-file.ts
  var loadFile;
  var init_wasm_utils_load_file = __esm({
    "web/lib/wasm/wasm-utils-load-file.ts"() {
      "use strict";
      init_fs();
      init_promises();
      loadFile = async (file) => {
        if (typeof file === "string") {
          if (typeof process !== "undefined" && process.versions && process.versions.node) {
            try {
              return new Uint8Array(await readFile(file));
            } catch (e) {
              if (e.code === "ERR_FS_FILE_TOO_LARGE") {
                const stream = createReadStream(file);
                const chunks = [];
                for await (const chunk of stream) {
                  chunks.push(chunk);
                }
                return new Uint8Array(Buffer.concat(chunks));
              }
              throw e;
            }
          } else {
            const response = await fetch(file);
            if (!response.ok) {
              throw new Error(`failed to load external data file: ${file}`);
            }
            const contentLengthHeader = response.headers.get("Content-Length");
            const fileSize = contentLengthHeader ? parseInt(contentLengthHeader, 10) : 0;
            if (fileSize < 1073741824) {
              return new Uint8Array(await response.arrayBuffer());
            } else {
              if (!response.body) {
                throw new Error(`failed to load external data file: ${file}, no response body.`);
              }
              const reader = response.body.getReader();
              let buffer;
              try {
                buffer = new ArrayBuffer(fileSize);
              } catch (e) {
                if (e instanceof RangeError) {
                  const pages = Math.ceil(fileSize / 65536);
                  buffer = new WebAssembly.Memory({ initial: pages, maximum: pages }).buffer;
                } else {
                  throw e;
                }
              }
              let offset = 0;
              while (true) {
                const { done, value } = await reader.read();
                if (done) {
                  break;
                }
                const chunkSize = value.byteLength;
                const chunk = new Uint8Array(buffer, offset, chunkSize);
                chunk.set(value);
                offset += chunkSize;
              }
              return new Uint8Array(buffer, 0, fileSize);
            }
          }
        } else if (file instanceof Blob) {
          return new Uint8Array(await file.arrayBuffer());
        } else if (file instanceof Uint8Array) {
          return file;
        } else {
          return new Uint8Array(file);
        }
      };
    }
  });

  // web/lib/wasm/wasm-core-impl.ts
  var initOrt, initRuntime, initEp, activeSessions, getSessionInputOutputCount, copyFromExternalBuffer, createSession, releaseSession, prepareInputOutputTensor, run, endProfiling, extractTransferableBuffers;
  var init_wasm_core_impl = __esm({
    "web/lib/wasm/wasm-core-impl.ts"() {
      "use strict";
      init_run_options();
      init_session_options();
      init_wasm_common();
      init_wasm_factory();
      init_wasm_utils();
      init_wasm_utils_load_file();
      initOrt = (numThreads, loggingLevel) => {
        const errorCode = getInstance()._OrtInit(numThreads, loggingLevel);
        if (errorCode !== 0) {
          checkLastError("Can't initialize onnxruntime.");
        }
      };
      initRuntime = async (env3) => {
        initOrt(env3.wasm.numThreads, logLevelStringToEnum(env3.logLevel));
      };
      initEp = async (env3, epName) => {
        if (false) {
          const initJsep = null.init;
          if (epName === "webgpu") {
            if (typeof navigator === "undefined" || !navigator.gpu) {
              throw new Error("WebGPU is not supported in current environment");
            }
            let adapter = env3.webgpu.adapter;
            if (!adapter) {
              const powerPreference = env3.webgpu.powerPreference;
              if (powerPreference !== void 0 && powerPreference !== "low-power" && powerPreference !== "high-performance") {
                throw new Error(`Invalid powerPreference setting: "${powerPreference}"`);
              }
              const forceFallbackAdapter = env3.webgpu.forceFallbackAdapter;
              if (forceFallbackAdapter !== void 0 && typeof forceFallbackAdapter !== "boolean") {
                throw new Error(`Invalid forceFallbackAdapter setting: "${forceFallbackAdapter}"`);
              }
              adapter = await navigator.gpu.requestAdapter({ powerPreference, forceFallbackAdapter });
              if (!adapter) {
                throw new Error(
                  'Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.'
                );
              }
            } else {
              if (typeof adapter.limits !== "object" || typeof adapter.features !== "object" || typeof adapter.requestDevice !== "function") {
                throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.");
              }
            }
            if (!env3.wasm.simd) {
              throw new Error(
                "Not supported for WebGPU=ON and SIMD=OFF. Please set `env.wasm.simd` to true when using `webgpu` EP"
              );
            }
            await initJsep("webgpu", getInstance(), env3, adapter);
          }
          if (epName === "webnn") {
            if (typeof navigator === "undefined" || !navigator.ml) {
              throw new Error("WebNN is not supported in current environment");
            }
            await initJsep("webnn", getInstance(), env3);
          }
        }
      };
      activeSessions = /* @__PURE__ */ new Map();
      getSessionInputOutputCount = (sessionHandle) => {
        const wasm3 = getInstance();
        const stack = wasm3.stackSave();
        try {
          const dataOffset = wasm3.stackAlloc(8);
          const errorCode = wasm3._OrtGetInputOutputCount(sessionHandle, dataOffset, dataOffset + 4);
          if (errorCode !== 0) {
            checkLastError("Can't get session input/output count.");
          }
          return [wasm3.HEAP32[dataOffset / 4], wasm3.HEAP32[dataOffset / 4 + 1]];
        } finally {
          wasm3.stackRestore(stack);
        }
      };
      copyFromExternalBuffer = (model) => {
        const wasm3 = getInstance();
        const modelDataOffset = wasm3._malloc(model.byteLength);
        if (modelDataOffset === 0) {
          throw new Error(`Can't create a session. failed to allocate a buffer of size ${model.byteLength}.`);
        }
        wasm3.HEAPU8.set(model, modelDataOffset);
        return [modelDataOffset, model.byteLength];
      };
      createSession = async (modelData, options) => {
        let modelDataOffset, modelDataLength;
        const wasm3 = getInstance();
        if (Array.isArray(modelData)) {
          [modelDataOffset, modelDataLength] = modelData;
        } else if (modelData.buffer === wasm3.HEAPU8.buffer) {
          [modelDataOffset, modelDataLength] = [modelData.byteOffset, modelData.byteLength];
        } else {
          [modelDataOffset, modelDataLength] = copyFromExternalBuffer(modelData);
        }
        let sessionHandle = 0;
        let sessionOptionsHandle = 0;
        let ioBindingHandle = 0;
        let allocs = [];
        const inputNamesUTF8Encoded = [];
        const outputNamesUTF8Encoded = [];
        try {
          [sessionOptionsHandle, allocs] = setSessionOptions(options);
          if (options?.externalData && wasm3.mountExternalData) {
            const loadingPromises = [];
            for (const file of options.externalData) {
              const path = typeof file === "string" ? file : file.path;
              loadingPromises.push(loadFile(typeof file === "string" ? file : file.data).then((data) => {
                wasm3.mountExternalData(path, data);
              }));
            }
            await Promise.all(loadingPromises);
          }
          sessionHandle = await wasm3._OrtCreateSession(modelDataOffset, modelDataLength, sessionOptionsHandle);
          if (sessionHandle === 0) {
            checkLastError("Can't create a session.");
          }
          const [inputCount, outputCount] = getSessionInputOutputCount(sessionHandle);
          const enableGraphCapture = !!options?.enableGraphCapture;
          const inputNames = [];
          const outputNames = [];
          const outputPreferredLocations = [];
          for (let i = 0; i < inputCount; i++) {
            const name2 = wasm3._OrtGetInputName(sessionHandle, i);
            if (name2 === 0) {
              checkLastError("Can't get an input name.");
            }
            inputNamesUTF8Encoded.push(name2);
            inputNames.push(wasm3.UTF8ToString(name2));
          }
          for (let i = 0; i < outputCount; i++) {
            const name2 = wasm3._OrtGetOutputName(sessionHandle, i);
            if (name2 === 0) {
              checkLastError("Can't get an output name.");
            }
            outputNamesUTF8Encoded.push(name2);
            const nameString = wasm3.UTF8ToString(name2);
            outputNames.push(nameString);
            if (false) {
              if (enableGraphCapture && options?.preferredOutputLocation === void 0) {
                outputPreferredLocations.push("gpu-buffer");
                continue;
              }
              const location = typeof options?.preferredOutputLocation === "string" ? options.preferredOutputLocation : options?.preferredOutputLocation?.[nameString] ?? "cpu";
              if (location !== "cpu" && location !== "cpu-pinned" && location !== "gpu-buffer") {
                throw new Error(`Not supported preferred output location: ${location}.`);
              }
              if (enableGraphCapture && location !== "gpu-buffer") {
                throw new Error(`Not supported preferred output location: ${location}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);
              }
              outputPreferredLocations.push(location);
            }
          }
          let bindingState = null;
          if (false) {
            ioBindingHandle = wasm3._OrtCreateBinding(sessionHandle);
            if (ioBindingHandle === 0) {
              checkLastError("Can't create IO binding.");
            }
            bindingState = {
              handle: ioBindingHandle,
              outputPreferredLocations,
              outputPreferredLocationsEncoded: outputPreferredLocations.map((l) => dataLocationStringToEnum(l))
            };
          }
          activeSessions.set(
            sessionHandle,
            [sessionHandle, inputNamesUTF8Encoded, outputNamesUTF8Encoded, bindingState, enableGraphCapture, false]
          );
          return [sessionHandle, inputNames, outputNames];
        } catch (e) {
          inputNamesUTF8Encoded.forEach((buf) => wasm3._OrtFree(buf));
          outputNamesUTF8Encoded.forEach((buf) => wasm3._OrtFree(buf));
          if (ioBindingHandle !== 0) {
            wasm3._OrtReleaseBinding(ioBindingHandle);
          }
          if (sessionHandle !== 0) {
            wasm3._OrtReleaseSession(sessionHandle);
          }
          throw e;
        } finally {
          wasm3._free(modelDataOffset);
          if (sessionOptionsHandle !== 0) {
            wasm3._OrtReleaseSessionOptions(sessionOptionsHandle);
          }
          allocs.forEach((alloc) => wasm3._free(alloc));
          wasm3.unmountExternalData?.();
        }
      };
      releaseSession = (sessionId) => {
        const wasm3 = getInstance();
        const session = activeSessions.get(sessionId);
        if (!session) {
          throw new Error(`cannot release session. invalid session id: ${sessionId}`);
        }
        const [sessionHandle, inputNamesUTF8Encoded, outputNamesUTF8Encoded, ioBindingState, enableGraphCapture] = session;
        if (ioBindingState) {
          if (enableGraphCapture) {
            wasm3._OrtClearBoundOutputs(ioBindingState.handle);
          }
          wasm3._OrtReleaseBinding(ioBindingState.handle);
        }
        wasm3.jsepOnReleaseSession?.(sessionId);
        inputNamesUTF8Encoded.forEach((buf) => wasm3._OrtFree(buf));
        outputNamesUTF8Encoded.forEach((buf) => wasm3._OrtFree(buf));
        wasm3._OrtReleaseSession(sessionHandle);
        activeSessions.delete(sessionId);
      };
      prepareInputOutputTensor = (tensor, tensorHandles, allocs, sessionId, index, enableGraphCapture = false) => {
        if (!tensor) {
          tensorHandles.push(0);
          return;
        }
        const wasm3 = getInstance();
        const dataType = tensor[0];
        const dims = tensor[1];
        const location = tensor[3];
        let rawData;
        let dataByteLength;
        if (dataType === "string" && location === "gpu-buffer") {
          throw new Error("String tensor is not supported on GPU.");
        }
        if (enableGraphCapture && location !== "gpu-buffer") {
          throw new Error(
            `External buffer must be provided for input/output index ${index} when enableGraphCapture is true.`
          );
        }
        if (location === "gpu-buffer") {
          const gpuBuffer = tensor[2].gpuBuffer;
          const elementSizeInBytes = getTensorElementSize(tensorDataTypeStringToEnum(dataType));
          dataByteLength = dims.reduce((a, b) => a * b, 1) * elementSizeInBytes;
          const registerBuffer = wasm3.jsepRegisterBuffer;
          if (!registerBuffer) {
            throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');
          }
          rawData = registerBuffer(sessionId, index, gpuBuffer, dataByteLength);
        } else {
          const data = tensor[2];
          if (Array.isArray(data)) {
            dataByteLength = 4 * data.length;
            rawData = wasm3._malloc(dataByteLength);
            allocs.push(rawData);
            let dataIndex = rawData / 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`);
              }
              wasm3.HEAPU32[dataIndex++] = allocWasmString(data[i], allocs);
            }
          } else {
            dataByteLength = data.byteLength;
            rawData = wasm3._malloc(dataByteLength);
            allocs.push(rawData);
            wasm3.HEAPU8.set(new Uint8Array(data.buffer, data.byteOffset, dataByteLength), rawData);
          }
        }
        const stack = wasm3.stackSave();
        const dimsOffset = wasm3.stackAlloc(4 * dims.length);
        try {
          let dimIndex = dimsOffset / 4;
          dims.forEach((d) => wasm3.HEAP32[dimIndex++] = d);
          const tensor2 = wasm3._OrtCreateTensor(
            tensorDataTypeStringToEnum(dataType),
            rawData,
            dataByteLength,
            dimsOffset,
            dims.length,
            dataLocationStringToEnum(location)
          );
          if (tensor2 === 0) {
            checkLastError(`Can't create tensor for input/output. session=${sessionId}, index=${index}.`);
          }
          tensorHandles.push(tensor2);
        } finally {
          wasm3.stackRestore(stack);
        }
      };
      run = async (sessionId, inputIndices, inputTensors, outputIndices, outputTensors, options) => {
        const wasm3 = getInstance();
        const session = activeSessions.get(sessionId);
        if (!session) {
          throw new Error(`cannot run inference. invalid session id: ${sessionId}`);
        }
        const sessionHandle = session[0];
        const inputNamesUTF8Encoded = session[1];
        const outputNamesUTF8Encoded = session[2];
        const ioBindingState = session[3];
        const enableGraphCapture = session[4];
        const inputOutputBound = session[5];
        const inputCount = inputIndices.length;
        const outputCount = outputIndices.length;
        let runOptionsHandle = 0;
        let runOptionsAllocs = [];
        const inputTensorHandles = [];
        const outputTensorHandles = [];
        const inputOutputAllocs = [];
        const beforeRunStack = wasm3.stackSave();
        const inputValuesOffset = wasm3.stackAlloc(inputCount * 4);
        const inputNamesOffset = wasm3.stackAlloc(inputCount * 4);
        const outputValuesOffset = wasm3.stackAlloc(outputCount * 4);
        const outputNamesOffset = wasm3.stackAlloc(outputCount * 4);
        try {
          [runOptionsHandle, runOptionsAllocs] = setRunOptions(options);
          for (let i = 0; i < inputCount; i++) {
            prepareInputOutputTensor(
              inputTensors[i],
              inputTensorHandles,
              inputOutputAllocs,
              sessionId,
              inputIndices[i],
              enableGraphCapture
            );
          }
          for (let i = 0; i < outputCount; i++) {
            prepareInputOutputTensor(
              outputTensors[i],
              outputTensorHandles,
              inputOutputAllocs,
              sessionId,
              inputCount + outputIndices[i],
              enableGraphCapture
            );
          }
          let inputValuesIndex = inputValuesOffset / 4;
          let inputNamesIndex = inputNamesOffset / 4;
          let outputValuesIndex = outputValuesOffset / 4;
          let outputNamesIndex = outputNamesOffset / 4;
          for (let i = 0; i < inputCount; i++) {
            wasm3.HEAPU32[inputValuesIndex++] = inputTensorHandles[i];
            wasm3.HEAPU32[inputNamesIndex++] = inputNamesUTF8Encoded[inputIndices[i]];
          }
          for (let i = 0; i < outputCount; i++) {
            wasm3.HEAPU32[outputValuesIndex++] = outputTensorHandles[i];
            wasm3.HEAPU32[outputNamesIndex++] = outputNamesUTF8Encoded[outputIndices[i]];
          }
          if (false) {
            const { handle, outputPreferredLocations, outputPreferredLocationsEncoded } = ioBindingState;
            if (inputNamesUTF8Encoded.length !== inputCount) {
              throw new Error(`input count from feeds (${inputCount}) is expected to be always equal to model's input count (${inputNamesUTF8Encoded.length}).`);
            }
            for (let i = 0; i < inputCount; i++) {
              const index = inputIndices[i];
              const errorCode2 = await wasm3._OrtBindInput(handle, inputNamesUTF8Encoded[index], inputTensorHandles[i]);
              if (errorCode2 !== 0) {
                checkLastError(`Can't bind input[${i}] for session=${sessionId}.`);
              }
            }
            for (let i = 0; i < outputCount; i++) {
              const index = outputIndices[i];
              const location = outputTensors[i]?.[3];
              if (location) {
                const errorCode2 = wasm3._OrtBindOutput(handle, outputNamesUTF8Encoded[index], outputTensorHandles[i], 0);
                if (errorCode2 !== 0) {
                  checkLastError(`Can't bind pre-allocated output[${i}] for session=${sessionId}.`);
                }
              } else {
                const errorCode2 = wasm3._OrtBindOutput(handle, outputNamesUTF8Encoded[index], 0, outputPreferredLocationsEncoded[index]);
                if (errorCode2 !== 0) {
                  checkLastError(`Can't bind output[${i}] to ${outputPreferredLocations[i]} for session=${sessionId}.`);
                }
              }
            }
            activeSessions.set(
              sessionId,
              [sessionHandle, inputNamesUTF8Encoded, outputNamesUTF8Encoded, ioBindingState, enableGraphCapture, true]
            );
          }
          wasm3.jsepOnRunStart?.(sessionHandle);
          let errorCode;
          if (false) {
            errorCode = await wasm3._OrtRunWithBinding(
              sessionHandle,
              ioBindingState.handle,
              outputCount,
              outputValuesOffset,
              runOptionsHandle
            );
          } else {
            errorCode = await wasm3._OrtRun(
              sessionHandle,
              inputNamesOffset,
              inputValuesOffset,
              inputCount,
              outputNamesOffset,
              outputCount,
              outputValuesOffset,
              runOptionsHandle
            );
          }
          if (errorCode !== 0) {
            checkLastError("failed to call OrtRun().");
          }
          const output = [];
          for (let i = 0; i < outputCount; i++) {
            const tensor = wasm3.HEAPU32[outputValuesOffset / 4 + i];
            if (tensor === outputTensorHandles[i]) {
              output.push(outputTensors[i]);
              continue;
            }
            const beforeGetTensorDataStack = wasm3.stackSave();
            const tensorDataOffset = wasm3.stackAlloc(4 * 4);
            let keepOutputTensor = false;
            let type, dataOffset = 0;
            try {
              const errorCode2 = wasm3._OrtGetTensorData(
                tensor,
                tensorDataOffset,
                tensorDataOffset + 4,
                tensorDataOffset + 8,
                tensorDataOffset + 12
              );
              if (errorCode2 !== 0) {
                checkLastError(`Can't access output tensor data on index ${i}.`);
              }
              let tensorDataIndex = tensorDataOffset / 4;
              const dataType = wasm3.HEAPU32[tensorDataIndex++];
              dataOffset = wasm3.HEAPU32[tensorDataIndex++];
              const dimsOffset = wasm3.HEAPU32[tensorDataIndex++];
              const dimsLength = wasm3.HEAPU32[tensorDataIndex++];
              const dims = [];
              for (let i2 = 0; i2 < dimsLength; i2++) {
                dims.push(wasm3.HEAPU32[dimsOffset / 4 + i2]);
              }
              wasm3._OrtFree(dimsOffset);
              const size = dims.reduce((a, b) => a * b, 1);
              type = tensorDataTypeEnumToString(dataType);
              const preferredLocation = ioBindingState?.outputPreferredLocations[outputIndices[i]];
              if (type === "string") {
                if (preferredLocation === "gpu-buffer") {
                  throw new Error("String tensor is not supported on GPU.");
                }
                const stringData = [];
                let dataIndex = dataOffset / 4;
                for (let i2 = 0; i2 < size; i2++) {
                  const offset = wasm3.HEAPU32[dataIndex++];
                  const maxBytesToRead = i2 === size - 1 ? void 0 : wasm3.HEAPU32[dataIndex] - offset;
                  stringData.push(wasm3.UTF8ToString(offset, maxBytesToRead));
                }
                output.push([type, dims, stringData, "cpu"]);
              } else {
                if (preferredLocation === "gpu-buffer" && size > 0) {
                  const getBuffer = wasm3.jsepGetBuffer;
                  if (!getBuffer) {
                    throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');
                  }
                  const gpuBuffer = getBuffer(dataOffset);
                  const elementSize = getTensorElementSize(dataType);
                  if (elementSize === void 0 || !isGpuBufferSupportedType(type)) {
                    throw new Error(`Unsupported data type: ${type}`);
                  }
                  keepOutputTensor = true;
                  output.push([
                    type,
                    dims,
                    {
                      gpuBuffer,
                      download: wasm3.jsepCreateDownloader(gpuBuffer, size * elementSize, type),
                      dispose: () => {
                        wasm3._OrtReleaseTensor(tensor);
                      }
                    },
                    "gpu-buffer"
                  ]);
                } else {
                  const typedArrayConstructor = tensorTypeToTypedArrayConstructor(type);
                  const data = new typedArrayConstructor(size);
                  new Uint8Array(data.buffer, data.byteOffset, data.byteLength).set(wasm3.HEAPU8.subarray(dataOffset, dataOffset + data.byteLength));
                  output.push([type, dims, data, "cpu"]);
                }
              }
            } finally {
              wasm3.stackRestore(beforeGetTensorDataStack);
              if (type === "string" && dataOffset) {
                wasm3._free(dataOffset);
              }
              if (!keepOutputTensor) {
                wasm3._OrtReleaseTensor(tensor);
              }
            }
          }
          if (ioBindingState && !enableGraphCapture) {
            wasm3._OrtClearBoundOutputs(ioBindingState.handle);
            activeSessions.set(
              sessionId,
              [sessionHandle, inputNamesUTF8Encoded, outputNamesUTF8Encoded, ioBindingState, enableGraphCapture, false]
            );
          }
          return output;
        } finally {
          wasm3.stackRestore(beforeRunStack);
          inputTensorHandles.forEach((v) => wasm3._OrtReleaseTensor(v));
          outputTensorHandles.forEach((v) => wasm3._OrtReleaseTensor(v));
          inputOutputAllocs.forEach((p) => wasm3._free(p));
          if (runOptionsHandle !== 0) {
            wasm3._OrtReleaseRunOptions(runOptionsHandle);
          }
          runOptionsAllocs.forEach((p) => wasm3._free(p));
        }
      };
      endProfiling = (sessionId) => {
        const wasm3 = getInstance();
        const session = activeSessions.get(sessionId);
        if (!session) {
          throw new Error("invalid session id");
        }
        const sessionHandle = session[0];
        const profileFileName = wasm3._OrtEndProfiling(sessionHandle);
        if (profileFileName === 0) {
          checkLastError("Can't get an profile file name.");
        }
        wasm3._OrtFree(profileFileName);
      };
      extractTransferableBuffers = (tensors) => {
        const buffers = [];
        for (const tensor of tensors) {
          const data = tensor[2];
          if (!Array.isArray(data) && "buffer" in data) {
            buffers.push(data.buffer);
          }
        }
        return buffers;
      };
    }
  });

  // proxy-worker:./proxy-worker/main
  var require_main = __commonJS({
    "proxy-worker:./proxy-worker/main"(exports2, module2) {
      module2.exports = '/*!\n * ONNX Runtime Web v1.18.0\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n"use strict";\n(() => {\n  var __defProp = Object.defineProperty;\n  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;\n  var __getOwnPropNames = Object.getOwnPropertyNames;\n  var __hasOwnProp = Object.prototype.hasOwnProperty;\n  var __esm = (fn, res) => function __init() {\n    return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;\n  };\n  var __commonJS = (cb, mod) => function __require() {\n    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;\n  };\n  var __export = (target, all) => {\n    for (var name in all)\n      __defProp(target, name, { get: all[name], enumerable: true });\n  };\n  var __copyProps = (to, from, except, desc) => {\n    if (from && typeof from === "object" || typeof from === "function") {\n      for (let key of __getOwnPropNames(from))\n        if (!__hasOwnProp.call(to, key) && key !== except)\n          __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n    }\n    return to;\n  };\n  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);\n\n  // nodejs-ignore:fs\n  var fs_exports = {};\n  __export(fs_exports, {\n    createReadStream: () => createReadStream,\n    readFile: () => readFile,\n    readFileSync: () => readFileSync\n  });\n  var readFile, readFileSync, createReadStream;\n  var init_fs = __esm({\n    "nodejs-ignore:fs"() {\n      readFile = void 0;\n      readFileSync = void 0;\n      createReadStream = void 0;\n    }\n  });\n\n  // nodejs-ignore:path\n  var path_exports = {};\n  __export(path_exports, {\n    join: () => join2\n  });\n  var join2;\n  var init_path = __esm({\n    "nodejs-ignore:path"() {\n      join2 = void 0;\n    }\n  });\n\n  // web/lib/wasm/binding/ort-wasm.js\n  var require_ort_wasm = __commonJS({\n    "web/lib/wasm/binding/ort-wasm.js"(exports, module) {\n      "use strict";\n      var ortWasm = (() => {\n        var _scriptDir = typeof document != "undefined" ? document.currentScript?.src : void 0;\n        if (typeof __filename != "undefined")\n          _scriptDir ||= __filename;\n        return function(moduleArg = {}) {\n          var f = moduleArg, k, l, readyPromise = new Promise((a, b) => {\n            k = a;\n            l = b;\n          }), u = Object.assign({}, f), v = "./this.program", aa = "object" == typeof window, w = "function" == typeof importScripts, ba = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, z = "", A, B, C;\n          if (ba) {\n            var fs = (init_fs(), __toCommonJS(fs_exports)), D = (init_path(), __toCommonJS(path_exports));\n            z = w ? D.dirname(z) + "/" : __dirname + "/";\n            A = (a, b) => {\n              a = E(a) ? new URL(a) : D.normalize(a);\n              return fs.readFileSync(a, b ? void 0 : "utf8");\n            };\n            C = (a) => {\n              a = A(a, true);\n              a.buffer || (a = new Uint8Array(a));\n              return a;\n            };\n            B = (a, b, c, e = true) => {\n              a = E(a) ? new URL(a) : D.normalize(a);\n              fs.readFile(a, e ? void 0 : "utf8", (g, h) => {\n                g ? c(g) : b(e ? h.buffer : h);\n              });\n            };\n            !f.thisProgram && 1 < process.argv.length && (v = process.argv[1].replace(/\\\\/g, "/"));\n            process.argv.slice(2);\n          } else if (aa || w)\n            w ? z = self.location.href : "undefined" != typeof document && document.currentScript && (z = document.currentScript.src), _scriptDir && (z = _scriptDir), z.startsWith("blob:") ? z = "" : z = z.substr(0, z.replace(/[?#].*/, "").lastIndexOf("/") + 1), A = (a) => {\n              var b = new XMLHttpRequest();\n              b.open("GET", a, false);\n              b.send(null);\n              return b.responseText;\n            }, w && (C = (a) => {\n              var b = new XMLHttpRequest();\n              b.open("GET", a, false);\n              b.responseType = "arraybuffer";\n              b.send(null);\n              return new Uint8Array(b.response);\n            }), B = (a, b, c) => {\n              var e = new XMLHttpRequest();\n              e.open("GET", a, true);\n              e.responseType = "arraybuffer";\n              e.onload = () => {\n                200 == e.status || 0 == e.status && e.response ? b(e.response) : c();\n              };\n              e.onerror = c;\n              e.send(null);\n            };\n          var ca = console.log.bind(console), F = console.error.bind(console);\n          Object.assign(f, u);\n          u = null;\n          var G, da = false, H, I, J, K, ea;\n          function fa() {\n            var a = G.buffer;\n            f.HEAP8 = H = new Int8Array(a);\n            f.HEAP16 = new Int16Array(a);\n            f.HEAPU8 = I = new Uint8Array(a);\n            f.HEAPU16 = new Uint16Array(a);\n            f.HEAP32 = J = new Int32Array(a);\n            f.HEAPU32 = K = new Uint32Array(a);\n            f.HEAPF32 = new Float32Array(a);\n            f.HEAPF64 = ea = new Float64Array(a);\n          }\n          var L = [], M = [], ha = [], N = 0, O = null, P = null;\n          function ia(a) {\n            a = "Aborted(" + a + ")";\n            F(a);\n            da = true;\n            a = new WebAssembly.RuntimeError(a + ". Build with -sASSERTIONS for more info.");\n            l(a);\n            throw a;\n          }\n          var ja = (a) => a.startsWith("data:application/octet-stream;base64,"), E = (a) => a.startsWith("file://"), Q;\n          Q = "ort-wasm.wasm";\n          if (!ja(Q)) {\n            var ka = Q;\n            Q = f.locateFile ? f.locateFile(ka, z) : z + ka;\n          }\n          function la(a) {\n            if (C)\n              return C(a);\n            throw "both async and sync fetching of the wasm failed";\n          }\n          function ma(a) {\n            if (aa || w) {\n              if ("function" == typeof fetch && !E(a))\n                return fetch(a, { credentials: "same-origin" }).then((b) => {\n                  if (!b.ok)\n                    throw `failed to load wasm binary file at \'${a}\'`;\n                  return b.arrayBuffer();\n                }).catch(() => la(a));\n              if (B)\n                return new Promise((b, c) => {\n                  B(a, (e) => b(new Uint8Array(e)), c);\n                });\n            }\n            return Promise.resolve().then(() => la(a));\n          }\n          function na(a, b, c) {\n            return ma(a).then((e) => WebAssembly.instantiate(e, b)).then(c, (e) => {\n              F(`failed to asynchronously prepare wasm: ${e}`);\n              ia(e);\n            });\n          }\n          function oa(a, b) {\n            var c = Q;\n            return "function" != typeof WebAssembly.instantiateStreaming || ja(c) || E(c) || ba || "function" != typeof fetch ? na(c, a, b) : fetch(c, { credentials: "same-origin" }).then((e) => WebAssembly.instantiateStreaming(e, a).then(b, function(g) {\n              F(`wasm streaming compile failed: ${g}`);\n              F("falling back to ArrayBuffer instantiation");\n              return na(c, a, b);\n            }));\n          }\n          var R, pa = { 798088: (a, b, c, e) => {\n            if ("undefined" == typeof f || !f.ya)\n              return 1;\n            a = S(a >>> 0);\n            a.startsWith("./") && (a = a.substring(2));\n            a = f.ya.get(a);\n            if (!a)\n              return 2;\n            b >>>= 0;\n            c >>>= 0;\n            if (b + c > a.byteLength)\n              return 3;\n            try {\n              return I.set(a.subarray(b, b + c), e >>> 0 >>> 0), 0;\n            } catch {\n              return 4;\n            }\n          } };\n          class qa {\n            constructor(a) {\n              this.wa = a - 24;\n            }\n          }\n          var ra = 0, sa = 0, ta = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0, ua = (a, b, c) => {\n            b >>>= 0;\n            var e = b + c;\n            for (c = b; a[c] && !(c >= e); )\n              ++c;\n            if (16 < c - b && a.buffer && ta)\n              return ta.decode(a.subarray(b, c));\n            for (e = ""; b < c; ) {\n              var g = a[b++];\n              if (g & 128) {\n                var h = a[b++] & 63;\n                if (192 == (g & 224))\n                  e += String.fromCharCode((g & 31) << 6 | h);\n                else {\n                  var m = a[b++] & 63;\n                  g = 224 == (g & 240) ? (g & 15) << 12 | h << 6 | m : (g & 7) << 18 | h << 12 | m << 6 | a[b++] & 63;\n                  65536 > g ? e += String.fromCharCode(g) : (g -= 65536, e += String.fromCharCode(55296 | g >> 10, 56320 | g & 1023));\n                }\n              } else\n                e += String.fromCharCode(g);\n            }\n            return e;\n          }, S = (a, b) => (a >>>= 0) ? ua(I, a, b) : "", va = (a) => {\n            for (var b = 0, c = 0; c < a.length; ++c) {\n              var e = a.charCodeAt(c);\n              127 >= e ? b++ : 2047 >= e ? b += 2 : 55296 <= e && 57343 >= e ? (b += 4, ++c) : b += 3;\n            }\n            return b;\n          }, T = (a, b, c, e) => {\n            c >>>= 0;\n            if (!(0 < e))\n              return 0;\n            var g = c;\n            e = c + e - 1;\n            for (var h = 0; h < a.length; ++h) {\n              var m = a.charCodeAt(h);\n              if (55296 <= m && 57343 >= m) {\n                var q = a.charCodeAt(++h);\n                m = 65536 + ((m & 1023) << 10) | q & 1023;\n              }\n              if (127 >= m) {\n                if (c >= e)\n                  break;\n                b[c++ >>> 0] = m;\n              } else {\n                if (2047 >= m) {\n                  if (c + 1 >= e)\n                    break;\n                  b[c++ >>> 0] = 192 | m >> 6;\n                } else {\n                  if (65535 >= m) {\n                    if (c + 2 >= e)\n                      break;\n                    b[c++ >>> 0] = 224 | m >> 12;\n                  } else {\n                    if (c + 3 >= e)\n                      break;\n                    b[c++ >>> 0] = 240 | m >> 18;\n                    b[c++ >>> 0] = 128 | m >> 12 & 63;\n                  }\n                  b[c++ >>> 0] = 128 | m >> 6 & 63;\n                }\n                b[c++ >>> 0] = 128 | m & 63;\n              }\n            }\n            b[c >>> 0] = 0;\n            return c - g;\n          }, U = (a) => 0 === a % 4 && (0 !== a % 100 || 0 === a % 400), za = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], Aa = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], V = [], W = {}, Ba = () => {\n            if (!X) {\n              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", _: v || "./this.program" }, b;\n              for (b in W)\n                void 0 === W[b] ? delete a[b] : a[b] = W[b];\n              var c = [];\n              for (b in a)\n                c.push(`${b}=${a[b]}`);\n              X = c;\n            }\n            return X;\n          }, X, Ca = [null, [], []], Da = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], Ea = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n          function Fa(a) {\n            var b = Array(va(a) + 1);\n            T(a, b, 0, b.length);\n            return b;\n          }\n          function Ga(a, b, c, e) {\n            function g(d, n, p) {\n              for (d = "number" == typeof d ? d.toString() : d || ""; d.length < n; )\n                d = p[0] + d;\n              return d;\n            }\n            function h(d, n) {\n              return g(d, n, "0");\n            }\n            function m(d, n) {\n              function p(wa) {\n                return 0 > wa ? -1 : 0 < wa ? 1 : 0;\n              }\n              var y;\n              0 === (y = p(d.getFullYear() - n.getFullYear())) && 0 === (y = p(d.getMonth() - n.getMonth())) && (y = p(d.getDate() - n.getDate()));\n              return y;\n            }\n            function q(d) {\n              switch (d.getDay()) {\n                case 0:\n                  return new Date(d.getFullYear() - 1, 11, 29);\n                case 1:\n                  return d;\n                case 2:\n                  return new Date(d.getFullYear(), 0, 3);\n                case 3:\n                  return new Date(\n                    d.getFullYear(),\n                    0,\n                    2\n                  );\n                case 4:\n                  return new Date(d.getFullYear(), 0, 1);\n                case 5:\n                  return new Date(d.getFullYear() - 1, 11, 31);\n                case 6:\n                  return new Date(d.getFullYear() - 1, 11, 30);\n              }\n            }\n            function x(d) {\n              var n = d.sa;\n              for (d = new Date(new Date(d.ta + 1900, 0, 1).getTime()); 0 < n; ) {\n                var p = d.getMonth(), y = (U(d.getFullYear()) ? Da : Ea)[p];\n                if (n > y - d.getDate())\n                  n -= y - d.getDate() + 1, d.setDate(1), 11 > p ? d.setMonth(p + 1) : (d.setMonth(0), d.setFullYear(d.getFullYear() + 1));\n                else {\n                  d.setDate(d.getDate() + n);\n                  break;\n                }\n              }\n              p = new Date(d.getFullYear() + 1, 0, 4);\n              n = q(new Date(\n                d.getFullYear(),\n                0,\n                4\n              ));\n              p = q(p);\n              return 0 >= m(n, d) ? 0 >= m(p, d) ? d.getFullYear() + 1 : d.getFullYear() : d.getFullYear() - 1;\n            }\n            a >>>= 0;\n            b >>>= 0;\n            c >>>= 0;\n            e >>>= 0;\n            var r = K[e + 40 >>> 2 >>> 0];\n            e = { Ba: J[e >>> 2 >>> 0], Aa: J[e + 4 >>> 2 >>> 0], ua: J[e + 8 >>> 2 >>> 0], xa: J[e + 12 >>> 2 >>> 0], va: J[e + 16 >>> 2 >>> 0], ta: J[e + 20 >>> 2 >>> 0], na: J[e + 24 >>> 2 >>> 0], sa: J[e + 28 >>> 2 >>> 0], Da: J[e + 32 >>> 2 >>> 0], za: J[e + 36 >>> 2 >>> 0], Ca: r ? S(r) : "" };\n            c = S(c);\n            r = {\n              "%c": "%a %b %d %H:%M:%S %Y",\n              "%D": "%m/%d/%y",\n              "%F": "%Y-%m-%d",\n              "%h": "%b",\n              "%r": "%I:%M:%S %p",\n              "%R": "%H:%M",\n              "%T": "%H:%M:%S",\n              "%x": "%m/%d/%y",\n              "%X": "%H:%M:%S",\n              "%Ec": "%c",\n              "%EC": "%C",\n              "%Ex": "%m/%d/%y",\n              "%EX": "%H:%M:%S",\n              "%Ey": "%y",\n              "%EY": "%Y",\n              "%Od": "%d",\n              "%Oe": "%e",\n              "%OH": "%H",\n              "%OI": "%I",\n              "%Om": "%m",\n              "%OM": "%M",\n              "%OS": "%S",\n              "%Ou": "%u",\n              "%OU": "%U",\n              "%OV": "%V",\n              "%Ow": "%w",\n              "%OW": "%W",\n              "%Oy": "%y"\n            };\n            for (var t in r)\n              c = c.replace(new RegExp(t, "g"), r[t]);\n            var xa = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), ya = "January February March April May June July August September October November December".split(" ");\n            r = {\n              "%a": (d) => xa[d.na].substring(0, 3),\n              "%A": (d) => xa[d.na],\n              "%b": (d) => ya[d.va].substring(0, 3),\n              "%B": (d) => ya[d.va],\n              "%C": (d) => h((d.ta + 1900) / 100 | 0, 2),\n              "%d": (d) => h(d.xa, 2),\n              "%e": (d) => g(d.xa, 2, " "),\n              "%g": (d) => x(d).toString().substring(2),\n              "%G": x,\n              "%H": (d) => h(d.ua, 2),\n              "%I": (d) => {\n                d = d.ua;\n                0 == d ? d = 12 : 12 < d && (d -= 12);\n                return h(d, 2);\n              },\n              "%j": (d) => {\n                for (var n = 0, p = 0; p <= d.va - 1; n += (U(d.ta + 1900) ? Da : Ea)[p++])\n                  ;\n                return h(d.xa + n, 3);\n              },\n              "%m": (d) => h(d.va + 1, 2),\n              "%M": (d) => h(d.Aa, 2),\n              "%n": () => "\\n",\n              "%p": (d) => 0 <= d.ua && 12 > d.ua ? "AM" : "PM",\n              "%S": (d) => h(d.Ba, 2),\n              "%t": () => "	",\n              "%u": (d) => d.na || 7,\n              "%U": (d) => h(Math.floor((d.sa + 7 - d.na) / 7), 2),\n              "%V": (d) => {\n                var n = Math.floor((d.sa + 7 - (d.na + 6) % 7) / 7);\n                2 >= (d.na + 371 - d.sa - 2) % 7 && n++;\n                if (n)\n                  53 == n && (p = (d.na + 371 - d.sa) % 7, 4 == p || 3 == p && U(d.ta) || (n = 1));\n                else {\n                  n = 52;\n                  var p = (d.na + 7 - d.sa - 1) % 7;\n                  (4 == p || 5 == p && U(d.ta % 400 - 1)) && n++;\n                }\n                return h(n, 2);\n              },\n              "%w": (d) => d.na,\n              "%W": (d) => h(Math.floor((d.sa + 7 - (d.na + 6) % 7) / 7), 2),\n              "%y": (d) => (d.ta + 1900).toString().substring(2),\n              "%Y": (d) => d.ta + 1900,\n              "%z": (d) => {\n                d = d.za;\n                var n = 0 <= d;\n                d = Math.abs(d) / 60;\n                return (n ? "+" : "-") + String("0000" + (d / 60 * 100 + d % 60)).slice(-4);\n              },\n              "%Z": (d) => d.Ca,\n              "%%": () => "%"\n            };\n            c = c.replace(/%%/g, "\\0\\0");\n            for (t in r)\n              c.includes(t) && (c = c.replace(new RegExp(t, "g"), r[t](e)));\n            c = c.replace(/\\0\\0/g, "%");\n            t = Fa(c);\n            if (t.length > b)\n              return 0;\n            H.set(t, a >>> 0);\n            return t.length - 1;\n          }\n          var Ia = { a: function(a, b, c) {\n            a >>>= 0;\n            var e = new qa(a);\n            K[e.wa + 16 >>> 2 >>> 0] = 0;\n            K[e.wa + 4 >>> 2 >>> 0] = b >>> 0;\n            K[e.wa + 8 >>> 2 >>> 0] = c >>> 0;\n            ra = a;\n            sa++;\n            throw ra;\n          }, e: function() {\n            return 0;\n          }, H: function() {\n          }, x: function() {\n          }, z: function() {\n          }, J: function() {\n            return 0;\n          }, F: function() {\n          }, A: function() {\n          }, E: function() {\n          }, g: function() {\n          }, y: function() {\n          }, v: function() {\n          }, G: function() {\n          }, w: function() {\n          }, k: () => 1, I: function(a, b, c) {\n            b >>>= 0;\n            return I.copyWithin(a >>> 0 >>> 0, b >>> 0, b + (c >>> 0) >>> 0);\n          }, n: function(a, b, c) {\n            a = b + 2097152 >>> 0 < 4194305 - !!a ? (a >>> 0) + 4294967296 * b : NaN;\n            c >>>= 0;\n            a = new Date(1e3 * a);\n            J[c >>> 2 >>> 0] = a.getUTCSeconds();\n            J[c + 4 >>> 2 >>> 0] = a.getUTCMinutes();\n            J[c + 8 >>> 2 >>> 0] = a.getUTCHours();\n            J[c + 12 >>> 2 >>> 0] = a.getUTCDate();\n            J[c + 16 >>> 2 >>> 0] = a.getUTCMonth();\n            J[c + 20 >>> 2 >>> 0] = a.getUTCFullYear() - 1900;\n            J[c + 24 >>> 2 >>> 0] = a.getUTCDay();\n            J[c + 28 >>> 2 >>> 0] = (a.getTime() - Date.UTC(a.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0;\n          }, o: function(a, b, c) {\n            a = b + 2097152 >>> 0 < 4194305 - !!a ? (a >>> 0) + 4294967296 * b : NaN;\n            c >>>= 0;\n            a = new Date(1e3 * a);\n            J[c >>> 2 >>> 0] = a.getSeconds();\n            J[c + 4 >>> 2 >>> 0] = a.getMinutes();\n            J[c + 8 >>> 2 >>> 0] = a.getHours();\n            J[c + 12 >>> 2 >>> 0] = a.getDate();\n            J[c + 16 >>> 2 >>> 0] = a.getMonth();\n            J[c + 20 >>> 2 >>> 0] = a.getFullYear() - 1900;\n            J[c + 24 >>> 2 >>> 0] = a.getDay();\n            J[c + 28 >>> 2 >>> 0] = (U(a.getFullYear()) ? za : Aa)[a.getMonth()] + a.getDate() - 1 | 0;\n            J[c + 36 >>> 2 >>> 0] = -(60 * a.getTimezoneOffset());\n            b = new Date(a.getFullYear(), 6, 1).getTimezoneOffset();\n            var e = new Date(a.getFullYear(), 0, 1).getTimezoneOffset();\n            J[c + 32 >>> 2 >>> 0] = (b != e && a.getTimezoneOffset() == Math.min(e, b)) | 0;\n          }, p: function(a) {\n            a >>>= 0;\n            var b = new Date(\n              J[a + 20 >>> 2 >>> 0] + 1900,\n              J[a + 16 >>> 2 >>> 0],\n              J[a + 12 >>> 2 >>> 0],\n              J[a + 8 >>> 2 >>> 0],\n              J[a + 4 >>> 2 >>> 0],\n              J[a >>> 2 >>> 0],\n              0\n            ), c = J[a + 32 >>> 2 >>> 0], e = b.getTimezoneOffset(), g = new Date(b.getFullYear(), 6, 1).getTimezoneOffset(), h = new Date(b.getFullYear(), 0, 1).getTimezoneOffset(), m = Math.min(h, g);\n            0 > c ? J[a + 32 >>> 2 >>> 0] = Number(g != h && m == e) : 0 < c != (m == e) && (g = Math.max(h, g), b.setTime(b.getTime() + 6e4 * ((0 < c ? m : g) - e)));\n            J[a + 24 >>> 2 >>> 0] = b.getDay();\n            J[a + 28 >>> 2 >>> 0] = (U(b.getFullYear()) ? za : Aa)[b.getMonth()] + b.getDate() - 1 | 0;\n            J[a >>> 2 >>> 0] = b.getSeconds();\n            J[a + 4 >>> 2 >>> 0] = b.getMinutes();\n            J[a + 8 >>> 2 >>> 0] = b.getHours();\n            J[a + 12 >>> 2 >>> 0] = b.getDate();\n            J[a + 16 >>> 2 >>> 0] = b.getMonth();\n            J[a + 20 >>> 2 >>> 0] = b.getYear();\n            a = b.getTime();\n            a = isNaN(a) ? -1 : a / 1e3;\n            Ha((R = a, 1 <= +Math.abs(R) ? 0 < R ? +Math.floor(R / 4294967296) >>> 0 : ~~+Math.ceil((R - +(~~R >>> 0)) / 4294967296) >>> 0 : 0));\n            return a >>> 0;\n          }, l: function() {\n            return -52;\n          }, m: function() {\n          }, t: function(a, b, c, e) {\n            c >>>= 0;\n            e >>>= 0;\n            var g = (/* @__PURE__ */ new Date()).getFullYear(), h = new Date(g, 0, 1), m = new Date(g, 6, 1);\n            g = h.getTimezoneOffset();\n            var q = m.getTimezoneOffset();\n            K[a >>> 0 >>> 2 >>> 0] = 60 * Math.max(g, q);\n            J[b >>> 0 >>> 2 >>> 0] = Number(g != q);\n            a = (x) => x.toLocaleTimeString(void 0, { hour12: false, timeZoneName: "short" }).split(" ")[1];\n            h = a(h);\n            m = a(m);\n            q < g ? (T(h, I, c, 17), T(m, I, e, 17)) : (T(h, I, e, 17), T(m, I, c, 17));\n          }, d: () => {\n            ia("");\n          }, B: function(a, b, c) {\n            a >>>= 0;\n            b >>>= 0;\n            c >>>= 0;\n            V.length = 0;\n            for (var e; e = I[b++ >>> 0]; ) {\n              var g = 105 != e;\n              g &= 112 != e;\n              c += g && c % 8 ? 4 : 0;\n              V.push(112 == e ? K[c >>> 2 >>> 0] : 105 == e ? J[c >>> 2 >>> 0] : ea[c >>> 3 >>> 0]);\n              c += g ? 8 : 4;\n            }\n            return pa[a](...V);\n          }, h: () => Date.now(), u: function() {\n            return 4294901760;\n          }, b: () => performance.now(), s: function(a) {\n            a >>>= 0;\n            var b = I.length;\n            if (4294901760 < a)\n              return false;\n            for (var c = 1; 4 >= c; c *= 2) {\n              var e = b * (1 + 0.2 / c);\n              e = Math.min(e, a + 100663296);\n              var g = Math;\n              e = Math.max(a, e);\n              a: {\n                g = (g.min.call(g, 4294901760, e + (65536 - e % 65536) % 65536) - G.buffer.byteLength + 65535) / 65536;\n                try {\n                  G.grow(g);\n                  fa();\n                  var h = 1;\n                  break a;\n                } catch (m) {\n                }\n                h = void 0;\n              }\n              if (h)\n                return true;\n            }\n            return false;\n          }, C: function(a, b) {\n            a >>>= 0;\n            b >>>= 0;\n            var c = 0;\n            Ba().forEach((e, g) => {\n              var h = b + c;\n              g = K[a + 4 * g >>> 2 >>> 0] = h;\n              for (h = 0; h < e.length; ++h)\n                H[g++ >>> 0] = e.charCodeAt(h);\n              H[g >>> 0] = 0;\n              c += e.length + 1;\n            });\n            return 0;\n          }, D: function(a, b) {\n            a >>>= 0;\n            b >>>= 0;\n            var c = Ba();\n            K[a >>> 2 >>> 0] = c.length;\n            var e = 0;\n            c.forEach((g) => e += g.length + 1);\n            K[b >>> 2 >>> 0] = e;\n            return 0;\n          }, f: () => 52, j: function() {\n            return 52;\n          }, q: function() {\n            return 70;\n          }, i: function(a, b, c, e) {\n            b >>>= 0;\n            c >>>= 0;\n            e >>>= 0;\n            for (var g = 0, h = 0; h < c; h++) {\n              var m = K[b >>> 2 >>> 0], q = K[b + 4 >>> 2 >>> 0];\n              b += 8;\n              for (var x = 0; x < q; x++) {\n                var r = I[m + x >>> 0], t = Ca[a];\n                0 === r || 10 === r ? ((1 === a ? ca : F)(ua(t, 0)), t.length = 0) : t.push(r);\n              }\n              g += q;\n            }\n            K[e >>> 2 >>> 0] = g;\n            return 0;\n          }, r: Ga, c: function(a, b, c, e) {\n            return Ga(a >>> 0, b >>> 0, c >>> 0, e >>> 0);\n          } }, Y = function() {\n            function a(c) {\n              Y = c.exports;\n              Y = Ja();\n              G = Y.K;\n              fa();\n              M.unshift(Y.L);\n              N--;\n              0 == N && (null !== O && (clearInterval(O), O = null), P && (c = P, P = null, c()));\n              return Y;\n            }\n            var b = { a: Ia };\n            N++;\n            if (f.instantiateWasm)\n              try {\n                return f.instantiateWasm(b, a);\n              } catch (c) {\n                F(`Module.instantiateWasm callback failed with error: ${c}`), l(c);\n              }\n            oa(b, function(c) {\n              a(c.instance);\n            }).catch(l);\n            return {};\n          }();\n          f._OrtInit = (a, b) => (f._OrtInit = Y.M)(a, b);\n          f._OrtGetLastError = (a, b) => (f._OrtGetLastError = Y.N)(a, b);\n          f._OrtCreateSessionOptions = (a, b, c, e, g, h, m, q, x, r) => (f._OrtCreateSessionOptions = Y.O)(a, b, c, e, g, h, m, q, x, r);\n          f._OrtAppendExecutionProvider = (a, b) => (f._OrtAppendExecutionProvider = Y.P)(a, b);\n          f._OrtAddFreeDimensionOverride = (a, b, c) => (f._OrtAddFreeDimensionOverride = Y.Q)(a, b, c);\n          f._OrtAddSessionConfigEntry = (a, b, c) => (f._OrtAddSessionConfigEntry = Y.R)(a, b, c);\n          f._OrtReleaseSessionOptions = (a) => (f._OrtReleaseSessionOptions = Y.S)(a);\n          f._OrtCreateSession = (a, b, c) => (f._OrtCreateSession = Y.T)(a, b, c);\n          f._OrtReleaseSession = (a) => (f._OrtReleaseSession = Y.U)(a);\n          f._OrtGetInputOutputCount = (a, b, c) => (f._OrtGetInputOutputCount = Y.V)(a, b, c);\n          f._OrtGetInputName = (a, b) => (f._OrtGetInputName = Y.W)(a, b);\n          f._OrtGetOutputName = (a, b) => (f._OrtGetOutputName = Y.X)(a, b);\n          f._OrtFree = (a) => (f._OrtFree = Y.Y)(a);\n          f._OrtCreateTensor = (a, b, c, e, g, h) => (f._OrtCreateTensor = Y.Z)(a, b, c, e, g, h);\n          f._OrtGetTensorData = (a, b, c, e, g) => (f._OrtGetTensorData = Y._)(a, b, c, e, g);\n          f._OrtReleaseTensor = (a) => (f._OrtReleaseTensor = Y.$)(a);\n          f._OrtCreateRunOptions = (a, b, c, e) => (f._OrtCreateRunOptions = Y.aa)(a, b, c, e);\n          f._OrtAddRunConfigEntry = (a, b, c) => (f._OrtAddRunConfigEntry = Y.ba)(a, b, c);\n          f._OrtReleaseRunOptions = (a) => (f._OrtReleaseRunOptions = Y.ca)(a);\n          f._OrtCreateBinding = (a) => (f._OrtCreateBinding = Y.da)(a);\n          f._OrtBindInput = (a, b, c) => (f._OrtBindInput = Y.ea)(a, b, c);\n          f._OrtBindOutput = (a, b, c, e) => (f._OrtBindOutput = Y.fa)(a, b, c, e);\n          f._OrtClearBoundOutputs = (a) => (f._OrtClearBoundOutputs = Y.ga)(a);\n          f._OrtReleaseBinding = (a) => (f._OrtReleaseBinding = Y.ha)(a);\n          f._OrtRunWithBinding = (a, b, c, e, g) => (f._OrtRunWithBinding = Y.ia)(a, b, c, e, g);\n          f._OrtRun = (a, b, c, e, g, h, m, q) => (f._OrtRun = Y.ja)(a, b, c, e, g, h, m, q);\n          f._OrtEndProfiling = (a) => (f._OrtEndProfiling = Y.ka)(a);\n          f._malloc = (a) => (f._malloc = Y.la)(a);\n          f._free = (a) => (f._free = Y.ma)(a);\n          var Ha = (a) => (Ha = Y.oa)(a), Ka = (a) => (Ka = Y.pa)(a), La = (a) => (La = Y.qa)(a), Ma = () => (Ma = Y.ra)();\n          function Ja() {\n            var a = Y;\n            a = Object.assign({}, a);\n            var b = (c) => (e) => c(e) >>> 0;\n            a.la = b(a.la);\n            a.qa = b(a.qa);\n            a.ra = ((c) => () => c() >>> 0)(a.ra);\n            return a;\n          }\n          f.stackSave = () => Ma();\n          f.stackRestore = (a) => Ka(a);\n          f.stackAlloc = (a) => La(a);\n          f.UTF8ToString = S;\n          f.stringToUTF8 = (a, b, c) => T(a, I, b, c);\n          f.lengthBytesUTF8 = va;\n          var Z;\n          P = function Na() {\n            Z || Oa();\n            Z || (P = Na);\n          };\n          function Oa() {\n            if (!(0 < N)) {\n              if (f.preRun)\n                for ("function" == typeof f.preRun && (f.preRun = [f.preRun]); f.preRun.length; ) {\n                  var a = f.preRun.shift();\n                  L.unshift(a);\n                }\n              for (; 0 < L.length; )\n                L.shift()(f);\n              if (!(0 < N || Z || (Z = true, f.calledRun = true, da))) {\n                for (; 0 < M.length; )\n                  M.shift()(f);\n                for (k(f); 0 < ha.length; )\n                  ha.shift()(f);\n              }\n            }\n          }\n          Oa();\n          return readyPromise;\n        };\n      })();\n      if (typeof exports === "object" && typeof module === "object")\n        module.exports = ortWasm;\n      else if (typeof define === "function" && define["amd"])\n        define([], () => ortWasm);\n    }\n  });\n\n  // nodejs-ignore:worker_threads\n  var require_worker_threads = __commonJS({\n    "nodejs-ignore:worker_threads"() {\n    }\n  });\n\n  // nodejs-ignore:perf_hooks\n  var require_perf_hooks = __commonJS({\n    "nodejs-ignore:perf_hooks"() {\n    }\n  });\n\n  // nodejs-ignore:os\n  var os_exports = {};\n  __export(os_exports, {\n    cpus: () => cpus\n  });\n  var cpus;\n  var init_os = __esm({\n    "nodejs-ignore:os"() {\n      cpus = void 0;\n    }\n  });\n\n  // web/lib/wasm/binding/ort-wasm-threaded.js\n  var require_ort_wasm_threaded = __commonJS({\n    "web/lib/wasm/binding/ort-wasm-threaded.js"(exports, module) {\n      "use strict";\n      var ortWasmThreaded = (() => {\n        var _scriptDir = typeof document != "undefined" ? document.currentScript?.src : void 0;\n        if (typeof __filename != "undefined")\n          _scriptDir ||= __filename;\n        return function(moduleArg = {}) {\n          function aa() {\n            e.buffer != l.buffer && m();\n            return l;\n          }\n          function n() {\n            e.buffer != l.buffer && m();\n            return ba;\n          }\n          function p() {\n            e.buffer != l.buffer && m();\n            return ca;\n          }\n          function r() {\n            e.buffer != l.buffer && m();\n            return da;\n          }\n          function ea() {\n            e.buffer != l.buffer && m();\n            return fa;\n          }\n          var v = moduleArg, ha, x, readyPromise = new Promise((a, b) => {\n            ha = a;\n            x = b;\n          }), ia = Object.assign({}, v), ja = "./this.program", z = (a, b) => {\n            throw b;\n          }, ka = "object" == typeof window, A = "function" == typeof importScripts, B = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, D = v.ENVIRONMENT_IS_PTHREAD || false, E = "";\n          function la(a) {\n            return v.locateFile ? v.locateFile(a, E) : E + a;\n          }\n          var ma, G, H;\n          if (B) {\n            var fs = (init_fs(), __toCommonJS(fs_exports)), na = (init_path(), __toCommonJS(path_exports));\n            E = A ? na.dirname(E) + "/" : __dirname + "/";\n            ma = (a, b) => {\n              a = I(a) ? new URL(a) : na.normalize(a);\n              return fs.readFileSync(a, b ? void 0 : "utf8");\n            };\n            H = (a) => {\n              a = ma(a, true);\n              a.buffer || (a = new Uint8Array(a));\n              return a;\n            };\n            G = (a, b, c, d = true) => {\n              a = I(a) ? new URL(a) : na.normalize(a);\n              fs.readFile(a, d ? void 0 : "utf8", (h, g) => {\n                h ? c(h) : b(d ? g.buffer : g);\n              });\n            };\n            !v.thisProgram && 1 < process.argv.length && (ja = process.argv[1].replace(/\\\\/g, "/"));\n            process.argv.slice(2);\n            z = (a, b) => {\n              process.exitCode = a;\n              throw b;\n            };\n            global.Worker = require_worker_threads().Worker;\n          } else if (ka || A)\n            A ? E = self.location.href : "undefined" != typeof document && document.currentScript && (E = document.currentScript.src), typeof _scriptDir !== "undefined" && _scriptDir && (E = _scriptDir), E.startsWith("blob:") ? E = "" : E = E.substr(0, E.replace(/[?#].*/, "").lastIndexOf("/") + 1), B || (ma = (a) => {\n              var b = new XMLHttpRequest();\n              b.open("GET", a, false);\n              b.send(null);\n              return b.responseText;\n            }, A && (H = (a) => {\n              var b = new XMLHttpRequest();\n              b.open("GET", a, false);\n              b.responseType = "arraybuffer";\n              b.send(null);\n              return new Uint8Array(b.response);\n            }), G = (a, b, c) => {\n              var d = new XMLHttpRequest();\n              d.open("GET", a, true);\n              d.responseType = "arraybuffer";\n              d.onload = () => {\n                200 == d.status || 0 == d.status && d.response ? b(d.response) : c();\n              };\n              d.onerror = c;\n              d.send(null);\n            });\n          B && "undefined" == typeof performance && (global.performance = require_perf_hooks().performance);\n          var oa = console.log.bind(console), pa = console.error.bind(console);\n          B && (oa = (...a) => fs.writeSync(1, a.join(" ") + "\\n"), pa = (...a) => fs.writeSync(2, a.join(" ") + "\\n"));\n          var qa = oa, J = pa;\n          Object.assign(v, ia);\n          ia = null;\n          var e, ra, K = false, L, l, ba, ca, da, fa;\n          function m() {\n            var a = e.buffer;\n            v.HEAP8 = l = new Int8Array(a);\n            v.HEAP16 = new Int16Array(a);\n            v.HEAPU8 = ba = new Uint8Array(a);\n            v.HEAPU16 = new Uint16Array(a);\n            v.HEAP32 = ca = new Int32Array(a);\n            v.HEAPU32 = da = new Uint32Array(a);\n            v.HEAPF32 = new Float32Array(a);\n            v.HEAPF64 = fa = new Float64Array(a);\n          }\n          var sa = 16777216;\n          if (D)\n            e = v.wasmMemory;\n          else if (v.wasmMemory)\n            e = v.wasmMemory;\n          else if (e = new WebAssembly.Memory({ initial: sa / 65536, maximum: 65536, shared: true }), !(e.buffer instanceof SharedArrayBuffer))\n            throw J("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 && J("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"), Error("bad memory");\n          m();\n          sa = e.buffer.byteLength;\n          var ta = [], ua = [], va = [], M = 0, wa = null, N = null;\n          function xa() {\n            M--;\n            if (0 == M && (null !== wa && (clearInterval(wa), wa = null), N)) {\n              var a = N;\n              N = null;\n              a();\n            }\n          }\n          function ya(a) {\n            a = "Aborted(" + a + ")";\n            J(a);\n            K = true;\n            L = 1;\n            a = new WebAssembly.RuntimeError(a + ". Build with -sASSERTIONS for more info.");\n            x(a);\n            throw a;\n          }\n          var za = (a) => a.startsWith("data:application/octet-stream;base64,"), I = (a) => a.startsWith("file://"), O;\n          O = "ort-wasm-threaded.wasm";\n          za(O) || (O = la(O));\n          function Aa(a) {\n            if (H)\n              return H(a);\n            throw "both async and sync fetching of the wasm failed";\n          }\n          function Ba(a) {\n            if (ka || A) {\n              if ("function" == typeof fetch && !I(a))\n                return fetch(a, { credentials: "same-origin" }).then((b) => {\n                  if (!b.ok)\n                    throw `failed to load wasm binary file at \'${a}\'`;\n                  return b.arrayBuffer();\n                }).catch(() => Aa(a));\n              if (G)\n                return new Promise((b, c) => {\n                  G(a, (d) => b(new Uint8Array(d)), c);\n                });\n            }\n            return Promise.resolve().then(() => Aa(a));\n          }\n          function Ca(a, b, c) {\n            return Ba(a).then((d) => WebAssembly.instantiate(d, b)).then(c, (d) => {\n              J(`failed to asynchronously prepare wasm: ${d}`);\n              ya(d);\n            });\n          }\n          function Da(a, b) {\n            var c = O;\n            return "function" != typeof WebAssembly.instantiateStreaming || za(c) || I(c) || B || "function" != typeof fetch ? Ca(c, a, b) : fetch(c, { credentials: "same-origin" }).then((d) => WebAssembly.instantiateStreaming(d, a).then(b, function(h) {\n              J(`wasm streaming compile failed: ${h}`);\n              J("falling back to ArrayBuffer instantiation");\n              return Ca(c, a, b);\n            }));\n          }\n          var P, Ea = { 799444: (a, b, c, d) => {\n            if ("undefined" == typeof v || !v.bb)\n              return 1;\n            a = Q(a >>> 0);\n            a.startsWith("./") && (a = a.substring(2));\n            a = v.bb.get(a);\n            if (!a)\n              return 2;\n            b >>>= 0;\n            c >>>= 0;\n            d >>>= 0;\n            if (b + c > a.byteLength)\n              return 3;\n            try {\n              return n().set(a.subarray(b, b + c), d >>> 0), 0;\n            } catch {\n              return 4;\n            }\n          } };\n          function R(a) {\n            this.name = "ExitStatus";\n            this.message = `Program terminated with exit(${a})`;\n            this.status = a;\n          }\n          var Fa = (a) => {\n            a.terminate();\n            a.onmessage = () => {\n            };\n          }, Ha = (a) => {\n            0 == S.Oa.length && (Ga(), S.Xa(S.Oa[0]));\n            var b = S.Oa.pop();\n            if (!b)\n              return 6;\n            S.Pa.push(b);\n            S.La[a.Na] = b;\n            b.Na = a.Na;\n            var c = { cmd: "run", start_routine: a.gb, arg: a.cb, pthread_ptr: a.Na };\n            B && b.unref();\n            b.postMessage(c, a.mb);\n            return 0;\n          }, T = 0, Ja = (a) => {\n            var b = Ia();\n            a = a();\n            U(b);\n            return a;\n          }, V = (a, b, ...c) => Ja(() => {\n            for (var d = c.length, h = Ka(8 * d), g = h >>> 3, k = 0; k < c.length; k++) {\n              var t = c[k];\n              ea()[g + k >>> 0] = t;\n            }\n            return La(a, 0, d, h, b);\n          });\n          function Ma(a) {\n            if (D)\n              return V(0, 1, a);\n            L = a;\n            0 < T || (S.hb(), v.onExit?.(a), K = true);\n            z(a, new R(a));\n          }\n          var Oa = (a) => {\n            L = a;\n            if (D)\n              throw Na(a), "unwind";\n            Ma(a);\n          };\n          function Pa() {\n            for (var a = v.numThreads; a--; )\n              Ga();\n            ta.unshift(() => {\n              M++;\n              Qa(() => xa());\n            });\n          }\n          function Ga() {\n            var a = la("ort-wasm-threaded.worker.js");\n            a = new Worker(a);\n            S.Oa.push(a);\n          }\n          function Qa(a) {\n            D ? a() : Promise.all(S.Oa.map(S.Xa)).then(a);\n          }\n          var S = { Oa: [], Pa: [], ab: [], La: {}, Va() {\n            D ? (S.receiveObjectTransfer = S.fb, S.threadInitTLS = S.$a, S.setExitStatus = S.Za) : Pa();\n          }, Za: (a) => L = a, pb: ["$terminateWorker"], hb: () => {\n            for (var a of S.Pa)\n              Fa(a);\n            for (a of S.Oa)\n              Fa(a);\n            S.Oa = [];\n            S.Pa = [];\n            S.La = [];\n          }, Ya: (a) => {\n            var b = a.Na;\n            delete S.La[b];\n            S.Oa.push(a);\n            S.Pa.splice(S.Pa.indexOf(a), 1);\n            a.Na = 0;\n            Ra(b);\n          }, fb() {\n          }, $a() {\n            S.ab.forEach((a) => a());\n          }, Xa: (a) => new Promise((b) => {\n            a.onmessage = (g) => {\n              g = g.data;\n              var k = g.cmd;\n              if (g.targetThread && g.targetThread != W()) {\n                var t = S.La[g.targetThread];\n                t ? t.postMessage(g, g.transferList) : J(`Internal error! Worker sent a message "${k}" to target pthread ${g.targetThread}, but that thread no longer exists!`);\n              } else if ("checkMailbox" === k)\n                Sa();\n              else if ("spawnThread" === k)\n                Ha(g);\n              else if ("cleanupThread" === k)\n                S.Ya(S.La[g.thread]);\n              else if ("killThread" === k)\n                g = g.thread, k = S.La[g], delete S.La[g], Fa(k), Ra(g), S.Pa.splice(S.Pa.indexOf(k), 1), k.Na = 0;\n              else if ("cancelThread" === k)\n                S.La[g.thread].postMessage({ cmd: "cancel" });\n              else if ("loaded" === k)\n                a.loaded = true, B && !a.Na && a.unref(), b(a);\n              else if ("alert" === k)\n                alert(`Thread ${g.threadId}: ${g.text}`);\n              else if ("setimmediate" === g.target)\n                a.postMessage(g);\n              else if ("callHandler" === k)\n                v[g.handler](...g.args);\n              else\n                k && J(`worker sent an unknown command ${k}`);\n            };\n            a.onerror = (g) => {\n              J(`${"worker sent an error!"} ${g.filename}:${g.lineno}: ${g.message}`);\n              throw g;\n            };\n            B && (a.on("message", (g) => a.onmessage({ data: g })), a.on("error", (g) => a.onerror(g)));\n            var c = [], d = ["onExit"], h;\n            for (h of d)\n              v.hasOwnProperty(h) && c.push(h);\n            a.postMessage({ cmd: "load", handlers: c, urlOrBlob: v.mainScriptUrlOrBlob || _scriptDir, wasmMemory: e, wasmModule: ra });\n          }) };\n          v.PThread = S;\n          var Ta = (a) => {\n            for (; 0 < a.length; )\n              a.shift()(v);\n          };\n          v.establishStackSpace = () => {\n            var a = W(), b = r()[a + 52 >>> 2 >>> 0];\n            a = r()[a + 56 >>> 2 >>> 0];\n            Ua(b, b - a);\n            U(b);\n          };\n          function Na(a) {\n            if (D)\n              return V(1, 0, a);\n            Oa(a);\n          }\n          var Va = [], Wa;\n          v.invokeEntryPoint = (a, b) => {\n            T = 0;\n            var c = Va[a];\n            c || (a >= Va.length && (Va.length = a + 1), Va[a] = c = Wa.get(a));\n            a = c(b);\n            0 < T ? S.Za(a) : Xa(a);\n          };\n          class Ya {\n            constructor(a) {\n              this.Ua = a - 24;\n            }\n            Va(a, b) {\n              r()[this.Ua + 16 >>> 2 >>> 0] = 0;\n              r()[this.Ua + 4 >>> 2 >>> 0] = a;\n              r()[this.Ua + 8 >>> 2 >>> 0] = b;\n            }\n          }\n          var Za = 0, $a = 0;\n          function ab(a, b, c, d) {\n            return D ? V(2, 1, a, b, c, d) : bb(a, b, c, d);\n          }\n          function bb(a, b, c, d) {\n            a >>>= 0;\n            b >>>= 0;\n            c >>>= 0;\n            d >>>= 0;\n            if ("undefined" == typeof SharedArrayBuffer)\n              return J("Current environment does not support SharedArrayBuffer, pthreads are not available!"), 6;\n            var h = [];\n            if (D && 0 === h.length)\n              return ab(a, b, c, d);\n            a = { gb: c, Na: a, cb: d, mb: h };\n            return D ? (a.ob = "spawnThread", postMessage(a, h), 0) : Ha(a);\n          }\n          var cb = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0, db = (a, b, c) => {\n            b >>>= 0;\n            var d = b + c;\n            for (c = b; a[c] && !(c >= d); )\n              ++c;\n            if (16 < c - b && a.buffer && cb)\n              return cb.decode(a.buffer instanceof SharedArrayBuffer ? a.slice(b, c) : a.subarray(b, c));\n            for (d = ""; b < c; ) {\n              var h = a[b++];\n              if (h & 128) {\n                var g = a[b++] & 63;\n                if (192 == (h & 224))\n                  d += String.fromCharCode((h & 31) << 6 | g);\n                else {\n                  var k = a[b++] & 63;\n                  h = 224 == (h & 240) ? (h & 15) << 12 | g << 6 | k : (h & 7) << 18 | g << 12 | k << 6 | a[b++] & 63;\n                  65536 > h ? d += String.fromCharCode(h) : (h -= 65536, d += String.fromCharCode(55296 | h >> 10, 56320 | h & 1023));\n                }\n              } else\n                d += String.fromCharCode(h);\n            }\n            return d;\n          }, Q = (a, b) => (a >>>= 0) ? db(n(), a, b) : "";\n          function eb(a, b, c) {\n            return D ? V(3, 1, a, b, c) : 0;\n          }\n          function fb(a, b) {\n            if (D)\n              return V(4, 1, a, b);\n          }\n          var gb = (a) => {\n            for (var b = 0, c = 0; c < a.length; ++c) {\n              var d = a.charCodeAt(c);\n              127 >= d ? b++ : 2047 >= d ? b += 2 : 55296 <= d && 57343 >= d ? (b += 4, ++c) : b += 3;\n            }\n            return b;\n          }, hb = (a, b, c, d) => {\n            c >>>= 0;\n            if (!(0 < d))\n              return 0;\n            var h = c;\n            d = c + d - 1;\n            for (var g = 0; g < a.length; ++g) {\n              var k = a.charCodeAt(g);\n              if (55296 <= k && 57343 >= k) {\n                var t = a.charCodeAt(++g);\n                k = 65536 + ((k & 1023) << 10) | t & 1023;\n              }\n              if (127 >= k) {\n                if (c >= d)\n                  break;\n                b[c++ >>> 0] = k;\n              } else {\n                if (2047 >= k) {\n                  if (c + 1 >= d)\n                    break;\n                  b[c++ >>> 0] = 192 | k >> 6;\n                } else {\n                  if (65535 >= k) {\n                    if (c + 2 >= d)\n                      break;\n                    b[c++ >>> 0] = 224 | k >> 12;\n                  } else {\n                    if (c + 3 >= d)\n                      break;\n                    b[c++ >>> 0] = 240 | k >> 18;\n                    b[c++ >>> 0] = 128 | k >> 12 & 63;\n                  }\n                  b[c++ >>> 0] = 128 | k >> 6 & 63;\n                }\n                b[c++ >>> 0] = 128 | k & 63;\n              }\n            }\n            b[c >>> 0] = 0;\n            return c - h;\n          }, X = (a, b, c) => hb(a, n(), b, c);\n          function ib(a, b) {\n            if (D)\n              return V(5, 1, a, b);\n          }\n          function jb(a, b, c) {\n            if (D)\n              return V(6, 1, a, b, c);\n          }\n          function kb(a, b, c) {\n            return D ? V(7, 1, a, b, c) : 0;\n          }\n          function lb(a, b) {\n            if (D)\n              return V(8, 1, a, b);\n          }\n          function mb(a, b, c) {\n            if (D)\n              return V(9, 1, a, b, c);\n          }\n          function nb(a, b, c, d) {\n            if (D)\n              return V(10, 1, a, b, c, d);\n          }\n          function ob(a, b, c, d) {\n            if (D)\n              return V(11, 1, a, b, c, d);\n          }\n          function pb(a, b, c, d) {\n            if (D)\n              return V(12, 1, a, b, c, d);\n          }\n          function qb(a) {\n            if (D)\n              return V(13, 1, a);\n          }\n          function rb(a, b) {\n            if (D)\n              return V(14, 1, a, b);\n          }\n          function sb(a, b, c) {\n            if (D)\n              return V(15, 1, a, b, c);\n          }\n          function tb(a) {\n            a >>>= 0;\n            "function" === typeof Atomics.nb && (Atomics.nb(p(), a >>> 2, a).value.then(Sa), a += 128, Atomics.store(p(), a >>> 2, 1));\n          }\n          v.__emscripten_thread_mailbox_await = tb;\n          var Sa = () => {\n            var a = W();\n            if (a && (tb(a), a = ub, !K))\n              try {\n                if (a(), !(0 < T))\n                  try {\n                    D ? Xa(L) : Oa(L);\n                  } catch (b) {\n                    b instanceof R || "unwind" == b || z(1, b);\n                  }\n              } catch (b) {\n                b instanceof R || "unwind" == b || z(1, b);\n              }\n          };\n          v.checkMailbox = Sa;\n          var vb = [], Y = (a) => 0 === a % 4 && (0 !== a % 100 || 0 === a % 400), wb = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], xb = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];\n          function yb(a, b, c, d, h, g, k, t) {\n            return D ? V(16, 1, a, b, c, d, h, g, k, t) : -52;\n          }\n          function zb(a, b, c, d, h, g, k) {\n            if (D)\n              return V(17, 1, a, b, c, d, h, g, k);\n          }\n          var Ab = [], Bb = {}, Db = () => {\n            if (!Cb) {\n              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", _: ja || "./this.program" }, b;\n              for (b in Bb)\n                void 0 === Bb[b] ? delete a[b] : a[b] = Bb[b];\n              var c = [];\n              for (b in a)\n                c.push(`${b}=${a[b]}`);\n              Cb = c;\n            }\n            return Cb;\n          }, Cb;\n          function Eb(a, b) {\n            if (D)\n              return V(18, 1, a, b);\n            a >>>= 0;\n            b >>>= 0;\n            var c = 0;\n            Db().forEach((d, h) => {\n              var g = b + c;\n              h = r()[a + 4 * h >>> 2 >>> 0] = g;\n              for (g = 0; g < d.length; ++g)\n                aa()[h++ >>> 0] = d.charCodeAt(g);\n              aa()[h >>> 0] = 0;\n              c += d.length + 1;\n            });\n            return 0;\n          }\n          function Ib(a, b) {\n            if (D)\n              return V(19, 1, a, b);\n            a >>>= 0;\n            b >>>= 0;\n            var c = Db();\n            r()[a >>> 2 >>> 0] = c.length;\n            var d = 0;\n            c.forEach((h) => d += h.length + 1);\n            r()[b >>> 2 >>> 0] = d;\n            return 0;\n          }\n          function Jb(a) {\n            return D ? V(20, 1, a) : 52;\n          }\n          function Kb(a, b, c, d) {\n            return D ? V(21, 1, a, b, c, d) : 52;\n          }\n          function Lb(a, b, c, d, h) {\n            return D ? V(22, 1, a, b, c, d, h) : 70;\n          }\n          var Mb = [null, [], []];\n          function Nb(a, b, c, d) {\n            if (D)\n              return V(23, 1, a, b, c, d);\n            b >>>= 0;\n            c >>>= 0;\n            d >>>= 0;\n            for (var h = 0, g = 0; g < c; g++) {\n              var k = r()[b >>> 2 >>> 0], t = r()[b + 4 >>> 2 >>> 0];\n              b += 8;\n              for (var C = 0; C < t; C++) {\n                var w = n()[k + C >>> 0], y = Mb[a];\n                0 === w || 10 === w ? ((1 === a ? qa : J)(db(y, 0)), y.length = 0) : y.push(w);\n              }\n              h += t;\n            }\n            r()[d >>> 2 >>> 0] = h;\n            return 0;\n          }\n          var Ob = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], Pb = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n          function Qb(a) {\n            var b = Array(gb(a) + 1);\n            hb(a, b, 0, b.length);\n            return b;\n          }\n          var Rb = (a, b) => {\n            aa().set(a, b >>> 0);\n          };\n          function Sb(a, b, c, d) {\n            function h(f, q, u) {\n              for (f = "number" == typeof f ? f.toString() : f || ""; f.length < q; )\n                f = u[0] + f;\n              return f;\n            }\n            function g(f, q) {\n              return h(f, q, "0");\n            }\n            function k(f, q) {\n              function u(Fb) {\n                return 0 > Fb ? -1 : 0 < Fb ? 1 : 0;\n              }\n              var F;\n              0 === (F = u(f.getFullYear() - q.getFullYear())) && 0 === (F = u(f.getMonth() - q.getMonth())) && (F = u(f.getDate() - q.getDate()));\n              return F;\n            }\n            function t(f) {\n              switch (f.getDay()) {\n                case 0:\n                  return new Date(f.getFullYear() - 1, 11, 29);\n                case 1:\n                  return f;\n                case 2:\n                  return new Date(f.getFullYear(), 0, 3);\n                case 3:\n                  return new Date(\n                    f.getFullYear(),\n                    0,\n                    2\n                  );\n                case 4:\n                  return new Date(f.getFullYear(), 0, 1);\n                case 5:\n                  return new Date(f.getFullYear() - 1, 11, 31);\n                case 6:\n                  return new Date(f.getFullYear() - 1, 11, 30);\n              }\n            }\n            function C(f) {\n              var q = f.Qa;\n              for (f = new Date(new Date(f.Ra + 1900, 0, 1).getTime()); 0 < q; ) {\n                var u = f.getMonth(), F = (Y(f.getFullYear()) ? Ob : Pb)[u];\n                if (q > F - f.getDate())\n                  q -= F - f.getDate() + 1, f.setDate(1), 11 > u ? f.setMonth(u + 1) : (f.setMonth(0), f.setFullYear(f.getFullYear() + 1));\n                else {\n                  f.setDate(f.getDate() + q);\n                  break;\n                }\n              }\n              u = new Date(f.getFullYear() + 1, 0, 4);\n              q = t(new Date(\n                f.getFullYear(),\n                0,\n                4\n              ));\n              u = t(u);\n              return 0 >= k(q, f) ? 0 >= k(u, f) ? f.getFullYear() + 1 : f.getFullYear() : f.getFullYear() - 1;\n            }\n            a >>>= 0;\n            b >>>= 0;\n            c >>>= 0;\n            d >>>= 0;\n            var w = r()[d + 40 >>> 2 >>> 0];\n            d = { kb: p()[d >>> 2 >>> 0], jb: p()[d + 4 >>> 2 >>> 0], Sa: p()[d + 8 >>> 2 >>> 0], Wa: p()[d + 12 >>> 2 >>> 0], Ta: p()[d + 16 >>> 2 >>> 0], Ra: p()[d + 20 >>> 2 >>> 0], Ma: p()[d + 24 >>> 2 >>> 0], Qa: p()[d + 28 >>> 2 >>> 0], qb: p()[d + 32 >>> 2 >>> 0], ib: p()[d + 36 >>> 2 >>> 0], lb: w ? Q(w) : "" };\n            c = Q(c);\n            w = {\n              "%c": "%a %b %d %H:%M:%S %Y",\n              "%D": "%m/%d/%y",\n              "%F": "%Y-%m-%d",\n              "%h": "%b",\n              "%r": "%I:%M:%S %p",\n              "%R": "%H:%M",\n              "%T": "%H:%M:%S",\n              "%x": "%m/%d/%y",\n              "%X": "%H:%M:%S",\n              "%Ec": "%c",\n              "%EC": "%C",\n              "%Ex": "%m/%d/%y",\n              "%EX": "%H:%M:%S",\n              "%Ey": "%y",\n              "%EY": "%Y",\n              "%Od": "%d",\n              "%Oe": "%e",\n              "%OH": "%H",\n              "%OI": "%I",\n              "%Om": "%m",\n              "%OM": "%M",\n              "%OS": "%S",\n              "%Ou": "%u",\n              "%OU": "%U",\n              "%OV": "%V",\n              "%Ow": "%w",\n              "%OW": "%W",\n              "%Oy": "%y"\n            };\n            for (var y in w)\n              c = c.replace(new RegExp(y, "g"), w[y]);\n            var Gb = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), Hb = "January February March April May June July August September October November December".split(" ");\n            w = {\n              "%a": (f) => Gb[f.Ma].substring(0, 3),\n              "%A": (f) => Gb[f.Ma],\n              "%b": (f) => Hb[f.Ta].substring(0, 3),\n              "%B": (f) => Hb[f.Ta],\n              "%C": (f) => g((f.Ra + 1900) / 100 | 0, 2),\n              "%d": (f) => g(f.Wa, 2),\n              "%e": (f) => h(f.Wa, 2, " "),\n              "%g": (f) => C(f).toString().substring(2),\n              "%G": C,\n              "%H": (f) => g(f.Sa, 2),\n              "%I": (f) => {\n                f = f.Sa;\n                0 == f ? f = 12 : 12 < f && (f -= 12);\n                return g(f, 2);\n              },\n              "%j": (f) => {\n                for (var q = 0, u = 0; u <= f.Ta - 1; q += (Y(f.Ra + 1900) ? Ob : Pb)[u++])\n                  ;\n                return g(f.Wa + q, 3);\n              },\n              "%m": (f) => g(f.Ta + 1, 2),\n              "%M": (f) => g(f.jb, 2),\n              "%n": () => "\\n",\n              "%p": (f) => 0 <= f.Sa && 12 > f.Sa ? "AM" : "PM",\n              "%S": (f) => g(f.kb, 2),\n              "%t": () => "	",\n              "%u": (f) => f.Ma || 7,\n              "%U": (f) => g(Math.floor((f.Qa + 7 - f.Ma) / 7), 2),\n              "%V": (f) => {\n                var q = Math.floor((f.Qa + 7 - (f.Ma + 6) % 7) / 7);\n                2 >= (f.Ma + 371 - f.Qa - 2) % 7 && q++;\n                if (q)\n                  53 == q && (u = (f.Ma + 371 - f.Qa) % 7, 4 == u || 3 == u && Y(f.Ra) || (q = 1));\n                else {\n                  q = 52;\n                  var u = (f.Ma + 7 - f.Qa - 1) % 7;\n                  (4 == u || 5 == u && Y(f.Ra % 400 - 1)) && q++;\n                }\n                return g(q, 2);\n              },\n              "%w": (f) => f.Ma,\n              "%W": (f) => g(Math.floor((f.Qa + 7 - (f.Ma + 6) % 7) / 7), 2),\n              "%y": (f) => (f.Ra + 1900).toString().substring(2),\n              "%Y": (f) => f.Ra + 1900,\n              "%z": (f) => {\n                f = f.ib;\n                var q = 0 <= f;\n                f = Math.abs(f) / 60;\n                return (q ? "+" : "-") + String("0000" + (f / 60 * 100 + f % 60)).slice(-4);\n              },\n              "%Z": (f) => f.lb,\n              "%%": () => "%"\n            };\n            c = c.replace(\n              /%%/g,\n              "\\0\\0"\n            );\n            for (y in w)\n              c.includes(y) && (c = c.replace(new RegExp(y, "g"), w[y](d)));\n            c = c.replace(/\\0\\0/g, "%");\n            y = Qb(c);\n            if (y.length > b)\n              return 0;\n            Rb(y, a);\n            return y.length - 1;\n          }\n          S.Va();\n          var Tb = [Ma, Na, ab, eb, fb, ib, jb, kb, lb, mb, nb, ob, pb, qb, rb, sb, yb, zb, Eb, Ib, Jb, Kb, Lb, Nb], Wb = {\n            b: function(a, b, c) {\n              a >>>= 0;\n              new Ya(a).Va(b >>> 0, c >>> 0);\n              Za = a;\n              $a++;\n              throw Za;\n            },\n            L: function(a) {\n              Ub(a >>> 0, !A, 1, !ka, 131072, false);\n              S.$a();\n            },\n            j: function(a) {\n              a >>>= 0;\n              D ? postMessage({ cmd: "cleanupThread", thread: a }) : S.Ya(S.La[a]);\n            },\n            H: bb,\n            h: eb,\n            S: fb,\n            D: ib,\n            F: jb,\n            T: kb,\n            Q: lb,\n            J: mb,\n            P: nb,\n            n: ob,\n            E: pb,\n            B: qb,\n            R: rb,\n            C: sb,\n            p: () => 1,\n            z: function(a, b) {\n              a >>>= 0;\n              a == b >>> 0 ? setTimeout(Sa) : D ? postMessage({ targetThread: a, cmd: "checkMailbox" }) : (a = S.La[a]) && a.postMessage({ cmd: "checkMailbox" });\n            },\n            I: function(a, b, c, d, h) {\n              b >>>= 0;\n              c >>>= 0;\n              vb.length = d;\n              h = h >>> 0 >>> 3;\n              for (var g = 0; g < d; g++)\n                vb[g] = ea()[h + g >>> 0];\n              a = b ? Ea[b] : Tb[a];\n              S.eb = c;\n              c = a(...vb);\n              S.eb = 0;\n              return c;\n            },\n            K: tb,\n            o: function(a) {\n              B && S.La[a >>> 0].ref();\n            },\n            s: function(a, b, c) {\n              a = b + 2097152 >>> 0 < 4194305 - !!a ? (a >>> 0) + 4294967296 * b : NaN;\n              c >>>= 0;\n              a = new Date(1e3 * a);\n              p()[c >>> 2 >>> 0] = a.getUTCSeconds();\n              p()[c + 4 >>> 2 >>> 0] = a.getUTCMinutes();\n              p()[c + 8 >>> 2 >>> 0] = a.getUTCHours();\n              p()[c + 12 >>> 2 >>> 0] = a.getUTCDate();\n              p()[c + 16 >>> 2 >>> 0] = a.getUTCMonth();\n              p()[c + 20 >>> 2 >>> 0] = a.getUTCFullYear() - 1900;\n              p()[c + 24 >>> 2 >>> 0] = a.getUTCDay();\n              a = (a.getTime() - Date.UTC(a.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0;\n              p()[c + 28 >>> 2 >>> 0] = a;\n            },\n            t: function(a, b, c) {\n              a = b + 2097152 >>> 0 < 4194305 - !!a ? (a >>> 0) + 4294967296 * b : NaN;\n              c >>>= 0;\n              a = new Date(1e3 * a);\n              p()[c >>> 2 >>> 0] = a.getSeconds();\n              p()[c + 4 >>> 2 >>> 0] = a.getMinutes();\n              p()[c + 8 >>> 2 >>> 0] = a.getHours();\n              p()[c + 12 >>> 2 >>> 0] = a.getDate();\n              p()[c + 16 >>> 2 >>> 0] = a.getMonth();\n              p()[c + 20 >>> 2 >>> 0] = a.getFullYear() - 1900;\n              p()[c + 24 >>> 2 >>> 0] = a.getDay();\n              b = (Y(a.getFullYear()) ? wb : xb)[a.getMonth()] + a.getDate() - 1 | 0;\n              p()[c + 28 >>> 2 >>> 0] = b;\n              p()[c + 36 >>> 2 >>> 0] = -(60 * a.getTimezoneOffset());\n              b = new Date(a.getFullYear(), 6, 1).getTimezoneOffset();\n              var d = new Date(a.getFullYear(), 0, 1).getTimezoneOffset();\n              a = (b != d && a.getTimezoneOffset() == Math.min(d, b)) | 0;\n              p()[c + 32 >>> 2 >>> 0] = a;\n            },\n            u: function(a) {\n              a >>>= 0;\n              var b = new Date(p()[a + 20 >>> 2 >>> 0] + 1900, p()[a + 16 >>> 2 >>> 0], p()[a + 12 >>> 2 >>> 0], p()[a + 8 >>> 2 >>> 0], p()[a + 4 >>> 2 >>> 0], p()[a >>> 2 >>> 0], 0), c = p()[a + 32 >>> 2 >>> 0], d = b.getTimezoneOffset(), h = new Date(b.getFullYear(), 6, 1).getTimezoneOffset(), g = new Date(\n                b.getFullYear(),\n                0,\n                1\n              ).getTimezoneOffset(), k = Math.min(g, h);\n              0 > c ? p()[a + 32 >>> 2 >>> 0] = Number(h != g && k == d) : 0 < c != (k == d) && (h = Math.max(g, h), b.setTime(b.getTime() + 6e4 * ((0 < c ? k : h) - d)));\n              p()[a + 24 >>> 2 >>> 0] = b.getDay();\n              c = (Y(b.getFullYear()) ? wb : xb)[b.getMonth()] + b.getDate() - 1 | 0;\n              p()[a + 28 >>> 2 >>> 0] = c;\n              p()[a >>> 2 >>> 0] = b.getSeconds();\n              p()[a + 4 >>> 2 >>> 0] = b.getMinutes();\n              p()[a + 8 >>> 2 >>> 0] = b.getHours();\n              p()[a + 12 >>> 2 >>> 0] = b.getDate();\n              p()[a + 16 >>> 2 >>> 0] = b.getMonth();\n              p()[a + 20 >>> 2 >>> 0] = b.getYear();\n              a = b.getTime();\n              a = isNaN(a) ? -1 : a / 1e3;\n              Vb((P = a, 1 <= +Math.abs(P) ? 0 < P ? +Math.floor(P / 4294967296) >>> 0 : ~~+Math.ceil((P - +(~~P >>> 0)) / 4294967296) >>> 0 : 0));\n              return a >>> 0;\n            },\n            q: yb,\n            r: zb,\n            y: function(a, b, c, d) {\n              a >>>= 0;\n              b >>>= 0;\n              c >>>= 0;\n              d >>>= 0;\n              var h = (/* @__PURE__ */ new Date()).getFullYear(), g = new Date(h, 0, 1), k = new Date(h, 6, 1);\n              h = g.getTimezoneOffset();\n              var t = k.getTimezoneOffset(), C = Math.max(h, t);\n              r()[a >>> 2 >>> 0] = 60 * C;\n              p()[b >>> 2 >>> 0] = Number(h != t);\n              a = (w) => w.toLocaleTimeString(void 0, { hour12: false, timeZoneName: "short" }).split(" ")[1];\n              g = a(g);\n              k = a(k);\n              t < h ? (X(g, c, 17), X(k, d, 17)) : (X(g, d, 17), X(k, c, 17));\n            },\n            c: () => {\n              ya("");\n            },\n            O: function(a, b, c) {\n              a >>>= 0;\n              b >>>= 0;\n              c >>>= 0;\n              Ab.length = 0;\n              for (var d; d = n()[b++ >>> 0]; ) {\n                var h = 105 != d;\n                h &= 112 != d;\n                c += h && c % 8 ? 4 : 0;\n                Ab.push(112 == d ? r()[c >>> 2 >>> 0] : 105 == d ? p()[c >>> 2 >>> 0] : ea()[c >>> 3 >>> 0]);\n                c += h ? 8 : 4;\n              }\n              return Ea[a](...Ab);\n            },\n            k: () => {\n            },\n            i: () => Date.now(),\n            U: () => {\n              T += 1;\n              throw "unwind";\n            },\n            A: function() {\n              return 4294901760;\n            },\n            e: () => performance.timeOrigin + performance.now(),\n            f: () => B ? (init_os(), __toCommonJS(os_exports)).cpus().length : navigator.hardwareConcurrency,\n            x: function(a) {\n              a >>>= 0;\n              var b = n().length;\n              if (a <= b || 4294901760 < a)\n                return false;\n              for (var c = 1; 4 >= c; c *= 2) {\n                var d = b * (1 + 0.2 / c);\n                d = Math.min(d, a + 100663296);\n                var h = Math;\n                d = Math.max(a, d);\n                a: {\n                  h = (h.min.call(h, 4294901760, d + (65536 - d % 65536) % 65536) - e.buffer.byteLength + 65535) / 65536;\n                  try {\n                    e.grow(h);\n                    m();\n                    var g = 1;\n                    break a;\n                  } catch (k) {\n                  }\n                  g = void 0;\n                }\n                if (g)\n                  return true;\n              }\n              return false;\n            },\n            M: Eb,\n            N: Ib,\n            G: Oa,\n            g: Jb,\n            m: Kb,\n            v: Lb,\n            l: Nb,\n            a: e || v.wasmMemory,\n            w: Sb,\n            d: function(a, b, c, d) {\n              return Sb(a >>> 0, b >>> 0, c >>> 0, d >>> 0);\n            }\n          }, Z = function() {\n            function a(c, d) {\n              Z = c.exports;\n              Z = Xb();\n              S.ab.push(Z.ya);\n              Wa = Z.za;\n              ua.unshift(Z.V);\n              ra = d;\n              xa();\n              return Z;\n            }\n            var b = { a: Wb };\n            M++;\n            if (v.instantiateWasm)\n              try {\n                return v.instantiateWasm(\n                  b,\n                  a\n                );\n              } catch (c) {\n                J(`Module.instantiateWasm callback failed with error: ${c}`), x(c);\n              }\n            Da(b, function(c) {\n              a(c.instance, c.module);\n            }).catch(x);\n            return {};\n          }();\n          v._OrtInit = (a, b) => (v._OrtInit = Z.W)(a, b);\n          v._OrtGetLastError = (a, b) => (v._OrtGetLastError = Z.X)(a, b);\n          v._OrtCreateSessionOptions = (a, b, c, d, h, g, k, t, C, w) => (v._OrtCreateSessionOptions = Z.Y)(a, b, c, d, h, g, k, t, C, w);\n          v._OrtAppendExecutionProvider = (a, b) => (v._OrtAppendExecutionProvider = Z.Z)(a, b);\n          v._OrtAddFreeDimensionOverride = (a, b, c) => (v._OrtAddFreeDimensionOverride = Z._)(a, b, c);\n          v._OrtAddSessionConfigEntry = (a, b, c) => (v._OrtAddSessionConfigEntry = Z.$)(a, b, c);\n          v._OrtReleaseSessionOptions = (a) => (v._OrtReleaseSessionOptions = Z.aa)(a);\n          v._OrtCreateSession = (a, b, c) => (v._OrtCreateSession = Z.ba)(a, b, c);\n          v._OrtReleaseSession = (a) => (v._OrtReleaseSession = Z.ca)(a);\n          v._OrtGetInputOutputCount = (a, b, c) => (v._OrtGetInputOutputCount = Z.da)(a, b, c);\n          v._OrtGetInputName = (a, b) => (v._OrtGetInputName = Z.ea)(a, b);\n          v._OrtGetOutputName = (a, b) => (v._OrtGetOutputName = Z.fa)(a, b);\n          v._OrtFree = (a) => (v._OrtFree = Z.ga)(a);\n          v._OrtCreateTensor = (a, b, c, d, h, g) => (v._OrtCreateTensor = Z.ha)(a, b, c, d, h, g);\n          v._OrtGetTensorData = (a, b, c, d, h) => (v._OrtGetTensorData = Z.ia)(a, b, c, d, h);\n          v._OrtReleaseTensor = (a) => (v._OrtReleaseTensor = Z.ja)(a);\n          v._OrtCreateRunOptions = (a, b, c, d) => (v._OrtCreateRunOptions = Z.ka)(a, b, c, d);\n          v._OrtAddRunConfigEntry = (a, b, c) => (v._OrtAddRunConfigEntry = Z.la)(a, b, c);\n          v._OrtReleaseRunOptions = (a) => (v._OrtReleaseRunOptions = Z.ma)(a);\n          v._OrtCreateBinding = (a) => (v._OrtCreateBinding = Z.na)(a);\n          v._OrtBindInput = (a, b, c) => (v._OrtBindInput = Z.oa)(a, b, c);\n          v._OrtBindOutput = (a, b, c, d) => (v._OrtBindOutput = Z.pa)(a, b, c, d);\n          v._OrtClearBoundOutputs = (a) => (v._OrtClearBoundOutputs = Z.qa)(a);\n          v._OrtReleaseBinding = (a) => (v._OrtReleaseBinding = Z.ra)(a);\n          v._OrtRunWithBinding = (a, b, c, d, h) => (v._OrtRunWithBinding = Z.sa)(a, b, c, d, h);\n          v._OrtRun = (a, b, c, d, h, g, k, t) => (v._OrtRun = Z.ta)(a, b, c, d, h, g, k, t);\n          v._OrtEndProfiling = (a) => (v._OrtEndProfiling = Z.ua)(a);\n          var W = v._pthread_self = () => (W = v._pthread_self = Z.va)();\n          v._malloc = (a) => (v._malloc = Z.wa)(a);\n          v._free = (a) => (v._free = Z.xa)(a);\n          v.__emscripten_tls_init = () => (v.__emscripten_tls_init = Z.ya)();\n          var Ub = v.__emscripten_thread_init = (a, b, c, d, h, g) => (Ub = v.__emscripten_thread_init = Z.Aa)(a, b, c, d, h, g);\n          v.__emscripten_thread_crashed = () => (v.__emscripten_thread_crashed = Z.Ba)();\n          var La = (a, b, c, d, h) => (La = Z.Ca)(a, b, c, d, h), Ra = (a) => (Ra = Z.Da)(a), Xa = v.__emscripten_thread_exit = (a) => (Xa = v.__emscripten_thread_exit = Z.Ea)(a), ub = () => (ub = Z.Fa)(), Vb = (a) => (Vb = Z.Ga)(a), Ua = (a, b) => (Ua = Z.Ha)(a, b), U = (a) => (U = Z.Ia)(a), Ka = (a) => (Ka = Z.Ja)(a), Ia = () => (Ia = Z.Ka)();\n          function Xb() {\n            var a = Z;\n            a = Object.assign({}, a);\n            var b = (d) => () => d() >>> 0, c = (d) => (h) => d(h) >>> 0;\n            a.va = b(a.va);\n            a.wa = c(a.wa);\n            a.emscripten_main_runtime_thread_id = b(a.emscripten_main_runtime_thread_id);\n            a.Ja = c(a.Ja);\n            a.Ka = b(a.Ka);\n            return a;\n          }\n          v.wasmMemory = e;\n          v.stackSave = () => Ia();\n          v.stackRestore = (a) => U(a);\n          v.stackAlloc = (a) => Ka(a);\n          v.keepRuntimeAlive = () => 0 < T;\n          v.UTF8ToString = Q;\n          v.stringToUTF8 = X;\n          v.lengthBytesUTF8 = gb;\n          v.ExitStatus = R;\n          v.PThread = S;\n          var Yb;\n          N = function Zb() {\n            Yb || $b();\n            Yb || (N = Zb);\n          };\n          function $b() {\n            if (!(0 < M))\n              if (D)\n                ha(v), D || Ta(ua), startWorker(v);\n              else {\n                if (v.preRun)\n                  for ("function" == typeof v.preRun && (v.preRun = [v.preRun]); v.preRun.length; )\n                    ta.unshift(v.preRun.shift());\n                Ta(ta);\n                0 < M || Yb || (Yb = true, v.calledRun = true, K || (D || Ta(ua), ha(v), D || Ta(va)));\n              }\n          }\n          $b();\n          return readyPromise;\n        };\n      })();\n      if (typeof exports === "object" && typeof module === "object")\n        module.exports = ortWasmThreaded;\n      else if (typeof define === "function" && define["amd"])\n        define([], () => ortWasmThreaded);\n    }\n  });\n\n  // web/lib/wasm/binding/ort-wasm-threaded.worker.js\n  var require_ort_wasm_threaded_worker = __commonJS({\n    "web/lib/wasm/binding/ort-wasm-threaded.worker.js"(exports, module) {\n      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");var vm=require("vm");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:f=>vm.runInThisContext(fs.readFileSync(f,"utf8"),{filename:f}),postMessage:msg=>parentPort.postMessage(msg),performance:global.performance||{now:Date.now}})}var initializedJS=false;function threadPrintErr(...args){var text=args.join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+"\\\\n");return}console.error(text)}function threadAlert(...args){var text=args.join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=(info,receiveInstance)=>{var module=Module["wasmModule"];Module["wasmModule"]=null;var instance=new WebAssembly.Instance(module,info);return receiveInstance(instance)};self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let messageQueue=[];self.onmessage=e=>messageQueue.push(e);self.startWorker=instance=>{Module=instance;postMessage({"cmd":"loaded"});for(let msg of messageQueue){handleMessage(msg)}self.onmessage=handleMessage};Module["wasmModule"]=e.data.wasmModule;for(const handler of e.data.handlers){Module[handler]=(...args)=>{postMessage({cmd:"callHandler",handler:handler,args:args})}}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)}else if(e.data.cmd==="run"){Module["__emscripten_thread_init"](e.data.pthread_ptr,/*is_main=*/0,/*is_runtime=*/0,/*can_block=*/1);Module["__emscripten_thread_mailbox_await"](e.data.pthread_ptr);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInitTLS();if(!initializedJS){initializedJS=true}try{Module["invokeEntryPoint"](e.data.start_routine,e.data.arg)}catch(ex){if(ex!="unwind"){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==="checkMailbox"){if(initializedJS){Module["checkMailbox"]()}}else if(e.data.cmd){err(`worker.js received unknown command ${e.data.cmd}`);err(e.data)}}catch(ex){Module["__emscripten_thread_crashed"]?.();throw ex}}self.onmessage=handleMessage;\\n\';\n    }\n  });\n\n  // nodejs-ignore:node:path\n  var join = void 0;\n\n  // web/lib/wasm/wasm-factory.ts\n  var ortWasmFactory;\n  if (false) {\n    ortWasmFactory = null;\n  } else {\n    ortWasmFactory = true ? require_ort_wasm() : null;\n  }\n  var ortWasmFactoryThreaded = true ? true ? require_ort_wasm_threaded() : null : ortWasmFactory;\n  var wasm;\n  var initialized = false;\n  var initializing = false;\n  var aborted = false;\n  var isMultiThreadSupported = (numThreads) => {\n    if (numThreads === 1) {\n      return false;\n    }\n    if (typeof SharedArrayBuffer === "undefined") {\n      if (typeof self !== "undefined" && !self.crossOriginIsolated) {\n        console.warn(\n          "env.wasm.numThreads is set to " + numThreads + ", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."\n        );\n      }\n      return false;\n    }\n    if (typeof process !== "undefined" && process.versions && process.versions.node) {\n      console.warn(\n        "env.wasm.numThreads is set to " + numThreads + ", however, currently onnxruntime-web does not support multi-threads in Node.js. Please consider using onnxruntime-node for performance critical scenarios."\n      );\n    }\n    try {\n      if (typeof MessageChannel !== "undefined") {\n        new MessageChannel().port1.postMessage(new SharedArrayBuffer(1));\n      }\n      return WebAssembly.validate(new Uint8Array([\n        0,\n        97,\n        115,\n        109,\n        1,\n        0,\n        0,\n        0,\n        1,\n        4,\n        1,\n        96,\n        0,\n        0,\n        3,\n        2,\n        1,\n        0,\n        5,\n        4,\n        1,\n        3,\n        1,\n        1,\n        10,\n        11,\n        1,\n        9,\n        0,\n        65,\n        0,\n        254,\n        16,\n        2,\n        0,\n        26,\n        11\n      ]));\n    } catch (e) {\n      return false;\n    }\n  };\n  var isSimdSupported = () => {\n    try {\n      return WebAssembly.validate(new Uint8Array([\n        0,\n        97,\n        115,\n        109,\n        1,\n        0,\n        0,\n        0,\n        1,\n        4,\n        1,\n        96,\n        0,\n        0,\n        3,\n        2,\n        1,\n        0,\n        10,\n        30,\n        1,\n        28,\n        0,\n        65,\n        0,\n        253,\n        15,\n        253,\n        12,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        0,\n        253,\n        186,\n        1,\n        26,\n        11\n      ]));\n    } catch (e) {\n      return false;\n    }\n  };\n  var getWasmFileName = (useSimd, useThreads) => {\n    if (useSimd) {\n      if (false) {\n        return "ort-training-wasm-simd.wasm";\n      }\n      return useThreads ? "ort-wasm-simd-threaded.wasm" : "ort-wasm-simd.wasm";\n    } else {\n      return useThreads ? "ort-wasm-threaded.wasm" : "ort-wasm.wasm";\n    }\n  };\n  var 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    const timeout = flags.initTimeout;\n    const numThreads = flags.numThreads;\n    const simd = flags.simd;\n    const useThreads = isMultiThreadSupported(numThreads);\n    const useSimd = simd && isSimdSupported();\n    const wasmPaths = flags.wasmPaths;\n    const wasmPrefixOverride = typeof wasmPaths === "string" ? wasmPaths : void 0;\n    const wasmFileName = getWasmFileName(useSimd, useThreads);\n    const wasmPathOverride = typeof wasmPaths === "object" ? wasmPaths[wasmFileName] : void 0;\n    let isTimeout = false;\n    const tasks = [];\n    if (timeout > 0) {\n      tasks.push(new Promise((resolve) => {\n        setTimeout(() => {\n          isTimeout = true;\n          resolve();\n        }, timeout);\n      }));\n    }\n    tasks.push(new Promise((resolve, reject) => {\n      const factory = useThreads ? ortWasmFactoryThreaded : ortWasmFactory;\n      const config = {\n        locateFile: (fileName, scriptDirectory) => {\n          if (useThreads && fileName.endsWith(".worker.js") && typeof Blob !== "undefined") {\n            return URL.createObjectURL(new Blob(\n              [\n                // This require() function is handled by esbuild plugin to load file content as string.\n                // eslint-disable-next-line @typescript-eslint/no-require-imports\n                require_ort_wasm_threaded_worker()\n              ],\n              { type: "text/javascript" }\n            ));\n          }\n          if (fileName.endsWith(".wasm")) {\n            if (wasmPathOverride) {\n              return wasmPathOverride;\n            }\n            const prefix = wasmPrefixOverride ?? scriptDirectory;\n            if (false) {\n              if (wasmFileName === "ort-wasm-simd.wasm") {\n                return prefix + "ort-wasm-simd.jsep.wasm";\n              } else if (wasmFileName === "ort-wasm-simd-threaded.wasm") {\n                return prefix + "ort-wasm-simd-threaded.jsep.wasm";\n              }\n            }\n            return prefix + wasmFileName;\n          }\n          return scriptDirectory + fileName;\n        }\n      };\n      if (useThreads) {\n        config.numThreads = numThreads;\n        if (typeof Blob === "undefined") {\n          config.mainScriptUrlOrBlob = join(__dirname, "ort-wasm-threaded.js");\n        } else {\n          const scriptSourceCode = `var ortWasmThreaded=${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    }));\n    await Promise.race(tasks);\n    if (isTimeout) {\n      throw new Error(`WebAssembly backend initializing failed due to timeout: ${timeout}ms`);\n    }\n  };\n  var getInstance = () => {\n    if (initialized && wasm) {\n      return wasm;\n    }\n    throw new Error("WebAssembly is not initialized yet.");\n  };\n\n  // web/lib/wasm/wasm-utils.ts\n  var allocWasmString = (data, allocs) => {\n    const wasm2 = getInstance();\n    const dataLength = wasm2.lengthBytesUTF8(data) + 1;\n    const dataOffset = wasm2._malloc(dataLength);\n    wasm2.stringToUTF8(data, dataOffset, dataLength);\n    allocs.push(dataOffset);\n    return dataOffset;\n  };\n  var 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      } 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        iterateExtraOptions(value, name + ".", seen, handler);\n      } else if (typeof value === "string" || typeof value === "number") {\n        handler(name, value.toString());\n      } else if (typeof value === "boolean") {\n        handler(name, value ? "1" : "0");\n      } else {\n        throw new Error(`Can\'t handle extra config type: ${typeof value}`);\n      }\n    });\n  };\n  var checkLastError = (message) => {\n    const wasm2 = getInstance();\n    const stack = wasm2.stackSave();\n    try {\n      const paramsOffset = wasm2.stackAlloc(8);\n      wasm2._OrtGetLastError(paramsOffset, paramsOffset + 4);\n      const errorCode = wasm2.HEAP32[paramsOffset / 4];\n      const errorMessagePointer = wasm2.HEAPU32[paramsOffset / 4 + 1];\n      const errorMessage = errorMessagePointer ? wasm2.UTF8ToString(errorMessagePointer) : "";\n      throw new Error(`${message} ERROR_CODE: ${errorCode}, ERROR_MESSAGE: ${errorMessage}`);\n    } finally {\n      wasm2.stackRestore(stack);\n    }\n  };\n\n  // web/lib/wasm/run-options.ts\n  var setRunOptions = (options) => {\n    const wasm2 = getInstance();\n    let runOptionsHandle = 0;\n    const allocs = [];\n    const runOptions = options || {};\n    try {\n      if (options?.logSeverityLevel === void 0) {\n        runOptions.logSeverityLevel = 2;\n      } else if (typeof options.logSeverityLevel !== "number" || !Number.isInteger(options.logSeverityLevel) || options.logSeverityLevel < 0 || options.logSeverityLevel > 4) {\n        throw new Error(`log serverity level is not valid: ${options.logSeverityLevel}`);\n      }\n      if (options?.logVerbosityLevel === void 0) {\n        runOptions.logVerbosityLevel = 0;\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?.terminate === void 0) {\n        runOptions.terminate = false;\n      }\n      let tagDataOffset = 0;\n      if (options?.tag !== void 0) {\n        tagDataOffset = allocWasmString(options.tag, allocs);\n      }\n      runOptionsHandle = wasm2._OrtCreateRunOptions(\n        runOptions.logSeverityLevel,\n        runOptions.logVerbosityLevel,\n        !!runOptions.terminate,\n        tagDataOffset\n      );\n      if (runOptionsHandle === 0) {\n        checkLastError("Can\'t create run options.");\n      }\n      if (options?.extra !== void 0) {\n        iterateExtraOptions(options.extra, "", /* @__PURE__ */ new WeakSet(), (key, value) => {\n          const keyDataOffset = allocWasmString(key, allocs);\n          const valueDataOffset = allocWasmString(value, allocs);\n          if (wasm2._OrtAddRunConfigEntry(runOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n            checkLastError(`Can\'t set a run config entry: ${key} - ${value}.`);\n          }\n        });\n      }\n      return [runOptionsHandle, allocs];\n    } catch (e) {\n      if (runOptionsHandle !== 0) {\n        wasm2._OrtReleaseRunOptions(runOptionsHandle);\n      }\n      allocs.forEach((alloc) => wasm2._free(alloc));\n      throw e;\n    }\n  };\n\n  // web/lib/wasm/session-options.ts\n  var 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  };\n  var 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  };\n  var 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      session.use_ort_model_bytes_directly = "1";\n    }\n    if (options.executionProviders && options.executionProviders.some((ep) => (typeof ep === "string" ? ep : ep.name) === "webgpu")) {\n      options.enableMemPattern = false;\n    }\n  };\n  var setExecutionProviders = (sessionOptionsHandle, executionProviders, allocs) => {\n    for (const ep of executionProviders) {\n      let epName = typeof ep === "string" ? ep : ep.name;\n      switch (epName) {\n        case "webnn":\n          epName = "WEBNN";\n          if (typeof ep !== "string") {\n            const webnnOptions = ep;\n            if (webnnOptions?.deviceType) {\n              const keyDataOffset = allocWasmString("deviceType", allocs);\n              const valueDataOffset = allocWasmString(webnnOptions.deviceType, allocs);\n              if (getInstance()._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n                checkLastError(`Can\'t set a session config entry: \'deviceType\' - ${webnnOptions.deviceType}.`);\n              }\n            }\n            if (webnnOptions?.numThreads) {\n              let numThreads = webnnOptions.numThreads;\n              if (typeof numThreads != "number" || !Number.isInteger(numThreads) || numThreads < 0) {\n                numThreads = 0;\n              }\n              const keyDataOffset = allocWasmString("numThreads", allocs);\n              const valueDataOffset = allocWasmString(numThreads.toString(), allocs);\n              if (getInstance()._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n                checkLastError(`Can\'t set a session config entry: \'numThreads\' - ${webnnOptions.numThreads}.`);\n              }\n            }\n            if (webnnOptions?.powerPreference) {\n              const keyDataOffset = allocWasmString("powerPreference", allocs);\n              const valueDataOffset = allocWasmString(webnnOptions.powerPreference, allocs);\n              if (getInstance()._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n                checkLastError(\n                  `Can\'t set a session config entry: \'powerPreference\' - ${webnnOptions.powerPreference}.`\n                );\n              }\n            }\n          }\n          break;\n        case "webgpu":\n          epName = "JS";\n          if (typeof ep !== "string") {\n            const webgpuOptions = ep;\n            if (webgpuOptions?.preferredLayout) {\n              if (webgpuOptions.preferredLayout !== "NCHW" && webgpuOptions.preferredLayout !== "NHWC") {\n                throw new Error(`preferredLayout must be either \'NCHW\' or \'NHWC\': ${webgpuOptions.preferredLayout}`);\n              }\n              const keyDataOffset = allocWasmString("preferredLayout", allocs);\n              const valueDataOffset = allocWasmString(webgpuOptions.preferredLayout, allocs);\n              if (getInstance()._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n                checkLastError(\n                  `Can\'t set a session config entry: \'preferredLayout\' - ${webgpuOptions.preferredLayout}.`\n                );\n              }\n            }\n          }\n          break;\n        case "wasm":\n        case "cpu":\n          continue;\n        default:\n          throw new Error(`not supported execution provider: ${epName}`);\n      }\n      const epNameDataOffset = allocWasmString(epName, allocs);\n      if (getInstance()._OrtAppendExecutionProvider(sessionOptionsHandle, epNameDataOffset) !== 0) {\n        checkLastError(`Can\'t append execution provider: ${epName}.`);\n      }\n    }\n  };\n  var setSessionOptions = (options) => {\n    const wasm2 = getInstance();\n    let sessionOptionsHandle = 0;\n    const allocs = [];\n    const sessionOptions = options || {};\n    appendDefaultOptions(sessionOptions);\n    try {\n      const graphOptimizationLevel = getGraphOptimzationLevel(sessionOptions.graphOptimizationLevel ?? "all");\n      const executionMode = getExecutionMode(sessionOptions.executionMode ?? "sequential");\n      const logIdDataOffset = typeof sessionOptions.logId === "string" ? allocWasmString(sessionOptions.logId, allocs) : 0;\n      const logSeverityLevel = sessionOptions.logSeverityLevel ?? 2;\n      if (!Number.isInteger(logSeverityLevel) || logSeverityLevel < 0 || logSeverityLevel > 4) {\n        throw new Error(`log serverity level is not valid: ${logSeverityLevel}`);\n      }\n      const logVerbosityLevel = sessionOptions.logVerbosityLevel ?? 0;\n      if (!Number.isInteger(logVerbosityLevel) || logVerbosityLevel < 0 || logVerbosityLevel > 4) {\n        throw new Error(`log verbosity level is not valid: ${logVerbosityLevel}`);\n      }\n      const optimizedModelFilePathOffset = typeof sessionOptions.optimizedModelFilePath === "string" ? allocWasmString(sessionOptions.optimizedModelFilePath, allocs) : 0;\n      sessionOptionsHandle = wasm2._OrtCreateSessionOptions(\n        graphOptimizationLevel,\n        !!sessionOptions.enableCpuMemArena,\n        !!sessionOptions.enableMemPattern,\n        executionMode,\n        !!sessionOptions.enableProfiling,\n        0,\n        logIdDataOffset,\n        logSeverityLevel,\n        logVerbosityLevel,\n        optimizedModelFilePathOffset\n      );\n      if (sessionOptionsHandle === 0) {\n        checkLastError("Can\'t create session options.");\n      }\n      if (sessionOptions.executionProviders) {\n        setExecutionProviders(sessionOptionsHandle, sessionOptions.executionProviders, allocs);\n      }\n      if (sessionOptions.enableGraphCapture !== void 0) {\n        if (typeof sessionOptions.enableGraphCapture !== "boolean") {\n          throw new Error(`enableGraphCapture must be a boolean value: ${sessionOptions.enableGraphCapture}`);\n        }\n        const keyDataOffset = allocWasmString("enableGraphCapture", allocs);\n        const valueDataOffset = allocWasmString(sessionOptions.enableGraphCapture.toString(), allocs);\n        if (wasm2._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n          checkLastError(\n            `Can\'t set a session config entry: \'enableGraphCapture\' - ${sessionOptions.enableGraphCapture}.`\n          );\n        }\n      }\n      if (sessionOptions.freeDimensionOverrides) {\n        for (const [name, value] of Object.entries(sessionOptions.freeDimensionOverrides)) {\n          if (typeof name !== "string") {\n            throw new Error(`free dimension override name must be a string: ${name}`);\n          }\n          if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {\n            throw new Error(`free dimension override value must be a non-negative integer: ${value}`);\n          }\n          const nameOffset = allocWasmString(name, allocs);\n          if (wasm2._OrtAddFreeDimensionOverride(sessionOptionsHandle, nameOffset, value) !== 0) {\n            checkLastError(`Can\'t set a free dimension override: ${name} - ${value}.`);\n          }\n        }\n      }\n      if (sessionOptions.extra !== void 0) {\n        iterateExtraOptions(sessionOptions.extra, "", /* @__PURE__ */ new WeakSet(), (key, value) => {\n          const keyDataOffset = allocWasmString(key, allocs);\n          const valueDataOffset = allocWasmString(value, allocs);\n          if (wasm2._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n            checkLastError(`Can\'t set a session config entry: ${key} - ${value}.`);\n          }\n        });\n      }\n      return [sessionOptionsHandle, allocs];\n    } catch (e) {\n      if (sessionOptionsHandle !== 0) {\n        wasm2._OrtReleaseSessionOptions(sessionOptionsHandle);\n      }\n      allocs.forEach((alloc) => wasm2._free(alloc));\n      throw e;\n    }\n  };\n\n  // web/lib/wasm/wasm-common.ts\n  var tensorDataTypeStringToEnum = (type) => {\n    switch (type) {\n      case "int8":\n        return 3 /* int8 */;\n      case "uint8":\n        return 2 /* uint8 */;\n      case "bool":\n        return 9 /* bool */;\n      case "int16":\n        return 5 /* int16 */;\n      case "uint16":\n        return 4 /* uint16 */;\n      case "int32":\n        return 6 /* int32 */;\n      case "uint32":\n        return 12 /* uint32 */;\n      case "float16":\n        return 10 /* float16 */;\n      case "float32":\n        return 1 /* float */;\n      case "float64":\n        return 11 /* double */;\n      case "string":\n        return 8 /* string */;\n      case "int64":\n        return 7 /* int64 */;\n      case "uint64":\n        return 13 /* uint64 */;\n      default:\n        throw new Error(`unsupported data type: ${type}`);\n    }\n  };\n  var tensorDataTypeEnumToString = (typeProto) => {\n    switch (typeProto) {\n      case 3 /* int8 */:\n        return "int8";\n      case 2 /* uint8 */:\n        return "uint8";\n      case 9 /* bool */:\n        return "bool";\n      case 5 /* int16 */:\n        return "int16";\n      case 4 /* uint16 */:\n        return "uint16";\n      case 6 /* int32 */:\n        return "int32";\n      case 12 /* uint32 */:\n        return "uint32";\n      case 10 /* float16 */:\n        return "float16";\n      case 1 /* float */:\n        return "float32";\n      case 11 /* double */:\n        return "float64";\n      case 8 /* string */:\n        return "string";\n      case 7 /* int64 */:\n        return "int64";\n      case 13 /* uint64 */:\n        return "uint64";\n      default:\n        throw new Error(`unsupported data type: ${typeProto}`);\n    }\n  };\n  var getTensorElementSize = (dateType) => [void 0, 4, 1, 1, 2, 2, 4, 8, void 0, 1, 2, 8, 4, 8, void 0, void 0, void 0][dateType];\n  var tensorTypeToTypedArrayConstructor = (type) => {\n    switch (type) {\n      case "float16":\n        return typeof Float16Array !== "undefined" && Float16Array.from ? Float16Array : Uint16Array;\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  var logLevelStringToEnum = (logLevel) => {\n    switch (logLevel) {\n      case "verbose":\n        return 0;\n      case "info":\n        return 1;\n      case "warning":\n        return 2;\n      case "error":\n        return 3;\n      case "fatal":\n        return 4;\n      default:\n        throw new Error(`unsupported logging level: ${logLevel}`);\n    }\n  };\n  var isGpuBufferSupportedType = (type) => type === "float32" || type === "float16" || type === "int32" || type === "int64" || type === "uint32" || type === "uint8" || type === "bool";\n  var dataLocationStringToEnum = (location) => {\n    switch (location) {\n      case "none":\n        return 0;\n      case "cpu":\n        return 1;\n      case "cpu-pinned":\n        return 2;\n      case "texture":\n        return 3;\n      case "gpu-buffer":\n        return 4;\n      default:\n        throw new Error(`unsupported data location: ${location}`);\n    }\n  };\n\n  // web/lib/wasm/wasm-utils-load-file.ts\n  init_fs();\n\n  // nodejs-ignore:node:fs/promises\n  var readFile2 = void 0;\n\n  // web/lib/wasm/wasm-utils-load-file.ts\n  var loadFile = async (file) => {\n    if (typeof file === "string") {\n      if (typeof process !== "undefined" && process.versions && process.versions.node) {\n        try {\n          return new Uint8Array(await readFile2(file));\n        } catch (e) {\n          if (e.code === "ERR_FS_FILE_TOO_LARGE") {\n            const stream = createReadStream(file);\n            const chunks = [];\n            for await (const chunk of stream) {\n              chunks.push(chunk);\n            }\n            return new Uint8Array(Buffer.concat(chunks));\n          }\n          throw e;\n        }\n      } else {\n        const response = await fetch(file);\n        if (!response.ok) {\n          throw new Error(`failed to load external data file: ${file}`);\n        }\n        const contentLengthHeader = response.headers.get("Content-Length");\n        const fileSize = contentLengthHeader ? parseInt(contentLengthHeader, 10) : 0;\n        if (fileSize < 1073741824) {\n          return new Uint8Array(await response.arrayBuffer());\n        } else {\n          if (!response.body) {\n            throw new Error(`failed to load external data file: ${file}, no response body.`);\n          }\n          const reader = response.body.getReader();\n          let buffer;\n          try {\n            buffer = new ArrayBuffer(fileSize);\n          } catch (e) {\n            if (e instanceof RangeError) {\n              const pages = Math.ceil(fileSize / 65536);\n              buffer = new WebAssembly.Memory({ initial: pages, maximum: pages }).buffer;\n            } else {\n              throw e;\n            }\n          }\n          let offset = 0;\n          while (true) {\n            const { done, value } = await reader.read();\n            if (done) {\n              break;\n            }\n            const chunkSize = value.byteLength;\n            const chunk = new Uint8Array(buffer, offset, chunkSize);\n            chunk.set(value);\n            offset += chunkSize;\n          }\n          return new Uint8Array(buffer, 0, fileSize);\n        }\n      }\n    } else if (file instanceof Blob) {\n      return new Uint8Array(await file.arrayBuffer());\n    } else if (file instanceof Uint8Array) {\n      return file;\n    } else {\n      return new Uint8Array(file);\n    }\n  };\n\n  // web/lib/wasm/wasm-core-impl.ts\n  var initOrt = (numThreads, loggingLevel) => {\n    const errorCode = getInstance()._OrtInit(numThreads, loggingLevel);\n    if (errorCode !== 0) {\n      checkLastError("Can\'t initialize onnxruntime.");\n    }\n  };\n  var initRuntime = async (env) => {\n    initOrt(env.wasm.numThreads, logLevelStringToEnum(env.logLevel));\n  };\n  var initEp = async (env, epName) => {\n    if (false) {\n      const initJsep = null.init;\n      if (epName === "webgpu") {\n        if (typeof navigator === "undefined" || !navigator.gpu) {\n          throw new Error("WebGPU is not supported in current environment");\n        }\n        let adapter = env.webgpu.adapter;\n        if (!adapter) {\n          const powerPreference = env.webgpu.powerPreference;\n          if (powerPreference !== void 0 && powerPreference !== "low-power" && powerPreference !== "high-performance") {\n            throw new Error(`Invalid powerPreference setting: "${powerPreference}"`);\n          }\n          const forceFallbackAdapter = env.webgpu.forceFallbackAdapter;\n          if (forceFallbackAdapter !== void 0 && typeof forceFallbackAdapter !== "boolean") {\n            throw new Error(`Invalid forceFallbackAdapter setting: "${forceFallbackAdapter}"`);\n          }\n          adapter = await navigator.gpu.requestAdapter({ powerPreference, forceFallbackAdapter });\n          if (!adapter) {\n            throw new Error(\n              \'Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.\'\n            );\n          }\n        } else {\n          if (typeof adapter.limits !== "object" || typeof adapter.features !== "object" || typeof adapter.requestDevice !== "function") {\n            throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.");\n          }\n        }\n        if (!env.wasm.simd) {\n          throw new Error(\n            "Not supported for WebGPU=ON and SIMD=OFF. Please set `env.wasm.simd` to true when using `webgpu` EP"\n          );\n        }\n        await initJsep("webgpu", getInstance(), env, adapter);\n      }\n      if (epName === "webnn") {\n        if (typeof navigator === "undefined" || !navigator.ml) {\n          throw new Error("WebNN is not supported in current environment");\n        }\n        await initJsep("webnn", getInstance(), env);\n      }\n    }\n  };\n  var activeSessions = /* @__PURE__ */ new Map();\n  var getSessionInputOutputCount = (sessionHandle) => {\n    const wasm2 = getInstance();\n    const stack = wasm2.stackSave();\n    try {\n      const dataOffset = wasm2.stackAlloc(8);\n      const errorCode = wasm2._OrtGetInputOutputCount(sessionHandle, dataOffset, dataOffset + 4);\n      if (errorCode !== 0) {\n        checkLastError("Can\'t get session input/output count.");\n      }\n      return [wasm2.HEAP32[dataOffset / 4], wasm2.HEAP32[dataOffset / 4 + 1]];\n    } finally {\n      wasm2.stackRestore(stack);\n    }\n  };\n  var copyFromExternalBuffer = (model) => {\n    const wasm2 = getInstance();\n    const modelDataOffset = wasm2._malloc(model.byteLength);\n    if (modelDataOffset === 0) {\n      throw new Error(`Can\'t create a session. failed to allocate a buffer of size ${model.byteLength}.`);\n    }\n    wasm2.HEAPU8.set(model, modelDataOffset);\n    return [modelDataOffset, model.byteLength];\n  };\n  var createSession = async (modelData, options) => {\n    let modelDataOffset, modelDataLength;\n    const wasm2 = getInstance();\n    if (Array.isArray(modelData)) {\n      [modelDataOffset, modelDataLength] = modelData;\n    } else if (modelData.buffer === wasm2.HEAPU8.buffer) {\n      [modelDataOffset, modelDataLength] = [modelData.byteOffset, modelData.byteLength];\n    } else {\n      [modelDataOffset, modelDataLength] = copyFromExternalBuffer(modelData);\n    }\n    let sessionHandle = 0;\n    let sessionOptionsHandle = 0;\n    let ioBindingHandle = 0;\n    let allocs = [];\n    const inputNamesUTF8Encoded = [];\n    const outputNamesUTF8Encoded = [];\n    try {\n      [sessionOptionsHandle, allocs] = setSessionOptions(options);\n      if (options?.externalData && wasm2.mountExternalData) {\n        const loadingPromises = [];\n        for (const file of options.externalData) {\n          const path = typeof file === "string" ? file : file.path;\n          loadingPromises.push(loadFile(typeof file === "string" ? file : file.data).then((data) => {\n            wasm2.mountExternalData(path, data);\n          }));\n        }\n        await Promise.all(loadingPromises);\n      }\n      sessionHandle = await wasm2._OrtCreateSession(modelDataOffset, modelDataLength, sessionOptionsHandle);\n      if (sessionHandle === 0) {\n        checkLastError("Can\'t create a session.");\n      }\n      const [inputCount, outputCount] = getSessionInputOutputCount(sessionHandle);\n      const enableGraphCapture = !!options?.enableGraphCapture;\n      const inputNames = [];\n      const outputNames = [];\n      const outputPreferredLocations = [];\n      for (let i = 0; i < inputCount; i++) {\n        const name = wasm2._OrtGetInputName(sessionHandle, i);\n        if (name === 0) {\n          checkLastError("Can\'t get an input name.");\n        }\n        inputNamesUTF8Encoded.push(name);\n        inputNames.push(wasm2.UTF8ToString(name));\n      }\n      for (let i = 0; i < outputCount; i++) {\n        const name = wasm2._OrtGetOutputName(sessionHandle, i);\n        if (name === 0) {\n          checkLastError("Can\'t get an output name.");\n        }\n        outputNamesUTF8Encoded.push(name);\n        const nameString = wasm2.UTF8ToString(name);\n        outputNames.push(nameString);\n        if (false) {\n          if (enableGraphCapture && options?.preferredOutputLocation === void 0) {\n            outputPreferredLocations.push("gpu-buffer");\n            continue;\n          }\n          const location = typeof options?.preferredOutputLocation === "string" ? options.preferredOutputLocation : options?.preferredOutputLocation?.[nameString] ?? "cpu";\n          if (location !== "cpu" && location !== "cpu-pinned" && location !== "gpu-buffer") {\n            throw new Error(`Not supported preferred output location: ${location}.`);\n          }\n          if (enableGraphCapture && location !== "gpu-buffer") {\n            throw new Error(`Not supported preferred output location: ${location}. Only \'gpu-buffer\' location is supported when enableGraphCapture is true.`);\n          }\n          outputPreferredLocations.push(location);\n        }\n      }\n      let bindingState = null;\n      if (false) {\n        ioBindingHandle = wasm2._OrtCreateBinding(sessionHandle);\n        if (ioBindingHandle === 0) {\n          checkLastError("Can\'t create IO binding.");\n        }\n        bindingState = {\n          handle: ioBindingHandle,\n          outputPreferredLocations,\n          outputPreferredLocationsEncoded: outputPreferredLocations.map((l) => dataLocationStringToEnum(l))\n        };\n      }\n      activeSessions.set(\n        sessionHandle,\n        [sessionHandle, inputNamesUTF8Encoded, outputNamesUTF8Encoded, bindingState, enableGraphCapture, false]\n      );\n      return [sessionHandle, inputNames, outputNames];\n    } catch (e) {\n      inputNamesUTF8Encoded.forEach((buf) => wasm2._OrtFree(buf));\n      outputNamesUTF8Encoded.forEach((buf) => wasm2._OrtFree(buf));\n      if (ioBindingHandle !== 0) {\n        wasm2._OrtReleaseBinding(ioBindingHandle);\n      }\n      if (sessionHandle !== 0) {\n        wasm2._OrtReleaseSession(sessionHandle);\n      }\n      throw e;\n    } finally {\n      wasm2._free(modelDataOffset);\n      if (sessionOptionsHandle !== 0) {\n        wasm2._OrtReleaseSessionOptions(sessionOptionsHandle);\n      }\n      allocs.forEach((alloc) => wasm2._free(alloc));\n      wasm2.unmountExternalData?.();\n    }\n  };\n  var releaseSession = (sessionId) => {\n    const wasm2 = getInstance();\n    const session = activeSessions.get(sessionId);\n    if (!session) {\n      throw new Error(`cannot release session. invalid session id: ${sessionId}`);\n    }\n    const [sessionHandle, inputNamesUTF8Encoded, outputNamesUTF8Encoded, ioBindingState, enableGraphCapture] = session;\n    if (ioBindingState) {\n      if (enableGraphCapture) {\n        wasm2._OrtClearBoundOutputs(ioBindingState.handle);\n      }\n      wasm2._OrtReleaseBinding(ioBindingState.handle);\n    }\n    wasm2.jsepOnReleaseSession?.(sessionId);\n    inputNamesUTF8Encoded.forEach((buf) => wasm2._OrtFree(buf));\n    outputNamesUTF8Encoded.forEach((buf) => wasm2._OrtFree(buf));\n    wasm2._OrtReleaseSession(sessionHandle);\n    activeSessions.delete(sessionId);\n  };\n  var prepareInputOutputTensor = (tensor, tensorHandles, allocs, sessionId, index, enableGraphCapture = false) => {\n    if (!tensor) {\n      tensorHandles.push(0);\n      return;\n    }\n    const wasm2 = getInstance();\n    const dataType = tensor[0];\n    const dims = tensor[1];\n    const location = tensor[3];\n    let rawData;\n    let dataByteLength;\n    if (dataType === "string" && location === "gpu-buffer") {\n      throw new Error("String tensor is not supported on GPU.");\n    }\n    if (enableGraphCapture && location !== "gpu-buffer") {\n      throw new Error(\n        `External buffer must be provided for input/output index ${index} when enableGraphCapture is true.`\n      );\n    }\n    if (location === "gpu-buffer") {\n      const gpuBuffer = tensor[2].gpuBuffer;\n      const elementSizeInBytes = getTensorElementSize(tensorDataTypeStringToEnum(dataType));\n      dataByteLength = dims.reduce((a, b) => a * b, 1) * elementSizeInBytes;\n      const registerBuffer = wasm2.jsepRegisterBuffer;\n      if (!registerBuffer) {\n        throw new Error(\'Tensor location "gpu-buffer" is not supported without using WebGPU.\');\n      }\n      rawData = registerBuffer(sessionId, index, gpuBuffer, dataByteLength);\n    } else {\n      const data = tensor[2];\n      if (Array.isArray(data)) {\n        dataByteLength = 4 * data.length;\n        rawData = wasm2._malloc(dataByteLength);\n        allocs.push(rawData);\n        let dataIndex = rawData / 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          wasm2.HEAPU32[dataIndex++] = allocWasmString(data[i], allocs);\n        }\n      } else {\n        dataByteLength = data.byteLength;\n        rawData = wasm2._malloc(dataByteLength);\n        allocs.push(rawData);\n        wasm2.HEAPU8.set(new Uint8Array(data.buffer, data.byteOffset, dataByteLength), rawData);\n      }\n    }\n    const stack = wasm2.stackSave();\n    const dimsOffset = wasm2.stackAlloc(4 * dims.length);\n    try {\n      let dimIndex = dimsOffset / 4;\n      dims.forEach((d) => wasm2.HEAP32[dimIndex++] = d);\n      const tensor2 = wasm2._OrtCreateTensor(\n        tensorDataTypeStringToEnum(dataType),\n        rawData,\n        dataByteLength,\n        dimsOffset,\n        dims.length,\n        dataLocationStringToEnum(location)\n      );\n      if (tensor2 === 0) {\n        checkLastError(`Can\'t create tensor for input/output. session=${sessionId}, index=${index}.`);\n      }\n      tensorHandles.push(tensor2);\n    } finally {\n      wasm2.stackRestore(stack);\n    }\n  };\n  var run = async (sessionId, inputIndices, inputTensors, outputIndices, outputTensors, options) => {\n    const wasm2 = getInstance();\n    const session = activeSessions.get(sessionId);\n    if (!session) {\n      throw new Error(`cannot run inference. invalid session id: ${sessionId}`);\n    }\n    const sessionHandle = session[0];\n    const inputNamesUTF8Encoded = session[1];\n    const outputNamesUTF8Encoded = session[2];\n    const ioBindingState = session[3];\n    const enableGraphCapture = session[4];\n    const inputOutputBound = session[5];\n    const inputCount = inputIndices.length;\n    const outputCount = outputIndices.length;\n    let runOptionsHandle = 0;\n    let runOptionsAllocs = [];\n    const inputTensorHandles = [];\n    const outputTensorHandles = [];\n    const inputOutputAllocs = [];\n    const beforeRunStack = wasm2.stackSave();\n    const inputValuesOffset = wasm2.stackAlloc(inputCount * 4);\n    const inputNamesOffset = wasm2.stackAlloc(inputCount * 4);\n    const outputValuesOffset = wasm2.stackAlloc(outputCount * 4);\n    const outputNamesOffset = wasm2.stackAlloc(outputCount * 4);\n    try {\n      [runOptionsHandle, runOptionsAllocs] = setRunOptions(options);\n      for (let i = 0; i < inputCount; i++) {\n        prepareInputOutputTensor(\n          inputTensors[i],\n          inputTensorHandles,\n          inputOutputAllocs,\n          sessionId,\n          inputIndices[i],\n          enableGraphCapture\n        );\n      }\n      for (let i = 0; i < outputCount; i++) {\n        prepareInputOutputTensor(\n          outputTensors[i],\n          outputTensorHandles,\n          inputOutputAllocs,\n          sessionId,\n          inputCount + outputIndices[i],\n          enableGraphCapture\n        );\n      }\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        wasm2.HEAPU32[inputValuesIndex++] = inputTensorHandles[i];\n        wasm2.HEAPU32[inputNamesIndex++] = inputNamesUTF8Encoded[inputIndices[i]];\n      }\n      for (let i = 0; i < outputCount; i++) {\n        wasm2.HEAPU32[outputValuesIndex++] = outputTensorHandles[i];\n        wasm2.HEAPU32[outputNamesIndex++] = outputNamesUTF8Encoded[outputIndices[i]];\n      }\n      if (false) {\n        const { handle, outputPreferredLocations, outputPreferredLocationsEncoded } = ioBindingState;\n        if (inputNamesUTF8Encoded.length !== inputCount) {\n          throw new Error(`input count from feeds (${inputCount}) is expected to be always equal to model\'s input count (${inputNamesUTF8Encoded.length}).`);\n        }\n        for (let i = 0; i < inputCount; i++) {\n          const index = inputIndices[i];\n          const errorCode2 = await wasm2._OrtBindInput(handle, inputNamesUTF8Encoded[index], inputTensorHandles[i]);\n          if (errorCode2 !== 0) {\n            checkLastError(`Can\'t bind input[${i}] for session=${sessionId}.`);\n          }\n        }\n        for (let i = 0; i < outputCount; i++) {\n          const index = outputIndices[i];\n          const location = outputTensors[i]?.[3];\n          if (location) {\n            const errorCode2 = wasm2._OrtBindOutput(handle, outputNamesUTF8Encoded[index], outputTensorHandles[i], 0);\n            if (errorCode2 !== 0) {\n              checkLastError(`Can\'t bind pre-allocated output[${i}] for session=${sessionId}.`);\n            }\n          } else {\n            const errorCode2 = wasm2._OrtBindOutput(handle, outputNamesUTF8Encoded[index], 0, outputPreferredLocationsEncoded[index]);\n            if (errorCode2 !== 0) {\n              checkLastError(`Can\'t bind output[${i}] to ${outputPreferredLocations[i]} for session=${sessionId}.`);\n            }\n          }\n        }\n        activeSessions.set(\n          sessionId,\n          [sessionHandle, inputNamesUTF8Encoded, outputNamesUTF8Encoded, ioBindingState, enableGraphCapture, true]\n        );\n      }\n      wasm2.jsepOnRunStart?.(sessionHandle);\n      let errorCode;\n      if (false) {\n        errorCode = await wasm2._OrtRunWithBinding(\n          sessionHandle,\n          ioBindingState.handle,\n          outputCount,\n          outputValuesOffset,\n          runOptionsHandle\n        );\n      } else {\n        errorCode = await wasm2._OrtRun(\n          sessionHandle,\n          inputNamesOffset,\n          inputValuesOffset,\n          inputCount,\n          outputNamesOffset,\n          outputCount,\n          outputValuesOffset,\n          runOptionsHandle\n        );\n      }\n      if (errorCode !== 0) {\n        checkLastError("failed to call OrtRun().");\n      }\n      const output = [];\n      for (let i = 0; i < outputCount; i++) {\n        const tensor = wasm2.HEAPU32[outputValuesOffset / 4 + i];\n        if (tensor === outputTensorHandles[i]) {\n          output.push(outputTensors[i]);\n          continue;\n        }\n        const beforeGetTensorDataStack = wasm2.stackSave();\n        const tensorDataOffset = wasm2.stackAlloc(4 * 4);\n        let keepOutputTensor = false;\n        let type, dataOffset = 0;\n        try {\n          const errorCode2 = wasm2._OrtGetTensorData(\n            tensor,\n            tensorDataOffset,\n            tensorDataOffset + 4,\n            tensorDataOffset + 8,\n            tensorDataOffset + 12\n          );\n          if (errorCode2 !== 0) {\n            checkLastError(`Can\'t access output tensor data on index ${i}.`);\n          }\n          let tensorDataIndex = tensorDataOffset / 4;\n          const dataType = wasm2.HEAPU32[tensorDataIndex++];\n          dataOffset = wasm2.HEAPU32[tensorDataIndex++];\n          const dimsOffset = wasm2.HEAPU32[tensorDataIndex++];\n          const dimsLength = wasm2.HEAPU32[tensorDataIndex++];\n          const dims = [];\n          for (let i2 = 0; i2 < dimsLength; i2++) {\n            dims.push(wasm2.HEAPU32[dimsOffset / 4 + i2]);\n          }\n          wasm2._OrtFree(dimsOffset);\n          const size = dims.reduce((a, b) => a * b, 1);\n          type = tensorDataTypeEnumToString(dataType);\n          const preferredLocation = ioBindingState?.outputPreferredLocations[outputIndices[i]];\n          if (type === "string") {\n            if (preferredLocation === "gpu-buffer") {\n              throw new Error("String tensor is not supported on GPU.");\n            }\n            const stringData = [];\n            let dataIndex = dataOffset / 4;\n            for (let i2 = 0; i2 < size; i2++) {\n              const offset = wasm2.HEAPU32[dataIndex++];\n              const maxBytesToRead = i2 === size - 1 ? void 0 : wasm2.HEAPU32[dataIndex] - offset;\n              stringData.push(wasm2.UTF8ToString(offset, maxBytesToRead));\n            }\n            output.push([type, dims, stringData, "cpu"]);\n          } else {\n            if (preferredLocation === "gpu-buffer" && size > 0) {\n              const getBuffer = wasm2.jsepGetBuffer;\n              if (!getBuffer) {\n                throw new Error(\'preferredLocation "gpu-buffer" is not supported without using WebGPU.\');\n              }\n              const gpuBuffer = getBuffer(dataOffset);\n              const elementSize = getTensorElementSize(dataType);\n              if (elementSize === void 0 || !isGpuBufferSupportedType(type)) {\n                throw new Error(`Unsupported data type: ${type}`);\n              }\n              keepOutputTensor = true;\n              output.push([\n                type,\n                dims,\n                {\n                  gpuBuffer,\n                  download: wasm2.jsepCreateDownloader(gpuBuffer, size * elementSize, type),\n                  dispose: () => {\n                    wasm2._OrtReleaseTensor(tensor);\n                  }\n                },\n                "gpu-buffer"\n              ]);\n            } else {\n              const typedArrayConstructor = tensorTypeToTypedArrayConstructor(type);\n              const data = new typedArrayConstructor(size);\n              new Uint8Array(data.buffer, data.byteOffset, data.byteLength).set(wasm2.HEAPU8.subarray(dataOffset, dataOffset + data.byteLength));\n              output.push([type, dims, data, "cpu"]);\n            }\n          }\n        } finally {\n          wasm2.stackRestore(beforeGetTensorDataStack);\n          if (type === "string" && dataOffset) {\n            wasm2._free(dataOffset);\n          }\n          if (!keepOutputTensor) {\n            wasm2._OrtReleaseTensor(tensor);\n          }\n        }\n      }\n      if (ioBindingState && !enableGraphCapture) {\n        wasm2._OrtClearBoundOutputs(ioBindingState.handle);\n        activeSessions.set(\n          sessionId,\n          [sessionHandle, inputNamesUTF8Encoded, outputNamesUTF8Encoded, ioBindingState, enableGraphCapture, false]\n        );\n      }\n      return output;\n    } finally {\n      wasm2.stackRestore(beforeRunStack);\n      inputTensorHandles.forEach((v) => wasm2._OrtReleaseTensor(v));\n      outputTensorHandles.forEach((v) => wasm2._OrtReleaseTensor(v));\n      inputOutputAllocs.forEach((p) => wasm2._free(p));\n      if (runOptionsHandle !== 0) {\n        wasm2._OrtReleaseRunOptions(runOptionsHandle);\n      }\n      runOptionsAllocs.forEach((p) => wasm2._free(p));\n    }\n  };\n  var endProfiling = (sessionId) => {\n    const wasm2 = 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 profileFileName = wasm2._OrtEndProfiling(sessionHandle);\n    if (profileFileName === 0) {\n      checkLastError("Can\'t get an profile file name.");\n    }\n    wasm2._OrtFree(profileFileName);\n  };\n  var extractTransferableBuffers = (tensors) => {\n    const buffers = [];\n    for (const tensor of tensors) {\n      const data = tensor[2];\n      if (!Array.isArray(data) && "buffer" in data) {\n        buffers.push(data.buffer);\n      }\n    }\n    return buffers;\n  };\n\n  // web/lib/wasm/proxy-worker/main.ts\n  self.onmessage = (ev) => {\n    const { type, in: message } = ev.data;\n    try {\n      switch (type) {\n        case "init-wasm":\n          initializeWebAssembly(message.wasm).then(\n            () => {\n              initRuntime(message).then(\n                () => {\n                  postMessage({ type });\n                },\n                (err) => {\n                  postMessage({ type, err });\n                }\n              );\n            },\n            (err) => {\n              postMessage({ type, err });\n            }\n          );\n          break;\n        case "init-ep": {\n          const { epName, env } = message;\n          initEp(env, epName).then(\n            () => {\n              postMessage({ type });\n            },\n            (err) => {\n              postMessage({ type, err });\n            }\n          );\n          break;\n        }\n        case "copy-from": {\n          const { buffer } = message;\n          const bufferData = copyFromExternalBuffer(buffer);\n          postMessage({ type, out: bufferData });\n          break;\n        }\n        case "create": {\n          const { model, options } = message;\n          createSession(model, options).then(\n            (sessionMetadata) => {\n              postMessage({ type, out: sessionMetadata });\n            },\n            (err) => {\n              postMessage({ type, err });\n            }\n          );\n          break;\n        }\n        case "release":\n          releaseSession(message);\n          postMessage({ type });\n          break;\n        case "run": {\n          const { sessionId, inputIndices, inputs, outputIndices, options } = message;\n          run(sessionId, inputIndices, inputs, outputIndices, new Array(outputIndices.length).fill(null), options).then(\n            (outputs) => {\n              if (outputs.some((o) => o[3] !== "cpu")) {\n                postMessage({ type, err: "Proxy does not support non-cpu tensor location." });\n              } else {\n                postMessage(\n                  { type, out: outputs },\n                  extractTransferableBuffers([...inputs, ...outputs])\n                );\n              }\n            },\n            (err) => {\n              postMessage({ type, err });\n            }\n          );\n          break;\n        }\n        case "end-profiling":\n          endProfiling(message);\n          postMessage({ type });\n          break;\n        default:\n      }\n    } catch (err) {\n      postMessage({ type, err });\n    }\n  };\n})();\n//# sourceMappingURL=data:application/json;base64,[encoded data, 255916 characters]\n';
    }
  });

  // web/lib/wasm/proxy-wrapper.ts
  var isProxy, proxyWorker, initializing2, initialized2, aborted2, initWasmCallbacks, queuedCallbacks, enqueueCallbacks, ensureWorker, onProxyWorkerMessage, scriptSrc, initializeWebAssemblyAndOrtRuntime, initializeOrtEp, copyFromExternalBuffer2, createSession2, releaseSession2, run2, endProfiling2;
  var init_proxy_wrapper = __esm({
    "web/lib/wasm/proxy-wrapper.ts"() {
      "use strict";
      init_esm();
      init_wasm_core_impl();
      init_wasm_factory();
      isProxy = () => !!env2.wasm.proxy && typeof document !== "undefined";
      initializing2 = false;
      initialized2 = false;
      aborted2 = false;
      queuedCallbacks = /* @__PURE__ */ new Map();
      enqueueCallbacks = (type, callbacks) => {
        const queue = queuedCallbacks.get(type);
        if (queue) {
          queue.push(callbacks);
        } else {
          queuedCallbacks.set(type, [callbacks]);
        }
      };
      ensureWorker = () => {
        if (initializing2 || !initialized2 || aborted2 || !proxyWorker) {
          throw new Error("worker not ready");
        }
      };
      onProxyWorkerMessage = (ev) => {
        switch (ev.data.type) {
          case "init-wasm":
            initializing2 = false;
            if (ev.data.err) {
              aborted2 = true;
              initWasmCallbacks[1](ev.data.err);
            } else {
              initialized2 = true;
              initWasmCallbacks[0]();
            }
            break;
          case "init-ep":
          case "copy-from":
          case "create":
          case "release":
          case "run":
          case "end-profiling": {
            const callbacks = queuedCallbacks.get(ev.data.type);
            if (ev.data.err) {
              callbacks.shift()[1](ev.data.err);
            } else {
              callbacks.shift()[0](ev.data.out);
            }
            break;
          }
          default:
        }
      };
      scriptSrc = typeof document !== "undefined" ? document?.currentScript?.src : void 0;
      initializeWebAssemblyAndOrtRuntime = async () => {
        if (initialized2) {
          return;
        }
        if (initializing2) {
          throw new Error("multiple calls to 'initWasm()' detected.");
        }
        if (aborted2) {
          throw new Error("previous call to 'initWasm()' failed.");
        }
        initializing2 = true;
        if (isProxy()) {
          if (env2.wasm.wasmPaths === void 0) {
            if (scriptSrc && scriptSrc.indexOf("blob:") !== 0) {
              env2.wasm.wasmPaths = scriptSrc.substr(0, +scriptSrc.lastIndexOf("/") + 1);
            }
          }
          return new Promise((resolve, reject) => {
            proxyWorker?.terminate();
            const workerUrl = URL.createObjectURL(new Blob(
              [
                // This require() function is handled by esbuild plugin to load file content as string.
                // eslint-disable-next-line @typescript-eslint/no-require-imports
                require_main()
              ],
              { type: "text/javascript" }
            ));
            proxyWorker = new Worker(workerUrl, { name: "ort-wasm-proxy-worker" });
            proxyWorker.onerror = (ev) => reject(ev);
            proxyWorker.onmessage = onProxyWorkerMessage;
            URL.revokeObjectURL(workerUrl);
            initWasmCallbacks = [resolve, reject];
            const message = { type: "init-wasm", in: env2 };
            proxyWorker.postMessage(message);
          });
        } else {
          try {
            await initializeWebAssembly(env2.wasm);
            await initRuntime(env2);
            initialized2 = true;
          } catch (e) {
            aborted2 = true;
            throw e;
          } finally {
            initializing2 = false;
          }
        }
      };
      initializeOrtEp = async (epName) => {
        if (isProxy()) {
          ensureWorker();
          return new Promise((resolve, reject) => {
            enqueueCallbacks("init-ep", [resolve, reject]);
            const message = { type: "init-ep", in: { epName, env: env2 } };
            proxyWorker.postMessage(message);
          });
        } else {
          await initEp(env2, epName);
        }
      };
      copyFromExternalBuffer2 = async (buffer) => {
        if (isProxy()) {
          ensureWorker();
          return new Promise((resolve, reject) => {
            enqueueCallbacks("copy-from", [resolve, reject]);
            const message = { type: "copy-from", in: { buffer } };
            proxyWorker.postMessage(message, [buffer.buffer]);
          });
        } else {
          return copyFromExternalBuffer(buffer);
        }
      };
      createSession2 = async (model, options) => {
        if (isProxy()) {
          if (options?.preferredOutputLocation) {
            throw new Error('session option "preferredOutputLocation" is not supported for proxy.');
          }
          ensureWorker();
          return new Promise((resolve, reject) => {
            enqueueCallbacks("create", [resolve, reject]);
            const message = { type: "create", in: { model, options: { ...options } } };
            const transferable = [];
            if (model instanceof Uint8Array) {
              transferable.push(model.buffer);
            }
            proxyWorker.postMessage(message, transferable);
          });
        } else {
          return createSession(model, options);
        }
      };
      releaseSession2 = async (sessionId) => {
        if (isProxy()) {
          ensureWorker();
          return new Promise((resolve, reject) => {
            enqueueCallbacks("release", [resolve, reject]);
            const message = { type: "release", in: sessionId };
            proxyWorker.postMessage(message);
          });
        } else {
          releaseSession(sessionId);
        }
      };
      run2 = async (sessionId, inputIndices, inputs, outputIndices, outputs, options) => {
        if (isProxy()) {
          if (inputs.some((t) => t[3] !== "cpu")) {
            throw new Error("input tensor on GPU is not supported for proxy.");
          }
          if (outputs.some((t) => t)) {
            throw new Error("pre-allocated output tensor is not supported for proxy.");
          }
          ensureWorker();
          return new Promise((resolve, reject) => {
            enqueueCallbacks("run", [resolve, reject]);
            const serializableInputs = inputs;
            const message = { type: "run", in: { sessionId, inputIndices, inputs: serializableInputs, outputIndices, options } };
            proxyWorker.postMessage(message, extractTransferableBuffers(serializableInputs));
          });
        } else {
          return run(sessionId, inputIndices, inputs, outputIndices, outputs, options);
        }
      };
      endProfiling2 = async (sessionId) => {
        if (isProxy()) {
          ensureWorker();
          return new Promise((resolve, reject) => {
            enqueueCallbacks("end-profiling", [resolve, reject]);
            const message = { type: "end-profiling", in: sessionId };
            proxyWorker.postMessage(message);
          });
        } else {
          endProfiling(sessionId);
        }
      };
    }
  });

  // web/lib/wasm/session-handler-inference.ts
  var encodeTensorMetadata, decodeTensorMetadata, OnnxruntimeWebAssemblySessionHandler;
  var init_session_handler_inference2 = __esm({
    "web/lib/wasm/session-handler-inference.ts"() {
      "use strict";
      init_esm();
      init_proxy_wrapper();
      init_wasm_common();
      init_wasm_utils_load_file();
      encodeTensorMetadata = (tensor, getName) => {
        switch (tensor.location) {
          case "cpu":
            return [tensor.type, tensor.dims, tensor.data, "cpu"];
          case "gpu-buffer":
            return [tensor.type, tensor.dims, { gpuBuffer: tensor.gpuBuffer }, "gpu-buffer"];
          default:
            throw new Error(`invalid data location: ${tensor.location} for ${getName()}`);
        }
      };
      decodeTensorMetadata = (tensor) => {
        switch (tensor[3]) {
          case "cpu":
            return new Tensor2(tensor[0], tensor[2], tensor[1]);
          case "gpu-buffer": {
            const dataType = tensor[0];
            if (!isGpuBufferSupportedType(dataType)) {
              throw new Error(`not supported data type: ${dataType} for deserializing GPU tensor`);
            }
            const { gpuBuffer, download, dispose } = tensor[2];
            return Tensor2.fromGpuBuffer(gpuBuffer, { dataType, dims: tensor[1], download, dispose });
          }
          default:
            throw new Error(`invalid data location: ${tensor[3]}`);
        }
      };
      OnnxruntimeWebAssemblySessionHandler = class {
        async fetchModelAndCopyToWasmMemory(path) {
          return copyFromExternalBuffer2(await loadFile(path));
        }
        async loadModel(pathOrBuffer, options) {
          TRACE_FUNC_BEGIN();
          let model;
          if (typeof pathOrBuffer === "string") {
            if (typeof process !== "undefined" && process.versions && process.versions.node) {
              model = await loadFile(pathOrBuffer);
            } else {
              model = await this.fetchModelAndCopyToWasmMemory(pathOrBuffer);
            }
          } else {
            model = pathOrBuffer;
          }
          [this.sessionId, this.inputNames, this.outputNames] = await createSession2(model, options);
          TRACE_FUNC_END();
        }
        async dispose() {
          return releaseSession2(this.sessionId);
        }
        async run(feeds, fetches, options) {
          TRACE_FUNC_BEGIN();
          const inputArray = [];
          const inputIndices = [];
          Object.entries(feeds).forEach((kvp) => {
            const name2 = kvp[0];
            const tensor = kvp[1];
            const index = this.inputNames.indexOf(name2);
            if (index === -1) {
              throw new Error(`invalid input '${name2}'`);
            }
            inputArray.push(tensor);
            inputIndices.push(index);
          });
          const outputArray = [];
          const outputIndices = [];
          Object.entries(fetches).forEach((kvp) => {
            const name2 = kvp[0];
            const tensor = kvp[1];
            const index = this.outputNames.indexOf(name2);
            if (index === -1) {
              throw new Error(`invalid output '${name2}'`);
            }
            outputArray.push(tensor);
            outputIndices.push(index);
          });
          const inputs = inputArray.map((t, i) => encodeTensorMetadata(t, () => `input "${this.inputNames[inputIndices[i]]}"`));
          const outputs = outputArray.map(
            (t, i) => t ? encodeTensorMetadata(t, () => `output "${this.outputNames[outputIndices[i]]}"`) : null
          );
          const results = await run2(this.sessionId, inputIndices, inputs, outputIndices, outputs, options);
          const resultMap = {};
          for (let i = 0; i < results.length; i++) {
            resultMap[this.outputNames[outputIndices[i]]] = outputArray[i] ?? decodeTensorMetadata(results[i]);
          }
          TRACE_FUNC_END();
          return resultMap;
        }
        startProfiling() {
        }
        endProfiling() {
          void endProfiling2(this.sessionId);
        }
      };
    }
  });

  // web/lib/backend-wasm.ts
  var initializeFlags, OnnxruntimeWebAssemblyBackend;
  var init_backend_wasm = __esm({
    "web/lib/backend-wasm.ts"() {
      "use strict";
      init_node_os();
      init_esm();
      init_proxy_wrapper();
      init_session_handler_inference2();
      initializeFlags = () => {
        if (typeof env2.wasm.initTimeout !== "number" || env2.wasm.initTimeout < 0) {
          env2.wasm.initTimeout = 0;
        }
        if (typeof env2.wasm.simd !== "boolean") {
          env2.wasm.simd = true;
        }
        if (typeof env2.wasm.proxy !== "boolean") {
          env2.wasm.proxy = false;
        }
        if (typeof env2.wasm.trace !== "boolean") {
          env2.wasm.trace = false;
        }
        if (typeof env2.wasm.numThreads !== "number" || !Number.isInteger(env2.wasm.numThreads) || env2.wasm.numThreads <= 0) {
          if (typeof self !== "undefined" && !self.crossOriginIsolated || typeof process !== "undefined" && process.versions && process.versions.node) {
            env2.wasm.numThreads = 1;
          }
          const numCpuLogicalCores = typeof navigator === "undefined" ? cpus().length : navigator.hardwareConcurrency;
          env2.wasm.numThreads = Math.min(4, Math.ceil((numCpuLogicalCores || 1) / 2));
        }
      };
      OnnxruntimeWebAssemblyBackend = class {
        /**
         * This function initializes the WebAssembly backend.
         *
         * This function will be called only once for each backend name. It will be called the first time when
         * `ort.InferenceSession.create()` is called with a registered backend name.
         *
         * @param backendName - the registered backend name.
         */
        async init(backendName) {
          initializeFlags();
          await initializeWebAssemblyAndOrtRuntime();
          await initializeOrtEp(backendName);
        }
        async createInferenceSessionHandler(pathOrBuffer, options) {
          const handler = new OnnxruntimeWebAssemblySessionHandler();
          await handler.loadModel(pathOrBuffer, options);
          return Promise.resolve(handler);
        }
      };
    }
  });

  // web/lib/backend-wasm-inference.ts
  var backend_wasm_inference_exports = {};
  __export(backend_wasm_inference_exports, {
    wasmBackend: () => wasmBackend
  });
  var wasmBackend;
  var init_backend_wasm_inference = __esm({
    "web/lib/backend-wasm-inference.ts"() {
      "use strict";
      init_backend_wasm();
      wasmBackend = new OnnxruntimeWebAssemblyBackend();
    }
  });

  // web/lib/index.ts
  var lib_exports = {};
  __export(lib_exports, {
    InferenceSession: () => InferenceSession2,
    TRACE: () => TRACE,
    TRACE_FUNC_BEGIN: () => TRACE_FUNC_BEGIN,
    TRACE_FUNC_END: () => TRACE_FUNC_END,
    Tensor: () => Tensor2,
    TrainingSession: () => TrainingSession2,
    default: () => lib_default,
    env: () => env2,
    registerBackend: () => registerBackend
  });
  init_esm();
  init_esm();
  init_esm();

  // web/lib/version.ts
  var version2 = "1.18.0";

  // web/lib/index.ts
  var lib_default = esm_exports;
  if (true) {
    const onnxjsBackend2 = (init_backend_onnxjs(), __toCommonJS(backend_onnxjs_exports)).onnxjsBackend;
    registerBackend("webgl", onnxjsBackend2, -10);
  }
  if (true) {
    const wasmBackend2 = true ? (init_backend_wasm_inference(), __toCommonJS(backend_wasm_inference_exports)).wasmBackend : null.wasmBackend;
    if (false) {
      registerBackend("webgpu", wasmBackend2, 5);
      registerBackend("webnn", wasmBackend2, 5);
    }
    registerBackend("cpu", wasmBackend2, 10);
    registerBackend("wasm", wasmBackend2, 10);
  }
  Object.defineProperty(env2.versions, "web", { value: version2, enumerable: true });
  return __toCommonJS(lib_exports);
})();
/*! Bundled license information:

long/index.js:
  (**
   * @license
   * Copyright 2009 The Closure Library Authors
   * Copyright 2020 Daniel Wirtz / The long.js Authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *
   * SPDX-License-Identifier: Apache-2.0
   *)
*/
//# sourceMappingURL=data:application/json;base64,[encoded data, 3282036 characters]
